text
stringlengths
10
2.61M
# frozen_string_literal: true module Airbrussh VERSION = "1.4.2".freeze end
# -------------------------------------------------------------------------- # # Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) # # # # 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. # #--------------------------------------------------------------------------- # require 'scripts_common' class File # Helper method used to create symlink in directories available only to root user # For example: /vz/template/cache def self.symlink source, target OpenNebula.exec_and_log "sudo ln -s #{source} #{target}" end # Helper method used to remove file in directories available only to root user def self.delete what OpenNebula.exec_and_log "sudo rm -rf #{what}" end end module OpenNebula # FileUtils groups utilities performing actions on files class FileUtils # An utility used to determine archive type # # * *Args* : # - +file_name+ -> name of the file to be checked # * *Returns* : # - archive type, currently one of these values: 'tar.gz', 'tar.bz2', 'tar.xz' (only these are supported by OpenVz) def self.archive_type(file_name) # compression type is determined by 2 bytes representing 'magic number' types = {"\x1F\x8B" => 'tar.gz', "BZ" => 'tar.bz2', "\xFD\x00" => 'tar.xz'} File.open(file_name, "r") do |file| bytes = file.read(2) return types[bytes] if types[bytes] end raise "Cannot determine filetype of #{file_name}" end # An utility used to filter executable filenames # # * *Args* : # - +files+ -> String containing filenames separated by whitespaces # * *Returns* : # - Filtered array containing only executable filenames. If none of the filenames matches, the empty array is returned def self.filter_executables(files) # allowed executable extensions exts = %w(.sh .ksh .zsh) return [] if files.nil? or files.empty? files.split.find_all {|f| exts.find {|e| e == File.extname(f) } != nil } end end end
require 'spec_helper' describe "esattori/edit.html.erb" do before(:each) do @esattore = assign(:esattore, stub_model(Esattore, :name => "MyString", :code => "MyString", :tipo => "MyString", :tipo_indennita => "MyString", :valore_indennita => 1 )) end it "renders the edit esattore form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form", :action => esattori_path(@esattore), :method => "post" do assert_select "input#esattore_name", :name => "esattore[name]" assert_select "input#esattore_code", :name => "esattore[code]" assert_select "input#esattore_tipo", :name => "esattore[tipo]" assert_select "input#esattore_tipo_indennita", :name => "esattore[tipo_indennita]" assert_select "input#esattore_valore_indennita", :name => "esattore[valore_indennita]" end end end
class SourceType < DefaultObject include Types::Inclusions::TaskAndAnnotationFields description "Source type" implements GraphQL::Types::Relay::Node field :image, GraphQL::Types::String, null: true field :description, GraphQL::Types::String, null: false field :name, GraphQL::Types::String, null: false field :dbid, GraphQL::Types::Int, null: true field :user_id, GraphQL::Types::Int, null: true field :permissions, GraphQL::Types::String, null: true field :pusher_channel, GraphQL::Types::String, null: true field :lock_version, GraphQL::Types::Int, null: true field :medias_count, GraphQL::Types::Int, null: true field :accounts_count, GraphQL::Types::Int, null: true field :overridden, JsonStringType, null: true field :archived, GraphQL::Types::Int, null: true field :accounts, AccountType.connection_type, null: true field :account_sources, AccountSourceType.connection_type, null: true def account_sources object.account_sources.order(id: :asc) end field :medias, ProjectMediaType.connection_type, null: true def medias object.media end field :medias_count, GraphQL::Types::Int, null: true field :collaborators, UserType.connection_type, null: true end
# == Schema Information # # Table name: user_push_subscriptions # # id :integer not null, primary key # auth :string # endpoint :string # p256dh :string # sub_auth :string # created_at :datetime not null # updated_at :datetime not null # user_id :integer # class UserPushSubscription < ApplicationRecord belongs_to :user before_save :set_sub_auth def pushable? endpoint.present? && p256dh.present? && auth.present? end private def set_sub_auth return if sub_auth.present? self.sub_auth = loop do token = SecureRandom.hex(10) break token unless self.class.where(sub_auth: token).any? end end end
class AddTargetDataToMeritActions < ActiveRecord::Migration[5.0] def change add_column :merit_actions, :target_data, :text end end
class Booking < ApplicationRecord belongs_to :kid validates :reservation, presence: true end
# frozen_string_literal: true class Restaurant < ApplicationRecord has_many :dishes validates :name, :description, presence: true end
# frozen_string_literal: true # user model class User < ApplicationRecord has_secure_password has_many :habits, dependent: :delete_all end
class ListsController < ApplicationController def index @lists = List.all end def new @list = List.new end def create @list = List.create(lists_param) if @list.save redirect_to lists_path else render("new") end end def edit @list = List.find(params[:id]) end def destroy @list = List.find(params[:id]) @list.destroy redirect_to lists_path end def show @list = List.find(params[:id]) end private def lists_param params.require(:list).permit(:title) end end
# frozen_string_literal: true class Contract < ApplicationRecord belongs_to :vendor belongs_to :category belongs_to :user validates :costs, :ends_on, presence: true validates :costs, numericality: { greater_than: 0 } validate :validate_ends_on private def validate_ends_on return errors.add(:ends_on, 'is invalid') unless ends_on.present? errors.add(:ends_on, "can't be in the past") unless ends_on.future? end end
require 'recipe_scraper' require 'open-uri' # Recipe represent a delicious recipe posted on raspberry-cook.fr # # @attr name [String] the name of the recipe # @attr description [String] the description of the recipe # @attr ingredients [String] ingredients needed for the recipe # @attr steps [String] steps to create the recipe # @attr season [String] season to cook recipe # @attr t_baking [DateTime] Baking time needed # @attr t_cooling [DateTime] Cooling time needed # @attr t_cooking [DateTime] Cooking time needed # @attr t_rest [DateTime] Rest time needed # @attr image [String] Url of picture # @attr root_recipe_id [Integer] Id of original recipe # @attr variant_name [String] name of the variant # @attr rtype [String] Type of the recipe # # @attr user [User] as owner of recipe # @attr comments [Array<Comment>] comments owned by recipe class Recipe < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged before_save :set_default_time attr_accessible :name, :description, :ingredients, :steps, :season, :t_baking, :t_cooling, :t_cooking, :t_rest, :baking, :cooling, :cooking, :rest, :image, :root_recipe_id, :variant_name, :rtype, :tags belongs_to :user has_many :comments , :dependent => :destroy has_many :views , :dependent => :destroy has_and_belongs_to_many :allergens mount_uploader :image , ImageUploader validates :name , presence: true, uniqueness: { scope: :root_recipe_id, message: "Cette recette existe déjà. Trouvez la et en créer une variante." } acts_as_readable :on => :created_at # for use of unread gem self.per_page = 20 # Availables types of recipe @@types = ['Entrée', 'Plat', 'Dessert', 'Cocktail', 'Apéritif'] # Availables seasons for a recipe @@seasons = ['Toutes', 'Printemps', 'Eté', 'Automne', 'Hiver'] # Time zero represent zero value for a task ZERO_TIME = DateTime.new 2000, 01, 01, 00, 00, 00 TIME_LABELS = { baking: 'cuisson', cooling: 'refrigération', cooking: 'préparation', rest: 'repos' } # Get a given number of record # # @param number [Integer] # @yield [ActiveRecord::Base] as Recipes corresponding to params # @return [Array] list conatining recipes if no block given def self.random number count = self.count if block_given? number.times { yield self.offset(rand(count)).first} else recipes = [] number.times { recipes << self.offset(rand(count)).first} return recipes end end # Get most viewed # # @param number [Integer] # @yield [ActiveRecord::Base] as Recipes corresponding to params # @return [Array] list conatining recipes if no block given def self.most_viewed number recipes = [] Recipe.joins(:views).group('views.recipe_id').order('count_recipe_id desc').count('recipe_id').each do |id, count| number -= 1 recipes << Recipe.find(id) return recipes if number == 0 end end # search all recipes given by a search query params # # @param params [Hash] as GET params # @return [ActiveRecord::Relation] as Recipes corresponding to params def self.search params sql_query_parts = [] params_query = [] # add all name exploded if params.has_key?(:name) and params[:name] != '' name_query_part = '' params[:name].split(' ').each do |part_name| name_query_part += ' recipes.name LIKE ? OR ingredients LIKE ? AND ' params_query.push "%#{part_name}%" params_query.push "%#{part_name}%" end name_query_part.chomp! 'AND ' # surround with () sql_query_parts.push "(#{name_query_part})" end # add seasons if params.has_key?(:season) and not params[:season] == 'Toutes' sql_query_parts.push "( season LIKE ? )" params_query.push params[:season] end # add type if params.has_key?(:type) and not params[:type] == 'Toutes' sql_query_parts.push "( rtype LIKE ? )" params_query.push params[:type] end # add allergens if params.has_key?(:allergens) params['allergens'].each_key do |allergen_id| sql_query_parts.push "( allergens_recipes.allergen_id = ? )" params_query.push allergen_id end end # create query and add ask database sql_query = sql_query_parts.join ' AND ' self.joins(" LEFT JOIN allergens_recipes ON allergens_recipes.recipe_id = recipes.id LEFT JOIN allergens ON allergens_recipes.allergen_id = allergens.id ").where(sql_query , *params_query).group(:id).paginate( :page => params[:page] ).order('created_at DESC') end # Create a recipe from a marmiton url # # @param url [String] as url recipe # @param user_id [Integer] as id of the User creator of the recipe # @return [Recipe] as recipe created def self.import url, user_id # get data from url marmiton_recipe = RecipeScraper::Recipe.new url marmiton_recipe_data = marmiton_recipe.to_hash if marmiton_recipe_data[:ingredients].empty? and marmiton_recipe_data[:steps].empty? raise "Could not find suffiscent informations from #{url}.." end # create recipe new_recipe = Recipe.new new_recipe.name = marmiton_recipe_data[:title] new_recipe.ingredients = marmiton_recipe_data[:ingredients].join "\r\n" new_recipe.steps = marmiton_recipe_data[:steps].join "\r\n" cooking_minutes = marmiton_recipe_data[:cooktime].to_i baking_minutes = marmiton_recipe_data[:preptime].to_i new_recipe.t_cooking = ZERO_TIME.advance minutes: cooking_minutes new_recipe.t_baking = ZERO_TIME.advance minutes: baking_minutes new_recipe.user_id = user_id if marmiton_recipe_data[:image] && marmiton_recipe_data[:image] != NoMethodError extention = marmiton_recipe_data[:image].split('.').last open("/tmp/image_from_marmiton.#{extention}", 'wb') do |file| file << open(marmiton_recipe_data[:image]).read new_recipe.image = file end end if new_recipe.save return new_recipe else raise 'Something goes wrong in fetching data from host' end end # Type of of recipes ('Entrée', 'Plat', etc..) # # @return [Array] as types def self.types return @@types end # Seasons ('Toutes', 'Printemps', etc..) # # @return [Array] as seasons def self.seasons return @@seasons end # Copy the recipe from the user to a new user # # @param new_user_id [Integer] as id of the user owner of the new recipe # @return [Recipe] as recipe created def fork new_user_id forked_recipe = self.dup forked_recipe.root_recipe_id = self.id forked_recipe.user_id = new_user_id return forked_recipe end # Get the formatted name for the recipe (add variant name if forked recipe) # # @return [String] def pretty_name self.variant_name ? "%s - %s " % [ self.name , self.variant_name] : self.name end # Get the formatted description for the recipe (and provide them if emty) # # @return [String] def pretty_description self.description || "Une délicieuse recette" end # Get the average rate of this recipe # # @return [Integer] as rate def rate sql = "SELECT AVG(rate) as rate FROM comments WHERE recipe_id = ?" statement = ActiveRecord::Base.connection.raw_connection.prepare sql result = statement.execute([self.id]).first average = result == [nil] ? 0 : result['rate'].to_i statement.close return average end # Check if recipe is original or is a copy of another # # @return [Bollean] as true if it's a copy def forked? return self.root_recipe_id != 0 end # Get the original recipe if this is a copy # # @return [Recipe] as original recipe or self if it's the original def root_recipe if self.root_recipe_id != 0 return Recipe.find self.root_recipe_id rescue ActiveRecord::RecordNotFound return self else return self end end # search all recipes given by a search query params # # @return [ActiveRecord::Base] as Recipes corresponding to params def forked_recipes return Recipe.where(root_recipe_id: self.id ).order( :variant_name ) end # get image_url :thumb # if the recipe havn't picture and she's forked , we get the parent image # # @return [String] as url of the image def true_thumb_image_url bd_image = self.image_url(:thumb) if self.forked? and not picture_exist? bd_image return self.root_recipe.image_url(:thumb) else return bd_image end end # get image_url # if the recipe havn't picture and she's forked , we get the parent image # # @return [String] as url of the image def true_image_url bd_image = self.image_url if self.forked? and not picture_exist? bd_image return self.root_recipe.image_url else return bd_image end end # Return true if user has set an image for this recipe # # @return [Boolean] def has_image? return true_image_url != ImageUploader.new.default_url end # Add view on recipe # # @param user_id [Integer] # @return [View] as view object added def add_view user_id=nil View.create recipe_id: self.id, user_id: user_id end # Get nouber of this recipe has been counted # # @return [Integer] as count def count_views self.views.count end # Return the sum of the time # # @return [Integer] def sum_of_times sum = 0 [:baking, :cooling, :cooking, :rest].each do |time| sum += self.send time end return sum end # Return a percentage of time according to the total sum # # @param time [string] as time name # @return [float] def percentage_time time return (self.send(time.to_s).to_f / sum_of_times.to_f) * 100 end # Format a beautifull string # # @return [String] as a JSON object def to_json option data = self.attributes # TODO: create uniq SQL query instead of load each objects data[:allergens] = self.allergens.map{ |allergen| {name: allergen.name, icon: allergen.icon_url} } return data.to_json end # Format to json_ld # # @return [Hash] def to_jsonld # setup user or Raspberry Cook society author = {} if self.user author = self.user.to_jsonld else author = RaspberryCookFundation.to_jsonld 'Organization' end comments_count = self.comments.count jsonld = { "@context" => "http://schema.org/", "@type": "Recipe", position: self.id, name: self.name, description: self.pretty_description, url: Rails.application.routes.url_helpers.recipe_url(self.id), author: author, creator: author, # editor: author, # contributor: author, dateCreated: self.created_at, datePublished: self.created_at, dateModified: self.updated_at, # todo: insert URL of forked recipe # isBasedOn: '' image: ApplicationController.helpers.image_url(self.true_image_url), thumbnailUrl: ApplicationController.helpers.image_url(self.true_thumb_image_url), aggregateRating: { "@type" => "AggregateRating", ratingValue: self.rate, reviewCount: comments_count, bestRating: 5, worstRating: 1 }, prepTime: Time.at(self.cooking * 60).utc.strftime('%H:%M:%S'), totalTime: Time.at(self.sum_of_times * 60).utc.strftime('%H:%M:%S'), # "recipeYield": "8", } jsonld[:recipeIngredient] = self.ingredients.split(/\r\n/) if self.ingredients jsonld[:recipeInstructions] = self.steps.split(/\r\n/) if self.steps jsonld[:aggregateRating] = { "@context" => "http://schema.org/", "@type" => "AggregateRating", ratingValue: self.rate, reviewCount: comments_count, bestRating: 5, worstRating: 1 } if comments_count != 0 return jsonld end private # set default time on t_baking, t_cooling, t_cooking, t_rest if not already set def set_default_time zero_time = Time.new 2000, 1, 1, 1, 0, 0 [:t_baking, :t_cooling, :t_cooking, :t_rest].each { |t_time| self.send("#{t_time}=".to_sym, zero_time) unless self.send(t_time).present? } end # Ensure to picture exists # # @param picture_url [String] as url to check # @return [Boolean] if picture exists def picture_exist? picture_url absolute_path = File.join Rails.root , 'public', picture_url return File.file? absolute_path end # check if we need to generate slug for this model # # @return [Boolean] if picture exists def should_generate_new_friendly_id? name_changed? || super end end
module Ricer::Plug::Params class ChannelNameParam < Base def convert_in!(input, message) Ricer::Irc::Lib.instance.channelname_valid?(input) or failed_input input end def convert_out!(value, message) message ? value + ":#{message.server.domain}" : value end end end
require 'test_helper' class Apicast::SandboxProxyConfGeneratorTest < ActiveSupport::TestCase def setup master = FactoryBot.build_stubbed(:simple_master) master.stubs(provider_key: "master-#{provider_key}") provider = FactoryBot.build_stubbed(:simple_provider) provider.stubs(provider_key: provider_key) service = FactoryBot.build_stubbed(:simple_service, account: provider) @proxy = FactoryBot.build_stubbed(:simple_proxy, service: service) @generator = Apicast::SandboxProxyConfGenerator.new(@proxy) end def test_lua_file assert_equal "sandbox_service_#{@proxy.service_id}", @generator.lua_file end def test_emit assert @generator.emit end def provider_key 'some-provider-key' end end
class ParticipationTagging < ApplicationRecord belongs_to :participation belongs_to :tag end
module Boxzooka class Address < BaseElement # Address Line 1 scalar :address1 # Address Line 2 scalar :address2 # Address Line 3 scalar :address3 # Shipment City scalar :city # Shipment Company scalar :company # Shipment country code. ISO2. scalar :country_code # Shipment email address scalar :email # Shipment first name scalar :first_name # Shipment last name scalar :last_name # Shipment phone # scalar :phone # Shipment Postal Code scalar :postal_code # Shipment State or Province scalar :province # Shipment customer tax ID scalar :tax_id, node_name: 'TaxID' end end
# Original # class Student # def initialize(name, year) # @name = name # @year = year # end # end # class Graduate # def initialize(name, year, parking) # end # end # class Undergraduate # def initialize(name, year) # end # end # Updated class Student def initialize(name, year) @name = name @year = year end end class Graduate < Student def initialize(name, year, parking) super(name, year) @parking = parking end end class Undergraduate < Student def initialize(name, year) super end # We can also delete the entire Undergraduate#initialize method; # since it only calls Student#initialize with the same arguments and does nothing else, we can omit it. end grad = Graduate.new('Joe', 1999, true) p grad under = Undergraduate.new('john', 2005) p under
# frozen_string_literal: true require 'open-uri' require 'json' module NasaNeo module CloseObj class Client ESTIMATED_DIAMETER_OPTIONS = ["kilometers", "meters", "miles", "feet"] MISS_DISTANCE_OPTIONS = ["astronomical", "lunar", "kilometers", "miles"] VELOCITY_OPTIONS = ["kilometers_per_second", "kilometers_per_hour", "miles_per_hour"] NEO_NAME_KEYS = ["name"] NEO_ID_KEYS = ["id"] HAZARDOUS_KEYS = ["is_potentially_hazardous_asteroid"] ESTIMATED_DIAMETER_KEYS = ["estimated_diameter"] MISS_DISTANCE_KEYS = ["close_approach_data", 0, "miss_distance"] VELOCITY_KEYS = ["close_approach_data", 0, "relative_velocity"] attr_accessor :date attr_reader :key def initialize(config) @config = config @calls_remaining = nil @key = config.api_key @date = parsed_date @full_url = nil @full_url_neo = nil @neo_id = nil @result = nil @result_neo = nil @neo_position = 0 end def key=(value) @calls_remaining = nil @key = value end def calls_remaining @calls_remaining == nil ? error_feedback("make new API call first") : @calls_remaining end def estimated_diameter(measurement = nil, min_max = nil) retrieve_specific(ESTIMATED_DIAMETER_OPTIONS, ESTIMATED_DIAMETER_KEYS, measurement, min_max) end def hazardous? call_and_rescue { retrieve_neo(HAZARDOUS_KEYS) } end def miss_distance(measurement = nil) retrieve_specific(MISS_DISTANCE_OPTIONS, MISS_DISTANCE_KEYS, measurement) end def neo_name call_and_rescue { retrieve_neo(NEO_NAME_KEYS) } end def neo_data call_and_rescue { retrieve_neo } end def neo_data_verbose call_and_rescue { retrieve_neo_verbose } end def neo_total if @full_url != set_full_url call_and_rescue { get_api_data["element_count"]} else @result["element_count"] end end def update call_and_rescue { get_api_data } end def neo_select(n) @neo_position = n - 1 end def velocity(measurement = nil) retrieve_specific(VELOCITY_OPTIONS, VELOCITY_KEYS, measurement) end private def buffer_url(url) api_data = open(url) @calls_remaining = api_data.meta['x-ratelimit-remaining'].to_i api_data.read end def call_and_rescue yield if block_given? rescue OpenURI::HTTPError => e @full_url = nil @full_url_neo = nil error_feedback(e.io.status) end def get_api_data @full_url = set_full_url @neo_position = 0 buffer = JSON.parse(buffer_url(@full_url)) @result = buffer end def parsed_date Time.now.strftime("%Y-%m-%d") end def retrieve_neo(keys = []) get_api_data if @full_url != set_full_url root_keys = ["near_earth_objects", "#{@date}", @neo_position] @result.dig(*root_keys + keys) end def retrieve_neo_verbose @neo_id = retrieve_neo(NEO_ID_KEYS) if @full_url_neo != set_full_url_neo @full_url_neo = set_full_url_neo @result_neo = JSON.parse(buffer_url(@full_url_neo)) else @result_neo end end def retrieve_specific(options, keys, measurement, min_max = nil) if options.include? measurement chained_keys = retrieve_neo(keys + ["#{measurement}"]) if ["min", "max"].include? min_max chained_keys = retrieve_neo(keys + ["#{measurement}", "estimated_diameter_#{min_max}"]) call_and_rescue { chained_keys } else min_max == nil ? call_and_rescue { (chained_keys.respond_to?(:to_f) && chained_keys != nil) ? chained_keys.to_f : chained_keys } : error_feedback(['min_max', 'check arguments']) end else measurement == nil ? call_and_rescue { retrieve_neo(keys) } : error_feedback(['measurement', 'check arguments']) end end def error_feedback(error_info) { 'error': error_info } end def set_full_url "#{@config.host}/feed?start_date=#{@date}&end_date=#{@date}&detailed=false&api_key=#{@key}" end def set_full_url_neo "#{@config.host}/neo/#{@neo_id}?api_key=#{@key}" end end end end
class Rider < ActiveRecord::Base belongs_to :user validates :bus, presence: true, numericality: true validates :busline, presence: true, numericality: true validates :story, presence: true end
class SocialProfileSerializer < ActiveModel::Serializer attributes :id, :label ,:url end
class Currency def initialize(amount, currency_code = "x") currency_hash = {"$" => :USD , "!" => :PS , "?" => :HD} @currency_hash = currency_hash if @currency_code == "x" @currency_code = @amount[0] @amount = @amount[1..-1].to_f else @amount = amount.to_f @currency_code = currency_code.to_sym end end def amount @amount end def currency_code @currency_code end def look_at_this "#{@amount}, #{@currency_code}" end def ==(value) if @amount == value.amount && @currency_code == value.currency_code true else false end end def +(addend) if @currency_code == addend.currency_code Currency.new(@amount + addend.amount, @currency_code) return Currency.new(amount, currency_code) else raise DifferentCurrencyCodeError end end def -(minuend) if @currency_code == minuend.currency_code Currency.new(@amount - minuend.amount, @currency_code) return Currency.new(amount, currency_code) else raise DifferentCurrencyCodeError end end def *(factor) if factor.class == Fixnum || factor.class == Float sum = @amount * factor new_num = Currency.new(sum, @currency_code) return Currency.new(amount, currency_code) end end # below is the latest # def find_currency_symbol(symbol) # if Currency.new(amount, currency_code).include?("$") # @currency_code = :USD # end # end # above is the latest end
# # an in-memory resource set for testing rufus-verbs # # jmettraux@gmail.com # # Fri Jan 11 12:36:45 JST 2008 # require 'date' require 'webrick' $dcount = 0 # tracking the number of hits when doing digest auth # # the hash for the /items resource (collection) # class LastModifiedHash def initialize @hash = {} touch end def touch (key=nil) now = Time.now.httpdate @hash[key] = now if key @hash['__self'] = now end def delete (key) @hash.delete key @hash['__self'] = Time.now.httpdate end def last_modified (key) key = key || '__self' @hash[key] end def clear @hash.clear @hash['__self'] = Time.now.httpdate end end # # This servlet provides a RESTful in-memory resource "/items". # class ItemServlet < WEBrick::HTTPServlet::AbstractServlet @@items = {} @@last_item_id = -1 @@lastmod = LastModifiedHash.new @@authenticator = WEBrick::HTTPAuth::DigestAuth.new( :UserDB => WEBrick::HTTPAuth::Htdigest.new('test/test.htdigest'), :Realm => 'test_realm') def initialize (server, *options) super @auth = server.auth end # # Overriding the service() method to perform a potential auth check # def service (req, res) if @auth == :basic WEBrick::HTTPAuth.basic_auth(req, res, "items") do |u, p| (u != nil and u == p) end elsif @auth == :digest $dcount += 1 @@authenticator.authenticate(req, res) end super end def do_GET (req, res) i = item_id req return reply(res, 404, "no item '#{i}'") \ if i and not items[i] representation, et, lm = fetch_representation i since = req['If-Modified-Since'] since = DateTime.parse(since) if since match = req['If-None-Match'] if ((not since and not match) or (since and (since > DateTime.parse(lm))) or (match and (match != et))) res['Etag'] = et res['Last-Modified'] = lm res.body = representation.inspect + "\n" else reply(res, 304, "Not Modified") end end def do_POST (req, res) query = WEBrick::HTTPUtils::parse_query(req.query_string) m = query['_method'] m = m.downcase if m return do_PUT(req, res) if m == 'put' return do_DELETE(req, res) if m == 'delete' i = item_id req i = (@@last_item_id += 1) unless i items[i] = req.body lastmod.touch i res['Location'] = "#{@host}/items/#{i}" reply res, 201, "item created" end def do_PUT (req, res) i = item_id req return reply(res, 404, "no item '#{i}'") unless items[i] items[i] = req.body lastmod.touch i reply res, 200, "item updated" end def do_DELETE (req, res) i = item_id req return reply(res, 404, "no item '#{i}'") unless items[i] items.delete i lastmod.delete i reply res, 200, "item deleted" end # # clears the items # def self.flush @@items.clear @@lastmod.clear end protected def items @@items end def lastmod @@lastmod end def is_modified (req, key) since = req['If-Modified-Since'] match = req['If-None-Match'] return true unless since or match #puts #p [ since, match ] #puts (since or match) end # # Returns representation, etag, last_modified # def fetch_representation (key=nil) representation = if key items[key] else items end [ representation, representation.inspect.hash.to_s, lastmod.last_modified(key) ] end def reply (res, code, message) res.status = code res.body = message + "\n" res['Content-type'] = "text/plain" end def item_id (req) p = req.path_info[1..-1] return nil if not p or p == '' p.to_i end end # # just redirecting to the ItemServlet... # class ThingServlet < WEBrick::HTTPServlet::AbstractServlet def do_GET (req, res) res.set_redirect( WEBrick::HTTPStatus[303], "http://localhost:7777/items") end end # # testing Rufus::Verbs cookies... # class CookieServlet < WEBrick::HTTPServlet::AbstractServlet @@sessions = {} def do_GET (req, res) res.body = get_session(req, res).inspect end def do_POST (req, res) get_session(req, res) << req.body.strip res.body = "ok." end protected def get_session (req, res) c = req.cookies.find { |c| c.name == 'tcookie' } if c @@sessions[c.value] else s = [] key = (Time.now.to_f * 100000).to_i.to_s @@sessions[key] = s res.cookies << WEBrick::Cookie.new('tcookie', key) s end end end # # a servlet that doesn't reply (for timeout testing) # class LostServlet < WEBrick::HTTPServlet::AbstractServlet def do_GET (req, res) sleep 200 end end # # Serving items, a dummy resource... # Also serving things, which just redirect to items... # class ItemServer def initialize (args={}) port = args[:port] || 7777 #al = [ # [ "", WEBrick::AccessLog::COMMON_LOG_FORMAT ], # [ "", WEBrick::AccessLog::REFERER_LOG_FORMAT ]] @server = WEBrick::HTTPServer.new :Port => port, :AccessLog => nil class << @server attr_accessor :auth end @server.auth = args[:auth] @server.mount "/items", ItemServlet @server.mount "/things", ThingServlet @server.mount "/cookie", CookieServlet @server.mount "/lost", LostServlet [ 'INT', 'TERM' ].each do |signal| trap(signal) { shutdown } end end def start Thread.new { @server.start } # else the server and the test lock each other end def shutdown ItemServlet.flush @server.shutdown end end
require 'general_job' require 'hashie/mash' require 'qless' require 'log_streamer' require 'scanner_extensions' require 'wallarm_logger' require 'datadog/statsd' require_relative './metric' require_relative './log_formatter' require_relative './remote_logger' # Preserve formatter class StandartLogger < Logger def reopen close unless params[0] == STDOUT r = StandartLogger.new *params r.formatter = formatter r end end # Support jid logging class LoggerHub def jid=(val) @loggers.each { |logger| logger.formatter.jid = val } end end ActiveLoggerHubs.trap('SIGWINCH') module App class << self def config @config ||= Hashie::Mash.new( api: Wallarm::API::DEFAULTS.merge( ca_verify: false ), log_file: STDOUT, redis: 'redis://127.0.0.1/0', queue: 'scanner', # save_attack_status_redis: 'redis://127.0.0.1/0', # save_attack_status_queue: 'save_attack_status', private_scan: false, max_requests: 1000, max_memory: 2**27, extensions: {}, wait_validated_timeout: 30, log_streamer: { cache_ttl: 10, redis_addr: 'redis://127.0.0.1/0', elastic_schema: '%Y%m%d', elastic_step: 86_400, elastic_addrs: '127.0.0.1:9200;127.0.0.2:9200' }, #:rps_limit => { # :port => 2379 # }, exceptions: [ [/BaselineCheckJob/, { action: :retry, tries: 3, timeout: 5 * 60 }], [/BaselineCheckError/, { action: :retry, tries: 5, timeout: 5 * 60 }], [/RpsLimit::EtcdError/, { action: :retry, tries: 5, timeout: 30 * 60 }], [/OpenSSL::SSL::SSLError/, { action: :retry, tries: 5, timeout: 10 * 60 }], [/Timeout::Error/, { action: :retry, tries: 5, timeout: 10 * 60 }], [/Errno::ECONNREFUSED/, { action: :retry, tries: 5, timeout: 10 * 60 }], [/Errno::EHOSTUNREACH/, { action: :retry, tries: 5, timeout: 10 * 60 }], [/SocketError/, { action: :retry, tries: 5, timeout: 10 * 60 }], [/EOFError/, { action: :retry, tries: 5, timeout: 10 * 60 }], [/Errno::ECONNRESET/, { action: :retry, tries: 5, timeout: 10 * 60 }], [/Net::HTTPFatalError/, { action: :retry, tries: 5, timeout: 10 * 60 }], [/Net::OpenTimeout/, { action: :retry, tries: 5, timeout: 10 * 60 }], [/Net::ReadTimeout/, { action: :retry, tries: 5, timeout: 10 * 60 }], [/API::ServerError/, { action: :retry, tries: 5, timeout: 10 * 60 }], [/API::InternalServerError/, { action: :retry, tries: 5, timeout: 10 * 60 }] ], remote_logger: { retry_timeout: 5 } ) end def init RpsLimit.config = config.rps_limit if config.rps_limit end def log_streamer @log_streamer ||= LogStreamer::Log.new( wrappers: { cache: Metric.method(:redis_log), persistent_storage: Metric.method(:elastic_log) }, id_schema: '%0<time>10i:%0<id>10i', schema: { baseline_check_id: :int, msg: :string, level: :string }, cache_ttl: config.log_streamer.cache_ttl, cache: { type: :redis, key_schema: '%<baseline_check_id>i', addr: config.log_streamer.redis_addr }, persistent_storage: { type: :es, date_schema: config.log_streamer.elastic_schema, date_step: config.log_streamer.elastic_step, addrs: config.log_streamer.elastic_addrs.split(';') } ) end def switch_to_http_logger def App.log_streamer if @remote_logger.nil? @remote_logger = RemoteLogger.new @remote_logger.run! end @remote_logger end end def log(params) App.logger.send(params[:level], params[:msg]) params = params.merge( baseline_check_id: Thread.current[:baseline_check_id] ) begin log_streamer.write(params) rescue => ex App.logger.error(ex) end end def statsd statsd_host = ENV.fetch('STATSD_HOST', '127.0.0.1') statsd_port = ENV.fetch('STATSD_PORT', 9125).to_i @statsd ||= Datadog::Statsd.new(statsd_host, statsd_port) end def wapi @wapi ||= Wallarm::API.new(config.api) end def wapi=(config) @wapi = Wallarm::API.new(config) end def watch_node_yaml node_yaml = IO.binread('/etc/wallarm/node.yaml') return if node_yaml == @node_yaml @node_yaml = node_yaml config = YAML.load(@node_yaml) App.config.api = { uuid: config['uuid'], secret: config['secret'], host: ENV.fetch('WALLARM_API_HOST', 'api.wallarm.com'), port: ENV.fetch('WALLARM_API_PORT', '443'), use_ssl: ENV.fetch('WALLARM_API_USE_SSL', 'true').casecmp('true').zero?, ca_verify: ENV.fetch('WALLARM_API_CA_VERIFY', 'false').casecmp('true').zero? } App.wapi = App.config.api FastAPI.reload end def queue @queue ||= Qless::Client.new(url: config.redis, tcp_keepalive: 5).queues[config.queue] end def save_attack_status_queue @attack_status_queue ||= Qless::Client.new(url: config.save_attack_status_redis, tcp_keepalive: 5) .queues[config.save_attack_status_queue] end def logger if @logger.nil? logger = StandartLogger.new(config.log_file) logger.formatter = LogFormatter.new @logger = LoggerHub.new @logger.add_logger(logger) end @logger end end end require './lib/exceptions'
class Room def initialize(capacity) @capacity = capacity @occupants = [] end def capacity @capacity end def occupants @occupants end def full? if @occupants.size < @capacity return false end true end def available_space @capacity - @occupants.size end def add_occupant(string) if full? return false end @occupants << string true end end
class Fuel < ApplicationRecord has_many :fuel_arms, dependent: :destroy validates :name, :min_density, :max_density, presence: true end
require 'net/ssh' class RemoteTask::Drivers::Ssh < RemoteTask::Drivers::Base class UnexpectedError < StandardError; end class ExecutionFailed < StandardError; end def self.make_s3_client(region: nil) Aws::S3::Client.new( region: region || Rails.application.config.x.remote_task.driver.ssh.log_s3_region, logger: Rails.logger, ) end class_attribute :s3, default: make_s3_client() def self.description_for(execution) "SSH run for #{execution.target['hostname']}" end def initialize(*) super @hostname = execution.target.fetch('hostname') @user = execution.target.fetch('user', Rails.application.config.x.remote_task.driver.ssh.user) end attr_reader :hostname, :user def execute! execution.state ||= {} begin prepare_scratch! run_command! mark_success! rescue Net::SSH::Exception, ExecutionFailed, Timeout::Error => e mark_failure!(e) end upload_log! end def prepare_scratch! return unless scratch return if execution.state['scratch_path'] execution.state['scratch_path'] = ssh.exec!('tempfile -d /dev/shm -p ioic_ -s _ioi-console_remote-task-' + execution.task.id.to_s + '-' + execution.id.to_s + '_scratch -m 0600').chomp ssh_run("cat > '#{execution.state['scratch_path']}'") do |ch| ch.send_data(scratch.read) ch.eof! end execution.save! end def ssh_command [ 'set -ex', scratch ? [ "IOI_SCRATCH_PATH='#{execution.state.fetch('scratch_path')}'", ] : nil, script, scratch ? 'shred --remove "${IOI_SCRATCH_PATH}"' : nil, "\n", ].flatten.join(?\n) end def run_command! execution.status = :pending execution.save! Timeout.timeout(execution.target.fetch('command_timeout', 900)&.to_i) do ssh_run("IOI_REMOTE_TASK=#{execution.task.id}_#{execution.id} bash") do |ch| set_ssh_output_hook(ch) ch.send_data(ssh_command) ch.eof! execution.status = :running execution.save! end end end def mark_success! execution.update!(status: :succeeded) end def mark_failure!(e) execution.update!(status: :failed) logfile.puts "[EXCEPTION] #{e.inspect}\n\n#{e.full_message}" end def upload_log! finalize_log! execution.log_kind = 'AwsS3' execution.log = { 'region' => s3.config.region, 'bucket' => Rails.application.config.x.remote_task.driver.ssh.log_s3_bucket, 'key' => "#{Rails.application.config.x.remote_task.driver.ssh.log_s3_prefix}#{execution.task.id}_#{execution.id}.log", } logfile(:read).rewind s3.put_object( bucket: execution.log.fetch('bucket'), key: execution.log.fetch('key'), body: logfile(:read), ) execution.save! end def ssh_run(cmd, error: true) exitstatus, exitsignal = nil puts "$ #{cmd}" cha = ssh.open_channel do |ch| ch.exec(cmd) do |c, success| raise ExecutionFailed, "execution failed on #{hostname}: #{cmd.inspect}" if !success && error c.on_request("exit-status") { |_c, data| exitstatus = data.read_long } c.on_request("exit-signal") { |_c, data| exitsignal = data.read_long } yield c if block_given? end end cha.wait raise ExecutionFailed, "execution failed on #{hostname} (status=#{exitstatus.inspect}, signal=#{exitsignal.inspect}): #{cmd.inspect}" if (exitstatus != 0 || exitsignal) && error [exitstatus, exitsignal] end def ssh @ssh ||= Net::SSH.start(hostname, user, key_data: Rails.application.config.x.remote_task.driver.ssh.key_data, timeout: execution.target.fetch('connect_timeout', 20).to_i) end def finalize_log! @logfile_finalized = true logfile(:force).flush end def logfile_finalized? @logfile_finalized end def logfile(read = nil) if !read && logfile_finalized? raise "Don't read a log aftr finalization" else @logfile ||= Tempfile.new end end private def set_ssh_output_hook(c) outbuf, errbuf = [], [] check = ->(prefix,data,buf) do has_newline = data.include?("\n") lines = data.lines last = lines.pop if last[-1] == "\n" buf << last end if has_newline (buf+lines).join.each_line do |line| Rails.logger.info "[SSH_OUT/#{execution.task.id}_#{execution.id}]#{prefix} #{line}" logfile.puts "#{prefix} #{line}" end buf.replace([]) end if last[-1] != "\n" buf << last end end c.on_data do |_c, data| check.call "[OUT] ", data, outbuf end c.on_extended_data do |_c, _, data| check.call "[ERR] ", data, errbuf end end end
module Gitlab module Badge ## # Build badge # class Build include Gitlab::Application.routes.url_helpers include ActionView::Helpers::AssetTagHelper include ActionView::Helpers::UrlHelper def initialize(project, ref) @project, @ref = project, ref @image = ::Ci::ImageForBuildService.new.execute(project, ref: ref) end def type 'image/svg+xml' end def data File.read(@image[:path]) end def to_s @image[:name].sub(/\.svg$/, '') end def to_html link_to(image_tag(image_url, alt: 'build status'), link_url) end def to_markdown "[![build status](#{image_url})](#{link_url})" end def image_url build_namespace_project_badges_url(@project.namespace, @project, @ref, format: :svg) end def link_url namespace_project_commits_url(@project.namespace, @project, id: @ref) end end end end
class Member < ActiveRecord::Base has_secure_password attr_accessible :team_id, :username, :password, :password_confirmation belongs_to :team validates :username, presence: true, uniqueness: true validates :password, presence: true validates :team, presence: { message: "must exist" } def logged_in?; !id.nil? end def whiteteam?; team.whiteteam? end def blueteam?; team.blueteam? end def redteam?; team.redteam? end # Standard permissions def self.can_index?(member) member.whiteteam? end def can_show?(member) member.whiteteam? end def self.can_new?(member) member.whiteteam? end def can_edit?(member) member.whiteteam? end def can_create?(member) member.whiteteam? end def can_update?(member) member.whiteteam? end def can_destroy?(member) member.whiteteam? end def can_overview_users? return true if Cyberengine.can_show_all_blueteam_users return true if Blueteam.can_show_all_blueteam_users return true if Redteam.can_show_all_blueteam_users false end def can_overview_properties? return true if Cyberengine.can_show_all_blueteam_properties return true if Blueteam.can_show_all_blueteam_properties && blueteam? return true if Redteam.can_show_all_blueteam_properties && redteam? false end def can_scoreboard? return true if Cyberengine.can_show_all_blueteam_scores return true if Blueteam.can_show_all_blueteam_scores && blueteam? return true if Redteam.can_show_all_blueteam_scores && redteam? false end end
# coding: utf-8 module Preflight module Rules # For PDFX/1a, every page must have MediaBox, plus either ArtBox or # TrimBox # # Arguments: none # # Usage: # # class MyPreflight # include Preflight::Profile # # rule Preflight::Rules::PrintBoxes # end # class PrintBoxes attr_reader :issues def page=(page) dict = page.attributes if dict[:MediaBox].nil? @issues = [Issue.new("every page must have a MediaBox", self, :page => page.number)] elsif dict[:ArtBox].nil? && dict[:TrimBox].nil? @issues = [Issue.new("every page must have either an ArtBox or a TrimBox", self, :page => page.number)] elsif dict[:ArtBox] && dict[:TrimBox] @issues = [Issue.new("no page can have both ArtBox and TrimBox - TrimBox is preferred", self, :page => page.number)] else @issues = [] end end end end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_filter :authenticate_user, :only => [:show, :delete, :update] helper_method :current_user # Checks if a user session exists. def current_user @current_user = User.find(session[:user_id]) if session[:user_id] end protected def authenticate_user if session[:user_id] # set current user object to @current_user object variable @current_user = User.find(session[:user_id]) else flash[:notice] = "Action requires login." redirect_to(:controller => 'static_pages', :action => 'home') end end def save_login_state if session[:user_id] redirect_to(:controller => 'static_pages', :action => 'home') false else true end end end
require 'rails_helper' describe "Routing", type: :controller do describe "Sessions Routing" do it "routes GET /login to sessions#new" do expect(:get => '/login').to route_to('sessions#new') end it "routes POST /login to sessions#create" do expect(:post => '/login').to route_to('sessions#create') end end end
#=============================================================================== # ** Window_SaveList #------------------------------------------------------------------------------- # Viene gestita all'interno di Scene_File, contiene la lista dei salvataggi. #=============================================================================== class Window_SaveList < Window_Selectable # inizializzazione def initialize(x, y, width, height, saving = false) make_item_list super(x, y, width, height) @savin = saving refresh self.index = DataManager.last_savefile_index end def col_max 3 end def item_max @data ? @data.size : 0 end def refresh make_item_list super end # aggiornamento def update super update_detail_window end # ottieni i salvataggi def make_item_list @data = [] (0..DataManager.savefile_max - 1).each { |i| header = DataManager.load_header(i) @data.push(Save_Data.new(i, header)) } end # determina se l'oggetto selezionato dal cursore è cliccabile def current_item_enabled? return true if SceneManager.scene_is? Scene_Save enable?(@data[@index]) end # Ottieni oggetto # @return [Save_Data] def item @data[self.index] end # Ottieni se attivato def enable?(item) for_save? or !item.header.nil? end def for_save? @savin end def for_load? !@savin end # Disegna l'oggetto # index : indice dell'oggetto def draw_item(index) item = @data[index] return if item.nil? rect = item_rect_for_text(index) draw_save_name(item, rect) end # Aggiornamento della finestra dei dettagli def update_detail_window return if item.nil? || @detail_window.nil? || self.active == false @detail_window.update_header(item.header, item.slot) end # Assegnazione di una nuova finestra di dettagli def detail_window=(dw) @detail_window = dw update_detail_window end # Disegna il nome del salvataggio # @param [Save_Data] item # @param [Rect] rect # @param [Boolean] enabled def draw_save_name(item, rect, enabled = true) return if item.nil? enabled = enable? item change_color normal_color, enabled icon = item.present? ? SaveConfig::FULLSLOT_ICON : SaveConfig::EMPTYSLOT_ICON draw_icon(icon, rect.x, rect.y) rect.x += 24 rect.width -= 24 draw_text(rect, item.name) end end #window_savelist #=============================================================================== # ** Save_Data #------------------------------------------------------------------------------- # Viene gestita all'interno di Window_SaveList, contiene header e numero salvat. #=============================================================================== class Save_Data attr_reader :slot #numero slot attr_reader :header #dati del salvataggio # Inizializzazione def initialize(save_slot, save_header = nil) @slot = save_slot @header = save_header end # determina se un salvataggio è presente nello slot def present? @header != nil end # @return [String] def name slot_number = sprintf(Vocab.slot, @slot + 1) return slot_number if @header.nil? return slot_number if @header[:save_name].empty? @header[:save_name] end end #save_storer
# Model for group suggestions ("you might like notebooks owned by this group") class SuggestedGroup < ApplicationRecord belongs_to :user belongs_to :group include ExtendableModel class << self def compute_all User.find_each(batch_size: 100) do |user| compute_for(user) end end def compute_for(user) # Get suggestions from helper methods suggestors = methods.select {|m| m.to_s.start_with?('suggest_groups_')} suggested = suggestors .map {|suggestor| send(suggestor, user)} .reduce(&:+) .map {|id| SuggestedGroup.new(user_id: user.id, group_id: id)} # Import into database SuggestedGroup.transaction do SuggestedGroup.where(user_id: user).delete_all # no callbacks SuggestedGroup.import(suggested) end end # Suggest groups that own notebooks suggested for the user def suggest_groups_from_suggested_notebooks(user) Set.new( SuggestedNotebook .select("notebooks.owner_id") .joins(:notebook) .where("user_id = ? AND owner_type = 'Group'", user.id) .map(&:owner_id) ) end # Suggest any of the user's groups that own notebooks def suggest_groups_from_membership(user) Set.new(Notebook.where(owner: user.groups).map(&:owner_id)) end end end
# frozen_string_literal: true # Controller for collections of slides class CollectionsController < ApplicationController before_action :find_collection, only: %i[show edit update destroy] before_action :related_models, only: %i[new show edit update destroy] before_action :authenticate_user! before_action :authorize # GET /collections # GET /collections.json def index @collections = Collection.all end # GET /collections/1 # GET /collections/1.json def show; end # GET /collections/new def new @collection = Collection.new end # GET /collections/1/edit def edit; end # POST /collections # POST /collections.json def create @collection = Collection.new(collection_params) build_kiosks(params) respond_to do |format| if @collection.save format.html { redirect_to @collection, notice: 'Collection was successfully created.' } format.json { render :show, status: :created, location: @collection } else format.html { render :new } format.json { render json: @collection.errors, status: :unprocessable_entity } end end end # PATCH/PUT /collections/1 # PATCH/PUT /collections/1.json def update upload_slides(params) build_kiosks(params) respond_to do |format| if @collection.update(collection_params) format.html { redirect_to @collection, notice: 'Collection was successfully updated.' } format.json { render :show, status: :ok, location: @collection } else format.html { render :edit } format.json { render json: @collection.errors, status: :unprocessable_entity } end end end # DELETE /collections/1 # DELETE /collections/1.json def destroy @collection.destroy respond_to do |format| format.html { redirect_to collections_url, notice: 'Collection was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def find_collection @collection = Collection.find(params[:id]) end def upload_slides(params) return unless params['commit'] == 'Upload Slides' params['uploaded_files'].each do |fid| s = Slide.find(fid) s.collection_id = params['id'] s.save! end end def build_kiosks(params) return unless params[:collection] && params[:collection][:slides_attributes] slides = {} params[:collection][:slides_attributes].each do |k, v| slide_id = v ? v['id'] : k['id'] slide_kiosks = v ? v['kiosk_ids'] : k['kiosk_ids'] slides[slide_id] = slide_kiosks if slide_id end @collection.slides.each do |slide| slide_id = slide.id.to_s kiosks = [] if slides.key? slide_id slides[slide_id].each do |k| kiosks << Kiosk.find(k) end end if params['commit'] == 'Upload Slides' slide.kiosks = kiosks if slides.key? slide_id else slide.kiosks = kiosks end end end def related_models @kiosks = Kiosk.all @slide_types = SlideType.all @default_kiosk = Kiosk.find_or_create_by(name: 'touch') @default_slide_type = SlideType.find_or_create_by(name: 'Basic') @kiosk_options = Kiosk.all.collect { |obj| { obj.name => obj.id } }.inject(:merge) @slide_type_options = SlideType.all.collect { |obj| { obj.name => obj.id } }.inject(:merge) end # Never trust parameters from the scary internet, only allow the white list through. def collection_params params.require(:collection).permit( :detail, :name, :primary_slide_id, slides_attributes: [ :id, :caption, :expires_at, :title, :collection_id, :slide_type_id, :image, :_destroy, { date_ranges_attributes: %i[id start_date end_date slide_id _destroy] } ] ) end def authorize unless current_user&.admin? flash[:alert] = 'You do not have sufficient permissions to view this page' redirect_to root_path end end end
class DeleteCvcColumnFromCreditCard < ActiveRecord::Migration def up remove_column :credit_cards, :cvc end def down add_column :credit_cards, :cvc end end
desc "normalize demo permit addresses" namespace :address do task :remove_address_space => :environment do DemoPermit.find_each do |single_record| normalized_address = single_record.address.strip single_record.update(:address => normalized_address) end end end
class PrototypesController < ApplicationController before_action :set_prototype, only: [:show, :edit, :update,:destroy] def index @prototypes = Prototype.order("created_at DESC").page(params[:page]).per(6) end def new @prototype = Prototype.new @prototype.captured_images.build @prototype.tags.build end def create @prototype = Prototype.new(prototype_params) tags = [] @prototype.tags.each do |tag| _tag = Tag.find_or_create_by(name: tag.name) tags <<_tag end @prototype.tags = tags if @prototype.save redirect_to :root, notice: 'New prototype was successfully created' else redirect_to ({ action: new }), alert: 'YNew prototype was unsuccessfully created' end end def show end def edit @main = @prototype.captured_images.where(status: 0).first @sub = @prototype.captured_images.where(status: 1) @new_sub = @prototype.captured_images.where(status: 1).build @tags = @prototype.tags end def update _prototype = Prototype.new(prototype_params) tags = [] _prototype.tags.each do |tag| _tag = Tag.find_or_create_by(name: tag.name) tags <<_tag end @prototype.tags = tags if @prototype.update(update_params) redirect_to :root, notice: 'The prototype was successfully updated' else redirect_to ({ action: new }), alert: 'YNew prototype was unsuccessfully updated' end end def destroy if @prototype.user_id == current_user.id @prototype.destroy redirect_to :root, notice: 'prototype was deleted' end end private def set_prototype @prototype = Prototype.find(params[:id]) end def prototype_params params.require(:prototype).permit( :title, :catch_copy, :concept, :user_id, tag_ids: [], captured_images_attributes: [:content, :status], tags_attributes: :name ) end def update_params params.require(:prototype).permit( :title, :catch_copy, :concept, :user_id, captured_images_attributes: [:id, :_destroy, :content, :status] ) end end
class NonBlockingDebuggerOverTCP < DebuggerOverTCP def initialize(verbose = false) super end def self.debugger_input(input) s = "begin\n" r = "\nrescue => exc\nNonBlockingDebuggerOverTCP.instance.puts exc.class.to_s; NonBlockingDebuggerOverTCP.instance.puts exc.inspect\nend" s + input + r end protected def client @client ||= SimpleTCP::Client.new(blocking: false) # Prevent calling to connect too often if failing return @client if @last_failed_at && (Time.now.to_i - @last_failed_at < 3) @last_failed_at = nil @client.connect("127.0.0.1", 3465) unless @client.connected? @client rescue SimpleTCP::FailedToConnectError => e @last_failed_at = Time.now.to_i raise e end end NB_TCP_DEBUGGER = ' begin NonBlockingDebuggerOverTCP.instance.print("(nbdebugger) > ") _input = NonBlockingDebuggerOverTCP.instance.gets if !_input.nil? && _input.length > 0 output = eval(NonBlockingDebuggerOverTCP.debugger_input(_input)).inspect NonBlockingDebuggerOverTCP.instance.puts("=> #{output}") NonBlockingDebuggerOverTCP.instance.print("(debugger) > ") end rescue SimpleTCP::FailedToConnectError, SimpleTCP::DisconnectedError end '
require 'rails_helper' RSpec.describe Appointment, type: :model do include_examples "create models" describe "Model" do it "has a date and time" do expect(appointment.datetime).to eq(DateTime.parse("2019-01-06T16:30:00")) expect(appointment.date).to eq("2019-01-06") expect(appointment.time).to eq("4:30pm") end end describe "Associations" do it "has a pet" do expect(appointment.pet).to eq(pet) end it "as a doctor" do expect(appointment.doctor).to eq(doctor) end it "has an invoice" do expect(appointment.invoice).to eq(invoice) end end end
class AuditStructuresController < SecuredController include RemoteObjectProcessing before_action :load_structure, except: [:create] def show render json: AuditStructure.find(params[:id]) end def create render json: process_object(AuditStructure, audit_structure_params) end def update render json: process_object(AuditStructure, audit_structure_params) end def export_full render json: [FullStructurePresenter.new(@audit_structure)] end private def load_structure @audit_structure = AuditStructure.find(params[:id]) end def audit_structure_params params.require(:audit_structure) .permit(:id, :destroy_attempt_on, :audit_strc_type_id, :name, :successful_upload_on, :upload_attempt_on, :parent_structure_id, :sample_group_id, :full_download_on, :physical_structure_id, :physical_structure_type, :created_at, :updated_at) end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :goal do user_id 1 name "lose weight" is_private false complete false end end
class HomesController < ApplicationController def index @restaurants = Restaurant.all.order('rating_cache desc').limit(7) end end
module ExternalLinksHelper DEPLOYMENT_CHECKLIST_LINK = "https://docs.google.com/document/d/1cleJkm09VRGUAafkpzC9U2ao9r4r8ewZjLPwfTTj57Q/edit?usp=sharing" BP_PASSPORT_CREATOR_LINK = "https://drive.google.com/file/d/1fB9RFdrFC4NaU1CQUfEodC6IyXdQcs_A/view?usp=sharing" INDIA_SIMPLE_TRAINING_GUIDE_LINK = "https://docs.google.com/presentation/d/1YKlZfXpnX0tGk6NMO6JLuZY0l9O3P3zOxKXsWNJh7W0/edit#slide=id.g25f6af9dd6_0_0" BANGLADESH_SIMPLE_TRAINING_GUIDE_LINK = "https://docs.google.com/presentation/d/1Ce2LIPlnByn-6LPhgbKUkhoGold3R5ciXtFbVXFOhaU/edit#slide=id.g25f6af9dd6_0_0" ETHIOPIA_SIMPLE_TRAINING_GUIDE_LINK = "https://docs.google.com/presentation/d/1GM57_sHZ53huaMCi1Vsg5O2aAjtXKWdLGvsvKzMROME/edit#slide=id.g25f6af9dd6_0_0" SRI_LANKA_SIMPLE_TRAINING_GUIDE_LINK = "https://docs.google.com/presentation/d/1hjgVHNcFfpWVeK7K0ZOvilIYGo5TlITFFNZLdKIE03g/edit#slide=id.g25f6af9dd6_0_0" TELEMEDICINE_SIMPLE_TRAINING_GUIDE_LINK = "https://docs.google.com/presentation/d/1wg0VlsEpBFWjSoqIUH5Jwj368g9Ku-IEj9DoujdqG5c/edit?usp=sharing" TRAINING_VIDEO_ALL_CHAPTERS_YOUTUBE_LINK = "https://youtu.be/MC_45DoRw2g" TRAINING_VIDEO_ALL_CHAPTERS_DOWNLOAD_LINK = "https://drive.google.com/file/d/1XbQ9vejHXL8dXA0tuAyMvb0e9ToJR0yh/view?usp=sharing" TRAINING_VIDEO_ALL_CHAPTERS_AMHARIC_YOUTUBE_LINK = "https://youtu.be/pE7LPGGXWyw" TRAINING_VIDEO_ALL_CHAPTERS_AMHARIC_DOWNLOAD_LINK = "https://drive.google.com/file/d/1w7Ej6W6kQUv74rVA9FGx9xLj3XnnxzOf/view?usp=sharing" TRAINING_VIDEO_ALL_CHAPTERS_OROMO_YOUTUBE_LINK = "https://youtu.be/ibg_ZUj4cQ0" TRAINING_VIDEO_ALL_CHAPTERS_OROMO_DOWNLOAD_LINK = "https://drive.google.com/file/d/1y2FwHOUGG-nfalQBgb85WZuCRp6yxm4v/view?usp=sharing" HOW_TO_CONDUCT_A_TRAINING_YOUTUBE_LINK = "https://youtu.be/wfrMbvTXn38" HOW_TO_CONDUCT_A_TRAINING_DOWNLOAD_LINK = "https://drive.google.com/file/d/1X2jD3hMQwRNtmP51Ea0-JKxDqvdteeKe/view?usp=sharing" INSTALL_THE_APP_YOUTUBE_LINK = "https://youtu.be/r0mbu1s0l7A" INSTALL_THE_APP_DOWNLOAD_LINK = "https://drive.google.com/file/d/1XDS-TkSAmxWFiAyTZ-XrGN7LIClGfz_M/view?usp=sharing" INSTALL_THE_APP_AMHARIC_YOUTUBE_LINK = "https://youtu.be/jT2G4qmj47U" INSTALL_THE_APP_AMHARIC_DOWNLOAD_LINK = "https://drive.google.com/file/d/1qPKZqmQqXXLMB64U7FBD62XTDXv65jDs/view?usp=sharing" INSTALL_THE_APP_OROMO_YOUTUBE_LINK = "https://youtu.be/0MnjaEXs6Bk" INSTALL_THE_APP_OROMO_DOWNLOAD_LINK = "https://drive.google.com/file/d/1eWMYDqi19T7SCL3N4xk9D4I79h7aqLfP/view?usp=sharing" INTRODUCTION_YOUTUBE_LINK = "https://youtu.be/YPySS9sL-EU" INTRODUCTION_DOWNLOAD_LINK = "https://drive.google.com/file/d/1X4eKkSCLW0pQCseGKS5dfpaDhsTtO2ki/view?usp=sharing" INTRODUCTION_AMHARIC_YOUTUBE_LINK = "https://youtu.be/msNUbBc02o4" INTRODUCTION_AMHARIC_DOWNLOAD_LINK = "https://drive.google.com/file/d/1kabpnC06NSs6cn0QAMLcEC5-5GxV39lS/view?usp=sharing" INTRODUCTION_OROMO_YOUTUBE_LINK = "https://youtu.be/BK1uLJBZRq4" INTRODUCTION_OROMO_DOWNLOAD_LINK = "https://drive.google.com/file/d/1YsodXTxfDifzpVVAJ2RhPa8XvdfiLVtV/view?usp=sharing" REGISTER_A_PATIENT_YOUTUBE_LINK = "https://youtu.be/5P5mGQVQFOU" REGISTER_A_PATIENT_DOWNLOAD_LINK = "https://drive.google.com/file/d/1XK17vrqvIdnOzVIF3r8lJIY7NODCQ8Ol/view?usp=sharing" REGISTER_A_PATIENT_AMHARIC_YOUTUBE_LINK = "https://youtu.be/j229YDx4NAw" REGISTER_A_PATIENT_AMHARIC_DOWNLOAD_LINK = "https://drive.google.com/file/d/1LM9QkTyLeYtap95MZqc3He_D82woQu7N/view?usp=sharing" REGISTER_A_PATIENT_OROMO_YOUTUBE_LINK = "https://youtu.be/pDs4ntPtoq4" REGISTER_A_PATIENT_OROMO_DOWNLOAD_LINK = "https://drive.google.com/file/d/1CZeu-BrMLInZYDY59TBr1ViJrT_r2McP/view?usp=sharing" SEARCH_FOR_PATIENT_YOUTUBE_LINK = "https://youtu.be/6hR1vQ8hoTU" SEARCH_FOR_PATIENT_DOWNLOAD_LINK = "https://drive.google.com/file/d/1XMfLvj8ev5VXJIRFTU-Yrkg7iZNlgHRG/view?usp=sharing" SEARCH_FOR_PATIENT_AMHARIC_YOUTUBE_LINK = "https://youtu.be/gomFZdnQvwk" SEARCH_FOR_PATIENT_AMHARIC_DOWNLOAD_LINK = "https://drive.google.com/file/d/1aNr9hiQ8OVjWCr1XDmZBgnE3YPXy_zUX/view?usp=sharing" SEARCH_FOR_PATIENT_OROMO_YOUTUBE_LINK = "https://youtu.be/ik_rkdJQKAI" SEARCH_FOR_PATIENT_OROMO_DOWNLOAD_LINK = "https://drive.google.com/file/d/16HdAsJIUY1hTjgBcXFuX11k2xyXvgOCD/view?usp=sharing" FIND_PATIENT_YOUTUBE_LINK = "https://youtu.be/o3klwHrMEi0" FIND_PATIENT_DOWNLOAD_LINK = "https://drive.google.com/file/d/1XLyY_lAEdnxcYJIyCHRg1VqhTfQ_uGpp/view?usp=sharing" FIND_PATIENT_AMHARIC_YOUTUBE_LINK = "https://youtu.be/ogyi4rWPnXI" FIND_PATIENT_AMHARIC_DOWNLOAD_LINK = "https://drive.google.com/file/d/1chByLCC7VxmRlR96W9piaEo4z7wiJIrB/view?usp=sharing" FIND_PATIENT_OROMO_YOUTUBE_LINK = "https://youtu.be/0DKZe_KPip8" FIND_PATIENT_OROMO_DOWNLOAD_LINK = "https://drive.google.com/file/d/15Qq5F390ujwOWz88SFQsI_5rVhqHSpi7/view?usp=sharing" CALL_OVERDUE_PATIENTS_YOUTUBE_LINK = "https://youtu.be/PuM29XINOn4" CALL_OVERDUE_PATIENTS_DOWNLOAD_LINK = "https://drive.google.com/file/d/1XORZPiZuc0UbOEge9kGE-Eqd0LUjfKkP/view?usp=sharing" CALL_OVERDUE_PATIENTS_AMHARIC_YOUTUBE_LINK = "https://youtu.be/6LXMAeOmlVY" CALL_OVERDUE_PATIENTS_AMHARIC_DOWNLOAD_LINK = "https://drive.google.com/file/d/1z8fqQXDixHbhayPCRxQvPxLICXgzMR8g/view?usp=sharing" CALL_OVERDUE_PATIENTS_OROMO_YOUTUBE_LINK = "https://youtu.be/zO1G1jonryY" CALL_OVERDUE_PATIENTS_OROMO_DOWNLOAD_LINK = "https://drive.google.com/file/d/1cTiwlqakKVQ29DPnSk8t5LCNpFwN3VFC/view?usp=sharing" IMPORTANT_FEATURES_YOUTUBE_LINK = "https://youtu.be/elCBnApJLIM" IMPORTANT_FEATURES_DOWNLOAD_LINK = "https://drive.google.com/file/d/1XS3nozUd1ip81_s2k9VYVnQPHb3eHa5d/view?usp=sharing" IMPORTANT_FEATURES_AMHARIC_YOUTUBE_LINK = "https://youtu.be/xrhVoVjb-JI" IMPORTANT_FEATURES_AMHARIC_DOWNLOAD_LINK = "https://drive.google.com/file/d/1gYv08RR00FUdy31-_Ojx4s5DLiD5ze3T/view?usp=sharing" IMPORTANT_FEATURES_OROMO_YOUTUBE_LINK = "https://youtu.be/5ua5GlHTQV0" IMPORTANT_FEATURES_OROMO_DOWNLOAD_LINK = "https://drive.google.com/file/d/1DGKq9yroAIh8rjj--fuYSpNbB86DlRFN/view?usp=sharing" FAQ_YOUTUBE_LINK = "https://youtu.be/Aj-dKn_kmlw" FAQ_DOWNLOAD_LINK = "https://drive.google.com/file/d/1XVTpv3taQQhUeFBctKKMVgkThxC4iF7O/view?usp=sharing" FAQ_AMHARIC_YOUTUBE_LINK = "https://youtu.be/Re-41u25Kxo" FAQ_AMHARIC_DOWNLOAD_LINK = "https://drive.google.com/file/d/1HssfJoQd0CkaLHMURhwduroDIhNYceKg/view?usp=sharing" FAQ_OROMO_YOUTUBE_LINK = "https://youtu.be/KNFTE-lAqFo" FAQ_OROMO_DOWNLOAD_LINK = "https://drive.google.com/file/d/19okIUGm72XoiWPP18pYt6OX1R8b07VWU/view?usp=sharing" HOW_TO_GET_HELP_YOUTUBE_LINK = "https://youtu.be/wF4t_pFuugY" HOW_TO_GET_HELP_DOWNLOAD_LINK = "https://drive.google.com/file/d/1XSZjssc20gfh8eO5l7BGNn-U6INS16qG/view?usp=sharing" HOW_TO_GET_HELP_AMHARIC_YOUTUBE_LINK = "https://youtu.be/fFvZB1LtqQc" HOW_TO_GET_HELP_AMHARIC_DOWNLOAD_LINK = "https://drive.google.com/file/d/1m8jvIQYTRzNSqUCkGytB4664zd2B8nwi/view?usp=sharing" HOW_TO_GET_HELP_OROMO_YOUTUBE_LINK = "https://youtu.be/lcnY-jiPDms" HOW_TO_GET_HELP_OROMO_DOWNLOAD_LINK = "https://drive.google.com/file/d/1OeohR7xC-rnKPnq1yyxP_PYz4W4Q70JW/view?usp=sharing" START_USING_SIMPLE_YOUTUBE_LINK = "https://youtu.be/kls4QnWz1Nw" START_USING_SIMPLE_DOWNLOAD_LINK = "https://drive.google.com/file/d/1XZw2ZHMERapNhnnKcc8ENlwA1G492O88/view?usp=sharing" START_USING_SIMPLE_AMHARIC_YOUTUBE_LINK = "https://youtu.be/TvZxys_vlY8" START_USING_SIMPLE_AMHARIC_DOWNLOAD_LINK = "https://drive.google.com/file/d/1TRMHu-usYVSzE3oQDmgr5RP0lw_pRM9F/view?usp=sharing" START_USING_SIMPLE_OROMO_YOUTUBE_LINK = "https://youtu.be/83KM_G4WFP0" START_USING_SIMPLE_OROMO_DOWNLOAD_LINK = "https://drive.google.com/file/d/1j87O-NZeNQKc5QgMesCqQUi7p0GJ-jFV/view?usp=sharing" TELEMEDICINE_TRAINING_ENGLISH_YOUTUBE_LINK = "https://youtu.be/aI1bGpS08oY" TELEMEDICINE_TRAINING_HINDI_YOUTUBE_LINK = "https://youtu.be/JVfeNmY_n08" TELEMEDICINE_TRAINING_ENGLISH_DOWNLOAD_LINK = "https://drive.google.com/file/d/1ZWy-Umqc71ZSiUZlZ78QwrytSltXgxGk/view?usp=sharing" TELEMEDICINE_TRAINING_HINDI_DOWNLOAD_LINK = "https://drive.google.com/file/d/1ZZCyKGvvNnUtjV4rS4Pe_Ujf8GZTye4P/view?usp=sharing" QUICK_SIMPLE_TRAINING_ENGLISH_YOUTUBE_LINK = "https://youtu.be/YjfPCUtZHlI" QUICK_SIMPLE_TRAINING_HINDI_YOUTUBE_LINK = "https://youtu.be/zthrk6XfpjQ" HOW_TO_USE_BP_PASSPORT_HINDI_YOUTUBE_LINK = "https://youtu.be/aktZ1yTdDOA" SIMPLE_DOCUMENTARY_SHORT_YOUTUBE_LINK = "https://youtu.be/C26CoyeExmU" SIMPLE_DOCUMENTARY_LONG_YOUTUBE_LINK = "https://youtu.be/G0Pj_2aFGCQ" ONE_PAGER_INDIA_LINK = "https://drive.google.com/a/resolvetosavelives.org/file/d/1M2BpHYZALN8UAOaLZUfwFKCRvmq0fI7s/view?usp=sharing" ONE_PAGER_SIMPLE_LINK = "https://drive.google.com/file/d/12bo_H82Jk8k9cBmN4ta0OGcHP988rDeo/view" APP_USERS_GUIDE_AMHARIC_DOWNLOAD_LINK = "https://drive.google.com/file/d/1_RemdV7sOgTPsihXOxRp9Ud_ZV8DP1U_/view?usp=sharing" APP_USERS_GUIDE_BENGALI_DOWNLOAD_LINK = "https://drive.google.com/file/d/1yHBxU1gifqqDbwhkc1vgd-fg6NxKTj9i/view?usp=sharing" APP_USERS_GUIDE_ENGLISH_DOWNLOAD_LINK = "https://drive.google.com/file/d/1mFE2sFtDkUqCxGS-jBfUfrVHvqqtNHoU/view?usp=sharing" APP_USERS_GUIDE_HINDI_DOWNLOAD_LINK = "https://drive.google.com/file/d/1fVFZZZu9sW8jxsM2H11d7jmbjV8RJzA_/view?usp=sharing" APP_USERS_GUIDE_MARATHI_DOWNLOAD_LINK = "https://drive.google.com/file/d/1v_B9uoI4zmKDXJFQ0bigjB6-ChuMUngh/view?usp=sharing" APP_USERS_GUIDE_OROMO_DOWNLOAD_LINK = "https://drive.google.com/file/d/1ho_g1tOkY6r8oWItKLRqkaQITUuyWEOq/view?usp=sharing" APP_USERS_GUIDE_PUNJABI_DOWNLOAD_LINK = "https://drive.google.com/file/d/1NkcvXFXjnabhO8aVRZkvcbgf3kaEJugO/view?usp=sharing" APP_USERS_GUIDE_TAMIL_DOWNLOAD_LINK = "https://drive.google.com/file/d/18SquYM3RrtZSAbyocnOnPDtzLMtEctRp/view?usp=sharing" APP_USERS_GUIDE_TELUGU_DOWNLOAD_LINK = "https://drive.google.com/file/d/1otvYVtmHu0QXTpdcst8EgIlwU5Tkqv5V/view?usp=sharing" APP_USERS_GUIDE_TIGRINYA_DOWNLOAD_LINK = "https://drive.google.com/file/d/11vosmjIiLKDoMlOyd5vHICPBOKX1k2lE/view?usp=sharing" HOW_TO_TAKE_A_BP_POSTER_AMHARIC_DOWNLOAD_LINK = "https://drive.google.com/file/d/1EuQ8VanfY2qFBu22-HhK6Duaue0GyifN/view?usp=sharing" HOW_TO_TAKE_A_BP_POSTER_BENGALI_DOWNLOAD_LINK = "https://drive.google.com/file/d/1_k8IhV6NsMClwZTi_vzkeZgEeK_09cq-/view?usp=sharing" HOW_TO_TAKE_A_BP_POSTER_ENGLISH_DOWNLOAD_LINK = "https://drive.google.com/file/d/1DK90sSCIn1y-MvAAYktbFyYhqxreKHea/view?usp=sharing" HOW_TO_TAKE_A_BP_POSTER_HINDI_DOWNLOAD_LINK = "https://drive.google.com/file/d/1qnh9GEfEl1zMz10-yzKeT39bFIMRO2VV/view?usp=sharing" HOW_TO_TAKE_A_BP_POSTER_MARATHI_DOWNLOAD_LINK = "https://drive.google.com/file/d/1Qd8EIxyeL3A4Ok1xjllzw0TaVIgleeW1/view?usp=sharing" HOW_TO_TAKE_A_BP_POSTER_OROMO_DOWNLOAD_LINK = "https://drive.google.com/file/d/1EWE4bdlqN8aLrzAysP-jUGdEUXv8Hakd/view?usp=sharing" HOW_TO_TAKE_A_BP_POSTER_PUNJABI_DOWNLOAD_LINK = "https://drive.google.com/file/d/1MgGKXdwslTSA2xlKMwMa8M6-o486NMLs/view?usp=sharing" HOW_TO_TAKE_A_BP_POSTER_TAMIL_DOWNLOAD_LINK = "https://drive.google.com/file/d/1sb2xnwKGjVZCSTSktVtATot0e2ZF9lj6/view?usp=sharing" HOW_TO_TAKE_A_BP_POSTER_TELUGU_DOWNLOAD_LINK = "https://drive.google.com/file/d/1FvgNytO9WYLl3QkJD5hObOCJLwq4BeHw/view?usp=sharing" HOW_TO_TAKE_A_BP_POSTER_TIGRINYA_DOWNLOAD_LINK = "https://drive.google.com/file/d/16yQIyykh1EBNxmzTKfD6Ett__NrSvL0y/view?usp=sharing" end
class AddSubscriptionFieldsToUsers < ActiveRecord::Migration[6.1] def change add_column :users, :plan, :string add_column :users, :subscription_status, :string, default: "incomplete" end end
class NetworkController < ApplicationController before_action :network_params, :breadcrumbs private def breadcrumbs @breadcrumbs = [ {name: 'Blockchains', url: locale_path_prefix}, {name: @network[:name], url: "#{locale_path_prefix}#{@network[:network]}"}, (params[:address] ? {name: "#{t("tabs.#{controller_name}.show.name")}: #{params[:address].truncate(15)}", url: "#{locale_path_prefix}#{@network[:network]}/address/#{params[:address]}"} : nil), (params[:token1] ? {name: "#{params[:token1].truncate(15)} - #{params[:token2].truncate(15)}", url: "#{locale_path_prefix}#{@network[:network]}/tokenpair/#{params[:token1]}/#{params[:token2]}"} : nil), (params[:block] ? {name: "#{t("tabs.#{controller_name}.show.name")}: #{params[:block].truncate(15)}", url: "#{locale_path_prefix}#{@network[:network]}/block/#{params[:block]}"} : nil), (params[:hash] ? {name: "#{t("tabs.#{controller_name}.show.name")}: #{params[:hash].truncate(15)}", url: "#{locale_path_prefix}#{@network[:network]}/tx/#{params[:hash]}"} : nil), ((params[:address] || params[:block] || params[:hash]) && action_name != 'show' ? {name: t("tabs.#{controller_name}.#{action_name}.name"), url: "#{locale_path_prefix}#{@network[:network]}/#{params[:hash]}"} : nil), (params[:symbol] ? {name: "#{t("tabs.#{controller_name}.show.name")}: #{params[:symbol].truncate(15)}", url: "#{locale_path_prefix}#{@network[:network]}/token/#{params[:symbol]}"} : nil), ].compact end def locale_path_prefix if params[:locale] "/#{params[:locale]}/" else '/' end end def network_params raise "Network not defined" unless params[:network] @network = params[:network].kind_of?(ActionController::Parameters) ? params[:network].permit(:network, :tag, :name, :family, :currency, :icon, :streaming, :chainId, :platform, :innovation).to_h : BLOCKCHAIN_BY_NAME[params[:network]] @id = params[:id] @streaming = @network[:streaming] if params[:address] @address = @query = params[:address] elsif params[:block] || params[:height] @height = params[:block] || params[:height] elsif params[:hash] @hash = @query = params[:hash] end end end
class CreateUsuarioRoots < ActiveRecord::Migration[5.0] def change create_table :usuario_roots, id: false do |t| t.string :IdRoot, primary_key: true t.string :DNI t.string :Correo t.string :Password t.timestamps end add_foreign_key :usuario_roots, :usuario_generals , column: :DNI, primary_key: :DNI end end
Pod::Spec.new do |s| s.name = 'WVRUtil' s.version = '0.0.1' s.summary = 'WVRUtil files' s.homepage = 'https://git.moretv.cn/whaley-vr-ios-lib/WVRUtil' s.license = 'MIT' s.authors = {'whaleyvr' => 'vr-iosdev@whaley.cn'} s.platform = :ios, '9.0' s.source = {:git => 'https://git.moretv.cn/whaley-vr-ios-lib/WVRUtil.git', :tag => s.version} s.source_files = ['WVRUtil/Classes/**/*.{h,m}', 'WVRUtil/Classes/*.h'] s.resources = ['WVRUtil/Classes/nation.db'] s.requires_arc = true s.frameworks = ['Foundation', 'UIKit'] s.dependency 'FMDB' s.dependency 'CocoaHTTPServer' end
require 'active_support/core_ext/object/try' require 'active_support/inflector' require_relative './db_connection.rb' class AssocParams def other_class other_class_name.constantize end def other_table_name other_class.table_name end end class BelongsToAssocParams < AssocParams def initialize(name, params) @name = name.to_s @params = params end def primary_key @params[:primary_key] || "id" end def foreign_key @params[:foreign_key] || "#{@name}_id" end def other_class_name @params[:class_name] || @name.to_s.camelize end def type :belongs_to end end class HasManyAssocParams < AssocParams def initialize(name, params) @name = name.to_s @params = params end def primary_key @params[:primary_key] || "id" end def foreign_key @params[:foreign_key] || "#{other_table_name}_id" end def other_class_name @params[:class_name] || @name.singularize.camelize end def type :has_many end end module Associatable def assoc_params @assoc_params ? @assoc_params : @assoc_params = {} end def belongs_to(name, params = {}) assoc_params[name] = BelongsToAssocParams.new(name, params) aps = assoc_params[name] define_method(name) do command = <<-SQL SELECT DISTINCT #{aps.other_table_name}.* FROM #{self.class.table_name} INNER JOIN #{aps.other_table_name} ON #{aps.other_table_name}.#{aps.primary_key} = #{self.class.table_name}.#{aps.foreign_key} WHERE #{aps.other_table_name}.#{aps.primary_key} = ? SQL results = DBConnection.execute(command, self.send(aps.foreign_key)) aps.other_class.parse_all(results) end end def has_many(name, params = {}) aps = HasManyAssocParams.new(name, params) define_method(name) do command = <<-SQL SELECT * FROM #{aps.other_table_name} WHERE #{aps.other_table_name}.#{aps.foreign_key} = (?) SQL results = DBConnection.execute(command, self.send(aps.primary_key)) aps.other_class.parse_all(results) end end def has_one_through(name, assoc1, assoc2) aps1 = @assoc_params[assoc1] define_method(name) do aps2 = aps1.other_class.assoc_params[assoc2] command = <<-SQL SELECT #{aps2.other_table_name}.* FROM #{self.class.table_name} INNER JOIN #{aps1.other_table_name} INNER JOIN #{aps2.other_table_name} ON #{self.class.table_name}.#{aps1.foreign_key} = #{aps1.other_table_name}.#{aps1.primary_key} AND #{aps1.other_table_name}.#{aps2.foreign_key} = #{aps2.other_table_name}.#{aps2.primary_key} WHERE #{self.class.table_name}.#{aps1.primary_key} = ? SQL p self.send(aps1.primary_key) p DBConnection.execute(command, self.send(aps1.primary_key)) end end end
require_relative "../require/macfuse" class CryfsMac < Formula desc "Encrypts your files so you can safely store them in Dropbox, iCloud, etc." homepage "https://www.cryfs.org" url "https://github.com/cryfs/cryfs/releases/download/0.11.0/cryfs-0.11.0.tar.xz" sha256 "5583f84f3fcbd4bdbdcc9bfe4bb10971b2fca80a67b539b340556b5de482b737" license "LGPL-3.0-only" bottle do root_url "https://github.com/gromgit/homebrew-fuse/releases/download/cryfs-mac-0.11.0" sha256 cellar: :any, big_sur: "aebb5495fbbce0865daa8d78eb10bbf5f2353c80a7db15168f6579b43bb63493" sha256 cellar: :any, catalina: "9e60ca10a4fef208741d9c0675d529f60a8bf51f2f90a522b69887f72cb7c423" sha256 cellar: :any, mojave: "4a944758eccb9d7fa906425a1944ee3bb1337134b2d0051c1ee39ba7d0f52017" end head do url "https://github.com/cryfs/cryfs.git", branch: "develop", shallow: false end depends_on "cmake" => :build depends_on "conan" => :build depends_on "ninja" => :build depends_on "pkg-config" => :build depends_on "boost" depends_on "libomp" depends_on MacfuseRequirement depends_on :macos depends_on "openssl@1.1" def install setup_fuse configure_args = [ "-GNinja", "-DBUILD_TESTING=off", ] if build.head? libomp = Formula["libomp"] configure_args.concat( [ "-DOpenMP_CXX_FLAGS='-Xpreprocessor -fopenmp -I#{libomp.include}'", "-DOpenMP_CXX_LIB_NAMES=omp", "-DOpenMP_omp_LIBRARY=#{libomp.lib}/libomp.dylib", ], ) end # macFUSE puts pkg-config into /usr/local/lib/pkgconfig, which is not included in # homebrew's default PKG_CONFIG_PATH. We need to tell pkg-config about this path for our build ENV.prepend_path "PKG_CONFIG_PATH", "#{HOMEBREW_PREFIX}/lib/pkgconfig" system "cmake", ".", *configure_args, *std_cmake_args system "ninja", "install" end test do ENV["CRYFS_FRONTEND"] = "noninteractive" # Test showing help page assert_match "CryFS", shell_output("#{bin}/cryfs 2>&1", 10) # Test mounting a filesystem. This command will ultimately fail because homebrew tests # don't have the required permissions to mount fuse filesystems, but before that # it should display "Mounting filesystem". If that doesn't happen, there's something # wrong. For example there was an ABI incompatibility issue between the crypto++ version # the cryfs bottle was compiled with and the crypto++ library installed by homebrew to. mkdir "basedir" mkdir "mountdir" assert_match "Operation not permitted", pipe_output("#{bin}/cryfs -f basedir mountdir 2>&1", "password") end end
require 'minitest/autorun' require '././test/test_helper' require '././lib/api/yandex_api' describe YandexAPI do before do config = YAML.load_file('./config/yandex.yml') @yandex_api = YandexAPI.new(config) end describe '#translate' do it 'should translate a simple text from polish to english' do VCR.use_cassette('yandex_api') do @yandex_api.translate('krowa', 'en', 'pl').must_equal 'cow' end end end end
# list of films documentary = "Supersize Me" drama = "Girl on a Train" comedy = "Dumb and Dumber" dramedy = "Dragon Tattoo" book = "Cat in the Hat" #Questions puts "On a scale from 1 to 5, with 5 being the highest, how much did you like each genre?" puts "documentaries" doc_like = gets.chomp.to_i puts "dramas" drama_like = gets.chomp.to_i puts "comedies" comedy_like = gets.chomp.to_i # The code below goes through the combination of answers # documentary result if doc_like >= 4 puts "You can watch, #{documentary}" # dramedy result elsif doc_like <=3 && drama_like >=4 && comedy_like >=4 puts "May I recommend you watch, #{dramedy}" elsif doc_like <=3 && drama_like >=4 && comedy_like <=3 puts "You will love #{drama}!" elsif doc_like <=3 && drama_like <=3 && comedy_like >=4 puts "You should watch #{comedy}" elsif doc_like <=3 && drama_like <=3 && comedy_like <=3 if doc_like > drama_like && doc_like>comedy_like puts "watch doc" end if drama_like > doc_like && drama_like > comedy_like puts "watch drama" end if comedy_like > doc_like && comedy_like > drama_like puts "watch comedy" end puts "I recommend reading a #{book}" end
json.array!(@clients) do |client| json.extract! client, :id, :name, :guests_of_honor, :date_of_event, :date_booked, :type_of_event, :minimum_guarantee, :amount_of_guests, :base_price, :additional_charges, :deposit, :payment_1_date, :payment_2_date, :final_payment_date, :payment_1, :payment_2, :menu json.url client_url(client, format: :json) end
require 'rails_helper' describe List, 'relations' do it { should belong_to :account } it { should belong_to :store } it { should have_many :list_items } end describe List, 'validations' do it { should validate_presence_of :account_id } it { should validate_presence_of :store_id } it { should validate_numericality_of(:account_id).only_integer } it { should validate_numericality_of(:store_id).only_integer } end
# Dingbats and decorations for console output module Dings SPEAR = '➤' RTRI = '►' LTRI = '◄' RRTRI = '⏩' LLTRI = '⏪' LLQ = '«' RRQ = '»' LLQBIG = '《' RRQBIG = '》' LSQBR = '【' RSQBR = '】' SFSQ = '▮' SESQ = '▯' STAR = '✱' DIAM = '♦' SQRBULLF = '⬛' SQRBULLE = '⬜' CIRBULLF = '⬤' CIRBULLE = '◯' SHADE1 = '░' SHADE2 = '▒' TALLBLK1 = '▉' TALLBLK2 = '▇' TALLBLK3 = '▆' TALLBLK4 = '█' CHKT = '✓' CHKF = '✔' XTHIN = '✗' XFAT = '✘' RARR = '←' LARR = '→' UARR = '↑' DARR = '↓' LRARR = '↔' UDARR = '↕' ULARR = '↖' URARR = '↗' DLARR = '↘' DRARR = '↙' RARRR = '⟵' LARRR = '⟶' RLARRR = '⟷' end
Spree::Payment.class_eval do def global_collect_amount Spree::Money.new(amount_without_decimals).cents end private def amount_without_decimals Spree::Config[:hide_cents] ? amount.floor : amount end end
require 'rails_helper' RSpec.describe 'Readings', type: :request do let!(:user) { create(:user) } let!(:readings) { create_list(:reading, 2, user_id: user.id) } let(:user_id) { user.id } let(:id) { readings.first.id } describe 'POST /api/v1/readings' do let!(:valid_attributes) do { bedroom: 1, study: 1, garage: 1, living: 1, kitchen: 1, guest: 1, consumption: 1, available: 1, saved: 1, user_id: 1 } end context 'when the readings creation' do before { post '/api/v1/readings', params: valid_attributes } it 'returns error code 401 before login' do expect(json['code']).to eq(401) end end context 'when the request is invalid' do before do post '/api/v1/readings', params: { bedroom: ' ', study: ' ', garage: 1, living: 1, kitchen: 1, guest: 1, consumption: 1, available: 1, saved: 1, user_id: 1 } end it 'return status code 401 before login' do expect(json['code']).to eq(401) end end end describe 'GET /api/v1/readings' do before { get '/api/v1/readings' } context 'when all readings are hidden before required login' do it 'returns error code 401' do expect(json['code']).to eq(401) end end end describe 'GET /api/v1/readings/user/:user_id' do before { get "/api/v1/readings/user/#{user_id}" } context 'when users readings are hidden before required login' do it 'returns error code 401' do expect(json['code']).to eq(401) end end context 'when user does not exists' do let(:user_id) { 0 } it 'returns status code 401' do expect(json['code']).to eql(401) end end end describe 'GET /api/v1/user/:user_id/reading/:id' do before { get "/api/v1/user/#{user_id}/reading/#{id}" } context 'when user single reading is hidden before required login' do it 'returns status code 401' do expect(json['code']).to eq(401) end context 'when user does not exists' do let(:user_id) { 0 } it 'returns status code 401' do expect(json['code']).to eql(401) end end end end end
require 'spec_helper' describe AuroraProvider do describe(".create_from_aurora_service") do before do @previous_config = Chorus::Application.config.chorus end after do Chorus::Application.config.chorus = @previous_config end context "aurora is configured" do before do mock(Aurora::JavaModules::AuroraService).get_instance(anything) { Object.new } aurora_config = YAML.load_file(Rails.root.join('config', 'chorus.yml.example'))['aurora'] Chorus::Application.config.chorus = {'aurora' => aurora_config} end it "returns a valid provider" do provider = AuroraProvider.create_from_aurora_service provider.should be_valid end end context "aurora is not configured" do before do Chorus::Application.config.chorus = {'aurora' => nil} # stub out exception because java library caches service returned from get_instance mock(Aurora::JavaModules::AuroraService).get_instance(anything) { raise StandardError } end it "handles an exception" do provider = AuroraProvider.create_from_aurora_service provider.should_not be_valid end end end describe "#valid?" do it "returns the aurora provider status" do aurora_service = Object.new mock(aurora_service).valid? { true } provider = AuroraProvider.new(aurora_service) provider.should be_valid end end describe ".provide!" do let(:gpdb_instance) { gpdb_instances(:aurora) } let(:database) { Object.new } let(:schema_name) { "schema_name" } let(:attributes) { {"template" => "small", "size" => 1, "database_name" => "database", "schema_name" => schema_name} } let(:new_database) { GpdbDatabase.create({:name => 'database', :gpdb_instance => gpdb_instance}, :without_protection => true) } context "when provisioning succeeds" do before do stub(database).public_ip { '123.321.12.34' } any_instance_of(Aurora::Service) do |service| mock(service).find_template_by_name("small") { Aurora::DB_SIZE[:small] } mock(service).create_database({ :template => Aurora::DB_SIZE[:small], :database_name => 'database', :db_username => gpdb_instance.owner_account.db_username, :db_password => gpdb_instance.owner_account.db_password, :size => 1, :schema_name => schema_name }) { database } end any_instance_of(GpdbInstance) do |gpdb_instance| stub(gpdb_instance).refresh_databases() {} end end it "creates a database" do AuroraProvider.provide!(gpdb_instance.id, attributes) end it "updates the host of the instance with the correct ip address" do AuroraProvider.provide!(gpdb_instance.id, attributes) gpdb_instance.reload gpdb_instance.host.should == "123.321.12.34" end it "generates a ProvisioningSuccess event" do AuroraProvider.provide!(gpdb_instance.id, attributes) event = Events::ProvisioningSuccess.where(:actor_id => gpdb_instance.owner.id).last event.greenplum_instance.should == gpdb_instance end context "state" do before do mock(Gpdb::ConnectionBuilder).connect!(gpdb_instance, gpdb_instance.owner_account, 'database') {} end it "updates the state to online" do AuroraProvider.provide!(gpdb_instance.id, attributes) gpdb_instance.reload gpdb_instance.state.should == 'online' end end context "when schema name is not public" do before do mock(Gpdb::ConnectionBuilder).connect!(gpdb_instance, gpdb_instance.owner_account, 'database') { } mock(gpdb_instance).databases { [new_database] } end it "connects to the newly created database and creates new schema" do AuroraProvider.provide!(gpdb_instance.id, attributes) gpdb_instance.reload gpdb_instance.databases.map(&:name).should include("database") end end context "when new schema name is public" do let(:schema_name) { 'public' } let(:create_new_schema_called) { false } before do stub(Gpdb::ConnectionBuilder).connect!(gpdb_instance, gpdb_instance.owner_account, 'database') { create_new_schema_called = true } end it "connects to the newly created database and does not create new schema if schema_name is public" do AuroraProvider.provide!(gpdb_instance.id, attributes) create_new_schema_called.should == false end end end context "when provisioning fails" do before do any_instance_of(Aurora::Service) do |service| stub(service).find_template_by_name { 'template' } mock(service).create_database(anything) { raise StandardError.new("server cannot be reached") } end end it "generates a ProvisioningFail event" do AuroraProvider.provide!(gpdb_instance.id, attributes) event = Events::ProvisioningFail.find_last_by_actor_id(gpdb_instance.owner) event.greenplum_instance.should == gpdb_instance event.additional_data['error_message'].should == "server cannot be reached" end it "updates the state to fault" do AuroraProvider.provide!(gpdb_instance.id, attributes) gpdb_instance.reload gpdb_instance.state.should == 'fault' end end end end
class SubscriptionsController < ApplicationController before_action :set_subscription, only: [:show, :edit, :update, :destroy] before_action :correct_user, only: [:edit, :update, :destroy] # GET /subscriptions # GET /subscriptions.json def index @subscriptions = Subscription.all end # GET /subscriptions/1 # GET /subscriptions/1.json def show end # GET /subscriptions/new def new # check if user has two subscriptions or less if current_user.subscriptions.size <= 2 # if the user has less than 2 subscriptions, we'll allow them to create a 3rd @subscription = current_user.subscriptions.build # but if the user aleady has three subscriptions, then we redirect them with a message elsif current_user.subscriptions.size >= 3 redirect_to users_profile_url(current_user.id), notice: 'You lost more than three pets? | Call the Police!' end end # GET /subscriptions/1/edit def edit end # POST /subscriptions # POST /subscriptions.json def create @subscription = current_user.subscriptions.build(subscription_params) respond_to do |format| if @subscription.save format.html { redirect_to users_profile_url(current_user.id), notice: 'Your pet was successfully created.' } format.json { render :show, status: :created, location: @subscription } else format.html { render :new } format.json { render json: @subscription.errors, status: :unprocessable_entity } end end # PATCH/PUT /subscriptions/1 # PATCH/PUT /subscriptions/1.json def update respond_to do |format| if @subscription.update(subscription_params) format.html { redirect_to users_profile_url(current_user.id), notice: 'Your pet was successfully updated.' } format.json { render :show, status: :ok, location: @subscription } else format.html { render :edit } format.json { render json: @subscription.errors, status: :unprocessable_entity } end end end # DELETE /subscriptions/1 # DELETE /subscriptions/1.json def destroy @subscription.destroy respond_to do |format| format.html { redirect_to :back, notice: 'Your pet was successfully destroyed.' } format.json { head :no_content } end private # Use callbacks to share common setup or constraints between actions. def set_subscription @subscription = Subscription.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def subscription_params params.require(:subscription).permit(:title, :company, :url, :start_time, :end_time, :phone_number, :time, :pet_name, :breed, :animal, :notes, :pet_image, :option_1, :option_2, :gender) end def correct_user @subscriptions = current_user.subscriptions.find_by(id: params[:id]) redirect_to users_profile_url, notice: "Not authorized to edit this pet" if @subscription.nil? end end end end
require_relative '../../../app/elastic_client' ES_HOST = 'http://elasticsearch' class SpecUtils class << self def create_index(index_name) url = "#{ES_HOST}/#{index_name}" @client = ElasticClient.new( url, Net::HTTP::Delete, {} ) @client.perform end end
class AlarmListener attr_accessor :app_db def initialize @app_db = AppDb.new end def start! proc_id = Process.fork do listen_pin = @app_db.data[:input_pin].to_i activate_pin = @app_db.data[:output_pin].to_i gpio = WiringPi::GPIO.new gpio.mode( listen_pin, INPUT) if listen_pin > 0 if activate_pin > 0 gpio.mode( activate_pin, OUTPUT) gpio.write activate_pin, 0 end loop do state = gpio.readAll if state[listen_pin] == 0 RestClient.post 'http://localhost:4567/api/start', {} gpio.write( activate_pin, 1 ) if activate_pin > 0 end sleep 0.3 end Process.exit end @app_db.update_attribute :event_listener_pid, proc_id end def stop! if proc_id = @app_db.read_attribute( :event_listener_pid ) begin Process.kill(9, proc_id) rescue Exception => e puts e end end end end
require './config/dotenv' require './config/oj' require 'bigdecimal/util' require 'tty/table' require 'pry' require 'awesome_print' require './lib/tinky/client' require './lib/tinky/client_error' module Tinky # rubocop:disable Metrics/ModuleLength CURRENCIES = { RUB: { symbol: '₽', ticker: nil }, USD: { symbol: '$', ticker: 'USD000UTSTOM' }, EUR: { symbol: '€', ticker: 'EUR_RUB__TOM' } }.freeze class << self def portfolio items = positions puts "\nPortfolio:" puts portfolio_table(items) puts "\nTotal amount summary:" rates = exchange_rates(items) summary_data = full_summary(items, rates).values puts summary_table(summary_data) print_timestamp end def wallet items = client.portfolio_currencies.dig(:payload, :currencies) puts "\nWallet:" puts wallet_table(items) print_timestamp end def portfolio_table(items) prev_type = items.first[:instrumentType] table = TTY::Table.new( header: %w[Type Name Amount Avg.\ buy Current\ price Yield Yield\ %] ) items.each do |item| # table << :separator if item[:instrumentType] != prev_type table << row_data(item) prev_type = item[:instrumentType] end table.render(:unicode, padding: [0, 1, 0, 1]) end def wallet_table(items) table = TTY::Table.new(header: %w[Currencies]) items.each do |item| currency = CURRENCIES[item[:currency].to_sym] formatted_value = format('%.2f %s', item[:balance], currency[:symbol]) table << [ { value: pastel.bold(formatted_value), alignment: :right } ] end table.render(:unicode, padding: [0, 1, 0, 1]) end # rubocop:disable Metrics/AbcSize def total_amount(positions) total = Hash.new do |h, k| h[k] = { price: 0, yield: 0, total: 0 } end positions.each_with_object(total) do |item, result| currency = item.dig(:averagePositionPrice, :currency).to_sym avg_price = item.dig(:averagePositionPrice, :value).to_d price = avg_price * item[:balance].to_d expected_yield = item.dig(:expectedYield, :value).to_d result[currency][:price] += price result[currency][:yield] += expected_yield result[currency][:total] += price + expected_yield end end # rubocop:enable Metrics/AbcSize def exchange_rates(positions) # calculate exchange rate in RUB by currency currencies(positions).reduce({}) do |result, c| balance = c[:balance].to_d # currency amount in EUR, USD avg_price = c.dig(:averagePositionPrice, :value).to_d # price inRUB sum = avg_price * balance # sum in RUB expected_yield = c.dig(:expectedYield, :value).to_d # profit in RUB total = sum + expected_yield # avg. buy price + profit in RUB rate = (total / balance).round(4) # exchange rate in RUB # get currency code by ticker currency = currency_by_ticker(c[:ticker]) result.merge(currency => rate) end end def summary(items, rates) # rubocop:disable Metrics/AbcSize total = Hash.new { |h, k| h[k] = [0, '₽'] } total_amount(items).each_with_object(total) do |(key, value), memo| rate = rates.fetch(key, 1) memo[:price][0] += value[:price] * rate memo[:yield][0] += value[:yield] * rate memo[:total][0] += value[:total] * rate end end def full_summary(items, rates) result = summary(items, rates) result.merge( yield_percent: [result[:yield][0] / result[:price][0] * 100, '%'], total_with_rub: [result[:total][0] + rub_balance, '₽'] ) end private def client Client.new end def pastel Pastel.new end def portfolio_data client.portfolio end def sell_price(item) balance = item[:balance].to_d avg_buy_price = item[:averagePositionPrice][:value].to_d expected_yield = item[:expectedYield][:value].to_d { value: ((balance * avg_buy_price) + expected_yield) / balance, currency: item[:averagePositionPrice][:currency] } end def row_data(item) [ item[:instrumentType].upcase, decorate_name(item[:name]), { value: decorate_amount(item[:balance]), alignment: :right }, { value: decorate_price(item[:averagePositionPrice]), alignment: :right }, { value: decorate_price(sell_price(item)), alignment: :right }, { value: decorate_yield(item[:expectedYield]), alignment: :right }, { value: decorate_yield_percent(item), alignment: :right } ] end def decorate_yield(expected_yield) value = expected_yield[:value] currency = CURRENCIES[expected_yield[:currency].to_sym] formatted_value = format('%+.2f %s', value, currency[:symbol]) pastel.decorate(formatted_value, yield_color(value)) end def decorate_yield_percent(item) total = item.dig(:averagePositionPrice, :value).to_d * item[:balance].to_d value = item.dig(:expectedYield, :value).to_d / total.to_d * 100 formatted_value = format('%+.2f %%', value.round(2)) pastel.decorate(formatted_value, yield_color(value)) end def yield_color(value) if value.positive? :green elsif value.negative? :red else :clear end end def decorate_amount(amount) if amount == amount.to_i amount.round else amount end end def decorate_name(name) stripped_name = if name.length > 29 "#{name[0..28]}…" else name end pastel.bold(stripped_name) end def decorate_price(price) currency = CURRENCIES[price[:currency].to_sym] format('%.2f %s', price[:value], currency[:symbol]) end def print_timestamp puts "\nLast updated: #{Time.now}\n\n" end def currency_by_ticker(ticker) CURRENCIES.select { |_, v| v[:ticker] == ticker }.keys.first end def positions portfolio_data.dig(:payload, :positions) end # select only currencies positions (wallet) def currencies(positions) positions.select do |position| position[:instrumentType] == 'Currency' end end def decorate_summary(items) items.map do |item| value = format('%+.2f %s', item[0].to_f.round(2), item[1]) { value: pastel.decorate(value, yield_color(item[0]), :bold), alignment: :right } end end def summary_table(items) table = TTY::Table.new( header: [ 'Total Purchases', 'Expected Yield', 'Expected Total', 'Yield %', 'Total + RUB balance' ] ) table << decorate_summary(items) table.render(:unicode, padding: [0, 1, 0, 1]) end def rub_balance client .portfolio_currencies .dig(:payload, :currencies) .find { |i| i[:currency] == 'RUB' }[:balance].to_d end end end
# frozen_string_literal: true class BaseSerializer < ActiveModel::Serializer def editable return false unless current_user Pundit.policy!(current_user, object).update? end def show_personal_info? scope.authorized_to_edit?(object) end end
require 'spec_helper' describe "Quote that makes a product unavailable" do let (:quote) { Quote.new(travelers: travelers, total_trip_cost: total_trip_cost) } context "when a single traveler is too old" do let (:travelers) { [Traveler.new(age: 150)] } let (:total_trip_cost) { 1_000 } it "should return a premium of nil" do expect( quote.premium ).to be_nil end end context "when a traveler in a group of multiple travelers is too old" do let (:travelers) { [Traveler.new(age: 14), Traveler.new(age: 12), Traveler.new(age: 150)] } let (:total_trip_cost) { 1_000 } it "should return a premium of nil" do expect( quote.premium ).to be_nil end end end
# frozen_string_literal: true class Address < ApplicationRecord belongs_to :province has_many :addresslists has_many :users, through: :addresslists accepts_nested_attributes_for :addresslists accepts_nested_attributes_for :users def name street_no + ' ' + city + ' ' + postal_code end end
# frozen_string_literal: true class StudentTagsController < HtmlController include Pagy::Backend has_scope :table_order, only: [:index, :show], type: :hash has_scope :search, only: [:index, :show] def index authorize Tag @pagy, @tags = pagy apply_scopes(policy_scope(StudentTagTableRow.includes(:organization), policy_scope_class: TagPolicy::Scope)) end def show @tag = Tag.find params.require(:id) authorize @tag @student_table_component = StudentComponents::StudentTable.new { |students| pagy apply_scopes(policy_scope(students.joins("INNER JOIN student_tags ON student_id = student_table_rows.id AND tag_id = '#{@tag.id}'"))) } end def edit @tag = Tag.find params.require(:id) authorize @tag end def update @tag = Tag.find params.require(:id) authorize @tag return redirect_to student_tag_path(@tag) if @tag.update tag_params render :edit end def new authorize Tag @tag = Tag.new end def create tag = Tag.new tag_params authorize tag return link_notice_and_redirect t(:tag_created, name: tag.tag_name), new_student_tag_path, I18n.t(:create_another), student_tag_path(tag) if tag.save render :new end private def tag_params params.require(:tag).permit(:tag_name, :organization_id, :shared) end end
#!/usr/bin/env ruby -I ../lib require 'vrb' # require 'rbvmomi' require 'trollop' opts = Trollop.options do banner <<-EOS Clone a VM. Usage: clone_vm.rb source_vm_path dest_vm_name [cust_spec_name] [dest_ip_address] [network_label] Example: clone_vm.rb Tukwila/vm/UnixTeam/Templates/centos6-test-2 seapnewbox01 custom-test-fixed EOS end # assign CLI arguments ARGV.size >= 2 or abort "must specify VM source name and VM target name" source_vm_path = ARGV[0] dest_vm_name = ARGV[1] if ARGV[2] cust_spec_name = ARGV[2] dest_ip_address = ARGV[3] or abort "must specify IP address when using customization" if ARGV[4] network_label = ARGV[4] end end # connect to vcenter using .fog file vc = Vrb::Vcenter.new # create empty clone_spec, then populate properties below clone_spec = RbVmomi::VIM.VirtualMachineCloneSpec # power on new vm after clone? clone_spec.powerOn = false # create new vm as a template? clone_spec.template = false # set default location for clone_spec clone_spec.location = RbVmomi::VIM.VirtualMachineRelocateSpec if cust_spec_name # get the actual customization spec object by name from vcenter spec_mgr = vc.mob.serviceContent.customizationSpecManager clone_spec.customization = spec_mgr.GetCustomizationSpec(:name => cust_spec_name).spec clone_spec.customization.nicSettingMap.first.adapter.ip.ipAddress = dest_ip_address end # vm = vc.get_vm_by_path('source_vm_path') <-- isn't working, falling back to rbvmomi method vm_mob = vc.mob.searchIndex.FindByInventoryPath(:inventoryPath => source_vm_path) vm_mob.CloneVM_Task(:folder => vm_mob.parent, :name => dest_vm_name, :spec => clone_spec).wait_for_completion
class CreatePropertiesPeakSeasons < ActiveRecord::Migration[5.0] def change create_table :peak_seasons_properties do |t| t.references :property, foreign_key: true t.references :peak_season, foreign_key: true end end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_filter :load_header_image def load_header_image possible_images = Photograph.for_location("#{controller_name}_#{action_name}-header") @header_image = possible_images.count > 1 ? possible_images.to_a.sample : possible_images.first end private def authenticate authenticate_or_request_with_http_basic do |username, password| ENV['USERNAME'].present? && ENV['PASSWORD'].present? && username == ENV['USERNAME'] && password == ENV['PASSWORD'] end end end
describe 'Contacts API' do describe 'GET #index' do it_behaves_like 'API Authenticable' context 'authorized' do let(:me) { create :user } let!(:contact) { create :contact, user_id: me.id } let(:access_token) { create :access_token, resource_owner_id: me.id } before { get '/api/v1/contacts', params: { format: :json, access_token: access_token.token } } it 'returns 200 status' do expect(response).to be_success end it 'contains list of user contacts' do expect(response.body).to be_json_eql(ContactSerializer.new(contact).serializable_hash.to_json).at_path('contacts/0') end end def do_request(options = {}) get '/api/v1/contacts', params: { format: :json }.merge(options) end end describe 'GET #show' do let(:me) { create :user } let!(:contact) { create :contact, user_id: me.id } let!(:another_contact) { create :contact } it_behaves_like 'API Authenticable' context 'authorized' do let(:access_token) { create :access_token, resource_owner_id: me.id } context 'with valid attributes' do before { get "/api/v1/contacts/#{contact.id}", params: { format: :json, access_token: access_token.token } } it 'returns 200 status' do expect(response).to be_success end %w(id name email phone address company).each do |attr| it "and contains #{attr}" do expect(response.body).to be_json_eql(contact.send(attr.to_sym).to_json).at_path("contact/#{attr}") end end it 'and contains modified birthday' do expect(response.body).to be_json_eql(contact.birthday.strftime('%d/%m/%Y').to_json).at_path("contact/birthday") end end context 'with invalid attributes' do it 'returns error message if try access to another user contact or unexisted contact' do get "/api/v1/contacts/#{another_contact.id}", params: { format: :json, access_token: access_token.token } expect(response.body).to eq "{\"error\":\"Contact does not exist\"}" end end end def do_request(options = {}) get "/api/v1/contacts/#{contact.id}", params: { format: :json }.merge(options) end end describe 'POST #create' do it_behaves_like 'API Authenticable' context 'authorized' do let(:me) { create :user } let(:access_token) { create :access_token, resource_owner_id: me.id } context 'with valid attributes' do it 'saves the new contact in the DB and it belongs to current user' do expect { post '/api/v1/contacts', params: { contact: attributes_for(:contact), format: :json, access_token: access_token.token } }.to change(me.contacts, :count).by(1) end it 'and returns 200 status code' do post '/api/v1/contacts', params: { contact: attributes_for(:contact), format: :json, access_token: access_token.token } expect(response).to be_success end it 'and renders json with contact hash' do post '/api/v1/contacts', params: { contact: attributes_for(:contact), format: :json, access_token: access_token.token } expect(response.body).to be_json_eql(ContactSerializer.new(Contact.last).serializable_hash.to_json).at_path('contacts/0') end end context 'with invalid attributes' do it 'does not save the new contact in the DB' do expect { post '/api/v1/contacts', params: { contact: attributes_for(:contact, :empty_name), format: :json, access_token: access_token.token } }.to_not change(Contact, :count) end it 'and returns 400 status code' do post '/api/v1/contacts', params: { contact: attributes_for(:contact, :empty_name), format: :json, access_token: access_token.token } expect(response.status).to eq 400 end it 'and returns error message' do post '/api/v1/contacts', params: { contact: attributes_for(:contact, :empty_name), format: :json, access_token: access_token.token } expect(response.body).to eq "{\"error\":\"Incorrect contact data\"}" end end end def do_request(options = {}) post '/api/v1/contacts', params: { format: :json }.merge(options) end end describe 'PATCH #update' do let(:me) { create :user } let(:access_token) { create :access_token, resource_owner_id: me.id } let!(:contact) { create :contact, user_id: me.id } it_behaves_like 'API Authenticable' context 'authorized' do context 'with valid attributes' do before do patch "/api/v1/contacts/#{contact.id}", params: { contact: attributes_for(:contact, name: 'New Name for Contact'), format: :json, access_token: access_token.token } contact.reload end it 'updates contact in the DB' do expect(contact.name).to eq 'New Name for Contact' end it 'and returns 200 status code' do expect(response).to be_success end it 'and renders json with contact hash' do expect(response.body).to be_json_eql(ContactSerializer.new(contact).serializable_hash.to_json).at_path('contacts/0') end end context 'with invalid attributes' do let!(:another_contact) { create :contact } it 'does not update contact in the DB if incorrect data' do patch "/api/v1/contacts/#{contact.id}", params: { contact: attributes_for(:contact, name: ''), format: :json, access_token: access_token.token } contact.reload expect(contact.name).to eq 'Contact Name' end it 'and returns 400 status code' do patch "/api/v1/contacts/#{contact.id}", params: { contact: attributes_for(:contact, name: ''), format: :json, access_token: access_token.token } expect(response.status).to eq 400 end it 'returns error message if try access to another user contact or unexisted contact' do patch "/api/v1/contacts/#{another_contact.id}", params: { contact: attributes_for(:contact), format: :json, access_token: access_token.token } expect(response.body).to eq "{\"error\":\"Contact does not exist\"}" end it 'returns error message if try send incorrect data' do patch "/api/v1/contacts/#{contact.id}", params: { contact: attributes_for(:contact, :empty_name), format: :json, access_token: access_token.token } expect(response.body).to eq "{\"error\":\"Incorrect contact data\"}" end end end def do_request(options = {}) patch "/api/v1/contacts/#{contact.id}", params: { contact: attributes_for(:contact), format: :json }.merge(options) end end describe 'DELETE #destroy' do let(:me) { create :user } let!(:contact) { create :contact, user_id: me.id } it_behaves_like 'API Authenticable' context 'authorized' do let(:access_token) { create :access_token, resource_owner_id: me.id } context 'with valid attributes' do it 'returns 200 status' do delete "/api/v1/contacts/#{contact.id}", params: { format: :json, access_token: access_token.token } expect(response).to be_success end it 'and removes contact from DB' do expect { delete "/api/v1/contacts/#{contact.id}", params: { format: :json, access_token: access_token.token } }.to change(Contact, :count).by(-1) end end context 'with invalid attributes' do let!(:another_contact) { create :contact } it 'returns error message if try access to another user contact or unexisted contact' do delete "/api/v1/contacts/#{another_contact.id}", params: { format: :json, access_token: access_token.token } expect(response.body).to eq "{\"error\":\"Contact does not exist\"}" end end end def do_request(options = {}) get "/api/v1/contacts/#{contact.id}", params: { format: :json }.merge(options) end end end
class SessionsController < ApplicationController before_action :redirect_if_logged_in, except: [:destroy] layout :determine_layout def new end def create @user = User.find_by(username: params[:user][:username]) if @user && @user.authenticate(params[:user][:password]) session[:user_id] = @user.id redirect_to projects_path else @errors = ["Username or password incorrect"] render :new end end def create_with_facebook user = User.find_or_create_by(email: auth["info"]["email"]) do |u| u.username = auth["info"]["name"] u.first_name = auth["info"]["name"].split(" ")[0] u.last_name = auth["info"]["name"].split(" ").last # byebug u.password = "password" end if user.save session[:user_id] = user.id redirect_to projects_path else @user = User.new render 'users/new' end end def destroy session.clear redirect_to '/' end private def auth request.env['omniauth.auth'] end end
require 'securerandom' require 'shoryuken' require 'shoryuken/redis_connection' require 'shoryuken/batch/callback' require 'shoryuken/batch/middleware' require 'shoryuken/batch/status' require 'shoryuken/batch/version' module Shoryuken def self.redis raise ArgumentError, 'requires a block' unless block_given? redis_pool.with do |conn| retryable = true begin yield conn rescue Redis::CommandError => ex # Failover can cause the server to become a slave, need # to disconnect and reopen the socket to get back to the master. (conn.disconnect!; retryable = false; retry) if retryable && ex.message =~ /READONLY/ raise end end end def self.redis_pool @redis ||= Shoryuken::RedisConnection.create end def self.redis=(hash) @redis = if hash.is_a?(ConnectionPool) hash else Shoryuken::RedisConnection.create(hash) end end class Batch class NoBlockGivenError < StandardError; end BID_EXPIRE_TTL = 108_000 attr_reader :bid, :description, :callback_queue, :created_at def initialize(existing_bid = nil) @bid = existing_bid || SecureRandom.urlsafe_base64(10) @existing = !(!existing_bid || existing_bid.empty?) # Basically existing_bid.present? @initialized = false @created_at = Time.now.utc.to_f @bidkey = 'BID-' + @bid.to_s @ready_to_queue = [] end def description=(description) @description = description persist_bid_attr('description', description) end def callback_queue=(callback_queue) @callback_queue = callback_queue persist_bid_attr('callback_queue', callback_queue) end def on(event, callback, options = {}) return unless %w[success complete].include?(event.to_s) callback_key = "#{@bidkey}-callbacks-#{event}" Shoryuken.redis do |r| r.multi do r.sadd(callback_key, JSON.unparse(callback: callback, opts: options)) r.expire(callback_key, BID_EXPIRE_TTL) end end end def jobs raise NoBlockGivenError unless block_given? bid_data, Thread.current[:bid_data] = Thread.current[:bid_data], [] begin if !@existing && !@initialized parent_bid = Thread.current[:bid].bid if Thread.current[:bid] Shoryuken.redis do |r| r.multi do r.hset(@bidkey, 'created_at', @created_at) r.hset(@bidkey, 'parent_bid', parent_bid.to_s) if parent_bid r.expire(@bidkey, BID_EXPIRE_TTL) end end @initialized = true end @ready_to_queue = [] begin parent = Thread.current[:bid] Thread.current[:bid] = self yield ensure Thread.current[:bid] = parent end return [] if @ready_to_queue.empty? Shoryuken.redis do |r| r.multi do if parent_bid r.hincrby("BID-#{parent_bid}", 'children', 1) r.expire("BID-#{parent_bid}", BID_EXPIRE_TTL) end r.hincrby(@bidkey, 'pending', @ready_to_queue.size) r.hincrby(@bidkey, 'total', @ready_to_queue.size) r.expire(@bidkey, BID_EXPIRE_TTL) r.sadd(@bidkey + '-jids', @ready_to_queue) r.expire(@bidkey + '-jids', BID_EXPIRE_TTL) end end @ready_to_queue ensure Thread.current[:bid_data] = bid_data end end def increment_job_queue(jid) @ready_to_queue << jid end def parent_bid Shoryuken.redis do |r| r.hget(@bidkey, 'parent_bid') end end def parent Shoryuken::Batch.new(parent_bid) if parent_bid end def valid?(batch = self) valid = !Shoryuken.redis { |r| r.exists("invalidated-bid-#{batch.bid}") } batch.parent ? valid && valid?(batch.parent) : valid end private def persist_bid_attr(attribute, value) Shoryuken.redis do |r| r.multi do r.hset(@bidkey, attribute, value) r.expire(@bidkey, BID_EXPIRE_TTL) end end end class << self def process_failed_job(bid, jid) _, pending, failed, children, complete = Shoryuken.redis do |r| r.multi do r.sadd("BID-#{bid}-failed", jid) r.hincrby("BID-#{bid}", 'pending', 0) r.scard("BID-#{bid}-failed") r.hincrby("BID-#{bid}", 'children', 0) r.scard("BID-#{bid}-complete") r.expire("BID-#{bid}-failed", BID_EXPIRE_TTL) end end enqueue_callbacks(:complete, bid) if pending.to_i == failed.to_i && children == complete end def process_successful_job(bid, jid) failed, pending, children, complete, success, _total, parent_bid = Shoryuken.redis do |r| r.multi do r.scard("BID-#{bid}-failed") r.hincrby("BID-#{bid}", 'pending', -1) r.hincrby("BID-#{bid}", 'children', 0) r.scard("BID-#{bid}-complete") r.scard("BID-#{bid}-success") r.hget("BID-#{bid}", 'total') r.hget("BID-#{bid}", 'parent_bid') r.srem("BID-#{bid}-failed", jid) r.srem("BID-#{bid}-jids", jid) r.expire("BID-#{bid}", BID_EXPIRE_TTL) end end Shoryuken.logger.info "done: #{jid} in batch #{bid}" enqueue_callbacks(:complete, bid) if pending.to_i == failed.to_i && children == complete enqueue_callbacks(:success, bid) if pending.to_i.zero? && children == success end def enqueue_callbacks(event, bid) batch_key = "BID-#{bid}" callback_key = "#{batch_key}-callbacks-#{event}" callbacks, queue, parent_bid = Shoryuken.redis do |r| r.multi do r.smembers(callback_key) r.hget(batch_key, 'callback_queue') r.hget(batch_key, 'parent_bid') end end return if callbacks.empty? parent_bid = !parent_bid || parent_bid.empty? ? nil : parent_bid # Basically parent_bid.blank? options ||= {} options[:message_attributes] ||= {} options[:message_attributes]['shoryuken_class'] = { string_value: 'Shoryuken::Batch::Callback::Worker', data_type: 'String' } callbacks.each do |jcb| cb = JSON.parse(jcb) options[:message_body] = { 'event' => event, 'bid' => bid, 'parent_bid' => parent_bid, 'job_class' => cb['callback'], 'arguments' => cb['opts'] } Shoryuken::Client.queues(queue).send_message(options) end end end end end
class BootstrapFormBuilder < ActionView::Helpers::FormBuilder def label_default(method, text = nil, options = {}, &block) label(method, text, merge_class(options, 'form-label'), &block) end def text_field(method, options = {}) super(method, merge_class(options, 'form-control')) end def number_field(method, options = {}) super(method, merge_class(options, 'form-control')) end def email_field(method, options = {}) super(method, merge_class(options, 'form-control')) end def password_field(method, options = {}) super(method, merge_class(options, 'form-control')) end def text_field_with_label(method, options = {}) label_default(method) + text_field(method, options) + attribute_errors(@object, method) end def number_field_with_label(method, options = {}) label_default(method) + number_field(method, options) + attribute_errors(@object, method) end def email_field_with_label(method, options = {}) label_default(method) + email_field(method, options) + attribute_errors(@object, method) end def password_field_with_label(method, options = {}) label_default(method) + password_field(method, options) + attribute_errors(@object, method) end private def attribute_errors(resource, method) @template.content_tag(:span, class: 'form-text text-danger') do return '' unless resource.errors.has_key?(method) resource.errors.full_messages_for(method).join(', ') end end def merge_class_attribute_value(options, value) new_options = options.clone new_options[:class] = [value, new_options[:class]].join(" ") new_options end alias_method :merge_class, :merge_class_attribute_value end
Rails.application.routes.draw do mount RailsAdmin::Engine => "/admin", :as => "rails_admin" root controller: "display", action: "index" end
#Write four instance methods for rectangle: #area, which returns the area of the rectangle #perimeter, which returns the perimeter of the rectangle #diagonal, which returns the length of the rectangle's diagonal as a Float #square?, which returns true if the rectangle is a square and false otherwise class Rectangle attr_accessor :width, :height def initialize(width, height) @width = width @height = height end def ==(other) (other.width == self.width && other.height == self.height ) || (other.height == self.width && other.width == self.height ) end def area @width.to_f * @height.to_f end def perimeter 2 * @width + 2 * @height end def diagonal x = (@height**2 + width**2) Math.sqrt(x) end def square? @width == @height end end test_rect = Rectangle.new(10,20) puts test_rect.area puts test_rect.perimeter puts test_rect.diagonal puts test_rect.square?
#!/usr/bin/env ruby require 'optparse' require 'myimdb' options = {} OptionParser.new do |opts| opts.banner = "Usage: #{File.basename($0)} [movie name]" opts.on("-h", "--help", "Displays this help info") do puts opts exit 0 end opts.on("-r", "--rottentomatoes", "Generates data from Rotten Tomatoes") do options[:rottentomatoes] = true end opts.on("-m", "--metacritic", "Generates data from Metacritic") do options[:metacritic] = true end opts.on("-b", "--freebase", "Generates data from Freebase") do options[:freebase] = true end opts.on("-i", "--imdb", "Generates data from Imdb") do options[:imdb] = true end begin opts.parse!(ARGV) rescue OptionParser::ParseError => e warn e.message puts opts exit 1 end # need a movie name if ARGV.empty? puts opts exit(0) end end # add imdb as default options.merge!(:imdb=> true) if options.empty? name = ARGV.join(' ') def details(klass_name, name) search_scope = "#{klass_name.downcase}.com" search_result = Myimdb::Search::Base.search(name, :restrict_to=> search_scope)[0] site = eval("Myimdb::Scraper::#{klass_name}").new(search_result[:url]) puts "====================================================" puts "#{klass_name} details for: #{name}" puts "====================================================" puts "#{site.summary}\n" rescue Exception=> ex puts "Unable to fetch #{klass_name} details for: #{name} because: #{ex.message}" end ['Imdb', 'RottenTomatoes', 'Metacritic', 'Freebase'].each do |site| details(site, name) if options[site.downcase.to_sym] end
module BasicAuthUrl module_function def build(url, user: Figaro.env.basic_auth_user_name, password: Figaro.env.basic_auth_password) URI.parse(url).tap do |uri| uri.user = user.present? ? user : nil uri.password = password.present? ? password : nil end.to_s end end
class ReviewsController < ApplicationController before_action :find_play before_action :find_review , only: [:edit , :update , :destroy] before_action :authenticate_user!, except: [:index, :show] def new @review=Review.new end def create @review=Review.new(review_params) @review.play_id=Play.id @review.user_id=current_user.id if @review.save redirect_to play_path(@play) else render 'new' end end def update if @review.update(review_params) redirect_to play_path(@play) else render 'edit' end end def edit end def destroy @review.destroy redirect_to play_path(@play) end private def review_params params.require(:review).permit(:rating , :comment) end def find_review @review = Review.find(params[:id]) end def find_play @play=Play.find(params[:play_id]) end end
require 'spec_helper' require 'json' describe 'title subfield a boost' do include_context 'solr_helpers' before(:all) do delete_all end context 'when performing a keyword search combining author and title' do silence_by_cage = '1228819' anarchy_silence_by_cage = '6184414' four_by_cage = '4789869' no_such_thing_as_silence = '6081592' sounds_like_silence_cage_in_title = '7381137' before(:all) do add_doc(silence_by_cage) add_doc(anarchy_silence_by_cage) add_doc(four_by_cage) add_doc(no_such_thing_as_silence) add_doc(sounds_like_silence_cage_in_title) end it 'work matching 245a and author comes first' do expect(solr_resp_doc_ids_only({ 'q' => 'cage silence' })) .to include(silence_by_cage).as_first.document end it 'works matching exact titles first' do expect(solr_resp_doc_ids_only({ 'q' => 'Silence'})) .to include(silence_by_cage).as_first.document end it 'work matching 245a and not author comes before work matching author and not 245a' do expect(solr_resp_doc_ids_only({ 'q' => 'cage silence' })) .to include(sounds_like_silence_cage_in_title).before(four_by_cage) end it 'both match 245a but work that includes author in rest of title comes first' do expect(solr_resp_doc_ids_only({ 'q' => 'cage silence' })) .to include(sounds_like_silence_cage_in_title).before(no_such_thing_as_silence) end end context 'when performing a keyword search with local and scsb results' do capitalism_socialism_democracy_1 = '1225885' capitalism_socialism_democracy_2 = '1225884' capitalism_socialism_democracy_3 = 'SCSB-3330744' before(:all) do add_doc(capitalism_socialism_democracy_1) add_doc(capitalism_socialism_democracy_2) add_doc(capitalism_socialism_democracy_3) end it 'sorts scsb record after local records' do expect(solr_resp_doc_ids_only({ 'q' => 'capitalism socialism democracy' })) .to include(capitalism_socialism_democracy_1).before(capitalism_socialism_democracy_3) expect(solr_resp_doc_ids_only({ 'q' => 'capitalism socialism democracy' })) .to include(capitalism_socialism_democracy_2).before(capitalism_socialism_democracy_3) end end context 'when performing CJK searches' do exact_match = '6581897' variant_exact_match = '1831578' japanese_exact_match = '3175938' left_anchor_match = '4216926' non_phrase_match = '4276901' before(:all) do add_doc(exact_match) add_doc(variant_exact_match) add_doc(japanese_exact_match) add_doc(left_anchor_match) add_doc(non_phrase_match) end it 'records that contain non-phrase mathces appear last' do expect(solr_resp_doc_ids_only({ 'q' => '诗经研究', 'sort' => 'score ASC' })) .to include(non_phrase_match).as_first.document end it 'work matching full 245 as phrase comes first' do expect(solr_resp_doc_ids_only({ 'q' => '诗经研究'})) .to include(japanese_exact_match).as_first.document end end after(:all) do delete_all end end
class Stuff < ActiveRecord::Base has_many :tags, through: :stuffs_tags has_many :stuffs_tags belongs_to :user default_scope -> { order('created_at DESC') } validates :user_id, presence: true validates :content, presence: true, length: {maximum: 250} STATU_CODE_AT_INBOX = 1 STATU_CODE_AT_TRASH = -1 STATU_CODE_AT_REF = -2 STATU_CODE_AT_FUTURE = -3 STATU_CODE_DONE = -99 STATU_CODE_AT_ORG =3 STATU_CODE_AT_OTHER =4 STATU_CODE_AT_NEXT = 99 STATU_CODE_AT_SCHEDULE =98 STATU_CODE_AT_PROJECT =97 NEED_DOING_STUFF_MIN_VAL = 50 STATU_CODE_2_NAME = { -99 => 'Done', 99 => 'at Next Action folder', 98 => 'at Schedule folder', 97 => 'at Project folder', -2 => 'at Refence folder', 1 => 'at Inbox', -1 => 'at Trashcan', -3 => 'at Future folder', 3 => 'at Organzie folder', -4 => 'at Other folder' } PLAN_TIME =[['', -1], ['5 m', 1], ['15 m', 2], ['30 m', 3], ['1 h', 4], ['2 h', 5], ['3 h', 6], ['4 h', 7], ['5 h', 8], ['6 h', 9], ['7 h', 10], ['1 day', 11], ['2 day', 12], ['3 day', 13], ['4 day', 14], ['1 week', 15], ['2 week', 16], ['3 week', 17], ['1 month', 18], ['2 month', 19], ['3 month', 20], ['4 month', 21], ['5 month', 22], ['6 month', 23], ['1 year', 24], ['2 year', 25], ['3 year', 26], ] PLAN_TIME_2 =[['', -1], ['5 m', 1], ['15 m', 2], ['30 m', 3], ['1 h', 4], ['2 h', 5], ['3 h', 6], ['4 h', 7], ['5 h', 8], ['6 h', 9], ['7 h', 10] ] def Stuff.statu_code_2_name(statu_code) STATU_CODE_2_NAME[statu_code] end def plan_time_set if self.parent_id != nil Stuff::PLAN_TIME[0..10] else Stuff::PLAN_TIME end end def tags_ids self.stuffs_tags.all.map { |t| t.tag_id } end def Stuff.groups(user) user.stuffs.select('statu_code ,COUNT(statu_code ) AS statu_num'). group(:statu_code).reorder('') #user.stuffs.all( # :select => 'statu_code ,COUNT(statu_code ) AS statu_num', # :group => "statu_code" # #) end def Stuff.stuff_code_2_group_num(groups, stuff_code) groups.each do |g| if g.stuff_code == stuff_code return g.statu_num end end return nil end # def update_tags(new_stuff_tags) old_stuff_tags = self.tags if new_stuff_tags.count == 1 && new_stuff_tags.first == "0" self.stuffs_tags.destroy_all else old_stuff_tags.each do |ost| self.stuffs_tags.find_by(tag_id: ost).destroy unless new_stuff_tags.include? ost end new_stuff_tags.each do |nst| self.stuffs_tags.create(tag_id: nst) unless old_stuff_tags.include? nst end end end def to_next_act STATU_CODE_AT_NEXT end def to_schedule STATU_CODE_AT_SCHEDULE end def to_project STATU_CODE_AT_PROJECT end end
require 'gap_intelligence/client/requestable' require 'gap_intelligence/client/ad_images' require 'gap_intelligence/client/ad_pages' require 'gap_intelligence/client/ad_page_advertisements' require 'gap_intelligence/client/ad_shares' require 'gap_intelligence/client/advertisements' require 'gap_intelligence/client/brands' require 'gap_intelligence/client/categories' require 'gap_intelligence/client/category_versions' require 'gap_intelligence/client/countries' require 'gap_intelligence/client/delta' require 'gap_intelligence/client/downloads' require 'gap_intelligence/client/files' require 'gap_intelligence/client/headers' require 'gap_intelligence/client/in_store_images' require 'gap_intelligence/client/merchants' require 'gap_intelligence/client/merchant_pricing_trends' require 'gap_intelligence/client/notes_and_changes' require 'gap_intelligence/client/pricings' require 'gap_intelligence/client/pricing_images' require 'gap_intelligence/client/products' require 'gap_intelligence/client/product_presence' require 'gap_intelligence/client/promo_matrix' require 'gap_intelligence/client/promotions' module GapIntelligence class Client include Requestable include AdImages include AdPages include AdPageAdvertisements include AdShares include Advertisements include Brands include Countries include Categories include CategoryVersions include Delta include Downloads include InStoreImages include Merchants include MerchantPricingTrends include NotesAndChanges include Pricings include PricingImages include Products include ProductPresence include PromoMatrix include Promotions include Headers include Files attr_reader :connection attr_accessor :client_id, :client_secret, :host, :port, :use_ssl, :scope, :connection_build, :connection_opts, :raise_errors def initialize(config = {}, &block) @client_id = config[:client_id] || GapIntelligence.config.client_id @client_secret = config[:client_secret] || GapIntelligence.config.client_secret @host = config[:host] || GapIntelligence.config.host @port = config[:port] || GapIntelligence.config.port @use_ssl = config[:use_ssl] || GapIntelligence.config.use_ssl @scope = config[:scope] @connection_build = block || GapIntelligence.config.connection_build @raise_errors = config[:raise_errors] || GapIntelligence.config.raise_errors @connection_opts = config[:connection_opts] || GapIntelligence.config.connection_opts end # Returns the current connection to gAPI. If the connection is old or # has not be established, do whatever is required to provide a connection. # # @return [OAuth2::AccessToken] def connection @connection = create_connection! unless connected? @connection end # Checks the current connection to gAPI is established and not expired. # # @return [Boolean] def connected? @connection && !@connection.expired? end # Opens a connection to gAPI # # @raise [ConfigurationError] If the client is not properly configured properly. # @raise [AuthenticationError] If authentication fails for any reason. def create_connection! raise ConfigurationError unless client_id && client_secret begin client_params = {} client_params[:scope] = @scope if @scope OAuth2::Client.new(client_id, client_secret, { site: api_base_uri, connection_opts: connection_opts }, &connection_build) .client_credentials .get_token(client_params, 'auth_scheme' => 'request_body') rescue OAuth2::Error => e raise AuthenticationError, e.message end end # Returns headers # # @return [Hash] def headers { 'Accept' => 'application/vnd.gapintelligence.com; version=1' } end def api_base_uri ( use_ssl ? URI::HTTPS : URI::HTTP).build(host: host, port: port) end end end
module Infosell class XMLFormGroup < Infosell::Model::XMLBase def self.parse(xml) { :title => xml.attribute("title").try(:content), :elements => xml.css("element").collect { |element_xml| XMLFormElement.new(element_xml) } } end end end
#!/usr/bin/env ruby HEADER = <<-header /* * Copyright #{Time.new.year} Navita Tecnologia. * * 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. */ header Dir['**/*.java'].each do |java_file| original = File.read(java_file) next unless original.scan(HEADER).empty? puts "Including header for: #{java_file}" File.open(java_file, 'w') do |f| f.write(HEADER) f.write(original) end end
class Game < ApplicationRecord default_scope -> { order(created_at: :desc) } validates :user_id, presence: true validates :description, presence: true, length: { maximum: 500 } validates :title, presence: true, uniqueness: true validates :genre, presence: { message: "を選択してください"} validates :participation, presence: { message: "を選択してください"} validates :target_age, presence: { message: "を選択してください"} validates :play_time, presence: { message: "を選択してください"} validates :price, presence: { message: "を選択してください"} validate :image_size belongs_to :user has_many :reviews has_many :favorites has_many :favorite_users, through: :favorites, source: "user" mount_uploader :image, ImageUploader def self.search(search) if search where(["title LIKE ?", "%#{search}%"]) else all end end private def image_size if image.size > 5.megabytes errors.add(:image, "5MB以内の画像にしてください") end end end
class Zombie < ApplicationRecord has_one :brain, dependent: :destroy end
# # Author:: Jamie Winsor (<jamie@vialstudios.com>) # Copyright:: 2011, En Masse Entertainment, Inc # License:: Apache License, Version 2.0 # # 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. # require 'pathname' module EnMasse module Dragonfly module FFMPEG class Encoder autoload :Profile, 'dragonfly-ffmpeg/encoder/profile' #include ::Dragonfly::Configurable attr_writer :encoder_profiles def encoder_profiles @encoder_profiles || { :mp4 => [ Profile.new(:html5, :video_codec => "libx264", :resolution => "1024x768", :frame_rate => 25, :video_bitrate => 1600, :x264_vprofile => "baseline", :audio_codec => "libfaac", :audio_bitrate => 128, :audio_channels => 2, :audio_sample_rate => 48000, #:video_preset => "x264" ) ], :ogv => [ Profile.new(:html5, :video_codec => "libtheora", :resolution => "640x480", :frame_rate => 25, :video_bitrate => 1500, :audio_codec => "libvorbis", :audio_bitrate => 128, :audio_channels => 2, :audio_sample_rate => 48000 ) ], :webm => [ Profile.new(:html5, :video_codec => "libvpx", :resolution => "1280x720", :frame_rate => 29.97, :video_bitrate => 3072, :audio_codec => "libvorbis", :audio_bitrate => 128, :audio_channels => 2, :audio_sample_rate => 48000, :custom => "-f webm" ) ], :mp3 => [ Profile.new(:html5, :audio_codec => "libmp3lame", :audio_channels => 2, :custom => "-qscale:a 5" ) ], :ogg => [ Profile.new(:html5, :audio_codec => "libvorbis", :audio_channels => 2, :custom => "-qscale:a 5" ) ] } end attr_writer :output_directory def output_directory @output_directory || '/tmp' end def update_url(attrs, format, args="") attrs.ext = format.to_s end def call(content, format, args="") Rails.logger.debug(content.inspect) temp_obj,meta = encode(content.temp_object, format) content.update(temp_obj) Rails.logger.debug(content.inspect) content.meta = meta content.ext = meta[:format] Rails.logger.debug(content.meta) end # Encodes a Dragonfly::TempObject with the given format. # # An optional profile may be specified by passing a symbol in as the optional profile parameter. # Profiles are defined by the configurable attribute 'encoder_profiles' - by default one profile # is defined for major web formats, :html5. def encode(temp_object, format, profile = :html5, options = {}) options[:meta] = {} unless options[:meta] format = format.to_sym original_basename = File.basename(temp_object.path, '.*') raise UnsupportedFormat, "Format not supported - #{format}" unless supported_format?(format) unless profile.is_a?(Profile) raise UnknownEncoderProfile unless profile_defined?(format, profile.to_sym) profile = get_profile(format, profile.to_sym) end options.merge!(profile.encoding_options) origin = ::FFMPEG::Movie.new(temp_object.path) tempfile = new_tempfile(format, original_basename) transcoded_file = origin.transcode(tempfile.path, options) if(format.to_s == 'mp4' && `qt-faststart`) `qt-faststart #{transcoded_file.path} #{transcoded_file.path}.tmp.mp4` `mv #{transcoded_file.path}.tmp.mp4 #{transcoded_file.path}` end content = ::Dragonfly::TempObject.new(File.new(transcoded_file.path)) meta = { :name => (original_basename + ".#{format}"), :format => format, :ext => File.extname(transcoded_file.path) }.merge(options[:meta]) Rails.logger.debug("Finished the encoding..." + meta.inspect) [content,meta] end private def new_tempfile(ext = nil, name = 'dragonfly-video') tempfile = ext ? Tempfile.new(["#{name}-", ".#{ext}"]) : Tempfile.new("#{name}-") tempfile.binmode tempfile.close tempfile end def profiles(format) encoder_profiles[format] end def get_profile(format, profile_name) result = profiles(format).select { |profile| profile.name == profile_name } result.first end def supported_format?(format) encoder_profiles.has_key?(format) end def profile_defined?(format, profile_name) return false if profiles(format).nil? encoder_profiles[format].any? { |profile| profile.name == profile_name } end end end end end
module OpenAPIParser::Parser::List def _openapi_attr_list_objects @_openapi_attr_list_objects ||= {} end def openapi_attr_list_object(name, klass, options = {}) target_klass.send(:attr_reader, name) _openapi_attr_list_objects[name] = OpenAPIParser::SchemaLoader::ListLoader.new(name, options.merge(klass: klass)) end end
FactoryGirl.define do factory :a_item, class: Item do name "complete awesome markdown on rspec" due_date "11/18/14" completed true end end
class AddSpecificFieldsForLeagueHdcpCalc < ActiveRecord::Migration[5.0] def change add_column :bowling_leagues, :hdcp_base, :integer, default: 210 add_column :bowling_leagues, :hdcp_factor, :float, default: 0.95 remove_column :bowling_leagues, :handicap_calculation, :string, default: "(210 - AVG) * 0.95" end end
require 'rails_helper' RSpec.describe 'show page for applications' do before(:each) do @application = Application.create(name: 'Greg', address: '123 streetname', description: 'I good pet owner', status: 'In Progress') @shelter = Shelter.create(name: 'Aurora shelter', city: 'Aurora, CO', foster_program: false, rank: 9) @pet_1 = Pet.create(name: 'Scooby', age: 2, breed: 'Great Dane', adoptable: true, shelter_id: @shelter.id) @pet_2 = Pet.create(name: 'Bob', age: 5, breed: 'Big Boy', adoptable: true, shelter_id: @shelter.id) ApplicationPet.create(application: @application, pet: @pet_1) ApplicationPet.create(application: @application, pet: @pet_2) end it 'shows the name of the applicant' do visit "/applications/#{@application.id}" expect(page).to have_content(@application.name) end it 'shows the address of the applicant' do visit "/applications/#{@application.id}" expect(page).to have_content(@application.address) end it 'lists partial matches as search results' do shelter = Shelter.create(name: 'Aurora shelter', city: 'Aurora, CO', foster_program: false, rank: 9) pet_1 = Pet.create(adoptable: true, age: 7, breed: 'sphynx', name: 'Bare-y Manilow', shelter_id: shelter.id) pet_2 = Pet.create(adoptable: true, age: 3, breed: 'domestic pig', name: 'Babe', shelter_id: shelter.id) pet_3 = Pet.create(adoptable: true, age: 4, breed: 'chihuahua', name: 'Elle', shelter_id: shelter.id) visit "/applications/#{@application.id}" fill_in 'Add a Pet to this Application', with: "Ba" click_on("Submit") expect(page).to have_content(pet_1.name) expect(page).to have_content(pet_2.name) expect(page).to_not have_content(pet_3.name) end it 'has an adopt a pet option' do shelter = Shelter.create(name: 'Aurora shelter', city: 'Aurora, CO', foster_program: false, rank: 9) pet_1 = Pet.create(adoptable: true, age: 7, breed: 'sphynx', name: 'Bare-y Manilow', shelter_id: shelter.id) pet_2 = Pet.create(adoptable: true, age: 3, breed: 'domestic pig', name: 'Babe', shelter_id: shelter.id) pet_3 = Pet.create(adoptable: true, age: 4, breed: 'chihuahua', name: 'Elle', shelter_id: shelter.id) visit "/applications/#{@application.id}" fill_in 'Add a Pet to this Application', with: "Ba" click_on("Submit") within("#pet-0") do expect(page).to have_button("Adopt this Pet") click_on("Adopt this Pet") end expect(current_path).to eq("/applications/#{@application.id}") expect(@application.pets).to include(pet_1) end it 'can be submitted' do shelter = Shelter.create(name: 'Aurora shelter', city: 'Aurora, CO', foster_program: false, rank: 9) pet_1 = Pet.create(adoptable: true, age: 7, breed: 'sphynx', name: 'Bare-y Manilow', shelter_id: shelter.id) visit "/applications/#{@application.id}" fill_in 'Add a Pet to this Application', with: "Ba" click_on("Submit") click_on("Adopt this Pet") fill_in 'description', with: 'example' click_on("Submit Application") expect(current_path).to eq("/applications/#{@application.id}") expect(page).to have_content("example") expect(page).to have_content("Pending") expect(page).to_not have_content("In Progress") expect(page).to_not have_content("Add a Pet to this Application") expect(page).to_not have_content("Submit Your Application") expect(page).to_not have_button('Submit') end end
class CreateCampaignsTable < ActiveRecord::Migration def change create_table :campaigns do |t| t.string :name t.integer :fund_amount t.integer :fund_goal end end end
# frozen_string_literal: true module RubyPushNotifications module FCM # Class that encapsulates the result of a single sent notification to a single # Registration ID # (https://developer.android.com/google/fcm/server-ref.html#table4) # @author Carlos Alonso class FCMResult; end # Indicates that the notification was successfully sent to the corresponding # registration ID class FCMResultOK < FCMResult def ==(other) other.is_a?(FCMResultOK) || super(other) end end # Indicates that the notification was successfully sent to the corresponding # registration ID but FCM sent a canonical ID for it, so the received canonical # ID should be used as registration ID ASAP. class FCMCanonicalIDResult < FCMResult # @return [String]. The suggested canonical ID from FCM attr_reader :canonical_id def initialize(canonical_id) @canonical_id = canonical_id end def ==(other) (other.is_a?(FCMCanonicalIDResult) && @canonical_id == other.canonical_id) || super(other) end end # An error occurred sending the notification to the registration ID. class FCMResultError < FCMResult # @return [String]. The error sent by FCM attr_accessor :error def initialize(error) @error = error end def ==(other) (other.is_a?(FCMResultError) && @error == other.error) || super(other) end end end end
Puppet::Type.newtype(:fluffy_rule) do @doc = 'Manage Fluffy rules' ensurable do defaultvalues defaultto(:present) end newparam(:name, :namevar => true) do desc 'Friendly name' end newparam(:rule, :namevar => true) do desc 'Rule name' newvalues(/^[\w_]+/) end newparam(:chain, :namevar => true) do desc 'Rule chain name' end newparam(:table, :namevar => true) do desc 'Rule packet filtering table' defaultto(:filter) newvalues(:filter,:nat,:mangle,:raw,:security) end #newproperty(:index) do # desc 'Rule index' #end newproperty(:before_rule) do desc 'Define the rule which should precede this' end newproperty(:after_rule) do desc 'Define the rule which should proceed this' end newproperty(:action) do desc 'Rule action' defaultto(:absent) newvalues(:absent,'ACCEPT','DROP','REJECT','QUEUE','RETURN','DNAT','SNAT','LOG','MASQUERADE','REDIRECT','MARK','TCPMSS') end newproperty(:jump) do desc 'Rule jump target' defaultto(:absent) end newproperty(:negate_protocol, :boolean => true) do desc 'Negate protocol' defaultto(:false) newvalues(:true,:false) end newproperty(:protocol, :array_matching => :all) do desc 'Network protocol(s)' def insync?(is) is.each do |value| return false unless @should.include?(value) end @should.each do |value| return false unless is.include?(value) end true end def should_to_s(newvalue = @should) if newvalue newvalue.inspect else nil end end validate do |value| fail "Invalid protocol '#{value}' in #{self[:name]}" unless ['ip','tcp','udp','icmp','ipv6-icmp','esp','ah','vrrp','igmp','ipencap','ipv4','ipv6','ospf','gre','cbt','sctp','pim','any'].include?(value) end defaultto([]) end newproperty(:negate_icmp_type, :boolean => true) do desc 'Negate ICMP type' defaultto(:false) newvalues(:true,:false) end newproperty(:icmp_type) do desc 'ICMP type' defaultto(:absent) newvalues(:absent, :any, 'echo-reply','destination-unreachable','network-unreachable','host-unreachable','protocol-unreachable','port-unreachable','fragmentation-needed','source-route-failed','network-unknown','host-unknown','network-prohibited','host-prohibited','TOS-network-unreachable','TOS-host-unreachable','communication-prohibited','host-precedence-violation','precedence-cutoff','source-quench','redirect','network-redirect','host-redirect','TOS-network-redirect','TOS-host-redirect','echo-request','router-advertisement','router-solicitation','time-exceeded','ttl-zero-during-transit','ttl-zero-during-reassembly','parameter-problem','ip-header-bad','required-option-missing','timestamp-request','timestamp-reply','address-mask-request','address-mask-reply') end newproperty(:negate_tcp_flags, :boolean => true) do desc 'Negate TCP flags' defaultto(:false) newvalues(:true,:false) end newproperty(:tcp_flags) do desc 'TCP flags' defaultto(:absent) end newproperty(:negate_ctstate, :boolean => true) do desc 'Negate conntrack state' defaultto(:false) newvalues(:true,:false) end newproperty(:ctstate, :array_matching => :all) do desc 'Conntrack state(s)' def insync?(is) is.each do |value| return false unless @should.include?(value) end @should.each do |value| return false unless is.include?(value) end true end def should_to_s(newvalue = @should) if newvalue newvalue.inspect else nil end end defaultto([]) end newproperty(:negate_state, :boolean => true) do desc 'Negate connection state(s)' defaultto(:false) newvalues(:true,:false) end newproperty(:state, :array_matching => :all) do desc 'Connection state(s)' def insync?(is) is.each do |value| return false unless @should.include?(value) end @should.each do |value| return false unless is.include?(value) end true end def should_to_s(newvalue = @should) if newvalue newvalue.inspect else nil end end defaultto([]) end newproperty(:negate_src_address_range, :boolean => true) do desc 'Negate source range address(es)' defaultto(:false) newvalues(:true,:false) end newproperty(:src_address_range, :array_matching => :all) do desc 'Source range address(es)' def insync?(is) is.each do |value| return false unless @should.include?(value) end @should.each do |value| return false unless is.include?(value) end true end def should_to_s(newvalue = @should) if newvalue newvalue.inspect else nil end end defaultto([]) end newproperty(:negate_dst_address_range, :boolean => true) do desc 'Negate destination range address(es)' defaultto(:false) newvalues(:true,:false) end newproperty(:dst_address_range, :array_matching => :all) do desc 'Destination range address(es)' def insync?(is) is.each do |value| return false unless @should.include?(value) end @should.each do |value| return false unless is.include?(value) end true end def should_to_s(newvalue = @should) if newvalue newvalue.inspect else nil end end defaultto([]) end newproperty(:negate_in_interface, :boolean => true) do desc 'Negate input interface' defaultto(:false) newvalues(:true,:false) end newproperty(:in_interface, :array_matching => :all) do desc 'Input interface' def insync?(is) is.each do |value| return false unless @should.include?(value) end @should.each do |value| return false unless is.include?(value) end true end def should_to_s(newvalue = @should) if newvalue newvalue.inspect else nil end end defaultto([]) end newproperty(:negate_out_interface, :boolean => true) do desc 'Negate output interface' defaultto(:false) newvalues(:true,:false) end newproperty(:out_interface, :array_matching => :all) do desc 'Output interface' def insync?(is) is.each do |value| return false unless @should.include?(value) end @should.each do |value| return false unless is.include?(value) end true end def should_to_s(newvalue = @should) if newvalue newvalue.inspect else nil end end defaultto([]) end newproperty(:negate_src_address, :boolean => true) do desc 'Negate source address(es)' defaultto(:false) newvalues(:true,:false) end newproperty(:src_address, :array_matching => :all) do desc 'Source address(es)' def insync?(is) is.each do |value| return false unless @should.include?(value) end @should.each do |value| return false unless is.include?(value) end true end def should_to_s(newvalue = @should) if newvalue newvalue.inspect else nil end end defaultto([]) end newproperty(:negate_dst_address, :boolean => true) do desc 'Negate destination address(es)' defaultto(:false) newvalues(:true,:false) end newproperty(:dst_address, :array_matching => :all) do desc 'Destination address(es)' def insync?(is) is.each do |value| return false unless @should.include?(value) end @should.each do |value| return false unless is.include?(value) end true end def should_to_s(newvalue = @should) if newvalue newvalue.inspect else nil end end defaultto([]) end newproperty(:negate_src_service, :boolean => true) do desc 'Negate source service(s)' defaultto(:false) newvalues(:true,:false) end newproperty(:src_service, :array_matching => :all) do desc 'Source services(s)' def insync?(is) is.each do |value| return false unless @should.include?(value) end @should.each do |value| return false unless is.include?(value) end true end def should_to_s(newvalue = @should) if newvalue newvalue.inspect else nil end end defaultto([]) end newproperty(:negate_dst_service, :boolean => true) do desc 'Negate destination service(s)' defaultto(:false) newvalues(:true,:false) end newproperty(:dst_service, :array_matching => :all) do desc 'Destination services(s)' def insync?(is) is.each do |value| return false unless @should.include?(value) end @should.each do |value| return false unless is.include?(value) end true end def should_to_s(newvalue = @should) if newvalue newvalue.inspect else nil end end defaultto([]) end newproperty(:reject_with) do desc 'Reject with' defaultto(:absent) newvalues(:absent,'icmp-net-unreachable','icmp-host-unreachable','icmp-port-unreachable','icmp-proto-unreachable','icmp-net-prohibited','icmp-host-prohibited','icmp-admin-prohibited') end newproperty(:set_mss) do desc 'Set maximum segment size (MSS)' validate do |value| if value != :absent fail "Rule MSS '#{value}' is not an Integer for #{self[:name]}" unless value.is_a?(Integer) end end defaultto(:absent) end newproperty(:clamp_mss_to_pmtu, :boolean => true) do desc 'Clamp MSS to path MTU' defaultto(:false) newvalues(:true,:false) end newproperty(:to_src) do desc 'Source NAT' defaultto(:absent) end newproperty(:to_dst) do desc 'Destination NAT' defaultto(:absent) end newproperty(:limit) do desc 'Limit rate' defaultto(:absent) end newproperty(:limit_burst) do desc 'Limit burst' defaultto(:absent) end newproperty(:log_prefix) do desc 'Log prefix' defaultto(:absent) end newproperty(:log_level) do desc 'Log level' defaultto(:absent) newvalues(:absent,:emerg,:alert,:crit,:err,:warning,:notice,:info,:debug) end newproperty(:comment) do desc 'Comment' defaultto(:absent) end def self.title_patterns [ [ /(^([^:]*)$)/, [ [:name], [:rule] ] ], [ /(^([^:]+):([^:]+):([^:]+)$)/, [ [:name], [:table], [:chain], [:rule] ] ] ] end autorequire(:fluffy_chain) do builtin_chains = { :filter => ['INPUT', 'FORWARD', 'OUTPUT'], :nat => ['INPUT', 'OUTPUT', 'PREROUTING', 'POSTROUTING'], :mangle => ['INPUT', 'FORWARD', 'OUTPUT', 'PREROUTING', 'POSTROUTING'], :raw => ['PREROUTING', 'OUTPUT'], :security => ['INPUT', 'FORWARD', 'OUTPUT'] } unless builtin_chains[self[:table]].include?(self[:chain]) ["#{self[:table]}:#{self[:chain]}"] else [] end end autorequire(:fluffy_service) do builtin_services = ['any'] req = [] [:src_service, :dst_service].each do |k| self[k].each do |service| req << service unless builtin_services.include?(service) end end req end autorequire(:fluffy_interface) do builtin_interfaces = ['any'] req = [] [:in_interface, :out_interface].each do |k| self[k].each do |interface| req << interface unless builtin_interfaces.include?(interface) end end req end autorequire(:fluffy_address) do reserved_addresses = ['any', 'any_broadcast'] req = [] [:src_address, :dst_address, :src_address_range, :dst_address_range].each do |k| self[k].each do |address| req << address unless reserved_addresses.include?(address) end end req end autorequire(:fluffy_rule) do req = [] req << self[:after_rule] if self[:after_rule] req << self[:before_rule] if self[:before_rule] req end validate do if self[:ensure] != :absent fail "Either jump or action are required for #{self[:name]}" unless self[:action] or self[:jump] end end autonotify(:fluffy_commit) do ['puppet'] end end
Rails.application.routes.draw do get 'likes/create' get 'likes/destroy' #homes routes root 'homes#index' get '/show' => 'homes#show' #likes routes get '/like' => 'likes#create' get '/unlike' => 'likes#destroy' #users routes get 'users/:id/following' => 'users#following',as: :following_user get 'users/:id/followers' => 'users#followers',as: :followers_user get 'users' => 'users#index', as: :users get 'users/new' => 'users#new', as: :new_user post 'users' => 'users#create', as: :create_user delete 'users/:id' => 'users#delete',as: :destroy_user patch 'users/:id/edit' => 'users#update' get 'users/:id' => 'users#show', as: :show_user get 'users/:id/edit' => 'users#edit', as: :edit_user #arts get 'arts' => 'arts#index', as: :art_index get "arts/new" => "arts#new" post "arts" => "arts#create", as: :create_art patch "arts/:id/edit" => "arts#update" get "arts/:id/edit" => "arts#edit", as: :edit_art get "arts/:id" => "arts#show", as: :show_art delete "arts/:id" => "arts#delete",as: :destroy_art #sessions get '/logout' => 'sessions#destroy',as: :logout resources :sessions, only: [:new, :create] resources :relationships, only: [:create, :destroy] end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception def current_user if session[:user_id].blank? || params[:q] === 0 then session[:user_id] = 0 elsif params[:q].present? and (session[:user_id] != params[:q]) then session[:user_id] = params[:q] end if session[:user_id] == "11" session[:card_flag] = 0 session[:user_id] = 1 end @current_user ||= User.find_by(id: session[:user_id]) end helper_method :current_user end
class InvitationController < ApplicationController def edit invite = current_user.inverse_invitations.find(params[:id]) if invite.nil? flash[:notice] = "Wrong Invite" redirect_to new_brand_path else InvitationService.new.accept_invitation(invite,current_user) redirect_to projects_path end end end
class Reduction < ApplicationRecord attr_accessor :date belongs_to :worker belongs_to :workshop validates_presence_of :cost, :worker_id, :workshop_id end
# frozen_string_literal: true class UpdateUserForm include ActiveModel::Model attr_accessor :user, :email, :first_name, :last_name, :phone, :contract_name, :lang, :active, :birthdate def initialize(attributes = {}) super @attributes = attributes end def save user.update(@attributes.slice(:email, :first_name, :last_name, :phone, :contract_name, :lang, :birthdate)) return if user.invalid? active ? user.undiscard : user.discard end end
require 'ffi-rzmq' module QueueTester module Engines class ZeroMQ_Transient def enqueue(messages) context = ZMQ::Context.new 1 requester = context.socket ZMQ::PUSH error_check(requester.connect('tcp://127.0.0.1:5555')) log_debug '[0MQ] Connected to broker' messages.each do |message| error_check(requester.send_string("ENQU#{message}")) progress(1) end log_debug '[0MQ] Sent' error_check(requester.close) end def dequeue(number) messages = [] context = ZMQ::Context.new 1 # Setup listening port port = 5556 receiver = context.socket ZMQ::PULL while error_check(receiver.bind("tcp://127.0.0.1:#{port}")) port += 1 log_debug "[0MQ] Failed to bind on port #{port}. Trying further." end log_debug "[0MQ] Listening on port #{port}..." # Create thread to inform broker broker_thread = Thread.new do requester = context.socket ZMQ::PUSH error_check(requester.connect('tcp://127.0.0.1:5555')) log_debug '[0MQ] Connected to broker' error_check(requester.send_string("SUBS[#{port},#{number}]")) log_debug "[0MQ] Sent subscription [#{port},#{number}]" error_check(requester.close) end number.times do |idx| message = '' error_check(receiver.recv_string(message)) log_debug "[0MQ] Received message #{message}" messages << message progress(1) end error_check(receiver.close) broker_thread.join return messages end def flush context = ZMQ::Context.new 1 requester = context.socket ZMQ::PUSH error_check(requester.connect('tcp://127.0.0.1:5555')) log_debug '[0MQ] Connected to broker' error_check(requester.send_string("FLUS")) log_debug '[0MQ] Sent' error_check(requester.close) progress(1) end private def error_check(rc) if ZMQ::Util.resultcode_ok?(rc) false else STDERR.puts "Operation failed, errno [#{ZMQ::Util.errno}] description [#{ZMQ::Util.error_string}]" caller(1).each { |callstack| STDERR.puts(callstack) } true end end end end end
class Api::CharactersController < ApplicationController def index @characters = User.find(params[:user_id]).characters render json: @characters end def show @character = Character.find(params[:id]) render json: @character end def create @user = User.find(params[:user_id]) @character = @user.characters.create(character_params) render json: @character end def update @character = Character.find(params[:id]) @character.update(character_params) render json: @character end def destroy @character = Character.find(params[:id]).destroy render status: :ok end private def character_params params.require(:character).permit(:name, :occupation, :head_element, :body_element, :leg_element, :color_scheme, :stories_completed, :points) end end
class ChangeLongLatActivities < ActiveRecord::Migration[6.0] def change change_column :activities, :longitude, :decimal change_column :activities, :latitude, :decimal end end