text
stringlengths
10
2.61M
class MatchSerializer < ActiveModel::Serializer attributes :id, :home_score, :away_score belongs_to :home_player belongs_to :away_player end
module Yaks module Serializer def self.register(format, serializer) raise "Serializer for #{format} already registered" if all.key? format all[format] = serializer end def self.all @serializers ||= {json: JSONWriter} end module JSONWriter extend Yaks::FP::Callable def self.call(data, _env) JSON.pretty_generate(data) end def self.transitive? true end def self.inverse JSONReader end end module JSONReader extend Yaks::FP::Callable def self.call(data, _env) JSON.parse(data) end def self.transitive? true end def self.inverse JSONWriter end end end end
require 'minitest_helper' describe JsonStructure::Number do describe 'without options' do it do js = build { number } assert js === -100 assert js === 0.99 refute js === [128] end end describe 'with :max option' do it do js = build { number(max: 100) } assert js === -100.11 assert js === 100 refute js === 321 end end describe 'with :min option' do it do js = build { number(min: 18) } assert js === 20 assert js === 18.0 refute js === 12 end end end
class Updateusers < ActiveRecord::Migration def change add_column :users, :uid, :integer add_index :users, :uid end end
class Assignment < ActiveRecord::Base attr_accessible :project_id, :researcher_id belongs_to :researcher belongs_to :project validates :project_id, :presence => true validates :researcher_id, :presence => true end
module Pacer::Utils module Trie class << self def trie(graph, name) t = graph.v(self, :name => name).first if t t else graph.create_vertex self, :type => 'Trie', :name => name end end def route_conditions(graph) { :type => 'Trie' } end end module Vertex def find_word(word) find word.scan(/./) end def find(array) found = find_partial(array) if found.length == array.length found.last.in_vertex.add_extensions [Trie] end end def find_partial(array) return [] if array.empty? strings = array.map &:to_s max_depth = array.length - 1 found = [] v.out_e(strings.first).loop { |e| e.in_v.out_e }.while do |e, depth| if e.label == "trie:#{strings[depth]}" and depth <= max_depth found << e :loop end end.to_a found end def add_word(word) add word.scan(/./) end def add(array) found = find_partial(array) if found.length == array.length result = found.last.in_vertex else found[array.length] ||= nil result = array.zip(found).inject(self) do |vertex, (part, edge)| if edge edge.in_vertex else new_vertex = graph.create_vertex :type => 'Trie' graph.create_edge nil, vertex, new_vertex, "trie:#{part.to_s}" new_vertex end end end result[:end] = true result.add_extensions [Trie] end def path result = [] v.in_e.chain_route(:pipe_class => Pacer::Pipes::LabelPrefixPipe, :pipe_args => 'trie:').loop do |e| e.out_v.in_e.chain_route(:pipe_class => Pacer::Pipes::LabelPrefixPipe, :pipe_args => 'trie:') end.while do |e, d| if e.out_vertex[:type] == 'Trie' :emit else :loop end end.paths.to_a.first.reverse.to_route(:element_type => :mixed, :graph => graph) end def array path.e.labels.map { |label| label[/^trie:(.*)$/, 1] }.to_a end def word array.join end end end end
child @friend => "friends" do attributes :user_id,:first_name,:last_name,:username, :email, :status end
module Midishark class Cli def initialize(config, args = ARGV) @config = config @args = args end def run! case @args.first when 'capture' capture! when 'format' format! else abort "Unknown command: #{@args.first}" end end private def format! parser = @config.parser.new(@config) transformer = @config.transformer.new(@config) outputter = @config.outputter.new Midishark::Format.new(parser, transformer, outputter).run! end def capture! Midishark::Wireshark.new(@config.tshark_command).exec_process! end end end
# # Cookbook:: firefox_configuration # Recipe:: default # # MIT def ensure_dir(path) directory path do action :create recursive true end end def create_template(source_template, path) template path do source source_template end end # Set the firefox installation base directory install_path = File.join(node['firefox_configuration']['install_directory'], "") # Make sure that directory exists if File.directory?(install_path) # Set the preferences directory prefs_dir = File.join(install_path, "defaults/pref/") # Set the chrome profile directory chrome_profile_dir = File.join(install_path, "browser/defaults/profile/chrome/") # Set the path to the autoconfig.js file autoconfig_js_path = File.join(prefs_dir, 'autoconfig.js') # Set the path to the channel-prefs.js file channel_prefs_js_path = File.join(prefs_dir, 'channel-prefs.js') # Set the path for the mozilla.cfg file mozilla_cfg_path = File.join(install_path, 'mozilla.cfg') # Set the path for the override.ini file override_ini_path = File.join(prefs_dir, 'override.ini') # Set the path for the userChrome.css file user_chrome_css_path = File.join(chrome_profile_dir, 'userChrome.css') # Make sure parent directories exist ensure_dir prefs_dir ensure_dir chrome_profile_dir # Create the template files create_template('autoconfig.js.erb', autoconfig_js_path) create_template('channel-prefs.js.erb', channel_prefs_js_path) create_template('mozilla.cfg.erb', mozilla_cfg_path) create_template('override.ini.erb', override_ini_path) create_template('userChrome.css.erb', user_chrome_css_path) else # If it does not exists throw a fatal error log 'Firefox Install Not Found' do message "Could not locate the firefox installation directory at: #{install_path} ... Aborting!" level :fatal end end
Puppet::Type.type(:wlp_feature).provide(:ruby) do def get_installed_features begin feature_command = "#{@resource[:base_path]}/bin/productInfo" command = [feature_command, 'featureInfo'] installed_features = Puppet::Util::Execution.execute(command, :uid => resource[:wlp_user], :combine => true, :failonfail => true) rescue Puppet::ExecutionFailure => e Puppet.debug("get_installed_features failed to generate report -> #{e.inspect}") return nil end return nil if installed_features.empty? installed_features end def exists? get_installed_features.include?(resource[:name]) end def create installutility = "#{@resource[:base_path]}/bin/installUtility" arguments = Array.new arguments.push(resource[:name]) arguments.push('--acceptLicense') if resource[:accept_license] == :true arguments.push('--to=extension') if resource[:install_type] == 'extension' arguments.push("--from=#{resource[:install_from]}") if resource[:install_from] arguments.push("--downloadDependencies=false") if resource[:download_deps] != :true arguments.push("--verbose") if resource[:verbose] == :true command = arguments.unshift('install') command = arguments.unshift(installutility).flatten Puppet::Util::Execution.execute(command, :uid => resource[:wlp_user], :combine => true, :failonfail => true) end def destroy installutility = "#{@resource[:base_path]}/bin/installUtility" arguments = ['uninstall','--verbose','--noPrompts',"#{resource[:name]}"] command = arguments.unshift(installutility).flatten.uniq Puppet::Util::Execution.execute(command, :uid => resource[:wlp_user], :combine => true, :failonfail => true) end end
Pod::Spec.new do |s| s.name = 'SwiftCrypto' s.version = '0.2.0' s.license = 'MIT' s.summary = 'A simple Cryptography Implementation in Swift for the ARK Blockchain' s.homepage = 'https://github.com/ArkEcosystem/swift-crypto' s.authors = { 'Ark Ecosystem' => 'info@ark.io' } s.source = { :git => 'https://github.com/ArkEcosystem/swift-crypto.git', :tag => s.version } s.ios.deployment_target = '10.0' s.dependency 'BitcoinKit', '1.0.2' s.source_files = 'Crypto/Crypto/**/*.swift' end
RailsDeviseRspecCucumber::Application.routes.draw do get "users/index" get "users/show" # get "home/index" # get 'users/:id', :to =>'users#index', :as => :user # resources :users, :only => [:show] # authenticated users -- those logged in and # have an account -- will see the home page # By default, Devise will redirect to the # root_path after successful sign in/out authenticated :user do root :to => 'users#index', :as => :authenticated_root end # all other users (those not logged in) # NOTE: As of Rails 4, you can't have two routes routing # to the same controller#method. root :to => 'home#index' # routes for devise registrations, sessions, as well as standard user devise_for :users # standard routes after devise implements its own routing # place this before so devise doesn't override anything resources :users end
# Truthiness # The ability to express true and false is an important concept in any programming languages. # It is used to build conditional logic # "true" or "false" is expressed with boolean data type. # A boolean is an object whose only purpose is to convery whether it is "true" or "false" # Examples if true puts "hi" else puts "goodbye" end # -> always output "hi" if false puts "hi" else puts "goodbye" end # -> always output "goodbye" # logical operators # && : is 'and' operator. for this both condition has to be true, then it returns true if true && true puts "hi" else puts "bye" end # -> "hi" if true && false # both must be true puts "hi" else puts "bye" end # -> "bye" # short circuiting: && and || operators have a behaviour called short circuiting. They will stop # evaluating expression once it can guarantee the return value # && short circuits once it encounters the first 'false' expression # || short circuits once it encounters the first 'true' expression # Truthiness # It is what the language consider to be truthfull and treats it as true # In Ruby everything is truthy except 'false' and 'nil' # Note: an expression that Ruby considers true is not the same as 'true' object puts "hello" == true # -> false name = '' if name && name.valid? puts "great name" else puts "invalid name" end
module Test module HumbleUnit module Outputs class FileOutput < BaseOutput require 'fileutils' def flush(test_class_name, messages, stats) content = build_header(test_class_name) content += build_content(messages, stats) create_report_directory write_content_to_file test_class_name, content end private def directory_name "humble_file_reports" end def report_ext ".txt" end def build_header(test_class_name) "Testing class: #{test_class_name} (by HumbleUnit)" end def build_content(messages, stats) content = build_messages messages content += build_stats stats content end def build_messages(messages) content = '' order_messages(messages).each do |m| content += "\n#{m.status}:\t#{m.method_name}\t#{m.error}\t#{m.source_location_file}:#{m.source_location_line_number}" end content end def build_stats(stats) content = "\nTest result: #{test_result(stats)}" content << "\nPassed: #{stats.passed_count}" content << "\nFailed: #{stats.failed_count}" content << "\nTests: #{stats.number_of_tests}" content << "\nAt: #{stats.time}" content end def test_result(stats) percentage = "(#{stats.percentage}/100.0%)" stats.all_passed? ? "YES #{percentage}" : "NO #{percentage}" end end end end end
module Maestro module Util class Shell VERSION = '1.0.1' end end end
require 'nkf' class ArtistItem < ActiveRecord::Base belongs_to :artist has_many :artist_tracks has_many :users_artist_items_tags def self.find_items artist_id, page, keyword = '' artist = Artist.find artist_id search_artist = artist.name artist_alias_names = artist.artist_aliases.map{|artist_aliase|artist_aliase.name} artist_name = artist.name if artist_alias_names.present? artist_name += "|" + artist_alias_names.join('|') end artist_name = "(#{artist_name})" amazon_params = { :search_index => "Music", :response_group => 'ItemAttributes,Images', :browse_node => 562032, :item_page => page, :response_group => 'Large', :sort => 'salesrank', :Artist => search_artist } items_cache_key = 'artist_item_find_items_' + Digest::SHA1.hexdigest(keyword + amazon_params.to_yaml) total_cache_key = 'artist_item_find_items_total_' + Digest::SHA1.hexdigest(keyword + amazon_params.to_yaml) if Rails.cache.exist?(items_cache_key) && Rails.cache.exist?(total_cache_key) items = Rails.cache.read(items_cache_key).dup total = Rails.cache.read(total_cache_key) else result_set = Amazon::Ecs.item_search(keyword, amazon_params) items = [] result_set.items.each do |item| item_artist = item.get('ItemAttributes/Artist') item_artist = item_artist.present? ? item_artist.encode("UTF-8") : '' item_artist = NKF::nkf('-Z1 -Ww', CGI::unescapeHTML(item_artist)) #next unless item_artist.downcase =~ Regexp.new(artist_name.downcase) items << self.format_amazon_item(artist_id, item) end total = result_set.total_results res = Rails.cache.write items_cache_key, items res = Rails.cache.write total_cache_key, total end items.instance_eval <<-EVAL def current_page #{page || 1} end def num_pages #{total} end def limit_value 10 end EVAL items.map! do |item| self.convert_hash_to_arctive_record item end items end def self.find_or_create artist_id, asin artist_item = self.find_by_artist_id_and_asin artist_id, asin if artist_item.nil? artist_item = self.find_item_from_amazon artist_id, asin artist_item.save end artist_item end protected def self.find_item_from_amazon artist_id, asin Rails.cache.fetch("artist_item_#{asin}", :expires_in => 24.minutes) do item = Amazon::Ecs.item_lookup(asin, {:response_group => 'ItemAttributes,Images',:response_group => 'Large',}).items[0] item = self.format_amazon_item artist_id, item artist_item = self.convert_hash_to_arctive_record item end end def self.format_amazon_item artist_id, item tracks = [] if item.get_elements('Tracks/Disc').instance_of? Array item.get_elements('Tracks/Disc').each do |discs| discs.get_elements('Track').each do |track| title = track.get().present? ? track.get() : '' tracks << { :artist_id => artist_id, :asin => item.get('ASIN'), :disc => discs.attributes['Number'].to_s.to_i, :track => track.attributes['Number'].to_s.to_i, :title => CGI::unescapeHTML(title.encode("UTF-8")), } end end end title = item.get('ItemAttributes/Title').present? ? item.get('ItemAttributes/Title') : '' small_image = item.get_hash('SmallImage') small_image_url = small_image.present? ? small_image['URL'] : '/images/musick.png' medium_image = item.get_hash('MediumImage') medium_image_url = medium_image.present? ? medium_image['URL'] : '/images/musick.png' large_image = item.get_hash('LargeImage') large_image_url = large_image.present? ? large_image['URL'] : '/images/musick.png' label = item.get('ItemAttributes/Label').present? ? item.get('ItemAttributes/Label') : '' { :artist_id => artist_id, :asin => item.get('ASIN'), :ean => item.get('ItemAttributes/EAN'), :title => CGI::unescapeHTML(title.encode("UTF-8")), :detail_page_url => item.get('DetailPageURL'), :small_image_url => small_image_url, :medium_image_url => medium_image_url, :large_image_url => large_image_url, :label => CGI::unescapeHTML(label.encode("UTF-8")), :product_group => item.get('ItemAttributes/ProductGroup'), :format => item.get('ItemAttributes/Format'), :release_date => item.get('ItemAttributes/ReleaseDate'), :tracks => tracks, } end def self.convert_hash_to_arctive_record item artist_item = self.new( :artist_id => item[:artist_id], :asin => item[:asin], :ean => item[:ean], :title => item[:title], :detail_page_url => item[:detail_page_url], :small_image_url => item[:small_image_url], :medium_image_url => item[:medium_image_url], :large_image_url => item[:large_image_url], :label => item[:label], :product_group => item[:product_group], :format => item[:format], :release_date => item[:release_date], ) artist_tracks = [] item[:tracks].each do |track| artist_tracks << ArtistTrack.new(track) end artist_item.artist_tracks = artist_tracks artist_item end end
# Classes and Objects # objects contain states, tracked by instance variables # objects have behaviors, which are instance methods class Dog attr_accessor :weight, :name, :height @@count = 0 def self.total_dogs @@count end def initialize(name, height, weight) @name = name @height = height @weight = weight @@count += 1 end def bark "#{@name} bark!" end def info "#{@name} weights #{@weight} lbs and is #{@height} feet tall" end def update_info(n, h, w) self.name = n self.height = h self.weight = w end end teddy = Dog.new('teddy', 3, 100) fido = Dog.new('fido', 1.5, 150) puts teddy.info
class AdministratorsController < ApplicationController before_action :signed_in_administrator, only: [:new, :index, :show, :edit, :update, :topwaiters, :panel, :destory, :lastweektop, :alldayslong] def new @administrator = Administrator.new end def index @administrators = Administrator.all end def create @administrator = Administrator.new(administrator_params) if @administrator.save sign_in @administrator redirect_to controlpanel_path else render 'new' end end def show @administrator = Administrator.find(params[:id]) end def edit @administrator = Administrator.find(params[:id]) end def update @administrator = Administrator.find(params[:id]) if @administrator.update_attributes(administrator_params) redirect_to administrators_path else render 'edit' end end def topwaiters @waiters = Waiter.find_by_sql([" SELECT WAITERS.LASTNAME, ORDERS_PCS AS ORDERS_NUMBER FROM WAITERS INNER JOIN ( SELECT WAITER_ID, COUNT(ID) AS ORDERS_PCS FROM ORDERS GROUP BY WAITER_ID ORDER BY ORDERS_PCS DESC) AS RAITING ON WAITERS.ID = RAITING.WAITER_ID; "]) @chefs = Chef.find_by_sql([" SELECT CHEFS.LASTNAME, ORDERS_PCS FROM CHEFS INNER JOIN ( SELECT CHEF_ID, COUNT(ID) AS ORDERS_PCS FROM ORDERS GROUP BY CHEF_ID ORDER BY ORDERS_PCS DESC) AS RAITING ON CHEFS.ID = RAITING.CHEF_ID; "]) end def panel end def destroy Administrator.find(params[:id]).destroy redirect_to :back end def landing end def lastweektop @top = Item.find_by_sql([" SELECT ITEMS.DESCRIPTION AS ITEMDESC, RAWDATA.NUMBER_OF_PARTS AS VAL, (ITEMS.PRICE * RAWDATA.NUMBER_OF_PARTS) AS PROFIT FROM ITEMS INNER JOIN (SELECT PARTS.ITEM_ID AS ITEM_ORDERED, COUNT(PARTS.ID) AS NUMBER_OF_PARTS FROM PARTS WHERE PARTS.CREATED_AT::DATE BETWEEN NOW()::DATE - 7 AND NOW()::DATE GROUP BY PARTS.ITEM_ID ORDER BY NUMBER_OF_PARTS DESC) AS RAWDATA ON RAWDATA.ITEM_ORDERED = ITEMS.ID "]) @cost = 0 @top.each do |f| @cost += f.profit end end def alldayslong @rating = Restaurant.find_by_sql([" SELECT RESTAURANTS.NAME AS RESTNAME, SUM(TABLEDATA.RESERVATIONS_NUMBER) AS TOTAL, TABLEDATA.DAY_NUMBER AS RESTDAY FROM RESTAURANTS INNER JOIN ( SELECT TABLES.RESTAURANT_ID AS REST_ID, DAYDATA.RES_NUM AS RESERVATIONS_NUMBER, DAYDATA.MIMEDAY AS DAY_NUMBER, DAYDATA.TABNUM AS TABLE_NUM FROM TABLES INNER JOIN (SELECT COUNT(RESERVATIONS.ID) AS RES_NUM, EXTRACT(DOW FROM RESERVATIONS.RESERV_TIME) AS MIMEDAY, RESERVATIONS.TABLE_ID AS TABNUM FROM RESERVATIONS GROUP BY EXTRACT(DOW FROM RESERVATIONS.RESERV_TIME), RESERVATIONS.TABLE_ID ORDER BY EXTRACT(DOW FROM RESERVATIONS.RESERV_TIME) DESC) AS DAYDATA ON TABLES.ID = DAYDATA.TABNUM ) AS TABLEDATA ON RESTAURANTS.ID = TABLEDATA.REST_ID GROUP BY TABLEDATA.DAY_NUMBER, RESTAURANTS.NAME ORDER BY TABLEDATA.DAY_NUMBER "]) end private def administrator_params params.require(:administrator).permit(:login, :password, :password_confirmation) end end
#!/usr/bin/env ruby # command line tool for administering data pipeline queues # # To create queues for an app following certain models: # pipeline subscribe-app APP_NAME orders,products,users require 'thor' require 'aws-sdk' require 'iron_mq' require 'pry' class Pipeline < Thor # TODO: Kinda clunky, but there is a way to get the account ID programmatically: # https://forums.aws.amazon.com/thread.jspa?threadID=108012 AWS_ACCOUNT_ID = ENV["AWS_ACCOUNT_ID"] def initialize(args = [], local_options = {}, config = {}) super(args, local_options, config) @sns = AWS::SNS.new @sqs = AWS::SQS.new @iam = AWS::IAM.new end desc "sns-create-topic TABLE_NAME --env ENV --version VERSION", "create topic for TABLE_NAME" option :env option :version def create_sns_topic(table_name) env = options.fetch(:env, "test") version = options.fetch(:version, "1_0") topic_name = _topic_name(table_name, env, version) topic = _find_or_create_topic(topic_name) return topic end desc "sqs-subscribe-app APP TABLE_NAME[,TABLE_NAME_2,...] --env ENV --version VERSION", "create queue(s) for APP subscribed to TABLE_NAME feeds" option :env option :version def sqs_subscribe_app(app_name, table_names) env = options.fetch(:env, "test") version = options.fetch(:version, "1_0") table_names.split(',').each do |table_name| topic_name = _topic_name(table_name, env, version) queue_name = _queue_name(topic_name, app_name) queue = _find_or_create_queue(queue_name) topic = _find_or_create_topic(topic_name) sub = _subscribe_queue_to_topic(queue, topic) end end # Placeholders for IronMQ functions desc "ironmq-subscribe-endpoint ENDPOINT TABLE_NAME_1[,TABLE_NAME_2,...] --env ENV --version VERSION", "subscribe the endpoint to updates on ironmq" option :env option :version def ironmq_subscribe_endpoint(endpoint, table_names) env = options.fetch('env', "test") version = options.fetch('version', "1_0") table_names.split(',').each do |table_name| topic_name = _topic_name(table_name, env, version) queue = _iron.queue(topic_name) options = { push_type: "multicast", retries: 10, retries_delay: 10 } puts "Setting push queue settings on #{queue.name}" queue.update(options) puts "Subscribe #{topic_name} to #{endpoint}" queue.add_subscriber({ url: endpoint }) end end private def _topic_name(table_name, env, version) "harrys-#{env}-v#{_major_version(version)}-#{table_name}" end def _queue_name(topic_name, app) "#{topic_name}-#{app}" end def _major_version(v) v.include?('_') ? v.split('_')[0] : v end def _find_or_create_topic(topic_name) arn = _topic_arn(topic_name) topic = @sns.topics[arn] begin topic.owner puts "Found topic #{arn}" return topic rescue AWS::SNS::Errors::NotFound puts "Creating topic #{topic_name}" @sns.client.create_topic({name: topic_name}) return _find_or_create_topic(topic_name) end end def _find_or_create_queue(queue_name) puts "Find or create queue #{queue_name}" begin queue = @sqs.queues.named(queue_name) return queue rescue AWS::SQS::Errors::NonExistentQueue @sqs.queues.create(queue_name) puts "Creating queue #{queue_name}" return _find_or_create_queue(queue_name) end end def _subscribe_queue_to_topic(queue, topic) puts "Subscribing #{queue.arn} to #{topic.arn}" return topic.subscribe(queue) end def _topic_arn(topic_name, region="us-east-1") "arn:aws:sns:#{region}:#{AWS_ACCOUNT_ID}:#{topic_name}" end def _queue_arn(queue_name, region="us-east-1") "arn:aws:sns:#{region}:#{AWS_ACCOUNT_ID}:#{queue_name}" end def _iron @iron = IronMQ::Client.new if @iron.nil? return @iron end end Pipeline.start()
# # SurveyTemplatesController # class SurveyTemplatesController < ApplicationController before_action :authenticate_user! before_action :authenticate_admin before_action :set_survey_template, only: [:show, :edit, :update, :destroy] # # Render Survey Template data # def index @survey_templates = SurveyTemplate.all end # # Show route # def show end # # New route # def new @survey_template = SurveyTemplate.new end # # Create route # def create @survey_template = SurveyTemplate.new(survey_template_params) create_survey_template end # # Edit route # def edit end # # Update route # def update update_survey_template end # # Destroy route # def destroy destroy_survey_template end private # # Set survey_template to be used in routes # def set_survey_template @survey_template = SurveyTemplate.find(params[:id]) end # # Set and sanitize survey params # def survey_template_params params.require(:survey_template).permit(:title, :name) end # # Logic helper for create action # Extrapolated into new method to appease Rubocop # def create_survey_template if @survey_template.save flash[:success] = success_message(@survey_template, :create) redirect_to survey_template_path(@survey_template) else flash.now[:error] = error_message(@survey_template, :create) render :new end end # # Logic helper for update action # Extrapolated into new method to appease Rubocop # def update_survey_template if @survey_template.update(survey_template_params) flash[:success] = success_message(@survey_template, :update) redirect_to @survey_template, notice: 'Survey Template was successfully updated.' else flash.now[:error] = error_message(@survey_template, :update) render :edit end end # # Logic helper for destroy action # Extrapolated into new method to appease Rubocop # def destroy_survey_template if @survey_template.destroy flash[:success] = success_message(@survey_template, :delete) redirect_to survey_templates_url, notice: 'Survey Template was successfully destroyed.' else flash[:error] = error_message(@survey_template, :delete) redirect_back fallback_location: survey_templates_path end end end
class RemoveUserFromPost < ActiveRecord::Migration[5.0] def change remove_column :posts, :user_id, :refernces end end
require "pry" def consolidate_cart(cart) final_hash= {} cart.each do |row_hash| name= row_hash.keys[0] if !final_hash[name] final_hash[name] = row_hash[name] final_hash[name][:count] = 1 else final_hash[name][:count]+=1 end end final_hash end def apply_coupons(cart, coupons) coupons.each do |coupon| item_name = coupon[:item] if cart[item_name] if cart[item_name][:count]>= coupon[:num] and !cart["#{item_name} W/COUPON"] cart["#{item_name} W/COUPON"] = { price: coupon[:cost] / coupon[:num], clearance: cart[item_name][:clearance], count: coupon[:num] } cart[item_name][:count]-= coupon[:num] elsif cart[item_name][:count]>= coupon[:num] && cart["#{item_name} W/COUPON"] cart["#{item_name} W/COUPON"][:count]+= coupon[:num] cart[item_name][:count]-= coupon[:num] end end end cart end def apply_clearance(cart) final_hash ={} cart.each do |k,v| last_price= cart[k][:price] * 0.20 if cart[k][:clearance] final_hash["#{k}"] ={ price: cart[k][:price] - last_price, clearance: cart[k][:clearance], count: cart[k][:count] } elsif !cart[k][:clearance] final_hash["#{k}"] = v end end final_hash end def checkout(cart, coupons) new_cart = consolidate_cart(cart) after_coupons = apply_coupons(new_cart,coupons) after_clearance = apply_clearance(after_coupons) final_amount = after_clearance.reduce(0) do |acu, (k,v)| acu+= (v[:price]*v[:count]) acu end ten_percent = final_amount*0.10 final_amount> 100 ? final_amount - ten_percent : final_amount # binding.pry end
require 'spec_helper' describe MenuItem do before do @site = Site.make @menu = Menu.make(:site => @site) @folder1 = Folder.make(:site => @site ) @folder2 = Folder.make(:site => @site ) @folder3 = Folder.make(:site => @site ) @folder4 = Folder.make(:site => @site ) @folder5 = Folder.make(:site => @site ) end describe 'hierarchy_depth' do it " returns depth " do item1 = MenuItem.create(:folder => @folder1, :menu => @menu) item2 = MenuItem.create(:folder => @folder2, :menu => @menu, :parent => item1) item3 = MenuItem.create(:folder => @folder3, :menu => @menu, :parent => item2) item3.hierarchy_depth.should == 3 end it " returns depth 1" do item1 = MenuItem.create(:folder => @folder1, :menu => @menu) item1.hierarchy_depth.should == 1 end end describe 'tree_looped?' do it " returns true " do item1 = MenuItem.create(:folder => @folder1, :menu => @menu) item2 = MenuItem.create(:folder => @folder2, :menu => @menu, :parent => item1) item3 = MenuItem.create(:folder => @folder3, :menu => @menu, :parent => item2) item1.parent = item3 item1.parent.tree_looped?.should == true end it " returns false " do item1 = MenuItem.create(:folder => @folder1, :menu => @menu) item2 = MenuItem.create(:folder => @folder2, :menu => @menu, :parent => item1) item3 = MenuItem.create(:folder => @folder3, :menu => @menu, :parent => item2) item3.parent.tree_looped?.should == false end end describe 'set order of display ' do it " set order of display when created " do item1 = MenuItem.create(:folder => @folder1, :menu => @menu) item1.order_of_display.should == 1 item2_1 = MenuItem.create(:folder => @folder2, :menu => @menu, :parent => item1) item2_2 = MenuItem.create(:folder => @folder3, :menu => @menu, :parent => item1) item2_3 = MenuItem.create(:folder => @folder4, :menu => @menu, :parent => item1) item2_4 = MenuItem.create(:folder => @folder5, :menu => @menu, :parent => item1) item2_1.order_of_display.should == 1 item2_2.order_of_display.should == 2 item2_3.order_of_display.should == 3 item2_4.order_of_display.should == 4 end end describe 'move ahead' do it " move ahead " do item1 = MenuItem.create(:folder => @folder1, :menu => @menu) item2_1 = MenuItem.create(:folder => @folder2, :menu => @menu, :parent => item1) item2_2 = MenuItem.create(:folder => @folder3, :menu => @menu, :parent => item1) item2_3 = MenuItem.create(:folder => @folder4, :menu => @menu, :parent => item1) item2_4 = MenuItem.create(:folder => @folder5, :menu => @menu, :parent => item1) item2_3.move_ahead! item2_3 = item2_3.reload item2_2 = item2_2.reload item2_3.order_of_display.should == 2 item2_2.order_of_display.should == 3 end end describe 'move behind' do it " move behind " do item1 = MenuItem.create(:folder => @folder1, :menu => @menu) item2_1 = MenuItem.create(:folder => @folder2, :menu => @menu, :parent => item1) item2_2 = MenuItem.create(:folder => @folder3, :menu => @menu, :parent => item1) item2_3 = MenuItem.create(:folder => @folder4, :menu => @menu, :parent => item1) item2_4 = MenuItem.create(:folder => @folder5, :menu => @menu, :parent => item1) item2_2.move_behind! item2_3 = item2_3.reload item2_2 = item2_2.reload item2_3.order_of_display.should == 2 item2_2.order_of_display.should == 3 end end end
# == Schema Information # # Table name: logs # # id :integer not null, primary key # device_id :integer # actual_ip_address :string(255) # message_type :string(255) # message_data :text(255) # created_at :datetime not null # updated_at :datetime not null # custom_key :string(255) # class Log < ActiveRecord::Base belongs_to :device attr_accessible :actual_ip_address, :actual_port, :message_data, :message_type, :device_id, :custom_key default_scope order('created_at DESC') end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :machines, dependent: :destroy has_many :owner_bookings, through: :machines, source: :bookings, dependent: :destroy has_many :customer_bookings, class_name: "Booking" validates :name, presence: true mount_uploader :photo, PhotoUploader end
#!/usr/bin/env ruby $LOAD_PATH.unshift( File.expand_path( File.dirname( __FILE__ ) + "/../../lib/" ) ) require "command/node-history" require "configuration" require "lucie/log" require "lucie/script" Lucie::Log.path = File.join( Configuration.log_directory, "node-history.log" ) def target_node ARGV.each do | each | return each unless /\A\-/=~ each end end begin app = Command::NodeHistory::App.new app.usage_and_exit if target_node.empty? app.main target_node rescue => e Lucie::Script.handle_exception e, app exit -1 end ### Local variables: ### mode: Ruby ### coding: utf-8-unix ### indent-tabs-mode: nil ### End:
class REntry < ActiveRecord::Base belongs_to :r_language has_many :r_pages, through: :r_pages_to_entries end
class Instructor < ApplicationRecord has_many :students def average_student_age if students.count != 0 students.sum {|student| student.age} / students.count else 0 end end def students_sort_by_name students.sort_by {|student| student.name} end end
# frozen_string_literal: true module Queries module List class Teams < ::Queries::List::Base description 'List teams with various filters' type types[::Types::TeamType] def call(_obj, _args, ctx) super do ctx[:pundit].policy_scope ::Team.all end end end end end
# To install: # brew tap avencera/yamine # brew install yamine # # To remove: # brew uninstall yamine # brew untap avencera/yamine class Yamine < Formula version 'v0.1.0' desc "A simple CLI for combining json and yaml files" homepage "https://github.com/avencera/yamine" license "Apache-2.0" if OS.mac? && Hardware::CPU.intel? url "https://github.com/avencera/yamine/releases/download/#{version}/yamine-#{version}-x86_64-apple-darwin.tar.gz" sha256 "9789325e16bfb4443e64f1e7fc036f6f5e74bf853aab0e7898b7b36cef0e69a5" end if OS.mac? && Hardware::CPU.arm? url "https://github.com/avencera/yamine/releases/download/#{version}/yamine-#{version}-aarch64-apple-darwin.tar.gz" sha256 "9c4c8a7adf8fcf99c4d955d5803fd383719f83458228d0866672608948b40b55" end if OS.linux? && Hardware::CPU.intel? url "https://github.com/avencera/yamine/releases/download/#{version}/yamine-#{version}-x86_64-unknown-linux-musl.tar.gz" sha256 "212144e6025de75651b3942feadecc387d8f0302bf4d6bc4947d395d13112c32" end if OS.linux? && Hardware::CPU.arm? && Hardware::CPU.is_64_bit? url "https://github.com/avencera/yamine/releases/download/#{version}/yamine-#{version}-aarch64-unknown-linux-musl.tar.gz" sha256 "4847d632fb01ad8619a827fa11fb0e2b45d3c66e7ab0ce8dd2c0037b4e1513bc" end def install bin.install "yamine" end end
# frozen_string_literal: true require_relative './../../utils/response' module Sourcescrub # Get the data from API module Models # Entity class Entity include ::Sourcescrub::Utils::Response def fields field_ids.map(&:to_sym) end def parse_response(response) dynamic_attributes(self, field_ids, response) self end def as_json fields.each_with_object({}) { |item, hash| hash[item] = send(item) } end end end end
class JobsController < ApplicationController def show @job = Job.find(params[:id]) end def index @all_jobs = Job.all @jobs = Job.paginate(page: params[:page], per_page: 15).order('created_at DESC') @truncate_length = 64 @truncate_length_new = 50 end # # def new # @job = Job.new # end # # def create # @job = Job.new(jobs_params) # # if @job.save # redirect_to @job # else # render :new # end # end # # def destroy # @job = Job.find(params[:id]) # @job.destroy # redirect_to jobs_path # end # # private # def jobs_params # params.require(:job).permit(:title) # end end
# frozen_string_literal: true require 'open3' module SystemCall ## # A class responsible for communication with command line interfaces. # # @!attribute [r] args # @return [Array] class Command attr_reader :args ## # Initializes a {Command}. # # @param args [Array] The command line arguments. def initialize(*args) @args = args.flatten end ## # Initializes and calls a {Command}, then returns the {Result}. # # @param args [Array] The command line arguments. # @return [Result] def self.call(*args) new(*args).call end ## # Invokes the {Command} and returns the {Result}. # # @return [Result] def call Open3.popen3(*args) do |_, stdout, stderr, wait_thr| success_result = readlines(stdout) error_result = readlines(stderr) exit_status = wait_thr.value Result.new(exit_status, success_result, error_result) end end private def readlines(io) io.readlines.join.chomp end end end
## Exercise 5 # The following program prints the value of the variable. Why? my_string = 'Hello Ruby World' def my_string 'Hello World' end puts my_string
class Comment < ApplicationRecord validates :body, presence: true, length: { minimum: 6, maximum: 500 } #{ within 6..500 } { in 6..500 } validates :commenter, presence: true, email: true belongs_to :article end
require 'digest/sha1' class User < ActiveRecord::Base has_many :openid_trusts, :class_name => 'UserOpenidTrust' belongs_to :group belongs_to :image has_one :info has_one :mumble delegate :rights, :to => :group delegate :forum_rights, :to => :group has_many :topics has_many :posts has_many :password_resets has_many :reads, :class_name => 'UserTopicRead' has_many :topic_infos, :class_name => 'UserTopicInfo' do def can_reply?(topic, *args) !(info = find_by_topic_id(topic.id, *args)) or info.is_reply end alias :can_edit? :can_reply? end named_scope :active, :conditions => { :state => 'active' } named_scope :pending, :conditions => { :state => 'pending' } named_scope :confirmed, :conditions => { :state => 'confirmed' } named_scope :authenticatable, :conditions => { :state => ['confirmed', 'active' ] } named_scope :address, :select => 'users.city, users.country', :conditions => "users.city IS NOT NULL AND users.city != '' AND users.country IS NOT NULL AND users.country != ''" @@countries = ['France', 'Belgique', 'Suisse', 'Canada', 'Etats-Unis', 'Autre'] @@states = { :passive => 'Créé', :pending => 'En attente', :notified => 'Informé', :confirmed => 'Confirmé', :accepted => 'Accepté', :refused => 'Refusé', :active => 'Activé', :disabled => 'Désactivé' } def self.countries @@countries end def self.states @@states end attr_accessor :password, :previous_password attr_accessible # none validates_presence_of :login, :email validates_length_of :login, :within => 3..20 validates_format_of :login, :with => /^([a-zA-Z0-9_\-]+)$/i validates_length_of :email, :within => 3..200 validates_email_format_of :email, :message => ' ne semble pas être une adresse e-mail valide.' validates_uniqueness_of :login, :case_sensitive => false, :on => :create validates_uniqueness_of :login, :case_sensitive => false, :on => :update, :if => :login_changed? validates_uniqueness_of :email, :case_sensitive => false, :on => :create validates_uniqueness_of :email, :case_sensitive => false, :on => :update, :if => :email_changed? @reset_password = false validates_presence_of :password, :if => :password_required? validates_presence_of :password_confirmation, :if => :password_required?, :on => :update validates_confirmation_of :password, :if => :password_required?, :on => :update validates_length_of :password, :minimum => 4, :if => :password_required?, :on => :update validates_presence_of :previous_password, :if => :password_required?, :on => :update validates_length_of :first_name, :maximum => 100, :allow_blank => true, :allow_nil => true validates_length_of :last_name, :maximum => 100, :allow_blank => true, :allow_nil => true validates_length_of :city, :maximum => 50, :allow_blank => true, :allow_nil => true validates_length_of :country, :maximum => 50, :allow_blank => true, :allow_nil => true validates_inclusion_of :state, :in => self.states validates_inclusion_of :country, :in => self.countries, :allow_nil => true, :allow_blank => true validates_date :birthdate, :allow_nil => true, :message => 'n\'est pas une date correcte' before_validation_on_create :set_random_password before_create :make_confirmation_code before_save :encrypt_password # State machine acts_as_state_machine :initial => :passive state :passive state :pending state :notified, :after => :confirm! state :confirmed state :canceled, :after => :destroy state :accepted state :refused state :active, :enter => :do_activate, :after => :after_activate state :disabled event :register do transitions :from => :passive, :to => :pending end event :notify do transitions :from => :pending, :to => :notified end event :confirm do transitions :from => :notified, :to => :confirmed transitions :from => :pending, :to => :confirmed end event :cancel do transitions :from => :notified, :to => :canceled transitions :from => :pending, :to => :canceled end event :accept do transitions :from => :confirmed, :to => :accepted end event :refuse do transitions :from => :confirmed, :to => :refused end event :activate do transitions :from => :accepted, :to => :active end event :disable do transitions :from => :active, :to => :disabled end event :enable do transitions :from => :disabled, :to => :active end def validate_on_update errors.add_to_base('Ancien mot de passe incorrect') unless !password_required? || authenticated?(previous_password) end def validate errors.add('email', 'Adresse e-mail en @wefrag.com non autorisée') if email =~ /@wefrag.com$/ end def to_s "#{login}" end def to_param @string = URI.escape(to_s) end def address [ city, country ].reject{ |x| x.empty? }.join(', ') end def self.find_by_param(login) find_by_login(URI.unescape("#{login}")) end def self.find_by_login_or_email(login_or_email) find :first, :conditions => ['`users`.login = ? or `users`.email = ?', login_or_email, login_or_email] end def has_email_alias? active? and !info || info.is_email end def email_alias "#{to_s.downcase}@wefrag.com" end def openid_identity "http://www.wefrag.com/users/#{to_param}" end def attributes_from_input=(data) self.city = data[:city] self.country = data[:country] if confirmed? self.first_name = data[:first_name] self.last_name = data[:last_name] self.birthdate = { :year => data[:'birthdate(1i)'], :month => data[:'birthdate(2i)'], :day => data[:'birthdate(3i)'] } elsif active? self.password = data[:password] self.password_confirmation = data[:password_confirmation] self.previous_password = data[:previous_password] end end # Authenticates a user by their login name and unencrypted password. Returns the user or nil. def self.authenticate(login, password) if u = authenticatable.find_by_login(login) and u.authenticated?(password) u else nil end end def self.find_by_openid(identity) if match = identity.match(/^http:\/\/www\.wefrag\.com\/users\/([a-zA-Z0-9_\-]+)$/) find_by_param(match[1]) else nil end end # Authenticates a user by their openid identity and unencrypted password. Returns the user or nil. def self.authenticate_from_openid(identity, password) if u = authenticable.find_by_openid(identity) u else nil end end # Encrypts some data with the salt. def self.encrypt(password, salt) Digest::SHA1.hexdigest("--#{salt}--#{password}--") end # Encrypts the password with the user salt def encrypt(password) self.class.encrypt(password, salt) end def authenticated?(password) crypted_password == encrypt(password) end # User rights def can_login? confirmed? or active? end def can_admin? active? and is_admin end def image_code confirmation_code[0..4].upcase unless confirmation_code.nil? end def is_underage? !birthdate or ((Date.today.strftime("%Y%m%d").to_i - birthdate.strftime("%Y%m%d").to_i) / 10000).to_i < 18 end def age if birthdate ((Date.today.strftime("%Y%m%d").to_i - birthdate.strftime("%Y%m%d").to_i) / 10000).to_i end end def is_complete? [:first_name, :last_name, :city, :country, :birthdate, :image_id].each do |attribute| return false if self[attribute].nil? || self[attribute].to_s.empty? end true end def is_banned?(topic) (topic.user_id != id) && !topic_infos.can_reply?(topic) end def has_rights?(forum_id) return false unless active? return true if is_admin return false unless group_id if block_given? group.has_rights?(forum_id) do |rights| yield(rights) end else group.has_rights?(forum_id) end end def destroy image.destroy if image super end def birthdate=(value) if value.is_a?(Hash) begin value = Date.parse([ value[:year], value[:month], value[:day] ].join('-')).to_s(:db) rescue ArgumentError value = nil end end write_attribute :birthdate, value end def readable_forums if is_admin Forum.find :all elsif group group.readable_forums end end def writeable if frozen? User.find(id) rescue nil else self end end def self.auth_by_id(id) get_cache(id) end def self.get_cache(id) Rails.cache.fetch "User(#{id})", :expires_in => 1.hour do find(id) rescue false end end def delete_cache Rails.cache.delete "User(#{id})" end def request_new_password! password_resets.create! end def make_new_password! @reset_password = true set_random_password save! end protected def do_activate self.confirmation_code = nil end def after_activate image.destroy if image end def set_random_password self.password = Password.generate(10, Password::ONE_DIGIT) end def encrypt_password return if password.blank? self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record? self.crypted_password = encrypt(password) end def password_required? if @reset_password false else crypted_password.blank? or !password.blank? end end def make_confirmation_code self.confirmation_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ) end end
class CreateDayPlannerTasks < ActiveRecord::Migration def up create_table :day_planner_tasks do |t| t.string :name t.integer :interval t.datetime :last_execution t.datetime :next_execution end end def down drop_table :day_planner_tasks end end
class Micropost < ActiveRecord::Base attr_accessible :content belongs_to :user validates :user_id,presence: true validates :content,presence: true, length: {maximum: 140} default_scope order: 'microposts.created_at DESC' end
# frozen_string_literal: true class Board < SimpleDelegator attr_accessor :parent NON_BLOCKNG = /^((L*(LR)*L?\ L?(RL)*R*)|(R*(RL)*R?\ R?(LR)*L*))$/ def initialize(board_str) super(board_str) end def self.initial_board(size) new('L' * size + ' ' + 'R' * size) end def self.target_board(size) initial_board(size).reverse end def turns current_i = index(' ') result = [] prev_i = current_i - 1 prev_prev_i = current_i - 2 next_i = current_i + 1 next_next_i = current_i + 2 if prev_i >= 0 && self[prev_i] == 'L' new_board = dup new_board.parent = self new_board[current_i], new_board[prev_i] = new_board[prev_i], new_board[current_i] result << new_board end if prev_prev_i >= 0 && self[prev_prev_i] == 'L' new_board = dup new_board.parent = self new_board[current_i], new_board[prev_prev_i] = new_board[prev_prev_i], new_board[current_i] result << new_board end if next_i < length && self[next_i] == 'R' new_board = dup new_board.parent = self new_board[current_i], new_board[next_i] = new_board[next_i], new_board[current_i] result << new_board end if next_next_i < length && self[next_next_i] == 'R' new_board = dup new_board.parent = self new_board[current_i], new_board[next_next_i] = new_board[next_next_i], new_board[current_i] result << new_board end # result # use this for a non-optimized version result.reject(&:blocking?) # use this line for an optimized version end def blocking? !Board::NON_BLOCKNG.match?(self) end end
class AddColumnToClub < ActiveRecord::Migration[5.1] def change add_column :clubs, :position, :string, null: false add_column :clubs, :start_time, :date add_column :clubs, :end_time, :date add_column :clubs, :content, :text add_column :clubs, :current, :boolean, default: false end end
require 'vanagon/engine/base' require 'vanagon/logger' require 'json' require 'lock_manager' LOCK_MANAGER_HOST = ENV['LOCK_MANAGER_HOST'] || 'redis' LOCK_MANAGER_PORT = ENV['LOCK_MANAGER_PORT'] || 6379 VANAGON_LOCK_USER = ENV['USER'] class Vanagon class Engine # Class to use when building on a hardware device (e.g. AIX, Switch, etc) # class Hardware < Base # This method is used to obtain a vm to build upon # For the base class we just return the target that was passed in def select_target @target = node_lock(@build_hosts) end # Poll for a lock def polling_lock(host) Vanagon::Driver.logger.info "Polling for a lock on #{host}." @lockman.polling_lock(host, VANAGON_LOCK_USER, "Vanagon automated lock") Vanagon::Driver.logger.info "Lock acquired on #{host}." VanagonLogger.info "Lock acquired on #{host} for #{VANAGON_LOCK_USER}." host end # Iterate over the options and find a node open to lock. def node_lock(hosts) hosts.each do |h| Vanagon::Driver.logger.info "Attempting to lock #{h}." if @lockman.lock(h, VANAGON_LOCK_USER, "Vanagon automated lock") Vanagon::Driver.logger.info "Lock acquired on #{h}." VanagonLogger.info "Lock acquired on #{h} for #{VANAGON_LOCK_USER}." return h end end # If they are all locked, fall back to a polling lock on last item polling_lock(hosts.pop) end # Steps needed to tear down or clean up the system after the build is # complete. In this case, we'll attempt to unlock the hardware def teardown Vanagon::Driver.logger.info "Removing lock on #{@target}." VanagonLogger.info "Removing lock on #{@target}." @lockman.unlock(@target, VANAGON_LOCK_USER) end def initialize(platform, target, **opts) super Vanagon::Driver.logger.debug "Hardware engine invoked." @build_hosts = platform.build_hosts # Redis is the only backend supported in lock_manager currently @lockman = LockManager.new(type: 'redis', server: LOCK_MANAGER_HOST) @required_attributes << "build_hosts" end # Get the engine name def name 'hardware' end # Get the first build host name to build on def build_host_name if @build_host_name.nil? validate_platform # For now, get the first build host. In the future, lock management # will be pushed into the pooler (or something that wraps it), and # the hardware engine can go away. @build_host_name = @build_hosts.first end @build_host_name end end end end
class ErrorsController < ApplicationController before_action :set_error, only: [:destroy, :edit, :update, :show] before_action :move_to_index, except: [:index, :show, :search] def index @errors = Error.includes(:user).order('created_at DESC') end def new @error = Error.new end def create @error = Error.new(error_params) if @error.valid? @error.save redirect_to root_path else render :new end end def destroy if @error.destroy redirect_to root_path else render :edit end end def edit end def update if @error.update(error_params) redirect_to root_path else render :edit end end def show @comment = @error.comments.new @comments = @error.comments.includes(:user).order('created_at DESC') end def search @errors = Error.search(params[:keyword]).order('created_at DESC') end def about render :about end def category_show end def industry @errors = Error.where(industry_id: params[:industry_id]) end def own_error @errors = Error.where(own_error_id: params[:own_error_id]) end def human_factor @errors = Error.where(human_factor_id: params[:human_factor_id]) end def in_my_head @errors = Error.where(in_my_head_id: params[:in_my_head_id]) end private def set_error @error = Error.find(params[:id]) end def error_params params.require(:error).permit( :industry_id, :own_error_id, :human_factor_id, :in_my_head_id, :frequency_id, :try, :error, :learning, :next_action ).merge(user_id: current_user.id) end def move_to_index redirect_to root_path unless user_signed_in? end end
class Post < ActiveRecord::Base include Votable validates :title, :author, presence: true belongs_to :author, class_name: "User" has_many :sub_posts has_many :subs, through: :sub_posts, source: :sub has_many :comments has_many( :top_level_comments, -> { where("parent_comment_id IS NULL") }, class_name: "Comment" ) def comments_by_parent_id ret = Hash.new { [] } comments = Comment.order_by_score.where("comments.post_id = ?", self.id) comments.each do |comment| ret[comment.parent_comment_id] += [comment] end ret end end
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "kalimba/persistence/version" Gem::Specification.new do |gem| gem.name = "kalimba-redlander" gem.version = Kalimba::Persistence::Redlander::VERSION gem.authors = ["Slava Kravchenko"] gem.email = ["slava.kravchenko@gmail.com"] gem.description = %q{Redlander adapter for Kalimba. It provides the RDF storage backend for Kalimba.} gem.summary = %q{Redlander adapter for Kalimba} gem.homepage = "https://github.com/cordawyn/kalimba-redlander" gem.files = `git ls-files`.split($/) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.add_runtime_dependency "kalimba" gem.add_runtime_dependency "redlander", "~> 0.5.2" end
class Budget < ApplicationRecord belongs_to :user, optional: true has_many :transactions has_many :users, through: :transactions end
#!/usr/bin/env ruby # # Copyright:: Copyright 2016, Google Inc. All Rights Reserved. # # License:: 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. # # This example lists all existing campaigns for the specified user profile. require_relative '../dfareporting_utils' def get_campaigns(profile_id) # Authenticate and initialize API service. service = DfareportingUtils.initialize_service token = nil loop do result = service.list_campaigns(profile_id, page_token: token, fields: 'nextPageToken,campaigns(id,name)') # Display results. if result.campaigns.any? result.campaigns.each do |campaign| puts format('Found campaign with ID %d and name "%s".', campaign.id, campaign.name) end token = result.next_page_token else # Stop paging if there are no more results. token = nil end break if token.to_s.empty? end end if $PROGRAM_NAME == __FILE__ # Retrieve command line arguments. args = DfareportingUtils.parse_arguments(ARGV, :profile_id) get_campaigns(args[:profile_id]) end
require "date" class Rental attr_reader :distance, :car, :start_date, :end_date attr_accessor :discount, :commission, :id def initialize(car, start_date, end_date, distance, discount = 0) @id = nil @car = car @start_date = DateTime.parse(start_date) @end_date = DateTime.parse(end_date) @distance = Integer(distance) @commission = nil @discount = discount end def self.create_from_array(arr) ob = self.new( arr["car"], arr["start_date"], arr["end_date"], arr["distance"], arr["discount"].nil?? 0: arr["discount"] ) if !arr["id"].nil? ob.id = arr["id"] end return ob end def get_period Integer((@end_date - @start_date) + 1) end def get_raw_period_price self.get_period * car.price_per_day end def get_period_price self.get_raw_period_price - @discount end def get_raw_cost self.get_raw_period_price + (@distance * car.price_per_km) end def get_cost self.get_period_price + (@distance * car.price_per_km) end def get_transactions transactions = [] transactions << Transaction.new(User::DRIVER, TransactionType::DEBIT, self.get_cost) if self.commission transactions << Transaction.new(User::CAR_OWNER, TransactionType::CREDIT, (self.get_cost - self.commission.total)) transactions << Transaction.new(User::INSURANCE, TransactionType::CREDIT, self.commission.insurance) transactions << Transaction.new(User::ASSISTANCE, TransactionType::CREDIT, self.commission.assistance) transactions << Transaction.new(User::DRIVY, TransactionType::CREDIT, self.commission.drivy) end transactions end end
Pod::Spec.new do |s| s.name = 'VehicleID' s.version = '0.1.0' s.summary = 'Provides utilities to identify vehicles.' s.description = <<-DESC Provides a set of utilities to help identify a vehicle. DESC s.homepage = 'https://github.com/gpancio/VehicleID' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'Graham Pancio' => 'gpancio@yahoo.com' } s.source = { :git => 'https://github.com/gpancio/VehicleID.git', :tag => s.version.to_s } s.ios.deployment_target = '8.0' s.source_files = 'VehicleID/Classes/**/*' # s.resource_bundles = { # 'VehicleID' => ['VehicleID/Assets/*.png'] # } s.dependency 'MBProgressHUD', '~> 0.9.2' end
class MlsLookupType < ActiveRecord::Base attr_accessible :longvalue, :attr_lookup, :attr_resource, :shortvalue, :attr_date, :value, :app_title def self.get_for_filter(resource, lookup) self .select('longvalue AS name, value AS value') .order(:longvalue) .where('attr_lookup = ? AND attr_resource = ?', lookup, resource) .all end def self.all_towns_for_mls_name_options self .select('longvalue AS name, value AS value') .order(:longvalue) .where('attr_lookup = ? AND attr_resource = ?', 'Town', 'Property') .all end def self.all_counties_for_mls_name_options self .select('longvalue AS name, value AS value') .order(:longvalue) .where('attr_lookup = ? AND attr_resource = ?', 'County', 'Property') .all end def self.all_states_for_mls_name_options self .select('longvalue AS name, value AS value') .order(:longvalue) .where('attr_lookup = ? AND attr_resource = ?', 'State', 'Property') .all end end
class ChangeColumnPriority < ActiveRecord::Migration[5.1] def change rename_column :tasks, :priority, :position end end
class Admin::PagesController < ApplicationController permission_required :edit_content, :except => [ :destroy ] def index end def new @page = Page.new @page.language = Configuration['site.langs'].first if Configuration['site.langs'].size == 1 end def create @page = params[:page][:class_name].constantize.new(params[:page]) flash[:notice] = "Stránka byla vytvořena" if @page.valid? respond_to do |format| if @page.save @page.move_to_child_of(Page.find(params[:parent])) unless params[:parent].blank? make_appendixes params[:appendix], @page.id if params[:save_and_continue].blank? format.html { redirect_to(admin_pages_url) } else format.html { render :action => 'edit' } end else format.html { render :action => 'new' } end end end def edit @page = Page.find(params[:id]) end def edit_parent @page = Page.find(params[:id]) @pagelist = Page.all( :conditions => { :class_name => 'Page' } ) - [@page, @page.parent] end def update @page = Page.find(params[:id]) session[:last_body] = nil flash[:notice] = "Stránka byla upravena" if @page.valid? respond_to do |format| if params[:page] @page.class_name = params[:page][:class_name] params[:page][:slug] = "/" if @page.slug == "/" end if @page.update_attributes(params[:page]) @page.move_to_child_of(Page.find(params[:parent])) if ( not params[:parent].blank? ) and params[:parent].to_i > 0 and ( not @page.slug == "/" ) make_appendixes params[:appendix], @page.id if params[:save_and_continue].blank? format.html { redirect_to(admin_pages_url) } else format.html { render :action => 'edit' } end else format.html { render :action => 'edit' } end end end def destroy self.permission_options[:permission] = :destroy_content if check_permissions @page = Page.find( params[:id] ) unless @page.slug == '/' or (not @page.class == Page) flash[:notice] = "Stránka \"#{@page.title}\" byla smazána" @page.destroy end redirect_to admin_pages_url end end def add_appendix respond_to do |format| format.html { render :partial => 'admin/pages/add_appendix', :layout => false } end end def remove_appendix @appendix = Annex.find(params[:id]) @page = @appendix.page @appendix.destroy respond_to do |format| format.html { render :partial => 'admin/pages/appendixes', :layout => false } end end def pageslist session[:selected_language] = params[:lang] || "cz" respond_to do |format| format.html { render :partial => 'admin/pages/list_pages', :layout => false } end end def versions @page = Page.find( params[ :page ] ) if params[ :page ] case params[ :version ].to_i when 0 body = session[ :last_body ].blank? ? @page.versions.last.body : session[ :last_body ] when -1 session[ :last_body ] = params[ :page_body ] body = false else body = @page.versions.find( params[ :version ] ).body body = false if body.blank? end respond_to do |format| format.js { render :text => body } end end private def make_appendixes(appendixes, page) unless appendixes.blank? for appendix in appendixes appendix[:page_id] = page appendix[:class_name].constantize.create(appendix) end end true end end
name 'myemacs' maintainer 'Adam Edwards' maintainer_email 'adamed@opscode.com' license 'Apache 2.0' description 'Configures Emacs' long_description 'Configures Emacs' version '0.2.2' depends 'git' supports 'windows' supports 'ubuntu' supports 'mac_os_x' supports 'centos'
require 'test_helper' class NotifierTest < ActionMailer::TestCase test "order_received" do mail = Notifier.order_received(orders(:one)) assert_equal "EMusicStore уведомление о заказе", mail.subject assert_equal ["erofeevdn@yandex.ru"], mail.to assert_equal ["edenisn@gmail.com"], mail.from assert_match "", mail.body.encoded end test "order_shipped" do mail = Notifier.order_shipped(orders(:one)) assert_equal "EMusicStore товар отправлен", mail.subject assert_equal ["erofeevdn@yandex.ru"], mail.to assert_equal ["from@example.com"], mail.from assert_match "Hi", mail.body.encoded end end
require "minitest/autorun" require_relative '../../lib/arena/table.rb' class Table < Minitest::Test attr_reader :table def setup @table = Game::Table.new end def test_invalid_move? assert_equal true, table.invalid_move?(6,6) assert_equal true, table.invalid_move?(-1,6) end def test_valid_move? assert_equal false, table.invalid_move?(0,0) assert_equal false, table.invalid_move?(4,3) end end
require 'test_helper' class AnnotationTest < ActiveSupport::TestCase test 'render json' do object_keys = [:id, :type, :attributes, :relationships] attribute_keys = [:annotation_category_id, :detail, :created_at, :updated_at] annotation = Annotation.new(entry: create(:orga), annotation_category: AnnotationCategory.first, detail: 'FooBar') assert annotation.save, annotation.errors.messages json = JSON.parse(annotation.to_json).deep_symbolize_keys assert_equal(object_keys.sort, json.keys.sort) assert_equal(attribute_keys.sort, json[:attributes].keys.sort) assert json.key?(:relationships) end # test 'render todos json' do # object_keys = [:id, :type, :relationships] # relationships = [:entry] # todo = Annotation.new(entry: create(:orga), annotation_category: AnnotationCategory.first, detail: 'FooBar') # assert todo.save, todo.errors.messages # json = JSON.parse(todo.to_json).deep_symbolize_keys # assert_equal(object_keys.sort, json.keys.sort) # assert_not json.key?(:attributes) # assert_equal(relationships.sort, json[:relationships].keys.sort) # relationships.each do |relation| # assert_equal [:data], json[:relationships][relation].keys # if (data = json[:relationships][relation][:data]).is_a?(Array) # json[:relationships][relation][:data].each_with_index do |element, index| # assert_equal todo.send(relation)[index].to_hash, element # end # else # expected = # if todo.respond_to?("#{relation}_to_hash") # todo.send("#{relation}_to_hash") # else # todo.send(relation).to_hash(attributes: nil, relationships: nil) # end # # only care for type and id # assert_equal expected.slice(:type, :id), data.slice(:type, :id) # end # end # end end
class CheckIn < ActiveRecord::Base belongs_to :device has_many :check_in_apps end
DeviseAuthenticationApi::Application.routes.draw do devise_for :users, defaults: {format: :json}, skip: [:sessions, :passwords, :confirmations, :registrations, :unlock] # admin view user get 'admin/:authentication_token/users' => 'admin/users#show', defaults: {format: :json} # admin unlocks user account post 'admin/:authentication_token/users/unlock' => 'admin/unlocks#create', defaults: {format: :json} # admin suspends user account post 'admin/:authentication_token/users/suspend' => 'admin/suspends#create', defaults: {format: :json} # admin reinstates user account delete 'admin/:authentication_token/users/suspend' => 'admin/suspends#destroy', defaults: {format: :json} # admin adds admin rights to user post 'admin/:authentication_token/users/admin_user' => 'admin/admin_users#create', defaults: {format: :json} # admin removes admin rights from user delete 'admin/:authentication_token/users/admin_user' => 'admin/admin_users#destroy', defaults: {format: :json} # admin resends confirmation email post 'admin/:authentication_token/users/confirm' => 'admin/confirmation_emails#create', defaults: {format: :json} as :user do # registration post '/users' => 'registrations#create', as: 'user_registration', defaults: {format: :json} # session creation post '/sessions' => 'devise/sessions#create', as: 'user_session', defaults: {format: :json} # send password reset email post '/users/password' => 'devise/passwords#create', as: 'user_password', defaults: {format: :json} # reset user password patch '/users/password/:reset_password_token' => 'passwords#update', as: 'edit_user_password', defaults: {format: :json} # admin registration of user post '/admin/:authentication_token/users' => 'admin/registrations#create', defaults: {format: :json} # unlock locked account post '/users/unlock/:unlock_token' => 'unlocks#create', as: 'user_unlock', defaults: {format: :json} end # registration confirmation post 'users/confirmation/:confirmation_token' => 'confirmations#create', as: 'user_confirmation', defaults: {format: :json} # registration activation and password initialization post 'users/activation/:confirmation_token' => 'activations#create', defaults: {format: :json} # token based authentication get 'users/:authentication_token' => 'tokens#show', defaults: {format: :json} # password change patch 'users/:authentication_token' => 'users#update', defaults: {format: :json} # session deletion delete 'sessions/:authentication_token' => 'sessions#destroy', defaults: {format: :json} # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
#!/usr/bin/env ruby require File.join(File.dirname(__FILE__), '..', 'script', 'vp_script') require 'rubygems' require 'faster_csv' Dir.chdir RAILS_ROOT options = vp_script do |opts, options| opts.separator "" opts.on(:REQUIRED, "-f", "--file FILE", "Required file") do |f| options[:file] = f end end logger.fatal("No file given...exiting") and exit unless options[:file] time_started = Time.now count_nil_products = 0 count_no_pid = 0 count_update_stale_products = 0 count_mapping_existed = 0 count_partner_data_created = 0 FasterCSV.foreach(options[:file]) do |row| # Get the product object from the ID provided by Mobius product = Product.find_by_id(row[0]) if product.nil? || product.status != :active logger.info "* No active product found with ID #{row[0]}" count_nil_products += 1 next end # See if there's any data to work with if (row[1].blank? || row[1] == '0') && (row[3].blank? || row[3] == '0') logger.info "** No PID provided" count_no_pid += 1 next end logger.info "* #{product.title} (#{product.id})" # Determine the partner key, bail out if there isn't one partner_key = (row[2] == 'No') ? row[3] : row[1] if [nil,"",0].include?(partner_key) logger.info "** No PID provided" count_no_pid += 1 next end # See if there's an existing partner product and if the product is inactive/stale existing_partner_product = PartnerProduct.find_by_partner_key(partner_key) if existing_partner_product p = existing_partner_product.product logger.info "** Found existing partner product for partner key #{partner_key} mapped to #{p.title} (#{p.id})" if p.status != :active || p.num_reviews == 0 logger.info "**** Existing product is not active or has no reviews, replacing" count_update_stale_products += 1 existing_partner_product.update_attribute(:product_id, product.id) else logger.info "**** PID already in use, skipping" count_mapping_existed += 1 end next else logger.info "** No partner product found, creating" count_partner_data_created += 1 PartnerProduct.create(:source_id => 3, :product => product, :partner_key => partner_key, :sort_order => 1) end end logger.info "" logger.info "SUMMARY" logger.info "=======" logger.info "Time started: #{time_started}" logger.info "Product not found or not active: #{count_nil_products}" logger.info "No PID provided: #{count_no_pid}" logger.info "Partner products updated based on inactive/deleted/unreviewed: #{count_update_stale_products}" logger.info "PID was already in use: #{count_mapping_existed}" logger.info "Partner product data created: #{count_partner_data_created}" logger.info "Time ended: #{Time.now}"
class CategoriesController < ApplicationController helper_method :near_column, :sort_column, :sort_direction def index @categories = Category.all end def show @category = Category.find(params[:id]) if params[:near].present? @businesses = @category.businesses.near(near_column, 50, :order => :distance).paginate(:page => params[:page]) else @businesses = @category.businesses.order(sort_column + " " + sort_direction).paginate(:page => params[:page]) end end private def near_column if params[:near].present? params[:near] elsif @city + ", " + @state else "San Francisco" end end def sort_column if Business.column_names.include?(params[:sort]) if params[:sort] == "rating" "rating desc, review_count" else params[:sort] end else "name" end end def sort_direction %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc" end end
class CreateEducationalRelationships < ActiveRecord::Migration[5.1] def change create_table :educational_relationships do |t| t.references :educational, polymorphic: true, index: { name: 'index_on_educational_type_and_id' } t.references :education_program, index: { name: 'index_on_education_program_id' } t.timestamps end add_index :educational_relationships, [:educational_id, :educational_type, :education_program_id], name: 'index_unique', unique: true end end
require 'date' require './action' class Rental attr_accessor :start_date attr_accessor :end_date attr_accessor :distance def initialize(id, car:, start_date:, end_date:, distance:, deductible_reduction:) @id = id @car = car @start_date = start_date @end_date = end_date @days = calc_days @distance = distance @deductible_reduction = deductible_reduction end def total_price time_price + @car.price_per_km * @distance end def commission_amount total_price * 30 / 100 end def insurance_fee commission_amount / 2 end def assistance_fee @days * 100 end def drivy_fee commission_amount - insurance_fee - assistance_fee end def deductible_reduction_fee @deductible_reduction ? 400 * @days : 0 end # Compute rental actions for each actor def actions return [ action_for('driver'), action_for('owner'), action_for('insurance'), action_for('assistance'), action_for('drivy') ] end # Create action for a given actor def action_for(actor) case actor when 'driver' Action.debit(from: 'driver', amount: total_price + deductible_reduction_fee) when 'owner' Action.credit(to: 'owner', amount: total_price - commission_amount) when 'insurance' Action.credit(to: 'insurance', amount: insurance_fee) when 'assistance' Action.credit(to: 'assistance', amount: assistance_fee) when 'drivy' Action.credit(to: 'drivy', amount: drivy_fee + deductible_reduction_fee) else raise 'Unknown actor' end end # Compute all actions needed given updates on rental time / distance def actions_for_update(start_date: @start_date, end_date: @end_date, distance: @distance) # Compute original actions driver_action = action_for('driver') owner_action = action_for('owner') insurance_action = action_for('insurance') assistance_action = action_for('assistance') drivy_action = action_for('drivy') # Update rental data @start_date = start_date @end_date = end_date @days = calc_days @distance = distance return [ driver_action.diff(action_for('driver')), owner_action.diff(action_for('owner')), insurance_action.diff(action_for('insurance')), assistance_action.diff(action_for('assistance')), drivy_action.diff(action_for('drivy')) ] end def to_hash return { :id => @id, :price => total_price, :options => { :deductible_reduction => deductible_reduction_fee }, :commission => { :insurance_fee => insurance_fee, :assistance_fee => assistance_fee, :drivy_fee => drivy_fee } } end private # Compute the final price for time component, with eventual discount def time_price price = 0 @days.downto(1) do |day| disc = 0 if day > 10 disc = 50 elsif day > 4 disc = 30 elsif day > 1 disc = 10 end price += @car.price_per_day - (@car.price_per_day * disc / 100) end return price end def calc_days start_at = Date.parse(@start_date) end_at = Date.parse(@end_date) return (end_at - start_at).to_i + 1 end end
require 'test_helper' class D2L::Dataclips::ResultTest < Minitest::Unit::TestCase def test_that_fields_are_required err = assert_raises D2L::Dataclips::Error do D2L::Dataclips::Result.from({ 'fields' => nil, 'values' => [] }) end assert_equal err.message, "'fields' is missing" end def test_that_values_are_required err = assert_raises D2L::Dataclips::Error do D2L::Dataclips::Result.from({ 'fields' => [], 'values' => nil }) end assert_equal err.message, "'values' is missing" end def test_that_fields_is_an_array err = assert_raises D2L::Dataclips::Error do D2L::Dataclips::Result.from({ 'fields' => {}, 'values' => [] }) end assert_equal err.message, "'fields' is not an array" end def test_that_values_is_an_array err = assert_raises D2L::Dataclips::Error do D2L::Dataclips::Result.from({ 'fields' => [], 'values' => {} }) end assert_equal err.message, "'values' is not an array" end def test_empty_fields_raise_error err = assert_raises D2L::Dataclips::Error do result = D2L::Dataclips::Result.from({ 'fields' => [], 'values' => [[1]] }) end assert_equal err.message, "'fields' is empty" end def test_more_fields_than_in_values_raise_error err = assert_raises D2L::Dataclips::Error do result = D2L::Dataclips::Result.from({ 'fields' => ['a', 'b'], 'values' => [[1]] }) end assert_equal err.message, "value '[1]' has not the right fields [:a, :b]" end def test_correctly_formatted_json_returns_a_result result = D2L::Dataclips::Result.from({ 'fields' => ['count'], 'values' => [['1'], ['4']] }) assert_equal result.values.size, 2 assert_respond_to result.values.first, :count assert_equal result.values.first.count, '1' assert_equal result.values.first['count'], '1' end def test_empty_returns_if_values_is_empty result = D2L::Dataclips::Result.new([], []) assert result.empty? end end
require 'spec_helper' describe BillsController do login_user create_account describe "GET #edit" do it "assigns the requested bill as @bill" do bill = create(:bill, account_id: @account.id) get :edit, id: bill expect(assigns(:bill)).to eq bill end it "renders the edit template" do bill = create(:bill, account_id: @account.id) get :edit, id: bill expect(response).to render_template :edit end end describe "PATCH #update" do before :each do @bill = create(:bill, account_id: @account.id, description: "large bill", amount: 10) end context "with valid entries" do it "finds the bill in question" do patch :update, id: @bill, bill: attributes_for(:bill) expect(assigns(:bill)).to eq(@bill) end it "applies the requested changes" do patch :update, id: @bill, bill: attributes_for(:bill, description: "New bill") @bill.reload expect(@bill.description).to eq "New bill" end it "redirects to the bills index" do patch :update, id: @bill, bill: attributes_for(:bill) expect(response).to redirect_to bills_path end end context "with invalid attributes" do it "does not save the updated bill to the database" do patch :update, id: @bill, bill: attributes_for(:bill).merge(amount: "") expect(@bill.amount).to eq 10 end it "renders the edit template" do patch :update, id: @bill, bill: attributes_for(:bill).merge(amount: "") expect(response).to render_template :edit end end end end
#!/usr/bin/env ruby require 'fileutils' require 'pp' require 'rubygems' require 'jira-ruby' require 'json' # prerequisite: # gem install jira-ruby # interactive script--no args needed # just run ./jira -c or ./jira -b # it'll ask for confirmation before making changes # # requires: # - `fzf` on $PATH # - $JIRA_USERNAME set (email address) # - $JIRA_TOKEN set (i forget where i got mine tbh) # # this might be where you find api tokens # https://id.atlassian.com/manage/api-tokens def command?(name) `which #{name}` $?.success? end def env?(name) v = ENV[name] v and v.chomp != "" end throw "This script requires fzf" unless command? "fzf" throw "This script requires $JIRA_USERNAME in env" unless env? "JIRA_USERNAME" throw "This script requires $JIRA_TOKEN in env" unless env? "JIRA_TOKEN" $cache_dir = "#{ENV["HOME"]}/.cache" module Cache @@dir = $cache_dir def clear fileutils.rm_rf(@@dir) end def set(k,v) Dir.mkdir(@@dir) unless File.exists?(@@dir) old = Dir["#{k}-*"][0] File.delete(old) if old File.write("#{@@dir}/#{k}-#{Time.now.to_i}", v.to_json) end def get(k, max_age = 60 * 60 * 4) now = Time.now.to_i path = Dir["#{@@dir}/#{k}-*"][0] date = File.basename(path)["#{k}-".length..-1].to_i if path if date and max_age != nil and date > (now - max_age) return JSON.parse(File.read(path)) end return false end def read_through(k, max_age = 60 * 60 * 4) got = get(k, max_age) return got if got puts "Fetching #{k}..." new = JSON.parse(yield.to_json) set(k, new) new end end module Terminal @@dir = $cache_dir @@pipefile = nil def pipefile if @@pipefile == nil Dir.mkdir(@@dir) unless File.exists?(@@dir) @@pipefile = "#{@@dir}/tmp-#{`date "+%Y-%m-%d-%H%M%S-#{rand 10}"`}".chomp end @@pipefile end def write(stdin) File.write(pipefile, stdin) end def read File.read(pipefile) end # lol oof this is probably slow or something # TODO: figure out irl streams def pipe_to(stdin, cmd) write stdin `cat #{pipefile} | #{cmd}` end def vim(stdin) write stdin system("vim #{pipefile}") read end # this api is kinda stupid. should have one function # - allow-no-input is kw arg # - accept-unknown-value is kw arg def select(options) result = pipe_to("\n" + options.join("\n"), "fzf").chomp result == "" ? false : result end def select_or_create(options) lines = pipe_to(options.join("\n"), "fzf --print-query").chomp.split("\n") result = lines.length == 1 ? lines[0] : lines[1] result == "" ? false : result end end module Jira include Terminal include Cache @@options = { :username => ENV["JIRA_USERNAME"], :password => ENV["JIRA_TOKEN"], :site => 'https://samsaradev.atlassian.net', :context_path => '', :auth_type => :basic } @@client = JIRA::Client.new(@@options) def client @@client end def issuetypes(project_id) Cache.read_through("#{project_id}-issuetypes") do client.Project.find(project_id).issueTypes.map do |t| t["name"] end end end def users(project_id) Cache.read_through("#{project_id}-users") do client.Project.find(project_id).users(max_results: 1000).map do |u| u.name end end end def issues(project_id) Cache.read_through("#{project_id}-issues") do client.Issue.jql("project = #{project_id}").map do |i| "#{i.key}| #{i.summary}" end end end # TODO jank string bs use data or something def epics(project_id) Cache.read_through("#{project_id}-epics") do client.Issue.jql("project = #{project_id} and type = 'epic'").map do |i| "#{i.key}| #{i.summary}" end end end def fields Cache.read_through("all-fields", 60 * 60 * 24 * 7) do JIRA::Resource::Createmeta.all(client, expand: "projects.issuetypes.fields") end end def url(issue) "#{@@options[:site]}/browse/#{issue["key"]}" end def field_by_name(project_id, issue_type, field_name) project = fields.find do |p| p["key"] == project_id end issue_type = project["issuetypes"].find do |i| i["name"] == issue_type end field = issue_type["fields"].values.find do |f| f["name"].downcase.include? field_name.downcase end puts "Inferred '#{field["name"]}' as custom field matching '#{field_name}'" field["key"] end def build client.Field.map_fields fields = {} # project project = "MOB" throw "error" unless project fields["project"] = {"key" => project} # summary print "Summary: " summary = gets.chomp throw "error" unless summary != "" fields["summary"] = summary # issue type issuetype = Terminal.select(issuetypes(project)) throw "error" unless issuetype fields["issuetype"] = {"name" => issuetype} # assignee assignee = Terminal.select(users(project)) fields["assignee"] = {"name" => assignee} if assignee # description description = Terminal.vim("").chomp fields["description"] = description if description != "" # story points print "Story points: " storypoints = gets.chomp fields[field_by_name(project, issuetype, "story")] = storypoints.to_i if storypoints != "" # epic epic = Terminal.select(epics(project)) puts epic fields[field_by_name(project, issuetype, "epic")] = epic.split("|")[0].chomp if epic # TODO: prompt for "components" # - can get from createmeta # - use fzf --multi to select >1 # todo: ask if it should be in the active sprint # use boards api to get boards in project, then sprints in board, then filter active # :grimacing: puts pp fields puts print "create? y/n: " exit 1 if gets.chomp() != "y" fields end def create fields = build issue = client.Issue.build issue.save({"fields" => fields}) or throw "API error" issue end def browse # project project = "MOB" throw "error" unless project key = Terminal.select(issues(project)).split("|")[0].chomp JSON.parse client.Issue.find(key).to_json end end module CLI include Jira def main if ARGV.include? "create" ARGV.clear puts JIRA.url Jira.create exit 0 end puts JIRA.url JIRA.browse exit 0 end end include CLI CLI.main
module Navigable extend ActiveSupport::Concern included do before_action do if (content_item = request.env[:content_item]) setup_content_item(content_item) else fetch_and_setup_content_item("/#{params[:slug]}") end end end end
class CreditCompaniesController < ApplicationController before_action :set_credit_company, only: [:show, :edit, :update, :destroy] before_action :authorize_for_managing # GET /credit_companies # GET /credit_companies.json def index @credit_companies = CreditCompany.all.page(params[:page]).per(10) end # GET /credit_companies/1 # GET /credit_companies/1.json def show end # GET /credit_companies/new def new @credit_company = CreditCompany.new end # GET /credit_companies/1/edit def edit end # POST /credit_companies # POST /credit_companies.json def create @credit_company = CreditCompany.new(credit_company_params) respond_to do |format| if @credit_company.save format.html { redirect_to @credit_company, notice: t('credit_company.created') } format.json { render :show, status: :created, location: @credit_company } else format.html { render :new } format.json { render json: @credit_company.errors, status: :unprocessable_entity } end end end # PATCH/PUT /credit_companies/1 # PATCH/PUT /credit_companies/1.json def update respond_to do |format| if @credit_company.update(credit_company_params) format.html { redirect_to @credit_company, notice: t('credit_company.updated') } format.json { render :show, status: :ok, location: @credit_company } else format.html { render :edit } format.json { render json: @credit_company.errors, status: :unprocessable_entity } end end end # DELETE /credit_companies/1 # DELETE /credit_companies/1.json def destroy @credit_company.destroy respond_to do |format| format.html { redirect_to credit_companies_url, notice: t('credit_company.destroyed') } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_credit_company @credit_company = CreditCompany.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def credit_company_params params.require(:credit_company).permit(:name, :short_name, :identifier, :contact, :phone, :email, :website, :location_id, :executive_id) end def authorize_for_managing authorize CreditCompany, :manage? end end
class Message < ApplicationRecord validates :postid, {presence: true} validates :content, {presence: true} end
require 'boxzooka/item' module Boxzooka # Request to populate Boxzooka's Item metadata from our own. class CatalogRequest < BaseRequest # List of Items collection :items, entry_node_name: 'Item', entry_field_type: :entity, entry_type: Boxzooka::Item end end
class Event < ApplicationRecord belongs_to :organizer, class_name: 'User', foreign_key: 'organizer_id' belongs_to :location has_many :tickets has_one_attached :image default_scope { order(start_date: :desc) } scope :keyword_search, -> (params) { if params[:keyword].present? joins(:location).where('events.name ilike ? or locations.display_name ilike ?', "%#{params[:keyword]}%", "%#{params[:keyword]}%") else all end } scope :date_search, -> (params) { if params[:start_date].present? where('events.start_date >= ? and events.end_date <= ?', params[:start_date].beginning_of_day, params.fetch(:end_date, params[:start_date]).end_of_day) else all end } scope :unsold_events, -> { where('events.attending_count is not null and (events.attending_count > (SELECT COUNT(tickets.id) FROM tickets WHERE tickets.event_id = events.id))') } scope :type_search, -> (params) { (params[:type].present? && params[:type] != 'All') ? where('events.event_type': params[:type]) : all } def location_name self.location.display_name end def self.apply_filters(params) self.keyword_search(params).type_search(params).date_search(params) end def ticket_available? self.attending_count.to_i > self.tickets.count end def expected_revenue self.ticket_price.to_f * self.attending_count.to_i end def actual_revenue self.ticket_price.to_f * self.tickets.count end def tickets_available return 0 if !ticket_available? self.attending_count.to_i - self.tickets.count end end
Rails.application.routes.draw do get'projects/index' #get 'projects/dashboard' post 'projects/new' get 'dashboard', to: 'projects#dashboard' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html root 'projects#index' end
class CreateDogWalkings < ActiveRecord::Migration[5.2] def change create_table :dog_walkings, id: :uuid do |t| t.integer :status, default: 0 t.datetime :schedule_date t.float :price t.float :duration t.decimal :latitude, { precision: 10, scale: 6 } t.decimal :longitude, { precision: 10, scale: 6 } t.integer :pets t.datetime :start_date t.datetime :end_date t.timestamps end end end
module ActiveSesame::Behaviors module Ontology def self.mimic(klass, options={}) defaults = {:repository => ActiveSesame::Repository.new, :ontology_attribute => :name} defaults.merge!(options) klass.send(:include, self) klass.repository = defaults[:repository] klass.ontology_attribute = defaults[:ontology_attribute] return klass end def self.included(klass) class << klass attr_accessor :ontology_attribute, :repository end klass.ontology_attribute = :name klass.repository = ActiveSesame::Repository.new klass.class_eval do def self.set_ontology_attribute(value,&block) block_given? ? attribute_value = yield(value) : attribute_value = value self.ontology_attribute = value.to_sym end def self.set_repository(repository) self.repository = repository end end end def ontology @ontology ||= ActiveSesame::Ontology::Term.new(self.send(self.class.ontology_attribute), self.class.repository) end end end
# # Cookbook Name:: postgresql # Provider:: default # # Author:: LLC Express 42 (info@express42.com) # # Copyright (C) 2012-2013 LLC Express 42 # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is furnished to do # so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # action :create do cluster_databag = new_resource.databag if cluster_databag begin cluster_users = data_bag_item(cluster_databag, 'users')['users'] rescue cluster_users = {} end begin cluster_databases = data_bag_item(cluster_databag, 'databases')['databases'] rescue cluster_databases = {} end end configuration = Chef::Mixin::DeepMerge.merge(node["postgresql"]["defaults"]["server"].to_hash, new_resource.configuration) hba_configuration = node["postgresql"]["defaults"]["hba_configuration"] | new_resource.hba_configuration ident_configuration = node["postgresql"]["defaults"]["ident_configuration"] | new_resource.ident_configuration if new_resource.cluster_create_options.has_key?("locale") and not new_resource.cluster_create_options["locale"].empty? system_lang = ENV['LANG'] ENV['LANG'] = new_resource.cluster_create_options["locale"] end %W{postgresql-#{configuration[:version]} postgresql-server-dev-all}.each do |pkg| package pkg do action :nothing end.run_action(:install) end if new_resource.cluster_create_options.has_key?("locale") and not new_resource.cluster_create_options["locale"].empty? ENV['LANG'] = system_lang end create_cluster(new_resource.name, configuration, hba_configuration, ident_configuration, new_resource.replication, Mash.new(new_resource.cluster_create_options)) if cluster_databag cluster_users.each_pair do |cluster_user, user_options| create_user(cluster_user, configuration, user_options["options"]) end cluster_databases.each_pair do |cluster_database, database_options| create_database(cluster_database, configuration, database_options["options"]) end end end private def create_cluster(cluster_name, configuration, hba_configuration, ident_configuration, replication, cluster_options) parsed_cluster_options = [] parsed_cluster_options << "--locale #{cluster_options[:locale]}" if cluster_options[:locale] parsed_cluster_options << "--lc-collate #{cluster_options[:'lc-collate']}" if cluster_options[:'lc-collate'] parsed_cluster_options << "--lc-ctype #{cluster_options[:'lc-ctype']}" if cluster_options[:'lc-ctype'] parsed_cluster_options << "--lc-messages #{cluster_options[:'lc-messages']}" if cluster_options[:'lc-messages'] parsed_cluster_options << "--lc-monetary #{cluster_options[:'lc-monetary']}" if cluster_options[:'lc-monetary'] parsed_cluster_options << "--lc-numeric #{cluster_options[:'lc-numeric']}" if cluster_options[:'lc-numeric'] parsed_cluster_options << "--lc-time #{cluster_options[:'lc-time']}" if cluster_options[:'lc-time'] if ::File.exist?("/etc/postgresql/#{configuration[:version]}/#{cluster_name}/postgresql.conf") Chef::Log.info("postgresql_cluster:create - cluster #{configuration[:version]}/#{cluster_name} already exists, skiping") else io_output = IO.popen( "pg_createcluster #{parsed_cluster_options.join(' ')} #{configuration[:version]} #{cluster_name}" ) string_output=io_output.readlines.join io_output.close if $?.exitstatus != 0 raise "pg_createcluster #{parsed_cluster_options.join(' ')} #{configuration[:version]} #{cluster_name} - returned #{$?.exitstatus}, expected 0" else Chef::Log.info( "postgresql_cluster:create - cluster #{configuration[:version]}/#{cluster_name} created" ) new_resource.updated_by_last_action(true) end end if configuration[:version] == '9.3' configuration[:connection][:unix_socket_directories] ||= configuration[:connection][:unix_socket_directory] configuration[:connection].delete :unix_socket_directory end configuration_template = template "/etc/postgresql/#{configuration[:version]}/#{cluster_name}/postgresql.conf" do action :nothing source "postgresql.conf.erb" owner "postgres" group "postgres" mode 0644 variables :configuration => configuration, :cluster_name => cluster_name if new_resource.cookbook cookbook new_resource.cookbook else cookbook "postgresql" end end hba_template = template "/etc/postgresql/#{configuration[:version]}/#{cluster_name}/pg_hba.conf" do action :nothing source "pg_hba.conf.erb" owner "postgres" group "postgres" mode 0644 variables :configuration => hba_configuration if new_resource.cookbook cookbook new_resource.cookbook else cookbook "postgresql" end end ident_template = template "/etc/postgresql/#{configuration[:version]}/#{cluster_name}/pg_ident.conf" do action :nothing source "pg_ident.conf.erb" owner "postgres" group "postgres" mode 0644 variables :configuration => ident_configuration if new_resource.cookbook cookbook new_resource.cookbook else cookbook "postgresql" end end replication_template = template "/var/lib/postgresql/#{configuration[:version]}/#{cluster_name}/recovery.conf" do action :nothing source "recovery.conf.erb" owner "postgres" group "postgres" mode 0644 variables :replication => replication if new_resource.cookbook cookbook new_resource.cookbook else cookbook "postgresql" end end postgresql_service = service "postgresql" do status_command "su -c '/usr/lib/postgresql/#{configuration[:version]}/bin/pg_ctl \ -D /var/lib/postgresql/#{configuration[:version]}/#{cluster_name} status' postgres" supports :status => true, :restart => true, :reload => true action :enable end configuration_template.run_action(:create) hba_template.run_action(:create) ident_template.run_action(:create) replication_file = "/var/lib/postgresql/#{configuration[:version]}/#{cluster_name}/recovery.conf" if replication.empty? ::File.exist?( replication_file ) and ::File.unlink( replication_file ) postgresql_service.run_action(:start) else replication_template.run_action(:create) end if configuration_template.updated_by_last_action? or hba_template.updated_by_last_action? or ident_template.updated_by_last_action? postgresql_service.run_action(:reload) new_resource.updated_by_last_action(true) end end def create_database(cluster_database, configuration, database_options) parsed_database_options = [] if cluster_database parsed_database_options << "--locale=#{database_options['locale']}" if database_options['locale'] parsed_database_options << "--lc-collate=#{database_options['lc-collate']}" if database_options['lc-collate'] parsed_database_options << "--lc-ctype=#{database_options['lc-ctype']}" if database_options['lc-ctype'] parsed_database_options << "--owner=#{database_options['owner']}" if database_options['owner'] parsed_database_options << "--template=#{database_options['template']}" if database_options['template'] parsed_database_options << "--tablespace=#{database_options['tablespace']}" if database_options['tablespace'] end io_output = IO.popen("echo 'SELECT datname FROM pg_database;' | su -c 'psql -t -A -p #{configuration["connection"]["port"]}' postgres") current_databases_list = io_output.readlines.map { |line| line.chop } io_output.close raise "postgresql_database:create - can't get database list" if $?.exitstatus !=0 if current_databases_list.include? cluster_database Chef::Log.info("postgresql_database:create - database '#{cluster_database}' already exists, skiping") else io_output =IO.popen("su -c 'createdb #{parsed_database_options.join(' ')} #{cluster_database} -p #{configuration["connection"]["port"]}' postgres") io_output.close raise "postgresql_database:create - can't create database #{cluster_database}" if $?.exitstatus !=0 Chef::Log.info("postgresql_database:create - database '#{cluster_database}' created") end end def create_user(cluster_user, configuration, user_options) parsed_user_options = [] if user_options parsed_user_options << "REPLICATION" if user_options["replication"] =~ /\A(true|yes)\Z/i parsed_user_options << "SUPERUSER" if user_options["superuser"] =~ /\A(true|yes)\Z/i parsed_user_options << "UNENCRYPTED PASSWORD '#{user_options["password"]}'" if user_options["password"] end io_output = IO.popen("echo 'SELECT usename FROM pg_user;' | su -c 'psql -t -A -p #{configuration["connection"]["port"]}' postgres") current_users_list = io_output.readlines.map { |line| line.chop } io_output.close raise "postgresql_user:create - can't get users list" if $?.exitstatus !=0 if current_users_list.include? cluster_user Chef::Log.info("postgresql_user:create - user '#{cluster_user}' already exists, skiping") else io_output =IO.popen("echo \"CREATE USER #{cluster_user} #{parsed_user_options.join(' ')};\" | su -c 'psql -t -A -p #{configuration["connection"]["port"]}' postgres") create_response = io_output.readlines io_output.close if not create_response.include?("CREATE ROLE\n") raise "postgresql_user:create - can't create user #{cluster_user}" end Chef::Log.info("postgresql_user:create - user '#{cluster_user}' created") end end
# Copyright (c) 2011 Nick Markwell # Released under the ISC license. See LICENSE. # If this does not work properly, read the README file. require 'yaml' class VolumeConfig def self.get file = nil if File.exist?(File.join(File.dirname(__FILE__), 'config.yaml')) file = File.join(File.dirname(__FILE__), 'config.yaml') else file = File.join(File.dirname(__FILE__), 'config.yaml.dist') end raise "No config file found!" unless file return YAML.load_file(file) end end
require "#{ENV['CORTO_BUILD']}/common" COMPONENTS = [] if not defined? COMPONENTS task :all => :default task :default do COMPONENTS.each do |e| verbose(VERBOSE) if ENV['silent'] != "true" then sh "echo '#{C_BOLD}[ >> entering #{C_NORMAL}#{C_NAME}#{e}#{C_NORMAL}#{C_BOLD} ]#{C_NORMAL}'" end sh "rake -f #{e}/rakefile" if ENV['silent'] != "true" then sh "echo '#{C_BOLD}[ << leaving #{C_NORMAL}#{C_NAME}#{e}#{C_NORMAL}#{C_BOLD} ]#{C_NORMAL}'" end end end task :collect do COMPONENTS.each do |e| verbose(false) sh "rake collect -f #{e}/rakefile" end end task :clean do COMPONENTS.each do |e| verbose(VERBOSE) sh "rake clean -f #{e}/rakefile" if File.exists? "#{e}/test/rakefile" then sh "rake clean -f #{e}/test/rakefile" end end end task :clobber do COMPONENTS.each do |e| verbose(VERBOSE) sh "rake clobber -f #{e}/rakefile" if File.exists? "#{e}/test/rakefile" then sh "rake clobber -f #{e}/test/rakefile" end end end task :test do verbose(VERBOSE) error = 0 COMPONENTS.each do |e| if File.exists? "#{e}" then begin sh "rake test -f #{e}/rakefile" rescue error = 1 end end end if File.exists? "test" then begin sh "rake -f test/rakefile silent=true" sh "rake test -f test/rakefile" rescue error = 1 end end if error != 0 then abort end end task :gcov do COMPONENTS.each do |e| verbose(VERBOSE) if ENV['silent'] != "true" then sh "echo '#{C_BOLD}[ >> entering #{C_NORMAL}#{C_NAME}#{e}#{C_NORMAL}#{C_BOLD} ]#{C_NORMAL}'" end sh "rake gcov -f #{e}/rakefile" if ENV['silent'] != "true" then sh "echo '#{C_BOLD}[ << leaving #{C_NORMAL}#{C_NAME}#{e}#{C_NORMAL}#{C_BOLD} ]#{C_NORMAL}'" end end end task :sha do FileList.new("**/.git/config").each do |gitconfig| git_dir = gitconfig.pathmap("%d") remote = `git --git-dir #{git_dir} config --get remote.origin.url` if not remote.empty? remote = remote.chomp().split("/").slice(-2, 2).join("/") sha = `git --git-dir #{git_dir} rev-parse HEAD`.chomp() else remote = git_dir.pathmap("%d") sha = "unknown" end puts "#{remote}@#{sha}" end end
require 'rails_helper' RSpec.describe LocationGroup, type: :model do it { should validate_presence_of(:name) } it { should belong_to(:country) } it { should have_many(:locations).through(:location_relations) } end
class Cruise < ApplicationRecord belongs_to :user belongs_to :project has_many :data has_many :equipments validates :ship, presence: :true validates :project, presence: :true validates :responsible, presence: :true validates :field, presence: :true end
=begin Copyright (c) 2019 Aspose Pty Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =end require 'date' module AsposeSlidesCloud # Provides options that control how a presentation is saved in SWF format. class SwfExportOptions # Export format. attr_accessor :format # Specifies whether the generated document should include hidden slides or not. Default is false. attr_accessor :show_hidden_slides # Specifies whether the generated SWF document should be compressed or not. Default is true. attr_accessor :compressed # Specifies whether the generated SWF document should include the integrated document viewer or not. Default is true. attr_accessor :viewer_included # Specifies whether border around pages should be shown. Default is true. attr_accessor :show_page_border # Show/hide fullscreen button. Can be overridden in flashvars. Default is true. attr_accessor :show_full_screen # Show/hide page stepper. Can be overridden in flashvars. Default is true. attr_accessor :show_page_stepper # Show/hide search section. Can be overridden in flashvars. Default is true. attr_accessor :show_search # Show/hide whole top pane. Can be overridden in flashvars. Default is true. attr_accessor :show_top_pane # Show/hide bottom pane. Can be overridden in flashvars. Default is true. attr_accessor :show_bottom_pane # Show/hide left pane. Can be overridden in flashvars. Default is true. attr_accessor :show_left_pane # Start with opened left pane. Can be overridden in flashvars. Default is false. attr_accessor :start_open_left_pane # Enable/disable context menu. Default is true. attr_accessor :enable_context_menu # Image that will be displayed as logo in the top right corner of the viewer. The image data is a base 64 string. Image should be 32x64 pixels PNG image, otherwise logo can be displayed improperly. attr_accessor :logo_image # Gets or sets the full hyperlink address for a logo. Has an effect only if a LogoImage is specified. attr_accessor :logo_link # Specifies the quality of JPEG images. Default is 95. attr_accessor :jpeg_quality # Gets or sets the position of the notes on the page. attr_accessor :notes_position # Gets or sets the position of the comments on the page. attr_accessor :comments_position # Gets or sets the width of the comment output area in pixels (Applies only if comments are displayed on the right). attr_accessor :comments_area_width # Gets or sets the color of comments area (Applies only if comments are displayed on the right). attr_accessor :comments_area_color # True if comments that have no author are displayed. (Applies only if comments are displayed). attr_accessor :show_comments_by_no_author class EnumAttributeValidator attr_reader :datatype attr_reader :allowable_values def initialize(datatype, allowable_values) @allowable_values = allowable_values.map do |value| case datatype.to_s when /Integer/i value.to_i when /Float/i value.to_f else value end end end def valid?(value) !value || allowable_values.any?{ |s| s.casecmp(value) == 0 } end end # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'format' => :'Format', :'show_hidden_slides' => :'ShowHiddenSlides', :'compressed' => :'Compressed', :'viewer_included' => :'ViewerIncluded', :'show_page_border' => :'ShowPageBorder', :'show_full_screen' => :'ShowFullScreen', :'show_page_stepper' => :'ShowPageStepper', :'show_search' => :'ShowSearch', :'show_top_pane' => :'ShowTopPane', :'show_bottom_pane' => :'ShowBottomPane', :'show_left_pane' => :'ShowLeftPane', :'start_open_left_pane' => :'StartOpenLeftPane', :'enable_context_menu' => :'EnableContextMenu', :'logo_image' => :'LogoImage', :'logo_link' => :'LogoLink', :'jpeg_quality' => :'JpegQuality', :'notes_position' => :'NotesPosition', :'comments_position' => :'CommentsPosition', :'comments_area_width' => :'CommentsAreaWidth', :'comments_area_color' => :'CommentsAreaColor', :'show_comments_by_no_author' => :'ShowCommentsByNoAuthor' } end # Attribute type mapping. def self.swagger_types { :'format' => :'String', :'show_hidden_slides' => :'BOOLEAN', :'compressed' => :'BOOLEAN', :'viewer_included' => :'BOOLEAN', :'show_page_border' => :'BOOLEAN', :'show_full_screen' => :'BOOLEAN', :'show_page_stepper' => :'BOOLEAN', :'show_search' => :'BOOLEAN', :'show_top_pane' => :'BOOLEAN', :'show_bottom_pane' => :'BOOLEAN', :'show_left_pane' => :'BOOLEAN', :'start_open_left_pane' => :'BOOLEAN', :'enable_context_menu' => :'BOOLEAN', :'logo_image' => :'String', :'logo_link' => :'String', :'jpeg_quality' => :'Integer', :'notes_position' => :'String', :'comments_position' => :'String', :'comments_area_width' => :'Integer', :'comments_area_color' => :'String', :'show_comments_by_no_author' => :'BOOLEAN' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } if attributes.has_key?(:'Format') self.format = attributes[:'Format'] else self.format = "swf" end if attributes.has_key?(:'ShowHiddenSlides') self.show_hidden_slides = attributes[:'ShowHiddenSlides'] end if attributes.has_key?(:'Compressed') self.compressed = attributes[:'Compressed'] end if attributes.has_key?(:'ViewerIncluded') self.viewer_included = attributes[:'ViewerIncluded'] end if attributes.has_key?(:'ShowPageBorder') self.show_page_border = attributes[:'ShowPageBorder'] end if attributes.has_key?(:'ShowFullScreen') self.show_full_screen = attributes[:'ShowFullScreen'] end if attributes.has_key?(:'ShowPageStepper') self.show_page_stepper = attributes[:'ShowPageStepper'] end if attributes.has_key?(:'ShowSearch') self.show_search = attributes[:'ShowSearch'] end if attributes.has_key?(:'ShowTopPane') self.show_top_pane = attributes[:'ShowTopPane'] end if attributes.has_key?(:'ShowBottomPane') self.show_bottom_pane = attributes[:'ShowBottomPane'] end if attributes.has_key?(:'ShowLeftPane') self.show_left_pane = attributes[:'ShowLeftPane'] end if attributes.has_key?(:'StartOpenLeftPane') self.start_open_left_pane = attributes[:'StartOpenLeftPane'] end if attributes.has_key?(:'EnableContextMenu') self.enable_context_menu = attributes[:'EnableContextMenu'] end if attributes.has_key?(:'LogoImage') self.logo_image = attributes[:'LogoImage'] end if attributes.has_key?(:'LogoLink') self.logo_link = attributes[:'LogoLink'] end if attributes.has_key?(:'JpegQuality') self.jpeg_quality = attributes[:'JpegQuality'] end if attributes.has_key?(:'NotesPosition') self.notes_position = attributes[:'NotesPosition'] end if attributes.has_key?(:'CommentsPosition') self.comments_position = attributes[:'CommentsPosition'] end if attributes.has_key?(:'CommentsAreaWidth') self.comments_area_width = attributes[:'CommentsAreaWidth'] end if attributes.has_key?(:'CommentsAreaColor') self.comments_area_color = attributes[:'CommentsAreaColor'] end if attributes.has_key?(:'ShowCommentsByNoAuthor') self.show_comments_by_no_author = attributes[:'ShowCommentsByNoAuthor'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new if @show_hidden_slides.nil? invalid_properties.push('invalid value for "show_hidden_slides", show_hidden_slides cannot be nil.') end if @compressed.nil? invalid_properties.push('invalid value for "compressed", compressed cannot be nil.') end if @viewer_included.nil? invalid_properties.push('invalid value for "viewer_included", viewer_included cannot be nil.') end if @show_page_border.nil? invalid_properties.push('invalid value for "show_page_border", show_page_border cannot be nil.') end if @show_full_screen.nil? invalid_properties.push('invalid value for "show_full_screen", show_full_screen cannot be nil.') end if @show_page_stepper.nil? invalid_properties.push('invalid value for "show_page_stepper", show_page_stepper cannot be nil.') end if @show_search.nil? invalid_properties.push('invalid value for "show_search", show_search cannot be nil.') end if @show_top_pane.nil? invalid_properties.push('invalid value for "show_top_pane", show_top_pane cannot be nil.') end if @show_bottom_pane.nil? invalid_properties.push('invalid value for "show_bottom_pane", show_bottom_pane cannot be nil.') end if @show_left_pane.nil? invalid_properties.push('invalid value for "show_left_pane", show_left_pane cannot be nil.') end if @start_open_left_pane.nil? invalid_properties.push('invalid value for "start_open_left_pane", start_open_left_pane cannot be nil.') end if @enable_context_menu.nil? invalid_properties.push('invalid value for "enable_context_menu", enable_context_menu cannot be nil.') end if @jpeg_quality.nil? invalid_properties.push('invalid value for "jpeg_quality", jpeg_quality cannot be nil.') end if @notes_position.nil? invalid_properties.push('invalid value for "notes_position", notes_position cannot be nil.') end if @comments_position.nil? invalid_properties.push('invalid value for "comments_position", comments_position cannot be nil.') end if @comments_area_width.nil? invalid_properties.push('invalid value for "comments_area_width", comments_area_width cannot be nil.') end if @show_comments_by_no_author.nil? invalid_properties.push('invalid value for "show_comments_by_no_author", show_comments_by_no_author cannot be nil.') end invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? return false if @show_hidden_slides.nil? return false if @compressed.nil? return false if @viewer_included.nil? return false if @show_page_border.nil? return false if @show_full_screen.nil? return false if @show_page_stepper.nil? return false if @show_search.nil? return false if @show_top_pane.nil? return false if @show_bottom_pane.nil? return false if @show_left_pane.nil? return false if @start_open_left_pane.nil? return false if @enable_context_menu.nil? return false if @jpeg_quality.nil? return false if @notes_position.nil? notes_position_validator = EnumAttributeValidator.new('String', ['None', 'BottomFull', 'BottomTruncated']) return false unless notes_position_validator.valid?(@notes_position) return false if @comments_position.nil? comments_position_validator = EnumAttributeValidator.new('String', ['None', 'Bottom', 'Right']) return false unless comments_position_validator.valid?(@comments_position) return false if @comments_area_width.nil? return false if @show_comments_by_no_author.nil? true end # Custom attribute writer method checking allowed values (enum). # @param [Object] notes_position Object to be assigned def notes_position=(notes_position) validator = EnumAttributeValidator.new('String', ['None', 'BottomFull', 'BottomTruncated']) unless validator.valid?(notes_position) fail ArgumentError, 'invalid value for "notes_position", must be one of #{validator.allowable_values}.' end @notes_position = notes_position end # Custom attribute writer method checking allowed values (enum). # @param [Object] comments_position Object to be assigned def comments_position=(comments_position) validator = EnumAttributeValidator.new('String', ['None', 'Bottom', 'Right']) unless validator.valid?(comments_position) fail ArgumentError, 'invalid value for "comments_position", must be one of #{validator.allowable_values}.' end @comments_position = comments_position end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && format == o.format && show_hidden_slides == o.show_hidden_slides && compressed == o.compressed && viewer_included == o.viewer_included && show_page_border == o.show_page_border && show_full_screen == o.show_full_screen && show_page_stepper == o.show_page_stepper && show_search == o.show_search && show_top_pane == o.show_top_pane && show_bottom_pane == o.show_bottom_pane && show_left_pane == o.show_left_pane && start_open_left_pane == o.start_open_left_pane && enable_context_menu == o.enable_context_menu && logo_image == o.logo_image && logo_link == o.logo_link && jpeg_quality == o.jpeg_quality && notes_position == o.notes_position && comments_position == o.comments_position && comments_area_width == o.comments_area_width && comments_area_color == o.comments_area_color && show_comments_by_no_author == o.show_comments_by_no_author end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [format, show_hidden_slides, compressed, viewer_included, show_page_border, show_full_screen, show_page_stepper, show_search, show_top_pane, show_bottom_pane, show_left_pane, start_open_left_pane, enable_context_menu, logo_image, logo_link, jpeg_quality, notes_position, comments_position, comments_area_width, comments_area_color, show_comments_by_no_author].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = AsposeSlidesCloud.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| if Vagrant.has_plugin?("vagrant-cachier") config.cache.scope = :box end config.vm.define "paper-search-vm" do |default| ip_address = "192.168.33.20" default.vm.box = "ubuntu/trusty64" default.vm.provision "shell" do |shell| user = ENV['USER'] || ENV['USERNAME'] shell.path = "provision.sh" shell.args = [user] end default.vm.synced_folder ".", "/vagrant", :mount_options => ['dmode=775', 'fmode=664'] hosthome = ENV['HOME'] || ENV['USERPROFILE'] default.vm.synced_folder hosthome, "/hosthome", :mount_options => ['dmode=777', 'fmode=666'] default.vm.network "private_network", ip: ip_address default.vm.provider :virtualbox do |vb| vb.gui = true vb.customize ["modifyvm", :id, "--memory", 2048] vb.customize ["modifyvm", :id, "--clipboard", "bidirectional"] vb.customize ["modifyvm", :id, "--vram", "256"] vb.customize ["setextradata", :id, "GUI/MaxGuestResolution", "any"] #vb.customize ["storagectl", :id, '--name', 'IDE Controller', '--add', 'ide'] #vb.customize ['storageattach', :id, '--storagectl', 'IDE Controller', '--port', 0, '--device', 1, '--type', 'dvddrive', '--medium', 'emptydrive'] end end end
class Admin::SermonsController < Admin::BaseController def index @sermons = Sermon.all end def show @sermon = Sermon.find(params[:id]) end def new @sermon = Sermon.new end def edit @sermon = Sermon.find(params[:id]) end def update @sermon = Sermon.find(params[:id]) if @sermon.update_attributes(params[:sermon]) flash[:notice] = "Sermon updated" redirect_to admin_sermon_path(@sermon) else flash[:error] = "Error updating sermon" render :action => :edit end end def create @sermon = Sermon.new(params[:sermon]) if @sermon.save flash[:notice] = "Sermon saved" redirect_to :action => :index else flash[:error] = "Error saving sermon" render :action => :new end end def destroy @sermon = Sermon.find(params[:id]) @sermon.destroy flash[:notice] = "Sermon Destroyed" redirect_to :action => :index end end
class Merchant::BaseController < ApplicationController before_filter :authenticate_merchant! layout "merchant" end
class VoicemailResponse def initialize(incoming_call) @incoming_call = incoming_call @response = Twilio::TwiML::VoiceResponse.new end def to_s play_greeting response.record(action: RouteHelper.voicemail_store_url(incoming_call), play_beep: true) response.to_s end private attr_reader :incoming_call, :response def play_greeting if incoming_call.voicemail_greeting.attached? response.play(url: RouteHelper.rails_blob_url(incoming_call.voicemail_greeting)) else response.say( <<~GREETING The person you are trying to reach is currently unavailable. Please leave a message after the tone. GREETING ) end end end
class AddThemes < ActiveRecord::Migration def self.up create_table :themes do |t| t.string :name end connection.execute("INSERT INTO themes VALUES (1, 'default')") end def self.down drop_table :themes end end
require 'fileutils' require 'date' class HtmlTagParser attr_reader :html_file, :file_location, :tag attr_accessor :formatted_output_string def initialize(html_file=nil,file_location=FileUtils.pwd) begin @html_file = html_file rescue @html_file = nil end if File.basename(file_location).include?('.html') if File.exist?(file_location) @file_location = "#{file_location}#{Date.today}" else @file_location = file_location end else @file_location = 'index.html' end end def replace_index_page_with_django_tags tags_to_look_for = { img: ' <img', css: '<link rel', js: '<script src="js', } return_formatted_string(tags_to_look_for) end def to_html File.open(@file_location,'w') {|line| line.write(@formatted_output_string)} end def parse_file_and_append_some_lines_and_create_file(look_for_str, add_after_arr, where_to_save) output_string = generate_output_string for i in 0..output_string.length-1 full_word = output_string[i..i+look_for_str.length-1] if full_word == look_for_str add_after_arr.each {|line| output_string[look_for_str] += "\n" + "\n" + line + "\n"} end end begin file = File.open(where_to_save,'w') file.write(output_string) rescue p 'file didnt write' ensure file.close unless file == nil end end protected def return_formatted_string(tags_to_look_for) output_string = generate_output_string @formatted_output_string = "{% load staticfiles %}\n" for i in 0..output_string.length-1 tags_to_look_for.each_pair do |short_name,tag| full_word = output_string[i..i+tag.length-1] if full_word == tag x = i whole_line = "" bracket_count = 0 havnt_found_everything_inside_brackets = true while havnt_found_everything_inside_brackets do unless output_string[x].nil? whole_line += output_string[x] bracket_count += 1 if output_string[x] == '>' if bracket_count != 1 x += 1 else begin new_formatted_line = return_regex(short_name,whole_line) @formatted_output_string += new_formatted_line output_string[i..x] = '' rescue end havnt_found_everything_inside_brackets = false end end end end end @formatted_output_string += output_string[i] unless output_string[i].nil? end return self end def return_regex(short_name,line) whole_line_de_stringed = line.gsub(/\"/, '') if short_name == :img match = /(?<start><img src=)(?<middle>\w{0,4}\/\w{0,25}\/\d{0,10}\.\w{0,4})\s\w{0,9}\=(?<class>\w{0,5}.\w{0,20})(?<all_else>.{0,10})/.match(whole_line_de_stringed) new_formatted_line = "#{match[:start]} " + %Q["{% static '#{match[:middle]}' %}"] + ' ' + "class='#{match[:class]}' + alt=''>" elsif short_name == :css match = /\<\w{0,5}.\w{0,4}.\w{0,10}.\w{0,5}\=(?<css>[^.]{0,20}\.[^\s]{0,20})/.match(whole_line_de_stringed) new_formatted_line = "<link rel='stylesheet' " + "href=" + %Q["{% static '#{match[:css]}' %}"] + ' ' + "type='text/css'>" elsif short_name == :js match = /\<\w{0,5}.\w{0,4}.\w{0,10}.\w{0,5}\=(?<css>[^.]{0,20}\.[^\s]{0,20})\>/.match(whole_line_de_stringed) new_formatted_line = "<script src=" + %Q["{% static '#{match[:css]}' %}">] + "<" end return new_formatted_line end def generate_output_string output_string = "" File.open(@html_file, "r") do |line| line.each_char do |char| output_string += char end end return output_string end end # end class
# Counts the support of given ItemSets class SetCounter def initialize(baskets) @baskets = baskets @threshold = baskets.rows.length * Settings::CONFIG.support_threshold @job_queue = Queue.new end # Counts an array for item sets by checking each bucket def count_item_sets(item_sets) threaded_count(item_sets) end # Returns an array of item sets with high enough support def supported_sets(item_sets) item_sets.flatten.compact.reject do |item_set| item_set.support < @threshold end end private # Creates threads that counts item sets in baskets # and waits for them to finish def threaded_count(item_sets) create_job_queue create_workers(item_sets).each(&:join) end # Puts each basket on the job queue def create_job_queue (0 .. @baskets.rows.length - 1).each do |row_index| @job_queue << row_index end end # Creates worker threads and tells them to count baskets def create_workers(item_sets) (0 .. Settings::CONFIG.pool_size - 1).map do Thread.new { threaded_basket_count(item_sets) } end end # Worker method that takes baskets from a job queue and counts them def threaded_basket_count(item_sets) begin while row_index = @job_queue.pop(true) SetCounter.count_all_item_sets_in_basket( @baskets.rows[row_index], item_sets ) end rescue ThreadError end end # Counts the support of all item sets in a given basket def self.count_all_item_sets_in_basket(basket, item_sets) basket.each do |item_id| SetCounter.count_sub_item_sets_in_basket(basket, item_sets[item_id]) end end # Counts the support of item sets starting with a specific item_id in a basket def self.count_sub_item_sets_in_basket(basket, item_sets) if item_sets item_sets.each do |item_set| item_set.check_basket(basket) end end end end
class AddVatNullProject < ActiveRecord::Migration[5.2] def change add_column :projects, :is_vat_null, :boolean end end
class ApplicationController < ActionController::Base protect_from_forgery with: :null_session respond_to :json before_action :configure_permitted_parameters, if: :devise_controller? before_action :authenticate_user private # allow for additional parameters not permitted by devise natively when applicable def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:username]) end def authenticate_user if request.headers['Authorization'].present? authenticate_or_request_with_http_token do |token| begin jwt_payload = TokenAuth.decode(token) @current_user_id = jwt_payload['id'] rescue JWT::ExpiredSignature, JWT::VerificationError, JWT::DecodeError render json: {error: 'Invalid Request'}, status: :unauthorized end end else render json: {error: 'Invalid Request'}, status: :unauthorized end end def authenticate_user!(options = {}) render json: {error: 'Invalid Request'}, status: :unauthorized unless signed_in? end def current_user # @current_user_id is set by authenticate_user when auth is successful @current_user || User.find(@current_user_id) end def signed_in? @current_user_id.present? end end
DataMagic.load("canada.yml") Given(/^I am logged into a Canadian Account, Toggle on French Language and Navigate to Statements and Documents page$/) do visit LoginPage on(LoginPage) do |page| logindata = page.data_for(:canadian_account1) username = logindata['username'] password = logindata['password'] ssoid = logindata['ssoid'] page.login(username, password, ssoid) end on(AccountSummaryPage).canada_lang_toggle_element.click on(AccountSummaryPage).can_lan_french_element.click visit(StatementsPage) end Then(/^the statement date will appear in the following french format DD\-MM\-YYYY$/) do on(StatementsPage) do |page| expect(page.date_stmnts_canada).to eql data_for(:can_statements_language_date_format)['statements_date_format'] end end When(/^a user clicks on the Documents Tab$/) do on(StatementsPage).documents_tab_element.click end Then(/^the document date will appear in the following french format DD\-MM\-YYYY$/) do on(StatementsPage) do |page| expect(page.date_stmnts_canada).to eql data_for(:can_statements_language_date_format)['documents_date_format'] end end
# Helper module to create various cached instances for bike CSV imports class BikeCsvImporter module Cache def cached_bike_purpose(purpose) @bike_purpose_cache ||= {} @bike_purpose_cache[purpose] ||= BikePurpose.find_by_purpose purpose end def cached_bike_brand(brand, new_if_empty = false) @bike_brand_cache ||= {} if @bike_brand_cache.has_key? brand @bike_brand_cache[brand] else bike_brand = BikeBrand.where('lower(brand) = ?', brand.downcase).first bike_brand ||= BikeBrand.new(brand: brand) if new_if_empty @bike_brand_cache[brand] = bike_brand end end def cached_bike_model(model) @bike_model_cache ||= {} if @bike_model_cache.has_key? model @bike_model_cache[model] else @bike_model_cache[model] = BikeModel.where('lower(model) = ?', model.downcase).first end end def cached_log_bike_action(action) @log_bike_action_id_cache ||= {} @log_bike_action_id_cache[action] ||= ActsAsLoggable::BikeAction.find_by_action(action) end end end
class BECoding::Command::Left def execute(rover) rover.spin_left end end
require 'rails_helper' RSpec.describe 'devise/registrations/edit.html.erb', type: :view do describe 'when signed in' do describe 'layout integration' do before(:each) do begin_with_new_signed_in_user render template: 'devise/registrations/edit', layout: 'layouts/application' end it 'should have the title for edit account' do expect(rendered).to have_title('Happy House | Edit Profile') end end describe 'view local' do before(:each) do begin_with_new_signed_in_user assign(:resource, @user) render end it 'should have breadcrumbs' do expect(rendered).to have_selector('ol.breadcrumb') end it 'should have first name field' do expect(rendered).to have_field('user_first_name', with: @user.first_name) end it 'should have last name field' do expect(rendered).to have_field('user_last_name', with: @user.last_name) end it 'should have email field' do expect(rendered).to have_field('user_email', with: @user.email) end it 'should have change password link' do expect(rendered).to have_link('Change password', :user_edit_current_password_path) end it 'should have cancel account link' do expect(rendered).to have_link('Cancel account', :user_cancel_registration_path) end it 'should have update button' do expect(rendered).to have_selector('input[type=submit][value=\'Update account\']') end end end end
class Status < ApplicationRecord validates_presence_of :name has_many :book_users, dependent: :destroy end
# == Schema Information # # Table name: users # # id :integer(4) not null, primary key # active :boolean(1) default(TRUE) # screen_name :string(255) # email :string(255) # password :string(255) # reason_for_deactivation :string(255) default("") # created_at :datetime # updated_at :datetime # authorization_token :string(255) # last_login :datetime # logged_in :boolean(1) default(FALSE) # reputation :integer(4) default(0) # require 'digest/sha1' class User < ActiveRecord::Base has_one :user_information accepts_nested_attributes_for :user_information, :allow_destroy => true has_many :thirdparty_accounts has_many :reports, :order => "actual_created_at DESC" has_many :favorites has_many :surfspots, :through => :favorites, :order => "state, city, name" has_many :suggested_surfspots has_many :events, :order => "created_at DESC" has_many :report_photos, :source => :photos, :through => :reports has_many :surf_session_photos, :source => :photos, :through => :surf_sessions has_many :user_roles has_many :roles, :through => :user_roles has_many :surf_sessions, :order => "actual_date DESC, created_at DESC" has_many :comments, :order => "created_at DESC", :dependent => :destroy has_many :friendships has_many :friends, :through => :friendships, :conditions => "status = 'accepted'", :order => :screen_name has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => "status = 'requested'" has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => "status = 'pending'" has_many :gears has_many :gear_photos, :source => :photos, :through => :gears has_many :surfboards has_many :surfboard_photos, :source => :photos, :through => :surfboards has_many :posts has_many :post_photos, :source => :photos, :through => :posts has_many :votes ##is_indexed :fields => ['screen_name'] attr_accessor :remember_me attr_accessor :current_password # Max and min lengths for all fields SCREEN_NAME_MIN_LENGTH = 4 SCREEN_NAME_MAX_LENGTH = 20 PASSWORD_MIN_LENGTH = 4 PASSWORD_MAX_LENGTH = 40 EMAIL_MAX_LENGTH = 50 SCREEN_NAME_RANGE = SCREEN_NAME_MIN_LENGTH..SCREEN_NAME_MAX_LENGTH PASSWORD_RANGE = PASSWORD_MIN_LENGTH..PASSWORD_MAX_LENGTH # Text box sizes for display in the views SCREEN_NAME_SIZE = 20 PASSWORD_SIZE = 10 EMAIL_SIZE = 30 # Reasons for deactivating account SVC_NOT_USEFUL = "I don't find the service useful" NOT_ENOUGHT_REPORTS = "There are too few surf reports posted" SURFSPOTS_NOT_COVERED = "The surfspots I usually go to are not covered" BAD_PERFORMANCE = "The website is too slow" OTHER = "Other" validates_uniqueness_of :screen_name, :email validates_confirmation_of :password validates_length_of :screen_name, :within => SCREEN_NAME_RANGE validates_length_of :password, :within => PASSWORD_RANGE validates_length_of :email, :maximum => EMAIL_MAX_LENGTH validates_length_of :reason_for_deactivation, :maximum => Surftrottr::Application.config.db_string_max_length validates_format_of :screen_name, :with => /^[A-Z0-9_]*$/i, :message => "must contain only letters, numbers, and underscores" validates_format_of :email, :with => /^[A-Z0-9._%-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i, :message => "must be a valid email address" # Return the user full name. def full_name self.user_information.full_name end # Log a user in. def login!(session) session[:user_id] = self.id self.logged_in = true self.last_login = Time.now save! end # Log a user out. def self.logout!(session, cookies) session[:user_id] = nil cookies.delete(:authorization_token) end # Remember a user for future login, # i.e. sent back a cookie uniquely identifying the user. def remember!(cookies) cookie_expiration = 10.years.from_now cookies[:remember_me] = {:value => "1", :expires => cookie_expiration} self.authorization_token = unique_identifier save! cookies[:authorization_token] = {:value => self.authorization_token, :expires => cookie_expiration} end # Forget a user's login status, # i.e. make sure no cookies are sent back. def forget!(cookies) cookies.delete(:remember_me) cookies.delete(:authorization_token) end # Return true if the user wants the login status remembered. def remember_me? self.remember_me == "1" end # Clear a user's password (typically to suppress its display in a view). def clear_password! self.password = nil self.password_confirmation = nil self.current_password = nil end # Return true if the password from params is correct. def correct_password?(params) current_password = params[:user][:current_password] password == current_password end # Generate messages for password errors. def password_errors(params) self.password = params[:user][:password] self.password_confirmation = params[:user][:password_confirmation] valid? errors.add(:current_password, "is incorrect") end # Checks whether an email is valid or not. def self.is_email_valid?(email) email.match(/^[A-Z0-9._%-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i) end # Cheks wether the user is active or not. def active? self.active end # Return the user avatar. def avatar Avatar.new(self) end # Check if the user has a given role. def has_role?(role) self.roles.count(:conditions => ["name = ?", role]) > 0 end # Check if the user has admin role. def is_admin? self.has_role?("Admin") end # Add a role to the user. def add_role(role) return if self.has_role?(role) self.roles << Role.find_by_name(role) end # Return all user photos. def photos photos = self.report_photos + self.surf_session_photos + self.gear_photos + self.surfboard_photos + self.post_photos photos.sort! { |a, b| b.created_at <=> a.created_at } end # Return a list of active thirdparty accounts. def active_thirdparty_accounts accounts = [] self.thirdparty_accounts.each do |account| if account.active? accounts << account end end return accounts end # Return all standard reports. def standard_reports std_reports = [] self.reports.each do |report| if report.class.to_s == Report::STANDARD_REPORT std_reports << report end end return std_reports end # Return all twitter reports. def twitter_reports twttr_reports = [] self.reports.each do |report| if report.class.to_s == Report::TWITTER_REPORT twttr_reports << report end end return twttr_reports end # Perform a text search on a user. # Uses Sphinx under the covers. def self.text_search(q) search = Ultrasphinx::Search.new(:query => q, :class_names => 'User') search.run search.results end # Add a new report. def add_report(report) User.transaction do self.reports << report self.update_attributes! :reputation => self.reputation + 2 end end private def unique_identifier Digest::SHA1.hexdigest("#{self.screen_name}:#{self.password}") end end
class UpdateAllSourcesWorker include Sidekiq::Worker def perform(options = {}) Source.find_each do |source| NewsFeedUpdateWorker.perform_async( source.id, source.category.id, source.feed_url, source.feed_options ) end end end
class BlockField < ApplicationRecord include ActiveModel::Validations attr_accessor :value attr_accessor :conditional_fields validates_presence_of :name validates_presence_of :text # todo test validates_uniqueness_of :marker, conditions: -> { where.not(data_type: I18n.t(:condition)) } validates_numericality_of :weight validate :conditional_validation # for conditional blocks! ref to block that depends on field! has_one :block has_many :block_field_block_parts has_many :block_parts, through: :block_field_block_parts enum data_type: [I18n.t(:text), I18n.t(:number), I18n.t(:money), I18n.t(:condition)] validates :data_type, inclusion: { in: data_types } def self.data_types_list self.data_types.keys.to_a end def self.sorted self.all.sort_by { |i| i.weight } end def self.select_list list = self.sorted list.collect { |i| [ i.name, i.id ] } end def conditional? self.data_type == I18n.t(:condition) end def self.conditional_available_list list = self.where(data_type: I18n.t(:condition)).sort_by { |i| i.weight } # it is possible to link conditional field only to one block list.reject! { |i| not i.block.nil? } list.collect { |i| [ i.name, i.id ] } end def self.non_conditional self.where.not(data_type: I18n.t(:condition)).sort_by { |i| i.weight } end def conditional_validation errors.add(:marker, I18n.t(:field_is_required)) if marker_not_set? end def marker_not_set? self.data_type != I18n.t(:condition) && self.marker.blank? end def self.fetch_and_fill(params) fields = [] params.each do |key, value| block_field = self.where(id: value[:id]).first block_field.value = value[:value] fields << block_field #we add fields with markers only on condition TODO: test -> PASS if block_field.conditional? && block_field.value == '1' conditional_fields = [] value[:fields].each do |sub_key, sub_value| sub_block_field = self.where(id: sub_value[:id]).first sub_block_field.value = sub_value[:value] conditional_fields << sub_block_field end block_field.conditional_fields = conditional_fields end fields << block_field end fields end end
#! /usr/bin/ruby #usage: this rb script is used to produce random string sequence(ascii) from the sequence of state # -i filename #the trans_matrix file # -p filename #the input_otrace_file # -o directory #the outputfile destination # -l number #the limit of the length of the trace # -r number #the repeat times of each state_sequence # -c number #the total number of the traces # -a # open the mode of accepted states # milannic liu 2013 selected_traces = [] required_length = 100 total_number = 20 repeated_times = 1 count_number = 0 sequence_length = 0 endl = '\n' output_directory = "../../output_link/sTrace/" trans_matrix_file = "../resource/5_12" otrace_file = "../../output_link/oTrace/current" timestamp = Time.new.strftime("%Y-%m-%d-%H-%M") if (arg_index = ARGV.index("-l")) != nil if (ARGV[arg_index+1] =~ /^\d+$/) != nil required_length= ARGV[arg_index+1].to_i end end if (arg_index = ARGV.index("-r")) != nil if (ARGV[arg_index+1] =~ /^\d+$/) != nil repeated_times= ARGV[arg_index+1].to_i end end if (arg_index = ARGV.index("-c")) != nil if (ARGV[arg_index+1] =~ /^\d+$/) != nil total_number = ARGV[arg_index+1].to_i end end if (arg_index = ARGV.index("-i")) != nil if (ARGV[arg_index+1] =~ /^-/) == nil && ARGV[arg_index+1] != nil trans_matrix_file = ARGV[arg_index+1] end end if (arg_index = ARGV.index("-o")) != nil if (ARGV[arg_index+1] =~ /^-/) == nil && ARGV[arg_index+1] != nil output_directory = ARGV[arg_index+1] end end if (arg_index = ARGV.index("-p")) != nil if (ARGV[arg_index+1] =~ /^-/) == nil && ARGV[arg_index+1] != nil otrace_file= ARGV[arg_index+1] end end if (arg_index = ARGV.index("-a")) != nil output_directory += 'accepted_states/' otrace_file += '_accepted_states/' end output_directory += timestamp if(!File.exist?(output_directory)) Dir.mkdir(output_directory) end if File.exist?(otrace_file) record = File.open(otrace_file,'r+') while ((state_array = record.gets) != nil) && (count_number<total_number) if (sequence_length = record.gets) == nil p "file corrupted" exit else sequence_length = sequence_length.chop!.to_i end if sequence_length >= required_length count_number = count_number +1 state_array = state_array.chop!.strip.delete('[').delete(']').split(",") state_array.map!{|ele| ele.to_i } selected_traces<<state_array end end record.close else exit end p selected_traces.length #test code =begin selected_traces.each_with_index{|ele_array,index| p "#{index} : #{ele_array}" } =end total_state = 0 if File.exist?(trans_matrix_file) trans_file= File.open(trans_matrix_file,'r+') trans_matrix = [] total_state = trans_file.gets.chop!.to_i total_state.times{ line = trans_file.gets trans_vector = line.split("\s") trans_vector.map!{|state| state.to_i } trans_matrix<<trans_vector } trans_file.close else exit end p trans_matrix.length string_per_line = "" count = 0 selected_traces.each{|state_array_ele| repeated_times.times{|times_index| output_file = File.open("#{output_directory}/#{state_array_ele.length}_#{count}_#{times_index}","w+:ASCII-8BIT") count += 1 state_array_ele.each_with_index{|ele,index_ele| if index_ele <= required_length if index_ele != state_array_ele.length-1 temp_vector = trans_matrix[ele] temp_selector = [] temp_vector.each_with_index{|value,index| if value == state_array_ele[index_ele+1] temp_selector<<index end } selector = temp_selector[(rand()*temp_selector.length).floor] string_per_line<<(selector.chr) end end } output_file<<string_per_line output_file.close() string_per_line = "" } }
class RetailerCategoriesDecorator < Draper::CollectionDecorator def get(code) categories = (object + object.map(&:children)).flatten categories.find {|category| category.code == code} end def with_children object.select{|c| c.children.any? } end end
class AddPlayerFixtureHistoriesToPlayers < ActiveRecord::Migration[5.0] def change reversible do |dir| dir.up do add_column :players, :player_fixture_histories, :json Player.all.each do |player| player.update( player_fixture_histories: HTTParty.get("https://fantasy.premierleague.com/drf/element-summary/#{player.id}")['history'] ) end end dir.down do remove_column :players, :player_fixture_histories, :json end end end end
# West direction class. require 'toy_robot/model/direction/base_direction' module Direction class West < BaseDirection # String representation of the direction attr_reader:dir # Initialize the direction with a string representation def initialize @dir = W end # Make a left turn from west direction. # ====== Returns # - the new direction after left turn def turnLeft return SOUTH end # Make a right turn from west direction. # ====== Returns # - the new direction after right turn def turnRight return NORTH end # Move horizontally forward from current postion facing west. # ====== Parameters # - +x+:: the current x position # - +y+:: the current y position # ====== Returns # - the new x and y position after move def move(x, y) return x-1, y end end end
class Recipe < ApplicationRecord validates :name, presence: true validates :category, presence: true validates :url, presence: true, uniqueness: true validates :energy, presence: true, numericality: true validates :carbs, presence: true, numericality: true validates :fat, presence: true, numericality: true validates :protein, presence: true, numericality: true validates :data, presence: true end