text
stringlengths
10
2.61M
ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) abort("The Rails environment is running in production mode!") if Rails.env.production? Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } require 'spec_helper' require 'rspec/rails' require 'capybara/poltergeist' Capybara.javascript_driver = :poltergeist Capybara.default_driver = :poltergeist ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| config.use_transactional_fixtures = false config.infer_spec_type_from_file_location! config.before(:suite) do $webpack_dev_server_pid = spawn( "./node_modules/.bin/webpack-dev-server " + "--config config/webpack.config.js --quiet") DatabaseCleaner.clean_with(:truncation) end config.before(:each) do DatabaseCleaner.strategy = :transaction end config.before(:each, :type => :feature) do DatabaseCleaner.strategy = :truncation end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end config.after(:suite) do puts "Killing webpack-dev-server" Process.kill("HUP",$webpack_dev_server_pid) begin Timeout.timeout(2) do Process.wait($webpack_dev_server_pid,0) end rescue => Timeout::Error Process.kill(9,$webpack_dev_server_pid) end end config.filter_rails_from_backtrace! end
require 'test_helper' class MedicamentOrdersControllerTest < ActionDispatch::IntegrationTest setup do @medicament_order = medicament_orders(:one) end test "should get index" do get medicament_orders_url assert_response :success end test "should get new" do get new_medicament_order_url assert_response :success end test "should create medicament_order" do assert_difference('MedicamentOrder.count') do post medicament_orders_url, params: { medicament_order: { designation: @medicament_order.designation, medicament_id: @medicament_order.medicament_id, notes: @medicament_order.notes, patient_id: @medicament_order.patient_id, quantity: @medicament_order.quantity, status: @medicament_order.status, structure_id: @medicament_order.structure_id, unity: @medicament_order.unity } } end assert_redirected_to medicament_order_url(MedicamentOrder.last) end test "should show medicament_order" do get medicament_order_url(@medicament_order) assert_response :success end test "should get edit" do get edit_medicament_order_url(@medicament_order) assert_response :success end test "should update medicament_order" do patch medicament_order_url(@medicament_order), params: { medicament_order: { designation: @medicament_order.designation, medicament_id: @medicament_order.medicament_id, notes: @medicament_order.notes, patient_id: @medicament_order.patient_id, quantity: @medicament_order.quantity, status: @medicament_order.status, structure_id: @medicament_order.structure_id, unity: @medicament_order.unity } } assert_redirected_to medicament_order_url(@medicament_order) end test "should destroy medicament_order" do assert_difference('MedicamentOrder.count', -1) do delete medicament_order_url(@medicament_order) end assert_redirected_to medicament_orders_url end end
class InputFilesController < ApplicationController before_action :set_input_file, only: [:update, :destroy, :download] before_action :set_project, only: [:index, :new, :edit, :create, :update, :destroy] before_action :set_project_download, only: [:download] before_action :check_company before_action :check_auth # GET /input_files # GET /input_files.json def index @input_files = @project.input_files end # GET /input_files/new def new @input_file = InputFile.new end # POST /input_files # POST /input_files.json def create @input_file = InputFile.new(input_file_params) respond_to do |format| if @input_file.save @input_file.update_attribute(:project_id, @project.id) # Send email notification to Admins and PM of the project ExampleMailer.new_input_file(@project).deliver format.html { redirect_to @project, notice: 'Client file was successfully created.' } format.json { render :show, status: :created, location: @input_file } else format.html { render :new } format.json { render json: @input_file.errors, status: :unprocessable_entity } end end end # DELETE /input_files/1 # DELETE /input_files/1.json def destroy @input_file.destroy respond_to do |format| format.html { redirect_to @project, notice: 'Client file was successfully destroyed.' } format.json { head :no_content } end end # Download the file def download path = "#{@input_file.file_path}" send_file path, :x_sendfile=>true end private # Use callbacks to share common setup or constraints between actions. def set_input_file @input_file = InputFile.find(params[:id]) end # Set the project of the file def set_project @project = Project.find(params[:project_id]) end # Set the project of the file to download def set_project_download @project = Project.find(@input_file.project_id) end # Check if the current user belongs to a company or if they are an administrator or a project manager. def check_company if current_user.company == nil && !current_user.manager? && !current_user.admin? redirect_to new_company_path, :alert => "You have to create or be invited by a company before access to the website." and return end end # Check if the current user has the right to manage the client files of the current project. def check_auth if @project.project_owner_id != current_user.id && !current_user.admin? && current_user.id != @project.project_manager_id && !(current_user.company == @project.project_owner.company && current_user.company_admin?) redirect_to projects_path, :alert => "Access denied." and return end end # Never trust parameters from the scary internet, only allow the white list through. def input_file_params params.require(:input_file).permit(:name, :file_path, :project_id) end end
module ValidationHelper # Creates a couple of useful constants and a validation rule for a text field. # # * SYM_MIN_LENGTH # * SYM_MAX_LENGTH # * SYM_VALIDATION_MESSAGE # # Params: # * sym - the symbol representing the text field # * min - minimum number of characters # * max - maximum number of characters # * char_set - the allowed characters for this field (anything that can be placed in a # regex character set brackets []) # * opts - a hash of options: # ** :message - provide your own message instead of using the generated message # ** :regex - provide your own regex instead of using the constructed regex def text_validator(sym, min, max, char_set, opts=nil) opts ||= {} message = opts[:message] || build_text_message(min, max, char_set) regex = opts[:regex] || begin regex = char_set.dup CHAR_SET_TRANSLATION.each do |key, value| regex.sub! key, value end /^([#{regex}]){#{min},#{max}}$/u end allow_nil = opts[:allow_nil] || false my_const_set sym, 'MIN_LENGTH', min my_const_set sym, 'MAX_LENGTH', max my_const_set sym, 'VALIDATION_MESSAGE', message validates_format_of sym, :with => regex, :message => message, :allow_nil => allow_nil end # Creates a couple of useful constants and a validation rule for an enum field. # # * SYM_ENUM_VALUES # * SYM_ENUM_DEFAULT # * SYM_VALIDATION_MESSAGE # * SYM_DB_OPTS - a hash of params to be used in a migration, includes :null => false, # :limit => values, :default => SYM_ENUM_DEFAULT # # Params: # * sym - the symbol representing the enum field # * values - an array of allowed values for the enumeration # * opts - a hash of options: # ** :default - can be used to set the default value...values[0] will be used if this # default is not specified # ** :message - provide your own message instead of using the generated message def enum_validator(sym, values, opts=nil) opts ||= {} default = (opts.key?(:default)) ? opts[:default] : values[0] message = opts[:message] || "should be one of #{values.join ', '}" allow_nil = opts[:allow_nil] || false my_const_set sym, 'ENUM_VALUES', values my_const_set sym, 'ENUM_DEFAULT', default my_const_set sym, 'VALIDATION_MESSAGE', message my_const_set sym, 'DB_OPTS', { :limit => values, :null => allow_nil, :default => default } validates_inclusion_of sym, :in => values, :message => message, :allow_nil => allow_nil end def belongs_to_validator(sym, opts=nil) opts ||= {} message = opts[:message] || "must be present and valid" foreign_key = opts[:foreign_key] || "#{sym.to_s}_id".to_sym associated_if = opts[:associated_if] || Proc.new { |x| false } my_const_set sym, "VALIDATION_MESSAGE", message validates_presence_of foreign_key, :message => "#{message} 1" validates_associated sym, :message => "#{message} 2", :if => associated_if define_method("validate_belongs_to_#{sym}") do eval <<-CODE if self.#{sym}.nil? && self.#{foreign_key}.to_i < 1 self.errors.add :#{sym}, "#{message} 3" end CODE end end private def my_const_set(sym, suffix, value) const_set "#{sym.to_s.upcase}_#{suffix}", value end CHAR_SET_LOOKUP = { 'alnum' => ['letters', 'numbers'], 'alpha' => 'letters', 'blank' => ['spaces', 'tabs'], 'digit' => 'numbers', 'graph' => ['letters', 'numbers', 'punctuation'], 'print' => ['letters', 'numbers', 'punctuation', 'spaces'], 'punct' => 'punctuation', 'space' => 'spaces' } CHAR_SET_TRANSLATION = { '[:alnum:]' => 'A-Za-z0-9', '[:alpha:]' => 'A-Za-z', '[:blank:]' => ' \t', '[:digit:]' => '0-9', '[:graph:]' => '\x21-\x7E', '[:print:]' => '\x20-\x7E', '[:punct:]' => '-!"#$%&\'()*+,./:;<=>?@\[\\\]_`{|}~', '[:space:]' => '\s' } def build_text_message(min, max, char_set) ar = [] while char_set =~ /^(\[:([[:alpha:]]+):\])/ if CHAR_SET_LOOKUP[$2] ar << CHAR_SET_LOOKUP[$2] else raise "unexpected char_set #{$2}" end char_set = char_set.sub /^\[:[[:alpha:]]+:\]/, '' end raise "extra characters in char_set #{char_set}" if char_set.length > 0 raise 'no character sets found!' if ar.empty? ar.flatten! ar.sort!.uniq! s = if ar.size == 1 ar[0] elsif ar.size == 2 ar.join ' and ' else s = ar[0..-2].join ', ' s += ', and ' s += ar[-1] end size_str = min == 0 ? "at most #{max}" : "between #{min} and #{max}" "should be #{size_str} characters in length and contain only #{s}." end end
module RailsAdmin module Extensions module PunditNested # This adapter is for the Pundit[https://github.com/elabs/pundit] authorization library. # You can create another adapter for different authorization behavior, just be certain it # responds to each of the public methods here. class AuthorizationAdapter attr_reader :parent_object, :association_name # See the +authorize_with+ config method for where the initialization happens. def initialize(controller) @controller = controller @controller.extend ControllerExtension @parent_object = @controller.parent_object @association_name = @controller.association_name end # This method is called in every controller action and should raise an exception # when the authorization fails. The first argument is the name of the controller # action as a symbol (:create, :bulk_delete, etc.). The second argument is the # AbstractModel instance that applies. The third argument is the actual model # instance if it is available. def authorize(action, abstract_model = nil, model_object = nil) record = model_object || abstract_model && abstract_model.model fail ::Pundit::NotAuthorizedError.new("not allowed to #{action} this #{record}") unless policy(record).send(action_for_pundit(action)) if action end # This method is called primarily from the view to determine whether the given user # has access to perform the action on a given model. It should return true when authorized. # This takes the same arguments as +authorize+. The difference is that this will # return a boolean whereas +authorize+ will raise an exception when not authorized. def authorized?(action, abstract_model = nil, model_object = nil) record = model_object || abstract_model && abstract_model.model policy(record).send(action_for_pundit(action)) if action end # This is called when needing to scope a database query. It is called within the list # and bulk_delete/destroy actions and should return a scope which limits the records # to those which the user can perform the given action on. def query(_action, abstract_model) begin p_scope = begin if parent_object.present? && association_name.present? @controller.policy_scope!(@controller.send(:pundit_user), parent_object.send(association_name)) else @controller.policy_scope!(@controller.send(:pundit_user), abstract_model.model.all) end end rescue ::Pundit::NotDefinedError p_scope = begin if parent_object.present? && association_name.present? parent_object.send(association_name) else abstract_model.model.all end end end p_scope end # This is called in the new/create actions to determine the initial attributes for new # records. It should return a hash of attributes which match what the user # is authorized to create. def attributes_for(action, abstract_model) record = abstract_model && abstract_model.model policy(record).try(:attributes_for, action) || {} end module ControllerExtension # Retrieves the policy scope for the given record. # # @see https://github.com/elabs/pundit#scopes # @param user [Object] the user that initiated the action # @param record [Object] the object we're retrieving the policy scope for # @return [Scope{#resolve}, nil] instance of scope class which can resolve to a scope def policy_scope(user, scope) policy_scope = ::Pundit::PolicyFinder.new(scope).scope policy_scope.new(user, scope, self).resolve if policy_scope end # Retrieves the policy scope for the given record. # # @see https://github.com/elabs/pundit#scopes # @param user [Object] the user that initiated the action # @param record [Object] the object we're retrieving the policy scope for # @raise [NotDefinedError] if the policy scope cannot be found # @return [Scope{#resolve}] instance of scope class which can resolve to a scope def policy_scope!(user, scope) ::Pundit::PolicyFinder.new(scope).scope!.new(user, scope, self).resolve end # Retrieves the policy for the given record. # # @see https://github.com/elabs/pundit#policies # @param user [Object] the user that initiated the action # @param record [Object] the object we're retrieving the policy for # @return [Object, nil] instance of policy class with query methods def policy(user, record) policy = ::Pundit::PolicyFinder.new(record).policy policy.new(user, record, self) if policy end # Retrieves the policy for the given record. # # @see https://github.com/elabs/pundit#policies # @param user [Object] the user that initiated the action # @param record [Object] the object we're retrieving the policy for # @raise [NotDefinedError] if the policy cannot be found # @return [Object] instance of policy class with query methods def policy!(user, record) ::Pundit::PolicyFinder.new(record).policy!.new(user, record, self) end end private def policy(record) @controller.policy!(@controller.send(:pundit_user), record) rescue ::Pundit::NotDefinedError ::ApplicationPolicy.new(@controller.send(:pundit_user), record, @controller) end def action_for_pundit(action) action[-1, 1] == '?' ? action : "#{action}?" end end end end end
module EricWeixin class AccessToken < ActiveRecord::Base belongs_to :public_account, :class_name => '::EricWeixin::PublicAccount', foreign_key: :public_account_id self.table_name = "weixin_access_tokens" #设定最初的腾讯微信服务器列表 $ip_list = {"no-ip" => true} # 获取 AccessToken 方法一。根据 APPID 查到微信公众号 PublicAccount.id ,然后 # 调用 ::EricWeixin::AccessToken.get_valid_access_token 获取 AccessToken 并作为返回值返回. # ===参数说明 # * app_id #微信公众号的 app_id # ===调用示例 # ::EricWeixin::AccessToken.get_valid_access_token_by_app_id app_id: 'wx51729870d9012531' def self.get_valid_access_token_by_app_id options pa = ::EricWeixin::PublicAccount.find_by_weixin_app_id options[:app_id] ::EricWeixin::AccessToken.get_valid_access_token public_account_id: pa.id end # 获取 AccessToken 方法二。根据微信公众号 PublicAccount.id 获取 AccessToken. # 若微信公众号未存在 AccessToken 或者 AccessToken 过期都立即获取新的并返回。 # ===参数说明 # * public_account_id #公众账号 ID # ===调用示例 # ::EricWeixin::AccessToken.get_valid_access_token public_account_id: 1 def self.get_valid_access_token options ::EricWeixin::AccessToken.transaction do access_token = ::EricWeixin::AccessToken.find_by_public_account_id options[:public_account_id] if access_token.blank? public_account = ::EricWeixin::PublicAccount.find_by_id options[:public_account_id] access_token = ::EricWeixin::AccessToken.new :access_token => get_new_token(options[:public_account_id]), :expired_at => Time.now.to_i + 2*60*60, :public_account_id => public_account.id access_token.save! end if Time.now.to_i > (access_token.expired_at.to_i - 30) access_token.access_token = get_new_token(options[:public_account_id]) access_token.expired_at = Time.now.to_i + 2*60*60 access_token.save! end access_token.reload access_token.access_token end end # 根据微信公众号从微信服务器获取最新的 AccessToken. # ===参数说明 # * public_account_id #公众账号 ID # ===调用示例 # ::EricWeixin::AccessToken.get_new_token '5e3b98ca0000959946657212739fd535' # https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=12&secret=23 def self.get_new_token public_account_id account = ::EricWeixin::PublicAccount.find_by_id public_account_id BusinessException.raise 'account 不存在' if account.blank? url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=#{account.weixin_app_id}&secret=#{account.weixin_secret_key}" response = RestClient.get url pp response JSON.parse(response)["access_token"] end end end
# Back in the good old days, you used to be able to write a darn near # uncrackable code by simply taking each letter of a message and incrementing it # by a fixed number, so "abc" by 2 would look like "cde", wrapping around back # to "a" when you pass "z". Write a function, `caesar_cipher(str, shift)` which # will take a message and an increment amount and outputs the encoded message. # Assume lowercase and no punctuation. Preserve spaces. # # To get an array of letters "a" to "z", you may use `("a".."z").to_a`. To find # the position of a letter in the array, you may use `Array#find_index`. def caesar_cipher(str, shift) alphabet = ('a'..'z').to_a (0...str.length).each do |i| if str[i] != " " og_char = str[i] prev_idx = alphabet.index(og_char) new_idx = (prev_idx + shift) % 26 new_char = alphabet[new_idx] str[i] = new_char else " " end end str end # Write a method, `digital_root(num)`. It should Sum the digits of a positive # integer. If it is greater than 10, sum the digits of the resulting number. # Keep repeating until there is only one digit in the result, called the # "digital root". **Do not use string conversion within your method.** # # You may wish to use a helper function, `digital_root_step(num)` which performs # one step of the process. # Example: # digital_root(4322) => digital_root(11) => (2) def digital_root(num) end # Jumble sort takes a string and an alphabet. It returns a copy of the string # with the letters re-ordered according to their positions in the alphabet. If # no alphabet is passed in, it defaults to normal alphabetical order (a-z). # Example: # jumble_sort("hello") => "ehllo" # jumble_sort("hello", ['o', 'l', 'h', 'e']) => 'ollhe' def jumble_sort(str, alphabet = nil) if alphabet == nil alphabet = ('a'..'z').to_a end end class Array # Write a method, `Array#two_sum`, that finds all pairs of positions where the # elements at those positions sum to zero. # NB: ordering matters. I want each of the pairs to be sorted smaller index # before bigger index. I want the array of pairs to be sorted # "dictionary-wise": # [0, 2] before [1, 2] (smaller first elements come first) # [0, 1] before [0, 2] (then smaller second elements come first) def two_sum arr = [] self.each_with_index do |el1, idx1| self.each_with_index do |el2, idx2| if idx2 > idx1 && el1 + el2 == 0 arr << [idx1, idx2] end end end arr end end class String # Returns an array of all the subwords of the string that appear in the # dictionary argument. The method does NOT return any duplicates. def real_words_in_string(dictionary) arr = [] arr2 = [] (0...self.length).each do |i| (1...self.length).each do |i2| arr << self[i..i2] end end arr.each do |word| arr2 << word if dictionary.include?(word) && !arr2.include?(word) end arr2 end end # Write a method that returns the factors of a number in ascending order. def factors(num) fact = [] (1..num).each do |i| fact << i if num % i == 0 end fact end
class Participation < ActiveRecord::Base # Remember to create a migration! has_many :responses belongs_to :survey belongs_to :taker, class_name: "User" end
require 'spec_helper' RSpec.describe Viberroo::Message do describe '#text' do subject { Viberroo::Message.plain(text_params) } it { is_expected.to include({ type: :text }) } end describe '#rich' do subject { Viberroo::Message.rich(rich_params) } it { is_expected.to include({ type: :rich_media }) } it { is_expected.to include({ min_api_version: 2 }) } end describe '#location' do subject { Viberroo::Message.location(location_params) } it { is_expected.to include({ type: :location }) } end describe '#picture' do subject { Viberroo::Message.picture(picture_params) } it { is_expected.to include({ type: :picture }) } end describe '#url' do subject { Viberroo::Message.video(video_params) } it { is_expected.to include({ type: :video }) } end describe '#video' do subject { Viberroo::Message.file(file_params) } it { is_expected.to include({ type: :file }) } end describe '#file' do subject { Viberroo::Message.contact(contact_params) } it { is_expected.to include({ type: :contact }) } end describe '#contact' do subject { Viberroo::Message.url(url_params) } it { is_expected.to include({ type: :url }) } end describe '#sticker' do subject { Viberroo::Message.sticker(sticker_params) } it { is_expected.to include({ type: :sticker }) } end end
require 'symbol' module Noel class BaseScope attr_reader :scope_name, :parent def initialize(scope_name, parent) @scope_name = scope_name @parent = parent @table = {} end def define(symbol) @table[symbol.name] = symbol end def resolve(symbol_name) if @table.has_key?(symbol_name) return @table[symbol_name] end if not @parent.nil? return @parent.resolve(symbol_name) end raise end def to_s result = "" @table.each {|key, value| result += key.to_s + ":" + value.to_s + "\n" } return result end end class GlobalScope < BaseScope def initialize() super("global", nil) define(Noel::BuiltinTypeSymbol.new("Any")) define(Noel::BuiltinTypeSymbol.new("Number")) define(Noel::BuiltinTypeSymbol.new("Integer")) define(Noel::BuiltinTypeSymbol.new("Fixnum")) define(Noel::BuiltinTypeSymbol.new("Bignum")) define(Noel::BuiltinTypeSymbol.new("Character")) define(Noel::BuiltinTypeSymbol.new("String")) define(Noel::BuiltinTypeSymbol.new("Regexp")) define(Noel::BuiltinTypeSymbol.new("Pair")) define(Noel::BuiltinTypeSymbol.new("List")) define(Noel::BuiltinTypeSymbol.new("Hash")) define(Noel::BuiltinTypeSymbol.new("Vector")) define(Noel::BuiltinTypeSymbol.new("Closure")) define(Noel::BuiltinTypeSymbol.new("Class")) define(Noel::BuiltinTypeSymbol.new("Method")) define(Noel::BuiltinTypeSymbol.new("Boolean")) define(Noel::BuiltinTypeSymbol.new("Nil")) define(Noel::BuiltinTypeSymbol.new("Sequence")) end end end
require 'enumerator_ex/generators' require 'enumerable_lz/enumerable_ex' require File.join( File.dirname(__FILE__) , 'generators') require File.join(File.dirname(__FILE__),'..','enumerator_ex') module Enumerable extend EnumeratorEx::Generators #Intersperse several enumerator/enumerables, until all are #exhausted. Returns an Enumerator # # enum = EnumeratorEx.weave([1,2,3],%w[a b], %w[g h i j] # enum.to_a = [1, 'a', 'g',2,'b','h',3,'i','j'] def weave(*enums) enums[0,0] = self.to_enum result = EnumeratorEx.weave(*enums) end # append enumerator/enumerables to the end. returns an Enumerator # # enum = EnumeratorEx.cat([1,2,3],%w[a b], %w[g h i j]) # enum.to_a = [1,2,3,'a','b','g','h','i','j'] def cat(*enums) enums[0,0] = self.to_enum result = EnumeratorEx.cat(*enums) end # partition but in a lazy way def partition_lz(&block) e1 = self.to_enum e2 = self.to_enum e1_enum = e1.filter{|item| block.call(item)} e2_enum = e2.filter{|item| ! block.call(item)} [e1_enum,e2_enum] end def tee(n) enums = [] n.times do enums << Enumerator.new(self) end yield *enums end end class Enumerator extend EnumeratorEx::Generators # include EnumerableEx::InstanceMethods end
class WifiPage attr_accessor :driver def initialize(driver) @driver = driver end def wifitextisdisplayed @driver.find_element(:uiautomator, 'new UiSelector().className("android.widget.TextView").text("WiFi")').displayed? end def tickwificheckbox @driver.find_element(:id, 'android:id/checkbox') end def tapwifisettingbutton b = @driver.find_element(:uiautomator, 'new UiSelector().className("android.widget.TextView").text("WiFi settings")') tap_action = Appium::TouchAction.new.tap(element: b) tap_action.perform end def enterwifiname(wifiname) @driver.find_element(:id, 'android:id/edit').send_keys(wifiname) end def clickokbutton @driver.find_element(:id, 'android:id/button1') end def clickchildcheckbox scroll_action = Appium::TouchAction.new.swipe(start_x:0.5,start_y:0.8,end_x:0.5,end_y:0.2,duration:1000) scroll_action.perform array_of_elements = find_elements(id:'android:id/checkbox') actual_child_button=array_of_elements[2] actual_child_button.click end end
class AdminsController < ApplicationController before_action :get_admin, only: [:show, :edit, :update, :destroy, :admin_profile] before_action :authorized_to_see_page_admin skip_before_action :authorized_to_see_page_admin, only: [:login, :handle_login, :new, :create] def login @error = flash[:error] end def profile @contracts = Contract.all @request_jobs = RequestJob.all @request_services = RequestService.all @clients = Client.all @aides = Aide.all render :admin_profile end def handle_login @admin = Admin.find_by(first_name: params[:first_name]) if @admin && @admin.authenticate(params[:password]) session[:admin_id] = @admin.id redirect_to admin_profile_path else flash[:error] = "Incorrect username or password" redirect_to login_path end end def logout session[:admin_id] = nil redirect_to login_path end def show @admin = Admin.find(params[:id]) end def new @admin = flash[:errors] @admin = Admin.new end def create @admin = Admin.create(admin_params) if @admin.valid? session[:admin_id] = @admin.id redirect_to admin_profile_path else flash[:errors] = @admin.errors.full_messages redirect_to new_admin_path end end private def get_admin @admin = Admin.find(params[:id]) end def admin_params params.require(:admin).permit(:first_name, :last_name, :email, :password) end end
require 'docman/commands/command' module Docman module Builders class Builder < Docman::Command @@builders = {} @@build_results = {} def self.create(params = nil, context = nil, caller = nil) c = @@builders[params['handler']] if c c.new(params, context, caller, 'builder') else raise "Bad builder type: #{type}" end end def self.register_builder(name) @@builders[name] = self end def config super @version = nil add_action('before_execute', {'type' => :clean_changed}, @context) end def validate_command raise "Please provide 'context'" if @context.nil? raise "Context should be of type 'Info'" unless @context.is_a? Docman::Info end def version @version end before_execute do if @context.need_rebuild? @context.build_mode = :rebuild else if @context.changed? or changed? @context.build_mode = :update log("Changed") else log("Not changed") @context.build_mode = :none raise NoChangesError, 'This version already deployed' end end end after_execute do if @execute_result @execute_result = @context.write_info(@execute_result) end end def changed? false end def describe "Build: #{properties_info}" end def prefix "#{@context['name']} - #{self.class.name}" end end end end
require 'validation' class Striuct class << self alias_method :new_instance, :new private :new_instance # @group Constructors for Subclassies # @param [Symbol, String] autonyms # @yieldreturn [Class] # @return [Class] def new(*autonyms, &block) # warning for Ruby's Struct.new user first = autonyms.first if first.instance_of?(String) and /\A[A-Z]/ =~ first warn "no define constant first-arg(#{first}), the Struct behavior is not supported in Striuct" end Class.new(self) { autonyms.each do |autonym| add_member autonym end class_eval(&block) if block_given? } end # @yieldreturn [Class] (see Striuct.new) - reject floating class # @return [void] def define(&block) raise ArgumentError, 'block not supplied' unless block_given? new(&block).tap {|subclass| subclass.class_eval { raise 'not yet finished' if @autonyms.empty? close } } end # @groupend private def inherited(subclass) ret = super subclass subclass.class_eval { extend ClassMethods include Enumerable include Validation include InstanceMethods _init } ret end end end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe AccountsController do ActionController::Integration::Session describe "on create affiliate account post" do describe "with required parameters" do def required_params {:email => Faker::Internet.email} end def post_info post :aff_create, @params.merge({:user => required_params}) end fixtures :subscriptions, :subscription_plans before(:each) do @params = {:plan => 'Free'} end it "should create an account with just an email address" do lambda { post_info }.should change(User, :count).by(1) end it "should assign a special placeholder password" do post_info assigns[:user].should be_using_coreg_password end it "should assign a placeholder name only if none sent" do post_info assigns[:account].user.first_name.should == 'New' post :aff_create, @params.merge({:user => required_params.merge({:first_name => 'douchenick'})}) assigns[:account].user.first_name.should == 'douchenick' end it "should save gender in profile" do post :aff_create, @params.merge({:user => required_params.merge({:profile => {:gender => 'male'}})}) assigns[:account].user.profile.gender.should == 'male' end it "should save birthdate in profile" do post :aff_create, @params.merge({:user => required_params.merge({:profile => { 'birthday(1i)' => '1900', 'birthday(2i)' => '1', 'birthday(3i)' => '23' }})}) assigns[:account].user.profile.birthday.year.should == 1900 end describe "with address" do before(:each) do Region.stubs(:find_by_name).returns(stub(:id => 1, :country => stub(:id => 2))) Country.stubs(:find_by_alpha_2_code).returns(stub(:id => 111)) end it "should save correct region id from valid state param" do post :aff_create, @params.merge({:user => required_params}.merge({:address_book => { :address_attributes => {:postal_code => "123", :street_1 => 'fun town', :city => 'shooberg', :state => 'oregon'} }})) assigns[:account].user.address_book.addresses.should have(1).thing end it "should save correct country from valid country param" do post :aff_create, @params.merge({:user => required_params}.merge({:address_book => { :address_attributes => {:postal_code => "123", :street_1 => 'fun town', :city => 'shooberg', :country_code => "US"} }})) assigns[:account].user.address_book.addresses.should have(1).thing end it "should save correct address without street address param" do post :aff_create, @params.merge({:user => required_params}.merge({:address_book => { :address_attributes => {:postal_code => "123", :city => 'shooberg', :country_code => "US"} }})) assigns[:account].user.address_book.addresses.first.city.should == 'shooberg' end it "should save correct address with country code and country id" do post :aff_create, @params.merge({:user => required_params}.merge({:address_book => { :address_attributes => {:postal_code => "123", :city => 'shooberg', :country_code => "US", :country_id => 840} }})) assigns[:account].user.address_book.addresses.first.should be_valid end it "should save correct address with country code and country id and region id" do post :aff_create, @params.merge({:user => required_params}.merge({:address_book => { :address_attributes => {:postal_code => "123", :city => 'shooberg', :country_id => 840, :region_id => 4163} }})) assigns[:account].user.address_book.addresses.first.should be_valid assigns[:account].user.address_book.addresses.first.region_id.should == 4163 end it "should allow full address" do post :aff_create, @params.merge({:user => required_params.merge({ :profile => { 'birthday(1i)' => "1979", 'birthday(2i)' => "01", 'birthday(3i)' => "01", :gender => "female" }, :first_name => 'test', :last_name => 'best' })}.merge({ :address_book => { :address_attributes => { :city => "Kent", :country_code => "US", :postal_code => "11111", :state => "Washington" } }})) assigns[:account].user.address_book.addresses.should have(1).thing end it "should save cellphone in address_book" do post :aff_create, @params.merge({:user => required_params.merge({ :profile => {'birthday(1i)' => "1979", 'birthday(2i)' => "01", 'birthday(3i)' => "01", :gender => "female", :cellphone => '123-3322'}, :first_name => 'test', :last_name => 'best' })}) assigns[:account].user.address_book.phone_numbers.should have(1).thing end end it "should receive an activation email with a link to the password entry page" do post_info # Don't know why we have to double uri-escape the email address, but that's how it # shows up in these test emails... activation_link = Regexp.new(/\/activate\/\w+/) choose_pwd_link = Regexp.new(/\/choose_password$/) links = links_in_email(open_last_email_for(assigns[:user].email)) links.select { |link| activation_link.match link }.should be_empty links.select { |link| choose_pwd_link.match link }.should_not be_empty end # it "should allow user to login with generated password" do # post_info # user = assigns[:user] # pwd = user.generated_password # UserSession.create(:login => user.login, :password => pwd).should be_true # end end end end
Drinkster::Application.routes.draw do root to: 'main#index' scope 'api' do resources :users, only: [:create, :show] do resources :ingredients, only: [:create, :destroy, :index] resources :drinks, only: [:index] end resource :session, only: [:create, :destroy] end match '*path', to: 'main#index', via: :get end
class Types::FormSectionType < Types::BaseObject field :id, Int, null: false field :title, String, null: true field :form, Types::FormType, null: false, camelize: false field :position, Int, null: true field :form_items, [Types::FormItemType], null: false, camelize: false association_loaders FormSection, :form, :form_items authorize_record end
class ArticleTag < ActiveRecord::Base belongs_to :tag, counter_cache: true belongs_to :article # validates :article, :tag, presence: true delegate :name, to: :tag end
class AddSkillsheetToUsers < ActiveRecord::Migration[5.0] def change add_column :users, :skillsheet, :binary add_column :users, :skillsheet_name, :string, default: '未登録' end end
FUNCTIONS = { '+' => Proc.new { |args| args.reduce(&:+)}, '*' => Proc.new { |args| args.reduce(&:*)}, 'if' => Proc.new { |args| args[0] ? args[1] : args[2] }, 'def' => Proc.new { |args| VALUES[args[0]] = args[1] }, 'progn' => Proc.new { |args| args.last }, 'let' => Proc.new { |args| # ["(x 3)(y 4)", "x"] old_values = {} args[0][1..-2].split.each_slice 2 do |name, val| old_values[name] = VALUES[name] VALUES[name] = lisp_eval val end expression = args[1] #'x' result = lisp_eval expression old_values.each do |name, val| VALUES[name] = val end result }, 'defun' => Proc.new { |args| fn_name = args[0] arglist = args[1][1..-2].split body = args[2] FUNCTIONS[fn_name] = Proc.new { |inner_args| old_values = {} inner_args.each_with_index do |argval, i| name = arglist[i] old_values[name] = VALUES[name] VALUES[name] = argval end result = lisp_eval body old_values.each do |name, val| VALUES[name] = val end result } } } VALUES = {} def lisp_eval raw_expression raw_expression = raw_expression.strip.gsub(/\s+/, ' ') if integer? raw_expression raw_expression.to_i elsif boolean? raw_expression parse_boolean raw_expression elsif VALUES.include? raw_expression VALUES[raw_expression] elsif symbol? raw_expression raw_expression else primitive_matcher = '([^()]*)' first_complex_form_matcher= '(\(.*?\))?' rest_matcher= '(.*)' token_extractor = Regexp.new(primitive_matcher + first_complex_form_matcher + rest_matcher) expr = raw_expression if raw_expression.start_with? '(' expr = raw_expression[1..-1] end if raw_expression.end_with? ')' expr = expr[0..-2] end match = expr.match token_extractor primitives = match[1].split first_complex_form = match[2] rest = match[3] function_name = primitives.shift function = FUNCTIONS[function_name] unless rest =~ /\(.*\)/ rest = rest.strip.split end raw_arglist = (primitives + [first_complex_form] + [rest]).compact.flatten if special_form? function_name arguments = raw_arglist else arguments = raw_arglist.map { |e| lisp_eval e } end result = function.call(arguments) result end end def integer? expr expr =~ /^\d+$/ end def special_form? name %w(let defun).include? name end def symbol? expr expr =~ /^[\-_a-zA-Z0-9!@#\$%\^&*`~]+/ end def boolean? expr expr == "#t" or expr == "#f" end def parse_boolean expr if expr == "#t" true elsif expr == "#f" false else raise Exception end end
FactoryBot.define do factory :message_tag do title {Faker::Lorem.sentence} message {Faker::Lorem.sentence} whom {Faker::Name.name} open_plan {Faker::Date.between(from: 1.day.from_now, to: 100.years.from_now).strftime('%Y-%m-%d')} name {Faker::Lorem.sentence} end end
class Product < ActiveRecord::Base if Rails.env.production? has_attached_file :picture, :styles => { :medium => "300x400", :thumb => "150x250" }, :storage => :s3, :s3_credentials => "#{Rails.root}/config/s3.yml", :path => ":attachment/:id/:style.:extension", :bucket => 'product_pics' else has_attached_file :picture, :styles => { :medium => "300x400#", :thumb => "150x250#" }, :path => ":rails_root/public/system/:attachment/:id/:style/:basename.:extension" end validates_presence_of :name, :price validates_numericality_of :price validates_format_of :size, :with => /(?:^|,)(\\\"(?:[^\\\"]+|\\\"\\\")*\\\"|[^,]*)/ end
require_relative './spec_helper' require_relative '../helpers/language_helper' describe GitHubLanguage do include LanguageHelper context 'when a username has been provided' do it 'receives a response containing langauge data from the GitHub API', :vcr do user = "hamchapman" uri = "https://api.github.com/users/#{user}/repos" response = get_response_from uri expect(response.code).to eq "200" expect(response.body).to include '"language":"Ruby"' end it 'receives an error when an invalid username is provided', :vcr do user = "hamchapman777" uri = "https://api.github.com/users/#{user}/repos" response = get_response_from(uri) expect(response.code).to eq "404" expect(response.message).to eq "Not Found" end it 'can create an array of a user\'s used languages', :vcr do user = "hamchapman" uri = "https://api.github.com/users/#{user}/repos" user_repos = get_repos uri expect(get_array_of_languages user_repos ).to include("CSS", "JavaScript", "Objective-C", "Ruby", "Shell") end it 'can find a user\'s favourite language based on the number of times it occurs as a dominant language in a repo' do languages = ["Ruby", "Ruby", "JavaScript", "Shell", "CSS", "Ruby", "JavaScript"] expect(calculate_favourite languages).to eq "Ruby" end it 'can find a user\'s favourite languages if two (or more) are equally frequently occurring' do languages = ["Ruby", "Ruby", "JavaScript", "Shell", "JavaScript"] expect(calculate_favourite languages).to eq "Ruby, JavaScript" end it 'can calculate a user\'s favourite language(s) given a username', :vcr do user = "hamchapman" expect(get_favourite_language_of user).to eq "Ruby" end it 'returns an error message if the user has no repositories', :vcr do expect(get_favourite_language_of "charles1").to eq "not able to be calculated" end end end
require 'spec_helper' class MockController attr_accessor :request, :user def initialize(request, user) @request, @user = request, user end end class MockNoUserController attr_accessor :request def initialize(request) @request = request end end describe Arcane do let(:user) { double(name: :user) } let(:parameters) { nil_model_params } let(:controller) { double(request: request, current_user: user).tap { |c| c.extend(Arcane) } } let(:request) { double(parameters: parameters) } describe '#params' do it 'sets the user for parameters' do controller.params.user.should eq user end end describe '#params=' do context 'sets the user for' do it 'hash parameters' do controller.params = { foo: :bar } controller.instance_variable_get(:@_params).user.should eq user end it 'ActionController::Parameters parameters' do controller.params = ActionController::Parameters.new({ foo: :bar }) controller.instance_variable_get(:@_params).user.should eq user end end it 'handles nil' do controller.params = nil controller.instance_variable_get(:@_params).should be_nil end end describe "#current_params_user" do context "when there is no current user" do let(:controller) { MockNoUserController.new(request).tap { |c| c.extend(Arcane) } } it "should raise a no method error" do expect { controller.current_params_user }.to raise_exception NameError end end end end
class AdminUser < ApplicationRecord has_secure_password has_and_belongs_to_many :pages has_many :section_edits has_many :sections, :through => :section_edits EMAIL_REGEX = /\A[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}\Z/i FORBIDDEN_USERNAMES = ['littlebopeep', 'humptydumpty', 'marymary'] # "sexy" validations validates :first_name, :presence => true, :length => {:maximum=> 25} validates :last_name, :presence => true, :length => {:maximum=> 50} validates :username, :length => {:within => 8..25} , :uniqueness => true validates :email, :presence => true, :length => {:maximum => 100 }, :format => EMAIL_REGEX, :confirmation => true validate :username_is_allowed validate :no_new_users_on_monday, :on => :create # named scopes scope :sorted, lambda { order("last_name ASC, first_name ASC") } def name "#{first_name} #{last_name}" end private def username_is_allowed if FORBIDDEN_USERNAMES.include?(username) errors.add(:username, "has been restricted from use.") end end def no_new_users_on_monday if Time.now.wday == 1 errors.add(:base, "No new users on Mondays.") end end end
module Ign class Search attr_accessor :query def initialize(query) self.query = query.strip end def game same_name = games.select{|game| game.name.downcase == query.downcase} if same_name.count == 0 games.first elsif same_name.count == 1 same_name.first else same_name.select{|game| game.rating}.first || same_name.first end end def games @games ||= noko.css('div.product-result').collect{|result| Ign::Game.new(result)} end def noko @noko ||= Nokogiri::HTML(body) end def body @body ||= Net::HTTP.get_response(URI.parse("http://search.ign.com/product?" + {:query => query}.to_query)).body end end end
#!/usr/bin/env ruby # frozen_string_literal: true require 'sinatra' require 'fileutils' get '/:name/:md5/index' do result = '[' seperator = '' dir = File.join('public', params[:name], params[:md5]) halt 400, 'File not found' unless File.directory?(dir) Dir.glob(File.join(dir, '*.dep')) do |x| result += seperator seperator = ",\n" result += File.read(x) end result += ']' result end put '/:name/:md5/:file' do file = File.join('public', params[:name], params[:md5], params[:file]) FileUtils.mkdir_p(File.dirname(file)) File.open(file, 'w') do |f| f.write(request.body.read) end end
class Deck < ApplicationRecord belongs_to :hashtag has_many :card end
class Download < ApplicationRecord belongs_to :user belongs_to :movie validates :user_id, :movie_id, presence: :true end
require "net/ftp" module Podflow module Uploader def self.perform(path, opts) remote_size = 0 local_size = File.size(path) STDOUT.sync = true STDOUT.print "#{path} uploading to #{opts['host']}:#{opts['path']} - this may take a while... " Net::FTP.open(opts["host"]) do |ftp| ftp.login opts["user"], opts["pass"] ftp.chdir opts["path"] ftp.putbinaryfile path remote_size = ftp.list(File.basename(path)).last.split(" ")[4].to_i end STDOUT.puts "done\n Local size: #{local_size}\n Remote size: #{remote_size}" return (remote_size == local_size) end end end
class User < ApplicationRecord enum role: [:user, :vip, :admin] after_initialize :set_default_role, :if => :new_record? devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :galleries, dependent: :destroy has_many :images, dependent: :destroy has_many :categories, dependent: :destroy validates :name, presence: true accepts_nested_attributes_for :images, :galleries, :categories, allow_destroy: true def set_default_role self.role ||= :user end def generate_auth_token token = SecureRandom.hex self.update_columns(auth_token: token) token end def invalidate_auth_token self.update_columns(auth_token: nil) end end
class Comment include Mongoid::Document field :name field :email field :text field :approved, type: Boolean, default: false end
class UsersController < ApplicationController def show @videos = Video.all @transactions = current_user.transactions @user = User.find(params[:id]) authorize @user end end
class HappeningsForDisciplinesDatatable < BaseDatatable def columns { 'happenings.id': { hide: true }, 'happenings.name': {}, 'happenings.start_date': {}, 'venues.name': { title: Venue.model_name.human }, 'clubs.name': { title: Club.model_name.human }, 'clubs.id': { hide: true }, } end def disciplines Discipline.where id: @view.params[:discipline_ids] end def similar_disciplines disciplines .map(&:similar_disciplines) .flatten .uniq .reject { |discipline| disciplines.include? discipline } end def consists_of_and_used_in_disciplines ( disciplines .map(&:consists_of_disciplines) .flatten .uniq .to_a + disciplines .map(&:used_in_disciplines) .flatten .uniq .to_a ) .reject { |discipline| disciplines.include? discipline } end def all_items all = Happening.left_outer_joins(discipline_happenings: :discipline) all = all.where(discipline_happenings: { discipline: disciplines }) if disciplines.present? all = all.joins(:club, :venue) all = all.order(:start_date) all.distinct end def rows(filtered) filtered.map do |happening| link_to_club = if happening.club.sport_organization? @view.link_to(happening.club.name, @view.club_path(happening.club)) else happening.club.name end [ happening.id, @view.link_to(happening.name, @view.happening_path(happening)), I18n.l(happening.start_date, format: :long_with_week), happening.venue.name, link_to_club, happening.club.id, ] end end end
module Sortable extend ActiveSupport::Concern module ClassMethods def sort_columns_for(model, default_column, default_direction=nil) return if method_defined? "sort_column" or method_defined? "sort_direction" define_method "sort_column" do model.column_names.include?(params[:sort]) ? params[:sort] : default_column end define_method "sort_direction" do default_direction ||= "asc" %w[asc desc].include?(params[:direction]) ? params[:direction] : default_direction end private "sort_column" private "sort_direction" self.send(:helper_method, :sort_column, :sort_direction) end end end
# Copyright (c) 2015 - 2020 Ana-Cristina Turlea <turleaana@gmail.com> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. require 'omniauth-oauth2' module OmniAuth module Strategies class Autentificare < OmniAuth::Strategies::OAuth2 CUSTOM_PROVIDER_URL = '' option :client_options, { :site => CUSTOM_PROVIDER_URL, :authorize_url => "#{CUSTOM_PROVIDER_URL}/auth/autentificare/authorize", :access_token_url => "#{CUSTOM_PROVIDER_URL}/auth/autentificare/access_token" } uid { raw_info['id'] } info do { :email => raw_info['email'] } end extra do { :first_name => raw_info['extra']['first_name'], :last_name => raw_info['extra']['last_name'], :email => raw_info['extra']['email'], :student => raw_info['extra']['student'], :teacher => raw_info['extra']['teacher'], :management => raw_info['extra']['management'], :admin => raw_info['extra']['admin'] } end def raw_info @raw_info ||= access_token.get("/auth/autentificare/user.json?oauth_token=#{access_token.token}").parsed end end end end
class Carnival attr_reader :name, :rides, :attendees def initialize(name) @name = name @rides = [] @attendees = [] end def add_ride(ride) @rides << ride end def recommend_rides(attendee) @rides.find_all do |ride| attendee.interests.any? do |interest| ride.name == interest end end end def admit(attendee) @attendees << attendee end def attendees_by_ride_interest ride_interest = {} require "pry"; binding.pry @rides.each do |ride| ride_interest[ride] = @attendees end ride_interest end end
require 'test_helper' class ContactsControllerTest < ActionDispatch::IntegrationTest def setup @admin = users(:admin) @standard_user = users(:standard) @contact = contacts(:bill) end test 'users should be able to visit contact pages' do # Admin user log_in_as @admin get contacts_path assert_response :success get edit_contact_path @contact assert_response :success get new_contact_path assert_response :success # Standard User log_in_as @standard_user get contacts_path assert_response :success get edit_contact_path @contact assert_response :success get new_contact_path assert_response :success end test 'users should be able to create contacts' do log_in_as @standard_user assert_difference 'Contact.count', 1 do post contacts_path params: { contact: { name: 'Contact Name', email: 'example@email.com' } } end end test 'standard users should not be able to destroy users' do log_in_as @standard_user assert_no_difference 'User.count' do delete user_path @admin end end test 'admin users should be able to destroy users' do log_in_as @admin assert_difference 'User.count', -1 do delete user_path @standard_user end end end
class Ability include CanCan::Ability def initialize(user) user ||= User.new alias_action :index, :sign_in, :sign_out, :to => :nav can :nav, User can :show, User, :id => user.id if user.admin? can :manage, Post can :manage, User elsif user.vip? can :read, :update, Post end end end
load "waveguide.rb" class Eam_Lump include MyBasic include RBA attr_accessor :mesa_width_in, :mesa_width_hybrid, :mqw_width_in,:mqw_width_hybrid, :nInP_width, :nInP_length, :taper1, :taper2, :nmetal_gap, :lay_mesa, :lay_mqw, :lay_nInP, :lay_nmetal, :lay_pvia, :lay_nvia, :lay_probe, :dbu def initialize(mesa_width_in = 1.4, mesa_width_hybrid = 3.0, mqw_width_in = 1.8, mqw_width_hybrid = 4.0, nInP_width = 50.0, nInP_length = 300.0, taper1 = 90.0, taper2 = 15.0, wg_length = 100.0, nmetal_gap = 8.0, lay_mesa = CellView::active.layout.layer(1, 1), lay_mqw = CellView::active.layout.layer(3, 1), lay_nInP = CellView::active.layout.layer(4, 1), lay_nmetal = CellView::active.layout.layer(5, 1), lay_pvia = CellView::active.layout.layer(8, 1), lay_nvia = CellView::active.layout.layer(7, 1), lay_probe = CellView::active.layout.layer(9, 1), dbu = CellView::active.layout.dbu) @dbu = dbu @mesa_width_in = mesa_width_in/@dbu @mesa_width_hybrid = mesa_width_hybrid/@dbu @mqw_width_in = mqw_width_in/@dbu @mqw_width_hybrid = mqw_width_hybrid/@dbu @nInP_width = nInP_width/@dbu if wg_length+(taper1+taper2)*2.0>nInP_length nInP_length = wg_length+(taper1+taper2)*2.0+60.0 end @nInP_length = nInP_length/@dbu @taper1 = taper1/@dbu @taper2 = taper2/@dbu @wg_length = wg_length/@dbu @nmetal_gap = nmetal_gap/@dbu @lay_mesa = lay_mesa @lay_mqw = lay_mqw @lay_nInP = lay_nInP @lay_nmetal = lay_nmetal @lay_pvia = lay_pvia @lay_nvia = lay_nvia @lay_probe = lay_probe @nprobe_w = (@nInP_width - @nmetal_gap - 6.0/@dbu)/2.0 @nproble_l = 20.0/@dbu @ports = [] end def wg_length(wg_length) @wg_length = wg_length if @wg_length+(@taper1+@taper2)*2.0>@nInP_length @nInP_length = @wg_length+(@taper1+@taper2)*2.0-50.0/@dbu else @nInP_length = 300.0/@dbu end @nprobe_w = (@nInP_width - @nmetal_gap - 6.0/@dbu)/2.0 end def shapes(cell) @ports = [] @ports.push(Ports::new(width = @mesa_width_hybrid, direction = Math::PI, face_angle = direction+Math::PI/2.0, point = DPoint::new(0.0,0.0))) shape = cell.shapes(@lay_mesa) mesa(shape) shape = cell.shapes(@lay_mqw) mqw(shape) shape = cell.shapes(@lay_nInP) nInP(shape) shape = cell.shapes(@lay_nmetal) nmetal(shape) shape = cell.shapes(@lay_pvia) pvia(shape) shape = cell.shapes(@lay_nvia) nvia(shape) shape = cell.shapes(@lay_probe) probe(shape) end def mesa(shape) pts = [DPoint::new(0.0,0.0),DPoint::new(@wg_length,0.0)] wg = Waveguide::new(pts,@mesa_width_hybrid) shape.insert(wg.poly) pts = [DPoint::new(-@taper2,0.0),DPoint::new(0.0,0.0)] taper = Taper::new(pts,@mesa_width_in,@mesa_width_hybrid) shape.insert(taper.poly) t1 = Trans::new(DTrans::M90) t2 = Trans::new(@wg_length,0.0) shape.insert(taper.poly.transformed(t1).transformed(t2)) exten_length = 18.0/@dbu pts = [DPoint::new(-@taper2-exten_length,0.0),DPoint::new(-@taper2,0.0)] wg = Waveguide::new(pts,@mesa_width_in) shape.insert(wg.poly) t1 = Trans::new(DTrans::M90) t2 = Trans::new(@wg_length,0.0) shape.insert(wg.poly.transformed(t1).transformed(t2)) end def mqw(shape) pts = [DPoint::new(-@taper2,0.0),DPoint::new(@wg_length+@taper2,0.0)] wg = Waveguide::new(pts,@mqw_width_hybrid) shape.insert(wg.poly) pts = [DPoint::new(-@taper1-@taper2,0.0),DPoint::new(-@taper2,0.0)] taper = Taper::new(pts,@mqw_width_in,@mqw_width_hybrid) shape.insert(taper.poly) t1 = Trans::new(DTrans::M90) t2 = Trans::new(@wg_length,0.0) shape.insert(taper.poly.transformed(t1).transformed(t2)) tip = Circle.new(DPoint::new(-@taper1-@taper2,0.0), @mqw_width_in/2.0,90.0,270) shape.insert(tip.poly) shape.insert(tip.poly.transformed(t1).transformed(t2)) tmpw = [@mqw_width_hybrid,@mqw_width_hybrid-1.5/@dbu,(@mqw_width_hybrid-1.5/@dbu)/2.0] (1..3).each do |iter| pts = [DPoint::new(0.0,-@nInP_width/2.0-10.0*iter/@dbu),DPoint::new(@wg_length,-@nInP_width/2.0-10.0*iter/@dbu)] wg = Waveguide::new(pts,tmpw[iter-1]) shape.insert(wg.poly) end end def nInP(shape) offset = 0.0/@dbu pts = [DPoint::new(-@taper2-@taper1-offset,0.0),DPoint::new(@wg_length+@taper2+@taper1+offset,0.0)] wg = Waveguide::new(pts,@nInP_width) shape.insert(wg.poly) pts = [DPoint::new(@wg_length/2.0-@nInP_length/2.0,@nInP_width/2.0-@nprobe_w/2.0), DPoint::new(@wg_length/2.0+@nInP_length/2.0,@nInP_width/2.0-@nprobe_w/2.0)] wg = Waveguide::new(pts,@nprobe_w) shape.insert(wg.poly) t1 = Trans::new(0.0,-@nInP_width+@nprobe_w) shape.insert(wg.poly.transformed(t1)) end def nmetal(shape) offset= 3.0/@dbu pts = [DPoint::new(0.0,-@nmetal_gap/2.0-offset/2.0),DPoint::new(@wg_length,-@nmetal_gap/2.0-offset/2.0)] wg = Waveguide::new(pts,offset) shape.insert(wg.poly) t1 = Trans::new(Trans::M0) shape.insert(wg.poly.transformed(t1)) pts = [DPoint::new(@wg_length/2.0-@nInP_length/2.0,-@nInP_width/2.0+@nprobe_w/2.0), DPoint::new(@wg_length/2.0+@nInP_length/2.0,-@nInP_width/2.0+@nprobe_w/2.0)] wg = Waveguide::new(pts,@nprobe_w) shape.insert(wg.poly) t1 = Trans::new(Trans::M0) shape.insert(wg.poly.transformed(t1)) end def pvia(shape) offset = 1.0/@dbu pts = [DPoint::new(0.0,0.0),DPoint::new(@wg_length,0.0)] wg = Waveguide::new(pts,@mesa_width_hybrid-offset) shape.insert(wg.poly) t1 = Trans::new(Trans::M0) shape.insert(wg.poly.transformed(t1)) offset = 1.0/@dbu pts = [DPoint::new(@wg_length/2.0-@nInP_length/2.0+offset,-@nInP_width/2.0+@nprobe_w/2.0), DPoint::new(@wg_length/2.0-@nInP_length/2.0+@nproble_l+offset,-@nInP_width/2.0+@nprobe_w/2.0)] wg = Waveguide::new(pts,@nprobe_w) shape.insert(wg.poly) t1 = Trans::new(Trans::M0) shape.insert(wg.poly.transformed(t1)) pts = [DPoint::new(@wg_length/2.0+@nInP_length/2.0-@nproble_l-offset,-@nInP_width/2.0+@nprobe_w/2.0), DPoint::new(@wg_length/2.0+@nInP_length/2.0-offset,-@nInP_width/2.0+@nprobe_w/2.0)] wg = Waveguide::new(pts,@nprobe_w) shape.insert(wg.poly) t1 = Trans::new(Trans::M0) shape.insert(wg.poly.transformed(t1)) end def nvia(shape) offset = 1.0/@dbu smaller = 1.0/@dbu pts = [DPoint::new(@wg_length/2.0-@nInP_length/2.0+offset+smaller,-@nInP_width/2.0+@nprobe_w/2.0), DPoint::new(@wg_length/2.0-@nInP_length/2.0+@nproble_l+offset-smaller,-@nInP_width/2.0+@nprobe_w/2.0)] wg = Waveguide::new(pts,@nprobe_w-2.0*smaller) shape.insert(wg.poly) t1 = Trans::new(Trans::M0) shape.insert(wg.poly.transformed(t1)) pts = [DPoint::new(@wg_length/2.0+@nInP_length/2.0-@nproble_l-offset+smaller,-@nInP_width/2.0+@nprobe_w/2.0), DPoint::new(@wg_length/2.0+@nInP_length/2.0-offset-smaller,-@nInP_width/2.0+@nprobe_w/2.0)] wg = Waveguide::new(pts,@nprobe_w-2.0*smaller) shape.insert(wg.poly) t1 = Trans::new(Trans::M0) shape.insert(wg.poly.transformed(t1)) end def probe(shape) pprobe_width = 10.0/@dbu pts = [DPoint::new(0.0,0.0), DPoint::new(@wg_length,0.0)] wg = Waveguide::new(pts,pprobe_width) shape.insert(wg.poly) proble_w1 = 10.0/@dbu proble_w2 = 90.0/@dbu pts = [DPoint::new(@wg_length/2.0,pprobe_width/2.0), DPoint::new(@wg_length/2.0,@nInP_width/2.0)] wg = Waveguide::new(pts,proble_w1) shape.insert(wg.poly) taperL = 30.0/@dbu pts = [DPoint::new(@wg_length/2.0,@nInP_width/2.0), DPoint::new(@wg_length/2.0,@nInP_width/2.0+taperL)] taper = Taper::new(pts,proble_w1,proble_w2) shape.insert(taper.poly) probe_L = 80.0/@dbu pts = [DPoint::new(@wg_length/2.0,@nInP_width/2.0+taperL), DPoint::new(@wg_length/2.0,@nInP_width/2.0+taperL+probe_L)] wg = Waveguide::new(pts,proble_w2) shape.insert(wg.poly) gap = 10.0/@dbu pts = [DPoint::new(@wg_length/2.0-proble_w2/2.0-gap,@nInP_width/2.0+taperL+probe_L), DPoint::new(@wg_length/2.0-@nInP_length/2.0,@nInP_width/2.0+taperL+probe_L), DPoint::new(@wg_length/2.0-@nInP_length/2.0,-@nInP_width/2.0), DPoint::new(@wg_length/2.0-@nInP_length/2.0+@nproble_l+2.0/@dbu,-@nInP_width/2.0), DPoint::new(@wg_length/2.0-@nInP_length/2.0+@nproble_l+2.0/@dbu,@nInP_width/2.0), DPoint::new(@wg_length/2.0-proble_w2/2.0-gap,@nInP_width/2.0+taperL)] poly = Polygon::from_dpoly(DPolygon::new(pts)) shape.insert(poly) t1 = Trans::new(DTrans::M90) t2 = Trans::new(@wg_length,0.0) shape.insert(poly.transformed(t1).transformed(t2)) end def ports return @ports end end class Eam_TW include MyBasic include RBA attr_accessor :mesa_width_in, :mesa_width_hybrid, :mqw_width_in,:mqw_width_hybrid, :nInP_width, :nInP_length, :taper1, :taper2, :wg_length, :nmetal_gap, :cpw_radius, :cpw_gap, :cpw_width, :lay_mesa, :lay_mqw, :lay_nInP, :lay_nmetal, :lay_pvia, :lay_nvia, :lay_probe, :dbu def initialize(mesa_width_in = 1.4, mesa_width_hybrid = 3.0, mqw_width_in = 1.8, mqw_width_hybrid = 4.0, nInP_width = 50.0, nInP_length = 300.0, taper1 = 90.0, taper2 = 15.0, wg_length = 800.0, nmetal_gap = 8.0, cpw_gap = 15.0, cpw_radius = 50.0, cpw_width = 8.0, lay_mesa = CellView::active.layout.layer(1, 0), lay_mqw = CellView::active.layout.layer(3, 0), lay_nInP = CellView::active.layout.layer(4, 0), lay_nmetal = CellView::active.layout.layer(5, 0), lay_pvia = CellView::active.layout.layer(8, 0), lay_nvia = CellView::active.layout.layer(7, 0), lay_probe = CellView::active.layout.layer(9, 0), dbu = CellView::active.layout.dbu ) @dbu = dbu @mesa_width_in = mesa_width_in/@dbu @mesa_width_hybrid = mesa_width_hybrid/@dbu @mqw_width_in = mqw_width_in/@dbu @mqw_width_hybrid = mqw_width_hybrid/@dbu @nInP_width = nInP_width/@dbu if wg_length+(taper1+taper2)*2.0>nInP_length nInP_length = wg_length+(taper1+taper2)*2.0+60.0 end @nInP_length = nInP_length/@dbu @taper1 = taper1/@dbu @taper2 = taper2/@dbu @wg_length = wg_length/@dbu @nmetal_gap = nmetal_gap/@dbu @lay_mesa = lay_mesa @lay_mqw = lay_mqw @lay_nInP = lay_nInP @lay_nmetal = lay_nmetal @lay_pvia = lay_pvia @lay_nvia = lay_nvia @lay_probe = lay_probe @nprobe_w = (@nInP_width - @nmetal_gap - 6.0/@dbu)/2.0 @nproble_l = 20.0/@dbu @cpw_radius = cpw_radius/@dbu @cpw_gap = cpw_gap/@dbu @cpw_width = cpw_width/@dbu @ports = [] end def shapes(cell) @ports = [] @ports.push(Ports::new(width = @mesa_width_hybrid, direction = Math::PI, face_angle = direction+Math::PI/2.0, point = DPoint::new(0.0,0.0))) shape = cell.shapes(@lay_mesa) mesa(shape) shape = cell.shapes(@lay_mqw) mqw(shape) shape = cell.shapes(@lay_nInP) nInP(shape) shape = cell.shapes(@lay_nmetal) nmetal(shape) shape = cell.shapes(@lay_pvia) pvia(shape) shape = cell.shapes(@lay_nvia) nvia(shape) shape = cell.shapes(@lay_probe) probe(shape) end def mesa(shape) pts = [DPoint::new(0.0,0.0),DPoint::new(@wg_length,0.0)] wg = Waveguide::new(pts,@mesa_width_hybrid) shape.insert(wg.poly) pts = [DPoint::new(-@taper2,0.0),DPoint::new(0.0,0.0)] taper = Taper::new(pts,@mesa_width_in,@mesa_width_hybrid) shape.insert(taper.poly) t1 = Trans::new(DTrans::M90) t2 = Trans::new(@wg_length,0.0) shape.insert(taper.poly.transformed(t1).transformed(t2)) exten_length = 18.0/@dbu pts = [DPoint::new(-@taper2-exten_length,0.0),DPoint::new(-@taper2,0.0)] wg = Waveguide::new(pts,@mesa_width_in) shape.insert(wg.poly) t1 = Trans::new(DTrans::M90) t2 = Trans::new(@wg_length,0.0) shape.insert(wg.poly.transformed(t1).transformed(t2)) end def mqw(shape) pts = [DPoint::new(-@taper2,0.0),DPoint::new(@wg_length+@taper2,0.0)] wg = Waveguide::new(pts,@mqw_width_hybrid) shape.insert(wg.poly) pts = [DPoint::new(-@taper1-@taper2,0.0),DPoint::new(-@taper2,0.0)] taper = Taper::new(pts,@mqw_width_in,@mqw_width_hybrid) shape.insert(taper.poly) t1 = Trans::new(DTrans::M90) t2 = Trans::new(@wg_length,0.0) shape.insert(taper.poly.transformed(t1).transformed(t2)) tip = Circle.new(DPoint::new(-@taper1-@taper2,0.0), @mqw_width_in/2.0,90.0,270) shape.insert(tip.poly) shape.insert(tip.poly.transformed(t1).transformed(t2)) tmpw = [@mqw_width_hybrid,@mqw_width_hybrid-1.5/@dbu,(@mqw_width_hybrid-1.5/@dbu)/2.0] (1..3).each do |iter| pts = [DPoint::new(0.0,-@nInP_width/2.0-10.0*iter/@dbu),DPoint::new(@wg_length,-@nInP_width/2.0-10.0*iter/@dbu)] wg = Waveguide::new(pts,tmpw[iter-1]) shape.insert(wg.poly) end end def nInP(shape) offset = 20.0/@dbu pts = [DPoint::new(-@taper2-@taper1-offset,0.0),DPoint::new(@wg_length+@taper2+@taper1+offset,0.0)] wg = Waveguide::new(pts,@nInP_width) shape.insert(wg.poly) pts = [DPoint::new(@wg_length/2.0-@nInP_length/2.0,@nInP_width/2.0-@nprobe_w/2.0), DPoint::new(@wg_length/2.0+@nInP_length/2.0,@nInP_width/2.0-@nprobe_w/2.0)] wg = Waveguide::new(pts,@nprobe_w) shape.insert(wg.poly) t1 = Trans::new(0.0,-@nInP_width+@nprobe_w) shape.insert(wg.poly.transformed(t1)) end def nmetal(shape) offset= 3.0/@dbu pts = [DPoint::new(0.0,-@nmetal_gap/2.0-offset/2.0),DPoint::new(@wg_length,-@nmetal_gap/2.0-offset/2.0)] wg = Waveguide::new(pts,offset) shape.insert(wg.poly) t1 = Trans::new(Trans::M0) shape.insert(wg.poly.transformed(t1)) pts = [DPoint::new(@wg_length/2.0-@nInP_length/2.0,-@nInP_width/2.0+@nprobe_w/2.0), DPoint::new(@wg_length/2.0+@nInP_length/2.0,-@nInP_width/2.0+@nprobe_w/2.0)] wg = Waveguide::new(pts,@nprobe_w) shape.insert(wg.poly) t1 = Trans::new(Trans::M0) shape.insert(wg.poly.transformed(t1)) end def pvia(shape) offset = 1.0/@dbu pts = [DPoint::new(0.0,0.0),DPoint::new(@wg_length,0.0)] wg = Waveguide::new(pts,@mesa_width_hybrid-offset) shape.insert(wg.poly) t1 = Trans::new(Trans::M0) shape.insert(wg.poly.transformed(t1)) offset = 1.0/@dbu pts = [DPoint::new(@wg_length/2.0-@nInP_length/2.0+offset,-@nInP_width/2.0+@nprobe_w/2.0), DPoint::new(@wg_length/2.0-@nInP_length/2.0+@nproble_l+offset,-@nInP_width/2.0+@nprobe_w/2.0)] wg = Waveguide::new(pts,@nprobe_w) shape.insert(wg.poly) t1 = Trans::new(Trans::M0) shape.insert(wg.poly.transformed(t1)) pts = [DPoint::new(@wg_length/2.0+@nInP_length/2.0-@nproble_l-offset,-@nInP_width/2.0+@nprobe_w/2.0), DPoint::new(@wg_length/2.0+@nInP_length/2.0-offset,-@nInP_width/2.0+@nprobe_w/2.0)] wg = Waveguide::new(pts,@nprobe_w) shape.insert(wg.poly) t1 = Trans::new(Trans::M0) shape.insert(wg.poly.transformed(t1)) end def nvia(shape) offset = 1.0/@dbu smaller = 1.0/@dbu pts = [DPoint::new(@wg_length/2.0-@nInP_length/2.0+offset+smaller,-@nInP_width/2.0+@nprobe_w/2.0), DPoint::new(@wg_length/2.0-@nInP_length/2.0+@nproble_l+offset-smaller,-@nInP_width/2.0+@nprobe_w/2.0)] wg = Waveguide::new(pts,@nprobe_w-2.0*smaller) shape.insert(wg.poly) t1 = Trans::new(Trans::M0) shape.insert(wg.poly.transformed(t1)) pts = [DPoint::new(@wg_length/2.0+@nInP_length/2.0-@nproble_l-offset+smaller,-@nInP_width/2.0+@nprobe_w/2.0), DPoint::new(@wg_length/2.0+@nInP_length/2.0-offset-smaller,-@nInP_width/2.0+@nprobe_w/2.0)] wg = Waveguide::new(pts,@nprobe_w-2.0*smaller) shape.insert(wg.poly) t1 = Trans::new(Trans::M0) shape.insert(wg.poly.transformed(t1)) end def probe(shape) poly1 = [] poly2 = [] t1 = Trans::new(DTrans::M90) t2 = Trans::new(@wg_length,0.0) t3 = Trans::new(DTrans::M0) pts = [DPoint::new(-@cpw_radius,@cpw_radius), DPoint::new(-@cpw_radius,0.0), DPoint::new(@wg_length+@cpw_radius,0.0), DPoint::new(@wg_length+@cpw_radius,-@cpw_radius)] pts = round_corners(pts,@cpw_radius,2.0) wg = Waveguide::new(pts,@cpw_width,0,0) poly1.push(wg.poly) wg = Waveguide::new(pts,@cpw_width+@cpw_gap*2.0,0,0) poly2.push(wg.poly) taperL = 30.0/@dbu proble_w = 90.0/@dbu pts = [DPoint::new(-@cpw_radius,@cpw_radius), DPoint::new(-@cpw_radius,@cpw_radius+taperL)] taper = Taper::new(pts,@cpw_width,proble_w) poly = taper.poly poly1.push(poly) poly1.push(poly.transformed(t1).transformed(t2).transformed(t3)) taper = Taper::new(pts,@cpw_width+@cpw_gap*2.0,proble_w+@cpw_gap*2.0) poly = taper.poly poly2.push(poly) poly2.push(poly.transformed(t1).transformed(t2).transformed(t3)) probe_L = 80.0/@dbu pts = [DPoint::new(-@cpw_radius,@cpw_radius+taperL), DPoint::new(-@cpw_radius,@cpw_radius+taperL+probe_L)] wg = Waveguide::new(pts,proble_w) poly = wg.poly poly1.push(poly) poly1.push(poly.transformed(t1).transformed(t2).transformed(t3)) wg = Waveguide::new(pts,proble_w+@cpw_gap*2.0) poly = wg.poly poly2.push(poly) poly2.push(poly.transformed(t1).transformed(t2).transformed(t3)) nprobe_w = 90.0/@dbu pts = [DPoint::new(-@cpw_radius-proble_w/2.0-@cpw_gap-nprobe_w,@cpw_radius+taperL+probe_L), DPoint::new(-@cpw_radius-proble_w/2.0-@cpw_gap-nprobe_w,-(@cpw_radius+taperL+probe_L)), DPoint::new(@wg_length+@cpw_radius+proble_w/2.0+@cpw_gap+nprobe_w,-(@cpw_radius+taperL+probe_L)), DPoint::new(@wg_length+@cpw_radius+proble_w/2.0+@cpw_gap+nprobe_w,(@cpw_radius+taperL+probe_L))] poly = Polygon::from_dpoly(DPolygon::new(pts)) rpoly = poly.round_corners(0.0/@dbu,5.0/@dbu,128) ep = RBA::EdgeProcessor::new() out = ep.boolean_p2p(poly2,[rpoly],RBA::EdgeProcessor::ModeBNotA,false, false) out.each {|p| shape.insert(p)} poly1.each {|p| shape.insert(p)} end def ports return @ports end end if __FILE__ == $0 include MyBasic include RBA # create a new view (mode 1) with an empty layout main_window =Application::instance.main_window layout = main_window.create_layout(1).layout layout_view = main_window.current_view # set the database unit (shown as an example, the default is 0.001) dbu = 0.001 layout.dbu = dbu # create a cell cell = layout.create_cell("EAM_LUMP") wg35 = Eam_Lump.new() wg35.shapes(cell) layout_view.select_cell(cell.cell_index, 0) layout_view.add_missing_layers layout_view.zoom_fit end
class RequestMailer < ApplicationMailer # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.request_mailer.email_confirmation.subject # def email_confirmation(request) @request = request mail(to: @request.email, subject: 'Welcome to our Coworking place') end def renew_expiring_date(request) @request = request mail(to: @request.email, subject: 'Coworking: are you still interested ?') end end
class AddColumnPinyinToProducts < ActiveRecord::Migration def change add_column :products, :pinyin, :string end end
Given /^I have the following transactions$/ do |transaction_table| transaction_table.hashes.each do |hash| hash['transaction_datetime'] = eval(hash['transaction_datetime']) FactoryGirl.create(:transaction, hash.merge(user: @user)) end end Then /^I should see all transactions within (.*?)$/ do |type| case type when "today" then all("table//tr").length.should == 3 when "7 days" then all("table//tr").length.should == 5 else all("table//tr").length.should == 7 end end Then /^I should see the transaction is (.*?)$/ do |status| if status == 'pending' find(:xpath , "//td[@class='transaction-actions']").text.should include('Approve') find(:xpath , "//td[@class='transaction-actions']").text.should include('Reject') find(:xpath , "//td[@class='transaction-actions']").text.should include('Hold') else find(:xpath , "//td[@class='transaction-actions']").text.should include(status.capitalize) end end Then /^I should see the reviewer is "(.*?)"$/ do |email| find(:xpath, "//td[@class='reviewer']").text.should == email end When /^I change the amount threshold to '(\d+)'$/ do |value| fill_in 'user_setting_amount_threshold', with: value end Then /^I should see that the transactions are sorted by "(.*?)" in "(.*?)" order$/ do |value, order| transactions = Transaction.order("#{value} #{order}") index = 2 transactions.each do |transaction| find(:xpath , "//table//tr[#{index}]/td[1]").text.should == "#{transaction.id}" index += 2 end end Then /^I should see all transactions with amount above or equal '(.*?)'$/ do |amount_threshold| all("table//tr").length.should == 5 end Then /^I should see note form$/ do find(:xpath , "//textarea[@id='note_content']").should be_visible end Then /^I should not see note form$/ do find(:xpath , "//textarea[@id='note_content']").should_not be_visible end
module Dictionary def self.included(base) base.extend ClassMethods end module ClassMethods #builds a set of constants like: KEY = 'KEY' #as well as a method self.dict that returns all of those constants' values def build_dictionary *keys keys.each do |key| const_set key.to_s.upcase, key.to_s.upcase end define_singleton_method("dict") { keys.map{|k| k.to_s.upcase } } end end end
class TeamSerializer < ActiveModel::Serializer attributes :id, :name, :player1, :player2 end
class SurnameFieldForOwnerhistories < ActiveRecord::Migration[5.0] def change change_column :flats, :phone, :string add_column :ownerhistories, :surname, :string end end
class CreateFlights < ActiveRecord::Migration[5.2] def change create_table :flights do |t| t.string :departure_city t.string :arrival_city t.string :departure_date t.integer :departure_time_1 t.integer :departure_time_2 t.integer :departure_time_3 t.integer :departure_time_4 t.integer :departure_time_3 t.integer :departure_time_4 t.integer :departure_time_5 t.integer :departure_time_6 t.integer :departure_time_7 t.integer :departure_time_8 t.timestamps end end end
module Boxzooka class ProductListResponse < BaseResponse collection :results, entry_node_name: 'Item', entry_field_type: :entity, entry_type: Boxzooka::Item end end
require 'rubygems' require 'rubygems/package' require 'open3' require 'tempfile' # Exception for this class class Gem::OpenPGPException < RuntimeError; end # A wrapper that shells out the real OpenPGP crypto work # to gpg. module Gem::OpenPGP # Given a string of data, generate and return a detached # signature. By defualt, this will use your primary secret key. # This can be overridden by specifying a key_id for another # private key. def self.detach_sign data, key_id=nil, homedir=nil is_gpg_available is_key_valid key_id if key_id is_homedir_valid homedir if homedir key_flag = "" key_flag = "-u #{key_id}" if key_id homedir_flag = "" homedir_flag = "--homedir #{homedir}" if homedir cmd = "gpg #{key_flag} #{homedir_flag} --detach-sign --armor" sig, err = run_gpg_command cmd, data sig end # Given a string containing data, and a string containing # a detached signature, verify the data. If we can't verify # then raise an exception. # # Optionally tell gpg to retrive the key if it's not provided def self.verify data, sig, get_key=false, homedir=nil is_gpg_available is_homedir_valid homedir if homedir data_file = create_tempfile data sig_file = create_tempfile sig get_key_params = "--keyserver pool.sks-keyservers.net --keyserver-options auto-key-retrieve" get_key_params = "" if get_key != true homedir_flags = "" homedir_flags = "--homedir #{homedir}" if homedir cmd = "gpg #{get_key_params} #{homedir_flags} --verify #{sig_file.path} #{data_file.path}" res, err = run_gpg_command cmd [err, res] end # Signs an existing gemfile by iterating the tar'ed up contents, # and signing any contents. creating a new file with original contents # and OpenPGP sigs. The OpenPGP sigs are saved as .asc files so they # won't conflict with X509 sigs. # # Optional param "key" allows you to use a different private # key than the GPG default. def self.sign_gem gem, key=nil, homedir=nil output = [] unsigned_gem = gem + ".unsigned" begin FileUtils.mv gem, unsigned_gem rescue Errno::ENOENT => ex raise Gem::CommandLineError, "The gem #{gem} does not seem to exist. (#{ex.message})" end unsigned_gem_file = File.open(unsigned_gem, "r") signed_gem_file = File.open(gem, "w") signed_gem = Gem::Package::TarWriter.new(signed_gem_file) Gem::Package::TarReader.new(unsigned_gem_file).each do |f| output << f.full_name.inspect if f.full_name[-4..-1] == ".asc" output << "Skipping old signature file #{f.full_name}" next end output << "Signing #{f.full_name.inspect}..." file_contents = f.read() signed_gem.add_file(f.full_name, 0644) do |outfile| outfile.write(file_contents) end signed_gem.add_file(f.full_name + ".asc", 0644) do |outfile| outfile.write(Gem::OpenPGP.detach_sign(file_contents,key,homedir)) end end signed_gem_file.close unsigned_gem_file.close File.delete unsigned_gem_file output rescue Exception => ex if unsigned_gem_file FileUtils.mv unsigned_gem_file, gem end raise end def self.verify_gem gem, get_key=false, homedir=nil output =[] begin file = File.open(gem,"r") rescue Errno::ENOENT => ex raise Gem::CommandLineError, "Gem #{gem} not found. Note you can only verify local gems at this time, so you may need to run 'gem fetch #{gem}' before verifying." end tar_files = {} Gem::Package::TarReader.new(file).each do |f| tar_files[f.full_name] = f.read() end tar_files.keys.each do |file_name| next if file_name[-4..-1] == ".asc" output << "Verifying #{file_name}..." sig_file_name = file_name + ".asc" if !tar_files.has_key? sig_file_name output << "WARNING!!! No sig found for #{file_name}" next end begin err, res = Gem::OpenPGP.verify(tar_files[file_name], tar_files[sig_file_name], get_key, homedir) output << add_color(err, :green) output << add_color(res, :green) rescue Gem::OpenPGPException => ex color_code = "31" output << add_color(ex.message, :red) end end file.close output end private # Tests to see if gpg is installed and available. def self.is_gpg_available err_msg = "Unable to find a working gnupg installation. Make sure gnupg is installed and you can call 'gpg --version' from a command prompt." `gpg --version` raise Gem::OpenPGPException, err_msg if $? != 0 rescue Errno::ENOENT => ex raise Gem::OpenPGPException, err_msg if $? != 0 end def self.is_key_valid key_id valid = /^0x[A-Za-z0-9]{8,8}/.match(key_id) if valid.nil? err_msg = "Invalid key id. Keys should be in form of 0xDEADBEEF" raise Gem::OpenPGPException, err_msg end end def self.is_homedir_valid homedir if !File.exists? homedir raise OpenPGPException, "Bad homedir #{homedir.inspect}" end end def self.run_gpg_command cmd, data=nil exit_status = nil stdout, stderr = Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thr| stdin.write data if data stdin.close exit_status = wait_thr.value out = stdout.read() err = stderr.read() raise Gem::OpenPGPException, "#{err}" if exit_status != 0 [out,err] end [stdout, stderr] end def self.create_tempfile data temp_file = Tempfile.new("rubygems_gpg") temp_file.binmode temp_file.write(data) temp_file.close temp_file end def self.add_color s, color=:green color_code = case color when :green then "32" when :red then "31" else raise RuntimeError, "Invalid color #{color.inspect}" end #TODO - NO-OP on windows "\033[#{color_code}m#{s}\033[0m" end end
module MiW class TableView class DataCache DEFAULT_PAGE_SIZE = 4096 def initialize(query, page_size = DEFAULT_PAGE_SIZE) @query = query @pages = {} @page_size = page_size end attr_reader :dataset def reset @pages = {} end def count @query.count end def each(offset = 0) if block_given? page_offset = offset % @page_size page_index = offset / @page_size loop do page = (@pages[page_index] ||= @query.get(page_index * @page_size, @page_size)) break if page.empty? while page_offset < page.length yield page[page_offset] page_offset += 1 end page_offset = 0 page_index += 1 end else enum_for :each, offset end end end end end
class AddRelationshipsBetweenModels < ActiveRecord::Migration def change add_column :tasks, :list_id, :integer, :null => false, :default => "0" add_column :tasks, :user_id, :integer, :null => false, :default => "0" add_column :lists, :user_id, :integer, :null => false, :default => "0" end end
@songs.each do |song| json.partial! "api/songs/song", song: song end
# encoding: UTF-8 module OmniSearch # Builds a named index # ---------------------------------- # index_class - like DoctorIndex # index_type - like PlainText # # it stores DoctorIndex.records, # formatted the way thay PlainText needs them # # # Usage: # ================================================================ # instance = Indexes::Builder.new(SomethingIndex, Indexes::Plaintext) # instance.save # class Indexes::Builder # index_class holds an one of the user configurable classes. # see Indexes::Register, for how an index_class is specified attr_accessor :index_class # index_type holds the index generator # while a plaintext index is straightforward, a trigram index # requires the index class to do some work attr_accessor :index_type def initialize(index_class, index_type) @index_class = index_class @index_type = index_type end # save the constructed records to the storage engine def save storage.save(records) end # deletes the stored records def delete storage.delete end private def name index_class.index_name end def index @index ||= index_class.new end def collection index.all end # formats the collection using the index_type's build rules def records index_type.build(collection) end # creates an instance of the storage engine def storage @storage ||= index_type.storage_engine.new(name) end end end
class JobsController < ApplicationController before_action :set_job, only: %i[ show edit update destroy ] # GET /companies or /companies.json def index @jobs = Job.all end # GET /companies/1 or /companies/1.json def show @job = Job.find(params[:id]) @company = Company.find(@job.company_id) end # GET /companies/new def new @job = Job.new end # GET /companies/1/edit def edit end # POST /companies or /companies.json def create @job = Job.new(job_params) respond_to do |format| if @job.save format.html { redirect_to '/admin/'+@job.company.id.to_s , notice: "Job was successfully created." } format.json { render :show, status: :created, location: @job } else format.html { render :new, status: :unprocessable_entity } format.json { render json: @job.errors, status: :unprocessable_entity } end end end # PATCH/PUT /companies/1 or /companies/1.json def update respond_to do |format| if @job.update(job_params) format.html { redirect_to @job, notice: "Job was successfully updated." } format.json { render :show, status: :ok, location: @job } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @job.errors, status: :unprocessable_entity } end end end # DELETE /companies/1 or /companies/1.json def destroy @job.destroy respond_to do |format| format.html { redirect_to jobs_url, notice: "Job was successfully destroyed." } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_job @job = Job.find(params[:id]) end # Only allow a list of trusted parameters through. def job_params params.require(:job).permit(:content, :wage, :require, :status, :company_id,:benefits, :name) end end
require 'rails_helper' describe DevsController, type: :request do let!(:devs) { create_list(:dev, 10) } context 'index route' do let(:result) { JSON.parse(response.body) } before { get '/devs' } it 'request index and return 200 OK' do expect(response.code).to eq('200') expect(response).to have_http_status(:ok) end it 'displays all devs data' do expect(Dev.all.count).to eq(10) expect(result.count).to eq(10) expect(result.first["username"]).to eq(Dev.first.username) end end end
# == Schema Information # # Table name: engineers # # id :bigint not null, primary key # name :string not null # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' RSpec.describe Engineer, type: :model do describe 'associations' do it { should have_and_belong_to_many(:projects) } end describe 'validations' do it { should validate_presence_of(:name) } end describe "#pairing" do let(:project) { FactoryBot.create(:project, :with_sprints, :with_engineers, sprint_count: 3, engineer_count: 4) } let(:engineers) { project.engineers } let(:engineer) { engineers.first! } let(:sprint1_partner) { engineers.second! } let(:sprint2_partner) { engineers.third! } let(:sprint1) { project.sprints.first! } let(:sprint2) { project.sprints.second! } let(:sprint3) { project.sprints.third! } before do FactoryBot.create(:pairing, pair: Pair.new(engineer, sprint1_partner), sprint: sprint1) FactoryBot.create(:pairing, pair: Pair.new(engineer, sprint2_partner), sprint: sprint2) end it "returns nil if no pairing exists for the engineer for the given sprint" do expect(engineer.pairing(sprint: sprint3)).to be_nil end it "returns the correct pairing for the given sprint" do expect(engineer.pairing(sprint: sprint1).members).to contain_exactly(engineer, sprint1_partner) expect(engineer.pairing(sprint: sprint2).members).to contain_exactly(engineer, sprint2_partner) end end describe "#pairings" do let(:engineers) { FactoryBot.create_list(:engineer, 4) } let(:project1) { FactoryBot.create(:project, :with_sprints, :with_engineers, members: engineers, sprint_count: 3) } let(:project2) { FactoryBot.create(:project, :with_sprints, :with_engineers, members: engineers, sprint_count: 3, start_date: project1.end_date + 2.days) } let(:engineer) { engineers[0] } let(:proj1_sprint1_partner) { engineers[1] } let(:proj1_sprint2_partner) { engineers[2] } let(:proj2_sprint1_partner) { engineers[3] } let(:proj2_sprint2_partner) { engineers[2] } let!(:pairing1_proj1) { FactoryBot.create(:pairing, pair: Pair.new(engineer, proj1_sprint1_partner), sprint: project1.sprints.first!) } let!(:pairing2_proj1) { FactoryBot.create(:pairing, pair: Pair.new(engineer, proj1_sprint2_partner), sprint: project1.sprints.second!) } let!(:pairing3_proj2) { FactoryBot.create(:pairing, pair: Pair.new(engineer, proj2_sprint1_partner), sprint: project2.sprints.first!) } let!(:pairing4_proj2) { FactoryBot.create(:pairing, pair: Pair.new(engineer, proj2_sprint2_partner), sprint: project2.sprints.second!) } # a pairing that doesn't include the subject engineer let!(:other_pairing) { FactoryBot.create(:pairing, pair: Pair.new(proj2_sprint1_partner, proj1_sprint1_partner), sprint: project2.sprints.second!) } context "unscoped" do it "returns all of an engineer's pairings across all projects" do expect(engineer.pairings).to contain_exactly( pairing1_proj1, pairing2_proj1, pairing3_proj2, pairing4_proj2 ) end end context "scoped to a specific project" do it "returns all of an engineer's pairings for a specific project" do expect(engineer.pairings(project: project2)).to contain_exactly( pairing3_proj2, pairing4_proj2 ) end end end end
class CharacterSerializer < BaseSerializer attributes :id, :name, :level, :achievement_points, :created_at, :updated_at has_one :clazz, key: :class has_one :race has_one :realm has_one :faction end
unless defined? Thread fail "Thread not available for this ruby interpreter" end
class HasAndBelongsToManyIssuesUser < ActiveRecord::Migration def change create_table :got_fixed_issues_users do |t| t.belongs_to :user t.belongs_to :issue end end end
@string = "hello world" describe 'string methods' do context 'chop' do it 'returns a new string with the last char removed (also has a permanent version)' do end end context 'clear' do it '(pointlessly given reassignment?) removes all chars in the string' do expect("hello".clear).to be_empty end end context 'count' do it 'returns the number of chars in all of the strings passed as arguments that also exist within the original string' do expect("captain horatio hornblower".count("pti", "toi")).to eq 4 end end context 'each_char' do it 'runs a block for each character but returns the original string unchanged' do string = "hello world" expect(string.each_char {|char| char.upcase!}).to eq "hello world" end end context 'empty?' do it 'returns true if the string has no characters, else false' do expect("a".empty?).to be_false end end context 'each_line' do it 'separates lines at the argument given, runs a block on them, then returns the original string' do whatever = "" expect("hello world".each_line("o") {|line| whatever.upcase }).to eq "hello world" end end context 'delete' do it 'deletes all the characters common to all the arguments from the original string' do expect("captain hornblower".delete("pac", "hcb")).to eq "aptain hornblower" end end context 'gsub' do it 'finds the first string-argument in the original string and replaces it with the second argument. It also has a permanent vers' do expect("captain hornblower".gsub!("o", "SUP")).to eq "captain hSUPrnblSUPwer" end it 'alternatively looks for the first argument as a key in a hash and replaces it in the original string with the relevant key' do expect("captain hornblower".gsub!("captain", {"captain"=> "Aubrey"})).to eq "Aubrey hornblower" end end context 'include?' do it 'does what it says on the tin' do expect("hello world".include?("hello")).to be_true end end context 'index' do it 'returns the index of the first character of the first substring matching that in the argument' do expect("captain horatio hornblower".index("hor")).to eq 8 end end context 'insert' do it 'adds the string in argument1 to the index in argument2' do expect("helloworld".insert(5, " ")).to eq "hello world" end end context 'length' do it 'unlike arr.length differs from .count, since here it just returns the number of chars in the string' do expect('hello'.length).to eq 5 end end context 'lines' do it "much like .split, but doesn't omit the char(s?) given as an argument - keeps them in the line before the break" do expect("hello world".lines(" ")).to eq ["hello ", "world"] end end context 'ljust' do it "indents from the right by (the number of spaces in argument1 - the number of chars in the original string), filling the gap with the chars in argument2" do expect("hello world".ljust(3, "!!")).to eq "hello world" end end context 'lstrip!' do it 'deletes all spaces at the beginning of the string - has a permanent version' do expect(" hello".lstrip!).to eq "hello" end end context 'next!' do it 'increments the the string, starting with the rightmost character, cycling round character sets - has a perm version' do expect("ZZ".next).to eq "AAA" end end context 'partition' do it 'splits a string by the argument, and returns three arrays - the left of the argument, the argument and the right' do expect("captain hornblower".partition(" h")).to eq ["captain", " h", "ornblower"] end end context 'prepend' do it 'prepends the argument onto the original string' do expect("hornblower".prepend("captain ")).to eq "captain hornblower" end end context 'reverse!' do it 'returns the characters in the string from last to first - has a perm version' do expect("hello".reverse).to eq ("olleh") end end context 'rindex' do it 'returns the index of the first character of the last substring matching that in the argument' do expect("captain hornblower".rindex("bl")).to eq 12 end end context 'rjust' do it "indents from the left by the number of the argument iff it's higher than the number of chars in the string, filling with chars from the second arg" do expect("hello".rjust(6, "x")).to eq "xhello" end end context 'rpartition' do it "partitions in the same order as normal, but starts looking for the argument str from the right" do expect("helloworld".rpartition("l")).to eq ["hellowor", "l", "d"] end end context 'rstrip' do it "deletes all spaces and newline chars from the end of a string" do expect(" hello \n\n".rstrip).to eq " hello" end end context 'scan' do it 'either returns an array with an element for each match in the argument or passes each match in the argument to a block and returns the original string' do expect("captain horatio hornblower".scan(" ")).to eq [" ", " "] end end context 'slice!' do it 'permamently deletes the chars at the specified index, returning the deleted chars' do expect("helloworld".slice!(3..8)).to eq "loworl" end end context 'split' do it 'returns an array of subsections of the original string split by arg1, with at most arg2 elements' do expect("captain horatio hornblower hailed the halting herd of heroic harpies".split("h", 2)).to eq ["captain ", "oratio hornblower hailed the halting herd of heroic harpies"] end end context 'squeeze' do it 'returns a string with sequential duplicates of the letters given in the paramters (else all) deleted. has a perm vers' do expect("mississippi cheese".squeeze!("m-t")).to eq "misisipi cheese" end end context 'start_with?' do it 'returns true if the arg matches the first chars of the string' do expect("captain hornblower".start_with?("cap")).to be_true end end context 'strip!' do it 'removes all the spaces and newlines either side of a string' do expect("\n\n hello \n".strip!).to eq "hello" end end context 'sub!' do it 'behaves like gsub but only replaces the first instance of arg. Also has a perm version' do expect("hello world".sub!("l", "r")).to eq "herlo world" end end context 'succ!' do it 'is the same as .next' do expect("9".succ!).to eq "10" end end context 'swapcase!' do it 'does what you expect - has perm vers' do expect("hElLo".swapcase!).to eq "HeLlO" end end context 'to_f' do it 'turns chars into the equivalent float, stopping the first time it hits a non-number (defaulting to 0.0)' do expect('2,3h'.to_f).to eq 2.0 end end context 'to_r' do it 'turns chars into an equivalent fraction (rational) using same logic as above' do expect('34/2jsdf'.to_r).to eq (17/1) end end context 'tr!' do it 'swaps chars from those in arg1 for the equivalents in arg2 (can use a range, rounding up(?)) and returns a new string. Has perm version' do expect("captain b".tr!("a-c", "d-e")).to eq "edptdin e" end end context 'tr_s!' do it 'runs as .tr, but then deletes any duplicates of the substituted chars in a sequence. Has perm version' do expect("captain horatio hornblower".tr_s!("ow", "*")).to eq "captain h*rati* h*rnbl*er" end end context 'upto' do it 'runs a block for every string "between" the original and arg1 inclusive (using .succ), then returns the oriignal string' do a = 0 "hello world".upto("hello worlh") {|string| a += 1} expect(a).to eq 5 end end end
require('minitest/autorun') require_relative('../warehouse_picker') class TestWarehouse <Minitest::Test def setup @a_row = { a10: "rubber band", a9: "glow stick", a8: "model car", a7: "bookmark", a6: "shovel", a5: "rubber duck", a4: "hanger", a3: "blouse", a2: "stop sign", a1: "needle" } @b_row = { b1: "tyre swing", b2: "sharpie", b3: "picture frame", b4: "photo album", b5: "nail filer", b6: "tooth paste", b7: "bath fizzers", b8: "tissue box", b9: "deodorant", b10: "cookie jar", } @c_row = { c1: "rusty nail", c2: "drill press", c3: " chalk", c4: "word search", c5: "thermometer", c6: "face wash", c7: "paint brush", c8: "candy wrapper", c9: "shoe lace", c10: "leg warmers" } @warehouse = [@a_row, @c_row, @b_row] end # test for question 1 def test_single_bay_thing() result = single_bay(@warehouse,:c5) assert_equal("thermometer", result) end # test for question 2 def test_single_bay_number() result = single_bay_number(@warehouse, "bookmark") assert_equal(:a7, result) end # test for question 3 def test_multiple_bay_thing() result = multiple_bay_thing(@warehouse,[:b6, :b10, :b5]) assert_equal(["tooth paste", "cookie jar", "nail filer"], result) end # test for question 4 returning multiple bay numbers def test_multiple_bay_number() result = multiple_bay_number(@warehouse, ["shoe lace", "rusty nail", "leg warmers"]) assert_equal([:c9, :c1, :c10], result) end # test for question 5 checks for the items def test_multiple_bay_thing_q5() result = multiple_bay_thing(@warehouse,[:b3, :c7, :c9, :a3]) assert_equal(["picture frame", "paint brush", "shoe lace", "blouse"], result) end # test check for the distance between them def test_multiple_bay_number_distance() result = multiple_bay_number_distance(@warehouse, [:b3, :c7, :c9, :a3]) assert_equal(15, result) end # test for question 6 def test_multiple_bay_Qu6() result = multiple_bay_number_Qu6(@warehouse, ["hanger", "deodorant", "candy wrapper", "rubber band"]) assert_equal([:a10, :a4, :b9, :c8], result) end end
cask 'sonos-s1' do version '11.2' sha256 '1a98300bd16bb2f727eb1921db80777cc23178a483d56b44a9bb5d95d9ea6602' # 1a98300bd16bb2f727eb1921db80777cc23178a483d56b44a9bb5d95d9ea6602 SonosDesktopController112.dmg # download page: https://support.sonos.com/s/downloads?language=en_US url "https://update-software.sonos.com/software/mac/mdcr/SonosDesktopController#{version.no_dots}.dmg" name 'Sonos S1 Controller' homepage 'https://support.sonos.com/s/downloads' auto_updates true app 'Sonos S1 Controller.app' # this is the release notes page (can see latest release here too) appcast 'https://support.sonos.com/s/article/3521' zap trash: [ '~/Library/Application Support/Sonos', '~/Library/Application Support/com.sonos.macController' ] end
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'sinatra/shopified/version' Gem::Specification.new do |spec| spec.name = 'sinatra-shopified' spec.version = Sinatra::Shopified::VERSION spec.authors = ['Tyler King'] spec.email = ['tyler.n.king@gmail.com'] spec.summary = 'Shopify apps with Sinatra' spec.description = 'Provides some boilerplate helpers and routes for Shopify apps with Sinatra 1 & Sinatra 2' spec.homepage = 'https://github.com/ohmybrew/sinatra-shopified' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_dependency 'shopify_api', '>= 4.0' spec.add_dependency 'sinatra', '>= 1.4' spec.add_dependency 'sinatra-activerecord', '~> 2.0' spec.add_development_dependency 'yard', '~> 0.8' spec.add_development_dependency 'inch', '~> 0.7' spec.add_development_dependency 'rake', '~> 10.5' spec.add_development_dependency 'rack-test', '~> 0.6' spec.add_development_dependency 'webmock', '~> 1.24' spec.add_development_dependency 'sqlite3', '~> 1.3' spec.add_development_dependency 'simplecov', '~> 0.11' spec.add_development_dependency 'appraisal' end
# == Schema Information # # Table name: courts # # id :integer not null, primary key # name :string # address :text # longitude :string # latitude :string # summary :string # google_map_link :string # phone :string # indoor_courts :integer # outdoor_courts :integer # created_at :datetime not null # updated_at :datetime not null # class Court < ApplicationRecord has_many :matches end
class CommentsController < ApplicationController before_action :set_user before_action :set_post before_action :set_comment, only: [:destroy, :edit, :update] before_action :signed_in_user, only: [:create] def create @comment = @post.comments.new(comment_params) @comment.user_id = current_user.id @comment.save respond_to :js end def edit respond_to do |format| format.js end end def update store_location if @comment.update(comment_params) respond_to do |format| format.html { redirect_to @post } format.js end else flash[:error] = "Comment Not Updated" redirect_to @post end end # DELETE /post/1/comment/10 def destroy if @comment.destroy respond_to do |format| format.html {redirect_to @user} format.js end end end private def comment_params params.require(:comment).permit(:body, :user_id) end def set_user @user = current_user end def set_post @post = Post.find(params[:post_id]) end def set_comment @comment = @post.comments.find(params[:id]) end def signed_in_user unless signed_in? session[:return_to] = post_path(@post) redirect_to signin_url, notice: "Please sign in." end end end
# frozen_string_literal: true require 'pry' class Cult attr_reader :name, :location, :founding_year, :slogan attr_accessor :follower @@all = [] def initialize(name, location, founding_year, slogan) @name = name @location = location @founding_year = founding_year @slogan = slogan @@all << self end def self.all @@all end def followers BloodOath.all.map(&:follower) end def recruit_follower(follower) BloodOath.new(follower, self) end def cult_population followers.length end def self.find_by_name(cult) self.all.find { |cult| cult.name == cult } end def self.find_by_location(location) self.all.select { |cult| cult.location == location } end def self.find_by_founding_year(founding_year) self.all.select { |cult| cult.founding_year == founding_year } end def average_age ages = followers.reduce(0) { |sum, follower| sum + follower.age } ages / followers.length.to_f end def my_followers_mottos followers.each { |follower| puts follower.life_motto } end def self.least_popular self.all.min_by(&:follower).name end def self.most_common_location self.all.max_by(&:location).location end end
# Create a 2-Player math game where players take turns to # answer simple math addition problems. # A new math question is generated for each turn by # picking two numbers between 1 and 20. # The player whose turn it is is prompted the question # and must answer correctly or lose a life. # Both players start with 3 lives. # They lose a life if they mis-answer a question. # At the end of every turn, the game should output # the new scores for both players, so players know where they stand. # The game doesn’t end until one of the players loses all their lives. # At this point, the game should announce who won # and what the other player’s score is. players -state: name (USER_INPUT), lives, score -behaviour: player1_name and player2_name inputted -methods: function to take user input and display function to create lives based on wrong answer show player score games -state: random1, random2, correct_answer, player1_answer, player2_answer -methods: function to display random number (1 - 20) as random1 and random2 (result is string of math problem) function to check if player_answer (USER_INPUT) === correct_answer if match, show scores, generate two more random numbers (1-20) as math problem string else no match, player who answered loses 1 life, show scores, generate another random number (1-20) as question_id continue until player1 or player2 lives === 0, show winner & game over
#### # # A charge that is applied to a property's account. # # A charge represents the type, amount and, through due_ons, the date that # a property should become due a charge. # # The code is part of the charge system in the accounts. Charges are # associated with a property's account. When an operator decides they want to # bill a group of properties. Charges are generated according to this # information using the invoicing system. The information is passed, as a # chargeable, to becomes a debit in the property's account.debits # #### # class Charge < ApplicationRecord enum payment_type: { manual: 0, automatic: 1 } enum activity: { dormant: 0, active: 1 } belongs_to :account, optional: true has_many :credits, dependent: :destroy, inverse_of: :charge has_many :debits, dependent: :destroy, inverse_of: :charge belongs_to :cycle, inverse_of: :charges validates :charge_type, :cycle, presence: true validates :payment_type, inclusion: { in: payment_types.keys } validates :activity, inclusion: { in: activities.keys } validates :amount, price_bound: true, if: :active? delegate :monthly?, to: :cycle delegate :charged_in, to: :cycle # billing_period - the date range that we generate charges for. # returns - chargable_info array with data required to bill the # associated account. Empty array if nothing billed. def coming billing_period return [] if dormant? cycle.between(billing_period).map do |matched_cycle| make_chargeable(matched_cycle) end.compact end def prepare # maybe should be calling prepare on charge structure end def clear_up_form mark_for_destruction if empty? end def empty? attributes.except(*ignored_attrs).values.all?(&:blank?) end def to_s "charge: #{charge_type}, #{cycle}" end private # Converts a Charge object into a Chargeable object. # matched_cycle - struct of date the charge becomes due, spot, and # the period it is billed for, period. # returns - The information to bill, debit, the associated account. # def make_chargeable matched_cycle Chargeable.from_charge charge_id: id, at_time: matched_cycle.spot, amount: amount, account_id: account_id, period: matched_cycle.period end def ignored_attrs %w[id account_id activity created_at updated_at] end end
json.array!(@stores) do |store| json.extract! store, :id, :name, :email, :open, :image, :photos, :tags, :description, :lat, :lng, :votes, :props json.url store_url(store, format: :json) end
class Persons::StoragesController < ApplicationController before_filter :authenticate_user! before_action :set_storage, only: [:show, :edit, :update, :destroy] layout "user_dashboard" load_and_authorize_resource def index @per_page = params[:per_page] || 10; @storages = current_user.company.storages.order(:id).page(params[:page]).per(@per_page) @current_breadcrumb = [{ name: "Склады организации" }] end def new @storage = Storage.new @storage.build_delivery end def create @storage = Storage.new(storage_params) @storage.company_id = current_user.company.id respond_to do |format| if @storage.save format.html { redirect_to persons_storages_path } else format.html { render action: 'new' } end end end def edit @current_breadcrumb = [{ name: "Склады организации", url: persons_storages_path }, { name: "Редактирование склада: #{@storage.name}" }] end def show end def update respond_to do |format| if @storage.update(storage_params) format.html { redirect_to persons_storages_path } else format.html { render action: 'edit' } end end end def destroy @storage.destroy respond_to do |format| format.html { redirect_to persons_storages_path } end end private def set_storage @storage = Storage.find(params[:id]) end def storage_params params.require(:storage).permit(:name, :city_id, :address, :main, delivery_attributes: [:id, :delivery_types => []]) end end
module Sdc3 module StructHelper def members_to_b(*names) return unless names names.each do |mem| val = self[mem].downcase if self[mem] self[mem] = (val == '1' || val == 'yes' || val == 'true') end end def members_to_i(*names) return unless names names.each do |mem| self[mem] = self[mem].to_i if self[mem] end end def members_to_f(*names) return unless names names.each do |mem| self[mem] = self[mem].to_f if self[mem] end end end end
class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_user, :medusa_user?, :safe_can? def route_not_found render file: Rails.public_path.join('404.html'), status: :not_found, layout: false end protected def set_current_user(user) @current_user = user session[:current_user_id] = user.id end def unset_current_user @current_user = nil session[:current_user_id] = nil end def current_user @current_user ||= User.find_by(id: session[:current_user_id]) end def current_user_uid current_user.uid end def medusa_user? if Rails.env.production? || Rails.env.demo? logged_in? && GroupManager.instance.resolver.is_ad_user?(current_user) else logged_in? end end def require_medusa_user unless medusa_user? redirect_non_medusa_user end end def require_medusa_user_or_basic_auth unless medusa_user? or basic_auth? redirect_non_medusa_user end end def redirect_non_medusa_user if current_user redirect_to unauthorized_net_id_url(net_id: current_user.net_id) else redirect_non_logged_in_user end end def redirect_non_logged_in_user session[:login_return_uri] = request.env['REQUEST_URI'] respond_to do |format| format.js do render 'shared/unauthenticated' end format.html do redirect_to(login_path) end format.json do redirect_to(login_path) end end end def logged_in? current_user.present? end def require_logged_in redirect_non_logged_in_user unless logged_in? end def require_logged_in_or_basic_auth redirect_non_logged_in_user unless logged_in? or basic_auth? end def basic_auth? ActionController::HttpAuthentication::Basic.decode_credentials(request) == Settings.medusa.basic_auth rescue false end rescue_from CanCan::AccessDenied do redirect_to unauthorized_path end rescue_from ActiveRecord::InvalidForeignKey do |exception| redirect_back(fallback_location: root_path, alert: 'The record you are trying to delete has some associated database records so cannot be deleted. Please contact the medusa admins for help.') end rescue_from ActionController::RoutingError do |exception| #logger.error exception.message render plain: '404 Not found', status: 404 end rescue_from ActionView::MissingTemplate do |exception| logger.error exception.message render plain: '404 Not found', status: 404 end def record_event(eventable, key, user = current_user) eventable.events.create(actor_email: user.email, key: key, date: Date.today) end def reset_ldap_cache(user) user ||= current_user LdapQuery.reset_cache(user.net_id) if user.present? end #Use in place of Cancan's can? so that it will work when there is not a user (in this case permission is denied, as you'd expect) def safe_can?(action, *args) current_user and can?(action, *args) end end
# Namespace that maps to `Mdm::Module` and `Metasploit::Framework::Module` and contains constants and mixins to # DRY the implementation of the in-memory and in-database models in those namespaces. module Metasploit::Model::Module extend ActiveSupport::Autoload autoload :Action autoload :Ancestor autoload :Architecture autoload :Author autoload :Class autoload :Handler autoload :Instance autoload :Path autoload :Platform autoload :Rank autoload :Reference autoload :Stance autoload :Target autoload :Type end
class AddFieldLabelToConfigurationDefinitions < ActiveRecord::Migration def change add_column :configuration_definitions, :field_label, :string end end
# frozen_string_literal: true # == Schema Information # # Table name: authentication_tokens # # id :integer not null, primary key # body :string # expires_in :integer # ip_address :string # last_used_at :datetime # user_agent :string # created_at :datetime not null # updated_at :datetime not null # user_id :integer # # Indexes # # index_authentication_tokens_on_user_id (user_id) # # Foreign Keys # # fk_rails_... (user_id => users.id) # class AuthenticationToken < ApplicationRecord belongs_to :user end
# Controller handling admin activities class AdminController < ApplicationController require_dependency 'RMagick' before_filter :authorize def index end def news @news = NewsItem.find(:all, :order => "created_at desc", :limit => 10) end def new_news @news = NewsItem.new end def create_news @news = NewsItem.new(params[:news]) @news.save redirect_to :action => "news" end def edit_news @news = NewsItem.find(params[:id]) end def update_news @news = NewsItem.find(params[:id]) if @news.update_attributes(params[:news]) flash['notice'] = 'NewsItem was successfully updated.' redirect_to :action => 'news' else render :action => 'edit_news' end end def delete_news NewsItem.find(params[:id]).destroy redirect_to :action => 'news' end # List all logos uploaded def logos @customers = Customer.find(:all) end # Show a single logo def show_logo @customer = Customer.find(params[:id]) image = Magick::Image.read( @customer.logo_path ).first if image send_file @customer.logo_path, :filename => "logo", :type => image.mime_type, :disposition => 'inline' else render :nothing => true end end def stats @users_today = User.count( :conditions => ["created_at > '#{tz.now.at_midnight.to_s(:db)}'"] ) @users_yesterday = User.count( :conditions => ["created_at > '#{tz.now.yesterday.at_midnight.to_s(:db)}' AND created_at < '#{tz.now.at_midnight.to_s(:db)}'"] ) @users_this_week = User.count( :conditions => ["created_at > '#{tz.now.beginning_of_week.at_midnight.to_s(:db)}'"] ) @users_last_week = User.count( :conditions => ["created_at > '#{1.week.ago.beginning_of_week.at_midnight.to_s(:db)}' AND created_at < '#{tz.now.beginning_of_week.at_midnight.to_s(:db)}'"] ) @users_this_month = User.count( :conditions => ["created_at > '#{tz.now.beginning_of_month.at_midnight.to_s(:db)}'"] ) @users_last_month = User.count( :conditions => ["created_at > '#{1.month.ago.beginning_of_month.at_midnight.to_s(:db)}' AND created_at < '#{tz.now.beginning_of_month.at_midnight.to_s(:db)}'"] ) @users_this_year = User.count( :conditions => ["created_at > '#{tz.now.beginning_of_year.at_midnight.to_s(:db)}'"] ) @users_total = User.count @projects_today = Project.count( :conditions => ["created_at > '#{tz.now.at_midnight.to_s(:db)}'"] ) @projects_yesterday = Project.count( :conditions => ["created_at > '#{tz.now.yesterday.at_midnight.to_s(:db)}' AND created_at < '#{tz.now.at_midnight.to_s(:db)}'"] ) @projects_this_week = Project.count( :conditions => ["created_at > '#{tz.now.beginning_of_week.at_midnight.to_s(:db)}'"] ) @projects_last_week = Project.count( :conditions => ["created_at > '#{1.week.ago.beginning_of_week.at_midnight.to_s(:db)}' AND created_at < '#{tz.now.beginning_of_week.at_midnight.to_s(:db)}'"] ) @projects_this_month = Project.count( :conditions => ["created_at > '#{tz.now.beginning_of_month.at_midnight.to_s(:db)}'"] ) @projects_last_month = Project.count( :conditions => ["created_at > '#{1.month.ago.beginning_of_month.at_midnight.to_s(:db)}' AND created_at < '#{tz.now.beginning_of_month.at_midnight.to_s(:db)}'"] ) @projects_this_year = Project.count( :conditions => ["created_at > '#{tz.now.beginning_of_year.at_midnight.to_s(:db)}'"] ) @projects_total = Project.count @tasks_today = Task.count( :conditions => ["created_at > '#{tz.now.at_midnight.to_s(:db)}'"] ) @tasks_yesterday = Task.count( :conditions => ["created_at > '#{tz.now.yesterday.at_midnight.to_s(:db)}' AND created_at < '#{tz.now.at_midnight.to_s(:db)}'"] ) @tasks_this_week = Task.count( :conditions => ["created_at > '#{tz.now.beginning_of_week.at_midnight.to_s(:db)}'"] ) @tasks_last_week = Task.count( :conditions => ["created_at > '#{1.week.ago.beginning_of_week.at_midnight.to_s(:db)}' AND created_at < '#{tz.now.beginning_of_week.at_midnight.to_s(:db)}'"] ) @tasks_this_month = Task.count( :conditions => ["created_at > '#{tz.now.beginning_of_month.at_midnight.to_s(:db)}'"] ) @tasks_last_month = Task.count( :conditions => ["created_at > '#{1.month.ago.beginning_of_month.at_midnight.to_s(:db)}' AND created_at < '#{tz.now.beginning_of_month.at_midnight.to_s(:db)}'"] ) @tasks_this_year = Task.count( :conditions => ["created_at > '#{tz.now.beginning_of_year.at_midnight.to_s(:db)}'"] ) @tasks_total = Task.count @logged_in_today = User.count( :conditions => ["last_login_at > '#{tz.now.at_midnight.to_s(:db)}'"] ) @logged_in_this_week = User.count( :conditions => ["last_login_at > '#{tz.now.beginning_of_week.at_midnight.to_s(:db)}'"] ) @logged_in_this_month = User.count( :conditions => ["last_login_at > '#{tz.now.beginning_of_month.at_midnight.to_s(:db)}'"] ) @logged_in_this_year = User.count( :conditions => ["last_login_at > '#{tz.now.beginning_of_year.at_midnight.to_s(:db)}'"] ) @logged_in_now = User.count( :conditions => ["last_ping_at > '#{2.minutes.ago.utc.to_s(:db)}'"] ) @last_50_users = User.find(:all, :limit => 50, :order => "created_at desc") end def authorize unless current_user.admin > 1 redirect_to :controller => 'login', :action => 'login' return false end # Set current locale Localization.lang(current_user.locale || 'en_US') end end
class Beer require 'csv' attr_reader :name, :manf def initialize name, manf @name = name @manf = manf end def == another_beer return (@name == another_beer.name and @manf == another_beer.manf) end def self.all_beers $client.query("SELECT * FROM `beers`").map do |beer| Beer.new(beer['name'], beer['manf']) end end def liked_by @likes ||= $client.query("SELECT name, city, phone, addr FROM `drinkers` JOIN `likes` ON drinkers.name = likes.drinker WHERE likes.beer = '#{@name.gsub("'","''")}';").to_a.map do |drinker| Drinker.new(drinker['name'], drinker['city'], drinker['phone'], drinker['addr']) end return @likes end def self.get_beer_by_name name beer = $client.query("SELECT * FROM `beers` WHERE name='#{name.gsub("'","''")}'").to_a[0] return Beer.new(beer['name'], beer['manf']) if not beer.nil? nil end def self.add_ze_beers manfs = [] names = [] nums = [] count = 0 150.times do nums << rand(4759) end CSV.foreach('../seed_data/beer_data/openbeerdb_csv/breweries.csv') do |row| if row[1] and row[1].ascii_only? manfs << {id: row[0], name: row[1]} end end CSV.foreach('../seed_data/beer_data/openbeerdb_csv/beers.csv') do |row| count += 1 if row[2] and row[2].ascii_only? manfs.each do |manf| if row[1] == manf[:id] and not names.include? row[2].downcase and nums.include? count Beer.new(row[2], manf[:name]).add_to_db names.push row[2].downcase end end end end end def sold_at $client.query("SELECT name, city, license, phone, addr FROM `bars` JOIN `sells` ON bars.name = sells.bar WHERE sells.beer = '#{@name}';").to_a.map do |bar| Bar.new(bar['name'], bar['city'], bar['license'], bar['phone'], bar['addr']) end end def price_at bar $client.query("SELECT price FROM `sells` WHERE beer = '#{@name.gsub("'","''")}' AND bar='#{bar.name.gsub("'","''")}';").to_a[0]['price'].to_f end def add_to_db $client.query("INSERT INTO `beers` VALUES('#{@name.gsub("'","''")}', '#{@manf.gsub("'","''")}');") # puts ("INSERT INTO `beers` VALUES('#{@name}', '#{@manf}');") end end
# -*- coding: utf-8 -*- module Mushikago # Mushikago SDK for Ruby のバージョン VERSION = '2.4.2' end
module Pantograph module Actions class GitPullTagsAction < Action def self.run(params) Actions.sh('git fetch --tags') end def self.description 'Executes a simple `git fetch --tags` command' end def self.authors ['johnknapprs'] end def self.is_supported?(platform) true end def self.example_code [ 'git_pull_tags' ] end def self.category :source_control end end end end
class CreateMutableSettings < ActiveRecord::Migration def self.up create_table :mutable_settings do |t| t.belongs_to :cobrand t.string :key t.text :value t.timestamps end add_index :mutable_settings, :cobrand_id add_index :mutable_settings, [:cobrand_id, :key], :unique => true end def self.down drop_table :mutable_settings end end
# Dado el siguiente string y caracter, crear un método que reciba como parámetro el string # y el caracter. Luego debe buscar si existe ese caracter dentro del string. # hint: El método .include? de un string busca si un caracter # o string dado está contenido en éste. cadena = 'Hola Mundo!' caracter = 'o' def incluye(cad, car) if car.include? cad puts true else puts false end end incluye(cadena,caracter)
FactoryGirl.define do factory :model do sequence(:name) {|n| "#{Faker::Name.name} #{n}"} make end end
class AccTest def pub puts "pub is a public method." end public :pub def priv puts "private is a private method." end private :priv end #=> AccTest p acc = AccTest.new #=> #<AccTest:0x007fec0a367380> p acc.pub #=> pub is a public method. p acc.priv #=> NoMethodError: private method `priv' called for #<AccTest:0x007fec0a367380> class Processor def process protected_process end def protected_process private_process end protected :protected_process def private_process puts "Done!" end private :private_process end p processor = Processor.new #=> #<Processor:0x007fec0a475ad8> p processor.process #=> Done! p process.private_process #=> NameError: undefined local variable or method `process' for main:Object p process.protected_process #=>NameError: undefined local variable or method `process' for main:Object class Processor def process(other) other.protected_process end def protected_process puts "Called!!" end protected :protected_process end p processor = Processor.new #=> #<Processor:0x007fec09c6f550> p processor.process(Processor.new) #=> Called!! p processor.protected_process #=> NoMethodError: protected method `protected_process' called for #<Processor:0x007fec09c6f550>
# frozen_string_literal: true # typed: strict module WorkOS module Types # This DirectoryStruct acts as a typed interface # for the Directory class class DirectoryStruct < T::Struct const :id, String const :name, String const :domain, String const :type, String const :state, String const :organization_id, String end end end
class CreateIssuedLettersTypeOfIssuedLetters < ActiveRecord::Migration def change if !table_exists? :issued_letters_type_of_issued_letters create_table :issued_letters_type_of_issued_letters do |t| t.integer :issued_letter_id t.integer :type_of_issued_letter_id t.timestamps end end end end
require "test_helper" describe CustomersController do it "must get index" do # Act get customers_path body = JSON.parse(response.body) # Assert expect(body).must_be_instance_of Array expect(body.length).must_equal Customer.count # Check that each customer has the proper keys fields = ["id", "name", "registered_at", "postal_code", "phone", "videos_checked_out_count"].sort body.each do |customer| expect(customer.keys.sort).must_equal fields end must_respond_with :ok end it "works even with no customers" do Customer.destroy_all get customers_path body = JSON.parse(response.body) expect(body).must_be_instance_of Array expect(body.length).must_equal 0 must_respond_with :ok end end
require 'rails_helper' require 'swagger_helper' RSpec.describe Api::V1::ConsumersController, type: :request do include AuthHelper CONSUMER_ROOT = 'consumer'.freeze CONSUMER_TAG = 'Consumers'.freeze describe 'Consumers API', swagger_doc: 'v1/swagger.json' do let!(:user_one) { create(:user, :consumer_user) } let!(:user_two) { create(:user, :consumer_user) } # UPDATE path '/api/v1/consumers/{id}' do patch 'Updates a consumer' do tags CONSUMER_TAG consumes 'application/json' produces 'application/json' security [Bearer: []] parameter name: :id, in: :path, type: :string parameter name: :consumer, in: :body, schema: { type: :object, properties: { first_name: { type: :string }, last_name: { type: :string } } } let!(:update_params) { { first_name: 'Mary' } } response '200', 'Consumer updated' do let!(:Authorization) { auth_headers_for(user_one) } schema '$ref' => '#/definitions/consumer' let!(:id) { user_one.profile.id } let!(:consumer) { update_params } it 'responds with 200 OK', request_example: :consumer do expect(response).to have_http_status :ok end it 'updates the record', :skip_swagger do expect(User.find(user_one.id).profile.first_name).to eql 'Mary' end it 'returns expected attributes in valid JSON', :skip_swagger do user = User.find(user_one.id) expect(response.body).to eql( ConsumerSerializer.render(user.profile, root: CONSUMER_ROOT) ) end end response '401', 'Unauthorized' do context 'when updating another user\'s profile data' do let!(:Authorization) { auth_headers_for(user_two) } let!(:id) { user_one.profile.id } let!(:consumer) { update_params } it 'responds with 401 unauthorized' do expect(response).to have_http_status :unauthorized end end end end end end end
RSpec.describe 'OrderGroup' do let(:order_group) { ::RSpec::Mocks::OrderGroup.new } describe '#consume' do let(:ordered_1) { double :ordered? => true } let(:ordered_2) { double :ordered? => true } let(:unordered) { double :ordered? => false } before do order_group.register unordered order_group.register ordered_1 order_group.register unordered order_group.register ordered_2 order_group.register unordered order_group.register unordered end it 'returns the first ordered? expectation' do expect(order_group.consume).to eq ordered_1 end it 'keeps returning ordered? expectation until all are returned' do expectations = 3.times.map { order_group.consume } expect(expectations).to eq [ordered_1, ordered_2, nil] end end end
class DNAarray attr_reader :height #******************* #Initialization of a DNA array #******************* #4 modes: takes an array (of strings or of DNAsequences), takes a string (path to a file) or take a single DNA sequence def initialize(info, data = 0) return _fastinit(info) if $exec == 'real' #Introduce the DNA sequences @sequences = [] if info.is_a? Array 0.upto(info.length - 1){ |i| if info[i].is_a? String @sequences[i] = DNAsequence.new(info[i]) elsif info[i].is_a? DNAsequence @sequences[i] = info[i] end } elsif info.is_a? String i = 0 File.foreach(info).with_index do |val, ln| if ln >= data @sequences[i] = DNAsequence.new(val.chomp) i += 1 end end elsif info.is_a? DNAsequence @sequences[0] = info else puts "Wrong initialization of MotifMatrix" end #Store the other main properties @height = @sequences.length return self end #******************* #Get the whole DNAarray in a readable format #******************* def to_s str = "[\n" @sequences.each{ |seq| str += seq.to_s str += "\n" } str += ']' return str end #******************* #Return a whole DNA sequence (default) or a single base as a DNA sequence (if the second parameter is defined) #******************* def at(row, column = -1) if column == -1 return @sequences[row] else return @sequences[row].cut(column,1) end end #******************* #Add a new DNAsequence into the DNAarray #******************* def push(seq) if seq.is_a? DNAsequence @sequences.push(seq) @height += 1 else puts "You can only push DNA sequences into a DNA array" end return self end #******************* #Return the distance between a DNAsequence and the DNAarray as the sum of the distances between that DNAsequence and every DNAsequence in DNarray. #******************* def distanceTo(pattern) dist = 0 @sequences.each{ |seq| motif, d = seq.motifFor(pattern) dist += d } return dist end #******************* #Among all the k-mers, find the nearest to the DNAarray #******************* def medianSequence(k) median = [] distance = k * @height 0.upto(Base::NUM_TYPES ** k - 1){ |kmer| seq = DNAsequence.new(kmer, k) d = distanceTo(seq) if d < distance distance = d median.clear.push(seq) elsif d == distance median.push(seq) end } return median end #******************* #Returns a DNAmotifsArray from the DNAarray (randomly selected by default, or the first one otherwise) #************* def extractDNAMotifsArray(k, random = true) motifs = [] place = 0 0.upto(@height - 1){ |i| place = rand(@sequences[i].length - k) + 1 if random motifs.push(@sequences[i].cut(place, k)) } return DNAmotifsArray.new(motifs) end #******************* #TODO!!! Probably we have to move this to another place #******************* def greedyMotifSearch(k, pseudocounts = false) #Build the first motif matrix: first k-mer from every row in DNA array best = DNAarray.new(@sequences[0].cut(0, k)) 1.upto(@sequences.length - 1){ |i| best.push(@sequences[i].cut(0, k)) } bestscore = best.score #Iterate over all the k-mers from the first sequence 0.upto(@sequences[0].length - k){ |i| motifs = DNAarray.new(@sequences[0].cut(i, k)) #For each of them, iterate over every other sequence in DNA array and find the most probable k-mer through the previously computed profile matrix 1.upto(@height - 1){ |j| profile = motifs.profileMatrix(pseudocounts) motifs.push(@sequences[j].mostProbableThrough(k, profile)) } #If the motifs array you get scores better than the previous one, store it. if motifs.score < bestscore best = motifs bestscore = best.score end } return best end #******************* #******************* # #Private methods # #******************* #******************* private #Fast initialization for those times when we know everything is right and we need a fast computation def _fastinit(info) @sequences = info @height = info.length return self end end
module Reciter class Parser def parse(sequence) return [] if sequence.nil? || sequence.empty? validate_format(sequence) sequence. split(';'). map {|subsequence| if subsequence.include?('-') r = Range.new(*subsequence.split('-').map(&:to_i)) raise InvalidInput unless r.begin <= r.end r.to_a else subsequence.to_i end }. flatten. uniq. sort end def unparse(*sequence) mechanic, sequence = handle_unparse_params(sequence) ranges = [] last = nil sequence.sort.each do |n| if last.nil? || n != last + 1 ranges << Range.new(n, n) else ranges[-1] = Range.new(ranges[-1].begin, n) end last = n end ranges.map {|r| if r.end == r.begin || r.end == r.begin + 1 r.to_a else "%s%s%s" % [r.begin, mechanic ? '-' : " #{config.text_for_to} ", r.end] end }. flatten. join(mechanic ? ';' : ', ') end def self.config @config ||= Reciter::Config.new end private def handle_unparse_params(params) if params[0].is_a? Symbol [params[0] == :mechanic, handle_unparse_params_list(params[1..-1])] else [false, handle_unparse_params_list(params)] end end def handle_unparse_params_list(list) list[0].is_a?(Array) ? list[0] : list end def validate_format(sequence) subsequences = sequence.split(';') raise InvalidInput unless !subsequences.empty? && subsequences.all? {|subsequence| subsequence =~ /^(\d+\-\d+)$|^\d+$/ } end def config self.class.config end end end
class PackagesController < ApplicationController before_action :set_user, only: [:new, :create] def new @package = Package.new end def create @package = Package.new(params_package) @booking = current_user.bookings.find_by(status: "pending") @package.booking = @booking @package.user = current_user @furniture = @package.furniture if @package.save # notifiction "added to your packages redirect_to furnitures_path flash[:alert] = 'Item added to your package.' else render 'furnitures/show' end end def index @user = User.find_by(id: params[:user]) @user ||= current_user @booking = @user.bookings.find_by(status: "pending") @packages = @user.packages.where(booking: @booking).order(:created_at) @total_items = 0 @packages.each do |package| @total_items += package.number end @total = 0 @packages.each do |package| @total += package.price end @budget = 100 @budget - @total end def destroy @package = Package.find(params[:id]) @package.destroy redirect_to packages_path(user: current_user) end def update @package = Package.find(params[:id]) @package.update(params_package) redirect_to packages_path(user: current_user) end def item_increase @pack_numb = Package.find(params[:id]) @pack_numb.number += 1 @pack_numb.save redirect_to packages_path(user: current_user, anchor: "package-#{@pack_numb.id}") end def item_decrease @pack_numb = Package.find(params[:id]) @pack_numb.number -= 1 @pack_numb.save redirect_to packages_path(user: current_user, anchor: "package-#{@pack_numb.id}") end private def params_package params.require(:package).permit(:number, :furniture_id) end def set_user @user = current_user end end
class ModeloAgenda::Contacto attr_accessor :dni,:nombre,:apellidos,:email,:telefono,:direccion def initialize (dni,nombre,apellidos,email,telefono,direccion) @dni = dni @nombre = nombre @apellidos = apellidos @email = email @telefono = telefono @direccion = direccion #también se puede inicializar asi #@dni,@nombre,@apellidos,@email,@telefono,@cacahuete = dni,nombre,apellidos,email,telefono,cacahuete end #He cambiado direccion por cacahuete para comprobar que no tiene que ver con el nombre de la clase def to_s "#{@dni},#{@nombre},#{@apellidos},#{@email},#{@telefono},#{@direccion}" end end
require 'nokogiri' require 'open-uri' require 'openssl' class Scraper attr_accessor :source, :name def initialize(source, name) @source = source @name = name @AppRoot = File.join(Dir.pwd, name) end def open(*args) super *args, allow_redirections: :safe, ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE end def scrap system 'mkdir', '-p', @AppRoot scraproot = @AppRoot system 'mkdir', '-p', scraproot + "/img" system 'mkdir', '-p', scraproot + "/js" system 'mkdir', '-p', scraproot + "/css" page = Nokogiri::HTML(open(@source)) e = /^.*\.(jpg|JPG|gif|GIF|png|PNG|tiff|tif|TIFF|TIF)/ n=0 page.xpath('//img/@data-src', '//img/@src').each do |img| # asset_name = '/img/' + n.to_s + File.basename(img.value, ".*") + "." + # e.match(File.extname(img.value)).to_a.last.to_s asset_name = img.value filename = scraproot + asset_name system 'mkdir', '-p', File.dirname(filename) open(filename , 'wb') do |file| puts "Writing #{filename}" file << open(URI.join( @source, img.value ).to_s).read img.content = asset_name end n += 1 end n=0 page.xpath('//link/@href').each do |link| asset_name = '/css/' + n.to_s + ".css" filename = scraproot + asset_name open(filename, 'wb') do |file| puts "Writing #{filename}" begin open(URI.join( @source, link.value ).to_s).read rescue else file << open(URI.join( @source, link.value ).to_s).read end link.content = asset_name end n = n + 1 end n=0 page.xpath('//script/@src').each do |script| asset_name = '/js/' + n.to_s + File.basename(script.value) filename = scraproot + asset_name open(filename, 'wb') do |file| puts "Writing #{filename}" file << open(URI.join( @source, script.value ).to_s).read script.content = asset_name end n = n + 1 end open(scraproot + "/" + "index.html", "wb") do |file| puts "Writing #{scraproot + "/" + "index.html"}" file.write(page) end end end ##### # Patch to allow open-uri to follow safe (http to https) # and unsafe redirections (https to http). # # Original gist URL: # https://gist.github.com/1271420 # # Relevant issue: # http://redmine.ruby-lang.org/issues/3719 # # Source here: # https://github.com/ruby/ruby/blob/trunk/lib/open-uri.rb # # Thread-safe implementation adapted from: # https://github.com/obfusk/open_uri_w_redirect_to_https # module OpenURI class <<self alias_method :open_uri_original, :open_uri alias_method :redirectable_cautious?, :redirectable? def redirectable?(uri1, uri2) case Thread.current[:__open_uri_redirections__] when :safe redirectable_safe? uri1, uri2 when :all redirectable_all? uri1, uri2 else redirectable_cautious? uri1, uri2 end end def redirectable_safe?(uri1, uri2) redirectable_cautious?(uri1, uri2) || http_to_https?(uri1, uri2) end def redirectable_all?(uri1, uri2) redirectable_safe?(uri1, uri2) || https_to_http?(uri1, uri2) end end ##### # Patches the original open_uri method, so that it accepts the # :allow_redirections argument with these options: # # * :safe will allow HTTP => HTTPS redirections. # * :all will allow HTTP => HTTPS and HTTPS => HTTP redirections. # # OpenURI::open can receive different kinds of arguments, like a string for # the mode or an integer for the permissions, and then a hash with options # like UserAgent, etc. # # To find the :allow_redirections option, we look for this options hash. # def self.open_uri(name, *rest, &block) Thread.current[:__open_uri_redirections__] = allow_redirections(rest) block2 = lambda do |io| Thread.current[:__open_uri_redirections__] = nil block[io] end begin open_uri_original name, *rest, &(block ? block2 : nil) ensure Thread.current[:__open_uri_redirections__] = nil end end private def self.allow_redirections(args) options = first_hash_argument(args) options.delete :allow_redirections if options end def self.first_hash_argument(arguments) arguments.select { |arg| arg.is_a? Hash }.first end def self.http_to_https?(uri1, uri2) schemes_from([uri1, uri2]) == %w(http https) end def self.https_to_http?(uri1, uri2) schemes_from([uri1, uri2]) == %w(https http) end def self.schemes_from(uris) uris.map { |u| u.scheme.downcase } end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) # Create a main sample customer. customer = Customer.create!(name: "Sample User", email: "sampleuser@mail.org", password: "foobar", password_confirmation: "foobar") # Create a main sample coach. coach = Coach.create!(name: "Mike", email: "mikecoach@mail.org", password: "password", password_confirmation: "password") # Generate a bunch of additional customers. 30.times do |n| name = Faker::Name.name email = "sample-#{n+1}@mail.org" password = "password" Customer.create!( name: name, email: email, password: password, password_confirmation: password ) end 5.times do |n| name = Faker::Name.name email = "coach-#{n+1}@mail.org" password = "password" Coach.create!( name: name, email: email, password: password, password_confirmation: password ) end # Random schedules for coaches schedule1 = Coach.first.schedule schedule1.update( monday: ["7", "8", "9", "10", "11", "16", "17", "18", "19", "20"], tuesday: ["9", "10", "11", "12", "13"], wednesday: ["7", "8", "9", "15", "16", "17", "18", "19"], thursday: ["17", "18", "19", "20", "21"], friday: ["7", "8", "9", "10", "11", "16", "17", "18", "19", "20"], saturday: ["10", "11", "12"], sunday: ["16", "17", "18"] ) schedule2 = Coach.second.schedule schedule2.update( monday: ["17", "18", "19", "20", "21"], tuesday: ["7", "8", "9", "10", "14", "15"], wednesday: ["15", "16", "17", "18", "19", "20"], thursday: ["7", "8", "9", "10", "11", "12"], friday: ["15", "16", "17"], saturday: ["8", "9", "10", "11", "12"], sunday: ["11", "12", "13"] ) schedule3 = Coach.third.schedule schedule3.update( monday: ["7", "8", "9", "10"], tuesday: ["13", "14", "15", "16", "17"], wednesday: ["7", "8", "9", "10", "11", "12"], thursday: ["7", "8", "9", "10", "11", "12"], friday: ["17", "18", "19", "20", "21"], saturday: ["9", "10", "11"], sunday: ["9", "10", "11"] ) schedule4 = Coach.fourth.schedule schedule4.update( monday: ["17", "18", "19", "20", "21"], tuesday: ["17", "18", "19", "20", "21"], wednesday: ["10", "11", "12", "13", "14", "15"], thursday: ["10", "11", "12", "13", "14", "15"], friday: ["12", "13", "14"], saturday: ["12", "13", "14"], sunday: ["12", "13", "14"] ) schedule5 = Coach.fifth.schedule schedule5.update( monday: ["9", "10", "11", "12", "13", "14", "20", "21"], tuesday: ["20", "21"], wednesday: ["7", "8", "19", "20", "21"], thursday: ["7", "8", "9", "10", "11", "12"], friday: ["18", "19", "20", "21"], saturday: ["8", "9", "10", "11", "12"], sunday: ["12", "13"] ) # Bookings 20.times do |b| day = Time.zone.today + (1..20).to_a.sample.days time = day + (8..16).to_a.sample.hours customer_id = Customer.pluck(:id).sample coach_id = Coach.pluck(:id).sample Booking.create!( time: time, customer_id: customer_id, coach_id: coach_id ) end
require 'rails_helper' feature 'User view recipe list' do scenario 'successfully' do user = User.create!(email: 'carinha@mail.com', password: '123456') recipe_list = RecipeList.create(user: user, name: 'coisas gostosas') other_user = User.create!(email: 'carinho@mail.com', password: '123456') other_recipe_list = RecipeList.create(user: other_user, name: 'coisas deliciosas') visit root_path click_on 'Entrar' within('.formulario') do fill_in 'Email', with: user.email fill_in 'Senha', with: '123456' click_on 'Entrar' end click_on 'Minhas Listas' expect(page).to have_css('h1', text: recipe_list.name) expect(page).not_to have_content('Você ainda não possui listas') expect(page).not_to have_content('coisas deliciosas') end end
class CreateRestaurants < ActiveRecord::Migration def change create_table :restaurants do |t| t.string :name t.string :address t.text :description t.string :phone t.string :email t.integer :user_id t.boolean :deliverable t.boolean :shisha_allow t.boolean :disabled, default: false t.timestamps end end end
require 'spec_helper' require 'vcr_helper' describe "Parking" do before(:each) do CentreServiceNoticeService.stub(:fetch) end describe "a centre without parking" do before(:each) do VCR.use_cassette('knox_without_parking') do get centre_info_path(centre_id: 'knox') end end it "should not show any parking" do assert_select "h2#parking", count: 0 end end describe "a centre with complimentary parking" do before(:each) do VCR.use_cassette('caseycentral_with_complimetary_parking') do get centre_info_path(centre_id: 'caseycentral') end end it "should say the parking is free" do assert_select 'h2', 'Parking' assert_select 'p', 'Complimentary parking available for all customers.' end end describe "a centre with parking rates" do before(:each) do VCR.use_cassette('doncaster_parking_with_rates') do get centre_info_path(centre_id: 'doncaster') end end it "should show all the parking rates" do assert_select '#parking-rates' do assert_select 'td.test-times', "0 &#8211; 3.0hrs" assert_select 'td.test-weekday', "FREE" assert_select 'td.test-weekend', "FREE" assert_select 'td.test-times', "3.0 &#8211; 3.5hrs" assert_select 'td.test-weekday', "$3.00" assert_select 'td.test-weekend', "$3.00" assert_select 'td.test-times', "3.5 &#8211; 4.0hrs" assert_select 'td.test-weekday', "$4.00" assert_select 'td.test-weekend', "$4.00" end end it "have a link to the terms and conditions" do assert_select 'a.test-terms-link[href=?]', 'http://res.cloudinary.com/wlabs/image/upload/df4zc8o8cxd4u8oxvqhb.pdf' end end describe "a centre a fixed rate" do before(:each) do VCR.use_cassette('warringahmall_fixed_rate') do get centre_info_path(centre_id: 'warringahmall') end end it "should say the parking is fixed rate" do assert_select 'h2', 'Parking' assert_select 'p', "Fixed Parking rate of $5 per day" end end end
class CreateAcentros < ActiveRecord::Migration[5.1] def change create_table :acentros do |t| t.references :aempresa, foreign_key: true t.string :nombre t.string :descripcion t.string :direccion t.integer :numero t.string :comuna t.string :region t.string :lat t.string :lng t.timestamps end end end
class My::BooksController < ApplicationController def index @newbook = Book.new end def show @book = Book.find(params[:id]) respond_to do |format| format.html format.pdf do render pdf: @book.title, show_as_html: params.key?('debug'), margin: { top: 0, bottom: 0, left: 0, right: 0} end end end def create @book = Book.new(books_params) @book.user = current_user if @book.save redirect_to my_books_path else redirect_to my_books_path end end def update @book = Book.find(params[:id]) if @book.update(books_params) redirect_to my_book_path(@book) else render :show end end def destroy @book = Book.find(params[:id]) @book.destroy redirect_to my_books_path end private def books_params params.require(:book).permit(:title) end end