text
stringlengths
10
2.61M
class Cocktail attr_accessor :name, :recipe, :category def initialize(name, recipe, category) @name = name @recipe = recipe.split @category = category end end
RSpec.describe Crawler::Db::UrlBuffer, type: :use_db do describe '.fetch_for' do let(:host) { 'rspec.test' } let(:url) { "http://#{host}/path" } subject { described_class.fetch_for(host) } before { described_class.insert(hostname: host, url: url) if url } it 'returns record and removes it from table' do expect(subject).to eq url expect(described_class.count).to be 0 end context 'if table is empty' do let(:url) { nil } it { is_expected.to be_nil } end end describe '.buffering' do let(:source_host) { 'w3.rspec.test' } subject do described_class.buffering(source_host, [ [Addressable::URI.parse('http://rspec.test/2'), 2], [Addressable::URI.parse('http://www.rspec.test/0'), 0], [Addressable::URI.parse('http://rspec.test/1'), 1], [Addressable::URI.parse('http://rspec.test/0'), 0], [Addressable::URI.parse('http://www.rspec.test/1'), 1], [Addressable::URI.parse('http://www.rspec.test/2'), 2] ]) end it 'saves url' do subject expect(described_class.order(:url).map([:url, :hostname])).to contain_exactly( ['http://rspec.test/1', 'rspec.test'], ['http://rspec.test/2', 'rspec.test'], ['http://www.rspec.test/1', 'www.rspec.test'], ['http://www.rspec.test/2', 'www.rspec.test'] ) end it "returns url wasn't buffered" do expect(subject).to contain_exactly( [Addressable::URI.parse('http://www.rspec.test/0'), 0], [Addressable::URI.parse('http://rspec.test/0'), 0] ) end context 'if host of url equals source_host' do let(:source_host) { 'rspec.test' } it 'saves url' do subject expect(described_class.order(:url).map([:url, :hostname])).to contain_exactly( ['http://rspec.test/0', 'rspec.test'], ['http://rspec.test/1', 'rspec.test'], ['http://rspec.test/2', 'rspec.test'], ['http://www.rspec.test/1', 'www.rspec.test'], ['http://www.rspec.test/2', 'www.rspec.test'] ) end it "returns url wasn't buffered" do expect(subject).to contain_exactly( [Addressable::URI.parse('http://www.rspec.test/0'), 0] ) end end end end
module ESP32 module GPIO include Constants class << self alias :digital_write :digitalWrite alias :digital_read :digitalRead alias :analog_write :analogWrite alias :analog_read :analogRead alias :pin_mode :pinMode alias :hall_read :hallRead end class Pin PIN_MODE = { pullup: ESP32::GPIO::INPUT_PULLUP, pulldown: ESP32::GPIO::INPUT_PULLDOWN, input: ESP32::GPIO::INPUT, output: ESP32::GPIO::OUTPUT, inout: ESP32::GPIO::INPUT_OUTPUT } HIGH = ESP32::GPIO::HIGH LOW = ESP32::GPIO::LOW attr_reader :pin def initialize pin, mode = :input mode = PIN_MODE[mode] unless mode.is_a?(Integer) @pin = pin self.mode= mode end def analog_read GPIO.analog_read pin end def read GPIO.digital_read pin end def analog_write val GPIO.analog_write pin, val end def write val GPIO.digital_write pin, val val end def high! write HIGH end def low! write LOW end def off low! end def on high! end def mode= mode GPIO.pin_mode pin, mode end alias :digital_write :write alias :digital_read :read def high? read == LOW end def low? read == HIGH end # the following only work if GPIO_MODE_INPUT_OUTPUT ie, Pin.new(io_num, :inout) def toggle write((read==HIGH) ? LOW : HIGH) end end end end
module Api class IssuesController < ApiController before_action :authenticate_resource def create issue = Issue.create_by_manual(params, @current_resource) if issue.save render json: issue else status_code = 422 serialize_data = build_serialize_data( ApplicationHelper.pretty_error(issue, false), status_code ) render json: ErrorSerializer.new(serialize_data).to_json, status: status_code end end end end
class Timecard < ActiveRecord::Base belongs_to :location, inverse_of: :timecards belongs_to :user, inverse_of: :timecards belongs_to :activity, inverse_of: :timecard validates :location, presence: true validates :user, presence: true validates :start_time, presence: true validates :stop_time, presence: true, on: :update scope :published, -> { where(published: true) } scope :unpublished, -> { where(published: false) } def elapsed_seconds stop_time - start_time end def elapsed_rounded_hours (elapsed_hours * 4).round / 4.0 end def publish_activity activity = user.activities.create(location_id: location.id, date: stop_time.to_date, hours: elapsed_rounded_hours, description: notes) update_attributes({activity_id: activity.id, published: true}) if activity.save! end private def elapsed_hours (elapsed_seconds / 3600).round(2) end end
class AddBodyToDocumentTemplates < ActiveRecord::Migration[5.0] def change add_column :document_templates, :body, :text, null: false, default: '' change_column_default :document_templates, :body, nil end end
namespace :generators do desc "Generate random questions and answers associated with them" task :question_and_answers => :environment do number_of_questions = ENV['number_of_questions'] ? ENV['number_of_questions'].to_i : 50 number_of_answers = ENV['number_of_answers'] ? ENV['number_of_answers'].to_i : 10 number_of_questions.times do question = Question.create(title: Faker::Lorem.sentence(10), body: Faker::Lorem.sentence(50)) number_of_answers.times do question.answers.create(body: Faker::Lorem.sentence(12)) end end puts "Generated #{number_of_questions} question with #{number_of_answers} answers each" end desc "Generate default categories" task :default_categories => :environment do ["Technology", "Sports", "Entertainment", "Travel", "Photography","Food", "Cars", "Programming", "Design", "Investing", "Real Estate"].each do |category_name| Category.create(name: category_name) end end end
require 'rails_helper' RSpec.describe 'As a logged in user' do before(:each) do user_logs_in end context 'when I visit /companies' do VCR.use_cassette('companies_filtering_zip') do xscenario 'I can input a zip and only the companies within distance are shown', :js => true do denver_co = create_denver_company boulder_co = create_boulder_company co_springs_co = create_colorado_springs_company visit '/' check('companies_within') select '10', :from => 'distance_select' fill_in 'zip', with: '80203' click_button 'Go' expect(page).to have_content(denver_co.locations.first.street_address) expect(page).to_not have_content(boulder_co.locations.first.street_address) expect(page).to_not have_content(co_springs_co.locations.first.street_address) end xscenario 'I can choose from the dropdown and have it filter with a range of those miles', :js => true do denver_co = create_denver_company boulder_co = create_boulder_company co_springs_co = create_colorado_springs_company visit '/' check('companies_within') select '100', :from => 'distance_select' fill_in 'zip', with: '80203' click_button 'Go' expect(page).to have_content(denver_co.locations.first.street_address) expect(page).to have_content(boulder_co.locations.first.street_address) expect(page).to have_content(co_springs_co.locations.first.street_address) end end end end
module Poe class KeyboardHandler def self.output(&block) loop do key = Curses.getch unless key.nil? case key when Curses::Key::UP then yield :key_up when Curses::Key::DOWN then yield :key_down when Curses::Key::LEFT then yield :key_left when Curses::Key::RIGHT then yield :key_right when Curses::Key::BACKSPACE, 127, 263 then yield :backspace when 13 then yield :return when 3 then yield :ctrl_c when Curses::KEY_RESIZE, 410 then yield :resize else yield key end end end end end end
# == Schema Information # # Table name: schools # # id :integer not null, primary key # name :string(255) # code :string(255) # created_at :datetime # updated_at :datetime # free_trial :boolean default(TRUE) # class School < ActiveRecord::Base has_many :users has_many :classrooms has_many :pins, through: :users validates_uniqueness_of :code accepts_nested_attributes_for :users scope :free_trial, -> { where("created_at > ? AND free_trial", School.free_trial_days.days.ago)} scope :active, -> { where("created_at > ? OR NOT free_trial", School.free_trial_days.days.ago)} def students self.users.students end def teachers self.users.teachers end def admins self.users.admins end def is_active? (Date.today - self.created_at.to_date) < School.free_trial_days or not free_trial end # will return a negative number if the school is not on a free trial and is past 90 days def free_trial_days_remaining (School.free_trial_days - (Date.today - self.created_at.to_date)).to_i end def self.free_trial_days 90 end end
# frozen_string_literal: true module Decidim module Opinions module Metrics class VotesMetricManage < Decidim::MetricManage def metric_name "votes" end def save cumulative.each do |key, cumulative_value| next if cumulative_value.zero? quantity_value = quantity[key] || 0 category_id, space_type, space_id, opinion_id = key record = Decidim::Metric.find_or_initialize_by(day: @day.to_s, metric_type: @metric_name, organization: @organization, decidim_category_id: category_id, participatory_space_type: space_type, participatory_space_id: space_id, related_object_type: "Decidim::Opinions::Opinion", related_object_id: opinion_id) record.assign_attributes(cumulative: cumulative_value, quantity: quantity_value) record.save! end end private def query return @query if @query spaces = Decidim.participatory_space_manifests.flat_map do |manifest| manifest.participatory_spaces.call(@organization).public_spaces end opinion_ids = Decidim::Opinions::Opinion.where(component: visible_component_ids_from_spaces(spaces.pluck(:id))).except_withdrawn.not_hidden.pluck(:id) @query = Decidim::Opinions::OpinionVote.joins(opinion: :component) .left_outer_joins(opinion: :category) .where(opinion: opinion_ids) @query = @query.where("decidim_opinions_opinion_votes.created_at <= ?", end_time) @query = @query.group("decidim_categorizations.id", :participatory_space_type, :participatory_space_id, :decidim_opinion_id) @query end def quantity @quantity ||= query.where("decidim_opinions_opinion_votes.created_at >= ?", start_time).count end end end end end
class GoalSet < ActiveRecord::Base has_many :goals,:dependent => :delete_all attr_accessible :start_time, :daily, :goals_attributes accepts_nested_attributes_for :goals, :allow_destroy => true, :reject_if => :all_blank validates :start_time, :uniqueness=>true def completed_goals goals.complete.count end def start_time_readable if start_time.to_date == Date.today "Today" else start_time.strftime("%A") end end end
class TweetsController < ApplicationController before_action :authenticate_user! before_action :set_tweet, only: [:show, :edit, :update, :destroy] def index @all_tweets = current_user.tweets @all_users = User.where.not(id: current_user.id) end def show end def edit end def create @tweet = current_user.tweets.build(tweet_params) if @tweet.save redirect_to tweets_path else render :new end end def update if @tweet.update(tweet_params) redirect :index else render :edit end end def destroy @tweet.destroy end private def set_tweet @tweet = Tweet.find(params[:id]) end def tweet_params params.require(:tweet).permit(:content) end end
# Evaluate the best possible coordinate for of the next bomb. This is # done via by positioning all remaining enemy ships in all possible # ways over the board. Then the probability of a hit is computed by # counting how many times a particular bomb had hit a possible ship # placement. # # If there are hits on the board already, then all adjacent cells get # a probability boost that is exponentially proportional to the number # of hits in the possible placement. Cells containing sunk ships are # ignored. The exponential rule forces a directional kills as ships # are either horizontal or vertical. class ProbabilityBoard def initialize player @player = player @board = player.board @score_board = [] LordNelsonPlayer::GRID_SIZE.times do @score_board.push(Array.new(LordNelsonPlayer::GRID_SIZE, 0)) end compute end # Positions each remaining enemy ship using every possibly # placement. The score_board is a matrix where each cell contains # the damage score for a hit placed at (x, y). def compute @board.each_starting_position_and_direction do |x, y, dx, dy| @player.remaining.each do |length| placement = generate_placement x, y, dx, dy, length if placement.length == length score_placement placement end end end end def generate_placement x, y, dx, dy, length xi, yi = x, y placement = [[xi, yi]] (length-1).times do xi += dx yi += dy break unless @board.on?(xi, yi) if @board.hit_or_unknown?(xi, yi) placement.push([xi, yi]) end end placement end def count_hits_in placement return 0 unless @player.kill_mode? hits = placement.select { |x, y| @board.hit?(x, y) }.size end def score_placement placement hits = count_hits_in placement placement.each do |x, y| if @board.unknown?(x, y) @score_board[y][x] += 100**hits end end end # Computes the coordinate with the highest score. If multiple peaks # are found, a random one is selected. def best_move max_score = 0 moves = [] @board.each_starting_position do |x, y| next unless @board.unknown?(x, y) if @score_board[y][x] > max_score max_score = @score_board[y][x] moves = [[x, y]] elsif @score_board[y][x] == max_score moves.push([x, y]) end end moves.sample end end
require 'machinist/active_record' Road.blueprint(:road1) do user_id { rand(1..1000) } name { Faker::Lorem.sentence(word_count = 4) } description { Faker::Lorem.paragraph(sentence_count = 6) } start_point { "POINT(#{-74.095771} #{41.236122})" } end_point { "POINT(#{-74.065559} #{41.230571})" } g_map_line { 'a~tzFbzfcMO{@Co@Fu@Pw@RWVQd@GVDl@TdB~@TBP?TI~AmALWBUBo@AkBF{BBe@Jk@nAqEb@_AvAgBfH}H|AiB^i@`@w@^y@|@qAlAcA|B{A`Ag@~CqA`DuAt@k@b@[TYl@w@^o@nCaGhAqCt@sCr@gDJ_ADeBCyAGk@WqASu@_@{@k@mAcBgD}@wBy@iDM_A]gD[eA]i@YYm@a@}@a@_@S_@[}@oAe@uAk@mCyAoFwAwEmAaEc@{@Ug@Me@q@aEMmA?w@LiADi@' } path { "LINESTRING (-71 41, -71.1 41.1, -71.2 41.2, -71.3 41.3)" } road_distance { 10000 } start_address { Faker::Address.street_address + Faker::Address.city + Faker::Address.zip_code } end_address { Faker::Address.street_address + Faker::Address.city + Faker::Address.zip_code } twistiness_rating { (rand * 4 ) + 1 } twistiness_raters { rand(1..1000) } scenery_rating { (rand * 4 ) + 1 } scenery_raters { rand(1..1000) } end Road.blueprint(:road2) do user_id { rand(1..1000) } name { Faker::Lorem.sentence(word_count = 4) } description { Faker::Lorem.paragraph(sentence_count = 6) } start_point { "POINT(#{-74.105582} #{41.217532})" } end_point { "POINT(#{-74.075584} #{41.217338})" } g_map_line { 'chqzFn{bcMFdC@nGTlGj@xLr@jI?f@A\GXC\JXh@tAd@~AVp@B`@CpBBj@HRLJzBz@l@\b@b@PZ\x@Hr@KvAXjC\rBPh@p@dENjAb@dDf@tEZ`BdAxCHNf@^NXHZXrC`AfFNn@Xb@DV?^UvAUt@SZw@v@uBlA{@x@QLWH}@F_@LyA|@STy@`B[l@On@sAnF[dAa@|@k@p@_@Za@j@Qp@Kz@mAvJWjAOZ' } path { "LINESTRING (-72 42, -72.1 42.1, -72.2 42.2, -72.3 42.3)" } road_distance { 20000 } start_address { Faker::Address.street_address + Faker::Address.city + Faker::Address.zip_code } end_address { Faker::Address.street_address + Faker::Address.city + Faker::Address.zip_code } twistiness_rating { (rand * 4 ) + 1 } twistiness_raters { rand(1..1000) } scenery_rating { (rand * 4 ) + 1 } scenery_raters { rand(1..1000) } end Road.blueprint(:road3) do user_id { rand(1..1000) } name { Faker::Lorem.sentence(word_count = 4) } description { Faker::Lorem.paragraph(sentence_count = 6) } start_point { "POINT(#{-73.137567} #{42.89244})" } end_point { "POINT(#{-72.953031} #{42.891182})" } g_map_line { '{cxdGxug|L{ClCqBjBgIfImIvIeAnAm@x@m@dAu@hBm@tB_@nBMrACfBFzAb@zCrAbIb@nB~B`Hz@rC^nB\lCLbBFtCPrBZ|ARvANlBBtACrAG|@y@lGKrA?|BPjSEvBIjBM`B_AzLMvBErAF~DF`AV|BZvAl@~Bp@vDVjDHjC?`BEjCa@fMEvDJ`BNpAP|@\jAz@rBxCrHx@hCn@nCZlBVbCZpEh@`JPhBX`B^~A`@pAnBlEtDzH|@`Cr@jCb@pCJlAJjD@fPHfOFfOGrEGbBUtDs@zGSbBgBfJw@vDc@lCKlACpA@dBHnBd@jGJ~B?jBGjAKbAOdAMf@_CbJw@bCuAxC}@zAw@bA_AbAyAhAiA`AgApAk@dAWp@a@tAaAhF]rAm@dBaEbK]bAk@hCg@|Cy@jF_@nBy@vCwAtD]z@Sv@[nBO`CBhBJpBXnCh@pDZ|A`@dBXx@jAlClAlCfAfCtDrIvAnD|@hCh@`Af@p@vAzAp@j@b@z@p@pArAxCjApBx@l@dBbAbAv@n@n@\l@h@vA^nA~CrKTdAb@pDRfGH|@XpA~BdJv@pC`@dArBlEjAxB`AnAxD|DlBnB|BbCjC`Dt@p@VP~BrAnCxArJpE^L~BVj@Hz@VjAl@h@ZrAbArAz@|Ad@v@Lf@B`D\dARh@P`Aj@|@|@n@fAb@lAXpAPbC@v@IjAGv@Mn@YhA_@z@c@t@kFrHi@~@Q`@Mb@YtASnBKnCMvA[zAq@lB{AtDkApFaBhJUfBq@`IYxEAh@@p@BfAD`@Hd@H^`@tAxBfFf@tARt@Pz@LfAF~@?xAC`AEf@W|Ac@rA}CvGk@dBOl@]jBQnAEv@I~A@hCLnBNlAXdBtCnOXzAHn@D~AAr@Gf@I`@Sr@Qb@_@n@_@f@UTWTYNe@Ty@XUDe@?{@Io@U}E{AkBc@mGcAyBScBC{AHcATy@VgAb@aCjAm@^k@f@y@nA]x@wDbKw@jBeAdBsA`BoErEuCrCwFxEyI|G{BxBaDzE}@|Aa@~@[~@U~@UtAOzBCtABz@JtAJv@jApGjAbHd@lCHPz@vA`BbChB|BrB|BvCvCNN' } path { "LINESTRING (-73 43, -73.1 43.1, -73.2 43.2, -73.3 43.3)" } road_distance { 10000 } start_address { Faker::Address.street_address + Faker::Address.city + Faker::Address.zip_code } end_address { Faker::Address.street_address + Faker::Address.city + Faker::Address.zip_code } twistiness_rating { (rand * 4 ) + 1 } twistiness_raters { rand(1..1000) } scenery_rating { (rand * 4 ) + 1 } scenery_raters { rand(1..1000) } end User.blueprint do email { Faker::Internet.email } password { "password" } end Photo.blueprint do description { Faker::Lorem.paragraph(sentence_count = 6) } end Rating.blueprint(:road_twistiness) do rater_id { rand(1..1000) } rated_type { 'road' } rated_id { rand(1..1000) } rated_property { 'twistiness'} rating { rand(1..5) } end Rating.blueprint(:road_scenery) do rater_type { 'user' } rater_id { rand(1..1000) } rated_type { 'road' } rated_id { rand(1..1000) } rated_property { 'scenery' } rating { rand(1..5) } end
describe CorrelationChecker do subject { described_class.new(first_dataset: first_dataset, second_dataset: second_dataset) } context 'with invalid params' do context 'with empty datasets' do let(:first_dataset) { [] } let(:second_dataset) { [] } it 'does not generate result' do expect(subject.perform).to eq false expect(subject.result).to eq nil end end context 'with different datasets' do let(:first_dataset) { [1, 2, 3] } let(:second_dataset) { [1, 2] } it 'does not generate result' do expect(subject.perform).to eq false expect(subject.result).to eq nil end end context 'with duplicates' do let(:first_dataset) { [1, 2, 2, 5, 6] } let(:second_dataset) { [1, 3, 2, 7, 5] } it 'generates result' do expect(subject.perform).to eq false expect(subject.result).to eq nil end end end context 'with valid params' do context 'with equal datasets' do let(:first_dataset) { [1, 2, 3, 4, 5] } let(:second_dataset) { [1, 2, 3, 4, 5] } it 'generates result' do expect(subject.perform).to eq true expect(subject.result).to eq 1 end end context 'with different datasets' do let(:first_dataset) { [1, 2, 3, 4, 5] } let(:second_dataset) { [55, 74, 94, 108, 156] } it 'generates result' do expect(subject.perform).to eq true expect(subject.result).to eq 0.9713332474204632 end end context 'with equal string datasets' do let(:first_dataset) { ['1', '2', '3', '4', '5'] } let(:second_dataset) { ['1', '2', '3', '4', '5'] } it 'generates result' do expect(subject.perform).to eq true expect(subject.result).to eq 1 end end end end
class Api::TasksController < Api::ApplicationController before_action :set_task, only: %i[show edit update] def index @tasks = Task.incomplete.where(user_id: current_user.id) end def show end def create tag = Tag.find_or_create_by(name: params[:tags_attributes][:name]) task = Task.new(task_params) task.task_tags.build(tag_id: tag.id) if task.save render 'api/success' else render 'api/error' end end def edit end def update if task.update(task_params) render 'api/success' else render 'api/error' end end def destroy task = Task.find(params[:id]) task.completion_flg = true task.save render 'api/success' end private def task_params params.require(:task).permit(:title, :content, :expires_at, :completion_flg, tags_attributes:[:name]).merge(user_id: @current_user.id) end def set_task @task = Task.find(params[:id]) end end
# write a method that takes a string of digits # and returns the appropiate number as an integer # you may not use String#to_i or Integer() # assume all characters will be numeric # Examples: # # string_to_integer('4321') == 4321 # string_to_integer('570') == 570 # def string_to_integer(string) # string.split("").map do |letter| # case letter # when '0' then print 0 # when '1' then print 1 # when '2' then print 2 # when '3' then print 3 # when '4' then print 4 # when '5' then print 5 # when '6' then print 6 # when '7' then print 7 # when '8' then print 8 # when '9' then print 9 # end # end # end DIGITS = { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'A' => 10, 'B' => 11, 'C' => 12, 'D' => 13, 'E' => 14, 'F' => 15 } def hexadecimal_to_integer(string) digits = string.upcase.chars.map {|letter| DIGITS[letter]} new_integer = [] digits.each_with_index do |digit, index| new_integer << (digit * 16**(digits.length-1-index)) end new_integer.sum end p hexadecimal_to_integer('4D9f')
require 'rails_helper' describe "the add product process" do it "adds a new product" do visit root_path click_link 'New Product' fill_in 'Name', :with => 'Thingy' fill_in 'Cost', :with => '33.33' fill_in 'Country of origin', :with => 'USA' click_on 'Create Product' expect(page).to have_content 'Your product was successfully added!' expect(page).to have_content 'Thingy' end it "gives an error when no name is entered" do visit '/products/new' click_on 'Create Product' expect(page).to have_content "Name can't be blank" end end
# Use the modulo operator, division, or a combination of both to take a 4 digit number and find the digit in the: # 1) thousands place # 2) hundreds place # 3) tens place # 4) ones place puts 4893 / 1000 puts 4893 % 1000 / 100 puts 4893 % 1000 % 100 / 10 puts 4893 % 1000 % 100 % 10
require_relative '../exceptions.rb' require_relative '../release.rb' require_relative '../formulary.rb' require_relative '../platform.rb' require_relative 'shasum_options.rb' module Crew def self.shasum(args) options, args = ShasumOptions.parse_args(args) Formulary.new.select(args).each do |formula| formula.releases.each do |release| platforms = (formula.namespace == :target) ? ['android'] : options.platforms platforms.each do |platform_name| # an ugly special case for windows toolbox # it seems that everything related to windows is ugly next if formula.name == 'toolbox' and not platform_name.start_with?('windows') # archive = formula.cache_file(release, platform_name) print "#{formula.fqn} #{release}" print (formula.namespace == :target) ? ': ' : " #{platform_name}: " if not File.exist? archive puts "archive not found: #{archive}" else sum = Digest::SHA256.hexdigest(File.read(archive, mode: "rb")) if sum == formula.read_shasum(release, platform_name) puts "OK" elsif options.update? formula.update_shasum release, platform_name puts "updated" else puts "BAD" end end end end end end end
class AddStartDateToLiability < ActiveRecord::Migration def change add_column :liabilities, :start_date, :date end end
class Tweet < ApplicationRecord validates :message, length:{maximum: 14}, presence: true end
require 'net/http' # I know this is terrible, but it avoids additional dependencies module SimpleCov module Formatter class ShieldFormatter module Generators # TODO: Make configurable class ShieldsIO HOST = 'img.shields.io'.freeze PATH = 'badge'.freeze EXTENSION = 'png'.freeze STYLE = 'flat'.freeze def initialize(options) @options = options @image = nil end def generate return @image ||= begin generate! end end def generate! uri = build_uri response = Net::HTTP.get_response(uri) raise(Generators::Error, "Could not fetch image at #{uri} => #{response.msg} (#{response.code})") unless (200..399).cover?(response.code.to_i) return response.body end private :generate! def build_uri parts = [@options.text, @options.status, @options.color].map { |part| CGI.escape(part.to_s) } path = "/#{PATH}/#{parts.join('-')}.#{EXTENSION}" return URI::HTTPS.build(host: HOST, path: path, query: "style=#{STYLE}") end end end end end end
class Sort attr_accessor :array, :sortarray def initialize(array) @array = array @sortarray = [] end def insert_sort(array) target = [] << array.shift while array.length > 0 do item = array.shift insert(item, target) end return target end def insert(item, array) array << item if array.length == 0 0.upto(array.length - 1) do |index| if array[index] < item && array[index + 1] == nil array << item elsif array[index] > item && array[index - 1] == nil array.insert(0, item) elsif array[index] < item && array[index + 1] > item array.insert(index+1, item) end end end def bubble_sort(array) change = 0 (0).upto(array.length - 2) do |index| if array[index] > array[index + 1] mid = array[index] array[index] = array[index + 1] array[index + 1] = mid change = 1 end end return array if change == 0 bubble_sort(array) end def mergesort(array) recursive_array = [] array.each do |number| recursive_array << [number] end return recur(recursive_array) end def recur(array) mg_array = [] return array[0] if array.compact.length == 1 (0 .. (array.length)).step(2) do |index| mg_array << merge(array[index], array[index + 1]) end recur(mg_array) end def merge(array1, array2) mergearray = [] loop do return nil if array1 == nil && array2 == nil return array1 if array2 == nil return array2 if array1 == nil return mergearray if array1.length == 0 && array2.length == 0 if array2[0] == nil mergearray << array1[0] array1.shift elsif array1[0] == nil mergearray << array2[0] array2.shift elsif array1[0] != nil && array2[0] != nil if array1[0] <= array2[0] mergearray << array1[0] array1.shift elsif array2[0] < array1[0] mergearray << array2[0] array2.shift end end end end end s = Sort.new([1,3,7,2,5]) puts "----------------" print s.mergesort([1,3,7,2,5]) puts "" puts "----------------"
class CreateSteps < ActiveRecord::Migration def change create_table :steps do |t| t.integer :step_number t.integer :kind t.string :selector t.text :script_code t.text :response t.boolean :store_datalayer t.text :datalayer t.references :case_test, index: true t.timestamps null: false end add_attachment :steps, :screenshot end end
class Obp < ActiveRecord::Base self.table_name = "obp" self.primary_key = "obpid" has_many :sys end
# Preview all emails at http://localhost:3000/rails/mailers/admin_notifier class AdminNotifierPreview < ActionMailer::Preview # Preview this email at http://localhost:3000/rails/mailers/admin_notifier/contact_form def contact_form AdminNotifierMailer.contact_form end end
class Backend::AccountController < ApplicationController before_action do if current_admin != nil authenticate_admin! else authenticate_reseller! end end def index @list = Account.order(:created_at) if reseller_signed_in? @list = @list.for_reseller(current_reseller.id) end end def buy if request.get? @account = Account.new else @account = Account.new(self.allowed_params) @account.payment_method = 'contract' @account.reseller_id = current_reseller.id if @account.save redirect_to backend_account_index_path, flash: {notice: t('operation.created')} else flash[:error] = t('operation.error') end end end def show @account = Account if reseller_signed_in? @account = @account.for_reseller(current_reseller.id) end @account = @account.find_by_id(params[:id]) redirect_to backend_account_index_path, flash: {error: t('operation.record_not_present')} unless @account end protected def allowed_params params.require(:account).permit(:name, :qty, accesses: []) end end
# Given a nonnegative integer, return a hash whose keys are all the odd nonnegative integers up to it # and each key's value is an array containing all the even non negative integers up to it. # # Examples: # staircase 1 # => {1 => []} # staircase 2 # => {1 => []} # staircase 3 # => {1 => [], 3 => [2]} # staircase 4 # => {1 => [], 3 => [2]} # staircase 5 # => {1 => [], 3 => [2], 5 =>[2, 4]} def even_arr(odd_num) arr = [] idx = 0 while idx < odd_num if idx > 0 && idx.even? arr << idx end idx += 1 end arr end def staircase(num) hash1 = {} idx = 0 while idx <= num if idx.odd? hash1[idx] = even_arr(idx) end idx += 1 end hash1 end
class Contestant < ActiveRecord::Base has_many :votes, dependent: :destroy mount_uploader :avatar, AvatarUploader def self.avatar_path(id) "/uploads/#{id}/avatar.png" end def avatar_path self.class.avatar_path id end end
FactoryBot.define do factory :doctor do name { Faker::OnePiece.character } email { "#{Faker::Name.first_name}@hospital.com" } password { 'password' } trait :admin do admin { true } end factory :doctor_with_specialization do before(:create) do |doctor| doctor.specialization_id = create(:specialization).id end end end end
class CreateAirportTripPlanePilot < ActiveRecord::Migration[5.2] def change create_table :airports do |t| t.string :name t.float :longitude t.float :latitude end create_table :trips do |t| t.integer :origin_airport_id t.integer :destination_airport_id t.integer :plane_id t.string :trip_name end create_table :planes do |t| t.string :registration t.string :model t.integer :range t.integer :average_speed t.integer :pilot_id end create_table :pilots do |t| t.string :name end end end
require_relative "lib/db/postgres/version" Gem::Specification.new do |spec| spec.name = "db-postgres" spec.version = DB::Postgres::VERSION spec.summary = "Ruby FFI bindings for libpq C interface." spec.authors = ["Samuel Williams"] spec.license = "MIT" spec.files = Dir.glob('{lib}/**/*', File::FNM_DOTMATCH, base: __dir__) spec.required_ruby_version = ">= 2.5" spec.add_dependency "ffi-module", "~> 0.3.0" spec.add_dependency "async-io" spec.add_dependency "async-pool" spec.add_development_dependency "async-rspec" spec.add_development_dependency "bake" spec.add_development_dependency "covered" spec.add_development_dependency "bundler" spec.add_development_dependency "rspec", "~> 3.6" end
class ServiceImporterJob < ImporterJob def perform super { case action when 'create' #create when 'update' update_components(callback_url) when 'destroy' #destroy end } end private def update_components(callback_url) service = RemoteObjectFetcher.fetch(callback_url)["service"] if service["one_time_fee"] service_components = service["components"].split(',') line_items = LineItem.where(service_id: service["sparc_id"]) line_items.each do |li| li_components = li.components.map(&:component) to_destroy = li_components - service_components to_destroy.each{ |td| li.components.where(component: td).first.destroy } to_add = service_components - li_components to_add.each{ |ta| Component.create(component: ta, position: service_components.index(ta), composable_type: "LineItem", composable_id: li.id) } end end end end
# frozen_string_literal: true class RosterController < ApplicationController secure!(:users, :roster) title!('Roster Information') before_action :users, only: %i[new create edit update] before_action :record, only: %i[edit update destroy] def show @collection = model.all end def new @record = model.new end def edit render :new end def create @record = model.new(formatted_params) check_and_redirect(:create, :new) { @record.save } end def update check_and_redirect(:update, :edit) { @record.update(formatted_params) } end def destroy check_and_redirect(:remove) { @record.destroy } end private def safe_params params.permit(:id, :year) end def record_id clean_params[:id] rescue StandardError safe_params[:id] end def record @record = model.find_by(id: record_id) end def users @users ||= User.alphabetized.unlocked end def formatted_params return clean_params if clean_params[:year].blank? || clean_params[:year].is_a?(Date) date = Date.strptime(clean_params[:year].to_s, '%Y') clean_params.to_h.merge(year: date) end def check_and_redirect(verb, render_sym = nil) success = yield if block_given? flash[:success] = "Successfully #{verb}d #{model}!" if success flash[:alert] = "Unable to #{verb} #{model}." unless success render_or_redirect(success, render_sym) end def render_or_redirect(success, render_sym) return render(render_sym) if !success && render_sym.present? redirect_to send("#{model.to_s.underscore.tr('/', '_')}s_path") end end
require('minitest/autorun') require('minitest/rg') require_relative('../guest') require_relative('../room') require_relative('../song') class TestGuest < MiniTest::Test def setup @guest = Guest.new('Ian') @unity = Song.new('Unity','Rick James') end def test_guest_name assert_equal('Ian', @guest.name) end def test_add_money_to_guest result = @guest.add_money(10) assert_equal(10, result) end def test_show_balance assert_equal(0, @guest.show_balance) end def test_pay_money result_one = @guest.add_money(10) assert_equal(10, result_one) result_two = @guest.pay_money(5) assert_equal(5, result_two) end def test_add_favourite_song result = @guest.add_favourite_song(['Rick James','Unity']) assert_equal(result, [['Rick James','Unity']]) # testing for two '[' as there is an array of potential fav songs. end def test_hear_favourite_song @guest.add_favourite_song(['Rick James','Unity']) result = @guest.hear_favourite_song([['Rick James','Unity']]) assert_equal('Woo Hoo Alright', result) end # def test_favourite_song_with_currently_playing # room = Room.new('Room one') # room.add_song(@unity) # assert_equal(room.playlist, [@unity]) # # puts room.currently_playing # # result = @guest.hear_favourite_song(room.currently_playing) # # assert_equal('Woo Hoo Alright', [result]) # # # end end
require File.expand_path(File.join(File.dirname(__FILE__), %w[spec_helper])) describe Rhouse::Models::Device do before( :all ) do @lamp = Rhouse::Models::Device.find( 42 ) @lamp.should_not be_nil end it "should have the right template" do @lamp.template.should_not be_nil @lamp.template.Description.should == "Light Switch (dimmable)" end it "should have the right commands for a lamp" do @lamp.commands.should_not be_nil @lamp.commands.should have(3).items @lamp.commands.map{ |c| c.name }.sort.should == [ 'Off', 'On', 'Set Level' ] end it "should have the right parameter for set level" do cmd = @lamp.commands.select{ |c| c if c.name == "Set Level" } cmd.compact! cmd.should have(1).item params = cmd.first.params params.should have(1).item c = params.first c.name.should == "Level" c.param_id.should == 76 c.param_type.should == 'string' end it "should list out all light fixtures" do lights = Rhouse::Models::Device.all_lights lights.should have(1).item lights.first.Description.should == "Office dimmable light" end it "should list out all light fixtures" do cams = Rhouse::Models::Device.all_ip_cams cams.should have(1).item cams.first.Description.should == "Panasonic IP Camera" end end
class AddCoverToGoods < ActiveRecord::Migration[6.0] def change add_column :goods, :cover, :string end end
class AddDateToAcceptedNotification < ActiveRecord::Migration def change add_column :accepted_notifications, :date, :datetime end end
module Eel module CoreExt module SymbolExtensions def attr Arel::Attributes::Attribute.new(nil, self) end def of val relation = case val when Class val.arel_table when Symbol val when String Arel::Table.new(val) else raise "Can't use #{val.class} as a relation" end Arel::Attributes::Attribute.new(relation, self) end def respond_to_missing? method_name, private = false method_name.in? predicates end def method_missing method_name, *args, &block if method_name.in? predicates if args.present? attr.send(method_name, *args) # binary nodes else attr.send(method_name) # unary nodes end else super end end private def predicates Arel::OrderPredications.instance_methods + Arel::Predications.instance_methods end end end end
Rails.application.routes.draw do scope "(:locale)", locale: /en|it/ do resources :active_families, only: [:index] resources :all_families, only: [:index] resources :families resources :inactive_families, only: [:index] resources :schools, only: [:index, :new, :create, :edit, :update, :destroy] resources :trips do resources :trip_families, only: [:index, :new, :create] end resources :pages, only: [:show] root "pages#show" end end
class RemoveDaysLeftFromUsers < ActiveRecord::Migration def change remove_column :users, :days_left end end
module Authlogic # This allows you to scope your authentication. For example, let's say all users belong # to an account, you want to make sure only users that belong to that account can # actually login into that account. Simple, just do: # # class Account < ActiveRecord::Base # authenticates_many :user_sessions # end # # Now you can scope sessions just like everything else in ActiveRecord: # # @account.user_sessions.new(*args) # @account.user_sessions.create(*args) # @account.user_sessions.find(*args) # # ... etc # # Checkout the authenticates_many method for a list of options. # You may also want to checkout Authlogic::ActsAsAuthentic::Scope to scope your model. module AuthenticatesMany module Base # Allows you set essentially set up a relationship with your sessions. See module # definition above for more details. # # === Options # # * <tt>session_class:</tt> default: "#{name}Session", # This is the related session class. # # * <tt>relationship_name:</tt> default: options[:session_class].klass_name.underscore.pluralize, # This is the name of the relationship you want to use to scope everything. For # example an Account has many Users. There should be a relationship called :users # that you defined with a has_many. The reason we use the relationship is so you # don't have to repeat yourself. The relationship could have all kinds of custom # options. So instead of repeating yourself we essentially use the scope that the # relationship creates. # # * <tt>find_options:</tt> default: nil, # By default the find options are created from the relationship you specify with # :relationship_name. But if you want to override this and manually specify # find_options you can do it here. Specify options just as you would in # ActiveRecord::Base.find. # # * <tt>scope_cookies:</tt> default: false # By the nature of cookies they scope themselves if you are using subdomains to # access accounts. If you aren't using subdomains you need to have separate # cookies for each account, assuming a user is logging into more than one account. # Authlogic can take care of this for you by prefixing the name of the cookie and # session with the model id. Because it affects both cookies names and session keys, # the name `scope_cookies` is misleading. Perhaps simply `scope` or `scoped` # would have been better. def authenticates_many(name, options = {}) options[:session_class] ||= name.to_s.classify.constantize options[:relationship_name] ||= options[:session_class].klass_name.underscore.pluralize class_eval <<-"end_eval", __FILE__, __LINE__ def #{name} find_options = #{options[:find_options].inspect} || #{options[:relationship_name]}.where(nil) @#{name} ||= Authlogic::AuthenticatesMany::Association.new(#{options[:session_class]}, find_options, #{options[:scope_cookies] ? "self.class.model_name.name.underscore + '_' + self.send(self.class.primary_key).to_s" : "nil"}) end end_eval end end ::ActiveRecord::Base.extend(Base) if defined?(::ActiveRecord) end end
# == Schema Information # # Table name: animal_associations # # id :integer not null, primary key # animal_id :integer # service_provider_id :integer # created_at :datetime # updated_at :datetime # checked_in :boolean # class AnimalAssociation < ActiveRecord::Base belongs_to :animal belongs_to :service_provider validates_presence_of :animal_id validates_presence_of :service_provider_id def name self.service_provider.name end def provider_types #self.service_provider.service_provider_types.map {|t| t.name }.join(",") self.service_provider.service_provider_types.map {|t| t.name }.to_sentence end end
class Task attr_reader :date, :group, :description, :state BLANK_SPACE_DATE=" " def initialize(description=nil,date=nil,group=nil) return nil if description.nil? @description=description @date=date @group=group @state=0 #Estado 0 indica pendiente y 1 indica completado end def promote_state @state += 1 end def ==(other) [@description, @date, @group]==[other.description,other.date,other.group] end def <=>(other) #Se ordena por estado, fecha return @state<=>other.state unless (@state <=> other.state)==0 return -1 if @date.nil? && !other.date.nil? #Las ultimas tres lineas de codigo buscan salvar el hecho de comparar return 1 if other.date.nil? && !@date.nil? #un objeto de clase Date con uno de clase nil return @date<=>other.date end def sort_by_group(other) #Aca buscamos ordenar por grupo y dentro del grupo mantener el orden [estado fecha] return @group<=>other.group unless (@group<=>other.group)==0 self<=>other end def to_s "#{@description}" end def all_info(with_group=true) #Cada vez que quiero listar voy a poner toda la informacion de la tarea (@state==1? "[X] " : "[ ] ") + (@date.nil?? BLANK_SPACE_DATE : "#{@date.taskdate_to_s}" ) + ( @group.nil?? "" : " +") + "#{@group} #{@description}" end end def overdue? self.date<Date.today end end
class AnswersController < ApplicationController def index @questions = Question.order("created_at DESC") @answers = Answer.order("created_at DESC") end def new @question = Question.find(params[:question_id]) @answer = Answer.new @answer.question_id = @question.id @answer.user_id = @question.user_id end def create @answer = Answer.create(create_params) end def show @question = Question.find(params[:question_id]) @answers = @question.answers end private def create_params params.require(:answer).permit(:user_id, :question_id, :detail) end end
# Third-party dependencies. require 'bindata' module Evtx # The file header provides some basic information about an event log file: # # - the number of chunks # - the chunk current in use # - etc. # # While the header consists of 4096 bytes (1 page), only 128 bytes are # in use. Additionally, the header's integrity is protected by a # 32 bit checksum. class FileHeader < BinData::Record # "ElfFile\x00" string :signature, length: 8 uint64le :first_chunk_number uint64le :last_chunk_number uint64le :next_record_identifier uint32le :header_size uint16le :minor_version uint16le :major_version uint16le :header_block_size uint16le :number_of_chunks string :unknown, length: 76 # "0x0001 - Dirty || 0x0002 - Full" uint32le :flags # "CRC32 of the first 120 bytes of the file header" uint32le :checksum private # Check that first eight bytes of the FileHeader match the # expected signature. # # @return [Boolean] def check_signature signature == "ElfFile\x00" end # def check_signature def check_major_version major_version == 0x3 end # def check_major_version def check_minor_version minor_version == 0x1 end # def check_minor_version def check_header_block_size header_block_size == 0x1000 end # def check_header_block_size # Check if the log has been opened and was changed, though not # all changes might be reflected in the file header. # # @return [Boolean] def dirty? flags & 0x1 == 0x1 end # def dirty? # Check if the log has reached its maximum configured size and the # retention policy in effect does not allow a suitable amount of space # to be reclaimed from the oldest records; so event messages can not # be written to the log file. # # @return [Boolean] def full? flags & 0x2 == 0x2 end # def full? def number_of_chunks number_of_chunks end # def number_of_chunks # @return [Boolean] def verify check_signature && check_major_version && check_minor_version && check_header_block_size end # def verify public(:number_of_chunks, :verify) end # class FileHeader end # module Evtx
class Support::ResponsibleBodiesController < Support::BaseController before_action { authorize ResponsibleBody } def index @responsible_bodies = policy_scope(ResponsibleBody) .select('responsible_bodies.*') .excluding_department_for_education .with_users_who_have_signed_in_at_least_once(privacy_notice_required: @current_user.is_computacenter?) .with_user_count(privacy_notice_required: @current_user.is_computacenter?) .with_completed_preorder_info_count .order('type asc, name asc') end def show @responsible_body = ResponsibleBody.find(params[:id]) @virtual_cap_pools = @responsible_body.virtual_cap_pools.with_std_device_first @users = policy_scope(@responsible_body.users).order('last_signed_in_at desc nulls last, updated_at desc') @schools = @responsible_body .schools .gias_status_open .includes(:device_allocations, :preorder_information) .order(name: :asc) @closed_schools = @responsible_body .schools .gias_status_closed .includes(:device_allocations, :preorder_information) .left_outer_joins(:user_schools) .select('schools.*, count(user_schools.id) AS user_count') .group('schools.id') .order(name: :asc) end end
#encoding: UTF-8 class Boleto < ActiveRecord::Base belongs_to :aluno belongs_to :empresa def data_vencimento vencimento = self.data_documento.to_date return nil unless vencimento.kind_of?(Date) && self.dias_vencimento.kind_of?(Numeric) (vencimento + self.dias_vencimento.to_i) end def self.index_boletos_do_portal(empresa_id, documento_responsavel) empresa = Empresa.find(empresa_id) periodo_letivo = Parametro.get_valor_parametro(empresa.organizacao_id, empresa.id, Parametro::PARAMETRO[:periodo_letivo]) url_consulta = Parametro.get_valor_parametro(empresa.organizacao_id, empresa.id, Parametro::PARAMETRO[:url_consulta]) conexao_corpore = Parametro.get_valor_parametro(empresa.organizacao_id, empresa.id, Parametro::PARAMETRO[:conexao_corpore]) sql = empresa.configuracoes_sql["index_boletos_do_portal"] parametros = {:NUMERODOCUMENTO => documento_responsavel} PortalDamas::WebServices.executar_consulta(url_consulta, sql, parametros, conexao_corpore) end def self.show_boleto_do_portal(empresa_id, numero_documento) empresa = Empresa.find(empresa_id) url_consulta = Parametro.get_valor_parametro(empresa.organizacao_id, empresa.id, Parametro::PARAMETRO[:url_consulta]) conexao_corpore = Parametro.get_valor_parametro(empresa.organizacao_id, empresa.id, Parametro::PARAMETRO[:conexao_corpore]) sql = empresa.configuracoes_sql["show_boleto_do_portal"] parametros = {:NUMERODOCUMENTO => numero_documento} PortalDamas::WebServices.executar_consulta(url_consulta, sql, parametros, conexao_corpore).first end def self.mes(value) case value when 1 then "JANEIRO" when 2 then "FEVEREIRO" when 3 then "MARÇO" when 4 then "ABRIL" when 5 then "MAIO" when 6 then "JUNHO" when 7 then "JULHO" when 8 then "AGOSTO" when 9 then "SETEMBRO" when 10 then "OUTUBRO" when 11 then "NOVEMBRO" when 12 then "DEZEMBRO" end end end
module Enumerable def my_each self.length.times do |i| yield(self[i]) end end def my_each_with_index i = 0 while i < self.length yield(self[i], i) i += 1 end end def my_select new_array = [] self.my_each do |element| new_array << element if yield(element) end new_array end def my_all? self.my_each do |element| return false if !yield(element) end true end def my_any? self.my_each do |element| return true if yield(element) end false end def my_none? self.my_each do |element| return false if yield(element) end true end def my_count(obj = nil) i = 0 self.my_each do |element| if block_given? i += 1 if yield element elsif obj != nil i += 1 if element == obj else i = self.length end end i end def my_map(&block) new_array = [] self.my_each do |element| new_element = block ? (block.call element) : yield(element) new_array << new_element end new_array end def my_inject(memo = nil) accum = memo ? memo : self[0] if accum != memo i = 1 while i < self.length accum = yield(accum, self[i]) i += 1 end else self.my_each do |element| accum = yield(accum, element) end end accum end end def multiply_els(array) array.my_inject do |x, n| x * n end end
Rails.application.routes.draw do get 'welcome/index' #resource method which is used to declare a REST resource resources :articles #tells the browser where to map the root of project root 'welcome#index' end
# spec/requests/api/v1/cards_spec.rb require 'rails_helper' require 'support/auth_helper' include AuthHelper describe "Cards API" do before(:each) do @user = create(:user) @card = create(:card, user: @user) end it 'provides card data by id' do get "/api/v1/cards/#{@card.id}?#{user_credentials(@user)}" expect(response.status).to eq 200 json = JSON.parse(response.body) expect(json['card']['translated_text']).to eq 'house' end it 'does not provide another users card data' do another_user = create(:another_user) another_card = create(:card, user: another_user) get "/api/v1/cards/#{another_card.id}?#{user_credentials(@user)}" expect(response.status).to eq 200 json = JSON.parse(response.body) expect(json['status']).to eq 'error' expect(json['notice']).to include 'No card found' end it 'creates new card if valid' do pars = { email: @user.email, token: @user.api_token, card: { original_text: 'лицо', translated_text: 'face' } } post "/api/v1/cards", params: pars expect(response.status).to eq 200 json = JSON.parse(response.body) expect(json['status']).to eq 'ok' expect(json['card']['translated_text']).to eq 'face' expect(json['card']['user_id']).to eq @user.id end it 'errors if card data not valid' do pars = { email: @user.email, token: @user.api_token, card: { original_text: '', translated_text: 'face' } } post "/api/v1/cards", params: pars expect(response.status).to eq 200 json = JSON.parse(response.body) expect(json['status']).to eq 'error' expect(json['notice']).to include 'Error creating card' end it 'reviews card if correct translation provided' do pars = { email: @user.email, token: @user.api_token, id: @card.id, translation: 'house' } put "/api/v1/cards/review", params: pars expect(response.status).to eq 200 json = JSON.parse(response.body) expect(json['status']).to eq 'ok' expect(json['notice']).to include 'Correct translation' expect(json['card']['attempt']).to eq 1 end it 'reviews card if incorrect translation provided' do pars = { email: @user.email, token: @user.api_token, id: @card.id, translation: 'building' } put "/api/v1/cards/review", params: pars expect(response.status).to eq 200 json = JSON.parse(response.body) expect(json['status']).to eq 'error' expect(json['notice']).to include 'Incorrect translation' end it 'does not review another users card' do another_user = create(:another_user) another_card = create(:card, user: another_user) pars = { email: @user.email, token: @user.api_token, id: another_card.id, translation: 'house' } put "/api/v1/cards/review", params: pars expect(response.status).to eq 200 json = JSON.parse(response.body) expect(json['status']).to eq 'error' expect(json['notice']).to include 'No card found' end end
module Swow class Client REALM_STATUS_REQUEST = "/wow/realm/status".freeze module Realm def realm_status(locale: @locale) get REALM_STATUS_REQUEST, locale: locale end end end end
require 'rails_helper' RSpec.feature 'Deleting H.R' do before do @admin = create(:admin) login_as(@admin, scope: :admin) @hr = create(:hr) visit admin_hrs_path end scenario 'should has list of H.Rs' do expect(page).to have_content(@hr.full_name) find('.delete-link').click expect(page).to have_content('H.R was removed from Fustany Team.') expect(page).not_to have_content(@hr.full_name) end end
class OnlineExamOption < ActiveRecord::Base belongs_to :online_exam_question has_many :online_exam_score_details validates_presence_of :option attr_accessor :redactor_to_update, :redactor_to_delete xss_terminate :except => [ :option ] before_update :atleast_one_answer before_update :all_diff_answers def atleast_one_answer if self.is_answer_changed? if self.is_answer == false unless self.online_exam_question.online_exam_options.all(:conditions=>{:is_answer=>true}).count > 1 self.errors.add_to_base("Atleast one option must be Answer") return false end end end return true end def all_diff_answers if self.option_changed? if self.online_exam_question.online_exam_options.all(:conditions=>{:option=>self.option}).count >= 1 self.errors.add_to_base(:options_are_not_unique) return false end end return true end def self.get_correct_answer(question) OnlineExamOption.all(:conditions=>{:online_exam_question_id=>question.online_exam_question_id,:is_answer=>true}) end def update_redactor RedactorUpload.update_redactors(self.redactor_to_update,self.redactor_to_delete) end def delete_redactors RedactorUpload.delete_after_create(self.content) end def assigned_to_other_exams(exam_group_id) assigned_exams = OnlineExamGroupsQuestion.find_all_by_online_exam_group_id_and_online_exam_question_id(exam_group_id,self.online_exam_question_id) count = 0 assigned_exams.each do|e| count=count+1 if e.answer_ids.include?(self.id) end if count>1 return true else return false end end end
class Project < ActiveRecord::Base attr_accessible :city, :client_name, :completion_date, :country, :description, :project_name, :project_status, :project_value, :start_date, :state, :client_id, :images_attributes, :address1, :address2, :latitude, :longitude has_many :images, :as => :imageable, :dependent => :destroy accepts_nested_attributes_for :images, :allow_destroy => true belongs_to :client validates :client, :presence => true # validates_presence_of :client_name, :message => "Client can't be blank" validates_presence_of :project_name, :message => "Project Name can't be blank" # validates_presence_of :project_status, :message => "Project Status can't be blank" # validates_presence_of :start_date, :message => "Start Date can't be blank" # validates_presence_of :completion_date, :message => "Completion Date can't be blank" validates_presence_of :city, :message => "City can't be blank" # validates_presence_of :state, :message => "State can't be blank" validates_presence_of :country, :message => "Country can't be blank" # validates_presence_of :client_name, :message => "Client name can't be blank" validate :check_lat_long # validate :check_images def check_lat_long if (self.latitude == nil && self.longitude == nil) errors.add(:base, "Please select a valid location from suggestions") elsif (self.latitude == nil || self.longitude == nil) errors.add(:base, "Please select a valid location from suggestions") end end def check_images binding.pry if (self.images.count == 0) errors.add(:base, "Please select images") end end end
module MagicField class ManaButton attr_accessor :button def initialize(color) @value = 'off' @color = color @button = UIView.alloc.initWithFrame [[0, 0], [44, 45]] @bgEmpty = UIImage.imageNamed("#{@color.downcase}-mana-empty.png") @bgFull = UIImage.imageNamed("#{@color.downcase}-mana-full.png") @bgFullView = UIImageView.alloc.initWithImage @bgFull @bgEmptyView = UIImageView.alloc.initWithImage @bgEmpty @bgFullView.alpha = 0.0 @bgEmptyView.alpha = 100.0 @button.addSubview @bgEmptyView @button.addSubview @bgFullView registerEvents end def registerEvents @button.whenTapped do switch end end def on? @value === 'on' end def off? @value === 'off' end def switch(to = nil) if to @value = to else @value = @value === 'on' ? 'off' : 'on' end setButtonImage end def setButtonImage if on? @bgFullView.alpha = 100.0 else @bgFullView.alpha = 0.0 end end end end
class MembersController < ApplicationController def show_detail_members @info = Information.find(params[:information_id]) @member = Member.find_by_information_id(params[:information_id]) end def create member = Member.find_by_information_id(params[:information_id]) if member.nil? new_member = Member.new(members_params.merge(information_id: params[:information_id])) if new_member.save flash[:notice] = I18n.t('mes.action_success', action: I18n.t('mes.action_create')) redirect_to "/listcustomer/#{params[:house_id]}/#{params[:room_id]}/#{params[:information_id]}?locale=#{params[:locale]}" else flash[:notice] = I18n.t('mes.action_fail', action: I18n.t('mes.action_create')) redirect_to "/listcustomer/#{params[:house_id]}/#{params[:room_id]}/#{params[:information_id]}?locale=#{params[:locale]}" end else if member.update(members_params) flash[:notice] = I18n.t('mes.action_success', action: I18n.t('mes.action_create')) redirect_to "/listcustomer/#{params[:house_id]}/#{params[:room_id]}/#{params[:information_id]}?locale=#{params[:locale]}" else flash[:notice] = I18n.t('mes.action_fail', action: I18n.t('mes.action_create')) redirect_to "/listcustomer/#{params[:house_id]}/#{params[:room_id]}/#{params[:information_id]}?locale=#{params[:locale]}" end end end private def members_params params.require(:member).permit(name:[], sex:[], birth:[], indentifycard:[], address:[], phone:[]) end end
# frozen_string_literal: true require "spec_helper" describe GraphQL::Types::Relay::BaseEdge do module NonNullableDummy class NonNullableNode < GraphQL::Schema::Object field :some_field, String end class NonNullableNodeEdgeType < GraphQL::Types::Relay::BaseEdge node_type(NonNullableNode, null: false) end class NonNullableNodeClassOverrideEdgeType < GraphQL::Types::Relay::BaseEdge node_nullable(false) end class NonNullableNodeEdgeConnectionType < GraphQL::Types::Relay::BaseConnection edge_type(NonNullableNodeEdgeType, nodes_field: false) end class Query < GraphQL::Schema::Object field :connection, NonNullableNodeEdgeConnectionType, null: false end class Schema < GraphQL::Schema query Query end end it "runs the introspection query and the result contains a edge field that has non-nullable node" do res = NonNullableDummy::Schema.execute(GraphQL::Introspection::INTROSPECTION_QUERY) assert res edge_type = res["data"]["__schema"]["types"].find { |t| t["name"] == "NonNullableNodeEdge" } node_field = edge_type["fields"].find { |f| f["name"] == "node" } assert_equal "NON_NULL", node_field["type"]["kind"] assert_equal "NonNullableNode", node_field["type"]["ofType"]["name"] end it "supports class-level node_nullable config" do assert_equal false, NonNullableDummy::NonNullableNodeClassOverrideEdgeType.node_nullable end it "Supports extra kwargs for node field" do extension = Class.new(GraphQL::Schema::FieldExtension) connection = Class.new(GraphQL::Types::Relay::BaseEdge) do node_type(GraphQL::Schema::Object, field_options: { extensions: [extension] }) end field = connection.fields["node"] assert_equal 1, field.extensions.size assert_instance_of extension, field.extensions.first end it "is a default relay type" do edge_type = NonNullableDummy::Schema.get_type("NonNullableNodeEdge") assert_equal true, edge_type.default_relay? assert_equal true, GraphQL::Types::Relay::BaseEdge.default_relay? end end
require 'bundler/setup' require 'sinatra' require 'roo' #require 'msgpack' #require 'oj' require 'mongoid' require 'mongoid_search' require 'yajl/json_gem' #require 'iconv' require 'open-uri' require "sinatra/reloader" if development? require 'matrix' Mongoid.load!("./mongoid.yml", :development) # class Downloaded_item class Wdi_fact include Mongoid::Document #store_in collection: "downloaditem" field :country_name, type: String field :country_code, type: String field :series_name, type: String field :series_code, type: String field :content, type: Array embeds_one :Wdi_series embeds_one :Wdi_country index({ country_code: 1, series_code: 1 }, { unique: true, name: "c_s_code_index", backgroud: true }) end class Wdi_series include Mongoid::Document field :series_code, type: String field :topic, type: String field :dataset, type: String field :indicator_name, type: String field :dataset, type: String field :short_definition, type: String field :long_definition, type: String field :unit_of_measure, type: String field :power_code, type: String field :periodicity, type: String field :base_period, type: String field :reference_period, type: String field :other_notes, type: String field :derivation_method, type: String field :aggregation_method, type: String field :limitations_and_exceptions, type: String field :notes_from_original_source, type: String field :general_comments, type: String field :source, type: String field :data_quality, type: String field :statistical_concept_and_methodology, type: String field :development_relevance, type: String field :related_source, type: String field :other_web_links, type: String field :related_indicators, type: String embedded_in :Wdi_facts index({ series_code: 1 }, { name: "s_code_index" }) index({ topic: 1 }, { name: "topic_index" }) index({ indicator_name: 1 }, { name: "s_name_index" }) end class Wdi_country include Mongoid::Document field :country_code, type: String field :short_name, type: String field :table_name, type: String field :long_name, type: String field :two_alpha_code, type: String field :currency_unit, type: String field :special_notes, type: String field :region, type: String field :income_group, type: String field :international_memberships, type: String field :wb2_code, type: String field :national_accounts_base_year, type: String field :national_accounts_reference_year, type: String field :sna_price_valuation, type: String field :lending_category, type: String field :other_groups, type: String field :system_of_national_accounts, type: String field :alternative_conversion_factor, type: String field :ppp_survey_year, type: String field :balance_of_payments_manual_in_use, type: String field :external_debt_reporting_status, type: String field :system_of_trade, type: String field :government_accounting_concept, type: String field :imf_data_dessemination_standard, type: String field :latest_population_census, type: String field :latest_household_survey, type: String field :source_of_most_recent_income_and_expenditure_data, type: String field :vital_registration_complete, type: String field :latest_agricultural_census, type: String field :latest_industrial_data, type: String field :latest_trade_data, type: String field :latest_water_withdrawal_data, type: String embedded_in :Wdi_facts index({ country_code: 1, short_name: 1, table_name: 1, long_name: 1 }, { unique: true, name: "c_name_index" }) index({ country_code: 1, two_alpha_code: 1, wb2_code: 1 }, { unique: true, name: "c_code_index" }) index({ region: 1 }, { name: "region_index" }) index({ income_group: 1 }, { name: "income_index" }) index({ international_memberships: 1 }, { name: "membership_index" }) index({ lending_category: 1 }, { name: "lending_index" }) end get '/' do @n = Wdi_fact.count #for current accumulated sheet number of all downloaded files @n_series = Wdi_series.count erb :index end get '/index' do @n = Wdi_fact.count #for current accumulated sheet number of all downloaded files @n_series = Wdi_series.count erb :index end get '/viewer' do uri= case params[:item_id].to_i when 1 then 'http://www.oecd.org/eco/outlook/Demand-and-Output.xls' when 2 then 'http://www.oecd.org/eco/outlook/Wages-Costs-Unemployment-and-Inflation.xls' when 3 then 'http://www.oecd.org/eco/outlook/Key-Supply-Side-Data.xls' when 4 then 'http://www.oecd.org/eco/outlook/Saving.xls' when 5 then 'http://www.oecd.org/eco/outlook/Fiscal-balances-and-Public-Indebteness.xls' when 6 then 'http://www.oecd.org/eco/outlook/Interest-Rates-and-Exchange-Rates.xls' when 7 then 'http://www.oecd.org/eco/outlook/External-Trade-and-Payments.xls' when 8 then 'http://www.oecd.org/eco/outlook/Other-background-Data.xls' else '' end d_item_name = ['Demand and output', 'Wages, Costs, Unemployment and Inflation', 'Key Supply Side Data', 'Saving', 'Fiscal balances and public indebtedness', 'Interest Rates and Exchange Rates', 'External Trade and Payments', 'Other Background Data' ] d_item_name_id = (params[:item_id].to_i) d_item = Roo::Spreadsheet.open(uri) #RooObj 2 Matrix 2 Array d_item_firstsheet_narray = d_item.to_matrix.to_a @res = d_item_firstsheet_narray #@n = d_item.sheets.count #sheet number of current downloaded file #@d_item_id = #n_Array of each sheet set to Mongo i = 0 while i<d_item.sheets.count #d_item_matrix_i = d_item.sheet(i).to_matrix d_item_narray_i = d_item_matrix_i.to_a d_item_id = params[:item_id] sheet_name = d_item.sheets[i] sheet_name2 = d_item.sheet(i).cell('A',1).to_s sheet_no = i downloaditem = Downloaditem.create(d_item_id: d_item_id, book_name: d_item_name[d_item_name_id-1], sheet_id: sheet_no, sheet_name: sheet_name, sheet_name2: sheet_name2, uri: uri, content: d_item_narray_i) i +=1 end @n = Downloaditem.count #for current accumulated sheet number of all downloaded files #res_json = JSON.parse(res) @n_series = Series.count erb :tables end get '/sheetlist' do #get the name of thst sheet and embeded link(d_item_id & sheet_id) to show the sheet from Mongo #set the items above into array (or Hash) as instance variable @list_array = Downloaditem.all.asc(:book_name,:sheet_id) @n = Downloaditem.count @n_series = Series.count erb :sheetlist end get '/sheetview' do res = Downloaditem.where(d_item_id: params[:d_item_id].to_i).and(sheet_id: params[:sheet_id].to_i) @res = res[0].content.to_a @n = Downloaditem.count @n_series = Series.count erb :tables end get '/serieslist' do #@series = [] contents = Downloaditem.where(d_item_id: 1).and(sheet_id: 0) matrix = Matrix.rows(contents[0].content.to_a) series_n = 3 series_name_0 = matrix[0,0].to_s + matrix[1,0].to_s series_name_1 = series_name_0 + matrix[2,2].to_s + matrix[3,2].to_s series_name_2 = series_name_0 + matrix[2,19].to_s series_names = [series_name_0,series_name_1,series_name_2] country_names = matrix.minor(4..39, 0..0).to_a.flatten period_values_0 = matrix.minor(2..2,3..18).to_a.flatten period_values_1 = matrix[3,2].to_a.flatten period_values_2 = matrix.minor(3..3,19..21).to_a.flatten period_values = [period_values_0,period_values_1,period_values_2] data_values_narray_0 = matrix.minor(4..39,3..18).to_a #[[data_values01 of country A],[data_values01 of country B],,,,] data_values_narray_1 = matrix.minor(4..39,2..2).to_a #[data_values02 of country A,data_values02 of country B,,,,] data_values_narray_2 = matrix.minor(4..39,19..21).to_a #[[data_values03 of country A],[data_values03 of country B],,,,] data_values = [data_values_narray_0,data_values_narray_1,data_values_narray_2] #if Series.count > 0 then break else y = 0 while y < series_n do if Series.count >0 then break end x = 0 #series = [] while x < data_values[y].size do narray_x = [] i = 0 while i < period_values[y].size do j = period_values[y][i] k = data_values[y][x][i] ar = [] ar.push j,k narray_x.push ar i +=1 end l = country_names[x].to_s #ns_ar =[] sheet_id = 0 d_item_id = 1 #ns_ar.push d_item_id,sheet_id,series_name01,l,narray_x #series.push ns_ar Series.create(d_item_id: d_item_id, sheet_id: sheet_id, series_id: y, series_name: series_names[y], country_name: l, country_id: x, narray: narray_x) x +=1 end y +=1 end #end @series = Series.all.asc(:d_item_id,:sheet_id,:series_id,:country_id) @n_series = Series.count @n = Downloaditem.count erb :serieslist end get '/detail' do @item = Series.where(d_item_id: params[:d_item_id].to_i) .and(sheet_id: params[:sheet_id].to_i) .and(series_id: params[:series_id].to_i) .and(country_id: params[:country_id].to_i) @n_series = Series.count @n = Downloaditem.count erb :detail end
class Post < ActiveRecord::Base acts_as_mappable :default_units => :miles, :default_formula => :sphere, :distance_field_name => :distance, :lat_column_name => :latitude, :lng_column_name => :longitude attr_accessor :current_user_vote, :current_user_shared attr_reader :watch_stat, :ignore_stat, :share_stat belongs_to :user has_many :votes, dependent: :destroy has_many :shares has_many :reveal_notifications, dependent: :destroy validates_length_of :content, :minimum => 1, :maximum => 200, :allow_blank => false def watch_stat self.votes.where("action = ?", 'watch').count end def ignore_stat self.votes.where("action = ?", 'ignore').count end def share_stat self.shares.count end def rating(time) (0.0+self.votes.where("action = ? AND created_at < ?", 'watch', time).count-self.votes.where("action = ? AND created_at < ?", 'ignore', time).count)/(DateTime.now.to_f-self.created_at.to_f) end end
class ContactMailer < ActionMailer::Base #layout 'contact' #default from: "from@example.com" # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.contact_mailer.confirmation.subject # def confirmation(email) attachments['rails.png'] = File.read("#{Rails.root}/app/assets/images/rails.png") mail(to: email, from: "derrobertwolf@gmx.de", subject: "Ihre Kontaktnachricht erhalten") do |format| format.html { render layout: 'contact' } format.text end end # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.contact_mailer.inquiry.subject # def inquiry(contact_message) @contact_message = contact_message mail to: "newsletterstar@gmail.com", from: contact_message.email, subject: "Neue Kontaktanfrage" end end
require "test_helper" class LessonTest < Test::Unit::TestCase # Replace this with your real tests. context "assignments" do setup do @organization = Factory.create(:organization) @lesson = Factory.create(:lesson) @unassigned_user = Factory.create(:user) @assigned_user = Factory.create(:user) @assigned_user.assigned_lessons << @lesson end #WIP # should "know unassigned users" do # assert @lesson.unassigned_users.member?(@unassigned_user) # end should "know assigned users" do assert @lesson.assigned_users.member?(@assigned_user) end end context "sanitization" do setup do @old_lesson = Factory.create(:lesson, :name => "yelp") @new_lesson = Factory.build( :lesson, :name => "<a href=\"http://google.com\">google</a>") end should "save a new record and sanitize the name" do assert @new_lesson.name == "<a href=\"http://google.com\">google</a>" assert @new_lesson.save assert @new_lesson.name == "google" end should "save an old record with a new name" do assert @old_lesson.name == "yelp" @old_lesson.name = "<a href=\"http://google.com\">google</a>" assert @old_lesson.save assert @old_lesson.name == "google" end end end
ActiveAdmin.register User do index do column :name column :surname column :email column :created_at actions end form do |f| f.inputs 'User data' do f.input :name f.input :surname f.input :email end f.inputs 'Choose your password' do f.input :password f.input :password_confirmation end f.actions end permit_params :name,:surname, :email, :password, :password_confirmation, :on, :user end
require 'pry' class Startup attr_accessor :domain, :name attr_reader :founder, :funding_rounds @@all = [] def initialize(name,founder, domain) @name = name @founder = founder @domain = domain @funding_rounds = [] @@all << self end def pivot (domain = @domain, name = @name) @domain = domain @name = name end def self.all @@all end def self.find_by_founder(founder) all.find do |startup| founder == startup.founder #binding.pry end #binding.pry end def self.domains domains = [] all.each do |startup| domains << startup.domain #binding.pry end #binding.pry domains.uniq end def sign_contract(vc, inv_type, amount) new_contract = FundingRound.new(name, vc.name, amount.to_f, inv_type) @funding_rounds << new_contract end def num_funding_rounds funding_rounds.count end def total_funds total_funds = 0 funding_rounds.each do |rounds| total_funds += rounds.amount end total_funds end def investors @investor_list = [] funding_rounds.each do |rounds| @investor_list << rounds.vc end @investor_list.uniq end def big_investors ballers = [] VentureCapitalist.tres_commas_club.each do |baller| #binding.pry investors.each do |investor| if baller.vc_name == investor ballers << baller.vc_name end end end ballers.uniq end private attr_writer :founder end
# Copyright 2007-2014 Greg Hurrell. All rights reserved. # Licensed under the terms of the BSD 2-clause license. require 'spec_helper' describe Walrat::ProcParslet do before do @parslet = lambda do |string, options| if string == 'foobar' string else raise Walrat::ParseError.new("expected foobar but got '#{string}'") end end.to_parseable end it 'raises an ArgumentError if initialized with nil' do expect do Walrat::ProcParslet.new nil end.to raise_error(ArgumentError, /nil proc/) end it 'complains if asked to parse nil' do expect do @parslet.parse nil end.to raise_error(ArgumentError, /nil string/) end it 'raises Walrat::ParseError if unable to parse' do expect do @parslet.parse 'bar' end.to raise_error(Walrat::ParseError) end it 'returns a parsed value if able to parse' do expect(@parslet.parse('foobar')).to eq('foobar') end it 'can be compared for equality' do # in practice only parslets created with the exact same Proc instance will # be eql because Proc returns different hashes for each expect(@parslet).to eql(@parslet.clone) expect(@parslet).to eql(@parslet.dup) expect(@parslet).not_to eql(lambda { nil }.to_parseable) end end
require "spec_helper" RSpec.describe Stringer do it "concatenates undefined number of strings with a space" do expect(Stringer.spacify "Oscar", "Vazquez", "Zweig", "Olasaba", "Hernandez", "Ricardo", "Mendoza").to eq("Oscar Vazquez Zweig Olasaba Hernandez Ricardo Mendoza") end it "shortens the string based on the max lenght paramter(string, max_length)" do expect(Stringer.minify "Hello", 10).to eq("Hello") end it "shortens the string based on the max lenght paramter(string, max_length)" do expect(Stringer.minify "Hello, I'm learning how to create a gem", 10).to eq("Hello, I'm...") end it "iterates over a string and replaces each instance of that word with the replacement provided" do expect(Stringer.replacify "I can't do this", "can't", "can").to eq("I can do this") end it "parameters string. Iterates over a string and adds each word into an array, then returns that array." do expect(Stringer.tokenize "I love to code").to eq(["I", "love", "to", "code"]) end it "parameters string (original), string (word to remove). Remove each instance of the second parameter within the original string." do expect(Stringer.removify "I'm not a developer", "not").to eq("I'm a developer") end end
require "fog/core/collection" require "fog/brkt/models/compute/workload" module Fog module Compute class Brkt class WorkloadTemplates < Fog::Collection model Fog::Compute::Brkt::WorkloadTemplate # Get workload templates # # @return [Array<WorkloadTemple>] workload templates def all load(service.list_workload_templates.body) end # Get workload template by ID # # @param [String] id workload template id # @return [WorkloadTemplate] workload template def get(id) new(service.get_workload_template(id).body) end end end end end
class UsersController < ApplicationController skip_before_action :authorize, only: :create def create @new_user = User.create!(user_params) session[:user_id] = @new_user.id render json: @new_user, status: :created end def show render json: @current_user end private def user_params params.permit(:username, :password, :password_confirmation, :name, :bio, :email) end end
Rails.application.routes.draw do root to:'iteration_reviews#index' mount Rules::Engine, at: "rules" mount JsModel::Engine, at: 'models' mount ApiDoc::Engine, at:'doc' scope :session do get '/signup' => 'session#signup_page' get '/signout' => 'session#sign_out' post '/signup' => 'session#signup' get '/login' => 'session#login_page' post '/login' => 'session#login' end resources :message_actions resources :message_reasons resources :messages do resources :message_reasons resources :message_actions post '/vote' => 'messages#vote' end resources :iteration_reviews do resources :messages put '/status' => 'iteration_reviews#update_status' end resources :users post '/users/iteration_review' => 'users#join_in_iteration_review' end
class Api::CollegesController < ApplicationController before_action :set_college, only: [:show, :update, :destroy] def index colleges = College.all render json: colleges end def show render json: {college: @college, frats: @college.get_frats_with_event_info, events: @college.events, unassociated_frats: @college.get_unassociated_frats} end def create @college = College.new(college_params) if @college.save render json: @college else render json: {error: @college.errors}, status: 422 end end def update if @college.update(college_params) render json: @college else render json: {error: @college.errors}, status: 422 end end def destroy @college.destroy render json: @college end private def set_college @college = College.find(params[:id]) end def college_params params.require(:college).permit(:name, :mascot) end end
shared_examples 'a commentable' do let!(:user) { create(:user, :paul) } let!(:commentor) { create(:user, :billy) } before do login_as(commentor) visit commentable_path end context 'with valid comment' do it 'on a commentable' do within('.new_comment_form') do fill_in 'comment_body', with: 'Muito massa!' click_button I18n.t('actions.comment') end expect(page.current_path).to eql commentable_path expect(page).to have_content I18n.t('flash.comments.create.notice') expect(page).to have_selector "article.comment a[href='#{user_path(commentor)}']" expect(page).to have_content 'Muito massa!' end it 'on a comment' do within('.new_comment_form') do fill_in 'comment_body', with: 'Muito massa!' click_button I18n.t('actions.comment') end comment = commentable.reload.comments.first within("#comment_#{comment.id}") do click_link 'Responder' fill_in 'comment_body', with: 'Também achei!' click_button I18n.t('actions.answer') end expect(page.current_path).to eql commentable_path expect(page).to have_content I18n.t('flash.comments.create.notice') expect(page).to have_selector "#comment_#{comment.id} a[href='#{user_path(commentor)}']" expect(page).to have_content 'Também achei!' end end context 'when user owns a comment' do it 'he/she can delete comments' do within('.new_comment_form') do fill_in 'comment_body', with: 'Muito massa!' click_button I18n.t('actions.comment') end comment = commentable.reload.comments.first within("#comment_#{comment.id}") do click_link 'Responder' fill_in 'comment_body', with: 'Também achei!' click_button I18n.t('actions.answer') end answer = comment.reload.comments.first find("#answer_#{answer.id} a.delete").click expect(page.current_path).to eql commentable_path expect(page).to have_content I18n.t('flash.comments.destroy.notice') expect(page).to_not have_content answer.body find("#comment_#{comment.id} a.delete").click expect(page.current_path).to eql commentable_path expect(page).to have_content I18n.t('flash.comments.destroy.notice') expect(page).to_not have_content comment.body end end context 'with invalid comment' do it 'show error message' do within('.new_comment_form') do fill_in 'comment_body', with: '' click_button I18n.t('actions.comment') end expect(page.current_path).to eql commentable_path expect(page).to have_content I18n.t('flash.comments.create.alert') expect(page).to_not have_selector "article.comment a[href='#{user_path(commentor)}']" end end end
class CommentsController < ApplicationController http_basic_authenticate_with name:"sam", password:"secret", only: :destroy def create @article = Article.find(params[:article_id]) @comment = @article.comments.create(comment_parameters) redirect_to article_path(@article) end def destroy @article = Article.find(params[:article_id]) @comment = @article.comments.find(params[:id]) @comment.destroy redirect_to article_path(@article) end private def comment_parameters params.require(:comment).permit(:commenter, :body) end end
class AddOptionalContent56ToPosts < ActiveRecord::Migration[6.0] def change add_column :posts, :optional_content_5, :text add_column :posts, :optional_content_6, :text end end
# frozen_string_literal: true module Kafka module Protocol class DeleteTopicsRequest def initialize(topics:, timeout:) @topics, @timeout = topics, timeout end def api_key DELETE_TOPICS_API end def api_version 0 end def response_class Protocol::DeleteTopicsResponse end def encode(encoder) encoder.write_array(@topics) do |topic| encoder.write_string(topic) end # Timeout is in ms. encoder.write_int32(@timeout * 1000) end end end end
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Directive do class MultiWord < GraphQL::Schema::Directive end it "uses a downcased class name" do assert_equal "multiWord", MultiWord.graphql_name end module DirectiveTest class Secret < GraphQL::Schema::Directive argument :top_secret, Boolean locations(FIELD_DEFINITION, ARGUMENT_DEFINITION) end class Thing < GraphQL::Schema::Object field :name, String, null: false do directive Secret, top_secret: true argument :nickname, Boolean, required: false do directive Secret, top_secret: false end end end end it "can be added to schema definitions" do field = DirectiveTest::Thing.fields.values.first assert_equal [DirectiveTest::Secret], field.directives.map(&:class) assert_equal [field], field.directives.map(&:owner) assert_equal [true], field.directives.map{ |d| d.arguments[:top_secret] } argument = field.arguments.values.first assert_equal [DirectiveTest::Secret], argument.directives.map(&:class) assert_equal [argument], argument.directives.map(&:owner) assert_equal [false], argument.directives.map{ |d| d.arguments[:top_secret] } end it "raises an error when added to the wrong thing" do err = assert_raises ArgumentError do Class.new(GraphQL::Schema::Object) do graphql_name "Stuff" directive DirectiveTest::Secret end end expected_message = "Directive `@secret` can't be attached to Stuff because OBJECT isn't included in its locations (FIELD_DEFINITION, ARGUMENT_DEFINITION). Use `locations(OBJECT)` to update this directive's definition, or remove it from Stuff. " assert_equal expected_message, err.message end it "validates arguments" do err = assert_raises ArgumentError do GraphQL::Schema::Field.from_options( name: :something, type: String, null: false, owner: DirectiveTest::Thing, directives: { DirectiveTest::Secret => {} } ) end assert_equal "@secret.topSecret is required, but no value was given", err.message err2 = assert_raises ArgumentError do GraphQL::Schema::Field.from_options( name: :something, type: String, null: false, owner: DirectiveTest::Thing, directives: { DirectiveTest::Secret => { top_secret: 12.5 } } ) end assert_equal "@secret.topSecret is required, but no value was given", err2.message end describe 'repeatable directives' do module RepeatDirectiveTest class Secret < GraphQL::Schema::Directive argument :secret, String locations OBJECT, INTERFACE repeatable true end class OtherSecret < GraphQL::Schema::Directive argument :secret, String locations OBJECT, INTERFACE repeatable false end class Thing < GraphQL::Schema::Object directive(Secret, secret: "my secret") directive(Secret, secret: "my second secret") directive(OtherSecret, secret: "other secret") directive(OtherSecret, secret: "second other secret") end end it "allows repeatable directives twice" do directives = RepeatDirectiveTest::Thing.directives secret_directives = directives.select{ |x| x.is_a?(RepeatDirectiveTest::Secret) } assert_equal 2, secret_directives.size assert_equal ["my secret", "my second secret"], secret_directives.map{ |d| d.arguments[:secret] } end it "overwrites non-repeatable directives" do directives = RepeatDirectiveTest::Thing.directives other_directives = directives.select{ |x| x.is_a?(RepeatDirectiveTest::OtherSecret) } assert_equal 1, other_directives.size assert_equal ["second other secret"], other_directives.map{ |d| d.arguments[:secret] } end end module RuntimeDirectiveTest class CountFields < GraphQL::Schema::Directive locations(FIELD, FRAGMENT_SPREAD, INLINE_FRAGMENT) def self.resolve(obj, args, ctx) path = ctx[:current_path] result = nil ctx.dataloader.run_isolated do result = yield GraphQL::Execution::Interpreter::Resolve.resolve_all([result], ctx.dataloader) end ctx[:count_fields] ||= Hash.new { |h, k| h[k] = [] } field_count = result.respond_to?(:graphql_result_data) ? result.graphql_result_data.size : 1 ctx[:count_fields][path] << field_count nil # this does nothing end end class Thing < GraphQL::Schema::Object field :name, String, null: false end module HasThings include GraphQL::Schema::Interface field :thing, Thing, null: false, extras: [:ast_node] def thing(ast_node:) context[:name_resolved_count] ||= 0 context[:name_resolved_count] += 1 { name: ast_node.alias || ast_node.name } end field :lazy_thing, Thing, null: false, extras: [:ast_node] def lazy_thing(ast_node:) -> { thing(ast_node: ast_node) } end field :dataloaded_thing, Thing, null: false, extras: [:ast_node] def dataloaded_thing(ast_node:) dataloader.with(ThingSource).load(ast_node.alias || ast_node.name) end end Thing.implements(HasThings) class Query < GraphQL::Schema::Object implements HasThings end class ThingSource < GraphQL::Dataloader::Source def fetch(names) names.map { |n| { name: n } } end end class Schema < GraphQL::Schema query(Query) directive(CountFields) lazy_resolve(Proc, :call) use GraphQL::Dataloader end end describe "runtime directives" do it "works with fragment spreads, inline fragments, and fields" do query_str = <<-GRAPHQL { t1: dataloadedThing { t1n: name @countFields } ... @countFields { t2: thing { t2n: name } t3: thing { t3n: name } } t3: thing { t3n: name } t4: lazyThing { ...Thing @countFields } t5: thing { n5: name t5d: dataloadedThing { t5dl: lazyThing { t5dln: name @countFields } } } } fragment Thing on Thing { n1: name n2: name n3: name } GRAPHQL res = RuntimeDirectiveTest::Schema.execute(query_str) expected_data = { "t1" => { "t1n" => "t1", }, "t2"=>{"t2n"=>"t2"}, "t3"=>{"t3n"=>"t3"}, "t4" => { "n1" => "t4", "n2" => "t4", "n3" => "t4", }, "t5"=>{"n5"=>"t5", "t5d"=>{"t5dl"=>{"t5dln"=>"t5dl"}}}, } assert_equal expected_data, res["data"] expected_counts = { ["t1", "t1n"] => [1], [] => [2], ["t4"] => [3], ["t5", "t5d", "t5dl", "t5dln"] => [1], } assert_equal expected_counts, res.context[:count_fields] end it "runs things twice when they're in with-directive and without-directive parts of the query" do query_str = <<-GRAPHQL { t1: thing { name } # name_resolved_count = 1 t2: thing { name } # name_resolved_count = 2 ... @countFields { t1: thing { name } # name_resolved_count = 3 t3: thing { name } # name_resolved_count = 4 } t3: thing { name } # name_resolved_count = 5 ... { t2: thing { name @countFields } # This is merged back into `t2` above } } GRAPHQL res = RuntimeDirectiveTest::Schema.execute(query_str) expected_data = { "t1" => { "name" => "t1"}, "t2" => { "name" => "t2" }, "t3" => { "name" => "t3" } } assert_equal expected_data, res["data"] expected_counts = { [] => [2], ["t2", "name"] => [1], } assert_equal expected_counts, res.context[:count_fields] assert_equal 5, res.context[:name_resolved_count] end end describe "raising an error from an argument" do class DirectiveErrorSchema < GraphQL::Schema class MyDirective < GraphQL::Schema::Directive locations GraphQL::Schema::Directive::QUERY, GraphQL::Schema::Directive::FIELD argument :input, String, prepare: ->(input, ctx) { raise GraphQL::ExecutionError, "invalid argument" } end class QueryType < GraphQL::Schema::Object field :hello, String, null: false def hello "Hello World!" end end query QueryType directive MyDirective end it "halts execution and adds an error to the error key" do result = DirectiveErrorSchema.execute(<<-GQL) query @myDirective(input: "hi") { hello } GQL assert_equal({}, result["data"]) assert_equal ["invalid argument"], result["errors"].map { |e| e["message"] } assert_equal [[{"line"=>1, "column"=>13}]], result["errors"].map { |e| e["locations"] } result2 = DirectiveErrorSchema.execute(<<-GQL) query { hello hello2: hello @myDirective(input: "hi") } GQL assert_equal({ "hello" => "Hello World!" }, result2["data"]) assert_equal ["invalid argument"], result2["errors"].map { |e| e["message"] } assert_equal [[{"line"=>3, "column"=>23}]], result2["errors"].map { |e| e["locations"] } end end describe ".resolve_each" do class ResolveEachSchema < GraphQL::Schema class FilterByIndex < GraphQL::Schema::Directive locations FIELD argument :select, String def self.resolve_each(object, args, context) if context[:current_path].last.public_send(args[:select]) yield else # Don't send a value end end def self.resolve(obj, args, ctx) value = yield value.values.compact! value end end class Query < GraphQL::Schema::Object field :numbers, [Integer] def numbers [0,1,2,3,4,5] end end query(Query) directive(FilterByIndex) end it "is called for each item in a list during enumeration" do res = ResolveEachSchema.execute("{ numbers @filterByIndex(select: \"even?\")}") assert_equal [0,2,4], res["data"]["numbers"] res = ResolveEachSchema.execute("{ numbers @filterByIndex(select: \"odd?\")}") assert_equal [1,3,5], res["data"]["numbers"] end end it "parses repeated directives" do schema_sdl = <<~EOS directive @tag(name: String!) repeatable on ARGUMENT_DEFINITION | ENUM | ENUM_VALUE | FIELD_DEFINITION | INPUT_FIELD_DEFINITION | INPUT_OBJECT | INTERFACE | OBJECT | SCALAR | UNION type Query @tag(name: "t1") @tag(name: "t2") { something( arg: Boolean @tag(name: "t3") @tag(name: "t4") ): Int @tag(name: "t5") @tag(name: "t6") } enum Stuff { THING @tag(name: "t7") @tag(name: "t8") } EOS schema = GraphQL::Schema.from_definition(schema_sdl) query_type = schema.query assert_equal [["tag", { name: "t1" }], ["tag", { name: "t2" }]], query_type.directives.map { |dir| [dir.graphql_name, dir.arguments.to_h] } field = schema.get_field("Query", "something") arg = field.get_argument("arg") assert_equal [["tag", { name: "t3"}], ["tag", { name: "t4"}]], arg.directives.map { |dir| [dir.graphql_name, dir.arguments.to_h] } assert_equal [["tag", { name: "t5"}], ["tag", { name: "t6"}]], field.directives.map { |dir| [dir.graphql_name, dir.arguments.to_h] } enum_value = schema.get_type("Stuff").values["THING"] assert_equal [["tag", { name: "t7"}], ["tag", { name: "t8"}]], enum_value.directives.map { |dir| [dir.graphql_name, dir.arguments.to_h] } end end
class AddExtensionToClassRegistrations < ActiveRecord::Migration def change add_column :class_registrations, :add_extension, :boolean, :default => false end end
class Api::V1::ProjectTaskMappingsController < ApplicationController before_action :authenticate_user! before_action :set_task_mapping, only: [:show, :edit, :update] def index @project_task_mappings = ProjectTaskMapping.page(params[:page]) resp=[] @project_task_mappings.each do |p| if p.active.to_i==1 @status=true else @status=false end @project_task = ProjectTask.find_by_id(p.project_task_id) if @project_task!=nil and @project_task!="" @task_name =@project_task.task_name else @task_name ="" end resp << { 'id' => p.id, 'task_name' => @task_name, 'assign_date' => p.assign_date, 'completed_date' => p.completed_date, 'actual_duration' => p.actual_duration, 'assigned_by' => p.assigned_by, 'active' => p.active, 'priority' => p.priority, 'status' => @status } end #@search="" pagination(ProjectTaskMapping,@search) response = { 'no_of_records' => @no_of_records.size, 'no_of_pages' => @no_pages, 'next' => @next, 'prev' => @prev, 'project_tasks' => resp } render json: response end def show render json: @project_task_mapping end def create @project_task_mapping = ProjectTaskMapping.new(task_mapping_params) if @project_task_mapping.save index else render json: { valid: false, error: @project_task_mapping.errors }, status: 404 end end def update if @project_task_mapping.update(task_mapping_params) render json: @project_task_mapping else render json: { valid: false, error: @project_task_mapping.errors }, status: 404 end end private # Use callbacks to share common setup or constraints between actions. def set_task_mapping @project_task_mapping = ProjectTaskMapping.find_by_id(params[:id]) if @project_task_mapping else render json: { valid: false}, status: 404 end end # Never trust parameters from the scary internet, only allow the white list through. def task_mapping_params #params.require(:branch).permit(:name, :active, :user_id) raw_parameters = { :assign_date => "#{params[:assign_date]}", :completed_date => "#{params[:completed_date]}", :active => "#{params[:active]}", :priority => "#{params[:priority]}", :planned_duration => "#{params[:planned_duration]}", :actual_duration => "#{params[:actual_duration]}", :assigned_by => "#{params[:assigned_by]}", :sprint_planning_id => "#{params[:sprint_planning_id]}", :task_status_master_id => "#{params[:task_status_master_id]}", :project_task_id => "#{params[:project_task_id]}", :project_master_id => "#{params[:project_master_id]}", :release_planning_id => "#{params[:release_planning_id]}", :user_id => "#{params[:user_id]}" } parameters = ActionController::Parameters.new(raw_parameters) parameters.permit(:assign_date, :completed_date, :active, :priority, :planned_duration, :actual_duration, :assigned_by, :sprint_planning_id, :task_status_master_id, :project_task_id, :project_master_id, :release_planning_id, :user_id) end end
class ExpressionsController < ApplicationController def new @mfe = MonFrenchExpresso.find(params[:mon_french_expresso_id]) @expression = Expression.new end def create @expression = Expression.new(expression_params) @expression.mon_french_expresso = MonFrenchExpresso.find(params[:mon_french_expresso_id]) @expression.save redirect_to mon_french_expresso_path(@expression.mon_french_expresso) end private def expression_params params.require(:expression).permit(:expfr, :expen) end end
class SessionsController < ApplicationController skip_before_filter :require_current_user def new end def create email = user = User.find_by_email(params[:email]) if user flash[:notice] = "Logged In!" set_current_user(user.id) redirect_to root_path else flash[:notice] = "No user found with that email" redirect_to root_path end end def destroy logout_current_user flash[:notice] = "Logged out" redirect_to new_sessions_path end end
module Pushr module Daemon module ApnsSupport class FeedbackReceiver FEEDBACK_TUPLE_BYTES = 38 def initialize(configuration, _) @configuration = configuration @interruptible_sleep = InterruptibleSleep.new end def start @thread = Thread.new do loop do break if @stop check_every_configuration @interruptible_sleep.sleep @configuration.feedback_poll end end end def stop @stop = true @interruptible_sleep.interrupt @thread.join if @thread end def check_every_configuration Pushr::Configuration.all.each do |config| if config.enabled == true && config.class == Pushr::ConfigurationApns Pushr::Daemon.logger.info("[#{config.app}: Checking for feedback") check_for_feedback(config) end end end def check_for_feedback(config) connection = nil begin connection = ConnectionApns.new(config) connection.connect while tuple = connection.read(FEEDBACK_TUPLE_BYTES) timestamp, device = parse_tuple(tuple) create_feedback(config, connection, timestamp, device) end rescue StandardError => e Pushr::Daemon.logger.error(e) ensure connection.close if connection end end protected def parse_tuple(tuple) failed_at, _, device = tuple.unpack('N1n1H*') [Time.at(failed_at).utc, device] end def create_feedback(config, connection, failed_at, device) formatted_failed_at = failed_at.strftime('%Y-%m-%d %H:%M:%S UTC') Pushr::Daemon.logger.info("[#{connection.name}: Delivery failed at #{formatted_failed_at} for #{device}") Pushr::FeedbackApns.new(app: config.app, failed_at: failed_at, device: device, follow_up: 'delete').save end end end end end
Given(/^I am on the google site/) do visit 'http://www.google.com' end When(/^I enter "(.*?)" in the search input field$/) do |searchv1| fill_in('gbqfq', :with => 'hello') end And (/^I click google search/) do click_button('gbqfb') end Then(/^I should see message "(.*?)"$/) do |rmessage1| page.has_content?('About 797,000,000 results') end
class Coach::AreasController < CoachesController layout "coaches_areas" def show @area = CoachesArea.find params[:id] end end
require 'rails_helper' RSpec.describe Spree::Order do it "generates an order and advances it to the address state" do order = FactoryGirl.create(:order_with_line_items) order.next! expect(order.state).to eq("address") end end
class Driver module Contract class DriverForm < ::Reform::Form ::Driver.attribute_names.each { |col| property col.to_sym } validates :full_name, presence: true end end end
module RedmineRca module ProjectPatch def self.included(base) # :nodoc: base.extend(ClassMethods) base.send(:include, InstanceMethods) # Same as typing in the class base.class_eval do unloadable # Send unloadable so it will not be unloaded in development after_save :update_cmis_folder before_destroy :delete_cmis_folder end end module ClassMethods end module InstanceMethods def delete_cmis_folder Rails.logger.debug("\n[redmine_cmis_attachments] delete_cmis_folder on project #{self.id}") RedmineRca::Connection.delete_with_children cmis_object_id unless cmis_object_id.nil? end def update_cmis_folder Rails.logger.debug("\n[redmine_cmis_attachments] update_cmis_folder on project #{self.id}") create_folder if cmis_object_id.nil? move_folder if parent_cmis_object_id != RedmineRca::Connection.get_parent(cmis_object_id) update_description(cmis_object_id) Rails.logger.debug("[redmine_cmis_attachments] project #{self.id} has cmis_object_id #{cmis_object_id}\n") end def create_folder #Modificado el identificador de la carpeta que se guarda del proyecto #cogia el nombre y daba error, mejor con el identificador unico del proyecto #cmis_object_id = RedmineRca::Connection.mkdir(parent_cmis_object_id, self.name) #cmis_object_id = RedmineRca::Connection.mkdir(parent_cmis_object_id, self.identifier) nameFolderProject = self.name folder = RedmineRca::Connection.folder_by_tree_and_name(parent_cmis_object_id, nameFolderProject) if !folder.nil? nameFolderProject += '-' + self.identifier end nameFolderProject = nameFolderProject.gsub(/[\/\*\<\>\:\"\'\?\|\\]|[\. ]$/, '_') cmis_object_id = RedmineRca::Connection.mkdir(parent_cmis_object_id, nameFolderProject) update_description(cmis_object_id) RedmineCmisAttachmentsSettings.set_project_param_value(self, "documents_path_base", cmis_object_id) end def cmis_object_id RedmineCmisAttachmentsSettings.get_project_param_value_no_inherit(self, "documents_path_base") end def parent_cmis_object_id return Setting.plugin_redmine_cmis_attachments['documents_path_base'] if self.parent.nil? self.parent.create_folder if self.parent.cmis_object_id.nil? self.parent.cmis_object_id end def move_folder Rails.logger.debug("[redmine_cmis_attachments] update_folder_location for project #{self.id}\n") #RedmineRca::Connection.move cmis_object_id, self.name, parent_cmis_object_id #RedmineRca::Connection.move cmis_object_id, self.identifier, parent_cmis_object_id, nil, nil, self.identifier RedmineRca::Connection.move cmis_object_id, self.name, parent_cmis_object_id, nil, nil, self.cmis_object_id end def update_description(cmis_object_id) folder = RedmineRca::Connection.get_folder(cmis_object_id) if !folder.nil? folder.update_properties('cmis:description'=>self.description) end end end end end
class RedeemifyCode < ActiveRecord::Base belongs_to :provider belongs_to :user has_many :vendor_codes #accepts_nested_attributes_for :vendor_codes #validates_presence_of :code validates :code, presence: true, uniqueness: {message: "already registered"}, length: { maximum: 255, message: "longer than 255 characters" } def self.serve(myUser, myCode) rCode = self.where(code: myCode, user: nil).first #look up newcomer's provider token if rCode #happy path: redeem the token rCode.assign_to myUser myUser.code = myCode myUser.save! end end def assign_to(myUser) self.update_attributes(:user_id => myUser.id, :user_name => myUser.name, :email => myUser.email) provider = self.provider provider.update_attribute(:usedCodes, provider.usedCodes + 1) provider.update_attribute(:unclaimCodes, provider.unclaimCodes - 1) end def self.anonymize!(myUser) rCode = find_by user: myUser if rCode rCode.user_name = "anonymous" rCode.email = "anonymous@anonymous.com" rCode.save! end end end
class BatExtras < Formula desc "Bash scripts that integrate bat with various command-line tools" homepage "https://github.com/eth-p/bat-extras/blob" url "https://github.com/eth-p/bat-extras/archive/v2020.05.01.tar.gz" sha256 "ad6a65570f7dfd49e947eec65b2fae52be59feedf7030de801f7fd5b25193885" head "https://github.com/eth-p/bat-extras.git" depends_on "shfmt" => :build depends_on "bat" depends_on "entr" # batwatch depends_on "prettier" # prettybat depends_on "ripgrep" # batgrep depends_on "shfmt" # prettybat depends_on "clang-format" => :recommended # prettybat def install system "./build.sh", "--no-verify", "--minify=all" bin.install "bin/batgrep" => "batgrep" bin.install "bin/batman" => "batman" bin.install "bin/batwatch" => "batwatch" bin.install "bin/batdiff" => "batdiff" bin.install "bin/prettybat" => "prettybat" end def caveats <<~EOS The following packages are not installed by default: - clang-format (used by prettybat) EOS end test do (testpath/"test.txt").write <<~EOS abc def ghi cat dog fox EOS # batgrep assert_match /^batgrep\s+\d{4}\.\d{2}\.\d{2}\b/, shell_output("#{bin}/batgrep --version 2>&1").lines.first.chomp assert_equal ["def\n", "fox\n"], shell_output("#{bin}/batgrep '^f|f$' --context=0 --no-color").lines[1..-2] # batdiff assert_match /^batdiff\s+\d{4}\.\d{2}\.\d{2}\b/, shell_output("#{bin}/batdiff --version 2>&1").lines.first.chomp # batman assert_match /^batman\s+\d{4}\.\d{2}\.\d{2}\b/, shell_output("#{bin}/batman --version 2>&1").lines.first.chomp # batwatch assert_match /^batwatch\s+\d{4}\.\d{2}\.\d{2}\b/, shell_output("#{bin}/batwatch --version 2>&1").lines.first.chomp # prettybat assert_match /^prettybat\s+\d{4}\.\d{2}\.\d{2}\b/, shell_output("#{bin}/prettybat --version 2>&1").lines.first.chomp end end
FactoryGirl.define do sequence :name do |n| "Jennifer #{n}" end sequence :email do |n| "email#{n}@email.com" end factory :user do name email password 'Password123' password_confirmation 'Password123' end end
github_binary 'peco' do repository 'peco/peco' version 'v0.5.1' ext = (node[:platform] == 'darwin' ? 'zip' : 'tar.gz') archive "peco_#{node[:os]}_amd64.#{ext}" binary_path "peco_#{node[:os]}_amd64/peco" end dotfile '.peco'
class Pitchfile include Mongoid::Document include Mongoid::Timestamps belongs_to :user field :file_id, type: Integer field :name, type: String field :visible, type: Boolean, default: false field :parent_id, type: Integer field :is_Folder, type: Boolean validates_presence_of :file_id, :parent_id end
# handles venue reservation from user side module Reservable extend ActiveSupport::Concern def make_reservation unless current_user msg = { status: 'error', message: 'Log in to book!', html: '<b>...</b>' } render json: msg && return end paid = true reservations, errors = make_reservations(params[:bookings], paid) save_reservations(reservations, @venue, paid) reservations_response(errors) end def make_unpaid_reservation unless current_user msg = { status: 'error', message: 'Log in to book!', html: '<b>...</b>' } render json: msg && return end reservations, errors = make_reservations(params[:bookings]) save_reservations(reservations, @venue) reservations_response(errors) end private def reservations_response(errors) if errors.empty? render nothing: true, status: :ok else render json: errors.uniq, status: 402 end end def save_reservations(reservations, venue, paid=false) Reservation.transaction do # what happens if reservatons.valid? is empty ? reservations.select(&:valid?).each do |reservation| if paid && reservation.game_pass reservation.amount_paid = reservation.price reservation.is_paid = true reservation.game_pass.reload.use! end reservation.save reservation.track_booking end venue.add_customer(current_user) end end def make_reservations(bookings, paid=false) errors = [] reservations = bookings.values.map do |p| if paid booking_params = sanitize_booking_params(p, paid) else booking_params = sanitize_booking_params(p) end reservation = Reservation.new(booking_params).take_matching_resell if paid && !booking_params[:game_pass] reservation, error = handle_payment(reservation) end errors << error unless error.nil? reservation end [reservations, errors] end def sanitize_booking_params(p, paid=false) start_time = TimeSanitizer.input(p[:datetime]) end_time = start_time + p[:duration].to_i.minutes current_court = Court.find(p[:id]) game_pass = GamePass.find_by_id(p[:game_pass_id]) if paid { start_time: start_time, end_time: end_time, court: current_court, price: calculate_price(current_court, start_time, end_time), payment_type: :paid, booking_type: :online, user: current_user, game_pass: game_pass } else { start_time: start_time, end_time: end_time, court: current_court, price: calculate_price(current_court, start_time, end_time), payment_type: :unpaid, booking_type: :online, user: current_user } end end def calculate_price(court, start_time, end_time) discount = current_user.discounts .find_by(venue_id: court.venue .id) court.price_at(start_time, end_time, discount) end def handle_payment(reservation) error = if reservation.valid? reservation.charge(params[:card]) else 'Not charging invalid reservation' end [reservation, error] end end
module FacebookCommands class << self def friends(*args) if args.first == 'help' puts 'list [returns list of your friends]' puts 'list <uid> [returns list of <uid>\'s friends]' return end if args.first == 'list' args.shift person = !args.empty? ? args.first : 'me' friends = FacebookCL.get("#{person}/friends") friends['data'].each do |friend| puts "[*] #{friend['name']}" end end if args.first == 'count' args.shift person = !args.empty? ? args.first : 'me' friends = FacebookCL.get("#{person}/friends") puts "Count: #{friends['data'].size}" end end alias :friend :friends end end
# frozen_string_literal: true require 'common/client/base' require 'mvi/configuration' require 'mvi/responses/find_profile_response' require 'common/client/concerns/monitoring' require 'common/client/middleware/request/soap_headers' require 'common/client/middleware/response/soap_parser' require 'mvi/errors/errors' require 'sentry_logging' module MVI # Wrapper for the MVI (Master Veteran Index) Service. vets.gov has access # to three MVI endpoints: # * PRPA_IN201301UV02 (TODO(AJD): Add Person) # * PRPA_IN201302UV02 (TODO(AJD): Update Person) # * PRPA_IN201305UV02 (aliased as .find_profile) class Service < Common::Client::Base include Common::Client::Monitoring # The MVI Service SOAP operations vets.gov has access to unless const_defined?(:OPERATIONS) OPERATIONS = { add_person: 'PRPA_IN201301UV02', update_person: 'PRPA_IN201302UV02', find_profile: 'PRPA_IN201305UV02' }.freeze end # @return [MVI::Configuration] the configuration for this service configuration MVI::Configuration STATSD_KEY_PREFIX = 'api.mvi' unless const_defined?(:STATSD_KEY_PREFIX) # Given a user queries MVI and returns their VA profile. # # @param user [User] the user to query MVI for # @return [MVI::Responses::FindProfileResponse] the parsed response from MVI. def find_profile(user) with_monitoring do Rails.logger.measure_info('Performed MVI Query', payload: logging_context(user)) do raw_response = perform(:post, '', create_profile_message(user), soapaction: OPERATIONS[:find_profile]) MVI::Responses::FindProfileResponse.with_parsed_response(raw_response) end end rescue Faraday::ConnectionFailed => e log_console_and_sentry("MVI find_profile connection failed: #{e.message}", :error) MVI::Responses::FindProfileResponse.with_server_error rescue Common::Client::Errors::ClientError, Common::Exceptions::GatewayTimeout => e log_console_and_sentry("MVI find_profile error: #{e.message}", :error) MVI::Responses::FindProfileResponse.with_server_error rescue MVI::Errors::Base => e mvi_error_handler(user, e) if e.is_a?(MVI::Errors::RecordNotFound) MVI::Responses::FindProfileResponse.with_not_found else MVI::Responses::FindProfileResponse.with_server_error end end private def mvi_error_handler(user, e) case e when MVI::Errors::DuplicateRecords log_console_and_sentry('MVI Duplicate Record', :warn) when MVI::Errors::RecordNotFound # Not going to log RecordNotFound to sentry, cloudwatch only. log_console_and_sentry('MVI Record Not Found') when MVI::Errors::InvalidRequestError # NOTE: ICN based lookups do not return RecordNotFound. They return InvalidRequestError if user.mhv_icn.present? log_console_and_sentry('MVI Invalid Request (Possible RecordNotFound)', :error) else log_console_and_sentry('MVI Invalid Request', :error) end when MVI::Errors::FailedRequestError log_console_and_sentry('MVI Failed Request', :error) end end def log_console_and_sentry(message, sentry_classification = nil) Rails.logger.info(message) log_message_to_sentry(message, sentry_classification) if sentry_classification.present? end def logging_context(user) { uuid: user.uuid, authn_context: user.authn_context } end def create_profile_message(user) return message_icn(user) if user.mhv_icn.present? # from SAML::UserAttributes::MHV::BasicLOA3User raise Common::Exceptions::ValidationErrors, user unless user.valid?(:loa3_user) message_user_attributes(user) end def message_icn(user) MVI::Messages::FindProfileMessageIcn.new(user.mhv_icn).to_xml end def message_user_attributes(user) given_names = [user.first_name] given_names.push user.middle_name unless user.middle_name.nil? MVI::Messages::FindProfileMessage.new( given_names, user.last_name, user.birth_date, user.ssn, user.gender ).to_xml end end end
# frozen_string_literal: true require_relative 'test_helper' DB.create_table :legacy_humans do primary_key :id column :encrypted_email, :string column :password, :string column :encrypted_credentials, :string column :salt, :string end class LegacyHuman < Sequel::Model(:legacy_humans) self.attr_encrypted_options[:insecure_mode] = true self.attr_encrypted_options[:algorithm] = 'aes-256-cbc' self.attr_encrypted_options[:mode] = :single_iv_and_salt attr_encrypted :email, :key => 'a secret key', mode: :single_iv_and_salt attr_encrypted :credentials, :key => Proc.new { |human| Encryptor.encrypt(:value => human.salt, :key => 'some private key', insecure_mode: true, algorithm: 'aes-256-cbc') }, :marshal => true, mode: :single_iv_and_salt def after_initialize(attrs = {}) self.salt ||= Digest::SHA1.hexdigest((Time.now.to_i * rand(5)).to_s) self.credentials ||= { :username => 'example', :password => 'test' } end end class LegacySequelTest < Minitest::Test def setup LegacyHuman.all.each(&:destroy) end def test_should_encrypt_email @human = LegacyHuman.new :email => 'test@example.com' assert @human.save refute_nil @human.encrypted_email refute_equal @human.email, @human.encrypted_email assert_equal @human.email, LegacyHuman.first.email end def test_should_marshal_and_encrypt_credentials @human = LegacyHuman.new assert @human.save refute_nil @human.encrypted_credentials refute_equal @human.credentials, @human.encrypted_credentials assert_equal @human.credentials, LegacyHuman.first.credentials assert LegacyHuman.first.credentials.is_a?(Hash) end def test_should_encode_by_default assert LegacyHuman.attr_encrypted_options[:encode] end end
class Character < ApplicationRecord belongs_to :user belongs_to :race has_many :comments, dependent: :destroy has_many :users, through: :comments validates :name, presence: true def to_slug name.downcase.parameterize end def to_param slug end def average_rating rating = 0 count = 0 self.comments.each do |c| rating += c.rating count += 1 end (rating/count.to_f).round(1) end def has_rating? if self.comments.size == 0 false else true end end end
require File.expand_path(File.dirname(__FILE__) + "/../../../spec_helper") describe FreemarkerTemplateEngine do before(:all) do @project_path = "src/vraptor-scaffold" @webapp = "#{@project_path}/#{Configuration::WEB_APP}" @web_inf = "#{@project_path}/#{Configuration::WEB_INF}" @decorators = "#{@web_inf}/views/decorators" @app = "#{@project_path}/#{Configuration::MAIN_SRC}/br/com/caelum" end context "configuring" do before(:all) do AppGenerator.new(@project_path, ["--template-engine=ftl", "-p=br.com.caelum", "--orm=hibernate"]).invoke_all end after(:all) do FileUtils.remove_dir(@project_path) end it "should create decorators.xml" do source = File.join File.dirname(__FILE__), "templates", "decorators.xml" destination = "#{@web_inf}/decorators.xml" exists_and_identical?(source, destination) end it "should create web.xml" do source = File.join File.dirname(__FILE__), "templates", "freemarker-web.xml" destination = "#{@web_inf}/web.xml" exists_and_identical?(source, destination) end it "should create views folder" do File.exist?("#{@web_inf}/views").should be_true end it "should create infrastructure folder" do File.exist?("#{@app}/infrastructure").should be_true end it "should create path resolver" do source = File.join File.dirname(__FILE__), "templates", "FreemarkerPathResolver.java" destination = "#{@app}/infrastructure/FreemarkerPathResolver.java" exists_and_identical?(source, destination) end it "should create decorator file" do destination = "#{@decorators}/main.ftl" content = File.read(destination) content.include?("bootstrap").should be_false content.empty?.should be_false end it "should create html macro file" do source = "#{FreemarkerTemplateEngine.source_root}/macros/html.ftl" destination = "#{@webapp}/macros/html.ftl" exists_and_identical?(source, destination) end end context "bootstrap setup" do before(:all) do AppGenerator.new(@project_path, ["--template-engine=ftl", "--bootstrap"]).invoke_all end after(:all) do FileUtils.remove_dir(@project_path) end it "should add bootstrap js and css" do main = "#{@decorators}/main.ftl" js_added = '<@html.js "bootstrap"/>' css_added = '<@html.css "bootstrap"/>' content = File.read(main) content.include?(js_added).should be_true content.include?(css_added).should be_true end end end
class RailwayStationsRoute < ActiveRecord::Base belongs_to :railway_station belongs_to :route end
# -*- coding: utf-8 -*- require 'spec_helper' describe BooksController, 'GET /find/:query' do before(:each) do @book = Factory(:book) end it "リクエストが成功すること" do get 'find' response.should be_success end it "検索結果に本が含まれること" do get 'find', :query => @book.name assigns[:books].should include(@book) end it "検索結果に本が含まれないこと" do get 'find', :query => 'invailed query' assigns[:books].should_not include(@book) end end describe BooksController, 'GET /show/:id' do before(:each) do @book = FactoryGirl.create(:book) end it "リクエストが成功すること" do get 'show', :id => @book.id response.should be_success end it "対象のbookが取得されること" do get 'show', :id => @book.id assigns[:book].should == @book end end