text
stringlengths
10
2.61M
# # Copyright (c) 2013, 2021, Oracle and/or its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require_relative '../../../puppet_x/oracle/solaris_providers/util/svcs.rb' # This is only a pre-configured instance of svccfg Puppet::Type.type(:ldap).provide(:solaris, :parent => Puppet::Type.type(:svccfg).provider(:solaris)) do desc "Provider for management of the LDAP client for Oracle Solaris" confine :operatingsystem => [:solaris] defaultfor :osfamily => :solaris, :kernelrelease => ['5.11'] commands :svccfg => '/usr/sbin/svccfg', :svcprop => '/usr/bin/svcprop' Ldap_fmri = "svc:/network/ldap/client".freeze mk_resource_methods def self.instances if Process.euid != 0 # Failure is presumed to be better than returning the empty # set. We expect Puppet needs to always run as root so this # may be moot outside of testing fail "LDAP configuration is not availble to non-root users" end props = {} validprops = Puppet::Type.type(:ldap).validproperties svcprop("-p", "config", "-p", "cred", Ldap_fmri).split("\n").collect do |line| data = line.split() fullprop = data[0] _type = data[1] value = if data.length > 2 data[2..-1].join(" ") end _pg, prop = fullprop.split("/") prop = prop.intern props[prop] = value if validprops.include? prop end props[:name] = "current" props[:ensure] = :present return Array new(props) end def self.prefetch(resources) things = instances resources.keys.each do |key| things.find do |prop| # key.to_s in case name uses newvalues and is converted to symbol prop.name == key.to_s end.tap do |provider| next if provider.nil? resources[key].provider = provider end end end def exists? @property_hash[:ensure] == :present end def create fail "Cannot create a new instance. Use the fixed name 'current'" end # Define getters and setters Puppet::Type.type(:ldap).validproperties.each do |field| next if [:ensure].include?(field) # get the property group pg = Puppet::Type::Ldap.propertybyname(field).pg prop_type = Puppet::Type::Ldap.propertybyname(field).prop_type # Don't define accessors, mk_resource_methods and instances pre-populate define_method(field.to_s + "=") do |should| begin value = munge_value(should, prop_type) svccfg("-s", Ldap_fmri, "setprop", "#{pg}/#{field}=", value) return value rescue => detail fail "value: #{should.inspect}\n#{detail}\n" end end end def flush svccfg("-s", Ldap_fmri, "refresh") end end
class Gdk::SubPartsMastodonStatusInfo < Gdk::SubParts DEFAULT_ICON_SIZE = 20 register def get_photo(filename) return nil unless filename path = Pathname(__dir__) / 'icon' / filename uri = Diva::URI.new('file://' + path.to_s) Plugin.collect(:photo_filter, uri, Pluggaloid::COLLECT).first end def filename(visibility) # アイコン素材取得元→ http://icooon-mono.com/license/ case visibility when 'unlisted' 'unlisted.png' when 'private' 'private.png' when 'direct' 'direct.png' else nil end end def icon_pixbuf return nil if !helper.message.respond_to?(:visibility) photo = get_photo(filename(helper.message.visibility)) photo&.pixbuf(width: icon_size.width, height: icon_size.height) end def show_icon? return true if (UserConfig[:mastodon_show_subparts_bot] && helper.message.user.respond_to?(:bot) && helper.message.user.bot) return true if (UserConfig[:mastodon_show_subparts_pin] && helper.message.respond_to?(:pinned?) && helper.message.pinned?) return true if (UserConfig[:mastodon_show_subparts_visibility] && helper.message.respond_to?(:visibility) && filename(helper.message.visibility)) false end def visibility_text(visibility) case visibility when 'unlisted' Plugin[:mastodon]._('未収載') when 'private' Plugin[:mastodon]._('非公開') when 'direct' Plugin[:mastodon]._('ダイレクト') else '' end end def initialize(*args) super @margin = 2 end def render(context) if helper.visible? && show_icon? if helper.message.user.respond_to?(:bot) && helper.message.user.bot bot_pixbuf = get_photo('bot.png')&.pixbuf(width: icon_size.width, height: icon_size.height) end if helper.message.respond_to?(:pinned?) && helper.message.pinned? pin_pixbuf = get_photo('pin.png')&.pixbuf(width: icon_size.width, height: icon_size.height) end visibility_pixbuf = icon_pixbuf context.save do context.translate(0, margin) if UserConfig[:mastodon_show_subparts_bot] && bot_pixbuf context.translate(margin, 0) context.set_source_pixbuf(bot_pixbuf) context.paint context.translate(icon_size.width + margin, 0) layout = context.create_pango_layout layout.font_description = helper.font_description(UserConfig[:mumble_basic_font]) layout.text = Plugin[:mastodon]._('bot') bot_text_width = layout.extents[1].width / Pango::SCALE context.set_source_rgb(*(UserConfig[:mumble_basic_color] || [0,0,0]).map{ |c| c.to_f / 65536 }) context.show_pango_layout(layout) context.translate(bot_text_width, 0) end if UserConfig[:mastodon_show_subparts_pin] && pin_pixbuf context.translate(margin, 0) context.set_source_pixbuf(pin_pixbuf) context.paint context.translate(icon_size.width + margin, 0) layout = context.create_pango_layout layout.font_description = helper.font_description(UserConfig[:mumble_basic_font]) layout.text = Plugin[:mastodon]._('ピン留め') pin_text_width = layout.extents[1].width / Pango::SCALE context.set_source_rgb(*(UserConfig[:mumble_basic_color] || [0,0,0]).map{ |c| c.to_f / 65536 }) context.show_pango_layout(layout) context.translate(pin_text_width, 0) end if UserConfig[:mastodon_show_subparts_visibility] && visibility_pixbuf context.translate(margin, 0) context.set_source_pixbuf(visibility_pixbuf) context.paint context.translate(icon_size.width + margin, 0) layout = context.create_pango_layout layout.font_description = helper.font_description(UserConfig[:mumble_basic_font]) layout.text = visibility_text(helper.message.visibility) context.set_source_rgb(*(UserConfig[:mumble_basic_color] || [0,0,0]).map{ |c| c.to_f / 65536 }) context.show_pango_layout(layout) end end end end def margin helper.scale(@margin) end def icon_size @icon_size ||= Gdk::Rectangle.new(0, 0, helper.scale(DEFAULT_ICON_SIZE), helper.scale(DEFAULT_ICON_SIZE)) end def height @height ||= show_icon? ? icon_size.height + 2*margin : 0 end end
require 'securerandom' class BillsController < ApplicationController before_filter :authenticate_user, :only => [:new, :index, :create, :show, :edit, :update] def index rds = RdsClient.new #TODO: change the hard-code username to be the login username. bills = rds.get_user_bills(@current_user, params[:start], params[:end]) # Should show all the bills you have for given time range @bills_by_time = BillAnalyzer.sort_bills_by_date(bills) rds.close_connection() respond_to do |format| format.html format.json { render json: JSON.pretty_generate(@bills_by_time) } end end def create bill = Bill.new(params[:bill].merge!({ bill_id: SecureRandom.uuid, create_timestamp: Time.now, is_deleted: false, username: @current_user })) rds = RdsClient.new rds.save(bill) rds.close_connection() flash[:success] = "Successfully created a Bill!!" redirect_to bills_path end def new @bill = Bill.new end def show rds = RdsClient.new bills = rds.get_user_bill_by_id(params[:id]) rds.close_connection() if bills.empty? flash[:danger] = "There is no bill with #{params[:id]}" redirect_to bills_path else @bill = bills[0] respond_to do |format| format.html format.json { render json: JSON.pretty_generate(bill: @bill.to_hash) } end end end def edit rds = RdsClient.new bills = rds.get_user_bill_by_id(params[:id]) rds.close_connection() if bills.empty? flash[:danger] = "There is no bill with #{params[:id]}" redirect_to bills_path else @bill = bills[0] end end def update bill = Bill.new(params[:bill].merge!({ bill_id: params[:id] })) rds = RdsClient.new rds.update_bill(bill) rds.close_connection() flash[:success] = "Finish updating the bill" redirect_to bill_path end end
FactoryBot.define do factory :order_item do order item sequence(:quantity) { |n| ("#{n}".to_i+1)} ordered_price { 2.5 } fulfilled { false } end factory :fulfilled_order_item, parent: :order_item do fulfilled { true } end factory :fast_fulfilled_order_item, parent: :order_item do created_at { "Wed, 03 Apr 2019 14:10:25 UTC +00:00" } updated_at { "Thu, 04 Apr 2019 14:11:25 UTC +00:00" } fulfilled { true } end factory :slow_fulfilled_order_item, parent: :order_item do created_at { "Wed, 03 Apr 2019 14:10:25 UTC +00:00" } updated_at { "Sat, 06 Apr 2019 14:11:25 UTC +00:00" } fulfilled { true } end end
FactoryGirl.define do factory :position do name { Faker::Team.creature } end end
require 'spec_helper' RSpec.describe Raven::Logger do it "should log to a given IO" do stringio = StringIO.new log = Raven::Logger.new(stringio) log.fatal("Oh noes!") expect(stringio.string).to end_with("FATAL -- sentry: ** [Raven] Oh noes!\n") end it "should allow exceptions to be logged" do stringio = StringIO.new log = Raven::Logger.new(stringio) log.fatal(Exception.new("Oh exceptions")) expect(stringio.string).to end_with("FATAL -- sentry: ** [Raven] Oh exceptions\n") end end
Given("We navigate to the login page") do visit 'http://ec2-52-15-34-101.us-east-2.compute.amazonaws.com/users/sign_in' end When("We fill valid credentials") do find_by_id('user_email').send_keys('abhishek.kanojia+1@vinsol.com') find_by_id('user_password').send_keys('1111111') click_on('Log in') end Then("The dashboard will be displayed") do confirm = find('.positive') confirm.text.include?("Signed in successfully.") end When("We enter invalid email and correct password") do find_by_id('user_email').send_keys(' ') find_by_id('user_password').send_keys('1111111') click_on('Log in') end When("We enter correct email and invalid password") do find_by_id('user_email').send_keys('abhishek.kanojia+1@vinsol.com') find_by_id('user_password').send_keys('11111') click_on('Log in') end When("We enter incorrect email and password") do find_by_id('user_email').send_keys('abhishek.kanojia') find_by_id('user_password').send_keys('11111') click_on('Log in') end Then("We should see error") do confirm = find('.negative') confirm.text.include?("Invalid Email or password.") end
require './spec/spec_helper' describe Correction do it 'takes two arguments' do Correction.new('a', 'b') end it 'has one original' do Correction.new('a', 'b').original.should == 'a' end it 'has one replacement' do Correction.new('a', 'b').replacement.should == 'b' end end
require 'spec_helper' describe VehicleData::Vin do let(:vin){ SecureRandom.hex(10) } subject{ VehicleData::Vin } it { subject.should respond_to(:decode) } context ".decode" do before(:each) do api = stub("Typhoeus") Typhoeus.stub(:get).and_return(api) end it "should send a request to decode the vin" do VehicleData::Vin.decode(vin) end end end
class Knowledge < ActiveRecord::Base searchkick callbacks: :async belongs_to :user belongs_to :customer default_scope { order('knowledges.updated_at DESC') } end
require 'open-uri' require 'nokogiri' class RealTimeWeatherData URLS = { :rogers_pass => 'http://www.avalanche.ca/feeds/glacier_dataloggers/data/RogersPassLast24Hof60M.htm' } TIME = 0 MAX_TEMP = 1 MIN_TEMP = 2 RELATIVE_HUM = 3 PRECIPITATION = 4 WIND_DIRECTION = 5 WIND_SPEED = 6 MAX_WIND_SPEED = 7 def initialize(key) raise ArgumentError.new("Key #{key} unknown.") unless URLS.include?(key) doc = Nokogiri::HTML(open(URLS[key]).read) cells = doc.xpath('//td') cells = cells[11..-1].map do |e| if e.inner_text.to_i.to_s == e.inner_text e.inner_text.to_i else e.inner_text end end @rows = [] 24.times do |i| @rows[i] = cells[i*8..(i+1)*8-1] end @columns = @rows.transpose end def hours @columns[TIME] end def max_wind_speeds @columns[MAX_WIND_SPEED] end end
require 'rails_helper' RSpec.describe Unit, type: :model do before :each do @user = create(:user) @unit = create(:unit, user: @user) @act_indicator_relation = create(:act_indicator_relation, act_id: 1, indicator_id: 1, unit: @unit, user: @user) @measurement = create(:measurement, act_indicator_relation: @act_indicator_relation, unit: @unit, user: @user) end it 'Units count' do expect(Unit.count).to eq(1) expect(@unit.name).to eq('Euro') expect(@unit.symbol).to eq('€') expect(@unit.act_indicator_relations.count).to eq(1) expect(@unit.measurements.count).to eq(1) end end
# More Stuff Exercises # Exercise 1. Write a program that checks if the sequence of characters "lab" exists in the following strings. If it does exist, print out the word. "laboratory" "experiment" "Pans Labyrinth" "elaborate" "polar bear" def check_in(word) if /lab/ =~ word puts word else puts "No match" end end check_in("laboratory") check_in("experiment") check_in("Pans Labyrinth") check_in("elaborate") check_in("polar bear") # Exercise 2. What will the following program print to the screen? What will it return? def execute(&block) block end execute { puts "Hello from inside the execute method!" } # method returns a Proc object, and the block is never executed. # Exercise 3. What is exception handling and what problem does it solve? # is a structure used to handle the possibility of an error occuring in a program # it is a way of handling the error by changing the flow of control without # exiting the program entirely. # Exercise 4. Modify the code in exercise 2 to make the block execute properly. def execute(&block) block.call end execute { puts "Hello from inside the execute method!" } # Exercise 5. Why does the following code... def execute(block) block.call end execute { puts "Hello from inside the execute method!" } Give us the following error when we run it? block.rb1:in `execute': wrong number of arguments (0 for 1) (ArgumentError) from test.rb:5:in `<main>'' # The method parameter block is missing the ampersand sign & that allows a block # to be passed as a parameter.
require "rubygems" require 'fusefs' require 'rfuse_merged_fs_opts' class RFuseMergedFS # http://rubydoc.info/gems/fusefs/0.7.0/FuseFS/MetaDir # contents( path ) # file?( path ) # directory?( path ) # read_file( path ) # size( path ) # # save # touch( path ) # can_write?(path) # write_to(path,body) # # can_delete?(path) # delete( path ) # # can_mkdir?( path ) # mkdir( path ) # can_rmdir( path ) # rmdir( path ) # def debug( msg ) if false puts msg end end def initialize( options ) debug "initialize( #{options.inspect} )" @base_dir = options.input debug " @base_dir = #{@base_dir}" end def contents(path) debug "contents( #{path} )" n_path = File.expand_path( File.join( @base_dir, path ) ) debug " Expanded path: #{n_path}" Dir.chdir( n_path ) files = Dir.glob('*') debug files.inspect #Added command to OS X Finder not to index. #files << 'metadata_never_index' return files end def file?( path ) debug "file?( #{path} )" #If path ends with metadata_never_index it is a file #if path =~ /metadata_never_index$/ # return true #end val = !( File.directory?( File.join( @base_dir, path ) ) ) debug " return #{val}" return val end def directory?( path ) debug "directory?( #{path} )" val = File.directory?( File.join( @base_dir, path ) ) debug " return #{val}" return val end def read_file( path ) debug "read_file( #{path} )" if File.exists?( File.join( @base_dir, path ) ) return File.new( File.join( @base_dir, path ) , "r").read end return "ERROR, file not found\n" end def size( path ) debug "size( #{path} )" #if File.exists?( @base_dir + path ) return File.size( File.join( @base_dir, path ) ) #else # return 16 #end end end if $0 == __FILE__ options = RFuseMergedFSOpts.parse(ARGV) filesystem = RFuseMergedFS.new( options ) FuseFS.set_root( filesystem ) # Mount under a directory given on the command line. FuseFS.mount_under options.mountpoint FuseFS.run end
class OneLine desc 'find [TERM]', 'find a recent life by character name/hash/id' option :t, :type => :string, :desc => 'tag for known players if only one life is found' option :eve, :type => :boolean, :desc => 'only eves', :default => false def find(term, tag = options[:t]) found = [] matching_lives(term) do |life, lives| next unless !options[:eve] || life.chain == 1 print_life(life, lives) found << life end tagem(found, tag) end desc 'subjects [filename]', 'find recent lives by file with term,tag pairs' def subjects(file = 'subjects.csv') CSV.foreach(file) do |row| puts headline('-', row.join(' : ')) find(row[0], row[1]) end end desc 'children [PARENT]', 'find recent lives by parent name/hash/id' def children(term) matching_lives(term) do |life, lives| lives.children(life).each do |child| log.warn headline('x', 'pedicide') if child.killer == child.parent print_life(child, lives) end end end desc 'parent [CHILD]', 'find recent lives by child name/hash/id' option :t, :type => :string, :desc => 'tag for known players if only one life is found' def parent(term) found = {} matching_lives(term) do |life, lives| if life.parent mom = lives[life.parent] print_life(mom, lives) found[mom.key] = mom end end tagem(found.values, options[:t]) end desc 'killers [VICTIM]', 'find recent lives by victim name/hash/id' option :t, :type => :string, :desc => 'tag for known players if only one life is found' def killers(term) found = {} matching_lives(term) do |life, lives| if life.killer kil = lives[life.killer] print_life(kil, lives) found[kil.key] = kil end end tagem(found.values, options[:t]) end desc 'victims [KILLER]', 'find recent lives by killer name/hash/id' option :t, :type => :string, :desc => 'tag for known players if only one life is found' def victims(term) found = History.new matching_lives(term) do |life, lives| vic = lives.victims(life) vic.each do |v| print_life(v, lives) end found.merge! vic end tagem(found.lives.values, options[:t]) end private def print_life(life, lives) log.debug life.inspect lineage = lives.ancestors(life) if log.info? log.info { lineage.take(5).map(&:name).join(', ') } log.warn Time.at(life.time) log.info { [Time.at(lineage[-1].time), lives.family(life).length] } puts "#{life.hash} #{known_players[life.hash]}" puts "" end def tagem(found, tag) if tag && found.length == 1 && !known_players[found.first.hash] hash = found.first.hash known_players[hash] = tag line = %Q%"#{hash}","#{tag}"\n% log.warn "adding #{line}" open('known-players.csv', 'a') do |f| f << line end end end end
require 'test_helper' class SubchurchesControllerTest < ActionController::TestCase setup do @subchurch = subchurches(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:subchurches) end test "should get new" do get :new assert_response :success end test "should create subchurch" do assert_difference('Subchurch.count') do post :create, subchurch: { id_no: @subchurch.id_no, subchurch_address: @subchurch.subchurch_address, subchurch_name: @subchurch.subchurch_name, subchurch_phone_no: @subchurch.subchurch_phone_no } end assert_redirected_to subchurch_path(assigns(:subchurch)) end test "should show subchurch" do get :show, id: @subchurch assert_response :success end test "should get edit" do get :edit, id: @subchurch assert_response :success end test "should update subchurch" do patch :update, id: @subchurch, subchurch: { id_no: @subchurch.id_no, subchurch_address: @subchurch.subchurch_address, subchurch_name: @subchurch.subchurch_name, subchurch_phone_no: @subchurch.subchurch_phone_no } assert_redirected_to subchurch_path(assigns(:subchurch)) end test "should destroy subchurch" do assert_difference('Subchurch.count', -1) do delete :destroy, id: @subchurch end assert_redirected_to subchurches_path end end
module Api module V1 class AccountsController < ApplicationController def update account = AccountLimitUpdateService.new( token: request.headers['Authorization'], limit: limit_params[:limit] ).update if account render( json: { message: 'Limite atualizado com sucesso!', limit: account.limit.to_f }, status: :accepted ) else render json: { message: 'Não autorizado!' }, status: :forbidden end end def deposit deposit_transaction = AccountDepositService.new( token: request.headers['Authorization'], amount: deposit_params[:amount] ).deposit if deposit_transaction render( json: { message: 'Depósito realizado com sucesso!', amount: deposit_transaction.amount.to_i, balance: deposit_transaction.account.balance.to_f }, status: :created ) else render json: { message: 'Depósito não autorizado!' }, status: :forbidden end end def transfer debit_transaction, credit_transaction = AccountTransferService.new( token: request.headers['Authorization'], destiny_branch: transfer_params[:destiny_branch], destiny_account_number: transfer_params[:destiny_account_number], amount: transfer_params[:amount] ).transfer if debit_transaction && credit_transaction origin_balance = debit_transaction.account.reload.balance.to_f render( json: { message: 'Transferência realizada com sucesso!', amount: debit_transaction.amount.to_i.abs, balance: origin_balance, transfer_to: credit_transaction.account.user.full_name }, status: :created ) else render json: { message: 'Transferência não autorizada!' }, status: :forbidden end end def statement statement = AccountStatementService.new( token: request.headers['Authorization'], days: statement_params[:days] ).statement if statement days = statement_params[:days] render( json: { message: "Saldo do(s) último(s) #{days} dia(s)", statement: normalized_statement(statement) }, status: :ok ) else render json: { message: 'Não foi possível verificar seu extrato.' }, status: :not_found end end def balance token = request.headers['Authorization'] user = User.find_by(token: token) if user render json: { balance: user.account.balance.to_f }, status: :ok else render json: { message: 'Erro. Contate o administrador.' }, status: :forbidden end end private def normalized_statement(statement) transactions_message = [] statement.each do |s| transactions_message << "#{s.created_at.strftime('%d/%m/%Y')} | " \ "#{s.transaction_type.capitalize} | " \ "R$ #{s.amount}" end transactions_message end def limit_params params.permit(:limit) end def deposit_params params.permit(:amount) end def transfer_params params.permit(:destiny_branch, :destiny_account_number, :amount) end def statement_params params.permit(:days) end end end end
class Api::LtiDeploymentsController < Api::ApiApplicationController load_and_authorize_resource :application_instance load_and_authorize_resource :lti_deployment, through: :application_instance, parent: false def index per_page = 100 @lti_deployments = @lti_deployments. order(created_at: :desc). paginate(page: params[:page], per_page: per_page) lti_deployments_json = @lti_deployments.map do |lti_deployment| json_for(lti_deployment) end render json: { lti_deployment_keys: lti_deployments_json, total_pages: @lti_deployments.total_pages, per_page: per_page, } end def show respond_with_json end def create @lti_deployment.save! respond_with_json end def update @lti_deployment.update(lti_deployment_params) respond_with_json end def destroy @lti_deployment.destroy render json: { head: :ok } end private def respond_with_json @lti_deployments = [@lti_deployment] render json: json_for(@lti_deployment) end def json_for(lti_deployment) lti_deployment.as_json end def lti_deployment_params params.require(:lti_deployment).permit( :deployment_id, :lti_install_id, ) end end
class BookmarksController < ApplicationController include Authenticatable before_action :lookup_bookmarks, only: [:index, :show] before_action :lookup_bookmark, only: [:edit, :update, :destroy] # GET /bookmarks # GET /bookmarks.json def index respond_to do |format| format.html { render :index } format.json { render json: Bookmark.export(current_user.bookmarks), status: :unprocessable_entity } end end # GET /bookmarks/1 # GET /bookmarks/1.json def show end # GET /bookmarks/new def new @bookmark = Bookmark.new(params.permit(:tag)) end # GET /bookmarks/1/edit def edit end # POST /bookmarks # POST /bookmarks.json def create @bookmark = current_user.bookmarks.new(bookmark_params) respond_to do |format| if @bookmark.save format.html { redirect_to bookmark_path(@bookmark.tag), notice: "ADDED #{@bookmark.title}" } format.json { render :show, status: :created, location: @bookmark } else format.html { render :new } format.json { render json: @bookmark.errors, status: :unprocessable_entity } end end end # PATCH/PUT /bookmarks/1 # PATCH/PUT /bookmarks/1.json def update respond_to do |format| if @bookmark.update(bookmark_params) format.html { redirect_to bookmark_path(@bookmark.tag), notice: "UPDATED #{@bookmark.title}"} format.json { render :show, status: :ok, location: @bookmark } else format.html { render :edit } format.json { render json: @bookmark.errors, status: :unprocessable_entity } end end end # DELETE /bookmarks/1 # DELETE /bookmarks/1.json def destroy @bookmark.destroy respond_to do |format| format.html { redirect_to bookmarks_url, notice: "REMOVED #{@bookmark.title}" } format.json { head :no_content } end end private def lookup_bookmarks @tags = Bookmark.hashify_for(current_user) @subtags = @tags[params[:id]] end # Use callbacks to share common setup or constraints between actions. def lookup_bookmark @bookmark = current_user.bookmarks.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def bookmark_params params.require(:bookmark).permit(:title, :url, :tag, :subtag) end end
FactoryGirl.define do factory :organization do name Organization::MULTUNUS end end
# frozen_string_literal: true class Widget < ApplicationRecord belongs_to :user validates :name, presence: true def to_json(*_args) { id: id, name: name, } end end
# @param {Integer[]} target # @param {Integer[]} arr # @return {Boolean} # [1] # [1,2] # [2,1] # [1,2,3] # [1,3,2] # [3,2,1] # permutations, O(n!) def can_be_equal(target, arr) return true if target == arr permutations = [target,target.reverse] size = target.length (0...size).each do |idx| el = target[idx] (0...size).each do |pos| permutations << target[0...pos] + [el] + target[pos+1..-1] end end p permutations permutations.include?(arr) end # @param {Integer[]} target # @param {Integer[]} arr # @return {Boolean} # permutations, O(n!) def can_be_equal(target, arr) return true if target == arr permutations = target.permutation(target.size).to_a permutations.include?(arr) end def can_be_equal(target,arr) target.sort == arr.sort end
require 'rails_helper' RSpec.feature "Contacts", type: :feature do scenario "user no fill, and click submit, show alert" do visit root_path click_link 'お問い合わせ' click_button 'この内容で送信する' expect(page).to have_content '入力内容をご確認ください' end scenario "user don't fill name, and click submit, show alert name" do visit root_path click_link 'お問い合わせ' fill_in 'contact_email', with: 'some@email.com' fill_in 'contact_message', with: 'some message' click_button 'この内容で送信する' expect(page).to have_content 'お名前を入力してください' end scenario "user don't fill email, and click submit, show alert email" do visit root_path click_link 'お問い合わせ' fill_in 'contact_name', with: 'some name' fill_in 'contact_message', with: 'some message' click_button 'この内容で送信する' expect(page).to have_content 'メールアドレスを入力してください' end scenario "user don't fill message, and click submit, show alert message" do visit root_path click_link 'お問い合わせ' fill_in 'contact_name', with: 'some name' fill_in 'contact_email', with: 'some@email.com' click_button 'この内容で送信する' expect(page).to have_content 'お問い合わせ内容を入力してください' end scenario "user click submit, show confirm page" do visit root_path click_link 'お問い合わせ' fill_in 'contact_name', with: 'some name' fill_in 'contact_email', with: 'some@email.com' fill_in 'contact_message', with: 'some message' click_button 'この内容で送信する' expect(page).to have_button '戻る' end scenario "user click back button, show contact index page" do visit root_path click_link 'お問い合わせ' fill_in 'contact_name', with: 'some name' fill_in 'contact_email', with: 'some@email.com' fill_in 'contact_message', with: 'some message' click_button 'この内容で送信する' click_button '戻る' expect(page).to have_content 'ご覧いただきありがとうございます' end scenario "user once show alert, and click submit, after that click back button, show contact index page with filled data " do visit root_path click_link 'お問い合わせ' fill_in 'contact_name', with: 'some name' fill_in 'contact_email', with: 'some@email.com' click_button 'この内容で送信する' fill_in 'contact_message', with: 'some message' click_button 'この内容で送信する' click_button '戻る' expect(page).to have_field 'お名前', with: 'some name' expect(page).to have_field 'メールアドレス(半角)', with: 'some@email.com' expect(page).to have_field 'お問い合わせ内容', with: 'some message' end scenario "user click submit at confirm page, show contact create page" do visit root_path click_link 'お問い合わせ' fill_in 'contact_name', with: 'some name' fill_in 'contact_email', with: 'some@email.com' fill_in 'contact_message', with: 'some message' click_button 'この内容で送信する' click_button 'この内容で送信する' expect(page).to have_content 'お問い合わせを承りました' end end
class ContactController < ApplicationController def new @contact = ContactForm.new end def send_question @contact = ContactForm.new(contact_form_params) if @contact.valid? ContactMailer.contact_email(@contact).deliver redirect_to thank_you_path else render 'new' end end private def contact_form_params params.require(:contact_form).permit :email, :name, :message end end
require 'raw_string' def hammingDistance s, t sb = s.pack("c*").unpack("B*").join.chars tb = t.pack("c*").unpack("B*").join.chars dist = 0 for i in 0..([sb.length, tb.length].min - 1) if sb[i] != tb[i] dist += 1 end end return dist + (sb.length - tb.length).abs end # Tries to find the key size based on hamming distance between blocks. # Input: raw string: the string to XOR against # Input: [integer, integer]: key_length: the key length search interval (inclusive) # Input: integer: samples: the number of samples to take. This guides the keysize guesses. # Input: integer: results: the number of keysizes to return. # Output: keysize: the assumed key size def xor_keysize(raw_string, key_length, samples: 1, results: 3) results = [results, key_length.max - key_length.min].min keysizes = [] for length in key_length[0]..key_length[1] current_score = 0 sample1 = raw_string.value[0, length] samples.times do |sample_index| sample2 = raw_string.value[(sample_index+1)*length, length] current_score += sample1.to_raw.hamming_dist(sample2.to_raw) sample1 = sample2 end current_score /= length.to_f current_score /= samples.to_f keysizes.append([length, current_score]) end keysizes.sort_by { |elem| elem[1] }[0, results] end # Bruteforces the key based on some user defined metric. # Uses divide and conquer to exploit knowing the key length. # Input: raw string: the string to XOR against # Input: integer: key_length: the key length # Input (optional): [integer, integer]: key_value: the key value search interval (inclusive) (individual characters) # Input (optional), yield: fn -> number: yields a raw_string and expects to be returned a score, # for instance, a measure of character frequency. The score is maximized. # Output: raw string: the found key def xor_key_brute_daq(raw_string, key_length, key_value: [0, 255]) key = RawString.new("") key_length.times do |key_index| (key_index..raw_string.value.length).step(key_length).map do |data_index| raw_string.value[data_index] end.join.to_raw => data key_fragment = xor_key_brute(data, key_length: [1, 1], key_value: key_value) do |rs| yield(rs) end key = key.append(key_fragment) end key end # Bruteforces the key based on some user defined metric. # Input: raw string: the string to XOR against # Input (optional): [integer, integer]: key_length: the key length search interval (inclusive) # Input (optional): [integer, integer]: key_value: the key value search interval (inclusive) (individual characters) # Input (optional), yield: fn -> number: yields a raw_string and expects to be returned a score, # for instance, a measure of character frequency. The score is maximized. # Output: raw string: the found key def xor_key_brute(raw_string, key_length: [1, 1], key_value: [0, 255]) best_key = nil best_score = -1 value_interval_size = key_value[1] - key_value[0] for length in key_length[0]..key_length[1] (value_interval_size ** length).times do |value| current_key_bytes = get_key(value, length, key_value) current_key_str = current_key_bytes.pack("c*") current_key = RawString.new(current_key_str) xor_string = raw_string ^ current_key current_score = yield(xor_string) if best_score < current_score best_score = current_score best_key = current_key end end end best_key end # Cycles through all possible keys. # Can be thought of as the "key_index":ed number in base "key value's interval size" # with a modulo of "key value's interval size"^length. # In total there are "key value's interval size"^length different keys. # E.g. # get_key(0, 3, [0, 1]) => [0, 0, 0] # get_key(1, 3, [0, 1]) => [1, 0, 0] # get_key(2, 3, [0, 1]) => [0, 1, 0] # get_key(3, 3, [0, 1]) => [1, 1, 0] # get_key(3, 2, [0, 1]) => [1, 1] # get_key(3, 2, [0, 3]) => [3, 0] # # Input: integer: key_index: where in the cycle we are # Input: integer: length: how long the key is at most # Input: [integer, integer]: key_value: the key value search interval (inclusive) (individual characters) # Output: integer array: the key at the given position def get_key(key_index, length, key_value) value_interval_size = key_value[1] - key_value[0] previous_keys_sum = 0 current_key = Array.new(length) do |index| value = ((key_index - previous_keys_sum) % ((value_interval_size + 1) ** (index + 1))) / ((value_interval_size + 1) ** index) previous_keys_sum += value value end current_key.map { |value| value + key_value[0] } end
#encoding: utf-8 module PageCell class Parser < Temple::Parser WHITE_SPACE = /(?:&#160;|&nbsp;|\s)*/ CODE = /^#{TAG_START}#{WHITE_SPACE}(\w+)#{WHITE_SPACE}(.*)?#{WHITE_SPACE}#{TAG_END}$/om COMMENT = /^#{TAG_START}#{WHITE_SPACE}#(.*?)#{WHITE_SPACE}#{TAG_END}$/om DYNAMIC = /^#{DYNAMIC_START}#{WHITE_SPACE}(.*?)#{WHITE_SPACE}#{DYNAMIC_END}$/om #class SyntaxError < StandardError #def initialize(message, position) #@message = message #@lineno, @column, @line = position #@stripped_line = @line.strip #@stripped_column = @column - (@line.size - @line.lstrip.size) #end #def to_s #<<-EOF ##{@message} #Line #{@lineno} ##{@stripped_line} ##{' ' * @stripped_column}^ #EOF #end #end def call(template) parse(template) end def parse(template) tokens = tokenize(template) return [] if tokens.empty? sexps = [:multi] while token = tokens.shift case token when COMMENT #nothing #sexps << [:pagecell,:comment,$1] when CODE case $1.downcase.to_s.strip when 'render' sexps << [:pagecell,:render,$2.to_s.strip] else sexps << [:pagecell,:code,$1.to_s.strip,$2.to_s.strip] end when DYNAMIC sexps << [:pagecell,:dynamic,$1.to_s.strip] else sexps << [:pagecell,:static,token] end end sexps end private def tokenize(source) source = source.source if source.respond_to?(:source) return [] if source.to_s.empty? source.to_s.strip.split(TEMPLATE_PARSER) end end end
class OrderAddress include ActiveModel::Model attr_accessor :streetadoress, :postalcade, :cities, :buildname, :user_id, :token, :prefectures_id, :streetadores, :phonename, :item_id with_options presence: true do validates :user_id validates :postalcade, format: {with: /\A[0-9]{3}-[0-9]{4}\z/, message: "is invalid. Include hyphen(-)"} validates :token validates :prefectures_id, numericality: {other_than: 0} validates :cities validates :streetadoress validates :phonename, numericality: {only_number: true}, length: { maximum: 11 } validates :item_id end def save order = Order.create(user_id: user_id, item_id: item_id) Address.create(postalcade: postalcade, cities: cities, streetadoress: streetadoress, buildname: buildname, order_id: order.id, prefectures_id: prefectures_id, phonename: phonename) end end
class Rate < ActiveRecord::Base VALID_CURRENCY = ['SEK', 'NOK', 'EUR'] def self.at(date, base_currency, counter_currency) return 1 if base_currency == counter_currency date = Date.parse date raise ArgumentError, 'Invalid date' if Date.today < date raise ArgumentError, 'Invalid currency' unless(VALID_CURRENCY.include?(base_currency) && VALID_CURRENCY.include?(counter_currency)) search_result = Rate.where(date: date, base_currency: base_currency, counter_currency: counter_currency) raise ActiveRecord::RecordNotFound, 'no exchange rate was found for the data provided' if search_result.empty? search_result.first.rate end end
class Match < ApplicationRecord validates :outcome, presence: true validates :user_class, presence: true validates :opp_class, presence: true end
class MicropostsController < ApplicationController before_filter :signed_in_user, only: [:create, :destroy] before_filter :correct_user, only: :destroy caches_page :index,:correct_user,:create def index end def create @micropost = current_user.microposts.build(params[:micropost]) expire_page :action => :create if @micropost.save flash[:success] = "Micropost created!" redirect_to root_url else @feed_items = [] render 'static_pages/home' end end def destroy @micropost.destroy redirect_to root_url end def correct_user @micropost = current_user.microposts.find_by_id(params[:id]) rescue redirect_to root_url end private def signed_in_user unless signed_in? store_location redirect_to signin_url, notice: "Please sign in." end end end
class ChangeOptionToGenderIdInInterests < ActiveRecord::Migration def change rename_column :interests, :option, :gender_id change_column :interests, :gender_id, :integer end end
module Plympton # Class responsible for parsing a YAML serialized chunk object class Chunk # YAML entries attr_accessor :startEA, :endEA, :blockList, :numBlocks # Defines the objects YAML tag # @return [String] A string signifying the start of an object of this class def to_yaml_type "!fuzz.io,2011/Chunk" end # Convenience method for printing a chunk # @return [String] A string representation of a chunk object def to_s() "#{self.class} (#{self.__id__}):" end end end
module Signatory module API class Connection < ActiveResource::Connection private def new_http Signatory.credentials.token end def apply_ssl_options(http) http #noop end def request(method, path, *arguments) path += path.index('?') ? '&' : '?' path += "api_version=#{Signatory.credentials.api_version}" super(method, path, *arguments) end end end end
require 'rails_helper' RSpec.describe Exercise, type: :model do it { should have_valid(:name).when('Bench Press') } it { should have_valid(:category).when('Chest') } it { should have_valid(:description).when('Lay down on bench with bar above chest') } it { should have_valid(:muscles).when('Pectoralis major') } end
module IControl::Networking ## # The SelfIPPortLockdown interface enables you to lock down protocols and ports on # self IP addresses. class SelfIPPortLockdown < IControl::Base set_id_name "access_lists" class ProtocolPort < IControl::Base::Struct; end class SelfIPAccess < IControl::Base::Struct; end class AllowModeSequence < IControl::Base::Sequence ; end class ProtocolPortSequence < IControl::Base::Sequence ; end class SelfIPAccessSequence < IControl::Base::Sequence ; end # A list of access modes. class AllowMode < IControl::Base::Enumeration; end ## # Adds the list of access methods, with optional protocols/ports, for this self IPs. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def add_allow_access_list super end ## # Adds to the default list of protocols/ports on which access is allowed. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::Networking::SelfIPPortLockdown::ProtocolPort] :defaults The defaults protocols/ports to add. def add_default_protocol_port_access_list(opts) opts = check_params(opts,[:defaults]) super(opts) end ## # Deletes protocols and ports from the allow access list for this self IPs. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def delete_allow_access_list super end ## # Gets the access list for this self IPs. # @rspec_example # @return [SelfIPAccess] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [String] :self_ips The self IPs . def allow_access_list(opts) opts = check_params(opts,[:self_ips]) super(opts) end ## # Gets the default protocol/port access list on which access is allowed. # @rspec_example # @return [ProtocolPort] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def default_protocol_port_access_list super end ## # Gets the version information for this interface. # @rspec_example # @return [String] def version super end ## # Remove protocols and ports from the default list of protocols/ports on which access # is allowed. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::Networking::SelfIPPortLockdown::ProtocolPort] :defaults The defaults protocols/ports to remove. def remove_default_protocol_port_access_list(opts) opts = check_params(opts,[:defaults]) super(opts) end ## # A structure that defines protocol / port combination. # @attr [IControl::Common::ProtocolType] protocol The protocol on which access is allowed. # @attr [Numeric] port The port for which access is allowed. class ProtocolPort < IControl::Base::Struct icontrol_attribute :protocol, IControl::Common::ProtocolType icontrol_attribute :port, Numeric end ## # A structure that defines the access mode for the specified self IP. # @attr [String] self_ip The self IP address. # @attr [IControl::Networking::SelfIPPortLockdown::AllowMode] mode The access mode for the self IP. # @attr [IControl::Networking::SelfIPPortLockdown::ProtocolPortSequence] protocol_ports The list of protocols/ports for which access is allowed. class SelfIPAccess < IControl::Base::Struct icontrol_attribute :self_ip, String icontrol_attribute :mode, IControl::Networking::SelfIPPortLockdown::AllowMode icontrol_attribute :protocol_ports, IControl::Networking::SelfIPPortLockdown::ProtocolPortSequence end ## A sequence of access modes. class AllowModeSequence < IControl::Base::Sequence ; end ## A sequence of protocol/port structures. class ProtocolPortSequence < IControl::Base::Sequence ; end ## A sequence of self IP access modes. class SelfIPAccessSequence < IControl::Base::Sequence ; end # A list of access modes. class AllowMode < IControl::Base::Enumeration # Access to the self IP is allowed through the specified protocol/port. ALLOW_MODE_PROTOCOL_PORT = :ALLOW_MODE_PROTOCOL_PORT # Allow no access to the self IP. ALLOW_MODE_NONE = :ALLOW_MODE_NONE # Allow access to the self IP using a pre-determined set of protocols/ports. ALLOW_MODE_DEFAULTS = :ALLOW_MODE_DEFAULTS # Allow full access to the self IP. ALLOW_MODE_ALL = :ALLOW_MODE_ALL end end end
class OpenSourceStats class Organization < OpenSourceStats::User attr_accessor :name def initialize(name) @name = name end end end
require File.dirname(__FILE__) + '/../test_helper' class MovieTest < ActiveSupport::TestCase should_have_many :shows should_have_many :theaters, :through => :shows should_validate_presence_of :name end
require_relative '../test_helper' class ProjectMedia6Test < ActiveSupport::TestCase def setup require 'sidekiq/testing' Sidekiq::Testing.fake! super create_team_bot login: 'keep', name: 'Keep' create_verification_status_stuff end test "should get creator name based on channel" do RequestStore.store[:skip_cached_field_update] = false Sidekiq::Testing.inline! do u = create_user pm = create_project_media user: u assert_equal pm.creator_name, u.name pm2 = create_project_media user: u, channel: { main: CheckChannels::ChannelCodes::WHATSAPP } assert_equal pm2.creator_name, 'Tipline' pm3 = create_project_media user: u, channel: { main: CheckChannels::ChannelCodes::FETCH } assert_equal pm3.creator_name, 'Import' # update cache based on user update u.name = 'update name' u.save! assert_equal pm.creator_name, 'update name' assert_equal pm.creator_name(true), 'update name' assert_equal pm2.creator_name, 'Tipline' assert_equal pm2.creator_name(true), 'Tipline' assert_equal pm3.creator_name, 'Import' assert_equal pm3.creator_name(true), 'Import' User.delete_check_user(u) assert_equal pm.creator_name, 'Anonymous' assert_equal pm.reload.creator_name(true), 'Anonymous' assert_equal pm2.creator_name, 'Tipline' assert_equal pm2.creator_name(true), 'Tipline' assert_equal pm3.creator_name, 'Import' assert_equal pm3.creator_name(true), 'Import' end end test "should create blank item" do assert_difference 'ProjectMedia.count' do assert_difference 'Blank.count' do ProjectMedia.create! media_type: 'Blank', team: create_team end end end test "should convert old hash" do t = create_team pm = create_project_media team: t Team.any_instance.stubs(:settings).returns(ActionController::Parameters.new({ media_verification_statuses: { statuses: [] } })) assert_nothing_raised do pm.custom_statuses end Team.any_instance.unstub(:settings) end test "should assign item to default project if project not set" do t = create_team pm = create_project_media team: t assert_equal pm.project, t.default_folder end test "should detach similar items when trash parent item" do setup_elasticsearch RequestStore.store[:skip_delete_for_ever] = true t = create_team default_folder = t.default_folder p = create_project team: t pm = create_project_media project: p, disable_es_callbacks: false pm1_c = create_project_media project: p, disable_es_callbacks: false pm1_s = create_project_media project: p, disable_es_callbacks: false pm2_s = create_project_media project: p, disable_es_callbacks: false r = create_relationship source: pm, target: pm1_c, relationship_type: Relationship.confirmed_type r2 = create_relationship source: pm, target: pm1_s, relationship_type: Relationship.suggested_type r3 = create_relationship source: pm, target: pm2_s, relationship_type: Relationship.suggested_type assert_difference 'Relationship.count', -2 do pm.archived = CheckArchivedFlags::FlagCodes::TRASHED pm.save! end assert_raises ActiveRecord::RecordNotFound do r2.reload end assert_raises ActiveRecord::RecordNotFound do r3.reload end pm1_s = pm1_s.reload; pm2_s.reload assert_equal CheckArchivedFlags::FlagCodes::TRASHED, pm1_c.reload.archived assert_equal CheckArchivedFlags::FlagCodes::NONE, pm1_s.archived assert_equal CheckArchivedFlags::FlagCodes::NONE, pm2_s.archived assert_equal p.id, pm1_s.project_id assert_equal p.id, pm2_s.project_id # Verify ES result = $repository.find(get_es_id(pm1_c)) assert_equal CheckArchivedFlags::FlagCodes::TRASHED, result['archived'] result = $repository.find(get_es_id(pm1_s)) assert_equal CheckArchivedFlags::FlagCodes::NONE, result['archived'] assert_equal p.id, result['project_id'] result = $repository.find(get_es_id(pm2_s)) assert_equal CheckArchivedFlags::FlagCodes::NONE, result['archived'] assert_equal p.id, result['project_id'] end test "should detach similar items when spam parent item" do setup_elasticsearch RequestStore.store[:skip_delete_for_ever] = true t = create_team default_folder = t.default_folder p = create_project team: t pm = create_project_media project: p, disable_es_callbacks: false pm1_c = create_project_media project: p, disable_es_callbacks: false pm1_s = create_project_media project: p, disable_es_callbacks: false pm2_s = create_project_media project: p, disable_es_callbacks: false r = create_relationship source: pm, target: pm1_c, relationship_type: Relationship.confirmed_type r2 = create_relationship source: pm, target: pm1_s, relationship_type: Relationship.suggested_type r3 = create_relationship source: pm, target: pm2_s, relationship_type: Relationship.suggested_type assert_difference 'Relationship.count', -2 do pm.archived = CheckArchivedFlags::FlagCodes::SPAM pm.save! end assert_raises ActiveRecord::RecordNotFound do r2.reload end assert_raises ActiveRecord::RecordNotFound do r3.reload end pm1_s = pm1_s.reload; pm2_s.reload assert_equal CheckArchivedFlags::FlagCodes::SPAM, pm1_c.reload.archived assert_equal CheckArchivedFlags::FlagCodes::NONE, pm1_s.archived assert_equal CheckArchivedFlags::FlagCodes::NONE, pm2_s.archived assert_equal p.id, pm1_s.project_id assert_equal p.id, pm2_s.project_id # Verify ES result = $repository.find(get_es_id(pm1_c)) assert_equal CheckArchivedFlags::FlagCodes::SPAM, result['archived'] result = $repository.find(get_es_id(pm1_s)) assert_equal CheckArchivedFlags::FlagCodes::NONE, result['archived'] assert_equal p.id, result['project_id'] result = $repository.find(get_es_id(pm2_s)) assert_equal CheckArchivedFlags::FlagCodes::NONE, result['archived'] assert_equal p.id, result['project_id'] end test "should get cluster size" do pm = create_project_media assert_nil pm.reload.cluster c = create_cluster c.project_medias << pm assert_equal 1, pm.reload.cluster.size c.project_medias << create_project_media assert_equal 2, pm.reload.cluster.size end test "should get cluster teams" do RequestStore.store[:skip_cached_field_update] = false setup_elasticsearch t1 = create_team t2 = create_team pm1 = create_project_media team: t1 assert_nil pm1.cluster c = create_cluster project_media: pm1 c.project_medias << pm1 assert_equal [t1.name], pm1.cluster.team_names.values assert_equal [t1.id], pm1.cluster.team_names.keys sleep 2 id = get_es_id(pm1) es = $repository.find(id) assert_equal [t1.id], es['cluster_teams'] pm2 = create_project_media team: t2 c.project_medias << pm2 sleep 2 assert_equal [t1.name, t2.name].sort, pm1.cluster.team_names.values.sort assert_equal [t1.id, t2.id].sort, pm1.cluster.team_names.keys.sort es = $repository.find(id) assert_equal [t1.id, t2.id], es['cluster_teams'] end test "should complete media if there are pending tasks" do pm = create_project_media s = pm.last_verification_status_obj create_task annotated: pm, required: true assert_equal 'undetermined', s.reload.get_field('verification_status_status').status assert_nothing_raised do s.status = 'verified' s.save! end end test "should get account from author URL" do s = create_source pm = create_project_media assert_nothing_raised do pm.send :account_from_author_url, @url, s end end test "should not move media to active status if status is locked" do pm = create_project_media assert_equal 'undetermined', pm.last_verification_status s = pm.last_verification_status_obj s.locked = true s.save! create_task annotated: pm, disable_update_status: false assert_equal 'undetermined', pm.reload.last_verification_status end test "should have status permission" do u = create_user t = create_team p = create_project team: t pm = create_project_media project: p with_current_user_and_team(u, t) do permissions = JSON.parse(pm.permissions) assert permissions.has_key?('update Status') end end test "should not crash if media does not have status" do pm = create_project_media Annotation.delete_all assert_nothing_raised do assert_nil pm.last_verification_status_obj end end test "should have relationships and parent and children reports" do p = create_project s1 = create_project_media project: p s2 = create_project_media project: p t1 = create_project_media project: p t2 = create_project_media project: p create_project_media project: p create_relationship source_id: s1.id, target_id: t1.id create_relationship source_id: s2.id, target_id: t2.id assert_equal [t1], s1.targets assert_equal [t2], s2.targets assert_equal [s1], t1.sources assert_equal [s2], t2.sources end test "should return related" do pm = create_project_media pm2 = create_project_media assert_nil pm.related_to pm.related_to_id = pm2.id assert_equal pm2, pm.related_to end test "should include extra attributes in serialized object" do pm = create_project_media pm.related_to_id = 1 dump = YAML::dump(pm) assert_match /related_to_id/, dump end test "should skip screenshot archiver" do create_annotation_type_and_fields('Pender Archive', { 'Response' => ['JSON', false] }) l = create_link t = create_team t.save! BotUser.delete_all tb = create_team_bot login: 'keep', set_settings: [{ name: 'archive_pender_archive_enabled', type: 'boolean' }], set_approved: true tbi = create_team_bot_installation user_id: tb.id, team_id: t.id tbi.set_archive_pender_archive_enabled = false tbi.save! pm = create_project_media project: create_project(team: t), media: l assert pm.should_skip_create_archive_annotation?('pender_archive') end test "should destroy project media when associated_id on version is not valid" do with_versioning do m = create_valid_media t = create_team p = create_project team: t u = create_user create_team_user user: u, team: t, role: 'admin' pm = nil with_current_user_and_team(u, t) do pm = create_project_media project: p, media: m, user: u pm.source_id = create_source(team_id: t.id).id pm.save assert_equal 3, pm.versions.count end version = pm.versions.last version.update_attribute('associated_id', 100) assert_nothing_raised do pm.destroy end end end # https://errbit.test.meedan.com/apps/581a76278583c6341d000b72/problems/5ca644ecf023ba001260e71d # https://errbit.test.meedan.com/apps/581a76278583c6341d000b72/problems/5ca4faa1f023ba001260dbae test "should create claim with Indian characters" do str1 = "_Buy Redmi Note 5 Pro Mobile at *2999 Rs* (95�\u0000off) in Flash Sale._\r\n\r\n*Grab this offer now, Deal valid only for First 1,000 Customers. Visit here to Buy-* http://sndeals.win/" str2 = "*प्रधानमंत्री छात्रवृति योजना 2019*\n\n*Scholarship Form for 10th or 12th Open Now*\n\n*Scholarship Amount*\n1.50-60�\u0000- Rs. 5000/-\n2.60-80�\u0000- Rs. 10000/-\n3.Above 80�\u0000- Rs. 25000/-\n\n*सभी 10th और 12th के बच्चो व उनके अभिभावकों को ये SMS भेजे ताकि सभी बच्चे इस योजना का लाभ ले सके*\n\n*Click Here for Apply:*\nhttps://bit.ly/2l71tWl" [str1, str2].each do |str| assert_difference 'ProjectMedia.count' do m = create_claim_media quote: str create_project_media media: m end end end test "should not create project media with unsafe URL" do WebMock.disable_net_connect! allow: [CheckConfig.get('storage_endpoint')] url = 'http://unsafe.com/' pender_url = CheckConfig.get('pender_url_private') + '/api/medias' response = '{"type":"error","data":{"code":12}}' WebMock.stub_request(:get, pender_url).with({ query: { url: url } }).to_return(body: response) WebMock.stub_request(:get, pender_url).with({ query: { url: url, refresh: '1' } }).to_return(body: response) assert_raises RuntimeError do pm = create_project_media media: nil, url: url assert_equal 12, pm.media.pender_error_code end end test "should get metadata" do pender_url = CheckConfig.get('pender_url_private') + '/api/medias' url = 'https://twitter.com/test/statuses/123456' response = { 'type' => 'media', 'data' => { 'url' => url, 'type' => 'item', 'title' => 'Media Title', 'description' => 'Media Description' } }.to_json WebMock.stub_request(:get, pender_url).with({ query: { url: url } }).to_return(body: response) l = create_link url: url pm = create_project_media media: l assert_equal 'Media Title', l.metadata['title'] assert_equal 'Media Description', l.metadata['description'] assert_equal 'Media Title', pm.media.metadata['title'] assert_equal 'Media Description', pm.media.metadata['description'] pm.analysis = { title: 'Project Media Title', content: 'Project Media Description' } pm.save! l = Media.find(l.id) pm = ProjectMedia.find(pm.id) assert_equal 'Media Title', l.metadata['title'] assert_equal 'Media Description', l.metadata['description'] assert_equal 'Project Media Title', pm.analysis['title'] assert_equal 'Project Media Description', pm.analysis['content'] end test "should cache and sort by demand" do setup_elasticsearch RequestStore.store[:skip_cached_field_update] = false team = create_team p = create_project team: team create_annotation_type_and_fields('Smooch', { 'Data' => ['JSON', false] }) pm = create_project_media team: team, project_id: p.id, disable_es_callbacks: false ms_pm = get_es_id(pm) assert_queries(0, '=') { assert_equal(0, pm.demand) } create_dynamic_annotation annotation_type: 'smooch', annotated: pm assert_queries(0, '=') { assert_equal(1, pm.demand) } pm2 = create_project_media team: team, project_id: p.id, disable_es_callbacks: false ms_pm2 = get_es_id(pm2) assert_queries(0, '=') { assert_equal(0, pm2.demand) } 2.times { create_dynamic_annotation(annotation_type: 'smooch', annotated: pm2) } assert_queries(0, '=') { assert_equal(2, pm2.demand) } # test sorting result = $repository.find(ms_pm) assert_equal result['demand'], 1 result = $repository.find(ms_pm2) assert_equal result['demand'], 2 result = CheckSearch.new({projects: [p.id], sort: 'demand'}.to_json, nil, team.id) assert_equal [pm2.id, pm.id], result.medias.map(&:id) result = CheckSearch.new({projects: [p.id], sort: 'demand', sort_type: 'asc'}.to_json, nil, team.id) assert_equal [pm.id, pm2.id], result.medias.map(&:id) r = create_relationship source_id: pm.id, target_id: pm2.id, relationship_type: Relationship.confirmed_type assert_equal 1, pm.reload.requests_count assert_equal 2, pm2.reload.requests_count assert_queries(0, '=') { assert_equal(3, pm.demand) } assert_queries(0, '=') { assert_equal(3, pm2.demand) } pm3 = create_project_media team: team, project_id: p.id ms_pm3 = get_es_id(pm3) assert_queries(0, '=') { assert_equal(0, pm3.demand) } 2.times { create_dynamic_annotation(annotation_type: 'smooch', annotated: pm3) } assert_queries(0, '=') { assert_equal(2, pm3.demand) } create_relationship source_id: pm.id, target_id: pm3.id, relationship_type: Relationship.confirmed_type assert_queries(0, '=') { assert_equal(5, pm.demand) } assert_queries(0, '=') { assert_equal(5, pm2.demand) } assert_queries(0, '=') { assert_equal(5, pm3.demand) } create_dynamic_annotation annotation_type: 'smooch', annotated: pm3 assert_queries(0, '=') { assert_equal(6, pm.demand) } assert_queries(0, '=') { assert_equal(6, pm2.demand) } assert_queries(0, '=') { assert_equal(6, pm3.demand) } r.destroy! assert_queries(0, '=') { assert_equal(4, pm.demand) } assert_queries(0, '=') { assert_equal(2, pm2.demand) } assert_queries(0, '=') { assert_equal(4, pm3.demand) } assert_queries(0, '>') { assert_equal(4, pm.demand(true)) } assert_queries(0, '>') { assert_equal(2, pm2.demand(true)) } assert_queries(0, '>') { assert_equal(4, pm3.demand(true)) } end test "should create status and fact-check when creating an item" do u = create_user is_admin: true t = create_team assert_difference 'FactCheck.count' do assert_difference "Annotation.where(annotation_type: 'verification_status').count" do with_current_user_and_team(u, t) do create_project_media set_status: 'false', set_fact_check: { title: 'Foo', summary: 'Bar', url: random_url, language: 'en' }, set_claim_description: 'Test', team: t end end end end test "should not create duplicated fact-check when creating an item" do u = create_user is_admin: true t = create_team params = { title: 'Foo', summary: 'Bar', url: random_url, language: 'en' } with_current_user_and_team(u, t) do assert_nothing_raised do create_project_media set_fact_check: params, set_claim_description: 'Test', team: t create_project_media set_fact_check: params, set_claim_description: 'Test' end assert_raises ActiveRecord::RecordNotUnique do create_project_media set_fact_check: params, set_claim_description: 'Test', team: t end end end test "should have longer expiration date for tags cached field" do RequestStore.store[:skip_cached_field_update] = false pm = create_project_media Rails.cache.clear Sidekiq::Testing.inline! do # First call should query the database and cache the field assert_queries 0, '>' do pm.tags_as_sentence end # If not expired yet, should not query the database travel_to Time.now.since(2.years) assert_queries 0, '=' do pm.tags_as_sentence end travel_to Time.now.since(6.years) # After expiration date has passed, should query the database again assert_queries 0, '>' do pm.tags_as_sentence end end end test "should get media slug" do m = create_uploaded_image file: 'rails.png' # Youtube url = random_url pender_url = CheckConfig.get('pender_url_private') + '/api/medias' response = '{"type":"media","data":{"url":"' + url + '","type":"item", "provider": "youtube", "title":"youtube"}}' WebMock.stub_request(:get, pender_url).with({ query: { url: url } }).to_return(body: response) l_youtube = create_link url: url u = create_user team = create_team slug: 'workspace-slug' create_team_user team: team, user: u, role: 'admin' # File type pm_image = create_project_media team: team, media: m assert_equal "image-#{team.slug}-#{pm_image.id}", pm_image.media_slug # Link type pm_youtube = create_project_media team: team, media: l_youtube assert_equal "youtube-#{team.slug}-#{pm_youtube.id}", pm_youtube.media_slug # Claim type pm = create_project_media team: team, quote: random_string assert_equal "text-#{team.slug}-#{pm.id}", pm.media_slug end end
# # SurveyTemplatesHelper # module SurveyTemplatesHelper # # Renders action links for survey templates # def action_buttons(edit_path:, delete_path:) edit_link = link_to 'Edit', edit_path, class: 'btn btn-primary' delete_link = link_to 'Delete', delete_path, class: 'btn btn-danger', method: :delete, data: { confirm: 'Are you sure you want to delete this item?' } edit_link + delete_link end # # Checks if questions_template is required and returns formatted response for table # def required_check(questions_template) questions_template.response_required ? '✓' : '' end # # Renders link to create new survey template # def new_survey_template_link link_to 'New Survey Template', new_survey_template_path, class: 'btn btn-success' end # # Renders controller action links for show page # def survey_template_options content_tag :div, class: 'admin-options' do edit_link = link_to 'Edit Survey', edit_survey_template_path(@survey_template), class: 'btn btn-primary' delete_link = link_to 'Delete Survey', survey_template_path(@survey_template), class: 'btn btn-danger', method: :delete, data: { confirm: 'Are you sure you want to delete this item?' } edit_link + delete_link end end end
FactoryBot.define do factory :badge do name "MyString" kind_id 1 points 1 default false end end
class EventsController < ApplicationController before_action :require_logged_in_user def index @events = current_user.events end def new @event = Event.new end def create @event = current_user.events.build(event_params) if @event.save flash[:success] = 'Evento criado com sucesso.' redirect_to events_path else render 'new' end end def edit @event = current_user.events.find_by(id: params[:id]) if @event.nil? flash[:danger] = 'Evento não encontrado.' redirect_to events_path(current_user) end end def update @event = current_user.events.find(params[:id]) if @event.update(event_params) flash[:success] = 'Evento atualizado com sucesso.' redirect_to events_path else render 'edit' end end def show @event = current_user.events.find_by(id: params[:id]) if @event.nil? flash[:danger] = 'Evento não encontrado.' redirect_to events_path(current_user) end end def destroy @event = current_user.events.find(params[:id]) if @event.destroy flash[:success] = 'Evento removido com sucesso.' redirect_to events_path else flash[:danger] = 'Evento não encontrado.' redirect_to events_path(current_user) end end private def event_params params.require(:event).permit(:dated_at) end end
# Each player class Player attr_accessor :piece def initialize @piece = :X end def move(choice) choice.between?(1, 9) ? choice - 1 : bad_choice end private def bad_choice puts "Not a valid choice, try again\n>" c = new_choice move(c) end def new_choice gets.chomp.to_i end end
class Gblock attr_accessor :id, :the_geom, :nodes, :length, :nb_node, :gblock_nodes, :forward_gnodes ActiveRecord::Base.establish_connection :kbase42222 puts 'Definig class Gblock' INFINITY = 1 << 32 @@loaded = false @@linked = false @@gblocks = {} class << self; attr_accessor :loaded end def Gblock.gblocks @@gblocks end def block Kbase::Block.where(infraversionid: Kbase::InfraRecord.infraversionid, id: self.id).first end def inspect '#<Gblock:' + self.id.to_s + ',' + self.length.to_s + '>' end require 'enumerator' def compute_length res = 0 self.nodes.each_cons(2) do |vect| res += vect[0].fast_dist(vect[1]) end res end def initialize(ha) @id = ha[:id] @the_geom = ha[:the_geom] @length = INFINITY @nb_node = INFINITY @gblock_nodes = [] @nodes = [] @forward_gnodes = nil end def self.reset_cache @@gblocks.each do |k, gblk| gblk.gblock_nodes.first.previous = nil #gblk.gblock_nodes.each_cons(2) do |va| # va[1].previous = va[0] #end end true end def cleanup_previous # Nécessaire pour les cantons de démarrage self.gblock_nodes.each_cons(2) do |va| va[1].previous = va[0] end true end def self.find(id) @@gblocks[id] end def Gblock.test @@gblocks.length end def self.load_in_cache(infraversionid) unless @@loaded start = Time.now puts 'Loading Gblock' blks = Kbase::Block.select('id,the_geom').where(infraversionid: infraversionid) for blk in blks #blocknodes = Kbase::BlockNode.find :all, :order => 'seq asc', :conditions => "infraversionid = #{infraversionid} AND blockid = #{blk[:id]}" #nodes = blocknodes.collect {|blkn| Gnode.find blkn.node} gblk = Gblock.new :id => blk[:id], :the_geom => blk.the_geom #, :nodes => nodes @@gblocks[gblk.id] = gblk end puts 'End Loading Gblock ' + (Time.now - start).to_s @@loaded = true end end def forward_gnodes # La liste des sorties du block qui n'appartienne pas au block @forward_gnodes ||= self._forward_gnodes end def _forward_gnodes dist = 0 vres = [] pgbnd = nil for fgbnd in self.gblock_nodes unless pgbnd.nil? dist += pgbnd.node.fast_dist(fgbnd.node) lother = fgbnd.node.forward_blocks.collect {|blk| debugger unless blk blk != self ? blk.gblock_nodes.first : nil} lother.compact! for other in lother vres << [dist, other, fgbnd.seq] # vecteur de distance, extremité, nb de noeud end end pgbnd = fgbnd end self.gblock_nodes.each_cons(2) do |va| va[1].previous = va[0] end vres end def self.after_all_class_load(infraversionid) unless @@linked start = Time.now puts 'Linking Gblock' @@gblocks.each do |k, gblk| gblk.nodes = gblk.gblock_nodes.collect {|bn| bn.node} gblk.length = gblk.compute_length gblk.nb_node = gblk.nodes.length gblk.forward_gnodes end puts 'End Linking Gblock ' + (Time.now - start).to_s @@linked = true end end def self.some_gblocks(default= 100) i = 0 ; res = [] @@gblocks.each do |k, gblk| res << gblk i += 1 return res if i > default end res end def end_node @end_node ||= @nodes.last end def start_node @nodes.first end def end_block_node @end_blk_node ||= @gblock_nodes.last end def start_block_node @gblock_nodes.first end def dist_from_node_to_end(node = nil) res = 0 ; bad = false ; todo = false self.gblock_nodes.each_cons(2) do |vect| if node.nil? || vect[0] == node todo = true end if todo d = vect[0].node.fast_dist(vect[1].node) if d.is_a?(Fixnum) res += d else bad = true end end end bad ? 'n/a' : res end def dist_start_to_node(node = nil) res = 0 ; bad = false ; todo = true self.gblock_nodes.each_cons(2) do |vect| if node.nil? || vect[0] == node todo = false end if todo d = vect[0].node.fast_dist(vect[1].node) if d.nil? bad = true else res += d end end end bad ? 'n/a' : res end end
require 'spec_helper' class FakeTwilioSender def create(data) end end class FakeTwilioResponse def sid "SM727fd423411e4b1b8dcdc4d48ee07f20" end def status "accepted" end def error_code nil end def error_message nil end def price nil end def price_unit nil end def num_segments nil end end describe Smess::Twilio, iso_id: "7.2.4" do let(:sms) { Smess::Sms.new( to: '46701234567', message: 'Test SMS', originator: 'TestSuite', output: "test" ) } let(:concat_sms) { Smess::Sms.new( to: '46701234567', message: 'This tests a long concatenated message. This message will overflow the 160 character limit. It is sent as separate messages but it should still be glued together to a single message on the phone.', originator: 'TestSuite', output: "test" ) } subject { output = described_class.new({ sid: "", auth_token: "a", from: "", callback_url: "" }) output.sms = sms output } it 'generates correct data for a single message' do request = nil subject.stub(:create_client_message) { |data| request = data FakeTwilioResponse.new } subject.deliver expect(request[:to]).to eq("+#{sms.to}") expect(request[:body]).to eq(sms.message) end it 'does not swallow exceptions' do request = nil subject.stub(:create_client_message) { |data| raise "Hell" } expect{ results = subject.deliver }.to raise_error end end
module Openra class IRCBot < Cinch::Bot VERSION = File.read('VERSION').strip.freeze end end
class Admin::ProductsController < AdminController load_and_authorize_resource has_scope :by_product_name has_scope :by_article_name has_scope :by_product_provider_name def index @products = Kaminari.paginate_array(apply_scopes(Product).all.order("created_at")).page(params[:page]) @stores = Store.all end def create @product = Product.new(product_params) @product.product_stores.each do |ps| ps.stock = 0 end if @product.save redirect_to admin_product_path(@product) else render :new end end def update respond_to do |format| if @product.update(product_params) flash[:sucess] = "Produit mis à jour" format.html {redirect_to admin_product_path(@product)} else format.html { render 'edit'} format.json { render json: @product.errors, status: :unprocessable_entity } end end end def stock_update if @product.update(stock_product_params) @product.update_columns(stock: @product.unit * @product.multiple) else puts params[:product][:restocking] end end def info_update if @product.update(product_params) puts params[:product][:restocking] else puts params[:product][:restocking] end end def pricing_update if @product.update(stock_product_params) puts params[:product][:restocking] else puts params[:product][:restocking] end end def destroy @product.destroy redirect_to admin_products_path end private # Never trust parameters from the scary internet, only allow the white list through. def product_params params.require(:product).permit(:name,:stock,:multiple,:unit, :quantity_max, :restocking,:reference_us,:conditioning, :storage_zone,:can_return,:prod_category_id,:price_cents, :tva_cents,:margin, :prod_category_id,:store_ids => [], :article_ids => [], :accompaniment_ids => [], article_products_attributes:[:id, :quantity, :article_id, :product_id] ) end def stock_product_params params.require(:product).permit( :stock,:multiple, :quantity_max, :restocking,:unit,:price_cents, :margin, :tva_cents) end end
def transpose(array) number_of_rows = array.size number_of_columns = array[0].size new_array = [] number_of_columns.times { |_| new_array << [] } 0.upto(number_of_rows - 1) do |index_row| 0.upto(number_of_columns - 1) do |index_column| new_array[index_column][index_row] = array[index_row][index_column] end end new_array end puts transpose([[1, 2, 3, 4]]) == [[1], [2], [3], [4]] puts transpose([[1], [2], [3], [4]]) == [[1, 2, 3, 4]] puts transpose([[1, 2, 3, 4, 5], [4, 3, 2, 1, 0], [3, 7, 8, 6, 2]]) == [[1, 4, 3], [2, 3, 7], [3, 2, 8], [4, 1, 6], [5, 0, 2]] puts transpose([[1]]) == [[1]]
module Appilf class ResourcePage < AppilfObject include Enumerable include APIActions attr_accessor :items attr_accessor :page_meta attr_accessor :page_links # :page_number , :page_size, :total_results def page_meta @page_meta ||= {} end # :prev, :next def page_links @page_links ||= {} end def next get_page(page_links.next) end def previous get_page(page_links.prev) end def items @items ||= [] end def initialize(paginated_response) init_page_meta_data(paginated_response) paginated_response['data'].each do |api_element_data_hash| self.items << Util.translate_from_response({'data' => api_element_data_hash}) end end def each(&block) self.items.each(&block) end private def get_page(link) return unless link response = api_get(link) Util.translate_from_response(response) # set_page(response) end def init_page_meta_data(api_element_hash) self.page_meta = api_element_hash.fetch('meta', {}) self.page_links = api_element_hash.fetch('links', {}) self.page_meta.methodize! self.page_links.methodize! end end end
# Copyright (c) 2019 Danil Pismenny <danil@brandymint.ru> # frozen_string_literal: true # rubocop:disable Metrics/ClassLength class DeepStonerStrategy < Strategy LEVELS_MULT = ENV.fetch('LEVELS_MULT', 1).to_i LEVELS_DECADE = ENV.fetch('LEVELS_DECADE', 10).to_i attr_reader :buyout_account class Settings < StrategySettings attribute :base_min_volume, BigDecimal, default: 0.001 validates :base_min_volume, presence: true, numericality: { greater_than: 0 } attribute :base_max_volume, BigDecimal, default: 0.002 validates :base_max_volume, presence: true, numericality: { greater_than: 0 } attribute :buyout_enable, Boolean, default: false attribute :buyout_ask_percentage, BigDecimal, default: 0.1 validates :buyout_ask_percentage, presence: true, numericality: { greater_than_or_equal_to: 0.1, lower_than: 2 } attribute :buyout_bid_percentage, BigDecimal, default: 0.1 validates :buyout_bid_percentage, presence: true, numericality: { greater_than_or_equal_to: 0.1, lower_than: 2 } attribute :base_mad_mode_enable, Boolean, default: false attribute :base_enable_order_by_liquidity, Boolean, default: false attribute 'base_bid_total_volume', Float, default: 0.01 validates 'base_bid_total_volume', presence: true, numericality: { greater_than_or_equal_to: 0 } attribute 'base_ask_total_volume', Float, default: 0.01 validates 'base_ask_total_volume', presence: true, numericality: { greater_than_or_equal_to: 0 } LEVELS = 5 LEVELS.times.each do |i| attribute "base_best_price_deviation_from_#{i}", Float, default: 10 validates "base_best_price_deviation_from_#{i}", presence: true, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 100 } attribute "base_best_price_deviation_to_#{i}", Float, default: 10 validates "base_best_price_deviation_to_#{i}", presence: true, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 100 } attribute "base_liquidity_part_#{i}", Float, default: 10 validates "base_liquidity_part_#{i}", presence: true, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 100 } end def levels LEVELS end end def self.description %( <p>Наполнятель стакана. Цель - иметь наполненный стакан.</p> <p>Делает заявки на объём <code>base_min_volume</code> базовой валюты по средней цене в стаканe, с разбросом от <code>base_min_threshold</code> до <code>base_max_threshold</code> %.</p> <p class="alert alert-warning">Пока в peatio не сформирован стакан цена берется из стакана binance</p> ).html_safe end # rubocop:disable Metrics/ParameterLists def initialize(name:, market:, account:, source_account:, buyout_account:, default_settings: {}, comment: nil) @buyout_account = buyout_account super( name: name, market: market, account: account, source_account: source_account, default_settings: default_settings, comment: comment ) end # rubocop:enable Metrics/ParameterLists def buyout_currencies [market.binance_quote || market.quote, market.base] end def trade_created(trade) unless trade.account == account logger.debug("Skip trade #{trade.id} because of other account used") return end if trade.account == buyout_account logger.debug("Skip trade #{trade.id} because trade account is buyout account") return end unless trade.market.enable_buyout logger.debug("Skip trade #{trade.id} because market is disabled for buyout") return end settings.reload if settings.buyout_enable? if settings.enabled? logger.info("Make buyout for trade #{trade}") BuyoutOrderCreator .new .call(trade: trade, buyout_account: buyout_account, ask_percentage: settings.buyout_ask_percentage, bid_percentage: settings.buyout_bid_percentage) else logger.debug("Strategy is disabled. Skip buyout for trade #{trade.id}..") end end super end private def update_orders! orders_to_create = [] orders_to_cancel = [] account.update_active_orders! %i[ask bid].map do |side| prepare_orders_by_side(side, orders_to_cancel, orders_to_create) end updater.start! updater.cancel_orders! orders_to_cancel if orders_to_cancel.any? updater.create_orders! orders_to_create if orders_to_create.any? updater.errors.each do |error_info| # do something end state.update_attributes!( best_ask_price: best_price_for(:ask), best_bid_price: best_price_for(:bid), created_orders: orders_to_create.to_a, last_error_message: updater.errors.map(&:message).uniq.compact.join('; '), last_errors: [], acted_at: Time.now ) rescue StandardError => e report_exception(e) unless e.is_a? Valera::BaseClient::InsufficientBalance logger.error(e) state.update_attributes!( best_ask_price: best_price_for(:ask), best_bid_price: best_price_for(:bid), created_orders: [], last_error_message: e.message, last_errors: [], acted_at: Time.now ) end # rubpcop:disable Metrics/CyclomaticComplexity # rubocop:disable Metrics/PerceivedComplexity def prepare_orders_by_side(side, orders_to_cancel, orders_to_create) leveled_orders = settings.levels.times.each_with_object({}) { |a, o| o[a] = [] } account.active_orders.filter { |o| o.market == market && o.side?(side) }.each do |persisted_order| level = find_level_of_order persisted_order if level.nil? orders_to_cancel << persisted_order else leveled_orders[level] << persisted_order end end settings.levels.times.map do |level| target_orders_volume = calculate_target_orders_volume side, level logger.debug("target_orders_volume(level:#{level},side:#{side})=#{target_orders_volume}") persisted_orders = leveled_orders[level] orders_to_cancel << persisted_orders.pop while persisted_orders.sum(&:remaining_volume) > target_orders_volume persisted_volume = persisted_orders.sum(&:remaining_volume) new_orders = [] while persisted_volume + new_orders.sum(&:volume) < target_orders_volume && target_orders_volume - (persisted_volume + new_orders.sum(&:volume)) > settings.base_min_volume order = build_order(side, level, target_orders_volume - new_orders.sum(&:volume) - persisted_volume) new_orders << order unless order.nil? end orders_to_create.push(*new_orders) if new_orders.sum(&:volume) + persisted_orders.sum(&:remaining_volume) - orders_to_create.sum(&:volume) > target_orders_volume raise "Total orders sum (#{new_orders.sum(&:volume)} + #{persisted_orders.sum(&:remaining_volume)} - #{orders_to_create.sum(&:volume)}) larget then target #{target_orders_volume}" end end end # rubpcop:enable Metrics/CyclomaticComplexity # rubocop:enable Metrics/PerceivedComplexity def find_level_of_order(persisted_order) volume_range = settings.base_min_volume.to_f..settings.base_max_volume.to_f settings.levels.times.find do |level| build_price_range(persisted_order.side, level).member?(persisted_order.price) && volume_range.member?(persisted_order.remaining_volume) end end def build_order(side, level, max_volume) volume_range = settings.base_min_volume.to_f..[settings.base_max_volume, max_volume].min.to_f price_range = build_price_range side, level comparer = lambda do |persisted_order| !settings.base_mad_mode_enable? && \ price_range.member?(persisted_order.price) && \ volume_range.member?(persisted_order.remaining_volume) end price = rand price_range volume = rand volume_range logger.debug("Calculated price for #{side} level #{level} price_range=#{price_range} price=#{price} volume=#{volume}") super side, price, volume, comparer, level end def build_price_range(side, level) d = price_deviation_range side, level best_price = best_price_for side raise "no best price for #{side}" if best_price.to_d.zero? d.first.percent_of(best_price)..d.last.percent_of(best_price) end def price_deviation_range(side, level) level -= level / LEVELS_DECADE * LEVELS_DECADE deviation_from, deviation_to = [ settings.send("base_best_price_deviation_from_#{level}"), settings.send("base_best_price_deviation_to_#{level}") ].sort case side.to_sym when :ask (100.0.to_d + deviation_from)..(100.0.to_d + deviation_to) when :bid (100.to_d - deviation_to)..(100.to_d - deviation_from) else raise "WTF #{side}" end end def calculate_target_orders_volume(side, level) level -= level / LEVELS_DECADE * LEVELS_DECADE liquidity_part = settings.send "base_liquidity_part_#{level}" if settings.base_enable_order_by_liquidity liquidity_part.percent_of users_orders_volume(side) else liquidity_part.percent_of settings.send("base_#{side}_total_volume") end end end # rubocop:enable Metrics/ClassLength
group 'dev' do action :create end file '/etc/sudoers.d/10dev_users' do content '%dev ALL=(ALL) NOPASSWD:ALL' owner 'root' group 'root' mode '0500' action :create end node[:user][:dev_users].each do |dev| user_name = dev['name'] user_home = "/home/#{user_name}" user user_name do comment dev['full_name'] home user_home shell '/bin/bash' manage_home true action :create end group "add '#{user_name}' to dev group" do append true group_name 'dev' members user_name end directory "#{user_home}/.ssh" do owner user_name group user_name mode 0700 end cookbook_file "#{user_home}/.ssh/authorized_keys" do source "#{user_name}.pub" owner user_name group user_name mode 0700 action :create end end
class Brand < ApplicationRecord # アソシエーション has_many :items, dependent: :destroy belongs_to :user # バリデーション validates :brand_name, presence: true end
require 'rails_helper' RSpec.describe Section, type: :model do it "has a unique title" do section = FactoryGirl.create(:section) expect(FactoryGirl.build(:section, title: section.title)).to_not be_valid end end
#!/usr/bin/env ruby require 'trollop' require 'yaml' require 'rpmbuild' require 'pp' opts = Trollop::options do version "gen_rpm 2.0.0 (c) 2014 Albert Dixon" banner <<-EOS gen_rpm is basically a wrapper around rpmbuild. It will generate all spec files and run rpmbuild to create a custom rpm package. EOS opt :root, "The top level working directory for the build. Give absolute path.", type: String, required: true opt :buildroot, "The directory with the structured rpm sources. Give absolute path.", type: String, required: true opt :spec_config, "A yaml with spec file options. Give absolute path.", type: IO, required: true opt :product, "The name of the product", type: String, required: true opt :client, "The client deployment this is for", type: String, default: nil opt :environment, "The environment this is for", type: String, default: nil opt :verbose, "Verbose output" end Trollop::die :spec_config, "must exist and be readable!" unless File.exists?(opts[:spec_config]) and File.readable?(opts[:spec_config]) Trollop::die :root, "must exist!" unless Dir.exists?(opts[:root]) Trollop::die :buildroot, "must exist!" unless Dir.exists?(opts[:buildroot]) defaultspec = (ENV["DEFAULT_SPEC"] || File.join("/", "opt", "tools", "cfg", "default-spec.yml")) begin default = Psych.load_file(defaultspec).inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} default.each_pair do |k, v| if v.is_a? String /__(.*)__/.match(v) {|m| v.gsub! /__.*__/, eval(m[1])} elsif v.is_a? Hash v.each_pair do |k1, v1| if v1.is_a? String /__(.*)__/.match(v1) {|m| v1.gsub! /__.*__/, eval(m[1]).to_s} end end end end rescue Psych::SyntaxError => e $stderr.puts "#{e.file}: #{e.message}" default = {} rescue => e $stderr.puts "ERROR: #{e.message}" $stderr.puts e.backtrace default = {} end begin spec = Psych.load_file(opts[:spec_config]).inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} spec.merge!(default) do |key, v1, v2| if v1.is_a?(Hash) and v2.is_a?(Hash) v1.merge(v2) else v1 end end name = [] name << "msp" if not opts[:client].nil? name << opts[:client] end name << opts[:product] spec[:tags].store :name, name.join("-") spec[:tags][:release] = (opts[:environment].nil? ? "all" : opts[:environment]) $stdout.puts "** Using rpmbuild #{Gem.loaded_specs['rpmbuild'].version} **" $stdout.puts "default spec-yaml: #{defaultspec}" $stdout.puts "our spec-yaml: #{opts[:spec_config].path}" $stdout.puts "Running rpmbuild..." RPMBuild.new(opts[:root], opts[:buildroot], {spec: spec, log_level: (opts.include?(:verbose) ? Logger::DEBUG : Logger::INFO)}).build rescue Psych::SyntaxError => e $stderr.puts "#{e.file}: #{e.message}" rescue Exception => e $stderr.puts "ERROR: #{e.message}", e.backtrace end
class SurveysSweeper < ActionController::Caching::Sweeper observe Survey def after_save(survey) Rails.cache.write :surveys_cache_expirary_key, rand.to_s[2..-1] expire_action survey_questions_url(:survey_id => survey) end def after_destroy(survey) Rails.cache.write :surveys_cache_expirary_key, rand.to_s[2..-1] expire_action survey_questions_url(:survey_id => survey) end end
# Numbers to English Words # I worked on this challenge [by myself]. # This challenge took me [0.75] hours. # Pseudocode # Create three constants of hashes with keys of strings of single-digit numbers: # TEENS: the English words of all of the teens (this will have keys of two-digit numbers) # SINGLES: the English words of all of the single-digits # TENS: the English words of all of the tens-place numbers # IF the input number is between eleven and nineteen inclusive # return the value of the input number fed into TEENS # ELSE IF the input number is less than 10 # convert to string and return the value of the string fed into SINGLES # ELSE IF the input number is 100 # return 'one hundred' # ELSE IF the input number is 0 # return 'zero' # ELSE # convert input number to string # split the string into an array of single characters # feed the 0th value of the array into TENS # feed the 1st value of the array into SINGLES # join the array and return it # Initial Solution # SINGLES = { # '0' => 'zero', # '1' => 'one', # '2' => 'two', # '3' => 'three', # '4' => 'four', # '5' => 'five', # '6' => 'six', # '7' => 'seven', # '8' => 'eight', # '9' => 'nine' # } # TEENS = { # 11 => 'eleven', # 12 => 'twelve', # 13 => 'thirteen', # 14 => 'fourteen', # 15 => 'fifteen', # 16 => 'sixteen', # 17 => 'seventeen', # 18 => 'eighteen', # 19 => 'nineteen' # } # TENS = { # '1' => 'ten', # '2' => 'twenty', # '3' => 'thirty', # '4' => 'forty', # '5' => 'fifty', # '6' => 'sixty', # '7' => 'seventy', # '8' => 'eighty', # '9' => 'ninety' # } # def num_translator (number) # if number == 100 # return 'one hundred' # elsif number == 0 # return 'zero' # elsif number < 10 # return SINGLES[number.to_s] # elsif (number <= 19 && number >= 11) # return TEENS[number] # else # eng_number = number.to_s.chars # if number % 10 == 0 # return TENS[eng_number[0]] # else # eng_number[0] = TENS[eng_number[0]] + ' ' # eng_number[1] = SINGLES[eng_number[1]] # return eng_number.join # end # end # end # Refactored Solution # def num_translator (number) # if number == 100 # return 'one hundred' # elsif number < 10 # return SINGLES[number.to_s] # elsif (11..19).include?(number) # return TEENS[number] # else # eng_number = number.to_s.chars # if number % 10 == 0 # return TENS[eng_number[0]] # else # eng_number[0] = TENS[eng_number[0]] + ' ' # eng_number[1] = SINGLES[eng_number[1]] # return eng_number.join # end # end # end # p num_translator(10) # p num_translator(20) # I worked on this challenge [by myself]. # This challenge took me [0.15] hours. # Pseudocode # iterate over the array destructively # IF element is divisible by 15 # element replaced with "FizzBuzz" # ELSE IF element is divisible by 3 # element replaced with "Fizz" # ELSE IF element is divisible by 5 # element replaced with "Buzz" # return array # Initial Solution # def super_fizzbuzz(array) # array.map! {|num| # if num % 15 ==0 # num = "FizzBuzz" # elsif num % 3 == 0 # num = "Fizz" # elsif num % 5 == 0 # num = "Buzz" # else # num = num # end # } # return array # end # Refactored Solution def super_fizzbuzz(array) array.map! {|num| if num % 15 ==0 num = "FizzBuzz" elsif num % 3 == 0 num = "Fizz" elsif num % 5 == 0 num = "Buzz" else num = num end } return array end # Reflection # I tried to solidify the use of constants, and created my own constants for the first time. I did super_fizzbuzzfor fun, really. I didn't exaggerate the time it took me. # I'm not really confused about anything with Ruby, I'm just now a little unsure about syntax what with the addition of JavaScript into the mix. # I intend to finish most of the rest of these over the course of the next week, and try to create a clear delineation in my mind between the languages for syntax reasons. Otherwise I feel pretty ready.
require 'rails_helper' RSpec.describe Purchase, type: :model do before do @purchase = FactoryBot.build(:purchase) end describe '商品購入' do context '商品購入できるとき' do it 'user_id、item_id、post_code、prefecture_id、city、phone_number、tokenが存在すれば購入できる' do expect(@purchase).to be_valid end end end context '商品購入できないとき' do it 'user_idが空では登録できない' do @purchase.user_id = nil @purchase.valid? expect(@purchase.errors.full_messages).to include("Image can't be blank") end end # it 'nameが空では登録できない' do # @item.name = "" # @item.valid? # expect(@item.errors.full_messages).to include("Name can't be blank") # end # it 'priceが空では登録できない' do # @item.price = nil # @item.valid? # expect(@item.errors.full_messages).to include("Price can't be blank") # end # it 'descriptionが空では登録できない' do # @item.description = "" # @item.valid? # expect(@item.errors.full_messages).to include("Description can't be blank") # end # it 'condition_idが空では登録できない' do # @item.condition_id = nil # @item.valid? # #binding.pry # expect(@item.errors.full_messages).to include("Condition can't be blank") # end # it 'shipping_charge_idが空では登録できない' do # @item.shipping_charge_id = nil # @item.valid? # expect(@item.errors.full_messages).to include("Shipping charge can't be blank") # end # it 'prefecture_idが空では登録できない' do # @item.prefecture_id = nil # @item.valid? # expect(@item.errors.full_messages).to include("Prefecture can't be blank") # end # it 'shipping_date_idが空では登録できない' do # @item.shipping_date_id = nil # @item.valid? # expect(@item.errors.full_messages).to include("Shipping date can't be blank") # end # it 'category_idが空では登録できない' do # @item.category_id = nil # @item.valid? # expect(@item.errors.full_messages).to include("Category can't be blank") # end # it 'category_idが0では登録できない' do # @item.category_id = 0 # @item.valid? # expect(@item.errors.full_messages).to include("Category Select") # end # it 'condition_idが0では登録できない' do # @item.condition_id = 0 # @item.valid? # expect(@item.errors.full_messages).to include("Condition Select") # end # it 'shipping_charge_idが0では登録できない' do # @item.shipping_charge_id = 0 # @item.valid? # expect(@item.errors.full_messages).to include("Shipping charge Select") # end # it 'shipping_date_idが0では登録できない' do # @item.shipping_date_id = 0 # @item.valid? # expect(@item.errors.full_messages).to include("Shipping date Select") # end # it 'priceが299円以下だと登録できない' do # @item.price = 299 # @item.valid? # expect(@item.errors.full_messages).to include("Price must be greater than or equal to 300") # end # it 'priceが9,999,999円以上だと登録できない' do # @item.price = 10000000 # @item.valid? # # binding.pry # expect(@item.errors.full_messages).to include("Price must be less than or equal to 9999999") # end # it 'priceが半角数字以外だと登録できない' do # @item.price = '111' # @item.valid? # expect(@item.errors.full_messages).to include("Price is not a number") # end # it 'priceが半角数字と英字だと登録できない' do # @item.price = '111aaa' # @item.valid? # expect(@item.errors.full_messages).to include("Price is not a number") # end # it 'priceが文字だけだと登録できない' do # @item.price = 'aaaa' # @item.valid? # expect(@item.errors.full_messages).to include("Price is not a number") # end # end end
# frozen_string_literal: true module Analytics class GeneralController < AnalyticsController def index selected_organizations = find_resource_by_id_param @selected_organization_id, Organization selected_chapters = find_resource_by_id_param(@selected_chapter_id, Chapter) { |c| c.where(organization: selected_organizations) } selected_groups = find_resource_by_id_param(@selected_group_id, Group) { |g| g.where(chapter: selected_chapters) } @selected_students = find_resource_by_id_param(@selected_student_id, Student) { |s| s.where(group: selected_groups, deleted_at: nil) } @assessments_per_month = assessments_per_month @student_performance = histogram_of_student_performance.to_json @student_performance_change = histogram_of_student_performance_change.to_json @gender_performance_change = histogram_of_student_performance_change_by_gender.to_json @average_group_performance = average_performance_per_group_by_lesson.to_json end private def histogram_of_student_performance conn = ActiveRecord::Base.connection.raw_connection res = if @selected_students.blank? [] else conn.exec(Sql.student_performance_query(@selected_students)).values end [{ name: t(:frequency_perc), data: res }] end def histogram_of_student_performance_change_by_gender conn = ActiveRecord::Base.connection.raw_connection male_students = @selected_students.where(gender: 'M') female_students = @selected_students.where(gender: 'F') result = [] result << { name: "#{t(:gender)} M", data: conn.exec(Sql.performance_change_query(male_students)).values } if male_students.length.positive? result << { name: "#{t(:gender)} F", data: conn.exec(Sql.performance_change_query(female_students)).values } if female_students.length.positive? result end def histogram_of_student_performance_change conn = ActiveRecord::Base.connection.raw_connection res = if @selected_students.blank? [] else conn.exec(Sql.performance_change_query(@selected_students)).values end [{ name: t(:frequency_perc), data: res }] end def assessments_per_month # rubocop:disable Metrics/MethodLength conn = ActiveRecord::Base.connection.raw_connection lesson_ids = Lesson.where(group_id: @selected_students.map(&:group_id).uniq).ids res = if lesson_ids.blank? [] else conn.exec("select to_char(date_trunc('month', l.date), 'YYYY-MM') as month, count(distinct(l.id, g.student_id)) as assessments from lessons as l inner join grades as g on l.id = g.lesson_id inner join groups as gr on gr.id = l.group_id where l.id IN (#{lesson_ids.join(', ')}) group by month order by month;").values end { categories: res.map { |e| e[0] }, series: [{ name: t(:nr_of_assessments), data: res.map { |e| e[1] } }] } end def average_performance_per_group_by_lesson groups = Array(groups_for_average_performance) conn = ActiveRecord::Base.connection.raw_connection groups.map do |group| result = conn.exec(Sql.average_mark_in_group_lessons(group)).values { name: "#{t(:group)} #{group.group_chapter_name}", data: format_point_data(result) } end end def format_point_data(data) data.map do |e| { x: e[0], y: e[1], lesson_url: lesson_path(e[2]), date: e[3] } end end def groups_for_average_performance Group.where(id: @selected_students.select(:group_id)) end end end
module Fog module Google class SQL ## # Imports data into a Cloud SQL instance from a MySQL dump file in Google Cloud Storage # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/import class Real def import_instance(instance_id, uri, database: nil, csv_import_options: nil, file_type: nil, import_user: nil) data = { :kind => "sql#importContext", :uri => uri } data[:database] = database unless database.nil? data[:file_type] = file_type unless file_type.nil? data[:import_user] = import_user unless import_user.nil? unless csv_import_options.nil? data[:csv_import_options] = ::Google::Apis::SqladminV1beta4::ImportContext::CsvImportOptions.new(**csv_import_options) end @sql.import_instance( @project, instance_id, ::Google::Apis::SqladminV1beta4::ImportInstancesRequest.new( import_context: ::Google::Apis::SqladminV1beta4::ImportContext.new(**data) ) ) end end class Mock def import_instance(_instance_id, _uri, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end
class Question < ActiveRecord::Base # This assumes that the answer model has a question_id integer field that references the question. # possible values for dependent are :destroy or :nullify. :Destroy will delete all associated answers. :Nullify will update the question_id to be NULL for the associated records (they won't get deleted) has_many :answers, dependent: :nullify has_many :comments, through: :answers # set up many to many association has_many :likes, dependent: :destroy has_many :users, through: :likes # q.users = User.first has_many :favourites, dependent: :destroy has_many :favouriting_users, through: :favourites, source: :user has_many :taggings, dependent: :destroy has_many :tags, through: :taggings has_many :votes, dependent: :destroy has_many :voting_users, through: :votes, source: :question belongs_to :category belongs_to :user # adding validation validates :title, presence: true, uniqueness: true, length: { minimum: 3, maximum: 255 } # uniqueness: {case_sensitive: false}, # specify err msg validates :body, presence: true, uniqueness: {message: "must be unique"} # this validates that the combination of the title and the body are unique. This means that neither the title nor the body have to be unique by themselves. However, their combination is to be unique. validates :title, uniqueness: {scope: :body} # validates :view_count, numericality: true validates :view_count, numericality: { greater_than_or_equal_to: 0 } # using custom validation methods. We must make sure that 'no monkey' is a method available for our class. The method can be public or private, but should be private since we don't need to use it outside this class. validate :no_monkey # Call Backs after_initialize :set_defaults before_save :capitalize_title # simple class methods that AR can use to make queries # def self.recent(num = 5) # order("created_at DESC").limit(num) # end # OR USE SCOPES # scope: recent, lambda, method -- methods that encapsulate db query. # scope :recent, lambda {|num| order("created_at DESC").limit(num) } scope :recent, -> (number = 5){ order("created_at DESC").limit(number) } extend FriendlyId friendly_id :title, use: [:slugged, :finders, :history] mount_uploader :image, ImageUploader def self.search(term) where(["title ILIKE ? OR body ILIKE ?", "%#{term}%", "%#{term}%"]).order("view_count DESC") end # simplifies views by lowering dependencies on categories def category_name category.name if category end # delegate :full_name, to: :user, prefix: true, allow_nil: true # could delete a full group of methods to a single delegate pass # delegates the full_name method to the user def user_full_name user.full_name if user end def like_for(user) likes.find_by(user_id: user) end def favourite_for(user) favourites.find_by(user_id: user) end def vote_for(user) votes.find_by(user_id: user) end def vote_result votes.up_count- votes.down_count end # we've commented this out because friendly id is able to handle this method for us automatically through the gem # def to_param # # assists in overriding the defaults # # Rails will assist in parsing the integer of 'id' and does the rest # "#{id}-#{title}".parameterize # end private def set_defaults self.view_count ||= 0 end def capitalize_title self.title.titleize end def no_monkey if self.title && self.title.downcase.include?("monkey") # two fields, error on attr, message errors.add(:title, "No monkey!!") end end # validates(:body, {uniqueness: {message: "must be unique"}}) # DSL: Domain Specific Language: # the code we use is completely valid Ruby, # but the method naming and arguments are specific to Active Record. # validates :title, presence: true, uniqueness: { case_sensitive: false } end
class VoicemailMessage < ActiveRecord::Base self.table_name = 'voicemail_msgs' self.primary_key = 'uuid' belongs_to :voicemail_account, :foreign_key => 'username', :primary_key => 'name', :readonly => true # Prevent objects from being destroyed def before_destroy raise ActiveRecord::ReadOnlyRecord end # Prevent objects from being deleted def self.delete_all raise ActiveRecord::ReadOnlyRecord end # Delete Message on FreeSWITCH over EventAPI def delete require 'freeswitch_event' result = FreeswitchAPI.execute('vm_delete', "#{self.username}@#{self.domain} #{self.uuid}"); end # Alias for delete def destroy self.delete end # Mark Message read def mark_read(mark_read_or_unread = true) read_status = mark_read_or_unread ? 'read' : 'unread' require 'freeswitch_event' result = FreeswitchAPI.execute('vm_read', "#{self.username}@#{self.domain} #{read_status} #{self.uuid}"); end def format_date(epoch, date_format = '%m/%d/%Y %H:%M', date_today_format = '%H:%M') if epoch && epoch > 0 time = Time.at(epoch) if time.strftime('%Y%m%d') == Time.now.strftime('%Y%m%d') return time.in_time_zone.strftime(date_today_format) end return time.in_time_zone.strftime(date_format) end end def display_duration if self.message_len.to_i > 0 minutes = (self.message_len / 1.minutes).to_i seconds = self.message_len - minutes.minutes.seconds return '%i:%02i' % [minutes, seconds] end end def phone_book_entry_by_number(number) begin voicemail_accountable = self.voicemail_account.voicemail_accountable rescue return nil end if ! voicemail_accountable return nil end if voicemail_accountable.class == SipAccount owner = voicemail_accountable.sip_accountable else owner = voicemail_accountable end if owner.class == User phone_books = owner.phone_books.all phone_books.concat(owner.current_tenant.phone_books.all) elsif owner.class == Tenant phone_books = owner.phone_books.all end if ! phone_books return nil end phone_books.each do |phone_book| phone_book_entry = phone_book.find_entry_by_number(number) if phone_book_entry return phone_book_entry end end return nil end end
class HdfsEntry < ActiveRecord::Base include Stale attr_accessible :path has_many :activities, :as => :entity has_many :events, :through => :activities belongs_to :hadoop_instance belongs_to :parent, :class_name => HdfsEntry, :foreign_key => 'parent_id' has_many :children, :class_name => HdfsEntry, :foreign_key => 'parent_id', :dependent => :destroy validates_uniqueness_of :path, :scope => :hadoop_instance_id validates_presence_of :hadoop_instance validates_format_of :path, :with => %r{\A/.*} scope :files, where(:is_directory => false) attr_accessor :highlighted_attributes, :search_result_notes searchable :unless => lambda { |model| model.is_directory? || model.stale? } do text :name, :stored => true, :boost => SOLR_PRIMARY_FIELD_BOOST text :parent_name, :stored => true, :boost => SOLR_SECONDARY_FIELD_BOOST string :grouping_id string :type_name string :security_type_name end before_save :build_full_path, :on_create => true def name File.basename(path) end def parent_name File.basename(File.dirname(path)) end def ancestors #return @ancestors if @ancestors @ancestors = [] if parent parent_name = parent.path == '/' ? hadoop_instance.name : parent.name @ancestors << {:name => parent_name, :id => parent_id} @ancestors += parent.ancestors end @ancestors end def highlighted_attributes @highlighted_attributes.merge(:path => [highlighted_path]) end def highlighted_path dir = @highlighted_attributes.has_key?(:parent_name) ? @highlighted_attributes[:parent_name].first : parent_name *rest, dir_name, file_name = path.split("/") rest << dir rest.join('/') end def modified_at=(new_time) if modified_at != new_time super end end def self.list(path, hadoop_instance) hdfs_query = Hdfs::QueryService.new(hadoop_instance.host, hadoop_instance.port, hadoop_instance.username, hadoop_instance.version) current_entries = hdfs_query.list(path).map do |result| hdfs_entry = hadoop_instance.hdfs_entries.find_or_initialize_by_path(result["path"]) hdfs_entry.stale_at = nil if hdfs_entry.stale? hdfs_entry.hadoop_instance = hadoop_instance hdfs_entry.assign_attributes(result, :without_protection => true) hdfs_entry.save! if hdfs_entry.changed? hdfs_entry end parent = hadoop_instance.hdfs_entries.find_by_path(normalize_path(path)) current_entry_ids = current_entries.map(&:id) finder = parent.children finder = finder.where(['id not in (?)', current_entry_ids]) unless current_entry_ids.empty? finder.each do |hdfs_entry| hdfs_entry.mark_stale! next unless hdfs_entry.is_directory? hadoop_instance.hdfs_entries.where("stale_at IS NULL AND path LIKE ?", "#{hdfs_entry.path}/%").find_each do |entry_to_mark_stale| entry_to_mark_stale.mark_stale! end end current_entries end def entries HdfsEntry.list(path.chomp('/') + '/', hadoop_instance) end def contents hdfs_query = Hdfs::QueryService.new(hadoop_instance.host, hadoop_instance.port, hadoop_instance.username, hadoop_instance.version) hdfs_query.show(path) end def file unless is_directory? HdfsFile.new(path, hadoop_instance, { :modified_at => modified_at }) end end def parent_path File.dirname(path) end def url hadoop_instance.url.chomp('/') + path end def entity_type_name 'hdfs_file' end private def self.normalize_path(path) Pathname.new(path).cleanpath.to_s end def build_full_path return true if path == "/" self.parent = hadoop_instance.hdfs_entries.find_or_create_by_path(parent_path) self.parent.is_directory = true self.parent.save! end end
require 'pry' # rubocop:disable Style/MutableConstant INIT_MARKER = ' ' PLAYER_MARKER = 'X' COMPUTER_MARKER = 'O' # rubocop:enable Style/MutableConstant WIN_CONDITION = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + [[1, 4, 7], [2, 5, 8], [3, 6, 9]] + [[1, 5, 9], [3, 5, 7]] def prompt(msg) puts "=> #{msg}" end # rubocop:disable Metrics/AbcSize def display_board(board) system 'clear' puts "You're a #{PLAYER_MARKER}. Computer's #{COMPUTER_MARKER}" puts "" puts " | |" puts " #{board[1]} | #{board[2]} | #{board[3]}" puts " | |" puts "-----+-----+-----" puts " | |" puts " #{board[4]} | #{board[5]} | #{board[6]}" puts " | |" puts "-----+-----+-----" puts " | |" puts " #{board[7]} | #{board[8]} | #{board[9]}" puts " | |" puts "" end # rubocop:enable Metrics/AbcSize def initialize_board new_board = {} (1..9).each { |num| new_board[num] = INIT_MARKER } new_board end def empty_squares(brd) brd.keys.select { |num| brd[num] == INIT_MARKER } end def player_places_piece(brd) square = '' loop do prompt "Choose a square (#{joinor(empty_squares(brd), ', ', 'or')}) " square = gets.chomp.to_i break if empty_squares(brd).include?(square) prompt "Sorry, that's not a valid choice" end brd[square] = PLAYER_MARKER end def computer_places_piece(brd) if ai_offense(brd) brd[ai_offense(brd)] = COMPUTER_MARKER elsif ai_defense(brd) brd[ai_defense(brd)] = COMPUTER_MARKER else square = empty_squares(brd).sample brd[square] = COMPUTER_MARKER end end def ai_offense(brd) key = 0 WIN_CONDITION.each do |line| if brd.values_at(*line).count('O') == 2 if brd.values_at(*line).count(' ') != 0 key = brd.select { |k, v| line.include?(k) && v == ' ' }.keys.first break end else key = nil end end key end def ai_defense(brd) key = 0 WIN_CONDITION.each do |line| if brd.values_at(*line).count('X') == 2 if brd.values_at(*line).count(' ') != 0 key = brd.select { |k, v| line.include?(k) && v == ' ' }.keys.first break end else key = nil end end key end def board_full?(brd) empty_squares(brd).empty? end def someone_won?(brd) !!detect_winner(brd) end def detect_winner(brd) WIN_CONDITION.each do |line| next unless brd[line[0]] == brd[line[1]] && brd[line[1]] == brd[line[2]] winner = brd[line[0]] return "Player" if winner == PLAYER_MARKER return "Computer" if winner == COMPUTER_MARKER end nil end def joinor(arr, delimiter= ', ', word = 'or') arr[-1] = "#{word} #{arr.last}" if arr.size > 1 arr.size == 2 ? arr.join(' ') : arr.join(delimiter) end def result_record(result, scores) scores[result.downcase.to_sym] += 1 end def five_times?(scores) if scores[:player] == 5 return "players" elsif scores[:computer] == 5 return "computer" else false end end def place_piece!(board, current_player) if current_player == "Player" player_places_piece(board) else computer_places_piece(board) end end def alternate_player(current_player) if current_player == "Player" return "Computer" else return "Player" end end def go_first(player) if player.downcase.start_with?('p') return "Player" elsif player.downcase.start_with?('c') return "Computer" else puts "Please enter [c]omputer/[p]layer" return false end end loop do board = initialize_board scores = { player: 0, computer: 0 } choose = "" prompt "Get 5 points to win" loop do loop do prompt "Who do you want to go first? ([c]omputer/[p]layer)" choose = gets.chomp break if go_first(choose) end current_player = go_first(choose) board = initialize_board loop do display_board(board) prompt "Get 5 points to win" prompt "Your score: #{scores[:player]}" prompt "computer's score: #{scores[:computer]}" place_piece!(board, current_player) current_player = alternate_player(current_player) break if someone_won?(board) || board_full?(board) end display_board(board) if someone_won?(board) prompt "#{detect_winner(board)} won !" result_record(detect_winner(board), scores) else prompt "It's a tie!" end next unless five_times?(scores) scores = { player: 0, computer: 0 } answer = '' loop do prompt "Play again? (y or n )" answer = gets.chomp break if answer.downcase.start_with? "y", "n" prompt "Please enter y or n" end break if answer.downcase.start_with? "n" end break end prompt "Thanks to play tic tac toe. bye-bye"
class AddcodetoPurchaseOrders < ActiveRecord::Migration def change add_column :purchase_orders, :code, :string end end
class UserSetting < ActiveRecord::Base validates :user, presence: true validates :primary_market_coin, presence: true validates :weather, presence: false belongs_to :primary_market_coin, class_name: 'MarketCoin' belongs_to :base_currency belongs_to :user, touch: true end
require 'cucumber/formatter/ordered_xml_markup' require 'cucumber/formatter/interceptor' require 'cucumber/formatter/junit' # Based on Junit formatter. Add stderr/stdout output into testcase. class JenkinsJunitFormatter < Cucumber::Formatter::Junit def before_steps(steps) @interceptedout_steps = Cucumber::Formatter::Interceptor::Pipe.wrap(:stdout) @interceptederr_steps = Cucumber::Formatter::Interceptor::Pipe.wrap(:stderr) end def after_steps(steps) return if @in_background || @in_examples duration = Time.now - @steps_start if steps.failed? steps.each { |step| @output += "#{step.keyword}#{step.name}\n" } @output += "\nMessage:\n" end build_testcase(duration, steps.status, @interceptedout_steps, @interceptederr_steps, steps.exception) end def after_table_row(table_row) return unless @in_examples and Cucumber::Ast::OutlineTable::ExampleRow === table_row duration = Time.now - @table_start unless @header_row name_suffix = " (outline example : #{table_row.name})" if table_row.failed? @output += "Example row: #{table_row.name}\n" @output += "\nMessage:\n" end build_testcase(duration, table_row.status, @interceptedout_steps, @interceptederr_steps, table_row.exception, name_suffix) end @header_row = false if @header_row end private def build_testcase(duration, status, sys_output, sys_err, exception = nil, suffix = "") @time += duration classname = @feature_name name = "#{@scenario}#{suffix}" pending = [:pending, :undefined].include?(status) && (!@options[:strict]) @builder.testcase(:classname => classname, :name => name, :time => "%.6f" % duration) do if status == :skipped || pending @builder.skipped @skipped += 1 elsif status != :passed @builder.failure(:message => "#{status.to_s} #{name}", :type => status.to_s) do @builder.cdata! @output @builder.cdata!(format_exception(exception)) if exception end @failures += 1 end @builder.tag!('system-out') do @builder.cdata! sys_output.buffer.join end @builder.tag!('system-err') do @builder.cdata! sys_err.buffer.join end end @tests += 1 end end
require 'rails_helper' RSpec.describe '通知機能', type: :request do let!(:user) { create(:user) } context '通知一覧ページの表示' do context 'ログインしているユーザーの場合' do before do sign_in user end it 'レスポンスが正常に表示されること' do get notifications_path expect(response).to render_template('notifications/index') end end context 'ログインしていないユーザーの場合' do it 'ログインページへリダイレクトすること' do get notifications_path expect(response).to have_http_status(302) expect(response).to redirect_to new_user_session_path end end end context '通知処理' do before do sign_in user end context '自分以外のユーザーのtweetに対して' do let!(:other_user) { create(:user) } let!(:tweet) { create(:tweet, user: other_user) } it 'いいねによって通知が作成されること' do post "/api/tweets/#{tweet.id}/like", xhr: true expect(other_user.reload.active_notifications).to be_truthy end it 'コメントによって通知が作成されること' do post tweet_comments_path(tweet), xhr: true, params: { comment: { content: '頑張ろう' } } expect(other_user.reload.active_notifications).to be_truthy end end context '自分以外のユーザーに対して' do let!(:other_user) { create(:user) } it 'フォローによって通知が作成されること' do user.follow!(other_user) expect(other_user.reload.active_notifications).to be_truthy end end end end
def write_tmpfile # firetower sends two signals, # p # SIGHUP to the parent # and multiple to the child, SIGTERM and SIGINT, and in some versions SIGKILL # so we mark this process as the parent, and handle SIGHUP # while making a dummy process and denote it as the child `echo #{Process.pid} $(sleep 1000000000000000 > /dev/null & echo $!) > .firetower` end class TrapCatchException < Exception ; end def set_traps Signal.trap 'HUP' do raise TrapCatchException, 'trap in retry' end Signal.trap 'QUIT' do raise TrapCatchException, 'trap in retry' end Signal.trap 'INT' do `rm .firetower` exit end Signal.trap 'TERM' do `rm .firetower` exit end end def safely_load while true do STDERR.print `clear` STDERR.puts ARGV.join(' ') STDERR.puts `date` STDERR.puts t0 = Time.now begin load ARGV.first STDERR.puts STDERR.puts (Time.utc(2000,1,1) + (Time.now - t0)).utc.strftime("real %Mm%S.%3Ns") return rescue TrapCatchException => e next rescue Exception => e STDERR.puts "#{e.backtrace.first}: #{e.message} (#{e.class})", e.backtrace.drop(1).map{|s| "\t#{s}"} STDERR.puts STDERR.puts (Time.utc(2000,1,1) + (Time.now - t0)).utc.strftime("real %Mm%S.%3N") return end end end def frame &block STDERR.print `clear` STDERR.puts `date` STDERR.puts t0 = Time.now block.call STDERR.puts STDERR.puts (Time.utc(2000,1,1) + (Time.now - t0)).utc.strftime("real %Mm%S.%3N") STDERR.puts STDERR.puts end def set_ctrl_r `stty quit ^r` end set_ctrl_r write_tmpfile set_traps safely_load set_traps while true do begin sleep 1000000000000000000 rescue TrapCatchException => e safely_load write_tmpfile set_traps next end end
Pod::Spec.new do |spec| spec.name = "GaugeSlider" spec.version = "1.2.1" spec.summary = "Highly customizable GaugeSlider primarily designed for a Smart Home app." spec.homepage = "https://github.com/edgar-zigis/GaugeSlider" spec.screenshots = "https://raw.githubusercontent.com/edgar-zigis/GaugeSlider/master/sample.gif" spec.license = { :type => 'MIT', :file => './LICENSE' } spec.author = "Edgar Žigis" spec.platform = :ios spec.ios.deployment_target = '11.0' spec.swift_version = '5.0' spec.source = { :git => "https://github.com/edgar-zigis/GaugeSlider.git", :tag => "#{spec.version}" } spec.source_files = "Sources/GaugeSlider/**/*.{swift}" end
class CreateMeasurements < ActiveRecord::Migration def change create_table :measurements do |t| t.belongs_to :user, index: true t.string :suit_size t.float :chest_overarm t.float :chest_underarm t.float :pants_waist t.float :pants_hip t.float :pants_outseam t.float :shirt_collar t.string :shirt_sleeve t.string :shoe_size t.integer :height_feet t.integer :height_inches t.integer :weight t.string :body_type t.string :fit_preference t.timestamps null: false end end end
class CollaboratorRoleSerializer < ActiveModel::Serializer attributes :id, :job, :song end
require 'rails_helper' feature 'Admin register car' do scenario 'and must be sign in' do visit root_path click_on 'Frota de carro' expect(current_path).to eq new_user_session_path end scenario 'from index page' do user = User.create!(name: 'João Almeida', email: 'joao@gmail.com', password: '123456') login_as(user, scope: :user) visit root_path click_on 'Frota de carro' expect(page).to have_link('Registrar novo carro') end scenario 'successfully' do car_category = CarCategory.create!(name: 'Top', daily_rate: 105.5, car_insurance: 58.5, third_party_insurance: 10.5) car_model = CarModel.create!(name: 'Ka', year: 2019, manufacturer: 'Ford', motorization: '1.0', car_category: car_category, fuel_type: 'Flex') subsidiary = Subsidiary.create!(name: 'Unidas', cnpj: '63.463.524/0001-39', address: 'Rua Santiago') user = User.create!(name: 'João Almeida', email: 'joao@gmail.com', password: '123456') login_as(user, scope: :user) visit root_path click_on 'Frota de carro' click_on 'Registrar novo carro' fill_in 'Placa', with: 'FHI8800' fill_in 'Cor', with: 'Cinza' fill_in 'Kilometragem', with: 1000 select 'Ka', from: 'Modelo do carro' select 'Unidas', from: 'Filial' click_on 'Enviar' expect(page).to have_content('FHI8800') expect(page).to have_content('Cinza') expect(page).to have_content('1000') expect(page).to have_content('Ka') expect(page).to have_content('Unidas') end scenario 'and must fill all fields' do user = User.create!(name: 'João Almeida', email: 'joao@gmail.com', password: '123456') login_as(user, scope: :user) visit root_path click_on 'Frota de carro' click_on 'Registrar novo carro' click_on 'Enviar' expect(page).to have_content('Placa do carro não pode ficar em branco') expect(page).to have_content('Cor não pode ficar em branco') expect(page).to have_content('Kilometragem não pode ficar em branco') expect(page).to have_content('Modelo do carro é obrigatório') expect(page).to have_content('Filial é obrigatório(a)') expect(page).to have_link('Voltar') end scenario 'and license plate must be unique' do car_category = CarCategory.create!(name: 'Top', daily_rate: 105.5, car_insurance: 58.5, third_party_insurance: 10.5) car_model = CarModel.create!(name: 'Ka', year: 2019, manufacturer: 'Ford', motorization: '1.0', car_category: car_category, fuel_type: 'Flex') subsidiary = Subsidiary.create!(name: 'Unidas', cnpj: '63.463.524/0001-39', address: 'Rua Santiago') Car.create!(license_plate: 'FHI8800', color: 'Cinza', car_model: car_model , mileage: 1000, subsidiary: subsidiary) user = User.create!(name: 'João Almeida', email: 'joao@gmail.com', password: '123456') login_as(user, scope: :user) visit root_path click_on 'Frota de carro' click_on 'Registrar novo carro' fill_in 'Placa', with: 'FHI8800' fill_in 'Cor', with: 'Cinza' fill_in 'Kilometragem', with: 1000 select 'Ka', from: 'Modelo do carro' select 'Unidas', from: 'Filial' click_on 'Enviar' expect(page).to have_content('Placa do carro já está em uso') end end
# frozen_string_literal: true require_relative "./lib/colorizer" ## What's this sourcery def project_name "HOP! into the Grain 2019 🍺" end ## Serve task :serve do puts "== Project: " + project_name.green puts "== Start server..." system "bundle exec middleman serve" || exit(1) end ## Build the website task :build do puts "== Project: " + project_name.green puts "== Brewing...".green system "bundle exec middleman build" || exit(1) end ## Build & Proof task :proof do puts "== Project: " + project_name.green puts "== Brewing in verbose mode...".green system "bundle exec middleman build" || exit(1) puts "== Proofing the brew...".green system "ruby lib/html_proofer.rb" || exit(1) end def git_branch_name `git rev-parse --abbrev-ref HEAD` end desc "Submits PR to GitHub" task :pr do branch_name = git_branch_name if branch_name == "master" puts "On master branch, not PRing." exit 1 end `git push -u origin #{branch_name}` `open https://github.com/RonaldDijkstra/hop-into-the-grain/compare/#{branch_name}` end
class UsersAddPasswordDigest < ActiveRecord::Migration def change add_column :users, :password_digest, :string, unique: true end end
# frozen_string_literal: true require 'roar/decorator' require 'roar/json' require_relative 'comment_representer' module IndieLand module Representer # Represents Comments class Comments < Roar::Decorator include Roar::JSON property :event_id collection :comments, extend: Representer::Comment, class: OpenStruct end end end
class Order < ApplicationRecord belongs_to :circle before_save :default_values def default_values self.acceptUserName ||= '-1' end end
FactoryBot.define do sequence :id do |n| "#{n}"; end factory :item do association :merchant id { generate :id } name { Faker::Commerce.product_name } description {Faker::Quotes::Shakespeare.hamlet_quote } unit_price {Faker::Commerce.price} end end
# == Schema Information # # Table name: notes # # id :integer not null, primary key # title :string not null # content :string # user_id :integer not null # notebook_id :integer not null # created_at :datetime not null # updated_at :datetime not null # plain_text :string # class Note < ApplicationRecord validates :title, :user_id, :notebook_id, presence: true validates :title, uniqueness: { scope: :notebook_id, message: "already belongs to a note in this notebook." } belongs_to :user belongs_to :notebook has_many :taggings, dependent: :destroy has_many :tags, through: :taggings end
class VoteMangasController < ApplicationController before_action :authenticate_user! before_action :find_manga,only: [:create,:destroy] def create @manga.liked_by current_user respond_to do |format| format.html{redirect_to @manga} format.js end end def destroy @manga.disliked_by current_user respond_to do |format| format.html{redirect_to @manga} format.js end end private def find_manga @manga = Manga.friendly.find params[:manga_id] redirect_to manga_path unless @manga end end
# Assignment: Calculator # Code up your own calculator from the lecture. # Make sure you can run it from the command line. # Save the calculator file in a directory, and initialize the directory as a git repository. # Make sure this isn't nested in another existing git repository. Then, push this git repository to Github. # # Problem definition: # Create a calculator that takes 2 numbers from user and # perform addition, subtraction, multiplication and division depends on the choice of the user. # # Problem logic # 1. take 2 numbers from user input # 2. ask the user to make a choice to perform a calculation # 3. print out result. require 'pry' def say(msg) puts "=====> #{msg}" end # When user enter bad input, returns nil def verify(num) # the first check verifies that there is a digit somewhere, the second half sets the allowed format num.match(/\d/) && num.match(/^\d*.?\d*$/) end def do_math(num_1, num_2,choice) case choice when "1" say "The result is #{result = num_1.to_i + num_2.to_i}." calculator when "2" say "The result is #{result = num_1.to_i - num_2.to_i}." calculator when "3" say "The result is #{result = num_1.to_i * num_2.to_i}." calculator when "4" say "The result is #{result = num_1.to_f/num_2.to_f}." calculator when "5" say "Goodbye for now." abort else puts "Please make a choice between option 1-5." calculator end end def calculator say "Please enter a number." num_1 = gets.chomp say "Please enter another number." num_2 = gets.chomp # binding.pry if verify(num_1) != nil and verify(num_2) != nil say "What calculation do you want to perform?" say "1) Add 2) Subtract 3) Mutiply 4) Divide 5) Quit the calculator" choice = gets.chomp do_math(num_1,num_2,choice) else say "Are you sure what you have entered are both numbers? Try again!" calculator end end calculator
require "rails_helper" describe Api::V3::BloodPressurePayloadValidator, type: :model do describe "Data validations" do it "validates that the blood pressure's facility exists" do facility = create(:facility) blood_pressure = build_blood_pressure_payload(create(:blood_pressure, facility: facility)) facility.discard validator = described_class.new(blood_pressure) expect(validator.valid?).to be false end end end
describe Limbo::Client do use_vcr_cassette 'limbo.client.post' before do Limbo.configure do |config| config.key = "test-key" config.uri = "http://limbo-listener-staging.herokuapp.com" end end describe ".post" do it "returns a client instance" do Limbo::Client.post(data: "info").should be_an_instance_of(Limbo::Client) end end describe "#valid_data?" do context "valid data" do specify { Limbo::Client.post(data: "info").should be_valid_data } end context "invalid data" do context "string argument" do use_vcr_cassette 'limbo.client.post.string_argument', exclusive: true specify { Limbo::Client.post("info").should_not be_valid_data } end context "bad character" do use_vcr_cassette 'limbo.client.post.bad_character', exclusive: true specify do Limbo::Client.post(data: "bad\x80char").should_not be_valid_data end end end end describe "#posted?" do context "valid uri" do specify { Limbo::Client.post(data: "info").should be_posted } end context "invalid uri" do use_vcr_cassette 'limbo.client.post.invalid_uri', exclusive: true before do Limbo.configure do |config| config.uri = "http://example.com" end end specify { Limbo::Client.post(data: "info").should_not be_posted } end context "invalid body" do use_vcr_cassette 'limbo.client.post.bad_character', exclusive: true specify do Limbo::Client.post(data: "bad\x80char").should be_posted end end end end
require File.dirname(__FILE__) + "/spec_helper" describe Sequel::MigrationBuilder do it "should return nil if the table hash is empty and the database has no tables" do mock_db = double(:database) expect(mock_db).to receive(:tables).at_least(:once).and_return([]) expect(Sequel::MigrationBuilder.new(mock_db).generate_migration({})).to be_nil end it "should produce a simple migration string given a database connection and a hash of tables" do tables = {} tables[:example_table] = { :columns => [{:name => :foo, :column_type => :integer}] } expected = <<-END Sequel.migration do change do create_table :example_table do integer :foo, :null => false end end end END mock_db = double(:database) expect(mock_db).to receive(:tables).at_least(:once).and_return([]) expect(Sequel::MigrationBuilder.new(mock_db).generate_migration(tables)).to eql(expected) end it "should produce statements for multiple new tables" do tables = {} tables[:example_table] = { :columns => [{:name => :foo, :column_type => :integer}, {:name => :bar, :column_type => :varchar}] } tables[:example_table_2] = { :columns => [{:name => :foo, :column_type => :integer, :null => true}] } expected = <<-END Sequel.migration do change do create_table :example_table do integer :foo, :null => false varchar :bar, :null => false end create_table :example_table_2 do integer :foo end end end END mock_db = double(:database) expect(mock_db).to receive(:tables).at_least(:once).and_return([]) expect(Sequel::MigrationBuilder.new(mock_db).generate_migration(tables)).to eql(expected) end it "should add the primary key of the table" do mock_db = double(:database) expect(mock_db).to receive(:tables).at_least(:once).and_return([]) table = { :primary_key => :foo, :columns => [{:name => :foo, :column_type => :integer}, {:name => :bar, :column_type => :varchar}] } expected = <<-END create_table :example_table do primary_key :foo, :type => :integer, :null => false varchar :bar, :null => false end END expect(Sequel::MigrationBuilder.new(mock_db).create_table_statement(:example_table, table).join("\n")).to eql(expected.strip) end it "should add the non-integer primary key of the table" do mock_db = double(:database) expect(mock_db).to receive(:tables).at_least(:once).and_return([]) table = { :primary_key => :foo, :columns => [{:name => :foo, :column_type => :binary}, {:name => :bar, :column_type => :varchar}] } expected = <<-END create_table :example_table do binary :foo, :null => false varchar :bar, :null => false primary_key [:foo] end END expect(Sequel::MigrationBuilder.new(mock_db).create_table_statement(:example_table, table).join("\n")).to eql(expected.strip) end it "should add the table options do the create_table statement" do mock_db = double(:database) expect(mock_db).to receive(:tables).at_least(:once).and_return([]) table = { :table_options => {:engine => "myisam"}, :columns => [{:name => :foo, :column_type => :integer}] } expected = <<-END create_table :example_table, :engine => "myisam" do integer :foo, :null => false end END expect(Sequel::MigrationBuilder.new(mock_db).create_table_statement(:example_table, table).join("\n")).to eql(expected.strip) end it "should add indexes to the create_table statement" do mock_db = double(:database) expect(mock_db).to receive(:tables).at_least(:once).and_return([]) table = { :indexes => {:foo_index => {:columns => :foo, :unique => true}}, :columns => [{:name => :foo, :column_type => :integer}] } expected = <<-END create_table :example_table do integer :foo, :null => false index :foo, :name => :foo_index, :unique => true end END result = Sequel::MigrationBuilder. new(mock_db). create_table_statement(:example_table, table). join("\n") expect(result).to eql(expected.strip) end context "when a table needs to be altered" do before :each do @tables = { :example_table => { :indexes => {:foo_index => {:columns => :foo, :unique => true}}, :columns => [{:name => :foo, :column_type => :integer}, {:name => :bar, :column_type => :varchar}]} } @mock_db = double(:database) expect(@mock_db).to receive(:tables).at_least(:once).and_return([:example_table]) expect(@mock_db).to receive(:indexes).with(:example_table, :partial => true).and_return({}) expect(@mock_db).to receive(:schema).with(:example_table).and_return([[:foo, {:type => :integer, :db_type => "smallint(5) unsigned", :allow_null => true, :ruby_default => 10}]]) end it "should return an alter table statement with column changes for #generate_up" do expected = <<-END change do alter_table :example_table do set_column_type :foo, :integer, :default => nil set_column_allow_null :foo, false add_column :bar, :varchar, :null => false add_index :foo, :name => :foo_index, :unique => true end end END expect(Sequel::MigrationBuilder.new(@mock_db).generate_migration_body(@tables).join("\n")).to eql(expected.strip) end it "should return separate alter table statements when option is set" do expected = <<-END change do alter_table :example_table do set_column_type :foo, :integer, :default => nil end alter_table :example_table do set_column_allow_null :foo, false end alter_table :example_table do add_column :bar, :varchar, :null => false end alter_table :example_table do add_index :foo, :name => :foo_index, :unique => true end end END expect(Sequel::MigrationBuilder.new(@mock_db, :separate_alter_table_statements => true).generate_migration_body(@tables).join("\n")).to eql(expected.strip) end it "should drop and add columns instead of changing them if immutable_columns is set" do tables = { :example_table => { :indexes => nil, :columns => [{:name => :foo, :column_type => :integer}] } } expected = <<-END change do alter_table :example_table do drop_column :foo end alter_table :example_table do add_column :foo, :integer, :null => false, :default => 0 end end END expect(Sequel::MigrationBuilder.new(@mock_db, :separate_alter_table_statements => true, :immutable_columns => true).generate_migration_body(tables).join("\n")).to eql(expected.strip) end end end
require 'net/http' require 'qu-mongo' require 'qu-immediate' JobsDatabase = Mongo::Connection.new Qu.configure do |c| c.connection = Mongo::Connection.new.db("openreqs-qu") end class Clone def self.uri_escape(uri) uri.gsub(/([^a-zA-Z0-9_.-]+)/) do '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase end end def self.perform(db_name, url) mongo = JobsDatabase.db(db_name) mongo["docs"].remove docs_list = Net::HTTP.get(URI.parse(url + "/d.json")) docs = JSON.load(docs_list) docs.each {|doc_name| doc = JSON.load(Net::HTTP.get(URI.parse(url + "/#{uri_escape(doc_name)}.json?with_history=1"))) doc.each {|v| v["date"] = Time.parse(v["date"])} mongo["docs"].insert doc } end end class Find def self.uri_escape(uri) uri.gsub(/([^a-zA-Z0-9_.-]+)/) do '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase end end def self.perform(db_name, url) mongo = JobsDatabase.db(db_name) remote_text = Net::HTTP.get(URI.parse(url + "/a.json")) remote = JSON.load(remote_text) peer_request = { "date" => Time.now.utc, "server" => true, "_name" => remote["_name"], "local_url" => url, "key" => remote["key"] } mongo["peers.register"].insert peer_request end end class Sync def self.uri_escape(uri) uri.gsub(/([^a-zA-Z0-9_.-]+)/) do '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase end end def self.perform(db_name, remote_name) mongo = JobsDatabase.db(db_name) remote = mongo["peers"].find_one("_name" => remote_name) doc_versions = {} docs_list = Net::HTTP.get(URI.parse(remote["local_url"] + "/d.json")) docs = JSON.load(docs_list) mongo["docs.#{remote_name}"].remove self_versions = {} mongo["docs"].find( {"_name" => {"$in" => docs}}, {:fields => ["_name", "date"], :sort => ["date", :desc]} ).each {|doc| self_versions[doc["_name"]] ||= doc["date"] } docs.each {|doc_name| self_date = self_versions[doc_name] doc_url = remote["local_url"] + "/#{uri_escape(doc_name)}.json?with_history=1" # doc_url << "&after=#{self_date.xmlschema(2)}" if self_date doc_json = Net::HTTP.get(URI.parse(doc_url)) doc = JSON.load(doc_json) doc.each {|v| v["date"] = Time.parse(v["date"])} mongo["docs.#{remote_name}"].insert doc } end end class DocPull def self.uri_escape(uri) uri.gsub(/([^a-zA-Z0-9_.-]+)/) do '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase end end def self.perform(db, name, remote_name, doc_name) mongo = JobsDatabase.db(db_name) last_local_doc = mongo["docs"].find_one({"_name" => doc_name}, {:fields => "date", :sort => ["date", :desc]}) # Insert docs options = {} remote_doc_versions = DocVersions.new(mongo, :name => doc_name, :peer => remote_name, :after => last_local_doc && last_local_doc["date"]) remote_doc_versions.each {|doc| mongo["docs"].insert doc.to_hash} last_remote_doc = remote_doc_versions.first.to_hash last_remote_doc.delete("_id") last_remote_doc["date"] = Time.now.utc mongo["docs"].insert last_remote_doc end end
class User < ActiveRecord::Base def self.from_omniauth(auth_info) where(uid: auth_info[:uid]).first_or_create do |new_user| new_user.uid = auth_info.uid new_user.name = auth_info.extra.raw_info.name new_user.nickname = auth_info.extra.raw_info.login new_user.token = auth_info.credentials.token new_user.avatar_url = auth_info.extra.raw_info.avatar_url end end def stars stars = UserService.new(self).stars end def following following = UserService.new(self).following formatted_following = following.map do |follow| Following.new(follow) end end def followers followers = UserService.new(self).followers formatted_followers = followers.map do |follow| Follower.new(follow) end end def repos repos = UserService.new(self).repos formatted_repos = repos.map do |repo| Repository.new(repo) end formatted_repos end def organizations organizations = UserService.new(self).organizations formatted_orgs = organizations.map do |organization| Organization.new(organization) end formatted_orgs end def commits formatted_commits = [] repos = UserService.new(self).repos repos_commits = repos.map do |repo| UserService.new(self).repo_commits(repo) end repos_commits.map do |commits| commits.find_all do |commit| commit["author"]["id"] == self.uid.to_i end.each do |commit| formatted_commits << Commit.new(commit) end end sorted_commits = formatted_commits.sort_by do |commit| commit.created_at end.reverse sorted_commits[0...10] end end
class AddIndexesToNotations < ActiveRecord::Migration[4.2] def change add_index :notations, :concept_id end end
class ContactCategory < ActiveRecord::Base has_many :contacts, dependent: :restrict_with_error validates :name, presence: true validates :email, presence: true has_enumeration_for :status, with: CommonStatus, required: true, create_helpers: true, create_scopes: true default_scope { order(:name) } end
describe "get projects" do context "when I list all projects" do let(:user) { build(:user) } let(:token) { ApiUser.token(user.email, user.password) } let(:result) { ApiProject.find_projects("", token) } it { expect(result.response.code).to eql "200" } end context "when I list one project" do let(:user) { build(:user) } let(:token) { ApiUser.token(user.email, user.password) } let(:project) { ApiProject.create_project(build(:new_project, assignedTo: user.id).to_hash, token) } let(:id_project) { project["project"].values[1] } let(:result) { ApiProject.find_projects(id_project, token) } it { expect(result.response.code).to eql "200" } end context "when I searching a project that not exist" do let(:user) { build(:user) } let(:token) { ApiUser.token(user.email, user.password) } let(:result) { ApiProject.find_projects("23ff", token) } it { expect(result.response.code).to eql "400" } it { expect(result.parsed_response["error"]).to eql "Error loading project" } end context "when token number is wrong" do let(:user) { build(:user) } let(:token) { ApiUser.token(user.email, user.password) } let(:result) { ApiProject.find_projects("", "xpto") } it { expect(result.response.code).to eql "401" } it { expect(result.parsed_response["error"]).to eql "Token invalid" } end end
# # Author:: Matt Ray <matt@opscode.com> # Cookbook Name:: drbd # Recipe:: pair # # Copyright 2011, Opscode, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/shell_out' include_recipe "drbd" if node.key? :drbd and node[:drbd].key? :resources then node[:drbd][:resources].each do |name, data| drbd_pair name do action [:create, :bootstrap] disk data[:disk] remote_host data[:remote_host] device data[:device] if data.key? :device master data[:master] if data.key? :master local_ip data[:local_ip] if data.key? :local_ip local_port data[:local_port] if data.key? :local_port remote_ip data[:remote_ip] if data.key? :remote_ip remote_port data[:remote_port] if data.key? :remote_port end end end
package 'polipo' do if(ver = node[:polipo][:install][:version]) version ver end if(act = node[:polipo][:install][:action]) action act.to_sym end notifies :restart, 'service[polipo]' end file File.join(node[:polipo][:directories][:config], 'config') do content lazy{ node[:polipo][:config].map do |key, value| parts = key.split('_') "#{parts.first}#{parts[1,parts.size].map(&:capitalize).join} = #{value}" end.join("\n") } notifies :restart, 'service[polipo]' end file File.join(node[:polipo][:directories][:config], 'options') do content lazy{ node[:polipo][:options][:method].map do |value| "method #{value}" end.join("\n") } notifies :restart, 'service[polipo]' end file File.join(node[:polipo][:directories][:config], 'forbidden') do content lazy{ node[:polipo][:forbidden].join("\n") } notifies :restart, 'service[polipo]' end service 'polipo' do action :start end
class Access < ActiveRecord::Base belongs_to :meditation belongs_to :mystic validates :mystic_id, :presence => true validates :meditation_id, :uniqueness => {scope: :mystic_id}, :presence => true end
# require modules here require 'yaml' require 'pry' def load_library(yaml_file) yaml_data = YAML::load(File.open(yaml_file)) definition_hash = {} yaml_data.each do |definition, array_of_emoticons| japanese_emoticon = yaml_data[definition][1] definition_hash["get_meaning"] ||= {} definition_hash["get_meaning"][japanese_emoticon] ||= definition end yaml_data.each do |definition, array_of_emoticons| english_emoticon = yaml_data[definition][0] japanese_emoticon = yaml_data[definition][1] definition_hash["get_emoticon"] ||= {} definition_hash["get_emoticon"][english_emoticon] ||= japanese_emoticon end definition_hash end def get_japanese_emoticon(yaml_file, emoticon) emoticon_finder = load_library(yaml_file) if emoticon_finder["get_emoticon"][emoticon] emoticon_finder["get_emoticon"][emoticon] else "Sorry, that emoticon was not found" end end def get_english_meaning(yaml_file, emoticon) emoticon_finder = load_library(yaml_file) if emoticon_finder["get_meaning"][emoticon] emoticon_finder["get_meaning"][emoticon] else "Sorry, that emoticon was not found" end end
# Was named users_controller.rb just in case class UsersController < ApplicationController before_action :authenticate_user! skip_before_action :authenticate_user!, :only => [:create] # PATCH/PUT /users def create puts("Create User Firing in users_controller") user = User.new(user_params) if @user.save render :show else render json: { errors: @current_user.errors }, status: :unprocessable_entity end end def show end # PATCH /users/1 def update puts("Update User Firing in users_controller") if current_user.update_attributes(user_params) render :show else render json: { errors: current_user.errors }, status: :unprocessable_entity end end private def user_params params.require(:users).permit(:name, :email, :encrypted_password, :wallet_address) end end
class PostObserver < ActiveRecord::Observer observe :post def after_create(photo) message = "#{photo.user.name} posted a "+photo.media_type+"." notify_followers(message) end def notify_followers(message) APN::Device.all.each do |device| notification = APN::Notification.create(:device => device, :badge => 0, :alert=>message) APN::Notification.send_notifications end end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe TransferMailer, type: :mailer do describe '#created_transfer' do let(:user) { create :user } let(:other_user) { create :other_user } let(:transfer) { create :transfer, from: user, to: other_user } let(:mail) { described_class.created_transfer(transfer) } it 'sends an email' do expect { mail.deliver_now } .to change(ActionMailer::Base.deliveries, :count).by(1) end it 'renders the subject' do expect(mail.subject) .to eql('Bartek Szef has send you a transfer of 15.00 PLN') end it 'renders the receiver email' do expect(mail.to).to eql(['krus@test.net']) end it 'renders the sender email' do expect(mail.from).to eql(['admin@lunchiatto.com']) end end describe '#accepted_transfer' do let(:user) { create :user } let(:other_user) { create :other_user } let(:transfer) do create :transfer, from: user, to: other_user, status: :accepted end let(:mail) { described_class.accepted_transfer(transfer) } it 'sends an email' do expect { mail.deliver_now } .to change(ActionMailer::Base.deliveries, :count).by(1) end it 'renders the subject' do expect(mail.subject) .to eql('Kruszcz Puszcz has accepted your transfer of 15.00 PLN') end it 'renders the receiver email' do expect(mail.to[0]).to match(/bartek\d+@test.net/) end it 'renders the sender email' do expect(mail.from).to eql(['admin@lunchiatto.com']) end end describe '#rejected_transfer' do let(:user) { create :user } let(:other_user) { create :other_user } let(:transfer) do create :transfer, from: user, to: other_user, status: :rejected end let(:mail) { described_class.rejected_transfer(transfer) } it 'sends an email' do expect { mail.deliver_now } .to change(ActionMailer::Base.deliveries, :count).by(1) end it 'renders the subject' do expect(mail.subject) .to eql('Kruszcz Puszcz has rejected your transfer of 15.00 PLN') end it 'renders the receiver email' do expect(mail.to[0]).to match(/bartek\d+@test.net/) end it 'renders the sender email' do expect(mail.from).to eql(['admin@lunchiatto.com']) end end describe '#pending_transfers' do let(:user) { create :user } let(:other_user) { create :other_user } let(:transfer) do create :transfer, from: user, to: other_user, status: :rejected end let(:mail) { described_class.pending_transfers([transfer], other_user) } it 'sends an email' do expect { mail.deliver_now } .to change(ActionMailer::Base.deliveries, :count).by(1) end it 'renders the subject' do expect(mail.subject).to eql('You have pending transfers!') end it 'renders the receiver email' do expect(mail.to).to eql(['krus@test.net']) end it 'renders the sender email' do expect(mail.from).to eql(['admin@lunchiatto.com']) end end end
require 'yaml' require 'juggalo/portlet' require 'juggalo/page' require 'juggalo/page/loader/base' module Juggalo class Page::Loader class YAML < Base def initialize(location) @location = location end def page page_hash["page"] end def components page_hash["components"].map { |c| create_component_from c } end private def page_hash ::YAML::load(File.open(@location)) end end end end
describe 'Parsing des décors du film' do before(:all) do parse_collecte(folder_test_6) end let(:donnee_decors) { @donnee_decors ||= begin film.pstore.transaction do |ps| ps[:decor] end end } let(:saved_decors) { @saved_decors ||= donnee_decors[:items] } describe 'Le parse du film' do it 'parse les décors' do expect(film.decors).not_to eq nil end it 'enregistre les décors dans le pstore du film' do d = donnee_decors # puts "Donnée décors : #{d.inspect}" expect(d).not_to eq nil expect(d).to have_key :items expect(d[:items]).to be_instance_of Hash end describe 'enregistre dans le pstore du film' do it 'le bon nombre de décors' do # puts "saved_decors : #{saved_decors.inspect}" expect(saved_decors.count).to eq 6 end describe 'les bonnes données associées à' do { 1 => {decors_ids: [1], decor: 'MAISON DE JOE', sous_decor: 'GARAGE', lieu: 'I'}, 2 => {decors_ids: [2], decor: 'MAISON DE JAN', sous_decor: nil, lieu: 'I'}, 3 => {decors_ids: [3], decor: 'JARDIN', sous_decor: nil, lieu: 'E'}, 4 => {decors_ids: [4], decor: 'MAISON DE JOE', sous_decor: 'SALON', lieu: 'I'}, 5 => {decors_ids: [3], lieu: 'E'}, 6 => {decors_ids: [4], lieu: 'E'}, 7 => {decors_ids: [3,5], decor_alt:'MAISON DE JOE', lieu_alt:'I'}, 8 => {decors_ids: [6], decor: 'ABRIBUS', lieu:'E'} }.each do |sid, sdata| it "La scène #{sid} avec #{sdata.inspect}" do s = film.scenes[sid] expect(s.decors_ids).to eq sdata[:decors_ids] did = sdata[:decors_ids].first decor = film.decors[did] if sdata[:decor] expect(sdata[:decor]).to eq decor.decor expect(sdata[:sous_decor]).to eq decor.sous_decor expect(sdata[:lieu]).to eq decor.lieu end if sdata[:decors_ids].count > 1 did = sdata[:decors_ids].last decor = film.decors[did] expect(sdata[:decor_alt]).to eq decor.decor expect(sdata[:sous_decor_alt]).to eq decor.sous_decor expect(sdata[:lieu_alt]).to eq decor.lieu end end end end end end end
def string_to_integer(string) number_map = { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9 } integer = 0 string.reverse.each_char.with_index(1) do |c, index| integer += (number_map[c] * (10 ** index)) end integer / 10 end puts string_to_integer('9876543210') puts string_to_integer('43219') #== 4321 puts string_to_integer('570') #== 570
module Asciidoctor module Converter; end # required for Opal # An abstract base class for defining converters that can be used to convert # {AbstractNode} objects in a parsed AsciiDoc document to a backend format # such as HTML or DocBook. # # Concrete subclasses must implement the {#convert} method and, optionally, # the {#convert_with_options} method. class Converter::Base include Converter end # An abstract base class for built-in {Converter} classes. class Converter::BuiltIn def initialize backend, opts = {} end # Public: Converts the specified {AbstractNode} using the specified transform. # # See {Converter#convert} for more details. # # Returns the [String] result of conversion def convert node, transform = nil transform ||= node.node_name send transform, node end # Public: Converts the specified {AbstractNode} using the specified transform # with additional options. # # See {Converter#convert_with_options} for more details. # # Returns the [String] result of conversion def convert_with_options node, transform = nil, opts = {} transform ||= node.node_name send transform, node, opts end alias :handles? :respond_to? # Public: Returns the converted content of the {AbstractNode}. # # Returns the converted [String] content of the {AbstractNode}. def content node node.content end alias :pass :content # Public: Skips conversion of the {AbstractNode}. # # Returns [NilClass] def skip node nil end end end
class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] # GET /users # GET /users.json def index @users = User.all end # GET /users/1 # GET /users/1.json def show end # GET /users/new def new @user = User.new end # GET /users/1/edit def edit @user = User.find(params[:id]) end # POST /users # POST /users.json def create @user = User.new(user_params) if @user.save user_log = User.authenticate(user_params[:email], user_params[:password]) if user_log session[:user_id] = user_log.id end redirect_to root_url else render "new" end end # PATCH/PUT /users/1 # PATCH/PUT /users/1.json def update @user = User.find(params[:id]) if @user.update(user_params) redirect_to @user else render 'edit' end end # DELETE /users/1 # DELETE /users/1.json def destroy @user = User.find(params[:id]) @user.destroy redirect_to admin_path end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def user_params params.require(:user).permit(:email, :password, :username) end end
require 'nesta-contentfocus-extensions/paths' module Nesta class App < Sinatra::Base helpers do def authenticated?(page) return false if session[:passwords].nil? || session[:passwords].empty? page.passwords.detect do |password| session[:passwords].include? password end end def find_template(view_path, name, engine, &block) views = [view_path] views.unshift(*Nesta::ContentFocus::Paths.view_paths) views.each { |v| super(v, name, engine, &block) } end def body_class classes = [@body_class] if @page && @page.metadata('flags') classes += @page.metadata('flags').split(',') classes << 'bare' if @page.flagged_as? 'sign-up' end classes.compact.sort.uniq.join(' ') end def gravatar(email) if email hash = Digest::MD5.hexdigest(email.downcase) "//www.gravatar.com/avatar/#{hash}" end end end end end