hexsha
stringlengths
40
40
size
int64
2
1.01M
content
stringlengths
2
1.01M
avg_line_length
float64
1.5
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
1
e983a33d4d84f57d249db81364edc3cc4dcab42b
2,090
require "language/node" require "json" class Webpack < Formula desc "Bundler for JavaScript and friends" homepage "https://webpack.js.org/" url "https://registry.npmjs.org/webpack/-/webpack-5.11.0.tgz" sha256 "cf8fc82308a8196eab9d2e905a645b9eb65d72b704868880110db34112b54ffc" license "MIT" head "https://github.com/webpack/webpack.git" livecheck do url :stable end bottle do cellar :any_skip_relocation sha256 "c2ebd9cad7f2b642264f15666283a50305c6950509d025e52706980721ae6a37" => :big_sur sha256 "253d5b31cc29da6c3419d796f6d0e70371a984ba91f6bc03d3a3b8bb69cd7aee" => :catalina sha256 "53a73b0092cb4427a443ed30cf8fa26f01e9844d159b1c082a3b2d07d69ddcc2" => :mojave end depends_on "node" resource "webpack-cli" do url "https://registry.npmjs.org/webpack-cli/-/webpack-cli-4.2.0.tgz" sha256 "09ca2de6deee939a4a2f8edf206a776caafb6fe3590ed1a8310a3e3b69ad4a18" end def install (buildpath/"node_modules/webpack").install Dir["*"] buildpath.install resource("webpack-cli") cd buildpath/"node_modules/webpack" do system "npm", "install", *Language::Node.local_npm_install_args, "--production", "--legacy-peer-deps" end # declare webpack as a bundledDependency of webpack-cli pkg_json = JSON.parse(IO.read("package.json")) pkg_json["dependencies"]["webpack"] = version pkg_json["bundleDependencies"] = ["webpack"] IO.write("package.json", JSON.pretty_generate(pkg_json)) system "npm", "install", *Language::Node.std_npm_install_args(libexec) bin.install_symlink libexec/"bin/webpack-cli" bin.install_symlink libexec/"bin/webpack-cli" => "webpack" end test do (testpath/"index.js").write <<~EOS function component() { const element = document.createElement('div'); element.innerHTML = 'Hello' + ' ' + 'webpack'; return element; } document.body.appendChild(component()); EOS system bin/"webpack", testpath/"index.js" assert_match "const e=document\.createElement(\"div\");", File.read(testpath/"dist/main.js") end end
32.153846
107
0.71866
1cc5fb2fcf8db5dba3374ddea7a2cdc4299fe073
2,612
# frozen_string_literal: true module JekyllImport module Importers class RSS < Importer def self.specify_options(c) c.option "source", "--source NAME", "The RSS file or URL to import" c.option "tag", "--tag NAME", "Add a tag to posts" c.option "render_audio", "--render_audio", "Render <audio> element as necessary" end def self.validate(options) abort "Missing mandatory option --source." if options["source"].nil? end def self.require_deps JekyllImport.require_with_fallback(%w( rss rss/1.0 rss/2.0 open-uri fileutils safe_yaml )) end # Process the import. # # source - a URL or a local file String. # # Returns nothing. def self.process(options) source = options.fetch("source") content = "" open(source) { |s| content = s.read } rss = ::RSS::Parser.parse(content, false) raise "There doesn't appear to be any RSS items at the source (#{source}) provided." unless rss rss.items.each do |item| write_rss_item(item, options) end end def self.write_rss_item(item, options) frontmatter = options.fetch("frontmatter", []) body = options.fetch("body", ["description"]) render_audio = options.fetch("render_audio", false) formatted_date = item.date.strftime("%Y-%m-%d") post_name = Jekyll::Utils.slugify(item.title, :mode => "latin") name = "#{formatted_date}-#{post_name}" audio = render_audio && item.enclosure.url header = { "layout" => "post", "title" => item.title, "canonical_url" => item.link } header["tag"] = options["tag"] unless options["tag"].nil? || options["tag"].empty? frontmatter.each do |value| header[value] = item.send(value) end output = +"" body.each do |row| output << item.send(row).to_s end output.strip! output = item.content_encoded if output.empty? FileUtils.mkdir_p("_posts") File.open("_posts/#{name}.html", "w") do |f| f.puts header.to_yaml f.puts "---\n\n" if audio f.puts <<~HTML <audio controls=""> <source src="#{audio}" type="audio/mpeg"> Your browser does not support the audio element. </audio> HTML end f.puts output end end end end end
26.653061
103
0.542496
f8136a2e5cbfccce627eecf2becffa5185d66248
142
require 'test_helper' class KirpichTest < Minitest::Test def test_that_it_has_a_version_number refute_nil ::Kirpich::VERSION end end
17.75
39
0.788732
d5e77fd2e7ad7907ad1884f96a2104438b10c9fa
63
Dummy::Application.routes.draw do root "dashboard#index" end
15.75
33
0.777778
e98f247cead0ae6ccf05a3170385c9a002017ef2
1,196
class API module Parsers # Parse objects for API. class ObjectParser < ObjectBase attr_accessor :limit # Always has to have limit argument: the set of allowed object types. def initialize(*args) super self.limit = self.args[:limit] raise("missing limit!") unless limit end def parse(str) type, id = parse_object_type(str) val = find_object(type, id, str) check_view_permission!(val) if args[:must_have_view_permission] check_edit_permission!(val) if args[:must_have_edit_permission] val end def parse_object_type(str) match = str.match(/^([a-z][ _a-z]*[a-z]) #?(\d+)$/i) raise BadParameterValue.new(str, :object) unless match [match[1].tr(" ", "_").downcase, match[2]] end def find_object(type, id, str) val = nil limit.each do |model| next unless model.type_tag.to_s.casecmp(type).zero? val = model.safe_find(id) return val if val raise ObjectNotFoundById.new(str, model) end raise BadLimitedParameterValue.new(str, limit.map(&:type_tag)) end end end end
29.170732
75
0.606187
08ad9fe1bd4112c5bbb5912a6a66a6b82e01198b
5,003
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 module TwitterCldr module Shared class Calendar DEFAULT_FORMAT = :'stand-alone' DEFAULT_PERIOD_FORMAT = :format NAMES_FORMS = [:wide, :narrow, :abbreviated] ERAS_NAMES_FORMS = [:abbr, :name] DATETIME_METHOD_MAP = { :year_of_week_of_year => :year, :quarter_stand_alone => :quarter, :month_stand_alone => :month, :day_of_month => :day, :day_of_week_in_month => :day, :weekday_local => :weekday, :weekday_local_stand_alone => :weekday, :second_fraction => :second, :timezone_generic_non_location => :timezone, :timezone_metazone => :timezone } REDIRECT_CONVERSIONS = { :dayPeriods => :periods } attr_reader :locale, :calendar_type def initialize(locale = TwitterCldr.locale, calendar_type = TwitterCldr::DEFAULT_CALENDAR_TYPE) @locale = TwitterCldr.convert_locale(locale) @calendar_type = calendar_type end def months(names_form = :wide, format = DEFAULT_FORMAT) cache_field_data(:months, names_form, format) do data = get_with_names_form(:months, names_form, format) data && data.sort_by { |m| m.first }.map { |m| m.last } end end def weekdays(names_form = :wide, format = DEFAULT_FORMAT) cache_field_data(:weekdays, names_form, format) do get_with_names_form(:days, names_form, format) end end def fields cache_field_data(:fields) do get_data(:fields) end end def quarters(names_form = :wide, format = DEFAULT_FORMAT) cache_field_data(:quarters, names_form, format) do get_with_names_form(:quarters, names_form, format) end end def periods(names_form = :wide, format = DEFAULT_PERIOD_FORMAT) cache_field_data(:periods, names_form, format) do get_with_names_form(:periods, names_form, format) end end def eras(names_form = :name) cache_field_data(:eras, names_form) do get_data(:eras)[names_form] end end def date_order(options = {}) get_order_for(TwitterCldr::DataReaders::DateDataReader, options) end def time_order(options = {}) get_order_for(TwitterCldr::DataReaders::TimeDataReader, options) end def datetime_order(options = {}) get_order_for(TwitterCldr::DataReaders::DateTimeDataReader, options) end def calendar_data @calendar_data ||= TwitterCldr::Utils.traverse_hash(resource, [locale, :calendars, calendar_type]) end private def cache_field_data(field, names_form = nil, format = nil) cache_key = TwitterCldr::Utils.compute_cache_key(locale, field, names_form, format) field_cache[cache_key] ||= begin yield end end def field_cache @@field_cache ||= {} end def calendar_cache @@calendar_cache ||= {} end def get_order_for(data_reader_const, options) key_array = [data_reader_const.to_s, @locale] + options.keys.sort + options.values.sort cache_key = TwitterCldr::Utils.compute_cache_key(key_array) calendar_cache.fetch(cache_key) do |key| data_reader = data_reader_const.new(@locale, options) tokens = data_reader.tokenizer.tokenize(data_reader.pattern) calendar_cache[cache_key] = resolve_methods(methods_for_tokens(tokens)) end end def resolve_methods(methods) methods.map { |method| DATETIME_METHOD_MAP.fetch(method, method) } end def methods_for_tokens(tokens) tokens.inject([]) do |ret, token| if token.type == :pattern ret << TwitterCldr::Formatters::DateTimeFormatter::METHODS[token.value[0].chr] end ret end end def get_with_names_form(data_type, names_form, format) get_data(data_type, format, names_form) if NAMES_FORMS.include?(names_form.to_sym) end def get_data(*path) cache_key = TwitterCldr::Utils.compute_cache_key([@locale] + path) calendar_cache.fetch(cache_key) do |key| data = TwitterCldr::Utils.traverse_hash(calendar_data, path) redirect = parse_redirect(data) calendar_cache[key] = if redirect get_data(*redirect) else data end end end def parse_redirect(data) if data.is_a?(Symbol) && data.to_s =~ redirect_regexp result = $1.split('.').map(&:to_sym) result.map { |leg| REDIRECT_CONVERSIONS.fetch(leg, leg) } end end def redirect_regexp Regexp.new("^calendars\.#{calendar_type}\.(.*)$") end def resource TwitterCldr.get_locale_resource(@locale, :calendars) end end end end
29.958084
106
0.628823
bb53216c10ef42a0cbf81c9094a94fb83a8c8209
397
module Rubicure module Concerns # utility methods module Util # @param arg # @return [Date] arg is String or Date # @return [Time] arg is Time # @return [nil] arg is other def to_date(arg) case arg when Date, Time arg when String Date.parse(arg) else nil end end end end end
18.045455
44
0.513854
f89f740cd196a28e3469c1f7f809502871a58f82
2,532
# Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.4' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| config.gem 'thoughtbot-clearance', :lib => 'clearance', :source => 'http://gems.github.com' config.gem 'oauth', :version => '0.3.5' config.gem 'crafterm-comma',:lib=>'comma',:source=>"http://gems.github.com" config.gem 'haml', :lib => 'haml', :version => '>=2.2' config.gem "openrain-action_mailer_tls", :lib => "smtp_tls.rb", :source => "http://gems.github.com" config.gem "oauth-plugin", :lib=>'oauth-plugin' # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named config.plugins = [ "thoughtbot-clearance", :oauth,'oauth-plugin', :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'UTC' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de end DO_NOT_REPLY = "[email protected]" ISSUER_EMAIL = "[email protected]" ActiveSupport::JSON.backend = 'JSONGem'
46.888889
101
0.720379
5d4fb54c53dca0f5ddc333b39f637e66c250a956
1,176
require_relative('../config/environment') class Api API_KEY = "7ab46aa5f86d43f2addd9e5da1e6a23d" #get request to the api for a list of recipes including the ingredients that user inputs, creates Recipe instances with the returned recipes def self.get_recipes_from_ing(ing_array, num_of_recipes = 2) ingredients = ing_array.join(",+") #ingredients KW = the ingredients to include; number KW indeicates the number of recipes; ranking KW indicates to the program to proritize recipes with more of the given ingredients. url = "https://api.spoonacular.com/recipes/findByIngredients?apiKey=#{API_KEY}&ingredients=#{ingredients}&number=#{num_of_recipes}&ranking=1" response = HTTParty.get(url) Recipe.new_from_arr_of_hashes(response) end #get request to the api for the users chosen recipe, updates that recipe instance with the info returned def self.get_recipe(recipe) recipe_id = recipe.id url = "https://api.spoonacular.com/recipes/#{recipe_id}/information?apiKey=#{API_KEY}&includeNutrition=false" response = HTTParty.get(url) current = Recipe.find_by_id(recipe_id) current.info_from_hash(response) current end end
45.230769
186
0.765306
d507d33f5da9d636e02afb38dc3ade80f5d2c3e3
269
class AddAbbreviationToOrganizationQuarterStatusTypes < ActiveRecord::Migration def self.up add_column :organization_quarter_status_types, :abbreviation, :string end def self.down remove_column :organization_quarter_status_types, :abbreviation end end
26.9
79
0.821561
6ad495d7f26a4bf4f798bfd999249d2d25b1ec8f
4,943
# Source: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes module ThatLanguage module Iso639 def self.[](language_code) LOOKUP_HASH[language_code.to_sym] end private LOOKUP_HASH = { aa: :"Afar", ab: :"Abkhaz", ac: :"Australian", ae: :"Avestan", af: :"Afrikaans", ak: :"Akan", am: :"Amharic", an: :"Aragonese", ar: :"Arabic", as: :"Assamese", av: :"Avaric", ay: :"Aymara", az: :"Azerbaijani", ba: :"Bashkir", be: :"Belarusian", bg: :"Bulgarian", bh: :"Bihari", bi: :"Bislama", bm: :"Bambara", # bn: :"Bengali, Bangla", bn: :"Bengali", bo: :"Tibetan Standard, Tibetan, Central", br: :"Breton", bs: :"Bosnian", ca: :"Catalan", ce: :"Chechen", ch: :"Chamorro", co: :"Corsican", cr: :"Cree", cs: :"Czech", cu: :"Old Church Slavonic, Church Slavonic, Old Bulgarian", cv: :"Chuvash", cy: :"Welsh", da: :"Danish", de: :"German", dv: :"Divehi, Dhivehi, Maldivian", dz: :"Dzongkha", ee: :"Ewe", # el: :"Greek (modern)", el: :"Greek", en: :"English", eo: :"Esperanto", es: :"Spanish", et: :"Estonian", eu: :"Basque", # fa: :"Persian (Farsi)", fa: :"Persian", # ff: :"Fula, Fulah, Pulaar, Pular", ff: :"Fula", fi: :"Finnish", fj: :"Fijian", fo: :"Faroese", fr: :"French", fy: :"Western Frisian", ga: :"Irish", gd: :"Scottish Gaelic, Gaelic", gl: :"Galician", gn: :"Guaraní", gu: :"Gujarati", gv: :"Manx", ha: :"Hausa", # he: :"Hebrew (modern)", he: :"Hebrew", hi: :"Hindi", ho: :"Hiri Motu", hr: :"Croatian", # ht: :"Haitian, Haitian Creole", ht: :"Haitian", hu: :"Hungarian", hy: :"Armenian", hz: :"Herero", ia: :"Interlingua", id: :"Indonesian", ie: :"Interlingue", ig: :"Igbo", ii: :"Nuosu", ik: :"Inupiaq", io: :"Ido", is: :"Icelandic", it: :"Italian", iu: :"Inuktitut", ja: :"Japanese", jv: :"Javanese", ka: :"Georgian", kg: :"Kongo", ki: :"Kikuyu, Gikuyu", kj: :"Kwanyama, Kuanyama", kk: :"Kazakh", kl: :"Kalaallisut, Greenlandic", km: :"Khmer", kn: :"Kannada", ko: :"Korean", kr: :"Kanuri", ks: :"Kashmiri", ku: :"Kurdish", kv: :"Komi", kw: :"Cornish", ky: :"Kyrgyz", la: :"Latin", lb: :"Luxembourgish, Letzeburgesch", lg: :"Ganda", li: :"Limburgish, Limburgan, Limburger", ln: :"Lingala", lo: :"Lao", lt: :"Lithuanian", lu: :"Luba-Katanga", lv: :"Latvian", mg: :"Malagasy", mh: :"Marshallese", mi: :"Māori", mk: :"Macedonian", ml: :"Malayalam", mn: :"Mongolian", # mr: :"Marathi (Marāṭhī)", mr: :"Marathi", ms: :"Malay", mt: :"Maltese", my: :"Burmese", na: :"Nauru", nb: :"Norwegian Bokmål", nd: :"Northern Ndebele", ne: :"Nepali", ng: :"Ndonga", nl: :"Dutch", nn: :"Norwegian Nynorsk", no: :"Norwegian", nr: :"Southern Ndebele", nv: :"Navajo, Navaho", # ny: :"Chichewa, Chewa, Nyanja", ny: :"Chichewa", oc: :"Occitan", oj: :"Ojibwe, Ojibwa", om: :"Oromo", or: :"Oriya", os: :"Ossetian, Ossetic", # pa: :"Panjabi, Punjabi", pa: :"Panjabi", pi: :"Pāli", pl: :"Polish", # ps: :"Pashto, Pushto", ps: :"Pashto", pt: :"Portuguese", qu: :"Quechua", rm: :"Romansh", rn: :"Kirundi", ro: :"Romanian", ru: :"Russian", rw: :"Kinyarwanda", sa: :"Sanskrit (Saṁskṛta)", sc: :"Sardinian", sd: :"Sindhi", se: :"Northern Sami", sg: :"Sango", # si: :"Sinhala, Sinhalese", si: :"Sinhala", sk: :"Slovak", sl: :"Slovene", sm: :"Samoan", sn: :"Shona", so: :"Somali", sq: :"Albanian", sr: :"Serbian", ss: :"Swati", st: :"Southern Sotho", su: :"Sundanese", sv: :"Swedish", sw: :"Swahili", ta: :"Tamil", te: :"Telugu", tg: :"Tajik", th: :"Thai", ti: :"Tigrinya", tk: :"Turkmen", tl: :"Tagalog", tn: :"Tswana", to: :"Tonga (Tonga Islands)", tr: :"Turkish", ts: :"Tsonga", tt: :"Tatar", tw: :"Twi", ty: :"Tahitian", ug: :"Uyghur", uk: :"Ukrainian", ur: :"Urdu", uz: :"Uzbek", ve: :"Venda", vi: :"Vietnamese", vo: :"Volapük", wa: :"Walloon", wo: :"Wolof", xh: :"Xhosa", yi: :"Yiddish", yo: :"Yoruba", za: :"Zhuang, Chuang", zh: :"Chinese", zu: :"Zulu" } end end
23.538095
65
0.447906
f8e53e3411b573609efdfa23c8258e44384bd135
6,847
# frozen_string_literal: true require 'test_helper' module Dashboard::InternshipOffers class CreateTest < ActionDispatch::IntegrationTest include Devise::Test::IntegrationHelpers test 'POST #create (duplicate) as visitor redirects to internship_offers' do post dashboard_internship_offers_path(params: {}) assert_redirected_to user_session_path end test 'POST #create (duplicate) /InternshipOffers::WeeklyFramed as employer creates the post' do school = create(:school) employer = create(:employer) weeks = [weeks(:week_2019_1)] internship_offer = build(:troisieme_segpa_internship_offer, employer: employer) sign_in(internship_offer.employer) params = internship_offer .attributes .merge('type' => InternshipOffers::WeeklyFramed.name, 'week_ids' => weeks.map(&:id), 'coordinates' => { latitude: 1, longitude: 1 }, 'school_id' => school.id, 'description_rich_text' => '<div>description</div>', 'employer_description_rich_text' => '<div>hop+employer_description</div>', 'employer_id' => internship_offer.employer_id, 'employer_type' => 'Users::Employer') assert_difference('InternshipOffer.count', 1) do post(dashboard_internship_offers_path, params: { internship_offer: params }) end created_internship_offer = InternshipOffer.last assert_equal InternshipOffers::WeeklyFramed.name, created_internship_offer.type assert_equal employer, created_internship_offer.employer assert_equal school, created_internship_offer.school assert_equal weeks.map(&:id), created_internship_offer.week_ids assert_equal weeks.size, created_internship_offer.internship_offer_weeks_count assert_equal params['max_candidates'], created_internship_offer.max_candidates assert_redirected_to internship_offer_path(created_internship_offer) end test 'POST #create (duplicate) /InternshipOffers::FreeDate as employer creates the post' do school = create(:school) employer = create(:employer) internship_offer = build(:free_date_internship_offer, employer: employer) sign_in(internship_offer.employer) params = internship_offer .attributes .merge('type' => InternshipOffers::FreeDate.name, 'coordinates' => { latitude: 1, longitude: 1 }, 'school_id' => school.id, 'description_rich_text' => '<div>description</div>', 'employer_description_rich_text' => '<div>hop+employer_description</div>', 'employer_id' => internship_offer.employer_id, 'employer_type' => 'Users::Employer') assert_difference('InternshipOffer.count', 1) do post(dashboard_internship_offers_path, params: { internship_offer: params }) end created_internship_offer = InternshipOffer.last assert_equal InternshipOffers::FreeDate.name, created_internship_offer.type assert_equal employer, created_internship_offer.employer assert_equal school, created_internship_offer.school assert_equal 'troisieme_segpa', created_internship_offer.school_track assert_equal params['max_candidates'], created_internship_offer.max_candidates assert_redirected_to internship_offer_path(created_internship_offer) end test 'POST #create (duplicate) /InternshipOffers::WeeklyFramed as ministry statistican creates the post' do school = create(:school) employer = create(:ministry_statistician) weeks = [weeks(:week_2019_1)] internship_offer = build(:troisieme_segpa_internship_offer, employer: employer) sign_in(internship_offer.employer) params = internship_offer .attributes .merge('type' => InternshipOffers::WeeklyFramed.name, 'group' => employer.ministry, 'week_ids' => weeks.map(&:id), 'coordinates' => { latitude: 1, longitude: 1 }, 'school_id' => school.id, 'description_rich_text' => '<div>description</div>', 'employer_description_rich_text' => '<div>hop+employer_description</div>', 'employer_type' => 'Users::MinistryStatistician') assert_difference('InternshipOffer.count', 1) do post(dashboard_internship_offers_path, params: { internship_offer: params }) end created_internship_offer = InternshipOffer.last assert_equal InternshipOffers::WeeklyFramed.name, created_internship_offer.type assert_equal employer, created_internship_offer.employer assert_equal school, created_internship_offer.school assert_equal weeks.map(&:id), created_internship_offer.week_ids assert_equal weeks.size, created_internship_offer.internship_offer_weeks_count assert_equal params['max_candidates'], created_internship_offer.max_candidates assert_redirected_to internship_offer_path(created_internship_offer) end test 'POST #create as employer with missing params' do sign_in(create(:employer)) post(dashboard_internship_offers_path, params: { internship_offer: {} }) assert_response :bad_request end test 'POST #create as employer with invalid data, prefill form' do sign_in(create(:employer)) post(dashboard_internship_offers_path, params: { internship_offer: { title: 'hello', is_public: false, group: 'Accenture', max_candidates: 2, max_students_per_group: 2 } }) assert_select 'li label[for=internship_offer_coordinates]', text: 'Veuillez saisir et sélectionner une adresse avec ' \ "l'outil de complétion automatique" assert_select 'li label[for=internship_offer_zipcode]', text: "Veuillez renseigner le code postal de l'employeur" assert_select 'li label[for=internship_offer_city]', text: "Veuillez renseigner la ville l'employeur" assert_select '#internship_offer_is_public_true[checked]', count: 0 # "ensure user select kind of group" assert_select '#internship_offer_is_public_false[checked]', count: 1 # "ensure user select kind of group" assert_select '.form-group-select-group.d-none', count: 0 assert_select '#internship_type_true[checked]', count: 0 assert_select '#internship_type_false[checked]', count: 1 assert_select '.form-group-select-max-candidates.d-none', count: 0 end end end
49.258993
111
0.670951
6245ad22356d79aba3a516d62f4801e98fdd1bf8
2,996
# A Journey is the path (or intended path) between two locations. # # A Move is composed of one or more Journeys; each individual journey record indicates the path and whether it is billable. # Moves can be redirected for various reasons (e.g. supplier is late and the prison is closed; or the PMU call to say the prison is full and # the person should be taken to a different location). Sometimes these journeys are billable and sometimes not. # # Journeys are ordered chronologically by client_timestamp (as opposed to created_at), to allow for queueing and transmission delays in the system sending the journey record. # Journeys have an explicit link to a supplier; whereas moves currently do not. # # Example 1: a move: A--> B is redirected to C by PMU before the supplier arrives at B. # Journey1: A --> B (billable, cancelled) # Journey2: B --> C (billable, completed) # The supplier is paid for two journeys A-->B and B-->C. # # Example 2: a move: A--> B is redirected to C because the supplier arrived late and was locked out. # Journey1: A --> B (billable, completed) # Journey2: B --> C (not billable, completed) # The supplier is paid for only the first journey A-->B but not B-->C. # class Journey < ApplicationRecord FEED_ATTRIBUTES = %w[ id move_id billable state vehicle_registration client_timestamp created_at updated_at ].freeze include StateMachineable belongs_to :move, touch: true belongs_to :supplier belongs_to :from_location, class_name: 'Location' belongs_to :to_location, class_name: 'Location' has_many :generic_events, as: :eventable, dependent: :destroy enum states: { proposed: 'proposed', rejected: 'rejected', in_progress: 'in_progress', completed: 'completed', cancelled: 'cancelled', } validates :move, presence: true validates :supplier, presence: true validates :from_location, presence: true validates :to_location, presence: true validates :client_timestamp, presence: true validates :billable, exclusion: { in: [nil] } validates :state, presence: true, inclusion: { in: states } scope :default_order, -> { order(client_timestamp: :asc) } has_state_machine JourneyStateMachine delegate :start, :reject, :complete, :uncomplete, :cancel, :uncancel, :proposed?, :in_progress?, :completed?, :cancelled?, :rejected?, to: :state_machine def for_feed attributes.slice(*FEED_ATTRIBUTES) .merge(from_location.for_feed(prefix: :from)) .merge(to_location.for_feed(prefix: :to)) .merge(supplier.for_feed) .merge(vehicle_registration: vehicle_registration) end def vehicle_registration vehicle['registration'] if vehicle end def vehicle_registration=(reg) (self.vehicle ||= {})['registration'] = reg end def handle_event_run(dry_run: false) save! if changed? && valid? && !dry_run end end
31.87234
174
0.694259
4a7b1951ac8767c07004d07c38f19d06be9c0930
828
require 'spec_helper' describe Nydp do def run txt Nydp.setup ns Nydp::Runner.new(ns, Nydp::StringReader.new("test", txt)).run end describe "unhandled_error" do it "raises a helpful error" do error = nil begin run "(/ 10 0)" rescue StandardError => e error = e end expect(error).to be_a Nydp::Error expect(error.message).to eq "failed to eval (/ 10 0) from src (/ 10 0)" expect(error.cause).to be_a RuntimeError expect(error.cause.message).to eq "Called builtin// with args 10 0" expect(error.cause.cause).to be_a ZeroDivisionError expect(error.cause.cause.message).to eq "divided by 0" end it "recovers quickly from an error" do run "dflkjdgjeirgjeoi" expect(run "(+ 2 3 4)").to eq 9 end end end
21.789474
77
0.624396
1a293cbd6a98aa3b7bf3dbe89751dace54724fda
551
class <%= class_name.underscore.camelize %> < ActiveRecord::Migration[5.2] def self.up<% attributes.each do |attribute| %> <%= migration_action %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'add' %>, :<%= attribute.type %><% end -%> <%- end %> end def self.down<% attributes.reverse.each do |attribute| %> <%= migration_action == 'add' ? 'remove' : 'add' %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'remove' %>, :<%= attribute.type %><% end -%> <%- end %> end end
45.916667
176
0.597096
ab690695d9303d86dec4d56cd124aa6abde5ba37
2,706
require_relative '../lib/game.rb' RSpec.describe Game do let(:game) { Game.new } let(:player_one) { double('player one object', name: 'Recardo') } let(:player_two) { double('player two object', name: 'Ted') } describe '#player_two_is_the_same_as_player_one?' do context 'player two\'s name is the same as player one\'s name' do it 'returns true' do game.players_arry = [player_one] expect(game.player_two_is_the_same_as_player_one?('Recardo')).to eq(true) end end context 'player two\'s name is not the same as player one\'s name' do it 'returns false' do game.players_arry = [player_one] expect(game.player_two_is_the_same_as_player_one?('Ted')).to_not eq(true) end end end describe '#switch_player' do context 'current player is true' do it 'changes current_player to false' do expect(game.switch_player).to eq(false) end end context 'current player is false' do it 'changes current_player to true' do game.current_player = false expect(game.switch_player).to eq(true) end end end describe '#whos_turn?' do context 'current player is true' do it 'return player one name' do game.players_arry = [player_one, player_two] expect(game.whos_turn?).to eq('Recardo') end end context 'current player is false' do it 'return player two name' do game.players_arry = [player_one, player_two] game.current_player = false expect(game.whos_turn?).to eq('Ted') end end end describe '#play_again?' do context 'the user input passed to it is "y"' do it 'returns true' do user_input = 'y' expect(game.play_again?(user_input)).to eq(true) end end context 'the user input passed to it different than "y"' do it 'returns false' do user_input = 'n' expect(game.play_again?(user_input)).to eq(false) end end end describe '#reset' do it 'reset game object\'s variable [@players_arry] to default' do game.players_arry = [player_one, player_two] game.reset expect(game.players_arry).to match_array [] end context 'current player is true' do it 'reset game object\'s variable [@current_player] to default' do game.current_player = true game.reset expect(game.current_player).to eq(true) end end context 'current player is false' do it 'reset game object\'s variable [@current_player] to default' do game.current_player = false game.reset expect(game.current_player).to eq(true) end end end end
29.096774
81
0.641537
ff306c4a743b9d6b539e8653d40d231a061b42ec
4,516
# -------------------------------------------------------------------------- # # Copyright 2002-2022, OpenNebula Project, OpenNebula Systems # # # # Licensed under the Apache License, Version 2.0 (the "License"); you may # # not use this file except in compliance with the License. You may obtain # # a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # #--------------------------------------------------------------------------- # require 'opennebula/pool' module OpenNebula class HostPool < Pool ####################################################################### # Constants and Class attribute accessors ####################################################################### HOST_POOL_METHODS = { :info => "hostpool.info", :monitoring => "hostpool.monitoring" } ####################################################################### # Class constructor & Pool Methods ####################################################################### # +client+ a Client object that represents a XML-RPC connection def initialize(client) super('HOST_POOL','HOST',client) end # Factory Method for the Host Pool def factory(element_xml) OpenNebula::Host.new(element_xml,@client) end ####################################################################### # XML-RPC Methods for the Host Pool ####################################################################### # Retrieves all the Hosts in the pool. def info() super(HOST_POOL_METHODS[:info]) end def info_all() return super(HOST_POOL_METHODS[:info]) end def info_mine() return super(HOST_POOL_METHODS[:info]) end def info_group() return super(HOST_POOL_METHODS[:info]) end alias_method :info!, :info alias_method :info_all!, :info_all alias_method :info_mine!, :info_mine alias_method :info_group!, :info_group # Retrieves the monitoring data for all the Hosts in the pool # # @param [Array<String>] xpath_expressions Elements to retrieve. # # @return [Hash<String, <Hash<String, Array<Array<int>>>>>, # OpenNebula::Error] The first level hash uses the Host ID as keys, # and as value a Hash with the requested xpath expressions, # and an Array of 'timestamp, value'. # # @example # host_pool.monitoring( # ['HOST_SHARE/FREE_CPU', # 'HOST_SHARE/RUNNING_VMS', # 'TEMPLATE/CUSTOM_PROBE'] ) # # {"1"=> # {"TEMPLATE/CUSTOM_PROBE"=>[], # "HOST_SHARE/FREE_CPU"=>[["1337609673", "800"]], # "HOST_SHARE/RUNNING_VMS"=>[["1337609673", "3"]]}, # "0"=> # {"TEMPLATE/CUSTOM_PROBE"=>[], # "HOST_SHARE/FREE_CPU"=>[["1337609673", "800"]], # "HOST_SHARE/RUNNING_VMS"=>[["1337609673", "3"]]}} def monitoring(xpath_expressions) return super(HOST_POOL_METHODS[:monitoring], xpath_expressions) end # Retrieves the monitoring data for all the Hosts in the pool, in XML # # @param [Integer] num Optional Retrieve monitor records in the last num # seconds. 0 just the last record, -1 or nil all records # # @return [String] VM monitoring data, in XML def monitoring_xml(num = nil) return @client.call(HOST_POOL_METHODS[:monitoring]) if num.nil? @client.call(HOST_POOL_METHODS[:monitoring], num.to_i) end end end
39.269565
80
0.46147
387840e0e245ee2517c8f6b781472f0f423c98e3
5,267
# frozen_string_literal: true # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # This file is the source Rails uses to define your schema when running `bin/rails # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2021_06_04_064754) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "crawl_tweets", id: :string, force: :cascade do |t| t.text "text", null: false t.datetime "tweeted_at", null: false t.string "user_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.string "event_url", null: false t.index ["user_id"], name: "index_crawl_tweets_on_user_id" end create_table "events", force: :cascade do |t| t.bigint "site_id", null: false t.integer "site_event_id", null: false t.string "title", null: false t.datetime "started_at", null: false t.datetime "ended_at", null: false t.string "banner", null: false t.string "url", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.string "description" t.index ["site_id", "site_event_id"], name: "index_events_on_site_and_site_event_id", unique: true t.index ["site_id"], name: "index_events_on_site_id" end create_table "friendships", force: :cascade do |t| t.string "follower_id", null: false t.string "followed_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["follower_id", "followed_id"], name: "index_friendships_on_follower_id_and_followed_id", unique: true end create_table "sites", force: :cascade do |t| t.string "name" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "tweet_crawl_settings", force: :cascade do |t| t.string "max_id", default: "0", null: false t.string "since_id", default: "0", null: false t.string "search_base_max_id", default: "0", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "tweets", id: :string, force: :cascade do |t| t.text "text", null: false t.datetime "tweeted_at", null: false t.string "user_id", null: false t.string "quoted_tweet_id" t.string "retweeted_tweet_id" t.bigint "event_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.datetime "retweet_last_updated_at" t.index ["event_id"], name: "index_tweets_on_event_id" t.index ["quoted_tweet_id"], name: "index_tweets_on_quoted_tweet_id" t.index ["retweeted_tweet_id"], name: "index_tweets_on_retweeted_tweet_id" t.index ["user_id"], name: "index_tweets_on_user_id" end create_table "user_event_settings", force: :cascade do |t| t.string "user_id", null: false t.integer "event_sort_type", default: 0, null: false t.integer "time_filter_type", default: 1, null: false t.integer "friends_filter_type", default: 0, null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["user_id"], name: "index_user_event_settings_on_user_id" end create_table "user_tokens", force: :cascade do |t| t.string "user_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.text "access_token_ciphertext" t.text "access_token_secret_ciphertext" t.index ["user_id"], name: "index_user_tokens_on_user_id" end create_table "users", id: :string, force: :cascade do |t| t.string "screen_name", null: false t.string "name", null: false t.string "profile_image", null: false t.string "uid" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.datetime "following_last_updated_at" t.string "following_next_cursor", default: "-1", null: false t.index ["uid"], name: "index_users_on_uid", unique: true end add_foreign_key "crawl_tweets", "users" add_foreign_key "events", "sites" add_foreign_key "friendships", "users", column: "followed_id" add_foreign_key "friendships", "users", column: "follower_id" add_foreign_key "tweets", "events" add_foreign_key "tweets", "tweets", column: "quoted_tweet_id" add_foreign_key "tweets", "tweets", column: "retweeted_tweet_id" add_foreign_key "tweets", "users" add_foreign_key "user_event_settings", "users" add_foreign_key "user_tokens", "users" end
42.475806
114
0.715588
e2d02fd4757cc8053d694eba88d9c1b98b824742
571
# # frozen_string_literal: true module OmniAuth module Strategies autoload :OIDC, Rails.root.join('lib', 'omniauth', 'strategies', 'openid_connect') end end Rails.application.config.middleware.use OmniAuth::Builder do provider( :OIDC, scope: ENV["SCOPES"], issuer: ENV["ISSUER"], extra_authorize_params: {'vtr' => ENV["VTR"]}, client_pem_signing_key_path: 'private_key.pem', client_options: { host: ENV["ISSUER"], redirect_uri: ENV["REDIRECT_URL"], identifier: ENV["CLIENT_ID"] } ) end
25.954545
86
0.639229
b91ccee371ef3aebc97012e8884e839e368a34ad
339
# frozen_string_literal: true module Primer module ViewComponents module VERSION MAJOR = 0 MINOR = 0 PATCH = 60 STRING = [MAJOR, MINOR, PATCH].join(".") end end end # rubocop:disable Rails/Output puts Primer::ViewComponents::VERSION::STRING if __FILE__ == $PROGRAM_NAME # rubocop:enable Rails/Output
18.833333
73
0.681416
116322ff28ccdda81f4ea3514e44585915fc5fba
1,859
class Sollya < Formula desc "Library for safe floating-point code development" homepage "https://sollya.gforge.inria.fr/" url "https://gforge.inria.fr/frs/download.php/file/37749/sollya-7.0.tar.gz" sha256 "30487b8242fb40ba0f4bc2ef23a8ef216477e57b1db277712fde1f53ceebb92a" bottle do cellar :any sha256 "ac847fff33b334ea8d07ac75463c36a710f1da98fef3c6f3265a21d0e700dd2e" => :big_sur sha256 "ff549e2fff8c593449a7bf92d2d2d7ff423c6a40885838d5be4d7852308a4b28" => :catalina sha256 "5a3569111ea2936599668fc075a146ebfd01f471613b7c695a6a3d031ea6a309" => :mojave sha256 "5b5b3762879216a04a4fbcea2fa5407dddb331510a9e01f768d684ebdcd99c66" => :high_sierra end depends_on "automake" => :build depends_on "pkg-config" => :test depends_on "fplll" depends_on "gmp" depends_on "mpfi" depends_on "mpfr" uses_from_macos "libxml2" def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make", "install" end test do (testpath/"cos.sollya").write(<<~EOF) write(taylor(2*cos(x),1,0)) > "two.txt"; quit; EOF system bin/"sollya", "cos.sollya" assert_equal "2", File.read(testpath/"two.txt") end test do (testpath/"test.c").write(<<~EOF) #include <sollya.h> int main(void) { sollya_obj_t f; sollya_lib_init(); f = sollya_lib_pi(); sollya_lib_printf("%b", f); sollya_lib_clear_obj(f); sollya_lib_close(); return 0; } EOF pkg_config_flags = `pkg-config --cflags --libs gmp mpfr fplll`.chomp.split system ENV.cc, "test.c", *pkg_config_flags, "-I#{include}", "-L#{lib}", "-lsollya", "-o", "test" assert_equal "pi", `./test` end end
30.983333
100
0.651963
f8c68da6f59a6302cbbe30020d5c3ab8f8799f3a
1,156
# # Cookbook: consul # License: Apache 2.0 # # Copyright 2014-2016, Bloomberg Finance L.P. # require 'poise' module ConsulCookbook module Resource # Resource for providing `consul exec` functionality. # @since 1.0.0 class ConsulExecute < Chef::Resource include Poise(fused: true) provides(:consul_execute) default_action(:run) attribute(:command, kind_of: String, name_attribute: true) attribute(:environment, kind_of: Hash, default: { 'PATH' => '/usr/local/bin:/usr/bin:/bin' }) attribute(:options, option_collector: true, default: {}) action(:run) do options = new_resource.options.map do |k, v| next if v.is_a?(NilClass) || v.is_a?(FalseClass) if v.is_a?(TrueClass) "-#{k}" else ["-#{k}", v].join('=') end end command = ['/usr/bin/env consul exec', options, new_resource.command].flatten.compact notifying_block do execute command.join(' ') do environment new_resource.environment end end end end end end
25.130435
99
0.57872
1d2272d30ff46fbd7b897dc6161c0b65b5ea9565
3,937
#!/usr/bin/env ruby require_relative '../config/active_record_config' require_relative '../models/database/inv_type' require_relative '../models/build/job' require_relative '../models/build/waste_calculator' require_relative '../models/build/materials_calculator' require_relative '../models/build/pricing_calculator' require_relative '../models/build/decryptor_repository' require_relative '../models/build/invention_strategy' require_relative '../models/build/invention_probability_calculator' require_relative '../models/build/invention_cost_calculator' require_relative '../models/pricing/default_pricing_model' require_relative '../presentation/formatting' class DecryptorStrategy def initialize(decryptor) @decryptor = decryptor end def decryptor(item, options = {}) @decryptor end end class TechIStrategy def techI_item(item, options = {}) nil end def techI_item_meta_level(item, options = {}) 0 end end class MaterialLevelCalculator def initialize(modifier) @material_level = -4 + modifier end def material_level(item) @material_level end end class DecryptorReport def initialize @pricing = DefaultPricingModel.new.pricing @pricing_calculator = PricingCalculator.new(@pricing) @decryptor_repository = DecryptorRepository.new end def run(typeName) item = InvType.find_by_typeName(typeName) if !item.is_ship? puts "The decryptor report is only set up for ships. Sorry." exit end job = Job.new(item, 1) base_material_level_calculator = MaterialLevelCalculator.new(0) base_waste_calculator = WasteCalculator.new(5, base_material_level_calculator) base_materials_calculator = MaterialsCalculator.new(base_waste_calculator) base_data = job .accept(base_materials_calculator) .accept(@pricing_calculator) .data data = @decryptor_repository.types.map do |type| decryptor = @decryptor_repository.find(item, type) decryptor_strategy = DecryptorStrategy.new(decryptor) invention_strategy = InventionStrategy.new(decryptor_strategy, TechIStrategy.new) invention_calculator = InventionProbabilityCalculator.new(invention_strategy, @decryptor_repository) invention_cost = InventionCostCalculator.new(@pricing, invention_calculator, invention_strategy) material_level_calculator = MaterialLevelCalculator.new(@decryptor_repository.me_modifier(decryptor)) waste_calculator = WasteCalculator.new(5, material_level_calculator) materials_calculator = MaterialsCalculator.new(waste_calculator) build_data = job .accept(materials_calculator) .accept(invention_cost) .accept(@pricing_calculator) .data { name: decryptor.typeName, materials: build_data[:invention_materials], build_cost: build_data[:material_cost], build_profit: build_data[:profit], invention_cost: build_data[:invention_cost], invention_profit: build_data[:profit] - base_data[:profit], } end puts puts "-" * 50 puts item.typeName puts "-" * 50 puts puts "Sell price: #{Formatting.format_isk(base_data[:value])}" puts "Base cost: #{Formatting.format_isk(base_data[:material_cost])}" puts "Profit with no decryptors: #{Formatting.format_isk(base_data[:profit])}" puts data .sort_by { |d| d[:invention_profit] } .each do |d| puts d[:name] puts "\tBuild cost: #{Formatting.format_isk(d[:build_cost])}" puts "\tBuild value: #{Formatting.format_isk(base_data[:value])}" puts "\tBuild profit: #{Formatting.format_isk(d[:build_profit])}" puts "\tInvention cost per run: #{Formatting.format_isk(d[:invention_cost])}" puts "\tInvention profit per run: #{Formatting.format_isk(d[:invention_profit])}" puts "\tMaterials:" d[:materials].each do |material, quantity| puts "\t\t#{quantity} #{material.typeName} at #{Formatting.format_isk(@pricing.buy_price(material))}" end puts "" end end end ActiveRecordConfig.init DecryptorReport.new().run(ARGV[0])
30.053435
106
0.758954
1ab193e4e5b80311d752c28a1dde25f038a129a3
9,250
describe 'Ridgepole::Client#diff -> migrate' do context 'when change index' do let(:dsl) { erbh(<<-EOS) create_table "clubs", force: :cascade do |t| t.string "name", default: "", null: false t.index ["name"], name: "idx_name", unique: true, <%= i cond(5.0, using: :btree) %> end create_table "departments", primary_key: "dept_no", force: :cascade do |t| t.string "dept_name", limit: 40, null: false t.index ["dept_name"], name: "dept_name", unique: true, <%= i cond(5.0, using: :btree) %> end create_table "dept_emp", id: false, force: :cascade do |t| t.integer "emp_no", null: false t.string "dept_no", null: false t.date "from_date", null: false t.date "to_date", null: false t.index ["dept_no"], name: "dept_no", <%= i cond(5.0, using: :btree) %> t.index ["emp_no"], name: "emp_no", <%= i cond(5.0, using: :btree) %> end create_table "dept_manager", id: false, force: :cascade do |t| t.string "dept_no", null: false t.integer "emp_no", null: false t.date "from_date", null: false t.date "to_date", null: false t.index ["dept_no"], name: "dept_no", <%= i cond(5.0, using: :btree) %> t.index ["emp_no"], name: "emp_no", <%= i cond(5.0, using: :btree) %> end create_table "employee_clubs", force: :cascade do |t| t.integer "emp_no", null: false t.integer "club_id", null: false t.index ["emp_no", "club_id"], name: "idx_emp_no_club_id", <%= i cond(5.0, using: :btree) %> end create_table "employees", primary_key: "emp_no", force: :cascade do |t| t.date "birth_date", null: false t.string "first_name", limit: 14, null: false t.string "last_name", limit: 16, null: false t.string "gender", limit: 1, null: false t.date "hire_date", null: false end create_table "salaries", id: false, force: :cascade do |t| t.integer "emp_no", null: false t.integer "salary", null: false t.date "from_date", null: false t.date "to_date", null: false t.index ["emp_no"], name: "emp_no", <%= i cond(5.0, using: :btree) %> end create_table "titles", id: false, force: :cascade do |t| t.integer "emp_no", null: false t.string "title", limit: 50, null: false t.date "from_date", null: false t.date "to_date" t.index ["emp_no"], name: "emp_no", <%= i cond(5.0, using: :btree) %> end EOS } let(:actual_dsl) { erbh(<<-EOS) create_table "clubs", force: :cascade do |t| t.string "name", default: "", null: false t.index ["name"], name: "idx_name", unique: true, <%= i cond(5.0, using: :btree) %> end create_table "departments", primary_key: "dept_no", force: :cascade do |t| t.string "dept_name", limit: 40, null: false t.index ["dept_name"], name: "dept_name", unique: true, <%= i cond(5.0, using: :btree) %> end create_table "dept_emp", id: false, force: :cascade do |t| t.integer "emp_no", null: false t.string "dept_no", null: false t.date "from_date", null: false t.date "to_date", null: false t.index ["dept_no"], name: "dept_no", <%= i cond(5.0, using: :btree) %> t.index ["emp_no"], name: "emp_no", <%= i cond(5.0, using: :btree) %> end create_table "dept_manager", id: false, force: :cascade do |t| t.string "dept_no", null: false t.integer "emp_no", null: false t.date "from_date", null: false t.date "to_date", null: false t.index ["dept_no"], name: "dept_no", <%= i cond(5.0, using: :btree) %> t.index ["emp_no"], name: "emp_no", <%= i cond(5.0, using: :btree) %> end create_table "employee_clubs", force: :cascade do |t| t.integer "emp_no", null: false t.integer "club_id", null: false t.index ["emp_no", "club_id"], name: "idx_emp_no_club_id", <%= i cond(5.0, using: :btree) %> end create_table "employees", primary_key: "emp_no", force: :cascade do |t| t.date "birth_date", null: false t.string "first_name", limit: 14, null: false t.string "last_name", limit: 16, null: false t.string "gender", limit: 1, null: false t.date "hire_date", null: false end create_table "salaries", id: false, force: :cascade do |t| t.integer "emp_no", null: false t.integer "salary", null: false t.date "from_date", null: false t.date "to_date", null: false t.index ["emp_no"], name: "emp_no", <%= i cond(5.0, using: :btree) %> end create_table "titles", id: false, force: :cascade do |t| t.integer "emp_no", null: false t.string "title", limit: 50, null: false t.date "from_date", null: false t.date "to_date" t.index ["emp_no"], name: "emp_no", <%= i cond(5.0, using: :btree) %> end EOS } let(:expected_dsl) { erbh(<<-EOS) create_table "clubs", force: :cascade do |t| t.string "name", default: "", null: false t.index ["name"], name: "idx_name", unique: true, <%= i cond(5.0, using: :btree) %> end create_table "departments", primary_key: "dept_no", force: :cascade do |t| t.string "dept_name", limit: 40, null: false t.index ["dept_name"], name: "dept_name", unique: true, <%= i cond(5.0, using: :btree) %> end create_table "dept_emp", id: false, force: :cascade do |t| t.integer "emp_no", null: false t.string "dept_no", null: false t.date "from_date", null: false t.date "to_date", null: false t.index ["dept_no"], name: "dept_no", <%= i cond(5.0, using: :btree) %> t.index ["from_date"], name: "emp_no", <%= i cond(5.0, using: :btree) %> end create_table "dept_manager", id: false, force: :cascade do |t| t.string "dept_no", null: false t.integer "emp_no", null: false t.date "from_date", null: false t.date "to_date", null: false t.index ["dept_no"], name: "dept_no", <%= i cond(5.0, using: :btree) %> t.index ["from_date"], name: "emp_no", <%= i cond(5.0, using: :btree) %> end create_table "employee_clubs", force: :cascade do |t| t.integer "emp_no", null: false t.integer "club_id", null: false t.index ["emp_no", "club_id"], name: "idx_emp_no_club_id", <%= i cond(5.0, using: :btree) %> end create_table "employees", primary_key: "emp_no", force: :cascade do |t| t.date "birth_date", null: false t.string "first_name", limit: 14, null: false t.string "last_name", limit: 16, null: false t.string "gender", limit: 1, null: false t.date "hire_date", null: false end create_table "salaries", id: false, force: :cascade do |t| t.integer "emp_no", null: false t.integer "salary", null: false t.date "from_date", null: false t.date "to_date", null: false t.index ["from_date"], name: "emp_no", <%= i cond(5.0, using: :btree) %> end create_table "titles", id: false, force: :cascade do |t| t.integer "emp_no", null: false t.string "title", limit: 50, null: false t.date "from_date", null: false t.date "to_date" t.index ["emp_no"], name: "emp_no", <%= i cond(5.0, using: :btree) %> end EOS } before { subject.diff(actual_dsl).migrate } subject { client } it { delta = subject.diff(expected_dsl) expect(delta.differ?).to be_truthy expect(subject.dump).to match_ruby actual_dsl delta.migrate expect(subject.dump).to match_ruby expected_dsl } it { delta = client(:bulk_change => true).diff(expected_dsl) expect(delta.differ?).to be_truthy expect(subject.dump).to match_ruby actual_dsl expect(delta.script).to match_fuzzy <<-EOS change_table("dept_emp", {:bulk => true}) do |t| t.remove_index({:name=>"emp_no"}) t.index(["from_date"], {:name=>"emp_no", :using=>:btree, :unique=>false}) end change_table("dept_manager", {:bulk => true}) do |t| t.remove_index({:name=>"emp_no"}) t.index(["from_date"], {:name=>"emp_no", :using=>:btree, :unique=>false}) end change_table("salaries", {:bulk => true}) do |t| t.remove_index({:name=>"emp_no"}) t.index(["from_date"], {:name=>"emp_no", :using=>:btree, :unique=>false}) end EOS # XXX: Can not add an index of the same name expect { delta.migrate }.to raise_error(/Index name 'emp_no' on table 'dept_emp' already exists/) } end end
40.570175
102
0.544432
bbbdc7f2e1a7bf5d80e928571652e1b5bdb4b507
1,152
require 'test_helper' class ArticlesControllerTest < ActionDispatch::IntegrationTest setup do @article = articles(:one) end test "should get index" do get articles_url assert_response :success end test "should get new" do get new_article_url assert_response :success end test "should create article" do assert_difference('Article.count') do post articles_url, params: { article: { excerpt: @article.excerpt, name: @article.name, text: @article.text } } end assert_redirected_to article_url(Article.last) end test "should show article" do get article_url(@article) assert_response :success end test "should get edit" do get edit_article_url(@article) assert_response :success end test "should update article" do patch article_url(@article), params: { article: { excerpt: @article.excerpt, name: @article.name, text: @article.text } } assert_redirected_to article_url(@article) end test "should destroy article" do assert_difference('Article.count', -1) do delete article_url(@article) end assert_redirected_to articles_url end end
23.510204
125
0.713542
bbff5bf4f8a857ff7f5ef8eafe29c394a9fbe08c
353
require 'bibmarkdown' require 'bibtex' require 'csl/styles' Nanoc::Filter.define(:bibmarkdown) do |content, params| entries = BibTeX.parse(params[:bibfile].raw_content).entries entries.each_value { |e| e.convert!(:latex) { |key| key != :url } } params = params.merge(entries: entries) BibMarkdown::Document.new(content, params).to_markdown end
32.090909
69
0.733711
b9206b167cd78504b53475d8109816100fb57ab9
4,487
module RailsSemanticLogger # Options for controlling Rails Semantic Logger behavior # # * Convert Action Controller and Active Record text messages to semantic data # # Rails -- Started -- { :ip => "127.0.0.1", :method => "GET", :path => "/dashboards/inquiry_recent_activity" } # UserController -- Completed #index -- { :action => "index", :db_runtime => 54.64, :format => "HTML", :method => "GET", :mongo_runtime => 0.0, :path => "/users", :status => 200, :status_message => "OK", :view_runtime => 709.88 } # # config.rails_semantic_logger.semantic = true # # * Change Rack started message to debug so that it does not appear in production # # config.rails_semantic_logger.started = false # # * Change Processing message to debug so that it does not appear in production # # config.rails_semantic_logger.processing = false # # * Change Action View render log messages to debug so that they do not appear in production # # ActionView::Base -- Rendered data/search/_user.html.haml (46.7ms) # # config.rails_semantic_logger.rendered = false # # * Override the Awesome Print options for logging Hash data as text: # # Any valid AwesomePrint option for rendering data. # The defaults can changed be creating a `~/.aprc` file. # See: https://github.com/michaeldv/awesome_print # # Note: The option :multiline is set to false if not supplied. # Note: Has no effect if Awesome Print is not installed. # # config.rails_semantic_logger.ap_options = {multiline: false} # # * Whether to automatically add an environment specific log file appender. # For Example: 'log/development.log' # # Note: # When Semantic Logger fails to log to an appender it logs the error to an # internal logger, which by default writes to STDERR. # Example, change the default internal logger to log to stdout: # SemanticLogger::Processor.logger = SemanticLogger::Appender::File.new(io: STDOUT, level: :warn) # # config.rails_semantic_logger.add_file_appender = true # # * Silence asset logging # # config.rails_semantic_logger.quiet_assets = false # # * Override the output format for the primary Rails log file. # # Valid options: # * :default # Plain text output with no color. # * :color # Plain text output with color. # * :json # JSON output format. # * class # # * Proc # A block that will be called to format the output. # It is supplied with the `log` entry and should return the formatted data. # # Note: # * `:default` is automatically changed to `:color` if `config.colorize_logging` is `true`. # # JSON Example, in `application.rb`: # config.rails_semantic_logger.format = :json # # Custom Example, create `app/lib/my_formatter.rb`: # # # My Custom colorized formatter # class MyFormatter < SemanticLogger::Formatters::Color # # Return the complete log level name in uppercase # def level # "#{color}log.level.upcase#{color_map.clear}" # end # end # # # In application.rb: # config.rails_semantic_logger.format = MyFormatter.new # # # config.rails_semantic_logger.format = :default # # * Add a filter to the file logger [Regexp|Proc] # RegExp: Only include log messages where the class name matches the supplied # regular expression. All other messages will be ignored. # Proc: Only include log messages where the supplied Proc returns true. # The Proc must return true or false. # # config.rails_semantic_logger.filter = nil # # * named_tags: *DEPRECATED* # Instead, supply a Hash to config.log_tags # config.rails_semantic_logger.named_tags = nil class Options attr_accessor :semantic, :started, :processing, :rendered, :ap_options, :add_file_appender, :quiet_assets, :format, :named_tags, :filter # Setup default values def initialize @semantic = true @started = false @processing = false @rendered = false @ap_options = {multiline: false} @add_file_appender = true @quiet_assets = false @format = :default @named_tags = nil @filter = nil end end end
38.025424
235
0.633385
ff27b2208312cc2d7c164e6775e0fb861687f941
2,379
# frozen_string_literal: true module GraphQL module StaticValidation module ArgumentLiteralsAreCompatible def on_argument(node, parent) # Check the child arguments first; # don't add a new error if one of them reports an error super # Don't validate variables here if node.value.is_a?(GraphQL::Language::Nodes::VariableIdentifier) return end if @context.schema.error_bubbling || context.errors.none? { |err| err.path.take(@path.size) == @path } parent_defn = parent_definition(parent) if parent_defn && (arg_defn = parent_defn.arguments[node.name]) validation_result = context.validate_literal(node.value, arg_defn.type) if !validation_result.valid? kind_of_node = node_type(parent) error_arg_name = parent_name(parent, parent_defn) string_value = if node.value == Float::INFINITY "" else " (#{GraphQL::Language::Printer.new.print(node.value)})" end problems = validation_result.problems first_problem = problems && problems.first if first_problem message = first_problem["message"] # This is some legacy stuff from when `CoercionError` was raised thru the stack if message coerce_extensions = first_problem["extensions"] || { "code" => "argumentLiteralsIncompatible" } end end error_options = { nodes: parent, type: kind_of_node, argument_name: node.name, argument: arg_defn, value: node.value } if coerce_extensions error_options[:coerce_extensions] = coerce_extensions end message ||= "Argument '#{node.name}' on #{kind_of_node} '#{error_arg_name}' has an invalid value#{string_value}. Expected type '#{arg_defn.type.to_type_signature}'." error = GraphQL::StaticValidation::ArgumentLiteralsAreCompatibleError.new( message, **error_options ) add_error(error) end end end end end end end
35.507463
179
0.559058
616e07434706ad8e2c7946e0373b687fdac5eb3b
1,792
# frozen_string_literal: true Rails.application.configure do # Settings specified here will take precedence over those in # config/application.rb. # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Configure static file server for tests with Cache-Control for performance. config.serve_static_files = true config.static_cache_control = 'public, max-age=3600' # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. # config.action_mailer.delivery_method = :test # Randomize the order test cases are executed. config.active_support.test_order = :random # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end
38.956522
79
0.773438
18cc0d313a84c166e63db4c43f077ead7f76359f
9,949
require File.dirname(__FILE__) + '/../../spec_helper' require 'controller_spec_controller' ['integration', 'isolation'].each do |mode| describe "A controller example running in #{mode} mode", :type => :controller do controller_name :controller_spec integrate_views if mode == 'integration' specify "this example should be pending, not an error" it "should provide controller.session as session" do get 'action_with_template' session.should equal(controller.session) end it "should provide the same session object before and after the action" do session_before = session get 'action_with_template' session.should equal(session_before) end it "should keep the same data in the session before and after the action" do session[:foo] = :bar get 'action_with_template' session[:foo].should == :bar end it "should ensure controller.session is NOT nil before the action" do controller.session.should_not be_nil get 'action_with_template' end it "should ensure controller.session is NOT nil after the action" do get 'action_with_template' controller.session.should_not be_nil end it "should allow specifying a partial with partial name only" do get 'action_with_partial' response.should render_template("_partial") end it "should allow specifying a partial with should_receive(:render)" do controller.should_receive(:render).with(:partial => "controller_spec/partial") get 'action_with_partial' end it "should allow specifying a partial with should_receive(:render) with object" do controller.should_receive(:render).with(:partial => "controller_spec/partial", :object => "something") get 'action_with_partial_with_object', :thing => "something" end it "should allow specifying a partial with should_receive(:render) with locals" do controller.should_receive(:render).with(:partial => "controller_spec/partial", :locals => {:thing => "something"}) get 'action_with_partial_with_locals', :thing => "something" end it "should yield to render :update" do template = stub("template") controller.should_receive(:render).with(:update).and_yield(template) template.should_receive(:replace).with(:bottom, "replace_me", :partial => "non_existent_partial") get 'action_with_render_update' end it "should allow a path relative to RAILS_ROOT/app/views/ when specifying a partial" do get 'action_with_partial' response.should render_template("controller_spec/_partial") end it "should provide access to flash" do get 'action_which_sets_flash' flash[:flash_key].should == "flash value" end it "should provide access to flash values set after a session reset" do get 'action_setting_flash_after_session_reset' flash[:after_reset].should == "available" end it "should not provide access to flash values set before a session reset" do get 'action_setting_flash_before_session_reset' flash[:before_reset].should_not == "available" end it "should provide access to session" do session[:session_key] = "session value" lambda do get 'action_which_gets_session', :expected => "session value" end.should_not raise_error end describe "handling should_receive(:render)" do it "should warn" do controller.should_receive(:render).with(:template => "controller_spec/action_with_template") get :action_with_template end end describe "handling should_not_receive(:render)" do it "should warn" do controller.should_not_receive(:render).with(:template => "the/wrong/template") get :action_with_template end end describe "handling deprecated expect_render" do it "should warn" do Kernel.should_receive(:warn).with(/expect_render is deprecated/) controller.expect_render(:template => "controller_spec/action_with_template") get :action_with_template end end describe "handling deprecated stub_render" do it "should warn" do Kernel.should_receive(:warn).with(/stub_render is deprecated/) controller.stub_render(:template => "controller_spec/action_with_template") get :action_with_template end end describe "setting cookies in the request" do it "should support a String key" do cookies['cookie_key'] = 'cookie value' get 'action_which_gets_cookie', :expected => "cookie value" end it "should support a Symbol key" do cookies[:cookie_key] = 'cookie value' get 'action_which_gets_cookie', :expected => "cookie value" end if Rails::VERSION::STRING >= "2.0.0" it "should support a Hash value" do cookies[:cookie_key] = {'value' => 'cookie value', 'path' => '/not/default'} get 'action_which_gets_cookie', :expected => {'value' => 'cookie value', 'path' => '/not/default'} end end end describe "reading cookies from the response" do it "should support a Symbol key" do get 'action_which_sets_cookie', :value => "cookie value" cookies[:cookie_key].value.should == ["cookie value"] end it "should support a String key" do get 'action_which_sets_cookie', :value => "cookie value" cookies['cookie_key'].value.should == ["cookie value"] end end it "should support custom routes" do route_for(:controller => "custom_route_spec", :action => "custom_route").should == "/custom_route" end it "should support existing routes" do route_for(:controller => "controller_spec", :action => "some_action").should == "/controller_spec/some_action" end it "should generate params for custom routes" do params_from(:get, '/custom_route').should == {:controller => "custom_route_spec", :action => "custom_route"} end it "should generate params for existing routes" do params_from(:get, '/controller_spec/some_action').should == {:controller => "controller_spec", :action => "some_action"} end it "should expose instance vars through the assigns hash" do get 'action_setting_the_assigns_hash' assigns[:indirect_assigns_key].should == :indirect_assigns_key_value end it "should expose instance vars through the assigns hash that are set to false" do get 'action_that_assigns_false_to_a_variable' assigns[:a_variable].should be_false end it "should NOT complain when calling should_receive with arguments other than :render" do controller.should_receive(:anything_besides_render) lambda { controller.rspec_verify }.should raise_error(Exception, /expected :anything_besides_render/) end it "should not run a skipped before_filter" do lambda { get 'action_with_skipped_before_filter' }.should_not raise_error end end describe "Given a controller spec for RedirectSpecController running in #{mode} mode", :type => :controller do controller_name :redirect_spec integrate_views if mode == 'integration' it "a redirect should ignore the absence of a template" do get 'action_with_redirect_to_somewhere' response.should be_redirect response.redirect_url.should == "http://test.host/redirect_spec/somewhere" response.should redirect_to("http://test.host/redirect_spec/somewhere") end it "a call to response.should redirect_to should fail if no redirect" do get 'action_with_no_redirect' lambda { response.redirect?.should be_true }.should fail lambda { response.should redirect_to("http://test.host/redirect_spec/somewhere") }.should fail_with("expected redirect to \"http://test.host/redirect_spec/somewhere\", got no redirect") end end describe "Given a controller spec running in #{mode} mode" do example_group = describe "A controller spec" # , :type => :controller do # integrate_views if mode == 'integration' it "a spec in a context without controller_name set should fail with a useful warning" do pending("need a new way to deal with examples that should_raise") # , # :should_raise => [ # Spec::Expectations::ExpectationNotMetError, # /You have to declare the controller name in controller specs/ # ] do end end end ['integration', 'isolation'].each do |mode| describe "A controller example running in #{mode} mode", :type => :controller do controller_name :controller_inheriting_from_application_controller integrate_views if mode == 'integration' it "should only have a before filter inherited from ApplicationController run once..." do controller.should_receive(:i_should_only_be_run_once).once get :action_with_inherited_before_filter end end end describe ControllerSpecController, :type => :controller do it "should not require naming the controller if describe is passed a type" do end end describe "A controller spec with controller_name set", :type => :controller do controller_name :controller_spec describe "nested" do it "should inherit the controller name" do get 'action_with_template' response.should be_success end end end module Spec module Rails module Example describe ControllerExampleGroup do it "should clear its name from the description" do group = describe("foo", :type => :controller) do $nested_group = describe("bar") do end end group.description.to_s.should == "foo" $nested_group.description.to_s.should == "foo bar" end end end end end
35.659498
126
0.681978
0124c39c3be9c89428571d273828c0d60eaa379c
260
бот устанавливает локальный доступ для указанного пользователя {command} [!/доступ] [jid/nick] */{command} 6 Оби-Ван Кеноби бот установит локальный доступ 6 для Оби-Ван Кеноби */{command} ! [email protected] бот снимет доступ с [email protected]
43.333333
63
0.769231
bb5cd2aae430c1588f269d5b604d8b5a2ee83103
731
# # Cookbook Name:: patch-management # Recipe:: default # # Copyright 2014, Chef Software, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # include_recipe 'patch-management::audit' include_recipe 'patch-management::remediate'
33.227273
74
0.760602
6a9c78a87bd46433d14d4aa14fb78b9c63c1c5c7
135
#encoding: utf-8 class MobilyApiUnicodeConverter def self.convert(str) str.chars.map{ |x| '%04x' % x.ord }.join.upcase end end
19.285714
51
0.696296
4a51f1e3c740a7529ac9adf9a65ae281228401c6
28,907
## # This code was generated by # \ / _ _ _| _ _ # | (_)\/(_)(_|\/| |(/_ v1.0.0 # / / # # frozen_string_literal: true module Twilio module REST class Api < Domain class V2010 < Version class AccountContext < InstanceContext class ApplicationList < ListResource ## # Initialize the ApplicationList # @param [Version] version Version that contains the resource # @param [String] account_sid The SID of the # [Account](https://www.twilio.com/docs/api/rest/account) that created the # Application resource. # @return [ApplicationList] ApplicationList def initialize(version, account_sid: nil) super(version) # Path Solution @solution = {account_sid: account_sid} @uri = "/Accounts/#{@solution[:account_sid]}/Applications.json" end ## # Retrieve a single page of ApplicationInstance records from the API. # Request is executed immediately. # @param [String] friendly_name A descriptive string that you create to describe # the new application. It can be up to 64 characters long. # @param [String] api_version The API version to use to start a new TwiML session. # Can be: `2010-04-01` or `2008-08-01`. The default value is the account's default # API version. # @param [String] voice_url The URL we should call when the phone number assigned # to this application receives a call. # @param [String] voice_method The HTTP method we should use to call `voice_url`. # Can be: `GET` or `POST`. # @param [String] voice_fallback_url The URL that we should call when an error # occurs retrieving or executing the TwiML requested by `url`. # @param [String] voice_fallback_method The HTTP method we should use to call # `voice_fallback_url`. Can be: `GET` or `POST`. # @param [String] status_callback The URL we should call using the # `status_callback_method` to send status information to your application. # @param [String] status_callback_method The HTTP method we should use to call # `status_callback`. Can be: `GET` or `POST`. # @param [Boolean] voice_caller_id_lookup Whether we should look up the caller's # caller-ID name from the CNAM database (additional charges apply). Can be: `true` # or `false`. # @param [String] sms_url The URL we should call when the phone number receives an # incoming SMS message. # @param [String] sms_method The HTTP method we should use to call `sms_url`. Can # be: `GET` or `POST`. # @param [String] sms_fallback_url The URL that we should call when an error # occurs while retrieving or executing the TwiML from `sms_url`. # @param [String] sms_fallback_method The HTTP method we should use to call # `sms_fallback_url`. Can be: `GET` or `POST`. # @param [String] sms_status_callback The URL we should call using a POST method # to send status information about SMS messages sent by the application. # @param [String] message_status_callback The URL we should call using a POST # method to send message status information to your application. # @return [ApplicationInstance] Newly created ApplicationInstance def create(friendly_name: nil, api_version: :unset, voice_url: :unset, voice_method: :unset, voice_fallback_url: :unset, voice_fallback_method: :unset, status_callback: :unset, status_callback_method: :unset, voice_caller_id_lookup: :unset, sms_url: :unset, sms_method: :unset, sms_fallback_url: :unset, sms_fallback_method: :unset, sms_status_callback: :unset, message_status_callback: :unset) data = Twilio::Values.of({ 'FriendlyName' => friendly_name, 'ApiVersion' => api_version, 'VoiceUrl' => voice_url, 'VoiceMethod' => voice_method, 'VoiceFallbackUrl' => voice_fallback_url, 'VoiceFallbackMethod' => voice_fallback_method, 'StatusCallback' => status_callback, 'StatusCallbackMethod' => status_callback_method, 'VoiceCallerIdLookup' => voice_caller_id_lookup, 'SmsUrl' => sms_url, 'SmsMethod' => sms_method, 'SmsFallbackUrl' => sms_fallback_url, 'SmsFallbackMethod' => sms_fallback_method, 'SmsStatusCallback' => sms_status_callback, 'MessageStatusCallback' => message_status_callback, }) payload = @version.create( 'POST', @uri, data: data ) ApplicationInstance.new(@version, payload, account_sid: @solution[:account_sid], ) end ## # Lists ApplicationInstance records from the API as a list. # Unlike stream(), this operation is eager and will load `limit` records into # memory before returning. # @param [String] friendly_name The string that identifies the Application # resources to read. # @param [Integer] limit Upper limit for the number of records to return. stream() # guarantees to never return more than limit. Default is no limit # @param [Integer] page_size Number of records to fetch per request, when # not set will use the default value of 50 records. If no page_size is defined # but a limit is defined, stream() will attempt to read the limit with the most # efficient page size, i.e. min(limit, 1000) # @return [Array] Array of up to limit results def list(friendly_name: :unset, limit: nil, page_size: nil) self.stream(friendly_name: friendly_name, limit: limit, page_size: page_size).entries end ## # Streams ApplicationInstance records from the API as an Enumerable. # This operation lazily loads records as efficiently as possible until the limit # is reached. # @param [String] friendly_name The string that identifies the Application # resources to read. # @param [Integer] limit Upper limit for the number of records to return. stream() # guarantees to never return more than limit. Default is no limit. # @param [Integer] page_size Number of records to fetch per request, when # not set will use the default value of 50 records. If no page_size is defined # but a limit is defined, stream() will attempt to read the limit with the most # efficient page size, i.e. min(limit, 1000) # @return [Enumerable] Enumerable that will yield up to limit results def stream(friendly_name: :unset, limit: nil, page_size: nil) limits = @version.read_limits(limit, page_size) page = self.page(friendly_name: friendly_name, page_size: limits[:page_size], ) @version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit]) end ## # When passed a block, yields ApplicationInstance records from the API. # This operation lazily loads records as efficiently as possible until the limit # is reached. def each limits = @version.read_limits page = self.page(page_size: limits[:page_size], ) @version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit]).each {|x| yield x} end ## # Retrieve a single page of ApplicationInstance records from the API. # Request is executed immediately. # @param [String] friendly_name The string that identifies the Application # resources to read. # @param [String] page_token PageToken provided by the API # @param [Integer] page_number Page Number, this value is simply for client state # @param [Integer] page_size Number of records to return, defaults to 50 # @return [Page] Page of ApplicationInstance def page(friendly_name: :unset, page_token: :unset, page_number: :unset, page_size: :unset) params = Twilio::Values.of({ 'FriendlyName' => friendly_name, 'PageToken' => page_token, 'Page' => page_number, 'PageSize' => page_size, }) response = @version.page( 'GET', @uri, params ) ApplicationPage.new(@version, response, @solution) end ## # Retrieve a single page of ApplicationInstance records from the API. # Request is executed immediately. # @param [String] target_url API-generated URL for the requested results page # @return [Page] Page of ApplicationInstance def get_page(target_url) response = @version.domain.request( 'GET', target_url ) ApplicationPage.new(@version, response, @solution) end ## # Provide a user friendly representation def to_s '#<Twilio.Api.V2010.ApplicationList>' end end class ApplicationPage < Page ## # Initialize the ApplicationPage # @param [Version] version Version that contains the resource # @param [Response] response Response from the API # @param [Hash] solution Path solution for the resource # @return [ApplicationPage] ApplicationPage def initialize(version, response, solution) super(version, response) # Path Solution @solution = solution end ## # Build an instance of ApplicationInstance # @param [Hash] payload Payload response from the API # @return [ApplicationInstance] ApplicationInstance def get_instance(payload) ApplicationInstance.new(@version, payload, account_sid: @solution[:account_sid], ) end ## # Provide a user friendly representation def to_s '<Twilio.Api.V2010.ApplicationPage>' end end class ApplicationContext < InstanceContext ## # Initialize the ApplicationContext # @param [Version] version Version that contains the resource # @param [String] account_sid The SID of the # [Account](https://www.twilio.com/docs/api/rest/account) that created the # Application resource to fetch. # @param [String] sid The Twilio-provided string that uniquely identifies the # Application resource to fetch. # @return [ApplicationContext] ApplicationContext def initialize(version, account_sid, sid) super(version) # Path Solution @solution = {account_sid: account_sid, sid: sid, } @uri = "/Accounts/#{@solution[:account_sid]}/Applications/#{@solution[:sid]}.json" end ## # Deletes the ApplicationInstance # @return [Boolean] true if delete succeeds, true otherwise def delete @version.delete('delete', @uri) end ## # Fetch a ApplicationInstance # @return [ApplicationInstance] Fetched ApplicationInstance def fetch params = Twilio::Values.of({}) payload = @version.fetch( 'GET', @uri, params, ) ApplicationInstance.new( @version, payload, account_sid: @solution[:account_sid], sid: @solution[:sid], ) end ## # Update the ApplicationInstance # @param [String] friendly_name A descriptive string that you create to describe # the resource. It can be up to 64 characters long. # @param [String] api_version The API version to use to start a new TwiML session. # Can be: `2010-04-01` or `2008-08-01`. The default value is your account's # default API version. # @param [String] voice_url The URL we should call when the phone number assigned # to this application receives a call. # @param [String] voice_method The HTTP method we should use to call `voice_url`. # Can be: `GET` or `POST`. # @param [String] voice_fallback_url The URL that we should call when an error # occurs retrieving or executing the TwiML requested by `url`. # @param [String] voice_fallback_method The HTTP method we should use to call # `voice_fallback_url`. Can be: `GET` or `POST`. # @param [String] status_callback The URL we should call using the # `status_callback_method` to send status information to your application. # @param [String] status_callback_method The HTTP method we should use to call # `status_callback`. Can be: `GET` or `POST`. # @param [Boolean] voice_caller_id_lookup Whether we should look up the caller's # caller-ID name from the CNAM database (additional charges apply). Can be: `true` # or `false`. # @param [String] sms_url The URL we should call when the phone number receives an # incoming SMS message. # @param [String] sms_method The HTTP method we should use to call `sms_url`. Can # be: `GET` or `POST`. # @param [String] sms_fallback_url The URL that we should call when an error # occurs while retrieving or executing the TwiML from `sms_url`. # @param [String] sms_fallback_method The HTTP method we should use to call # `sms_fallback_url`. Can be: `GET` or `POST`. # @param [String] sms_status_callback The URL we should call using a POST method # to send status information about SMS messages sent by the application. # @param [String] message_status_callback The URL we should call using a POST # method to send message status information to your application. # @return [ApplicationInstance] Updated ApplicationInstance def update(friendly_name: :unset, api_version: :unset, voice_url: :unset, voice_method: :unset, voice_fallback_url: :unset, voice_fallback_method: :unset, status_callback: :unset, status_callback_method: :unset, voice_caller_id_lookup: :unset, sms_url: :unset, sms_method: :unset, sms_fallback_url: :unset, sms_fallback_method: :unset, sms_status_callback: :unset, message_status_callback: :unset) data = Twilio::Values.of({ 'FriendlyName' => friendly_name, 'ApiVersion' => api_version, 'VoiceUrl' => voice_url, 'VoiceMethod' => voice_method, 'VoiceFallbackUrl' => voice_fallback_url, 'VoiceFallbackMethod' => voice_fallback_method, 'StatusCallback' => status_callback, 'StatusCallbackMethod' => status_callback_method, 'VoiceCallerIdLookup' => voice_caller_id_lookup, 'SmsUrl' => sms_url, 'SmsMethod' => sms_method, 'SmsFallbackUrl' => sms_fallback_url, 'SmsFallbackMethod' => sms_fallback_method, 'SmsStatusCallback' => sms_status_callback, 'MessageStatusCallback' => message_status_callback, }) payload = @version.update( 'POST', @uri, data: data, ) ApplicationInstance.new( @version, payload, account_sid: @solution[:account_sid], sid: @solution[:sid], ) end ## # Provide a user friendly representation def to_s context = @solution.map {|k, v| "#{k}: #{v}"}.join(',') "#<Twilio.Api.V2010.ApplicationContext #{context}>" end ## # Provide a detailed, user friendly representation def inspect context = @solution.map {|k, v| "#{k}: #{v}"}.join(',') "#<Twilio.Api.V2010.ApplicationContext #{context}>" end end class ApplicationInstance < InstanceResource ## # Initialize the ApplicationInstance # @param [Version] version Version that contains the resource # @param [Hash] payload payload that contains response from Twilio # @param [String] account_sid The SID of the # [Account](https://www.twilio.com/docs/api/rest/account) that created the # Application resource. # @param [String] sid The Twilio-provided string that uniquely identifies the # Application resource to fetch. # @return [ApplicationInstance] ApplicationInstance def initialize(version, payload, account_sid: nil, sid: nil) super(version) # Marshaled Properties @properties = { 'account_sid' => payload['account_sid'], 'api_version' => payload['api_version'], 'date_created' => Twilio.deserialize_rfc2822(payload['date_created']), 'date_updated' => Twilio.deserialize_rfc2822(payload['date_updated']), 'friendly_name' => payload['friendly_name'], 'message_status_callback' => payload['message_status_callback'], 'sid' => payload['sid'], 'sms_fallback_method' => payload['sms_fallback_method'], 'sms_fallback_url' => payload['sms_fallback_url'], 'sms_method' => payload['sms_method'], 'sms_status_callback' => payload['sms_status_callback'], 'sms_url' => payload['sms_url'], 'status_callback' => payload['status_callback'], 'status_callback_method' => payload['status_callback_method'], 'uri' => payload['uri'], 'voice_caller_id_lookup' => payload['voice_caller_id_lookup'], 'voice_fallback_method' => payload['voice_fallback_method'], 'voice_fallback_url' => payload['voice_fallback_url'], 'voice_method' => payload['voice_method'], 'voice_url' => payload['voice_url'], } # Context @instance_context = nil @params = {'account_sid' => account_sid, 'sid' => sid || @properties['sid'], } end ## # Generate an instance context for the instance, the context is capable of # performing various actions. All instance actions are proxied to the context # @return [ApplicationContext] ApplicationContext for this ApplicationInstance def context unless @instance_context @instance_context = ApplicationContext.new(@version, @params['account_sid'], @params['sid'], ) end @instance_context end ## # @return [String] The SID of the Account that created the resource def account_sid @properties['account_sid'] end ## # @return [String] The API version used to start a new TwiML session def api_version @properties['api_version'] end ## # @return [Time] The RFC 2822 date and time in GMT that the resource was created def date_created @properties['date_created'] end ## # @return [Time] The RFC 2822 date and time in GMT that the resource was last updated def date_updated @properties['date_updated'] end ## # @return [String] The string that you assigned to describe the resource def friendly_name @properties['friendly_name'] end ## # @return [String] The URL to send message status information to your application def message_status_callback @properties['message_status_callback'] end ## # @return [String] The unique string that identifies the resource def sid @properties['sid'] end ## # @return [String] The HTTP method used with sms_fallback_url def sms_fallback_method @properties['sms_fallback_method'] end ## # @return [String] The URL that we call when an error occurs while retrieving or executing the TwiML def sms_fallback_url @properties['sms_fallback_url'] end ## # @return [String] The HTTP method to use with sms_url def sms_method @properties['sms_method'] end ## # @return [String] The URL to send status information to your application def sms_status_callback @properties['sms_status_callback'] end ## # @return [String] The URL we call when the phone number receives an incoming SMS message def sms_url @properties['sms_url'] end ## # @return [String] The URL to send status information to your application def status_callback @properties['status_callback'] end ## # @return [String] The HTTP method we use to call status_callback def status_callback_method @properties['status_callback_method'] end ## # @return [String] The URI of the resource, relative to `https://api.twilio.com` def uri @properties['uri'] end ## # @return [Boolean] Whether to lookup the caller's name def voice_caller_id_lookup @properties['voice_caller_id_lookup'] end ## # @return [String] The HTTP method used with voice_fallback_url def voice_fallback_method @properties['voice_fallback_method'] end ## # @return [String] The URL we call when a TwiML error occurs def voice_fallback_url @properties['voice_fallback_url'] end ## # @return [String] The HTTP method used with the voice_url def voice_method @properties['voice_method'] end ## # @return [String] The URL we call when the phone number receives a call def voice_url @properties['voice_url'] end ## # Deletes the ApplicationInstance # @return [Boolean] true if delete succeeds, true otherwise def delete context.delete end ## # Fetch a ApplicationInstance # @return [ApplicationInstance] Fetched ApplicationInstance def fetch context.fetch end ## # Update the ApplicationInstance # @param [String] friendly_name A descriptive string that you create to describe # the resource. It can be up to 64 characters long. # @param [String] api_version The API version to use to start a new TwiML session. # Can be: `2010-04-01` or `2008-08-01`. The default value is your account's # default API version. # @param [String] voice_url The URL we should call when the phone number assigned # to this application receives a call. # @param [String] voice_method The HTTP method we should use to call `voice_url`. # Can be: `GET` or `POST`. # @param [String] voice_fallback_url The URL that we should call when an error # occurs retrieving or executing the TwiML requested by `url`. # @param [String] voice_fallback_method The HTTP method we should use to call # `voice_fallback_url`. Can be: `GET` or `POST`. # @param [String] status_callback The URL we should call using the # `status_callback_method` to send status information to your application. # @param [String] status_callback_method The HTTP method we should use to call # `status_callback`. Can be: `GET` or `POST`. # @param [Boolean] voice_caller_id_lookup Whether we should look up the caller's # caller-ID name from the CNAM database (additional charges apply). Can be: `true` # or `false`. # @param [String] sms_url The URL we should call when the phone number receives an # incoming SMS message. # @param [String] sms_method The HTTP method we should use to call `sms_url`. Can # be: `GET` or `POST`. # @param [String] sms_fallback_url The URL that we should call when an error # occurs while retrieving or executing the TwiML from `sms_url`. # @param [String] sms_fallback_method The HTTP method we should use to call # `sms_fallback_url`. Can be: `GET` or `POST`. # @param [String] sms_status_callback The URL we should call using a POST method # to send status information about SMS messages sent by the application. # @param [String] message_status_callback The URL we should call using a POST # method to send message status information to your application. # @return [ApplicationInstance] Updated ApplicationInstance def update(friendly_name: :unset, api_version: :unset, voice_url: :unset, voice_method: :unset, voice_fallback_url: :unset, voice_fallback_method: :unset, status_callback: :unset, status_callback_method: :unset, voice_caller_id_lookup: :unset, sms_url: :unset, sms_method: :unset, sms_fallback_url: :unset, sms_fallback_method: :unset, sms_status_callback: :unset, message_status_callback: :unset) context.update( friendly_name: friendly_name, api_version: api_version, voice_url: voice_url, voice_method: voice_method, voice_fallback_url: voice_fallback_url, voice_fallback_method: voice_fallback_method, status_callback: status_callback, status_callback_method: status_callback_method, voice_caller_id_lookup: voice_caller_id_lookup, sms_url: sms_url, sms_method: sms_method, sms_fallback_url: sms_fallback_url, sms_fallback_method: sms_fallback_method, sms_status_callback: sms_status_callback, message_status_callback: message_status_callback, ) end ## # Provide a user friendly representation def to_s values = @params.map{|k, v| "#{k}: #{v}"}.join(" ") "<Twilio.Api.V2010.ApplicationInstance #{values}>" end ## # Provide a detailed, user friendly representation def inspect values = @properties.map{|k, v| "#{k}: #{v}"}.join(" ") "<Twilio.Api.V2010.ApplicationInstance #{values}>" end end end end end end end
47.544408
409
0.571903
28d8eef8232b299d46141022f77f7bfcdc33b0f0
337
ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' require "minitest/reporters" Minitest::Reporters.use! class ActiveSupport::TestCase # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. fixtures :all include ApplicationHelper end
24.071429
82
0.756677
18828ec6d7f7c6b306e9d44f085703d523cfd810
5,584
require 'spec_helper' include RR describe ProxiedTableScan do before(:each) do Initializer.configuration = deep_copy(proxied_config) # Small block size necessary to exercize all code paths in ProxiedTableScan # even when only using tables with very small number of records. Initializer.configuration.options[:proxy_block_size] = 2 ensure_proxy end it "initialize should raise exception if session is not proxied" do session = Session.new standard_config lambda { ProxiedTableScan.new session, 'dummy_table' } \ .should raise_error(RuntimeError, /only works with proxied sessions/) end it "initialize should cache the primary keys" do session = Session.new scan = ProxiedTableScan.new session, 'scanner_records' scan.primary_key_names.should == ['id'] end it "initialize should raise exception if table doesn't have primary keys" do session = Session.new lambda {ProxiedTableScan.new session, 'extender_without_key'} \ .should raise_error(RuntimeError, /.*extender_without_key.*primary key/) end it "block_size should return the :proxy_block_size value of the session options" do ProxiedTableScan.new(Session.new, 'scanner_records').block_size \ .should == 2 end it "block_size should return the matching table specific option if available" do config = Initializer.configuration old_table_specific_options = config.tables_with_options begin config.options = {:proxy_block_size => 2} config.include_tables 'scanner_records', {:proxy_block_size => 3} ProxiedTableScan.new(Session.new(config), 'scanner_records').block_size \ .should == 3 ensure config.instance_eval {@tables_with_options = old_table_specific_options} end end # Creates, prepares and returns a +ProxyBlockCursor+ for the given database # +connection+ and +table+. # Sets the ProxyBlockCursor#max_row_cache_size as per method parameter. def get_block_cursor(connection, table, max_row_cache_size = 1000000) cursor = ProxyBlockCursor.new connection, table cursor.max_row_cache_size = max_row_cache_size cursor.prepare_fetch cursor.checksum :proxy_block_size => 1000 cursor end it "compare_blocks should compare all the records in the range" do session = Session.new left_cursor = get_block_cursor session.left, 'scanner_records' right_cursor = get_block_cursor session.right, 'scanner_records' scan = ProxiedTableScan.new session, 'scanner_records' diff = [] scan.compare_blocks(left_cursor, right_cursor) do |type, row| diff.push [type, row] end # in this scenario the right table has the 'highest' data, # so 'right-sided' data are already implicitely tested here diff.should == [ [:conflict, [ {'id' => 2, 'name' => 'Bob - left database version'}, {'id' => 2, 'name' => 'Bob - right database version'}]], [:left, {'id' => 3, 'name' => 'Charlie - exists in left database only'}], [:right, {'id' => 4, 'name' => 'Dave - exists in right database only'}], [:left, {'id' => 5, 'name' => 'Eve - exists in left database only'}], [:right, {'id' => 6, 'name' => 'Fred - exists in right database only'}] ] end it "compare_blocks should destroy the created cursors" do session = Session.new left_cursor = get_block_cursor session.left, 'scanner_records', 0 right_cursor = get_block_cursor session.right, 'scanner_records', 0 scan = ProxiedTableScan.new session, 'scanner_records' scan.compare_blocks(left_cursor, right_cursor) { |type, row| } session.left.cursors.should == {} session.right.cursors.should == {} end it "run should only call compare single rows if there are different block checksums" do config = deep_copy(proxied_config) config.right = config.left session = Session.new config scan = ProxiedTableScan.new session, 'scanner_records' scan.should_not_receive(:compare_blocks) diff = [] scan.run do |type, row| diff.push [type,row] end diff.should == [] end it "run should compare all the records in the table" do session = Session.new scan = ProxiedTableScan.new session, 'scanner_records' diff = [] scan.run do |type, row| diff.push [type, row] end # in this scenario the right table has the 'highest' data, # so 'right-sided' data are already implicitely tested here diff.should == [ [:conflict, [ {'id' => 2, 'name' => 'Bob - left database version'}, {'id' => 2, 'name' => 'Bob - right database version'}]], [:left, {'id' => 3, 'name' => 'Charlie - exists in left database only'}], [:right, {'id' => 4, 'name' => 'Dave - exists in right database only'}], [:left, {'id' => 5, 'name' => 'Eve - exists in left database only'}], [:right, {'id' => 6, 'name' => 'Fred - exists in right database only'}] ] end it "run should update the progress" do session = Session.new scan = ProxiedTableScan.new session, 'scanner_records' number_steps = 0 scan.should_receive(:update_progress).at_least(1).times do |steps| number_steps += steps end scan.run {|_, _|} number_steps.should == 8 end it "run should update the progress even if there are no records" do # it should do that to ensure the progress bar is printed scan = ProxiedTableScan.new Session.new, 'extender_no_record' scan.should_receive(:update_progress).at_least(:once) scan.run {|_, _|} end end
36.736842
89
0.676755
ab6eb0d8d202c2b08d2952114bbc0c577940e597
59
module GoogleScholarScraper VERSION = "0.1.1".freeze end
14.75
27
0.762712
bf622f2ac78bc8631cd584df8b5ff154a772471d
108
module Bootstrap VERSION = '3.3.7' BOOTSTRAP_SHA = '0b9c4a4007c44201dce9a6cc1a38407005c26c86' end
21.6
60
0.75
1a33ab40aa327af1ba0833921974f85aa58d00a2
1,682
# -*- encoding: utf-8 -*- # stub: rack-protection 2.0.5 ruby lib Gem::Specification.new do |s| s.name = "rack-protection" s.version = "2.0.5" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.metadata = { "documentation_uri" => "https://www.rubydoc.info/gems/rack-protection", "homepage_uri" => "http://sinatrarb.com/protection/", "source_code_uri" => "https://github.com/sinatra/sinatra/tree/master/rack-protection" } if s.respond_to? :metadata= s.require_paths = ["lib"] s.authors = ["https://github.com/sinatra/sinatra/graphs/contributors"] s.date = "2018-12-22" s.description = "Protect against typical web attacks, works with all Rack apps, including Rails." s.email = "[email protected]" s.homepage = "http://sinatrarb.com/protection/" s.licenses = ["MIT"] s.rubygems_version = "2.5.2.1" s.summary = "Protect against typical web attacks, works with all Rack apps, including Rails." s.installed_by_version = "2.5.2.1" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rack>, [">= 0"]) s.add_development_dependency(%q<rack-test>, [">= 0"]) s.add_development_dependency(%q<rspec>, ["~> 3.6"]) else s.add_dependency(%q<rack>, [">= 0"]) s.add_dependency(%q<rack-test>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 3.6"]) end else s.add_dependency(%q<rack>, [">= 0"]) s.add_dependency(%q<rack-test>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 3.6"]) end end
42.05
258
0.662901
bf08bc908d942983a6a8460c89a1278ed2652b6f
2,454
class ApplicationFormBuilder < Formtastic::FormBuilder def cancel_link(options = {}) location = options[:url] || template.request.params[:_cancel_url] || template.request.referer || '/' template.hidden_field_tag(:_cancel_url, location) if location =~ /\?/ location = location + '&_cancel=1' else location = location + '?_cancel=1' end template.content_tag(:li, template.link_to('Cancel', location), :class => "cancel" ) end # Implements image preview and delete option. def attachment_input(method, options = {}) delete_attachment_link = "delete_#{method}_link" preview_id = "#{method}_preview" attachment_file_field = "#{method}_file_field" unless (attachment = @object.send(method)).blank? or (not attachment.file?) if (attachment.content_type =~ /^image\/.+/) and (attachment.styles.member?(:thumbnail) or attachment.styles.member?(:edit)) style = attachment.styles.member?(:thumbnail) ? :thumbnail : :edit preview = <<-HTML <img id="#{preview_id}" src="#{attachment.url(style)}" /> HTML else preview = <<-HTML <a href="#{attachment.url}" id="#{preview_id}">#{attachment.original_filename}</a> HTML end end deleter_input_id = "#{method}_deleter" deleter_input_html = hidden_field(method.to_s + '_file_name', :value => '', :id => deleter_input_id ) magic = <<-JAVASCRIPT <script type="text/javascript"> $(function() { $("##{delete_attachment_link}").click(function() { $('##{preview_id}').hide(); $('##{delete_attachment_link}').hide(); $(this).after('#{deleter_input_html}'); return false; }); $('form').submit(function () { if ($('##{attachment_file_field}').val() != '') { $('##{deleter_input_id}').remove(); } return true; }); }) </script> JAVASCRIPT ff = file_field method, {:id => attachment_file_field}.merge(options.except(:required)) if preview preview << <<-HTML <span class="attachment_delete" id="#{delete_attachment_link}">(<a href="#delete">Delete</a>)</span> HTML end l = label(method, options.delete(:label), options.slice(:required)) template.content_tag(:li, <<-HTML, nil, false) #{l} #{ff} <div class="attachment_preview">#{preview}</div> #{magic} HTML end end
36.088235
130
0.599837
4a935cf1c2dc7a4ec55f62068c7b0dd7e17628af
1,008
class GitDelta < Formula desc "Syntax-highlighting pager for git and diff output" homepage "https://github.com/dandavison/delta" url "https://github.com/dandavison/delta/archive/0.13.0.tar.gz" sha256 "5a0ba70a094a7884beb6f1efd4d155861e4b3e3584c452cabbce1607f8eb0f30" license "MIT" head "https://github.com/dandavison/delta.git", branch: "master" bottle do root_url "https://github.com/gromgit/homebrew-core-mojave/releases/download/git-delta" sha256 cellar: :any_skip_relocation, mojave: "93e3e836a446818beaf387b0948aed817b820c88120893620e7f04d72d28b7e9" end depends_on "rust" => :build uses_from_macos "zlib" conflicts_with "delta", because: "both install a `delta` binary" def install system "cargo", "install", *std_cargo_args bash_completion.install "etc/completion/completion.bash" => "delta" zsh_completion.install "etc/completion/completion.zsh" => "_delta" end test do assert_match "delta #{version}", `#{bin}/delta --version`.chomp end end
34.758621
115
0.750992
4a60830a98e6d676713c0997d64133a22109d1b0
423
require 'rubygems' require 'jruby-prof' require 'jrjackson_r' js = %({"one":1,"two":"deux","three":[333.333,66.666]}) result = JRubyProf.profile do JrJackson::Json.parse js end JRubyProf.print_flat_text result, "flat.txt" JRubyProf.print_graph_text result, "graph.txt" JRubyProf.print_graph_html result, "graph.html" JRubyProf.print_call_tree result, "call_tree.txt" JRubyProf.print_tree_html result, "call_tree.html"
26.4375
55
0.770686
183f8b744897d68f6bd59a5eae985ead8ba7cd7e
1,788
# require_relative "./pedia" # api = SNaPi::Pedia.new # # Change limit to :max later # response = api.query.list.title("Category:Is a genotype").prop(:ids).limit(500).response # genos_ids = response.to_h["categorymembers"].map(&:first).map(&:last) # i = 0 # puts "Genotypes:" # puts genos_ids.size # while response.continue? && i < 5 # response = response.continue # genos_ids += response.to_h["categorymembers"].map(&:first).map(&:last) # puts genos_ids.size # i += 1 # end # puts "Last id: ", genos_ids[-1] # response = api.parse.pageid(genos_ids[-1]).prop(:displaytitle, :wikitext).response # wikitext = response.to_h["wikitext"]["*"] # puts "\nPage content:" # puts wikitext # # Rustic manual interpretation of the text # start = wikitext.index("{{Genotype\n") # final = wikitext.index("}}") # if !start.nil? && !final.nil? # # Gets the start of the text, that's kind of a hash with some useful information # # It is in the format {{Genotype | key=value | key=value}} # # Logo, há vários splits numa tentativa de fazer um parse manual em um hash # geno_list = wikitext[start + 12, final - 10].split("|") # geno = {} # geno_list.length.times do |i| # part = geno_list[i].split("=") # geno[part[0]] = part[1].chomp # end # end # if geno.include? "rsid" # response = api.cargoquery.rsnum.where_rsid(geno["rsid"]) # else # response = api.cargoquery.rsnum.where_iid(geno[":iid"]) # end # response = response.fields( # :Gene, :Chromosome, :position, :Orientation, # :StabilizedOrientation, :GMAF, :Gene_s, :geno1, :geno2, :geno3 # ).response.to_h[0]["title"] # puts "\nInformations about the gene of the last genotype" # puts "Gene: " + response["Gene"] # puts "Chromosome: " + response["Chromosome"] # puts "position: " + response["position"]
32.509091
90
0.66443
1d90dfae7cd11be1032de024874c6d1398ff3e61
512
cask 'praat' do version '6.1.12' sha256 'c3da9f39833f923f40f91e3842cf5730f72b17fb06eb365df807a06a7a108c06' # github.com/praat/praat/ was verified as official when first introduced to the cask url "https://github.com/praat/praat/releases/download/v#{version}/praat#{version.no_dots}_mac64.dmg" appcast 'https://github.com/praat/praat/releases.atom' name 'Praat' homepage 'http://www.fon.hum.uva.nl/praat/' app 'Praat.app' binary "#{appdir}/Praat.app/Contents/MacOS/Praat", target: 'praat' end
36.571429
102
0.751953
03d68c0f89e4d3bda468aa1d6f718b356b6eb79b
43,139
# frozen_string_literal: true # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! module Google module Cloud module DataCatalog module V1 # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#search_catalog SearchCatalog}. # @!attribute [rw] scope # @return [::Google::Cloud::DataCatalog::V1::SearchCatalogRequest::Scope] # Required. The scope of this search request. A `scope` that has empty # `include_org_ids`, `include_project_ids` AND false # `include_gcp_public_datasets` is considered invalid. Data Catalog will # return an error in such a case. # @!attribute [rw] query # @return [::String] # Optional. The query string in search query syntax. An empty query string will result # in all data assets (in the specified scope) that the user has access to. # # Query strings can be simple as "x" or more qualified as: # # * name:x # * column:x # * description:y # # Note: Query tokens need to have a minimum of 3 characters for substring # matching to work correctly. See [Data Catalog Search # Syntax](https://cloud.google.com/data-catalog/docs/how-to/search-reference) # for more information. # @!attribute [rw] page_size # @return [::Integer] # Number of results in the search page. If <=0 then defaults to 10. Max limit # for page_size is 1000. Throws an invalid argument for page_size > 1000. # @!attribute [rw] page_token # @return [::String] # Optional. Pagination token returned in an earlier # {::Google::Cloud::DataCatalog::V1::SearchCatalogResponse#next_page_token SearchCatalogResponse.next_page_token}, which # indicates that this is a continuation of a prior # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#search_catalog SearchCatalogRequest} # call, and that the system should return the next page of data. If empty, # the first page is returned. # @!attribute [rw] order_by # @return [::String] # Specifies the ordering of results, currently supported case-sensitive # choices are: # # * `relevance`, only supports descending # * `last_modified_timestamp [asc|desc]`, defaults to descending if not # specified # # If not specified, defaults to `relevance` descending. class SearchCatalogRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # The criteria that select the subspace used for query matching. # @!attribute [rw] include_org_ids # @return [::Array<::String>] # The list of organization IDs to search within. To find your organization # ID, follow instructions in # https://cloud.google.com/resource-manager/docs/creating-managing-organization. # @!attribute [rw] include_project_ids # @return [::Array<::String>] # The list of project IDs to search within. To learn more about the # distinction between project names/IDs/numbers, go to # https://cloud.google.com/docs/overview/#projects. # @!attribute [rw] include_gcp_public_datasets # @return [::Boolean] # If `true`, include Google Cloud Platform (GCP) public datasets in the # search results. Info on GCP public datasets is available at # https://cloud.google.com/public-datasets/. By default, GCP public # datasets are excluded. # @!attribute [rw] restricted_locations # @return [::Array<::String>] # Optional. The list of locations to search within. # 1. If empty, search will be performed in all locations; # 2. If any of the locations are NOT [supported # regions](https://cloud.google.com/data-catalog/docs/concepts/regions#supported_regions), # error will be returned; # 3. Otherwise, search only the given locations for matching results. # Typical usage is to leave this field empty. When a location is # unreachable as returned in the `SearchCatalogResponse.unreachable` field, # users can repeat the search request with this parameter set to get # additional information on the error. class Scope include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end end # Response message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#search_catalog SearchCatalog}. # @!attribute [rw] results # @return [::Array<::Google::Cloud::DataCatalog::V1::SearchCatalogResult>] # Search results. # @!attribute [rw] next_page_token # @return [::String] # The token that can be used to retrieve the next page of results. # @!attribute [rw] unreachable # @return [::Array<::String>] # Unreachable locations. Search result does not include data from those # locations. Users can get additional information on the error by repeating # the search request with a more restrictive parameter -- setting the value # for `SearchDataCatalogRequest.scope.restricted_locations`. class SearchCatalogResponse include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#create_entry_group CreateEntryGroup}. # @!attribute [rw] parent # @return [::String] # Required. The name of the project this entry group belongs to. Example: # # `projects/{project_id}/locations/{location}` # # Note: The entry group itself and its child resources might not be # stored in the location specified in its name. # @!attribute [rw] entry_group_id # @return [::String] # Required. The ID of the entry group to create. # # The ID must contain only letters (a-z, A-Z), numbers (0-9), # underscores (_), and must start with a letter or underscore. # The maximum size is 64 bytes when encoded in UTF-8. # @!attribute [rw] entry_group # @return [::Google::Cloud::DataCatalog::V1::EntryGroup] # The entry group to create. Defaults to an empty entry group. class CreateEntryGroupRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#update_entry_group UpdateEntryGroup}. # @!attribute [rw] entry_group # @return [::Google::Cloud::DataCatalog::V1::EntryGroup] # Required. The updated entry group. "name" field must be set. # @!attribute [rw] update_mask # @return [::Google::Protobuf::FieldMask] # Names of fields whose values to overwrite on an entry group. # # If this parameter is absent or empty, all modifiable fields # are overwritten. If such fields are non-required and omitted in the # request body, their values are emptied. class UpdateEntryGroupRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#get_entry_group GetEntryGroup}. # @!attribute [rw] name # @return [::String] # Required. The name of the entry group. For example, # `projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}`. # @!attribute [rw] read_mask # @return [::Google::Protobuf::FieldMask] # The fields to return. If not set or empty, all fields are returned. class GetEntryGroupRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#delete_entry_group DeleteEntryGroup}. # @!attribute [rw] name # @return [::String] # Required. The name of the entry group. For example, # `projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}`. # @!attribute [rw] force # @return [::Boolean] # Optional. If true, deletes all entries in the entry group. class DeleteEntryGroupRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#list_entry_groups ListEntryGroups}. # @!attribute [rw] parent # @return [::String] # Required. The name of the location that contains the entry groups, which can be # provided in URL format. Example: # # * projects/\\{project_id}/locations/\\{location} # @!attribute [rw] page_size # @return [::Integer] # Optional. The maximum number of items to return. Default is 10. Max limit is 1000. # Throws an invalid argument for `page_size > 1000`. # @!attribute [rw] page_token # @return [::String] # Optional. Token that specifies which page is requested. If empty, the first page is # returned. class ListEntryGroupsRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Response message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#list_entry_groups ListEntryGroups}. # @!attribute [rw] entry_groups # @return [::Array<::Google::Cloud::DataCatalog::V1::EntryGroup>] # EntryGroup details. # @!attribute [rw] next_page_token # @return [::String] # Token to retrieve the next page of results. It is set to empty if no items # remain in results. class ListEntryGroupsResponse include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#create_entry CreateEntry}. # @!attribute [rw] parent # @return [::String] # Required. The name of the entry group this entry belongs to. Example: # # `projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}` # # Note: The entry itself and its child resources might not be stored in # the location specified in its name. # @!attribute [rw] entry_id # @return [::String] # Required. The ID of the entry to create. # # The ID must contain only letters (a-z, A-Z), numbers (0-9), # and underscores (_). # The maximum size is 64 bytes when encoded in UTF-8. # @!attribute [rw] entry # @return [::Google::Cloud::DataCatalog::V1::Entry] # Required. The entry to create. class CreateEntryRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#update_entry UpdateEntry}. # @!attribute [rw] entry # @return [::Google::Cloud::DataCatalog::V1::Entry] # Required. The updated entry. The "name" field must be set. # @!attribute [rw] update_mask # @return [::Google::Protobuf::FieldMask] # Names of fields whose values to overwrite on an entry. # # If this parameter is absent or empty, all modifiable fields # are overwritten. If such fields are non-required and omitted in the # request body, their values are emptied. # # The following fields are modifiable: # # * For entries with type `DATA_STREAM`: # * `schema` # * For entries with type `FILESET`: # * `schema` # * `display_name` # * `description` # * `gcs_fileset_spec` # * `gcs_fileset_spec.file_patterns` # * For entries with `user_specified_type`: # * `schema` # * `display_name` # * `description` # * `user_specified_type` # * `user_specified_system` # * `linked_resource` # * `source_system_timestamps` class UpdateEntryRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#delete_entry DeleteEntry}. # @!attribute [rw] name # @return [::String] # Required. The name of the entry. Example: # # * projects/\\{project_id}/locations/\\{location}/entryGroups/\\{entry_group_id}/entries/\\{entry_id} class DeleteEntryRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#get_entry GetEntry}. # @!attribute [rw] name # @return [::String] # Required. The name of the entry. Example: # # * projects/\\{project_id}/locations/\\{location}/entryGroups/\\{entry_group_id}/entries/\\{entry_id} class GetEntryRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#lookup_entry LookupEntry}. # @!attribute [rw] linked_resource # @return [::String] # The full name of the Google Cloud Platform resource the Data Catalog # entry represents. See: # https://cloud.google.com/apis/design/resource_names#full_resource_name. # Full names are case-sensitive. # # Examples: # # * //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId # * //pubsub.googleapis.com/projects/projectId/topics/topicId # @!attribute [rw] sql_resource # @return [::String] # The SQL name of the entry. SQL names are case-sensitive. # # Examples: # # * `pubsub.project_id.topic_id` # * ``pubsub.project_id.`topic.id.with.dots` `` # * `bigquery.table.project_id.dataset_id.table_id` # * `bigquery.dataset.project_id.dataset_id` # * `datacatalog.entry.project_id.location_id.entry_group_id.entry_id` # # `*_id`s should satisfy the standard SQL rules for identifiers. # https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical. # @!attribute [rw] fully_qualified_name # @return [::String] # Fully qualified name (FQN) of the resource. # # FQNs take two forms: # # * For non-regionalized resources: # # `{SYSTEM}:{PROJECT}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` # # * For regionalized resources: # # `{SYSTEM}:{PROJECT}.{LOCATION_ID}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` # # Example for a DPMS table: # # `dataproc_metastore:project_id.location_id.instance_id.database_id.table_id` class LookupEntryRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Entry Metadata. # A Data Catalog Entry resource represents another resource in Google # Cloud Platform (such as a BigQuery dataset or a Pub/Sub topic) or # outside of Google Cloud Platform. Clients can use the `linked_resource` field # in the Entry resource to refer to the original resource ID of the source # system. # # An Entry resource contains resource details, such as its schema. An Entry can # also be used to attach flexible metadata, such as a # {::Google::Cloud::DataCatalog::V1::Tag Tag}. # @!attribute [r] name # @return [::String] # Output only. The resource name of an entry in URL format. # Example: # # `projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}` # # Note: The entry itself and its child resources might not be # stored in the location specified in its name. # @!attribute [rw] linked_resource # @return [::String] # The resource this metadata entry refers to. # # For Google Cloud Platform resources, `linked_resource` is the [full name of # the # resource](https://cloud.google.com/apis/design/resource_names#full_resource_name). # For example, the `linked_resource` for a table resource from BigQuery is: # # `//bigquery.googleapis.com/projects/{projectId}/datasets/{datasetId}/tables/{tableId}` # # Output only when entry is one of the types in the `EntryType` enum. # # For entries with a `user_specified_type`, this field is optional and # defaults to an empty string. # # The resource string must contain only letters (a-z, A-Z), numbers (0-9), # underscores (_), periods (.), colons (:), slashes (/), dashes (-), # and hashes (#). # The maximum size is 200 bytes when encoded in UTF-8. # @!attribute [rw] fully_qualified_name # @return [::String] # Fully qualified name (FQN) of the resource. Set automatically for entries # representing resources from synced systems. Settable only during creation # and read-only afterwards. Can be used for search and lookup of the entries. # # # FQNs take two forms: # # * For non-regionalized resources: # # `{SYSTEM}:{PROJECT}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` # # * For regionalized resources: # # `{SYSTEM}:{PROJECT}.{LOCATION_ID}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` # # Example for a DPMS table: # # `dataproc_metastore:project_id.location_id.instance_id.database_id.table_id` # @!attribute [rw] type # @return [::Google::Cloud::DataCatalog::V1::EntryType] # The type of the entry. # Only used for Entries with types in the EntryType enum. # @!attribute [rw] user_specified_type # @return [::String] # Entry type if it does not fit any of the input-allowed values listed in # `EntryType` enum above. When creating an entry, users should check the # enum values first, if nothing matches the entry to be created, then # provide a custom value, for example "my_special_type". # `user_specified_type` strings must begin with a letter or underscore and # can only contain letters, numbers, and underscores; are case insensitive; # must be at least 1 character and at most 64 characters long. # # Currently, only FILESET enum value is allowed. All other entries created # through Data Catalog must use `user_specified_type`. # @!attribute [r] integrated_system # @return [::Google::Cloud::DataCatalog::V1::IntegratedSystem] # Output only. This field indicates the entry's source system that Data Catalog # integrates with, such as BigQuery or Pub/Sub. # @!attribute [rw] user_specified_system # @return [::String] # This field indicates the entry's source system that Data Catalog does not # integrate with. `user_specified_system` strings must begin with a letter # or underscore and can only contain letters, numbers, and underscores; are # case insensitive; must be at least 1 character and at most 64 characters # long. # @!attribute [rw] gcs_fileset_spec # @return [::Google::Cloud::DataCatalog::V1::GcsFilesetSpec] # Specification that applies to a Cloud Storage fileset. This is only valid # on entries of type FILESET. # @!attribute [rw] bigquery_table_spec # @return [::Google::Cloud::DataCatalog::V1::BigQueryTableSpec] # Specification that applies to a BigQuery table. This is only valid on # entries of type `TABLE`. # @!attribute [rw] bigquery_date_sharded_spec # @return [::Google::Cloud::DataCatalog::V1::BigQueryDateShardedSpec] # Specification for a group of BigQuery tables with name pattern # `[prefix]YYYYMMDD`. Context: # https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding. # @!attribute [rw] database_table_spec # @return [::Google::Cloud::DataCatalog::V1::DatabaseTableSpec] # Specification that applies to a table resource. Only valid # for entries of `TABLE` type. # @!attribute [rw] display_name # @return [::String] # Display name of an entry. # # The name must contain only Unicode letters, numbers (0-9), underscores (_), # dashes (-), spaces ( ), and can't start or end with spaces. # The maximum size is 200 bytes when encoded in UTF-8. # Default value is an empty string. # @!attribute [rw] description # @return [::String] # Entry description that can consist of several sentences or paragraphs # that describe entry contents. # # The description must not contain Unicode non-characters as well as C0 # and C1 control codes except tabs (HT), new lines (LF), carriage returns # (CR), and page breaks (FF). # The maximum size is 2000 bytes when encoded in UTF-8. # Default value is an empty string. # @!attribute [rw] schema # @return [::Google::Cloud::DataCatalog::V1::Schema] # Schema of the entry. An entry might not have any schema attached to it. # @!attribute [rw] source_system_timestamps # @return [::Google::Cloud::DataCatalog::V1::SystemTimestamps] # Timestamps about the underlying resource, not about this Data Catalog # entry. Output only when Entry is of type in the EntryType enum. For entries # with user_specified_type, this field is optional and defaults to an empty # timestamp. # @!attribute [r] data_source # @return [::Google::Cloud::DataCatalog::V1::DataSource] # Output only. Physical location of the entry. class Entry include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Specification that applies to a table resource. Only valid # for entries of `TABLE` type. # @!attribute [rw] type # @return [::Google::Cloud::DataCatalog::V1::DatabaseTableSpec::TableType] # Type of this table. class DatabaseTableSpec include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # Type of the table. module TableType # Default unknown table type. TABLE_TYPE_UNSPECIFIED = 0 # Native table. NATIVE = 1 # External table. EXTERNAL = 2 end end # EntryGroup Metadata. # An EntryGroup resource represents a logical grouping of zero or more # Data Catalog {::Google::Cloud::DataCatalog::V1::Entry Entry} resources. # @!attribute [rw] name # @return [::String] # The resource name of the entry group in URL format. Example: # # `projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}` # # Note: The entry group itself and its child resources might not be # stored in the location specified in its name. # @!attribute [rw] display_name # @return [::String] # A short name to identify the entry group, for example, # "analytics data - jan 2011". Default value is an empty string. # @!attribute [rw] description # @return [::String] # Entry group description, which can consist of several sentences or # paragraphs that describe entry group contents. Default value is an empty # string. # @!attribute [r] data_catalog_timestamps # @return [::Google::Cloud::DataCatalog::V1::SystemTimestamps] # Output only. Timestamps about this EntryGroup. Default value is empty timestamps. class EntryGroup include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#create_tag_template CreateTagTemplate}. # @!attribute [rw] parent # @return [::String] # Required. The name of the project and the template location # [region](https://cloud.google.com/data-catalog/docs/concepts/regions). # # Example: # # * projects/\\{project_id}/locations/us-central1 # @!attribute [rw] tag_template_id # @return [::String] # Required. The ID of the tag template to create. # # The ID must contain only lowercase letters (a-z), numbers (0-9), # or underscores (_), and must start with a letter or underscore. # The maximum size is 64 bytes when encoded in UTF-8. # @!attribute [rw] tag_template # @return [::Google::Cloud::DataCatalog::V1::TagTemplate] # Required. The tag template to create. class CreateTagTemplateRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#get_tag_template GetTagTemplate}. # @!attribute [rw] name # @return [::String] # Required. The name of the tag template. Example: # # * projects/\\{project_id}/locations/\\{location}/tagTemplates/\\{tag_template_id} class GetTagTemplateRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#update_tag_template UpdateTagTemplate}. # @!attribute [rw] tag_template # @return [::Google::Cloud::DataCatalog::V1::TagTemplate] # Required. The template to update. The "name" field must be set. # @!attribute [rw] update_mask # @return [::Google::Protobuf::FieldMask] # Names of fields whose values to overwrite on a tag template. Currently, # only `display_name` can be overwritten. # # In general, if this parameter is absent or empty, all modifiable fields # are overwritten. If such fields are non-required and omitted in the # request body, their values are emptied. class UpdateTagTemplateRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#delete_tag_template DeleteTagTemplate}. # @!attribute [rw] name # @return [::String] # Required. The name of the tag template to delete. Example: # # * projects/\\{project_id}/locations/\\{location}/tagTemplates/\\{tag_template_id} # @!attribute [rw] force # @return [::Boolean] # Required. Currently, this field must always be set to `true`. # This confirms the deletion of any possible tags using this template. # `force = false` will be supported in the future. class DeleteTagTemplateRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#create_tag CreateTag}. # @!attribute [rw] parent # @return [::String] # Required. The name of the resource to attach this tag to. Tags can be attached to # entries. An entry can have up to 1000 attached tags. Example: # # `projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}` # # Note: The tag and its child resources might not be stored in # the location specified in its name. # @!attribute [rw] tag # @return [::Google::Cloud::DataCatalog::V1::Tag] # Required. The tag to create. class CreateTagRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#update_tag UpdateTag}. # @!attribute [rw] tag # @return [::Google::Cloud::DataCatalog::V1::Tag] # Required. The updated tag. The "name" field must be set. # @!attribute [rw] update_mask # @return [::Google::Protobuf::FieldMask] # Names of fields whose values to overwrite on a tag. Currently, a tag has # the only modifiable field with the name `fields`. # # In general, if this parameter is absent or empty, all modifiable fields # are overwritten. If such fields are non-required and omitted in the # request body, their values are emptied. class UpdateTagRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#delete_tag DeleteTag}. # @!attribute [rw] name # @return [::String] # Required. The name of the tag to delete. Example: # # * projects/\\{project_id}/locations/\\{location}/entryGroups/\\{entry_group_id}/entries/\\{entry_id}/tags/\\{tag_id} class DeleteTagRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#create_tag_template_field CreateTagTemplateField}. # @!attribute [rw] parent # @return [::String] # Required. The name of the project and the template location # [region](https://cloud.google.com/data-catalog/docs/concepts/regions). # # Example: # # * projects/\\{project_id}/locations/us-central1/tagTemplates/\\{tag_template_id} # @!attribute [rw] tag_template_field_id # @return [::String] # Required. The ID of the tag template field to create. # # Note: Adding a required field to an existing template is *not* allowed. # # Field IDs can contain letters (both uppercase and lowercase), numbers # (0-9), underscores (_) and dashes (-). Field IDs must be at least 1 # character long and at most 128 characters long. Field IDs must also be # unique within their template. # @!attribute [rw] tag_template_field # @return [::Google::Cloud::DataCatalog::V1::TagTemplateField] # Required. The tag template field to create. class CreateTagTemplateFieldRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#update_tag_template_field UpdateTagTemplateField}. # @!attribute [rw] name # @return [::String] # Required. The name of the tag template field. Example: # # * projects/\\{project_id}/locations/\\{location}/tagTemplates/\\{tag_template_id}/fields/\\{tag_template_field_id} # @!attribute [rw] tag_template_field # @return [::Google::Cloud::DataCatalog::V1::TagTemplateField] # Required. The template to update. # @!attribute [rw] update_mask # @return [::Google::Protobuf::FieldMask] # Optional. Names of fields whose values to overwrite on an individual field of a tag # template. The following fields are modifiable: # # * `display_name` # * `type.enum_type` # * `is_required` # # If this parameter is absent or empty, all modifiable fields # are overwritten. If such fields are non-required and omitted in the request # body, their values are emptied with one exception: when updating an enum # type, the provided values are merged with the existing values. Therefore, # enum values can only be added, existing enum values cannot be deleted or # renamed. # # Additionally, updating a template field from optional to required is # *not* allowed. class UpdateTagTemplateFieldRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#rename_tag_template_field RenameTagTemplateField}. # @!attribute [rw] name # @return [::String] # Required. The name of the tag template. Example: # # * projects/\\{project_id}/locations/\\{location}/tagTemplates/\\{tag_template_id}/fields/\\{tag_template_field_id} # @!attribute [rw] new_tag_template_field_id # @return [::String] # Required. The new ID of this tag template field. For example, `my_new_field`. class RenameTagTemplateFieldRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#rename_tag_template_field_enum_value RenameTagTemplateFieldEnumValue}. # @!attribute [rw] name # @return [::String] # Required. The name of the enum field value. Example: # # * projects/\\{project_id}/locations/\\{location}/tagTemplates/\\{tag_template_id}/fields/\\{tag_template_field_id}/enumValues/\\{enum_value_display_name} # @!attribute [rw] new_enum_value_display_name # @return [::String] # Required. The new display name of the enum value. For example, `my_new_enum_value`. class RenameTagTemplateFieldEnumValueRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#delete_tag_template_field DeleteTagTemplateField}. # @!attribute [rw] name # @return [::String] # Required. The name of the tag template field to delete. Example: # # * projects/\\{project_id}/locations/\\{location}/tagTemplates/\\{tag_template_id}/fields/\\{tag_template_field_id} # @!attribute [rw] force # @return [::Boolean] # Required. Currently, this field must always be set to `true`. # This confirms the deletion of this field from any tags using this field. # `force = false` will be supported in the future. class DeleteTagTemplateFieldRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#list_tags ListTags}. # @!attribute [rw] parent # @return [::String] # Required. The name of the Data Catalog resource to list the tags of. The resource # could be an {::Google::Cloud::DataCatalog::V1::Entry Entry} or an # {::Google::Cloud::DataCatalog::V1::EntryGroup EntryGroup}. # # Examples: # # * projects/\\{project_id}/locations/\\{location}/entryGroups/\\{entry_group_id} # * projects/\\{project_id}/locations/\\{location}/entryGroups/\\{entry_group_id}/entries/\\{entry_id} # @!attribute [rw] page_size # @return [::Integer] # The maximum number of tags to return. Default is 10. Max limit is 1000. # @!attribute [rw] page_token # @return [::String] # Token that specifies which page is requested. If empty, the first page is # returned. class ListTagsRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Response message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#list_tags ListTags}. # @!attribute [rw] tags # @return [::Array<::Google::Cloud::DataCatalog::V1::Tag>] # {::Google::Cloud::DataCatalog::V1::Tag Tag} details. # @!attribute [rw] next_page_token # @return [::String] # Token to retrieve the next page of results. It is set to empty if no items # remain in results. class ListTagsResponse include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#list_entries ListEntries}. # @!attribute [rw] parent # @return [::String] # Required. The name of the entry group that contains the entries, which can # be provided in URL format. Example: # # * projects/\\{project_id}/locations/\\{location}/entryGroups/\\{entry_group_id} # @!attribute [rw] page_size # @return [::Integer] # The maximum number of items to return. Default is 10. Max limit is 1000. # Throws an invalid argument for `page_size > 1000`. # @!attribute [rw] page_token # @return [::String] # Token that specifies which page is requested. If empty, the first page is # returned. # @!attribute [rw] read_mask # @return [::Google::Protobuf::FieldMask] # The fields to return for each Entry. If not set or empty, all # fields are returned. # For example, setting read_mask to contain only one path "name" will cause # ListEntries to return a list of Entries with only "name" field. class ListEntriesRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Response message for # {::Google::Cloud::DataCatalog::V1::DataCatalog::Client#list_entries ListEntries}. # @!attribute [rw] entries # @return [::Array<::Google::Cloud::DataCatalog::V1::Entry>] # Entry details. # @!attribute [rw] next_page_token # @return [::String] # Token to retrieve the next page of results. It is set to empty if no items # remain in results. class ListEntriesResponse include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Entry resources in Data Catalog can be of different types e.g. a BigQuery # Table entry is of type `TABLE`. This enum describes all the possible types # Data Catalog contains. module EntryType # Default unknown type. ENTRY_TYPE_UNSPECIFIED = 0 # Output only. The type of entry that has a GoogleSQL schema, including # logical views. TABLE = 2 # Output only. The type of models, examples include # https://cloud.google.com/bigquery-ml/docs/bigqueryml-intro MODEL = 5 # An entry type which is used for streaming entries. Example: # Pub/Sub topic. DATA_STREAM = 3 # An entry type which is a set of files or objects. Example: # Cloud Storage fileset. FILESET = 4 # A database. DATABASE = 7 # A service, for example, a Dataproc Metastore service. SERVICE = 14 end end end end end
48.2
167
0.605299
79154e422b6ae6d14f1fa7b8ca64b12156e48a36
4,524
#!/usr/bin/env ruby # Define a task library for running unit tests. require 'rake' require 'rake/tasklib' module Rake # Create a task that runs a set of tests. # # Example: # # Rake::TestTask.new do |t| # t.libs << "test" # t.test_files = FileList['test/test*.rb'] # t.verbose = true # end # # If rake is invoked with a "TEST=filename" command line option, # then the list of test files will be overridden to include only the # filename specified on the command line. This provides an easy way # to run just one test. # # If rake is invoked with a "TESTOPTS=options" command line option, # then the given options are passed to the test process after a # '--'. This allows Test::Unit options to be passed to the test # suite. # # Examples: # # rake test # run tests normally # rake test TEST=just_one_file.rb # run just one test file. # rake test TESTOPTS="-v" # run in verbose mode # rake test TESTOPTS="--runner=fox" # use the fox test runner # class TestTask < TaskLib # Name of test task. (default is :test) attr_accessor :name # List of directories to added to $LOAD_PATH before running the # tests. (default is 'lib') attr_accessor :libs # True if verbose test output desired. (default is false) attr_accessor :verbose # Test options passed to the test suite. An explicit # TESTOPTS=opts on the command line will override this. (default # is NONE) attr_accessor :options # Request that the tests be run with the warning flag set. # E.g. warning=true implies "ruby -w" used to run the tests. attr_accessor :warning # Glob pattern to match test files. (default is 'test/test*.rb') attr_accessor :pattern # Style of test loader to use. Options are: # # * :rake -- Rake provided test loading script (default). # * :testrb -- Ruby provided test loading script. # * :direct -- Load tests using command line loader. # attr_accessor :loader # Array of commandline options to pass to ruby when running test loader. attr_accessor :ruby_opts # Explicitly define the list of test files to be included in a # test. +list+ is expected to be an array of file names (a # FileList is acceptable). If both +pattern+ and +test_files+ are # used, then the list of test files is the union of the two. def test_files=(list) @test_files = list end # Create a testing task. def initialize(name=:test) @name = name @libs = ["lib"] @pattern = nil @options = nil @test_files = nil @verbose = false @warning = false @loader = :rake @ruby_opts = [] yield self if block_given? @pattern = 'test/test*.rb' if @pattern.nil? && @test_files.nil? define end # Create the tasks defined by this task lib. def define lib_path = @libs.join(File::PATH_SEPARATOR) desc "Run tests" + (@name==:test ? "" : " for #{@name}") task @name do run_code = '' RakeFileUtils.verbose(@verbose) do run_code = case @loader when :direct "-e 'ARGV.each{|f| load f}'" when :testrb "-S testrb #{fix}" when :rake rake_loader end @ruby_opts.unshift( "-I#{lib_path}" ) @ruby_opts.unshift( "-w" ) if @warning ruby @ruby_opts.join(" ") + " \"#{run_code}\" " + file_list.collect { |fn| "\"#{fn}\"" }.join(' ') + " #{option_list}" end end self end def option_list # :nodoc: ENV['TESTOPTS'] || @options || "" end def file_list # :nodoc: if ENV['TEST'] FileList[ ENV['TEST'] ] else result = [] result += @test_files.to_a if @test_files result += FileList[ @pattern ].to_a if @pattern FileList[result] end end def fix # :nodoc: case RUBY_VERSION when '1.8.2' find_file 'rake/ruby182_test_unit_fix' else nil end || '' end def rake_loader # :nodoc: find_file('rake/rake_test_loader') or fail "unable to find rake test loader" end def find_file(fn) # :nodoc: $LOAD_PATH.each do |path| file_path = File.join(path, "#{fn}.rb") return file_path if File.exist? file_path end nil end end end
27.925926
76
0.587091
5dddda21a856dcee5749380b750aa135ed65d231
1,843
Portfolio::Application.routes.draw do devise_for :admin mount RailsAdmin::Engine => '/admin', as: 'rails_admin' root 'home#index' resources :contact, :about, only: [:index] constraints(id: /\d+/) do resources :blog, :portfolio, only: [:index, :show] end # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
26.710145
84
0.646229
265f0992115b293a968c8d62dc12e93f4909a48a
175
RSpec.describe Kovid do it "has a version number" do expect(Kovid::VERSION).not_to be nil end it "does something useful" do expect(false).to eq(true) end end
17.5
40
0.691429
032fdad0263e8cc7cd9e38b98fc6a07fc43c3d54
1,724
# encoding: utf-8 # This file is autogenerated. Do not edit it manually. # If you want change the content of this file, edit # # /spec/fixtures/responses/whois.eenet.ee/status_registered.expected # # and regenerate the tests with the following rake task # # $ rake genspec:parsers # require 'spec_helper' require 'whois/record/parser/whois.eenet.ee.rb' describe Whois::Record::Parser::WhoisEenetEe, "status_registered.expected" do before(:each) do file = fixture("responses", "whois.eenet.ee/status_registered.txt") part = Whois::Record::Part.new(:body => File.read(file)) @parser = klass.new(part) end context "#status" do it do @parser.status.should == :registered end end context "#available?" do it do @parser.available?.should == false end end context "#registered?" do it do @parser.registered?.should == true end end context "#created_on" do it do @parser.created_on.should be_a(Time) @parser.created_on.should == Time.parse("2003-04-22") end end context "#updated_on" do it do @parser.updated_on.should be_a(Time) @parser.updated_on.should == Time.parse("2010-05-28") end end context "#expires_on" do it do lambda { @parser.expires_on }.should raise_error(Whois::PropertyNotSupported) end end context "#nameservers" do it do @parser.nameservers.should be_a(Array) @parser.nameservers.should have(2).items @parser.nameservers[0].should be_a(_nameserver) @parser.nameservers[0].name.should == "ns1.google.com" @parser.nameservers[1].should be_a(_nameserver) @parser.nameservers[1].name.should == "ns2.google.com" end end end
25.731343
83
0.675174
26dd991a582b39a46bb81387e18a16b87abd9605
937
Pod::Spec.new do |s| s.name = 'MHVideoPhotoGallery' s.version = '2.2.1' s.license = 'MIT' s.homepage = 'https://github.com/falipate/MHVideoPhotoGallery.git' s.author = { 'Mario Hahn' => '[email protected]' } s.summary = 'Gallery for iOS 9 Devices.' s.platform = :ios s.source = { :git => 'https://github.com/falipate/MHVideoPhotoGallery.git', :tag => 'v2.2.1' } s.dependency 'SDWebImage' s.dependency 'TTTAttributedLabel', '1.13.3' s.dependency 'Masonry' s.frameworks = 'MessageUI','Social', 'ImageIO', 'QuartzCore', 'Accelerate','CoreMedia', 'AVFoundation','MediaPlayer' s.resources = "MHVideoPhotoGallery/MMHVideoPhotoGallery/**/*.{png,bundle}" s.public_header_files = "MHVideoPhotoGallery/MMHVideoPhotoGallery/**/*.h" s.source_files = ['MHVideoPhotoGallery/MMHVideoPhotoGallery/**/*.{h,m}'] s.ios.deployment_target = '9.0' s.requires_arc = true end
33.464286
118
0.658485
382133175b4454874978f39dc871ace8c196862f
1,516
module Locomotive module Concerns module ContentType module EntryTemplate extend ActiveSupport::Concern included do ## fields ## field :entry_template ## validation ## validate :entry_template_must_be_valid end def render_entry_template(context) return nil if entry_template.blank? parsed_entry_template.render(context) end def to_steam @steam_content_type ||= steam_repositories.content_type.build(self.attributes.symbolize_keys) end def to_steam_entry(entry) entry_attributes = entry.attributes.symbolize_keys steam_repositories.content_entry.with(to_steam).build(entry_attributes).tap do |entity| # copy error messages entry.errors.each do |name, message| next if name == :_slug entity.errors.add(name, message) end end end def steam_repositories @steam_repositories ||= Locomotive::Steam::Services.build_instance.repositories end protected def parsed_entry_template @parsed_entry_template ||= ::Liquid::Template.parse(self.entry_template) end def entry_template_must_be_valid begin parsed_entry_template rescue ::Liquid::SyntaxError => error self.errors.add :entry_template, error.to_s end end end end end end
25.694915
103
0.613456
18bba70466d89876677a58a7fd498dca3ea4b47a
33,670
# frozen_string_literal: true require "helper" class TestTags < JekyllUnitTest def setup FileUtils.mkdir_p("tmp") end # rubocop:disable Metrics/AbcSize def create_post(content, override = {}, converter_class = Jekyll::Converters::Markdown) site = fixture_site({ "highlighter" => "rouge" }.merge(override)) site.posts.docs.concat(PostReader.new(site).read_posts("")) if override["read_posts"] CollectionReader.new(site).read if override["read_collections"] site.read if override["read_all"] info = { :filters => [Jekyll::Filters], :registers => { :site => site } } @converter = site.converters.find { |c| c.class == converter_class } payload = { "highlighter_prefix" => @converter.highlighter_prefix, "highlighter_suffix" => @converter.highlighter_suffix, } @result = Liquid::Template.parse(content).render!(payload, info) @result = @converter.convert(@result) end # rubocop:enable Metrics/AbcSize def fill_post(code, override = {}) content = <<~CONTENT --- title: This is a test --- This document has some highlighted code in it. {% highlight text %} #{code} {% endhighlight %} {% highlight text linenos %} #{code} {% endhighlight %} CONTENT create_post(content, override) end def highlight_block_with_opts(options_string) Jekyll::Tags::HighlightBlock.parse( "highlight", options_string, Liquid::Tokenizer.new("test{% endhighlight %}\n"), Liquid::ParseContext.new ) end context "language name" do should "match only the required set of chars" do r = Jekyll::Tags::HighlightBlock::SYNTAX assert_match r, "ruby" assert_match r, "c#" assert_match r, "xml+cheetah" assert_match r, "x.y" assert_match r, "coffee-script" assert_match r, "shell_session" refute_match r, "blah^" assert_match r, "ruby key=val" assert_match r, "ruby a=b c=d" end end context "highlight tag in unsafe mode" do should "set the no options with just a language name" do tag = highlight_block_with_opts("ruby ") assert_equal({}, tag.instance_variable_get(:@highlight_options)) end should "set the linenos option as 'inline' if no linenos value" do tag = highlight_block_with_opts("ruby linenos ") assert_equal( { :linenos => "inline" }, tag.instance_variable_get(:@highlight_options) ) end should "set the linenos option to 'table' " \ "if the linenos key is given the table value" do tag = highlight_block_with_opts("ruby linenos=table ") assert_equal( { :linenos => "table" }, tag.instance_variable_get(:@highlight_options) ) end should "recognize nowrap option with linenos set" do tag = highlight_block_with_opts("ruby linenos=table nowrap ") assert_equal( { :linenos => "table", :nowrap => true }, tag.instance_variable_get(:@highlight_options) ) end should "recognize the cssclass option" do tag = highlight_block_with_opts("ruby linenos=table cssclass=hl ") assert_equal( { :cssclass => "hl", :linenos => "table" }, tag.instance_variable_get(:@highlight_options) ) end should "recognize the hl_linenos option and its value" do tag = highlight_block_with_opts("ruby linenos=table cssclass=hl hl_linenos=3 ") assert_equal( { :cssclass => "hl", :linenos => "table", :hl_linenos => "3" }, tag.instance_variable_get(:@highlight_options) ) end should "recognize multiple values of hl_linenos" do tag = highlight_block_with_opts 'ruby linenos=table cssclass=hl hl_linenos="3 5 6" ' assert_equal( { :cssclass => "hl", :linenos => "table", :hl_linenos => %w(3 5 6) }, tag.instance_variable_get(:@highlight_options) ) end should "treat language name as case insensitive" do tag = highlight_block_with_opts("Ruby ") assert_equal( "ruby", tag.instance_variable_get(:@lang), "lexers should be case insensitive" ) end end context "with the rouge highlighter" do context "post content has highlight tag" do setup do fill_post("test") end should "render markdown with rouge" do assert_match( %(<pre><code class="language-text" data-lang="text">test</code></pre>), @result ) end should "render markdown with rouge with line numbers" do assert_match( %(<table class="rouge-table"><tbody>) + %(<tr><td class="gutter gl">) + %(<pre class="lineno">1\n</pre></td>) + %(<td class="code"><pre>test\n</pre></td></tr>) + %(</tbody></table>), @result ) end end context "post content has raw tag" do setup do content = <<~CONTENT --- title: This is a test --- ```liquid {% raw %} {{ site.baseurl }}{% link _collection/name-of-document.md %} {% endraw %} ``` CONTENT create_post(content) end should "render markdown with rouge" do assert_match( %(<div class="language-liquid highlighter-rouge">) + %(<div class="highlight"><pre class="highlight"><code>), @result ) end end context "post content has highlight with file reference" do setup do fill_post("./jekyll.gemspec") end should "not embed the file" do assert_match( '<pre><code class="language-text" data-lang="text">' \ "./jekyll.gemspec</code></pre>", @result ) end end context "post content has highlight tag with UTF character" do setup do fill_post("Æ") end should "render markdown with pygments line handling" do assert_match( '<pre><code class="language-text" data-lang="text">Æ</code></pre>', @result ) end end context "post content has highlight tag with preceding spaces & lines" do setup do fill_post <<~EOS [,1] [,2] [1,] FALSE TRUE [2,] FALSE TRUE EOS end should "only strip the preceding newlines" do assert_match( '<pre><code class="language-text" data-lang="text"> [,1] [,2]', @result ) end end context "post content has highlight tag with " \ "preceding spaces & lines in several places" do setup do fill_post <<~EOS [,1] [,2] [1,] FALSE TRUE [2,] FALSE TRUE EOS end should "only strip the newlines which precede and succeed the entire block" do assert_match( "<pre><code class=\"language-text\" data-lang=\"text\"> [,1] [,2]\n\n\n" \ "[1,] FALSE TRUE\n[2,] FALSE TRUE</code></pre>", @result ) end end context "post content has highlight tag with linenumbers" do setup do create_post <<~EOS --- title: This is a test --- This is not yet highlighted {% highlight php linenos %} test {% endhighlight %} This should not be highlighted, right? EOS end should "should stop highlighting at boundary with rouge" do expected = <<~EOS <p>This is not yet highlighted</p>\n <figure class="highlight"><pre><code class="language-php" data-lang="php"><table class="rouge-table"><tbody><tr><td class="gutter gl"><pre class="lineno">1 </pre></td><td class="code"><pre><span class="n">test</span>\n</pre></td></tr></tbody></table></code></pre></figure>\n <p>This should not be highlighted, right?</p> EOS assert_match(expected, @result) end end context "post content has highlight tag with " \ "preceding spaces & Windows-style newlines" do setup do fill_post "\r\n\r\n\r\n [,1] [,2]" end should "only strip the preceding newlines" do assert_match( '<pre><code class="language-text" data-lang="text"> [,1] [,2]', @result ) end end context "post content has highlight tag with only preceding spaces" do setup do fill_post <<~EOS [,1] [,2] [1,] FALSE TRUE [2,] FALSE TRUE EOS end should "only strip the preceding newlines" do assert_match( '<pre><code class="language-text" data-lang="text"> [,1] [,2]', @result ) end end end context "simple post with markdown and pre tags" do setup do @content = <<~CONTENT --- title: Kramdown post with pre --- _FIGHT!_ {% highlight ruby %} puts "3..2..1.." {% endhighlight %} *FINISH HIM* CONTENT end context "using Kramdown" do setup do create_post(@content, "markdown" => "kramdown") end should "parse correctly" do assert_match %r{<em>FIGHT!</em>}, @result assert_match %r!<em>FINISH HIM</em>!, @result end end end context "simple page with post linking" do setup do content = <<~CONTENT --- title: Post linking --- {% post_url 2008-11-21-complex %} CONTENT create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end should "not cause an error" do refute_match(%r!markdown-html-error!, @result) end should "have the URL to the 'complex' post from 2008-11-21" do assert_match %r!/2008/11/21/complex/!, @result end end context "simple page with post linking containing special characters" do setup do content = <<~CONTENT --- title: Post linking --- {% post_url 2016-11-26-special-chars-(+) %} CONTENT create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end should "not cause an error" do refute_match(%r!markdown-html-error!, @result) end should "have the URL to the 'special-chars' post from 2016-11-26" do assert_match %r!/2016/11/26/special-chars-\(\+\)/!, @result end end context "simple page with nested post linking" do setup do content = <<~CONTENT --- title: Post linking --- - 1 {% post_url 2008-11-21-complex %} - 2 {% post_url /2008-11-21-complex %} - 3 {% post_url es/2008-11-21-nested %} - 4 {% post_url /es/2008-11-21-nested %} CONTENT create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end should "not cause an error" do refute_match(%r!markdown-html-error!, @result) end should "have the URL to the 'complex' post from 2008-11-21" do assert_match %r!1\s/2008/11/21/complex/!, @result assert_match %r!2\s/2008/11/21/complex/!, @result end should "have the URL to the 'nested' post from 2008-11-21" do assert_match %r!3\s/2008/11/21/nested/!, @result assert_match %r!4\s/2008/11/21/nested/!, @result end end context "simple page with nested post linking and path not used in `post_url`" do setup do content = <<~CONTENT --- title: Deprecated Post linking --- - 1 {% post_url 2008-11-21-nested %} CONTENT create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end should "not cause an error" do refute_match(%r!markdown-html-error!, @result) end should "have the url to the 'nested' post from 2008-11-21" do assert_match %r!1\s/2008/11/21/nested/!, @result end should "throw a deprecation warning" do deprecation_warning = " Deprecation: A call to "\ "'{% post_url 2008-11-21-nested %}' did not match a post using the new matching "\ "method of checking name (path-date-slug) equality. Please make sure that you "\ "change this tag to match the post's name exactly." assert_includes Jekyll.logger.messages, deprecation_warning end end context "simple page with invalid post name linking" do should "cause an error" do content = <<~CONTENT --- title: Invalid post name linking --- {% post_url abc2008-11-21-complex %} CONTENT assert_raises Jekyll::Errors::PostURLError do create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end end should "cause an error with a bad date" do content = <<~CONTENT --- title: Invalid post name linking --- {% post_url 2008-42-21-complex %} CONTENT assert_raises Jekyll::Errors::InvalidDateError do create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end end end context "simple page with linking to a page" do setup do content = <<~CONTENT --- title: linking --- {% link contacts.html %} {% link info.md %} {% link /css/screen.css %} CONTENT create_post(content, "source" => source_dir, "destination" => dest_dir, "read_all" => true) end should "not cause an error" do refute_match(%r!markdown-html-error!, @result) end should "have the URL to the 'contacts' item" do assert_match(%r!/contacts\.html!, @result) end should "have the URL to the 'info' item" do assert_match(%r!/info\.html!, @result) end should "have the URL to the 'screen.css' item" do assert_match(%r!/css/screen\.css!, @result) end end context "simple page with dynamic linking to a page" do setup do content = <<~CONTENT --- title: linking --- {% assign contacts_filename = 'contacts' %} {% assign contacts_ext = 'html' %} {% link {{contacts_filename}}.{{contacts_ext}} %} {% assign info_path = 'info.md' %} {% link {{\ info_path\ }} %} {% assign screen_css_path = '/css' %} {% link {{ screen_css_path }}/screen.css %} CONTENT create_post(content, "source" => source_dir, "destination" => dest_dir, "read_all" => true) end should "not cause an error" do refute_match(%r!markdown-html-error!, @result) end should "have the URL to the 'contacts' item" do assert_match(%r!/contacts\.html!, @result) end should "have the URL to the 'info' item" do assert_match(%r!/info\.html!, @result) end should "have the URL to the 'screen.css' item" do assert_match(%r!/css/screen\.css!, @result) end end context "simple page with linking" do setup do content = <<~CONTENT --- title: linking --- {% link _methods/yaml_with_dots.md %} CONTENT create_post(content, "source" => source_dir, "destination" => dest_dir, "collections" => { "methods" => { "output" => true } }, "read_collections" => true) end should "not cause an error" do refute_match(%r!markdown-html-error!, @result) end should "have the URL to the 'yaml_with_dots' item" do assert_match(%r!/methods/yaml_with_dots\.html!, @result) end end context "simple page with dynamic linking" do setup do content = <<~CONTENT --- title: linking --- {% assign yaml_with_dots_path = '_methods/yaml_with_dots.md' %} {% link {{yaml_with_dots_path}} %} CONTENT create_post(content, "source" => source_dir, "destination" => dest_dir, "collections" => { "methods" => { "output" => true } }, "read_collections" => true) end should "not cause an error" do refute_match(%r!markdown-html-error!, @result) end should "have the URL to the 'yaml_with_dots' item" do assert_match(%r!/methods/yaml_with_dots\.html!, @result) end end context "simple page with nested linking" do setup do content = <<~CONTENT --- title: linking --- - 1 {% link _methods/sanitized_path.md %} - 2 {% link _methods/site/generate.md %} CONTENT create_post(content, "source" => source_dir, "destination" => dest_dir, "collections" => { "methods" => { "output" => true } }, "read_collections" => true) end should "not cause an error" do refute_match(%r!markdown-html-error!, @result) end should "have the URL to the 'sanitized_path' item" do assert_match %r!1\s/methods/sanitized_path\.html!, @result end should "have the URL to the 'site/generate' item" do assert_match %r!2\s/methods/site/generate\.html!, @result end end context "simple page with invalid linking" do should "cause an error" do content = <<~CONTENT --- title: Invalid linking --- {% link non-existent-collection-item %} CONTENT assert_raises ArgumentError do create_post(content, "source" => source_dir, "destination" => dest_dir, "collections" => { "methods" => { "output" => true } }, "read_collections" => true) end end end context "simple page with invalid dynamic linking" do should "cause an error" do content = <<~CONTENT --- title: Invalid linking --- {% assign non_existent_path = 'non-existent-collection-item' %} {% link {{\ non_existent_path\ }} %} CONTENT assert_raises ArgumentError do create_post(content, "source" => source_dir, "destination" => dest_dir, "collections" => { "methods" => { "output" => true } }, "read_collections" => true) end end end context "include tag with parameters" do context "with symlink'd include" do should "not allow symlink includes" do File.open("tmp/pages-test", "w") { |file| file.write("SYMLINK TEST") } assert_raises IOError do content = <<~CONTENT --- title: Include symlink --- {% include tmp/pages-test %} CONTENT create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true, "safe" => true) end @result ||= "" refute_match(%r!SYMLINK TEST!, @result) end should "not expose the existence of symlinked files" do ex = assert_raises IOError do content = <<~CONTENT --- title: Include symlink --- {% include tmp/pages-test-does-not-exist %} CONTENT create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true, "safe" => true) end assert_match( "Could not locate the included file 'tmp/pages-test-does-not-exist' " \ "in any of [\"#{source_dir}/_includes\"]. Ensure it exists in one of " \ "those directories and is not a symlink as those are not allowed in " \ "safe mode.", ex.message ) end end context "with one parameter" do setup do content = <<~CONTENT --- title: Include tag parameters --- {% include sig.markdown myparam="test" %} {% include params.html param="value" %} CONTENT create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end should "correctly output include variable" do assert_match "<span id=\"include-param\">value</span>", @result.strip end should "ignore parameters if unused" do assert_match "<hr />\n<p>Tom Preston-Werner\ngithub.com/mojombo</p>\n", @result end end context "with simple syntax but multiline markup" do setup do content = <<~CONTENT --- title: Include tag parameters --- {% include sig.markdown myparam="test" %} {% include params.html param="value" %} CONTENT create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end should "correctly output include variable" do assert_match "<span id=\"include-param\">value</span>", @result.strip end should "ignore parameters if unused" do assert_match "<hr />\n<p>Tom Preston-Werner\ngithub.com/mojombo</p>\n", @result end end context "with variable syntax but multiline markup" do setup do content = <<~CONTENT --- title: Include tag parameters --- {% include sig.markdown myparam="test" %} {% assign path = "params" | append: ".html" %} {% include {{ path }} param="value" %} CONTENT create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end should "correctly output include variable" do assert_match "<span id=\"include-param\">value</span>", @result.strip end should "ignore parameters if unused" do assert_match "<hr />\n<p>Tom Preston-Werner\ngithub.com/mojombo</p>\n", @result end end context "with invalid parameter syntax" do should "throw a ArgumentError" do content = <<~CONTENT --- title: Invalid parameter syntax --- {% include params.html param s="value" %} CONTENT assert_raises ArgumentError, "Did not raise exception on invalid " \ '"include" syntax' do create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end content = <<~CONTENT --- title: Invalid parameter syntax --- {% include params.html params="value %} CONTENT assert_raises ArgumentError, "Did not raise exception on invalid " \ '"include" syntax' do create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end end end context "with several parameters" do setup do content = <<~CONTENT --- title: multiple include parameters --- {% include params.html param1="new_value" param2="another" %} CONTENT create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end should "list all parameters" do assert_match "<li>param1 = new_value</li>", @result assert_match "<li>param2 = another</li>", @result end should "not include previously used parameters" do assert_match "<span id=\"include-param\"></span>", @result end end context "without parameters" do setup do content = <<~CONTENT --- title: without parameters --- {% include params.html %} CONTENT create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end should "include file with empty parameters" do assert_match "<span id=\"include-param\"></span>", @result end end context "with custom includes directory" do setup do content = <<~CONTENT --- title: custom includes directory --- {% include custom.html %} CONTENT create_post(content, "includes_dir" => "_includes_custom", "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end should "include file from custom directory" do assert_match "custom_included", @result end end context "without parameters within if statement" do setup do content = <<~CONTENT --- title: without parameters within if statement --- {% if true %}{% include params.html %}{% endif %} CONTENT create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end should "include file with empty parameters within if statement" do assert_match "<span id=\"include-param\"></span>", @result end end context "include missing file" do setup do @content = <<~CONTENT --- title: missing file --- {% include missing.html %} CONTENT end should "raise error relative to source directory" do exception = assert_raises IOError do create_post(@content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end assert_match( "Could not locate the included file 'missing.html' in any of " \ "[\"#{source_dir}/_includes\"].", exception.message ) end end context "include tag with variable and liquid filters" do setup do site = fixture_site("pygments" => true).tap(&:read).tap(&:render) post = site.posts.docs.find do |p| p.basename.eql? "2013-12-17-include-variable-filters.markdown" end @content = post.output end should "include file as variable with liquid filters" do assert_match(%r!1 included!, @content) assert_match(%r!2 included!, @content) assert_match(%r!3 included!, @content) end should "include file as variable and liquid filters with arbitrary whitespace" do assert_match(%r!4 included!, @content) assert_match(%r!5 included!, @content) assert_match(%r!6 included!, @content) end should "include file as variable and filters with additional parameters" do assert_match("<li>var1 = foo</li>", @content) assert_match("<li>var2 = bar</li>", @content) end should "include file as partial variable" do assert_match(%r!8 included!, @content) end end end context "relative include tag with variable and liquid filters" do setup do site = fixture_site("pygments" => true).tap(&:read).tap(&:render) post = site.posts.docs.find do |p| p.basename.eql? "2014-09-02-relative-includes.markdown" end @content = post.output end should "include file as variable with liquid filters" do assert_match(%r!1 relative_include!, @content) assert_match(%r!2 relative_include!, @content) assert_match(%r!3 relative_include!, @content) end should "include file as variable and liquid filters with arbitrary whitespace" do assert_match(%r!4 relative_include!, @content) assert_match(%r!5 relative_include!, @content) assert_match(%r!6 relative_include!, @content) end should "include file as variable and filters with additional parameters" do assert_match("<li>var1 = foo</li>", @content) assert_match("<li>var2 = bar</li>", @content) end should "include file as partial variable" do assert_match(%r!8 relative_include!, @content) end should "include files relative to self" do assert_match(%r!9 —\ntitle: Test Post Where YAML!, @content) end context "trying to do bad stuff" do context "include missing file" do setup do @content = <<~CONTENT --- title: missing file --- {% include_relative missing.html %} CONTENT end should "raise error relative to source directory" do exception = assert_raises IOError do create_post(@content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end assert_match "Could not locate the included file 'missing.html' in any of " \ "[\"#{source_dir}\"].", exception.message end end context "include existing file above you" do setup do @content = <<~CONTENT --- title: higher file --- {% include_relative ../README.markdown %} CONTENT end should "raise error relative to source directory" do exception = assert_raises ArgumentError do create_post(@content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true) end assert_equal( "Invalid syntax for include tag. File contains invalid characters or " \ "sequences:\n\n ../README.markdown\n\nValid syntax:\n\n " \ "{% include_relative file.ext param='value' param2='value' %}\n\n", exception.message ) end end end context "with symlink'd include" do should "not allow symlink includes" do File.open("tmp/pages-test", "w") { |file| file.write("SYMLINK TEST") } assert_raises IOError do content = <<~CONTENT --- title: Include symlink --- {% include_relative tmp/pages-test %} CONTENT create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true, "safe" => true) end @result ||= "" refute_match(%r!SYMLINK TEST!, @result) end should "not expose the existence of symlinked files" do ex = assert_raises IOError do content = <<~CONTENT --- title: Include symlink --- {% include_relative tmp/pages-test-does-not-exist %} CONTENT create_post(content, "permalink" => "pretty", "source" => source_dir, "destination" => dest_dir, "read_posts" => true, "safe" => true) end assert_match( "Ensure it exists in one of those directories and is not a symlink "\ "as those are not allowed in safe mode.", ex.message ) end end end end
29.252824
165
0.533234
ff0bfb81370a57dc82b8b7d2955372846ea132d7
827
module Smartweb::V1 autoload :API, 'smartweb/v1/api' autoload :Order, 'smartweb/v1/order' module Workers autoload :BaseWorker, 'smartweb/v1/workers/base_worker' module Products autoload :CollectionWorker, 'smartweb/v1/workers/products/collection_worker' end module Categories autoload :CollectionWorker, 'smartweb/v1/workers/categories/collection_worker' end module Orders autoload :DisperseWorker, 'smartweb/v1/workers/orders/disperse_worker' autoload :CollectionWorker, 'smartweb/v1/workers/orders/collection_worker' end end module Formatters autoload :FormatProduct, 'smartweb/v1/formatters/format_product' autoload :FormatCategory, 'smartweb/v1/formatters/format_category' autoload :FormatOrder, 'smartweb/v1/formatters/format_order' end end
29.535714
84
0.754534
b944ba8478b4464cf2c4ecfc708f9f5f97dc0a37
177
class CreateOrders < ActiveRecord::Migration[6.1] def change create_table :orders do |t| t.string :name t.integer :state t.timestamps end end end
16.090909
49
0.644068
28e95aad071abc753f9fbeff9c4145d99a7a5b89
6,144
require 'test_helper' class RemoteRedsysSHA256Test < Test::Unit::TestCase def setup @gateway = RedsysGateway.new(fixtures(:redsys_sha256)) @credit_card = credit_card('4548812049400004') @declined_card = credit_card @options = { order_id: generate_order_id, } end def test_successful_purchase response = @gateway.purchase(100, @credit_card, @options) assert_success response assert_equal 'Transaction Approved', response.message end def test_purchase_with_invalid_order_id response = @gateway.purchase(100, @credit_card, order_id: "a%4#{generate_order_id}") assert_success response assert_equal 'Transaction Approved', response.message end def test_successful_purchase_using_vault_id response = @gateway.purchase(100, @credit_card, @options.merge(store: true)) assert_success response assert_equal 'Transaction Approved', response.message credit_card_token = response.params['ds_merchant_identifier'] assert_not_nil credit_card_token @options[:order_id] = generate_order_id response = @gateway.purchase(100, credit_card_token, @options) assert_success response assert_equal 'Transaction Approved', response.message end def test_failed_purchase response = @gateway.purchase(100, @declined_card, @options) assert_failure response assert_equal 'SIS0093 ERROR', response.message end def test_purchase_and_refund purchase = @gateway.purchase(100, @credit_card, @options) assert_success purchase refund = @gateway.refund(100, purchase.authorization) assert_success refund end # Multiple currencies are not supported in test, but should at least fail. def test_purchase_and_refund_with_currency response = @gateway.purchase(600, @credit_card, @options.merge(:currency => 'PEN')) assert_failure response assert_equal 'SIS0027 ERROR', response.message end def test_successful_authorise_and_capture authorize = @gateway.authorize(100, @credit_card, @options) assert_success authorize assert_equal 'Transaction Approved', authorize.message assert_not_nil authorize.authorization capture = @gateway.capture(100, authorize.authorization) assert_success capture assert_match /Refund.*approved/, capture.message end def test_successful_authorise_using_vault_id authorize = @gateway.authorize(100, @credit_card, @options.merge(store: true)) assert_success authorize assert_equal 'Transaction Approved', authorize.message assert_not_nil authorize.authorization credit_card_token = authorize.params['ds_merchant_identifier'] assert_not_nil credit_card_token @options[:order_id] = generate_order_id authorize = @gateway.authorize(100, credit_card_token, @options) assert_success authorize assert_equal 'Transaction Approved', authorize.message assert_not_nil authorize.authorization end def test_failed_authorize response = @gateway.authorize(100, @declined_card, @options) assert_failure response assert_equal 'SIS0093 ERROR', response.message end def test_successful_void authorize = @gateway.authorize(100, @credit_card, @options) assert_success authorize void = @gateway.void(authorize.authorization) assert_success void assert_equal '100', void.params['ds_amount'] assert_equal 'Cancellation Accepted', void.message end def test_failed_void authorize = @gateway.authorize(100, @credit_card, @options) assert_success authorize void = @gateway.void(authorize.authorization) assert_success void another_void = @gateway.void(authorize.authorization) assert_failure another_void assert_equal 'SIS0222 ERROR', another_void.message end def test_successful_verify assert response = @gateway.verify(@credit_card, @options) assert_success response assert_equal 'Transaction Approved', response.message assert_success response.responses.last, 'The void should succeed' assert_equal 'Cancellation Accepted', response.responses.last.message end def test_unsuccessful_verify assert response = @gateway.verify(@declined_card, @options) assert_failure response assert_equal 'SIS0093 ERROR', response.message end def test_transcript_scrubbing transcript = capture_transcript(@gateway) do @gateway.purchase(@amount, @credit_card, @options) end clean_transcript = @gateway.scrub(transcript) assert_scrubbed(@gateway.options[:secret_key], clean_transcript) assert_scrubbed(@credit_card.number, clean_transcript) assert_scrubbed(@credit_card.verification_value.to_s, clean_transcript) end def test_transcript_scrubbing_on_failed_transactions transcript = capture_transcript(@gateway) do @gateway.purchase(@amount, @declined_card, @options) end clean_transcript = @gateway.scrub(transcript) assert_scrubbed(@gateway.options[:secret_key], clean_transcript) assert_scrubbed(@credit_card.number, clean_transcript) assert_scrubbed(@credit_card.verification_value.to_s, clean_transcript) end def test_nil_cvv_transcript_scrubbing @credit_card.verification_value = nil transcript = capture_transcript(@gateway) do @gateway.purchase(@amount, @credit_card, @options) end clean_transcript = @gateway.scrub(transcript) assert_equal clean_transcript.include?('[BLANK]'), true end def test_empty_string_cvv_transcript_scrubbing @credit_card.verification_value = '' transcript = capture_transcript(@gateway) do @gateway.purchase(@amount, @credit_card, @options) end clean_transcript = @gateway.scrub(transcript) assert_equal clean_transcript.include?('[BLANK]'), true end def test_whitespace_string_cvv_transcript_scrubbing @credit_card.verification_value = ' ' transcript = capture_transcript(@gateway) do @gateway.purchase(@amount, @credit_card, @options) end clean_transcript = @gateway.scrub(transcript) assert_equal clean_transcript.include?('[BLANK]'), true end private def generate_order_id (Time.now.to_f * 100).to_i.to_s end end
33.032258
88
0.760742
d5adb8c0e381df20399e45fa4e1c102d58ddb5b3
62
module Itamae module Client VERSION = "0.1.0" end end
10.333333
21
0.645161
b9a999c012e086aff626aeeda9c95e9cd783033a
2,109
# libraries/default.rb module Zk PERM_NONE = 0x00 PERM_READ = 0x01 PERM_WRITE = 0x02 PERM_CREATE = 0x04 PERM_DELETE = 0x08 PERM_ADMIN = 0x10 PERM_ALL = PERM_READ | PERM_WRITE | PERM_CREATE | PERM_DELETE | PERM_ADMIN def self.error_message(error_code) case error_code when -1 then 'System error' when -2 then 'Runtime inconsistency' when -3 then 'Data inconsistency' when -4 then 'Connection loss' when -5 then 'Marshalling error' when -6 then 'Unimplemented' when -7 then 'Operation timeout' when -8 then 'Bad arguments' when -13 then 'New config no Quorum' when -14 then 'Another reconfiguration is in progress' when -100 then 'Api errors' when -101 then 'Node does not exists' when -102 then 'No authentication' when -103 then 'Bad version' when -108 then 'No children for ephemerals' when -110 then 'Node already exists' when -111 then 'Node not empty' when -112 then 'Session has expired' when -113 then 'Invalid callback' when -114 then 'Invalid acl' when -115 then 'Authentication has failed' when -118 then 'Session has moved' when -119 then 'This server does not support read only' when -120 then 'Attempt to create ephemeral node on a local session' when -121 then 'Attempts to remove a non-existing watcher' else 'Unknown' end end module Gem def zk require 'zookeeper' # use class variable otherwise new connection is created for each resource @@zk ||= ::Zookeeper.new(connect_str).tap do |zk| zk.add_auth scheme: auth_scheme, cert: auth_cert unless auth_cert.nil? end end def compile_acls require 'zookeeper' @compiled_acls ||= [].tap do |acls| acls << ::Zookeeper::ACLs::ACL.new(id: { id: 'anyone', scheme: 'world' }, perms: acl_world) %w(digest ip sasl).each do |scheme| send("acl_#{scheme}".to_sym).each do |id, perms| acls << ::Zookeeper::ACLs::ACL.new(id: { scheme: scheme, id: id }, perms: perms) end end end end end end
31.477612
99
0.652916
397bcdc5f580d36aab43d17e6b6ee1548e8d3ab1
408
Rails.application.routes.draw do get 'sessions/new' get '/signup', to: 'users#new' root 'static_pages#home' get '/help', to: 'static_pages#help', as: 'helf' get '/about', to: 'static_pages#about' get '/contact', to: 'static_pages#contact' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' delete '/logout', to: 'sessions#destroy' resources :users end
34
54
0.642157
4a6bde62d3bc927a682a159b2936072934fcb43e
2,886
Teacher.delete_all Teacher.create(:name => "Matt Hardy", :email => "[email protected]", :password => "hardip") Teacher.create(:name => "Chelsea Matthews", :email => "[email protected]", :password => "mattchel") Teacher.create(:name => "Robert Fredericks", :email => "[email protected]", :password => "robfred") Teacher.create(:name => "James Wilkos", :email => "[email protected]", :password => "jwilly") Teacher.create(:name => "Barry White", :email => "[email protected]", :password => "barry93") Student.delete_all Student.create(:student_name => "Jimmy Green", :student_birthday => "2010-10-5", :teacher_id => 99) Student.create(:student_name => "Lonnie Parker", :student_birthday => "2010-6-8", :teacher_id => 99) Student.create(:student_name => "Tim Hall", :student_birthday => "2010-3-5", :teacher_id => 100) Student.create(:student_name => "Pam Hollis", :student_birthday => "2010-4-4", :teacher_id => 100) Student.create(:student_name => "Brad Wilson", :student_birthday => "2010-7-8", :teacher_id => 101) Student.create(:student_name => "Terry Chan", :student_birthday => "2010-11-11", :teacher_id => 101) Student.create(:student_name => "Mike Campbell", :student_birthday => "2010-5-5", :teacher_id => 102) Student.create(:student_name => "Larry Thomas", :student_birthday => "2010-6-6", :teacher_id => 102) Student.create(:student_name => "Cal Webber", :student_birthday => "2010-7-7", :teacher_id => 103) Student.create(:student_name => "Jeff Williams", :student_birthday => "2010-04-06", :teacher_id => 103) Party.delete_all Party.create(:venue => "Gym", :student_name => "Jimmy Green", :party_date => "2010-10-5", :teacher_id => 99, :student_id => 122) Party.create(:venue => "Cafeteria", :student_name => "Lonnie Parker", :party_date => "2010-6-8", :teacher_id => 99, :student_id => 123) Party.create(:venue => "Gym", :student_name => "Tim Hall", :party_date => "2010-3-5", :teacher_id => 100, :student_id => 124) Party.create(:venue => "Cafeteria", :student_name => "Pam Hollis", :party_date => "2010-4-4", :teacher_id => 100, :student_id => 125) Party.create(:venue => "Gym", :student_name => "Brad Wilson", :party_date => "2010-7-8", :teacher_id => 101, :student_id => 126) Party.create(:venue => "Cafeteria", :student_name => "Terry Chan", :party_date => "2010-11-11", :teacher_id => 101, :student_id => 127) Party.create(:venue => "Gym", :student_name => "Mike Campbell", :party_date => "2010-5-5", :teacher_id => 102, :student_id => 128) Party.create(:venue => "Cafeteria", :student_name => "Larry Thomas", :party_date => "2010-6-6", :teacher_id => 102, :student_id => 129) Party.create(:venue => "Cafeteria", :student_name => "Cal Webber", :party_date => "2010-7-7", :teacher_id => 103, :student_id => 130) Party.create(:venue => "Gym", :student_name => "Jeff Williams", :party_date => "2010-04-06", :teacher_id => 103, :student_id => 131)
52.472727
135
0.670132
877922dd67b7e4986a51a22fe2031c8366ca87fe
2,320
# -*- ruby -*- # # Copyright 2017-2018 Kouhei Sutou <[email protected]> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. clean_white_space = lambda do |entry| entry.gsub(/(\A\n+|\n+\z)/, '') + "\n" end base_dir = __dir__ lib_dir = File.join(base_dir, "lib") $LOAD_PATH.unshift(lib_dir) require "arrow-pycall/version" pycall_version = File.read(File.join(base_dir, "pycall-version")).strip Gem::Specification.new do |spec| spec.name = "red-arrow-pycall" spec.version = ArrowPyCall::VERSION spec.homepage = "https://github.com/red-data-tools/red-arrow-pycall" spec.authors = ["Kouhei Sutou"] spec.email = ["[email protected]"] readme = File.read("README.md") readme.force_encoding("UTF-8") entries = readme.split(/^\#\#\s(.*)$/) clean_white_space.call(entries[entries.index("Description") + 1]) description = clean_white_space.call(entries[entries.index("Description") + 1]) spec.summary, spec.description, = description.split(/\n\n+/, 3) spec.license = "Apache-2.0" spec.files = ["README.md", "Rakefile", "Gemfile", "#{spec.name}.gemspec"] spec.files += [".yardopts"] spec.files += ["pycall-version"] spec.files += Dir.glob("lib/**/*.rb") spec.files += Dir.glob("ext/**/*.{c,cpp}") spec.files += Dir.glob("doc/text/*") spec.extensions = ["ext/arrow-pycall/extconf.rb"] spec.test_files += Dir.glob("test/**/*") spec.add_runtime_dependency("extpp") spec.add_runtime_dependency("red-arrow") spec.add_runtime_dependency("red-parquet") spec.add_runtime_dependency("pycall", pycall_version) spec.add_development_dependency("bundler") spec.add_development_dependency("rake") spec.add_development_dependency("test-unit") spec.add_development_dependency("rake-compiler") spec.add_development_dependency("packnga") spec.add_development_dependency("kramdown") end
36.825397
81
0.717241
6277edd249f94e4bdbf2b3ffd28d03d0ea80ac10
947
#encoding: utf-8 module Aequitas class Rule class Nullary class Attribute # Rule that tests inputs against formats class Format < self TYPE = :invalid # Builder for format rule class Builder < Builder::Nullary REQUIRED_OPTIONS = [:format].freeze private # Return rule for attribute name # # @return [Rule] # # @api private # def rule(name) klass.new(name, matcher) end # Return format matcher # # @return [Matcher::Format] # # @api private # def matcher Matcher::Nullary::Format.build(options.fetch(:format)) end memoize :matcher end register :validates_format_of end end end end end
20.148936
68
0.467793
796805ed011a8d0b6898a2be5a95e8cd776c3eb6
550
require 'puppet/provider/aos' Puppet::Type.type(:aos_a_vlan).provide :aos, :parent => Puppet::Provider::Aos do desc "Aos switch/router provider for vlans." mk_resource_methods def self.lookup(device, id) vlans = {} device.command do |dev| vlans = dev.parse_aos_vlans || {} end vlans[id] end def initialize(device, *args) super end # Clear out the cached values. def flush device.command do |dev| dev.update_aos_vlan(resource[:name], former_properties, properties) end super end end
18.965517
80
0.669091
792e7ad28bc65c193551d99bc75fbc6702251909
1,581
# frozen_string_literal: true # Copyright 2015 Australian National Botanic Gardens # # This file is part of the NSL Editor. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "test_helper" # Single integration test. class AvailableFieldsForReadOnlyUserTest < ActionDispatch::IntegrationTest include Capybara::DSL test "it" do visit_home_page_as_read_only_user standard_page_assertions select "Instances", from: "query-on" select "with id", from: "query-field" fill_in "search-field", with: instances(:britten_created_angophora_costata).id click_on "Search" big_sleep all(".takes-focus").first.click little_sleep search_result_details_must_include_link("Details", "Read only User should see Details tab.") search_result_details_must_not_include_link("Edit", "Read only user should not see Edit tab.") end end
35.133333
76
0.658444
269c873308ed4ae97faf02ea04fc04e53a588c51
1,533
require_relative "lib/multi_render/version" Gem::Specification.new do |spec| spec.name = "multi_render" spec.version = MultiRender::VERSION spec.authors = ["Karl Heitmann"] spec.email = ["[email protected]"] spec.summary = "MultiRenderer is a class that renders multiple partials on your view." spec.description = "Once you provide to a MultiRenderer instance the data it needs in each partial you are rendering in your view, the instance will render the given partial with it's local variables. This is usefull if you have a big view on your project, and you are rendering multiple arrays. Having all your iterations running on your controller can help you to detect a bottle neck that is causing your web page to run slow." spec.homepage = "https://github.com/KarlHeitmann/multi_renderer" spec.license = "MIT" # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host' # to allow pushing to a single host or delete this section to allow pushing to any host. # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'" spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = "https://github.com/KarlHeitmann/multi_renderer" spec.metadata["changelog_uri"] = "https://github.com/KarlHeitmann/multi_renderer/blob/master/CHANGELOG.md" spec.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"] spec.add_dependency "rails", "~> 6.1.4", ">= 6.1.4.1" end
54.75
434
0.72668
bb21870ae0d35cdba45c9220f6d0e8813e3d3bed
1,311
module Api module V1 class SearchController < ApplicationController include PaginationHeaders include CustomErrors include Cacheable after_action :set_cache_control, only: :index def index locations = Location.search(params).page(params[:page]). per(params[:per_page]) if stale?(etag: cache_key(locations), public: true) generate_pagination_headers(locations) render json: locations.preload(tables), each_serializer: LocationsSerializer, status: 200 end end def nearby location = Location.find(params[:location_id]) render json: [] and return if location.latitude.blank? render json: locations_near(location), each_serializer: NearbySerializer, status: 200 generate_pagination_headers(locations_near(location)) end private def tables [:organization, :address, :phones] end def locations_near(location) location.nearbys(params[:radius]).status('active'). page(params[:page]).per(params[:per_page]).includes(:address) end def cache_key(scope) Digest::MD5.hexdigest( "#{scope.to_sql}-#{scope.maximum(:updated_at)}-#{scope.total_count}" ) end end end end
27.3125
99
0.644546
5ddb3f10c47a15d8bd57fc3d3571ba79862637d3
81,255
###################################################################### # # Parser routine tests. One test for each grammar rule. # ###################################################################### require 'test_helper' class ParserTest < Test::Unit::TestCase def check(s) check_ast(s){|inp| @parser.parse(inp)} end def setup @parser = C::Parser.new end def test_features assert [email protected]_expressions_enabled? @parser.enable_block_expressions assert @parser.block_expressions_enabled? @parser.block_expressions_enabled = false assert [email protected]_expressions_enabled? end def test_comments check <<EOS /* blah "blah" 'blah' */ void f() { 1; /* " */ 2; /* /* * / */ 3; /*/*/ 4; /* multiline comment */ 5; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: IntLiteral val: 1 - ExpressionStatement expr: IntLiteral val: 2 - ExpressionStatement expr: IntLiteral val: 3 - ExpressionStatement expr: IntLiteral val: 4 - ExpressionStatement expr: IntLiteral val: 5 EOS #" end def test_translation_unit check <<EOS int i; ---- TranslationUnit entities: - Declaration type: Int declarators: - Declarator name: "i" EOS check <<EOS int i; int i; ---- TranslationUnit entities: - Declaration type: Int declarators: - Declarator name: "i" - Declaration type: Int declarators: - Declarator name: "i" EOS assert_raise(C::ParseError){C::Parser.new.parse("")} assert_raise(C::ParseError){C::Parser.new.parse(";")} end def test_external_declaration check <<EOS int i; void f() {} ---- TranslationUnit entities: - Declaration type: Int declarators: - Declarator name: "i" - FunctionDef type: Function type: Void name: "f" EOS end def test_function_def check <<EOS int main(int, char **) {} int main(argc, argv) char **argv; int argc; {} ---- TranslationUnit entities: - FunctionDef type: Function type: Int params: - Parameter type: Int - Parameter type: Pointer type: Pointer type: Char name: "main" - FunctionDef (no_prototype) type: Function type: Int params: - Parameter type: Int name: "argc" - Parameter type: Pointer type: Pointer type: Char name: "argv" name: "main" EOS # non-function type assert_raise(C::ParseError){C::Parser.new.parse("int f {}")} # both prototype and declist assert_raise(C::ParseError){C::Parser.new.parse("void f(int argc, int argv) int argc, argv; {}")} assert_raise(C::ParseError){C::Parser.new.parse("void f(int argc, argv) int argv; {}")} # bad param name assert_raise(C::ParseError){C::Parser.new.parse("void f(argc, argv) int argx, argc; {}")} assert_raise(C::ParseError){C::Parser.new.parse("void f(argc, argv) int argx, argc, argv; {}")} # type missing assert_raise(C::ParseError){C::Parser.new.parse("void f(argc, argv) int argc; {}")} # bad storage assert_raise(C::ParseError){C::Parser.new.parse("typedef void f(argc, argv) int argc; {}")} assert_raise(C::ParseError){C::Parser.new.parse("auto void f(argc, argv) int argc; {}")} assert_raise(C::ParseError){C::Parser.new.parse("register void f(argc, argv) int argc; {}")} # duplicate storages assert_raise(C::ParseError){C::Parser.new.parse("static auto int i;")} assert_raise(C::ParseError){C::Parser.new.parse("static extern int i;")} assert_raise(C::ParseError){C::Parser.new.parse("typedef register int i;")} # `inline' can be repeated assert_nothing_raised{C::Parser.new.parse("inline inline int i() {}")} end def test_declaration_list check <<EOS int main(argc, argv) int argc, argv; {} int main(argc, argv) int argc, argv; int; {} int main(argc, argv) int argc; int argv; int; {} int main(argc, argv) int argc, *argv; int; {} ---- TranslationUnit entities: - FunctionDef (no_prototype) type: Function type: Int params: - Parameter type: Int name: "argc" - Parameter type: Int name: "argv" name: "main" - FunctionDef (no_prototype) type: Function type: Int params: - Parameter type: Int name: "argc" - Parameter type: Int name: "argv" name: "main" - FunctionDef (no_prototype) type: Function type: Int params: - Parameter type: Int name: "argc" - Parameter type: Int name: "argv" name: "main" - FunctionDef (no_prototype) type: Function type: Int params: - Parameter type: Int name: "argc" - Parameter type: Pointer type: Int name: "argv" name: "main" EOS end def test_statement check <<EOS void f() { a: ; {} ; if (0); while (0); return; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement labels: - PlainLabel name: "a" - Block - ExpressionStatement - If cond: IntLiteral val: 0 then: ExpressionStatement - While cond: IntLiteral val: 0 stmt: ExpressionStatement - Return EOS end def test_labeled_statement check <<EOS typedef int I; void f() { a: I: case 1: default: ; if (0) b: I: case 2: default: ; switch (0) c: I: case 3: default: { d: I: case 4: default: ; } } ---- TranslationUnit entities: - Declaration storage: typedef type: Int declarators: - Declarator name: "I" - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement labels: - PlainLabel name: "a" - PlainLabel name: "I" - Case expr: IntLiteral val: 1 - Default - If cond: IntLiteral val: 0 then: ExpressionStatement labels: - PlainLabel name: "b" - PlainLabel name: "I" - Case expr: IntLiteral val: 2 - Default - Switch cond: IntLiteral val: 0 stmt: Block labels: - PlainLabel name: "c" - PlainLabel name: "I" - Case expr: IntLiteral val: 3 - Default stmts: - ExpressionStatement labels: - PlainLabel name: "d" - PlainLabel name: "I" - Case expr: IntLiteral val: 4 - Default EOS end def test_compound_statement check <<EOS void f() { { } {;} } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - Block - Block stmts: - ExpressionStatement EOS end def test_block_item_list check <<EOS void f() {; } void f() {;;} ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement - ExpressionStatement EOS end def test_block_item check <<EOS void f() { ;} void f() {int;} ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement - FunctionDef type: Function type: Void name: "f" def: Block stmts: - Declaration type: Int EOS end def test_expression_statement check <<EOS void f() { ; 1; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement - ExpressionStatement expr: IntLiteral val: 1 EOS end def test_selection_statement check <<EOS void f() { if (1) ; if (1) ; else ; if (1) ; else if (2) ; else ; if (1) if (2) ; else ; if (1) if (2) ; else ; else ; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - If cond: IntLiteral val: 1 then: ExpressionStatement - If cond: IntLiteral val: 1 then: ExpressionStatement else: ExpressionStatement - If cond: IntLiteral val: 1 then: ExpressionStatement else: If cond: IntLiteral val: 2 then: ExpressionStatement else: ExpressionStatement - If cond: IntLiteral val: 1 then: If cond: IntLiteral val: 2 then: ExpressionStatement else: ExpressionStatement - If cond: IntLiteral val: 1 then: If cond: IntLiteral val: 2 then: ExpressionStatement else: ExpressionStatement else: ExpressionStatement EOS check <<EOS void f() { switch (1) case 1: x: default: ; switch (1) case 1: y: default: if (0) ; else ; switch (1) { case 1: case 2: ; z: default: ; } } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - Switch cond: IntLiteral val: 1 stmt: ExpressionStatement labels: - Case expr: IntLiteral val: 1 - PlainLabel name: "x" - Default - Switch cond: IntLiteral val: 1 stmt: If labels: - Case expr: IntLiteral val: 1 - PlainLabel name: "y" - Default cond: IntLiteral val: 0 then: ExpressionStatement else: ExpressionStatement - Switch cond: IntLiteral val: 1 stmt: Block stmts: - ExpressionStatement labels: - Case expr: IntLiteral val: 1 - Case expr: IntLiteral val: 2 - ExpressionStatement labels: - PlainLabel name: "z" - Default EOS end def test_iteration_statement check <<EOS void f() { while (0) ; do ; while (0) ; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - While cond: IntLiteral val: 0 stmt: ExpressionStatement - While (do) cond: IntLiteral val: 0 stmt: ExpressionStatement EOS check <<EOS void f() { for (i = 0; i < 10; ++i) ; for (i = 0; i < 10; ) ; for (i = 0; ; ++i) ; for (i = 0; ; ) ; for ( ; i < 10; ++i) ; for ( ; i < 10; ) ; for ( ; ; ++i) ; for ( ; ; ) ; for (int i = 0, j = 1; i < 10, j < 10; ++i, ++j) ; for (int i = 0, j = 1; i < 10, j < 10; ) ; for (int i = 0, j = 1; ; ++i, ++j) ; for (int i = 0, j = 1; ; ) ; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - For init: Assign lval: Variable name: "i" rval: IntLiteral val: 0 cond: Less expr1: Variable name: "i" expr2: IntLiteral val: 10 iter: PreInc expr: Variable name: "i" stmt: ExpressionStatement - For init: Assign lval: Variable name: "i" rval: IntLiteral val: 0 cond: Less expr1: Variable name: "i" expr2: IntLiteral val: 10 stmt: ExpressionStatement - For init: Assign lval: Variable name: "i" rval: IntLiteral val: 0 iter: PreInc expr: Variable name: "i" stmt: ExpressionStatement - For init: Assign lval: Variable name: "i" rval: IntLiteral val: 0 stmt: ExpressionStatement - For cond: Less expr1: Variable name: "i" expr2: IntLiteral val: 10 iter: PreInc expr: Variable name: "i" stmt: ExpressionStatement - For cond: Less expr1: Variable name: "i" expr2: IntLiteral val: 10 stmt: ExpressionStatement - For iter: PreInc expr: Variable name: "i" stmt: ExpressionStatement - For stmt: ExpressionStatement - For init: Declaration type: Int declarators: - Declarator name: "i" init: IntLiteral val: 0 - Declarator name: "j" init: IntLiteral val: 1 cond: Comma exprs: - Less expr1: Variable name: "i" expr2: IntLiteral val: 10 - Less expr1: Variable name: "j" expr2: IntLiteral val: 10 iter: Comma exprs: - PreInc expr: Variable name: "i" - PreInc expr: Variable name: "j" stmt: ExpressionStatement - For init: Declaration type: Int declarators: - Declarator name: "i" init: IntLiteral val: 0 - Declarator name: "j" init: IntLiteral val: 1 cond: Comma exprs: - Less expr1: Variable name: "i" expr2: IntLiteral val: 10 - Less expr1: Variable name: "j" expr2: IntLiteral val: 10 stmt: ExpressionStatement - For init: Declaration type: Int declarators: - Declarator name: "i" init: IntLiteral val: 0 - Declarator name: "j" init: IntLiteral val: 1 iter: Comma exprs: - PreInc expr: Variable name: "i" - PreInc expr: Variable name: "j" stmt: ExpressionStatement - For init: Declaration type: Int declarators: - Declarator name: "i" init: IntLiteral val: 0 - Declarator name: "j" init: IntLiteral val: 1 stmt: ExpressionStatement EOS end def test_jump_statement check <<EOS typedef int I; void f() { goto x; continue; break; return 0; return; goto I; } ---- TranslationUnit entities: - Declaration storage: typedef type: Int declarators: - Declarator name: "I" - FunctionDef type: Function type: Void name: "f" def: Block stmts: - Goto target: "x" - Continue - Break - Return expr: IntLiteral val: 0 - Return - Goto target: "I" EOS end def test_declaration check <<EOS int; int i; int i, j; ---- TranslationUnit entities: - Declaration type: Int - Declaration type: Int declarators: - Declarator name: "i" - Declaration type: Int declarators: - Declarator name: "i" - Declarator name: "j" EOS # duplicate storages assert_raise(C::ParseError){C::Parser.new.parse("static auto int ;")} assert_raise(C::ParseError){C::Parser.new.parse("static extern int i ;")} assert_raise(C::ParseError){C::Parser.new.parse("typedef register int i, j;")} # `inline' can be repeated assert_nothing_raised{C::Parser.new.parse("inline inline int f();")} end def test_declaration_specifiers check <<EOS typedef int X; int typedef Y; const int const i; inline int inline i(); ---- TranslationUnit entities: - Declaration storage: typedef type: Int declarators: - Declarator name: "X" - Declaration storage: typedef type: Int declarators: - Declarator name: "Y" - Declaration type: Int (const) declarators: - Declarator name: "i" - Declaration (inline) type: Int declarators: - Declarator indirect_type: Function name: "i" EOS end def test_init_declarator_list check <<EOS int i; int i, j; ---- TranslationUnit entities: - Declaration type: Int declarators: - Declarator name: "i" - Declaration type: Int declarators: - Declarator name: "i" - Declarator name: "j" EOS end def test_init_declarator check <<EOS int i; int i = 0; ---- TranslationUnit entities: - Declaration type: Int declarators: - Declarator name: "i" - Declaration type: Int declarators: - Declarator name: "i" init: IntLiteral val: 0 EOS end def test_storage_class_specifier check <<EOS typedef int I; extern int i; static int f() { auto int i; register int j; } ---- TranslationUnit entities: - Declaration storage: typedef type: Int declarators: - Declarator name: "I" - Declaration storage: extern type: Int declarators: - Declarator name: "i" - FunctionDef storage: static type: Function type: Int name: "f" def: Block stmts: - Declaration storage: auto type: Int declarators: - Declarator name: "i" - Declaration storage: register type: Int declarators: - Declarator name: "j" EOS end def test_type_specifier check <<EOS void; char; char signed; char unsigned; short; int short; int short; int short signed; short unsigned; int short unsigned; int; signed; int signed; unsigned; int unsigned; long; long signed; int long; int long signed; long unsigned; int long unsigned; long long; long long signed; int long long; int long long signed; long long unsigned; int long long unsigned; float; double; double long; _Bool; _Complex float; _Complex double; _Complex long double; _Imaginary float; _Imaginary double; _Imaginary double long; struct s; enum e; typedef int I; I; ---- TranslationUnit entities: - Declaration type: Void - Declaration type: Char - Declaration type: Char signed: true - Declaration type: Char signed: false - Declaration type: Int longness: -1 - Declaration type: Int longness: -1 - Declaration type: Int longness: -1 - Declaration type: Int longness: -1 - Declaration type: Int (unsigned) longness: -1 - Declaration type: Int (unsigned) longness: -1 - Declaration type: Int - Declaration type: Int - Declaration type: Int - Declaration type: Int (unsigned) - Declaration type: Int (unsigned) - Declaration type: Int longness: 1 - Declaration type: Int longness: 1 - Declaration type: Int longness: 1 - Declaration type: Int longness: 1 - Declaration type: Int (unsigned) longness: 1 - Declaration type: Int (unsigned) longness: 1 - Declaration type: Int longness: 2 - Declaration type: Int longness: 2 - Declaration type: Int longness: 2 - Declaration type: Int longness: 2 - Declaration type: Int (unsigned) longness: 2 - Declaration type: Int (unsigned) longness: 2 - Declaration type: Float - Declaration type: Float longness: 1 - Declaration type: Float longness: 2 - Declaration type: Bool - Declaration type: Complex - Declaration type: Complex longness: 1 - Declaration type: Complex longness: 2 - Declaration type: Imaginary - Declaration type: Imaginary longness: 1 - Declaration type: Imaginary longness: 2 - Declaration type: Struct name: "s" - Declaration type: Enum name: "e" - Declaration storage: typedef type: Int declarators: - Declarator name: "I" - Declaration type: CustomType name: "I" EOS # some illegal combos assert_raise(C::ParseError){C::Parser.new.parse("int float;")} assert_raise(C::ParseError){C::Parser.new.parse("struct s {} int;")} assert_raise(C::ParseError){C::Parser.new.parse("_Complex;")} assert_raise(C::ParseError){C::Parser.new.parse("_Complex _Imaginary float;")} assert_raise(C::ParseError){C::Parser.new.parse("short long;")} assert_raise(C::ParseError){C::Parser.new.parse("signed unsigned char;")} assert_raise(C::ParseError){C::Parser.new.parse("int int;")} assert_raise(C::ParseError){C::Parser.new.parse("long char;")} assert_raise(C::ParseError){C::Parser.new.parse("long long long;")} end def test_struct_or_union_specifier check <<EOS struct s { int i; } ; struct { int i; } ; struct s ; typedef int I ; struct I { int i; } ; struct I ; ---- TranslationUnit entities: - Declaration type: Struct name: "s" members: - Declaration type: Int declarators: - Declarator name: "i" - Declaration type: Struct members: - Declaration type: Int declarators: - Declarator name: "i" - Declaration type: Struct name: "s" - Declaration storage: typedef type: Int declarators: - Declarator name: "I" - Declaration type: Struct name: "I" members: - Declaration type: Int declarators: - Declarator name: "i" - Declaration type: Struct name: "I" EOS end def test_struct_or_union check <<EOS struct s; union u; ---- TranslationUnit entities: - Declaration type: Struct name: "s" - Declaration type: Union name: "u" EOS end def test_struct_declaration_list check <<EOS struct { int i; } ; struct { int i; int j; } ; ---- TranslationUnit entities: - Declaration type: Struct members: - Declaration type: Int declarators: - Declarator name: "i" - Declaration type: Struct members: - Declaration type: Int declarators: - Declarator name: "i" - Declaration type: Int declarators: - Declarator name: "j" EOS end def test_struct_declaration check <<EOS struct { int i; }; ---- TranslationUnit entities: - Declaration type: Struct members: - Declaration type: Int declarators: - Declarator name: "i" EOS end def test_specifier_qualifier_list check <<EOS void f() { sizeof(int const); sizeof(const int); } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Sizeof expr: Int (const) - ExpressionStatement expr: Sizeof expr: Int (const) EOS # quals can be repeated assert_nothing_raised{C::Parser.new.parse("void f() {sizeof(const const int);}")} end def test_struct_declarator_list check <<EOS struct { int i; }; struct { int i, j; }; ---- TranslationUnit entities: - Declaration type: Struct members: - Declaration type: Int declarators: - Declarator name: "i" - Declaration type: Struct members: - Declaration type: Int declarators: - Declarator name: "i" - Declarator name: "j" EOS end def test_struct_declarator check <<EOS struct { int i; }; struct { int i : 1; }; struct { int : 2; }; ---- TranslationUnit entities: - Declaration type: Struct members: - Declaration type: Int declarators: - Declarator name: "i" - Declaration type: Struct members: - Declaration type: Int declarators: - Declarator name: "i" num_bits: IntLiteral val: 1 - Declaration type: Struct members: - Declaration type: Int declarators: - Declarator num_bits: IntLiteral val: 2 EOS end def test_enum_specifier check <<EOS enum e { i }; enum { i }; enum e { i, }; enum { i, }; enum e ; typedef int E; enum E { i }; enum E { i, }; enum E ; ---- TranslationUnit entities: - Declaration type: Enum name: "e" members: - Enumerator name: "i" - Declaration type: Enum members: - Enumerator name: "i" - Declaration type: Enum name: "e" members: - Enumerator name: "i" - Declaration type: Enum members: - Enumerator name: "i" - Declaration type: Enum name: "e" - Declaration storage: typedef type: Int declarators: - Declarator name: "E" - Declaration type: Enum name: "E" members: - Enumerator name: "i" - Declaration type: Enum name: "E" members: - Enumerator name: "i" - Declaration type: Enum name: "E" EOS end def test_enumerator_list check <<EOS enum e { i }; enum e { i, j }; ---- TranslationUnit entities: - Declaration type: Enum name: "e" members: - Enumerator name: "i" - Declaration type: Enum name: "e" members: - Enumerator name: "i" - Enumerator name: "j" EOS end def test_enumerator check <<EOS enum e { i }; enum e { i=0 }; ---- TranslationUnit entities: - Declaration type: Enum name: "e" members: - Enumerator name: "i" - Declaration type: Enum name: "e" members: - Enumerator name: "i" val: IntLiteral val: 0 EOS end def test_type_qualifier check <<EOS const int; restrict int; volatile int; ---- TranslationUnit entities: - Declaration type: Int (const) - Declaration type: Int (restrict) - Declaration type: Int (volatile) EOS end def test_function_specifier check <<EOS inline int f(); ---- TranslationUnit entities: - Declaration (inline) type: Int declarators: - Declarator indirect_type: Function name: "f" EOS end def test_declarator check <<EOS int *p; int *const restrict volatile p; int i, *volatile restrict const *p[]; int *i, *const (*restrict (*volatile p)[])(); ---- TranslationUnit entities: - Declaration type: Int declarators: - Declarator indirect_type: Pointer name: "p" - Declaration type: Int declarators: - Declarator indirect_type: Pointer (const restrict volatile) name: "p" - Declaration type: Int declarators: - Declarator name: "i" - Declarator indirect_type: Array type: Pointer type: Pointer (const restrict volatile) name: "p" - Declaration type: Int declarators: - Declarator indirect_type: Pointer name: "i" - Declarator indirect_type: Pointer (volatile) type: Array type: Pointer (restrict) type: Function type: Pointer (const) name: "p" EOS end def test_direct_declarator # TODO end def test_pointer check <<EOS int *const p; int * p; int *const *p; int * *p; ---- TranslationUnit entities: - Declaration type: Int declarators: - Declarator indirect_type: Pointer (const) name: "p" - Declaration type: Int declarators: - Declarator indirect_type: Pointer name: "p" - Declaration type: Int declarators: - Declarator indirect_type: Pointer type: Pointer (const) name: "p" - Declaration type: Int declarators: - Declarator indirect_type: Pointer type: Pointer name: "p" EOS end def test_type_qualifier_list check <<EOS int *const p; int *const restrict p; ---- TranslationUnit entities: - Declaration type: Int declarators: - Declarator indirect_type: Pointer (const) name: "p" - Declaration type: Int declarators: - Declarator indirect_type: Pointer (const restrict) name: "p" EOS end def test_parameter_type_list check <<EOS void f(int i) {} void f(int i, ...) {} ---- TranslationUnit entities: - FunctionDef type: Function type: Void params: - Parameter type: Int name: "i" name: "f" - FunctionDef type: Function (var_args) type: Void params: - Parameter type: Int name: "i" name: "f" EOS end def test_parameter_list check <<EOS void f(int i) {} void f(int i, int j) {} ---- TranslationUnit entities: - FunctionDef type: Function type: Void params: - Parameter type: Int name: "i" name: "f" - FunctionDef type: Function type: Void params: - Parameter type: Int name: "i" - Parameter type: Int name: "j" name: "f" EOS end def test_parameter_declaration check <<EOS void f(int i); void f(int *); void f(int ); ---- TranslationUnit entities: - Declaration type: Void declarators: - Declarator indirect_type: Function params: - Parameter type: Int name: "i" name: "f" - Declaration type: Void declarators: - Declarator indirect_type: Function params: - Parameter type: Pointer type: Int name: "f" - Declaration type: Void declarators: - Declarator indirect_type: Function params: - Parameter type: Int name: "f" EOS end def test_identifier_list check <<EOS void f(i); void f(i, j); ---- TranslationUnit entities: - Declaration type: Void declarators: - Declarator indirect_type: Function params: - Parameter name: "i" name: "f" - Declaration type: Void declarators: - Declarator indirect_type: Function params: - Parameter name: "i" - Parameter name: "j" name: "f" EOS end def test_type_name check <<EOS void f() { sizeof(int *); sizeof(int ); } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Sizeof expr: Pointer type: Int - ExpressionStatement expr: Sizeof expr: Int EOS end def test_abstract_declarator check <<EOS void f(int * ); void f(int *[]); void f(int []); ---- TranslationUnit entities: - Declaration type: Void declarators: - Declarator indirect_type: Function params: - Parameter type: Pointer type: Int name: "f" - Declaration type: Void declarators: - Declarator indirect_type: Function params: - Parameter type: Array type: Pointer type: Int name: "f" - Declaration type: Void declarators: - Declarator indirect_type: Function params: - Parameter type: Array type: Int name: "f" EOS end def test_direct_abstract_declarator # TODO end def test_typedef_name check <<EOS typedef int I; I; ---- TranslationUnit entities: - Declaration storage: typedef type: Int declarators: - Declarator name: "I" - Declaration type: CustomType name: "I" EOS end def test_initializer check <<EOS int x = 1 ; int x = {1 }; int x = {1,}; ---- TranslationUnit entities: - Declaration type: Int declarators: - Declarator name: "x" init: IntLiteral val: 1 - Declaration type: Int declarators: - Declarator name: "x" init: CompoundLiteral member_inits: - MemberInit init: IntLiteral val: 1 - Declaration type: Int declarators: - Declarator name: "x" init: CompoundLiteral member_inits: - MemberInit init: IntLiteral val: 1 EOS end def test_initializer_list check <<EOS int x = {.x = 1}; int x = { 1}; int x = {1, .x = 1}; int x = {1, 1}; ---- TranslationUnit entities: - Declaration type: Int declarators: - Declarator name: "x" init: CompoundLiteral member_inits: - MemberInit member: - Member name: "x" init: IntLiteral val: 1 - Declaration type: Int declarators: - Declarator name: "x" init: CompoundLiteral member_inits: - MemberInit init: IntLiteral val: 1 - Declaration type: Int declarators: - Declarator name: "x" init: CompoundLiteral member_inits: - MemberInit init: IntLiteral val: 1 - MemberInit member: - Member name: "x" init: IntLiteral val: 1 - Declaration type: Int declarators: - Declarator name: "x" init: CompoundLiteral member_inits: - MemberInit init: IntLiteral val: 1 - MemberInit init: IntLiteral val: 1 EOS end def test_designation check <<EOS int x = {.x = 1}; ---- TranslationUnit entities: - Declaration type: Int declarators: - Declarator name: "x" init: CompoundLiteral member_inits: - MemberInit member: - Member name: "x" init: IntLiteral val: 1 EOS end def test_designator_list check <<EOS int x = {.x = 1}; int x = {.x .y = 1}; ---- TranslationUnit entities: - Declaration type: Int declarators: - Declarator name: "x" init: CompoundLiteral member_inits: - MemberInit member: - Member name: "x" init: IntLiteral val: 1 - Declaration type: Int declarators: - Declarator name: "x" init: CompoundLiteral member_inits: - MemberInit member: - Member name: "x" - Member name: "y" init: IntLiteral val: 1 EOS end def test_designator check <<EOS int x = {.x = 1}; int x = {[0] = 1}; ---- TranslationUnit entities: - Declaration type: Int declarators: - Declarator name: "x" init: CompoundLiteral member_inits: - MemberInit member: - Member name: "x" init: IntLiteral val: 1 - Declaration type: Int declarators: - Declarator name: "x" init: CompoundLiteral member_inits: - MemberInit member: - IntLiteral val: 0 init: IntLiteral val: 1 EOS end def test_primary_expression check <<EOS void f() { x; 1; ""; (1); } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: IntLiteral val: 1 - ExpressionStatement expr: StringLiteral val: "" - ExpressionStatement expr: IntLiteral val: 1 EOS end def test_primary_expression_block_expression src = <<EOS void f() { ({;}); } EOS assert_raise(C::ParseError){@parser.parse(src)} @parser.enable_block_expressions check <<EOS #{src} ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: BlockExpression block: Block stmts: - ExpressionStatement EOS end def test_postfix_expression check <<EOS void f() { x; x[1]; x(1); x(); x.a; x->a; x++; x--; (int){1}; (int){1,}; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: Index expr: Variable name: "x" index: IntLiteral val: 1 - ExpressionStatement expr: Call expr: Variable name: "x" args: - IntLiteral val: 1 - ExpressionStatement expr: Call expr: Variable name: "x" - ExpressionStatement expr: Dot expr: Variable name: "x" member: Member name: "a" - ExpressionStatement expr: Arrow expr: Variable name: "x" member: Member name: "a" - ExpressionStatement expr: PostInc expr: Variable name: "x" - ExpressionStatement expr: PostDec expr: Variable name: "x" - ExpressionStatement expr: CompoundLiteral type: Int member_inits: - MemberInit init: IntLiteral val: 1 - ExpressionStatement expr: CompoundLiteral type: Int member_inits: - MemberInit init: IntLiteral val: 1 EOS end def test_argument_expression_list check <<EOS void f() { x(1); x(int); x(1, int); } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Call expr: Variable name: "x" args: - IntLiteral val: 1 - ExpressionStatement expr: Call expr: Variable name: "x" args: - Int - ExpressionStatement expr: Call expr: Variable name: "x" args: - IntLiteral val: 1 - Int EOS end def test_argument_expression check <<EOS void f() { x(a = 1); x(int*); x(const struct s[]); } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Call expr: Variable name: "x" args: - Assign lval: Variable name: "a" rval: IntLiteral val: 1 - ExpressionStatement expr: Call expr: Variable name: "x" args: - Pointer type: Int - ExpressionStatement expr: Call expr: Variable name: "x" args: - Array type: Struct (const) name: "s" EOS end def test_unary_expression check <<EOS void f() { x; ++x; --x; &x; sizeof x; sizeof(int); } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: PreInc expr: Variable name: "x" - ExpressionStatement expr: PreDec expr: Variable name: "x" - ExpressionStatement expr: Address expr: Variable name: "x" - ExpressionStatement expr: Sizeof expr: Variable name: "x" - ExpressionStatement expr: Sizeof expr: Int EOS end def test_unary_operator check <<EOS void f() { &x; *x; +x; -x; ~x; !x; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Address expr: Variable name: "x" - ExpressionStatement expr: Dereference expr: Variable name: "x" - ExpressionStatement expr: Positive expr: Variable name: "x" - ExpressionStatement expr: Negative expr: Variable name: "x" - ExpressionStatement expr: BitNot expr: Variable name: "x" - ExpressionStatement expr: Not expr: Variable name: "x" EOS end def test_cast_expression check <<EOS void f() { x; (int)x; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: Cast type: Int expr: Variable name: "x" EOS end def test_multiplicative_expression check <<EOS void f() { x; x * x; x / x; x % x; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: Multiply expr1: Variable name: "x" expr2: Variable name: "x" - ExpressionStatement expr: Divide expr1: Variable name: "x" expr2: Variable name: "x" - ExpressionStatement expr: Mod expr1: Variable name: "x" expr2: Variable name: "x" EOS end def test_additive_expression check <<EOS void f() { x; x + x; x - x; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: Add expr1: Variable name: "x" expr2: Variable name: "x" - ExpressionStatement expr: Subtract expr1: Variable name: "x" expr2: Variable name: "x" EOS end def test_shift_expression check <<EOS void f() { x; x << x; x >> x; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: ShiftLeft expr1: Variable name: "x" expr2: Variable name: "x" - ExpressionStatement expr: ShiftRight expr1: Variable name: "x" expr2: Variable name: "x" EOS end def test_relational_expression check <<EOS void f() { x; x < x; x > x; x <= x; x >= x; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: Less expr1: Variable name: "x" expr2: Variable name: "x" - ExpressionStatement expr: More expr1: Variable name: "x" expr2: Variable name: "x" - ExpressionStatement expr: LessOrEqual expr1: Variable name: "x" expr2: Variable name: "x" - ExpressionStatement expr: MoreOrEqual expr1: Variable name: "x" expr2: Variable name: "x" EOS end def test_equality_expression check <<EOS void f() { x; x == x; x != x; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: Equal expr1: Variable name: "x" expr2: Variable name: "x" - ExpressionStatement expr: NotEqual expr1: Variable name: "x" expr2: Variable name: "x" EOS end def test_and_expression check <<EOS void f() { x; x & x; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: BitAnd expr1: Variable name: "x" expr2: Variable name: "x" EOS end def test_exclusive_or_expression check <<EOS void f() { x; x ^ x; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: BitXor expr1: Variable name: "x" expr2: Variable name: "x" EOS end def test_inclusive_or_expression check <<EOS void f() { x; x | x; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: BitOr expr1: Variable name: "x" expr2: Variable name: "x" EOS end def test_logical_and_expression check <<EOS void f() { x; x && x; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: And expr1: Variable name: "x" expr2: Variable name: "x" EOS end def test_logical_or_expression check <<EOS void f() { x; x || x; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: Or expr1: Variable name: "x" expr2: Variable name: "x" EOS end def test_conditional_expression check <<EOS void f() { x; x ? x : x; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: Conditional cond: Variable name: "x" then: Variable name: "x" else: Variable name: "x" EOS end def test_assignment_expression check <<EOS void f() { x; x = x; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "x" - ExpressionStatement expr: Assign lval: Variable name: "x" rval: Variable name: "x" EOS end def test_assignment_operator check <<EOS void f() { x = x; x *= x; x /= x; x %= x; x += x; x -= x; x <<= x; x >>= x; x &= x; x ^= x; x |= x; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Assign lval: Variable name: "x" rval: Variable name: "x" - ExpressionStatement expr: MultiplyAssign lval: Variable name: "x" rval: Variable name: "x" - ExpressionStatement expr: DivideAssign lval: Variable name: "x" rval: Variable name: "x" - ExpressionStatement expr: ModAssign lval: Variable name: "x" rval: Variable name: "x" - ExpressionStatement expr: AddAssign lval: Variable name: "x" rval: Variable name: "x" - ExpressionStatement expr: SubtractAssign lval: Variable name: "x" rval: Variable name: "x" - ExpressionStatement expr: ShiftLeftAssign lval: Variable name: "x" rval: Variable name: "x" - ExpressionStatement expr: ShiftRightAssign lval: Variable name: "x" rval: Variable name: "x" - ExpressionStatement expr: BitAndAssign lval: Variable name: "x" rval: Variable name: "x" - ExpressionStatement expr: BitXorAssign lval: Variable name: "x" rval: Variable name: "x" - ExpressionStatement expr: BitOrAssign lval: Variable name: "x" rval: Variable name: "x" EOS end def test_expression check <<EOS void f() { a; a, b; a, b, c; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "a" - ExpressionStatement expr: Comma exprs: - Variable name: "a" - Variable name: "b" - ExpressionStatement expr: Comma exprs: - Variable name: "a" - Variable name: "b" - Variable name: "c" EOS end def test_constant_expression check <<EOS void f() { 1; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: IntLiteral val: 1 EOS end def test_identifier check <<EOS void f() { _abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" EOS end def test_constant check <<EOS void f() { 1; 1.0; 'a'; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: IntLiteral val: 1 - ExpressionStatement expr: FloatLiteral val: 1.0 - ExpressionStatement expr: CharLiteral val: "a" EOS end def test_enumeration_constant check <<EOS void f() { a; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: Variable name: "a" EOS end def test_string_literal check <<EOS void f() { ""; } ---- TranslationUnit entities: - FunctionDef type: Function type: Void name: "f" def: Block stmts: - ExpressionStatement expr: StringLiteral val: "" EOS end end
26.968138
101
0.342539
f89a76fd14fbb6c579985ce81a161e3cf0e7e8ba
6,011
require 'spec_helper_integration' describe 'Revoke Token Flow' do before do Doorkeeper.configure { orm DOORKEEPER_ORM } end context 'with default parameters' do let(:client_application) { FactoryGirl.create :application } let(:resource_owner) { User.create!(name: 'John', password: 'sekret') } let(:authorization_access_token) do FactoryGirl.create(:access_token, application: client_application, resource_owner_id: resource_owner.id, use_refresh_token: true) end let(:headers) { { 'HTTP_AUTHORIZATION' => "Bearer #{authorization_access_token.token}" } } context 'With invalid token to revoke' do it 'client wants to revoke the given access token' do post revocation_token_endpoint_url, { token: 'I_AM_AN_INVALIDE_TOKEN' }, headers authorization_access_token.reload # The authorization server responds with HTTP status code 200 if the token # has been revoked successfully or if the client submitted an invalid token. expect(response).to be_success expect(authorization_access_token).to_not be_revoked end end context 'The access token to revoke is the same than the authorization access token' do let(:token_to_revoke) { authorization_access_token } it 'client wants to revoke the given access token' do post revocation_token_endpoint_url, { token: token_to_revoke.token }, headers token_to_revoke.reload authorization_access_token.reload expect(response).to be_success expect(token_to_revoke.revoked?).to be_truthy expect(Doorkeeper::AccessToken.by_refresh_token(token_to_revoke.refresh_token).revoked?).to be_truthy end it 'client wants to revoke the given access token using the POST query string' do url_with_query_string = revocation_token_endpoint_url + '?' + Rack::Utils.build_query(token: token_to_revoke.token) post url_with_query_string, {}, headers token_to_revoke.reload authorization_access_token.reload expect(response).to be_success expect(token_to_revoke.revoked?).to be_falsey expect(Doorkeeper::AccessToken.by_refresh_token(token_to_revoke.refresh_token).revoked?).to be_falsey expect(authorization_access_token.revoked?).to be_falsey end end context 'The access token to revoke app and owners are the same than the authorization access token' do let(:token_to_revoke) do FactoryGirl.create(:access_token, application: client_application, resource_owner_id: resource_owner.id, use_refresh_token: true) end it 'client wants to revoke the given access token' do post revocation_token_endpoint_url, { token: token_to_revoke.token }, headers token_to_revoke.reload authorization_access_token.reload expect(response).to be_success expect(token_to_revoke.revoked?).to be_truthy expect(Doorkeeper::AccessToken.by_refresh_token(token_to_revoke.refresh_token).revoked?).to be_truthy expect(authorization_access_token.revoked?).to be_falsey end end context 'The access token to revoke authorization owner is the same than the authorization access token' do let(:other_client_application) { FactoryGirl.create :application } let(:token_to_revoke) do FactoryGirl.create(:access_token, application: other_client_application, resource_owner_id: resource_owner.id, use_refresh_token: true) end it 'client wants to revoke the given access token' do post revocation_token_endpoint_url, { token: token_to_revoke.token }, headers token_to_revoke.reload authorization_access_token.reload expect(response).to be_success expect(token_to_revoke.revoked?).to be_falsey expect(Doorkeeper::AccessToken.by_refresh_token(token_to_revoke.refresh_token).revoked?).to be_falsey expect(authorization_access_token.revoked?).to be_falsey end end context 'The access token to revoke app is the same than the authorization access token' do let(:other_resource_owner) { User.create!(name: 'Matheo', password: 'pareto') } let(:token_to_revoke) do FactoryGirl.create(:access_token, application: client_application, resource_owner_id: other_resource_owner.id, use_refresh_token: true) end it 'client wants to revoke the given access token' do post revocation_token_endpoint_url, { token: token_to_revoke.token }, headers token_to_revoke.reload authorization_access_token.reload expect(response).to be_success expect(token_to_revoke.revoked?).to be_falsey expect(Doorkeeper::AccessToken.by_refresh_token(token_to_revoke.refresh_token).revoked?).to be_falsey expect(authorization_access_token.revoked?).to be_falsey end end context 'With valid refresh token to revoke' do let(:token_to_revoke) do FactoryGirl.create(:access_token, application: client_application, resource_owner_id: resource_owner.id, use_refresh_token: true) end it 'client wants to revoke the given refresh token' do post revocation_token_endpoint_url, { token: token_to_revoke.refresh_token, token_type_hint: 'refresh_token' }, headers authorization_access_token.reload token_to_revoke.reload expect(response).to be_success expect(Doorkeeper::AccessToken.by_refresh_token(token_to_revoke.refresh_token).revoked?).to be_truthy expect(authorization_access_token).to_not be_revoked end end end end
41.743056
127
0.688072
91dcb0c189dcfa2bf5c7f9a81e3618ea24fd3946
301
class CreateBloodSpotRequests < ActiveRecord::Migration def change create_table :blood_spot_requests do |t| t.integer :study_subject_id t.date :sent_on t.date :returned_on t.boolean :is_found t.string :status t.text :notes t.string :request_type t.timestamps end end end
20.066667
55
0.737542
ffaddae6ae62abedc22642aaf1e2d606bf256fcd
1,952
require 'jar_installer' module JBundler class Vendor def initialize( dir ) @dir = File.expand_path( dir ) @jars_lock = File.join( @dir, 'Jars.lock' ) end def vendored? File.exists?( @dir ) && Dir[ File.join( @dir, '*' ) ].size > 0 end def require_jars if File.exists?(@jars_lock) $LOAD_PATH << @dir unless $LOAD_PATH.include? @dir ENV_JAVA['jars.lock'] = @jars_lock Jars.require_jars_lock! true else require_jars_legacy end end def require_jars_legacy jars = File.join( @dir, 'jbundler.rb' ) if File.exists?( jars ) $LOAD_PATH << @dir unless $LOAD_PATH.include? @dir require jars else Dir[ File.join( @dir, '**', '*' ) ].each do |f| require f end Jars.no_more_warnings true end end def clear FileUtils.mkdir_p( @dir ) Dir[ File.join( @dir, '*' ) ].each do |f| FileUtils.rm_rf( f ) end end def vendor_dependencies( deps ) FileUtils.mkdir_p( @dir ) File.open(@jars_lock, 'w') do |f| deps.each do |dep| if dep.scope == :runtime target = File.join( @dir, dep.path ) FileUtils.mkdir_p( File.dirname( target ) ) FileUtils.cp( dep.file, target ) line = dep.gav + ':runtime:' f.puts line end end end ['jbundler.rb', 'jbundle.rb'].each do |filename| File.write( File.join( @dir, filename ), "ENV['JARS_LOCK'] = File.join( File.dirname( __FILE__ ), 'Jars.lock' )\nrequire 'jars/setup'" ) end end def setup( classpath_file ) classpath_file.require_classpath FileUtils.mkdir_p( @dir ) JBUNDLER_CLASSPATH.each do |f| FileUtils.cp( f, File.join( @dir, File.basename( f ) ) ) end end end end
25.684211
115
0.535348
f8a673e4387f8610710519ab9a6f4690a4c9bbfc
336
require_relative 'base_icann_compliant' module Whois class Parsers class WhoisNicCapital < BaseIcannCompliant self.scanner = Scanners::BaseIcannCompliant, { pattern_available: /^Domain not found/ # pattern_disclaimer: /^Access to/, # pattern_throttled: /^WHOIS LIMIT EXCEEDED/, } end end end
25.846154
52
0.699405
f77c0553b29786be07f157a32b15ef50385dc8ee
268
require 'test_helper' class FeedControllerTest < ActionDispatch::IntegrationTest test "should get common" do get feed_common_url assert_response :success end test "should get private" do get feed_private_url assert_response :success end end
17.866667
58
0.757463
e84498d457675004e59d1441d7a49ee51b71e066
1,107
class PurchaseItem < ActiveRecord::Base # t.integer :organization_id # t.integer :purchase_id # t.integer :item_id # t.integer :batch_id # t.integer :quantity # t.integer :price # t.integer :amount # t.integer :vat belongs_to :organization belongs_to :purchase belongs_to :item belongs_to :batch attr_accessible :batch_id, :item_id, :quantity, :price, :total_amount accepts_nested_attributes_for :item, :batch validates :item_id, presence: true validates :batch, presence: true, if: :item_stocked? validates :quantity, presence: true validates :price, presence: true # Callbacks after_validation :collect_and_calculate def item_stocked? item.stocked end def can_delete? purchase.can_edit_items? end def vat_amount price * quantity * vat / 100 end def amount_exkl_vat price * quantity end private # Callback: after_validation def collect_and_calculate self.vat = vat || item.vat.vat_percent if quantity && price self.amount = quantity * price + vat_amount else self.amount = 0 end end end
19.767857
71
0.706414
28c56afb942b71194b403797b0fdcc3f523fd44b
8,509
# frozen_string_literal: true module RuboCop module Cop module Layout # This cop checks for the placement of the closing parenthesis # in a method call that passes a HEREDOC string as an argument. # It should be placed at the end of the line containing the # opening HEREDOC tag. # # @example # # bad # # foo(<<-SQL # bar # SQL # ) # # foo(<<-SQL, 123, <<-NOSQL, # bar # SQL # baz # NOSQL # ) # # foo( # bar(<<-SQL # baz # SQL # ), # 123, # ) # # # good # # foo(<<-SQL) # bar # SQL # # foo(<<-SQL, 123, <<-NOSQL) # bar # SQL # baz # NOSQL # # foo( # bar(<<-SQL), # baz # SQL # 123, # ) # class HeredocArgumentClosingParenthesis < Cop include RangeHelp MSG = 'Put the closing parenthesis for a method call with a ' \ 'HEREDOC parameter on the same line as the HEREDOC opening.' def on_send(node) heredoc_arg = extract_heredoc_argument(node) return unless heredoc_arg outermost_send = outermost_send_on_same_line(heredoc_arg) return unless outermost_send return unless outermost_send.loc.end return unless heredoc_arg.first_line != outermost_send.loc.end.line add_offense(outermost_send, location: :end) end # Autocorrection note: # # Commas are a bit tricky to handle when the method call is # embedded in another expression. Here's an example: # # [ # first_array_value, # foo(<<-SQL, 123, 456, # SELECT * FROM db # SQL # ), # third_array_value, # ] # # The "internal" trailing comma is after `456`. # The "external" trailing comma is after `)`. # # To autocorrect, we remove the latter, and move the former up: # # [ # first_array_value, # foo(<<-SQL, 123, 456), # SELECT * FROM db # SQL # third_array_value, # ] def autocorrect(node) lambda do |corrector| fix_closing_parenthesis(node, corrector) remove_internal_trailing_comma(node, corrector) if internal_trailing_comma?(node) fix_external_trailing_comma(node, corrector) if external_trailing_comma?(node) end end def self.autocorrect_incompatible_with [Style::TrailingCommaInArguments] end private def outermost_send_on_same_line(heredoc) previous = heredoc current = previous.parent until send_missing_closing_parens?(current, previous, heredoc) previous = current current = current.parent return unless previous && current end current end def send_missing_closing_parens?(parent, child, heredoc) parent&.call_type? && parent.arguments.include?(child) && parent.loc.begin && parent.loc.end.line != heredoc.last_line end def extract_heredoc_argument(node) node.arguments.find do |arg_node| extract_heredoc(arg_node) end end def extract_heredoc(node) return node if heredoc_node?(node) return node.receiver if single_line_send_with_heredoc_receiver?(node) return unless node.hash_type? node.values.find do |v| heredoc = extract_heredoc(v) return heredoc if heredoc end end def heredoc_node?(node) node.respond_to?(:heredoc?) && node.heredoc? end def single_line_send_with_heredoc_receiver?(node) return false unless node.send_type? return false unless heredoc_node?(node.receiver) node.receiver.location.heredoc_end.end_pos > node.source_range.end_pos end # Closing parenthesis helpers. def fix_closing_parenthesis(node, corrector) remove_incorrect_closing_paren(node, corrector) add_correct_closing_paren(node, corrector) end def add_correct_closing_paren(node, corrector) corrector.insert_after(node.arguments.last, ')') end def remove_incorrect_closing_paren(node, corrector) corrector.remove( range_between( incorrect_parenthesis_removal_begin(node), incorrect_parenthesis_removal_end(node) ) ) end def incorrect_parenthesis_removal_begin(node) end_pos = node.source_range.end_pos if safe_to_remove_line_containing_closing_paren?(node) last_line_length = node.source.scan(/\n(.*)$/).last[0].size end_pos - last_line_length - 1 # Add one for the line break itself. else end_pos - 1 # Just the `)` at the end of the string end end def safe_to_remove_line_containing_closing_paren?(node) last_line = processed_source[node.loc.end.line - 1] # Safe to remove if last line only contains `)`, `,`, and whitespace. last_line.match?(/^ *\) {0,20},{0,1} *$/) end def incorrect_parenthesis_removal_end(node) end_pos = node.source_range.end_pos if processed_source.buffer.source[end_pos] == ',' end_pos + 1 else end_pos end end # Internal trailing comma helpers. def remove_internal_trailing_comma(node, corrector) offset = internal_trailing_comma_offset_from_last_arg(node) last_arg_end_pos = node.children.last.source_range.end_pos corrector.remove( range_between( last_arg_end_pos, last_arg_end_pos + offset ) ) end def internal_trailing_comma?(node) !internal_trailing_comma_offset_from_last_arg(node).nil? end # Returns nil if no trailing internal comma. def internal_trailing_comma_offset_from_last_arg(node) source_after_last_arg = range_between( node.children.last.source_range.end_pos, node.loc.end.begin_pos ).source first_comma_offset = source_after_last_arg.index(',') first_new_line_offset = source_after_last_arg.index("\n") return if first_comma_offset.nil? return if first_new_line_offset.nil? return if first_comma_offset > first_new_line_offset first_comma_offset + 1 end # External trailing comma helpers. def fix_external_trailing_comma(node, corrector) remove_incorrect_external_trailing_comma(node, corrector) add_correct_external_trailing_comma(node, corrector) end def add_correct_external_trailing_comma(node, corrector) return unless external_trailing_comma?(node) corrector.insert_after(node.arguments.last, ',') end def remove_incorrect_external_trailing_comma(node, corrector) end_pos = node.source_range.end_pos return unless external_trailing_comma?(node) corrector.remove( range_between( end_pos, end_pos + external_trailing_comma_offset_from_loc_end(node) ) ) end def external_trailing_comma?(node) !external_trailing_comma_offset_from_loc_end(node).nil? end # Returns nil if no trailing external comma. def external_trailing_comma_offset_from_loc_end(node) end_pos = node.source_range.end_pos offset = 0 limit = 20 offset += 1 while offset < limit && space?(end_pos + offset) char = processed_source.buffer.source[end_pos + offset] return unless char == ',' offset + 1 # Add one to include the comma. end def space?(pos) processed_source.buffer.source[pos] == ' ' end end end end end
29.751748
93
0.573275
bf2753ac317dd43fc90f70e1c1dd96e35345db34
67
s = gets.to_s if s == "ABC" puts "ACR" else puts "ABC" end
9.571429
14
0.537313
bb0471fc355eaa2e57831ad0dd69b62de070a396
87
class Idea < ApplicationRecord validates :description, :author, presence: true end
21.75
51
0.770115
e86ad079097814c44b770c8489cb0d172d2a46e2
4,081
# encoding: utf-8 require 'spec_helper' describe BlabbrApi::Api, type: :requests do let!(:current_user) { BlabbrCore::Persistence::User.create(nickname: 'nickname', email: '[email protected]') } let(:admin) { BlabbrCore::Persistence::User.create(nickname: 'nickname', email: '[email protected]', roles: [:admin]) } let(:member) { BlabbrCore::Persistence::User.new(nickname: 'member', email: '[email protected]') } let(:topic) { BlabbrCore::Persistence::Topic.create(author: current_user, title: "Title please !") } let(:topic_by_member) { BlabbrCore::Persistence::Topic.create(author: member, title: "Title please !") } describe "GET /v1/users" do it 'returns a list of users' do get "/v1/users", {}, {'current_user' => current_user} last_response.status.should == 200 JSON.parse(last_response.body).first['nickname'].should == current_user.nickname end end describe 'GET /v1/users/:user' do it 'finds a user' do get "/v1/users/#{current_user.nickname}", {}, {'current_user' => current_user} last_response.status.should eq 200 JSON.parse(last_response.body)['nickname'].should eq current_user.nickname end end describe 'GET /me' do it 'finds current_user' do get "/v1/me", {}, {'current_user' => current_user} last_response.status.should eq 200 JSON.parse(last_response.body)['nickname'].should eq current_user.nickname end end describe 'PUT /me' do context 'with valid params' do it 'updates current_user' do put "/v1/me", {user: {nickname: 'New test'}}, {'current_user' => current_user} last_response.status.should eq 200 JSON.parse(last_response.body)['nickname'].should eq 'New test' end end context 'with invalid params' do it 'updates current_user' do put "/v1/me", {user: {nickname: 'a'}}, {'current_user' => current_user} last_response.status.should eq 412 JSON.parse(last_response.body).keys.should include 'nickname' end end end describe 'POST /v1/users' do context 'with valid params' do it 'return a user' do post "/v1/users", {user: {nickname: 'A new user', email: '[email protected]'}}, {'current_user' => admin} last_response.status.should eq 201 JSON.parse(last_response.body)['nickname'].should eq 'A new user' end end context 'with invalid params' do it 'return a hash of errors' do post "/v1/users", {user: {nickname: 'a'}}, {'current_user' => admin} last_response.status.should eq 412 JSON.parse(last_response.body).keys.should include 'nickname' end end end describe "GET /v1/topics" do context 'without topics' do it "returns an empty array of topics" do get "/v1/topics", {}, {'current_user' => current_user} last_response.status.should == 200 JSON.parse(last_response.body).should == [] end end context 'with topics' do before do topic get "/v1/topics", {}, {'current_user' => current_user} end it "should have a topic in list" do last_response.status.should == 200 JSON.parse(last_response.body).first['author_id'].should eq current_user.id.to_s end it 'should have a result do' do last_response.status.should == 200 JSON.parse(last_response.body).size.should eq 1 end end end describe "GET /v1/topics/limace" do context 'without topics' do it "returns an empty array of topics" do expect { get "/v1/topics/#{topic_by_member.limace}", {}, {'current_user' => current_user} }.should raise_error end end context 'with topics' do before do topic get "/v1/topics/#{topic.limace}", {}, {'current_user' => current_user} end it "should have a topic in list" do last_response.status.should == 200 JSON.parse(last_response.body)['author_id'].should eq current_user.id.to_s end end end end
30.684211
109
0.634648
e8ee337064a659dc974ea7c29a3e1d75f75beb11
959
# frozen_string_literal: true module Banzai module ReferenceParser class ExternalIssueParser < BaseParser self.reference_type = :external_issue def referenced_by(nodes, options = {}) issue_ids = issue_ids_per_project(nodes) projects = find_projects_for_hash_keys(issue_ids) issues = [] projects.each do |project| issue_ids[project.id].each do |id| issues << ExternalIssue.new(id, project) end end issues end def issue_ids_per_project(nodes) gather_attributes_per_project(nodes, self.class.data_attribute) end # we extract only external issue trackers references here, we don't extract cross-project references, # so we don't need to do anything here. def can_read_reference?(user, ref_project, node) true end def nodes_visible_to_user(user, nodes) nodes end end end end
25.236842
107
0.653806
ab7804592f5890244fe841f1cf62f4466d3a4f98
8,850
######################## # Cookbook Configuration ######################## default["transloader"]["repository"] = "https://github.com/GeoSensorWebLab/data-transloader" default["transloader"]["revision"] = "v0.7.0" default["transloader"]["install_home"] = "/opt/data-transloader" default["transloader"]["user_home"] = "/home/transloader" default["transloader"]["user"] = "transloader" ########################## # PostgreSQL Configuration ########################## default["postgresql"]["version"] = "11" #################### # Ruby Configuration #################### default["ruby"]["version"] = "2.6.4" ################### # ETL Configuration ################### # Start date for importing historical data using Airflow DAGs default["etl"]["year"] = 2016 default["etl"]["month"] = 1 default["etl"]["day"] = 1 default["etl"]["cache_dir"] = "/srv/data" default["etl"]["log_dir"] = "/srv/logs" ################ # Apache Airflow ################ # Installation directory for Airflow default["airflow"]["home"] = "/opt/airflow" # Base URL for Airflow interface default["airflow"]["base_url"] = "https://asw-airflow.gswlab.ca" # If false, will automatically enable all DAGs when added to scheduler default["airflow"]["dags_are_paused_at_creation"] = false # Limit number of DAGs that can run at the same time default["airflow"]["parallelism"] = 2 # Limit the number of runs of the *same* DAG that can happen at the same # time default["airflow"]["dag_concurrency"] = 1 # Limits the number of runs of a DAG that can be in an active state default["airflow"]["max_active_runs_per_dag"] = 1 ############################# # Environment Canada Stations ############################# # Remember to use the four-letter codes; check the following CSV file: # http://dd.weather.gc.ca/observations/doc/swob-xml_station_list.csv default["transloader"]["environment_canada_stations"] = [ "CMFJ", "CMFX", "CMIN", "CMJK", "CNBB", "CNBI", "CNCD", "CNCO", "CNDT", "CNEK", "CNFR", "CNGC", "CNGH", "CNPL", "CNPV", "CNSG", "CNSQ", "CNVQ", "CNZS", "CPYQ", "CVBR", "CVXY", "CWAY", "CWBJ", "CWFP", "CWFX", "CWFZ", "CWGZ", "CWHO", "CWHT", "CWIC", "CWID", "CWIJ", "CWIL", "CWJL", "CWJN", "CWLG", "CWLI", "CWMT", "CWND", "CWNV", "CWOI", "CWON", "CWPX", "CWQF", "CWQY", "CWRF", "CWRR", "CWSY", "CWUM", "CWXP", "CWYF", "CWYH", "CWZR", "CWZW", "CXAR", "CXAT", "CXBL", "CXCK", "CXCM", "CXDE", "CXDK", "CXFB", "CXHI", "CXQH", "CXRB", "CXSE", "CXTN", "CXTV", "CXUX", "CXWB", "CXYH", "CXZC", "CYAB", "CYAT", "CYBB", "CYBK", "CYCB", "CYCO", "CYCS", "CYCY", "CYDA", "CYDB", "CYDP", "CYEK", "CYER", "CYEV", "CYFB", "CYFR", "CYFS", "CYGH", "CYGT", "CYGW", "CYHI", "CYHK", "CYHY", "CYIO", "CYJF", "CYKD", "CYLC", "CYLK", "CYLT", "CYMA", "CYMH", "CYMO", "CYOC", "CYPC", "CYPH", "CYPO", "CYQH", "CYRA", "CYRB", "CYRT", "CYSK", "CYSM", "CYSY", "CYTE", "CYUB", "CYUT", "CYUX", "CYVL", "CYVM", "CYVP", "CYVQ", "CYWE", "CYWJ", "CYWY", "CYXN", "CYXP", "CYXQ", "CYXY", "CYYH", "CYYQ", "CYZF", "CYZG", "CYZS", "CYZW", "CZCY", "CZEV", "CZFA", "CZFM", "CZFN", "CZFS", "CZGH", "CZHK", "CZHY", "CZLT", "CZOC", "CZPK", "CZRP", "CZSM", "CZUB", "CZVM"] ######################## # Data Garrison Stations ######################## default["transloader"]["data_garrison_stations"] = [ { "name" => "30 Mile Weather Station", "user_id" => 300234063581640, "station_id" => 300234065673960, "latitude" => 69.1580, "longitude" => -107.0403, "timezone_offset" => "-06:00" }, { "name" => "Melbourne Island Weather Station", "user_id" => 300234063581640, "station_id" => 300234063588720, "latitude" => 68.5948, "longitude" => -104.9363, "timezone_offset" => "-06:00" } ] ############################## # Campbell Scientific Stations ############################## default["transloader"]["campbell_scientific_stations"] = [ { "name" => "Qikirtaarjuk Island Weather Station", "station_id" => 606830, "latitude" => 68.983639, "longitude" => -105.835833, "timezone_offset" => "-06:00", # From: http://dataservices.campbellsci.ca/sbd/606830/data/ "data_files" => [ "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR.dat" ], # Data files that will be used for a historical import DAG, *not* # for the regularly scheduled DAG. "archive_data_files" => [ "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2016-04-23%2009-05-25.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2016-04-23%2019-05-24.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2016-04-23%2019-15-21.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2016-04-25%2022-20-26.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2016-04-25%2022-25-22.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2016-04-25%2022-30-24.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2016-04-30%2021-05-27.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2016-05-02%2008-05-58.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2016-05-05%2018-05-26.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2016-05-09%2003-05-18.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2016-05-12%2015-05-26.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2016-07-29%2013-05-33.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2016-08-08%2018-05-39.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2016-08-08%2022-05-39.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2017-04-26%2011-06-15.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2017-04-26%2012-06-44.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2017-04-28%2012-06-30.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2017-04-30%2016-06-09.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2017-05-01%2019-06-35.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2017-05-02%2015-07-10.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2017-05-02%2017-07-45.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2018-04-12%2016-04-34.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2018-04-14%2013-04-31.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2018-04-14%2014-04-31.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2018-04-14%2015-04-10.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2018-05-24%2007-32-25.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2018-08-05%2012-04-09.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2018-08-05%2015-04-05.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2019-05-05%2013-03-55.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2019-05-06%2013-03-55.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2019-05-06%2014-03-56.dat", "http://dataservices.campbellsci.ca/sbd/606830/data/CBAY_MET_1HR-Archive_2019-08-09%2011-03-53.dat" ] } ] # Block these properties from being uploaded. # This is passed directly into the `--blocked` argument in the data # transloader command line tool. default["transloader"]["campbell_scientific_blocked"] = "LdnCo_Avg,Ux_Avg,Uy_Avg,Uz_Avg,CO2_op_Avg,H2O_op_Avg,Pfast_cp_Avg,xco2_cp_Avg,xh2o_cp_Avg,mfc_Avg" # Destination URL for uploading to SensorThings API. Include any path # components up to the complete root URL (e.g. "/v1.0/") with a trailing # slash. default["sensorthings"]["external_uri"] = "https://arctic-sensors.sensorup.com/v1.0/" # Arctic Sensors Dashboard default["dashboard"]["prefix"] = "/opt/community-sensorweb" default["dashboard"]["repository"] = "https://github.com/GeoSensorWebLab/community-sensorweb" ####################### # Node.js Configuration ####################### default["nodejs"]["install_method"] = "binary" default["nodejs"]["version"] = "10.16.0" default["nodejs"]["binary"]["checksum"] = "2e2cddf805112bd0b5769290bf2d1bc4bdd55ee44327e826fa94c459835a9d9a"
52.366864
155
0.654463
38a9a1ae1bd75c9379c14cef584ec89e14a43860
2,471
class Paginate < Liquid::Block Syntax = /(#{Liquid::QuotedFragment})\s*(by\s*(\d+))?/ def initialize(tag_name, markup, options) super if markup =~ Syntax @collection_name = $1 @page_size = if $2 $3.to_i else 20 end @attributes = { 'window_size' => 3 } markup.scan(Liquid::TagAttributes) do |key, value| @attributes[key] = value end else raise SyntaxError.new("Syntax Error in tag 'paginate' - Valid syntax: paginate [collection] by number") end end def render(context) @context = context context.stack do current_page = context['current_page'].to_i pagination = { 'page_size' => @page_size, 'current_page' => 5, 'current_offset' => @page_size * 5 } context['paginate'] = pagination collection_size = context[@collection_name].size raise ArgumentError.new("Cannot paginate array '#{@collection_name}'. Not found.") if collection_size.nil? page_count = (collection_size.to_f / @page_size.to_f).to_f.ceil + 1 pagination['items'] = collection_size pagination['pages'] = page_count - 1 pagination['previous'] = link('&laquo; Previous', current_page - 1) unless 1 >= current_page pagination['next'] = link('Next &raquo;', current_page + 1) unless page_count <= current_page + 1 pagination['parts'] = [] hellip_break = false if page_count > 2 1.upto(page_count - 1) do |page| if current_page == page pagination['parts'] << no_link(page) elsif page == 1 pagination['parts'] << link(page, page) elsif page == page_count - 1 pagination['parts'] << link(page, page) elsif page <= current_page - @attributes['window_size'] || page >= current_page + @attributes['window_size'] next if hellip_break pagination['parts'] << no_link('&hellip;') hellip_break = true next else pagination['parts'] << link(page, page) end hellip_break = false end end super end end private def no_link(title) { 'title' => title, 'is_link' => false } end def link(title, page) { 'title' => title, 'url' => current_url + "?page=#{page}", 'is_link' => true } end def current_url "/collections/frontpage" end end
27.153846
118
0.572643
ab0205aa39d2b7779e43488b76a312c74e61c1f3
497
Gem::Specification.new do |s| s.name = "sinatra-redis" s.description = "Redis module for Sinatra" s.summary = s.description s.authors = ["Alyssa Herzog"] s.email = "[email protected]" s.version = "0.0.1" s.date = "2016-07-09" s.license = "MIT" s.files = %w(Gemfile LICENSE sinatra-redis.gemspec) + Dir["lib/**/*"] s.required_ruby_version = '>= 2.2.0' s.add_dependency "sinatra", '~> 2.0' s.add_dependency "redis", '~> 3.2' end
35.5
77
0.589537
e288d803beaa6208190fa89985be7b18defde510
3,490
########################################################################## # Copyright 2016 ThoughtWorks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ########################################################################## require 'rails_helper' describe ApiV1::Admin::Internal::CommandSnippetsController do include ApiHeaderSetupTeardown include ApiV1::ApiVersionHelper before :each do allow(controller).to receive(:command_repository_service).and_return(@command_repository_service = double('command_repository_service')) end describe "index" do describe "authorization" do it 'should allow all with security disabled' do disable_security expect(controller).to allow_action(:get, :index) end it 'should disallow anonymous users, with security enabled' do enable_security login_as_anonymous expect(controller).to disallow_action(:get, :index).with(401, 'You are not authorized to perform this action.') end it 'should disallow normal users, with security enabled' do enable_security login_as_user expect(controller).to disallow_action(:get, :index).with(401, 'You are not authorized to perform this action.') end it 'should allow admin, with security enabled' do enable_security login_as_admin expect(controller).to allow_action(:get, :index) end end describe 'as admin' do it 'should fetch all command snippets filtered by prefix' do enable_security login_as_admin snippet = com.thoughtworks.go.helper.CommandSnippetMother.validSnippet("scp") presenter = ApiV1::CommandSnippetsRepresenter.new([snippet]) snippet_hash = presenter.to_hash(url_builder: controller, prefix: 'rake') expect(@command_repository_service).to receive(:lookupCommand).with('rake').and_return([snippet]) get_with_api_header :index, prefix: 'rake' expect(response).to be_ok expect(actual_response).to eq(JSON.parse(snippet_hash.to_json).deep_symbolize_keys) end end describe "route" do describe "with_header" do it 'should route to index action of the internal command_snippets controller' do expect(:get => 'api/admin/internal/command_snippets').to route_to(action: 'index', controller: 'api_v1/admin/internal/command_snippets') end end describe "without_header" do before :each do teardown_header end it 'should not route to index action of internal command_snippets controller without header' do expect(:get => 'api/admin/internal/command_snippets').to_not route_to(action: 'index', controller: 'api_v1/admin/internal/command_snippets') expect(:get => 'api/admin/internal/command_snippets').to route_to(controller: 'application', action: 'unresolved', url: 'api/admin/internal/command_snippets') end end end end end
38.351648
168
0.678797
f810e1991720bad1aa7d375d1dad353e2b8f9049
5,454
# frozen_string_literal: true module Solargraph module Parser module Rubyvm # A factory for generating chains from nodes. # class NodeChainer include Rubyvm::NodeMethods Chain = Source::Chain # @param node [Parser::AST::Node] # @param filename [String] def initialize node, filename = nil, in_block = false @node = node @filename = filename @in_block = in_block ? 1 : 0 end # @return [Source::Chain] def chain links = generate_links(@node) Chain.new(links, @node, (Parser.is_ast_node?(@node) && @node.type == :SPLAT)) end class << self # @param node [Parser::AST::Node] # @param filename [String] # @return [Source::Chain] def chain node, filename = nil, in_block = false NodeChainer.new(node, filename, in_block).chain end # @param code [String] # @return [Source::Chain] def load_string(code) node = Parser.parse(code.sub(/\.$/, '')) chain = NodeChainer.new(node).chain chain.links.push(Chain::Link.new) if code.end_with?('.') chain end end private # @param n [Parser::AST::Node] # @return [Array<Chain::Link>] def generate_links n return [] unless Parser.is_ast_node?(n) return generate_links(n.children[2]) if n.type == :SCOPE return generate_links(n.children[0]) if n.type == :SPLAT result = [] if n.type == :ITER @in_block += 1 result.concat generate_links(n.children[0]) @in_block -= 1 elsif n.type == :CALL || n.type == :OPCALL n.children[0..-3].each do |c| result.concat generate_links(c) end result.push Chain::Call.new(n.children[-2].to_s, node_to_argchains(n.children.last), @in_block > 0 || block_passed?(n)) elsif n.type == :ATTRASGN result.concat generate_links(n.children[0]) result.push Chain::Call.new(n.children[1].to_s, node_to_argchains(n.children[2]), @in_block > 0 || block_passed?(n)) elsif n.type == :VCALL result.push Chain::Call.new(n.children[0].to_s, [], @in_block > 0 || block_passed?(n)) elsif n.type == :FCALL result.push Chain::Call.new(n.children[0].to_s, node_to_argchains(n.children[1]), @in_block > 0 || block_passed?(n)) elsif n.type == :SELF result.push Chain::Head.new('self') elsif n.type == :ZSUPER result.push Chain::ZSuper.new('super', @in_block > 0 || block_passed?(n)) elsif n.type == :SUPER result.push Chain::Call.new('super', node_to_argchains(n.children.last), @in_block > 0 || block_passed?(n)) elsif [:COLON2, :COLON3, :CONST].include?(n.type) const = unpack_name(n) result.push Chain::Constant.new(const) elsif [:LVAR, :LASGN, :DVAR].include?(n.type) result.push Chain::Call.new(n.children[0].to_s) elsif [:IVAR, :IASGN].include?(n.type) result.push Chain::InstanceVariable.new(n.children[0].to_s) elsif [:CVAR, :CVASGN].include?(n.type) result.push Chain::ClassVariable.new(n.children[0].to_s) elsif [:GVAR, :GASGN].include?(n.type) result.push Chain::GlobalVariable.new(n.children[0].to_s) elsif n.type == :OP_ASGN_OR result.concat generate_links n.children[2] elsif [:class, :module, :def, :defs].include?(n.type) # @todo Undefined or what? result.push Chain::UNDEFINED_CALL elsif n.type == :AND result.concat generate_links(n.children.last) elsif n.type == :OR result.push Chain::Or.new([NodeChainer.chain(n.children[0], @filename), NodeChainer.chain(n.children[1], @filename)]) elsif n.type == :begin result.concat generate_links(n.children[0]) elsif n.type == :BLOCK_PASS result.push Chain::BlockVariable.new("&#{n.children[1].children[0].to_s}") else lit = infer_literal_node_type(n) result.push (lit ? Chain::Literal.new(lit) : Chain::Link.new) end result end def block_passed? node node.children.last.is_a?(RubyVM::AbstractSyntaxTree::Node) && node.children.last.type == :BLOCK_PASS end def node_to_argchains node return [] unless Parser.is_ast_node?(node) if [:ZARRAY, :ARRAY, :LIST].include?(node.type) node.children[0..-2].map { |c| NodeChainer.chain(c) } elsif node.type == :SPLAT [NodeChainer.chain(node)] elsif node.type == :ARGSCAT result = node.children[0].children[0..-2].map { |c| NodeChainer.chain(c) } result.push NodeChainer.chain(node.children[1]) # @todo Smelly instance variable access result.last.instance_variable_set(:@splat, true) result elsif node.type == :BLOCK_PASS result = node_to_argchains(node.children[0]) result.push Chain.new([Chain::BlockVariable.new("&#{node.children[1].children[0].to_s}")]) result else [] end end end end end end
40.4
131
0.563623
62086dd334ee98e5b92eb3e1789e53d35cd4495f
40
class PastEvent < ApplicationRecord end
13.333333
35
0.85
b9e646cf6d8699229ec0283ba8df1f1d85e0d889
1,891
describe "Acceptance: Fetching details of a client" do context "as an authorised client" do let(:token) { create_token scopes: %w[client:fetch] } describe "fetching an existing client" do let(:client) { create_client scopes: %w[one two], supplemental: { test: true } } let(:response) do make_request token do get "/api/client/#{client.id}" end end it "returns an ok status code" do expect(response.status).to eq 200 end it "the fetched client has the right name" do expect(response.get(%i[data client name])).to eq client.name end it "the fetched client has the right scopes" do expect(response.get(%i[data client scopes])).to eq client.scopes end it "the fetched client has the right supplemental data" do expect(response.get(%i[data client supplemental])).to eq({ test: true }) end it "the fetched client has no secret" do expect(response.get(%i[data client secret])).to be_nil end end describe "fetching a client that does not exist" do let(:response) do make_request token do get "/api/client/NONEXISTANT_CLIENT" end end it "returns a not found status code" do expect(response.status).to eq 404 end end end context "as an unauthenticated user" do describe "fetching a client " do let(:response) { get "/api/client/test" } it "returns an unauthenticated status code" do expect(response.status).to eq 401 end end end describe "fetching a client as an unauthorised user" do let(:token) { create_token } let(:response) do make_request token do get "/api/client/test" end end it "returns an unauthorised status code" do expect(response.status).to eq 403 end end end
27.014286
86
0.629825
183a6aa9d3566fe02b424640f8c8a7e2b8d12d25
378
# frozen_string_literal: true module NfgUi module Bootstrap module Utilities # Delivers the dismissibility of the component to the HAML partial module Headable def heading options.fetch(:heading, nil) end private def non_html_attribute_options super.push(:heading) end end end end end
18
72
0.626984
e982eead549aa4524a3703b09020e8ba5b41cf4e
1,532
class NotesController < ApplicationController def new @note = Note.new(user_id: session[:user_id], destination_id: params[:destination_id]) @destination = @note.destination end def create @note = Note.create(note_params) if @note.save destination = Destination.find_by(id: params[:note][:destination_id]) flash[:notice] = "Note for " + destination.name + " was successfully created!!" redirect_to destinations_path else @destination_id = params[:note][:destination_id] render :new end end def index if params[:destination_id] @destination = Destination.find_by(id: params[:destination_id]) @notes = @destination.notes if @notes.empty? @notes = "none" end else @notes = Note.all end end def edit @note = Note.find_by(id: params[:id]) end def update @note = Note.find_by(id: params[:id]) @note.update(note_params) redirect_to notes_path end def destroy destination = Note.find_by(id: params[:id]).destination Note.find(params[:id]).destroy flash[:notice] = "Note for " + destination.name + " was successfully deleted!!" redirect_to destinations_path end private def note_params params.require(:note).permit(:content, :destination_id, :user_id) end end
28.37037
93
0.576371
b9cb55595bb2cf128ca185472cd2f3b995949798
1,101
module Wikia module Response module RelatedPage class RelatedPages class RelatedPage class ImgOriginalDimension attr_reader :width, :height def initialize(img_original_dimensions) if img_original_dimensions @width = img_original_dimensions["width"] @height = img_original_dimensions["height"] end end end attr_reader :url, :title, :id, :img_url, :img_original_dimensions, :text def initialize(related_page) @url = related_page["url"] @title = related_page["title"] @id = related_page["id"] @img_original_dimensions = ImgOriginalDimension.new(related_page["img_original_dimensions"]) @text = related_page["text"] end end attr_reader :items, :basepath def initialize(data) @items = data["items"].map{|id, items| [id, items.map{|item| RelatedPage.new(item)}]}.to_h @basepath = data["basepath"] end end end end end
33.363636
104
0.580381
1164d1615e2509d4de0e820ad2a3ce68d5bd65ea
589
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::DataBoxEdge::Mgmt::V2019_08_01 module Models # # Defines values for DataBoxEdgeDeviceStatus # module DataBoxEdgeDeviceStatus ReadyToSetup = "ReadyToSetup" Online = "Online" Offline = "Offline" NeedsAttention = "NeedsAttention" Disconnected = "Disconnected" PartiallyDisconnected = "PartiallyDisconnected" Maintenance = "Maintenance" end end end
26.772727
70
0.70798
4a8f8837d9a90c647564976d1fd9802ec9864b65
734
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. # Rails.application.config.assets.version = '1.0' # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path # Add Yarn node_modules folder to the asset load path. # Rails.application.config.assets.paths << Rails.root.join('node_modules') # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in the app/assets # folder are already added. # Rails.application.config.assets.precompile += %w( admin.js admin.css ) # Add webfonts # Rails.application.config.assets.paths << Rails.root.join('app', 'assets', 'fonts')
43.176471
84
0.757493
1c3e9d37faebe77c0ea030bdf874543a735b3000
276
class CreateTranslationLog < EOL::LoggingMigration def self.up connection.create_table :translation_logs do |t| t.string :key, :limit => 128 t.integer :count, :default => 1 end end def self.down connection.drop_table :translation_logs end end
21.230769
52
0.695652
bfb6cdd1483de514c41c3b1a3676f189d8229c06
5,681
require 'spec_helper' describe 'New Order', type: :feature do let!(:product) { create(:product_in_stock) } let!(:state) { create(:state) } let!(:user) { create(:user, ship_address: create(:address), bill_address: create(:address)) } stub_authorization! before do create(:check_payment_method) create(:shipping_method) # create default store allow(Spree.user_class).to receive(:find_by).and_return(user) create(:store) visit spree.new_admin_order_path end it 'does check if you have a billing address before letting you add shipments' do click_on 'Shipments' expect(page).to have_content 'Please fill in customer info' expect(page).to have_current_path(spree.edit_admin_order_customer_path(Spree::Order.last)) end it 'completes new order successfully without using the cart', js: true do select2 product.name, from: Spree.t(:name_or_sku), search: true click_icon :add expect(page).to have_css('.card', text: 'Order Line Items') click_on 'Customer' select_customer check 'order_use_billing' fill_in_address click_on 'Update' click_on 'Payments' click_on 'Update' expect(page).to have_current_path(spree.admin_order_payments_path(Spree::Order.last)) click_icon 'capture' click_on 'Shipments' click_on 'Ship' expect(page).to have_content('shipped') end context 'adding new item to the order', js: true do it 'inventory items show up just fine and are also registered as shipments' do select2 product.name, from: Spree.t(:name_or_sku), search: true within('table.stock-levels') do fill_in 'variant_quantity', with: 2 click_icon :add end within('.line-items') do expect(page).to have_content(product.name) end click_on 'Customer' select_customer check 'order_use_billing' fill_in_address click_on 'Update' click_on 'Shipments' within('.stock-contents') do expect(page).to have_content(product.name) end end end context 'skipping to shipping without having an address', js: true do it 'prompts you with a flash notice to: Please fill in customer info' do click_on 'Shipments' assert_admin_flash_alert_notice('Please fill in customer info') end end context "adding new item to the order which isn't available", js: true do before do product.update(available_on: nil) select2 product.name, from: Spree.t(:name_or_sku), search: true end it 'inventory items is displayed' do expect(page).to have_content(product.name) expect(page).to have_css('#stock_details') end context 'on increase in quantity the product should be removed from order' do before do accept_alert do within('table.stock-levels') do fill_in 'variant_quantity', with: 2 click_icon :add end end end it { expect(page).not_to have_css('#stock_details') } end end # Regression test for #3958 context 'without a delivery step', js: true do before do allow(Spree::Order).to receive_messages checkout_step_names: [:address, :payment, :confirm, :complete] end it 'can still see line items' do select2 product.name, from: Spree.t(:name_or_sku), search: true click_icon :add within('.line-items') do within('.line-item-name') do expect(page).to have_content(product.name) end within('.line-item-qty-show') do expect(page).to have_content('1') end within('.line-item-price') do expect(page).to have_content(product.price) end end end end # Regression test for #3336 context 'start by customer address' do it 'completes order fine', js: true do click_on 'Customer' select_customer check 'order_use_billing' fill_in_address click_on 'Update' click_on 'Shipments' select2 product.name, from: Spree.t(:name_or_sku), search: true click_icon :add expect(page).not_to have_content('Your order is empty') click_on 'Payments' click_on 'Continue' expect(page).to have_css('.additional-info .state', text: 'COMPLETE') end end # Regression test for #5327 context 'customer with default credit card', js: true do before do allow(Spree.user_class).to receive(:find_by).and_return(user) create(:credit_card, default: true, user: user) end it 'transitions to delivery not to complete' do select2 product.name, from: Spree.t(:name_or_sku), search: true within('table.stock-levels') do fill_in 'variant_quantity', with: 1 click_icon :add end expect(page).not_to have_content('Your order is empty') click_link 'Customer' select_customer wait_for { !page.has_button?('Update') } click_button 'Update' expect(Spree::Order.last.state).to eq 'delivery' end end def fill_in_address(kind = 'bill') fill_in 'First Name', with: 'John 99' fill_in 'Last Name', with: 'Doe' fill_in 'Address', with: '100 first lane' fill_in 'Address (contd.)', with: '#101' fill_in 'City', with: 'Bethesda' fill_in 'Zip Code', with: '20170' select2 state.name, css: '#bstate' fill_in 'Phone', with: '123-456-7890' end def select_customer within 'div#select-customer' do select2 user.email, css: '#customer-search-field', search: true end end end
28.984694
108
0.647421
ff5f3d6d093e956b4afa153163f754e91cb85833
2,956
module Travis module Addons module Hipchat # Publishes a build notification to hipchat rooms as defined in the # configuration (`.travis.yml`). # # Hipchat credentials can be encrypted using the repository's ssl key. class Task < Travis::Task require 'travis/addons/hipchat/http_helper' DEFAULT_TEMPLATE = [ "%{repository}#%{build_number} (%{branch} - %{commit} : %{author}): the build has %{result}", "Change view: %{compare_url}", "Build details: %{build_url}" ] def targets params[:targets] end def message @messages ||= template.map { |line| Util::Template.new(line, payload, source: :hipchat).interpolate } end private def process(timeout) targets.each do |target| helper = HttpHelper.new(target) if helper.hostname == HttpHelper::HIPCHAT_DEFAULT_HOST info "Skipping HipChat notification to #{HttpHelper::HIPCHAT_DEFAULT_HOST}" return else info "task=hipchat build=#{build[:id]} repo=#{repository[:slug]} hostname=#{helper.hostname}" end if helper.url.nil? error "Empty HipChat URL for #{repository[:slug]}##{build[:id]}, decryption probably failed." next end send_message(helper, message, timeout = timeout) end end def send_message(helper, message, timeout) message.each do |line| response = http.post(helper.url) do |r| r.options.timeout = timeout r.body = helper.body(line: line, color: color, message_format: message_format, notify: notify) helper.add_content_type!(r.headers) end if not response.success? error "task=hipchat build=#{build[:id]} room=#{helper.room_id} message=#{response.body["error"].try(:[], "message")}" end end rescue Faraday::Error => e error "task=hipchat build=#{build[:id]} repo=#{repository[:slug]} hostname=#{helper.hostname}" end def template template = params[:template] || config[:template] rescue nil Array(template || DEFAULT_TEMPLATE) end def notify (config[:notify] rescue nil) || false end def color { "passed" => "green", "failed" => "red", "errored" => "red", "canceled" => "gray", }.fetch(build[:state], "yellow") end def message_format params[:format] || (config[:format] rescue nil) || 'text' end def config build[:config][:notifications][:hipchat] rescue {} end end end end end
31.446809
133
0.52977
1df4a5b09b0f4b8081bef89372c26af6f1344432
529
require 'minitest/autorun' require_relative 'src' # Tests for part1 class TestPart1 < MiniTest::Test def test_no_block assert_raises(LocalJumpError) { integrate(0, 5) } end def test_wrong_order assert_raises(ArgumentError) { integrate(10, 0) { |x| x } } end def test_eps exact_value = Math.log(2)**2 / 2 func = ->(x) { Math.log(x) / x } assert_in_delta integrate(1, 2, eps: 1e-4, &func)[0], exact_value, 1e-2 assert_in_delta integrate(1, 2, eps: 1e-6, &func)[0], exact_value, 1e-4 end end
24.045455
75
0.667297
f892486c5df225e53a3b41a410d2eedd34e0fbca
6,500
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. require 'date' # rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength module OCI # JWK model. class IdentityDataPlane::Models::JWK # **[Required]** The modulus. # @return [String] attr_accessor :n # **[Required]** The exponent. # @return [String] attr_accessor :e # **[Required]** The key id. # @return [String] attr_accessor :kid # **[Required]** The key use. # @return [String] attr_accessor :use # **[Required]** The algorithm. # @return [String] attr_accessor :alg # **[Required]** The key type. # @return [String] attr_accessor :kty # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { # rubocop:disable Style/SymbolLiteral 'n': :'n', 'e': :'e', 'kid': :'kid', 'use': :'use', 'alg': :'alg', 'kty': :'kty' # rubocop:enable Style/SymbolLiteral } end # Attribute type mapping. def self.swagger_types { # rubocop:disable Style/SymbolLiteral 'n': :'String', 'e': :'String', 'kid': :'String', 'use': :'String', 'alg': :'String', 'kty': :'String' # rubocop:enable Style/SymbolLiteral } end # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # Initializes the object # @param [Hash] attributes Model attributes in the form of hash # @option attributes [String] :n The value to assign to the {#n} property # @option attributes [String] :e The value to assign to the {#e} property # @option attributes [String] :kid The value to assign to the {#kid} property # @option attributes [String] :use The value to assign to the {#use} property # @option attributes [String] :alg The value to assign to the {#alg} property # @option attributes [String] :kty The value to assign to the {#kty} property def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } self.n = attributes[:'n'] if attributes[:'n'] self.e = attributes[:'e'] if attributes[:'e'] self.kid = attributes[:'kid'] if attributes[:'kid'] self.use = attributes[:'use'] if attributes[:'use'] self.alg = attributes[:'alg'] if attributes[:'alg'] self.kty = attributes[:'kty'] if attributes[:'kty'] end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # Checks equality by comparing each attribute. # @param [Object] other the other object to be compared def ==(other) return true if equal?(other) self.class == other.class && n == other.n && e == other.e && kid == other.kid && use == other.use && alg == other.alg && kty == other.kty end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # @see the `==` method # @param [Object] other the other object to be compared def eql?(other) self == other end # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [n, e, kid, use, alg, kty].hash end # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) public_method("#{key}=").call( attributes[self.class.attribute_map[key]] .map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) } ) end elsif !attributes[self.class.attribute_map[key]].nil? public_method("#{key}=").call( OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]]) ) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = public_method(attr).call next if value.nil? && !instance_variable_defined?("@#{attr}") hash[param] = _to_hash(value) end hash end private # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end # rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
32.338308
245
0.633077
ff0d183b7f4bc00781e1e64f2240b48ef2710057
146
# Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application Bi::Application.initialize!
24.333333
52
0.794521
b90a023b34d998e0bd91c59683a054af558db4c8
915
class Sxiv < Formula desc "Simple X Image Viewer" homepage "https://github.com/muennich/sxiv" url "https://github.com/muennich/sxiv/archive/v1.3.2.tar.gz" mirror "https://mirrors.kernel.org/debian/pool/main/s/sxiv/sxiv_1.3.2.orig.tar.gz" sha256 "9f5368de8f0f57e78ebe02cb531a31107a993f2769cec51bcc8d70f5c668b653" head "https://github.com/muennich/sxiv.git" bottle do cellar :any sha256 "e5bcdb136a9ffc360193193461e64502369bd5f8a083525a273cca35bf49e0f8" => :sierra sha256 "39d8e6f5f08b72e8e7d48681d7d44d7f56a52ee36f9c8b836e825e09a769e0c5" => :el_capitan sha256 "0ef89ec26f91d1639744ecb5ceec0db81d675e8a1ce6c7946f4a46488842e49a" => :yosemite end depends_on :x11 depends_on "imlib2" depends_on "giflib" depends_on "libexif" def install system "make", "config.h" system "make", "PREFIX=#{prefix}", "install" end test do system "#{bin}/sxiv", "-v" end end
29.516129
92
0.747541
6a5f7aa241402c30425238bc17129461fe77ef07
386
require 'data_mapper/adapters/data_object_adapter' class MockAdapter < DataMapper::Adapters::DataObjectAdapter COLUMN_QUOTING_CHARACTER = "`" TABLE_QUOTING_CHARACTER = "`" def delete(instance_or_klass, options = nil) end def save(database_context, instance) end def load(database_context, klass, options) end def table_exists?(name) true end end
18.380952
59
0.733161
617b862b814864cbba76f80991bd687f382a3aa1
4,143
require "rails_helper" describe Entities::Company do it_behaves_like "Entities::BaseEntity#initialize" input_args = { address: "Address", company_executives: ["Company Executive"], exchange: "Exchange", id: 123, issuer_type: "Issuer Type" } it_behaves_like("Entities::HasDbEntity.from_db_entity", input_args) do before :each do allow(entity).to receive(:address) { "address" } allow(Entities::Address).to receive(:from_db_entity).with("address") { "Address" } allow(entity).to receive(:company_executives) { ["company_executive"] } allow(Entities::CompanyExecutive).to receive(:from_db_entity).with("company_executive") { "Company Executive" } allow(entity).to receive(:exchange) { "exchange" } allow(Entities::Exchange).to receive(:from_db_entity).with("exchange") { "Exchange" } allow(entity).to receive(:issuer_type) { "issuer_type" } allow(Entities::IssuerType).to receive(:from_db_entity).with("issuer_type") { "Issuer Type" } allow(entity).to receive(:external_analysis) { "external_analysis" } end end es_args = { address: "Address", exchange: "Exchange", issuer_type: "Issuer Type" } it_behaves_like("Entities::HasElasticsearch.from_es_response", es_args) do before :each do allow(Entities::Address).to receive(:from_es_response) { "Address" } allow(Entities::Exchange).to receive(:from_es_response) { "Exchange" } allow(Entities::IssuerType).to receive(:from_es_response) { "Issuer Type" } end end let(:args) do { address: address, company_executives: company_executives, description: description, employees: employees, exchange: exchange, external_analysis: external_analysis, id: id, industry: industry, issuer_type: issuer_type, name: name, phone: phone, sector: sector, security_name: security_name, sic_code: sic_code, symbol: symbol, website: website } end let(:address) { double(:address) } let(:company_executives) { double(:company_executives) } let(:description) { double(:description) } let(:employees) { double(:employees) } let(:exchange) { double(:exchange) } let(:external_analysis) { double(:external_analysis) } let(:id) { double(:id) } let(:industry) { double(:industry) } let(:issuer_type) { double(:issuer_type) } let(:name) { double(:name) } let(:phone) { double(:phone) } let(:sector) { double(:sector) } let(:security_name) { double(:security_name) } let(:sic_code) { double(:sic_code) } let(:symbol) { double(:symbol) } let(:website) { double(:website) } subject(:company) { described_class.new(args) } describe ".from_iex_response" do let(:args) do { address: address, description: "Test Description", employees: 137_000, exchange: exchange, industry: "Telecommunications Equipment", issuer_type: issuer_type, name: "Apple, Inc.", phone: "1.408.996.1010", sector: "Electronic Technology", security_name: "Apple Inc.", sic_code: 3663, symbol: "AAPL", website: "http://www.apple.com" } end let!(:response) { json_fixture("/api_responses/iex/company.json") } subject(:company) { described_class.from_iex_response(response) } it "expect to create an entity with args" do expect(Entities::Address).to receive(:from_iex_response).with(response) { address } expect(Entities::Exchange).to receive(:from_iex_company_response).with(response) { exchange } expect(Entities::IssuerType).to receive(:from_iex_company_response).with(response) { issuer_type } expect(described_class).to receive(:new).with(args) subject end end describe "#etf?" do subject { company.etf? } context "without issuer_type" do let(:issuer_type) { nil } it { is_expected.to be_nil } end context "with issuer_type" do it "delegates to issuer_type's etf" do expect(issuer_type).to receive(:etf?) { "Result" } subject end end end end
33.682927
117
0.66015
4abd678c8b4f52bb2f144cfc66f7f9b690bcdbbf
1,415
Pod::Spec.new do |s| s.name = 'IBMWatsonPersonalityInsightsV3' s.version = '3.3.0' s.summary = 'Client framework for the IBM Watson Personality Insights service' s.description = <<-DESC IBM Watson™ Personality Insights uses linguistic analytics to infer individuals' intrinsic personality characteristics from digital communications such as email, text messages, tweets, and forum posts. DESC s.homepage = 'https://www.ibm.com/watson/services/personality-insights/' s.license = { :type => 'Apache License, Version 2.0', :file => 'LICENSE' } s.authors = { 'Jeff Arn' => '[email protected]', 'Mike Kistler' => '[email protected]' } s.module_name = 'PersonalityInsights' s.ios.deployment_target = '10.0' s.source = { :git => 'https://github.com/watson-developer-cloud/swift-sdk.git', :tag => "v#{s.version}" } s.source_files = 'Source/PersonalityInsightsV3/**/*.swift', 'Source/SupportingFiles/InsecureConnection.swift', 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/PersonalityInsightsV3/Shared.swift' s.swift_version = ['4.2', '5.0', '5.1'] s.dependency 'IBMSwiftSDKCore', '~> 1.0.0' end
50.535714
122
0.577385
d5ba178600effd4ca8329a122f417f5bd2b907d8
871
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. # Run `pod lib lint analytics_support.podspec` to validate before publishing. # Pod::Spec.new do |s| s.name = 'analytics_support' s.version = '0.0.1' s.summary = 'Support package for Google Analytics.' s.homepage = 'http://example.com' s.license = { :file => '../LICENSE' } s.author = { 'Your Company' => '[email protected]' } s.source = { :path => '.' } s.source_files = 'Classes/**/*' s.dependency 'Flutter' s.dependency 'GoogleTagManager', '~> 7.4' s.platform = :ios, '9.0' s.static_framework = true # Flutter.framework does not contain a i386 slice. s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' } s.swift_version = '5.0' end
37.869565
105
0.614237