text
stringlengths
10
2.61M
# frozen_string_literal: true class UserForSelectSerializer < ActiveModel::Serializer attributes :name, :id, :account_number, :current_user, :debt_permitted end
RSpec.describe Cards::Transactions::Sync do let(:card) { create :card } let(:transactions) do [ { date: Time.parse('20.07.2017'), title: 'Перечисление з/п по реестру', amount_cents: 5000000.0, amount_currency: 'RUB' }, { date: Time.parse('02.08.2017'), title: 'банкомат ФК Открытие', amount_cents: -500000.0, amount_currency: 'RUB' }, { date: Time.parse('01.08.2017'), title: 'АЗС Лукойл 101', amount_cents: -150000.0, amount_currency: 'RUB' } ] end let(:user) { card.user } let(:client) { double('openbank_client', transactions_history: transactions) } subject { described_class.call(card: card, client: client) } before do create :recurrent_expense_label, user: user, title: 'банкомат ФК Открытие' end it 'updates user expenses and incomes' do subject expect(user.recurrent_expenses.count).to eq 1 expect(user.random_expenses.count).to eq 1 expect(user.incomes.count).to eq 1 end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) # User.all.each do |user| user.mobile_device.split(",").each do |device| case device.strip when "iphone" user.update(:iphone => true) when "android" user.update(:android => true) when "blackberry" user.update(:blackberry => true) when "ipad" user.update(:ipad => true) when "tablet" user.update(:tablet => true) else #other user.update(:other => true) end end end
# coding: utf-8 class JournalTypesController < ApplicationController before_filter :auth_required def index end def search @items = JournalType.order(:name) if !params[:q].blank? @items = @items.where("(name LIKE :q)", {:q => "%#{params[:q]}%"}) end render :layout => false end def new @journal_type = JournalType.new render :layout => false end def create @journal_type = JournalType.new(journal_type_params) @journal_type.status = JournalType::ACTIVE flash = {} if @journal_type.save flash[:notice] = "Tipo de revista creado satisfactoriamente." # LOG @journal_type.activity_log.create(user_id: current_user.id, message: "Creó el tipo \"#{@journal_type.name}\" (ID: #{@journal_type.id}).") json = {} json[:id] = @journal_type.id json[:title] = @journal_type.name json[:flash] = flash render :json => json else flash[:error] = "No se pudo crear el tipo de revista." json = {} json[:flash] = flash json[:model_name] = self.class.name.sub("Controller", "").singularize json[:errors] = {} json[:errors] = @journal_type.errors render :json => json, :status => :unprocessable_entity end end def show @journal_type = JournalType.find(params[:id]) render :layout => false end def update @journal_type = JournalType.find(params[:id]) flash = {} if @journal_type.update_attributes(journal_type_params) flash[:notice] = "Tipo de revista actualizado satisfactoriamente." json = {} json[:id] = @journal_type.id json[:title] = @journal_type.name json[:flash] = flash render :json => json else flash[:error] = "No se pudo actualizar el tipo de revista." json = {} json[:flash] = flash json[:model_name] = self.class.name.sub("Controller", "").singularize json[:errors] = {} json[:errors] = @journal_type.errors render :json => json, :status => :unprocessable_entity end end protected def journal_type_params params[:journal_type].permit(:name, :is_international, :is_indexed, :is_refereed, :is_popular_science) end end
class Campus < ActiveRecord::Base has_many :buildings, dependent: :destroy has_many :polygons, as: :imageable, dependent: :destroy validates :name, presence: true, length: { maximum: 32}, uniqueness: true validates :description, length: {maximum: 64} end
class Commitment < ActiveRecord::Base belongs_to :team belongs_to :championship validates_presence_of :team, :championship end
require_relative "lib/bootstrap" RSpec.configure do |config| config.before :suite do AnsibleHelper.playbook("playbooks/install.yml", ENV["TARGET_HOST"], { env_name: "dev", install_mysql: true, new_db_name: "test_db", new_db_user: "test_db_owner", new_db_pass: "password123", new_db_priv: "*.*:SELECT" }) end end describe "New DB user" do let(:subject) { command('mysql -Nqs -utest_db_owner -ppassword123 -e "CREATE TABLE test_db.test_table (id INTEGER PRIMARY KEY)"') } it "should not be able to create tables" do expect(subject.stderr).to match /CREATE command denied to user 'test_db_owner'@'localhost'/ expect(subject.exit_status).not_to eq 0 end end
doctype html html head title Dashboard = csrf_meta_tags = csp_meta_tag = stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' //! Fonts and icons // Font Awesome link crossorigin="anonymous" href="https://use.fontawesome.com/releases/v5.0.8/css/all.css" integrity="sha384-3AB7yXWz4OeoZcPbieVW64vVXEwADiYyAEhwilzWsLw+9FgqpyjjStpPnpBO8o8S" rel="stylesheet" / // Google API fonts link href="https://fonts.googleapis.com/css2?family=Ubuntu&display=swap" rel="stylesheet" // Bootstrap style link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous" /! Material Kit CSS link href="/material-dashboard.css?v=2.1.2" rel="stylesheet" link href="/dashboard.css" rel="stylesheet" = javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0" body class="#{controller_name } #{action_name}" .row.position-relative.container-fluid .position-absolute.zIndex1000 - flash.each do |title, value| - if title == "notice" p.flash.alert.alert-success = value - elsif title == "alert" p.flash.alert.alert-danger = value .col-2.pr-0 = render 'layouts/sidebar' .col-10.bg-light.pt-3.px-4 = yield //script script src="https://code.jquery.com/jquery-1.12.4.min.js" script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js" script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js" script crossorigin="anonymous" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" script crossorigin="anonymous" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" css: .zIndex1000{ z-index: 1000; } javascript: let dataTable = "" document.addEventListener("turbolinks:before-cache", function () { if (dataTable !== null) { dataTable.destroy(); dataTable = null; } }); document.addEventListener('turbolinks:load', function () { setTimeout(function () { var flash = document.querySelector('.flash.alert'); if (flash) { flash.innerText = ''; flash.classList.remove('alert'); } }, 5000) dataTable = $('#example-table').DataTable({ "lengthChange": false, "bPaginate": false, "bInfo": false }); let search = $('.dataTables_filter') search.addClass('d-inline') search.find("label")[0].firstChild.data = "" search.find("input").attr("placeholder", "Search Here") var searchFilter = document.querySelector('.search-filter') searchFilter.append(search[0]) let searches = document.querySelectorAll('#example-table_filter'); if(searches.length == 2){ searches[0].remove(); let exampleTable = $('#example-table_filter'); exampleTable.addClass('d-inline'); exampleTable.find("label")[0].firstChild.data = ""; exampleTable.find("input").attr("placeholder", "Search Here"); searchFilter.append(exampleTable[0]); } });
require "rails_helper" RSpec.describe 'News', js: true do let!(:article) { NewsArticle.create!({ title: 'first title', body: 'first body', subtitle: 'first subtitle', background_image_url: 'http://lvh.me/testing.png' }) } let!(:article2) { NewsArticle.create!({ title: 'second title', body: 'second body', subtitle: 'second subtitle', background_image_url: 'http://lvh.me/testing.png' }) } before do visit "/news/#{article.id}" end include_examples "layout" include_examples "header" it "news article should contain body" do expect(page).to have_content(article.body) end it "navigation links should work" do page.find("a.next").click expect(page).to have_content(article2.body) page.find("a.previous").click expect(page).to have_content(article.body) end end
module JRuby::Lint module Checkers class Gemspec include Checker include CheckGemNode def visitCallNode(node) # Gem::Specification.new do |s| => # # CallNoArgBlockNode |new| # Colon2ConstNode |Specification| # IterNode # DAsgnNode |s| &0 >0 # NilImplicitNode |nil| # BlockNode if node.name == "new" && # new node.args_node.nil? && # no args node.iter_node && # with a block node.receiver_node.node_type.to_s == "COLON2NODE" && # :: - Colon2 node.receiver_node.name == "Specification" && # ::Specification node.receiver_node.left_node.name == "Gem" # Gem::Specification @gemspec_block_var = node.iter_node.var_node.name return proc { @gemspec_block_var = nil } end # s.add_dependency "rdiscount" => # # CallOneArgNode |add_dependency| # DVarNode |s| &0 >0 # ArrayNode # StrNode =="rdiscount" if @gemspec_block_var && node.name == "add_dependency" && node.receiver_node.name == @gemspec_block_var check_gem(collector, node) end rescue end end end end
class RemoveHstoreFromLists < ActiveRecord::Migration def change remove_column :lists, :items end end
# encoding: UTF-8 require 'test_helper' class Html5StringInputTest < ActionView::TestCase [:html5_date, :html5_datetime, :html5_time].each do |type| html5_type = type.to_s.sub(/^html5_/, '') test "input should allow type #{type}" do with_input_for @user, :name, type assert_select "input[type=#{html5_type}]" end test "input should not allow type #{type} if HTML5 compatibility is disabled" do swap_wrapper do with_input_for @user, :name, type assert_select "input[type=text]" assert_no_select "input[type=#{html5_type}]" end end end end
# public List<List<Integer>> subsets(int[] nums) { # List<List<Integer>> list = new ArrayList<>(); # Arrays.sort(nums); # backtrack(list, new ArrayList<>(), nums, 0); # return list; # } def subsets(nums) list = [] # nums.sort! backtrack(list, Array.new, nums, 0) # p list.size list end # private void backtrack(List<List<Integer>> list , List<Integer> tempList, int [] nums, int start){ # list.add(new ArrayList<>(tempList)); # for(int i = start; i < nums.length; i++){ # tempList.add(nums[i]); # backtrack(list, tempList, nums, i + 1); # tempList.remove(tempList.size() - 1); # } # } def backtrack(list, temp_list, nums, start) list << temp_list.dup p list for i in start...nums.length do temp_list << nums[i] backtrack(list, temp_list, nums, i + 1) temp_list.pop end end def subsets1(nums) return [[]] if nums.empty? subsets = subsets(nums[1..-1]) res = [] subsets.each do |subset| res << subset res << (subset.dup << nums[0]) end res end nums = [1,2,3] # backtrack([], temp, nums, 0) # list = [[temp]] # i = 0 # temp << nums[0] --> list [[1]] # [[1]] subsets(nums)
class App < HyperComponent include Hyperstack::Router class << self def reload! @reload = true end def reload? return unless @reload if Hyperstack.env.production? `window.newWorker.postMessage({ action: 'skipWaiting' })` else after(0.5) { mutate } end @reload = false true end def install_prompter(prompter) @install_prompter = prompter end def ready_to_install? @install_prompter end def confirm_install! `#{@install_prompter}.prompt()` @install_prompter = nil end end def wake_up! `window.location.reload()` unless @waking_up @waking_up = true end before_mount do Hyperstack::Model.load do Prayer.as_geojson end.then do @time = Time.now every(2) do puts "heartbeat! #{Time.now - @time}" wake_up! unless (Time.now - @time).between?(1, 4) @time = Time.now end end end after_render do `if (window.my_service_worker) window.my_service_worker.update()` # check for any updates nil end def display_error Mui::Paper(elevation: 3, style: { margin: 30, padding: 10, fontSize: 30, color: :red }) do 'Something went wrong, we will be back shortly!' end end render do # dynamically set height so it works on mobile devices like iphone / safari # which does not use 100vh properly. return display_error if @display_error DIV(class: :box, style: { height: WindowDims.height+1 }) do Header() Route('/about', mounts: About) Route('/reload', mounts: Reload) Route('/pray', mounts: Pray) Route('/schedule', mounts: Schedule) Route('/home', mounts: App.reload? ? Reload : Home) Route('/change-log', mounts: ChangeLog) Route('/frequent-cities', mounts: FrequentCities) Route('/recent-cities', mounts: RecentCities) Route('/done', mounts: Done) Route('/', exact: true) { mutate Redirect('/home') } Footer() unless App.location.pathname == '/' end end rescues do |error, info| ReportError.run(message: error.message, backtrace: error.backtrace, info: info) `window.location.href = '/home'` mutate @display_error = true end %x{ window.newWorker = null; // The click event on the notification // document.getElementById('reload').addEventListener('click', function(){ // newWorker.postMessage({ action: 'skipWaiting' }); // }); if ('serviceWorker' in navigator) { // Register the service worker navigator.serviceWorker.register('/service-worker.js').then(reg => { console.log('got the worker') window.my_service_worker = reg reg.addEventListener('updatefound', () => { console.log('update found') // An updated service worker has appeared in reg.installing! window.newWorker = reg.installing; window.newWorker.addEventListener('statechange', () => { console.log('statechange'); // Has service worker state changed? switch (window.newWorker.state) { case 'installed': console.log('installed!'); // There is a new service worker available, show the notification if (navigator.serviceWorker.controller) { console.log('its a controller') // alert('will load new code') #{reload!} // window.newWorker.postMessage({ action: 'skipWaiting' }); // let notification = document.getElementById('notification'); // notification.className = 'show'; } break; } }); }); }).catch(function(err) { // registration failed :( console.log('ServiceWorker registration failed: ', err); });; window.refreshing = null; // The event listener that is fired when the service worker updates // Here we reload the page navigator.serviceWorker.addEventListener('controllerchange', function () { if (refreshing) return; window.location.reload(); refreshing = true; }); } window.deferredPrompt = #{false}; window.addEventListener('beforeinstallprompt', function(e) { // Prevent the mini-infobar from appearing on mobile e.preventDefault(); // Stash the event so it can be triggered later. #{App.install_prompter(`e`)}; // later deferredPrompt.prompt(); }) } end
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc. # Authors: Adam Lebsack <adam@holonyx.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. class Admin::BaseController < InstallationController layout 'admin' def index if request.xhr? render :update do |page| page.replace_html 'appcontent', :partial => partial_path('index') end else render :partial => partial_path('index'), :layout => true end end protected def authorized? super @current_user.is_admin? end end
class User < ActiveRecord::Base has_many :posts has_secure_password #posts created by the user has_many :posts #votes ABOUT this user (via votable) has_many :votes, as: :votable #votes cast by the user (via user_id foreign key) has_many :ratings, class_name: 'Vote' validates :email, presence: true, uniqueness: {case_sensitive: false} validates :password, presence: true, :on => [:create, :update] def self.authenticate email, password User.find_by_email(email).try(:authenticate, password) end end
=begin Define a method that takes an array of numbers, and returns the total of the addition of all the numbers in the array. Store the result of a call to this method in a well-named variable. =end numbers = [3,5,8,6,3,6,5,3] def total(arr) arr.reduce( :+ ) end p result = total(numbers)
class AdminController < ApplicationController before_filter :require_authentication, except: [:login, :logout] def index redirect_to articles_path end def login if request.post? && params[:password] == ENV['AUTH_PASSWORD'] session[:authenticated] = true redirect_to admin_path end end def logout reset_session redirect_to root_path end end
require 'spec_helper' require 'json' def title_query_params q {qf: "${title_qf}", pf:"${title_pf}", q: q} end def left_anchor_query_params q {qf: "${left_anchor_qf}", pf: "${left_anchor_pf}", q: "#{q}*"} end describe 'title keyword search' do include_context 'solr_helpers' before do delete_all end describe 'title_display field' do let(:patterns_in_nature) { '1355809' } before do add_doc(patterns_in_nature) end it 'retrieves book when first word in title_display is searched' do expect(solr_resp_doc_ids_only(title_query_params('Patterns'))).to include(patterns_in_nature) end it 'retrieves book with multiword query of title_display field' do expect(solr_resp_doc_ids_only(title_query_params('Patterns in nature by'))).to include(patterns_in_nature) end it 'casing does not impact search' do expect(solr_resp_doc_ids_only(title_query_params('pAttErnS iN NatURE'))).to include(patterns_in_nature) end it 'title keywords are not required to appear in the same order as title_display field' do expect(solr_resp_doc_ids_only(title_query_params('stevens patterns'))).to include(patterns_in_nature) end it 'title keywords are stemmed' do expect(solr_resp_doc_ids_only(title_query_params('steven pattern'))).to include(patterns_in_nature) end it 'fails to match when word in query is missing from title_display field (mm 6<90%)' do expect(solr_resp_doc_ids_only(title_query_params('pattern in nature by peter rabbit'))).not_to include(patterns_in_nature) end end describe 'series_title_index field' do let(:mozart_series) { '8919079' } let(:series_title) { 'Neue Ausgabe samtlicher Werke' } before do add_doc(mozart_series) end it 'series title is not in 245' do expect(solr_resp_doc_ids_only({ 'fq' => "title_display:\"#{series_title}\"" })).not_to include(mozart_series) end it 'series title is in 490' do expect(solr_resp_doc_ids_only({ 'fq' => "series_title_index:\"#{series_title}\"" })).to include(mozart_series) end it 'title keyword search matches 490 field' do expect(solr_resp_doc_ids_only(title_query_params(series_title))).to include(mozart_series) end end describe 'title_a_index field relevancy' do let(:silence) { '1228819' } let(:four_silence_subtitle) { '4789869' } let(:sounds_like_silence) { '7381137' } before do add_doc(silence) add_doc(four_silence_subtitle) add_doc(sounds_like_silence) end it 'exact 245a match more relevant than longer 245a field' do expect(solr_resp_doc_ids_only(title_query_params('silence'))) .to include(silence).before(sounds_like_silence) end it '245a match more relevant than subtitle match' do expect(solr_resp_doc_ids_only(title_query_params('silence'))) .to include(sounds_like_silence).before(four_silence_subtitle) end end describe 'title exact match relevancy' do let(:first_science) { '9774575' } let(:science_and_spirit) { '9805613' } let(:second_science) { '857469' } before do add_doc(first_science) add_doc(science_and_spirit) add_doc(second_science) end it 'exact matches Science' do expect(solr_resp_doc_ids_only(title_query_params('Science').merge('sort' => 'score DESC'))["response"]["docs"].last) .to eq({"id" => science_and_spirit}) end it 'left anchor exact matches Science' do expect(solr_resp_doc_ids_only(left_anchor_query_params('Science').merge('sort' => 'score DESC'))["response"]["docs"].last) .to eq({"id" => science_and_spirit}) end context 'with a title which includes whitespace around punctuation marks' do let(:idioms_and_colloc) { '5188770' } before do add_doc(idioms_and_colloc) end it 'matches titles without the whitespace' do expect(solr_resp_doc_ids_only(left_anchor_query_params('Idioms\ and\ collocations\ \:\ corpus-based').merge('sort' => 'score DESC'))["response"]["docs"].last) .to eq({"id" => idioms_and_colloc}) expect(solr_resp_doc_ids_only(left_anchor_query_params('Idioms\ and\ collocations\:\ corpus-based').merge('sort' => 'score DESC'))["response"]["docs"].last) .to eq({"id" => idioms_and_colloc}) end end end describe 'handling for titles which contain dashes' do let(:bibid) { '212556' } let(:query) { 'theory of the avant garde' } let(:parameters) do title_query_params(query).merge('sort' => 'score DESC') end let(:response) { solr_resp_doc_ids_only(parameters) } let(:documents) { response["response"]["docs"] } before do add_doc(bibid) end it 'finds titles containing dashes' do expect(documents.last).to eq({ "id" => bibid }) end context 'when a query contains a dash character' do let(:query) { 'theory of the avant-garde' } it 'finds titles containing dashes' do expect(documents.last).to eq({ "id" => bibid }) end end end after do delete_all end end describe 'title_l search' do include_context 'solr_helpers' let(:response) { solr_resp_doc_ids_only(params)['response'] } let(:docs) { response['docs'] } before do solr.add({ id: 1, title_display: [title] }) solr.commit end context 'when colon excluded in query' do let(:title) { 'Photo-secession : the golden age' } let(:params) do left_anchor_query_params('Photo-secession\\ \\ the') end it 'matches when colon excluded in query' do expect(docs).to eq([{ "id" => "1" }]) end end context 'when dash is excluded in query' do let(:title) { 'Photo-secession : the golden age' } let(:params) do left_anchor_query_params('Photosecession\\ the') end it 'matches when dash is excluded in query' do expect(docs).to eq([{ "id" => "1" }]) end end context 'Tests that search is left-anchored' do let(:title) { 'Katja Strunz : Zeittraum' } let(:params) do left_anchor_query_params('Katja\\ Strunz\\ :\\ Zeittraum') end it 'matches when the query includes first word of title' do expect(docs).to eq([{ "id" => "1" }]) end end context 'Tests that cjk searches work with wildcards' do let(:title) { '浄名玄論 / 京都国' } let(:params) do left_anchor_query_params('浄名玄') end it 'matches when the query includes first word of title' do expect(docs).to eq([{ "id" => "1" }]) end end context 'when dash is excluded in query' do let(:title) { 'Katja Strunz : Zeittraum' } let(:params) do left_anchor_query_params('Strunz') end it 'does not match when first word of title is not in query' do expect(docs).to eq([]) end end after do delete_all end end
require "application_system_test_case" class CategoryAnswersTest < ApplicationSystemTestCase setup do @category_replay = category_answers(:one) end test "visiting the index" do visit category_answers_url assert_selector "h1", text: "Category Answers" end test "creating a Category replay" do visit category_answers_url click_on "New Category Replay" fill_in "Category", with: @category_replay.category_id fill_in "Replay", with: @category_replay.replay_id click_on "Create Category replay" assert_text "Category replay was successfully created" click_on "Back" end test "updating a Category replay" do visit category_answers_url click_on "Edit", match: :first fill_in "Category", with: @category_replay.category_id fill_in "Replay", with: @category_replay.replay_id click_on "Update Category replay" assert_text "Category replay was successfully updated" click_on "Back" end test "destroying a Category replay" do visit category_answers_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Category replay was successfully destroyed" end end
ActiveRecord::Schema.define do self.verbose = false create_table :issues, :force => :cascade do |t| t.integer :repo_id t.string :title t.text :description t.integer :source_user_id t.string :state t.boolean :locked t.datetime :opened_at t.datetime :closed_at t.timestamps end create_table :issues_labels, force: :cascade do |t| t.integer :issue_id t.integer :label_id t.timestamps end create_table :labels, force: :cascade do |t| t.integer :repo_id t.string :name t.timestamps end create_table :repos, :force => :cascade do |t| t.string :full_name t.timestamps end create_table :tags, force: :cascade do |t| t.integer :repo_id t.integer :issue_id t.string :name t.timestamps end end
=begin Write a method that takes a number as an argument. If the argument is a positive number, return the negative of that number. If the number is 0 or negative, return the original number. Examples; =end def negative(num) if num.zero? num elsif num.negative? num elsif num.positive? -num end end puts negative(5) == -5 puts negative(-3) == -3 puts negative(0) == 0
class Skill < ActiveRecord::Base has_many :divisions has_many :leagues, through: :divisions has_many :users, through: :divisions has_many :members, through: :divisions end
require 'spec_helper' require "rails_helper" describe UsersController, :type => :controller do before :each do @user1 = create(:user) @user2 = create(:user) photo = fixture_file_upload("/images/test.jpg", 'image/jpg') @params_update_avatar = { avatar: photo } end context "update avatar" do it "case 1: not login, call action should redirect to sign in page" do xhr :post, 'update_avatar', format: "js", id: @user1.id response.status.should eq 401 end it "case 2: login user, call action with other user, should redirect to home page" do sign_in @user2 xhr :post, 'update_avatar', format: "js", id: @user1.id, user: @params_update_avatar response.should redirect_to("/") end it "case 3: login admin, call action should success" do sign_in @user1 xhr :post, 'update_avatar', format: "js", id: @user1.id, user: @params_update_avatar, remotipart_submitted: true, "X-Requested-With"=>"IFrame", "X-Http-Accept"=>"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01" expect(@user1.reload.id).to eq @user1.id expect(assigns[:user].errors.blank?).to eq true # expect(@user1.avatar.url).to eq "test.jpg" end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) quiz_list = [ "Ruby Basics", "Intermediate Ruby", "Hard as a Ruby", "Polish Them Gems" ] question_list = [ ["For an array \"x = [1, 2, 3, 4]\", which does not return the value 4?", 1], ["How do you determine the type of an object in ruby?", 1], ["What will return the number of characters in \"QuizCode\"?", 1], ["Which is not a valid ruby variable?", 1], ["Which of the following will not add a 4 to array x?", 1], ["Question6", 1], ["Question1", 2], ["Question2", 2], ["Question3", 2], ["Question4", 2], ["Question5", 2], ["Question6", 2], ["Question1", 3], ["Question2", 3], ["Question3", 3], ["Question4", 3], ["Question5", 3], ["Question6", 3], ["Question1", 4], ["Question2", 4], ["Question3", 4], ["Question4", 4], ["Question5", 4], ["Question6", 4], ] answer_list = [ ["x.last", false, 1], ["x[-1]", false, 1], ["x[3]", false, 1], ["x[4]", true, 1], [".type", false, 2], [".inspect", false, 2], [".method", false, 2], [".class", true, 2], [".length", true, 3], [".string", false, 3], [".count", false, 3], [".chars", false, 3], ["!name", true, 4], ["@name", false, 4], ["$name", false, 4], ["name", false, 4], ["x << 4", false, 5], ["x + 4", true, 5], ["x[3] = 4", false, 5], ["x.push 4", false, 5], ["Answer", true, 6], ["WrongAnswer1", false, 6], ["WrongAnswer2", false, 6], ["WrongAnswer3", false, 6], ["Answer", true, 7], ["WrongAnswer1", false, 7], ["WrongAnswer2", false, 7], ["WrongAnswer3", false, 7], ["Answer", true, 8], ["WrongAnswer1", false, 8], ["WrongAnswer2", false, 8], ["WrongAnswer3", false, 8], ["Answer", true, 9], ["WrongAnswer1", false, 9], ["WrongAnswer2", false, 9], ["WrongAnswer3", false, 9], ["Answer", true, 10], ["WrongAnswer1", false, 10], ["WrongAnswer2", false, 10], ["WrongAnswer3", false, 10], ["Answer", true, 11], ["WrongAnswer1", false, 11], ["WrongAnswer2", false, 11], ["WrongAnswer3", false, 11], ["Answer", true, 12], ["WrongAnswer1", false, 12], ["WrongAnswer2", false, 12], ["WrongAnswer3", false, 12], ["Answer", true, 13], ["WrongAnswer1", false, 13], ["WrongAnswer2", false, 13], ["WrongAnswer3", false, 13], ["Answer", true, 14], ["WrongAnswer1", false, 14], ["WrongAnswer2", false, 14], ["WrongAnswer3", false, 14], ["Answer", true, 15], ["WrongAnswer1", false, 15], ["WrongAnswer2", false, 15], ["WrongAnswer3", false, 15], ["Answer", true, 16], ["WrongAnswer1", false, 16], ["WrongAnswer2", false, 16], ["WrongAnswer3", false, 16], ["Answer", true, 17], ["WrongAnswer1", false, 17], ["WrongAnswer2", false, 17], ["WrongAnswer3", false, 17], ["Answer", true, 18], ["WrongAnswer1", false, 18], ["WrongAnswer2", false, 18], ["WrongAnswer3", false, 18], ["Answer", true, 19], ["WrongAnswer1", false, 19], ["WrongAnswer2", false, 19], ["WrongAnswer3", false, 19], ["Answer", true, 20], ["WrongAnswer1", false, 20], ["WrongAnswer2", false, 20], ["WrongAnswer3", false, 20], ["Answer", true, 21], ["WrongAnswer1", false, 21], ["WrongAnswer2", false, 21], ["WrongAnswer3", false, 21], ["Answer", true, 22], ["WrongAnswer1", false, 22], ["WrongAnswer2", false, 22], ["WrongAnswer3", false, 22], ["Answer", true, 23], ["WrongAnswer1", false, 23], ["WrongAnswer2", false, 23], ["WrongAnswer3", false, 23], ["Answer", true, 24], ["WrongAnswer1", false, 24], ["WrongAnswer2", false, 24], ["WrongAnswer3", false, 24], ] quiz_list.each do |name| Quiz.create( name: name ) end question_list.each do |question_asked, quiz_id| Question.create( question_asked: question_asked, quiz_id: quiz_id ) end answer_list.each do |possible_answer, is_correct, question_id| Answer.create( possible_answer: possible_answer, is_correct: is_correct, question_id: question_id ) end
# frozen_string_literal: true require 'spec_helper' require 'web_test/util' include RSpec::WebserviceMatchers describe '#up?' do it 'follows redirects when necessary' do expect(WebTest::Util.up?('perm-redirector.com')).to be_truthy expect(WebTest::Util.up?('temp-redirector.org')).to be_truthy end it 'retries timeout errors once' do expect(WebTest::Util.up?('http://www.timeout-once.com')).to be_truthy end end
class Calendar include Neo4j::ActiveNode id_property :personal_id, on: :idHash property :calendarId, type: String property :idHash, type: String property :description, type: String property :background, type: String property :lastUpdate, type: DateTime has_many :in, :meetings, type: "BELONGS", model_class: Meeting end
require 'rails_helper' RSpec.describe "elblog/posts/index", :type => :view do before(:each) do @posts = FactoryGirl.create_list :elblog_post, 2 assign(:posts, @posts) end it "renders a list of posts" do render @posts.each do |post| assert_select "a[href=?]", post_path(post), :text => post.title, :count => 1 expect(rendered).to match(CGI.escapeHTML(post.content)) expect(rendered).to match(CGI.escapeHTML(post.author)) end end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable with_options presence: true do validates :email, uniqueness: true validates :password, format: { with: /\A(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9]{6,}\z/ } validates :user_name, uniqueness: true validates :full_name validates :corp_name end has_many :room_users has_many :users, through: :room_users end # 正規表現 # / / ;正規表現 # \A \z ;文頭と文末 ( == ^ $ ) # [ ] ;文字クラス指定 # ぁ-ん ァ-ン 一-龥 々 ヵ ヶ ;全角かなカナ漢字 # A-Z a-z 0-9 ;半角英数大小 # + ;直前の表現の繰り返し # .*? ;「0回以上(*)」繰り返す「任意の文字列(.)」(最短一致) # {x, y} ;直前の文字列(文字クラス)がx回以上y回以下の繰り返し # ?= ;肯定的先読み「hoge(?=huga)」 → hugaが直後に存在するhogeを検証する # ;(?=.*[~]) → 「[~]に一致する文字列」が直後に存在する「任意の文字列0文字以上」 # ;0文字=空文字を含むので、複数の(?=.*[])を同時に検証できる
require 'sinatra/base' require 'sinatra/async' require 'active_support' require_relative File.expand_path(File.join(File.dirname(__FILE__),'../app/models/Product')) module Mapper class Webserver < Sinatra::Base set :server, :thin register Sinatra::Async configure do set :threaded, true set :root, File.expand_path(File.join(File.dirname(__FILE__),"../app/")) # <= TODO: for gem location set :public_folder, Proc.new { File.join(root, "assets") } set :config, File.expand_path(File.join(File.dirname(__FILE__), '../config/config.yaml')) set :split_sign, "%" end helpers do def send(where, what, *redirect) EM.run do AMQP.connect do |connection| puts "Send message: #{what}" channel = AMQP::Channel.new connection queue = channel.queue(where, :auto_delete => true) exchange = channel.default_exchange exchange.publish(what, :routing_key => queue.name) EM.add_timer(1) { p "AMQP Broker says bye!" connection.close redirect to(redirect) if redirect } end end end def merge(settings, params) params.each do |key, value| new_data = path_to_hash(key, value) settings = settings.deep_merge(new_data) end p settings settings end def path_to_hash(path, value) arr = path.split(settings.split_sign) #["development", "db", "storage", "adapter"] hashes = Array.new(arr.length) #[{}, {}] hashes.fill(Hash.new) arr.each_with_index do |item, index| if index == 0 hashes[index][item] = value else hashes[index] = "" hashes[index] = {} hashes[index][item] = hashes[index - 1] end end hashes.last end def update_settings(new_data) raise ArgumentError, "new_data must be a hash!" unless new_data.kind_of? Hash raise StandardError, "Yaml file with settings is not defined!" unless settings.config.is_a? String begin File.open(settings.config, "w"){|f|f.write new_data.to_yaml} rescue => e p e end end end get '/hello-world' do body { "Url: #{request.url} \n Fullpath: #{request.fullpath} \n Path-info: #{request.path_info}" } end get '/' do @title = "Home" erb :index end aget '/send/:command' do send("rabbit.mapper", params[:command], "/") end aget '/delay/:n' do |n| EM.add_timer(n.to_i) { body { "delayed for #{n} seconds" } } end get '/link' do @title = "Таблиця порівняння товарів" @products = Product.get_all erb :link end post '/link/:id/:linked' do id = params[:id].to_i linked = params[:linked].to_i p Comparison.update(id, {:linked => linked}) unless linked.nil? or id.nil? end get '/settings' do p settings.config @env = ENV['MAPPER_ENV'] @action = "/settings/update" @method = "POST" @split_sign = settings.split_sign @options = YAML.load_file(settings.config)[@env] erb :options end post '/settings/update' do redirect to '/settings' if params.empty? options = YAML.load_file(settings.config) new_settings = merge(options, params) update_settings(new_settings) redirect to '/settings' end end end
class AddUserIdtoList < ActiveRecord::Migration def up create_table :lists do |t| t.string :name t.string :organization t.integer :user_id t.timestamps end def down end end
class AddDirecotryToAttachmentVersions < ActiveRecord::Migration def change add_column(:attachment_versions, :disk_directory, :string) unless column_exists?(:attachment_versions, :disk_directory) end end
require 'rails_helper' RSpec.describe PostsController, :type => :controller do let!(:published_post) { FactoryGirl.create(:post) } let!(:unpublished_post) { FactoryGirl.create(:post, unpublished_at: DateTime.now) } describe "GET index" do before { get :index } it "returns http success" do expect(response).to be_success end it "assigns public @posts" do expect(assigns(:posts).count).to eq 1 expect(assigns(:posts)).to_not include unpublished_post expect(assigns(:posts)).to include published_post end end describe "GET show" do it "returns http success when a post is published" do get :show, id: published_post expect(response).to be_success end it "assigns a published @post" do get :show, id: published_post expect(assigns(:post)).to eq published_post end it "returns http not found when a post is published" do get :show, id: unpublished_post expect(response).to be_not_found end end end
#--- # Excerpted from "Rails 4 Test Prescriptions", # published by The Pragmatic Bookshelf. # Copyrights apply to this code. It may not be used to create training material, # courses, books, articles, and the like. Contact us if you are in doubt. # We make no guarantees that this code is fit for any purpose. # Visit http://www.pragmaticprogrammer.com/titles/nrtest2 for more book information. #--- require 'test_helper' class TasksControllerTest < ActionController::TestCase setup do ActionMailer::Base.deliveries.clear sign_in users(:user) end test "on update with no completion, no email is sent" do task = Task.create!(title: "Write section on testing mailers", size: 2) patch :update, id: task.id, task: {size: 3} assert_equal 0, ActionMailer::Base.deliveries.size end test "on update with completion, send an email" do task = Task.create!(title: "Write section on testing mailers", size: 2) patch :update, id: task.id, task: {size: 3, completed: true} task.reload refute_nil task.completed_at assert_equal 1, ActionMailer::Base.deliveries.size email = ActionMailer::Base.deliveries.first assert_equal "A task has been completed", email.subject assert_equal ["monitor@tasks.com"], email.to assert_match /Write section on testing mailers/, email.body.to_s end # test "a user can create a task for a project they belong to" do project = Project.create!(name: "Project Runway") users(:user).projects << project users(:user).save! post :create, task: { project_id: project.id, title: "just do it", size: "1" } assert_equal project.reload.tasks.first.title, "just do it" end test "a user can not create a task for a project they do not belong to" do project = Project.create!(name: "Project Runway") post :create, task: { project_id: project.id, title: "just do it", size: "1" } assert_equal project.reload.tasks.size, 0 end # end
require 'minitest/autorun' require_relative '../contact' class TestContact < Minitest::Test def setup @contact = Contact.create( first_name: 'Grace', last_name: 'Hopper', email: 'grace@hopper.com', note: 'computer scientist') end def teardown Contact.delete_all end def test_all assert_equal [@contact], Contact.all end def test_find assert_equal @contact, Contact.find(@contact.id) end def test_find_by assert_equal @contact, Contact.find_by(first_name: 'Grace') end def test_delete_all Contact.delete_all assert_equal 0, Contact.all.size end def test_full_name assert_equal 'Grace Hopper', @contact.full_name end def test_update @contact.update(note: 'wrote the first compiler in 1952') assert_equal 'wrote the first compiler in 1952', @contact.note end def test_delete @contact.delete assert [], Contact.all end end
class Reward < ApplicationRecord has_many :user_rewards validates_presence_of :name end
class Api::PizzasController < ApplicationController before_action :set_pizza, only: [:show,:update, :destroy] def index render json: Pizza.all end def create @pizza = Pizza.new(pizza_params) if (@pizza.save) render json: @pizza else end end def show render json: @pizza end def update if (@pizza.update(pizza_params)) render json: @pizza else end end def destroy render json: @pizza.destroy end private def set_pizza @pizza = Pizza.find(params[:id]) end def pizza_params params.require(:pizza).permit(:name, :description, :price) end end
# == Schema Information # # Table name: plans # # id :integer not null, primary key # name :string # number_of_publications :integer # price :decimal(15, 2) default(0.0) # duration_in_days :integer default(0) # created_at :datetime not null # updated_at :datetime not null # additional_info :text # order :integer # class Plan < ActiveRecord::Base has_many :subscriptions has_many :coupons validates :name, presence: true validates :number_of_publications, presence: true, numericality: {greater_than: 0} validates :price, presence: true, numericality: {greater_than: 0.0} validates :duration_in_days, presence: true, numericality: {greater_than: 0} validates :order, presence: true def self.basic Plan.find_by_name('Basic') end end
# Section 5, lecture 63 grade = "B" if grade.downcase == "a" puts "That's an excellent grade. Good job!" elsif grade.downcase == "b" puts "That's a good grade. Let's bring it up next time." else # acts as a catch-all for all other possible scenarios puts "Unacceptable..." end def odd_or_even(number) if number.odd? "That number is odd." else "That number is even." end end p odd_or_even(3)
Rails.application.routes.draw do mount RailsAdmin::Engine => '/command_center', as: 'rails_admin' devise_for :team, controllers: { registrations: "registrations" } root to: "dashboard#index" resource :contests, only: [:show] resources :challenges, only: [:index] resources :challenge_responses, only: [:index, :create] resources :results, only: [:index] resources :teams, only: [:show, :new, :create] get "/__admin" => "admin#index", as: :admin post "/__admin" => "admin#send_message" post "/__admin/start_contest" => "admin#start_contest", as: :admin_start_contest post "/__admin/stop_contest" => "admin#stop_contest", as: :admin_stop_contest get "/unanswered", to: redirect("http://i.imgur.com/R1Xckcq.jpg") get "/presentation", to: "presentation#index" end
require 'sqlite3' require 'singleton' class QuestionDBConnection < SQLite3::Database include Singleton def initialize super('questions.db') self.type_translation = true self.results_as_hash = true end end require_relative 'ORMs/user' require_relative 'ORMs/question' require_relative 'ORMs/question_follow' require_relative 'ORMs/reply' require_relative 'ORMs/question_like' # class Question # # def self.all # data = QuestionDBConnection.instance.execute("SELECT * FROM questions") # data.map {|datum| Question.new(datum)} # end # # def self.find_by_id(id) # data = QuestionDBConnection.instance.execute("SELECT * FROM questions WHERE questions.id = '#{id}'") # Question.new(data.first) # end # # def self.find_by_author_id(id) # data = QuestionDBConnection.instance.execute("SELECT * FROM questions WHERE questions.user_id = '#{id}'") # data.map {|datum| Question.new(datum)} # end # # attr_accessor :title, :body, :user_id # attr_reader :id # # def initialize(options) # @id = options['id'] # @title = options['title'] # @body = options['body'] # @user_id = options['user_id'] # end # # def create # raise "#{self} already exists in database" if @id # QuestionDBConnection.instance.execute(<<-SQL, @title, @body, @user_id) # INSERT INTO # questions (title, body, user_id) # VALUES # (?, ?, ?); # SQL # @id = QuestionDBConnection.instance.last_insert_row_id # end # # def update # raise "#{self} does not exist in database" unless @id # QuestionDBConnection.instance.execute(<<-SQL, @title, @body, @user_id, @id) # UPDATE # questions # SET # title = ?, body = ?, user_id = ? # WHERE # id = ?; # SQL # end # # def author # User.find_by_id(self.user_id) # end # # def replies # Reply.find_by_question_id(self.id) # end # end # class User # # def self.all # data = QuestionDBConnection.instance.execute("SELECT * FROM users") # data.map {|datum| User.new(datum)} # end # # def self.find_by_id(id) # data = QuestionDBConnection.instance.execute("SELECT * FROM users WHERE users.id = '#{id}'") # User.new(data.first) # end # # def self.find_by_name(fname,lname) # data = QuestionDBConnection.instance.execute("SELECT * FROM users WHERE users.fname = '#{fname}' AND users.lname = '#{lname}'") # data.map {|datum| User.new(datum)} # end # # attr_accessor :fname, :lname # attr_reader :id # # def initialize(options) # @id = options['id'] # @fname = options['fname'] # @lname = options['lname'] # end # # def create # raise "#{self} already exists in database" if @id # QuestionDBConnection.instance.execute(<<-SQL, @fname, @lname) # INSERT INTO # users (fname, lname) # VALUES # (?, ?); # SQL # @id = QuestionDBConnection.instance.last_insert_row_id # end # # def update # raise "#{self} does not exist in database" unless @id # QuestionDBConnection.instance.execute(<<-SQL, @fname, @lname, @id) # UPDATE # users # SET # fname = ?, lname = ? # WHERE # id = ?; # SQL # end # # def authored_questions # Question.find_by_author_id(self.id) # end # # def authored_replies # Reply.find_by_user_id(self.id) # end # # end # class QuestionFollow # # def self.all # data = QuestionDBConnection.instance.execute("SELECT * FROM question_follows") # data.map {|datum| QuestionFollow.new(datum)} # end # # def self.find_by_id(id) # data = QuestionDBConnection.instance.execute("SELECT * FROM question_follows WHERE question_follows.id = '#{id}'") # QuestionFollow.new(data.first) # end # # def self.followers_for_question_id(id) # data = QuestionDBConnection.instance.execute(<<-SQL, id) # SELECT # users.id, users.fname, users.lname # FROM # users # JOIN # question_follows ON users.id = question_follows.user_id # WHERE # question_follows.question_id = ?; # SQL # data.map { |datum| User.new(datum) } # end # # attr_accessor :user_id, :question_id # attr_reader :id # # def initialize(options) # @id = options['id'] # @user_id = options['user_id'] # @question_id = options['question_id'] # end # # def create # raise "#{self} already exists in database" if @id # QuestionDBConnection.instance.execute(<<-SQL, @user_id, @question_id) # INSERT INTO # question_follows (user_id, question_id) # VALUES # (?, ?); # SQL # @id = QuestionDBConnection.instance.last_insert_row_id # end # # def update # raise "#{self} does not exist in database" unless @id # QuestionDBConnection.instance.execute(<<-SQL, @user_id, @question_id, @id) # UPDATE # question_follows # SET # user_id = ?, question_id = ? # WHERE # id = ?; # SQL # end # end # class Reply # # def self.all # data = QuestionDBConnection.instance.execute("SELECT * FROM replies") # data.map {|datum| Reply.new(datum)} # end # # def self.find_by_id(id) # data = QuestionDBConnection.instance.execute("SELECT * FROM replies WHERE replies.id = '#{id}'") # Reply.new(data.first) # end # # def self.find_by_user_id(id) # data = QuestionDBConnection.instance.execute("SELECT * FROM replies WHERE replies.user_id = '#{id}'") # data.map {|datum| Reply.new(datum)} # end # # def self.find_by_question_id(id) # data = QuestionDBConnection.instance.execute("SELECT * FROM replies WHERE replies.question_id = '#{id}'") # data.map {|datum| Reply.new(datum)} # end # # # attr_accessor :body, :user_id, :question_id, :parent_id # attr_reader :id # # def initialize(options) # @id = options['id'] # @body = options['body'] # @user_id = options['user_id'] # @question_id = options['question_id'] # @parent_id = options['parent_id'] # end # # def create # raise "#{self} already exists in database" if @id # QuestionDBConnection.instance.execute(<<-SQL, @body, @user_id, @question_id, @parent_id) # INSERT INTO # replies (body, user_id, question_id, parent_id) # VALUES # (?, ?, ?, ?); # SQL # @id = QuestionDBConnection.instance.last_insert_row_id # end # # def update # raise "#{self} does not exist in database" unless @id # QuestionDBConnection.instance.execute(<<-SQL, @body, @user_id, @question_id, @parent_id, @id) # UPDATE # replies # SET # body = ?, user_id = ?, question_id = ?, parent_id = ? # WHERE # id = ?; # SQL # end # # def author # User.find_by_id(self.user_id) # end # # def question # Question.find_by_id(self.question_id) # end # # def parent_reply # Reply.find_by_id(self.parent_id) # end # # def child_replies # QuestionDBConnection.instance.execute("SELECT * FROM replies WHERE replies.parent_id = '#{self.id}'") # end # end # class QuestionLike # # def self.all # data = QuestionDBConnection.instance.execute("SELECT * FROM question_likes") # data.map {|datum| QuestionLike.new(datum)} # end # # def self.find_by_id(id) # data = QuestionDBConnection.instance.execute("SELECT * FROM question_likes WHERE question_likes.id = '#{id}'") # QuestionLike.new(data.first) # end # # attr_accessor :user_id, :question_id # attr_reader :id # # def initialize(options) # @id = options['id'] # @user_id = options['user_id'] # @question_id = options['question_id'] # end # # def create # raise "#{self} already exists in database" if @id # QuestionDBConnection.instance.execute(<<-SQL, @user_id, @question_id) # INSERT INTO # question_likes (user_id, question_id) # VALUES # (?, ?); # SQL # @id = QuestionDBConnection.instance.last_insert_row_id # end # # def update # raise "#{self} does not exist in database" unless @id # QuestionDBConnection.instance.execute(<<-SQL, @user_id, @question_id, @id) # UPDATE # question_likes # SET # user_id = ?, question_id = ? # WHERE # id = ?; # SQL # end # end
# Modelo Texto # Tabla textos # Campos id:integer # texto:string # created_at:datetime # updated_at:datetime class Texto < ActiveRecord::Base has_many :textos_favoritos, class_name: 'TextoFavorito', inverse_of: :texto, dependent: :destroy validates :texto, presence: true end
raise "I can't handle this platform: #{RUBY_PLATFORM}" unless RUBY_PLATFORM =~ /darwin/ module Memetic class Environment def initialize @binary_path = [] @library_path = [] @variables = {} end def add_binary_path(path) @binary_path << path end def add_library_path(path) @library_path << path end def set_variable(name, value) @variables[name] = value end def as_command_prefix prefix = "" if (!@binary_path.empty?) prefix << "export PATH='" @binary_path.each do |p| prefix << p << ':' end prefix << "/usr/bin:/usr/sbin:/bin:/sbin'; " end if (!@library_path.empty?) prefix << "export DYLD_LIBRARY_PATH='" @library_path.each do |p| prefix << p << ':' end prefix.chop! prefix << "'; " end if (!@variables.empty?) @variables.each do |k,v| prefix << "export #{k}='#{v}'; " end end return prefix end end end
class CreateActivities < ActiveRecord::Migration[6.0] def change create_table :activities, id: :uuid do |t| t.string :identifier, unique: true t.string :sector t.string :title t.text :description t.string :status t.date :planned_start_date t.date :planned_end_date t.date :actual_start_date t.date :actual_end_date t.string :recipient_region t.string :flow t.string :finance t.string :aid_type t.string :tied_status t.references :fund, type: :uuid t.timestamps end end end
require 'pry' module Memorable def reset_all self.all.clear end def count self.all.count end def find_by_name(name) self.all.detect {|artist| artist.name == name} end end
class AboutContentsController < ApplicationController before_action :set_about_content, only: [:show, :edit, :update, :destroy] before_action :authenticate_user!, :authorize_record, :injectable_meta#from application_controller # GET /about_contents/1 # GET /about_contents/1.json def show end # GET /about_contents/1/edit def edit end # PATCH/PUT /about_contents/1 # PATCH/PUT /about_contents/1.json def update respond_to do |format| if @about_content.update(about_content_params) format.html { redirect_to @about_content, notice: 'About content was successfully updated.' } format.json { render :show, status: :ok, location: @about_content } else format.html { render :edit } format.json { render json: @about_content.errors, status: :unprocessable_entity } end end end # DELETE /about_contents/1 # DELETE /about_contents/1.json def destroy @about_content.destroy respond_to do |format| format.html { redirect_to about_contents_url, notice: 'About content was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_about_content @about_content = AboutContent.find(params[:id]) end def authorize_record authorize @about_content end # Never trust parameters from the scary internet, only allow the white list through. def about_content_params params.require(:about_content).permit(:user_id, :founder, :founded, :about_us, :background_story, :team, :message_from_founder, :other_info, :is_complete) end end
# == Schema Information # # Table name: weekly_internals # # id :integer not null, primary key # intro :text # lang :string # locale_only :boolean default(FALSE) # created_at :datetime not null # updated_at :datetime not null # weekly_id :integer # class WeeklyInternal < ApplicationRecord belongs_to :weekly end
class RichMediaLink attr_accessor :link, :view_context, :render_image def initialize(link, view_context, options={}) @link = link @view_context = view_context @render_image = options.fetch(:render_image, true) @image = options.fetch(:image, false) end def og_attributes { title: title, url: link, description: description, image: image, favicon: favicon, base_url: base_url, render_image: render_image } end def base_url uri = URI.parse(link) uri.host end def favicon "https://www.google.com/s2/favicons?domain=#{link}" end def title link_cache.update_attribute(:title, og_title) if link_cache.title.nil? link_cache.title end def description link_cache.update_attribute(:description, og_description) if link_cache.description.nil? view_context.truncate(link_cache.description, separator: ' ', length: 248) end def image link_cache.update_attribute(:image_url, og_image) if link_cache.image_url.nil? link_cache.image_url end def og @og ||= OpenGraph.new(link) end def render view_context.render partial: "shared/rich_media_link", locals: og_attributes end private def link_cache @link_cache ||= LinkCache.find_or_create_by(link: link) end def og_image og.images[-1] || '' end def og_description og.description || '' end def og_title og.title || '' end end
class Cat < Animal # attr_reader :name # attr_accessor :mood include Mammal def initialize(name, number_of_lives = 9) @number_of_lives = number_of_lives super(name) puts "I'm a cat" @mood = 'apathetic' end def self.twenty_three_and_me self.ancestors end # def self.ancestors # puts 'what?' # end end
class MoneyChecksController < ApplicationController before_action :set_money_check, only: [:show, :edit, :update, :destroy] # GET /money_checks # GET /money_checks.json def index @money_checks = MoneyCheck.all end # GET /money_checks/1 # GET /money_checks/1.json def show end # GET /money_checks/new def new @money_check = MoneyCheck.new end # GET /money_checks/1/edit def edit end # POST /money_checks # POST /money_checks.json def create @money_check = MoneyCheck.new(money_check_params) respond_to do |format| if @money_check.save format.html { redirect_to @money_check, notice: 'Money check was successfully created.' } format.json { render :show, status: :created, location: @money_check } else format.html { render :new } format.json { render json: @money_check.errors, status: :unprocessable_entity } end end end # PATCH/PUT /money_checks/1 # PATCH/PUT /money_checks/1.json def update respond_to do |format| if @money_check.update(money_check_params) format.html { redirect_to @money_check, notice: 'Money check was successfully updated.' } format.json { render :show, status: :ok, location: @money_check } else format.html { render :edit } format.json { render json: @money_check.errors, status: :unprocessable_entity } end end end # DELETE /money_checks/1 # DELETE /money_checks/1.json def destroy @money_check.destroy respond_to do |format| format.html { redirect_to money_checks_url, notice: 'Money check was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_money_check @money_check = MoneyCheck.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def money_check_params params[:money_check] end end
require 'net/https' require 'uri' module CVE class Crawler DATA_FEED_DEFAULT = URI('https://nvd.nist.gov/download/nvd-rss.xml') DATA_FEED_ANALYZED = URI('https://nvd.nist.gov/download/nvd-rss-analyzed.xml') def initialize(type, verify_cert, user_agent) @crawl_url = type.downcase == 'analyzed' ? DATA_FEED_ANALYZED : DATA_FEED_DEFAULT @verify_cert = verify_cert ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE @user_agent = user_agent end attr_reader :crawl_url, :verify_cert, :user_agent def crawl http = Net::HTTP.new(@crawl_url.host, @crawl_url.port) http.use_ssl = @crawl_url.scheme == 'https' if http.use_ssl? http.verify_mode = @verify_cert end request = Net::HTTP::Get.new(@crawl_url, {'User-Agent' => @user_agent}) response = http.request(request) response.value # Raise an error if status is not 200 response end def inspect "#<CVE::Crawler url=#{@crawl_url.to_s}>" end end end
class Technik < ActiveRecord::Base attr_accessible :name has_many :klasses, class_name: 'Klasse' end
class Ship attr_reader :name, :ship_length, :health def initialize(name, ship_length) @name = name @ship_length = ship_length @health = ship_length @sunk = false end def sunk? @sunk end def hit @health -= 1 @sunk = true if @health <= 0 end end
require File.expand_path(File.join(File.dirname(__FILE__), *%w[.. .. spec_helper])) describe '/customers/new' do before :each do assigns[:customer] = @customer = Customer.new end def do_render render '/customers/new' end it 'should include a customer creation form' do do_render response.should have_tag('form[id=?]', 'new_customer') end describe 'customer creation form' do it 'should send its contents to the customer create action' do do_render response.should have_tag('form[id=?][action=?]', 'new_customer', customers_path) end it 'should use the POST HTTP method' do do_render response.should have_tag('form[id=?][method=?]', 'new_customer', 'post') end it 'should have a name input' do do_render response.should have_tag('form[id=?]', 'new_customer') do with_tag('input[type=?][name=?]', 'text', 'customer[name]') end end it 'should preserve any existing name' do @customer.name = 'Test Name' do_render response.should have_tag('form[id=?]', 'new_customer') do with_tag('input[type=?][name=?][value=?]', 'text', 'customer[name]', 'Test Name') end end it 'should have a description input' do do_render response.should have_tag('form[id=?]', 'new_customer') do with_tag('textarea[name=?]', 'customer[description]') end end it 'should preserve any existing description' do @customer.description = 'Test Description' do_render response.should have_tag('form[id=?]', 'new_customer') do with_tag('textarea[name=?]', 'customer[description]', :text => /Test Description/) end end describe 'when the customer has parameters' do before :each do @parameters = { 'a' => 'b', 'c' => 'd', 'e' => 'f' } @customer.parameters = @parameters end it 'should have an input for each parameter name' do do_render response.should have_tag('form[id=?]', 'new_customer') do @parameters.each_pair do |key, value| with_tag('input[type=?][name=?][value=?]', 'text', 'customer[parameters][key][]', key) end end end it 'should have an input for each parameter value' do do_render response.should have_tag('form[id=?]', 'new_customer') do @parameters.each_pair do |key, value| with_tag('input[type=?][name=?][value=?]', 'text', 'customer[parameters][value][]', value) end end end it 'should not have a blank input for parameter name' do do_render response.should have_tag('form[id=?]', 'new_customer') do with_tag('input[type=?][name=?]:not(value)', 'text', 'customer[parameters][key][]') end end it 'should not have a blank input for parameter value' do do_render response.should have_tag('form[id=?]', 'new_customer') do with_tag('input[type=?][name=?]:not(value)', 'text', 'customer[parameters][value][]') end end it 'should have a link to delete an existing parameter' do do_render response.should have_tag('form[id=?]', 'new_customer') do with_tag('a[class=?]', 'delete_parameter_link', :count => @customer.parameters.size) end end end it 'should have a link to add a new parameter' do do_render response.should have_tag('form[id=?]', 'new_customer') do with_tag('a[id=?]', 'add_parameter_link') end end it 'should have a submit button' do do_render response.should have_tag('form[id=?]', 'new_customer') do with_tag('input[type=?]', 'submit') end end end end
module Faker class School < Base flexible :school class << self def name parse('school.name') end def suffix; fetch('school.suffix'); end end end end
class Spaces::SearchService PRICE_RANGE_REGEX = /(?<min>\d+),(?<max>\d+)/ def self.attrs @attrs ||= [:classification, :city_id, :ratings, :price_hourly_range, :categories, :amenities, :availabilities] end def self.permitted_params @permitted_params ||= [:classification, :city_id, :price_hourly_range, categories: [], amenities: [], availabilities: [], ratings: []] end attr_accessor *attrs def initialize(opts={}) opts.each do |k, v| if self.class.attrs.include?(k.to_sym) self.send("#{k}=", v) end end end def search(spaces=Space.all) spaces = spaces.where(classification: Space.classifications[classification]) if classification.present? spaces = spaces.where(city_id: city_id) if city_id.present? spaces = filter_by_ratings(spaces, ratings) if ratings.present? && ratings.any? spaces = spaces.where(':min <= price_hourly AND price_hourly <= :max', min: price_hourly_min, max: price_hourly_max) if price_hourly_range.present? spaces = filter_by_categories(spaces, categories) if categories.present? spaces = filter_by_amenities(spaces, amenities) if amenities.present? && amenities.any? spaces = filter_by_availabilities(spaces, availabilities) if availabilities.present? && availabilities.any? spaces end def formatted_price_hourly_range [price_hourly_min, price_hourly_max] if price_hourly_range.present? end private def price_hourly_min @price_hour_min ||= price_hourly_range.match(PRICE_RANGE_REGEX)[:min].to_i end def price_hourly_max @price_hour_max ||= price_hourly_range.match(PRICE_RANGE_REGEX)[:max].to_i end def filter_by_amenities(spaces, amenities) filter_by_boolean_columns(spaces, amenities.map(&:to_sym) & Space.amenities) end def filter_by_availabilities(spaces, availabilities) filter_by_boolean_columns(spaces, availabilities.map(&:to_sym) & Space.days) end def filter_by_boolean_columns(spaces, cols) cols.each do |col| spaces = spaces.where("#{col} = ?", true) end spaces end def filter_by_ratings(spaces, ratings) query = ratings.map { |r| '(spaces.rating >= ? AND spaces.rating < ?)' }.join(' OR ') vars = ratings.map(&:to_i).reduce([]) { |arr, x| arr.push(x, x+1) } spaces.where(query, *vars) end def filter_by_categories(spaces, categories) if categories.reject(&:blank?).any? spaces.joins(:space_categories).where('space_categories.category_id': categories.reject(&:blank?)) else spaces end end end
require_plugin 'tog_core' require_plugin 'seo_urls' require_plugin 'flashplayrhelpr' require_plugin 'paperclip' require "i18n" unless defined?(I18n) Dir[File.dirname(__FILE__) + '/locale/**/*.yml'].each do |file| I18n.load_path << file end Tog::Plugins.settings :tog_podcasts, "channel.cover.max_file_size_kb"=> 1000, #kb "channel.cover.big" => "150x150#", "channel.cover.medium" => "100x100#", "channel.cover.small" => "50x50#", "channel.cover.tiny" => "25x25#", "channel.cover.default_image" => '/tog_podcasts/images/default_cover.jpg', "episodes.max_file_size_kb" => 30000, #kb "allowed_mime_types" => %w( audio/mpeg audio/mpg audio/mp3 audio/mp4 audio/mpeg3 audio/x-mp3 audio/x-mpeg3 ).join(', ') Tog::Plugins.helpers Podcasts::ChannelsHelper Tog::Interface.sections(:site).add "Podcasts", "/podcasts/channels" Tog::Interface.sections(:member).add "Podcasts", "/member/podcasts/channels" Tog::Search.sources << "Channel" Tog::Search.sources << "Episode"
TextifierDemo::Application.routes.draw do resources :adjectives resources :entities resources :terms root :to => "homepage#show" end
require 'csv' class Person attr_accessor :name, :lastname def initialize(name:, lastname:) self.name = name self.lastname = lastname end def to_s "#{name} #{lastname}" end def self.load_csv(file) rows = [] CSV.new(file, headers: true).each do |row| row = row.to_h row = row.each_with_object({}){|(k,v), h| h[k.to_sym] = v} rows << row end rows.map do |row| Person.new(row) end end end
class Project < ActiveRecord::Base has_many :project_requirements, :dependent => :destroy has_many :project_targets, :dependent => :destroy has_many :startups, through: :startups_projects belongs_to :startup validates_presence_of :name, :description, :category validates_length_of :name, :within => 3 .. 150 validates_uniqueness_of :name, :message => "You have a project with the same name" # Cascade deletion to all associations accepts_nested_attributes_for :project_targets, :allow_destroy => true accepts_nested_attributes_for :project_requirements, :allow_destroy => true # Definition: "A startup can launch its project" # Changes the status of a project and redirects to the project's # page (show project) on success or error # update the status of launch project from unlaunch to launched and vice versa. # Input: project_id/Void. # Output: project_id/Void "it's an action" returns the success # of the changeable button of launch upon of it's previous status. # Author: Hana Magdy. def launched? @launch ? "Yes" : "No" end end
# frozen_string_literal: true module Contentful class Importer < ApplicationService def initialize; end def call client ||= ::Contentful::Client.new( space: ENV['CONTENTFUL_SPACE_ID'], access_token: ENV['CONTENTFUL_ACCESS_TOKEN'], dynamic_entries: :auto # Enables Content Type caching. ) client.entries(content_type: 'recipe').each do |entry| import_recipe(entry) end end private # rubocop:disable Metrics/AbcSize def import_recipe(entry) recipe = Recipe.find_or_initialize_by(contentful_id: entry.id) recipe.title = entry.title recipe.image = entry.photo.url recipe.description = entry.description recipe.tag_list.add(entry.tags.map(&:name)) if entry.fields.key?(:tags) recipe.chef = import_chef(entry) recipe.save end # rubocop:enable Metrics/AbcSize def import_chef(entry) return nil unless entry.fields.key?(:chef) chef = Chef.find_or_initialize_by(contentful_id: entry.chef.id) chef.name = entry.chef.name chef.save chef end end end
require 'jumpstart_auth' require 'bitly' class MicroBlogger attr_reader :client def initialize puts 'Initializing MicroBlogger' @client = JumpstartAuth.twitter end def followers_list screen_names = [] @client.followers.each {|f| screen_names << @client.user(f).screen_name} screen_names end def shorten(original_url) puts "Shortening this URL: #{original_url}" Bitly.use_api_version_3 bitly = Bitly.new('hungryacademy', 'R_430e9f62250186d2612cca76eee2dbc6') bitly.shorten(original_url).short_url end def tweet(message) if message.length <= 140 @client.update(message) else puts 'tweet is too long (>140 chars)' end end def dm(target, message) puts "Trying to send #{target} this dm:" puts message message = "d @#{target} #{message}" screen_names = @client.followers.collect {|f| @client.user(f).screen_name} if screen_names.include?(target) tweet(message) else puts 'ERROR!: Can only dm followers' end end def spam_followers(message) followers = followers_list followers.each do |f| dm(f, message) end end def friends_last_tweets friends = @client.friends friends.each do |friend| user = @client.user(friend) print "#{user.screen_name}: #{user.status.text}" puts end end def run puts "welcome to the twitter client" command = '' until command == 'q' printf "enter command: " input = gets.chomp parts = input.split(' ') command = parts[0] case command when 'q' then puts 'Goodbye!' when 't' then tweet(parts[1..-1].join(' ')) when 'dm' then dm(parts[1], parts[2..-1].join(' ')) when 'spam' then spam_followers(parts[1..-1].join ' ') when 'flt' then friends_last_tweets when 's' then puts shorten(parts[1]) when 'turl' then tweet(parts[1..-2].join(' ') + ' ' + shorten(parts[-1])) else puts "Sorry I don't know what '#{command}' means" end end end end blogger = MicroBlogger.new blogger.run
class AdventuresController < ApplicationController def new @adventure = Adventure.new @page = Page.new # respond_to do |f| # f.html # f.json { render :json => {error: 'Cannot access new page, try create'}, status: 404 } # end end def show #binding.pry @adventure = Adventure.find(params[:id]) # respond_to do |f| # f.html # f.json { render :json => @adventue.as_json} # end end def index @library = Library.new @adventures = Adventure.all @myadventures = Adventure.where(library_id: nil) # AdventuresWorker.perform_async(@adventures) respond_to do |f| f.html f.json { render json: {adventures: @myadventures.as_json(include: { pages: { only: [:name, :text] }} )}, status: 200} end end def create new_adventure = params.require(:adventure).permit(:title, :author) new_adventure[:guid] = SecureRandom.urlsafe_base64(10) @adventure = Adventure.create(new_adventure) end end
require 'sass' require 'base64' module SassBase64 def sassBase64(string) assert_type string, :String Sass::Script::String.new(Base64.strict_encode64(string.value)) end declare :sassBase64, :args => [:string] end module Sass::Script::Functions include SassBase64 end
class PickupsController < ApplicationController # GET /pickups # GET /pickups.xml def index @pickups = Pickup.order('created_at DESC') @pickups = @pickups.paginate(:page => params[:page], :per_page => 20) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @pickups } end end # GET /pickups/1 # GET /pickups/1.xml def show @pickups = Pickup.order('created_at DESC') @pickups = @pickups.paginate(:page => params[:page], :per_page => 20) @pickup = Pickup.find(params[:id]) @picture_first = Picture.find(@pickup.picture.to_i) @detail = @picture_first.details.last respond_to do |format| format.html # show.html.erb format.xml { render :xml => @pickup } end end # GET /pickups/new # GET /pickups/new.xml def new @pickup = Pickup.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @pickup } end end # GET /pickups/1/edit def edit @pickup = Pickup.find(params[:id]) end # POST /pickups # POST /pickups.xml def create @pickup = Pickup.new(params[:pickup]) respond_to do |format| if @pickup.save format.html { redirect_to(@pickup, :notice => 'Pickup was successfully created.') } format.xml { render :xml => @pickup, :status => :created, :location => @pickup } else format.html { render :action => "new" } format.xml { render :xml => @pickup.errors, :status => :unprocessable_entity } end end end # PUT /pickups/1 # PUT /pickups/1.xml def update @pickup = Pickup.find(params[:id]) respond_to do |format| if @pickup.update_attributes(params[:pickup]) format.html { redirect_to(@pickup, :notice => 'Pickup was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @pickup.errors, :status => :unprocessable_entity } end end end # DELETE /pickups/1 # DELETE /pickups/1.xml def destroy @pickup = Pickup.find(params[:id]) @pickup.destroy respond_to do |format| format.html { redirect_to(pickups_url) } format.xml { head :ok } end end end
class CreateInvestmentEntries < ActiveRecord::Migration def change create_table :investment_entries do |t| t.string :coin_name t.string :community t.string :code t.string :whitepaper t.integer :user_id t.datetime :date end end end
module Coercell module Value def self.coerce(model,attribute_name,value) attribute_type = (model.columns.select { |a| a.name == attribute_name }).first.type value = case attribute_type when :integer value.to_i if value.is_a? Numeric else value end value end end end
require 'pry' class String # self refers to the string being passed into method since a string is the object for that String class def sentence? return true if self.end_with?(".") return false end def question? return true if self.end_with?("?") return false end def exclamation? return true if self.end_with?("!") return false end def count_sentences # split using regex after ".", "?", or "!" followed by space a = self.split(/[.!?]\s/) a.count end end
require 'rails_helper' RSpec.describe Contact, type: :model do let(:title) { FFaker::BaconIpsum.phrase } let(:url) { FFaker::Internet.http_url } let(:intervention) { Fabricate(:intervention) } let(:contact) { Fabricate(:contact, title: title, url: url, intervention: intervention) } it 'creates a contact' do expect(contact.title).to eq(title) expect(contact.url).to eq(url) expect(contact.intervention).to eq(intervention) end end
module Admin::RemoteTasksHelper def status_label(task) case task.status when 'creating', 'created' 'label label-default' when 'pending' 'label label-warning' when 'running' 'label label-primary' when 'cleaning' 'label label-info' when 'succeeded', 'finished' 'label label-success' when 'cancelled', 'failed' 'label label-danger' end end end
# # Copyright (c) 2014 Webhippie <http://www.webhippie.de> # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # require "sshkey" require "active_support/concern" require "dockit/helper" require "dockit/base" require_relative "acl/version" require_relative "acl/command" module Dockit module Plugin module Acl module RegisterCommand extend ActiveSupport::Concern included do desc "Manipulate access control" command :acl do |o| o.desc "Create a new SSH key entry" o.arg :sshkey, :optional o.command :create do |c| c.action do |global, opts, args| sshkey = if args.empty? $stdin.read else args.shift end Command.new(global, opts).create(sshkey) end end o.desc "Remove an SSH key entry" o.arg :sshkey, :optional o.command :remove do |c| c.action do |global, opts, args| sshkey = if args.empty? $stdin.read else args.shift end Command.new(global, opts).remove(sshkey) end end o.desc "List all added SSH keys" o.command :list do |c| c.action do |global, opts, _args| Command.new(global, opts).list end end end end end module RegisterHook extend ActiveSupport::Concern included do end end end end end
#Warm up def range(start, endpt) #returns an array of all numbers from start to end excluding end #returns an empty array if end < start rarr = [] return rarr if endpt <= start rarr << start rarr += range(start+1,endpt) end # p range(1,10) #Sum an array recursive def re_sum(arr) return arr[0] if arr.length <=1 arr[0] + re_sum(arr[1..-1]) end # Examples re_sum # a = [] # p re_sum(a) # b = [1] # p re_sum(b) # c = [4,5,6] # p re_sum(c) # Sum an array iterative def it_sum(arr) arr.inject {|sum, n| sum+n} end # Examples it_sum # p it_sum([]) # p it_sum([1]) # p it_sum([4,5,6]) #Exponentiation def exp_1(b,n) return 1 if n == 0 b * exp_1(b,n-1) end # Examples exp_1 # p exp_1(0,1) # p exp_1(1,0) # p exp_1(2, 256) def exp_2(b,n) return 1 if n == 0 if n.even? m = n/2 return exp_2(b,m) * exp_2(b,m) else m = (n-1)/2 return b * exp_2(b,m) * exp_2(b,m) end end # Examples exp_2 # p exp_2(0,1) # p exp_2(1,0) # p exp_2(2,256) # p exp_2(3,4) def deep_dup(arr) dup = [] arr.each do |ele| if ele.is_a?(Array) dup << deep_dup(ele) else dup << ele end end dup end # Examples deep_dup # p deep_dup([1,['a'], [2], [3, [4]]]) def re_fib(n) return [0,1].take(n) if n <= 2 previous = re_fib(n-1) last = (previous[-1] + previous[-2]) previous << last end # p re_fib(18) def it_fib(n) return [0] if n == 0 return [0,1] if n == 1 fib_array = [0,1] i = 2 until i == n next_fib = fib_array[-1] + fib_array[-2] fib_array << next_fib i+=1 end fib_array end # Examples it_fib # p it_fib(18) def bsearch(array, target) return nil if array.empty? # if target isn't found mid = (array.length/2) lower = array[0...mid] upper = array[mid+1..-1] if target == array[mid] return mid elsif target < array[mid] bsearch(lower,target) else subsearch = bsearch(upper,target) if subsearch == nil return nil else return bsearch(upper,target) + (mid+1) end end end # p bsearch([1, 2, 3], 1) # => 0 # p bsearch([2, 3, 4, 5], 3) # => 1 # p bsearch([2, 4, 6, 8, 10], 6) # => 2 p bsearch([1, 3, 4, 5, 9], 5) # => 3 # p bsearch([1, 2, 3, 4, 5, 6], 6) # => 5 # p bsearch([1, 2, 3, 4, 5, 6], 0) # => nil # p bsearch([1, 2, 3, 4, 5, 7], 6) # => nil # p 1/2
require File.dirname(__FILE__) + '/../test_helper' require 'entries_controller' # Re-raise errors caught by the controller. class EntriesController; def rescue_action(e) raise e end; end class EntriesControllerTest < Test::Unit::TestCase fixtures :entries def setup @controller = EntriesController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new end def test_should_get_index get :index assert_response :success assert assigns(:entries) end def test_should_get_new get :new assert_response :success end def test_should_create_entry old_count = Entry.count post :create, :entry => { } assert_equal old_count+1, Entry.count assert_redirected_to entry_path(assigns(:entry)) end def test_should_show_entry get :show, :id => 1 assert_response :success end def test_should_get_edit get :edit, :id => 1 assert_response :success end def test_should_update_entry put :update, :id => 1, :entry => { } assert_redirected_to entry_path(assigns(:entry)) end def test_should_destroy_entry old_count = Entry.count delete :destroy, :id => 1 assert_equal old_count-1, Entry.count assert_redirected_to entries_path end end
# coding: utf-8 class Requirement < ActiveRecord::Base KINDS = %w[Udfald Funktion Finish Holdbarhed Miljø] belongs_to :work_process end
Copyright (c) 2014 Francesco Balestrieri Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. require 'singleton' require 'yaml' require 'jira4r' module Modules class JiraHelper include Singleton attr_reader :resolve_on_merge attr_reader :opened_pr_template attr_reader :closed_pr_template def initialize @jira_config = YAML.load(File.new "config/config.yml", 'r') @jira_projects = @jira_config['projects'] @resolve_on_merge = @jira_config['resolve_on_merge'] @jira_connection = Jira4R::JiraTool.new(2, @jira_config['address']) @opened_pr_template = @jira_config['comment_template_pr_opened'] @closed_pr_template = @jira_config['comment_template_pr_closed'] @regexp = Regexp.new(@jira_config['find_issue_regexp_template'] % { projects: @jira_projects.join('|') }, Regexp::IGNORECASE) # Optional SSL parameters if @jira_config['ssl_version'] != nil @jira_connection.driver.streamhandler.client.ssl_config.ssl_version = @jira_config['ssl_version'] end if @jira_config['verify_certificate'] == false @jira_connection.driver.options['protocol.http.ssl_config.verify_mode'] = OpenSSL::SSL::VERIFY_NONE end @jira_connection.login @jira_config['username'], @jira_config['password'] end def add_comment(issue_id, body) rc = Jira4R::V2::RemoteComment.new rc.body = body begin @jira_connection.addComment issue_id, rc rescue Rails.logger.error "Failed to add comment to issue #{issue_id}" else Rails.logger.debug "Successfully added comment to issue #{issue_id}" end end def resolve(issue_id) begin available_actions = @jira_connection.getAvailableActions issue_id if !available_actions.nil? resolve_action = available_actions.find {|s| s.name == 'Resolve Issue'} end if !resolve_action.nil? @jira_connection.progressWorkflowAction issue_id, resolve_action.id.to_s, [] else Rails.logger.debug "Not allowed to resolve issue #{issue_id}. Allowable actions: "\ "#{(available_actions.map {|s| s.name}).to_s}" end rescue StandardError => e Rails.logger.error "Failed to resolve issue #{issue_id} : #{e.to_s}" else Rails.logger.debug "Successfully resolved issue #{issue_id}" end end def scan_issues(body) body.scan @regexp do |match| yield !match[0].nil?, match[2] + '-' + match[3] end end end end
class CreateDownVotes < ActiveRecord::Migration def change create_table :down_votes do |t| t.references :like_a_little t.references :student t.timestamps end add_index :down_votes, [:like_a_little_id, :student_id], unique: true end end
# This migration comes from atomic_lti (originally 20220428175305) class CreateAtomicLtiDeployments < ActiveRecord::Migration[6.1] def change create_table :atomic_lti_deployments do |t| t.string :deployment_id, null: false t.string :client_id, null: false t.string :platform_guid t.string :iss, null: false t.timestamps end add_index :atomic_lti_deployments, [:deployment_id, :iss], unique: true, name: "index_atomic_lti_deployments_d_id_iss" end end
module Wechat::BaseHelper def full_url url "#{ENV['WESELL_SERVER']}#{url}" end end
json.array!(@hairsummaries) do |hairsummary| json.extract! hairsummary, :id json.url hairsummary_url(hairsummary, format: :json) end
require 'rails_helper' RSpec.describe CommentsController, type: :controller do let!(:user) { create(:user) } before { @request.env['devise.mapping'] = Devise.mappings[:user] } before { sign_in user } describe '#index' do def do_request get :index end let!(:comment_parent) { create(:comment, parent_id: nil) } it 'show comment parent' do do_request expect(assigns(:comment_parent).count).to eq 1 end end describe '#create' do def do_request xhr :post, 'create', comment: comment.attributes end let(:comment) { build(:comment) } it 'save a comment' do expect{ do_request }.to change(Comment, :count).by(1) end end end
class CardsController < AuthenticatedUserController onboard :owner_cards, :companion_cards, with: [:survey, :save_survey] def index # Unfortunately I can't figure out a better way of avoiding all the N+1 issues # without reloading the current account, since you can't call `includes` # after the account has already been loaded. account = Account.includes( people: [:account, { card_accounts: :card_product }, actionable_card_recommendations: [:card_product, { offer: { card_product: :currency } }],], ).find(current_account.id) if account.actionable_card_recommendations? cookies[:recommendation_timeout] = { value: "timeout", expires: 24.hours.from_now } end unless current_admin account.card_recommendations.unseen.update_all(seen_at: Time.zone.now) end render cell(Card::Cell::Index, account) end def survey @person = load_person redirect_if_onboarding_wrong_person_type! && return redirect_if_onboarding_wrong_person_type! && true form = Card::Survey.new(@person) render cell(Card::Cell::Survey, @person, form: form) end def save_survey @person = load_person redirect_if_onboarding_wrong_person_type! && return form = Card::Survey.new(@person) if form.validate(survey_params) # There's currently no way that survey_params can be invalid form.save redirect_to onboarding_survey_path else raise 'this should never happen!' end end private def load_person current_account.people.find(params[:person_id]) end def survey_params # key will be nil if they clicked 'I don't have any cards' result = params[:cards_survey] || { cards: [] } # couldn't figure out how to filter out unopened cards from within the form # object, so I'm doing it at the controller level result[:cards].select! { |c| Types::Form::Bool.(c[:opened]) } result end end
require_relative "../require/macfuse" class Mp3fsMac < Formula desc "Read-only FUSE file system: transcodes audio formats to MP3" homepage "https://khenriks.github.io/mp3fs/" url "https://github.com/khenriks/mp3fs/releases/download/v1.1.1/mp3fs-1.1.1.tar.gz" sha256 "942b588fb623ea58ce8cac8844e6ff2829ad4bc9b4c163bba58e3fa9ebc15608" license "GPL-3.0-or-later" bottle do root_url "https://github.com/gromgit/homebrew-fuse/releases/download/mp3fs-mac-1.1.1" sha256 cellar: :any, big_sur: "f5d8b429073bd633bb0e3bfdf0fa5d72170e3e2c50ea35498169203c3aeb7b5a" sha256 cellar: :any, catalina: "87445edbdfdec0ee366b5bbfb57349b4b7fc380fda83fe0c866049055ecfcda7" sha256 cellar: :any, mojave: "64aeb9e00ab95135f27a62319c607ee47ecbaf24459e27289da40ff8c70366a2" end depends_on "pkg-config" => :build depends_on "flac" depends_on "lame" depends_on "libid3tag" depends_on "libvorbis" depends_on MacfuseRequirement depends_on :macos patch :DATA def install setup_fuse system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end test do assert_match "mp3fs version: #{version}", shell_output("#{bin}/mp3fs -V") end end __END__ diff --git a/src/mp3fs.cc b/src/mp3fs.cc index f846da9..f215f10 100644 --- a/src/mp3fs.cc +++ b/src/mp3fs.cc @@ -28,9 +28,6 @@ #include <fuse.h> #include <fuse_common.h> #include <fuse_opt.h> -#ifdef __APPLE__ -#include <fuse_darwin.h> -#endif #include <cstddef> #include <cstdlib> @@ -166,9 +163,6 @@ void print_versions(std::ostream&& out) { print_codec_versions(out); out << "FUSE library version: " << FUSE_MAJOR_VERSION << "." << FUSE_MINOR_VERSION << std::endl; -#ifdef __APPLE__ - out << "OS X FUSE version: " << osxfuse_version() << std::endl; -#endif } int mp3fs_opt_proc(void* /*unused*/, const char* arg, int key,
class ProjectsController < ApplicationController rescue_from ActiveRecord::RecordNotFound, with: :record_not_found def index if tool = project_params[:tool] projects = Tool.find_by(name: tool).projects else projects = Project.all end if type = project_params[:type] projects = projects.where(type: Type.find_by(name: type)) end if order = project_params[:order] if order == "awesomeness" projects = projects.order(rank: :asc) elsif order == "random" projects = projects.shuffle else projects = projects.order(date: order) end else projects = projects.order(date: :desc) end render :json => projects end def show project = Project.find(project_params[:id]) project_json = project.as_json project_json[:type] = project.type.name.capitalize project_json[:tools] = project.tools.map(&:name).join(", ") render :json => project_json end private def project_params params.permit(:type, :tool, :order, :id) end def record_not_found render plain: "404 Not Found", status: 404 end end
# se accede a la informacion sin necesidad de la posición. # se accede a través del objeto directamente. Formado por CLAVE y VALOR # se define con { } # tutor = {"nombre" => "Maria", "edad" => 34, 20 => "veinte", [] => "arreglo" } # puts tutor["nombre"] # muestro solo el que busco en concreto # tutor["cursos"] = 10 # para añadir clave y valor # #puedo definir un valor por default para las posiciones en las que no hay nada # tutor.default = ";)" # puts tutor [[]] #me imprime el último elemento cuya clave la he definido como [] # puts tutor #muestra todo el hash # puts tutor [6] # definimos símbolos con : (es como otro tipo de elemento) tutor = {:nombre => "Maria", :edad => 34, :cursos => 10} # este es mas adecuado tutor = {nombre: "Maria", edad: 34, cursos: 10} puts tutor [:nombre] #se puede iterar con each (pero usaremos CLAVE y VALOR) tutor.each do |clave, valor| puts "En #{clave} está guardado #{valor}" end
# -*- encoding: utf-8 -*- require "test/unit" require "unicode_utils/nfd" require "unicode_utils/nfc" # See data/NormalizationTest.txt class TestNormalization < Test::Unit::TestCase class Record def initialize(ary) @ary = ary end def c1 @ary[0] end def c2 @ary[1] end def c3 @ary[2] end def c4 @ary[3] end def c5 @ary[4] end end def each_testdata_record fn = File.join(File.dirname(__FILE__), "..", "data", "NormalizationTest.txt") File.open(fn, "r:utf-8:-") do |input| input.each_line { |line| if line =~ /^([^#]*)#/ line = $1 end line.strip! next if line.empty? || line =~ /^@Part/ columns = line.split(";") ary = columns.map { |column| String.new.force_encoding(Encoding::UTF_8).tap do |str| column.split(" ").each { |c| str << c.strip.to_i(16) } end } yield Record.new(ary) } end end def test_nfd each_testdata_record { |r| assert_equal r.c3, UnicodeUtils.nfd(r.c1) assert_equal r.c3, UnicodeUtils.nfd(r.c2) assert_equal r.c3, UnicodeUtils.nfd(r.c3) assert_equal r.c5, UnicodeUtils.nfd(r.c4) assert_equal r.c5, UnicodeUtils.nfd(r.c5) } end def test_nfc each_testdata_record { |r| assert_equal r.c2, UnicodeUtils.nfc(r.c1) assert_equal r.c2, UnicodeUtils.nfc(r.c2) assert_equal r.c2, UnicodeUtils.nfc(r.c3) assert_equal r.c4, UnicodeUtils.nfc(r.c4) assert_equal r.c4, UnicodeUtils.nfc(r.c5) } end def test_nfkd each_testdata_record { |r| assert_equal r.c5, UnicodeUtils.nfkd(r.c1) assert_equal r.c5, UnicodeUtils.nfkd(r.c2) assert_equal r.c5, UnicodeUtils.nfkd(r.c3) assert_equal r.c5, UnicodeUtils.nfkd(r.c4) assert_equal r.c5, UnicodeUtils.nfkd(r.c5) } end def test_nfkc each_testdata_record { |r| assert_equal r.c4, UnicodeUtils.nfkc(r.c1) assert_equal r.c4, UnicodeUtils.nfkc(r.c2) assert_equal r.c4, UnicodeUtils.nfkc(r.c3) assert_equal r.c4, UnicodeUtils.nfkc(r.c4) assert_equal r.c4, UnicodeUtils.nfkc(r.c5) } end end
# module ActsAsTaggable # extend ActiveSupport::Concern # included do # has_many :taggings, as: :taggable, class_name: 'Tagging' # has_many :tags, through: :taggings, class_name: 'Tag' # end # end # module ActsAsTaggable # def self.included(base) # base.extend(ClassMethods) # end # module ClassMethods # has_many :taggings, as: :taggable, class_name: 'Tagging' # has_many :tags, through: :taggings, class_name: 'Tag' # def acts_as_taggable # self.send :include, ActsAsTaggable::InstanceMethods # end # end # module InstanceMethods # end # end # ActiveRecord::Base.send(:include, ActsAsTaggable)
class LivechatController < ApplicationController def chat @title = "Live Chat" end end
require 'formula' class Chicken < Formula homepage 'http://www.call-cc.org/' url 'http://code.call-cc.org/releases/4.9.0/chicken-4.9.0.1.tar.gz' sha1 'd6ec6eb51c6d69e006cc72939b34855013b8535a' head 'git://code.call-cc.org/chicken-core' bottle do revision 1 sha1 "336ed80fce3e2e2d548ad966b4a60d249523592d" => :mavericks sha1 "8a8b278480ab05e46452f61e64e4939cb5d12d3d" => :mountain_lion sha1 "e2a9863f311099590265704fe410f39de802c600" => :lion end def install ENV.deparallelize args = %W[ PLATFORM=macosx PREFIX=#{prefix} C_COMPILER=#{ENV.cc} LIBRARIAN=ar POSTINSTALL_PROGRAM=install_name_tool ] system "make", *args system "make", "install", *args end test do assert_equal "25", shell_output("#{bin}/csi -e '(print (* 5 5))'").strip end end
require 'typhoeus' module Typhoid class Request < TyphoeusDecorator decorate ::Typhoeus::Request ACCESSOR_OPTIONS = [ :method, :params, :body, :headers, :cache_key_basis, :connect_timeout, :timeout, :user_agent, :response, :cache_timeout, :follow_location, :max_redirects, :proxy, :proxy_username, :proxy_password, :disable_ssl_peer_verification, :disable_ssl_host_verification, :interface, :ssl_cert, :ssl_cert_type, :ssl_key, :ssl_key_type, :ssl_key_password, :ssl_cacert, :ssl_capath, :ssl_version, :verbose, :username, :password, :auth_method, :proxy_auth_method, :proxy_type ] def run if Typhoid.typhoeus.major_version == 0 if Typhoid.typhoeus.minor_version >= 6 response = source.run else response = Typhoeus::Request.send(method, url, options) end end Typhoid::Response.new response end def response compat [:handled_response, :response] end # Need to force override, because Object#method def method options[:method] || :get end def options @options ||= if source.respond_to?(:options) source.options else ACCESSOR_OPTIONS.reduce({}) do |hash, key| hash[key] = source.send(key) if source.respond_to?(key) && source.class.instance_method(key).arity < 1 hash end end end end end
# frozen_string_literal: true require_relative 'application_repo' module Repos class CoinRepo < ApplicationRepo[:coins] commands(:create, update: :by_pk) def count_by_denomination(denomination) coins.where(denomination: denomination).count end def count_processed coins.where(state: 'processed').count end def count_dispensed coins.where(state: 'dispensed').count end def dispensable coins.where { state.not('dispensed') }.to_a end def processing coins.where(state: 'processing').to_a end end end
module PPC module API class Sm class Account < Sm Service = 'account' AccountType = { id: :userId, name: :userName, balance: :balance, cost: :cost, payment: :payment, budget_type: :budgetType, budget: :budget, region: :regionTarget, exclude_ip: :excludeIp, open_domains: :openDomains, reg_domain: :regDomain, offline_time: :budgetOfflineTime, weekly_budget: :weeklyBudget, status: :userStat, } @map = AccountType def self.info( auth ) response = request(auth, Service, 'getAccount', {requestData: ["account_all"]}) process( response, 'accountInfoType' ){ |x|reverse_type(x)[0] } end def self.update(auth, param = {} ) """ update account info @ params : account_info_type @return : account info_type """ # for account service, there is not bulk operation body = { accountInfoType: make_type( param )[0] } response = request(auth, Service, 'updateAccount', body) process( response, 'accountInfoType' ){ |x|reverse_type(x)[0] } end end end end end
# == Schema Information # # Table name: badge_ownerships # # id :integer not null, primary key # user_id :integer # badge_id :integer # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' RSpec.describe BadgeOwnership, type: :model do context 'associations' do it { should belong_to(:user) } it { should belong_to(:badge) } end context 'validations' do it { should validate_presence_of :user } it { should validate_presence_of :badge } end it "has a valid factory" do expect(build(:badge_ownership)).to be_valid end it "creates a notification after create" do user = create(:user) # when the user is created, it will receive a notification expect { create(:badge_ownership, user: user) }.to change(Notification, :count).by(1) end end
FactoryBot.define do factory :item do name {"タケオキクチ 7分袖シャツ"} price {12000} explanation {"7分袖なので、春夏秋で着用できます!"} category_id {1} size {"M"} brand_name {"タケオキクチ"} condition_id {1} delivery_fee_id {1} prefecture_id {1} days_until_shipping_id {1} status_id {1} association :category, factory: :category after(:build) do |item| item.images << build(:image, item: item) end end factory :item_no_image, class: Item do name {"タケオキクチ 7分袖シャツ"} price {12000} explanation {"7分袖なので、春夏秋で着用できます!"} category_id {23} size {"M"} brand_name {"タケオキクチ"} condition_id {1} delivery_fee_id {1} prefecture_id {1} days_until_shipping_id {1} status_id {1} end factory :item_edit, class: Item do name {"タケオキクチ 7分袖シャツ"} price {12000} explanation {"7分袖なので、春夏秋で着用できます!"} category_id {1} size {"M"} brand_name {"タケオキクチ"} condition_id {1} delivery_fee_id {1} prefecture_id {1} days_until_shipping_id {1} status_id {1} association :category, factory: :category after(:build) do |item| item.images << build(:image, item: item) end end factory :item_edit_no_image, class: Item do name {"タケオキクチ 7分袖シャツ"} price {12000} explanation {"7分袖なので、春夏秋で着用できます!"} category_id {1} size {"M"} brand_name {"タケオキクチ"} condition_id {1} delivery_fee_id {1} prefecture_id {1} days_until_shipping_id {1} status_id {1} association :category, factory: :category end end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2019-2021 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo module Crypt module KMS module Local # Local KMS master key document object contains KMS master key parameters. # # @api private class MasterKeyDocument # Creates a master key document object form a parameters hash. # This empty method is to keep a uniform interface for all KMS providers. def initialize(_opts) end # Convert master key document object to a BSON document in libmongocrypt format. # # @return [ BSON::Document ] Local KMS credentials in libmongocrypt format. def to_document BSON::Document.new({ provider: "local" }) end end end end end end
require 'database_helpers' require 'Booking' describe Booking do describe 'booking' do it 'request can be raised' do test_user = create_test_user name = 'Makers BNB' description = 'Lovely space to stay' price = 99 user_id = test_user['user_id'] image = 'duck.jpg' space = Space.create( name: name, description: description, price: price, user_id: user_id, image: 'duck.jpg' ) booking_start_date = "2018-12-12" booking_end_date = "2018-12-13" booking = Booking.create_booking_request(booker_user_id: user_id, space_id: space.space_id, booking_start_date: booking_start_date, booking_end_date: booking_end_date) expect(booking).to be_a Booking expect(booking.booker_user_id).to eq user_id expect(booking.space_id.to_i).to eq space.space_id expect(booking.booking_start_date).to eq booking_start_date expect(booking.booking_end_date).to eq booking_end_date expect(booking.booking_confirmed).to eq "f" end it 'if end date is not specified then it should use the start date' do test_user = create_test_user name = 'Makers BNB' description = 'Lovely space to stay' price = 99 user_id = test_user['user_id'] image = 'duck.jpg' space = Space.create( name: name, description: description, price: price, user_id: user_id, image: image ) booking_start_date = "2018-12-12" booking = Booking.create_booking_request(booker_user_id: user_id, space_id: space.space_id, booking_start_date: booking_start_date) expect(booking.booking_start_date).to eq booking_start_date expect(booking.booking_end_date).to eq booking_start_date end end end
class Climbing < ActiveRecord::Base belongs_to :user belongs_to :gym end
class SearchMain < SitePrism::Page set_url 'https://www.airbnb.com/' #Elements on SearchMain element :where, :id, 'Koan-magic-carpet-koan-search-bar__input' element :searchOptionOne, :id, 'Koan-magic-carpet-koan-search-bar__option-0' element :checkIn, :id, 'checkin_input' element :checkOut, :id, 'checkout_input' element :nextMonth, :xpath, '//*[contains(@aria-label,"next month")]' element :guestsButton, :id, 'lp-guestpicker' element :adultAddButton, :xpath, '//*[contains(@aria-labelledby,"adults")]//*[@aria-label="add"]' element :childAddButton, :xpath, '//*[contains(@aria-labelledby,"children")]//*[@aria-label="add"]' element :infantAddButton, :xpath, '//*[contains(@aria-labelledby,"infants")]//*[@aria-label="add"]' element :saveButton, :id, 'filter-panel-save-button' element :searchButton, :xpath, "//span[contains(text(),'Search')]" $nextMonthClicked = false #Functions for elements on SearchMain def enterLocation(location) where.set location end def clickSearchOptionOne searchOptionOne.click end def enterCheckIn(daysToAddString) #Interacts with the date widget as a user would and selects date which is current date + 'daysToAddString' # daysToAdd = daysToAddString.split[3].to_i #Multiple cases handled for all months currentDay = DateTime.now.strftime("%d").to_i currentMonth = DateTime.now.strftime("%m").to_i currentYear = DateTime.now.strftime("%y").to_i currentMonthDays = (Date.new(currentYear, 12, 31) << (12-currentMonth)).day checkInDay = currentDay + daysToAdd #Leap year's feb if currentMonthDays == 29 && checkInDay > 29 checkInDay= checkInDay - 29 checkIn.click nextMonth.click $nextMonthClicked = true if checkInDay <= 9 page.all(:xpath, "(//table)[2]//td", text: checkInDay)[0].click elsif checkInDay >= 10 find("td", :text => checkInDay).click end #Normal year's feb elsif currentMonthDays == 28 && checkInDay > 28 checkInDay= checkInDay - 28 checkIn.click nextMonth.click loopCount = true if checkInDay <= 9 page.all(:xpath, "(//table)[2]//td", text: checkInDay)[0].click elsif checkInDay >= 10 find("td", :text => checkInDay).click end elsif currentMonthDays == 30 && checkInDay > 30 checkInDay= checkInDay - 30 checkIn.click nextMonth.click $nextMonthClicked = true if checkInDay <= 9 page.all(:xpath, "(//table)[2]//td", text: checkInDay)[0].click elsif checkInDay >= 10 find("td", :text => checkInDay).click end elsif currentMonthDays == 31 && checkInDay > 31 checkInDay= checkInDay - 31 checkIn.click nextMonth.click $nextMonthClicked = true if checkInDay <= 9 page.all(:xpath, "(//table)[2]//td", text: checkInDay)[0].click elsif checkInDay >= 10 find("td", :text => checkInDay).click end elsif checkInDay <= 31 checkIn.click if checkInDay <= 9 page.all(:xpath, "(//table)[2]//td", text: checkInDay)[0].click elsif checkInDay >= 10 find("td", :text => checkInDay).click end end end def enterCheckOut(daysToAddString) #Interacts with the date widget as a user would and selects date which is current date + 'daysToAddString' daysToAdd = daysToAddString.split[3].to_i #Multiple cases handled for all months currentDay = DateTime.now.strftime("%d").to_i currentMonth = DateTime.now.strftime("%m").to_i currentYear = DateTime.now.strftime("%y").to_i currentMonthDays = (Date.new(currentYear, 12, 31) << (12-currentMonth)).day checkOutDay = currentDay + daysToAdd #Leap year's feb if currentMonthDays == 29 && checkOutDay > 29 checkOutDay = checkOutDay - 29 #checkOut.click if ($nextMonthClicked == false) nextMonth.click end if checkOutDay <= 9 page.all("td", :text => checkOutDay)[0].click elsif checkOutDay >= 10 find("td", :text => checkOutDay).click end #Normal year's feb elsif currentMonthDays == 28 && checkOutDay > 28 checkOutDay = checkOutDay - 28 if ($nextMonthClicked == false) nextMonth.click end if checkOutDay <= 9 page.all("td", :text => checkOutDay)[0].click elsif checkOutDay >= 10 find("td", :text => checkOutDay).click end elsif currentMonthDays == 30 && checkOutDay > 30 checkOutDay = checkOutDay - 30 if ($nextMonthClicked == false) nextMonth.click end if checkOutDay <= 9 page.all("td", :text => checkOutDay)[0].click elsif checkOutDay >= 10 find("td", :text => checkOutDay).click end elsif currentMonthDays == 31 && checkOutDay > 31 checkOutDay = checkOutDay - 31 if ($nextMonthClicked == false) nextMonth.click end if checkOutDay <= 9 page.all(:xpath, "(//table)[2]//td", text: checkOutDay)[0].click elsif checkOutDay >= 10 find("td", :text => checkOutDay).click end elsif checkOutDay <= 31 if checkOutDay <= 9 page.all("td", :text => checkOutDay)[0].click elsif checkOutDay >= 10 find("td", :text => checkOutDay).click end end end def addAdults (noOfAdults) #Clicks the '+' for Adults 'noOfAdults' times guestsButton.click adultLoop = noOfAdults.to_i adultLoop.times do adultAddButton.click end saveButton.click end def addChildren (noOfChildren) #Clicks the '+' for Children 'noOfChildren' times guestsButton.click childLoop = noOfChildren.to_i childLoop.times do childAddButton.click end saveButton.click end def addInfants (noOfInfants) #Clicks the '+' for Infants 'noOfInfants' times guestsButton.click infantLoop = noOfInfants.to_i infantLoop.times do infantAddButton.click end saveButton.click end def clickSearch searchButton.click end end
class Localization < ActiveRecord::Base self.table_name = 'locations' include Activable include Sanitizable belongs_to :user, foreign_key: :user_id, touch: true belongs_to :localizable, polymorphic: true, touch: true after_update :check_main_location, if: 'main and main_changed?' validates :long, presence: true validates :lat, presence: true validates_with EndDateValidator scope :main_locations, -> { where( main: true ) } scope :by_date, -> (start_date, end_date) { filter_localizations(start_date, end_date) } def self.filter_localizations(start_date, end_date) if start_date || end_date @first_date = (Time.zone.now - 50.years).beginning_of_day @second_date = (Time.zone.now + 50.years).end_of_day end @query = self if start_date && !end_date @query = @query.where("COALESCE(start_date, '#{@first_date}') >= ? OR COALESCE(end_date, '#{@second_date}') >= ?", start_date.to_time.beginning_of_day, start_date.to_time.beginning_of_day) end if end_date && !start_date @query = @query.where("COALESCE(end_date, '#{@second_date}') <= ? OR COALESCE(start_date, '#{@first_date}') <= ?", end_date.to_time.end_of_day, end_date.to_time.beginning_of_day) end if start_date && end_date @query = @query.where("COALESCE(start_date, '#{@first_date}') BETWEEN ? AND ? OR COALESCE(end_date, '#{@second_date}') BETWEEN ? AND ? OR ? BETWEEN COALESCE(start_date, '#{@first_date}') AND COALESCE(end_date, '#{@second_date}')", start_date.to_time.beginning_of_day, end_date.to_time.end_of_day, start_date.to_time.beginning_of_day, end_date.to_time.end_of_day, start_date.to_time.beginning_of_day) end @query = @query.distinct end private def check_main_location Localization.where.not(id: self.id).where( localizable_id: self.localizable_id, localizable_type: self.localizable_type ).each do |location| unless location.update(main: false) return false end end end end
namespace :localities do namespace :city do desc "Rename city FROM to city TO, moving all associated locations" task :rename do city_from_name = ENV["FROM"] city_to_name = ENV["TO"] if city_from_name.blank? or city_to_name.blank? puts "usage: missing FROM or TO" exit end city_from = City.find_by_name(city_from_name) city_to = City.find_by_name(city_to_name) if city_from.blank? puts "usage: could not find city #{city_from_name}" exit end if city_to.blank? puts "usage: could not find city #{city_to_name}" exit end puts "#{Time.now}: renaming city #{city_from.name} to #{city_to.name}: moving #{city_from.locations_count} locations and #{city_from.neighborhoods_count} neighborhoods" city_from.locations.each do |location| location.city = city_to location.save end city_from.neighborhoods.each do |neighborhood| neighborhood.city = city_co neighborhood.save end # reload city, check counter cache values city_from.reload if city_from.locations_count != 0 or city_from.neighborhoods_count != 0 puts "#{Time.now}: xxx error, city #{city_from.name} locations or neighborhoods count not 0" exit end # remove city city_from.destroy puts "#{Time.now}: completed" end desc "Print all cities in csv format" task :to_csv do City.order_by_state_name.each do |city| puts city.to_csv end end end # city namespace namespace :zip do desc "Print all zips in csv format" task :to_csv do Zip.order_by_state_name.each do |city| puts city.to_csv end end end # zip namespace end
class AddDraftStatDistributions < ActiveRecord::Migration[5.2] def change create_table "draft_stat_distributions", id: :integer, force: :cascade do |t| t.references :defined_stat t.integer "player_type", default: 1 t.string "label" t.string "name" t.float "mean" t.float "max" t.float "min" t.float "median" t.float "range" t.text "distribution" t.text "scaled_distribution" t.datetime "created_at" t.datetime "updated_at" end end end