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
6254e9dfee06d75e9bddbb7cce0f4c333aa4f93c
319
module Fog module Compute class Ninefold class Real def update_virtual_machine(options = {}) request('updateVirtualMachine', options, :expects => [200], :response_prefix => 'updatevirtualmachineresponse', :response_type => Hash) end end end end end
21.266667
93
0.611285
281f3949914a8f49b0a66721dff1229ca5abe6fd
663
module RailsAuthorize module Matchers extend RSpec::Matchers::DSL matcher :forbid_action do |action, *args| match do |policy| !policy.public_send("#{action}?", *args) end failure_message do |policy| "#{policy.class} does not forbid #{action} for " + policy.public_send(RailsAuthorize::Matchers.configuration.user_alias) .inspect + '.' end failure_message_when_negated do |policy| "#{policy.class} does not permit #{action} for " + policy.public_send(RailsAuthorize::Matchers.configuration.user_alias) .inspect + '.' end end end end
27.625
79
0.616893
332d302374abed30bbadd200df8e92d98224d58e
4,129
require 'digest' require 'open-uri' require 'resolv-replace' require 'timeout' class Voice::File extend SS::Translation include SS::Document include SS::Reference::Site include Cms::SitePermission include Voice::Downloadable include Voice::Lockable store_in_default_post set_permission_name "cms_tools", :use field :error, type: String field :has_error, type: Integer, default: 0 field :age, type: Integer, default: 0 scope :search, ->(params) do criteria = self.where({}) if params.present? save_term = params[:keyword] if save_term.present? from = History::Log.term_to_date save_term criteria = criteria.lt(created: from) if from end keyword = params[:keyword] criteria = criteria.keyword_in keyword, :url if keyword.present? has_error = params[:has_error] if has_error.present? has_error = has_error.to_i if has_error.kind_of? String criteria = criteria.where(has_error: 1) if has_error != 0 end end criteria end before_save :set_has_error after_destroy :delete_file class << self def root return test_root if Rails.env.test? ::File.join(Rails.root, "private", "files") end def save_term_options [ [I18n.t(:"history.save_term.day"), "day"], [I18n.t(:"history.save_term.month"), "month"], [I18n.t(:"history.save_term.year"), "year"], [I18n.t(:"history.save_term.all_save"), "all_save"], ] end private def test_root prefix = "voice" timestamp = Time.zone.now.strftime("%Y%m%d") tmp = ::File.join(Dir.tmpdir, "#{prefix}-#{timestamp}") ::Dir.mkdir(tmp) unless ::Dir.exists?(tmp) tmp end end def file site_part = site_id.to_s.split(//).join("/") id_part = Digest::SHA1.hexdigest(id.to_s).scan(/.{1,2}/).shift(2).join("/") file_part = "#{id}.mp3" "#{self.class.root}/voice_files/#{site_part}/#{id_part}/_/#{file_part}" end def exists? Fs.exists?(file) end def latest?(margin = 60) return false unless exists? # check for whether file is fresh enough to prevent infinite loops in voice synthesis. return true if fresh?(margin) download # check for whether this has same identity return false unless same_identity? # check for whether kana dictionary is updated. Kana::Dictionary.pull(self.site_id) do |kanadic| if kanadic kanadic_modified = ::File.mtime(kanadic) file_modified = Fs.stat(self.file).mtime return false if file_modified < kanadic_modified end end # this one is latest. true end def synthesize(force = false) self.class.ensure_release_lock(self) do begin download unless force if self.latest? # voice file is up-to-date Rails.logger.info("voice file up-to-date: #{self.url}") break end end Fs.mkdir_p(::File.dirname(self.file)) Voice::Converter.convert(self.site_id, @cached_page.html, self.file) self.page_identity = @cached_page.page_identity self.error = nil # incrementing age ensures that 'updated' field is updated. self.age += 1 self.save! rescue OpenURI::HTTPError raise rescue Exception => e self.page_identity = nil self.error = e.to_s # incrementing age ensures that 'updated' field is updated. self.age += 1 guard_from_exception(self.url) do self.save! end raise end end true end private def set_has_error self.has_error = self.error.blank? ? 0 : 1 end def delete_file file = self.file Fs.rm_rf(file) if exists? end def guard_from_exception(message, klass = Mongoid::Errors::MongoidError) begin yield rescue klass => e Rails.logger.error("#{message}: #{e.class} (#{e.message}):\n #{e.backtrace.join('\n ')}") end end def fresh?(margin) elapsed = Time.zone.now - Fs.stat(file).mtime elapsed < margin end end
24.288235
97
0.625575
b967a443ea956998fdc4340271a2e1837be83e9b
547
class UserMailer < ApplicationMailer default :from => '[email protected]' def signup_confirmation(user) @user = user mail to: user.email, subject: "Welcome to the UnderTow" end def question_email(question) @question = question @user = @question.user mail to: @user.email, subject: "#{@question.name} Successfully Asked" end def answer_email(answer) @answer = answer @question = @answer.question @user = @question.user mail to: @user.email, subject: "New answer for: #{@question.name}" end end
24.863636
73
0.680073
262c9465b2946bcf9826c2d3c5869ce295128b37
3,824
class Sslyze < Formula include Language::Python::Virtualenv desc "SSL scanner" homepage "https://github.com/nabla-c0d3/sslyze" license "AGPL-3.0-only" stable do url "https://files.pythonhosted.org/packages/7a/c5/92c28ccdd0641c3b5c59b246861f50d738ac0d4a4e0314f9f2700191c464/sslyze-5.0.4.tar.gz" sha256 "369adefac083c3ef6ad60b84ffd48c5fd66cfa47d3bd6cdbdf9a546c50123d23" resource "nassl" do url "https://github.com/nabla-c0d3/nassl/archive/4.0.2.tar.gz" sha256 "440296e07ee021dc283bfe7b810f3139349e26445bc21b5e05820808e15186a2" # patch is needed until https://github.com/nabla-c0d3/nassl/pull/89 is merged patch do url "https://github.com/nabla-c0d3/nassl/commit/f210a0d15d65c6ec11f43d3fef9f6004549bf19a.patch?full_index=1" sha256 "270d5a76c8753afa318cd3fa0d53fe29f89786cba57096e384697acc1259552d" end end end bottle do sha256 cellar: :any, monterey: "c55c4bea4ee7beb0320c1b12d315ae340409b036fee4e630b80e16634b0b4f27" sha256 cellar: :any, big_sur: "5e946542c424ed0446128a9fd0287482a4088e1f84a3393c4878e2e0151eaa9d" sha256 cellar: :any, catalina: "6ee55f116dd5aae0385167ae2ea634b6e66f984a93983ab2f000d405b8cf15d2" sha256 cellar: :any_skip_relocation, x86_64_linux: "24c6d236aa6fc9f1b93f1002fc734eeee0292d24658846822a2e10c97c1c6380" end head do url "https://github.com/nabla-c0d3/sslyze.git", branch: "release" resource "nassl" do url "https://github.com/nabla-c0d3/nassl.git", branch: "release" end end depends_on "pyinvoke" => :build depends_on "rust" => :build # for cryptography depends_on "libffi" depends_on "[email protected]" depends_on "[email protected]" resource "cffi" do url "https://files.pythonhosted.org/packages/00/9e/92de7e1217ccc3d5f352ba21e52398372525765b2e0c4530e6eb2ba9282a/cffi-1.15.0.tar.gz" sha256 "920f0d66a896c2d99f0adbb391f990a84091179542c205fa53ce5787aff87954" end resource "cryptography" do url "https://files.pythonhosted.org/packages/10/a7/51953e73828deef2b58ba1604de9167843ee9cd4185d8aaffcb45dd1932d/cryptography-36.0.2.tar.gz" sha256 "70f8f4f7bb2ac9f340655cbac89d68c527af5bb4387522a8413e841e3e6628c9" end resource "pycparser" do url "https://files.pythonhosted.org/packages/5e/0b/95d387f5f4433cb0f53ff7ad859bd2c6051051cebbb564f139a999ab46de/pycparser-2.21.tar.gz" sha256 "e644fdec12f7872f86c58ff790da456218b10f863970249516d60a5eaca77206" end resource "pydantic" do url "https://files.pythonhosted.org/packages/60/a3/23a8a9378ff06853bda6527a39fe317b088d760adf41cf70fc0f6110e485/pydantic-1.9.0.tar.gz" sha256 "742645059757a56ecd886faf4ed2441b9c0cd406079c2b4bee51bcc3fbcd510a" end resource "tls-parser" do url "https://files.pythonhosted.org/packages/12/fc/282d5dd9e90d3263e759b0dfddd63f8e69760617a56b49ea4882f40a5fc5/tls_parser-2.0.0.tar.gz" sha256 "3beccf892b0b18f55f7a9a48e3defecd1abe4674001348104823ff42f4cbc06b" end resource "typing-extensions" do url "https://files.pythonhosted.org/packages/fe/71/1df93bd59163c8084d812d166c907639646e8aac72886d563851b966bf18/typing_extensions-4.2.0.tar.gz" sha256 "f1c24655a0da0d1b67f07e17a5e6b2a105894e6824b92096378bb3668ef02376" end def install venv = virtualenv_create(libexec, "python3") venv.pip_install resources.reject { |r| r.name == "nassl" } ENV.prepend_path "PATH", Formula["[email protected]"].opt_libexec/"bin" resource("nassl").stage do system "invoke", "build.all" venv.pip_install Pathname.pwd end venv.pip_install_and_link buildpath end test do assert_match "SCANS COMPLETED", shell_output("#{bin}/sslyze --mozilla_config=old google.com") refute_match("exception", shell_output("#{bin}/sslyze --certinfo letsencrypt.org")) end end
41.565217
147
0.770136
7aef60d7a59c41559436ad3d9831595b923074d3
2,449
require "test_helper" module ShopifyCli module Commands class WhoamiTest < MiniTest::Test def test_no_shop_no_org_id stub_db_setup(shop: nil, organization_id: nil) ShopifyCli::PartnersAPI::Organizations.expects(:fetch).never io = capture_io { run_cmd("whoami") } assert_message_output( io: io, expected_content: [ @context.message("core.whoami.not_logged_in", ShopifyCli::TOOL_NAME), ] ) end def test_yes_shop_no_org_id shop = "testshop2.myshopify.com" stub_db_setup(shop: shop, organization_id: nil) ShopifyCli::PartnersAPI::Organizations.expects(:fetch).never io = capture_io { run_cmd("whoami") } assert_message_output( io: io, expected_content: [ @context.message("core.whoami.logged_in_shop_only", shop), ] ) end def test_no_shop_yes_org_id test_org = { "id" => "1234567", "businessName" => "test business name", } stub_db_setup(shop: nil, organization_id: test_org["id"]) ShopifyCli::PartnersAPI::Organizations.expects(:fetch) .with(@context, id: test_org["id"]) .once .returns(test_org) io = capture_io { run_cmd("whoami") } assert_message_output( io: io, expected_content: [ @context.message("core.whoami.logged_in_partner_only", test_org["businessName"]), ] ) end def test_yes_shop_yes_org_id test_org = { "id" => "1234567", "businessName" => "test business name", } shop = "testshop2.myshopify.com" stub_db_setup(shop: shop, organization_id: test_org["id"]) ShopifyCli::PartnersAPI::Organizations.expects(:fetch) .with(@context, id: test_org["id"]) .once .returns(test_org) io = capture_io { run_cmd("whoami") } assert_message_output( io: io, expected_content: [ @context.message("core.whoami.logged_in_partner_and_shop", shop, test_org["businessName"]), ] ) end private def stub_db_setup(shop:, organization_id:) ShopifyCli::DB.stubs(:get).with(:shop).returns(shop) ShopifyCli::DB.stubs(:get).with(:organization_id).returns(organization_id) end end end end
29.154762
103
0.587178
f8541c1c366e5987f1a3aef377d5f1306ba250a9
87
# desc "Explaining what the task does" # task :rpush_web do # # Task goes here # end
17.4
38
0.678161
08b161ded70045d61822aac957e031c05436adfd
848
Sequel.migration do up do alter_table(:mr_bulk_stock_adjustment_items) do add_column :old_product_code, String, text: true end unless ENV['RACK_ENV'] == 'test' run <<~SQL UPDATE mr_bulk_stock_adjustment_items SET old_product_code = (select material_resource_product_variants.old_product_code from mr_bulk_stock_adjustment_items bi join mr_skus on mr_skus.id = bi.mr_sku_id join material_resource_product_variants on mr_skus.mr_product_variant_id = material_resource_product_variants.id WHERE bi.id = mr_bulk_stock_adjustment_items.id); SQL end end down do alter_table(:mr_bulk_stock_adjustment_items) do drop_column :old_product_code end end end
33.92
144
0.652123
2660943d2d585e8cbd0dfcdb9175fa305cdf9e44
741
class AddCheckTemplates < ActiveRecord::Migration def up create_table :check_templates do |t| t.integer :org_id, :null => true t.string :name, :limit => 255, :null => false t.integer :mode, :limit => 2, :null => false t.string :tags, :limit => 255, :null => true end add_foreign_key("check_templates", "orgs") create_table :check_template_items do |t| t.integer :check_template_id, :null => false t.integer :command_id, :null => false t.text :args end add_foreign_key("check_template_items", "check_templates") add_foreign_key("check_template_items", "commands") end def down drop_table :check_template_items drop_table :check_templates end end
27.444444
62
0.662618
e9ae55370218160b4086f9cafd6a7496d2774ffa
1,078
class Darkstat < Formula desc "Network traffic analyzer" homepage "https://unix4lyfe.org/darkstat/" url "https://unix4lyfe.org/darkstat/darkstat-3.0.719.tar.bz2" sha256 "aeaf909585f7f43dc032a75328fdb62114e58405b06a92a13c0d3653236dedd7" bottle do cellar :any_skip_relocation sha256 "8cfff973e95ff4c31248690df0ae28e05ddbef97f926ed4f075b919274c59116" => :el_capitan sha256 "290629ecfb0a650104bd6560bb352af9b54e2d0c1e1e0de0d7113dab13167133" => :yosemite sha256 "c613e70eb9f84aa7acaef6f1791495762537ab0fe12368ddec009a66fb91d3f8" => :mavericks sha256 "fba985f30c240602c9b5ebccda87fcea7c52caba69c4c8cc5375e090a773ce19" => :mountain_lion end head do url "https://www.unix4lyfe.org/git/darkstat", :using => :git depends_on "automake" => :build depends_on "autoconf" => :build end def install system "autoreconf", "-iv" if build.head? system "./configure", "--disable-debug", "--prefix=#{prefix}" system "make", "install" end test do system sbin/"darkstat", "--verbose", "-r", test_fixtures("test.pcap") end end
34.774194
95
0.747681
33e1a2ec8870ac5231e7ac9af7561b21595fd243
32,604
# WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE module Aws::AutoScaling class Resource # @param options ({}) # @option options [Client] :client def initialize(options = {}) @client = options[:client] || Client.new(options) end # @return [Client] def client @client end # @!group Actions # @example Request syntax with placeholder values # # autoscalinggroup = auto_scaling.create_group({ # auto_scaling_group_name: "XmlStringMaxLen255", # required # launch_configuration_name: "ResourceName", # launch_template: { # launch_template_id: "XmlStringMaxLen255", # launch_template_name: "LaunchTemplateName", # version: "XmlStringMaxLen255", # }, # mixed_instances_policy: { # launch_template: { # launch_template_specification: { # launch_template_id: "XmlStringMaxLen255", # launch_template_name: "LaunchTemplateName", # version: "XmlStringMaxLen255", # }, # overrides: [ # { # instance_type: "XmlStringMaxLen255", # }, # ], # }, # instances_distribution: { # on_demand_allocation_strategy: "XmlString", # on_demand_base_capacity: 1, # on_demand_percentage_above_base_capacity: 1, # spot_allocation_strategy: "XmlString", # spot_instance_pools: 1, # spot_max_price: "MixedInstanceSpotPrice", # }, # }, # instance_id: "XmlStringMaxLen19", # min_size: 1, # required # max_size: 1, # required # desired_capacity: 1, # default_cooldown: 1, # availability_zones: ["XmlStringMaxLen255"], # load_balancer_names: ["XmlStringMaxLen255"], # target_group_arns: ["XmlStringMaxLen511"], # health_check_type: "XmlStringMaxLen32", # health_check_grace_period: 1, # placement_group: "XmlStringMaxLen255", # vpc_zone_identifier: "XmlStringMaxLen2047", # termination_policies: ["XmlStringMaxLen1600"], # new_instances_protected_from_scale_in: false, # lifecycle_hook_specification_list: [ # { # lifecycle_hook_name: "AsciiStringMaxLen255", # required # lifecycle_transition: "LifecycleTransition", # required # notification_metadata: "XmlStringMaxLen1023", # heartbeat_timeout: 1, # default_result: "LifecycleActionResult", # notification_target_arn: "NotificationTargetResourceName", # role_arn: "ResourceName", # }, # ], # tags: [ # { # resource_id: "XmlString", # resource_type: "XmlString", # key: "TagKey", # required # value: "TagValue", # propagate_at_launch: false, # }, # ], # service_linked_role_arn: "ResourceName", # }) # @param [Hash] options ({}) # @option options [required, String] :auto_scaling_group_name # The name of the Auto Scaling group. This name must be unique within # the scope of your AWS account. # @option options [String] :launch_configuration_name # The name of the launch configuration. This parameter, a launch # template, a mixed instances policy, or an EC2 instance must be # specified. # # For more information, see [Creating an Auto Scaling Group Using a # Launch Configuration][1] in the *Amazon EC2 Auto Scaling User Guide*. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-asg.html # @option options [Types::LaunchTemplateSpecification] :launch_template # The launch template to use to launch instances. This parameter, a # launch configuration, a mixed instances policy, or an EC2 instance # must be specified. # # For more information, see [Creating an Auto Scaling Group Using a # Launch Template][1] in the *Amazon EC2 Auto Scaling User Guide*. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-asg-launch-template.html # @option options [Types::MixedInstancesPolicy] :mixed_instances_policy # The mixed instances policy to use to launch instances. This parameter, # a launch template, a launch configuration, or an EC2 instance must be # specified. # # For more information, see [Auto Scaling Groups with Multiple Instance # Types and Purchase Options][1] in the *Amazon EC2 Auto Scaling User # Guide*. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-purchase-options.html # @option options [String] :instance_id # The ID of the instance used to create a launch configuration for the # group. This parameter, a launch configuration, a launch template, or a # mixed instances policy must be specified. # # When you specify an ID of an instance, Amazon EC2 Auto Scaling creates # a new launch configuration and associates it with the group. This # launch configuration derives its attributes from the specified # instance, except for the block device mapping. # # For more information, see [Create an Auto Scaling Group Using an EC2 # Instance][1] in the *Amazon EC2 Auto Scaling User Guide*. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-asg-from-instance.html # @option options [required, Integer] :min_size # The minimum size of the group. # @option options [required, Integer] :max_size # The maximum size of the group. # @option options [Integer] :desired_capacity # The number of EC2 instances that should be running in the group. This # number must be greater than or equal to the minimum size of the group # and less than or equal to the maximum size of the group. If you do not # specify a desired capacity, the default is the minimum size of the # group. # @option options [Integer] :default_cooldown # The amount of time, in seconds, after a scaling activity completes # before another scaling activity can start. The default value is `300`. # # For more information, see [Scaling Cooldowns][1] in the *Amazon EC2 # Auto Scaling User Guide*. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/Cooldown.html # @option options [Array<String>] :availability_zones # One or more Availability Zones for the group. This parameter is # optional if you specify one or more subnets for `VPCZoneIdentifier`. # # Conditional: If your account supports EC2-Classic and VPC, this # parameter is required to launch instances into EC2-Classic. # @option options [Array<String>] :load_balancer_names # One or more Classic Load Balancers. To specify an Application Load # Balancer or a Network Load Balancer, use `TargetGroupARNs` instead. # # For more information, see [Using a Load Balancer With an Auto Scaling # Group][1] in the *Amazon EC2 Auto Scaling User Guide*. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-load-balancer.html # @option options [Array<String>] :target_group_arns # The Amazon Resource Names (ARN) of the target groups. # @option options [String] :health_check_type # The service to use for the health checks. The valid values are `EC2` # and `ELB`. The default value is `EC2`. If you configure an Auto # Scaling group to use ELB health checks, it considers the instance # unhealthy if it fails either the EC2 status checks or the load # balancer health checks. # # For more information, see [Health Checks for Auto Scaling # Instances][1] in the *Amazon EC2 Auto Scaling User Guide*. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/healthcheck.html # @option options [Integer] :health_check_grace_period # The amount of time, in seconds, that Amazon EC2 Auto Scaling waits # before checking the health status of an EC2 instance that has come # into service. During this time, any health check failures for the # instance are ignored. The default value is `0`. # # For more information, see [Health Checks for Auto Scaling # Instances][1] in the *Amazon EC2 Auto Scaling User Guide*. # # Conditional: This parameter is required if you are adding an `ELB` # health check. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/healthcheck.html # @option options [String] :placement_group # The name of the placement group into which to launch your instances, # if any. A placement group is a logical grouping of instances within a # single Availability Zone. You cannot specify multiple Availability # Zones and a placement group. For more information, see [Placement # Groups][1] in the *Amazon EC2 User Guide for Linux Instances*. # # # # [1]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html # @option options [String] :vpc_zone_identifier # A comma-separated list of subnet IDs for your virtual private cloud # (VPC). # # If you specify `VPCZoneIdentifier` with `AvailabilityZones`, the # subnets that you specify for this parameter must reside in those # Availability Zones. # # Conditional: If your account supports EC2-Classic and VPC, this # parameter is required to launch instances into a VPC. # @option options [Array<String>] :termination_policies # One or more termination policies used to select the instance to # terminate. These policies are executed in the order that they are # listed. # # For more information, see [Controlling Which Instances Auto Scaling # Terminates During Scale In][1] in the *Amazon EC2 Auto Scaling User # Guide*. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-termination.html # @option options [Boolean] :new_instances_protected_from_scale_in # Indicates whether newly launched instances are protected from # termination by Amazon EC2 Auto Scaling when scaling in. # # For more information about preventing instances from terminating on # scale in, see [Instance Protection][1] in the *Amazon EC2 Auto Scaling # User Guide*. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-termination.html#instance-protection # @option options [Array<Types::LifecycleHookSpecification>] :lifecycle_hook_specification_list # One or more lifecycle hooks. # @option options [Array<Types::Tag>] :tags # One or more tags. # # For more information, see [Tagging Auto Scaling Groups and # Instances][1] in the *Amazon EC2 Auto Scaling User Guide*. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html # @option options [String] :service_linked_role_arn # The Amazon Resource Name (ARN) of the service-linked role that the # Auto Scaling group uses to call other AWS services on your behalf. By # default, Amazon EC2 Auto Scaling uses a service-linked role named # AWSServiceRoleForAutoScaling, which it creates if it does not exist. # For more information, see [Service-Linked Roles][1] in the *Amazon EC2 # Auto Scaling User Guide*. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-service-linked-role.html # @return [AutoScalingGroup] def create_group(options = {}) resp = @client.create_auto_scaling_group(options) AutoScalingGroup.new( name: options[:auto_scaling_group_name], client: @client ) end # @example Request syntax with placeholder values # # launchconfiguration = auto_scaling.create_launch_configuration({ # launch_configuration_name: "XmlStringMaxLen255", # required # image_id: "XmlStringMaxLen255", # key_name: "XmlStringMaxLen255", # security_groups: ["XmlString"], # classic_link_vpc_id: "XmlStringMaxLen255", # classic_link_vpc_security_groups: ["XmlStringMaxLen255"], # user_data: "XmlStringUserData", # instance_id: "XmlStringMaxLen19", # instance_type: "XmlStringMaxLen255", # kernel_id: "XmlStringMaxLen255", # ramdisk_id: "XmlStringMaxLen255", # block_device_mappings: [ # { # virtual_name: "XmlStringMaxLen255", # device_name: "XmlStringMaxLen255", # required # ebs: { # snapshot_id: "XmlStringMaxLen255", # volume_size: 1, # volume_type: "BlockDeviceEbsVolumeType", # delete_on_termination: false, # iops: 1, # encrypted: false, # }, # no_device: false, # }, # ], # instance_monitoring: { # enabled: false, # }, # spot_price: "SpotPrice", # iam_instance_profile: "XmlStringMaxLen1600", # ebs_optimized: false, # associate_public_ip_address: false, # placement_tenancy: "XmlStringMaxLen64", # }) # @param [Hash] options ({}) # @option options [required, String] :launch_configuration_name # The name of the launch configuration. This name must be unique within # the scope of your AWS account. # @option options [String] :image_id # The ID of the Amazon Machine Image (AMI) to use to launch your EC2 # instances. # # If you do not specify `InstanceId`, you must specify `ImageId`. # # For more information, see [Finding an AMI][1] in the *Amazon EC2 User # Guide for Linux Instances*. # # # # [1]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html # @option options [String] :key_name # The name of the key pair. For more information, see [Amazon EC2 Key # Pairs][1] in the *Amazon EC2 User Guide for Linux Instances*. # # # # [1]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html # @option options [Array<String>] :security_groups # One or more security groups with which to associate the instances. # # If your instances are launched in EC2-Classic, you can either specify # security group names or the security group IDs. For more information, # see [Amazon EC2 Security Groups][1] in the *Amazon EC2 User Guide for # Linux Instances*. # # If your instances are launched into a VPC, specify security group IDs. # For more information, see [Security Groups for Your VPC][2] in the # *Amazon Virtual Private Cloud User Guide*. # # # # [1]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html # [2]: https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html # @option options [String] :classic_link_vpc_id # The ID of a ClassicLink-enabled VPC to link your EC2-Classic instances # to. This parameter is supported only if you are launching EC2-Classic # instances. For more information, see [ClassicLink][1] in the *Amazon # EC2 User Guide for Linux Instances* and [Linking EC2-Classic Instances # to a VPC][2] in the *Amazon EC2 Auto Scaling User Guide*. # # # # [1]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html # [2]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-in-vpc.html#as-ClassicLink # @option options [Array<String>] :classic_link_vpc_security_groups # The IDs of one or more security groups for the specified # ClassicLink-enabled VPC. For more information, see [ClassicLink][1] in # the *Amazon EC2 User Guide for Linux Instances* and [Linking # EC2-Classic Instances to a VPC][2] in the *Amazon EC2 Auto Scaling # User Guide*. # # Conditional: This parameter is required if you specify a # ClassicLink-enabled VPC, and is not supported otherwise. # # # # [1]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html # [2]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-in-vpc.html#as-ClassicLink # @option options [String] :user_data # The user data to make available to the launched EC2 instances. For # more information, see [Instance Metadata and User Data][1] in the # *Amazon EC2 User Guide for Linux Instances*. # # # # [1]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html # @option options [String] :instance_id # The ID of the instance to use to create the launch configuration. The # new launch configuration derives attributes from the instance, except # for the block device mapping. # # If you do not specify `InstanceId`, you must specify both `ImageId` # and `InstanceType`. # # To create a launch configuration with a block device mapping or # override any other instance attributes, specify them as part of the # same request. # # For more information, see [Create a Launch Configuration Using an EC2 # Instance][1] in the *Amazon EC2 Auto Scaling User Guide*. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-lc-with-instanceID.html # @option options [String] :instance_type # The instance type of the EC2 instance. # # If you do not specify `InstanceId`, you must specify `InstanceType`. # # For information about available instance types, see [Available # Instance Types][1] in the *Amazon EC2 User Guide for Linux Instances.* # # # # [1]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#AvailableInstanceTypes # @option options [String] :kernel_id # The ID of the kernel associated with the AMI. # @option options [String] :ramdisk_id # The ID of the RAM disk associated with the AMI. # @option options [Array<Types::BlockDeviceMapping>] :block_device_mappings # One or more mappings that specify how block devices are exposed to the # instance. For more information, see [Block Device Mapping][1] in the # *Amazon EC2 User Guide for Linux Instances*. # # # # [1]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html # @option options [Types::InstanceMonitoring] :instance_monitoring # Enables detailed monitoring (`true`) or basic monitoring (`false`) for # the Auto Scaling instances. The default value is `true`. # @option options [String] :spot_price # The maximum hourly price to be paid for any Spot Instance launched to # fulfill the request. Spot Instances are launched when the price you # specify exceeds the current Spot market price. For more information, # see [Launching Spot Instances in Your Auto Scaling Group][1] in the # *Amazon EC2 Auto Scaling User Guide*. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-launch-spot-instances.html # @option options [String] :iam_instance_profile # The name or the Amazon Resource Name (ARN) of the instance profile # associated with the IAM role for the instance. # # EC2 instances launched with an IAM role automatically have AWS # security credentials available. You can use IAM roles with Amazon EC2 # Auto Scaling to automatically enable applications running on your EC2 # instances to securely access other AWS resources. For more # information, see [Use an IAM Role for Applications That Run on Amazon # EC2 Instances][1] in the *Amazon EC2 Auto Scaling User Guide*. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/us-iam-role.html # @option options [Boolean] :ebs_optimized # Indicates whether the instance is optimized for Amazon EBS I/O. By # default, the instance is not optimized for EBS I/O. The optimization # provides dedicated throughput to Amazon EBS and an optimized # configuration stack to provide optimal I/O performance. This # optimization is not available with all instance types. Additional # usage charges apply. For more information, see [Amazon EBS-Optimized # Instances][1] in the *Amazon EC2 User Guide for Linux Instances*. # # # # [1]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html # @option options [Boolean] :associate_public_ip_address # Used for groups that launch instances into a virtual private cloud # (VPC). Specifies whether to assign a public IP address to each # instance. For more information, see [Launching Auto Scaling Instances # in a VPC][1] in the *Amazon EC2 Auto Scaling User Guide*. # # If you specify this parameter, be sure to specify at least one subnet # when you create your group. # # Default: If the instance is launched into a default subnet, the # default is to assign a public IP address. If the instance is launched # into a nondefault subnet, the default is not to assign a public IP # address. # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-in-vpc.html # @option options [String] :placement_tenancy # The tenancy of the instance. An instance with a tenancy of `dedicated` # runs on single-tenant hardware and can only be launched into a VPC. # # To launch Dedicated Instances into a shared tenancy VPC (a VPC with # the instance placement tenancy attribute set to `default`), you must # set the value of this parameter to `dedicated`. # # If you specify this parameter, be sure to specify at least one subnet # when you create your group. # # For more information, see [Launching Auto Scaling Instances in a # VPC][1] in the *Amazon EC2 Auto Scaling User Guide*. # # Valid values: `default` \| `dedicated` # # # # [1]: https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-in-vpc.html # @return [LaunchConfiguration] def create_launch_configuration(options = {}) resp = @client.create_launch_configuration(options) LaunchConfiguration.new( name: options[:launch_configuration_name], client: @client ) end # @!group Associations # @example Request syntax with placeholder values # # activities = auto_scaling.activities({ # activity_ids: ["XmlString"], # auto_scaling_group_name: "ResourceName", # }) # @param [Hash] options ({}) # @option options [Array<String>] :activity_ids # The activity IDs of the desired scaling activities. You can specify up # to 50 IDs. If you omit this parameter, all activities for the past six # weeks are described. If unknown activities are requested, they are # ignored with no error. If you specify an Auto Scaling group, the # results are limited to that group. # @option options [String] :auto_scaling_group_name # The name of the Auto Scaling group. # @return [Activity::Collection] def activities(options = {}) batches = Enumerator.new do |y| resp = @client.describe_scaling_activities(options) resp.each_page do |page| batch = [] page.data.activities.each do |a| batch << Activity.new( id: a.activity_id, data: a, client: @client ) end y.yield(batch) end end Activity::Collection.new(batches) end # @param [String] id # @return [Activity] def activity(id) Activity.new( id: id, client: @client ) end # @param [String] name # @return [AutoScalingGroup] def group(name) AutoScalingGroup.new( name: name, client: @client ) end # @example Request syntax with placeholder values # # groups = auto_scaling.groups({ # auto_scaling_group_names: ["ResourceName"], # }) # @param [Hash] options ({}) # @option options [Array<String>] :auto_scaling_group_names # The names of the Auto Scaling groups. Each name can be a maximum of # 1600 characters. By default, you can only specify up to 50 names. You # can optionally increase this limit using the `MaxRecords` parameter. # # If you omit this parameter, all Auto Scaling groups are described. # @return [AutoScalingGroup::Collection] def groups(options = {}) batches = Enumerator.new do |y| resp = @client.describe_auto_scaling_groups(options) resp.each_page do |page| batch = [] page.data.auto_scaling_groups.each do |a| batch << AutoScalingGroup.new( name: a.auto_scaling_group_name, data: a, client: @client ) end y.yield(batch) end end AutoScalingGroup::Collection.new(batches) end # @example Request syntax with placeholder values # # instances = auto_scaling.instances({ # instance_ids: ["XmlStringMaxLen19"], # }) # @param [Hash] options ({}) # @option options [Array<String>] :instance_ids # The IDs of the instances. You can specify up to `MaxRecords` IDs. If # you omit this parameter, all Auto Scaling instances are described. If # you specify an ID that does not exist, it is ignored with no error. # @return [Instance::Collection] def instances(options = {}) batches = Enumerator.new do |y| resp = @client.describe_auto_scaling_instances(options) resp.each_page do |page| batch = [] page.data.auto_scaling_instances.each do |a| batch << Instance.new( group_name: a.auto_scaling_group_name, id: a.instance_id, data: a, client: @client ) end y.yield(batch) end end Instance::Collection.new(batches) end # @param [String] name # @return [LaunchConfiguration] def launch_configuration(name) LaunchConfiguration.new( name: name, client: @client ) end # @example Request syntax with placeholder values # # launch_configurations = auto_scaling.launch_configurations({ # launch_configuration_names: ["ResourceName"], # }) # @param [Hash] options ({}) # @option options [Array<String>] :launch_configuration_names # The launch configuration names. If you omit this parameter, all launch # configurations are described. # @return [LaunchConfiguration::Collection] def launch_configurations(options = {}) batches = Enumerator.new do |y| resp = @client.describe_launch_configurations(options) resp.each_page do |page| batch = [] page.data.launch_configurations.each do |l| batch << LaunchConfiguration.new( name: l.launch_configuration_name, data: l, client: @client ) end y.yield(batch) end end LaunchConfiguration::Collection.new(batches) end # @example Request syntax with placeholder values # # policies = auto_scaling.policies({ # auto_scaling_group_name: "ResourceName", # policy_names: ["ResourceName"], # policy_types: ["XmlStringMaxLen64"], # }) # @param [Hash] options ({}) # @option options [String] :auto_scaling_group_name # The name of the Auto Scaling group. # @option options [Array<String>] :policy_names # The names of one or more policies. If you omit this parameter, all # policies are described. If a group name is provided, the results are # limited to that group. This list is limited to 50 items. If you # specify an unknown policy name, it is ignored with no error. # @option options [Array<String>] :policy_types # One or more policy types. The valid values are `SimpleScaling`, # `StepScaling`, and `TargetTrackingScaling`. # @return [ScalingPolicy::Collection] def policies(options = {}) batches = Enumerator.new do |y| resp = @client.describe_policies(options) resp.each_page do |page| batch = [] page.data.scaling_policies.each do |s| batch << ScalingPolicy.new( name: s.policy_name, data: s, client: @client ) end y.yield(batch) end end ScalingPolicy::Collection.new(batches) end # @param [String] name # @return [ScalingPolicy] def policy(name) ScalingPolicy.new( name: name, client: @client ) end # @param [String] name # @return [ScheduledAction] def scheduled_action(name) ScheduledAction.new( name: name, client: @client ) end # @example Request syntax with placeholder values # # scheduled_actions = auto_scaling.scheduled_actions({ # auto_scaling_group_name: "ResourceName", # scheduled_action_names: ["ResourceName"], # start_time: Time.now, # end_time: Time.now, # }) # @param [Hash] options ({}) # @option options [String] :auto_scaling_group_name # The name of the Auto Scaling group. # @option options [Array<String>] :scheduled_action_names # The names of one or more scheduled actions. You can specify up to 50 # actions. If you omit this parameter, all scheduled actions are # described. If you specify an unknown scheduled action, it is ignored # with no error. # @option options [Time,DateTime,Date,Integer,String] :start_time # The earliest scheduled start time to return. If scheduled action names # are provided, this parameter is ignored. # @option options [Time,DateTime,Date,Integer,String] :end_time # The latest scheduled start time to return. If scheduled action names # are provided, this parameter is ignored. # @return [ScheduledAction::Collection] def scheduled_actions(options = {}) batches = Enumerator.new do |y| resp = @client.describe_scheduled_actions(options) resp.each_page do |page| batch = [] page.data.scheduled_update_group_actions.each do |s| batch << ScheduledAction.new( name: s.scheduled_action_name, data: s, client: @client ) end y.yield(batch) end end ScheduledAction::Collection.new(batches) end # @example Request syntax with placeholder values # # tags = auto_scaling.tags({ # filters: [ # { # name: "XmlString", # values: ["XmlString"], # }, # ], # }) # @param [Hash] options ({}) # @option options [Array<Types::Filter>] :filters # One or more filters to scope the tags to return. The maximum number of # filters per filter type (for example, `auto-scaling-group`) is 1000. # @return [Tag::Collection] def tags(options = {}) batches = Enumerator.new do |y| resp = @client.describe_tags(options) resp.each_page do |page| batch = [] page.data.tags.each do |t| batch << Tag.new( key: t.key, resource_id: t.resource_id, resource_type: t.resource_type, data: t, client: @client ) end y.yield(batch) end end Tag::Collection.new(batches) end end end
40.451613
115
0.639983
d5c1eb7944fb328dc9444d03b11cd6a63301432a
514
module Tensorflow module Keras module Datasets module MNIST def self.load_data(path: "mnist.npz") file = Utils.get_file( path, "https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz", file_hash: "731c5ac602752760c8e48fbffcf8c3b850d9dc2a2aedcf2cc48468fc17b673d1" ) data = Npy.load_npz(file) [[data["x_train"], data["y_train"]], [data["x_test"], data["y_test"]]] end end end end end
27.052632
89
0.599222
ffcb499801236031557af84cacb32f3b7aec68ed
2,475
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Standard rails dev caching behaviour # if Rails.root.join('tmp', 'caching-dev.txt').exist? # config.action_controller.perform_caching = true # config.cache_store = :memory_store # config.public_file_server.headers = { # 'Cache-Control' => "public, max-age=#{2.days.to_i}" # } # else # config.action_controller.perform_caching = false # config.cache_store = :null_store # end # Using cache for sessions and permissions forces to use redis cache_store as mandatory store # Here we use ENV.fetch instead of Barong::App.config, because environment/* files loads before lib and initializers config.cache_store = :redis_cache_store, { driver: :hiredis, url: ENV.fetch('BARONG_REDIS_URL', 'redis://localhost:6379/1') } # Store uploaded files on the local file system (see config/storage.yml for options) config.active_storage.service = :local # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Highlight code that triggered database queries in logs. config.active_record.verbose_query_logs = true # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker end
39.285714
127
0.75798
1a240126dc06358d7dc2f3b81a2bc6406de85464
588
ENV["RAILS_ENV"] ||= "test" require_relative "../config/environment" require "rails/test_help" class ActiveSupport::TestCase fixtures :all include ApplicationHelper def is_logged_in? session[:user_id].present? end def log_in_as user session[:user_id] = user.id end end class ActionDispatch::IntegrationTest def log_in_as user, password: "password", remember_me: "1" post login_path, params: {session: {email: user.email, password: password, remember_me: remember_me}} end end
23.52
66
0.637755
1d743113e72cc4ae78ea97bf713582bffc24d038
376
class FixProjectsStates < ActiveRecord::Migration def up execute " UPDATE projects SET state = 'waiting_funds' WHERE state IN ('successful', 'online') AND current_timestamp BETWEEN expires_at and expires_at + '4 day'::interval; UPDATE projects SET state = 'online' WHERE state = 'successful' AND current_timestamp < expires_at; " end def down end end
31.333333
164
0.728723
38eb6e588ddbb243daff64be46e7f359716b620e
16,258
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright 2019 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. # # Tests the LoggingInterceptor class. require 'minitest/autorun' require 'google/ads/google_ads' require 'google/ads/google_ads/interceptors/logging_interceptor' require 'google/ads/google_ads/v6/services/media_file_service_services_pb' require 'google/ads/google_ads/v6/services/customer_user_access_service_services_pb' require 'google/ads/google_ads/v6/services/google_ads_service_services_pb' require 'google/ads/google_ads/v6/services/feed_service_services_pb' require 'google/ads/google_ads/v6/services/customer_service_services_pb' require 'google/ads/google_ads/v6/resources/customer_user_access_pb' require 'google/ads/google_ads/v6/resources/change_event_pb' require 'google/ads/google_ads/v6/resources/feed_pb' class TestLoggingInterceptor < Minitest::Test attr_reader :sio attr_reader :logger attr_reader :li def setup @sio = StringIO.new @logger = Logger.new(sio) @li = Google::Ads::GoogleAds::Interceptors::LoggingInterceptor.new(logger) end def test_logging_interceptor_logs_na_customer_id_with_missing_customer_id li.request_response( request: make_request_with_no_customer_id, call: make_fake_call, method: :doesnt_matter, ) do end sio.rewind assert_includes(sio.read, "CID: N/A") end def test_logging_interceptor_logs_customer_id customer_id = "123" li.request_response( request: make_request(customer_id: customer_id), call: make_fake_call, method: :doesnt_matter, ) do end sio.rewind assert_includes(sio.read, "CID: #{customer_id}") end def test_logging_interceptor_logs_host host = "example.com" li.request_response( request: make_request, call: make_fake_call(host: host), method: :doesnt_matter, ) do end sio.rewind assert_includes(sio.read, "Host: #{host}") end def test_logging_interceptor_logs_method method = :method li.request_response( request: make_request, call: make_fake_call, method: method, ) do end sio.rewind assert_includes(sio.read, "Method: #{method}") end def test_logging_interceptor_inspects_request li.request_response( request: make_request, call: make_fake_call, method: :doesnt_matter, ) do end sio.rewind assert_includes(sio.read, "Google::Ads::GoogleAds::V6::Services::MutateMediaFilesRequest") end def test_logging_interceptor_logs_isfault_no li.request_response( request: make_request, call: make_fake_call, method: :doesnt_matter, ) do end sio.rewind assert_includes(sio.read, "IsFault: no") end def test_logging_interceptor_logs_isfault_yes_when_call_explodes li.request_response( request: make_request, call: make_fake_call, method: :doesnt_matter, ) do raise "boom" end rescue Exception => e if e.message != "boom" raise end sio.rewind assert_includes(sio.read, "IsFault: yes") end def test_logging_interceptor_logs_response li.request_response( request: make_request, call: make_fake_call, method: :doesnt_matter, ) do Google::Protobuf::StringValue.new(value: "some data") end sio.rewind assert_includes(sio.read, JSON.dump("some data")) end def test_logging_interceptor_logs_some_error_details_if_v6_error li.request_response( request: make_small_request, call: make_fake_call, method: :doesnt_matter, ) do raise make_realistic_error("v6") end rescue GRPC::InvalidArgument sio.rewind assert_includes(sio.read, "InvalidArgument(3:bees)") end def test_logging_interceptor_logs_error_details_if_partial_failure li.request_response( request: make_small_request, call: make_fake_call, method: :doesnt_matter, ) do make_realistic_response_with_partial_error end sio.rewind data = sio.read assert_includes(data, "Partial failure errors: ") assert_includes(data, "required field was not specified") end def test_logging_interceptor_can_serialize_images # this test segfaults the ruby virtual machine before c26ae44 li.request_response( request: make_request, call: make_fake_call, method: :doesnt_matter ) do end end def test_logging_interceptor_sanitizes_dev_token li.request_response( request: make_request, call: make_fake_call, method: :doesnt_matter, metadata: {:"developer-token" => "abcd"} ) do end sio.rewind data = sio.read assert(!data.include?("abcd")) assert_includes(data, "REDACTED") end def test_logging_interceptor_sanitizes_customer_user_access_response email_address = "abcdefghijkl" inviter_user = "zyxwvutsr" li.request_response( request: make_request, call: make_fake_call, method: :doesnt_matter ) do Google::Ads::GoogleAds::V6::Resources::CustomerUserAccess.new( email_address: email_address, inviter_user_email_address: inviter_user, ) end sio.rewind data = sio.read assert(!data.include?(email_address), "Failed to remove email address.") assert(!data.include?(inviter_user), "Failed to remove inviter user email address.") assert_includes(data, "REDACTED") end def test_logging_interceptor_sanitizes_customer_user_access_mutate email_address = "abcdefghijkl" inviter_user = "zyxwvutsr" request = Google::Ads::GoogleAds::V6::Services::MutateCustomerUserAccessRequest.new( operation: Google::Ads::GoogleAds::V6::Services::CustomerUserAccessOperation.new( update: Google::Ads::GoogleAds::V6::Resources::CustomerUserAccess.new( email_address: email_address, inviter_user_email_address: inviter_user, ) ) ) li.request_response( request: request, call: make_fake_call, method: :doesnt_matter ) do end sio.rewind data = sio.read assert(!data.include?(email_address), "Failed to remove email address.") assert(!data.include?(inviter_user), "Failed to remove inviter user email address.") assert_includes(data, "REDACTED") end def test_logging_interceptor_sanitizes_feed_get email_address = "abcdefghijkl" li.request_response( request: make_request, call: make_fake_call, method: :doesnt_matter ) do Google::Ads::GoogleAds::V6::Resources::Feed.new( places_location_feed_data: Google::Ads::GoogleAds::V6:: Resources::Feed::PlacesLocationFeedData.new( email_address: email_address, ), ) end sio.rewind data = sio.read assert(!data.include?(email_address), "Failed to remove email address.") assert_includes(data, "REDACTED") end def test_logging_interceptor_sanitizes_feed_mutate_request email_address = "abcdefghijkl" email_address_2 = "zyxwvutsr" li.request_response( request: Google::Ads::GoogleAds::V6::Services::MutateFeedsRequest.new( operations: [ Google::Ads::GoogleAds::V6::Services::FeedOperation.new( create: Google::Ads::GoogleAds::V6::Resources::Feed.new( places_location_feed_data: Google::Ads::GoogleAds::V6:: Resources::Feed::PlacesLocationFeedData.new( email_address: email_address, ), ), ), Google::Ads::GoogleAds::V6::Services::FeedOperation.new( create: Google::Ads::GoogleAds::V6::Resources::Feed.new( places_location_feed_data: Google::Ads::GoogleAds::V6:: Resources::Feed::PlacesLocationFeedData.new( email_address: email_address_2, ), ), ), ] ), call: make_fake_call, method: :doesnt_matter, ) do end sio.rewind data = sio.read assert(!data.include?(email_address), "Failed to remove email address.") assert(!data.include?(email_address_2), "Failed to remove email address.") assert_includes(data, "REDACTED") end def test_logging_interceptor_sanitizes_customer_client_create_request email_address = "abcdefghijkl" li.request_response( request: Google::Ads::GoogleAds::V6::Services::CreateCustomerClientRequest.new( email_address: email_address, ), call: make_fake_call, method: :doesnt_matter, ) do end sio.rewind data = sio.read assert(!data.include?(email_address), "Failed to remove email address.") assert_includes(data, "REDACTED") end def test_logging_interceptor_sanitizes_search_request li.request_response( request: Google::Ads::GoogleAds::V6::Services::SearchGoogleAdsRequest.new( query: "SELECT change_event.user_email FROM change_event", ), call: make_fake_call, method: :doesnt_matter ) do end sio.rewind data = sio.read assert(!data.include?("user_email"), "Failed to remove query containing user email.") assert_includes(data, "REDACTED") end def test_logging_interceptor_sanitizes_search_stream_request li.request_response( request: Google::Ads::GoogleAds::V6::Services::SearchGoogleAdsStreamRequest.new( query: "SELECT change_event.user_email FROM change_event", ), call: make_fake_call, method: :doesnt_matter ) do end sio.rewind data = sio.read assert(!data.include?("user_email"), "Failed to remove query containing user email.") assert_includes(data, "REDACTED") end def test_logging_interceptor_sanitizes_search_response email_address = "UNIQUE-STRING-ONE" inviter_user = "UNIQUE-STRING-TWO" user_email = "UNIQUE-STRING-THREE" li.request_response( request: make_request, call: make_fake_call, method: :doesnt_matter ) do Google::Ads::GoogleAds::V6::Services::SearchGoogleAdsResponse.new( field_mask: Google::Protobuf::FieldMask.new( paths: [ "customer_user_access.email_address", "customer_user_access.inviter_user_email_address", "change_event.user_email", ] ), results: [ Google::Ads::GoogleAds::V6::Services::GoogleAdsRow.new( customer_user_access: Google::Ads::GoogleAds::V6::Resources::CustomerUserAccess.new( email_address: email_address, inviter_user_email_address: inviter_user, ), change_event: Google::Ads::GoogleAds::V6::Resources::ChangeEvent.new( user_email: user_email, ), ) ] ) end sio.rewind data = sio.read assert(!data.include?(email_address), "Failed to remove email address.") assert(!data.include?(inviter_user), "Failed to remove inviter user email address.") assert(!data.include?(user_email), "Failed to remove change event user email.") assert_includes(data, "REDACTED") end def test_logging_interceptor_sanitizes_search_stream_response email_address = "UNIQUE-STRING-ONE" inviter_user = "UNIQUE-STRING-TWO" user_email = "UNIQUE-STRING-THREE" response = li.server_streamer( request: make_request, call: make_fake_call, method: :doesnt_matter ) do [ Google::Ads::GoogleAds::V6::Services::SearchGoogleAdsStreamResponse.new( field_mask: Google::Protobuf::FieldMask.new( paths: [ "customer_user_access.email_address", "customer_user_access.inviter_user_email_address", "change_event.user_email", ] ), results: [ Google::Ads::GoogleAds::V6::Services::GoogleAdsRow.new( customer_user_access: Google::Ads::GoogleAds::V6::Resources::CustomerUserAccess.new( email_address: email_address, inviter_user_email_address: inviter_user, ), change_event: Google::Ads::GoogleAds::V6::Resources::ChangeEvent.new( user_email: user_email, ), ) ] ) ] end # We need to iterate through all the results to finish logging when streaming. response.each do end sio.rewind data = sio.read assert(!data.include?(email_address), "Failed to remove email address.") assert(!data.include?(inviter_user), "Failed to remove inviter user email address.") assert(!data.include?(user_email), "Failed to remove change event user email.") assert_includes(data, "REDACTED") end def make_fake_call(host: "peer") Class.new do def initialize(host) @wrapped = Struct.new(:peer).new(host) @wrapped.instance_variable_set( :@call, Struct.new(:trailing_metadata).new( {"request-id": "fake-id"} ) ) end end.new(host) end def make_request_with_no_customer_id # this can be literally any protobuf type, because the class's descriptor # is the only method we cal Google::Protobuf::StringValue.new(value: "bees") end def make_realistic_response_with_partial_error Google::Ads::GoogleAds::V6::Services::MutateMediaFilesResponse.new( results: [], partial_failure_error: Google::Rpc::Status.new( code: 13, message: "Multiple errors in ‘details’. First error: A required field was not specified or is an empty string., at operations[0].create.type", details: [ Google::Protobuf::Any.new( type_url: "type.googleapis.com/google.ads.googleads.v6.errors.GoogleAdsFailure", value: "\nh\n\x03\xB0\x05\x06\x129A required field was not specified or is an empty string.\x1A\x02*\x00\"\"\x12\x0E\n\noperations\x12\x00\x12\b\n\x06create\x12\x06\n\x04type\n=\n\x02P\x02\x12\x1FAn internal error has occurred.\x1A\x02*\x00\"\x12\x12\x10\n\noperations\x12\x02\b\x01".b ) ] ) ) end def make_small_request(customer_id: "123") Google::Ads::GoogleAds::V6::Services::MutateMediaFilesRequest.new( customer_id: customer_id, operations: [ Google::Ads::GoogleAds::V6::Services::MediaFileOperation.new( create: Google::Ads::GoogleAds::V6::Resources::MediaFile.new( image: Google::Ads::GoogleAds::V6::Resources::MediaImage.new( data: File.open("test/fixtures/sam.jpg", "rb").read[0..10] ) ) ) ] ) end def make_realistic_error(version) GRPC::InvalidArgument.new( "bees", make_error_metadata(version), ) end def make_error_metadata(version) { "google.rpc.debuginfo-bin" => "\x12\xA9\x02[ORIGINAL ERROR] generic::invalid_argument: Invalid customer ID 'INSERT_CUSTOMER_ID_HERE'. [google.rpc.error_details_ext] { details { type_url: \"type.googleapis.com/google.ads.googleads.v6.errors.GoogleAdsFailure\" value: \"\\n4\\n\\002\\010\\020\\022.Invalid customer ID \\'INSERT_CUSTOMER_ID_HERE\\'.\" } }", "request-id" =>"btwmoTYjaQE1UwVZnDCGAA", } end def make_request(customer_id: "123123123") Google::Ads::GoogleAds::V6::Services::MutateMediaFilesRequest.new( customer_id: customer_id, operations: [ Google::Ads::GoogleAds::V6::Services::MediaFileOperation.new( create: Google::Ads::GoogleAds::V6::Resources::MediaFile.new( image: Google::Ads::GoogleAds::V6::Resources::MediaImage.new( data: File.open("test/fixtures/sam.jpg", "rb").read ) ) ) ] ) end end
31.507752
360
0.673884
032ad2b77d0fcb4bbc7cc3aad7f226d570cb118e
639
# frozen_string_literal: true module Openpay class Connection def initialize(environment, options = {}) @environment = environment @base_url = "#{@environment.api_url}#{@environment.client_id}" @options = options end def connection Faraday.new(url: @base_url) do |conn| conn.use Faraday::Response::RaiseError conn.options.timeout = @options[:timeout] conn.headers['Authorization'] = @environment.authorization conn.headers['Content-Type'] = 'application/json' conn.headers['User-Agent'] = "Ruby - Openpay SDK v#{Openpay::VERSION}" end end end end
29.045455
78
0.655712
ed183eb8f62ac0ca8a57c4ba1416e2d37142ba91
506
# frozen_string_literal: true require 'cloud_payments/models/model' require 'cloud_payments/models/like_subscription' require 'cloud_payments/models/secure3d' require 'cloud_payments/models/transaction' require 'cloud_payments/models/subscription' require 'cloud_payments/models/order' require 'cloud_payments/models/apple_session' require 'cloud_payments/models/on_recurrent' require 'cloud_payments/models/on_pay' require 'cloud_payments/models/on_fail' require 'cloud_payments/models/on_kassa_receipt'
36.142857
49
0.857708
188996d68cd84bd4c4016ff952d3a2c4d8e0d7ed
5,171
# frozen_string_literal: true module Geos class LineString < Geometry include Enumerable def each if block_given? num_points.times do |n| yield point_n(n) end self else num_points.times.collect { |n| point_n(n) }.to_enum end end if FFIGeos.respond_to?(:GEOSGeomGetNumPoints_r) def num_points FFIGeos.GEOSGeomGetNumPoints_r(Geos.current_handle_pointer, ptr) end else def num_points coord_seq.length end end def point_n(n) raise Geos::IndexBoundsError if n.negative? || n >= num_points cast_geometry_ptr(FFIGeos.GEOSGeomGetPointN_r(Geos.current_handle_pointer, ptr, n), srid_copy: srid) end def [](*args) if args.length == 1 && args.first.is_a?(Numeric) && args.first >= 0 point_n(args.first) else to_a[*args] end end alias slice [] def offset_curve(width, options = {}) options = Constants::BUFFER_PARAM_DEFAULTS.merge(options) cast_geometry_ptr( FFIGeos.GEOSOffsetCurve_r( Geos.current_handle_pointer, ptr, width, options[:quad_segs], options[:join], options[:mitre_limit] ), srid_copy: srid ) end if FFIGeos.respond_to?(:GEOSisClosed_r) def closed? bool_result(FFIGeos.GEOSisClosed_r(Geos.current_handle_pointer, ptr)) end end def to_linear_ring return Geos.create_linear_ring(coord_seq, srid: pick_srid_according_to_policy(srid)) if closed? self_cs = coord_seq.to_a self_cs.push(self_cs[0]) Geos.create_linear_ring(self_cs, srid: pick_srid_according_to_policy(srid)) end def to_polygon to_linear_ring.to_polygon end def dump_points(cur_path = []) cur_path.concat(to_a) end def snap_to_grid!(*args) unless empty? cs = coord_seq.snap_to_grid!(*args) if cs.empty? @ptr = Geos.create_empty_line_string(srid: srid).ptr elsif cs.length <= 1 raise Geos::InvalidGeometryError, "snap_to_grid! produced an invalid number of points in for a LineString - found #{cs.length} - must be 0 or > 1" else @ptr = Geos.create_line_string(cs).ptr end end self end def snap_to_grid(*args) ret = dup.snap_to_grid!(*args) ret.srid = pick_srid_according_to_policy(srid) ret end def line_interpolate_point(fraction) raise ArgumentError, 'fraction must be between 0 and 1' unless fraction.between?(0, 1) case fraction when 0 start_point when 1 end_point else length = self.length total_length = 0 segs = num_points - 1 segs.times do |i| p_1 = self[i] p_2 = self[i + 1] seg_length = p_1.distance(p_2) / length if fraction < total_length + seg_length dseg = (fraction - total_length) / seg_length args = [] args << p_1.x + ((p_2.x - p_1.x) * dseg) args << p_1.y + ((p_2.y - p_1.y) * dseg) args << p_1.z + ((p_2.z - p_1.z) * dseg) if has_z? args << { srid: pick_srid_according_to_policy(srid) } unless srid.zero? return Geos.create_point(*args) end total_length += seg_length end # if all else fails... end_point end end alias interpolate_point line_interpolate_point %w{ max min }.each do |op| %w{ x y }.each do |dimension| native_method = "GEOSGeom_get#{dimension.upcase}#{op[0].upcase}#{op[1..-1]}_r" if FFIGeos.respond_to?(native_method) class_eval(<<-RUBY, __FILE__, __LINE__ + 1) def #{dimension}_#{op} return if empty? double_ptr = FFI::MemoryPointer.new(:double) FFIGeos.#{native_method}(Geos.current_handle_pointer, ptr, double_ptr) double_ptr.read_double end RUBY else class_eval(<<-RUBY, __FILE__, __LINE__ + 1) def #{dimension}_#{op} unless self.empty? self.coord_seq.#{dimension}_#{op} end end RUBY end end class_eval(<<-RUBY, __FILE__, __LINE__ + 1) def z_#{op} unless self.empty? if self.has_z? self.coord_seq.z_#{op} else 0 end end end RUBY end %w{ affine rotate rotate_x rotate_y rotate_z scale trans_scale translate }.each do |m| class_eval(<<-RUBY, __FILE__, __LINE__ + 1) def #{m}!(*args) unless self.empty? self.coord_seq.#{m}!(*args) end self end def #{m}(*args) ret = self.dup.#{m}!(*args) ret.srid = pick_srid_according_to_policy(self.srid) ret end RUBY end end end
24.276995
156
0.554438
08bf6fc6b2bb37fc4682a5b2d16c438da8f4de55
7,814
require "spec_helper" describe Teaspoon::Suite do before do Teaspoon.configuration.stub(:suites).and_return "default" => proc{} end describe ".all" do it "returns all the suites" do Teaspoon.configuration.stub(:suites).and_return "default" => proc{}, "foo" => proc{} results = Teaspoon::Suite.all expect(results.first).to be_a(Teaspoon::Suite) expect(results.length).to be(2) expect(results.first.name).to eq("default") expect(results.last.name).to eq("foo") end end describe ".resolve_spec_for" do it "return a hash with the suite name and path" do results = Teaspoon::Suite.resolve_spec_for("fixture_spec") expect(results[:suite]).to eq("default") expect(results[:path].first).to include("base/fixture_spec.") end it "returns a hash with the suite name and an array of paths if a directory is given" do results = Teaspoon::Suite.resolve_spec_for("base") expect(results[:suite]).to eq("default") dirs = ["base/fixture_spec.", "base/runner_spec.", "base/teaspoon_spec"] expect(dirs.all? { |path| results[:path].grep(/#{path}/)[0] }).to be_true end end describe "#initialize" do it "uses default suite configuration" do expect(subject.config.helper).to eq("spec_helper") end it "accepts a suite configuration name" do Teaspoon.configuration.should_receive(:suites).and_return "test" => proc{ |s| s.helper = "helper_file" } subject = Teaspoon::Suite.new({suite: :test}) expect(subject.config.helper).to eq("helper_file") end end describe "#name" do it "returns the name of the suite" do expect(subject.name).to eql("default") end end describe "#stylesheets" do it "returns an array of stylesheets" do expect(subject.stylesheets).to include("teaspoon") end end describe "#helper" do it "returns the javascript helper" do expect(subject.helper).to eq("spec_helper") end end describe "#javascripts" do it "returns an array of all javascripts" do results = subject.javascripts expect(results).to include("teaspoon-jasmine") expect(results).to include("spec_helper") end end describe "#core_javascripts" do it "returns an array of core javascripts" do results = subject.core_javascripts expect(results).to eql(["teaspoon-jasmine"]) end end describe "#spec_javascripts" do it "returns an array of spec javascripts" do results = subject.spec_javascripts expect(results).to include("spec_helper") expect(results).to include("teaspoon/base/reporters/console_spec.js") end it "returns the file requested if one was passed" do subject = Teaspoon::Suite.new({file: "spec/javascripts/foo.js"}) results = subject.spec_javascripts expect(results).to eql(["spec_helper", "foo.js"]) end end describe "#spec_javascripts_for_require" do let(:files) { ['/path/file1.js.coffee', 'path/file2.coffee', 'file3.coffee.erb', 'file4.js.erb' ] } before do subject.should_receive(:specs).and_return(files) end it 'returns an array of spec javascripts without .js and Teaspoon prefix' do expect( subject.spec_javascripts_for_require ).to eq(['/path/file1', 'path/file2', 'file3', 'file4']) end end describe "#suites" do it "returns as hash with expected results" do expect(subject.suites).to eql({all: ["default"], active: "default"}) end end describe "#spec_files" do it "returns an array of hashes with the filename and the asset name" do file = Teaspoon::Engine.root.join("spec/javascripts/teaspoon/base/reporters/console_spec.js").to_s subject.should_receive(:glob).and_return([file]) expect(subject.spec_files[0]).to eql({path: file, name: "teaspoon/base/reporters/console_spec.js"}) end end describe "#link" do it "returns a link for the specific suite" do expect(subject.link).to eql("/teaspoon/default") end it "returns a link with added params" do expect(subject.link(file: ["file1", "file2"], grep: "foo")).to eql("/teaspoon/default/?file%5B%5D=file1&file%5B%5D=file2&grep=foo") end end describe "#instrument_file?" do before do Teaspoon.configuration.stub(:suites).and_return "default" => proc{ |s| s.no_coverage = ["file_", /some\/other/] } subject.stub(:include_spec?).and_return(false) end it "returns false if the file is a spec" do subject.should_receive(:include_spec?).with("_some/file_").and_return(true) expect(subject.instrument_file?("_some/file_")).to be(false) end it "returns false if the file should be ignored" do expect(subject.instrument_file?("_some/file_")).to be(false) expect(subject.instrument_file?("_some/other_file_")).to be(false) end it "returns true if it's a valid file that should get instrumented" do expect(subject.instrument_file?("_some/file_for_instrumenting_")).to be(true) end end describe "#include_spec?" do it "returns true if the spec was found" do files = subject.send(:glob) expect(subject.include_spec?(files.first)).to eq(true) end end describe "#include_spec_for?" do it "returns the spec if an exact match was found" do files = subject.send(:glob) expect(subject.include_spec_for?(files.first)).to eq(files.first) end it "returns a list of specs when the file name looks like it could be a match" do expect( subject.include_spec_for?('fixture_spec').any? { |file| file.include?('fixture_spec.coffee') }).to be_true end it "returns false if a matching spec isn't found" do expect(subject.include_spec_for?('_not_a_match_')).to eq(false) end end describe "#specs" do it "converts file names that are in registered asset paths into usable asset urls" do Teaspoon.configuration.should_receive(:suites).and_return "default" => proc{ |s| s.matcher = Teaspoon::Engine.root.join("spec/javascripts/support/*.*") } expect(subject.send(:specs)).to include("support/support.js") end it "raises an AssetNotServable exception if the file can't be served by sprockets" do Teaspoon.configuration.should_receive(:suites).and_return "default" => proc{ |s| s.matcher = __FILE__ } expect{ subject.send(:specs) }.to raise_error(Teaspoon::AssetNotServable, "#{__FILE__} is not within an asset path") end end describe "#asset_from_file" do before do Rails.application.config.assets.stub(paths: ["/Users/person/workspace/spec/javascripts"]) end it "converts a file name into a usable asset url" do file = '/Users/person/workspace/spec/javascripts/support/support.js' expect(subject.send(:asset_from_file, file)).to eq('support/support.js') end context "when the file name has .js.coffee or .coffee extensions" do it "returns an asset url with a .js suffix" do coffee_file = '/Users/person/workspace/spec/javascripts/support/support.coffee' expect(subject.send(:asset_from_file, coffee_file)).to eq('support/support.js') jscoffee_file = '/Users/person/workspace/spec/javascripts/support/support.js.coffee' expect(subject.send(:asset_from_file, jscoffee_file)).to eq('support/support.js') end end context "when the file name contains regex special characters" do it "converts a file name into a usable asset url" do regex_file = '/Users/person/.$*?{}/spec/javascripts/support/support.js' Rails.application.config.assets.stub(paths: ["/Users/person/.$*?{}/spec/javascripts"]) expect(subject.send(:asset_from_file, regex_file)).to eq('support/support.js') end end end end
31.635628
159
0.681085
4a40ac37fa5488b690d665038ffc9b85126ca278
4,859
require "spec_helper" require "json" require "securerandom" module AttrVault describe Keyring do describe ".load" do let(:key_data) { { '1' => SecureRandom.base64(32), '2' => SecureRandom.base64(32), } } it "loads a valid keyring string" do keyring = Keyring.load(key_data.to_json) expect(keyring).to be_a Keyring expect(keyring.keys.count).to eq 2 key_data.keys.each do |key_id| key = keyring.keys.find { |k| k.id == Integer(key_id) } expect(key.value).to eq key_data[key_id] end end it "rejects unexpected JSON" do expect { Keyring.load('hello') }.to raise_error(InvalidKeyring) end it "rejects unknown formats" do keys = key_data.map do |k,v| "<key id='#{k}' value='#{v}'/>" end.join(',') expect { Keyring.load("<keys>#{keys}</keys>") }.to raise_error(InvalidKeyring) end it "rejects keys with missing values" do key_data['1'] = nil expect { Keyring.load(key_data) }.to raise_error(InvalidKeyring) end it "rejects keys with empty values" do key_data['1'] = '' expect { Keyring.load(key_data) }.to raise_error(InvalidKeyring) end end end describe "#keys" do let(:keyring) { Keyring.new } let(:k1) { Key.new(1, ::SecureRandom.base64(32)) } let(:k2) { Key.new(2, ::SecureRandom.base64(32)) } before do keyring.add_key(k1) keyring.add_key(k2) end it "lists all keys" do expect(keyring.keys).to include(k1) expect(keyring.keys).to include(k2) end end describe "#fetch" do let(:keyring) { Keyring.new } let(:k1) { Key.new(1, ::SecureRandom.base64(32)) } let(:k2) { Key.new(2, ::SecureRandom.base64(32)) } before do keyring.add_key(k1) keyring.add_key(k2) end it "finds the right key by its id" do expect(keyring.fetch(k1.id)).to be k1 expect(keyring.fetch(k2.id)).to be k2 end it "raises for an unknown id" do expect { keyring.fetch('867344d2-ac73-493b-9a9e-5fa688ba25ef') } .to raise_error(UnknownKey) end end describe "#has_key?" do let(:keyring) { Keyring.new } let(:k1) { Key.new(1, ::SecureRandom.base64(32)) } let(:k2) { Key.new(2, ::SecureRandom.base64(32)) } before do keyring.add_key(k1) keyring.add_key(k2) end it "is true if the keyring has a key with the given id" do expect(keyring.has_key?(k1.id)).to be true expect(keyring.has_key?(k2.id)).to be true end it "is false if no such key is present" do expect(keyring.has_key?(5)).to be false end end describe "#add_key" do let(:keyring) { Keyring.new } let(:k1) { Key.new(1, ::SecureRandom.base64(32)) } it "adds keys" do expect(keyring.keys).to be_empty expect { keyring.add_key(k1) }.to change { keyring.keys.count }.by 1 expect(keyring.keys[0]).to be k1 end end describe "#drop_key" do let(:keyring) { Keyring.new } let(:k1) { Key.new(1, ::SecureRandom.base64(32)) } let(:k2) { Key.new(2, ::SecureRandom.base64(32)) } before do keyring.add_key(k1) keyring.add_key(k2) end it "drops keys by identity" do expect(keyring.keys.count).to eq 2 expect { keyring.drop_key(k1) }.to change { keyring.keys.count }.by -1 expect(keyring.keys.count).to eq 1 expect(keyring.keys[0]).to be k2 end it "drops keys by identifier" do expect(keyring.keys.count).to eq 2 expect { keyring.drop_key(k1.id) }.to change { keyring.keys.count }.by -1 expect(keyring.keys.count).to eq 1 expect(keyring.keys[0]).to be k2 end end describe "#to_json" do let(:keyring) { Keyring.new } let(:k1) { Key.new(1, ::SecureRandom.base64(32)) } let(:k2) { Key.new(2, ::SecureRandom.base64(32)) } before do keyring.add_key(k1) keyring.add_key(k2) end it "serializes the keyring to an expected format" do keyring_data = keyring.to_json reparsed = JSON.parse(keyring_data) expect(reparsed[k1.id.to_s]).to eq k1.value expect(reparsed[k2.id.to_s]).to eq k2.value end end describe "#current_key" do let(:keyring) { Keyring.new } let(:k1) { Key.new(1, ::SecureRandom.base64(32)) } let(:k2) { Key.new(2, ::SecureRandom.base64(32)) } before do keyring.add_key(k1) keyring.add_key(k2) end it "returns the key with the largest id" do expect(keyring.current_key).to eq k2 end it "raise if no keys are registered" do other_keyring = Keyring.new expect { other_keyring.current_key }.to raise_error(KeyringEmpty) end end end
26.994444
86
0.600535
edbf1dadd5d8f11921773ea161c0463efd5eeddd
1,108
puts ' == Contributing to zinbei ** Fixed ** The number of files was reduced. Remind zinbei option * add -v,version * add -d,datetime * add -h,help * add -s,start New zinbei option **How to use** [zinbei -m notojima.txt] * add -m * add -n * add -o * add -u sava and rantan is zinbei(rubyshell). support hakoirimusume project. Please remember this command by zinbeiw * delete * find * remove *exit * rename * makefolder * wordcount * NumberGame *Numbers *loto6 *Encode * OneRunner *Eval * week ** Try ** zinbeiw >help >exit ----Please enter the following words------ | in the command prompt for windows | | | | zinbei help | | | ------------------------------------------ wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww Thank you for reading to the last. wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww '
24.086957
47
0.49278
381b8701ea1a8ad47b1d9bdc15ebd5486a15a174
1,263
module ActiveAdmin class Resource module Attributes def default_attributes resource_class.columns.each_with_object({}) do |c, attrs| unless reject_col?(c) name = c.name.to_sym attrs[name] = (method_for_column(name) || name) end end end def method_for_column(c) resource_class.respond_to?(:reflect_on_all_associations) && foreign_methods.has_key?(c) && foreign_methods[c].name.to_sym end def foreign_methods @foreign_methods ||= resource_class.reflect_on_all_associations. select { |r| r.macro == :belongs_to }. reject { |r| r.chain.length > 2 && !r.options[:polymorphic] }. index_by { |r| r.foreign_key.to_sym } end def reject_col?(c) primary_col?(c) || sti_col?(c) || counter_cache_col?(c) || filtered_col?(c) end def primary_col?(c) c.name == resource_class.primary_key end def sti_col?(c) c.name == resource_class.inheritance_column end def counter_cache_col?(c) c.name.end_with?("_count") end def filtered_col?(c) ActiveAdmin.application.filter_attributes.include?(c.name.to_sym) end end end end
26.3125
129
0.611243
38b381cf911baee437715f65fd8514f13cb27210
3,189
# frozen_string_literal: true require 'rails_helper' describe Maintainer do it { should be_a(ApplicationRecord) } context 'Associations' do it { should have_many(:teams) } it { should have_many(:gears) } it { should have_many(:ftbfs) } end context 'Validation' do it { should validate_presence_of(:name) } it { should validate_presence_of(:email) } it { should validate_presence_of(:login) } end it 'should validate_uniqueness_of :login' do Maintainer.create!(name: 'Igor Zubkov', email: '[email protected]', login: 'icesik') should validate_uniqueness_of :login end it 'should return Maintainer.login on .to_param' do expect(Maintainer.new(login: 'icesik').to_param).to eq('icesik') end it 'should deny change email' do maintainer = Maintainer.create!(name: 'Igor Zubkov', email: '[email protected]', login: 'icesik') maintainer.email = '[email protected]' expect(maintainer.save).to eq(false) end it 'should deny change login' do maintainer = Maintainer.create!(name: 'Igor Zubkov', email: '[email protected]', login: 'icesik') maintainer.login = 'ldv' expect(maintainer.save).to eq(false) end it 'should deny change name' do maintainer = Maintainer.create!(name: 'Igor Zubkov', email: '[email protected]', login: 'icesik') maintainer.name = 'Dmitry V. Levin' expect(maintainer.save).to eq(false) end it 'should return true if Maintainer exists' do Maintainer.create!(name: 'Igor Zubkov', email: '[email protected]', login: 'icesik') expect(Maintainer.login_exists?('icesik')).to eq(true) end it 'should return false if Maintainer not exists' do expect(Maintainer.login_exists?('ice')).to eq(false) end it 'should downcase login before checking for exists' do Maintainer.create!(name: 'Igor Zubkov', email: '[email protected]', login: 'icesik') expect(Maintainer.login_exists?('ICESIK')).to eq(true) end it 'should create one Maintainer' do expect { Maintainer.import('Igor Zubkov <[email protected]>') }.to change(Maintainer, :count).by(1) end it 'should not create Maintainer if Maintainer already exists' do Maintainer.import('Igor Zubkov <[email protected]>') expect { Maintainer.import('Igor Zubkov <[email protected]>') }.not_to change(Maintainer, :count) end it 'should create new Maintainer team' do expect { Maintainer.import('Ruby Maintainers Team <[email protected]>') }.to change(MaintainerTeam, :count).by(1) end it 'should not create new Maintainer team' do Maintainer.import('Ruby Maintainers Team <[email protected]>') expect { Maintainer.import('Ruby Maintainers Team <[email protected]>') }.not_to change(MaintainerTeam, :count) end end
30.961165
77
0.622766
013a146dfdea97773a65563a9f9237af587938a7
3,955
=begin #Selling Partner API for Fulfillment Inbound #The Selling Partner API for Fulfillment Inbound lets you create applications that create and update inbound shipments of inventory to Amazon's fulfillment network. OpenAPI spec version: v0 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 3.0.24 =end require 'spec_helper' require 'json' require 'date' # Unit tests for AmzSpApi::FulfillmentInboundApiModel::PartneredLtlDataOutput # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'PartneredLtlDataOutput' do before do # run before each test @instance = AmzSpApi::FulfillmentInboundApiModel::PartneredLtlDataOutput.new end after do # run after each test end describe 'test an instance of PartneredLtlDataOutput' do it 'should create an instance of PartneredLtlDataOutput' do expect(@instance).to be_instance_of(AmzSpApi::FulfillmentInboundApiModel::PartneredLtlDataOutput) end end describe 'test attribute "contact"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "box_count"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "seller_freight_class"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "freight_ready_date"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "pallet_list"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "total_weight"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "seller_declared_value"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "amazon_calculated_value"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "preview_pickup_date"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "preview_delivery_date"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "preview_freight_class"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "amazon_reference_id"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "is_bill_of_lading_available"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "partnered_estimate"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "carrier_name"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
31.64
164
0.732238
91ed472b302a5ce27d4c3fb4c556c33eee1750c5
701
require 'simplecov' if ENV['CI'] require 'coveralls' SimpleCov.formatter = Coveralls::SimpleCov::Formatter end SimpleCov.start do add_group 'Parsers', 'lib/trackerific/parsers' add_group 'Builders', 'lib/trackerific/builders' add_group 'Services', 'lib/trackerific/services' add_filter 'spec' end ENV['RACK_ENV'] = 'test' require 'rubygems' require 'bundler/setup' require 'trackerific' require 'fakeweb' require 'savon/mock/spec_helper' require 'active_support/core_ext/hash/conversions' # load all the support files Dir["spec/support/**/*.rb"].each { |f| require File.expand_path(f) } RSpec.configure do |config| config.treat_symbols_as_metadata_keys_with_true_values = true end
23.366667
68
0.763195
d51d35440e922c5f9afd3d5abdf0317245a5cd9f
174
class AddStudentCourseIdToPlans < ActiveRecord::Migration def change add_column :plans, :student_course_id, :integer add_index :plans, :student_course_id end end
24.857143
57
0.781609
b9e3c40fa9015dca2fe36aa5b22f9b50f2186737
6,783
#-- encoding: UTF-8 #-- copyright # OpenProject is a project management system. # Copyright (C) 2012-2015 the OpenProject Foundation (OPF) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2013 Jean-Philippe Lang # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See doc/COPYRIGHT.rdoc for more details. #++ module API module Utilities # Since APIv3 uses different names for some properties, there is sometimes the need to convert # names between the "old" Rails/ActiveRecord world of names and the "new" APIv3 world of names. # This class provides methods to cope with the neccessary name conversions # There are multiple reasons for naming differences: # - APIv3 is using camelCase as opposed to snake_case # - APIv3 defines some properties as a different type, which requires a name change # e.g. estimatedTime vs estimated_hours (AR: hours; API: generic duration) # - some names used in AR are even there kind of deprecated # e.g. fixed_version, which everyone refers to as version # - some names in AR are plainly inconsistent, whereas the API tries to be as consistent as # possible, e.g. updated_at vs updated_on # # Callers note: While this class is envisioned to be generally usable, it is currently solely # used for purposes around work packages. Further work might be required for conversions to make # sense in different contexts. class PropertyNameConverter class << self WELL_KNOWN_AR_TO_API_CONVERSIONS = { assigned_to: 'assignee', fixed_version: 'version', done_ratio: 'percentageDone', estimated_hours: 'estimatedTime', created_on: 'createdAt', updated_on: 'updatedAt', remaining_hours: 'remainingTime', spent_hours: 'spentTime', subproject: 'subprojectId', relation_type: 'type', mail: 'email' }.freeze # Converts the attribute name as refered to by ActiveRecord to a corresponding API-conform # attribute name: # * camelCasing the attribute name # * unifying :status and :status_id to 'status' (and other foo_id fields) # * converting totally different attribute names (e.g. createdAt vs createdOn) def from_ar_name(attribute) attribute = normalize_foreign_key_name attribute attribute = expand_custom_field_name attribute special_conversion = WELL_KNOWN_AR_TO_API_CONVERSIONS[attribute.to_sym] return special_conversion if special_conversion # use the generic conversion rules if there is no special conversion attribute.camelize(:lower) end # Converts the attribute name as refered to by the APIv3 to the source name of the attribute # in ActiveRecord. For that to work properly, an instance of the correct AR-class needs # to be passed as context. def to_ar_name(attribute, context:, refer_to_ids: false) attribute = underscore_attribute attribute.to_s.underscore attribute = collapse_custom_field_name(attribute) special_conversion = special_api_to_ar_conversions[attribute] if special_conversion && context.respond_to?(special_conversion) attribute = special_conversion end attribute = denormalize_foreign_key_name(attribute, context) if refer_to_ids attribute end private def special_api_to_ar_conversions @api_to_ar_conversions ||= WELL_KNOWN_AR_TO_API_CONVERSIONS.inject({}) { |result, (k, v)| result[v.underscore] = k.to_s result } end # Unifies different attributes refering to the same thing via a foreign key # e.g. status_id -> status def normalize_foreign_key_name(attribute) attribute.to_s.sub(/(.+)_id\z/, '\1') end # Adds _id suffix to field names that refer to foreign key relations, # leaves other names untouched. # e.g. status_id -> status def denormalize_foreign_key_name(attribute, context) name, id_name = key_name_with_and_without_id attribute # When appending an ID is valid, the context object will understand that message # in case of a `belongs_to` relation (e.g. status => status_id). The second check is for # `has_many` relations (e.g. watcher => watchers). if context.respond_to?(id_name) || context.respond_to?(name.pluralize) id_name else attribute end end def key_name_with_and_without_id(attribute_name) if attribute_name =~ /^(.*)_id$/ [$1, attribute_name] else [attribute_name, "#{attribute_name}_id"] end end # expands short custom field column names to be represented in their long form # (e.g. cf_1 -> custom_field_1) def expand_custom_field_name(attribute) match = attribute.match /\Acf_(?<id>\d+)\z/ if match "custom_field_#{match[:id]}" else attribute end end # collapses long custom field column names to be represented in their short form # (e.g. custom_field_1 -> cf_1) def collapse_custom_field_name(attribute) match = attribute.match /\Acustom_field_(?<id>\d+)\z/ if match "cf_#{match[:id]}" else attribute end end def underscore_attribute(attribute) # vanilla underscore will not puts underscores between letters and digits # we add them with the power of regex (esp. used for custom fields) attribute.underscore.gsub(/([a-z])(\d)/, '\1_\2') end end end end end
40.616766
100
0.66475
116a54a4865b7f54acf7263ca30a0e60f2a4f8a4
2,728
class Libx11 < Formula desc "X.Org: Core X11 protocol client library" homepage "https://www.x.org/" url "https://www.x.org/archive/individual/lib/libX11-1.7.2.tar.bz2" sha256 "1cfa35e37aaabbe4792e9bb690468efefbfbf6b147d9c69d6f90d13c3092ea6c" license "MIT" bottle do sha256 arm64_big_sur: "07000e94eab9193f9306fa2fd097ad8910e937c5573e77360d53bd9f9db64e7c" sha256 big_sur: "7aee5576a2669a20c9c0421a5afdce633130aeebe3f610c646f15dd5fe299f34" sha256 catalina: "d7dede7503227acecc6992b96b2c14472d704cf6a7c71d81efd9a8ea710ba089" sha256 mojave: "fc897d1f8a8619461f8e50cb7fe20682cd3021393cac7fd3ec94fa4c3c3ee7fd" sha256 x86_64_linux: "035f49996ae8031ba4531113482e789feb51abeb8877eb8c0681ea615ff8cd93" end depends_on "pkg-config" => :build depends_on "util-macros" => :build depends_on "xtrans" => :build depends_on "libxcb" depends_on "xorgproto" def install ENV.delete "LC_ALL" ENV["LC_CTYPE"] = "C" args = %W[ --prefix=#{prefix} --sysconfdir=#{etc} --localstatedir=#{var} --disable-dependency-tracking --disable-silent-rules --enable-unix-transport --enable-tcp-transport --enable-ipv6 --enable-local-transport --enable-loadable-i18n --enable-xthreads --enable-specs=no ] system "./configure", *args system "make" system "make", "install" end test do (testpath/"test.c").write <<~EOS #include <X11/Xlib.h> #include <stdio.h> int main() { Display* disp = XOpenDisplay(NULL); if (disp == NULL) { fprintf(stderr, "Unable to connect to display\\n"); return 0; } int screen_num = DefaultScreen(disp); unsigned long background = BlackPixel(disp, screen_num); unsigned long border = WhitePixel(disp, screen_num); int width = 60, height = 40; Window win = XCreateSimpleWindow(disp, DefaultRootWindow(disp), 0, 0, width, height, 2, border, background); XSelectInput(disp, win, ButtonPressMask|StructureNotifyMask); XMapWindow(disp, win); // display blank window XGCValues values; values.foreground = WhitePixel(disp, screen_num); values.line_width = 1; values.line_style = LineSolid; GC pen = XCreateGC(disp, win, GCForeground|GCLineWidth|GCLineStyle, &values); // draw two diagonal lines XDrawLine(disp, win, pen, 0, 0, width, height); XDrawLine(disp, win, pen, width, 0, 0, height); return 0; } EOS system ENV.cc, "test.c", "-L#{lib}", "-lX11", "-o", "test", "-I#{include}" system "./test" assert_equal 0, $CHILD_STATUS.exitstatus end end
33.268293
116
0.657625
bbf30e7519236aed168703eed1a6c486ec280a6e
2,772
gamelog = File.open("games.log", "r").read.split("\n") #Divide game.log em um array de linhas def CreateGameReport(start,gamelog) a = start+1 #contador total_kills = 0 #conta todos os kills do jogo players = [] #Lista os players no formato [nome, tag] kills = [] #Lista os kills individuais no formato [nome, tag, no de kills] while not gamelog[a].include? "InitGame:" and a != gamelog.length-1 #analisa todas as linhas até o começo de outro jogo (ou final do arquivo) line = gamelog[a].split(" ") #divide a linha em palavras if line.include? "Kill:" #se há um kill, aumente o total de kills total_kills += 1 if line[2] == "1022" #se a tag for "1022" (tag de <world>), diminua os kills da vítima for i in kills if i.include? line[line.index("killed")+1..line.index("by")-1].join(" ") i[2] += -1 end end else #caso contrário, aumente o no de kills de quem o fez for i in kills if i.include? line[5..line.index("killed")-1].join(" ") i[2] += 1 end end end end if line.include? "ClientUserinfoChanged:" #se as info do jogador mudaram, atualize as listas str = line[3,line.length].join(" ")[2,line[3,line.length].join(" ").index("\\t")-2] b = true #se o cadastro ja existe, o atualize for i in players if i.include? str i[1] = line[2] for j in kills if j.include? str j[0] = i[0] end end b = false end end #caso contrário, crie um novo cadastro (fiz uma estrutura análoga ao mecanismo for..else do python) if b players.push([str, line[2]]) kills.push([str, "Tag:"+line[2], 0]) end end #aumente o contador a+=1 end #retorne os dados return [total_kills,players,kills] end def format(data,gameno) #formata os dados no formato pedido a = "game_"+gameno.to_s+": {\n total_kills: "+data[0].to_s+"\n players: [" for i in data[1] a+="'"+i[0]+"', " end a+="] kills: {\n" for i in data[2] a+=" '"+i[0]+"' : "+i[2].to_s+",\n" end a+=" }\n}\n" return a end result = "" contador = 1 i = 0 while i < gamelog.length #analiza cada linha e cria um report caso seja o começo de um jogo(inclui "InitGame:") if gamelog[i].include? "InitGame:" #assimila o report ao resultado final e aumenta o contador result += format(CreateGameReport(i,gamelog),contador) contador += 1 end #aumenta o contador i i += 1 end #Registra o resultado no arquivo data.log File.open("data.log","w") { |file| file.write(result)} #imprime o relatório dos jogos puts result
28
105
0.579726
e94a1b53109cab2516ad5fb876df2966cc328681
1,131
cask 'station' do version '1.31.2' sha256 '73626dd8e8c1322206e9fa40ea27e400cc961a477dedff7559b908189a3e3cea' # github.com/getstation/desktop-app-releases was verified as official when first introduced to the cask url "https://github.com/getstation/desktop-app-releases/releases/download/#{version}/Station-#{version}.dmg" appcast 'https://github.com/getstation/desktop-app-releases/releases.atom' name 'Station' homepage 'https://getstation.com/' auto_updates true app 'Station.app' uninstall quit: [ 'org.efounders.BrowserX', 'org.efounders.BrowserX.helper', ] zap trash: [ '~/Library/Application Support/Station/', '~/Library/Caches/org.efounders.BrowserX', '~/Library/Caches/org.efounders.BrowserX.ShipIt', '~/Library/Logs/Station', '~/Library/Preferences/org.efounders.BrowserX.helper.plist', '~/Library/Preferences/org.efounders.BrowserX.plist', '~/Library/Saved Application State/org.efounders.BrowserX.savedState', ] end
37.7
110
0.648983
08b130b3be0aef375fac67ac2d559ce52b83bb64
5,136
module Irwi::Extensions::Controllers::WikiPages extend ActiveSupport::Concern module ClassMethods def page_class @page_class ||= Irwi.config.page_class end def set_page_class(arg) @page_class = arg end end include Irwi::Extensions::Controllers::WikiPageAttachments include Irwi::Support::TemplateFinder def show return not_allowed unless show_allowed? render_template(@page.new_record? ? 'no' : 'show') end def history return not_allowed unless history_allowed? @versions = Irwi.config.paginator.paginate(@page.versions, page: params[:page]) # Paginating them render_template(@page.new_record? ? 'no' : 'history') end def compare return not_allowed unless history_allowed? if @page.new_record? render_template 'no' else @versions, @old_version, @new_version = load_paginated_versions(*version_number_params) render_template 'compare' end end def new return not_allowed unless show_allowed? && edit_allowed? render_template 'new' end def edit return not_allowed unless show_allowed? && edit_allowed? render_template 'edit' end def update return not_allowed unless params[:page] && (@page.new_record? || edit_allowed?) # Check for rights (but not for new record, for it we will use second check only) @page.attributes = permitted_page_params return not_allowed unless edit_allowed? # Double check: used beacause action may become invalid after attributes update @page.updator = @current_user # Assing user, which updated page @page.creator = @current_user if @page.new_record? # Assign it's creator if it's new page if !params[:preview] && (params[:cancel] || @page.save) redirect_to url_for(action: :show, path: @page.path.split('/')) # redirect to new page's path (if it changed) else render_template 'edit' end end def destroy return not_allowed unless destroy_allowed? @page.destroy redirect_to url_for(action: :show) end def all @pages = Irwi.config.paginator.paginate(page_class, page: params[:page]) # Loading and paginating all pages render_template 'all' end private def load_paginated_versions(old_num, new_num) versions = @page.versions.irwi_between(old_num, new_num) # Loading all versions between first and last paginated_versions = Irwi.config.paginator.paginate(versions, page: params[:page]) # Paginating them new_version = paginated_versions.first.number == new_num ? paginated_versions.first : versions.first # Load next version old_version = paginated_versions.last.number == old_num ? paginated_versions.last : versions.last # Load previous version [paginated_versions, old_version, new_version] end def version_number_params new_num = params[:new].to_i || @page.last_version_number # Last version number old_num = params[:old].to_i || 1 # First version number if new_num < old_num # Swapping them if last < first [new_num, old_num] else [old_num, new_num] end end def permitted_page_params params.require(:page).permit(:title, :content, :comment) end # Retrieves wiki_page_class for this controller def page_class self.class.page_class end # Renders user-specified or default template def render_template(template) render "#{template_dir template}/#{template}", status: select_template_status(template) end def select_template_status(template) case template when 'no' then 404 when 'not_allowed' then 403 else 200 end end # Initialize @current_user instance variable def setup_current_user @current_user = respond_to?(:current_user, true) ? current_user : nil # Find user by current_user method or return nil end # Initialize @page instance variable def setup_page @page = page_class.find_by_path_or_new(params[:path] || '') # Find existing page by path or create new end # Method, which called when user tries to visit def not_allowed render_template 'not_allowed' end # Check is it allowed for current user to see current page. Designed to be redefined by application programmer def show_allowed? true end # Check is it allowed for current user see current page history. Designed to be redefined by application programmer def history_allowed? show_allowed? end # Check is it allowed for current user edit current page. Designed to be redefined by application programmer def edit_allowed? show_allowed? end # Check is it allowed for current user destroy current page. Designed to be redefined by application programmer def destroy_allowed? edit_allowed? end included do before_action :setup_current_user # Setup @current_user instance variable before each action # Setup @page instance variable before each action before_action :setup_page, only: [:show, :history, :compare, :new, :edit, :update, :destroy, :add_attachment] helper_method :show_allowed?, :edit_allowed?, :history_allowed?, :destroy_allowed? # Access control methods are avaliable in views end end
29.348571
165
0.728972
28975c9021d358b8ee3ed2962a9561bb506a6759
569
require 'test_helper' module Elasticsearch module Test class CatShardsTest < UnitTest context "Cat: Shards" do subject { FakeClient.new } should "perform correct request" do subject.expects(:perform_request).with do |method, url, params, body| assert_equal 'GET', method assert_equal '_cat/shards', url assert_equal Hash.new, params assert_nil body true end.returns(FakeResponse.new) subject.cat.shards end end end end end
21.074074
79
0.595782
21eafdc09ba5d0316510eead449eb337fe34f35a
119
class AddImportDate < ActiveRecord::Migration def change add_column :uploads, :imported_at, :timestamp end end
19.833333
49
0.764706
5d35e0cd05ca67dad7915d63f5510211dc937db4
4,719
# Copyright © 2011-2016 MUSC Foundation for Research Development # All rights reserved. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. namespace :data do desc "Describe audits when provided with a porotocol id" task :audit_by_id => :environment do $indicator = nil def prompt(*args) print(*args) STDIN.gets.strip end def status auditable_type, auditable_id puts "" print "Retrieving #{auditable_type} - #{auditable_id} audit data" end def show_processing_indicator $indicator = Thread.new do loop do print "." sleep 0.2 end end.run end def hide_processing_indicator $indicator.kill puts "" end def audits_for x_auditable_type, x_auditable_id status x_auditable_type, x_auditable_id show_processing_indicator all_audits = AuditRecovery.where(:auditable_id => x_auditable_id, :auditable_type => x_auditable_type) #audits for protocol hide_processing_indicator child_audits = [] x_auditable_type.constantize.reflect_on_all_associations.map{|assoc| assoc.name.to_s.classify}.each do |auditable_type| next if auditable_type == 'Audit' print "Searching #{auditable_type} audit data for #{x_auditable_type} - #{x_auditable_id}" show_processing_indicator child_audits.concat AuditRecovery.where(:auditable_type => auditable_type) .where("audited_changes like '%#{x_auditable_type.underscore}_id: #{x_auditable_id}%' OR audited_changes like '%#{x_auditable_type.underscore}_id:\n- \n- #{x_auditable_id}%'") hide_processing_indicator end ids_and_types = Hash.new {|this_hash, nonexistent_key| this_hash[nonexistent_key] = []} child_audits.each do |audit| ids_and_types[audit.auditable_type] << audit.auditable_id end ids_and_types.each do |auditable_type, ids| ids.uniq! ids.each do |id| all_audits.concat audits_for(auditable_type, id) end end all_audits end model = prompt "Enter the model you would like to investigate (eg. Protocol): " record_id = prompt "Enter the specific record id you would like to investigate (eg. 7356): " audits = audits_for model, record_id puts "Sorting audits" audits.sort_by!(&:id) puts "Removing duplicate audits" audits.uniq_by!(&:id) #{"StudyType" => [1, 2, 3, 3, 3], "ResearchTypeInfo" => [1, 3, 4]} CSV.open("tmp/audit_by_id_data_protocol_id_#{record_id}.csv","wb") do |csv| csv << ["Model: #{model}", "Record ID: #{record_id}"] csv << ["Audit ID", "Created At", "User Display Name", "User ID", "Auditable Type", "Auditable ID", "Action", "Changes"] audits.each do |e| user = Identity.find(e.user_id) rescue nil csv << [e.id, e.created_at, user.try(:display_name), e.user_id, e.auditable_type, e.auditable_id, e.action, e.audited_changes] end end end end #csv << [e.created_at, e.user_id, e.user_type, e.remote_address,e.auditable_type, e.action, e.audited_changes] # AuditRecovery.where(:auditable_type => 'ServiceRequest').where("audited_changes like '%protocol_id => [ ,6371]%'") #[
40.681034
145
0.699301
61860f23ca2f0703f4ad6e33acbe8c4fa0a24394
175
require 'test_helper' class Users::StatusUpdatesControllerTest < ActionController::TestCase # Replace this with your real tests. def test_truth assert true end end
19.444444
69
0.777143
7a98012b18a5c8a61e29a4ad17f82360c6fca3e9
9,179
require 'spec_helper' require 'datadog/statsd' require 'ddtrace' require 'benchmark/ips' if !PlatformHelpers.jruby? && Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.1.0') require 'benchmark/memory' require 'memory_profiler' end require 'fileutils' require 'json' RSpec.shared_context 'benchmark' do # When applicable, runs the test subject for different input sizes. # Similar to how N in Big O notation works. # # This value is provided to the `subject(i)` method in order for the test # to appropriately execute its run based on input size. let(:steps) { defined?(super) ? super() : [1, 10, 100] } # How many times we run our program when testing for memory allocation. # In theory, we should only need to run it once, as memory tests are not # dependent on competing system resources. # But occasionally we do see a few blimps of inconsistency, making the benchmarks skewed. # By running the benchmarked snippet many times, we drown out any one-off anomalies, allowing # the real memory culprits to surface. let(:memory_iterations) { defined?(super) ? super() : 100 } # How long the program will run when calculating IPS performance, in seconds. let(:timing_runtime) { defined?(super) ? super() : 5 } # Outputs human readable information to STDERR. # Most of the benchmarks have nicely formatted reports # that are by default printed to terminal. before do |e| @test = e.metadata[:example_group][:full_description] @type = e.description STDERR.puts "Test:#{e.metadata[:example_group][:full_description]} #{e.description}" end def warm_up steps.each do |s| subject(s) end end # Report JSON result objects to ./tmp/benchmark/ folder # Theses results can be historically tracked (e.g. plotting) if needed. def write_result(result, subtype = nil) file_name = if subtype "#{@type}-#{subtype}" else @type end STDERR.puts(@test, file_name, result) directory = result_directory!(subtype) path = File.join(directory, file_name) File.write(path, JSON.pretty_generate(result)) STDERR.puts("Result written to #{path}") end # Create result directory for current benchmark def result_directory!(subtype = nil) path = File.join('tmp', 'benchmark', @test) path = File.join(path, subtype.to_s) if subtype FileUtils.mkdir_p(path) path end # Measure execution time it 'timing' do report = Benchmark.ips do |x| x.config(time: timing_runtime, warmup: timing_runtime / 10.0) steps.each do |s| x.report(s) do subject(s) end end x.compare! end result = report.entries.each_with_object({}) do |entry, hash| hash[entry.label] = { ips: entry.stats.central_tendency, error: entry.stats.error_percentage / 100 } end.to_h write_result(result) end # Measure memory usage (object creation and memory size) it 'memory' do warm_up if PlatformHelpers.jruby? || Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.1.0') skip("'benchmark/memory' not supported") end report = Benchmark.memory do |x| steps.each do |s| x.report(s) do memory_iterations.times { subject(s) } end end x.compare! end result = report.entries.map do |entry| row = entry.measurement.map do |metric| { type: metric.type, allocated: metric.allocated, retained: metric.retained } end [entry.label, row] end.to_h write_result(result) end # Measure GC cycles triggered during run it 'gc' do skip if PlatformHelpers.jruby? warm_up io = StringIO.new GC::Profiler.enable memory_iterations.times { subject(steps[0]) } GC.disable # Prevent data collection from influencing results data = GC::Profiler.raw_data GC::Profiler.report(io) GC::Profiler.disable GC.enable puts io.string result = { count: data.size, time: data.map { |d| d[:GC_TIME] }.inject(0, &:+) } write_result(result) end # Reports that generate non-aggregated data. # Useful for debugging. context 'detailed' do before { skip('Detailed report are too verbose for CI') if ENV.key?('CI') } let(:ignore_files) { defined?(super) ? super() : nil } # Memory report with reference to each allocation site it 'memory report' do if PlatformHelpers.jruby? || Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.1.0') skip("'benchmark/memory' not supported") end warm_up steps.each do |step| report = MemoryProfiler.report(ignore_files: ignore_files) do memory_iterations.times { subject(step) } end report_results(report, step) end end def report_results(report, step) puts "Report for step: #{step}" report.pretty_print per_gem_report = lambda do |results| Hash[results.map { |x| [x[:data], x[:count]] }.sort_by(&:first)] end result = { total_allocated: report.total_allocated, total_allocated_memsize: report.total_allocated_memsize, total_retained: report.total_retained, total_retained_memsize: report.total_retained_memsize, allocated_memory_by_gem: per_gem_report[report.allocated_memory_by_gem], allocated_objects_by_gem: per_gem_report[report.allocated_objects_by_gem], retained_memory_by_gem: per_gem_report[report.retained_memory_by_gem], retained_objects_by_gem: per_gem_report[report.retained_objects_by_gem] } write_result(result, step) end # CPU profiling report context 'RubyProf report' do before do if PlatformHelpers.jruby? || Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.4.0') skip("'ruby-prof' not supported") end end before do require 'ruby-prof' RubyProf.measure_mode = RubyProf::PROCESS_TIME end it do warm_up steps.each do |step| result = RubyProf.profile do (memory_iterations * 5).times { subject(step) } end report_results(result, step) end end def report_results(result, step) puts "Report for step: #{step}" directory = result_directory!(step) printer = RubyProf::CallTreePrinter.new(result) printer.print(path: directory) STDERR.puts("Results written in Callgrind format to #{directory}") STDERR.puts('You can use KCachegrind or QCachegrind to read these results.') STDERR.puts('On MacOS:') STDERR.puts('$ brew install qcachegrind') STDERR.puts("$ qcachegrind '#{Dir["#{directory}/*"].sort[0]}'") end end end end require 'socket' # An "agent" that always responds with a proper OK response, while # keeping minimum overhead. # # The goal is to reduce external performance noise from running a real # agent process in the system. # # It finds a locally available port to listen on, and updates the value of # {Datadog::Ext::Transport::HTTP::ENV_DEFAULT_PORT} accordingly. RSpec.shared_context 'minimal agent' do let(:agent_server) { TCPServer.new '127.0.0.1', agent_port } let(:agent_port) { ENV[Datadog::Ext::Transport::HTTP::ENV_DEFAULT_PORT].to_i } # Sample agent response, collected from a real agent exchange. AGENT_HTTP_RESPONSE = "HTTP/1.1 200\r\n" \ "Content-Length: 40\r\n" \ "Content-Type: application/json\r\n" \ "Date: Thu, 03 Sep 2020 20:05:54 GMT\r\n" \ "\r\n" \ "{\"rate_by_service\":{\"service:,env:\":1}}\n".freeze def server_runner previous_conn = nil loop do conn = agent_server.accept conn.print AGENT_HTTP_RESPONSE conn.flush # Read HTTP request to allow other side to have enough # buffer write room. If we don't, the client won't be # able to send the full request until the buffer is cleared. conn.read(1 << 31 - 1) # Closing the connection immediately can sometimes # be too fast, cause to other side to not be able # to read the response in time. # We instead delay closing the connection until the next # connection request comes in. previous_conn.close if previous_conn previous_conn = conn end end before do # Initializes server in a fork, to allow for true concurrency. # In JRuby, threads are not supported, but true thread concurrency is. @agent_runner = if PlatformHelpers.supports_fork? fork { server_runner } else Thread.new { server_runner } end end after do if PlatformHelpers.supports_fork? # rubocop:disable Lint/RescueWithoutErrorClass Process.kill('TERM', @agent_runner) rescue nil Process.wait(@agent_runner) else @agent_runner.kill end end around do |example| # Set the agent port used by the default HTTP transport ClimateControl.modify(Datadog::Ext::Transport::HTTP::ENV_DEFAULT_PORT => available_port.to_s) do example.run end end end
29.325879
106
0.659658
264aba0368d1e9df1b24fa6969b7ab0a13a4a535
251
FactoryGirl.define do factory :tpl_gooddata_extract_report do sequence(:name) { |n| "MyGooddataExtractReport-#{n}" } report_oid '12345' destination_file_name "somefile.csv" export_method 'executed' tpl_gooddata_extract end end
25.1
58
0.741036
bbb86b64e9bbde56562ec63f3e8eb17ff2e6ccf7
2,504
describe ProblemsHelper do describe '#truncated_problem_message' do it 'is html safe' do problem = double('problem', :message => '#<NoMethodError: ...>') truncated = helper.truncated_problem_message(problem) expect(truncated).to be_html_safe expect(truncated).to_not include('<', '>') end it 'does not double escape html' do problem = double('problem', :message => '#<NoMethodError: ...>') truncated = helper.truncated_problem_message(problem) expect(truncated).to be_html_safe expect(truncated).to_not include('&amp;') end end describe "#gravatar_tag" do let(:email) { "[email protected]" } let(:email_hash) { Digest::MD5.hexdigest email } let(:base_url) { "http://www.gravatar.com/avatar/#{email_hash}" } context "default config" do before do allow(Errbit::Config).to receive(:use_gravatar).and_return(true) allow(Errbit::Config).to receive(:gravatar_default).and_return('identicon') end it "should render image_tag with correct alt and src" do expected = "<img alt=\"#{email}\" class=\"gravatar\" src=\"#{base_url}?d=identicon&amp;s=48\" />" expect(helper.gravatar_tag(email, :s => 48)).to eq(expected) end it "should override :d" do expected = "<img alt=\"#{email}\" class=\"gravatar\" src=\"#{base_url}?d=retro&amp;s=48\" />" expect(helper.gravatar_tag(email, :d => 'retro', :s => 48)).to eq(expected) end end context "no email" do it "should not render the tag" do expect(helper.gravatar_tag(nil)).to be_nil end end end describe "#gravatar_url" do context "no email" do let(:email) { nil } it "should return nil" do expect(helper.gravatar_url(email)).to be_nil end end context "without ssl" do let(:email) { "[email protected]" } let(:email_hash) { Digest::MD5.hexdigest email } it "should return the http url" do expect(helper.gravatar_url(email)).to eq("http://www.gravatar.com/avatar/#{email_hash}?d=identicon") end end context "with ssl" do let(:email) { "[email protected]" } let(:email_hash) { Digest::MD5.hexdigest email } it "should return the http url" do allow(controller.request).to receive(:ssl?).and_return(true) expect(helper.gravatar_url(email)).to eq("https://secure.gravatar.com/avatar/#{email_hash}?d=identicon") end end end end
32.947368
112
0.633786
abf342068f6b2bed5b4251e115e7ffd3e21c5d3f
31
include_recipe 'vagrant::rhel'
15.5
30
0.806452
f79e97bc3446e8de3f97ef98974a557cf6179816
609
require 'helper' class TestSoulmate < Test::Unit::TestCase def test_integration_can_load_values_and_query items = [] venues = File.open(File.expand_path(File.dirname(__FILE__)) + '/samples/venues.json', "r") venues.each_line do |venue| items << JSON.parse(venue) end items_loaded = Soulmate::Loader.new('venues').load(items) assert_equal 5, items_loaded matcher = Soulmate::Matcher.new('venues') results = matcher.matches_for_term('stad', :limit => 5) assert_equal 3, results.size assert_equal 'Angel Stadium', results[0]['term'] end end
27.681818
94
0.676519
38b21ba6c219e82e5d391347d4983f41f26b371f
6,866
require File.expand_path(File.join(File.dirname(__FILE__),'helper.rb')) class TestExact < Test::Unit::TestCase def setup initialize_context end def test_exact_no_traps Decimal.context.exact = true Decimal.context.traps[Decimal::Inexact] = false assert_equal Decimal("9"*100+"E-50"), Decimal('1E50')-Decimal('1E-50') assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal(2),Decimal(6)/Decimal(3) assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('1.5'),Decimal(6)/Decimal(4) assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('15241578780673678546105778281054720515622620750190521'), Decimal('123456789123456789123456789')*Decimal('123456789123456789123456789') assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal(2), Decimal('4').sqrt assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal(4), Decimal('16').sqrt assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('42398.78077199232'), Decimal('1.23456')*Decimal('34343.232222') assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('12.369885'), Decimal('210.288045')/Decimal('17') assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('25'),Decimal('125')/Decimal('5') assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('12345678900000000000.1234567890'),Decimal('1234567890E10')+Decimal('1234567890E-10') assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('39304'),Decimal('34').power(Decimal(3)) assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('39.304'),Decimal('3.4').power(Decimal(3)) assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('4'),Decimal('16').power(Decimal('0.5')) assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('4'),Decimal('10000.0').log10 assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('-5'),Decimal('0.00001').log10 assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal.infinity, Decimal.infinity.exp assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal.zero, Decimal.infinity(-1).exp assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal(1), Decimal(0).exp assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal.infinity(-1), Decimal(0).ln assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal.infinity, Decimal.infinity.ln assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal(0), Decimal(1).ln assert !Decimal.context.flags[Decimal::Inexact] assert((Decimal(1)/Decimal(3)).nan?) assert Decimal.context.flags[Decimal::Inexact] Decimal.context.flags[Decimal::Inexact] = false assert((Decimal(18).power(Decimal('0.5'))).nan?) assert Decimal.context.flags[Decimal::Inexact] Decimal.context.flags[Decimal::Inexact] = false assert((Decimal(18).power(Decimal('1.5'))).nan?) assert Decimal.context.flags[Decimal::Inexact] Decimal.context.flags[Decimal::Inexact] = false assert Decimal(18).log10.nan? assert Decimal.context.flags[Decimal::Inexact] Decimal.context.flags[Decimal::Inexact] = false assert Decimal(1).exp.nan? assert Decimal.context.flags[Decimal::Inexact] Decimal.context.flags[Decimal::Inexact] = false assert Decimal('-1.2').exp.nan? assert Decimal.context.flags[Decimal::Inexact] Decimal.context.flags[Decimal::Inexact] = false assert Decimal('1.1').ln.nan? assert Decimal.context.flags[Decimal::Inexact] Decimal.context.flags[Decimal::Inexact] = false end def test_exact_traps Decimal.context.exact = true assert_nothing_raised(Decimal::Inexact){ Decimal(6)/Decimal(4) } assert_equal Decimal("9"*100+"E-50"), Decimal('1E50')-Decimal('1E-50') assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal(2),Decimal(6)/Decimal(3) assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('1.5'),Decimal(6)/Decimal(4) assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('15241578780673678546105778281054720515622620750190521'), Decimal('123456789123456789123456789')*Decimal('123456789123456789123456789') assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal(2), Decimal('4').sqrt assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal(4), Decimal('16').sqrt assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal.infinity, Decimal.infinity.exp assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal.zero, Decimal.infinity(-1).exp assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal(1), Decimal(0).exp assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('42398.78077199232'), Decimal('1.23456')*Decimal('34343.232222') assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('12.369885'), Decimal('210.288045')/Decimal('17') assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('25'),Decimal('125')/Decimal('5') assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('12345678900000000000.1234567890'),Decimal('1234567890E10')+Decimal('1234567890E-10') assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('39304'),Decimal('34').power(Decimal(3)) assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('39.304'),Decimal('3.4').power(Decimal(3)) assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('4'),Decimal('16').power(Decimal('0.5')) assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('4'),Decimal('10000.0').log10 assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal('-5'),Decimal('0.00001').log10 assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal.infinity(-1), Decimal(0).ln assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal.infinity, Decimal.infinity.ln assert !Decimal.context.flags[Decimal::Inexact] assert_equal Decimal(0), Decimal(1).ln assert !Decimal.context.flags[Decimal::Inexact] assert_raise(Decimal::Inexact){ Decimal(2).sqrt } assert_raise(Decimal::Inexact){ Decimal(1)/Decimal(3) } assert_raise(Decimal::Inexact){ Decimal(18).power(Decimal('0.5')) } assert_raise(Decimal::Inexact){ Decimal(18).power(Decimal('1.5')) } assert_raise(Decimal::Inexact){ Decimal(18).log10 } assert_raise(Decimal::Inexact){ Decimal(1).exp } assert_raise(Decimal::Inexact){ Decimal('1.2').exp } assert_raise(Decimal::Inexact){ Decimal('1.2').ln } end end
46.707483
160
0.729246
ab449d9165da7e1bb8b5f09c806d16212bab3180
67
module Compass module Slickmap VERSION = "0.5.1.1" end end
11.166667
23
0.656716
f8d1e0ae18466ef511b8aa2c0ca9d4b3be34c868
2,175
class Libsass < Formula homepage "https://github.com/sass/libsass" url "https://github.com/sass/libsass/archive/3.1.0.tar.gz" sha1 "858c41405f5ff8b4186c7111e08f29893f4e51a1" head "https://github.com/sass/libsass.git" bottle do cellar :any sha1 "af2bbeb2d2221df2fece3eaa054a65270768bb92" => :yosemite sha1 "c626b584ef3e650e3ea3e05db123958c8a00d947" => :mavericks sha1 "9c7460ce74317a03c996f215a890e0ab88b6c73d" => :mountain_lion end depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build needs :cxx11 def install ENV.cxx11 ENV["LIBSASS_VERSION"] = "HEAD" if build.head? system "autoreconf", "-fvi" system "./configure", "--prefix=#{prefix}", "--disable-silent-rules", "--disable-dependency-tracking" system "make", "install" # The header below is deprecated and should not be used outside of test do. # We only install it here for backward compatibility and so brew test works. # https://github.com/sass/libsass/wiki/API-Documentation include.install "sass_interface.h" if build.devel? end test do # This will need to be updated when devel = stable due to API changes. (testpath/"test.c").write <<-EOS.undent #include <sass_context.h> #include <string.h> int main() { char* source_string = "a { color:blue; &:hover { color:red; } }"; struct Sass_Data_Context* data_ctx = sass_make_data_context(source_string); struct Sass_Options* options = sass_data_context_get_options(data_ctx); sass_option_set_precision(options, SASS_STYLE_NESTED); sass_option_set_source_comments(options, 0); sass_compile_data_context(data_ctx); struct Sass_Context* ctx = sass_data_context_get_context(data_ctx); int err = sass_context_get_error_status(ctx); if(err != 0) { return 1; } else { return strcmp(sass_context_get_output_string(ctx), "a {\\n color: blue; }\\n a:hover {\\n color: red; }\\n") != 0; } } EOS system ENV.cc, "-o", "test", "test.c", "-lsass" system "./test" end end
36.864407
129
0.664368
110c0b0768a3f4820b116d54b644a25856b7e5af
1,635
# # Be sure to run `pod lib lint ShareModule.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'ShareModule' s.version = '0.0.1' s.summary = 'A share module like UC browser.' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC TODO: Add long description of the pod here. DESC s.homepage = 'https://github.com/YuePei/ShareModule' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'YuePei' => '[email protected]' } s.source = { :git => 'https://github.com/YuePei/ShareModule.git', :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '9.0' s.source_files = 'ShareModule/Classes/**/*' # s.resource_bundles = { # 'ShareModule' => ['ShareModule/Assets/*.png'] # } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' # s.dependency 'AFNetworking', '~> 2.3' s.dependency 'Masonry', '~>1.1.0' end
35.543478
102
0.632416
ffda413038fbdd65e40a8c0f1d934b53fa18602c
2,076
# frozen_string_literal: true # Class encapsulating the user action of making a UKHPI query class QueryCommand include DataService MILLISECONDS = 1000.0 attr_reader :user_selections, :results, :query def initialize(user_selections) @user_selections = user_selections @query = build_query end # Perform the UKHPI query encapsulated by this command object # @param service Optional API service end-point to use. Defaults to the UKHPI # API service endpoint def perform_query(service = nil) Rails.logger.debug "About to ask DsAPI query: #{query.to_json}" time_taken = execute_query(service, query) Rails.logger.debug(format("query took %.1f ms\n", time_taken)) end # @return True if this a query execution command def query_command? true end # @return True if this is a query explanation command def explain_query_command? false end private # Construct the DsAPI query that matches the given user constraints def build_query query = add_date_range_constraint(base_query) query1 = add_location_constraint(query) add_sort(query1) end def api_service(service) @api_service ||= service || default_service end def default_service dataset(:ukhpi) end # Run the given query, and stash the results. Return time taken in ms. def execute_query(service, query) start = Time.zone.now @results = api_service(service).query(query) (Time.zone.now - start) * MILLISECONDS end def add_date_range_constraint(query) from = month_year_value(user_selections.from_date) to = month_year_value(user_selections.to_date) query.ge('ukhpi:refMonth', from) .le('ukhpi:refMonth', to) end def add_location_constraint(query) value = DataServicesApi::Value.uri(location_uri) query.eq('ukhpi:refRegion', value) end def add_sort(query) query.sort(:up, 'ukhpi:refMonth') end def month_year_value(date) DataServicesApi::Value.year_month(date.year, date.month) end def location_uri user_selections.selected_location end end
24.714286
79
0.73025
01f269d2d2de8028993959a44bc4fc9a6987129b
309
module Alexa module Responses class Delegate def as_json(options={}) { "version": "1.0", "response": { "directives": [ { "type": "Dialog.Delegate" } ] } } end end end end
16.263158
41
0.365696
e8c623a0c1f10e86cfa810bcb4989ed5654b5c80
291
module Fog module Compute class Ninefold class Real def list_zones(options = {}) request('listZones', options, :expects => [200], :response_prefix => 'listzonesresponse/zone', :response_type => Array) end end end end end
19.4
88
0.570447
79d6ba27446d19ccd1d7c8baf065b154b0012533
2,325
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::NetApp::Mgmt::V2017_08_15_preview module Models # # Microsoft.NetApp REST API operation definition. # class Operation include MsRestAzure # @return [String] Operation name: {provider}/{resource}/{operation} attr_accessor :name # @return [OperationDisplay] Display metadata associated with the # operation. attr_accessor :display # @return [String] The origin of operations. attr_accessor :origin # @return [ServiceSpecification] One property of operation, include # metric specifications. attr_accessor :service_specification # # Mapper for Operation class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'Operation', type: { name: 'Composite', class_name: 'Operation', model_properties: { name: { client_side_validation: true, required: false, serialized_name: 'name', type: { name: 'String' } }, display: { client_side_validation: true, required: false, serialized_name: 'display', type: { name: 'Composite', class_name: 'OperationDisplay' } }, origin: { client_side_validation: true, required: false, serialized_name: 'origin', type: { name: 'String' } }, service_specification: { client_side_validation: true, required: false, serialized_name: 'properties.serviceSpecification', type: { name: 'Composite', class_name: 'ServiceSpecification' } } } } } end end end end
28.012048
74
0.510108
39d5d6f944bddcbfe04c8becf81b0a13092e9c46
518
class ApplicationController < ActionController::API rescue_from ActiveRecord::RecordNotFound, with: Proc.new{|e| render status: 404, json: { errors: { detail: "#{e.model.titleize.humanize} not found" } } } rescue_from ActionController::UnpermittedParameters, with: Proc.new{|e| render status: 422, json: { errors: { invalid_params: e.params } } } rescue_from ActiveModel::UnknownAttributeError, with: Proc.new{|e| render status: 422, json: { errors: { invalid_params: [ e.attribute ] } } } end
43.166667
94
0.710425
1d6ea7288cf0db7694fc8dfc68cb088aa370d397
5,914
# frozen_string_literal: true module MediaWiktory::Wikipedia module Modules # List all pages in a given category. _Generator module: for fetching pages corresponding to request._ # # The "submodule" (MediaWiki API term) is included in action after setting some param, providing # additional tweaking for this param. Example (for {MediaWiktory::Wikipedia::Actions::Query} and # its submodules): # # ```ruby # api.query # returns Actions::Query # .prop(:revisions) # adds prop=revisions to action URL, and includes Modules::Revisions into action # .limit(10) # method of Modules::Revisions, adds rvlimit=10 to URL # ``` # # All submodule's parameters are documented as its public methods, see below. # module GCategorymembers # Which category to enumerate (required). Must include the Category: prefix. Cannot be used together with cmpageid. # # @param value [String] # @return [self] def title(value) merge(gcmtitle: value.to_s) end # Page ID of the category to enumerate. Cannot be used together with cmtitle. # # @param value [Integer] # @return [self] def pageid(value) merge(gcmpageid: value.to_s) end # Only include pages in these namespaces. Note that cmtype=subcat or cmtype=file may be used instead of cmnamespace=14 or 6. # # @param values [Array<String>] Allowed values: "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "100", "101", "108", "109", "118", "119", "446", "447", "710", "711", "828", "829", "2300", "2301", "2302", "2303". # @return [self] def namespace(*values) values.inject(self) { |res, val| res._namespace(val) or fail ArgumentError, "Unknown value for namespace: #{val}" } end # @private def _namespace(value) defined?(super) && super || ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "100", "101", "108", "109", "118", "119", "446", "447", "710", "711", "828", "829", "2300", "2301", "2302", "2303"].include?(value.to_s) && merge(gcmnamespace: value.to_s, replace: false) end # Which type of category members to include. Ignored when cmsort=timestamp is set. # # @param values [Array<String>] Allowed values: "page", "subcat", "file". # @return [self] def type(*values) values.inject(self) { |res, val| res._type(val) or fail ArgumentError, "Unknown value for type: #{val}" } end # @private def _type(value) defined?(super) && super || ["page", "subcat", "file"].include?(value.to_s) && merge(gcmtype: value.to_s, replace: false) end # When more results are available, use this to continue. # # @param value [String] # @return [self] def continue(value) merge(gcmcontinue: value.to_s) end # The maximum number of pages to return. # # @param value [Integer, "max"] # @return [self] def limit(value) merge(gcmlimit: value.to_s) end # Property to sort by. # # @param value [String] One of "sortkey", "timestamp". # @return [self] def sort(value) _sort(value) or fail ArgumentError, "Unknown value for sort: #{value}" end # @private def _sort(value) defined?(super) && super || ["sortkey", "timestamp"].include?(value.to_s) && merge(gcmsort: value.to_s) end # In which direction to sort. # # @param value [String] One of "asc", "desc", "ascending", "descending", "newer", "older". # @return [self] def dir(value) _dir(value) or fail ArgumentError, "Unknown value for dir: #{value}" end # @private def _dir(value) defined?(super) && super || ["asc", "desc", "ascending", "descending", "newer", "older"].include?(value.to_s) && merge(gcmdir: value.to_s) end # Timestamp to start listing from. Can only be used with cmsort=timestamp. # # @param value [Time] # @return [self] def start(value) merge(gcmstart: value.iso8601) end # Timestamp to end listing at. Can only be used with cmsort=timestamp. # # @param value [Time] # @return [self] def end(value) merge(gcmend: value.iso8601) end # Sortkey to start listing from, as returned by cmprop=sortkey. Can only be used with cmsort=sortkey. # # @param value [String] # @return [self] def starthexsortkey(value) merge(gcmstarthexsortkey: value.to_s) end # Sortkey to end listing at, as returned by cmprop=sortkey. Can only be used with cmsort=sortkey. # # @param value [String] # @return [self] def endhexsortkey(value) merge(gcmendhexsortkey: value.to_s) end # Sortkey prefix to start listing from. Can only be used with cmsort=sortkey. Overrides cmstarthexsortkey. # # @param value [String] # @return [self] def startsortkeyprefix(value) merge(gcmstartsortkeyprefix: value.to_s) end # Sortkey prefix to end listing before (not at; if this value occurs it will not be included!). Can only be used with cmsort=sortkey. Overrides cmendhexsortkey. # # @param value [String] # @return [self] def endsortkeyprefix(value) merge(gcmendsortkeyprefix: value.to_s) end # Use cmstarthexsortkey instead. # # @param value [String] # @return [self] def startsortkey(value) merge(gcmstartsortkey: value.to_s) end # Use cmendhexsortkey instead. # # @param value [String] # @return [self] def endsortkey(value) merge(gcmendsortkey: value.to_s) end end end end
34.584795
310
0.594691
ab42a75b4c75cab6746832124fca8fa0e8f21b35
177
class AddNextInspectionDate < ActiveRecord::Migration[5.2] def change add_column :highway_structures, :next_inspection_date, :date, after: :inspection_frequency end end
29.5
94
0.79661
0396b7d5e7234f18d27910d06c6a5cd90e425463
404
cask 'font-padauk' do version :latest sha256 :no_check # github.com/google/fonts was verified as official when first introduced to the cask url 'https://github.com/google/fonts/trunk/ofl/padauk', using: :svn, revision: '50', trust_cert: true name 'Padauk' homepage 'https://www.google.com/fonts/earlyaccess' font 'Padauk-Bold.ttf' font 'Padauk-Regular.ttf' end
25.25
86
0.685644
91327b302763b521b524c47613c6c297dd5c8194
202
require 'test_helper' class KvstoreTest < Minitest::Test def test_that_it_has_a_version_number refute_nil ::Kvstore::VERSION end def test_it_does_something_useful assert false end end
16.833333
39
0.782178
792bb200648ede575584e6981fbb0ebfd0524674
9,578
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) MenuItem.create(name: 'Pho', description: "It's almost impossible to walk a block in Vietnam's major destinations without bumping into a crowd of hungry patrons slurping noodles at a makeshift pho stand. This simple staple consisting of a salty broth, fresh rice noodles, a sprinkling of herbs and chicken or beef, features predominately in the local diet -- and understandably so. It's cheap, tasty, and widely available at all hours.", price: 40000, section: 'Breakfast', url: "https://dynaimage.cdn.cnn.com/cnn/q_auto,w_634,c_fill,g_auto,h_357,ar_16:9/http%3A%2F%2Fcdn.cnn.com%2Fcnnnext%2Fdam%2Fassets%2F170504142019-pho.jpg") MenuItem.create(name: 'Cha Ca', description: "Hanoians consider cha ca to be so exceptional that there is a street in the capital dedicated to these fried morsels of fish. This namesake alley is home to Cha Ca La Vong, which serves sizzling chunks of fish seasoned with garlic, ginger, turmeric and dill on a hot pan tableside.", price: 50000, section: 'Lunch', url: "https://dynaimage.cdn.cnn.com/cnn/q_auto,w_634,c_fill,g_auto,h_357,ar_16:9/http%3A%2F%2Fcdn.cnn.com%2Fcnnnext%2Fdam%2Fassets%2F170504142339-banh-xeo.jpg") MenuItem.create(name: 'Banh Xeo', description: "A good banh xeo is a crispy crepe bulging with pork, shrimp, and bean sprouts, plus the garnish of fresh herbs that are characteristic of most authentic Vietnamese dishes. To enjoy one like a local, cut it into manageable slices, roll it up in rice paper or lettuce leaves and dunk it in whatever special sauce the chef has mixed up for you.", price: 30000, section: 'Dinner', url: "https://dynaimage.cdn.cnn.com/cnn/q_auto,w_634,c_fill,g_auto,h_357,ar_16:9/http%3A%2F%2Fcdn.cnn.com%2Fcnnnext%2Fdam%2Fassets%2F170504142339-banh-xeo.jpg") MenuItem.create(name: 'Cao Lau', description: "This pork noodle dish from Hoi An is a bit like the various cultures that visited the trading port at its prime. The thicker noodles are similar to Japanese udon, the crispy won-ton crackers and pork are a Chinese touch, while the broth and herbs are clearly Vietnamese. Authentic cau lao is made only with water drawn from the local Ba Le well.", price: 40000, section: 'Dinner', url: "https://dynaimage.cdn.cnn.com/cnn/q_auto,w_634,c_fill,g_auto,h_357,ar_16:9/http%3A%2F%2Fcdn.cnn.com%2Fcnnnext%2Fdam%2Fassets%2F111005063013-vietnam-food-cao-lau.jpg") MenuItem.create(name: 'Goi Cuon', description: "These light and healthy fresh spring rolls are a wholesome choice when you've been indulging in too much of the fried food in Vietnam. The translucent parcels are first packed with salad greens, a slither of meat or seafood and a layer of coriander, before being neatly rolled and dunked in Vietnam's favorite condiment -- fish sauce.", price: 60000, section: 'Dinner', url: "https://dynaimage.cdn.cnn.com/cnn/q_auto,w_634,c_fill,g_auto,h_357,ar_16:9/http%3A%2F%2Fcdn.cnn.com%2Fcnnnext%2Fdam%2Fassets%2F170306134418-goi-cuon.jpg") MenuItem.create(name: 'Banh Khot', description: "This dainty variation of a Vietnamese pancake has all the same tasty ingredients but is a fraction of the size. Each banh knot can be scoffed in one ambitious but satisfying mouthful. The crunchy outside is made using coconut milk and the filling usually consists of shrimp, mung beans, and spring onions with a dusting of dried shrimp flakes on top.", price: 60000, section: 'Dinner', url: "https://dynaimage.cdn.cnn.com/cnn/q_auto,w_634,c_fill,g_auto,h_357,ar_16:9/http%3A%2F%2Fcdn.cnn.com%2Fcnnnext%2Fdam%2Fassets%2F170504151643-banh-knot.jpg") MenuItem.create(name: 'Bun bo nam bo', description: "This bowl of noodles comes sans broth, keeping the ingredients from becoming sodden and the various textures intact. The tender slices of beef mingle with crunchy peanuts and bean sprouts, and are flavored with fresh herbs, crisp dried shallots, and a splash of fish sauce and fiery chili pepper.", price: 50000, section: 'Lunch', url: "https://dynaimage.cdn.cnn.com/cnn/q_auto,w_634,c_fill,g_auto,h_357,ar_16:9/http%3A%2F%2Fcdn.cnn.com%2Fcnnnext%2Fdam%2Fassets%2F170504151239-bun-bo-nam-bo.jpg") MenuItem.create(name: 'Ga Nuong', description: "KFC may be everywhere in Vietnam these days, but skip the fast food for the local version. Honey marinated then grilled over large flaming barbecues, the chicken legs, wings and feet served are unusually tender, while the skin stays crispy but not dry.", price: 60000, section: 'Breakfast', url: "https://dynaimage.cdn.cnn.com/cnn/q_auto,w_634,c_fill,g_auto,h_357,ar_16:9/http%3A%2F%2Fcdn.cnn.com%2Fcnnnext%2Fdam%2Fassets%2F170504150749-ga-nuong.jpg") MenuItem.create(name: 'Xoi', description: "Savory sticky rice is less of an accompaniment to meals in Vietnam, more a meal itself. The glutinous staple comes with any number of mix-ins (from slithers of chicken, or pork to fried or preserved eggs), but almost always with a scattering of dried shallots on top.", price: 60000, section: 'Breakfast', url: "https://dynaimage.cdn.cnn.com/cnn/q_auto,w_634,c_fill,g_auto,h_357,ar_16:9/http%3A%2F%2Fcdn.cnn.com%2Fcnnnext%2Fdam%2Fassets%2F160524100325-05-vietnam-dishes-xoi.jpg") MenuItem.create(name: 'Banh Cuon', description: "These rolled up rice flour pancakes are best when served piping hot, still soft and delicate. Although seemingly slender and empty they have a savory filling of minced pork and mushrooms. Zest is also added by dunking the slippery parcels in a fishy dipping sauce.", price: 40000, section: 'Breakfast', url: "https://dynaimage.cdn.cnn.com/cnn/q_auto,w_634,c_fill,g_auto,h_357,ar_16:9/http%3A%2F%2Fcdn.cnn.com%2Fcnnnext%2Fdam%2Fassets%2F170504150157-banh-cuon.jpg") MenuItem.create(name: 'Bot Chien', description: "Saigon's favorite streetside snack, bot chien, is popular with both the afterschool and the after-midnight crowd. Chunks of rice flour dough are fried in a large wok until crispy and then an egg is broken into the mix. Once cooked it's served with slices of papaya, shallots and green onions, before more flavor is added with pickled chili sauce and rice vinegar.", price: 30000, section: 'Lunch', url: "https://dynaimage.cdn.cnn.com/cnn/q_auto,w_634,c_fill,g_auto,h_357,ar_16:9/http%3A%2F%2Fcdn.cnn.com%2Fcnnnext%2Fdam%2Fassets%2F160524092144-vietnam-street-food-bot-chien.jpg") MenuItem.create(name: 'Bun Cha', description: "Pho might be Vietnam's most famous dish but bun cha is the top choice when it comes to lunchtime in the capital. Just look for the clouds of meaty smoke after 11 a.m. when street-side restaurants start grilling up small patties of seasoned pork and slices of marinated pork belly over a charcoal fire. Once they're charred and crispy the morsels are served with a large bowl of a fish sauce-heavy broth, a basket of herbs and a helping of rice noodles.", price: 70000, section: 'Lunch', url: "https://dynaimage.cdn.cnn.com/cnn/q_auto,w_634,c_fill,g_auto,h_357,ar_16:9/http%3A%2F%2Fcdn.cnn.com%2Fcnnnext%2Fdam%2Fassets%2F170504145056-bun-cha.jpg") MenuItem.create(name: 'Banh Mi', description: "The French may have brought with them the baguette, but Vietnam takes it to a different level. How exactly depends on what end of the country you're in. In the north, chefs stick to the basic elements of carbohydrate, fat and protein -- bread, margarine and pata -- but head south and your banh mi may contain a more colorful combination of cheese, cold cuts, pickled vegetables, sausage, fried egg, fresh cilantro and chili sauce.", price: 30000, section: 'Breakfast', url: "https://dynaimage.cdn.cnn.com/cnn/q_auto,w_634,c_fill,g_auto,h_357,ar_16:9/http%3A%2F%2Fcdn.cnn.com%2Fcnnnext%2Fdam%2Fassets%2F170124150901-26--banh-mi.jpg") MenuItem.create(name: 'Orange Tea', description: "Orange tea leaf from Nothern Mountain of Vietnam", price: 30000, section: 'Drinks', url: "https://i.pinimg.com/originals/eb/f9/2d/ebf92d9e18d51c295c27b238e8936c1c.jpg") MenuItem.create(name: 'Juice Fruits', description: "Freshly peeled firm bananas are so tasty and produce a high volume of nutritious potassium. ", price: 30000, section: 'Drinks', url: "https://ladylatoya.files.wordpress.com/2016/01/apple-and-orange-juice.jpg") MenuItem.create(name: 'Absolute Vodka', description: "Absolut Vodka is the leading brand of Premium vodka offering the true taste of vodka in original or your favorite flavors made from natural ingredients.", price: 300000, section: 'Drinks', url: "http://www.4usky.com/data/out/100/164907593-vodka-wallpapers.jpg") MenuItem.create(name: 'Heineken Beer', description: "Heineken Lager Beer (Dutch: Heineken Pilsener), or simply Heineken is a pale lager beer with 5% alcohol by volume produced by the Dutch brewing company.", price: 30000, section: 'Drinks', url: "http://www.hd-freeimages.com/uploads/large/brands/heineken-beer-drink-logo-brand.jpg") MenuItem.create(name: '7Up', description: "Get inspired to mix it up a little with 7UP! Crisp and refreshing, it mixes into all kinds of drinks, cocktails, punches, baked goods, and more, perfect for your next.", price: 30000, section: 'Drinks', url: "https://screenbeauty.com/image/compress/7up-drink-symbol-123623.jpg")
92.990291
470
0.770098
1cb4d033839df7d9e017fd40de7decd9ce75cfed
1,145
ActiveAdmin.register User do config.filters = false # See permitted parameters documentation: # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # permit_params :organization_id, :email, :name, :phone_number, :role_id, :password, :password_confirmation # # or # # permit_params do # permitted = [:permitted, :attributes] # permitted << :other if params[:action] == 'create' && current_user.admin? # permitted # end controller do def scoped_collection super.includes :organization super.includes :role end # def new # @user = User.new(name: "Nirali", role_id: 1, email: "[email protected]", phone_number: "+17324072459") # end end index do column :name column :organization column :email column :phone_number column :role actions end form do |f| f.inputs "User Details" do f.input :organization f.input :role f.input :name f.input :email f.input :phone_number f.input :password f.input :password_confirmation end f.actions end end
22.9
122
0.679476
26f93ccf2a18069f12018bf6e8a01afb2d9b37b8
11,601
# Fix the countries table. # class UpdateCountries < ActiveRecord::Migration # Number of orders array, used to fix the wrong initial values. NOO_ARRAY = [[[1], 4987], [[3], 151], [[4], 128], [[2], 121], [[5], 58], [[101], 36], [[85, 91], 21], [[52], 16], [[191], 14], [[173], 13], [[72, 115, 167], 10], [[164], 9], [[133, 168], 8], [[122], 7], [[95, 67, 92, 118, 93], 6], [[75, 29, 160, 66, 51], 4], [[136, 130, 42], 3], [[139, 86, 129, 161, 176, 59, 17, 7, 88, 104, 151, 192, 8, 137, 94, 223, 124, 9], 2], [[55, 100, 58, 225, 78, 144, 6, 18], 1]] # Ufsi array, here just to be able to be restored. UFSI_ARRAY = [[1, "001"], [2, "034"], [3, "073"], [4, "012"], [5, "087"], [6, "002"], [7, "003"], [8, "004"], [9, "005"], [10, "006"], [11, "007"], [12, "008"], [13, "009"], [14, "010"], [15, "011"], [16, "013"], [17, "014"], [18, "015"], [19, "016"], [20, "017"], [21, "018"], [22, "019"], [23, "020"], [24, "021"], [25, "022"], [26, "023"], [27, "024"], [28, "025"], [29, "026"], [30, "027"], [31, "028"], [32, "029"], [33, "030"], [34, "031"], [35, "032"], [36, "033"], [37, "035"], [38, "036"], [39, "037"], [40, "038"], [41, "039"], [42, "040"], [43, "041"], [44, "042"], [45, "043"], [46, "044"], [47, "045"], [48, "046"], [49, "047"], [50, "048"], [51, "049"], [52, "050"], [53, "051"], [54, "052"], [55, "053"], [56, "054"], [57, "055"], [58, "056"], [59, "057"], [60, "058"], [61, "059"], [62, "060"], [63, "061"], [64, "062"], [65, "063"], [66, "064"], [67, "065"], [68, "066"], [69, "067"], [70, "068"], [71, "069"], [72, "070"], [73, "071"], [74, "072"], [75, "074"], [76, "075"], [77, "076"], [78, "077"], [79, "078"], [80, "079"], [81, "080"], [82, "081"], [83, "082"], [84, "083"], [85, "084"], [86, "085"], [87, "086"], [88, "088"], [89, "089"], [90, "090"], [91, "091"], [92, "092"], [93, "093"], [94, "094"], [95, "095"], [96, "096"], [97, "097"], [98, "098"], [99, "099"], [100, "100"], [101, "101"], [102, "102"], [103, "103"], [104, "104"], [105, "105"], [106, "106"], [107, "107"], [108, "108"], [109, "109"], [110, "110"], [111, "111"], [112, "112"], [113, "113"], [114, "114"], [115, "115"], [116, "116"], [117, "117"], [118, "118"], [119, "119"], [120, "120"], [121, "121"], [122, "122"], [123, "123"], [124, "124"], [125, "125"], [126, "126"], [127, "127"], [128, "128"], [129, "129"], [130, "130"], [131, "131"], [132, "132"], [133, "133"], [134, "134"], [135, "135"], [136, "136"], [137, "137"], [138, "138"], [139, "139"], [140, "140"], [141, "141"], [142, "142"], [143, "143"], [144, "144"], [145, "145"], [146, "146"], [147, "147"], [148, "148"], [149, "149"], [150, "150"], [151, "151"], [152, "152"], [153, "153"], [154, "154"], [155, "155"], [156, "156"], [157, "157"], [158, "158"], [159, "159"], [160, "160"], [161, "161"], [162, "162"], [163, "163"], [164, "164"], [165, "165"], [166, "166"], [167, "167"], [168, "168"], [169, "169"], [170, "170"], [171, "171"], [172, "172"], [173, "173"], [174, "174"], [175, "175"], [176, "176"], [177, "177"], [178, "178"], [179, "179"], [180, "180"], [181, "181"], [182, "182"], [183, "183"], [184, "184"], [185, "185"], [186, "186"], [187, "187"], [188, "188"], [189, "189"], [190, "190"], [191, "191"], [192, "192"], [193, "193"], [194, "194"], [195, "195"], [196, "196"], [197, "197"], [198, "198"], [199, "199"], [200, "200"], [201, "201"], [202, "202"], [203, "225"], [204, "226"], [205, "227"], [206, "229"], [207, "230"], [208, "231"], [209, "232"], [210, "233"], [211, "234"], [212, "235"], [213, "236"], [214, "237"], [215, "238"], [216, "239"], [217, "240"], [218, "241"], [219, "242"], [220, "243"], [221, "244"], [222, "245"], [223, "246"], [224, "247"], [225, "280"], [226, "248"], [227, "249"], [228, "250"], [229, "251"], [230, "252"], [231, "253"], [232, "254"], [233, "257"], [234, "258"], [235, "259"], [236, "260"], [237, "261"], [238, "301"], [239, "262"], [240, "263"], [241, "304"], [242, "265"], [243, "266"], [244, "267"], [245, "268"], [246, "305"], [247, "306"], [248, "271"], [249, "272"], [250, "310"], [251, "311"], [252, "275"], [253, "276"], [255, "278"], [256, "279"], [257, "300"], [258, "302"], [259, "303"], [260, "307"], [261, "308"], [262, "309"], [263, "312"]] def self.up remove_column :countries, :ufsi_code remove_column :countries, :number_of_orders rename_column :countries, :fedex_code, :code add_column :countries, :rank, :integer add_column :countries, :is_obsolete, :boolean, :default => false, :null => false ActiveRecord::Base.transaction do # New countries to add. Country.create( [ { :code => "WS", :name => "Samoa" }, { :code => "RS", :name => "Serbia" }, { :code => "IM", :name => "Isle of Man" }, { :code => "GG", :name => "Guernsey" }, { :code => "AX", :name => "Åland Islands" }, { :code => "CK", :name => "Cook Islands" }, { :code => "JE", :name => "Jersey" }, { :code => "ME", :name => "Montenegro" }, { :code => "UM", :name => "United States Minor Outlying Islands" }, { :code => "BL", :name => "Saint Barthélemy" }, { :code => "MF", :name => "Saint Martin" } ] ) # Update codes and/or names of some countries. Country.update( 3, :name => "United Kingdom") Country.update( 30, :name => "Virgin Islands, British") Country.update( 31, :name => "Brunei Darussalam") Country.update( 45, :name => "Congo, Republic of the") Country.update( 48, :name => "Côte d'Ivoire") Country.update( 56, :name => "Timor-Leste") Country.update( 63, :name => "Falkland Islands (Malvinas)") Country.update( 89, :name => "Iran, Islamic Republic of") Country.update(100, :code => "KP", :name => "Korea, North") Country.update(102, :name => "Lao People's Democratic Republic") Country.update(107, :name => "Libyan Arab Jamahiriya") Country.update(117, :code => "ML") Country.update(131, :name => "Netherlands Antilles") Country.update(145, :name => "Pitcairn") Country.update(149, :name => "Réunion") Country.update(151, :name => "Russian Federation") Country.update(153, :name => "Saint Kitts and Nevis") Country.update(157, :name => "Saint Vincent and the Grenadines") Country.update(159, :name => "Sao Tome and Principe") Country.update(175, :name => "Syrian Arab Republic") Country.update(185, :name => "Turks and Caicos Islands") Country.update(187, :name => "Wallis and Futuna Islands") Country.update(194, :name => "Vatican City State") Country.update(196, :name => "Viet Nam") Country.update(202, :name => "Korea, South") Country.update(205, :code => "BY", :name => "Belarus") Country.update(206, :name => "Georgia") Country.update(216, :name => "Bosnia and Herzegovina") Country.update(221, :name => "Slovakia") Country.update(229, :name => "British Indian Ocean Territory") Country.update(232, :name => "Cocos (Keeling) Islands") Country.update(235, :name => "French Southern Territories") Country.update(237, :name => "Heard Island and McDonald Islands") Country.update(241, :name => "Micronesia, Federated States of") Country.update(249, :code => "PR") Country.update(250, :name => "South Georgia and the South Sandwich Islands") Country.update(251, :name => "Svalbard") Country.update(255, :name => "Virgin Islands, U.S.") Country.update(257, :name => "Congo, Democratic Republic of the") Country.update(260, :name => "Palestinian Territory, Occupied") # Initializing new columns. Country.update_all("is_obsolete = 0") Country.update_all("rank = 10") # Old countries to make obsolete. [15, 17, 34, 46, 97, 113, 182, 189, 198, 199, 209, 210, 211, 212, 218, 222, 223, 224, 225, 234, 238, 256, 258, 259, 261, 262, 263].each do |country_id| Country.find(country_id).update_attribute(:is_obsolete, true) end # Lower the rank of the countries we want to see first. Country.update(1, :rank => 0) end # transaction end def self.down add_column :countries, :ufsi_code, :string add_column :countries, :number_of_orders, :integer rename_column :countries, :code, :fedex_code remove_column :countries, :rank remove_column :countries, :is_obsolete ActiveRecord::Base.transaction do # Putting back old columns. # Put zeros at all number of orders then set those different of zero. Country.update_all("number_of_orders = 0") NOO_ARRAY.each do |a_pair| a_pair[0].each do |a_country_id| Country.update(a_country_id, :number_of_orders => a_pair[1]) end end # Put back ufsi codes. UFSI_ARRAY.each do |a_pair| Country.update(a_pair[0], :ufsi_code => a_pair[1]) end # Delete added countries. ["WS", "RS", "IM", "GG", "AX", "CK", "JE", "ME", "UM", "BL", "MF"].each do |country_code| Country.find_by_fedex_code(country_code).destroy end # Update codes and/or names of some countries back to original. Country.update( 3, :name => "Great Britian") Country.update( 30, :name => "British Virgin Islands") Country.update( 31, :name => "Brunei") Country.update( 45, :name => "Congo") Country.update( 48, :name => "Cote d'Ivoire") Country.update( 56, :name => "East Timor") Country.update( 63, :name => "Falkland Islands") Country.update( 89, :name => "Iran") Country.update(100, :fedex_code => "", :name => "Korea, Democ. Peoples Rep.") Country.update(102, :name => "Laos") Country.update(107, :name => "Libya") Country.update(117, :fedex_code => "MI") Country.update(131, :name => "Netherlands Antilies") Country.update(145, :name => "Pitcairn Islands") Country.update(149, :name => "Reunion Island") Country.update(151, :name => "Russia") Country.update(153, :name => "St. Christopher & Nevis") Country.update(157, :name => "St. Vincent&The Grenadines") Country.update(159, :name => "Sao Tome & Principe") Country.update(175, :name => "Syria") Country.update(185, :name => "Turks & Caicos Islands") Country.update(187, :name => "Wallis & Futuna Islands") Country.update(194, :name => "Vatican City") Country.update(196, :name => "Vietnam") Country.update(202, :name => "South Korea") Country.update(205, :fedex_code => "", :name => "Byelorussia (Belarus)") Country.update(206, :name => "Georgia, Republic Of") Country.update(216, :name => "Bosnia (Hercgovina)") Country.update(221, :name => "Slovak Republic") Country.update(229, :name => "British Indian Ocean Terri") Country.update(232, :name => "Cocos (keeling) Islands") Country.update(235, :name => "French Southern Territorie") Country.update(237, :name => "Heard And Mc Donald Island") Country.update(241, :name => "Micronesia") Country.update(249, :fedex_code => "US") Country.update(250, :name => "South Georgia And The Sout") Country.update(251, :name => "Svalbard And Jan Mayen Isl") Country.update(255, :name => "U.S. Virgin Islands") Country.update(257, :name => "Congo, The Democratic Republic") Country.update(260, :name => "Palestine") end # transaction end end
57.147783
112
0.533747
f8361abb79c822461b913860f564c990a21cc9d6
3,872
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like # NGINX, varnish or squid. # config.action_dispatch.rack_cache = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? # Set static files to be cached forever config.static_cache_control = "public, s-maxage=15552000, max-age=2592000" # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Use Postmark to send email config.action_mailer.delivery_method = :postmark config.action_mailer.postmark_settings = { :api_token => ENV.fetch("POSTMARK_API_TOKEN") } # Logging with Lograge config.lograge.enabled = true config.lograge.custom_options = lambda do |event| {remote_ip: event.payload[:remote_ip], user_id: event.payload[:user_id], params: event.payload[:params].except('controller', 'action', 'format', 'utf8')} end end
41.634409
157
0.761364
bb0341acd6d06c996e6ef0917988626ae7ca6559
510
config = YAML.load(ERB.new(IO.read(Rails.root + 'config' + 'redis.yml')).result)[Rails.env].with_indifferent_access redis_conn = { url: "redis://#{config[:host]}:#{config[:port]}/" } Sidekiq.configure_server do |s| s.redis = redis_conn Sidekiq::Status.configure_server_middleware s, expiration: 30.days Sidekiq::Status.configure_client_middleware s, expiration: 30.days end Sidekiq.configure_client do |s| s.redis = redis_conn Sidekiq::Status.configure_client_middleware s, expiration: 30.days end
36.428571
115
0.754902
ff74c9d637a9d364f57c5d2ed3fb7b6ccecd2cf8
49
module MusicBrainz class Area < Model end end
12.25
20
0.755102
e2aa3239094f61fb800cb89f99c996a0fa822297
1,761
require 'spec_helper' RSpec.describe 'Client draft 76 handshake' do let(:handshake) { WebSocket::Handshake::Client.new({ uri: 'ws://example.com/demo', origin: 'http://example.com', version: version }.merge(@request_params || {})) } let(:version) { 76 } let(:client_request) { client_handshake_76({ key1: handshake.handler.send(:key1), key2: handshake.handler.send(:key2), key3: handshake.handler.send(:key3) }.merge(@request_params || {})) } let(:server_response) { server_handshake_76({ challenge: handshake.handler.send(:challenge) }.merge(@request_params || {})) } it_should_behave_like 'all client drafts' it 'disallows client with invalid challenge' do @request_params = { challenge: 'invalid' } handshake << server_response expect(handshake).to be_finished expect(handshake).not_to be_valid expect(handshake.error).to be(:invalid_handshake_authentication) end context 'protocol header specified' do let(:handshake) { WebSocket::Handshake::Client.new(uri: 'ws://example.com/demo', origin: 'http://example.com', version: version, protocols: %w(binary)) } context 'supported' do it 'returns a valid handshake' do @request_params = { headers: { 'Sec-WebSocket-Protocol' => 'binary' } } handshake << server_response expect(handshake).to be_finished expect(handshake).to be_valid end end context 'unsupported' do it 'fails with an unsupported protocol error' do @request_params = { headers: { 'Sec-WebSocket-Protocol' => 'xmpp' } } handshake << server_response expect(handshake).to be_finished expect(handshake).not_to be_valid expect(handshake.error).to be(:unsupported_protocol) end end end end
38.282609
190
0.687677
38a4cebb683e5a3330da7696f926f6d566d81395
596
Pod::Spec.new do |spec| spec.name = "ImageTransition" spec.version = "0.5.0" spec.summary = "ImageTransition is a library for smooth animation of images during transitions." spec.homepage = "https://github.com/shtnkgm/ImageTransition" spec.license = { :type => "MIT", :file => "LICENSE" } spec.author = "shtnkgm" spec.platform = :ios, "12.0" spec.swift_version = "5.5" spec.source = { :git => "https://github.com/shtnkgm/ImageTransition.git", :tag => "#{spec.version}" } spec.source_files = "ImageTransition/**/*.swift" end
45.846154
111
0.61745
ac6c06d3d1b70c94648ba628647e2ecf0946c85d
1,371
require 'rails_helper' require 'rails/generators' require 'generators/croesus/croesus_generator' describe Croesus::Generators::CroesusGenerator, type: :generator do destination File.expand_path("../../tmp", __FILE__) before do prepare_destination copy_routes run_generator %w(baklava) end describe 'the authentication credentials migration' do subject { migration_file 'db/migrate/croesus_create_auth_credentials.rb' } it 'exists' do expect(subject).to exist end end describe 'the authenticatable model' do subject { file 'app/models/baklava.rb' } it 'exists' do expect(subject).to exist end it 'contains the croesus command' do expect(subject).to contain /^ croesus$/ end end describe 'the routes file' do subject { file 'config/routes.rb' } it 'contains croesus_for :baklava' do expect(subject).to contain /croesus_for :baklava/ end end describe 'the initializer' do subject { file 'config/initializers/croesus.rb' } it 'exists' do expect(subject).to exist end end def copy_routes routes = File.expand_path("../../../spec/test_app/config/routes.rb", __FILE__) destination = File.join(destination_root, "config") FileUtils.mkdir_p(destination) FileUtils.cp routes, destination end end
24.052632
82
0.681984
ed8c216c4cf246782b4f7bbc670c9623c1bd13fb
2,862
#require 'redis' module AuthHelpers include Rack::Utils alias_method :h, :escape_html def cgi_escape(text) URI.escape(CGI.escape(text.to_s), '.').gsub(' ','+') end def query_string(parameters, escape = true) if escape parameters.map{|key,val| val ? "#{cgi_escape(key)}=#{cgi_escape(val)}" : nil }.compact.join('&') else parameters.map{|key,val| val ? "#{key}=#{val}" : nil }.compact.join('&') end end def merge_uri_with_query_parameters(uri, parameters = {}) parameters = query_string(parameters) if uri.to_s =~ /\?/ parameters = "&#{parameters}" else parameters = "?#{parameters}" end URI.escape(uri.to_s) + parameters.to_s end def merge_uri_with_fragment_parameters(uri, parameters = {}) parameters = query_string(parameters) parameters = "##{parameters}" URI.escape(uri.to_s) + parameters.to_s end def merge_uri_based_on_response_type(uri, parameters = {}) case params[:response_type] when 'code', nil merge_uri_with_query_parameters(uri, parameters) when 'token', 'code_and_token' merge_uri_with_fragment_parameters(uri, parameters) else halt(400, 'Unsupported response type request') end end def sentry if Oauth2.sentry @sentry ||= Oauth2.sentry.new(request) else @sentry ||= request.env['warden'] || request.env['rack.auth'] || Sentry.new(request) end end def validate_redirect_uri! params[:redirect_uri] ||= sentry.user(:client).redirect_uri if URI(params[:redirect_uri]).host.to_s.downcase != URI(sentry.user(:client).redirect_uri).host.to_s.downcase halt(400, 'Invalid redirect URI') end rescue URI::InvalidURIError halt(400, 'Invalid redirect URI') end def authenticate! error!('401 Unauthorized', 401) unless headers['Auth'] == 'tokenke' #TODO rendesen bekötni a UI app-ot regisztrálva end def paginate(set, page_num, limit) if limit.nil? limit = LIMIT end if page_num.nil? page_num = 1 end # Get number of pages num_pages = 1 + set.size / limit start = (page_num - 1) * limit # Select range if set.respond_to? :range # It's a zset limited_set = set.revrange(start, start + limit) else # Normal set limited_set = set.sort(limit: [start, limit], order: 'DESC') end # Generate response page = Array.new limited_set.each do |element| page << element.to_hash end {:num_pages => num_pages, :page => page} end def rescue_db_errors #TODO error handling begin yield rescue Redis::BaseError => e AUTH.Logger.new(STDERR).error('Redis Error Rescued. Error message: #{e}.') {:success => false} end end end
26.018182
119
0.625087
bf3636de6c61f3b0088f7664b5d3ebb07aeb78d7
3,504
#-- encoding: UTF-8 #-- copyright # OpenProject is an open source project management software. # Copyright (C) 2012-2020 the OpenProject GmbH # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2017 Jean-Philippe Lang # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See docs/COPYRIGHT.rdoc for more details. #++ module API module V3 module WorkPackages module EagerLoading class Checksum < Base def apply(work_package) work_package.cache_checksum = cache_checksum_of(work_package) end def self.module CacheChecksumAccessor end class << self def for(work_package) fetch_checksums_for(Array(work_package))[work_package.id] end def fetch_checksums_for(work_packages) WorkPackage .where(id: work_packages.map(&:id).uniq) .left_joins(*checksum_associations) .pluck('work_packages.id', Arel.sql(md5_concat.squish)) .to_h end protected def md5_concat md5_parts = checksum_associations.map do |association_name| table_name = md5_checksum_table_name(association_name) %W[#{table_name}.id #{table_name}.updated_at] end.flatten <<-SQL MD5(CONCAT(#{md5_parts.join(', ')})) SQL end def checksum_associations %i[status author responsible assigned_to version priority category type] end def md5_checksum_table_name(association_name) case association_name when :responsible 'responsibles_work_packages' when :assigned_to 'assigned_tos_work_packages' else association_class(association_name).table_name end end def association_class(association_name) WorkPackage.reflect_on_association(association_name).class_name.constantize end end private def cache_checksum_of(work_package) cache_checksums[work_package.id] end def cache_checksums @cache_checksums ||= self.class.fetch_checksums_for(work_packages) end end module CacheChecksumAccessor extend ActiveSupport::Concern included do attr_accessor :cache_checksum end end end end end end
31.00885
91
0.630137
627be7e09b73725607c613ecdce19ffcbb901fa8
1,005
class AddCountsToEvents < ActiveRecord::Migration def change add_column :events, :bookmarks_count, :integer, :default => 0, null: false add_column :events, :attended_count, :integer, :default => 0, null: false add_column :events, :watchers_count, :integer, :default => 0, null: false add_column :events, :commentators_count, :integer, :default => 0, null: false Event.reset_column_information Event.find_each(select: 'id') do |event| Event.update_counters(event.id, :bookmarks_count => event.bookmarks.count) Event.update_counters(event.id, :attended_count => event.attended.count) Event.update_counters(event.id, :watchers_count => event.watchers.count) Event.update_counters(event.id, :commentators_count => event.commentators.count) end end def self.down remove_column :events, :bookmarks_count remove_column :events, :attended_count remove_column :events, :watchers_count remove_column :events, :commentators_count end end
40.2
86
0.733333
28995f4d18a375921236482d121a085c23c62e64
488
require 'minitest/autorun' $test = true require_relative "../breeder" class TestBreeder < Minitest::Test def initialize(test_name) super(test_name) end def test_bw_balance num_games = 200 size = 9 tolerance = 0.15 # 0.10=>10% (+ or -); the more games you play the lower tolerance you can set (but it takes more time...) b = Breeder.new(size) num_wins = b.bw_balance_check(num_games,size) assert_in_epsilon(num_wins,num_games/2,tolerance) end end
21.217391
126
0.696721
5d53e2c1f4539a55caa480bec1ee00d38d128f63
1,924
# Can be used to run different callbacks for each message bus response class MultiResponseMessageBusRequest class Error < StandardError; end def initialize(message_bus, subject) @message_bus = message_bus @subject = subject @responses = [] @response_timeouts = [] end def on_response(timeout, &response_callback) @responses.insert(0, response_callback) @response_timeouts.insert(0, timeout) end def request(data) raise ArgumentError, "at least one callback must be provided" if @responses.empty? raise ArgumentError, "request was already made" if @sid @sid = @message_bus.request(@subject, data) do |response, error| handle_received_response(response, error) end logger.info "request: sid=#{@sid} response='#{data}'" timeout_request end def ignore_subsequent_responses raise ArgumentError, "request was not yet made" unless @sid EM.cancel_timer(@timeout) if @timeout unsubscribe end private def handle_received_response(response, response_error = nil) logger.info "handle_received_response: sid=#{@sid} response='#{response}'" error = Error.new("Internal error: failed to decode response") if response_error timeout_request trigger_on_response(response, error) end def trigger_on_response(response, error) return unless (response_callback = @responses.pop) response_callback.call(response, error) end def timeout_request EM.cancel_timer(@timeout) if @timeout if (secs = @response_timeouts.pop) logger.info "timeout_request: sid=#{@sid} timeout=#{secs}" @timeout = EM.add_timer(secs) do unsubscribe trigger_on_response(nil, Error.new("Operation timed out")) end end end def unsubscribe logger.info "unsubscribe: sid=#{@sid}" @message_bus.unsubscribe(@sid) end def logger @logger ||= Steno.logger(self.class.name) end end
26.356164
86
0.710499
1a8b0cf56178de61dc7bf153618139a6479231dc
569
require 'rubygems' require 'xcodeproj' require 'fileutils' xcodeproj_filepath = ARGV[0] file_name = ARGV[1] group_name = ARGV[2] # Find group project = Xcodeproj::Project.open(xcodeproj_filepath) xcodeproj_group = project.main_group[group_name] # Remove file from group if xcodeproj_group != nil xcodeproj_group.files.find{ |file| if file.real_path.to_s.include? file_name file.referrers.each do |ref| if ref.isa == "PBXBuildFile" ref.remove_from_project end end file.remove_from_project end } end project.save
21.884615
53
0.71529
0388229712cee531a2b308ea4e9e5b60a748d67b
367
# 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::ResourceGraph::Mgmt::V2019_04_01 module Models # # Defines values for ResultTruncated # module ResultTruncated True = "true" False = "false" end end end
21.588235
70
0.694823
33674c9b03f6e987bb95fe9e50e7bd6179715064
198
class Genre < ApplicationRecord has_many :pokemon_types, dependent: :destroy has_many :pokemons, through: :pokemon_types validates :name, presence: true validates :slug, presence: true end
24.75
46
0.772727
d5dc0ef9c8565fc92105c8abfdaf775c2c1cb09d
154
require File.expand_path('../../../../spec_helper', __FILE__) describe "Zlib::GzipFile#os_code" do it "needs to be reviewed for spec completeness" end
25.666667
61
0.720779
ac72dd00c22def7de9300352b3c984a3bee8e674
464
# # encoding: utf-8 # Inspec test for recipe Wordpress::database # The Inspec reference, with examples and extensive documentation, can be # found at http://inspec.io/docs/reference/resources/ unless os.windows? # This is an example test, replace with your own test. describe user('root'), :skip do it { should exist } end end # This is an example test, replace it with your own test. describe port(80), :skip do it { should_not be_listening } end
24.421053
73
0.724138
f76b6394ba325c630570f3f3dd9552f1583afb13
605
Pod::Spec.new do |s| s.name = 'RNGridMenu' s.version = '0.1.1' s.license = 'MIT' s.platform = :ios, '5.0' s.summary = 'A grid menu with elastic layout, depth of field, and realistic animation.' s.homepage = 'https://github.com/rnystrom/RNGridMenu' s.author = { 'Ryan Nystrom' => '[email protected]'} s.source = { :git => 'https://github.com/rnystrom/RNGridMenu.git', :tag => '0.1.1' } s.source_files = 'RNGridMenu.{h,m}' s.requires_arc = true s.frameworks = 'QuartzCore', 'Accelerate' end
33.611111
97
0.568595
5d4958f88c507bd6bfc796bda41f44c216c6ff72
2,162
module Solargraph module LanguageServer module Message class Base # @return [Solargraph::LanguageServer::Host] attr_reader :host # @return [Integer] attr_reader :id # @return [Hash] attr_reader :request # @return [String] attr_reader :method # @return [Hash] attr_reader :params # @return [Hash, Array, nil] attr_reader :result # @return [Hash, nil] attr_reader :error # @param host [Solargraph::LanguageServer::Host] # @param request [Hash] def initialize host, request @host = host @id = request['id'].freeze @request = request.freeze @method = request['method'].freeze @params = (request['params'] || {}).freeze post_initialize end # @return [void] def post_initialize; end # @return [void] def process; end # @param data [Hash, Array, nil] # @return [void] def set_result data @result = data end # @param code [Integer] See Solargraph::LanguageServer::ErrorCodes # @param message [String] # @return [void] def set_error code, message @error = { code: code, message: message } end # @return [void] def send_response return if id.nil? if host.cancel?(id) Solargraph::Logging.logger.info "Cancelled response to #{method}" return end Solargraph::Logging.logger.info "Sending response to #{method}" response = { jsonrpc: "2.0", id: id, } response[:result] = result unless result.nil? response[:error] = error unless error.nil? response[:result] = nil if result.nil? and error.nil? json = response.to_json envelope = "Content-Length: #{json.bytesize}\r\n\r\n#{json}" Solargraph.logger.debug envelope host.queue envelope host.clear id end end end end end
25.738095
77
0.528677
1cc125d9f0536ffa92f73a8ccdae163c3bf3d277
15,069
require 'rexml/document' module ActiveMerchant #:nodoc: module Billing #:nodoc: # In NZ DPS supports ANZ, Westpac, National Bank, ASB and BNZ. # In Australia DPS supports ANZ, NAB, Westpac, CBA, St George and Bank of South Australia. # The Maybank in Malaysia is supported and the Citibank for Singapore. class PaymentExpressGateway < Gateway self.default_currency = 'NZD' # PS supports all major credit cards; Visa, Mastercard, Amex, Diners, BankCard & JCB. # Various white label cards can be accepted as well; Farmers, AirNZCard and Elders etc. # Please note that not all acquirers and Eftpos networks can support some of these card types. # VISA, Mastercard, Diners Club and Farmers cards are supported # # However, regular accounts with DPS only support VISA and Mastercard self.supported_cardtypes = %i[visa master american_express diners_club jcb] self.supported_countries = %w[AU FJ GB HK IE MY NZ PG SG US] self.homepage_url = 'https://www.windcave.com/' self.display_name = 'Windcave (formerly PaymentExpress)' self.live_url = 'https://sec.paymentexpress.com/pxpost.aspx' self.test_url = 'https://uat.paymentexpress.com/pxpost.aspx' APPROVED = '1' TRANSACTIONS = { purchase: 'Purchase', credit: 'Refund', authorization: 'Auth', capture: 'Complete', validate: 'Validate' } # We require the DPS gateway username and password when the object is created. # # The PaymentExpress gateway also supports a :use_custom_payment_token boolean option. # If set to true the gateway will use BillingId for the Token type. If set to false, # then the token will be sent as the DPS specified "DpsBillingId". This is per the documentation at # http://www.paymentexpress.com/technical_resources/ecommerce_nonhosted/pxpost.html#Tokenbilling def initialize(options = {}) requires!(options, :login, :password) super end # Funds are transferred immediately. # # `payment_source` can be a usual ActiveMerchant credit_card object, or can also # be a string of the `DpsBillingId` or `BillingId` which can be gotten through the # store method. If you are using a `BillingId` instead of `DpsBillingId` you must # also set the instance method `#use_billing_id_for_token` to true, see the `#store` # method for an example of how to do this. def purchase(money, payment_source, options = {}) request = build_purchase_or_authorization_request(money, payment_source, options) commit(:purchase, request) end # NOTE: Perhaps in options we allow a transaction note to be inserted # Verifies that funds are available for the requested card and amount and reserves the specified amount. # See: http://www.paymentexpress.com/technical_resources/ecommerce_nonhosted/pxpost.html#Authcomplete # # `payment_source` can be a usual ActiveMerchant credit_card object or a token, see #purchased method def authorize(money, payment_source, options = {}) request = build_purchase_or_authorization_request(money, payment_source, options) commit(:authorization, request) end # Transfer pre-authorized funds immediately # See: http://www.paymentexpress.com/technical_resources/ecommerce_nonhosted/pxpost.html#Authcomplete def capture(money, identification, options = {}) request = build_capture_or_credit_request(money, identification, options) commit(:capture, request) end # Refund funds to the card holder def refund(money, identification, options = {}) requires!(options, :description) request = build_capture_or_credit_request(money, identification, options) commit(:credit, request) end def credit(money, identification, options = {}) ActiveMerchant.deprecated CREDIT_DEPRECATION_MESSAGE refund(money, identification, options) end def verify(payment_source, options = {}) request = build_purchase_or_authorization_request(nil, payment_source, options) commit(:validate, request) end # Token Based Billing # # Instead of storing the credit card details locally, you can store them inside the # Payment Express system and instead bill future transactions against a token. # # This token can either be specified by your code or autogenerated by the PaymentExpress # system. The default is to let PaymentExpress generate the token for you and so use # the `DpsBillingId`. If you do not pass in any option of the `billing_id`, then the store # method will ask PaymentExpress to create a token for you. Additionally, if you are # using the default `DpsBillingId`, you do not have to do anything extra in the # initialization of your gateway object. # # To specify and use your own token, you need to do two things. # # Firstly, pass in a `:billing_id` as an option in the hash of this store method. No # validation is done on this BillingId by PaymentExpress so you must ensure that it is unique. # # gateway.store(credit_card, {:billing_id => 'YourUniqueBillingId'}) # # Secondly, you will need to pass in the option `{:use_custom_payment_token => true}` when # initializing your gateway instance, like so: # # gateway = ActiveMerchant::Billing::PaymentExpressGateway.new( # :login => 'USERNAME', # :password => 'PASSWORD', # :use_custom_payment_token => true # ) # # see: http://www.paymentexpress.com/technical_resources/ecommerce_nonhosted/pxpost.html#Tokenbilling # # Note, once stored, PaymentExpress does not support unstoring a stored card. def store(credit_card, options = {}) request = build_token_request(credit_card, options) commit(:validate, request) end def supports_scrubbing true end def scrub(transcript) transcript. gsub(%r((<PostPassword>).+(</PostPassword>)), '\1[FILTERED]\2'). gsub(%r((Authorization: Basic )\w+), '\1[FILTERED]\2'). gsub(%r((<CardNumber>)\d+(</CardNumber>)), '\1[FILTERED]\2'). gsub(%r((<Cvc2>)\d+(</Cvc2>)), '\1[FILTERED]\2') end private def use_custom_payment_token? @options[:use_custom_payment_token] end def build_purchase_or_authorization_request(money, payment_source, options) result = new_transaction if payment_source.is_a?(String) add_billing_token(result, payment_source) else add_credit_card(result, payment_source) end add_amount(result, money, options) if money add_invoice(result, options) add_address_verification_data(result, options) add_optional_elements(result, options) add_ip(result, options) result end def build_capture_or_credit_request(money, identification, options) result = new_transaction add_amount(result, money, options) add_invoice(result, options) add_reference(result, identification) add_optional_elements(result, options) add_ip(result, options) result end def build_token_request(credit_card, options) result = new_transaction add_credit_card(result, credit_card) add_amount(result, 100, options) # need to make an auth request for $1 add_token_request(result, options) add_optional_elements(result, options) add_ip(result, options) result end def add_credentials(xml) xml.add_element('PostUsername').text = @options[:login] xml.add_element('PostPassword').text = @options[:password] end def add_reference(xml, identification) xml.add_element('DpsTxnRef').text = identification end def add_credit_card(xml, credit_card) xml.add_element('CardHolderName').text = credit_card.name xml.add_element('CardNumber').text = credit_card.number xml.add_element('DateExpiry').text = format_date(credit_card.month, credit_card.year) if credit_card.verification_value? xml.add_element('Cvc2').text = credit_card.verification_value xml.add_element('Cvc2Presence').text = '1' end end def add_billing_token(xml, token) if use_custom_payment_token? xml.add_element('BillingId').text = token else xml.add_element('DpsBillingId').text = token end end def add_token_request(xml, options) xml.add_element('BillingId').text = options[:billing_id] if options[:billing_id] xml.add_element('EnableAddBillCard').text = 1 end def add_amount(xml, money, options) xml.add_element('Amount').text = amount(money) xml.add_element('InputCurrency').text = options[:currency] || currency(money) end def add_transaction_type(xml, action) xml.add_element('TxnType').text = TRANSACTIONS[action] end def add_invoice(xml, options) xml.add_element('TxnId').text = options[:order_id].to_s.slice(0, 16) unless options[:order_id].blank? xml.add_element('MerchantReference').text = options[:description].to_s.slice(0, 50) unless options[:description].blank? end def add_address_verification_data(xml, options) address = options[:billing_address] || options[:address] return if address.nil? xml.add_element('EnableAvsData').text = options[:enable_avs_data] || 1 xml.add_element('AvsAction').text = options[:avs_action] || 1 xml.add_element('AvsStreetAddress').text = address[:address1] xml.add_element('AvsPostCode').text = address[:zip] end def add_ip(xml, options) xml.add_element('ClientInfo').text = options[:ip] if options[:ip] end # The options hash may contain optional data which will be passed # through the specialized optional fields at PaymentExpress # as follows: # # { # :client_type => :web, # Possible values are: :web, :ivr, :moto, :unattended, :internet, or :recurring # :txn_data1 => "String up to 255 characters", # :txn_data2 => "String up to 255 characters", # :txn_data3 => "String up to 255 characters" # } # # +:client_type+, while not documented for PxPost, will be sent as # the +ClientType+ XML element as described in the documentation for # the PaymentExpress WebService: http://www.paymentexpress.com/Technical_Resources/Ecommerce_NonHosted/WebService#clientType # (PaymentExpress have confirmed that this value works the same in PxPost). # The value sent for +:client_type+ will be normalized and sent # as one of the explicit values allowed by PxPost: # # :web => "Web" # :ivr => "IVR" # :moto => "MOTO" # :unattended => "Unattended" # :internet => "Internet" # :recurring => "Recurring" # # If you set the +:client_type+ to any value not listed above, # the ClientType element WILL NOT BE INCLUDED at all in the # POST data. # # +:txn_data1+, +:txn_data2+, and +:txn_data3+ will be sent as # +TxnData1+, +TxnData2+, and +TxnData3+, respectively, and are # free form fields of the merchant's choosing, as documented here: # http://www.paymentexpress.com/technical_resources/ecommerce_nonhosted/pxpost.html#txndata # # These optional elements are added to all transaction types: # +purchase+, +authorize+, +capture+, +refund+, +store+ def add_optional_elements(xml, options) if client_type = normalized_client_type(options[:client_type]) xml.add_element('ClientType').text = client_type end xml.add_element('TxnData1').text = options[:txn_data1].to_s.slice(0, 255) unless options[:txn_data1].blank? xml.add_element('TxnData2').text = options[:txn_data2].to_s.slice(0, 255) unless options[:txn_data2].blank? xml.add_element('TxnData3').text = options[:txn_data3].to_s.slice(0, 255) unless options[:txn_data3].blank? end def new_transaction REXML::Document.new.add_element('Txn') end # Take in the request and post it to DPS def commit(action, request) add_credentials(request) add_transaction_type(request, action) url = test? ? self.test_url : self.live_url # Parse the XML response response = parse(ssl_post(url, request.to_s)) # Return a response PaymentExpressResponse.new(response[:success] == APPROVED, message_from(response), response, test: response[:test_mode] == '1', authorization: authorization_from(action, response)) end # Response XML documentation: http://www.paymentexpress.com/technical_resources/ecommerce_nonhosted/pxpost.html#XMLTxnOutput def parse(xml_string) response = {} xml = REXML::Document.new(xml_string) # Gather all root elements such as HelpText xml.elements.each('Txn/*') do |element| response[element.name.underscore.to_sym] = element.text unless element.name == 'Transaction' end # Gather all transaction elements and prefix with "account_" # So we could access the MerchantResponseText by going # response[account_merchant_response_text] xml.elements.each('Txn/Transaction/*') do |element| response[element.name.underscore.to_sym] = element.text end response end def message_from(response) (response[:card_holder_help_text] || response[:response_text]) end def authorization_from(action, response) case action when :validate (response[:billing_id] || response[:dps_billing_id] || response[:dps_txn_ref]) else response[:dps_txn_ref] end end def format_date(month, year) "#{format(month, :two_digits)}#{format(year, :two_digits)}" end def normalized_client_type(client_type_from_options) case client_type_from_options.to_s.downcase when 'web' then 'Web' when 'ivr' then 'IVR' when 'moto' then 'MOTO' when 'unattended' then 'Unattended' when 'internet' then 'Internet' when 'recurring' then 'Recurring' else nil end end end class PaymentExpressResponse < Response # add a method to response so we can easily get the token # for Validate transactions def token @params['billing_id'] || @params['dps_billing_id'] || @params['dps_txn_ref'] end end end end
40.291444
130
0.657841
87863da4ed9fe021fc9a8ea2080790fb1e1ab131
749
class Word @@words = [] attr_reader(:string_form, :definitions) define_method(:initialize) do |attributes| @string_form = attributes[:string_form] @definitions = [] end define_method(:add_definition) do |definition| @definitions.push(definition) end define_method(:save) do @@words.push(self) end define_singleton_method(:all) do @@words end define_singleton_method(:clear) do @@words = [] end define_singleton_method(:find) do |word_string| @@words.each() do |word| if word.string_form() == word_string return word end end nil end define_singleton_method(:delete) do |remove_word| @@words.select! {|word| word.string_form() != remove_word} end end
18.725
62
0.664887
39bd423140bf4f3c107816b224e0060b67d5738e
958
cask 'i1profiler' do version '1.7.2' sha256 '276aeda81784d074e50fc6b0a6f4b9a7ffca4e15496b58733ae50acb68091b15' url "https://downloads.xrite.com/downloads/software/i1Profiler/#{version}/Mac/i1Profiler.zip" name 'i1Profiler' name 'Eye-One Profiler' name 'i1Publish' homepage "http://www.xrite.com/service-support/downloads/I/i1Profiler-i1Publish_V#{version.dots_to_underscores}" pkg 'i1Profiler.pkg' uninstall pkgutil: [ 'com.xrite.i1profiler.*', 'com.xrite.xritedeviceservices.*', 'com.xrite.hasp.installer.*', ], launchctl: [ 'com.xrite.device.softwareupdate.plist', 'com.xrite.device.xrdd.plist', ], delete: '/Applications/i1Profiler/i1Profiler.app', rmdir: '/Applications/i1Profiler' caveats do reboot end end
33.034483
114
0.586639
1cccd366c116b574fd93508353a134aeeb8f67b2
5,885
require File.dirname(__FILE__) + '/../../../spec_helper' require File.dirname(__FILE__) + '/../fixtures/classes' describe "BasicSocket#setsockopt" do before(:each) do @sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) end after :each do @sock.close unless @sock.closed? end it "sets the socket linger to 0" do linger = [0, 0].pack("ii") @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER, linger).should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER) if (n.size == 8) # linger struct on some platforms, not just a value n.should == [0, 0].pack("ii") else n.should == [0].pack("i") end end it "sets the socket linger to some positive value" do linger = [64, 64].pack("ii") @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER, linger).should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER) if (n.size == 8) # linger struct on some platforms, not just a value n.should == [1, 64].pack("ii") else n.should == [64].pack("i") end end it "sets the socket option Socket::SO_OOBINLINE" do @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE, true).should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE) n.should == [1].pack("i") @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE, false).should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE) n.should == [0].pack("i") @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE, 1).should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE) n.should == [1].pack("i") @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE, 0).should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE) n.should == [0].pack("i") @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE, 2).should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE) n.should == [1].pack("i") platform_is_not :os => :windows do lambda { @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE, "") }.should raise_error(SystemCallError) end @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE, "blah").should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE) n.should == [1].pack("i") platform_is_not :os => :windows do lambda { @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE, "0") }.should raise_error(SystemCallError) end @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE, "\x00\x00\x00\x00").should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE) n.should == [0].pack("i") platform_is_not :os => :windows do lambda { @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE, "1") }.should raise_error(SystemCallError) end platform_is_not :os => :windows do lambda { @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE, "\x00\x00\x00") }.should raise_error(SystemCallError) end @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE, [1].pack('i')).should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE) n.should == [1].pack("i") @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE, [0].pack('i')).should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE) n.should == [0].pack("i") @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE, [1000].pack('i')).should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE) n.should == [1].pack("i") end it "sets the socket option Socket::SO_SNDBUF" do @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF, 4000).should == 0 sndbuf = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF) # might not always be possible to set to exact size sndbuf.unpack('i')[0].should >= 4000 @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF, true).should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF) n.unpack('i')[0].should >= 1 lambda { @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF, nil).should == 0 }.should raise_error(TypeError) @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF, 1).should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF) n.unpack('i')[0].should >= 1 @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF, 2).should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF) n.unpack('i')[0].should >= 2 lambda { @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF, "") }.should raise_error(SystemCallError) lambda { @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF, "bla") }.should raise_error(SystemCallError) lambda { @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF, "0") }.should raise_error(SystemCallError) lambda { @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF, "1") }.should raise_error(SystemCallError) lambda { @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF, "\x00\x00\x00") }.should raise_error(SystemCallError) @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF, "\x00\x00\x01\x00").should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF) n.unpack('i')[0].should >= "\x00\x00\x01\x00".unpack('i')[0] @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF, [4000].pack('i')).should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF) n.unpack('i')[0].should >= 4000 @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF, [1000].pack('i')).should == 0 n = @sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF) n.unpack('i')[0].should >= 1000 end end
37.246835
94
0.662192
4a57431ee254ac06fd9c4bd01ce4c9b0d2091b3f
14,339
module Typelib # Base class for all dynamic containers # # See the Typelib module documentation for an overview about how types are # values are represented. class ContainerType < IndirectType include Enumerable attr_reader :element_t def typelib_initialize super @element_t = self.class.deference @elements = [] end # Module used to extend frozen values module Freezer def clear; raise TypeError, "frozen object" end def do_set(*args); raise TypeError, "frozen object" end def do_delete_if(*args); raise TypeError, "frozen object" end def do_erase(*args); raise TypeError, "frozen object" end def do_push(*args); raise TypeError, "frozen object" end end # Module used to extend invalidated values module Invalidate def clear; raise TypeError, "invalidated object" end def size; raise TypeError, "invalidated object" end def length; raise TypeError, "invalidated object" end def do_set(*args); raise TypeError, "invalidated object" end def do_delete_if(*args); raise TypeError, "invalidated object" end def do_erase(*args); raise TypeError, "invalidated object" end def do_push(*args); raise TypeError, "invalidated object" end def do_each(*args); raise TypeError, "invalidated object" end def do_get(*args); raise TypeError, "invalidated object" end def contained_memory_id; raise TypeError, "invalidated object" end end # Call to freeze the object, i.e. to make it readonly def freeze super # Nothing to do here extend Freezer self end # Remove all elements from this container def clear do_clear invalidate_children end # Call to invalidate the object, i.e. to forbid any R/W access to it. # This is used in the framework when the underlying memory zone has been # made invalid by some operation (as e.g. container resizing) def invalidate super extend Invalidate self end def freeze_children super for obj in @elements obj.freeze if obj end end def invalidate_children super for obj in @elements obj.invalidate if obj end @elements.clear end # Module included in container types that offer random access # functionality module RandomAccessContainer # Private version of the getters, to bypass the index boundary # checks def raw_get_no_boundary_check(index) @elements[index] ||= do_get(index, true) end # Private version of the getters, to bypass the index boundary # checks def get_no_boundary_check(index) if @elements[index] return __element_to_ruby(@elements[index]) else value = do_get(index, false) if value.kind_of?(Typelib::Type) @elements[index] = value __element_to_ruby(value) else value end end end def raw_get(index) if index < 0 raise ArgumentError, "index out of bounds (#{index} < 0)" elsif index >= size raise ArgumentError, "index out of bounds (#{index} >= #{size})" end raw_get_no_boundary_check(index) end def raw_get_cached(index) @elements[index] end def get(index) self[index] end # Returns the value at the given index def [](index, chunk_size = nil) if chunk_size if index < 0 raise ArgumentError, "index out of bounds (#{index} < 0)" elsif (index + chunk_size) > size raise ArgumentError, "index out of bounds (#{index} + #{chunk_size} >= #{size})" end result = self.class.new chunk_size.times do |i| result.push(raw_get_no_boundary_check(index + i)) end result else if index < 0 raise ArgumentError, "index out of bounds (#{index} < 0)" elsif index >= size raise ArgumentError, "index out of bounds (#{index} >= #{size})" end get_no_boundary_check(index) end end def raw_set(index, value) if index < 0 || index >= size raise ArgumentError, "index out of bounds" end do_set(index, value) end def set(index, value) self[index] = value end def []=(index, value) v = __element_from_ruby(value) raw_set(index, v) end def raw_each return enum_for(:raw_each) if !block_given? for idx in 0...size yield(raw_get_no_boundary_check(idx)) end end def each return enum_for(:each) if !block_given? for idx in 0...size yield(get_no_boundary_check(idx)) end end end class DeepCopyArray < Array def dup result = DeepCopyArray.new for v in self result << v end result end end def self.subclass_initialize super if defined? super if random_access? include RandomAccessContainer end convert_from_ruby Array do |value, expected_type| t = expected_type.new t.concat(value) t end convert_from_ruby DeepCopyArray do |value, expected_type| t = expected_type.new t.concat(value) t end end def self.extend_for_custom_convertions if deference.contains_converted_types? self.contains_converted_types = true # There is a custom convertion on the elements of this # container. We have to convert to a Ruby array once and for all # # This can be *very* costly for big containers # # Note that it is called before super() so that it gets # overriden by convertions that are explicitely defined for this # type (i.e. that reference this type by name) convert_to_ruby Array do |value| # Convertion is done by #map result = DeepCopyArray.new for v in value result << v end result end end # This is done last so that convertions to ruby that refer to this # type by name can override the default convertion above super if defined? super if deference.needs_convertion_to_ruby? include ConvertToRuby end if deference.needs_convertion_from_ruby? include ConvertFromRuby end end # DEPRECATED. Use #push instead def insert(value) # :nodoc: Typelib.warn "Typelib::ContainerType#insert(value) is deprecated, use #push(value) instead" push(value) end # Adds a new value at the end of the sequence def push(*values) concat(values) end # Create a new container with the given size and element def self.of_size(size, element = deference.new) element = Typelib.from_ruby(element, deference).to_byte_array from_buffer([size].pack("Q") + element * size) end # This should return an object that allows to identify whether the # Typelib instances pointing to elements should be invalidated after # certain operations # # The default always returns nil, which means that no invalidation is # performed def contained_memory_id end def handle_container_invalidation memory_id = self.contained_memory_id yield ensure if invalidated? # All children have been invalidated already by #invalidate elsif memory_id && (memory_id != self.contained_memory_id) Typelib.debug { "invalidating all elements in #{raw_to_s}" } invalidate_children elsif @elements.size > self.size Typelib.debug { "invalidating #{@elements.size - self.size} trailing elements in #{raw_to_s}" } while @elements.size > self.size if el = @elements.pop el.invalidate end end end end module ConvertToRuby def __element_to_ruby(value) Typelib.to_ruby(value, element_t) end end module ConvertFromRuby def __element_from_ruby(value) Typelib.from_ruby(value, element_t) end end def __element_to_ruby(value) value end def __element_from_ruby(value) value end def concat(array) # NOTE: no need to care about convertions to ruby here, as -- when # the elements require a convertion to ruby -- we convert the whole # container to Array allocating_operation do for v in array do_push(__element_from_ruby(v)) end end self end def raw_each_cached(&block) @elements.compact.each(&block) end def raw_each return enum_for(:raw_each) if !block_given? idx = 0 do_each(true) do |el| yield(@elements[idx] ||= el) idx += 1 end end # Enumerates the elements of this container def each return enum_for(:each) if !block_given? idx = 0 do_each(false) do |el| if el.kind_of?(Typelib::Type) el = (@elements[idx] ||= el) el = __element_to_ruby(el) end yield(el) idx += 1 end end # Erases an element from this container def erase(el) # NOTE: no need to care about convertions to ruby here, as -- when # the elements require a convertion to ruby -- we convert the whole # container to Array handle_invalidation do do_erase(__element_from_ruby(el)) end end # Deletes the elements def delete_if # NOTE: no need to care about convertions to ruby here, as -- when # the elements require a convertion to ruby -- we convert the whole # container to Array handle_invalidation do do_delete_if do |el| yield(__element_to_ruby(el)) end end end # True if this container is empty def empty?; length == 0 end # Appends a new element to this container def <<(value); push(value) end def pretty_print(pp) apply_changes_from_converted_types index = 0 pp.text '[' pp.nest(2) do pp.breakable pp.seplist(enum_for(:each)) do |element| pp.text "[#{index}] = " element.pretty_print(pp) index += 1 end end pp.breakable pp.text ']' end # Returns the description of a type using only simple ruby objects # (Hash, Array, Numeric and String). # # { name: TypeName, # class: NameOfTypeClass, # CompoundType, ... # # The content of 'element' is controlled by the :recursive option # element: DescriptionOfArrayElement, # size: SizeOfTypeInBytes # Only if :layout_info is true # } # # @option (see Type#to_h) # @return (see Type#to_h) def self.to_h(options = Hash.new) info = super info[:element] = if options[:recursive] deference.to_h(options) else deference.to_h_minimal(options) end info end # (see Type#to_simple_value) # # Container types are returned as either an array of their converted # elements, or the hash described for the :pack_simple_arrays option. In # the latter case, a 'size' field is added with the number of elements # in the container to allow for validation on the receiving end. def to_simple_value(options = Hash.new) apply_changes_from_converted_types if options[:pack_simple_arrays] && element_t.respond_to?(:pack_code) Hash[pack_code: element_t.pack_code, size: size, data: Base64.strict_encode64(to_byte_array[8..-1])] else raw_each.map { |v| v.to_simple_value(options) } end end end end
33.424242
111
0.514053
1c307949c672d11825718f509288500f4a21412a
773
# # Cookbook Name:: postgresql # Resource:: user # actions :create, :update, :drop default_action :create attribute :name, kind_of: String, name_attribute: true attribute :superuser, kind_of: [TrueClass, FalseClass], default: false attribute :createdb, kind_of: [TrueClass, FalseClass], default: false attribute :createrole, kind_of: [TrueClass, FalseClass], default: false attribute :inherit, kind_of: [TrueClass, FalseClass], default: true attribute :replication, kind_of: [TrueClass, FalseClass], default: false attribute :login, kind_of: [TrueClass, FalseClass], default: true attribute :password, kind_of: String attribute :encrypted_password, kind_of: String attr_accessor :exists
36.809524
79
0.698577
4a2053ce31f3e6ccfcdba8d9b8d7100ec7a53bce
3,257
# # Copyright 2017, Noah Kantrowitz # # # 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 'spec_helper' describe PoiseDSL::DSL do # Declare some DSLs to work with for testing. Since these can't be cleaned up # there is no good way to isolate the tests right now. described_class.declare_dsl('poise-dsl_spec') do def helper_method_one 'one' end end described_class.declare_dsl('poise-dsl_other') do def helper_method_two 'two' end end described_class.declare_dsl(%w{poise-dsl_spec other}) do def helper_method_three 'three' end def helper_method_four 'four' end end described_class.declare_dsl(global: true) do def helper_method_five 'five' end end described_class.declare_dsl do def helper_method_six 'six' end end PoiseDSL do def helper_method_seven 'seven' end end context 'with a recipe-level helper' do recipe do val = helper_method_one file '/test' do content val end end it { is_expected.to create_file('/test').with(content: 'one') } end # /context with a recipe-level helper context 'with a resource-level helper' do recipe do file '/test' do content helper_method_one end end it { is_expected.to create_file('/test').with(content: 'one') } end # /context with a resource-level helper context 'with a helper declared for a different cookbook' do recipe do helper_method_two end it { expect { subject }.to raise_error NameError } end # /context with a helper declared for a different cookbook context 'with a helper defined using an array' do recipe do file '/test' do content helper_method_three + helper_method_four end end it { is_expected.to create_file('/test').with(content: 'threefour') } end # /context with a helper defined using an array context 'with a global helper' do recipe do file '/test' do content helper_method_five end end it { is_expected.to create_file('/test').with(content: 'five') } end # /context with a global helper context 'with an auto-named helper' do recipe do self.cookbook_name = 'poise-dsl' file '/test' do content helper_method_six end end it { is_expected.to create_file('/test').with(content: 'six') } end # /context with an auto-named helper context 'with the short definition syntax' do recipe do self.cookbook_name = 'poise-dsl' file '/test' do content helper_method_seven end end it { is_expected.to create_file('/test').with(content: 'seven') } end # /context with the short definition syntax end
23.264286
79
0.67731
ffa5901f1ceed7165ff77ef8ceeb98514096528c
1,345
module FaceB class Session attr_reader :api_key, :secret_key, :session_key, :user_facebook_uid def self.create(api_key, secret_key, session_key = nil) @current_session = self.new(api_key, secret_key, session_key) unless defined?(@current_session) && !!@current_session @current_session end def self.current @current_session end def self.reset! @current_session = nil end def reset! self.class.reset! end def initialize(api_key, secret_key, session_key = nil) @api_key = api_key @secret_key = secret_key @session_key = session_key secure_with_session_key!(session_key) unless !session_key end def call(method, params ={}) @scope = nil Api.new(self).call(method, params) end def secure_with_session_key!(session_key) @session_key = session_key @user_facebook_uid = self.call('users.getLoggedInUser', :session_key => session_key).data end def secured? !!@user_facebook_uid end # Allow session to dynamically call API method def method_missing(method_name, args={}) if !!@scope self.call("#{@scope}.#{method_name}", args) else @scope = method_name self end end end end
25.377358
123
0.623048
399a9a566b2cb786374c1f571e230044a7df2349
334
=begin #OpenAPI Extension generating aliases to maps and arrays as models #This specification shows how to generate aliases to maps and arrays as models. The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech OpenAPI Generator version: 5.3.0-SNAPSHOT =end module Petstore VERSION = '1.0.0' end
20.875
79
0.775449
38dea2222e207c46b556c10596c6ccc38265cfd4
1,128
require 'rails_helper' describe "Edit author page", type: :feature do before { @my_author = FactoryBot.create :author visit edit_author_path(@my_author) } it "should exist at 'edit_author_path' and render withour error" do end it "should edit an existing author in the database after submitting a filled form" do page.fill_in 'author[first_name]', with: 'Alann' page.fill_in 'author[last_name]', with: 'Turingg' page.fill_in 'author[homepage]', with: 'https://wikipedia.org/Alan_Turing' page.find('input[type="submit"]').click expect(page).to have_text('Alann') expect(page).to have_text('Turingg') expect(page).to have_text('https://wikipedia.org/Alan_Turing') end it "should display an error message if the edit is invalid" do page.fill_in 'author[first_name]', with: 'Foo' page.fill_in 'author[last_name]', with: '' page.fill_in 'author[homepage]', with: 'http://foo.bar' page.find('input[type="submit"]').click expect(page).to have_text(/error/i) expect(page).to have_text(/Last name can\'t be blank/) end end
40.285714
88
0.677305
bf16bf5ff88bc7ba8382591f3e4d63c6571d8778
9,685
assert 'File::Stat.new' do assert_kind_of File::Stat, File::Stat.new('README.md') assert_raise(RuntimeError){ File::Stat.new('unknown.file') } end assert 'File.stat' do assert_kind_of File::Stat, File.stat('README.md') end assert 'File.lstat' do assert_kind_of File::Stat, File.lstat('README.md') end assert 'File::Stat#initialize_copy' do orig = File::Stat.new('README.md') copy = orig.dup assert_equal orig.inspect, copy.inspect end assert 'File::Stat#<=>' do stat1 = File::Stat.new('README.md') stat2 = File::Stat.new('README.md') assert_equal 0, stat1.<=>(stat2) assert_equal nil, stat1.<=>(1) assert_raise(ArgumentError) { stat1 < 1 } end assert 'File::Stat#dev' do stat = File::Stat.new('README.md') assert_kind_of Fixnum, stat.dev end assert 'File::Stat#dev_major' do stat = File::Stat.new('README.md') if stat.dev_major assert_equal Fixnum, stat.dev_major.class else assert_nil stat.dev_major ## not supported end end assert 'File::Stat#dev_minor' do stat = File::Stat.new('README.md') if stat.dev_minor assert_equal Fixnum, stat.dev_minor.class else assert_nil stat.dev_minor ## not supported end end assert 'File::Stat#ino' do stat = File::Stat.new('README.md') assert_kind_of Numeric, stat.ino end assert 'File::Stat#mode' do stat = File::Stat.new('README.md') assert_kind_of Fixnum, stat.mode end assert 'File::Stat#nlink' do stat = File::Stat.new('README.md') assert_kind_of Fixnum, stat.nlink end assert 'File::Stat#uid' do stat = File::Stat.new('README.md') assert_kind_of Numeric, stat.uid end assert 'File::Stat#gid' do stat = File::Stat.new('README.md') assert_kind_of Numeric, stat.gid end assert 'File::Stat#rdev' do stat = File::Stat.new('README.md') assert_kind_of Fixnum, stat.rdev end assert 'File::Stat#rdev_major' do stat = File::Stat.new('README.md') if stat.rdev_major assert_equal Fixnum, stat.rdev_major.class else assert_nil stat.rdev_major ## not supported end end assert 'File::Stat#rdev_minor' do stat = File::Stat.new('README.md') if stat.rdev_minor assert_equal Fixnum, stat.rdev_minor.class else assert_nil stat.rdev_minor ## not supported end end assert 'File::Stat#blocks' do stat = File::Stat.new('README.md') blocks = stat.blocks skip "This system not support `struct stat.st_blocks`" if blocks.nil? assert_kind_of Integer, blocks end assert 'File::Stat#atime' do stat = File::Stat.new('README.md') assert_kind_of Time, stat.atime end assert 'File::Stat#mtime' do stat = File::Stat.new('README.md') assert_kind_of Time, stat.mtime end assert 'File::Stat#ctime' do stat = File::Stat.new('README.md') assert_kind_of Time, stat.ctime end assert 'File::Stat#birthtime' do stat = File::Stat.new('README.md') begin assert_kind_of Time, stat.birthtime rescue NameError skip 'This system not support `struct stat.birthtimespec`' end end assert 'File::Stat#size' do stat = File::Stat.new('README.md') assert_true 0 < stat.size end assert 'File::Stat#blksize' do stat = File::Stat.new('README.md') blksize = stat.blksize skip "This system not support `struct stat.st_blksize`" if blksize.nil? assert_kind_of Integer, blksize end assert 'File::Stat#inspect' do stat = File::Stat.new('README.md') %w(dev ino mode nlink uid gid size blksize blocks atime mtime ctime).all? do |name| assert_include stat.inspect, name end end assert 'File::Stat#ftype' do stat = File::Stat.new('README.md') assert_equal "file", stat.ftype stat = File::Stat.new('bin') assert_equal "directory", stat.ftype end assert 'File::Stat#directory?' do stat = File::Stat.new('README.md') assert_false stat.directory? stat = File::Stat.new('bin') assert_true stat.directory? end assert 'File::Stat#readable?' do skip "when windows" if FileStatTest.win? dir = __FILE__[0..-18] # 18 = /test/file-stat.rb FileStatTest.system("chmod +r-w-x #{dir}/test/readable") FileStatTest.system("chmod -r+w-x #{dir}/test/writable") FileStatTest.system("chmod -r-w+x #{dir}/test/executable") assert_true File::Stat.new("#{dir}/test/readable").readable? assert_false File::Stat.new("#{dir}/test/writable").readable? assert_false File::Stat.new("#{dir}/test/executable").readable? end assert 'File::Stat#readable_real?' do skip "when windows" if FileStatTest.win? dir = __FILE__[0..-18] # 18 = /test/file-stat.rb FileStatTest.system("chmod +r-w-x #{dir}/test/readable") FileStatTest.system("chmod -r+w-x #{dir}/test/writable") FileStatTest.system("chmod -r-w+x #{dir}/test/executable") assert_true File::Stat.new("#{dir}/test/readable").readable_real? assert_false File::Stat.new("#{dir}/test/writable").readable_real? assert_false File::Stat.new("#{dir}/test/executable").readable_real? end assert 'File::Stat#world_readable?' do skip "when windows" if FileStatTest.win? dir = __FILE__[0..-18] # 18 = /test/file-stat.rb FileStatTest.system("chmod 0400 #{dir}/test/readable") assert_equal nil, File::Stat.new("#{dir}/test/readable").world_readable? FileStatTest.system("chmod 0444 #{dir}/test/readable") assert_equal 0444, File::Stat.new("#{dir}/test/readable").world_readable? end assert 'File::Stat#writable?' do dir = __FILE__[0..-18] # 18 = /test/file-stat.rb FileStatTest.system("chmod +r-w-x #{dir}/test/readable") FileStatTest.system("chmod -r+w-x #{dir}/test/writable") FileStatTest.system("chmod -r-w+x #{dir}/test/executable") assert_false File::Stat.new("#{dir}/test/readable").writable? assert_true File::Stat.new("#{dir}/test/writable").writable? assert_false File::Stat.new("#{dir}/test/executable").writable? end assert 'File::Stat#writable_real?' do dir = __FILE__[0..-18] # 18 = /test/file-stat.rb FileStatTest.system("chmod +r-w-x #{dir}/test/readable") FileStatTest.system("chmod -r+w-x #{dir}/test/writable") FileStatTest.system("chmod -r-w+x #{dir}/test/executable") assert_false File::Stat.new("#{dir}/test/readable").writable_real? assert_true File::Stat.new("#{dir}/test/writable").writable_real? assert_false File::Stat.new("#{dir}/test/executable").writable_real? end assert 'File::Stat#world_writable?' do skip "when windows" if FileStatTest.win? dir = __FILE__[0..-18] # 18 = /test/file-stat.rb FileStatTest.system("chmod 0600 #{dir}/test/writable") assert_equal nil, File::Stat.new("#{dir}/test/writable").world_writable? FileStatTest.system("chmod 0666 #{dir}/test/writable") assert_equal 0666, File::Stat.new("#{dir}/test/writable").world_writable? end assert 'File::Stat#executable?' do skip "when windows" if FileStatTest.win? dir = __FILE__[0..-18] # 18 = /test/file-stat.rb FileStatTest.system("chmod +r-w-x #{dir}/test/readable") FileStatTest.system("chmod -r+w-x #{dir}/test/writable") FileStatTest.system("chmod -r-w+x #{dir}/test/executable") assert_false File::Stat.new("#{dir}/test/readable").executable? assert_false File::Stat.new("#{dir}/test/writable").executable? assert_true File::Stat.new("#{dir}/test/executable").executable? end assert 'File::Stat#executable_real?' do skip "when windows" if FileStatTest.win? dir = __FILE__[0..-18] # 18 = /test/file-stat.rb FileStatTest.system("chmod +r-w-x #{dir}/test/readable") FileStatTest.system("chmod -r+w-x #{dir}/test/writable") FileStatTest.system("chmod -r-w+x #{dir}/test/executable") assert_false File::Stat.new("#{dir}/test/readable").executable_real? assert_false File::Stat.new("#{dir}/test/writable").executable_real? assert_true File::Stat.new("#{dir}/test/executable").executable_real? end assert 'File::Stat#file?' do stat = File::Stat.new('README.md') assert_true stat.file? stat = File::Stat.new('bin') assert_false stat.file? end assert 'File::Stat#zero?' do stat = File::Stat.new('README.md') assert_false stat.zero? end assert 'File::Stat#size?' do stat = File::Stat.new('README.md') assert_true 0 < stat.size? end assert 'File::Stat#owned?' do stat = File::Stat.new('README.md') assert_true stat.owned? end assert 'File::Stat#owned_real?' do stat = File::Stat.new('README.md') assert_true stat.owned_real? end assert 'File::Stat#grpowned?' do is_unix = File::Stat.new('/dev/tty') rescue false if is_unix stat = File::Stat.new('README.md') assert_true stat.grpowned? else skip "is not supported" end end assert 'File::Stat#pipe?' do stat = File::Stat.new('README.md') assert_false stat.pipe? end assert 'File::Stat#symlink?' do stat = File::Stat.new('README.md') assert_false stat.symlink? end assert 'File::Stat#socket?' do stat = File::Stat.new('README.md') assert_false stat.socket? end assert 'File::Stat#blockdev?' do stat = File::Stat.new('README.md') assert_false stat.blockdev? end assert 'File::Stat#chardev?' do stat = File::Stat.new('README.md') assert_false stat.chardev? begin stat = File::Stat.new('/dev/tty') assert_true stat.chardev? rescue RuntimeError skip '/dev/tty is not found' end end assert 'File::Stat#setuid?' do stat = File::Stat.new('README.md') assert_false stat.setuid? end assert 'File::Stat#setgid?' do stat = File::Stat.new('README.md') assert_false stat.setgid? end assert 'File::Stat#sticky?' do stat = File::Stat.new('README.md') assert_false stat.sticky? end
28.569322
86
0.678369
ed46843e950ca9465b8bd76eacb32421336f0c2d
1,909
class SimCardsController < ApplicationController load_and_authorize_resource :sim_card_provider load_and_authorize_resource :sim_card, :through => [:sim_card_provider] before_filter :set_parent before_filter :spread_breadcrumbs def index end def show end def new @sim_card = @sim_card_provider.sim_cards.build @with_phones_connected_sip_account_ids = SipAccount.where(:id => PhoneSipAccount.pluck(:sip_account_id)).pluck(:id) @with_sim_cards_connected_sip_account_ids = SimCard.pluck(:sip_account_id) @available_sip_account_ids = SipAccount.pluck(:id) - (@with_phones_connected_sip_account_ids + @with_sim_cards_connected_sip_account_ids) @available_sip_accounts = SipAccount.where(:id => @available_sip_account_ids) if @available_sip_accounts.count == 0 redirect_to sim_card_provider_sim_cards_path(@sim_card_provider), :alert => t('sim_cards.controller.no_existing_sip_accounts_warning') end end def create @sim_card = @sim_card_provider.sim_cards.build(params[:sim_card]) if @sim_card.save redirect_to [@sim_card_provider, @sim_card], :notice => t('sim_cards.controller.successfuly_created') else render :new end end def destroy @sim_card.destroy redirect_to sim_card_provider_sim_cards_url(@sim_card_provider), :notice => t('sim_cards.controller.successfuly_destroyed') end private def set_parent @parent = @sim_card_provider end def spread_breadcrumbs add_breadcrumb t("sim_card_providers.index.page_title"), sim_card_providers_path add_breadcrumb @sim_card_provider, sim_card_provider_path(@sim_card_provider) add_breadcrumb t("sim_cards.index.page_title"), sim_card_provider_sim_cards_path(@sim_card_provider) if @sim_card && !@sim_card.new_record? add_breadcrumb @sim_card, sim_card_provider_sim_card_path(@sim_card_provider, @sim_card) end end end
32.913793
141
0.777894
e230d7fa7787d3b0cffd335320d9a3769e7d1d39
370
require "bundler/setup" require "garden_planner" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
24.666667
66
0.756757
f773ac5ab188fc0264ae60e69b5341e59338e8e6
1,193
require 'test_helper' class CategoriaControllerTest < ActionController::TestCase setup do @categorium = categoria(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:categoria) end test "should get new" do get :new assert_response :success end test "should create categorium" do assert_difference('Categorium.count') do post :create, categorium: { descricao: @categorium.descricao, user_id: @categorium.user_id } end assert_redirected_to categorium_path(assigns(:categorium)) end test "should show categorium" do get :show, id: @categorium assert_response :success end test "should get edit" do get :edit, id: @categorium assert_response :success end test "should update categorium" do patch :update, id: @categorium, categorium: { descricao: @categorium.descricao, user_id: @categorium.user_id } assert_redirected_to categorium_path(assigns(:categorium)) end test "should destroy categorium" do assert_difference('Categorium.count', -1) do delete :destroy, id: @categorium end assert_redirected_to categoria_path end end
23.86
114
0.720034
1d8d4daa6ca127f8bace8a8c7732a4ec8dd96b00
8,981
# frozen_string_literal: true require "rails_helper" feature "user form password field" do let(:mission) { get_mission } before { login(actor) } shared_examples("edit methods that should work online and offline") do scenario "leaving password unchanged should work" do visit(url) expect(page).to have_content("No change") select("No change", from: "user_reset_password_method") click_button("Save") expect(page).to have_content("updated successfully") end scenario "generating new password should work" do visit(url) expect(page).to have_content("Generate a new password and show printable login instructions") select("Generate a new password and show printable login instructions", from: "user_reset_password_method") click_button("Save") expect(page).to have_content("Login Instructions") end scenario "entering new password should work" do visit(url) expect(page).to have_content("Enter a new password") select("Enter a new password", from: "user_reset_password_method") fill_in("Password", with: "n3wP*ssword", match: :prefer_exact) fill_in("Retype Password", with: "n3wP*ssword", match: :prefer_exact) click_button("Save") expect(page).to have_content("updated successfully") end scenario "entering invalid password shows validation errors" do visit(url) select("Enter a new password", from: "user_reset_password_method") fill_in("Password", with: "n3wP*ssword", match: :prefer_exact) fill_in("Retype Password", with: "", match: :prefer_exact) click_button("Save") expect(page).to have_content("User is invalid") expect(page).to have_content("doesn't match Password") end scenario "entering new password with instructions should work" do visit(url) expect(page).to have_content("Enter a new password and show printable login instructions") select("Enter a new password and show printable login instructions", from: "user_reset_password_method") fill_in("Password", with: "n3wP*ssword", match: :prefer_exact) fill_in("Retype Password", with: "n3wP*ssword", match: :prefer_exact) click_button("Save") expect(page).to have_content("Login Instructions") end scenario "entering invalid password shows validation errors" do visit(url) select("Enter a new password and show printable login instructions", from: "user_reset_password_method") fill_in("Password", with: "n3wP*ssword", match: :prefer_exact) fill_in("Retype Password", with: "", match: :prefer_exact) click_button("Save") expect(page).to have_content("User is invalid") expect(page).to have_content("doesn't match Password") end end shared_examples("editing in online and offline mode") do context "online mode" do include_examples("edit methods that should work online and offline") scenario "sending password reset instructions via email should work" do visit(url) expect(page).to have_content("Send password reset instructions via email") select("Send password reset instructions via email", from: "user_reset_password_method") expect { click_button("Save") }.to change { ActionMailer::Base.deliveries.count }.by(1) expect(page).to have_content("updated successfully") end end context "offline mode" do around do |example| configatron.offline_mode = true example.run configatron.offline_mode = false end include_examples("edit methods that should work online and offline") scenario do visit(url) expect(page).to_not(have_content("Send password reset instructions via email")) end end end context "as admin" do let(:actor) { create(:admin, mission: mission) } context "creating user" do context "online mode" do scenario "setting enumerator password via printable should be unavailable in admin mode" do visit "/en/admin/users/new" expect(page).to have_content("Send password reset instructions via email") expect(page).not_to have_content("Generate a new password and show printable login instructions") end end context "offline mode" do around do |example| configatron.offline_mode = true example.run configatron.offline_mode = false end scenario "setting enumerator password via printable should work in admin mode" do visit "/en/admin/users/new" expect(page).to have_content("Generate a new password and show printable login instructions") expect(page).not_to have_content("Send password reset instructions via email") fill_out_form(role: nil, admin: true) select("Generate a new password and show printable login instructions", from: "user_reset_password_method") click_button("Save") expect(page).to have_content("Login Instructions") end end end end context "as coordinator" do let(:actor) { create(:user, role_name: :coordinator, mission: mission) } context "creating user" do context "online mode" do scenario "setting enumerator password via email should work" do visit "/en/m/#{mission.compact_name}/users/new" expect(page).to have_content("Send password reset instructions via email") expect(page).to have_content("Generate a new password and show printable login instructions") fill_out_form select("Send password reset instructions via email", from: "user_reset_password_method") expect { click_button("Save") }.to change { ActionMailer::Base.deliveries.count }.by(1) expect(page).to have_content("User created successfully") end scenario "setting enumerator password via email without email should fail" do visit "/en/m/#{mission.compact_name}/users/new" fill_out_form(email: false) select("Send password reset instructions via email", from: "user_reset_password_method") click_button("Save") expect(page).to have_content("Not allowed unless an email address is provided") end scenario "setting enumerator password via printable should work" do visit "/en/m/#{mission.compact_name}/users/new" fill_out_form select("Generate a new password and show printable login instructions", from: "user_reset_password_method") click_button("Save") expect(page).to have_content("Login Instructions") end end context "offline mode" do around do |example| configatron.offline_mode = true example.run configatron.offline_mode = false end scenario "setting enumerator password via email should be unavailable" do visit "/en/m/#{mission.compact_name}/users/new" expect(page).to have_content("Generate a new password and show printable login instructions") expect(page).not_to have_content("Send password reset instructions via email") end scenario "setting coordinator password via printable should work" do visit "/en/m/#{mission.compact_name}/users/new" fill_out_form(role: "Coordinator") select("Generate a new password and show printable login instructions", from: "user_reset_password_method") click_button("Save") expect(page).to have_content("Login Instructions") end end end context "editing user in mission mode" do let(:url) { "/en/m/#{mission.compact_name}/users/#{target_user.id}/edit" } context "acting on enumerator" do let(:target_user) { create(:user, role_name: :enumerator) } include_examples("editing in online and offline mode") end end end context "as enumerator" do let(:actor) { create(:user, role_name: :enumerator, mission: mission) } context "editing user in mission mode" do let(:url) { "/en/m/#{mission.compact_name}/users/#{target_user.id}/edit" } context "acting on self" do let(:target_user) { actor } include_examples("editing in online and offline mode") end context "acting on other enumerator" do let(:target_user) { create(:user, role_name: :enumerator) } scenario "should be forbidden" do visit(url) expect(page).to have_content("Unauthorized") end end end end def fill_out_form(role: "Enumerator", email: true, admin: false) fill_in("* Full Name", with: "Foo") fill_in("* Username", with: "foo") select(role, from: "user_assignments_attributes_0_role") unless role.nil? fill_in("Email", with: "[email protected]") if email check("Is Admin?") if admin end end
39.047826
107
0.669747
18a41fe889664bb012d7b04f6ec0d051d652274b
11,174
require "feidee_utils_test" require "feidee_utils/transaction" require "feidee_utils/database" require 'minitest/autorun' class FeideeUtils::TransactionTest < MiniTest::Test def setup @sqlite_db = FeideeUtils::TestUtils.open_test_sqlite @all = @sqlite_db.ledger::Transaction.all @income = @all.find do |transaction| transaction.poid == -6 end @expenditure = @all.find do |transaction| transaction.poid == -5 end @transfer_out = @all.find do |transaction| transaction.poid == -9 end @transfer_in = @all.find do |transaction| transaction.poid == -10 end @debit_init = @all.find do |transaction| transaction.poid == -1 end @credit_init = @all.find do |transaction| transaction.poid == -2 end end def test_fields assert_equal 1433311141000, @income.raw_created_at assert_equal 1433311126000, @expenditure.raw_created_at assert_equal 1433311162000, @income.raw_modified_at assert_equal 1433311316000, @expenditure.raw_modified_at assert_equal 1433347200000, @income.raw_trade_at assert_equal 1433347200000, @expenditure.raw_trade_at assert_equal 1, @income.raw_type assert_equal 0, @expenditure.raw_type assert_equal "", @income.memo assert_equal "", @expenditure.memo assert_equal "Pay back", @transfer_in.memo assert_equal 0, @income.buyer_account_poid assert_equal (-18), @expenditure.buyer_account_poid assert_equal (-58), @income.buyer_category_poid assert_equal 0, @expenditure.buyer_category_poid assert_equal (-17), @income.seller_account_poid assert_equal 0, @expenditure.seller_account_poid assert_equal 0, @income.seller_category_poid assert_equal (-16), @expenditure.seller_category_poid assert_equal 125, @income.raw_buyer_deduction assert_equal 75, @expenditure.raw_buyer_deduction assert_equal 125, @income.raw_seller_addition assert_equal 75, @expenditure.raw_seller_addition assert_nil @income.uuid assert_nil @expenditure.uuid assert_equal "03886DB7-F1C0-4667-9148-73498FCAE501", @transfer_in.uuid end def test_type assert_equal :expenditure, @expenditure.type assert_equal :income, @income.type assert_equal 2, @transfer_in.raw_type assert_equal 3, @transfer_out.raw_type assert_equal :transfer_seller, @transfer_in.type assert_equal :transfer_buyer, @transfer_out.type assert_equal 8, @debit_init.raw_type assert_equal 9, @credit_init.raw_type assert_equal :positive_initial_balance, @debit_init.type assert_equal :negative_initial_balance, @credit_init.type end def test_is_transfer refute @income.is_transfer? refute @expenditure.is_transfer? assert @transfer_in.is_transfer? assert @transfer_out.is_transfer? refute @debit_init.is_transfer? refute @credit_init.is_transfer? end def test_is_initial_balance refute @income.is_initial_balance? refute @expenditure.is_initial_balance? refute @transfer_in.is_initial_balance? refute @transfer_out.is_initial_balance? assert @debit_init.is_initial_balance? assert @credit_init.is_initial_balance? end def test_validate_global_integrity_errors values = build_transaction_with_columns({ "type" => 3, "amount" => 100, "modifiedTime" => 0, "createdTime" => 0, "lastUpdateTime" => 0, "tradeTime" => 0, "buyerCategoryPOID" => 0, "sellerCategoryPOID" => 0, }) extra_transaction = @sqlite_db.ledger::Transaction.new(values) assert extra_transaction.is_transfer? extra_transactions = @all + [ extra_transaction ] @sqlite_db.ledger::Transaction.class_eval do define_singleton_method :all do extra_transactions end end assert_raises FeideeUtils::Transaction::TransfersNotPaired do @sqlite_db.ledger::Transaction.validate_global_integrity end end def test_uuid transfers = @all.select do |transaction| transaction.is_transfer? end refute_empty transfers transfers.each do |transfer| refute_empty transfer.uuid, "#{transfer.poid} should have a uuid" end end def test_validate_global_integrity @sqlite_db.ledger::Transaction.validate_global_integrity end def test_credit_account_init_amount credit_init = @all.select do |transaction| transaction.raw_type == 9 end.map do |transaction| transaction.amount end assert_equal [-500, -400], credit_init.sort end def test_memo memo_trans = @all.find do |transaction| transaction.poid == -9 end assert_equal "Pay back", memo_trans.memo memo_trans = @all.find do |transaction| transaction.poid == -10 end assert_equal "Pay back", memo_trans.memo end def test_timestamps @all.each do |transaction| assert_equal 2015, transaction.modified_at.year assert_equal 2015, transaction.created_at.year assert_equal 2015, transaction.trade_at.year assert_equal 2015, transaction.last_update_time.year end end def test_seller_account_poid assert_equal (-17), @income.seller_account_poid assert_equal 0, @expenditure.seller_account_poid assert_equal (-19), @transfer_in.seller_account_poid assert_equal (-19), @transfer_out.seller_account_poid assert_equal (-17), @debit_init.seller_account_poid assert_equal (-18), @credit_init.seller_account_poid end def test_buyer_account_poid assert_equal 0, @income.buyer_account_poid assert_equal (-18), @expenditure.buyer_account_poid assert_equal (-20), @transfer_in.buyer_account_poid assert_equal (-20), @transfer_out.buyer_account_poid assert_equal 0, @debit_init.buyer_account_poid assert_equal 0, @credit_init.buyer_account_poid end def test_validate_account_integrity_errors values1 = build_transaction_with_columns({ "buyerAccountPOID" => 2, "sellerAccountPOID" => 3 }) assert_raises FeideeUtils::Transaction::InconsistentBuyerAndSellerException do # nolint @sqlite_db.ledger::Transaction.new(values1) end values2 = build_transaction_with_columns({ "buyerAccountPOID" => 0, "sellerAccountPOID" => 0 }) assert_raises FeideeUtils::Transaction::InconsistentBuyerAndSellerException do # nolint @sqlite_db.ledger::Transaction.new(values2) end end def test_transfer_validate_account_integrity_errors values1 = build_transaction_with_columns({ "type" => 2, "buyerAccountPOID" => 0 }) assert_raises FeideeUtils::Transaction::TransferLackBuyerOrSellerException do # nolint @sqlite_db.ledger::Transaction.new(values1) end values2 = build_transaction_with_columns({ "type" => 2, "sellerAccountPOID" => 0 }) assert_raises FeideeUtils::Transaction::TransferLackBuyerOrSellerException do # nolint @sqlite_db.ledger::Transaction.new(values2) end end def test_has_category assert @income.has_category? refute @transfer_in.has_category? refute @transfer_out.has_category? end def test_category_poid assert_equal (-58), @income.category_poid assert_equal (-16), @expenditure.category_poid end def test_validate_category_integrity_errors values = build_transaction_with_columns({ "buyerAccountPOID" => 0, "buyerCategoryPOID" => 1, "sellerCategoryPOID" => 2 }) assert_raises FeideeUtils::Transaction::InconsistentCategoryException do @sqlite_db::ledger::Transaction.new(values) end end def test_transfer_validate_category_integrity_errors values1 = build_transaction_with_columns({ "type" => 3, "buyerCategoryPOID" => 2 }) assert_raises FeideeUtils::Transaction::TransferWithCategoryException do @sqlite_db::ledger::Transaction.new(values1) end values2 = build_transaction_with_columns({ "type" => 3, "sellerCategoryPOID" => 2 }) assert_raises FeideeUtils::Transaction::TransferWithCategoryException do @sqlite_db::ledger::Transaction.new(values2) end end # ID 1..14, 16..19, 21 Amounts = [ 100, -400, -500, 200, # Initial balances 75, 125, # expenditure and income 100, 100, 100, 100, # 2 transfers 25, 25, 50, 50, # another 2 transfers 100, 100, 100, 16, # 2 more transfers, one is forex. 200, # Initial balance of a claim account. ] def test_amount @all.zip(Amounts).each do |transaction, amount| assert_equal amount, transaction.amount, "#{transaction.poid} incorrect amount" end end def test_validate_amount_integrity_errors values = build_transaction_with_columns({ "buyerAccountPOID" => 0, "buyerCategoryPOID" => 0, "sellerCategoryPOID" => 0, "buyerMoney" => 0, "sellerMoney" => 1 }) assert_raises FeideeUtils::Transaction::InconsistentAmountException do @sqlite_db::ledger::Transaction.new(values) end end def test_validate_integrity values1 = build_transaction_with_columns({ "buyerAccountPOID" => 0, "sellerAccountPOID" => 1, "buyerCategoryPOID" => 0, "sellerCategoryPOID" => 2, "buyerMoney" => 0, "sellerMoney" => 0 }) @sqlite_db.ledger::Transaction.new(values1) values2 = build_transaction_with_columns({ "buyerAccountPOID" => 2, "sellerAccountPOID" => 0, "buyerCategoryPOID" => 2, "sellerCategoryPOID" => 0, "buyerMoney" => 0, "sellerMoney" => 0 }) @sqlite_db.ledger::Transaction.new(values2) end def test_transfer_validate_integrity # Type 2 values1 = build_transaction_with_columns({ "buyerAccountPOID" => 2, "sellerAccountPOID" => 1, "buyerCategoryPOID" => 0, "sellerCategoryPOID" => 0, "type" => 2 }) @sqlite_db.ledger::Transaction.new(values1) # Type 3 values2 = build_transaction_with_columns({ "buyerAccountPOID" => 2, "sellerAccountPOID" => 1, "buyerCategoryPOID" => 0, "sellerCategoryPOID" => 0, "type" => 3 }) @sqlite_db.ledger::Transaction.new(values2) end def test_revised_account_poid assert_equal (-17), @income.revised_account_poid assert_equal (-18), @expenditure.revised_account_poid assert_equal (-19), @transfer_in.revised_account_poid assert_equal (-20), @transfer_out.revised_account_poid assert_equal (-17), @debit_init.revised_account_poid assert_equal (-18), @credit_init.revised_account_poid end def test_revised_amount assert_equal @income.amount, @income.revised_amount assert_equal ([email protected]), @expenditure.revised_amount assert_equal @transfer_in.amount, @transfer_in.revised_amount assert_equal (-@transfer_out.amount), @transfer_out.revised_amount assert_equal @debit_init.amount, @debit_init.revised_amount # This looks wrong to me. assert_equal @credit_init.seller_addition, @credit_init.revised_amount # TODO: Add a test for forex transaction where buyer/seller amount are # different end def build_transaction_with_columns values @sqlite_db.ledger::Transaction.column_names.map do |name| values[name] end end end
32.201729
91
0.718185
e22ee74af56cddf11dfa1d2144ea7d3cde0f5a8b
354
cask :v1 => 'moreamp' do version '0.1.29' sha256 '770dad0b69979f51807dee3f873e0ebbb755f9f2f2f60c734ac55094e6a6f707' url "http://downloads.sourceforge.net/project/moreamp/moreamp/MoreAmp-#{version}/MoreAmp-#{version}-binOSX104intel.dmg" name 'MoreAmp' homepage 'http://sourceforge.net/projects/moreamp/' license :oss app 'MoreAmp.app' end
29.5
121
0.762712
62fbae7c181a2b5996bd92ffe939d0508e48c659
5,542
Navigasmic.configure do |config| # Defining Navigation Structures: # # You can define your navigation structures and configure the builders in this initializer. # # When defining navigation here, it's important to understand that the scope is not the same as the view scope -- and # you should use procs where you want things to execute in the view scope. # # Once you've defined some navigation structures and configured your builders you can render navigation in your views # using the `semantic_navigation` view helper. You can also use the same syntax to define your navigation structures # in your views -- and eventually move them here if you want. # # <%= semantic_navigation :primary %> # # You can optionally provided a :builder and :config option to the semantic_navigation view helper. # # <%= semantic_navigation :primary, config: :blockquote %> # <%= semantic_navigation :primary, builder: Navigasmic::Builder::MapBuilder %> # # When defining navigation in your views just pass it a block. # # <%= semantic_navigation :primary do |n| %> # <% n.item "About Me" %> # <% end %> # # Here's a basic example: config.semantic_navigation :primary do |n| n.item "Home", "/" # Groups and Items: # # Create navigation structures using the `group`, and `item` methods. You can nest items inside groups or items. In # the following example, the "Articles" item will always highlight on the blog/posts controller, and the nested # article items will only highlight on those specific pages. The "Links" item will be disabled unless the user is # logged in. # #n.group "Blog" do # n.item "Articles", controller: "/blog/posts" do # n.item "First Article", "/blog/posts/1" # n.item "Second Article", "/blog/posts/2", map: { changefreq: "weekly" } # end # n.item "Links", controller: "/blog/links", disabled_if: proc { !logged_in? } #end # You can hide specific specific items or groups, and here we specify that the "Admin" section of navigation should # only be displayed if the user is logged in. # #n.group "Admin", hidden_unless: proc{ logged_in? } do # n.item "Manage Posts", class: "posts", link_html: { data: { tools: "posts" } } #end # Scoping: # # Scoping is different than in the view here, so we've provided some nice things for you to get around that. In the # above example we just provide "/" as what the home page is, but that may not be correct. You can also access the # path helpers, using a proc, or by proxying them through the navigation object. Any method called on the navigation # scope will be called within the scope of the view. # #n.item "Home", proc { root_path } #n.item "Home", n.root_path # This proxy behavior can be used for I18n as well. # #n.item n.t("hello"), "/" end # Setting the Default Builder: # # By default the Navigasmic::Builder::ListBuilder is used unless otherwise specified. # # You can change this here: #config.default_builder = MyCustomBuilder # Configuring Builders: # # You can change various builder options here by specifying the builder you want to configure and the options you # want to change. # # Changing the default ListBuilder options: #config.builder Navigasmic::Builder::ListBuilder do |builder| # builder.wrapper_class = 'semantic-navigation' #end # Naming Builder Configurations: # # If you want to define a named configuration for a builder, just provide a hash with the name and the builder to # configure. The named configurations can then be used during rendering by specifying a `:config => :bootstrap` # option. # # A Twitter Bootstrap configuration: # # Example usage: # # <%= semantic_navigation :primary, config: :bootstrap, class: "nav-pills" %> # # Or to create a full navigation bar using twitter bootstrap you could use the following in your view: # # <div class="navbar"> # <div class="navbar-inner"> # <a class="brand" href="/">Title</a> # <%= semantic_navigation :primary, config: :bootstrap %> # </div> # </div> config.builder bootstrap: Navigasmic::Builder::ListBuilder do |builder| # Set the nav and nav-pills css (you can also use 'nav nav-tabs') -- or remove them if you're using this inside a # navbar. builder.wrapper_class = "nav nav-pills" # Set the classed for items that have nested items, and that are nested items. builder.has_nested_class = "dropdown" builder.is_nested_class = "dropdown-menu" # For dropdowns to work you'll need to include the bootstrap dropdown js # For groups, we adjust the markup so they'll be clickable and be picked up by the javascript. builder.label_generator = proc do |label, options, has_link, has_nested| if !has_nested || has_link "<span>#{label}</span>" else link_to(%{#{label}<b class="caret"></b>}.html_safe, "#", class: "dropdown-toggle", data: { toggle: "dropdown" }) end end # For items, we adjust the links so they're "#", and do the same as for groups. This allows us to use more complex # highlighting rules for dropdowns. builder.link_generator = proc do |label, link, link_options, has_nested| if has_nested link = "#" label << %{<b class="caret"></b>} link_options.merge!(class: "dropdown-toggle", data: { toggle: "dropdown" }) end link_to(label, link, link_options) end end end
41.051852
120
0.679899
617c320d1cebde4159e3b4ca84711a210efbb7f5
859
# # Cookbook:: chef-atom # Recipe:: windows # # Copyright:: (c) 2016 Doug Ireton # # 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. package 'Atom' do # ~FC009 source node['chefdk_bootstrap']['atom']['source_url'] remote_file_attributes( path: File.join(Chef::Config[:file_cache_path], 'AtomSetup.exe') ) installer_type :custom options '/silent' end
31.814815
74
0.738068
ed155e6dcc0ef7ee9455a270bd8d9ced14908f9a
13,790
require 'test_helper' class MonerisTest < Test::Unit::TestCase include CommStub def setup Base.mode = :test @gateway = MonerisGateway.new( :login => 'store1', :password => 'yesguy' ) @amount = 100 @credit_card = credit_card('4242424242424242') @options = { :order_id => '1', :customer => '1', :billing_address => address} end def test_default_options assert_equal 7, @gateway.options[:crypt_type] assert_equal "store1", @gateway.options[:login] assert_equal "yesguy", @gateway.options[:password] end def test_successful_purchase @gateway.expects(:ssl_post).returns(successful_purchase_response) assert response = @gateway.authorize(100, @credit_card, @options) assert_success response assert_equal '58-0_3;1026.1', response.authorization end def test_failed_purchase @gateway.expects(:ssl_post).returns(failed_purchase_response) assert response = @gateway.authorize(100, @credit_card, @options) assert_failure response end def test_deprecated_credit @gateway.expects(:ssl_post).with(anything, regexp_matches(/txn_number>123<\//), anything).returns("") @gateway.expects(:parse).returns({}) assert_deprecation_warning(Gateway::CREDIT_DEPRECATION_MESSAGE) do @gateway.credit(@amount, "123;456", @options) end end def test_refund @gateway.expects(:ssl_post).with(anything, regexp_matches(/txn_number>123<\//), anything).returns("") @gateway.expects(:parse).returns({}) @gateway.refund(@amount, "123;456", @options) end def test_amount_style assert_equal '10.34', @gateway.send(:amount, 1034) assert_raise(ArgumentError) do @gateway.send(:amount, '10.34') end end def test_preauth_is_valid_xml params = { :order_id => "order1", :amount => "1.01", :pan => "4242424242424242", :expdate => "0303", :crypt_type => 7, } assert data = @gateway.send(:post_data, 'preauth', params) assert REXML::Document.new(data) assert_equal xml_capture_fixture.size, data.size end def test_purchase_is_valid_xml params = { :order_id => "order1", :amount => "1.01", :pan => "4242424242424242", :expdate => "0303", :crypt_type => 7, } assert data = @gateway.send(:post_data, 'purchase', params) assert REXML::Document.new(data) assert_equal xml_purchase_fixture.size, data.size end def test_capture_is_valid_xml params = { :order_id => "order1", :amount => "1.01", :pan => "4242424242424242", :expdate => "0303", :crypt_type => 7, } assert data = @gateway.send(:post_data, 'preauth', params) assert REXML::Document.new(data) assert_equal xml_capture_fixture.size, data.size end def test_supported_countries assert_equal ['CA'], MonerisGateway.supported_countries end def test_supported_card_types assert_equal [:visa, :master, :american_express, :diners_club, :discover], MonerisGateway.supported_cardtypes end def test_should_raise_error_if_transaction_param_empty_on_credit_request [nil, '', '1234'].each do |invalid_transaction_param| assert_raise(ArgumentError) { @gateway.void(invalid_transaction_param) } end end def test_successful_store @gateway.expects(:ssl_post).returns(successful_store_response) assert response = @gateway.store(@credit_card) assert_success response assert_equal "Successfully registered cc details", response.message assert response.params["data_key"].present? @data_key = response.params["data_key"] end def test_successful_unstore @gateway.expects(:ssl_post).returns(successful_unstore_response) test_successful_store assert response = @gateway.unstore(@data_key) assert_success response assert_equal "Successfully deleted cc details", response.message assert response.params["data_key"].present? end def test_update @gateway.expects(:ssl_post).returns(successful_update_response) test_successful_store assert response = @gateway.update(@data_key, @credit_card) assert_success response assert_equal "Successfully updated cc details", response.message assert response.params["data_key"].present? end def test_successful_purchase_with_vault @gateway.expects(:ssl_post).returns(successful_purchase_response) test_successful_store assert response = @gateway.purchase(100, @data_key, {:order_id => generate_unique_id, :customer => generate_unique_id}) assert_success response assert_equal "Approved", response.message assert response.authorization.present? end def test_successful_authorization_with_vault @gateway.expects(:ssl_post).returns(successful_purchase_response) test_successful_store assert response = @gateway.authorize(100, @data_key, {:order_id => generate_unique_id, :customer => generate_unique_id}) assert_success response assert_equal "Approved", response.message assert response.authorization.present? end def test_failed_authorization_with_vault @gateway.expects(:ssl_post).returns(failed_purchase_response) test_successful_store assert response = @gateway.authorize(100, @data_key, @options) assert_failure response end def test_cvv_enabled_and_provided gateway = MonerisGateway.new(login: 'store1', password: 'yesguy', cvv_enabled: true) @credit_card.verification_value = "452" stub_comms(gateway) do gateway.purchase(@amount, @credit_card, @options) end.check_request do |endpoint, data, headers| assert_match(%r{cvd_indicator>1<}, data) assert_match(%r{cvd_value>452<}, data) end.respond_with(successful_purchase_response) end def test_cvv_enabled_but_not_provided gateway = MonerisGateway.new(login: 'store1', password: 'yesguy', cvv_enabled: true) @credit_card.verification_value = "" stub_comms(gateway) do gateway.purchase(@amount, @credit_card, @options) end.check_request do |endpoint, data, headers| assert_match(%r{cvd_indicator>0<}, data) assert_no_match(%r{cvd_value>}, data) end.respond_with(successful_purchase_response) end def test_cvv_disabled_and_provided @credit_card.verification_value = "452" stub_comms do @gateway.purchase(@amount, @credit_card, @options) end.check_request do |endpoint, data, headers| assert_no_match(%r{cvd_value>}, data) assert_no_match(%r{cvd_indicator>}, data) end.respond_with(successful_purchase_response) end def test_cvv_disabled_but_not_provided @credit_card.verification_value = "" stub_comms do @gateway.purchase(@amount, @credit_card, @options) end.check_request do |endpoint, data, headers| assert_no_match(%r{cvd_value>}, data) assert_no_match(%r{cvd_indicator>}, data) end.respond_with(successful_purchase_response) end def test_avs_enabled_and_provided gateway = MonerisGateway.new(login: 'store1', password: 'yesguy', avs_enabled: true) billing_address = address(address1: "1234 Anystreet", address2: "") stub_comms do gateway.purchase(@amount, @credit_card, billing_address: billing_address, order_id: "1") end.check_request do |endpoint, data, headers| assert_match(%r{avs_street_number>1234<}, data) assert_match(%r{avs_street_name>Anystreet<}, data) assert_match(%r{avs_zipcode>#{billing_address[:zip]}<}, data) end.respond_with(successful_purchase_response_with_avs_result) end def test_avs_enabled_but_not_provided gateway = MonerisGateway.new(login: 'store1', password: 'yesguy', avs_enabled: true) stub_comms do gateway.purchase(@amount, @credit_card, @options.tap { |x| x.delete(:billing_address) }) end.check_request do |endpoint, data, headers| assert_no_match(%r{avs_street_number>}, data) assert_no_match(%r{avs_street_name>}, data) assert_no_match(%r{avs_zipcode>}, data) end.respond_with(successful_purchase_response) end def test_avs_disabled_and_provided billing_address = address(address1: "1234 Anystreet", address2: "") stub_comms do @gateway.purchase(@amount, @credit_card, billing_address: billing_address, order_id: "1") end.check_request do |endpoint, data, headers| assert_no_match(%r{avs_street_number>}, data) assert_no_match(%r{avs_street_name>}, data) assert_no_match(%r{avs_zipcode>}, data) end.respond_with(successful_purchase_response_with_avs_result) end def test_avs_disabled_and_not_provided stub_comms do @gateway.purchase(@amount, @credit_card, @options.tap { |x| x.delete(:billing_address) }) end.check_request do |endpoint, data, headers| assert_no_match(%r{avs_street_number>}, data) assert_no_match(%r{avs_street_name>}, data) assert_no_match(%r{avs_zipcode>}, data) end.respond_with(successful_purchase_response) end def test_avs_result_valid_with_address @gateway.expects(:ssl_post).returns(successful_purchase_response_with_avs_result) assert response = @gateway.purchase(100, @credit_card, @options) assert_equal(response.avs_result, { 'code' => 'A', 'message' => 'Street address matches, but 5-digit and 9-digit postal code do not match.', 'street_match' => 'Y', 'postal_match' => 'N' }) end def test_customer_can_be_specified stub_comms do @gateway.purchase(@amount, @credit_card, order_id: "3", customer: "Joe Jones") end.check_request do |endpoint, data, headers| assert_match(%r{cust_id>Joe Jones}, data) end.respond_with(successful_purchase_response) end def test_customer_not_specified_card_name_used stub_comms do @gateway.purchase(@amount, @credit_card, order_id: "3") end.check_request do |endpoint, data, headers| assert_match(%r{cust_id>Longbob Longsen}, data) end.respond_with(successful_purchase_response) end def test_add_swipe_data_with_creditcard @credit_card.track_data = "Track Data" stub_comms do @gateway.purchase(@amount, @credit_card, @options) end.check_request do |endpoint, data, headers| assert_match "<pos_code>00</pos_code>", data assert_match "<track2>Track Data</track2>", data end.respond_with(successful_purchase_response) end private def successful_purchase_response <<-RESPONSE <?xml version="1.0"?> <response> <receipt> <ReceiptId>1026.1</ReceiptId> <ReferenceNum>661221050010170010</ReferenceNum> <ResponseCode>027</ResponseCode> <ISO>01</ISO> <AuthCode>013511</AuthCode> <TransTime>18:41:13</TransTime> <TransDate>2008-01-05</TransDate> <TransType>00</TransType> <Complete>true</Complete> <Message>APPROVED * =</Message> <TransAmount>1.00</TransAmount> <CardType>V</CardType> <TransID>58-0_3</TransID> <TimedOut>false</TimedOut> </receipt> </response> RESPONSE end def successful_purchase_response_with_avs_result <<-RESPONSE <?xml version="1.0"?> <response> <receipt> <ReceiptId>9c7189ec64b58f541335be1ca6294d09</ReceiptId> <ReferenceNum>660110910011136190</ReferenceNum> <ResponseCode>027</ResponseCode> <ISO>01</ISO> <AuthCode>115497</AuthCode> <TransTime>15:20:51</TransTime> <TransDate>2014-06-18</TransDate> <TransType>00</TransType> <Complete>true</Complete><Message>APPROVED * =</Message> <TransAmount>10.10</TransAmount> <CardType>V</CardType> <TransID>491573-0_9</TransID> <TimedOut>false</TimedOut> <BankTotals>null</BankTotals> <Ticket>null</Ticket> <CorporateCard>false</CorporateCard> <AvsResultCode>A</AvsResultCode> <ITDResponse>null</ITDResponse> <IsVisaDebit>false</IsVisaDebit> </receipt> </response> RESPONSE end def failed_purchase_response <<-RESPONSE <?xml version="1.0"?> <response> <receipt> <ReceiptId>1026.1</ReceiptId> <ReferenceNum>661221050010170010</ReferenceNum> <ResponseCode>481</ResponseCode> <ISO>01</ISO> <AuthCode>013511</AuthCode> <TransTime>18:41:13</TransTime> <TransDate>2008-01-05</TransDate> <TransType>00</TransType> <Complete>true</Complete> <Message>DECLINED * =</Message> <TransAmount>1.00</TransAmount> <CardType>V</CardType> <TransID>97-2-0</TransID> <TimedOut>false</TimedOut> </receipt> </response> RESPONSE end def successful_store_response <<-RESPONSE <?xml version="1.0"?> <response> <receipt> <DataKey>1234567890</DataKey> <ResponseCode>027</ResponseCode> <Complete>true</Complete> <Message>Successfully registered cc details * =</Message> </receipt> </response> RESPONSE end def successful_unstore_response <<-RESPONSE <?xml version="1.0"?> <response> <receipt> <DataKey>1234567890</DataKey> <ResponseCode>027</ResponseCode> <Complete>true</Complete> <Message>Successfully deleted cc details * =</Message> </receipt> </response> RESPONSE end def successful_update_response <<-RESPONSE <?xml version="1.0"?> <response> <receipt> <DataKey>1234567890</DataKey> <ResponseCode>027</ResponseCode> <Complete>true</Complete> <Message>Successfully updated cc details * =</Message> </receipt> </response> RESPONSE end def xml_purchase_fixture '<request><store_id>store1</store_id><api_token>yesguy</api_token><purchase><amount>1.01</amount><pan>4242424242424242</pan><expdate>0303</expdate><crypt_type>7</crypt_type><order_id>order1</order_id></purchase></request>' end def xml_capture_fixture '<request><store_id>store1</store_id><api_token>yesguy</api_token><preauth><amount>1.01</amount><pan>4242424242424242</pan><expdate>0303</expdate><crypt_type>7</crypt_type><order_id>order1</order_id></preauth></request>' end end
32.069767
225
0.717694
082645ce22203e91f541cbde9c0e11489eebf918
217
# frozen_string_literal: true require_relative "gitoc/version" module Gitoc class Error < StandardError; end # Your code goes here... autoload :Cli, "gitoc/cli" autoload :Repository, "gitoc/repository" end
18.083333
42
0.741935
33af6cd480d0d5eb9adb6f624cfbc17fdca2c3f7
759
require_relative "boot" require "rails/all" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Lafamiglia class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.1 # Configuration for the application, engines, and railties goes here. # # These settings can be overridden in specific environments using the files # in config/environments, which are processed later. # # config.time_zone = "Central Time (US & Canada)" # config.eager_load_paths << Rails.root.join("extras") config.autoload_paths << Rails.root.join('lib') end end
31.625
79
0.735178
f76fc9d6fe0e6082f6bee1e70e19996f10796ae7
1,894
# # Cookbook:: jupyterhub-chef # Spec:: jupyter_ipykernel # # The MIT License (MIT) # # Copyright:: 2019, Ryan Hansohn # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' describe 'jupyterhub-chef::jupyter_ipykernel' do context 'When all attributes are default, on Ubuntu 18.04' do # for a complete list of available platforms and versions see: # https://github.com/chefspec/fauxhai/blob/master/PLATFORMS.md platform 'ubuntu', '18.04' it 'converges successfully' do expect { chef_run }.to_not raise_error end end context 'When all attributes are default, on CentOS 7' do # for a complete list of available platforms and versions see: # https://github.com/chefspec/fauxhai/blob/master/PLATFORMS.md platform 'centos', '7' it 'converges successfully' do expect { chef_run }.to_not raise_error end end end
37.88
79
0.750264
b94325c4226f4cd09a27728a28b01f0f3c634cd6
144
class RegistrationsController < Devise::RegistrationsController protected def after_sign_up_path_for(_resource) recipes_path end end
18
63
0.819444
62bbe1ba3b49575dabe62f705e5477e214ce82f9
680
class MembershipsController < ApplicationController def index @user = User.friendly.find params[:user_id] render layout: 'user' end def update membership = Membership.find(params[:id]) if can?(:update, membership) && membership.update(params.require(:membership).permit(:role)) render json: { success: true } else render json: { success: false } end end def destroy @user = User.friendly.find params[:user_id] @membership = @user.memberships.find params[:id] if @membership.deletable? @membership.destroy else render json: { success: false, message: 'You can not remove this member.' } end end end
26.153846
96
0.670588