text
stringlengths
10
2.61M
class ForgotmailsController < ApplicationController before_action :set_forgotmail, only: [:show, :edit, :update, :destroy] before_action :authenticate_user! # GET /forgotmails # GET /forgotmails.json def index @forgotmails = Forgotmail.all end # GET /forgotmails/1 # GET /forgotmails/1.json def show end # GET /forgotmails/new def new @forgotmail = Forgotmail.new end # GET /forgotmails/1/edit def edit end # POST /forgotmails # POST /forgotmails.json def create @user = current_user; @forgotmail = Forgotmail.new(forgotmail_params) Usermailer.welcome_email(@user, @forgotmail.sender, @forgotmail.reciever, @forgotmail.title, @forgotmail.content).deliver_now respond_to do |format| if @forgotmail.save format.html { redirect_to @forgotmail, notice: 'Forgotmail was successfully created.' } format.json { render :show, status: :created, location: @forgotmail } else format.html { render :new } format.json { render json: @forgotmail.errors, status: :unprocessable_entity } end end end # PATCH/PUT /forgotmails/1 # PATCH/PUT /forgotmails/1.json def update respond_to do |format| if @forgotmail.update(forgotmail_params) format.html { redirect_to @forgotmail, notice: 'Forgotmail was successfully updated.' } format.json { render :show, status: :ok, location: @forgotmail } else format.html { render :edit } format.json { render json: @forgotmail.errors, status: :unprocessable_entity } end end end # DELETE /forgotmails/1 # DELETE /forgotmails/1.json def destroy @forgotmail.destroy respond_to do |format| format.html { redirect_to forgotmails_url, notice: 'Forgotmail was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_forgotmail @forgotmail = Forgotmail.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def forgotmail_params params.require(:forgotmail).permit(:sender, :reciever, :title, :content) end end
require 'crates' require 'thor' module Crates class CLI < Thor desc 'get_rates', 'load rates' method_option :base_currency, default: 'USD' method_option :target_currencies, default: 'GBP' method_option :best, type: :boolean, aliases: '-b' method_option :amount method_option :date def send_rates Crates.exchange_rates(options) end end end
class Appointment < ActiveRecord::Base belongs_to :doctor belongs_to :patient attr_accessible :end_time, :start_time, :doctor_id, :patient_id validates :doctor, presence:true validates :patient, presence:true end
class CreateSentimentCaches < ActiveRecord::Migration def change create_table :sentiment_caches do |t| t.timestamp :tweet_when t.decimal :score, precision: 6, scale: 3 t.string :tweet_text t.string :tweet_author t.integer :num_tweets t.references :company, index: {:unique=>true}, foreign_key: true t.timestamps null: false end end end
# -*- mode: ruby -*- # vi: set ft=ruby : # # Automate installation of a Ubuntu VM, with docker+tools and webfact container. # # USAGE: see vagrant.md # See also https://docs.vagrantup.com, # provider-specific configuration for VirtualBox # https://docs.vagrantup.com/v2/virtualbox/configuration.html ######## # The "2" in Vagrant.configure configures the configuration version Vagrant.configure(2) do |config| config.vm.box = "ubuntu/trusty64" # Disable automatic box update checking. # Boxes can be checked for updates with `vagrant box outdated`. config.vm.box_check_update = false # Proxies: if ENV['http_proxy'] and Vagrant.has_plugin?("vagrant-proxyconf") config.proxy.http = ENV.fetch('http_proxy') if ENV['https_proxy'] config.proxy.https = ENV.fetch('https_proxy') end if ENV['no_proxy'] config.proxy.no_proxy = ENV.fetch('no_proxy') end end # Create a forwarded port mapping which allows access to a specific port # within the machine from a port on the host machine. # Forward the Webfactory UI and prepare for 5 website containers: config.vm.network "forwarded_port", guest: 8000, host: 8000 config.vm.network "forwarded_port", guest: 8001, host: 8001 config.vm.network "forwarded_port", guest: 8002, host: 8002 config.vm.network "forwarded_port", guest: 8003, host: 8003 config.vm.network "forwarded_port", guest: 8004, host: 8004 config.vm.network "forwarded_port", guest: 8005, host: 8005 # Option: use a reverse proxy to access websites by name and not by port number # so first, map 8080,8443 in vagrant (for nginx proxy) config.vm.network "forwarded_port", guest: 8080, host: 8080 config.vm.network "forwarded_port", guest: 8443, host: 8443 # Option above: grab the default http port 80/443 # MAC: Vagrant cannot fwd ports below 1024 (unix limitation) # for Mac 10.10, see http://salvatore.garbesi.com/vagrant-port-forwarding-on-mac/ # and https://github.com/emyl/vagrant-triggers # so portmap 80 > 8080, 443->8443 # >> uncomment he ffoling standza for mac 10.10, if you wish to bind to port 80 #if Vagrant.has_plugin?("vagrant-triggers") # config.trigger.after [:provision, :up, :reload] do # system('echo " #rdr pass on lo0 inet proto tcp from any to 127.0.0.1 port 80 -> 127.0.0.1 port 8080 #rdr pass on lo0 inet proto tcp from any to 127.0.0.1 port 443 -> 127.0.0.1 port 8443 #" | sudo pfctl -f - > /dev/null 2>&1; echo "==> Fowarding Ports: host 80 -> host 8080, 443 -> 8443"') # end # # remove port fwd when not needed # config.trigger.after [:halt, :destroy] do # system("sudo pfctl -f /etc/pf.conf > /dev/null 2>&1; echo '==> Removing Port Forwarding'") # end #end # Provider-specific configuration for VirtualBox config.vm.provider "virtualbox" do |vb| # Increase these resources if many containers vb.memory = "2048" #vb.cpus = 2 # do not allow the VM to hog too many resources vb.customize ["modifyvm", :id, "--cpuexecutioncap", "50"] # Setting the hostname can be useful #vb.name = "webfact-vm" end # Run provisioning script config.vm.provision "shell", path: "vagrant.sh" # Create containers config.vm.provision "shell", inline: "cd /vagrant/docker-compose && docker-compose up -d mysql" config.vm.provision "shell", inline: "cd /vagrant/docker-compose && docker-compose up -d webfact" config.vm.provision "shell", inline: "echo 'Connect to the Webfact UI in about 5 minutes http://localhost:8000, or logon with <vagrant ssh> and do <docker logs webfact> to see the progress of the Webfactory installation' " #config.vm.provision "shell", inline: "cd /vagrant/docker-compose && docker-compose up -d nginx nginx-gen" #config.vm.provision "shell", inline: "echo 'To use the nginx reverse proxy, configure DNS as noted in vagrant.md and then connect to http://webfact.docker' " end
require 'wicked_pdf' require 'combine_pdf' require_relative './htmlentities' require_relative './helpers' require_relative './sparql_queries' module DocumentGenerator class DeliveryNote include DocumentGenerator::Helpers def generate(path, data) id = data['id'] path_supplier = "/tmp/#{id}-delivery-note-supplier.pdf" path_customer = "/tmp/#{id}-delivery-note-customer.pdf" language = select_language(data) @inline_css = '' generate_delivery_note(path_supplier, data, language, 'supplier') @inline_css = '' generate_delivery_note(path_customer, data, language, 'customer') merged_pdf = CombinePDF.new merged_pdf << CombinePDF.load(path_supplier) merged_pdf << CombinePDF.load(path_customer) document_title = document_title(data, language) merged_pdf.info[:Title] = document_title # See https://github.com/boazsegev/combine_pdf/issues/150 merged_pdf.save path File.delete(path_supplier) File.delete(path_customer) end def generate_delivery_note(path, data, language, scope) coder = HTMLEntities.new template_path = select_template(data, language) html = File.open(template_path, 'rb') { |file| file.read } own_reference = coder.encode(generate_own_reference(data), :named) html.gsub! '<!-- {{OWN_REFERENCE}} -->', own_reference ext_reference = coder.encode(generate_ext_reference(data), :named) html.gsub! '<!-- {{EXT_REFERENCE}} -->', ext_reference building = coder.encode(generate_building(data), :named) html.gsub! '<!-- {{BUILDING}} -->', building contactlines = coder.encode(generate_contactlines(data), :named) html.gsub! '<!-- {{CONTACTLINES}} -->', contactlines addresslines = coder.encode(generate_addresslines(data), :named) html.gsub! '<!-- {{ADDRESSLINES}} -->', addresslines deliverylines = coder.encode(generate_deliverylines(data, language), :named) html.gsub! '<!-- {{DELIVERYLINES}} -->', deliverylines display_element("scope--#{scope}") html.gsub! '<!-- {{INLINE_CSS}} -->', @inline_css header_path = select_header(data, language) header_html = if header_path then File.open(header_path, 'rb') { |file| file.read } else '' end header_html.gsub! '<!-- {{HEADER_REFERENCE}} -->', generate_header_reference(data) footer_path = select_footer(data, language) footer_html = if footer_path then File.open(footer_path, 'rb') { |file| file.read } else '' end document_title = document_title(data, language) write_to_pdf(path, html, header: { content: header_html }, footer: { content: footer_html }, title: document_title) end def select_header(data, language) if language == 'FRA' ENV['DELIVERY_NOTE_HEADER_TEMPLATE_FR'] || '/templates/leveringsbon-header-fr.html' else ENV['DELIVERY_NOTE_HEADER_TEMPLATE_NL'] || '/templates/leveringsbon-header-nl.html' end end def select_template(data, language) if language == 'FRA' ENV['DELIVERY_NOTE_TEMPLATE_FR'] || '/templates/leveringsbon-fr.html' else ENV['DELIVERY_NOTE_TEMPLATE_NL'] || '/templates/leveringsbon-nl.html' end end def document_title(data, language) reference = generate_header_reference(data) document_type = if language == 'FRA' then 'Bon de livraison' else 'Leveringsbon' end "#{document_type} #{reference}" end def generate_deliverylines(data, language) solutions = fetch_invoicelines(order_id: data['id']) deliverylines = solutions.map do |invoiceline| line = "<div class='deliveryline'>" line += " <div class='col col-1'>#{invoiceline[:description]}</div>" line += "</div>" line end deliverylines.join end def generate_own_reference(data) request = data['offer']['request'] if request own_reference = "<b>AD #{format_request_number(request['id'])}</b>" visit = request['visit'] own_reference += " <b>#{visit['visitor']}</b>" if visit and visit['visitor'] own_reference += "<br><span class='note'>#{data['offerNumber']}</span>" else hide_element('references--own_reference') end end def generate_header_reference(data) request = data['offer']['request'] if request reference = "AD #{format_request_number(request['id'])}" visit = request['visit'] reference += " #{visit['visitor']}" if visit and visit['visitor'] reference else '' end end end end
class FontKanit < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/kanit" desc "Kanit" homepage "https://fonts.google.com/specimen/Kanit" def install (share/"fonts").install "Kanit-Black.ttf" (share/"fonts").install "Kanit-BlackItalic.ttf" (share/"fonts").install "Kanit-Bold.ttf" (share/"fonts").install "Kanit-BoldItalic.ttf" (share/"fonts").install "Kanit-ExtraBold.ttf" (share/"fonts").install "Kanit-ExtraBoldItalic.ttf" (share/"fonts").install "Kanit-ExtraLight.ttf" (share/"fonts").install "Kanit-ExtraLightItalic.ttf" (share/"fonts").install "Kanit-Italic.ttf" (share/"fonts").install "Kanit-Light.ttf" (share/"fonts").install "Kanit-LightItalic.ttf" (share/"fonts").install "Kanit-Medium.ttf" (share/"fonts").install "Kanit-MediumItalic.ttf" (share/"fonts").install "Kanit-Regular.ttf" (share/"fonts").install "Kanit-SemiBold.ttf" (share/"fonts").install "Kanit-SemiBoldItalic.ttf" (share/"fonts").install "Kanit-Thin.ttf" (share/"fonts").install "Kanit-ThinItalic.ttf" end test do end end
class CreateOrderLogs < ActiveRecord::Migration def self.up create_table :order_logs do |t| t.integer :order_id t.integer :user_id t.string :log t.timestamps end end def self.down drop_table :order_logs end end
require 'rest-client' require 'json' require_relative '../lib/engine' require 'minitest/autorun' class TestEngine < MiniTest::Test def setup @engine = Engine.new @request_body = { "arguments": [ { "id": '123', "input": [ [ 1, 2, 3 ] ], "converterIds": [ 36 ] } ] } end def test_main response = @engine.run @request_body assert response end def get_converter id body = RestClient.get "http://54.148.156.110:4567/sync-module/converters/#{id}" JSON.parse body, symbolize_names: true end def test_request assert get_converter 36 end def test_t_request body = get_converter(36) request_body = { "arguments": [ 1, 2, 3 ], "converter": { "name": "Multiplier", "code": body[:code] } } response = @engine.test request_body assert response.key? :status end end
#require "gtk3" #load 'Sauvegarde.rb' load 'Plateau.rb' load 'Highscore.rb' # Coeur et gestion du jeu # @attr_reader plateau [Plateau] le plateau de jeu # @attr_reader nom_joueur [String] # @attr nom_joueur_label [Gtk::Label] # @attr_reader temps_de_jeu # @attr window [Gtk::Window] composant Gtk de la fenêtre # @attr_reader en_jeu [Boolean] prédicat de la continuité du Jeu class Jeu attr_reader :plateau, :nom_joueur,:temps_de_jeu,:en_jeu @plateau @nom_joueur @nom_joueur_label @temps_de_jeu @window @en_jeu # Constructeur du jeu # @param [Plateau] le plateau dans lequel se déroule le jeu # @param [String] le nom du joueur # @param [Fixnum] le temps de jeu def initialize(plateau:, nom_joueur:, temps_de_jeu:) @plateau, @nom_joueur, @temps_de_jeu = plateau, nom_joueur, temps_de_jeu @en_jeu = true end # Affichage de notre jeu # @return [void] def affiche_toi builder = Gtk::Builder.new builder.add_from_file("../Glade/EnJeu.glade") @window = builder.get_object("fn_select") @window.signal_connect('destroy') { |_widget| exit!() } # Récupérations des objets # Boutons btn_options = builder.get_object("Options") btn_undo = builder.get_object("Undo") btn_point_de_retour = builder.get_object("Point de retour") btn_revenir_point_de_retour = builder.get_object("Revenir point de retour") btn_aide = builder.get_object("Aide") btn_verification = builder.get_object("Verification") btn_indice = builder.get_object("Indice") # Autres @nom_joueur_label = builder.get_object("nom_joueur") grid = builder.get_object("grilleJeu") # Configurations des objets récupéré # Boutons btn_options.signal_connect('clicked'){afficherOption()} btn_undo.signal_connect('clicked'){@plateau.on_click_undo} btn_point_de_retour.signal_connect('clicked'){@plateau.on_click_creer_retour} btn_revenir_point_de_retour.signal_connect('clicked'){@plateau.on_click_aller_retour} btn_aide.signal_connect('clicked'){@plateau.on_click_regle(self)} btn_verification.signal_connect('clicked'){self.afficher_erreur} btn_indice.signal_connect('clicked'){@plateau.on_click_aide(self)} # initialisation du plateau dans la grille grid.set_property "row-homogeneous", true grid.set_property "column-homogeneous", true (0..@plateau.taille-1).each do |i| (0..@plateau.taille-1).each do |j| temp = @plateau.damier[i][j].bouton grid.attach temp, j, i, 1, 1 end end # configuration de la fenêtre @window.set_title "Nurikabe!" @window.signal_connect "destroy" do #Sauvegarde.creer_sauvegarde(self) @en_jeu = false @window.destroy() exit!() end @window.set_window_position :center @window.show_all # lancement du timer timer_thread = Thread.new{self.lancer_timer} Gtk.main end # Affichages des différentes options possible # @return [void] def afficherOption builder_opt = Gtk::Builder.new builder_opt.add_from_file("../Glade/Options.glade") windowOpt = builder_opt.get_object("fen_opt") windowOpt.signal_connect('destroy') { |_widget| windowOpt.hide() } btn_sav = builder_opt.get_object("btn_sav") btn_sav.signal_connect('clicked') {Sauvegarde.creer_sauvegarde(self) } btn_quit = builder_opt.get_object("btn_quit") btn_quit.signal_connect('clicked') {|_widget| tout_fermer(windowOpt)} windowOpt.show_all() end # Fermeture des fernêtre # @return [void] def tout_fermer(windowOpt) @en_jeu = false @window.destroy() windowOpt.destroy() exit!() end # Lancement d'une boucle qui enregistre le temps tant que le jeu n'est pas finit # @return [void] def lancer_timer t1 = Time.now - @temps_de_jeu while(@en_jeu) t2 = Time.now @temps_de_jeu = (t2 - t1).round @nom_joueur_label.set_label("Joueur : " + @nom_joueur + " | temps : " + @temps_de_jeu.to_s + " s (+ " + @plateau.malus_aide.to_s + " s malus) | " + @plateau.niveau) sleep(1) end end # Affichage du résultat de la vérification du plateau # @return [void] def afficher_erreur # return if @plateau.partie_finie tab_erreur = @plateau.verifier_damier @en_jeu = false if @plateau.partie_finie pop = Gtk::MessageDialog.new(Gtk::Window.new("fenetre"), Gtk::DialogFlags::DESTROY_WITH_PARENT, (tab_erreur.empty? && !@plateau.partie_finie ? Gtk::MessageType::INFO : Gtk::MessageType::QUESTION), (tab_erreur.empty? && !@plateau.partie_finie ? :OK : :yes_no), (@plateau.partie_finie ? "Bravo " + @nom_joueur +" ! Vous avez fini le jeu en " + (@temps_de_jeu+@plateau.malus_aide).to_s + " seconde.\nVoulez-vous rejouer ?" : (tab_erreur.empty? ? "Vous avez #{tab_erreur.size} erreurs! " : "Vous avez #{tab_erreur.size} erreurs!\nVoulez-vous les visionner ?"))) reponse = pop.run pop.destroy if(@plateau.partie_finie) classement = @plateau.niveau.chomp.downcase getHighscore = Highscore.recuperer_ds_fichier if(classement == "facile") getHighscore.inserer_score_facile(@nom_joueur,@temps_de_jeu+@plateau.malus_aide) elsif(classement == "moyen") getHighscore.inserer_score_moyen(@nom_joueur,@temps_de_jeu+@plateau.malus_aide) else getHighscore.inserer_score_difficile(@nom_joueur,@temps_de_jeu+@plateau.malus_aide) end Sauvegarde.sauvegarde_highscore(getHighscore) if(reponse == Gtk::ResponseType::YES) @window.hide menu = Menu.getInstance() menu.afficheChoixMode(@nom_joueur) else @window.destroy() Gtk.main_quit() end elsif(reponse == Gtk::ResponseType::YES) # affichage en rouge des erreurs @plateau.malus_aide += tab_erreur.size*5 tab_erreur.each do |err| err.en_rouge end end end end
# This simple file shows how Ruby creates an Object Class, in this case "Song". The "methods" within this class (initialize, first_test_method, name, etc...), # are used do stuff to the original Song object. There are different ways to do this, a few are shown below: class Song def initialize(name, artist, duration) # the initialize method allows you to create a new Song object using Song.new and pass in a name, artist, and duration in parenthesis like: # Song.new("name_of_song", "song_artist", "song_duration") # Once created using new, the values you pass into the parenthesis will be stored below into @variables to be accessed elsewhere in the code (like below) @name = name @artist = artist @duration = duration end def first_test_method # uses "puts" to print to terminal # then starts a string "" # then uses Ruby string concatenation, meaning you can add Ruby into a string using a # sign and curly braces: "#{ruby_code_goes_here}" puts "Song: #{@name}--#{@artist}--#{@duration}" end a = Song.new("Paint it Black", "The Rolling Stones", "3:23") a.first_test_method def name # this will allow you to call the name of the method "name" on a Song object like: song_object.name # it will return the value of @name which is set as the first parameter passed into the perenthesis when you create the object. @name end def artist # this will allow you to call the name of the method "artist" on a Song object like: song_object.artist # it will return the value of @artist which is set as the second parameter passed into the perenthesis when you create the object. @artist end def duration # this will allow you to call the name of the method "duration" on a Song object like: song_object.duration # it will return the value of @duration which is set as the last parameter passed into the perenthesis when you create the object. @duration end b = Song.new("Magic Carpet Ride", "Steppenwolf", "4:55") # the following new way of accessing the attributes (b.name) does the same thing as the original first_test_method puts "Song: #{b.name}--#{b.artist}--#{b.duration}" # the following is the same as above b.first_test_method end # save this file, open a terminal in the same directory and type: ruby test.rb
require 'rails_helper' RSpec.describe Garden do describe 'relationships' do it { should have_many(:plots) } end describe 'instance methods' do before :each do @garden = Garden.create!(name: "Sunshine Gardens", organic: true) @plot_1 = @garden.plots.create!(number: 10, size: "Big", direction: "East") @plot_2 = @garden.plots.create!(number: 20, size: "small", direction: "West") @plant_1 = Plant.create!(name: 'Ivy', description: 'An ivy plant', days_to_harvest: 90) @growing_plant_1 = GrowingPlant.create!(plot: @plot_1, plant: @plant_1) @growing_plant_2 = GrowingPlant.create!(plot: @plot_2, plant: @plant_1) @growing_plant_3 = GrowingPlant.create!(plot: @plot_2, plant: @plant_1) @plant_2 = @plot_1.plants.create!(name: 'Pumpkin', description: 'Orange', days_to_harvest: 180) @plant_3 = @plot_2.plants.create!(name: 'Apricot', description: 'Yellow', days_to_harvest: 50) @plant_4 = @plot_2.plants.create!(name: 'Blueberry', description: 'Blue', days_to_harvest: 90) end it 'returns a list of distinct plants with harvest days less than 100' do exp_array = [@plant_1, @plant_3, @plant_4] expect(@garden.plants_near_harvest.include?(@plant_2)).to eq false expect(@garden.plants_near_harvest).to eq exp_array end it 'sorts plants from all plots sorted by number planted' do expect(@garden.sorted_plants_near_harvest.first).to eq @plant_1 expect(@garden.sorted_plants_near_harvest.first.number_planted).to eq 3 expect(@garden.sorted_plants_near_harvest.last.number_planted).to eq 1 end end end
# frozen_string_literal: true module MFCCase # Версия модуля VERSION = '0.6.8' end
=begin no termina con ; #comentarios en linea el begin y end deben ir pegados a comienzo utilizar los parentesis solo cuando no se este ejecutando una funcion de dsl Snackcase uso de _ para la separacion de palabras scamelcase o algo asi para separar las palabras por mayuscula =end
# rails generate repres:dosser:swagger administration --version 2 require 'rails/generators' class Repres::Dosser::SwaggerGenerator < Rails::Generators::NamedBase # https://github.com/erikhuda/thor/blob/master/lib/thor/base.rb#L273 class_option :version, type: :numeric, required: false, default: 1, desc: 'a positive integer, the default value is 1' source_root File.expand_path('../templates', __FILE__) def produce bind_options generate 'repres:dosser:platform', "#{@platform_name} --version #{@version_number}" generate_gemfile generate_initializer generate_swagger generate_route end def bind_options @platform_name = file_name.downcase @version_number = options['version'].to_i @platform_module_name = @platform_name.camelize @version_module_name = "V#{@version_number}" @version_name = "v#{@version_number}" @application_name = application_name @application_name_const = application_name.upcase end # gemfile # # Gemfile # def generate_gemfile gem 'swagger_engine' end # initializer # # config/initializers/swagger_engine.rb # def generate_initializer template 'config/initializers/swagger_engine.rb.erb', 'config/initializers/swagger_engine.rb' line = "'#{@platform_module_name} API #{@version_name}': 'lib/swagger/#{@platform_name}_api_#{@version_name}.json'" file = Rails.root.join 'config', 'initializers', 'swagger_engine.rb' if :invoke==behavior puts "Please make sure the following line is in the file #{file}:\n\n #{line}\n\n" elsif :revoke==behavior puts "Please remove the following line from the file #{file}:\n\n #{line}\n\n" end end # swagger # # lib/swagger/{platform}_api_{version}.json # def generate_swagger template 'lib/swagger/api.json.erb', "lib/swagger/#{@platform_name}_api_#{@version_name}.json" end # route # # config/routes.rb # def generate_route source = File.expand_path find_in_source_paths('config/routes.rb.erb') content = ERB.new(File.binread(source).strip, nil, '-', "@output_buffer").result instance_eval('binding') route content end private :generate_gemfile, :generate_initializer, :generate_swagger, :generate_route end
class Account::PostsController < ApplicationController before_action :authenticate_user! before_action :find_params, only: [:edit, :update, :destroy] def index @posts = current_user.posts.paginate(:page => params[:page], :per_page => 4) end def edit if @post.user != current_user flash[:warning] = "您不是該筆記的作者!" redirect_to posts_path end end def update if @post.update(account_post_params) redirect_to account_posts_path flash[:warning] = "已完成編輯!" else render :edit end end def destroy @post.delete redirect_to account_posts_path end private def account_post_params params.require(:post).permit(:title, :content) end def find_params @post = Post.find(params[:id]) end end
class CreateMhpSkills < ActiveRecord::Migration[5.0] def change create_table :mhp_skills do |t| t.string :name t.integer :skill_system_id t.integer :required_point t.timestamps end add_index :mhp_skills, :skill_system_id end end
class TwitterDatum < ActiveRecord::Base include Datum belongs_to :social_network set_type :twitter_data comparable_metrics :total_followers, :total_mentions, :ret_tweets, :total_clicks, :interactions_ads, :total_interactions, :total_prints, :favorites, :lists def new_followers previous_datum.present? ? total_followers - previous_datum.total_followers : 0 end def period_tweets previous_datum.present? ? total_tweets - previous_datum.total_tweets : total_tweets end def total_interactions (total_mentions + ret_tweets + total_clicks + interactions_ads) end def total_prints (prints + prints_ads) end def total_investment (agency_investment + investment_ads + investment_actions) end def cost_per_prints total_prints != 0 ? (total_investment.to_f/total_prints.to_f)*1000 : 0 end def cost_per_interaction total_interactions != 0 ? (total_investment.to_f/total_interactions.to_f) : 0 end def cost_follower (total_investment.to_f/new_followers.to_f) end end
require 'rails_helper' RSpec.describe Admin::TeamsController, type: :controller do let(:valid_attributes) { { slug: 'test', name: 'test' } } let(:invalid_attributes) { skip("Add a hash of attributes invalid for your model") } let(:valid_session) { {} } describe "GET #index" do it "assigns all teams as @teams" do team = create :team, valid_attributes get :index, params: {}, session: valid_session expect(assigns(:teams)).to eq([team]) end end describe "GET #show" do it "assigns the requested admin_team as @admin_team" do team = create :team, valid_attributes get :show, params: { id: team.to_param }, session: valid_session expect(assigns(:team)).to eq(team) end end describe "GET #new" do it "assigns a new admin_team as @admin_team" do get :new, params: {}, session: valid_session expect(assigns(:team)).to be_a_new(Team) end end describe "GET #edit" do it "assigns the requested admin_team as @admin_team" do team = create :team, valid_attributes get :edit, params: { id: team.to_param }, session: valid_session expect(assigns(:team)).to eq(team) end end describe "POST #create" do context "with valid params" do it "creates a new Team" do expect { post :create, params: { team: valid_attributes }, session: valid_session }.to change(Team, :count).by(1) end it "assigns a newly created admin_team as @admin_team" do post :create, params: { team: valid_attributes }, session: valid_session expect(assigns(:team)).to be_a(Team) expect(assigns(:team)).to be_persisted end it "redirects to the created admin_team" do post :create, params: { team: valid_attributes }, session: valid_session expect(response).to redirect_to([:admin, Team.last]) end end context "with invalid params" do it "assigns a newly created but unsaved admin_team as @admin_team" do post :create, params: { team: invalid_attributes }, session: valid_session expect(assigns(:team)).to be_a_new(Team) end it "re-renders the 'new' template" do post :create, params: { team: invalid_attributes }, session: valid_session expect(response).to render_template("new") end end end describe "PUT #update" do context "with valid params" do let(:new_attributes) { { name: 'new-name' } } it "updates the requested admin_team" do team = create :team, valid_attributes put :update, params: { id: team.to_param, team: new_attributes }, session: valid_session expect(team.reload.name).to eql 'new-name' end it "assigns the requested admin_team as @admin_team" do team = create :team, valid_attributes put :update, params: { id: team.to_param, team: valid_attributes }, session: valid_session expect(assigns(:team)).to eq(team) end it "redirects to the admin_team" do team = create :team, valid_attributes put :update, params: { id: team.to_param, team: valid_attributes }, session: valid_session expect(response).to redirect_to([:admin, team]) end end context "with invalid params" do it "assigns the admin_team as @admin_team" do team = create :team, valid_attributes put :update, params: { id: team.to_param, :team => invalid_attributes }, session: valid_session expect(assigns(:team)).to eq(team) end it "re-renders the 'edit' template" do team = create :team, valid_attributes put :update, params: { id: team.to_param, team: invalid_attributes }, session: valid_session expect(response).to render_template("edit") end end end describe "DELETE #destroy" do it "destroys the requested admin_team" do team = create :team, valid_attributes expect { delete :destroy, params: { id: team.to_param }, session: valid_session }.to change(Team, :count).by(-1) end it "redirects to the teams list" do team = create :team, valid_attributes delete :destroy, params: { id: team.to_param }, session: valid_session expect(response).to redirect_to(admin_teams_url) end end end
require 'spec_helper' describe 'campaigns/show' do include CampaignExampleHelpers let(:campaign) { create_campaign_with_tier_taglines } let(:charity) { campaign.charity } let(:donation_order) { DonationOrder.new } let(:campaign_stat) { mock('CampaignStat') } before do assign(:campaign, campaign) assign(:charity, charity) assign(:donation_order, donation_order) assign(:campaign_stat, campaign_stat) campaign_stat.stub(:donations_count).and_return(0) campaign_stat.stub(:donations_amount_sum).and_return(Money.new(0)) end describe "donation order form" do before do donation_order.donation.amount = 15 render end it "has a form for a new donation order" do rendered.should have_selector("form", :method => "post", :action => charity_campaign_donation_orders_path(charity, campaign)) end it "renders the donation order form amount partial" do view.should render_template(:partial => 'donation_orders/_form_fields_amount', :count => 1) end it "renders the donation order form info partial" do view.should render_template(:partial => 'donation_orders/_form_fields_info', :count => 1) end it "has terms field" do rendered.should have_unchecked_field('I agree to the Terms and Conditions') end it "has the donate now button" do rendered.should have_button('Donate Now') end end describe ".campaign-banner" do it "has the campaign charity's name" do render rendered.should have_selector('.campaign-banner h5', :text => "Donate to #{charity.name}") end it "has a button to the charity's rewards page" do render rendered.should have_selector('.campaign-banner a.btn.btn-primary', :text => 'Get Rewards When You Donate') end end describe ".campaign-header" do it "has the campaign's tagline" do render rendered.should have_selector('h1', :text => campaign.tagline) end end describe '.campaign-content' do before do render end it "has a button and tagline for each tier" do campaign.tiers.each do |tier| rendered.should have_selector('button.btn-tier', :text => tier.amount.format(:no_cents_if_whole => true)) rendered.should have_selector('.campaign-tier-description', :text => tier.tagline) end end it "has form for other amount" do rendered.should have_field('other_amount', :with => '') rendered.should have_selector('.form-amount button', :text => 'Submit') end end describe '.campaign-side' do it "has the campaign charity's image" do render rendered.should have_image(charity.picture.campaign_sidebar) end it "has .donation-stats element when there are 5 or more donations" do campaign_stat.stub(:donations_count).and_return(5) render rendered.should have_selector(".campaign-side .donation-stats") end it "renders the donation stats with delimiters" do campaign_stat.stub(:donations_count).and_return(999999) campaign_stat.stub(:donations_amount_sum).and_return(Money.new(99999900)) render rendered.should have_selector(".donation-stats", :text => /Raised:\s*\$999,999/) rendered.should have_selector(".donation-stats", :text => /Donors:\s*\999,999/) end it "does not render donation stats" do render rendered.should_not have_selector(".campaign-side", :text => /Raised:\s*\$0/) rendered.should_not have_selector(".campaign-side", :text => /Donors:\s*\0/) end it "has the an about us for the charity" do render rendered.should have_selector(".campaign-side", :text => /About Us:\s*#{charity.description}/) end it "does not have an about us if charity description is not present" do charity.description = nil assign(:charity, charity) render rendered.should_not have_selector(".campaign-side", :text => "About Us:") end it "has the charity's website" do render rendered.should have_selector(".campaign-side", :text => "Visit our website.") rendered.should have_link('website', :href => charity.website_url) end it "does not have the charity's website" do charity.website_url = nil assign(:charity, charity) render rendered.should_not have_selector(".campaign-side", :text => "Visit our website") end end end
require File.expand_path("../lib/jaguar/version", __FILE__) Gem::Specification.new do |gem| gem.name = "jaguar" gem.version = Jaguar::VERSION gem.license = "MIT" gem.authors = ["Tiago Cardoso"] gem.email = ["cardoso_tiago@hotmail.com"] gem.description = "Evented HTTP Server" gem.summary = "Evented Server for HTTP" gem.homepage = "http://github.com/TiagoCardos1983/jaguar" gem.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) } gem.files = `git ls-files`.split("\n") gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") gem.require_paths = ["lib"] gem.add_dependency "celluloid-io", ">= 0.17" gem.add_dependency "http_parser.rb"#, "~> 0.6.0" gem.add_dependency "http-2" gem.add_development_dependency "reqrep" gem.add_development_dependency "minitest" gem.add_development_dependency "rake" gem.add_development_dependency "certificate_authority" end
require 'rails_helper' describe Pii::Attribute do let(:first_name_utf8) { 'José' } let(:first_name_ascii) { 'Jose' } subject { described_class.new(raw: first_name_utf8) } describe '#ascii' do it 'transliterates' do expect(subject.ascii).to eq first_name_ascii end end # rubocop:disable UnneededInterpolation describe 'delegation' do it 'delegates to raw' do expect(subject.blank?).to eq false expect(subject.present?).to eq true expect(subject.to_s).to eq first_name_utf8 expect(subject.to_str).to eq first_name_utf8 expect("#{subject}").to eq first_name_utf8 expect(subject).to eq first_name_utf8 end end # rubocop:enable UnneededInterpolation end
class MadeBy include Neo4j::ActiveRel from_class :Product to_class :Brand type :MADE_BY end
class GridLayer < RenderLayer def render(g,width,height) if battle.info[:grid_show] grid_ratio = battle.info[:grid_ratio] g.color = Color::WHITE current_x = 0 current_y = 0 battle.objects.values.select{|o| o[:layer]=='background'}.each do |o| img = battle.load_image(o[:image]) map_size_x = img.width map_size_y = img.height while current_x < map_size_x start_x = battle.info[:grid_offset_x] + current_x g.drawLine(start_x, o.x, start_x, map_size_y) current_x += grid_ratio end while current_y < map_size_y do start_y = battle.info[:grid_offset_y] + current_y current_y += grid_ratio g.drawLine(o.y, start_y, map_size_x, start_y) end end end end end
class EncounterSerializer < ActiveModel::Serializer attributes :id, :description, :name has_one :campaign has_many :creatures has_many :characters class CreatureSerializer < ActiveModel::Serializer attributes :id, :name, :creature_type, :str, :dex, :con, :int, :wis, :cha, :challenge_rating, :armor_class, :speed, :hp, :alignment has_many :positions end class CharacterSerializer < ActiveModel::Serializer attributes :id, :name, :race, :char_class, :level, :str, :dex, :con, :int, :wis, :cha, :speed, :hp, :alignment, :armor_class has_one :user has_many :positions end end
#write your code here def echo(word) word end def shout(word) word.upcase end def repeat(word, n=2) [word]*n*' ' end def start_of_word(word,n) word[0..(n-1)] end def first_word(word) word.split.first end def titleize(title) little_words = %w[and the over] title = title.split.map.with_index do |word,i| little_words.include?(word) && i!=0 ? word : word.capitalize end title.join(' ') end
#encoding: utf-8 require 'rubygems' require 'sinatra' require 'sinatra/reloader' require 'pony' require 'sqlite3' def is_barber_exists? db, name db.execute('select * from barbers where name=?', [name]).length > 0 end def seed_db db, barbers barbers.each do |barber| if !is_barber_exists? db, barber db.execute 'insert into barbers (name) values (?)', [barber] end end end def get_db db = SQLite3::Database.new 'visit.db' db.results_as_hash = true return db end configure do db = get_db db.execute 'CREATE TABLE IF NOT EXISTS "visit" ( "id" INTEGER, "name" TEXT, "phone" INTEGER, "date_visit" INTEGER, "barber" TEXT, "color" TEXT, PRIMARY KEY("id" AUTOINCREMENT) )' db.execute 'CREATE TABLE IF NOT EXISTS "barbers" ( "id" INTEGER, "name" TEXT, PRIMARY KEY("id" AUTOINCREMENT) )' seed_db db, ['Walter White', 'Jessie Pinkman', 'Gus Fring', 'Joe Trebiani'] end get '/' do erb "Hello!!! <a href=\"https://github.com/bootstrap-ruby/sinatra-bootstrap\">Original</a> pattern has been modified for <a href=\"http://rubyschool.us/\">Ruby School</a>" end get '/about' do erb :about end get '/admin' do erb :admin end get '/visit' do erb :visit end get '/contacts' do erb :contacts end get '/something' do erb :something end before do db = get_db @barb = db.execute 'SELECT * FROM barbers ' end post '/visit' do @user_name = params[:username] @user_phone = params[:userphone] @date_visit = params[:datevisit] @time_visit = params[:timevisit] @barber = params[:barbers] hh = { :username => 'Укажите имя', :userphone => 'Укажите номер телефона', :datevisit => 'Укажите дату визита', :timevisit => 'Укажите время визита'} @error = hh.select {|key,_| params[key] == ""}.values.join (", ") if @error != "" return erb :visit end @colorpicker = params[:colorpicker] @title = 'Thank you' @second_message = "Dear #{@user_name}, you'r visit is date #{@date_visit}, time #{@time_visit} you'r barber is #{@barber} you color is #{@colorpicker}" db = get_db db.execute 'insert into visit ( name, phone, date_visit, barber, color ) values (?,?,?,?,?)', [@user_name, @user_phone, @date_visit, @barber, @colorpicker] # @f = File.open "./public/appointment.txt", "a" # @f.write " Name - #{@user_name}, phone number #{@user_phone}, date visit #{@date_visit}, time visit #{@time_visit} barber - #{@barber}\n" # @f.close # @f = File.open "./public/contacts.txt", "a" # @f.write " Name - #{@user_name}, phone number #{@user_phone} \n" # @f.close erb :message end post '/contacts' do @username = params[:username] @message = params[:message] Pony.mail({ :to => 'xxxxxxxxxx@rambler.ru' , :from => 'zxc@gmail.com', :via => :smtp, :subject => "Новое сообщение от пользователя #{@username}", :body => "#{@message}", :via_options => { :address => 'smtp.gmail.com', :port => '587', :enable_starttls_auto => true, :user_name => 'zxc', :password => 'zxc', :authentication => :plain, :domain => "localhost:4567" } }) erb :contacts end post '/admin' do @login = params[:login] @password = params[:password] @title = 'You in admin room' @first_message = 'Visit' db = get_db @one = db.execute 'SELECT * FROM visit ' erb :show end # if @login == 'admin' && @password == 'secret' # else # 'Wrong password or login' # end
namespace :db do desc "Fill database with sample data" task populate: :environment do User.create!(name: "Example User", email: "example@railstutorial.org", password: "foobar", password_confirmation: "foobar") 99.times do |n| name = Faker::Name.name email = "example-#{n+1}@railstutorial.org" password = "password" User.create!(name: name, email: email, password: password, password_confirmation: password) end users = User.all(limit: 6) 35.times do title = Faker::Lorem.sentence(6) if rand(2) == 0 pub_type = "newspaper" else pub_type = "conference" end pub_name = Faker::Lorem.sentence(1) year = rand(1980...2012) month = rand(1...13) pages = rand(5...500) notes = Faker::Lorem.sentence(50) summary = Faker::Lorem.sentence(150) users.each { |user| user.publications.create!(title: title, pub_type: pub_type, pub_name: pub_name, year: year, month: month, pages: pages, notes: notes, summary: summary) } end end end
class CreateRequests < ActiveRecord::Migration[5.0] def change create_table :requests do |t| t.integer :song_id, null: false t.integer :artist_id, null: false t.integer :genre_id, null: false t.integer :source_id, null: false t.integer :requestlog_id, null: false t.integer :listener_id, null: false t.boolean :in_system? t.timestamps end end end
require 'test_helper' class StudentsMustChangePasswordOnFirstSigningInTest < ActionDispatch::IntegrationTest def setup log_in_as_student end test "students cannot create students" do # Student can go to student index get students_path assert_select 'h1', "Students#index" # Student only sees their own assignments assert_select 'td', "jill" assert_select 'td', "jill@jill.com" # Trying to post to new_assignment_path gives flash notice we can assert_equal flash[:notice] post students_path, params: { student: { name: "jill", email: "jill@jill.com", password: "password", role: "student", course_name: "GSO"}} assert_equal "You do not have permission to access that page.", flash[:notice] # logout delete logout_path end test "students cannot create assignments" do # Students can go to assignments index get assignments_path # Students can see all assignments assert_select 'h1', "Assignments#index" # Trying to post to new assignment path gives flash notice we can assert equal flash[:notice] post assignments_path, params: { assignment: { title: "Review", description: "This rocks", due_date: Date.new(2017, 1, 1), user_ids: [1, 2] }} # logout delete logout_path end end
class AnnualReport class Categories class CategoryWithMonthlyValues < Base private attr_reader :data public def initialize(data) super(data) end def total values.sum end def average_total average_values.sum.fdiv(average_values.count) end def median_total sorted = median_values.sort count = sorted.count (sorted[(count - 1) / 2] + sorted[count / 2]) / 2.0 end def values @values ||= data["values"] || [] end def average_values @average_values ||= data["averages"] || data["values"] || [] end def median_values @median_values ||= data["medians"] || data["values"] || [] end end end end
require_relative 'test_helper' class SimpleTestCase < Test::Unit::TestCase def test_successful_run assert true end def test_failed_run assert_equal false, true, "test assertion message" end # This line prevents tests from SimpleTestCase class from being executed @@test_suites.delete(SimpleTestCase) end class TestTestInstance < Test::Unit::TestCase def test_handling_failures @test = Bachelor::TestInstance.new(SimpleTestCase, 'test_failed_run') assert !@test.passed? end def test_handling_success @test = Bachelor::TestInstance.new(SimpleTestCase, 'test_successful_run') assert @test.passed? end def test_failed_test_output_capture @test = Bachelor::TestInstance.new(SimpleTestCase, 'test_failed_run') report = @test.report assert report.is_a?(String) assert_match /test_failed_run\(SimpleTestCase\)/, @test.report assert_match /test_test_instance.rb:9/, @test.report assert_match /test assertion message/, @test.report end end
require 'rails_helper' RSpec.describe(Account, :type => :model) do it 'can deposit' do account = Account.new('Indra', 1_000_000) account.deposit(500_000) expect(account.amount).to(eq(1_500_000)) end it 'can withdraw' do account = Account.new('Indra', 1_000_000) account.withdraw(500_000) expect(account.amount).to(eq(500_000)) end it 'can transfer' do account_indra = Account.new('Indra', 1_000_000) account_firmansyah = Account.new('Firmansyah', 5_000_000) account_indra.transfer(account_firmansyah, 500_000) expect(account_indra.amount).to(eq(500_000)) expect(account_firmansyah.amount).to(eq(5_500_000)) end it 'raise NotEnoughAmount' do account_indra = Account.new('Indra', 1_000_000) expect() do account_indra.withdraw(5_000_000) end.to(raise_error(NotEnoughAmount)) expect(account_indra.amount).to(eq(1_000_000)) end it 'cannot transfer because of not enough amount' do account_indra = Account.new('Indra', 1_000_000) account_firmansyah = Account.new('Firmansyah', 5_000_000) expect() do account_indra.transfer(account_firmansyah, 5_000_000) end.to(raise_error(NotEnoughAmount)) expect(account_indra.amount).to(eq(1_000_000)) expect(account_firmansyah.amount).to(eq(5_000_000)) end end
class AnswerQuestion < AiBase def initialize(result) @request_data = result question_id = result['parameters']['id'] @url = "questions/#{question_id}/answers" @intent = "posted your answer" end def prepare_payload { 'content' => request_data['parameters']['content'] } end def prepare_response(dummy, response) response.add_text(dummy.content) response.package_response end end
class Comment < ActiveRecord::Base attr_accessible :cuerpo, :noticia_id, :persona_id, :updated_at, :edited belongs_to :persona belongs_to :noticia end
class NotificationsController < ApplicationController def index @grid = NotificationsGrid.new(params[:notifications_grid]) respond_to do |f| f.html do if @current_user.is_admin? @grid.scope {|scope| scope.page(params[:page]) } else @grid.scope {|scope| scope.where(:receiver_id => @current_user.id).page(params[:page]) } end end f.csv do send_data @grid.to_csv(col_sep: ";").encode("ISO-8859-1"), type: "text/csv", disposition: 'inline', filename: "Notificações-#{Time.now.to_s}.csv" end end end def get_new_notifications user_id = params[:user_id].to_i user = User.find user_id notifications_unread = Notification.where(:receiver_id => user_id).unread_by(user).order(created_at: :desc).limit(10) notifications_unread_length = Notification.where(:receiver_id => user_id).unread_by(user).count data = { :notifications_unread => notifications_unread, :notifications_unread_length => notifications_unread_length } respond_to do |format| format.json {render :json => data, :status => 200} end end def update_notifications_read notifications_unread = Notification.where(:receiver_id => @current_user.id).unread_by(@current_user).order(created_at: :desc).limit(10) notifications_unread_length = Notification.where(:receiver_id => @current_user.id).unread_by(@current_user).order(created_at: :desc).count for notification in notifications_unread notification.mark_as_read! :for => @current_user end data = { :notifications_unread => notifications_unread, :notifications_unread_length => notifications_unread_length } respond_to do |format| format.json {render :json => data, :status => 200} end end def mark_as_read notification_unread = Notification.where(:id => params[:notification_id]).first notification_unread.mark_as_read! :for => @current_user notifications_unread = Notification.where(:receiver_id => @current_user.id).unread_by(@current_user).order(created_at: :desc).limit(10) notifications_unread_length = Notification.where(:receiver_id => @current_user.id).unread_by(@current_user).order(created_at: :desc).count data = { :notifications_unread => notifications_unread, :notifications_unread_length => notifications_unread_length } respond_to do |format| format.json {render :json => data, :status => 200} end end def mark_as_unread notification_read = Notification.where(:id => params[:notification_id]).first ReadMark.where(readable_type: notification_read.class.name, readable_id: notification_read.id).each(&:destroy!) notifications_unread = Notification.where(:receiver_id => @current_user.id).unread_by(@current_user).order(created_at: :desc).limit(10) notifications_unread_length = Notification.where(:receiver_id => @current_user.id).unread_by(@current_user).order(created_at: :desc).count data = { :notifications_unread => notifications_unread, :notifications_unread_length => notifications_unread_length, } respond_to do |format| format.json {render :json => data, :status => 200} end end end
require "spec_helper" RSpec.describe "Day 24: It Hangs in the Balance" do let(:runner) { Runner.new("2015/24") } let(:input) do <<~TXT 1 2 3 4 5 7 8 9 10 11 TXT end describe "Part One" do let(:solution) { runner.execute!(input, part: 1) } it "computes ideal quantum entanglement" do expect(solution).to eq(99) end end describe "Part Two" do let(:solution) { runner.execute!(input, part: 2) } it "computes ideal quantum entanglement (with a trunk)" do expect(solution).to eq(44) end end end
When /^I edit the conference$/ do fill_in "Name", with: "MLS" click_button "commit" end When /^I create a new conference$/ do fill_in "Name", with: @new_conference.name select @edit_league.name, from: 'conference[league_id]' click_button "commit" end Then /^the changes to the conference should be saved$/ do @edit_conference.reload @edit_conference.name.should == "MLS" end Then /^I should see the details of the new conference$/ do page.should have_content(@new_conference.name) end Then /^I should be able to associate a sport with the conference$/ do page.should have_selector("#conference_league_id") end
#!/usr/bin/env jruby require 'java' require 'cache' require 'code_search' require 'view_matrix' require 'uri' require 'fileutils' #import 'abstractor.cluster.hierarchical.DerivedAgglomerativeClusterer' #import 'abstractor.cluster.hierarchical.AgglomerativeClusterer' #import 'abstractor.cluster.hierarchical.CompleteLinkage' import 'abstractor.cluster.hierarchical.Similarity' class CodeSearchSimilarity include Java::AbstractorClusterHierarchical::Similarity CACHE_DIR = 'data' def initialize FileUtils.mkdir CACHE_DIR unless File.exist? CACHE_DIR end def similarity_ids(id1, id2) queries = ["lang:java #{id1} #{id2}", "lang:java #{id1}", "lang:java #{id2}"] results = queries.map do |q| begin cache lambda {puts 'Caching'; code_search(q)}, CACHE_DIR, URI.encode(q), CACHE_TO_S, CACHE_TO_I rescue Exception File.open(CACHE_DIR + '/' + URI.encode(q), 'w') { |f| f.write('0') } return 0.0 end end #total = results[1] + results[2] - results[0] total = results.max if total == 0 then return 0.0 else return results[0].to_f / total end end def similarity(v1, v2) id1 = v1.getUserDatum('label') id2 = v2.getUserDatum('label') return similarity_ids(id1, id2) end end #if __FILE__ == $0 # ids = %w( # junit.framework.ComparisonCompactor # junit.framework.Assert # junit.framework.TestResult # junit.runner.BaseTestRunner # junit.extensions.TestDecorator # junit.extensions.ActiveTestSuite # junit.framework.JUnit4TestAdapterCache # junit.framework.ComparisonFailure # junit.framework.TestListener # junit.framework.JUnit4TestAdapter # junit.framework.Protectable # junit.framework.TestCase # junit.runner.TestRunListener # junit.textui.TestRunner # junit.framework.AssertionFailedError # junit.extensions.TestSetup # junit.extensions.RepeatedTest # junit.framework.JUnit4TestCaseFacade # junit.runner.Version # junit.framework.Test # junit.framework.TestFailure # junit.textui.ResultPrinter # junit.framework.TestSuite).sort # # # n = ids.size # sim = CodeSearchSimilarity.new # array2d = Array.new(n) { Array.new(n) { 1.0 } } # # 0.upto(n-1) do |i| # i.upto(n-1) do |j| # puts "Comparing: #{ids[i]} - #{ids[j]}" # array2d[i][j] = array2d[j][i] = sim.similarity_ids(ids[i], ids[j]) # end # end # # puts "Visualizaing array..." # array2d_to_html(array2d) # #end #
require 'stock_quote' class Stock < ActiveRecord::Base has_many :closes def fetch_closes(days_old) results = StockQuote::Stock.history(symbol, Date.today - days_old, Date.today) results.each do |result| close = Close.find_or_create_by(stock_id: id, date: result.date) close.open = result.open close.close = result.close close.adj_close = result.adj_close close.high = result.high close.volume = result.volume close.save end end end
class Subject < ApplicationRecord belongs_to :education validates :title, presence: true end
class ContractTemplate < ActiveRecord::Base belongs_to :contract_partner belongs_to :interval has_many :contracts end
class AddColDiscountToLeaseBooking < ActiveRecord::Migration def change add_column :leasingx_lease_bookings, :discount, :tinyint, :default => 0 end end
# == Schema Information # Schema version: 3 # # Table name: groups # # id :integer(11) not null, primary key # name :string(255) # desc :text # permalink :string(255) # published :boolean(1) # gcategory_id :integer(11) # created_at :datetime # updated_at :datetime # class Group < ActiveRecord::Base acts_as_taggable has_many :services belongs_to :gcategory validates_presence_of :name, :gcategory end
class ApplicationController < ActionController::API PAGE_TOKEN = 'EAASZBQhnIYvQBAFcIn7pbyLxsam6absGnOAA0UZAReTA7bgppLyRVAZAStaOssxGUlqSpEV48bwhj7MDvOrZAAZCqhhP9epbxWdhMktLmMm9u0qoiAPVx5ON1WH7gIJxR5G4blpWVdKEGqCZBACaayyZAqtdCEkelzMSrCnRVw4rwZDZD' RESPONSES_HASH = { 'is nikhil stupid?' => 'Yes he is', 'what is the meaning of the universe?' => '42', 'toilet paper' => 'In the upstairs storage closet.', 'bills' => 'Ask Victor', 'fuck you' => 'No fuck you!' } # { # "token" => "BOkRhXHS0tcxjeZEfsOHMEnU", # "team_id" => "T2JTK19R7", # "api_app_id" => "A4T7LAP6Y", # "event"=> { # "type"=>"message", # "user"=>"U2K5X8VMH", # "text"=>"bills", # "ts"=>"1491099306.357268", # "channel"=>"C4AGYTZFA", # "event_ts"=>"1491099306.357268" # }, # "type"=>"event_callback", # "authed_users"=>["U2K5X8VMH"], # "event_id"=>"Ev4TSW834P", # "event_time"=>1491099306, # "application"=>{ # "token"=>"BOkRhXHS0tcxjeZEfsOHMEnU", # "team_id"=>"T2JTK19R7", # "api_app_id"=>"A4T7LAP6Y", # "event"=>{ # "type"=>"message", # "user"=>"U2K5X8VMH", # "text"=>"bills", # "ts"=>"1491099306.357268", # "channel"=>"C4AGYTZFA", # "event_ts"=>"1491099306.357268" # }, # "type"=>"event_callback", # "authed_users"=>["U2K5X8VMH"], # "event_id"=>"Ev4TSW834P", # "event_time"=>1491099306 # } # } def message return head 200 if params[:event][:subtype] == 'bot_message' # This is nikhils rule # if params[:event][:user] == 'U2KDGT9V2' # connection = Faraday.new( # url: 'https://hooks.slack.com', # ) # connection.post do |request| # request.url('/services/T2JTK19R7/B4T7QKH52/2ZmMXsKBLHtuU7yZCgU3MCIQ') # request.headers['Content-Type'] = 'application/json' # request.body = { text: 'Nope' }.to_json # end # # return head 200 # end text = params[:event].try(:[], :text) return head 200 unless response = RESPONSES_HASH[text.downcase] connection = Faraday.new( url: 'https://hooks.slack.com', ) connection.post do |request| request.url('/services/T2JTK19R7/B4T7QKH52/2ZmMXsKBLHtuU7yZCgU3MCIQ') request.headers['Content-Type'] = 'application/json' request.body = { text: response }.to_json end head 200 end # { # "object"=>"page", # "entry"=> [ # { # "id"=>"1323532757671429", # "time"=>1478582556893, # "messaging"=>[ # { # "sender"=>{ # "id"=>"1141243189291202" # }, # "recipient"=>{ # "id"=>"1323532757671429" # }, # "timestamp"=>1478582556765, # "message"=>{ # "mid"=>"mid.1478582556765:0038074b75", # "seq"=>7, # "text"=>"hi" # } # } # ] # } # ], # "application"=>{ # "object"=>"page", # "entry"=>[ # { # "id"=>"1323532757671429", # "time"=>1478582556893, # "messaging"=>[ # { # "sender"=>{ # "id"=>"1141243189291202" # }, # "recipient"=>{ # "id"=>"1323532757671429" # }, # "timestamp"=>1478582556765, # "message"=>{ # "mid"=>"mid.1478582556765:0038074b75", # "seq"=>7, # "text"=>"hi" # } # } # ] # } # ] # } # } def verify verify_token = params['token'] challenge = params['challenge'] puts verify_token puts challenge render json: { challenge: challenge } end end
class AddIndexToCreatorEvents < ActiveRecord::Migration def change add_index :events, [ :creator_id , :date ], unique: true end end
Rails.application.routes.draw do root to: 'categories#index' resources :categories, only: [:index, :show] do resources :recipes, only: [:new, :create] end resources :recipes, except: [:new, :create] do resources :ingredients, except: [:show] end get 'login', to: 'sessions#new' post 'login', to: 'sessions#create' delete 'logout', to: 'sessions#destroy' resources :users, only: [:show] get 'register', to: 'users#new' post 'register', to: 'users#create' resources :recipes, only: [:show] do resources :ratings, only: [:create] end post 'tokens', to: 'tokens#create' end
# frozen_string_literal: true class DiscountSerializer < ActiveModel::Serializer attributes :id, :kind, :name, :count, :price, :product_ids end
class Address < ActiveRecord::Base attr_accessible :name, :address, :neighbourhood, :description, :longitude, :latitude, :studio_id belongs_to :studio geocoded_by :address after_validation :geocode end
class AddUserIdToSurl < ActiveRecord::Migration[5.2] def change change_column :shortened_urls, :user_id, :integer, :null => false end end
class Job < ActiveRecord::Base #extend ::Geocoder::Model::ActiveRecord belongs_to :user has_many :comments validates :user_id, presence: true validates :job_title, presence: true validates :job_address, presence: true validates :job_contact_name, presence: true validates :job_contact_phone, presence: true validates :job_contact_email, presence: true #validates :job_request_date, presence: true validates :job_description, presence: true geocoded_by :job_address after_validation :geocode scope :sorted, lambda { order('created_at DESC') } mount_uploader :picture, PictureUploader validate :picture_size private def picture_size if picture.size > 5.megabytes errors.add(:picture, "Should be less than 5MB") end end end
class Teacher::QuestionsController < ApplicationController layout 'teacher' before_filter :get_teacher_and_course, :get_exam # GET /teacher/courses/1/exams/1/questions # GET /teacher/courses/1/exams/1/questions.json def index @questions = Question.where(:exam_id => @exam.id).order(:position).page(params[:page]) respond_to do |format| format.html # index.html.erb format.json { render :json => @questions } end end # GET /teacher/courses/1/exams/1/questions/1 # GET /teacher/courses/1/exams/1/questions/1.json def show @question = @exam.questions.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render :json => @question } end end # GET /teacher/courses/1/exams/1/questions/new # GET /teacher/courses/1/exams/1/questions/new.json def new @question = Question.new respond_to do |format| format.html # new.html.erb format.json { render :json => @question } end end # GET /teacher/courses/1/exams/1/questions/1/edit def edit @question = @exam.questions.find(params[:id]) end # POST /teacher/courses/1/exams/1/questions # POST /teacher/courses/1/exams/1/questions.json def create @question = Question.new(params[:question]) @exam.questions << @question respond_to do |format| if @question.save format.html { redirect_to [:teacher, @course, @exam, @question], :notice => 'Question was successfully created.' } format.json { render :json => @question, :status => :created, :location => @question } else format.html { render :action => "new" } format.json { render :json => @question.errors, :status => :unprocessable_entity } end end end # PUT /teacher/courses/1/exams/1/questions/1 # PUT /teacher/courses/1/exams/1/questions/1.json def update @question = @exam.questions.find(params[:id]) respond_to do |format| if @question.update_attributes(params[:question]) format.html { redirect_to [:teacher, @course, @exam, @question], :notice => 'Question was successfully updated.' } format.json { head :no_content } else format.html { render :action => "edit" } format.json { render :json => @question.errors, :status => :unprocessable_entity } end end end # DELETE /teacher/courses/1/exams/1/questions/1 # DELETE /teacher/courses/1/exams/1/questions/1.json def destroy @question = @exam.questions.find(params[:id]) @question.destroy respond_to do |format| format.html { redirect_to teacher_course_exam_questions_url(@course, @exam) } format.json { head :no_content } end end # GET /teacher/course/1/exams/1/questions/1/question def question @question = @exam.questions.find(params[:id]) send_data(@question.question_img, :type => @question.question_content_type, :disposition => "inline") end # GET /teacher/course/1/exams/1/questions/1/choices def choices @question = @exam.questions.find(params[:id]) send_data(@question.choices_img, :type => @question.choices_content_type, :disposition => "inline") end # POST /teacher/course/1/exams/1/questions/1/move_up def move_up @question = @exam.questions.find(params[:id]) @question.move_higher redirect_to teacher_course_exam_questions_path(@course, @exam) end # POST /teacher/course/1/exams/1/questions/1/move_down def move_down @question = @exam.questions.find(params[:id]) @question.move_lower redirect_to teacher_course_exam_questions_path(@course, @exam) end end
json.array!(@clientes) do |cliente| json.extract! cliente, :id, :name, :description, :nif, :address, :city, :telephone, :email json.url cliente_url(cliente, format: :json) end
# frozen_string_literal: true module RubyNext module Language module Rewriters class EndlessMethod < Base SYNTAX_PROBE = "obj = Object.new; def obj.foo() = 42" MIN_SUPPORTED_VERSION = Gem::Version.new("2.8.0") def on_def_e(node) context.track! self replace(node.loc.assignment, "; ") insert_after(node.loc.expression, "; end") process( node.updated( :def, node.children ) ) end def on_defs_e(node) context.track! self replace(node.loc.assignment, "; ") insert_after(node.loc.expression, "; end") process( node.updated( :defs, node.children ) ) end end end end end
class AddNicknameToFacebookUsers < ActiveRecord::Migration def change add_column :facebook_users, :nickname, :string end end
require "rails_helper" RSpec.describe Operation, type: :model do it { is_expected.to belong_to(:sleep) } it { is_expected.to belong_to(:user) } it { is_expected.to define_enum_for(:operation_type).with_values(stop: 0, start: 1) } context "when all attributes are valid except for redundant sleep_id" do context "when operation is created on Operation model" do let(:operation) { build(:operation, operation_type: "start", sleep_id: 1) } it "returns error message for sleep" do expect(operation).not_to be_valid expect(operation.errors.messages.count).to eq(2) expect(operation.errors.messages[:sleep]).to eq([I18n.t("errors.messages.required")]) expect(operation.errors.messages[:sleep_id]).to eq([I18n.t("activerecord.errors.messages.redundant")]) end end context "when operation is created through Sleep model's association" do let(:sleep) { create(:sleep) } it "returns error message for sleep" do operation_start = sleep.build_operation_start(operation_type: "start", operated_at: 10.hours.ago, user: sleep.user) operation_stop = sleep.build_operation_start(operation_type: "stop", operated_at: 10.hours.ago, user: sleep.user) # puts operation_start.errors.messages expect(operation_start).not_to be_valid expect(operation_start.errors.messages.count).to eq(1) expect(operation_start.errors.messages[:sleep_id]).to eq([I18n.t("activerecord.errors.messages.redundant")]) expect(operation_stop).not_to be_valid expect(operation_stop.errors.messages.count).to eq(1) expect(operation_stop.errors.messages[:sleep_id]).to eq([I18n.t("activerecord.errors.messages.redundant")]) end end end end
require 'spec_helper' describe "Adding and removing notifications" do let(:user) { User.create(username: "Test") } let(:message_notification) { NotifyMe::Notification.create(:message => "This is a test msg")} it "stores new notifications" do user.notifications << message_notification user.notifications.reload.should == [message_notification] end it "removes existing notifications" do user.notifications << message_notification user.notifications.delete message_notification user.notifications.reload.should == [] end end
Given /the following events exist/ do |events_table| events_table.hashes.each do |event| Event.create! event end end Then /(.*) seed events should exist/ do | n_seeds | Event.count.should be n_seeds.to_i end Then /I should see the correct number of events cards/ do num_events = Event.all.size num_events_cards = all(:css, ".card").size expect(num_events_cards).to eq num_events end Then /I should see the correct number of events with a search: (.*)/ do | query | num_events = Event.search_description(query, nil).size num_events_cards = all(:css, ".card").size expect(num_events_cards).to eq num_events end Then /I should see "(.*)" before "(.*)"/ do |e1, e2| expect(page.body).to match(/.*#{e1}.*#{e2}.*/m) end
# encoding: UTF-8 module API module V1 class Presentations < API::V1::Base helpers API::Helpers::V1::PresentationsHelpers helpers API::Helpers::V1::SharedParamsHelpers helpers API::Helpers::V1::SharedServiceActionsHelpers before do authenticate_user end namespace :presentations do desc 'Create a new presentation for LearningTrack' params do use :new_presentation group :presentation, type: Hash do requires :learning_track_id end end post do new_learning_track_presentation_service_response(current_user, params) end route_param :id do namespace :slides do desc 'Create a new PresentationSlide for Presetation' params do use :new_presentation_slide end post do params[:slide].merge!(presentation_id: params[:id]) new_presentation_slide_service_response(current_user, params) end route_param :slide_id do desc 'Reorder a slide inside a presentation' params do use :slide_reorder end put :reorder do slide = current_user.slides.find_by(id: params[:slide_id]) slide_reorder_service_response(current_user, slide, params) end end end end end end end end
class Contract < ActiveRecord::Base audited attr_accessor :step, :subject, :email, :cc, :cco, :message has_and_belongs_to_many :users, :validate => false belongs_to :client belongs_to :proposal belongs_to :user belongs_to :comercial_agent, :class_name => 'User' belongs_to :intermediary, :class_name => 'User' # validate :require_at_least_one_responsible, if: Proc.new { |contract| contract.step == 1 || contract.step == "1" } has_many :contract_responsibles, :validate => false, dependent: :destroy accepts_nested_attributes_for :contract_responsibles, allow_destroy: true validates_associated :contract_responsibles, if: Proc.new { |contract| contract.step == 1 || contract.step == "1" } has_many :contract_responsible_financials, :validate => false, dependent: :destroy accepts_nested_attributes_for :contract_responsible_financials, allow_destroy: true validates_associated :contract_responsible_financials, if: Proc.new { |contract| contract.step == 2 || contract.step == "2" } has_many :contract_payments, :validate => false, dependent: :destroy accepts_nested_attributes_for :contract_payments, allow_destroy: true validates_associated :contract_payments, if: Proc.new { |contract| contract.step == 2 || contract.step == "2" } has_many :attachments, :as => :attachmentable, dependent: :destroy accepts_nested_attributes_for :attachments, allow_destroy: true, :reject_if => proc { |attrs| attrs[:attachment].blank? } validates_presence_of :proposal_id, if: Proc.new { |contract| contract.step == 1 || contract.step == "1" } def get_phones text = "" if self.contract_responsibles && self.contract_responsibles.length > 0 self.contract_responsibles.each do |cr| if cr.phone_users && cr.phone_users.length > 0 cr.phone_users.each do |phone| text += phone.phone + ", " end end end end return text end def get_social_name if self.proposal return self.proposal.social_name else return "Sem razão social" end end # Mensagens de notificações def self.notification_new_contract(contract, user) return 'Contrato <b>'+Contract.get_text_contract(contract)+'</b> cadastrado por <b>'+user.name+'</b>' end def self.notification_edit_contract(contract, user) return 'Contrato <b>'+Contract.get_text_contract(contract)+'</b> editado por <b>'+user.name+'</b>' end def self.notification_delete_contract(contract, user) return 'Contrato <b>'+Contract.get_text_contract(contract)+'</b> removido por <b>'+user.name+'</b>' end def self.get_text_contract(contract) if contract && contract.proposal return contract.proposal.social_name end return contract.title end # Rotina de atualização dos descontos nos contratos def self.update_values_contracts contracts = Contract.all contracts.each do |contract| update_monthly_payment(contract) update_comission(contract) end end def self.update_monthly_payment(contract) discount = true if contract.monthly_discount && contract.monthly_discount.length > 0 if contract.monthly_initial_date && contract.monthly_final_date if !Time.zone.today.between?(contract.monthly_initial_date, contract.monthly_final_date) discount = false end elsif contract.monthly_initial_date if contract.monthly_initial_date > Time.zone.today discount = false end elsif contract.monthly_final_date if contract.monthly_final_date < Time.zone.today discount = false end else discount = false end if discount discount = return_string_like_number(contract.monthly_discount) value = return_string_like_number(contract.monthly_fixed_payment) value_calculed = value.to_f - discount.to_f value_formatted = return_number_like_string(value_calculed.to_s, 1) contract.update_column(:monthly_payment, value_formatted) end else discount = false end if !discount contract.update_column(:monthly_payment, contract.monthly_fixed_payment) end end def self.update_comission(contract) discount = true if contract.comission_discount && contract.comission_discount.length > 0 if contract.comission_initial_date && contract.comission_final_date if !Time.zone.today.between?(contract.comission_initial_date, contract.comission_final_date) discount = false end elsif contract.comission_initial_date if contract.comission_initial_date > Time.zone.today discount = false end elsif contract.comission_final_date if contract.comission_final_date < Time.zone.today discount = false end else discount = false end if discount discount = return_string_like_number(contract.comission_discount) value = return_string_like_number(contract.comission_fixed_payment) value_calculed = value.to_f - discount.to_f value_formatted = return_number_like_string(value_calculed.to_s, 2) contract.update_column(:comission_payment, value_formatted) end else discount = false end if !discount contract.update_column(:comission_payment, contract.comission_fixed_payment) end end def self.return_string_like_number(value) if value value = value.gsub('R$ ','') value = value.gsub('%','') value = value.gsub('.','') value = value.gsub(',','.') end return value end def self.return_number_like_string(value, type) if value temp = value.to_s.split('.') if temp[0] && temp[0].length == 1 initial = '0'+temp[0] else initial = temp[0] end if temp[1] && temp[1].length == 1 decimal = temp[1]+'0' elsif temp[1] decimal = temp[1] else decimal = '0' end if type == 1 value = 'R$ '+initial+','+decimal elsif type == 2 value = initial+','+decimal+'%' end end return value end private def require_at_least_one_responsible errors.add(:base,"Deve haver ao menos 1 intermediador") if self.users.blank? end end
class Post < ActiveRecord::Base belongs_to :category validates_associated :category validates :email, presence: true validates :title, presence: true validates :title, length: { in: 5..100 } validates :body, presence: true validates :price, presence: true validates :price, numericality: { greater_than: 0 } before_create :encrypt_url def encrypt_url self.edit_key = Digest::SHA256.hexdigest(Time.now.to_s + self.title + rand(1..99).to_s + ('a'..'z').to_a.sample) end end
MultipleMan.configure do |config| # A connection string to your local server. Defaults to localhost. config.connection = { addresses: ['192.168.99.100:5673', '192.168.99.100:5674', '192.168.99.100:5675'] } # The topic name to push to. If you have multiple # multiple man apps, this should be unique per application. Publishers # and subscribers should always use the same topic. config.topic_name = 'rabbit_topic' # The application name (used for subscribers) - defaults to your # Rails application name if you're using rails config.app_name = 'RabbitPost' # Specify what should happen when MultipleMan # encounters an exception. config.on_error do |exception| ErrorLogger.log(exception) end # Add opts that go directly to the bunny constructor (Advanced) # config.bunny_opts = { # tls_ca_certificates: ['/usr/lib/ssl/certs/cacert.pem'] # } # Add opts that are used when creating the exchange config.exchange_opts = { durable: true } # Where you want to log errors to. Should be an instance of Logger # Defaults to the Rails logger (for Rails) or STDOUT otherwise. config.logger = Logger.new(STDOUT) end
Dado('que o usuário esteja na pagina inicial do google') do @google_page = GooglePage.new @google_page.load end Quando('realizar a pesquisa {string}') do |pesquisa| @google_page.pesquisar(pesquisa) @pesquisa = pesquisa end Então('sistema deve retornar os resultados de acordo com o que foi pesquisado') do expect(page).to have_content @pesquisa end
require_relative 'spec_helper' require 'pp' describe 'App' do let(:headers) { { "Content-Type": "application/json" } } let(:realm) { ENV['quickbooks_realm'] } let(:secret) { ENV['quickbooks_access_secret'] } let(:token) { ENV['quickbooks_access_token'] } let(:order) { { "email": nil, "status": "1", "totals": { "tax": 0.0, "item": 173.7, "order": 173.7, "payment": 173.7, "discount": 0.0, "shipping": 0.0 }, "channel": "3DCart", "payments": [ { "amount": 173.7, "status": "1", "payment_method": "Discover" } ], "line_items": [ { "name": "1234321", "quantity": 1.0, "product_id": "1234321", "line_item_price": 30 } ], "adjustments": [ { "name": "Tax", "value": 0.0 }, { "name": "Shipping", "value": 0.0 }, { "name": "Discounts", "value": 0.0 } ], "tax_line_items": [ { "name": "Sales Tax", "amount": 0.0 } ], "billing_address": { "city": "Chicopee", "phone": "800-700-1111", "state": "MA", "country": "US", "zipcode": "01013", "address1": "21 Main Drive", "address2": "", "lastname": "Salomm", "firstname": "Marcmm" }, "three_d_cart_id": 14888, "shipping_address": { "city": "Chicopee", "phone": "800-700-1111", "state": "MA", "country": "US", "zipcode": "01013", "address1": "21 Main Drive", "address2": "", "lastname": "Salo", "firstname": "Marc" }, "shipping_line_items": [ { "name": "By Value", "amount": 0.0 } ], } } let(:new_order) { { "email": nil, "status": "1", "totals": { "tax": 0.0, "item": 173.7, "order": 173.7, "payment": 173.7, "discount": 0.0, "shipping": 0.0 }, "channel": "3DCart", "payments": [ { "amount": 173.7, "status": "1", "payment_method": "Discover" } ], "line_items": [ { "name": "09876", "quantity": 1.0, "product_id": "09876", "line_item_price": 30 } ], "adjustments": [ { "name": "Tax", "value": 0.0 }, { "name": "Shipping", "value": 0.0 }, { "name": "Discounts", "value": 0.0 } ], "tax_line_items": [ { "name": "Sales Tax", "amount": 0.0 } ], "billing_address": { "city": "Chicopee", "phone": "800-700-1111", "state": "MA", "country": "US", "zipcode": "01013", "address1": "21 Main Drive", "address2": "", "lastname": "Rogers", "firstname": "Steve" }, "three_d_cart_id": 14888, "shipping_address": { "city": "Chicopee", "phone": "800-700-1111", "state": "MA", "country": "US", "zipcode": "01013", "address1": "21 Main Drive", "address2": "", "lastname": "Salo", "firstname": "Marc" }, "shipping_line_items": [ { "name": "By Value", "amount": 0.0 } ], } } let(:existing_order) { { "number": 1080, "email": nil, "status": "1", "totals": { "tax": 0.0, "item": 173.7, "order": 173.7, "payment": 173.7, "discount": 0.0, "shipping": 0.0 }, "channel": "3DCart", "payments": [ { "amount": 173.7, "status": "1", "payment_method": "Discover" } ], "line_items": [ { "name": "1234321", "quantity": 1.0, "product_id": "1234321", "line_item_price": 30 } ], "adjustments": [ { "name": "Tax", "value": 0.0 }, { "name": "Shipping", "value": 0.0 }, { "name": "Discounts", "value": 0.0 } ], "tax_line_items": [ { "name": "Sales Tax", "amount": 0.0 } ], "billing_address": { "city": "Chicopee", "phone": "800-700-1111", "state": "MA", "country": "US", "zipcode": "01013", "address1": "21 Main Drive", "address2": "", "lastname": "Salomm", "firstname": "Marcmm" }, "three_d_cart_id": 14888, "shipping_address": { "city": "Chicopee", "phone": "800-700-1111", "state": "MA", "country": "US", "zipcode": "01013", "address1": "21 Main Drive", "address2": "", "lastname": "Salo", "firstname": "Marc" }, "shipping_line_items": [ { "name": "By Value", "amount": 0.0 } ], } } include Rack::Test::Methods def app QuickbooksEndpoint end describe "get_orders", vcr: true do it "returns 200 and summary with id for default configs" do post '/get_orders', { "request_id": "25d4847a-a9ba-4b1f-9ab1-7faa861a4e67", "parameters": { "quickbooks_realm": realm, "quickbooks_access_token": token, "quickbooks_access_secret": secret, "quickbooks_since": "2019-01-13T14:50:22-08:00", "quickbooks_page_num": "1", }, }.to_json, headers response = JSON.parse(last_response.body) expect(last_response.status).to eq 206 expect(response["summary"]).to be_instance_of(String) expect(response["orders"].count).to eq 50 first = response["orders"].first totals = first["totals"] expect(totals["tax"]).to eq "0.0" expect(totals["shipping"]).to eq "0.0" expect(totals["discount"]).to eq "0.0" expect(totals["item"]).to eq "22.5" expect(totals["order"]).to eq "22.50" end it "returns 200 and accepts a quickbooks_prefix param" do post '/get_orders', { "request_id": "25d4847a-a9ba-4b1f-9ab1-7faa861a4e67", "parameters": { "quickbooks_realm": realm, "quickbooks_access_token": token, "quickbooks_access_secret": secret, "quickbooks_since": "2019-01-13T14:50:22-08:00", "quickbooks_page_num": "1", "quickbooks_prefix": "FL-", }, }.to_json, headers response = JSON.parse(last_response.body) expect(last_response.status).to eq 206 expect(response["summary"]).to be_instance_of(String) expect(response["orders"].count).to eq 50 # Original doc_number of TEST115 first = response["orders"][0] expect(first["number"]).to eq "TEST115" # Original doc_number of FL-1104 order = response["orders"][7] expect(order["number"]).to eq "1104" end end describe "add_order", vcr: true do it "add a quickbooks_prefix" do merged_order = order.merge({ number: "23" }) post '/add_order', { "request_id": "25d4847a-a9ba-4b1f-9ab1-7faa861a4e67", "parameters": { "quickbooks_realm": realm, "quickbooks_access_token": token, "quickbooks_access_secret": secret, "quickbooks_track_inventory": "1", "quickbooks_account_name": "Sales of Product Income", "quickbooks_web_orders_users": "1", "quickbooks_payment_method_name": "[{\"shopify_payments\":\"MasterCard\", \"PayPal\":\"PayPal\", \"Visa\":\"Visa\", \"Discover\":\"Discover\", \"American Express\":\"American Express\", \"None\":\"Cash\", \"Cash\":\"Cash\", \"Money Order\":\"Cash\", \"Check Payments\":\"Cash\"}]", "quickbooks_inventory_account": "Inventory Asset", "quickbooks_create_new_product": "0", "quickbooks_cogs_account": "Cost of Goods Sold", "quickbooks_prefix": "QBO-", }, "order": merged_order }.to_json, headers response = JSON.parse(last_response.body) expect(last_response.status).to eq 200 expect(response["summary"]).to be_instance_of(String) end it "returns 200 and summary with id for default configs" do skip("Transaction date is prior to start date for inventory item") post '/add_order', { "request_id": "25d4847a-a9ba-4b1f-9ab1-7faa861a4e67", "parameters": { "quickbooks_realm": realm, "quickbooks_access_token": token, "quickbooks_access_secret": secret, "quickbooks_tax_item": "product_tax", "quickbooks_discount_item": "discount", "quickbooks_shipping_item": "shipping", "quickbooks_track_inventory": "1", "quickbooks_account_name": "Sales of Product Income", "quickbooks_web_orders_users": "1", "quickbooks_payment_method_name": "[{\"shopify_payments\":\"MasterCard\", \"PayPal\":\"PayPal\", \"Visa\":\"Visa\", \"Discover\":\"Discover\", \"American Express\":\"American Express\", \"None\":\"Cash\", \"Cash\":\"Cash\", \"Money Order\":\"Cash\", \"Check Payments\":\"Cash\"}]", "quickbooks_inventory_account": "Inventory Asset", "quickbooks_create_new_product": "1", "quickbooks_cogs_account": "Cost of Goods Sold" }, "order": order }.to_json, headers response = JSON.parse(last_response.body) expect(last_response.status).to eq 200 expect(response["summary"]).to be_instance_of(String) end it "returns 200 when quickbooks_payment_method_name in order" do merged_order = order.merge({ "quickbooks_payment_method_name": "American Express" }) post '/add_order', { "request_id": "25d4847a-a9ba-4b1f-9ab1-7faa861a4e67", "parameters": { "quickbooks_realm": realm, "quickbooks_access_token": token, "quickbooks_access_secret": secret, "quickbooks_tax_item": "product_tax", "quickbooks_discount_item": "discount", "quickbooks_shipping_item": "shipping", "quickbooks_track_inventory": "1", "quickbooks_account_name": "Sales of Product Income", "quickbooks_web_orders_users": "1", "quickbooks_inventory_account": "Inventory Asset", "quickbooks_create_new_product": "0", "quickbooks_cogs_account": "Cost of Goods Sold" }, "order": merged_order }.to_json, headers response = JSON.parse(last_response.body) expect(last_response.status).to eq 200 expect(response["summary"]).to be_instance_of(String) end it "returns 200 when tax, discount, and shipping item in order" do merged_order = order.merge({ "quickbooks_tax_item": "product_tax", "quickbooks_discount_item": "discount", "quickbooks_shipping_item": "shipping", }) post '/add_order', { "request_id": "25d4847a-a9ba-4b1f-9ab1-7faa861a4e67", "parameters": { "quickbooks_realm": realm, "quickbooks_access_token": token, "quickbooks_access_secret": secret, "quickbooks_track_inventory": "1", "quickbooks_account_name": "Sales of Product Income", "quickbooks_web_orders_users": "1", "quickbooks_payment_method_name": "[{\"shopify_payments\":\"MasterCard\", \"PayPal\":\"PayPal\", \"Visa\":\"Visa\", \"Discover\":\"Discover\", \"American Express\":\"American Express\", \"None\":\"Cash\", \"Cash\":\"Cash\", \"Money Order\":\"Cash\", \"Check Payments\":\"Cash\"}]", "quickbooks_inventory_account": "Inventory Asset", "quickbooks_create_new_product": "0", "quickbooks_cogs_account": "Cost of Goods Sold" }, "order": merged_order }.to_json, headers response = JSON.parse(last_response.body) expect(last_response.status).to eq 200 expect(response["summary"]).to be_instance_of(String) end it "returns 200 when deposit to account name and account name" do merged_order = order.merge({ "quickbooks_deposit_to_account_name": "Undeposited Funds", "quickbooks_account_name": "Sales of Product Income", }) post '/add_order', { "request_id": "25d4847a-a9ba-4b1f-9ab1-7faa861a4e67", "parameters": { "quickbooks_realm": realm, "quickbooks_access_token": token, "quickbooks_access_secret": secret, "quickbooks_track_inventory": "1", "quickbooks_web_orders_users": "1", "quickbooks_tax_item": "product_tax", "quickbooks_discount_item": "discount", "quickbooks_shipping_item": "shipping", "quickbooks_payment_method_name": "[{\"shopify_payments\":\"MasterCard\", \"PayPal\":\"PayPal\", \"Visa\":\"Visa\", \"Discover\":\"Discover\", \"American Express\":\"American Express\", \"None\":\"Cash\", \"Cash\":\"Cash\", \"Money Order\":\"Cash\", \"Check Payments\":\"Cash\"}]", "quickbooks_create_new_product": "0", "quickbooks_inventory_account": "Inventory Asset", "quickbooks_cogs_account": "Cost of Goods Sold" }, "order": merged_order }.to_json, headers response = JSON.parse(last_response.body) expect(last_response.status).to eq 200 expect(response["summary"]).to be_instance_of(String) end it "returns 200 when inventory and cogs account in order" do order["line_items"] = [ { "name": "new item 2", "quantity": 1.0, "sku": "new-item-sku-2", "line_item_price": 30 } ] order["placed_on"] = Time.now merged_order = order.merge({ "quickbooks_inventory_account": "Inventory Asset", "quickbooks_cogs_account": "Cost of Goods Sold" }) post '/add_order', { "request_id": "25d4847a-a9ba-4b1f-9ab1-7faa861a4e67", "parameters": { "quickbooks_realm": realm, "quickbooks_access_token": token, "quickbooks_access_secret": secret, "quickbooks_track_inventory": "1", "quickbooks_web_orders_users": "1", "quickbooks_tax_item": "product_tax", "quickbooks_discount_item": "discount", "quickbooks_shipping_item": "shipping", "quickbooks_payment_method_name": "[{\"shopify_payments\":\"MasterCard\", \"PayPal\":\"PayPal\", \"Visa\":\"Visa\", \"Discover\":\"Discover\", \"American Express\":\"American Express\", \"None\":\"Cash\", \"Cash\":\"Cash\", \"Money Order\":\"Cash\", \"Check Payments\":\"Cash\"}]", "quickbooks_create_new_product": "1", "quickbooks_deposit_to_account_name": "Undeposited Funds", "quickbooks_account_name": "Sales of Product Income", }, "order": merged_order }.to_json, headers response = JSON.parse(last_response.body) expect(last_response.status).to eq 200 expect(response["summary"]).to be_instance_of(String) end it "returns 200 when track_inventory, create_new_customers, and create_new_product in order" do merged_order = new_order.merge({ "quickbooks_track_inventory": "1", "quickbooks_create_new_product": "1", "quickbooks_create_new_customers": "1" }) post '/add_order', { "request_id": "25d4847a-a9ba-4b1f-9ab1-7faa861a4e67", "parameters": { "quickbooks_realm": realm, "quickbooks_access_token": token, "quickbooks_access_secret": secret, "quickbooks_web_orders_users": "0", "quickbooks_tax_item": "product_tax", "quickbooks_discount_item": "discount", "quickbooks_shipping_item": "shipping", "quickbooks_payment_method_name": "[{\"shopify_payments\":\"MasterCard\", \"PayPal\":\"PayPal\", \"Visa\":\"Visa\", \"Discover\":\"Discover\", \"American Express\":\"American Express\", \"None\":\"Cash\", \"Cash\":\"Cash\", \"Money Order\":\"Cash\", \"Check Payments\":\"Cash\"}]", "quickbooks_deposit_to_account_name": "Undeposited Funds", "quickbooks_account_name": "Sales of Product Income", "quickbooks_inventory_account": "Inventory Asset", "quickbooks_cogs_account": "Cost of Goods Sold" }, "order": merged_order }.to_json, headers response = JSON.parse(last_response.body) expect(last_response.status).to eq 200 expect(response["summary"]).to be_instance_of(String) end end describe "update_order", vcr: true do it "uses quickbooks_prefix" do merged_order = existing_order.merge({ "number": "23" }) post '/update_order', { "request_id": "25d4847a-a9ba-4b1f-9ab1-7faa861a4e67", "parameters": { "quickbooks_create_or_update": "1", "quickbooks_realm": realm, "quickbooks_access_token": token, "quickbooks_access_secret": secret, "quickbooks_tax_item": "product_tax", "quickbooks_discount_item": "discount", "quickbooks_shipping_item": "shipping", "quickbooks_track_inventory": "1", "quickbooks_account_name": "Sales of Product Income", "quickbooks_web_orders_users": "1", "quickbooks_payment_method_name": "[{\"shopify_payments\":\"MasterCard\", \"PayPal\":\"PayPal\", \"Visa\":\"Visa\", \"Discover\":\"Discover\", \"American Express\":\"American Express\", \"None\":\"Cash\", \"Cash\":\"Cash\", \"Money Order\":\"Cash\", \"Check Payments\":\"Cash\"}]", "quickbooks_inventory_account": "Inventory Asset", "quickbooks_create_new_product": "0", "quickbooks_cogs_account": "Cost of Goods Sold", "quickbooks_prefix": "QBO-" }, "order": merged_order }.to_json, headers response = JSON.parse(last_response.body) pp response expect(last_response.status).to eq 200 expect(response["summary"]).to be_instance_of(String) end it "returns 200 and summary with id for default configs" do post '/update_order', { "request_id": "25d4847a-a9ba-4b1f-9ab1-7faa861a4e67", "parameters": { "quickbooks_realm": realm, "quickbooks_access_token": token, "quickbooks_access_secret": secret, "quickbooks_tax_item": "product_tax", "quickbooks_discount_item": "discount", "quickbooks_shipping_item": "shipping", "quickbooks_track_inventory": "1", "quickbooks_account_name": "Sales of Product Income", "quickbooks_web_orders_users": "1", "quickbooks_payment_method_name": "[{\"shopify_payments\":\"MasterCard\", \"PayPal\":\"PayPal\", \"Visa\":\"Visa\", \"Discover\":\"Discover\", \"American Express\":\"American Express\", \"None\":\"Cash\", \"Cash\":\"Cash\", \"Money Order\":\"Cash\", \"Check Payments\":\"Cash\"}]", "quickbooks_inventory_account": "Inventory Asset", "quickbooks_create_new_product": "0", "quickbooks_cogs_account": "Cost of Goods Sold" }, "order": existing_order }.to_json, headers response = JSON.parse(last_response.body) expect(last_response.status).to eq 200 expect(response["summary"]).to be_instance_of(String) end it "returns 200 and when setting quickbooks_create_or_update" do merged_order = existing_order.merge({ "number": "404-does_not_exist" }) post '/update_order', { "request_id": "25d4847a-a9ba-4b1f-9ab1-7faa861a4e67", "parameters": { "quickbooks_create_or_update": "1", "quickbooks_realm": realm, "quickbooks_access_token": token, "quickbooks_access_secret": secret, "quickbooks_tax_item": "product_tax", "quickbooks_discount_item": "discount", "quickbooks_shipping_item": "shipping", "quickbooks_track_inventory": "1", "quickbooks_account_name": "Sales of Product Income", "quickbooks_web_orders_users": "1", "quickbooks_payment_method_name": "[{\"shopify_payments\":\"MasterCard\", \"PayPal\":\"PayPal\", \"Visa\":\"Visa\", \"Discover\":\"Discover\", \"American Express\":\"American Express\", \"None\":\"Cash\", \"Cash\":\"Cash\", \"Money Order\":\"Cash\", \"Check Payments\":\"Cash\"}]", "quickbooks_inventory_account": "Inventory Asset", "quickbooks_create_new_product": "0", "quickbooks_cogs_account": "Cost of Goods Sold" }, "order": merged_order }.to_json, headers response = JSON.parse(last_response.body) expect(last_response.status).to eq 200 expect(response["summary"]).to be_instance_of(String) end end end
require "horseman/dom/document" module Horseman class Response attr_reader :body, :headers, :document def initialize(body, headers={}) @body = body @headers = headers @document = Dom::Document.new(@body) end def[](key) @headers[key] end end end
class Rol < ActiveRecord::Base validates_presence_of :nombre, :message => "no debe ser vacío" def self.nombres roles_conjunto = Rol.find(:all) @roles = Array.new for rol in roles_conjunto @roles << rol.nombre end @roles end end
class Contest < ApplicationRecord validates :battlepets, length: {minimum: 2, message: "are too short (minimum is 2)"} validates_presence_of :contest_type validates_inclusion_of :contest_type, :in => %w( simple ) validates :battlepet_traits, length: {minimum: 1, maximum: 1, message: "are too long or too short (maximum is 1, minimum is 1)"} end
#encoding: utf-8 class FriendMailer < ActionMailer::Base add_template_helper(ApplicationHelper) default from: APP_DATA["email"]["from"]["normal"] def invite(params) mail(:to => params[:email], :subject => params[:subject]) { |format| format.html { render :text => params[:body] }} end end
class AddTwitterIdToCars < ActiveRecord::Migration def change add_column :cars, :twitter_id, :integer, :after => :meter_fare add_column :cars, :twitter_name, :string, :after => :twitter_id add_column :cars, :access_token, :string, :after => :twitter_name end end
# Keep track of the conditions for a query. This is needed due to where clauses # being chainable. module Geotab module Concerns module Conditionable def conditions @conditions ||= {} end # Conditions should be cleared after each .all class so that new # queries do not use previous queries' where clauses.s def clear_conditions @conditions = {} end # Format the conditions hash according to Geotab spec. A normal hash # looks like: {'id':'XXXX'} def formatted_conditions conditions.to_s.gsub(/\s*=>\s*/, ":").gsub("\"", "'") end end end end
class Creditcard < ApplicationRecord validates :number, presence: true, length: {in: 16..19}, numericality: true validates :expiration, presence: true, numericality: true validates :cvc, presence: true, length: {in: 3..4}, numericality: true validates :avs_street, presence: true validates :avs_zip, presence: true, numericality: true validates :cardholder, presence: true end
class Micropost < ApplicationRecord belongs_to :user validates :content,length:{maximum:10}, presence:true end
class CreatePushes < ActiveRecord::Migration[5.0] def change create_table :pushes do |t| t.jsonb :data, null: false, default: {} t.timestamps end end end
class Patron attr_reader(:name, :id) define_method(:initialize) do |attributes| @name = attributes.fetch(:name) @id = attributes[:id] end define_singleton_method(:all) do patrons = [] returned_patrons = DB.exec("SELECT * FROM patrons ;") returned_patrons.each() do |patron| name = patron.fetch("name") id = patron.fetch('id').to_i() patrons.push(Patron.new({:name => name, :id => id})) end patrons end define_method(:save) do result = DB.exec("INSERT INTO patrons (name) VALUES ('#{@name}') RETURNING id ;") @id = result.first().fetch('id').to_i() end define_method(:==) do |other_patron| self.name() == other_patron.name() end define_singleton_method(:find) do |patron_id| @id = patron_id result = DB.exec("SELECT * FROM patrons WHERE id = #{@id} ;") @name = result.first().fetch('name') Patron.new({:name => @name, :id => @id}) end define_method(:update) do |attributes| @name = attributes.fetch(:name, @name) DB.exec("UPDATE patrons SET name = '#{@name}' WHERE id = #{self.id()};") end define_method(:add_ticket) do |ticket_id| DB.exec("INSERT INTO tickets (patron_id) VALUES (#{self.id()}) WHERE id = #{ticket_id};") end define_method(:tickets) do tickets = [] patron_tickets = DB.exec("SELECT * FROM tickets WHERE patron_id = #{self.id()}") patron_tickets.each() do |ticket| id = ticket.fetch('id').to_i() patron_id = self.id() tickets.push(Ticket.new({:id => id, :patron_id => patron_id})) end tickets.count() end define_method(:delete) do DB.exec("DELETE FROM patrons WHERE id = #{self.id()} ;") end end
# frozen_string_literal: true module Vedeu # This module is the direct interface between Vedeu and your # terminal/ console, via Ruby's IO core library. # module Terminal end # Terminal # :nocov: # See {file:docs/events/view.md#\_resize_} Vedeu.bind(:_resize_, delay: 0.25) { Vedeu.resize } # :nocov: end # Vedeu require 'vedeu/terminal/mode' require 'vedeu/terminal/terminal'
class Image < ActiveRecord::Base attr_accessible :description, :title, :image_object belongs_to :image_reference, polymorphic: true has_attached_file :image_object, :styles => { :portrait => "300X600", :thumb => "75x75>" }, :storage => :s3, :s3_credentials => "#{Rails.root}/config/amazon_s3.yml", :path => ":class/:attachment/:id-:basename-:style.:extension" #:bucket => "natures-plate-dev", #:s3_permissions => :private validates_attachment_presence :image_object validates_attachment_size :image_object, :less_than => 5.megabytes validates_attachment_content_type :image_object, :content_type => ['image/jpeg', 'image/png', 'image/gif'] end
module Helpers module Authentication def sign_in(user_arg) visit login_path fill_in 'Email', with: user_arg.email fill_in 'Password', with: user_arg.password click_button 'Log in' end def incorrect_sign_in(user_arg) visit login_path fill_in 'Email', with: user_arg.email fill_in 'Password', with: 'incorrect_password' click_button 'Log in' end def sign_up(username, email, password, password_confirmation) visit signup_path fill_in 'Username', with: username fill_in 'Email', with: email fill_in 'Password', with: password fill_in 'confirm your password', with: password_confirmation click_button 'Create User' end end end
class AddRightToUserRegions < ActiveRecord::Migration[5.0] def change add_column :user_regions, :right, :boolean end end
class RestoAdmin::MenuItemsController < RestoAdmin::BaseApiController include CleanPagination before_action :build_options, only: [:create, :update] def index @menu_items = if params[:category_id] @branch_group.menu_items_by_category(params[:category_id]) else @branch_group.menu_items end max_per_page = 10 paginate @menu_items.count, max_per_page do |limit, offset| @menu_items = @menu_items.limit(limit).offset(offset).order(:name) end end def create @item = MenuItem.new(item_params) @item.image = decode_image @item.branch_menu_categories = branch_menu_categories @item.item_options = @item_options @item.save render :show end def update @item = MenuItem.find(params[:id]) @item.image = decode_image if decode_image @item.branch_menu_categories = branch_menu_categories @item.item_options = @item_options @item.save render :show end def show @item = MenuItem.find(params[:id]) end def destroy MenuItem.find(params[:id]).delete render nothing: true, status: 204 end private def branch_menu_categories branch_menu_categories = [] branch_ids.each do |b_id| menu_category_ids.each do |c_id| branch_menu_categories << BranchMenuCategory.find_or_create_by(branch_id: b_id, menu_category_id: c_id) end end branch_menu_categories end def item_params @ip = params .permit( :slug, :name, :description, :price, :meta_keywords, :meta_description, :deleted_at ) end def branch_ids (params[:branches] || []).map { |e| e[:id] } end def menu_category_ids (params[:categories] || []).map { |e| e[:id] } end def build_options @item_options = [] item_options_params.each do |item_option_params| item_option = ItemOption.new( name: item_option_params[:name], description: item_option_params[:description], option_limit: item_option_params[:option_limit] ) (item_option_params[:options]||[]).each do |option| item_option_option = ItemOptionOption.new item_option_option.name = option[:name] item_option_option.price = option[:price] item_option.options << item_option_option end @item_options << item_option end @item_options end def item_options_params params[:item_options] || [] end def decode_image # decode base64 string if params[:img] Rails.logger.info 'decoding now' decoded_data = Base64.decode64(params[:img][:imageData]) # json parameter set in directive scope # create 'file' understandable by Paperclip data = StringIO.new(decoded_data) data.class_eval do attr_accessor :content_type, :original_filename end # set file properties data.content_type = params[:img][:imageContent] # json parameter set in directive scope data.original_filename = params[:img][:imagePath] # json parameter set in directive scope # update hash, I had to set @up to persist the hash so I can pass it for saving # since set_params returns a new hash everytime it is called (and must be used to explicitly list which params are allowed otherwise it throws an exception) data # user Icon is the model attribute that i defined as an attachment using paperclip generator else nil end end end
require 'im_magick/command/collector' require 'im_magick/command/emitter' module ImMagick module Command class NotImplemented < StandardError end class Base include Emitter def initialize(*args, &block) yield self if block_given? end def run(options = {}) self.class.const_get('Runner').new(self, options).execute rescue self.class.const_get('Runner').new(self, options) end def to_options(options = {}) collector.to_command(options) end alias :inspect :to_options def identify(fname = nil) fname ||= @filename fname.is_a?(String) && File.exists?(fname) ? ImageInfo.new(fname) : nil end def to_command(options = {}) "#{self.class.path} #{self.to_options(options)}" end alias :command :to_command alias :to_s :to_command class << self # Return the current command name def command_name self.name.split('::').last.downcase.to_sym end def inherited(base) # set the default path/name for native *magick cli-commands base.cattr_accessor :path base.path = base.command_name.to_s # create a class method on ImMagick module ImMagick::register_command(base) end end end end end
require 'test_helper' class InvitationsControllerTest < ActionController::TestCase def login session[:login] = @user end setup do @user = users(:one) @event = events(:one) @invitation = invitations(:one) login end test "should get new" do get :new, event_id: @event.id assert_response :success end test "should create invitation" do assert_difference('Invitation.count') do post :create, event_id: @invitation.event_id, invitation: { event_id: @invitation.event_id, intention: @invitation.intention, owner_id: @invitation.owner_id, user_id: '999' } end assert_redirected_to '/events/1' end test "should get edit" do get :edit, id: @invitation, event_id: @invitation.event_id assert_response :success end test "should update invitation" do put :update, id: @invitation, event_id: @invitation.event_id, invitation: { event_id: @invitation.event_id, intention: @invitation.intention, owner_id: @invitation.owner_id, user_id: @invitation.user_id } assert_redirected_to event_path end test "should destroy invitation" do assert_difference('Invitation.count', -1) do delete :destroy, id: @invitation, event_id: @invitation.event_id end assert_redirected_to '/events/1' end end
require 'usiri/toleo' require 'usiri/mwisho' class ChaguoCLI attr_accessor :jina, :siti, :alama, :urefu, :toleo def initialize @jina = nil @siti = nil @alama = nil @urefu = nil @toleo = nil @toleo_usiri = Usiri::TOLEO end def fasili_chaguo mfasili mfasili.banner = 'usiri [chaguo]' chaguo_jina mfasili chaguo_siti mfasili chaguo_alama mfasili chaguo_urefu mfasili chaguo_toleo mfasili mfasili.on_tail("-m", MAELEZO[:msaada]) do puts mfasili exit end mfasili.on_tail("-T", MAELEZO[:toleo_usiri]) do puts @toleo_usiri exit end end private def chaguo_jina mfasili mfasili.on("-j", "--jina JINA", MAELEZO[:jina]) do |jina| raise kosa jina if jina.match? REGEX[:chaguo_cli] @jina = jina end end def chaguo_siti mfasili mfasili.on("-s", "--siti SITI", MAELEZO[:siti]) do |siti| raise kosa siti if siti.match? REGEX[:chaguo_cli] @siti = siti end end def chaguo_alama mfasili mfasili.on("-a", "--alama [AINA]", AINA_MAALAMA, MAELEZO[:alama]) do |alama| if AINA_MAALAMA.include? alama @alama = alama else @alama = MSINGI[:alama] end end end def chaguo_urefu mfasili mfasili.on("-u", "--urefu UREFU", REGEX[:urefu], MAELEZO[:urefu]) do |urefu| @urefu = urefu.to_i end end def chaguo_toleo mfasili mfasili.on("-t", "--toleo TOLEO", REGEX[:toleo], MAELEZO[:toleo]) do |toleo| @toleo = toleo end end def kosa jibu OptionParser::InvalidArgument.new jibu end end
class SubRequest < ApplicationRecord belongs_to :group belongs_to :user has_many :sendees, dependent: :destroy has_many :replies, through: :sendees has_one :selected_sub, dependent: :destroy after_create :send_to_sendees validates_presence_of :start_date_time validates_presence_of :end_date_time validates_presence_of :class_name validates_presence_of :class_id_mb scope :unresolved, -> { where('closed = ? AND start_date_time >= ?', false, Time.now.to_date) } scope :resolved, -> { where('closed = ? AND start_date_time >= ?', true, Time.now.to_date) } scope :past, -> { where('start_date_time < ?', Time.now.to_date)} def send_to_sendees group = Group.find(self.group_id) group.users.each do |user| if (user != self.user) Sendee.create!(user: user, sub_request: self) end end end end
module V1 class FollowsController < ApplicationController include ExceptionHandler before_action :set_followed_user, only: %i[create destroy] def create @follow = current_user.follow(@followed_user) render json: @follow, status: :created end def destroy current_user.unfollow(@followed_user) head :no_content end private def follow_params params.require(:follow).permit(:followed_id) end def set_followed_user @followed_user = User.find(params[:follow][:followed_id]) end end end
require_relative '../../spec_helper' describe MangoPayV1::Withdrawal, :type => :feature do let(:new_user) { user = MangoPayV1::User.create({ 'Tag' => 'test', 'Email' => 'my@email.com', 'FirstName' => 'John', 'LastName' => 'Doe', 'CanRegisterMeanOfPayment' => true }) contribution = MangoPayV1::Contribution.create({ 'Tag' => 'test_contribution', 'UserID' => user['ID'], 'WalletID' => 0, 'Amount' => 10000, 'ReturnURL' => 'https://leetchi.com' }) visit(contribution['PaymentURL']) fill_in('number', :with => '4970100000000154') fill_in('cvv', :with => '123') click_button('paybutton') contribution = MangoPayV1::Contribution.details(contribution['ID']) while contribution["IsSucceeded"] == false do contribution = MangoPayV1::Contribution.details(contribution['ID']) end user } let(:new_beneficiary) { MangoPayV1::Beneficiary.create({ 'Tag' => 'test', 'UserID' => new_user['ID'], 'BankAccountOwnerName' => new_user['FirstName'], 'BankAccountOwnerAddress' => '1 bis cite paradis', 'BankAccountIBAN' => 'FR76 1790 6000 3200 0833 5232 973', 'BankAccountBIC' => 'AGRIFRPP879' }) } let(:new_withdrawal) { MangoPayV1::Withdrawal.create({ 'Tag' => 'test_withdrawal', 'UserID' => new_user['ID'], 'WalletID' => 0, 'Amount' => 2500, 'BeneficiaryID' => new_beneficiary['ID'] }) } describe "CREATE" do it "create a withdrawal" do expect(new_withdrawal['ID']).not_to be_nil expect(new_withdrawal['UserID']).to eq(new_user['ID']) expect(new_withdrawal['BeneficiaryID']).to eq(new_beneficiary['ID']) end it "fails and return a 2001 error code: Invalid withdrawal amount" do fail_withdrawal = MangoPayV1::Withdrawal.create({ 'Tag' => 'test_withdrawal', 'UserID' => new_user['ID'], 'WalletID' => 0, 'Amount' => -123, 'BeneficiaryID' => new_beneficiary['ID'] }) expect(fail_withdrawal['ErrorCode']).to eq(2001) end it "fails and return a 2002 error code: Both parameters are specified: Amount and AmountWithoutFees" do fail_withdrawal = MangoPayV1::Withdrawal.create({ 'Tag' => 'test_withdrawal', 'UserID' => new_user['ID'], 'WalletID' => 0, 'Amount' => 2500, 'AmountWithoutFees' => 2500, 'BeneficiaryID' => new_beneficiary['ID'] }) expect(fail_withdrawal['ErrorCode']).to eq(2002) end it "fails and return a 2003 error code: Invalid withdrawal ClientFeeAmount" do fail_withdrawal = MangoPayV1::Withdrawal.create({ 'Tag' => 'test_withdrawal', 'UserID' => new_user['ID'], 'WalletID' => 0, 'Amount' => 2500, 'BeneficiaryID' => new_beneficiary['ID'], 'ClientFeeAmount' => -3000 }) expect(fail_withdrawal['ErrorCode']).to eq(2003) end end describe "GET" do it "get the withdrawal" do withdrawal = MangoPayV1::Withdrawal.details(new_withdrawal['ID']) expect(withdrawal['ID']).to eq(new_withdrawal['ID']) end end end
module Admin class BaseController < ApplicationController before_action :verify_staff def current_ability @current_ability ||= AdminAbility.new(current_user) end def download_emails if params[:project_id].present? project = Project.find(params[:project_id]) @emails = project.participations.select { |p| p.user.email.present? }.map { |p| {project: p.project.title, email: p.user.email, name: p.user.nickname, provider: p.user.provider} }.uniq { |p| p[:email]} else @emails = User.all.select { |u| u.email.present? }.map { |u| {email: u.email, name: u.nickname, provider: u.provider} }.uniq { |u| u[:email] } end respond_to do |format| format.xlsx end end private def verify_staff redirect_to root_url unless current_user.try(:role).try(:staff?) end end end
class AddHoursToPlanningConfirmation < ActiveRecord::Migration def change add_column :planning_confirmations, :hours, :float, default: 0.0 end end
require 'json' def to_upper_case(event:, context:) begin puts "Received Request: #{event}" { statusCode: 200, body: event["body"].upcase, } rescue StandardError => e puts e.message puts e.backtrace.inspect { statusCode: 400, body: e.message, }.to_json end end
class RiotApi BASE_URL = "https://euw.api.pvp.net" GLOBAL_URL = "https://global.api.riotgames.com" RIOT_API_KEY = ENV['RIOT_API_KEY'] def get_response(url) response = RestClient.get(url) JSON.parse(response) end def get_challenger_league challenger_league_url = "#{BASE_URL}/api/lol/EUW/v2.5/league/challenger?type=RANKED_SOLO_5x5&api_key=#{RIOT_API_KEY}" get_response(challenger_league_url) end def get_master_league master_league_url = "#{BASE_URL}/api/lol/EUW/v2.5/league/master?type=RANKED_SOLO_5x5&api_key=#{RIOT_API_KEY}" get_response(master_league_url) end def get_mastery_points(summonerid) mastery_points_url = "#{BASE_URL}/championmastery/location/EUW1/player/#{summonerid}/champions?api_key=#{RIOT_API_KEY}" get_response(mastery_points_url) end def get_top_champion(summonerid) top_champion_url = "#{BASE_URL}/championmastery/location/EUW1/player/#{summonerid}/topchampions?count=1&api_key=#{RIOT_API_KEY}" get_response(top_champion_url) end def get_all_champions get_all_champions_url = "#{GLOBAL_URL}/api/lol/static-data/EUW/v1.2/champion?dataById=true&api_key=#{RIOT_API_KEY}" get_response(get_all_champions_url) end end
module SlackServices module ChannelsImporter extend Client def import channels = client.channels_list.fetch('channels') { [] } channels.each do |channel_attributes| begin import_channel(channel_attributes) rescue => ex Rails.logger.error(ex.message) end end end def import_channel(channel_attributes) external_id = channel_attributes.fetch('id') do fail 'Channel has no ID!' end topic = channel_attributes.fetch('topic', {}) purpose = channel_attributes.fetch('purpose', {}) params = { name: channel_attributes.fetch('name', 'Noname'), topic: topic.fetch('value', 'Unknown'), purpose: purpose.fetch('value', 'Unknown') } create_or_update_channel(external_id, params) end def create_or_update_channel(external_id, params) channel = ::Channel.where(external_id: external_id).first_or_initialize return unless channel channel.attributes = params channel.save! end module_function :import, :import_channel, :create_or_update_channel end end
#!/usr/bin/env ruby # (c) Copyright 2016 Thoughtgang <http://www.thoughtgang.org> # Utility for listing the contents of a Plan R repo require 'plan-r/application/cli' require 'plan-r/repo' class App < PlanR::CliApplication # inspect needs nothing def self.disable_plugins?; true; end def self.disable_jruby?; true; end def self.disable_vcs?; true; end def self.disable_database?; true; end def handle_options(args) @options.repo = nil @options.node_type = nil @options.paths = [] opts = OptionParser.new do |opts| opts.banner = "Usage: #{File.basename $0} [-t str] REPO [PATH] [...]" opts.separator "Inspect the contents of a Plan-R repo by path." opts.separator " * REPO is the path to a Plan-R repo dir." opts.separator " * PATH is a content or metadata path in the repo." opts.separator "" opts.separator "Options:" opts.on( '-t', '--type str', 'Node type [default: all]', 'Try "-t help"' ) { |str| @options.node_type = str.to_sym } standard_cli_options(opts) end opts.parse!(args) if @options.node_type == :help puts "Node types:" puts available_node_types.concat(available_node_types(true)).join("\n") exit -1 end @options.repo = args.shift @options.paths = args @options.paths << '/' if (@options.paths.empty?) if ! @options.repo $stderr.puts "REPO argument required!" puts opts exit -1 end end def start repo = PlanR::Application::RepoManager.open(@options.repo) raise "Unable to open repo at '#{@options.repo}'" if ! repo doc_mgr = PlanR::Application::DocumentManager meta_selected = (available_node_types(true).include? @options.node_type) ctype = meta_selected ? nil : @options.node_type mtype = meta_selected ? @options.node_type : nil @options.paths.each do |path| puts path repo.lookup(path, ctype, false, true).each do |ntype, path| puts " [#{ntype}] " repo.metadata(path, ctype, mtype).each do |meta_type, node| puts " #{meta_type} : #{node.contents.inspect}" end if (! meta_selected) data = repo.content(path, ntype) puts " CONTENT : #{data.inspect}" end end end PlanR::Application::RepoManager.close(repo) end end if __FILE__ == $0 App.new(ARGV).exec end
class V1::Dashboards::DashboardController < V1::CacheController #before_filter authorize_user! api :GET, "/dashboard/menu", "List dashboad role specific menu" param :edit, String, "request menu items for edit by given role name" meta "## if no `:edit` params passed, just return role specific menu items" def menu if params[:edit] && (authorize! :edit, Menu) load_full_menu else load_menu end render_menu end protected def load_full_menu return if !current_user.has_role?(params[:edit]) key = "dashboard_#{params[:edit]}" menu = Menu.find_by(name: key).children #Rails.cache.delete(sk) @menu = ActiveModel::ArraySerializer.new(menu, each_serializer: MenuSerializer, scope: params) end def load_menu key = "dashboard_#{current_user.xrole.name}" menu = cache_with key, expires_in: 1.day do Menu.find_by(name: key).children end @menu = ActiveModel::ArraySerializer.new(menu, each_serializer: MenuSerializer, scope: params) end def authorized_user! authorize! :read, Menu end def render_menu render status: 200, json: { menu: @menu } end end
class CommentsController < ApplicationController def create #before_action :authenticate_user!, :except => [:create] @article = Article.find(params[:article_id]) # т.е внутри статьи создаем комментарий который передается через параметры #@article.comments.create(comment_params) article = @article.comments.new (comment_params) article.save redirect_to article_path(@article) end private #разрешение на передачу параметров def comment_params params.require(:comment).permit(:author, :body) end end
class AdminMailer < Base default to: ADMIN_EMAIL # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.admin_mailer.new_merchant.subject # def new_merchant(merchant) @merchant = merchant greeting("Admin") mail from: SENDER_EMAIL end def update_merchant(merchant) @merchant = merchant greeting("Admin") mail end def new_charity(charity) @charity = charity greeting("Admin") mail from: SENDER_EMAIL end def activated_charity(charity) @charity = charity greeting("Admin") mail from: SENDER_EMAIL end end
# frozen_string_literal: true require_relative 'human_size/version' require_relative 'human_size/overloads' # # Add docs # module HumanSize # # Add docs # class Size def self.human_size(bytes, a_kilobyte_is_1024_bytes = true) suffixes_table = { # Unit prefixes used for SI file sizes. 'SI' => ['B', 'KB', 'MB', 'GB', 'TB', 'Pb', 'EB', 'ZB', 'YB'], # Unit prefixes used for binary file sizes. 'BINARY' => ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'Pib', 'EiB', 'ZiB', 'YiB'] } return 'unknown' if bytes.negative? return '0.0 B' if bytes.zero? units = if a_kilobyte_is_1024_bytes suffixes_table['BINARY'] else suffixes_table['SI'] end multiple = if a_kilobyte_is_1024_bytes 1024 else 1000 end exp = (Math.log(bytes) / Math.log(multiple)).to_i exp = units.length if exp > units.length # rubocop:disable Layout/SpaceAroundOperators format('%<bytes>.1f %<unit>s', bytes: bytes.to_f / multiple ** exp, unit: units[exp]) # rubocop:enable Layout/SpaceAroundOperators end end end
class Admin::TeamsController < ApplicationController before_filter :authorize_admin layout "admin" # GET /teams # GET /teams.json def index @teams = Team.all respond_to do |format| format.html # index.html.erb format.json { render json: @teams } end end # GET /teams/1 # GET /teams/1.json def show @team = Team.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @team } end end # GET /teams/new # GET /teams/new.json def new @team = Team.new respond_to do |format| format.html # new.html.erb format.json { render json: @team } end end # GET /teams/1/edit def edit @team = Team.find(params[:id]) @students = Student.where(:team_id => @team.id) end # POST /teams # POST /teams.json def create @team = Team.new(params[:team]) respond_to do |format| if @team.save format.html { redirect_to :action => "teamassign", :id => @team.id, notice: 'Team was successfully created.' } format.json { render json: @team, status: :created, location: @team } else format.html { render action: "new" } format.json { render json: @team.errors, status: :unprocessable_entity } end end end # PUT /teams/1 # PUT /teams/1.json def update @team = Team.find(params[:id]) respond_to do |format| if @team.update_attributes(params[:team]) format.html { redirect_to edit_admin_team_path(@team)} format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @team.errors, status: :unprocessable_entity } end end end def teamassign @team = Team.find(params[:id]) @students = Student.where(:team_id => nil) respond_to do |format| format.html # index.html.erb format.json { render json: @students } format.json { render json: @team } end end def assignmember @students = Student.find(params[:student]) @team = Team.find(params[:team_id]) @team.students << @students @students.each do |student| student.update_attribute(:team_id,@team.id) end respond_to do |format| format.html { redirect_to admin_teams_url } format.json { head :no_content } end end def unassignmember @student = Student.find(params[:student_id]) @team_id = @student.team_id @student.update_attribute(:team_id, nil) respond_to do |format| format.html { redirect_to :action => "edit", :id => @team_id} format.json { head :no_content } end end # DELETE /teams/1 # DELETE /teams/1.json def destroy @team = Team.find(params[:id]) @students = Student.where(:team_id => @team.id) @students.each do |student| student.update_attribute(:team_id, nil) end @team.destroy respond_to do |format| format.html { redirect_to admin_teams_url } format.json { head :no_content } end end protected def authorize_admin #unless Usuario.find_by_id(session[:user_id]) @projects = Project.all @projects.sort! { |a,b| a.nombre.downcase <=> b.nombre.downcase } @session_admin = Usuario.find_by_auth_token( cookies[:auth_token]) if @session_admin.tipo != "Admin" redirect_to login_url, :alert => "Usted no tiene permisos suficientes" end end end
RSpec.describe S3WebsiteDeploy::CachePolicy do describe S3WebsiteDeploy::CachePolicy::Policy do describe "#match?" do def policy(pattern) S3WebsiteDeploy::CachePolicy::Policy.new(pattern, { "cache_control" => "max-age=600" }) end context "with exact pattern" do it "matches exact only pattern" do expect(policy("index.html")).to be_match("index.html") expect(policy("index.html")).not_to be_match("foobar/index.html") end end context "with wildcard patterns" do let(:pattern) { "*.html" } it "matches exact only pattern" do expect(policy("*.html")).to be_match("index.html") expect(policy("*.html")).to be_match("foobar/index.html") expect(policy("*.html")).to be_match("other.html") expect(policy("*.html")).to be_match("other.html") expect(policy("*.html")).not_to be_match("other.css") expect(policy("123*45*6789*")).to be_match("123456789") expect(policy("123*45*6789*")).to be_match("123xxx45x6789xxxx") expect(policy("123*45*6789")).not_to be_match("123xxx45x6789xxxx") end end end end describe "#value" do let(:config) { { "*.html" => { "cache_control" => "max-age=600" } } } let(:cache_policy) { S3WebsiteDeploy::CachePolicy.new(config) } it "returns cache-policy value" do expect(cache_policy.cache_control("index.html")).to eq("max-age=600") expect(cache_policy.cache_control("app.css")).to eq(nil) end end end
Blog::Application.routes.draw do #Create get "posts/new" => 'posts#new', :as => "new_post" post "posts/" => 'posts#create' #Update get "posts/:id/edit" => 'posts#edit', :as =>"edit_post" patch "posts/:id" => 'posts#update' #Read get "posts" => 'posts#index' get "posts/:id" => 'posts#show', :as => "details" get "about" => 'posts#about', :as => "about" #Destroy - don't need to define because it is on line 4 delete "posts/:id" => 'posts#destroy' end
class Api::V1::UsersController < ApplicationController def index case params[:type] when 'friends' users = current_user.friends when 'incoming_requests' users = current_user.requested_friends else friend_ids = current_user.friends&.pluck(:id) pending_ids = current_user.pending_friends&.pluck(:id) incoming_request_ids = current_user.requested_friends&.pluck(:id) users = User.where.not(id: friend_ids + pending_ids + incoming_request_ids << current_user.id) end render json: users end def update @user = User.find(params[:id]) request = params[:user][:request] case request when 'friend_request' current_user.friend_request(@user) when 'confirm_friend_request' current_user.accept_request(@user) when 'decline_friend_request' current_user.decline_request(@user) when 'remove_friend' current_user.remove_friend(@user) end users = User.where.not(id: [current_user.id, @user.id]) if request == 'friend_request' users = User.where.not(id: current_user.id) if request == 'remove_friend' users = User.where.not(id: current_user.id) if request == 'confirm_friend_request' users = User.where.not(id: current_user.id) if request == 'decline_friend_request' render json: users end private def strong_params end end
require 'auth/hatenagroup_auth' class TestHatenaGroupAuth < Test::Unit::TestCase def setup @obj = HatenaGroup.new('generation1991', 'api_key', 'sec_key') end def test_initialize assert_equal('generation1991', @obj.group_name) assert_equal('http://generation1991.g.hatena.ne.jp/', @obj.group_url) assert_raise(HatenaGroup::GroupNotFound) do HatenaGroup.new('notfoundnotfoundnotfound', 'api_key', 'sec_key') end end def test_generater assert_instance_of?(String, @obj.login_url) assert(@obj.login_url(:var => 'test') =~ /var=test/) end def test_members assert_instance_of?(Array, @obj.members) end def test_member? assert(@obj.member?('rosylilly')) end def test_get_user assert_instance_of?(HatenaGroup::User, @obj.cert('cert')) end def test_user user = @obj.get_user('cert') assert_instance_of?(String, user.name) assert_instance_of?(String, user.image) assert_instance_of?(String, user.thumbnail) end end