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
|
---|---|---|---|---|---|
d5b5cf1c26133e2bed49a8240cab0c579dd96ffb
| 41,082 |
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module GamesV1
class AchievementDefinition
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListAchievementDefinitionsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class AchievementIncrementResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class AchievementRevealResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class AchievementSetStepsAtLeastResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class AchievementUnlockResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class AchievementUpdateMultipleRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class AchievementUpdateMultipleResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class UpdateAchievementRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class UpdateAchievementResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Application
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ApplicationCategory
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ApplicationVerifyResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Category
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListCategoryResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class EventBatchRecordFailure
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class EventChild
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class EventDefinition
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListEventDefinitionResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class EventPeriodRange
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class EventPeriodUpdate
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class EventRecordFailure
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class EventRecordRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class UpdateEventRequest
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class UpdateEventResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GamesAchievementIncrement
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class GamesAchievementSetStepsAtLeast
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ImageAsset
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Instance
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class InstanceAndroidDetails
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class InstanceIosDetails
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class InstanceWebDetails
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Leaderboard
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class LeaderboardEntry
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListLeaderboardResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class LeaderboardScoreRank
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class LeaderboardScores
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class MetagameConfig
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Player
class Representation < Google::Apis::Core::JsonRepresentation; end
class Name
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
include Google::Apis::Core::JsonObjectSupport
end
class PlayerAchievement
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListPlayerAchievementResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class PlayerEvent
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListPlayerEventResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class PlayerExperienceInfo
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class PlayerLeaderboardScore
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListPlayerLeaderboardScoreResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class PlayerLevel
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListPlayerResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class PlayerScore
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListPlayerScoreResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class PlayerScoreResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class PlayerScoreSubmissionList
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ProfileSettings
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class CheckRevisionResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ScoreSubmission
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class Snapshot
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class SnapshotImage
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class ListSnapshotResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class StatsResponse
class Representation < Google::Apis::Core::JsonRepresentation; end
include Google::Apis::Core::JsonObjectSupport
end
class AchievementDefinition
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :achievement_type, as: 'achievementType'
property :description, as: 'description'
property :experience_points, :numeric_string => true, as: 'experiencePoints'
property :formatted_total_steps, as: 'formattedTotalSteps'
property :id, as: 'id'
property :initial_state, as: 'initialState'
property :is_revealed_icon_url_default, as: 'isRevealedIconUrlDefault'
property :is_unlocked_icon_url_default, as: 'isUnlockedIconUrlDefault'
property :kind, as: 'kind'
property :name, as: 'name'
property :revealed_icon_url, as: 'revealedIconUrl'
property :total_steps, as: 'totalSteps'
property :unlocked_icon_url, as: 'unlockedIconUrl'
end
end
class ListAchievementDefinitionsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :items, as: 'items', class: Google::Apis::GamesV1::AchievementDefinition, decorator: Google::Apis::GamesV1::AchievementDefinition::Representation
property :kind, as: 'kind'
property :next_page_token, as: 'nextPageToken'
end
end
class AchievementIncrementResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :current_steps, as: 'currentSteps'
property :kind, as: 'kind'
property :newly_unlocked, as: 'newlyUnlocked'
end
end
class AchievementRevealResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :current_state, as: 'currentState'
property :kind, as: 'kind'
end
end
class AchievementSetStepsAtLeastResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :current_steps, as: 'currentSteps'
property :kind, as: 'kind'
property :newly_unlocked, as: 'newlyUnlocked'
end
end
class AchievementUnlockResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :kind, as: 'kind'
property :newly_unlocked, as: 'newlyUnlocked'
end
end
class AchievementUpdateMultipleRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :kind, as: 'kind'
collection :updates, as: 'updates', class: Google::Apis::GamesV1::UpdateAchievementRequest, decorator: Google::Apis::GamesV1::UpdateAchievementRequest::Representation
end
end
class AchievementUpdateMultipleResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :kind, as: 'kind'
collection :updated_achievements, as: 'updatedAchievements', class: Google::Apis::GamesV1::UpdateAchievementResponse, decorator: Google::Apis::GamesV1::UpdateAchievementResponse::Representation
end
end
class UpdateAchievementRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :achievement_id, as: 'achievementId'
property :increment_payload, as: 'incrementPayload', class: Google::Apis::GamesV1::GamesAchievementIncrement, decorator: Google::Apis::GamesV1::GamesAchievementIncrement::Representation
property :kind, as: 'kind'
property :set_steps_at_least_payload, as: 'setStepsAtLeastPayload', class: Google::Apis::GamesV1::GamesAchievementSetStepsAtLeast, decorator: Google::Apis::GamesV1::GamesAchievementSetStepsAtLeast::Representation
property :update_type, as: 'updateType'
end
end
class UpdateAchievementResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :achievement_id, as: 'achievementId'
property :current_state, as: 'currentState'
property :current_steps, as: 'currentSteps'
property :kind, as: 'kind'
property :newly_unlocked, as: 'newlyUnlocked'
property :update_occurred, as: 'updateOccurred'
end
end
class Application
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :achievement_count, as: 'achievement_count'
collection :assets, as: 'assets', class: Google::Apis::GamesV1::ImageAsset, decorator: Google::Apis::GamesV1::ImageAsset::Representation
property :author, as: 'author'
property :category, as: 'category', class: Google::Apis::GamesV1::ApplicationCategory, decorator: Google::Apis::GamesV1::ApplicationCategory::Representation
property :description, as: 'description'
collection :enabled_features, as: 'enabledFeatures'
property :id, as: 'id'
collection :instances, as: 'instances', class: Google::Apis::GamesV1::Instance, decorator: Google::Apis::GamesV1::Instance::Representation
property :kind, as: 'kind'
property :last_updated_timestamp, :numeric_string => true, as: 'lastUpdatedTimestamp'
property :leaderboard_count, as: 'leaderboard_count'
property :name, as: 'name'
property :theme_color, as: 'themeColor'
end
end
class ApplicationCategory
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :kind, as: 'kind'
property :primary, as: 'primary'
property :secondary, as: 'secondary'
end
end
class ApplicationVerifyResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :alternate_player_id, as: 'alternate_player_id'
property :kind, as: 'kind'
property :player_id, as: 'player_id'
end
end
class Category
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :category, as: 'category'
property :experience_points, :numeric_string => true, as: 'experiencePoints'
property :kind, as: 'kind'
end
end
class ListCategoryResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :items, as: 'items', class: Google::Apis::GamesV1::Category, decorator: Google::Apis::GamesV1::Category::Representation
property :kind, as: 'kind'
property :next_page_token, as: 'nextPageToken'
end
end
class EventBatchRecordFailure
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :failure_cause, as: 'failureCause'
property :kind, as: 'kind'
property :range, as: 'range', class: Google::Apis::GamesV1::EventPeriodRange, decorator: Google::Apis::GamesV1::EventPeriodRange::Representation
end
end
class EventChild
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :child_id, as: 'childId'
property :kind, as: 'kind'
end
end
class EventDefinition
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :child_events, as: 'childEvents', class: Google::Apis::GamesV1::EventChild, decorator: Google::Apis::GamesV1::EventChild::Representation
property :description, as: 'description'
property :display_name, as: 'displayName'
property :id, as: 'id'
property :image_url, as: 'imageUrl'
property :is_default_image_url, as: 'isDefaultImageUrl'
property :kind, as: 'kind'
property :visibility, as: 'visibility'
end
end
class ListEventDefinitionResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :items, as: 'items', class: Google::Apis::GamesV1::EventDefinition, decorator: Google::Apis::GamesV1::EventDefinition::Representation
property :kind, as: 'kind'
property :next_page_token, as: 'nextPageToken'
end
end
class EventPeriodRange
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :kind, as: 'kind'
property :period_end_millis, :numeric_string => true, as: 'periodEndMillis'
property :period_start_millis, :numeric_string => true, as: 'periodStartMillis'
end
end
class EventPeriodUpdate
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :kind, as: 'kind'
property :time_period, as: 'timePeriod', class: Google::Apis::GamesV1::EventPeriodRange, decorator: Google::Apis::GamesV1::EventPeriodRange::Representation
collection :updates, as: 'updates', class: Google::Apis::GamesV1::UpdateEventRequest, decorator: Google::Apis::GamesV1::UpdateEventRequest::Representation
end
end
class EventRecordFailure
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :event_id, as: 'eventId'
property :failure_cause, as: 'failureCause'
property :kind, as: 'kind'
end
end
class EventRecordRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :current_time_millis, :numeric_string => true, as: 'currentTimeMillis'
property :kind, as: 'kind'
property :request_id, :numeric_string => true, as: 'requestId'
collection :time_periods, as: 'timePeriods', class: Google::Apis::GamesV1::EventPeriodUpdate, decorator: Google::Apis::GamesV1::EventPeriodUpdate::Representation
end
end
class UpdateEventRequest
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :definition_id, as: 'definitionId'
property :kind, as: 'kind'
property :update_count, :numeric_string => true, as: 'updateCount'
end
end
class UpdateEventResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :batch_failures, as: 'batchFailures', class: Google::Apis::GamesV1::EventBatchRecordFailure, decorator: Google::Apis::GamesV1::EventBatchRecordFailure::Representation
collection :event_failures, as: 'eventFailures', class: Google::Apis::GamesV1::EventRecordFailure, decorator: Google::Apis::GamesV1::EventRecordFailure::Representation
property :kind, as: 'kind'
collection :player_events, as: 'playerEvents', class: Google::Apis::GamesV1::PlayerEvent, decorator: Google::Apis::GamesV1::PlayerEvent::Representation
end
end
class GamesAchievementIncrement
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :kind, as: 'kind'
property :request_id, :numeric_string => true, as: 'requestId'
property :steps, as: 'steps'
end
end
class GamesAchievementSetStepsAtLeast
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :kind, as: 'kind'
property :steps, as: 'steps'
end
end
class ImageAsset
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :height, as: 'height'
property :kind, as: 'kind'
property :name, as: 'name'
property :url, as: 'url'
property :width, as: 'width'
end
end
class Instance
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :acquisition_uri, as: 'acquisitionUri'
property :android_instance, as: 'androidInstance', class: Google::Apis::GamesV1::InstanceAndroidDetails, decorator: Google::Apis::GamesV1::InstanceAndroidDetails::Representation
property :ios_instance, as: 'iosInstance', class: Google::Apis::GamesV1::InstanceIosDetails, decorator: Google::Apis::GamesV1::InstanceIosDetails::Representation
property :kind, as: 'kind'
property :name, as: 'name'
property :platform_type, as: 'platformType'
property :realtime_play, as: 'realtimePlay'
property :turn_based_play, as: 'turnBasedPlay'
property :web_instance, as: 'webInstance', class: Google::Apis::GamesV1::InstanceWebDetails, decorator: Google::Apis::GamesV1::InstanceWebDetails::Representation
end
end
class InstanceAndroidDetails
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :enable_piracy_check, as: 'enablePiracyCheck'
property :kind, as: 'kind'
property :package_name, as: 'packageName'
property :preferred, as: 'preferred'
end
end
class InstanceIosDetails
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :bundle_identifier, as: 'bundleIdentifier'
property :itunes_app_id, as: 'itunesAppId'
property :kind, as: 'kind'
property :preferred_for_ipad, as: 'preferredForIpad'
property :preferred_for_iphone, as: 'preferredForIphone'
property :support_ipad, as: 'supportIpad'
property :support_iphone, as: 'supportIphone'
end
end
class InstanceWebDetails
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :kind, as: 'kind'
property :launch_url, as: 'launchUrl'
property :preferred, as: 'preferred'
end
end
class Leaderboard
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :icon_url, as: 'iconUrl'
property :id, as: 'id'
property :is_icon_url_default, as: 'isIconUrlDefault'
property :kind, as: 'kind'
property :name, as: 'name'
property :order, as: 'order'
end
end
class LeaderboardEntry
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :formatted_score, as: 'formattedScore'
property :formatted_score_rank, as: 'formattedScoreRank'
property :kind, as: 'kind'
property :player, as: 'player', class: Google::Apis::GamesV1::Player, decorator: Google::Apis::GamesV1::Player::Representation
property :score_rank, :numeric_string => true, as: 'scoreRank'
property :score_tag, as: 'scoreTag'
property :score_value, :numeric_string => true, as: 'scoreValue'
property :time_span, as: 'timeSpan'
property :write_timestamp_millis, :numeric_string => true, as: 'writeTimestampMillis'
end
end
class ListLeaderboardResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :items, as: 'items', class: Google::Apis::GamesV1::Leaderboard, decorator: Google::Apis::GamesV1::Leaderboard::Representation
property :kind, as: 'kind'
property :next_page_token, as: 'nextPageToken'
end
end
class LeaderboardScoreRank
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :formatted_num_scores, as: 'formattedNumScores'
property :formatted_rank, as: 'formattedRank'
property :kind, as: 'kind'
property :num_scores, :numeric_string => true, as: 'numScores'
property :rank, :numeric_string => true, as: 'rank'
end
end
class LeaderboardScores
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :items, as: 'items', class: Google::Apis::GamesV1::LeaderboardEntry, decorator: Google::Apis::GamesV1::LeaderboardEntry::Representation
property :kind, as: 'kind'
property :next_page_token, as: 'nextPageToken'
property :num_scores, :numeric_string => true, as: 'numScores'
property :player_score, as: 'playerScore', class: Google::Apis::GamesV1::LeaderboardEntry, decorator: Google::Apis::GamesV1::LeaderboardEntry::Representation
property :prev_page_token, as: 'prevPageToken'
end
end
class MetagameConfig
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :current_version, as: 'currentVersion'
property :kind, as: 'kind'
collection :player_levels, as: 'playerLevels', class: Google::Apis::GamesV1::PlayerLevel, decorator: Google::Apis::GamesV1::PlayerLevel::Representation
end
end
class Player
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :avatar_image_url, as: 'avatarImageUrl'
property :banner_url_landscape, as: 'bannerUrlLandscape'
property :banner_url_portrait, as: 'bannerUrlPortrait'
property :display_name, as: 'displayName'
property :experience_info, as: 'experienceInfo', class: Google::Apis::GamesV1::PlayerExperienceInfo, decorator: Google::Apis::GamesV1::PlayerExperienceInfo::Representation
property :friend_status, as: 'friendStatus'
property :kind, as: 'kind'
property :name, as: 'name', class: Google::Apis::GamesV1::Player::Name, decorator: Google::Apis::GamesV1::Player::Name::Representation
property :original_player_id, as: 'originalPlayerId'
property :player_id, as: 'playerId'
property :profile_settings, as: 'profileSettings', class: Google::Apis::GamesV1::ProfileSettings, decorator: Google::Apis::GamesV1::ProfileSettings::Representation
property :title, as: 'title'
end
class Name
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :family_name, as: 'familyName'
property :given_name, as: 'givenName'
end
end
end
class PlayerAchievement
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :achievement_state, as: 'achievementState'
property :current_steps, as: 'currentSteps'
property :experience_points, :numeric_string => true, as: 'experiencePoints'
property :formatted_current_steps_string, as: 'formattedCurrentStepsString'
property :id, as: 'id'
property :kind, as: 'kind'
property :last_updated_timestamp, :numeric_string => true, as: 'lastUpdatedTimestamp'
end
end
class ListPlayerAchievementResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :items, as: 'items', class: Google::Apis::GamesV1::PlayerAchievement, decorator: Google::Apis::GamesV1::PlayerAchievement::Representation
property :kind, as: 'kind'
property :next_page_token, as: 'nextPageToken'
end
end
class PlayerEvent
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :definition_id, as: 'definitionId'
property :formatted_num_events, as: 'formattedNumEvents'
property :kind, as: 'kind'
property :num_events, :numeric_string => true, as: 'numEvents'
property :player_id, as: 'playerId'
end
end
class ListPlayerEventResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :items, as: 'items', class: Google::Apis::GamesV1::PlayerEvent, decorator: Google::Apis::GamesV1::PlayerEvent::Representation
property :kind, as: 'kind'
property :next_page_token, as: 'nextPageToken'
end
end
class PlayerExperienceInfo
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :current_experience_points, :numeric_string => true, as: 'currentExperiencePoints'
property :current_level, as: 'currentLevel', class: Google::Apis::GamesV1::PlayerLevel, decorator: Google::Apis::GamesV1::PlayerLevel::Representation
property :kind, as: 'kind'
property :last_level_up_timestamp_millis, :numeric_string => true, as: 'lastLevelUpTimestampMillis'
property :next_level, as: 'nextLevel', class: Google::Apis::GamesV1::PlayerLevel, decorator: Google::Apis::GamesV1::PlayerLevel::Representation
end
end
class PlayerLeaderboardScore
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :friends_rank, as: 'friendsRank', class: Google::Apis::GamesV1::LeaderboardScoreRank, decorator: Google::Apis::GamesV1::LeaderboardScoreRank::Representation
property :kind, as: 'kind'
property :leaderboard_id, as: 'leaderboard_id'
property :public_rank, as: 'publicRank', class: Google::Apis::GamesV1::LeaderboardScoreRank, decorator: Google::Apis::GamesV1::LeaderboardScoreRank::Representation
property :score_string, as: 'scoreString'
property :score_tag, as: 'scoreTag'
property :score_value, :numeric_string => true, as: 'scoreValue'
property :social_rank, as: 'socialRank', class: Google::Apis::GamesV1::LeaderboardScoreRank, decorator: Google::Apis::GamesV1::LeaderboardScoreRank::Representation
property :time_span, as: 'timeSpan'
property :write_timestamp, :numeric_string => true, as: 'writeTimestamp'
end
end
class ListPlayerLeaderboardScoreResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :items, as: 'items', class: Google::Apis::GamesV1::PlayerLeaderboardScore, decorator: Google::Apis::GamesV1::PlayerLeaderboardScore::Representation
property :kind, as: 'kind'
property :next_page_token, as: 'nextPageToken'
property :player, as: 'player', class: Google::Apis::GamesV1::Player, decorator: Google::Apis::GamesV1::Player::Representation
end
end
class PlayerLevel
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :kind, as: 'kind'
property :level, as: 'level'
property :max_experience_points, :numeric_string => true, as: 'maxExperiencePoints'
property :min_experience_points, :numeric_string => true, as: 'minExperiencePoints'
end
end
class ListPlayerResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :items, as: 'items', class: Google::Apis::GamesV1::Player, decorator: Google::Apis::GamesV1::Player::Representation
property :kind, as: 'kind'
property :next_page_token, as: 'nextPageToken'
end
end
class PlayerScore
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :formatted_score, as: 'formattedScore'
property :kind, as: 'kind'
property :score, :numeric_string => true, as: 'score'
property :score_tag, as: 'scoreTag'
property :time_span, as: 'timeSpan'
end
end
class ListPlayerScoreResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :kind, as: 'kind'
collection :submitted_scores, as: 'submittedScores', class: Google::Apis::GamesV1::PlayerScoreResponse, decorator: Google::Apis::GamesV1::PlayerScoreResponse::Representation
end
end
class PlayerScoreResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :beaten_score_time_spans, as: 'beatenScoreTimeSpans'
property :formatted_score, as: 'formattedScore'
property :kind, as: 'kind'
property :leaderboard_id, as: 'leaderboardId'
property :score_tag, as: 'scoreTag'
collection :unbeaten_scores, as: 'unbeatenScores', class: Google::Apis::GamesV1::PlayerScore, decorator: Google::Apis::GamesV1::PlayerScore::Representation
end
end
class PlayerScoreSubmissionList
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :kind, as: 'kind'
collection :scores, as: 'scores', class: Google::Apis::GamesV1::ScoreSubmission, decorator: Google::Apis::GamesV1::ScoreSubmission::Representation
end
end
class ProfileSettings
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :friends_list_visibility, as: 'friendsListVisibility'
property :kind, as: 'kind'
property :profile_visible, as: 'profileVisible'
end
end
class CheckRevisionResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :api_version, as: 'apiVersion'
property :kind, as: 'kind'
property :revision_status, as: 'revisionStatus'
end
end
class ScoreSubmission
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :kind, as: 'kind'
property :leaderboard_id, as: 'leaderboardId'
property :score, :numeric_string => true, as: 'score'
property :score_tag, as: 'scoreTag'
property :signature, as: 'signature'
end
end
class Snapshot
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :cover_image, as: 'coverImage', class: Google::Apis::GamesV1::SnapshotImage, decorator: Google::Apis::GamesV1::SnapshotImage::Representation
property :description, as: 'description'
property :drive_id, as: 'driveId'
property :duration_millis, :numeric_string => true, as: 'durationMillis'
property :id, as: 'id'
property :kind, as: 'kind'
property :last_modified_millis, :numeric_string => true, as: 'lastModifiedMillis'
property :progress_value, :numeric_string => true, as: 'progressValue'
property :title, as: 'title'
property :type, as: 'type'
property :unique_name, as: 'uniqueName'
end
end
class SnapshotImage
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :height, as: 'height'
property :kind, as: 'kind'
property :mime_type, as: 'mime_type'
property :url, as: 'url'
property :width, as: 'width'
end
end
class ListSnapshotResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :items, as: 'items', class: Google::Apis::GamesV1::Snapshot, decorator: Google::Apis::GamesV1::Snapshot::Representation
property :kind, as: 'kind'
property :next_page_token, as: 'nextPageToken'
end
end
class StatsResponse
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :avg_session_length_minutes, as: 'avg_session_length_minutes'
property :churn_probability, as: 'churn_probability'
property :days_since_last_played, as: 'days_since_last_played'
property :high_spender_probability, as: 'high_spender_probability'
property :kind, as: 'kind'
property :num_purchases, as: 'num_purchases'
property :num_sessions, as: 'num_sessions'
property :num_sessions_percentile, as: 'num_sessions_percentile'
property :spend_percentile, as: 'spend_percentile'
property :spend_probability, as: 'spend_probability'
property :total_spend_next_28_days, as: 'total_spend_next_28_days'
end
end
end
end
end
| 38.322761 | 222 | 0.641644 |
612028f5038742c74549482c216b5e82bfdc7287
| 192 |
module MiqAeMethodService
class MiqAeServiceNOVAHawk_Providers_Openstack_CloudManager_AvailabilityZoneNull < MiqAeServiceNOVAHawk_Providers_Openstack_CloudManager_AvailabilityZone
end
end
| 38.4 | 155 | 0.932292 |
1db1b62e35ae954309f526b2160050481dc7b114
| 960 |
require "vmc/cli/user/base"
module VMC::User
class Register < Base
def precondition; end
desc "Create a user and log in"
group :admin, :user, :hidden => true
input :email, :desc => "Desired email", :argument => :optional
input :password, :desc => "Desired password"
input :verify, :desc => "Repeat password"
input :login, :desc => "Automatically log in?", :default => true
def register
email = input[:email]
password = input[:password]
validate_password!(password)
with_progress("Creating user") do
client.register(email, password)
end
if input[:login]
invoke :login, :username => email, :password => password
end
end
private
def ask_email
ask("Email")
end
def ask_password
ask("Password", :echo => "*", :forget => true)
end
def ask_verify
ask("Confirm Password", :echo => "*", :forget => true)
end
end
end
| 22.325581 | 68 | 0.6 |
e2b87214d52cc6d9cfe20508afdabd71a299c5a4
| 1,834 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module storage
module Models
#
# The URIs that are used to perform a retrieval of a public blob, queue or
# table object.
#
class Endpoints
include MsRestAzure
# @return [String] Gets the blob endpoint.
attr_accessor :blob
# @return [String] Gets the queue endpoint.
attr_accessor :queue
# @return [String] Gets the table endpoint.
attr_accessor :table
# @return [String] Gets the file endpoint.
attr_accessor :file
#
# Mapper for Endpoints class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
required: false,
serialized_name: 'Endpoints',
type: {
name: 'Composite',
class_name: 'Endpoints',
model_properties: {
blob: {
required: false,
serialized_name: 'blob',
type: {
name: 'String'
}
},
queue: {
required: false,
serialized_name: 'queue',
type: {
name: 'String'
}
},
table: {
required: false,
serialized_name: 'table',
type: {
name: 'String'
}
},
file: {
required: false,
serialized_name: 'file',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 24.131579 | 78 | 0.461287 |
bf797cc1c65249d13748d7fc21f6e1ac395c6f3e
| 82 |
require 'jace_beleren/version'
require 'jace_beleren/api'
module JaceBeleren
end
| 13.666667 | 30 | 0.829268 |
bfa4463339760c3867a207fab44458a73c3ab587
| 1,502 |
Dir.glob('models/*.rb') { |model| require_relative model }
class Application < Sinatra::Base
before do
headers 'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => ['OPTIONS', 'GET', 'POST']
end
get '/?' do
slim :index
end
get '/api/send/request/?' do
headers = {
'Authorization' => 'token a6aced0802246927eaa3de49aedfa13cd30e26ec'
}
result = HTTParty.get(params['url'], :headers => headers)
p result
return result.to_json
end
get '/api/comments/get/?' do
return SQLQuery.new.get('comments', ['id', 'text', 'sender']).where.if('projectId', params['projectId']).send.to_json
end
post '/api/comments/add/?' do
SQLQuery.new.add('comments', ['text', 'projectId', 'sender'], [params['text'], params['projectId'], params['sender']]).send
end
delete '/api/comments/delete/?' do
SQLQuery.new.del('comments').where.if('id', params['id']).send
end
get '/api/forks/status/?' do
p params['projectId']
return SQLQuery.new.get('status', ['status']).where.if('projectId', params['projectId']).send.first.to_json
end
post '/api/forks/status/?' do
SQLQuery.new.add('status', ['projectId'], [params['projectId']]).send
end
patch '/api/forks/status/?' do
SQLQuery.new.update('status', ['status'], [params['status']]).where.if('projectId', params['projectId']).send
end
end
| 31.957447 | 131 | 0.592543 |
910386b24b710d30afad603fd364b869a0449f4d
| 255 |
name "ntp"
maintainer "Opscode, Inc."
maintainer_email "[email protected]"
license "Apache-2.0"
description "Installs and configures ntp as a client or server"
version "0.8.2"
supports "ubuntu"
| 28.333333 | 69 | 0.6 |
21d72196a70c38070816530f5a1d976478f81596
| 2,268 |
require 'test_helper'
class ProgrammeTest < ActiveSupport::TestCase
test "uuid" do
p = Programme.new :title=>"fish"
assert_nil p.attributes["uuid"]
p.save!
refute_nil p.attributes["uuid"]
uuid = p.uuid
p.title="frog"
p.save!
assert_equal uuid,p.uuid
end
test "validation" do
p = Programme.new
refute p.valid?
p.title="frog"
assert p.valid?
p.save!
#title must be unique
p2 = Programme.new :title=>p.title
refute p2.valid?
p2.title="sdfsdfsdf"
assert p2.valid?
end
test "factory" do
p = Factory :programme
refute_nil p.title
refute_nil p.uuid
refute_empty p.projects
end
test "people via projects" do
person1 = Factory :person
person2 = Factory :person
person3 = Factory :person
assert_equal 1,person1.projects.size
assert_equal 1,person2.projects.size
projects = person1.projects | person2.projects
prog = Factory :programme,:projects=>projects
assert_equal 2,prog.projects.size
peeps = prog.people
assert_equal 2,peeps.size
assert_includes peeps,person1
assert_includes peeps,person2
refute_includes peeps,person3
end
test "institutions via projects" do
person1 = Factory :person
person2 = Factory :person
person3 = Factory :person
projects = person1.projects | person2.projects
prog = Factory :programme,:projects=>projects
assert_equal 2,prog.projects.size
inst = prog.institutions
assert_equal 2,inst.size
assert_includes inst,person1.institutions.first
assert_includes inst,person2.institutions.first
refute_includes inst,person3.institutions.first
end
test "can be edited by" do
#for now programmes can only be created and editing by an admin
person = Factory(:person)
admin = Factory(:admin)
programme = Factory(:programme)
assert programme.can_be_edited_by?(admin)
refute programme.can_be_edited_by?(person)
refute programme.can_be_edited_by?(nil)
end
test "disassociate projects on destroy" do
programme = Factory(:programme)
project = programme.projects.first
assert_equal programme.id,project.programme_id
programme.destroy
project.reload
assert_nil project.programme_id
end
end
| 24.923077 | 67 | 0.707231 |
abb0846902c65a67bf68d8c2fc4afe3ec0e2b901
| 162 |
class CreateApiToken < ActiveRecord::Migration[4.2]
def change
create_table :api_tokens do |t|
t.string :name
t.string :token
end
end
end
| 18 | 51 | 0.666667 |
614e96ac9e7a3c8959b965e1aff5ce2007ec67a0
| 192 |
# frozen_string_literal: true
module Spree
module TestingSupport
module UrlHelpers
def spree
Spree::Core::Engine.routes.url_helpers
end
end
end
end
| 16 | 47 | 0.645833 |
e90834d634712707d27308bcd57878b82411bfd9
| 4,675 |
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
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# 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
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# 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
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :local
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = ENV.fetch('FRAB_FORCE_SSL', 'false') == '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 = [ :request_id ]
# Use a different cache store in production.
config.cache_store = :mem_cache_store if ENV.fetch('FRAB_USE_MEMCACHE', 'false') == 'true'
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "frab_#{Rails.env}"
config.action_mailer.perform_caching = false
# 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 = [I18n.default_locale]
# 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
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
if ENV['EXCEPTION_EMAIL'].present? and ENV['FROM_EMAIL'].present?
Rails.application.config.middleware.use ExceptionNotification::Rack,
ignore_if: ->(env, exception) {
return true if exception.message =~ /^IP spoofing attack/
# from https://gist.github.com/jlxw/3357795
_limit = 1.minutes.ago
@@last_notification ||= _limit
if @@last_notification > _limit
Rails.logger.info "ExceptionNotifier rate limit triggered, #{ExceptionNotifier::Notifier.deliveries.size} notifications limited."
true
else
@@last_notification = Time.now
false
end
},
email: {
email_prefix: "frab on #{ENV['FRAB_HOST']}: ",
sender_address: "frab <#{ENV['FROM_EMAIL']}>",
exception_recipients: ENV['EXCEPTION_EMAIL']
}
end
end
| 42.117117 | 139 | 0.735615 |
39d54389e4f13077144e3b7e1a8f1d315d19422d
| 2,856 |
# This authentication controller has a number of functions
# [#login] Show the login view and login users
# [#create_admin] Create the first user: admin
# [#forgot_password] Generate and mail a new password
# [#logout] Logs out the current user (clears session)
class AuthenticationController < ApplicationController
skip_before_filter :authorize
# Display the login form and wait for user to enter a name and password.
# We then validate these, adding the user object to the session if they authorize.
def login
if request.get?
session[:user_id] = nil
else
# Try to get the user with the supplied username and password
logged_in_user = User.login(params[:user][:name], params[:login][:password])
# Create the session and redirect
unless logged_in_user.blank?
session[:user_id] = logged_in_user.id
jumpto = session[:jumpto] || { :action => 'list', :controller => 'folder' }
session[:jumpto] = nil
redirect_to(jumpto)
else
flash.now[:error] = t("authentication_controller.login.error", :default => "Invalid username/password combination")
end
end
end
# Show a form for creating the first user.
# Creates the first user: admin.
# Create the first group: admins.
# Add the admin to the admins group.
# Create the Root folder
# Give the admins group CRUD rights to the Root folder.
# The newly created admin user will be logged in automatically.
def create_admin
# Check if there already is an admin
redirect_to(:action => 'login') and return false if User.admin_exists?
if request.post?
# Create the object for the administrator user
@user = User.create_admin(params[:user][:email], params[:user][:name], params[:user][:password], params[:user][:password_confirmation])
# Create Admins group, Root folder and the permissions
if @user.save
Group.create_admins_group
Folder.create_root_folder
GroupPermission.create_initial_permissions
session[:user_id] = @user.id # Login
redirect_to(:action => 'list', :controller => 'folder')
end
end
end
# Generate/mail a new password for/to users who have forgotten it.
def forgot_password
if request.post?
# Try to generate and mail a new password
result = User.generate_and_mail_new_password(params[:user][:name], params[:user][:email], login_url)
# Act according to the result
if result['flash'] == 'forgotten_notice'
flash.now[:warning] = result['message']
else
flash[:notice] = result['message']
redirect_to(:action => 'login')
end
end
end
# Clear the current session and redirect to the login form.
def logout
reset_session
@logged_in_user = nil
redirect_to :action => 'login'
end
end
| 35.7 | 141 | 0.677171 |
0129d3305efca1e0a6c647a22dadaa3a32c4a4fa
| 177 |
class ContractsController < ApplicationController
def new
end
def create
generate_latex
system "pdflatex contrato.tex"
send_file 'contrato.pdf'
end
end
| 13.615385 | 49 | 0.723164 |
4a25a7b14cd1034e6c334b74be298ac9db712178
| 171 |
# frozen_string_literal: true
module Renalware
module ReportingHelper
def audits_breadcrumb
breadcrumb_for("Audits", reporting_audits_path)
end
end
end
| 17.1 | 53 | 0.766082 |
38bd469dad92a88e19747d0b8df3b567e8f8c063
| 11,153 |
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
require 'date'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# The configuration of a backend server that is a member of a network load balancer backend set.
# For more information, see [Managing Backend Servers](https://docs.cloud.oracle.com/Content/Balance/Tasks/managingbackendservers.htm).
#
class NetworkLoadBalancer::Models::BackendSummary
# A read-only field showing the IP address/IP OCID and port that uniquely identify this backend server in the backend set.
#
# Example: `10.0.0.3:8080`, or `ocid1.privateip..oc1.<var><unique_ID></var>:443` or `10.0.0.3:0`
#
# @return [String]
attr_accessor :name
# The IP address of the backend server.
# Example: `10.0.0.3`
#
# @return [String]
attr_accessor :ip_address
# The IP OCID/Instance OCID associated with the backend server.
# Example: `ocid1.privateip..oc1.<var><unique_ID></var>`
#
# @return [String]
attr_accessor :target_id
# **[Required]** The communication port for the backend server.
#
# Example: `8080`
#
# @return [Integer]
attr_accessor :port
# The network load balancing policy weight assigned to the server. Backend servers with a higher weight receive a larger
# proportion of incoming traffic. For example, a server weighted '3' receives three times the number of new connections
# as a server weighted '1'.
# For more information about load balancing policies, see
# [How Network Load Balancing Policies Work](https://docs.cloud.oracle.com/Content/Balance/Reference/lbpolicies.htm).
#
# Example: `3`
#
# @return [Integer]
attr_accessor :weight
# Whether the network load balancer should drain this server. Servers marked \"isDrain\" receive no
# incoming traffic.
#
# Example: `false`
#
# @return [BOOLEAN]
attr_accessor :is_drain
# Whether the network load balancer should treat this server as a backup unit. If `true`, then the network load balancer forwards no ingress
# traffic to this backend server unless all other backend servers not marked as \"isBackup\" fail the health check policy.
#
# Example: `false`
#
# @return [BOOLEAN]
attr_accessor :is_backup
# Whether the network load balancer should treat this server as offline. Offline servers receive no incoming
# traffic.
#
# Example: `false`
#
# @return [BOOLEAN]
attr_accessor :is_offline
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'name': :'name',
'ip_address': :'ipAddress',
'target_id': :'targetId',
'port': :'port',
'weight': :'weight',
'is_drain': :'isDrain',
'is_backup': :'isBackup',
'is_offline': :'isOffline'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'name': :'String',
'ip_address': :'String',
'target_id': :'String',
'port': :'Integer',
'weight': :'Integer',
'is_drain': :'BOOLEAN',
'is_backup': :'BOOLEAN',
'is_offline': :'BOOLEAN'
# rubocop:enable Style/SymbolLiteral
}
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
# @option attributes [String] :name The value to assign to the {#name} property
# @option attributes [String] :ip_address The value to assign to the {#ip_address} property
# @option attributes [String] :target_id The value to assign to the {#target_id} property
# @option attributes [Integer] :port The value to assign to the {#port} property
# @option attributes [Integer] :weight The value to assign to the {#weight} property
# @option attributes [BOOLEAN] :is_drain The value to assign to the {#is_drain} property
# @option attributes [BOOLEAN] :is_backup The value to assign to the {#is_backup} property
# @option attributes [BOOLEAN] :is_offline The value to assign to the {#is_offline} property
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
self.name = attributes[:'name'] if attributes[:'name']
self.ip_address = attributes[:'ipAddress'] if attributes[:'ipAddress']
raise 'You cannot provide both :ipAddress and :ip_address' if attributes.key?(:'ipAddress') && attributes.key?(:'ip_address')
self.ip_address = attributes[:'ip_address'] if attributes[:'ip_address']
self.target_id = attributes[:'targetId'] if attributes[:'targetId']
raise 'You cannot provide both :targetId and :target_id' if attributes.key?(:'targetId') && attributes.key?(:'target_id')
self.target_id = attributes[:'target_id'] if attributes[:'target_id']
self.port = attributes[:'port'] if attributes[:'port']
self.weight = attributes[:'weight'] if attributes[:'weight']
self.is_drain = attributes[:'isDrain'] unless attributes[:'isDrain'].nil?
self.is_drain = false if is_drain.nil? && !attributes.key?(:'isDrain') # rubocop:disable Style/StringLiterals
raise 'You cannot provide both :isDrain and :is_drain' if attributes.key?(:'isDrain') && attributes.key?(:'is_drain')
self.is_drain = attributes[:'is_drain'] unless attributes[:'is_drain'].nil?
self.is_drain = false if is_drain.nil? && !attributes.key?(:'isDrain') && !attributes.key?(:'is_drain') # rubocop:disable Style/StringLiterals
self.is_backup = attributes[:'isBackup'] unless attributes[:'isBackup'].nil?
self.is_backup = false if is_backup.nil? && !attributes.key?(:'isBackup') # rubocop:disable Style/StringLiterals
raise 'You cannot provide both :isBackup and :is_backup' if attributes.key?(:'isBackup') && attributes.key?(:'is_backup')
self.is_backup = attributes[:'is_backup'] unless attributes[:'is_backup'].nil?
self.is_backup = false if is_backup.nil? && !attributes.key?(:'isBackup') && !attributes.key?(:'is_backup') # rubocop:disable Style/StringLiterals
self.is_offline = attributes[:'isOffline'] unless attributes[:'isOffline'].nil?
self.is_offline = false if is_offline.nil? && !attributes.key?(:'isOffline') # rubocop:disable Style/StringLiterals
raise 'You cannot provide both :isOffline and :is_offline' if attributes.key?(:'isOffline') && attributes.key?(:'is_offline')
self.is_offline = attributes[:'is_offline'] unless attributes[:'is_offline'].nil?
self.is_offline = false if is_offline.nil? && !attributes.key?(:'isOffline') && !attributes.key?(:'is_offline') # rubocop:disable Style/StringLiterals
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# Checks equality by comparing each attribute.
# @param [Object] other the other object to be compared
def ==(other)
return true if equal?(other)
self.class == other.class &&
name == other.name &&
ip_address == other.ip_address &&
target_id == other.target_id &&
port == other.port &&
weight == other.weight &&
is_drain == other.is_drain &&
is_backup == other.is_backup &&
is_offline == other.is_offline
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# @see the `==` method
# @param [Object] other the other object to be compared
def eql?(other)
self == other
end
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[name, ip_address, target_id, port, weight, is_drain, is_backup, is_offline].hash
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
public_method("#{key}=").call(
attributes[self.class.attribute_map[key]]
.map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) }
)
end
elsif !attributes[self.class.attribute_map[key]].nil?
public_method("#{key}=").call(
OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]])
)
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = public_method(attr).call
next if value.nil? && !instance_variable_defined?("@#{attr}")
hash[param] = _to_hash(value)
end
hash
end
private
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 40.118705 | 245 | 0.670492 |
bbd106529c8400a0ddb42c263480ad12cf3c11b2
| 576 |
class Harbor
module Events
class ServerErrorEvent
attr_reader :request, :response, :exception
def initialize(request, response, exception)
@request = request
@response = response
@exception = exception
@occurred = Time::now
end
def trace
<<-EOS
#{@exception} (#{@exception.backtrace.first})
#{@exception.backtrace.join("\n")}
== [ Request ] ==
#{@request.env.to_yaml}
================================================================================
EOS
end
end
end
end
| 19.2 | 80 | 0.498264 |
ff03bac5a0b8daf69c94cb79e73076fdbce21cfa
| 3,964 |
# -------------------------------------------------------------------------- #
# Copyright 2002-2020, OpenNebula Project, OpenNebula Systems #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may #
# not use this file except in compliance with the License. You may obtain #
# a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
#--------------------------------------------------------------------------- #
require 'ipaddr'
module VXLAN
ATTR_VLAN_ID = :vlan_id
ATTR_VLAN_DEV = :vlan_dev
############################################################################
# This function creates and activate a VLAN device
############################################################################
def create_vlan_dev
vxlan_mode = @nic[:conf][:vxlan_mode] || 'multicast'
group = ""
if vxlan_mode.downcase == 'evpn'
vxlan_tep = @nic[:conf][:vxlan_tep] || 'dev'
if vxlan_tep.downcase == 'dev'
tep = "dev #{@nic[:phydev]}"
else
tep = "local #{get_interface_first_ip(@nic[:phydev])}"
end
else
begin
ipaddr = IPAddr.new @nic[:conf][:vxlan_mc]
rescue
ipaddr = IPAddr.new "239.0.0.0"
end
mc = ipaddr.to_i + @nic[@attr_vlan_id].to_i
mcs = IPAddr.new(mc, Socket::AF_INET).to_s
group = "group #{mcs}"
tep = "dev #{@nic[:phydev]}"
end
mtu = @nic[:mtu] ? "mtu #{@nic[:mtu]}" : "mtu #{@nic[:conf][:vxlan_mtu]}"
ttl = @nic[:conf][:vxlan_ttl] ? "ttl #{@nic[:conf][:vxlan_ttl]}" : ""
ip_link_conf = ""
@nic[:ip_link_conf].each do |option, value|
case value
when true
value = "on"
when false
value = "off"
end
ip_link_conf << "#{option} #{value} "
end
# `ip link add ...` returns 2 when vxlan device already exists
# allow it to prevent race conditions
OpenNebula.exec_and_log("#{command(:ip)} link add #{@nic[@attr_vlan_dev]}"\
" #{mtu} type vxlan id #{@nic[@attr_vlan_id]} #{group} #{ttl}"\
" #{tep} #{ip_link_conf}", nil, 2)
OpenNebula.exec_and_log("#{command(:ip)} link set #{@nic[@attr_vlan_dev]} up")
end
def delete_vlan_dev
OpenNebula.exec_and_log("#{command(:ip)} link delete #{@nic[@attr_vlan_dev]}")
end
def list_interface_vlan(name)
text = %x(#{command(:ip_unpriv)} -d link show #{name})
return nil if $?.exitstatus != 0
text.each_line do |line|
m = line.match(/^\s*vxlan id (\d+)/)
return m[1] if m
end
nil
end
def get_interface_first_ip(name)
text = %x(#{command(:ip_unpriv)} addr show dev #{name})
return nil if $?.exitstatus != 0
text.each_line do |line|
m = line.match(/^\s*inet6? ([a-f:\d\.]+)/i)
if m
next if m[1].start_with?('127.')
next if m[1] == '::1'
return m[1]
end
end
return nil
end
end
| 36.366972 | 86 | 0.445762 |
ed15af2362b39d8e085783cd629a7676b51b44d6
| 1,256 |
class UsersController < ApplicationController
get '/users/:slug' do
@user = User.find_by_slug(params[:slug])
erb :'users/show'
end
get '/signup' do
if !logged_in?
erb :'users/create_user', locals: {message: "Please sign up before you sign in"}
else
redirect to '/tweets'
end
end
post '/signup' do
if params[:username] == "" || params[:email] == "" || params[:password] == ""
redirect to '/signup'
else
@user = User.new(:username => params[:username], :email => params[:email], :password => params[:password])
@user.save
session[:user_id] = @user.id
redirect to '/tweets'
end
end
get '/login' do
if !logged_in?
erb :'users/login'
else
redirect '/tweets'
end
end
post '/login' do
user = User.find_by(:username => params[:username])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect "/tweets"
else
redirect to '/signup'
end
end
get '/logout' do
if logged_in?
session.destroy
redirect to '/login'
else
redirect to '/'
end
end
end
| 23.698113 | 114 | 0.539013 |
5dbf61938ec66b00bb2a46ccfa77b8e9d7d942bc
| 600 |
module Stripe
class FileUpload < APIResource
def self.url
"/v1/files"
end
def self.create(params={}, opts={})
opts = {
:content_type => 'multipart/form-data',
:api_base => Stripe::uploads_base
}.merge(opts)
response, opts = request(:post, url, params, opts)
Util.convert_to_stripe_object(response, opts)
end
def self.all(filters={}, opts={})
opts = {:api_base => Stripe::uploads_base}.merge(opts)
response, opts = request(:get, url, filters, opts)
Util.convert_to_stripe_object(response, opts)
end
end
end
| 26.086957 | 60 | 0.621667 |
e8d4fcb76e4bb77b018f41b0c6a3f3b814184d74
| 1,069 |
require "language/node"
class Nativefier < Formula
desc "Wrap web apps natively"
homepage "https://github.com/jiahaog/nativefier"
url "https://registry.npmjs.org/nativefier/-/nativefier-43.0.2.tgz"
sha256 "631bbc87ada48db0c225d9f81f6c81921865d686175d8fb40f47bf1c39e95b0a"
license "MIT"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "74c858a489c1d4f9dbebb3c92c105043f59e2328b72810c6d75b75cce53e56e4"
sha256 cellar: :any_skip_relocation, big_sur: "8617a8017656d3653fb51ed68d90f4359321ff7e332f0aa020463003540f3d5e"
sha256 cellar: :any_skip_relocation, catalina: "f209f65fadb14a260d0566d30b4a033d624573ba27152f96ec1464af82c45201"
sha256 cellar: :any_skip_relocation, mojave: "e06f4c59e370a23ac8fc97a04c4c157ce7dba0a5c0d9e0f3872ad80f98ceca59"
end
depends_on "node"
def install
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
assert_match version.to_s, shell_output("#{bin}/nativefier --version")
end
end
| 38.178571 | 122 | 0.784846 |
01492aa423b72d469c551e2b859b7ad6c5f20c4c
| 10,543 |
require 'pathname'
require 'exceptions'
require 'os/mac'
require 'utils/json'
require 'utils/inreplace'
require 'utils/popen'
require 'open-uri'
class Tty
class << self
def blue; bold 34; end
def white; bold 39; end
def red; underline 31; end
def yellow; underline 33; end
def reset; escape 0; end
def em; underline 39; end
def green; bold 32; end
def gray; bold 30; end
def width
`/usr/bin/tput cols`.strip.to_i
end
def truncate(str)
str.to_s[0, width - 4]
end
private
def color n
escape "0;#{n}"
end
def bold n
escape "1;#{n}"
end
def underline n
escape "4;#{n}"
end
def escape n
"\033[#{n}m" if $stdout.tty?
end
end
end
# :startdoc:
def ohai title, *sput
title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
puts "#{Tty.blue}==>#{Tty.white} #{title}#{Tty.reset}"
puts sput
end
def oh1 title
title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
puts "#{Tty.green}==>#{Tty.white} #{title}#{Tty.reset}"
end
def opoo warning
$stderr.puts "#{Tty.red}Warning#{Tty.reset}: #{warning}"
end
def onoe error
$stderr.puts "#{Tty.red}Error#{Tty.reset}: #{error}"
end
def ofail error
onoe error
Homebrew.failed = true
end
def odie error
onoe error
exit 1
end
# :stopdoc:
def pretty_duration s
return "2 seconds" if s < 3 # avoids the plural problem ;)
return "#{s.to_i} seconds" if s < 120
return "%.1f minutes" % (s/60)
end
def plural n, s="s"
(n == 1) ? "" : s
end
def interactive_shell f=nil
unless f.nil?
ENV['HOMEBREW_DEBUG_PREFIX'] = f.prefix
ENV['HOMEBREW_DEBUG_INSTALL'] = f.name
end
Process.wait fork { exec ENV['SHELL'] }
if $?.success?
return
elsif $?.exited?
puts "Aborting due to non-zero exit status"
exit $?.exitstatus
else
raise $?.inspect
end
end
module Homebrew
def self.system cmd, *args
puts "#{cmd} #{args*' '}" if ARGV.verbose?
pid = fork do
yield if block_given?
args.collect!{|arg| arg.to_s}
exec(cmd, *args) rescue nil
exit! 1 # never gets here unless exec failed
end
Process.wait(pid)
$?.success?
end
def self.git_head
HOMEBREW_REPOSITORY.cd { `git rev-parse --verify -q HEAD 2>/dev/null`.chuzzle }
end
def self.git_last_commit
HOMEBREW_REPOSITORY.cd { `git show -s --format="%cr" HEAD 2>/dev/null`.chuzzle }
end
end
def with_system_path
old_path = ENV['PATH']
ENV['PATH'] = '/usr/bin:/bin'
yield
ensure
ENV['PATH'] = old_path
end
# Kernel.system but with exceptions
def safe_system cmd, *args
Homebrew.system(cmd, *args) or raise ErrorDuringExecution.new(cmd, args)
end
# prints no output
def quiet_system cmd, *args
Homebrew.system(cmd, *args) do
# Redirect output streams to `/dev/null` instead of closing as some programs
# will fail to execute if they can't write to an open stream.
$stdout.reopen('/dev/null')
$stderr.reopen('/dev/null')
end
end
def curl *args
curl = Pathname.new '/usr/bin/curl'
raise "#{curl} is not executable" unless curl.exist? and curl.executable?
flags = HOMEBREW_CURL_ARGS
flags = flags.delete("#") if ARGV.verbose?
args = [flags, HOMEBREW_USER_AGENT, *args]
# See https://github.com/Homebrew/homebrew/issues/6103
args << "--insecure" if MacOS.version < "10.6"
args << "--verbose" if ENV['HOMEBREW_CURL_VERBOSE']
args << "--silent" unless $stdout.tty?
safe_system curl, *args
end
def puts_columns items, star_items=[]
return if items.empty?
if star_items && star_items.any?
items = items.map{|item| star_items.include?(item) ? "#{item}*" : item}
end
if $stdout.tty?
# determine the best width to display for different console sizes
console_width = `/bin/stty size`.chomp.split(" ").last.to_i
console_width = 80 if console_width <= 0
longest = items.sort_by { |item| item.length }.last
optimal_col_width = (console_width.to_f / (longest.length + 2).to_f).floor
cols = optimal_col_width > 1 ? optimal_col_width : 1
IO.popen("/usr/bin/pr -#{cols} -t -w#{console_width}", "w"){|io| io.puts(items) }
else
puts items
end
end
def which cmd, path=ENV['PATH']
path.split(File::PATH_SEPARATOR).each do |p|
pcmd = File.expand_path(cmd, p)
return Pathname.new(pcmd) if File.file?(pcmd) && File.executable?(pcmd)
end
return nil
end
def which_editor
editor = ENV.values_at('HOMEBREW_EDITOR', 'VISUAL', 'EDITOR').compact.first
# If an editor wasn't set, try to pick a sane default
return editor unless editor.nil?
# Find Textmate
return 'mate' if which "mate"
# Find BBEdit / TextWrangler
return 'edit' if which "edit"
# Find vim
return 'vim' if which "vim"
# Default to standard vim
return '/usr/bin/vim'
end
def exec_editor *args
safe_exec(which_editor, *args)
end
def exec_browser *args
browser = ENV['HOMEBREW_BROWSER'] || ENV['BROWSER'] || OS::PATH_OPEN
safe_exec(browser, *args)
end
def safe_exec cmd, *args
# This buys us proper argument quoting and evaluation
# of environment variables in the cmd parameter.
exec "/bin/sh", "-c", "#{cmd} \"$@\"", "--", *args
end
# GZips the given paths, and returns the gzipped paths
def gzip *paths
paths.collect do |path|
with_system_path { safe_system 'gzip', path }
Pathname.new("#{path}.gz")
end
end
# Returns array of architectures that the given command or library is built for.
def archs_for_command cmd
cmd = which(cmd) unless Pathname.new(cmd).absolute?
Pathname.new(cmd).archs
end
def ignore_interrupts(opt = nil)
std_trap = trap("INT") do
puts "One sec, just cleaning up" unless opt == :quietly
end
yield
ensure
trap("INT", std_trap)
end
def nostdout
if ARGV.verbose?
yield
else
begin
out = $stdout.dup
$stdout.reopen("/dev/null")
yield
ensure
$stdout.reopen(out)
out.close
end
end
end
def paths
@paths ||= ENV['PATH'].split(File::PATH_SEPARATOR).collect do |p|
begin
File.expand_path(p).chomp('/')
rescue ArgumentError
onoe "The following PATH component is invalid: #{p}"
end
end.uniq.compact
end
module GitHub extend self
ISSUES_URI = URI.parse("https://api.github.com/search/issues")
Error = Class.new(RuntimeError)
HTTPNotFoundError = Class.new(Error)
class RateLimitExceededError < Error
def initialize(reset, error)
super <<-EOS.undent
GitHub #{error}
Try again in #{pretty_ratelimit_reset(reset)}, or create an API token:
https://github.com/settings/applications
and then set HOMEBREW_GITHUB_API_TOKEN.
EOS
end
def pretty_ratelimit_reset(reset)
if (seconds = Time.at(reset) - Time.now) > 180
"%d minutes %d seconds" % [seconds / 60, seconds % 60]
else
"#{seconds} seconds"
end
end
end
class AuthenticationFailedError < Error
def initialize(error)
super <<-EOS.undent
GitHub #{error}
HOMEBREW_GITHUB_API_TOKEN may be invalid or expired, check:
https://github.com/settings/applications
EOS
end
end
def open url, headers={}, &block
# This is a no-op if the user is opting out of using the GitHub API.
return if ENV['HOMEBREW_NO_GITHUB_API']
safely_load_net_https
default_headers = {
"User-Agent" => HOMEBREW_USER_AGENT,
"Accept" => "application/vnd.github.v3+json",
}
default_headers['Authorization'] = "token #{HOMEBREW_GITHUB_API_TOKEN}" if HOMEBREW_GITHUB_API_TOKEN
begin
Kernel.open(url, default_headers.merge(headers)) do |f|
yield Utils::JSON.load(f.read)
end
rescue OpenURI::HTTPError => e
handle_api_error(e)
rescue EOFError, SocketError, OpenSSL::SSL::SSLError => e
raise Error, "Failed to connect to: #{url}\n#{e.message}", e.backtrace
rescue Utils::JSON::Error => e
raise Error, "Failed to parse JSON response\n#{e.message}", e.backtrace
end
end
def handle_api_error(e)
if e.io.meta["x-ratelimit-remaining"].to_i <= 0
reset = e.io.meta.fetch("x-ratelimit-reset").to_i
error = Utils::JSON.load(e.io.read)["message"]
raise RateLimitExceededError.new(reset, error)
end
case e.io.status.first
when "401", "403"
raise AuthenticationFailedError.new(e.message)
when "404"
raise HTTPNotFoundError, e.message, e.backtrace
else
raise Error, e.message, e.backtrace
end
end
def issues_matching(query, qualifiers={})
uri = ISSUES_URI.dup
uri.query = build_query_string(query, qualifiers)
open(uri) { |json| json["items"] }
end
def build_query_string(query, qualifiers)
s = "q=#{uri_escape(query)}+"
s << build_search_qualifier_string(qualifiers)
s << "&per_page=100"
end
def build_search_qualifier_string(qualifiers)
{
:repo => "Homebrew/homebrew",
:in => "title",
}.update(qualifiers).map { |qualifier, value|
"#{qualifier}:#{value}"
}.join("+")
end
def uri_escape(query)
if URI.respond_to?(:encode_www_form_component)
URI.encode_www_form_component(query)
else
require "erb"
ERB::Util.url_encode(query)
end
end
def issues_for_formula name
issues_matching(name, :state => "open")
end
def print_pull_requests_matching(query)
return [] if ENV['HOMEBREW_NO_GITHUB_API']
puts "Searching pull requests..."
open_or_closed_prs = issues_matching(query, :type => "pr")
open_prs = open_or_closed_prs.select {|i| i["state"] == "open" }
if open_prs.any?
puts "Open pull requests:"
prs = open_prs
elsif open_or_closed_prs.any?
puts "Closed pull requests:"
prs = open_or_closed_prs
else
return
end
prs.each { |i| puts "#{i["title"]} (#{i["html_url"]})" }
end
def private_repo?(user, repo)
uri = URI.parse("https://api.github.com/repos/#{user}/#{repo}")
open(uri) { |json| json["private"] }
end
private
# If the zlib formula is loaded, TypeError will be raised when we try to load
# net/https. This monkeypatch prevents that and lets Net::HTTP fall back to
# the non-gzip codepath.
def safely_load_net_https
return if defined?(Net::HTTP)
if defined?(Zlib) && RUBY_VERSION >= "1.9"
require "net/protocol"
http = Class.new(Net::Protocol) do
def self.require(lib)
raise LoadError if lib == "zlib"
super
end
end
Net.const_set(:HTTP, http)
end
require "net/https"
end
end
| 24.461717 | 104 | 0.653419 |
ff607c840cb9dbb6de4d94390a0305c6757db4af
| 765 |
require 'spec_helper'
require 'fileutils'
describe CSVSjis do
let(:file_path) do
RSpec.configuration.spec_root.join('tmp/sample.csv')
end
let(:charactors) do
%w(- ~)
end
let(:source_path) do
RSpec.configuration.spec_root.join('tmp/source.csv')
end
before :each do
FileUtils.mkdir_p(File.dirname(file_path))
end
after :each do
FileUtils.rm_rf(File.dirname(file_path))
end
describe '#open' do
subject do
-> {
CSVSjis.open(file_path, 'w+') do |csv|
csv << charactors
end
}
end
it 'not raise error' do
expect(subject).to_not raise_error
end
it 'generate valid csv' do
subject.call.close
expect(file_path.read).to eq("-,~\n")
end
end
end
| 17.386364 | 56 | 0.624837 |
28601d9f31f584c4511aa2474196d061a1d19be4
| 1,032 |
require_relative 'boot'
require 'bigdecimal'
require 'bigdecimal/util'
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 RailsExample
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'CET'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# config.active_record.schema_format = :sql
end
end
| 36.857143 | 99 | 0.731589 |
33ad31618cd140cca39f73df5dd803795d004e2d
| 1,553 |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'departure/version'
Gem::Specification.new do |spec|
spec.name = 'departure'
spec.version = Departure::VERSION
spec.authors = ['Ilya Zayats', 'Pau Pérez', 'Fran Casas', 'Jorge Morante', 'Enrico Stano', 'Adrian Serafin', 'Kirk Haines', 'Guillermo Iguaran']
spec.email = ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']
spec.summary = %q(pt-online-schema-change runner for ActiveRecord migrations)
spec.description = %q(Execute your ActiveRecord migrations with Percona's pt-online-schema-change. Formerly known as Percona Migrator.)
spec.homepage = 'https://github.com/departurerb/departure'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.require_paths = ['lib']
spec.add_runtime_dependency 'railties', '~> 5.2.0'
spec.add_runtime_dependency 'activerecord', '~> 5.2.0'
spec.add_runtime_dependency 'mysql2', '>= 0.4.0', '<= 0.5.2'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec', '~> 3.4', '>= 3.4.0'
spec.add_development_dependency 'rspec-its', '~> 1.2'
spec.add_development_dependency 'byebug', '~> 8.2', '>= 8.2.1'
spec.add_development_dependency 'climate_control', '~> 0.0.3'
end
| 48.53125 | 204 | 0.67933 |
bb8a13174c159d7c2cdc97db8abb9992bd16d767
| 1,167 |
require 'cuboid'
#This test is incomplete and, in fact, won't even run without errors.
# Do whatever you need to do to make it work and please add your own test cases for as many
# methods as you feel need coverage
describe Cuboid do
subject = Cuboid.new(20, 20, 20, 5, 5, 5)
other_subject = Cuboid.new(20, 20, 20, 5, 5, 5)
describe "move_to" do
it "changes the origin in the simple happy case" do
expect(subject.move_to!(5, 5, 5)).to be true
end
end
describe "intersects?" do
it "returns true if the two cuboids intersect" do
expect(subject.intersects?(other_subject)).to be true
end
it "returns false if the two cuboids do not intersect" do
expect(subject.intersects?(other_subject)).to be false
end
it "returns true if y coordinates intersect" do
expect(subject.y_pos_intersects?(other_subject)).to be true
end
it "returns true if x coordinates intersect" do
expect(subject.x_pos_intersects?(other_subject)).to be true
end
it "returns true if z coordinates intersect" do
expect(subject.z_pos_intersects?(other_subject)).to be true
end
end
end
| 27.139535 | 92 | 0.692374 |
ffebb176221d825e5db6279151e39b5cc3d41ec4
| 5,424 |
describe ReportController, "::Reports" do
let(:user) { FactoryGirl.create(:user) }
let(:chargeback_report) do
FactoryGirl.create(:miq_report, :db => "ChargebackVm", :db_options => {:options => {:owner => user.userid}},
:col_order => ["name"], :headers => ["Name"])
end
tabs = {:formatting => 2, :filter => 3, :summary => 4, :charts => 5, :timeline => 6, :preview => 7,
:consolidation => 8, :styling => 9}
chargeback_tabs = [:formatting, :filter, :preview]
before { login_as user }
describe "#build_edit_screen" do
tabs.slice(*chargeback_tabs).each do |tab_number|
it "flash messages should be nil" do
controller.instance_variable_set(:@rpt, chargeback_report)
controller.send(:set_form_vars)
controller.instance_variable_set(:@sb, :miq_tab => "edit_#{tab_number.second}")
controller.send(:build_edit_screen)
expect(assigns(:flash_array)).to be_nil
end
end
end
describe "#check_tabs" do
tabs.each_pair do |tab_title, tab_number|
title = tab_title.to_s.titleize
it "check existence of flash message when tab is changed to #{title} without selecting fields" do
controller.instance_variable_set(:@sb, {})
controller.instance_variable_set(:@edit, :new => {:fields => []})
controller.instance_variable_set(:@_params, :tab => "new_#{tab_number}")
controller.send(:check_tabs)
flash_messages = assigns(:flash_array)
flash_str = "#{title} tab is not available until at least 1 field has been selected"
expect(flash_messages.first[:message]).to eq(flash_str)
expect(flash_messages.first[:level]).to eq(:error)
end
it "flash messages should be nil when tab is changed to #{title} after selecting fields" do
controller.instance_variable_set(:@sb, {})
controller.instance_variable_set(:@edit, :new => {
:fields => [["Date Created", "Vm-ems_created_on"]],
:sortby1 => "some_field"
})
controller.instance_variable_set(:@_params, :tab => "new_#{tab_number}")
controller.send(:check_tabs)
expect(assigns(:flash_array)).to be_nil
end
end
it "check existence of flash message when tab is changed to preview without selecting filters(chargeback report)" do
controller.instance_variable_set(:@sb, {})
controller.instance_variable_set(:@edit, :new => {:fields => [["Date Created"]], :model => "ChargebackVm"})
controller.instance_variable_set(:@_params, :tab => "new_7") # preview
controller.send(:check_tabs)
flash_messages = assigns(:flash_array)
expect(flash_messages).not_to be_nil
flash_str = "Preview tab is not available until Chargeback Filters has been configured"
expect(flash_messages.first[:message]).to eq(flash_str)
expect(flash_messages.first[:level]).to eq(:error)
end
end
describe "#miq_report_delete" do
before do
EvmSpecHelper.local_miq_server # timezone stuff
login_as FactoryGirl.create(:user, :features => :miq_report_delete)
end
it "deletes the report" do
FactoryGirl.create(:miq_report)
report = FactoryGirl.create(:miq_report, :rpt_type => "Custom")
session['sandboxes'] = {
controller.controller_name => { :active_tree => 'report_1',
:trees => {'report_1' => {:active_node => "xx-0_xx-0-0_rep-#{report.id}"}}
}
}
get :x_button, :params => { :id => report.id, :pressed => 'miq_report_delete' }
expect(response.status).to eq(200)
expect(MiqReport.find_by(:id => report.id)).to be_nil
end
it "cant delete default reports" do
FactoryGirl.create(:miq_report)
report = FactoryGirl.create(:miq_report, :rpt_type => "Default")
session['sandboxes'] = {
controller.controller_name => { :active_tree => 'report_1',
:trees => {'report_1' => {:active_node => "xx-0_xx-0-0_rep-#{report.id}"}}
}
}
get :x_button, :params => { :id => report.id, :pressed => 'miq_report_delete' }
expect(response.status).to eq(200)
expect(MiqReport.find_by(:id => report.id)).not_to be_nil
end
# it "fails if widgets exist" do
# report = FactoryGirl.create(:miq_report)
# FactoryGirl.create(:miq_widget, :resource => report)
# end
end
describe "#verify is_valid? flash messages" do
it "show flash message when show cost by entity is selected but no entity_id chosen" do
model = "ChargebackContainerProject"
controller.instance_variable_set(:@edit, :new => {:model => model,
:fields => [["Date Created"]],
:cb_show_typ => "entity",
:cb_model => "ContainerProject"})
controller.instance_variable_set(:@sb, {})
rpt = FactoryGirl.create(:miq_report_chargeback)
controller.send(:valid_report?, rpt)
flash_messages = assigns(:flash_array)
flash_str = "A specific Project or all must be selected"
expect(flash_messages.first[:message]).to eq(flash_str)
expect(flash_messages.first[:level]).to eq(:error)
end
end
end
| 43.741935 | 120 | 0.614676 |
1d6ec14eaff51d288f553eac07b6353a28ea2dbd
| 491 |
class Sentence < ApplicationRecord
belongs_to :publication
has_many :similar, class_name: "Similarity",
foreign_key: "original_id",
dependent: :destroy
def percentage_max_score
maximum = self.publication.max_score
# self.publication.sentences.where.not('max_score' => nil).order("max_score DESC").first.max_score
own_score = self.max_score
return (own_score / maximum) rescue 0
end
end
| 32.733333 | 106 | 0.633401 |
1a941909c10a12292d3ea938d36151c4f7a00c2c
| 2,330 |
# frozen_string_literal: true
#
# Cookbook Name:: rabbitmq_test
# Recipe:: lwrps
#
# Copyright 2013, Chef Software, Inc. <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
chef_gem 'bunny' do
action :install
end
include_recipe 'rabbitmq::default'
# force the rabbitmq restart now, then start testing
execute 'sleep 10' do
notifies :restart, "service[#{node['rabbitmq']['service_name']}]", :immediately
end
include_recipe 'rabbitmq::plugin_management'
include_recipe 'rabbitmq::virtualhost_management'
include_recipe 'rabbitmq::policy_management'
include_recipe 'rabbitmq::user_management'
# can't verify it actually goes through without logging in, but at least exercise the code
rabbitmq_user 'kitchen3' do
password 'foobar'
action :change_password
end
# download the rabbitmqadmin util from management plugin
# this tests an immediate notifies statement
# see https://github.com/kennonkwok/rabbitmq/issues/141
rabbitmq_plugin 'rabbitmq_management' do
action :enable
notifies :restart, "service[#{node['rabbitmq']['service_name']}]", :immediately # must restart before we can download
end
remote_file '/usr/local/bin/rabbitmqadmin' do
source 'http://localhost:15672/cli/rabbitmqadmin'
mode '0755'
action :create
end
# rabbitmqadmin needs python which is not part of every systems. This is a shortcut,
# you probably want to use the cookbook poise-python for real python things.
package 'python' do
not_if 'which python'
end
rabbitmq_policy 'rabbitmq_cluster' do
pattern 'cluster.*'
parameters 'ha-mode' => 'all', 'ha-sync-mode' => 'automatic'
apply_to 'queues'
action :set
end
rabbitmq_plugin 'rabbitmq_federation'
rabbitmq_vhost '/sensu'
rabbitmq_parameter 'sensu-dc-1' do
vhost '/sensu'
component 'federation-upstream'
parameters 'uri' => 'amqp://dc-cluster-node'
end
| 29.493671 | 119 | 0.76309 |
6190720b4b1a731b7f270d71a9f3897604dd0cf5
| 431 |
require './config/environment'
require 'sinatra/flash'
class ApplicationController < Sinatra::Base
configure do
set :public_folder, 'public'
set :views, 'app/views'
enable :sessions
set :session_secret, 'seedy_secrets'
register Sinatra::Flash
end
get '/' do
erb :index
end
def is_logged_in?
!!session[:user_id]
end
def current_user
@user = User.find(session[:user_id])
end
end
| 15.962963 | 43 | 0.675174 |
384d001357790d025d23dac27e26f3b51b4ceb3c
| 269 |
class CreateFoods < ActiveRecord::Migration[6.1]
def change
create_table :foods do |t|
t.string :name
t.decimal :cost
t.integer :calories
t.belongs_to :category, null: false, foreign_key: true
t.timestamps
end
end
end
| 19.214286 | 60 | 0.63197 |
086d7273eacd226b266cdb58c7ba48de2874aa31
| 783 |
# == Schema Information
#
# Table name: laws
#
# id :integer not null, primary key
# written_infraction :text
# infraction :text
# sanctions :text
# min_fine :integer
# max_fine :integer
# penal_servitude :string
# other_penalties :text
# apv :text
# subcategory_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# country_id :integer
# currency :string
#
FactoryBot.define do
factory :law do
min_fine { rand(0..10) }
max_fine { rand(0..10) }
after(:build) do |law|
law.subcategory ||= FactoryBot.create :subcategory
law.country ||= FactoryBot.create :country
end
end
end
| 24.46875 | 61 | 0.564496 |
87f20be12a98abb60ab4bbb8f1c7cad3f8b74175
| 642 |
require 'ovh/rest'
OVH_APP_KEY = "{{OVH_APP_KEY}}"
OVH_APP_SECRET = "{{OVH_APP_SECRET}}"
OVH_APP_CONSUMER = "{{OVH_APP_CONSUMER}}"
OVH_PROJECT = "{{OVH_PROJECT}}"
OVH_FAILOVER_IP = "{{OVH_FAILOVER_IP}}"
OVH_CURRENT_SERVER = "{{OVH_CURRENT_SERVER}}"
ovh = OVH::REST.new(OVH_APP_KEY, OVH_APP_SECRET, OVH_APP_CONSUMER)
5.times do
result = ovh.get("/cloud/project/#{OVH_PROJECT}/ip/failover/#{OVH_FAILOVER_IP}") rescue {}
if result["routedTo"] != OVH_CURRENT_SERVER
ovh.post("/cloud/project/#{OVH_PROJECT}/ip/failover/#{OVH_FAILOVER_IP}/attach", {"instanceId" => OVH_CURRENT_SERVER}) rescue nil
sleep 10
else
break
end
end
| 30.571429 | 132 | 0.725857 |
acc1663813731fef8e99d9384f8d524db84d2998
| 218 |
class IncludeOptionsInApiAnswersView < ActiveRecord::Migration
def up
execute view_sql('20151111121003', 'api_answers_view')
end
def down
execute view_sql('20151109160327', 'api_answers_view')
end
end
| 21.8 | 62 | 0.766055 |
1df0f54c852396d22dabf80769996d063c399fb1
| 1,773 |
require File.expand_path('../boot', __FILE__)
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 Battleship
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
config.assets.paths << Rails.root.join("vendor","assets","bower_components")
config.assets.paths << Rails.root.join("vendor","assets","bower_components","bootstrap-sass-official","assets","fonts")
config.assets.precompile << %r(.*.(?:eot|svg|ttf|woff|woff2)$)
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
# Configure Generators
config.generators do |g|
g.orm :active_record
g.template_engine :erb
g.test_framework :rspec, fixture: false
g.view_specs false
g.helper_specs false
g.stylesheets false
g.javascripts false
end
# Add folders to autoload
config.autoload_paths << Rails.root.join('lib')
end
end
| 39.4 | 123 | 0.700508 |
bb657704c32c9c5f102316822b82fe945208ad18
| 2,020 |
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
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
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
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_caching = false
config.action_mailer.perform_deliveries = false
config.action_mailer.default_url_options = { host: "localhost:8787" }
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
# 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
# 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::FileUpdateChecker
# Needed for the CRA proxy to work in Docker
config.hosts << "rails"
end
| 36.071429 | 85 | 0.757426 |
084f8e457cb1cc1f8850c8361b7d9f3f24309069
| 450 |
class Course::Forum::TopicNotifier < Notifier::Base
# To be called when user created a new forum topic.
def topic_created(user, topic)
activity = create_activity(actor: user, object: topic, event: :created)
activity.notify(topic.forum.course, :feed)
topic.forum.subscriptions.includes(:user).each do |subscription|
activity.notify(subscription.user, :email) unless subscription.user == user
end
activity.save!
end
end
| 37.5 | 81 | 0.731111 |
39b87609c6172829e57f8faf8ff0948987feba0c
| 87 |
class WordSerializer < ActiveModel::Serializer
attributes :spelling, :definition
end
| 21.75 | 46 | 0.816092 |
e99526432b7d8321965a2a802dfd0e96acb2b1e5
| 611 |
# = MerbRuty Filter Tag
class MerbRuty::Tags::Filter < MerbRuty::Tag
def initialize parser, argstring
@filters = parser.parse_arguments('|' + argstring)
parser.fail('filter tag requires at least on filter') if @filters.empty?
@nodelist = parser.parse_until { |n, a| n == :endfilter }
end
def render_node context, stream
substream = MerbRuty::Datastructure::OutputStream.new
@nodelist.render_node(context, substream)
value = context.apply_filters(substream.to_s, @filters).to_s
stream << value if not value.empty?
nil
end
MerbRuty::Tags.register(self, :filter)
end
| 27.772727 | 76 | 0.708674 |
213cc51739b10bc453e8e57c8bceea735e858174
| 241 |
FactoryGirl.define do
factory :service_simpliss_v1_consulta_nfs_por_rps, class: BrNfe::Service::Simpliss::V1::ConsultaNfsPorRps do
rps { FactoryGirl.build(:br_nfe_rps) }
emitente { FactoryGirl.build(:service_emitente) }
end
end
| 40.166667 | 110 | 0.775934 |
1c96182466ccfe3a22c722ba3cfc4e28255de85b
| 470 |
# frozen_string_literal: true
class DirectoryNode
include Mindmap::Node
attr_accessor :path
def name
File.basename(path)
end
def children
Dir
.entries(path)
.sort
.reject! { |file| ['.', '..'].include?(file) }
.map { |file| child(File.expand_path(file, path)) }
end
private
def child(file_path)
return DirectoryNode.new(path: file_path) if File.directory?(file_path)
FileNode.new(path: file_path)
end
end
| 16.785714 | 75 | 0.648936 |
01bc4f29b10cc8e02b8f82448edebc38f4f211a5
| 938 |
# encoding: utf-8
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# /spec/fixtures/responses/whois.nic.tl/property_status_not_registered.expected
#
# and regenerate the tests with the following rake task
#
# $ rake spec:generate
#
require 'spec_helper'
require 'whois/record/parser/whois.nic.tl.rb'
describe Whois::Record::Parser::WhoisNicTl, "property_status_not_registered.expected" do
before(:each) do
file = fixture("responses", "whois.nic.tl/property_status_not_registered.txt")
part = Whois::Record::Part.new(:body => File.read(file))
@parser = klass.new(part)
end
describe "#status" do
it do
@parser.status.should == :available
end
end
describe "#available?" do
it do
@parser.available?.should == true
end
end
describe "#registered?" do
it do
@parser.registered?.should == false
end
end
end
| 23.45 | 88 | 0.696162 |
d5855a28e8d497699b7e4860a48886a883ca1609
| 368 |
require 'spec_helper'
describe Rubella::Input::JSON, '#self.string' do
it 'returns a Rubella::Input::JSON object' do
input = Rubella::Input::JSON.string '[]'
expect(input).to be_instance_of(Rubella::Input::JSON)
end
it "uses the given data" do
input = Rubella::Input::JSON.string '[1, 2, 3]'
expect(input.data).to eq([1, 2, 3])
end
end
| 20.444444 | 57 | 0.649457 |
4a572ae130d4dad2d709e2ba63833315ae6d2314
| 1,206 |
# frozen_string_literal: true
require 'spec_helper'
require 'aca_entities/serializers/xml/fdsh/ridp'
require 'pry'
RSpec.describe AcaEntities::Serializers::Xml::Fdsh::Ridp::SecondaryRequest,
"given a minimal Primary Response object" do
let(:secondary_request) do
AcaEntities::Fdsh::Ridp::H139::SecondaryRequest.new(
{
SessionIdentification: '123456789',
VerificationAnswerSet: {
VerificationAnswers: [
{
VerificatonAnswer: 1,
VerificationQuestionNumber: 1
},
{
VerificatonAnswer: 4,
VerificationQuestionNumber: 2
},
{
VerificatonAnswer: 2,
VerificationQuestionNumber: 3
}
]
}
}
)
end
subject do
AcaEntities::Serializers::Xml::Fdsh::Ridp::Request.domain_to_mapper(
secondary_request,
"secondary_request"
).to_xml
end
it "creates a schema valid result" do
validation_result = AcaEntities::Serializers::Xml::Fdsh::Ridp::Operations::ValidateRidpPayloadXml.new.call(subject)
expect(validation_result.success?).to be_truthy
end
end
| 26.217391 | 119 | 0.616915 |
bbcf3c28593fb516184d9d17011e27bc799d364d
| 1,282 |
require 'test_helper'
# $ rake test:func:ios TEST=test/functional/ios/patch_test.rb
# rubocop:disable Style/ClassVars
class AppiumLibCoreTest
class PathTest < AppiumLibCoreTest::Function::TestCase
def setup
@@core ||= ::Appium::Core.for(Caps.ios)
@@driver ||= @@core.start_driver
end
def teardown
save_reports(@@driver)
end
def test_method_missing_attributes
e = @@core.wait { @@driver.find_element :accessibility_id, 'Buttons' }
assert_equal 'Buttons', e.value
assert_equal 'Buttons', e.name
assert_equal 'Buttons', e.label
end
def test_type
e = @@core.wait { @@driver.find_element :accessibility_id, 'TextFields' }
e.click
text = @@core.wait { @@driver.find_element :name, '<enter text>' }
text.type 'hello'
text = @@core.wait { @@driver.find_element :name, 'Normal' }
assert_equal 'hello', text.value
assert_equal 'Normal', text.name
@@driver.back
end
def test_location_rel
e = @@core.wait { @@driver.find_element :accessibility_id, 'TextFields' }
location = e.location_rel(@@driver)
assert_equal '65.5 / 375.0', location.x
assert_equal '196.5 / 667.0', location.y
end
end
end
# rubocop:enable Style/ClassVars
| 26.163265 | 79 | 0.652106 |
911140bb6ad51f5f801d39e60539a8d58048c24c
| 79 |
require 'capistrano/uwsgi/version'
module Capistrano
module Uwsgi
end
end
| 11.285714 | 34 | 0.78481 |
267a979af417333963a36bcf6940fe43d949a8a8
| 18,592 |
require 'test_helper'
class NabTransactTest < Test::Unit::TestCase
include CommStub
def setup
@gateway = NabTransactGateway.new(
:login => 'login',
:password => 'password'
)
@credit_card = credit_card
@amount = 200
@options = {
:order_id => '1',
:billing_address => address,
:description => 'Test NAB Purchase'
}
end
def test_successful_purchase
@gateway.expects(:ssl_post).with(&check_transaction_type(:purchase)).returns(successful_purchase_response)
response = @gateway.purchase(@amount, @credit_card, @options)
assert_instance_of Response, response
assert_success response
assert_equal '009887*test**200', response.authorization
assert response.test?
end
def test_successful_purchase_with_merchant_descriptor
name, location = 'Active Merchant', 'USA'
response = assert_metadata(name, location) do
response = @gateway.purchase(@amount, @credit_card, @options.merge(:merchant_name => name, :merchant_location => location))
end
assert response
assert_instance_of Response, response
assert_success response
end
def test_successful_authorize
@gateway.expects(:ssl_post).with(&check_transaction_type(:authorization)).returns(successful_authorize_response)
response = @gateway.authorize(@amount, @credit_card, @options)
assert_equal '009887*test*009887*200', response.authorization
assert response.test?
end
def test_successful_authorize_with_merchant_descriptor
name, location = 'Active Merchant', 'USA'
response = assert_metadata(name, location) do
response = @gateway.authorize(@amount, @credit_card, @options.merge(:merchant_name => name, :merchant_location => location))
end
assert response
assert_instance_of Response, response
assert_success response
end
def test_successful_capture
@gateway.expects(:ssl_post).with(&check_transaction_type(:capture)).returns(successful_purchase_response)
response = @gateway.capture(@amount, '009887*test*009887*200')
assert_equal '009887*test**200', response.authorization
assert response.test?
end
def test_successful_capture_with_merchant_descriptor
name, location = 'Active Merchant', 'USA'
response = assert_metadata(name, location) do
response = @gateway.capture(@amount, '009887*test*009887*200', @options.merge(:merchant_name => name, :merchant_location => location))
end
assert response
assert_instance_of Response, response
assert_success response
end
def test_unsuccessful_purchase
@gateway.expects(:ssl_post).with(&check_transaction_type(:purchase)).returns(failed_purchase_response)
response = @gateway.purchase(@amount, @credit_card, @options)
assert_instance_of Response, response
assert_failure response
assert response.test?
assert_equal 'Expired Card', response.message
end
def test_failed_login
@gateway.expects(:ssl_post).returns(failed_login_response)
response = @gateway.purchase(@amount, @credit_card, @options)
assert_instance_of Response, response
assert_failure response
assert_equal 'Invalid merchant ID', response.message
end
def test_supported_countries
assert_equal ['AU'], NabTransactGateway.supported_countries
end
def test_supported_card_types
assert_equal [:visa, :master, :american_express, :diners_club, :jcb], NabTransactGateway.supported_cardtypes
end
def test_successful_refund
@gateway.expects(:ssl_post).with(&check_transaction_type(:refund)).returns(successful_refund_response)
assert_success @gateway.refund(@amount, '009887', {:order_id => '1'})
end
def test_successful_refund_with_merchant_descriptor
name, location = 'Active Merchant', 'USA'
response = assert_metadata(name, location) do
response = @gateway.refund(@amount, '009887', {:order_id => '1', :merchant_name => name, :merchant_location => location})
end
assert response
assert_instance_of Response, response
assert_success response
end
def test_successful_credit
@gateway.expects(:ssl_post).with(&check_transaction_type(:unmatched_refund)).returns(successful_refund_response)
assert_success @gateway.credit(@amount, @credit_card, {:order_id => '1'})
end
def test_failed_refund
@gateway.expects(:ssl_post).with(&check_transaction_type(:refund)).returns(failed_refund_response)
response = @gateway.refund(@amount, '009887', {:order_id => '1'})
assert_failure response
assert_equal 'Only $1.00 available for refund', response.message
end
def test_request_timeout_default
stub_comms(@gateway, :ssl_request) do
@gateway.purchase(@amount, @credit_card, @options)
end.check_request do |method, endpoint, data, headers|
assert_match(/<timeoutValue>60/, data)
end.respond_with(successful_purchase_response)
end
def test_override_request_timeout
gateway = NabTransactGateway.new(login: 'login', password: 'password', request_timeout: 44)
stub_comms(gateway, :ssl_request) do
gateway.purchase(@amount, @credit_card, @options)
end.check_request do |method, endpoint, data, headers|
assert_match(/<timeoutValue>44/, data)
end.respond_with(successful_purchase_response)
end
def test_nonfractional_currencies
stub_comms(@gateway, :ssl_request) do
@gateway.authorize(10000, @credit_card, @options.merge(currency: 'JPY'))
end.check_request do |method, endpoint, data, headers|
assert_match(/<amount>100<\/amount>/, data)
end.respond_with(successful_authorize_response)
end
def test_scrub
assert @gateway.supports_scrubbing?
assert_equal @gateway.scrub(pre_scrubbed), post_scrubbed
end
private
def pre_scrubbed
<<-'PRE_SCRUBBED'
opening connection to transact.nab.com.au:443...
opened
starting SSL for transact.nab.com.au:443...
SSL established
<- "POST /test/xmlapi/payment HTTP/1.1\r\nContent-Type: application/x-www-form-urlencoded\r\nAccept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3\r\nAccept: */*\r\nUser-Agent: Ruby\r\nConnection: close\r\nHost: transact.nab.com.au\r\nContent-Length: 715\r\n\r\n"
<- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><NABTransactMessage><MessageInfo><messageID>6673348a21d79657983ab247b2483e</messageID><messageTimestamp>20151212075932886818+000</messageTimestamp><timeoutValue>60</timeoutValue><apiVersion>xml-4.2</apiVersion></MessageInfo><MerchantInfo><merchantID>XYZ0010</merchantID><password>abcd1234</password></MerchantInfo><RequestType>Payment</RequestType><Payment><TxnList count=\"1\"><Txn ID=\"1\"><txnType>0</txnType><txnSource>23</txnSource><amount>200</amount><currency>AUD</currency><purchaseOrderNo></purchaseOrderNo><CreditCardInfo><cardNumber>4444333322221111</cardNumber><expiryDate>05/17</expiryDate><cvv>111</cvv></CreditCardInfo></Txn></TxnList></Payment></NABTransactMessage>"
-> "HTTP/1.1 200 OK\r\n"
-> "Date: Sat, 12 Dec 2015 07:59:34 GMT\r\n"
-> "Server: Apache-Coyote/1.1\r\n"
-> "Content-Type: text/xml;charset=ISO-8859-1\r\n"
-> "Content-Length: 920\r\n"
-> "Connection: close\r\n"
-> "\r\n"
reading 920 bytes...
-> ""
-> "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><NABTransactMessage><MessageInfo><messageID>6673348a21d79657983ab247b2483e</messageID><messageTimestamp>20151212185934964000+660</messageTimestamp><apiVersion>xml-4.2</apiVersion></MessageInfo><RequestType>Payment</RequestType><MerchantInfo><merchantID>XYZ0010</merchantID></MerchantInfo><Status><statusCode>000</statusCode><statusDescription>Normal</statusDescription></Status><Payment><TxnList count=\"1\"><Txn ID=\"1\"><txnType>0</txnType><txnSource>23</txnSource><amount>200</amount><currency>AUD</currency><purchaseOrderNo/><approved>No</approved><responseCode>103</responseCode><responseText>Invalid Purchase Order Number</responseText><settlementDate/><txnID/><authID/><CreditCardInfo><pan>444433...111</pan><expiryDate>05/17</expiryDate><cardType>6</cardType><cardDescription>Visa</cardDescription></CreditCardInfo></Txn></TxnList></Payment></NABTransactMessage>"
read 920 bytes
Conn close
PRE_SCRUBBED
end
def post_scrubbed
<<-'POST_SCRUBBED'
opening connection to transact.nab.com.au:443...
opened
starting SSL for transact.nab.com.au:443...
SSL established
<- "POST /test/xmlapi/payment HTTP/1.1\r\nContent-Type: application/x-www-form-urlencoded\r\nAccept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3\r\nAccept: */*\r\nUser-Agent: Ruby\r\nConnection: close\r\nHost: transact.nab.com.au\r\nContent-Length: 715\r\n\r\n"
<- "<?xml version=\"1.0\" encoding=\"UTF-8\"?><NABTransactMessage><MessageInfo><messageID>6673348a21d79657983ab247b2483e</messageID><messageTimestamp>20151212075932886818+000</messageTimestamp><timeoutValue>60</timeoutValue><apiVersion>xml-4.2</apiVersion></MessageInfo><MerchantInfo><merchantID>XYZ0010</merchantID><password>[FILTERED]</password></MerchantInfo><RequestType>Payment</RequestType><Payment><TxnList count=\"1\"><Txn ID=\"1\"><txnType>0</txnType><txnSource>23</txnSource><amount>200</amount><currency>AUD</currency><purchaseOrderNo></purchaseOrderNo><CreditCardInfo><cardNumber>[FILTERED]</cardNumber><expiryDate>05/17</expiryDate><cvv>[FILTERED]</cvv></CreditCardInfo></Txn></TxnList></Payment></NABTransactMessage>"
-> "HTTP/1.1 200 OK\r\n"
-> "Date: Sat, 12 Dec 2015 07:59:34 GMT\r\n"
-> "Server: Apache-Coyote/1.1\r\n"
-> "Content-Type: text/xml;charset=ISO-8859-1\r\n"
-> "Content-Length: 920\r\n"
-> "Connection: close\r\n"
-> "\r\n"
reading 920 bytes...
-> ""
-> "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><NABTransactMessage><MessageInfo><messageID>6673348a21d79657983ab247b2483e</messageID><messageTimestamp>20151212185934964000+660</messageTimestamp><apiVersion>xml-4.2</apiVersion></MessageInfo><RequestType>Payment</RequestType><MerchantInfo><merchantID>XYZ0010</merchantID></MerchantInfo><Status><statusCode>000</statusCode><statusDescription>Normal</statusDescription></Status><Payment><TxnList count=\"1\"><Txn ID=\"1\"><txnType>0</txnType><txnSource>23</txnSource><amount>200</amount><currency>AUD</currency><purchaseOrderNo/><approved>No</approved><responseCode>103</responseCode><responseText>Invalid Purchase Order Number</responseText><settlementDate/><txnID/><authID/><CreditCardInfo><pan>444433...111</pan><expiryDate>05/17</expiryDate><cardType>6</cardType><cardDescription>Visa</cardDescription></CreditCardInfo></Txn></TxnList></Payment></NABTransactMessage>"
read 920 bytes
Conn close
POST_SCRUBBED
end
def check_transaction_type(type)
Proc.new do |endpoint, data, headers|
request_hash = Hash.from_xml(data)
request_hash['NABTransactMessage']['Payment']['TxnList']['Txn']['txnType'] == NabTransactGateway::TRANSACTIONS[type].to_s
end
end
def valid_metadata(name, location)
return <<-XML.gsub(/^\s{4}/, '').gsub(/\n/, '')
<metadata><meta name="ca_name" value="#{name}"/><meta name="ca_location" value="#{location}"/></metadata>
XML
end
def assert_metadata(name, location, &block)
stub_comms(@gateway, :ssl_request) do
yield
end.check_request do |method, endpoint, data, headers|
metadata_matcher = Regexp.escape(valid_metadata(name, location))
assert_match %r{#{metadata_matcher}}, data
end.respond_with(successful_purchase_response)
end
def failed_login_response
'<NABTransactMessage><Status><statusCode>504</statusCode><statusDescription>Invalid merchant ID</statusDescription></Status></NABTransactMessage>'
end
def successful_purchase_response
<<-XML.gsub(/^\s{4}/, '')
<?xml version="1.0" encoding="UTF-8"?>
<NABTransactMessage>
<MessageInfo>
<messageID>8af793f9af34bea0cf40f5fb750f64</messageID>
<messageTimestamp>20042303111226938000+660</messageTimestamp>
<apiVersion>xml-4.2</apiVersion>
</MessageInfo>
<MerchantInfo>
<merchantID>ABC0001</merchantID>
</MerchantInfo>
<RequestType>Payment</RequestType>
<Status>
<statusCode>000</statusCode>
<statusDescription>Normal</statusDescription>
</Status>
<Payment>
<TxnList count="1">
<Txn ID="1">
<txnType>0</txnType>
<txnSource>23</txnSource>
<amount>200</amount>
<currency>AUD</currency>
<purchaseOrderNo>test</purchaseOrderNo>
<approved>Yes</approved>
<responseCode>00</responseCode>
<responseText>Approved</responseText>
<settlementDate>20040323</settlementDate>
<txnID>009887</txnID>
<CreditCardInfo>
<pan>444433...111</pan>
<expiryDate>08/12</expiryDate>
<cardType>6</cardType>
<cardDescription>Visa</cardDescription>
</CreditCardInfo>
</Txn>
</TxnList>
</Payment>
</NABTransactMessage>
XML
end
def failed_purchase_response
<<-XML.gsub(/^\s{4}/, '')
<?xml version="1.0" encoding="UTF-8"?>
<NABTransactMessage>
<MessageInfo>
<messageID>8af793f9af34bea0cf40f5fb5c630c</messageID>
<messageTimestamp>20042303111226938000+660</messageTimestamp>
<apiVersion>xml-4.2</apiVersion>
</MessageInfo>
<MerchantInfo>
<merchantID>ABC0001</merchantID>
</MerchantInfo>
<RequestType>Payment</RequestType>
<Status>
<statusCode>000</statusCode>
<statusDescription>Normal</statusDescription>
</Status>
<Payment>
<TxnList count="1">
<Txn ID="1">
<txnType>0</txnType>
<txnSource>23</txnSource>
<amount>200</amount>
<currency>AUD</currency>
<purchaseOrderNo>test</purchaseOrderNo>
<approved>No</approved>
<responseCode>54</responseCode>
<responseText>Expired Card</responseText>
<settlementDate>20040323</settlementDate>
<txnID>000000</txnID>
<CreditCardInfo>
<pan>444433...111</pan>
<expiryDate>08/12</expiryDate>
<cardType>6</cardType>
<cardDescription>Visa</cardDescription>
</CreditCardInfo>
</Txn>
</TxnList>
</Payment>
</NABTransactMessage>
XML
end
def successful_authorize_response
<<-XML.gsub(/^\s{4}/, '')
<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>
<NABTransactMessage>
<MessageInfo>
<messageID>4650de0ab4db398640b672a85e59ac</messageID>
<messageTimestamp>20131207164203929000+600</messageTimestamp>
<apiVersion>xml-4.2</apiVersion>
</MessageInfo>
<RequestType>Payment</RequestType>
<MerchantInfo>
<merchantID>XYZ0010</merchantID>
</MerchantInfo>
<Status>
<statusCode>000</statusCode>
<statusDescription>Normal</statusDescription>
</Status>
<Payment>
<TxnList count=\"1\">
<Txn ID=\"1\">
<txnType>10</txnType>
<txnSource>23</txnSource>
<amount>200</amount>
<currency>AUD</currency>
<purchaseOrderNo>test</purchaseOrderNo>
<approved>Yes</approved>
<responseCode>00</responseCode>
<responseText>Approved</responseText>
<settlementDate>20130712</settlementDate>
<txnID>009887</txnID>
<preauthID>009887</preauthID>
<authID/>
<CreditCardInfo>
<pan>444433...111</pan>
<expiryDate>09/14</expiryDate>
<cardType>6</cardType>
<cardDescription>Visa</cardDescription>
</CreditCardInfo>
</Txn>
</TxnList>
</Payment>
</NABTransactMessage>
XML
end
def successful_refund_response
<<-XML.gsub(/^\s{4}/, '')
<?xml version="1.0" encoding="UTF-8"?>
<NABTransactMessage>
<MessageInfo>
<messageID>feaedbe87239a005729aece8efa48b</messageID>
<messageTimestamp>20102807071306650000+600</messageTimestamp>
<apiVersion>xml-4.2</apiVersion>
</MessageInfo>
<RequestType>Payment</RequestType>
<MerchantInfo>
<merchantID>ABC0001</merchantID>
</MerchantInfo>
<Status>
<statusCode>000</statusCode>
<statusDescription>Normal</statusDescription>
</Status>
<Payment>
<TxnList count="1">
<Txn ID="1">
<txnType>4</txnType>
<txnSource>23</txnSource>
<amount>100</amount>
<currency>AUD</currency>
<purchaseOrderNo>269065</purchaseOrderNo>
<approved>Yes</approved>
<responseCode>00</responseCode>
<responseText>Approved</responseText>
<settlementDate>20100728</settlementDate>
<txnID>269067</txnID>
<CreditCardInfo>
<pan>444433...111</pan>
<expiryDate>08/12</expiryDate>
<cardType>6</cardType>
<cardDescription>Visa</cardDescription>
</CreditCardInfo>
</Txn>
</TxnList>
</Payment>
</NABTransactMessage>
XML
end
def failed_refund_response
<<-XML.gsub(/^\s{4}/, '')
<?xml version="1.0" encoding="UTF-8"?>
<NABTransactMessage>
<MessageInfo>
<messageID>6bacab2b7ae1200d8099e0873e25bc</messageID>
<messageTimestamp>20102807071248484000+600</messageTimestamp>
<apiVersion>xml-4.2</apiVersion>
</MessageInfo>
<RequestType>Payment</RequestType>
<MerchantInfo>
<merchantID>ABC0001</merchantID>
</MerchantInfo>
<Status>
<statusCode>000</statusCode>
<statusDescription>Normal</statusDescription>
</Status>
<Payment>
<TxnList count="1">
<Txn ID="1">
<txnType>4</txnType>
<txnSource>23</txnSource>
<amount>101</amount>
<currency>AUD</currency>
<purchaseOrderNo>269061</purchaseOrderNo>
<approved>No</approved>
<responseCode>134</responseCode>
<responseText>Only $1.00 available for refund</responseText>
<settlementDate />
<txnID />
<CreditCardInfo>
<pan>444433...111</pan>
<expiryDate>08/12</expiryDate>
<cardType>6</cardType>
<cardDescription>Visa</cardDescription>
</CreditCardInfo>
</Txn>
</TxnList>
</Payment>
</NABTransactMessage>
XML
end
end
| 40.417391 | 935 | 0.680239 |
38eb4a7b60e44f28fd73dc4fd2d59901c27bf41f
| 665 |
cask 'visual-paradigm-ce' do
version '16.1,20191237'
sha256 '61c54caded5c43b3237c71a5b8ceb14fa2cd6a0525266af9af92946f69d6c0be'
url "https://www.visual-paradigm.com/downloads/vpce/Visual_Paradigm_CE_#{version.before_comma.dots_to_underscores}_#{version.after_comma}_OSX_WithJRE.dmg"
appcast 'https://www.visual-paradigm.com/downloads/vpce/checksum.html',
configuration: "#{version.before_comma.dots_to_underscores}_#{version.after_comma}"
name 'Visual Paradigm Community Edition'
homepage 'https://www.visual-paradigm.com/'
# Renamed to avoid conflict with visual-paradigm.
app 'Visual Paradigm.app', target: 'Visual Paradigm CE.app'
end
| 47.5 | 156 | 0.78797 |
f7648eda45b870146a92359d0f29171cb7bc818c
| 1,575 |
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
end
test "login with valid email/invalid password" do
get login_path
assert_template 'sessions/new'
post login_path, params: { session: { email: @user.email,
password: "invalid"}}
assert_not is_logged_in?
assert_template 'sessions/new'
assert_not flash.empty?
get root_path
assert flash.empty?
end
test "login with valid infomation followed by logout" do
get login_path
post login_path, params: { session: { email: @user.email,
password: 'password'} }
assert is_logged_in?
assert_redirected_to @user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count:0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(@user)
delete logout_path
assert_not is_logged_in?
assert_redirected_to root_url
delete logout_path
follow_redirect!
assert_select "a[href=?]", login_path
assert_select "a[href=?]", logout_path, count:0
assert_select "a[href=?]", user_path(@user), count:0
end
test "login with remembering" do
log_in_as(@user, remember_me: '1')
assert_not_empty cookies[:remember_token]
end
test "login without remembering" do
# cookieを保存してログイン
log_in_as(@user,remember_me: '1')
delete logout_path
# cookieを削除してログイン
log_in_as(@user,remember_me: '0')
assert_empty cookies[:remember_token]
end
end
| 28.125 | 61 | 0.683175 |
01da68a956da115c92476ccaba758ee1d76679b6
| 922 |
module RedmineGitHosting
module Patches
module UserPatch
def self.included(base)
base.send(:include, InstanceMethods)
base.class_eval do
unloadable
has_many :gitolite_public_keys, :dependent => :destroy
before_destroy :delete_ssh_keys, prepend: true
end
end
module InstanceMethods
def gitolite_identifier
"#{RedmineGitolite::ConfigRedmine.get_setting(:gitolite_identifier_prefix)}#{self.login.underscore}".gsub(/[^0-9a-zA-Z\-]/, '_')
end
private
def delete_ssh_keys
RedmineGitolite::GitHosting.logger.info { "User '#{self.login}' has been deleted from Redmine delete membership and SSH keys !" }
end
end
end
end
end
unless User.included_modules.include?(RedmineGitHosting::Patches::UserPatch)
User.send(:include, RedmineGitHosting::Patches::UserPatch)
end
| 22.487805 | 139 | 0.664859 |
7ac563875ed52555937999b392359da8a2ee1275
| 615 |
describe 'start page' do
it 'shows start page in German' do
visit '/de'
expect(page).to have_content('Einloggen')
expect(page).to have_content('Als Speakerin registrieren')
expect(page).to have_content('Alle Speakerinnen* anschauen')
expect(page).to have_content('Twitter')
expect(page).to have_content('Impressum')
end
it 'shows start page in English' do
visit root_path
expect(page).to have_content('Log in')
expect(page).to have_content('Register as a speaker')
expect(page).to have_content('Twitter')
expect(page).to have_content('Legal Details')
end
end
| 27.954545 | 64 | 0.705691 |
d5f8884dcef95c1207b3d946848ad5f6210177e7
| 1,191 |
require "application_system_test_case"
class TutorialsTest < ApplicationSystemTestCase
setup do
@tutorial = tutorials(:one)
end
test "visiting the index" do
visit tutorials_url
assert_selector "h1", text: "Tutorials"
end
test "creating a Tutorial" do
visit tutorials_url
click_on "New Tutorial"
check "Ongoing" if @tutorial.ongoing
fill_in "Pipeline", with: @tutorial.pipeline
fill_in "Step", with: @tutorial.step
fill_in "User", with: @tutorial.user_id
click_on "Create Tutorial"
assert_text "Tutorial was successfully created"
click_on "Back"
end
test "updating a Tutorial" do
visit tutorials_url
click_on "Edit", match: :first
check "Ongoing" if @tutorial.ongoing
fill_in "Pipeline", with: @tutorial.pipeline
fill_in "Step", with: @tutorial.step
fill_in "User", with: @tutorial.user_id
click_on "Update Tutorial"
assert_text "Tutorial was successfully updated"
click_on "Back"
end
test "destroying a Tutorial" do
visit tutorials_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Tutorial was successfully destroyed"
end
end
| 23.82 | 53 | 0.706969 |
e973a2beb37f2ec8969fe928e4f604d0cb083a30
| 734 |
# snippet from https://medium.com/@darrenrush/save-414-on-your-heroku-bill-this-year-5680251ab972#.gx3ggczcm
# hopefully allows delayed job to work in single web dyno FREEE
if !Rails.const_defined?('Console') && !($0 =~ /rake$/) && !Rails.env.test?
Rails.application.config.after_initialize do
# (1..2).each do |thread_id|
Thread.new {
Thread.current[:thread_name] = "DJ Web Worker Thread 1"
ActiveRecord::Base.connection_pool.with_connection do |conn|
dj = Delayed::Worker.new
Rails.logger.warn "Starting #{Thread.current[:thread_name]}"
at_exit { Rails.logger.warn "Stopping background thread"; dj.stop }
dj.start
end
}
# end
end
end
| 40.777778 | 108 | 0.651226 |
e997daf09e043ddad79fab23fa98d34ad83de76f
| 372 |
# frozen_string_literal: true
[
'base',
'configuration',
'application',
'server',
'page',
'result',
'ci_runner',
File.join('formatters', 'exit_code'),
File.join('formatters', 'console'),
File.join('formatters', 'multi'),
File.join('runners', 'chrome_headless'),
'railtie'
].each do |file|
require File.join('jasmine-rails-webpacker', file)
end
| 18.6 | 52 | 0.653226 |
d516f7dcfc9543e4389088664a54c9057ade21bb
| 251 |
require 'rubygems'
require 'weary'
class PatClient < Weary::Client
domain "http://www.uk-postcodes.com"
get :get, "/postcode/{code}.json"
end
class Pat
def self.get(code)
PatClient.new.get(:code => code.gsub(' ', '')).perform
end
end
| 16.733333 | 58 | 0.661355 |
08f4264ee1b531aa58fb0a23095f257f231b8b1d
| 204 |
require_dependency 'support/application_record'
module Support
module Entity
class MemberJob < ApplicationRecord
self.table_name = 'sihab.entity_member_jobs'
audited
end
end
end
| 17 | 50 | 0.745098 |
ac0f154713e2745883f4182f68e4dad5814fd67e
| 1,443 |
module MembershipActions
extend ActiveSupport::Concern
def request_access
membershipable.request_access(current_user)
redirect_to polymorphic_path(membershipable),
notice: 'Your request for access has been queued for review.'
end
def request_access_with_secret
begin
membershipable.request_access_with_secret(current_user,params[:secret])
redirect_to polymorphic_path(membershipable),
notice: 'Success. You have joined the group.'
end
rescue
redirect_to polymorphic_path(membershipable),
alert: 'Incorrect secret.'
end
def approve_access_request
Members::ApproveAccessRequestService.new(membershipable, current_user, params).execute
redirect_to polymorphic_url([membershipable, :members])
end
def leave
member = Members::DestroyService.new(membershipable, current_user, user_id: current_user.id).
execute(:all)
source_type = membershipable.class.to_s.humanize(capitalize: false)
notice =
if member.request?
"Your access request to the #{source_type} has been withdrawn."
else
"You left the \"#{membershipable.human_name}\" #{source_type}."
end
redirect_path = member.request? ? member.source : [:dashboard, membershipable.class.to_s.tableize]
redirect_to redirect_path, notice: notice
end
protected
def membershipable
raise NotImplementedError
end
end
| 28.294118 | 102 | 0.722107 |
e92cddd1c2d58b0cc9683fa542d6410b01054836
| 312 |
module Spree
module RecentlyViewedProductsHelper
def cached_recently_viewed_products_ids
(cookies['recently_viewed_products'] || '').split(', ')
end
def cached_recently_viewed_products
Spree::Product.find_by_array_of_ids(cached_recently_viewed_products_ids).first(4)
end
end
end
| 26 | 87 | 0.762821 |
08ab371d5991ea65f71f8237b4f73e60a81716df
| 5,174 |
#! /usr/bin/env ruby
# frozen_string_literal: true
#
# check-smart-tests.rb
#
# DESCRIPTION:
# This script checks S.M.A.R.T. self-tests status and optionally time of last
# test run
#
# OUTPUT:
# plain text
#
# PLATFORMS:
# Linux
#
# DEPENDENCIES:
# gem: sensu-plugin
#
# USAGE:
# check-smart-tests.rb # Use default options
# check-smart-tests.rb -d /dev/sda,/dev/sdb -l 24 -t 336 # Check smart tests status for
# /dev/sda and /dev/sdb devices, also check if short tests were run in last 24 hours and
# extended tests were run in last 14 days(336 hours)
#
# NOTES:
# The plugin requires smartmontools to be installed and smartctl utility in particular.
#
# smartctl requires root rights to run, so you should allow sensu to execute
# this command as root without password by adding following line to /etc/sudoers:
#
# sensu ALL=(ALL) NOPASSWD: /usr/sbin/smartctl
#
# Tested only on Debian.
#
# LICENSE:
# Stanislav Sandalnikov <[email protected]>
# Released under the same terms as Sensu (the MIT license); see LICENSE
# for details.
require 'sensu-plugin/check/cli'
class Device
attr_accessor :name, :pwh, :str
def initialize(name, smartctl_executable)
@name = name
@exec = smartctl_executable
@pwh = poweron_hours
@str = selftest_results
end
def poweron_hours
`sudo #{@exec} -A #{@name}`.split("\n").each do |line|
columns = line.split
if columns[1] == 'Power_On_Hours'
return columns[9]
end
end
end
def selftest_results
results = []
headers = %w[num test_description status remaining lifetime lba_of_first_error]
`sudo #{@exec} -l selftest #{@name}`.split("\n").grep(/^#/).each do |test|
test = test.gsub!(/\s\s+/m, "\t").split("\t")
res = {}
headers.each_with_index do |v, k|
res[v] = test[k]
end
results << res
end
results
end
end
class CheckSMARTTests < Sensu::Plugin::Check::CLI
option :executable,
long: '--executable EXECUTABLE',
short: '-e EXECUTABLE',
default: '/usr/sbin/smartctl',
description: 'Path to smartctl executable'
option :devices,
long: '--devices *DEVICES',
short: '-d *DEVICES',
default: 'all',
description: 'Comma-separated list of devices to check, i.e. "/dev/sda,/dev/sdb"'
option :short_test_interval,
long: '--short_test_interval INTERVAL',
short: '-s INTERVAL',
description: 'If more time then this value passed since last short test run, then warning will be raised'
option :long_test_interval,
long: '--long_test_interval INTERVAL',
short: '-l INTERVAL',
description: 'If more time then this value passed since last extedned test run, then warning will be raised'
def initialize
super
@devices = []
@warnings = []
@criticals = []
set_devices
end
def set_devices
if config[:devices] == 'all'
`lsblk -plnd -o NAME`.split.each do |name|
unless name =~ /\/dev\/loop.*/
dev = Device.new(name, config[:executable])
@devices.push(dev)
end
end
else
config[:devices].split(',').each do |name|
dev = Device.new(name, config[:executable])
@devices.push(dev)
end
end
end
def check_tests(dev)
if dev.str.empty?
@warnings << "#{dev.name}: No self-tests have been logged."
return
end
unless dev.str[0]['status'] == 'Completed without error' || dev.str[0]['status'] =~ /Self-test routine in progress/
@criticals << "#{dev.name}: Last test failed - #{dev.str[0]['status']}"
end
unless config[:short_test_interval].nil?
dev.str.each_with_index do |t, i|
if t['test_description'] != 'Short offline'
if i == dev.str.length - 1
@warnings << "#{dev.name}: No short tests were run for this device in last #{dev.str.length} executions"
end
next
else
if dev.pwh.to_i - t['lifetime'].to_i > config[:short_test_interval].to_i
@warnings << "#{dev.name}: More than #{config[:short_test_interval]} hours passed since the last short test"
end
break
end
end
end
# TODO: refactor me
unless config[:long_test_interval].nil? # rubocop:disable Style/GuardClause
dev.str.each_with_index do |t, i|
if t['test_description'] != 'Extended offline'
if i == dev.str.length - 1
@warnings << "#{dev.name}: No extended tests were run for this device in last #{dev.str.length} executions"
end
next
else
if dev.pwh.to_i - t['lifetime'].to_i > config[:long_test_interval].to_i
@warnings << "#{dev.name}: More than #{config[:long_test_interval]} hours passed since the last extended test"
end
break
end
end
end
end
def run
@devices.each do |device|
check_tests(device)
end
if @criticals.any?
critical @criticals.join(' ')
elsif @warnings.any?
warning @warnings.join(' ')
else
ok 'All devices are OK'
end
end
end
| 28.273224 | 122 | 0.616931 |
e9621a98d7096b18a1fb7e15b9e3be0d2ce4bf80
| 1,268 |
#
# Licensed Materials - Property of IBM
#
# (c) Copyright IBM Corp. 2007,2008,2009
#
class TestIbmDb < Test::Unit::TestCase
def test_261_FetchObject
assert_expect do
conn = IBM_DB.connect("DATABASE=#{database};HOSTNAME=#{hostname};PORT=#{port};UID=#{user};PWD=#{password}",'','')
server = IBM_DB::server_info( conn )
if (server.DBMS_NAME[0,3] == 'IDS')
op = {IBM_DB::ATTR_CASE => IBM_DB::CASE_UPPER}
IBM_DB::set_option conn, op, 0
end
if (server.DBMS_NAME[0,3] == 'IDS')
sql = "SELECT breed, TRIM(TRAILING FROM name) AS name FROM animals WHERE id = ?"
else
sql = "SELECT breed, RTRIM(name) AS name FROM animals WHERE id = ?"
end
if conn
stmt = IBM_DB::prepare conn, sql
IBM_DB::execute stmt, [0]
while (pet = IBM_DB::fetch_object(stmt))
print "Come here, #{pet.NAME}, my little #{pet.BREED}!"
end
IBM_DB::close conn
else
puts "Connection failed."
end
end
end
end
__END__
__LUW_EXPECTED__
Come here, Pook, my little cat!
__ZOS_EXPECTED__
Come here, Pook, my little cat!
__SYSTEMI_EXPECTED__
Come here, Pook, my little cat!
__IDS_EXPECTED__
Come here, Pook, my little cat!
| 24.862745 | 119 | 0.614353 |
9191a8c504b2c43b36a493aaff6c55f1d2feef22
| 8,054 |
require 'test_helper'
class ScriptsControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers
setup do
@admin = create(:admin)
@not_admin = create(:user)
@levelbuilder = create(:levelbuilder)
Rails.application.config.stubs(:levelbuilder_mode).returns false
end
test "should get index" do
Rails.application.config.stubs(:levelbuilder_mode).returns true
sign_in(@levelbuilder)
get :index
assert_response :success
assert_not_nil assigns(:scripts)
assert_equal Script.all, assigns(:scripts)
end
test "should redirect when script has a redirect_to property" do
script = create :script
new_script = create :script
script.update(redirect_to: new_script.name)
get :show, params: {id: script.name}
assert_redirected_to "/s/#{new_script.name}"
end
test "should not get index if not signed in" do
get :index
assert_redirected_to_sign_in
end
test "should not get index if not levelbuilder" do
[@admin, @not_admin].each do |user|
sign_in user
get :index
assert_response :forbidden
end
end
test "should get show of hoc" do
get :show, params: {id: Script::HOC_NAME}
assert_response :success
end
test "should get show of k-8" do
get :show, params: {id: Script::TWENTY_HOUR_NAME}
assert_response :success
end
test "should get show of custom script" do
get :show, params: {id: 'course1'}
assert_response :success
end
test "should get show of ECSPD if signed in" do
sign_in @not_admin
get :show, params: {id: 'ECSPD'}
assert_response :success
end
test "should not get show of ECSPD if not signed in" do
get :show, params: {id: 'ECSPD'}
assert_redirected_to_sign_in
end
test "should not show link to Overview of Courses 1, 2, and 3 if logged in as a student" do
sign_in create(:student)
get :show, params: {id: 'course1'}
assert_response :success
assert_select 'a', text: 'Overview of Courses 1, 2, and 3', count: 0
end
test "should not show link to Overview of Courses 1, 2, and 3 if not logged in" do
get :show, params: {id: 'course1'}
assert_response :success
assert_select 'a', text: 'Overview of Courses 1, 2, and 3', count: 0
end
test "should show link to Overview of Courses 1, 2, and 3 if logged in as a teacher" do
sign_in create(:teacher)
get :show, params: {id: 'course1'}
assert_response :success
assert_select 'a', text: 'Overview of Courses 1, 2, and 3'
end
test "should redirect to /s/course1" do
get :show, params: {id: Script.find_by_name("course1").id}
assert_redirected_to "/s/course1"
end
test "show of hourofcode redirects to hoc" do
get :show, params: {id: 'hourofcode'}
assert_response :success
end
test "show of hourofcode by id should redirect to hoc" do
get :show, params: {id: Script.find_by_name('hourofcode').id}
assert_redirected_to '/s/hourofcode'
end
test "should get show if not signed in" do
get :show, params: {id: Script::FLAPPY_NAME}
assert_response :success
end
test "should get show if not admin" do
sign_in @not_admin
get :show, params: {id: Script::FLAPPY_NAME}
assert_response :success
end
test 'should not get show if admin' do
sign_in @admin
get :show, params: {id: Script::FLAPPY_NAME}
assert_response :forbidden
end
test "should use script name as param where script name is words but looks like a number" do
script = create(:script, name: '15-16')
get :show, params: {id: "15-16"}
assert_response :success
assert_equal script, assigns(:script)
end
test "should use script name as param where script name is words" do
script = create(:script, name: 'Heure de Code', skip_name_format_validation: true)
get :show, params: {id: "Heure de Code"}
assert_response :success
assert_equal script, assigns(:script)
end
test "renders 404 when id is an invalid id" do
assert_raises ActiveRecord::RecordNotFound do
get :show, params: {id: 232323}
end
end
test "renders 404 when id is an invalid string" do
assert_raises ActiveRecord::RecordNotFound do
get :show, params: {id: 'Hat'}
end
end
test "should not get edit if not levelbuilder mode" do
Rails.application.config.stubs(:levelbuilder_mode).returns false
sign_in @levelbuilder
get :edit, params: {id: 'course1'}
assert_response :forbidden
end
test "should not get edit if not signed in" do
Rails.application.config.stubs(:levelbuilder_mode).returns true
get :edit, params: {id: 'course1'}
assert_redirected_to_sign_in
end
test "should not get edit if not levelbuilder" do
Rails.application.config.stubs(:levelbuilder_mode).returns true
[@not_admin, @admin].each do |user|
sign_in user
get :edit, params: {id: 'course1'}
assert_response :forbidden
end
end
test "edit" do
Rails.application.config.stubs(:levelbuilder_mode).returns true
sign_in @levelbuilder
script = Script.find_by_name('course1')
get :edit, params: {id: script.name}
assert_equal script, assigns(:script)
end
# These two tests are the only remaining dependency on script seed order. Check that /s/1 redirects to /s/20-hour in
# production. On a fresh db the only guarantee that '20-hour.script' has id:1 is by manually specifying ID in the DSL.
test "should redirect old k-8" do
get :show, params: {id: 1}
assert_redirected_to script_path(Script.twenty_hour_script)
end
test "show should redirect to flappy" do
get :show, params: {id: 6}
assert_redirected_to "/s/flappy"
end
test "edit forbidden if not on levelbuilder" do
sign_in @levelbuilder
get :edit, params: {id: 'course1'}
assert_response :forbidden
end
test 'create' do
expected_contents = <<-TEXT.strip_heredoc
hidden false
login_required true
hideable_stages true
wrapup_video 'hoc_wrapup'
TEXT
File.stubs(:write).with {|filename, _| filename.end_with? 'scripts.en.yml'}.once
File.stubs(:write).with('config/scripts/test-script-create.script', expected_contents).once
Rails.application.config.stubs(:levelbuilder_mode).returns true
sign_in @levelbuilder
post :create, params: {
script: {name: 'test-script-create'},
script_text: '',
visible_to_teachers: true,
login_required: true,
hideable_stages: true,
wrapup_video: 'hoc_wrapup'
}
assert_redirected_to script_path id: 'test-script-create'
script = Script.find_by_name('test-script-create')
assert_equal 'test-script-create', script.name
refute script.hidden
assert script.login_required
assert script.hideable_stages
File.unstub(:write)
end
test 'destroy raises exception for evil filenames' do
Rails.application.config.stubs(:levelbuilder_mode).returns true
sign_in @levelbuilder
# Note that these script names (intentionally) fail model validation.
[
'~/evil_script_name',
'../evil_script_name',
'subdir/../../../evil_script_name'
].each do |name|
evil_script = Script.new(name: name)
evil_script.save(validate: false)
assert_raise ArgumentError do
delete :destroy, params: {id: evil_script.id}
end
end
end
test 'updates teacher resources' do
sign_in @levelbuilder
Rails.application.config.stubs(:levelbuilder_mode).returns true
script = create :script
File.stubs(:write).with {|filename, _| filename == "config/scripts/#{script.name}.script" || filename.end_with?('scripts.en.yml')}
post :update, params: {
id: script.id,
script: {name: script.name},
script_text: '',
resourceTypes: ['curriculum', 'vocabulary', ''],
resourceLinks: ['/link/to/curriculum', '/link/to/vocab', '']
}
assert_equal [['curriculum', '/link/to/curriculum'], ['vocabulary', '/link/to/vocab']], Script.find_by_name(script.name).teacher_resources
end
end
| 29.075812 | 142 | 0.689719 |
1c8c52c8a8470de3044e60d0900b1aefbec9556c
| 64 |
Rails.application.config.generators.scaffold_stylesheet = false
| 32 | 63 | 0.875 |
d56b52d02de31b5c5d2c8f2988414c57583e5aa7
| 138 |
module EE
SUBSCRIPTIONS_URL = 'https://customers.gitlab.com'.freeze
SUBSCRIPTIONS_PLANS_URL = "#{SUBSCRIPTIONS_URL}/plans".freeze
end
| 27.6 | 63 | 0.782609 |
61efb07bdab02e563e2690ad8c8208626e5aa1b1
| 8,396 |
require 'rails_helper'
require 'cancan'
require 'cancan/matchers'
require 'spree/testing_support/ability_helpers'
require 'spree/testing_support/bar_ability'
# Fake ability for testing registration of additional abilities
class FooAbility
include CanCan::Ability
def initialize(_user)
# allow anyone to perform index on Order
can :index, Spree::Order
# allow anyone to update an Order with id of 1
can :update, Spree::Order do |order|
order.id == 1
end
end
end
RSpec.describe Spree::Ability, type: :model do
let(:user) { build(:user) }
let(:ability) { Spree::Ability.new(user) }
let(:token) { nil }
after(:each) {
Spree::Ability.abilities = Set.new
}
describe "#initialize" do
subject { Spree::Ability.new(user) }
it "activates permissions from the role configuration" do
expect(Spree::Config.roles).to receive(:activate_permissions!).
once
subject
end
end
context 'register_ability' do
it 'should add the ability to the list of abilties' do
Spree::Ability.register_ability(FooAbility)
expect(Spree::Ability.new(user).abilities).not_to be_empty
end
it 'should apply the registered abilities permissions' do
Spree::Ability.register_ability(FooAbility)
expect(Spree::Ability.new(user).can?(:update, mock_model(Spree::Order, user: nil, id: 1))).to be true
end
end
context 'for general resource' do
let(:resource) { Object.new }
context 'with admin user' do
let(:user) { build :admin_user }
it_should_behave_like 'access granted'
it_should_behave_like 'index allowed'
end
context 'with customer' do
it_should_behave_like 'access denied'
it_should_behave_like 'no index allowed'
end
end
context 'for admin protected resources' do
let(:resource) { Object.new }
let(:resource_shipment) { Spree::Shipment.new }
let(:resource_product) { Spree::Product.new }
let(:resource_user) { create :user }
let(:resource_order) { Spree::Order.new }
let(:fakedispatch_user) { Spree.user_class.create }
let(:fakedispatch_ability) { Spree::Ability.new(fakedispatch_user) }
context 'with admin user' do
it 'should be able to admin' do
user.spree_roles << Spree::Role.find_or_create_by(name: 'admin')
expect(ability).to be_able_to :admin, resource
expect(ability).to be_able_to :index, resource_order
expect(ability).to be_able_to :show, resource_product
expect(ability).to be_able_to :create, resource_user
end
end
context 'with fakedispatch user' do
it 'should be able to admin on the order and shipment pages' do
user.spree_roles << Spree::Role.find_or_create_by(name: 'bar')
Spree::Ability.register_ability(BarAbility)
expect(ability).not_to be_able_to :admin, resource
expect(ability).to be_able_to :admin, resource_order
expect(ability).to be_able_to :index, resource_order
expect(ability).not_to be_able_to :update, resource_order
# ability.should_not be_able_to :create, resource_order # Fails
expect(ability).to be_able_to :admin, resource_shipment
expect(ability).to be_able_to :index, resource_shipment
expect(ability).to be_able_to :create, resource_shipment
expect(ability).not_to be_able_to :admin, resource_product
expect(ability).not_to be_able_to :update, resource_product
# ability.should_not be_able_to :show, resource_product # Fails
expect(ability).not_to be_able_to :admin, resource_user
expect(ability).not_to be_able_to :update, resource_user
expect(ability).to be_able_to :update, user
# ability.should_not be_able_to :create, resource_user # Fails
# It can create new users if is has access to the :admin, User!!
# TODO: change the Ability class so only users and customers get the extra premissions?
Spree::Ability.remove_ability(BarAbility)
end
end
context 'with customer' do
it 'should not be able to admin' do
expect(ability).not_to be_able_to :admin, resource
expect(ability).not_to be_able_to :admin, resource_order
expect(ability).not_to be_able_to :admin, resource_product
expect(ability).not_to be_able_to :admin, resource_user
end
end
end
context 'as Guest User' do
context 'for Country' do
let(:resource) { Spree::Country.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for OptionType' do
let(:resource) { Spree::OptionType.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for OptionValue' do
let(:resource) { Spree::OptionType.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for Order' do
let(:resource) { Spree::Order.new }
context 'requested by same user' do
before(:each) { resource.user = user }
it_should_behave_like 'access granted'
it_should_behave_like 'no index allowed'
end
context 'requested by other user' do
before(:each) { resource.user = Spree.user_class.new }
it_should_behave_like 'create only'
end
context 'requested with proper token' do
let(:token) { 'TOKEN123' }
before(:each) { allow(resource).to receive_messages guest_token: 'TOKEN123' }
it_should_behave_like 'access granted'
it_should_behave_like 'no index allowed'
end
context 'requested with inproper token' do
let(:token) { 'FAIL' }
before(:each) { allow(resource).to receive_messages guest_token: 'TOKEN123' }
it_should_behave_like 'create only'
end
end
context 'for Product' do
let(:resource) { Spree::Product.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for ProductProperty' do
let(:resource) { Spree::Product.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for Property' do
let(:resource) { Spree::Product.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for State' do
let(:resource) { Spree::State.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for Stock Item' do
let(:resource) { Spree::StockItem.new }
context 'active stock location' do
before { resource.build_stock_location(active: true) }
it_should_behave_like 'read only'
end
context 'inactive stock location' do
before { resource.build_stock_location(active: false) }
it_should_behave_like 'access denied'
end
end
context 'for Stock Location' do
let(:resource) { Spree::StockLocation.new }
context 'active' do
before { resource.active = true }
it_should_behave_like 'read only'
end
context 'inactive' do
before { resource.active = false }
it_should_behave_like 'access denied'
end
end
context 'for Taxons' do
let(:resource) { Spree::Taxon.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for Taxonomy' do
let(:resource) { Spree::Taxonomy.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for User' do
context 'requested by same user' do
let(:resource) { user }
it_should_behave_like 'access granted'
it_should_behave_like 'no index allowed'
end
context 'requested by other user' do
let(:resource) { Spree.user_class.create }
it_should_behave_like 'create only'
end
end
context 'for Variant' do
let(:resource) { Spree::Variant.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for Zone' do
let(:resource) { Spree::Zone.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
end
end
| 30.530909 | 107 | 0.663292 |
385697908e5c56c1dbfc6f43828f8d30d8acdf15
| 248 |
# frozen_string_literal: true
module Codebreaker
module Errors
class CheckTypeError < StandardError
STANDARD_MESSAGE = 'Invalid type'
def initialize(message = STANDARD_MESSAGE)
super(message)
end
end
end
end
| 17.714286 | 48 | 0.697581 |
ed80df2cd3b7102a4181481344bda40ce9e82b09
| 2,747 |
$TESTING = true
# if RUBY_VERSION >= "1.9"
# require "simplecov"
# require "coveralls"
#
# SimpleCov.formatters = [SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter]
#
# SimpleCov.start do
# add_filter "/spec"
# minimum_coverage(90)
# end
# end
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib"))
require "thor"
require "thor/group"
require "stringio"
require "rdoc"
require "rspec"
require "diff/lcs" # You need diff/lcs installed to run specs (but not to run Thor).
require "webmock/rspec"
require 'nrser'
require 'nrser/rspex'
# Log to `//tmp/spec.log` in color (and multiline)
NRSER::Log.setup_for_rspec! dest: {
file_name: Thor::ROOT.join( 'tmp', 'spec.log' ),
formatter: :color,
}
WebMock.disable_net_connect!(:allow => "coveralls.io")
# Set shell to basic
$0 = "thor"
$thor_runner = true
ARGV.clear
Encoding.default_external = Encoding::UTF_8 if RUBY_VERSION > '1.8.7'
Thor::Base.shell = Thor::Shell::Basic
# Load fixtures
load File.join(File.dirname(__FILE__), "fixtures", "enum.thor")
load File.join(File.dirname(__FILE__), "fixtures", "group.thor")
load File.join(File.dirname(__FILE__), "fixtures", "invoke.thor")
load File.join(File.dirname(__FILE__), "fixtures", "script.thor")
load File.join(File.dirname(__FILE__), "fixtures", "subcommand.thor")
load File.join(File.dirname(__FILE__), "fixtures", "command.thor")
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = \
(Thor::ROOT / 'tmp' / '.rspec_status').to_s
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
config.before do
ARGV.replace []
end
config.expect_with :rspec do |c|
c.syntax = :expect
end
def capture(stream)
begin
stream = stream.to_s
eval "$#{stream} = StringIO.new"
yield
result = eval("$#{stream}").string
ensure
eval("$#{stream} = #{stream.upcase}")
end
result
end
def source_root
File.join(File.dirname(__FILE__), "fixtures")
end
def destination_root
File.join(File.dirname(__FILE__), "sandbox")
end
# This code was adapted from Ruby on Rails, available under MIT-LICENSE
# Copyright (c) 2004-2013 David Heinemeier Hansson
def silence_warnings
old_verbose = $VERBOSE
$VERBOSE = nil
yield
ensure
$VERBOSE = old_verbose
end
alias silence capture
end
| 26.413462 | 97 | 0.694576 |
08056956effeeea6dcbc09eebf69404950bbb93e
| 1,065 |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "jira-picker"
spec.version = '0.0.1'
spec.authors = ["Gary Tierney"]
spec.email = ["[email protected]"]
spec.summary = %q{Easily open JIRA issues from a menu.}
spec.description = %q{A simple util which displays a dropdown
auto-completing menu with a list of current JIRA
issues, and opens the selected issue in the browser}
spec.homepage = "https://github.com/garyttierney/jirapicker"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = ['jira_picker']
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "json"
spec.add_dependency "jira-ruby", "~> 0.1.10"
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
end
| 39.444444 | 78 | 0.629108 |
ede69873aed6b7fe5aae6a99f858942d1c2a31ba
| 1,379 |
#
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module Shell
module Commands
class Split < Command
def help
<<-EOF
Split entire table or pass a region to split individual region. With the
second parameter, you can specify an explicit split key for the region.
Examples:
split 'TABLENAME'
split 'REGIONNAME'
split 'ENCODED_REGIONNAME'
split 'TABLENAME', 'splitKey'
split 'REGIONNAME', 'splitKey'
split 'ENCODED_REGIONNAME', 'splitKey'
EOF
end
def command(table_or_region_name, split_point = nil)
admin.split(table_or_region_name, split_point)
end
end
end
end
| 32.069767 | 74 | 0.736041 |
2890cc314acbd6dd2da0b3db941551c30487ce48
| 232 |
Rails.application.routes.draw do
namespace :snip_snap_zap do
resources :snap_schedules do
resources :snip_snaps
end
resources :stats do
collection do
get :kickoff_stats
end
end
end
end
| 17.846154 | 32 | 0.668103 |
18bc33622c5476302942b9af1f860806940e202a
| 1,908 |
module Intrigue
module Ident
module Check
class MediaWiki < Intrigue::Ident::Check::Base
def generate_checks(url)
[
{
type: 'fingerprint',
category: 'application',
tags: %w[COTS CMS],
vendor: 'MediaWiki',
product: 'MediaWiki',
website: 'https://www.mediawiki.org/wiki/MediaWiki',
description: 'MediaWiki - Body Match',
version: nil,
match_logic: :any,
matches: [
{
match_type: :content_body,
match_content: %r{<a href="//www.mediawiki.org/">Powered by MediaWiki</a>},
},
{
match_type: :content_body,
match_content: /poweredby_mediawiki/,
}
],
paths: [{ path: url.to_s, follow_redirects: true }],
inference: false
},
{
type: 'fingerprint',
category: 'application',
tags: %w[COTS CMS],
vendor: 'MediaWiki',
product: 'MediaWiki',
website: 'https://www.mediawiki.org/wiki/MediaWiki',
description: 'generator tag',
match_logic: :all,
matches: [
{
match_type: :content_body,
match_content: /<meta name="generator" content="MediaWiki/,
}
],
version: nil,
dynamic_version: lambda { |x|
_first_body_capture(x, %r{<meta name="generator" content="MediaWiki\ (.*?)"/>})
},
paths: [{ path: url.to_s, follow_redirects: true }],
inference: true
}
]
end
end
end
end
end
| 32.896552 | 112 | 0.433962 |
1a2b18a8433edee8632627a475346e3510892d2d
| 916 |
cask "logseq" do
version "0.2.3"
if Hardware::CPU.intel?
sha256 "1ac8a3a3f24613686cb60310867cf2d7d2de421386af1b4b975625bc45930e67"
url "https://github.com/logseq/logseq/releases/download/#{version}/logseq-darwin-x64-#{version}.dmg"
else
sha256 "b972eae50ac0c878e8e5327c7670b8bb6d8bef2e940f59997a7f071b9afeee1e"
url "https://github.com/logseq/logseq/releases/download/#{version}/logseq-darwin-arm64-#{version}.dmg"
end
name "Logseq"
desc "Privacy-first, open-source platform for knowledge sharing and management"
homepage "https://github.com/logseq/logseq"
livecheck do
url :url
strategy :github_latest
end
auto_updates true
app "Logseq.app"
zap trash: [
"~/Library/Application Support/Logseq",
"~/Library/Logs/Logseq",
"~/Library/Preferences/com.electron.logseq.plist",
"~/Library/Saved Application State/com.electron.logseq.savedState",
]
end
| 28.625 | 106 | 0.737991 |
d5b85d8ee16c01e12748d3a5a28d31bc25994cae
| 304 |
ENV['RAILS_ENV'] ||= 'test'
require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
RSpec.configure do |config|
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
end
| 25.333333 | 67 | 0.736842 |
260bad837e0c893580588becdca5cce2888bff74
| 1,571 |
module NewRelicAWS
module Collectors
class EC2 < Base
def instances
ec2 = AWS::EC2.new(
:access_key_id => @aws_access_key,
:secret_access_key => @aws_secret_key,
:region => @aws_region
)
ec2.instances
end
def metric_list
[
["CPUUtilization", "Average", "Percent"],
["DiskReadOps", "Sum", "Count"],
["DiskWriteOps", "Sum", "Count"],
["DiskWriteBytes" , "Sum", "Bytes"],
["NetworkIn", "Sum", "Bytes"],
["NetworkOut", "Sum", "Bytes"]
]
end
def collect
data_points = []
instances.each do |instance|
detailed = instance.monitoring == :enable
name_tag = instance.tags.detect { |tag| tag.first =~ /^name$/i }
metric_list.each do |(metric_name, statistic, unit)|
data_point = get_data_point(
:namespace => "AWS/EC2",
:metric_name => metric_name,
:statistic => statistic,
:unit => unit,
:dimension => {
:name => "InstanceId",
:value => instance.id
},
:period => detailed ? 60 : 300,
:start_time => (Time.now.utc-(detailed ? 120 : 660)).iso8601,
:component => name_tag.nil? ? instance.id : name_tag.last
)
unless data_point.nil?
data_points << data_point
end
end
end
data_points
end
end
end
end
| 29.641509 | 75 | 0.481859 |
ff5e565d83e9838c988f0e9000baeda5fb39ef1a
| 3,937 |
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
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# 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
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# 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
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :local
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# 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 = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "pundate_#{Rails.env}"
config.action_mailer.perform_caching = false
# 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
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| 41.442105 | 102 | 0.758192 |
39cd52acaa1196947ab048775842f2d27d3feaf1
| 697 |
# encoding: utf-8
require 'spec_helper'
describe Processor::Executor, '#compose' do
let(:input) { double('input') }
let(:output) { double('output') }
describe '#compose' do
subject { executor.compose(input, output) }
include_context 'Processor::Executor#initialize'
before do
expect(composer).to receive(:call).with(input, output).and_return(composed)
end
it { should be(composed) }
end
describe '#decompose' do
subject { executor.decompose(input) }
include_context 'Processor::Executor#initialize'
before do
expect(decomposer).to receive(:call).with(input).and_return(decomposed)
end
it { should be(decomposed) }
end
end
| 21.121212 | 81 | 0.678623 |
21f5bfa56235ecbc306ae058ddedbd470aa1d634
| 470 |
cask 'hstracker' do
version '1.5.1b'
sha256 '54080a7b92ce62c19ecdd582880d9ce76fde4b5a185115ae128c93b9e9b09095'
# github.com/HearthSim/HSTracker was verified as official when first introduced to the cask
url "https://github.com/HearthSim/HSTracker/releases/download/#{version}/HSTracker.app.zip"
appcast 'https://github.com/HearthSim/HSTracker/releases.atom'
name 'Hearthstone Deck Tracker'
homepage 'https://hsdecktracker.net/'
app 'HSTracker.app'
end
| 36.153846 | 93 | 0.785106 |
e2238b56721bfc362d1bf046c930e0ef5d79afe2
| 6,120 |
# frozen_string_literal: true
require_relative './detector'
module Fusuma
module Plugin
module Detectors
class PinchDetector < Detector
SOURCES = ['gesture'].freeze
BUFFER_TYPE = 'gesture'
GESTURE_RECORD_TYPE = 'pinch'
FINGERS = [2, 3, 4].freeze
BASE_THERESHOLD = 1.3
# @param buffers [Array<Buffer>]
# @return [Events::Event] if event is detected
# @return [NilClass] if event is NOT detected
def detect(buffers)
gesture_buffer = buffers.find { |b| b.type == BUFFER_TYPE }
.select_from_last_begin
.select_by_events { |e| e.record.gesture == GESTURE_RECORD_TYPE }
updating_events = gesture_buffer.updating_events
return if updating_events.empty?
finger = gesture_buffer.finger
status = case gesture_buffer.events.last.record.status
when 'end'
'end'
when 'update'
if updating_events.length == 1
'begin'
else
'update'
end
else
gesture_buffer.events.last.record.status
end
prev_event, event = if status == 'end'
[
gesture_buffer.events[-3],
gesture_buffer.events[-2]
]
else
[
gesture_buffer.events[-2],
gesture_buffer.events[-1]
]
end
delta = event.record.delta
prev_delta = prev_event.record.delta
repeat_direction = Direction.new(target: delta.zoom, base: (prev_delta&.zoom || 1.0)).to_s
# repeat_quantity = Quantity.new(target: delta.zoom, base: (prev_delta&.zoom || 1.0)).to_f
repeat_index = create_repeat_index(gesture: type, finger: finger,
direction: repeat_direction,
status: status)
if status == 'update'
return unless moved?(prev_event, event)
avg_zoom = gesture_buffer.avg_attrs(:zoom)
first_zoom = updating_events.first.record.delta.zoom
oneshot_quantity = Quantity.new(target: avg_zoom, base: first_zoom).to_f
oneshot_direction = Direction.new(target: avg_zoom, base: first_zoom).to_s
oneshot_index = create_oneshot_index(gesture: type, finger: finger,
direction: oneshot_direction)
if enough_oneshot_threshold?(index: oneshot_index, quantity: oneshot_quantity)
return [
create_event(record: Events::Records::IndexRecord.new(
index: oneshot_index, trigger: :oneshot, args: delta.to_h
)),
create_event(record: Events::Records::IndexRecord.new(
index: repeat_index, trigger: :repeat, args: delta.to_h
))
]
end
end
create_event(record: Events::Records::IndexRecord.new(
index: repeat_index, trigger: :repeat, args: delta.to_h
))
end
# @param [String] gesture
# @param [Integer] finger
# @param [String] direction
# @param [String] status
# @return [Config::Index]
def create_repeat_index(gesture:, finger:, direction:, status:)
Config::Index.new(
[
Config::Index::Key.new(gesture),
Config::Index::Key.new(finger.to_i),
Config::Index::Key.new(direction, skippable: true),
Config::Index::Key.new(status)
]
)
end
# @param [String] gesture
# @param [Integer] finger
# @param [String] direction
# @return [Config::Index]
def create_oneshot_index(gesture:, finger:, direction:)
Config::Index.new(
[
Config::Index::Key.new(gesture),
Config::Index::Key.new(finger.to_i, skippable: true),
Config::Index::Key.new(direction)
]
)
end
private
def moved?(prev_event, event)
zoom_delta = (event.record.delta.zoom - prev_event.record.delta.zoom).abs
updating_time = (event.time - prev_event.time) * 100
zoom_delta / updating_time > 0.01
end
def enough_oneshot_threshold?(index:, quantity:)
quantity >= threshold(index: index)
end
def threshold(index:)
@threshold ||= {}
@threshold[index.cache_key] ||= begin
keys_specific = Config::Index.new [*index.keys, 'threshold']
keys_global = Config::Index.new ['threshold', type]
config_value = Config.search(keys_specific) ||
Config.search(keys_global) || 1
BASE_THERESHOLD * config_value
end
end
# direction of gesture
class Direction
IN = 'in'
OUT = 'out'
def initialize(target:, base:)
@target = target.to_f
@base = base.to_f
end
def to_s
calc
end
def calc
if @target > @base
IN
else
OUT
end
end
end
# quantity of gesture
class Quantity
def initialize(target:, base:)
@target = target.to_f
@base = base.to_f
end
def to_f
calc.to_f
end
def calc
if @target > @base
@target / @base
else
@base / @target
end
end
end
end
end
end
end
| 32.727273 | 100 | 0.49232 |
acb7bb8f6d75a30d26644fce19ac86140de07ad4
| 1,068 |
require 'minitest/autorun'
require_relative 'accumulate'
class ArrayTest < Minitest::Test
def test_empty_accumulation
assert_equal [], [].accumulate { |e| e * e }
end
def test_accumulate_squares
# skip
result = [1, 2, 3].accumulate do |number|
number * number
end
assert_equal [1, 4, 9], result
end
def test_accumulate_upcases
# skip
result = %w(hello world).accumulate(&:upcase)
assert_equal %w(HELLO WORLD), result
end
def test_accumulate_reversed_strings
# skip
result = %w(the quick brown fox etc).accumulate(&:reverse)
assert_equal %w(eht kciuq nworb xof cte), result
end
def test_accumulate_recursively
# skip
result = %w(a b c).accumulate do |char|
%w(1 2 3).accumulate do |digit|
"#{char}#{digit}"
end
end
assert_equal [%w(a1 a2 a3), %w(b1 b2 b3), %w(c1 c2 c3)], result
end
def test_do_not_change_in_place
# skip
original = [1, 2, 3]
copy = original.dup
original.accumulate { |n| n * n }
assert_equal copy, original
end
end
| 22.723404 | 67 | 0.647004 |
6aa25b88175b54059488bfc681c6e9b00760005a
| 3,081 |
require 'spec_helper'
describe Bitcoin::ChainParams do
describe 'load params' do
context 'mainnet' do
subject{Bitcoin::ChainParams.mainnet}
it do
expect(subject.address_version).to eq('00')
expect(subject.mainnet?).to be true
expect(subject.testnet?).to be false
expect(subject.regtest?).to be false
expect(subject.signet?).to be false
expect(subject.genesis_block.header.to_hex).to eq('0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c')
expect(subject.genesis_block.header.block_hash).to eq('6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000')
expect(subject.dust_relay_fee).to eq(Bitcoin::DUST_RELAY_TX_FEE)
end
end
context 'testnet' do
subject{Bitcoin::ChainParams.testnet}
it do
expect(subject.address_version).to eq('6f')
expect(subject.mainnet?).to be false
expect(subject.testnet?).to be true
expect(subject.regtest?).to be false
expect(subject.signet?).to be false
expect(subject.genesis_block.header.to_hex).to eq('0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4adae5494dffff001d1aa4ae18')
expect(subject.genesis_block.header.block_hash).to eq('43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000')
expect(subject.dust_relay_fee).to eq(Bitcoin::DUST_RELAY_TX_FEE)
end
end
context 'regtest' do
subject{Bitcoin::ChainParams.regtest}
it do
expect(subject.default_port).to eq(18444)
expect(subject.mainnet?).to be false
expect(subject.testnet?).to be false
expect(subject.regtest?).to be true
expect(subject.signet?).to be false
expect(subject.genesis_block.header.to_hex).to eq('0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4adae5494dffff7f2002000000')
expect(subject.genesis_block.header.block_hash).to eq('06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f')
expect(subject.dust_relay_fee).to eq(3600)
end
end
# https://github.com/bitcoin/bips/blob/master/bip-0325.mediawiki
context 'signet' do
subject{Bitcoin::ChainParams.signet}
it do
expect(subject.default_port).to eq(38333)
expect(subject.mainnet?).to be false
expect(subject.testnet?).to be false
expect(subject.regtest?).to be false
expect(subject.signet?).to be true
expect(subject.genesis_block.header.to_hex).to eq('0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a008f4d5fae77031e8ad22203')
expect(subject.genesis_block.header.block_id).to eq('00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6')
end
end
end
end
| 48.140625 | 221 | 0.758195 |
ff9bb2c912cf03cf3ba36314796f06d65710398b
| 1,143 |
class Xxhash < Formula
desc "Extremely fast non-cryptographic hash algorithm"
homepage "https://github.com/Cyan4973/xxHash"
url "https://github.com/Cyan4973/xxHash/archive/v0.8.0.tar.gz"
sha256 "7054c3ebd169c97b64a92d7b994ab63c70dd53a06974f1f630ab782c28db0f4f"
revision 1 unless OS.mac?
license "BSD-2-Clause"
livecheck do
url :stable
strategy :github_latest
end
bottle do
cellar :any
sha256 "13fd891c5e884b86cd7273192bbea63d56e4f8f8c461009ee2050af09eeb2161" => :big_sur
sha256 "06ea145c49451bf37f2a73139100f436b4bf9f275b77b9dadcb5d36a7b07fae1" => :catalina
sha256 "df75758d4b4756b23530ec54e2289148652e3f54d6f9a8e45c43f662bc69d7c2" => :mojave
sha256 "821f8c8df3ada242236f2f231ae72cdcaf23412a5e22458c23df453631129300" => :high_sierra
sha256 "c1bd2046c7055bc4d321b40336e00ba6d30cabce4bdfd84aea766f4758f4a4d3" => :x86_64_linux
end
def install
system "make"
system "make", "install", "PREFIX=#{prefix}"
end
test do
(testpath/"leaflet.txt").write "No computer should be without one!"
assert_match /^67bc7cc242ebc50a/, shell_output("#{bin}/xxhsum leaflet.txt")
end
end
| 34.636364 | 94 | 0.775153 |
21cd691528410ec5d9e9d2676ed133b575af2f46
| 2,632 |
#-- encoding: UTF-8
#-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2018 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-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.
#++
require 'spec_helper'
def translate_with_base_url(string)
I18n.t(string, deep_interpolation: true, base_url: OpenProject::Configuration.rails_relative_url_root)
end
describe 'seeds' do
before do
allow(OpenProject::Configuration).to receive(:[]).and_call_original
allow(OpenProject::Configuration).to receive(:[]).with('edition').and_return(edition)
end
context 'BIM edition' do
let(:edition) { 'bim' }
it 'create the demo data' do
perform_deliveries = ActionMailer::Base.perform_deliveries
ActionMailer::Base.perform_deliveries = false
begin
# Avoid asynchronous DeliverWorkPackageCreatedJob
Delayed::Worker.delay_jobs = false
expect { BimSeeder::BasicDataSeeder.new.seed! }.not_to raise_error
expect { AdminUserSeeder.new.seed! }.not_to raise_error
expect { DemoDataSeeder.new.seed! }.not_to raise_error
expect(User.where(admin: true).count).to eq 1
expect(Project.count).to eq 4
expect(WorkPackage.count).to eq 77
expect(Wiki.count).to eq 3
expect(Query.count).to eq 25
expect(Group.count).to eq 8
expect(Type.count).to eq 7
expect(Status.count).to eq 4
expect(IssuePriority.count).to eq 4
expect(Project::Status.count).to eq 4
ensure
ActionMailer::Base.perform_deliveries = perform_deliveries
end
end
end
end
| 35.567568 | 104 | 0.722264 |
878c0c7bcfd84d058116f10ea2b803442b8fbe06
| 481 |
# Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) { wrap_parameters format: %i[json] }
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end
| 37 | 96 | 0.783784 |
213dd0b7b2ca8eb725a12d525537289b84140169
| 3,390 |
require 'wilbertils/exception_handler'
module Wilbertils::Authorization
class Oauth2
class << self
def access_token params
@@params = params.deep_symbolize_keys
fetch_access_token
end
private
def fetch_access_token
begin
token = retreive_access_token_from_redis
token = refresh_token(token) if expired?(token)
return token[token_name] if token
request_access_token
rescue => e
logger.error e.message
logger.error e.backtrace
end
end
def request_access_token
begin
response = JSON.parse(RestClient.post(token_url, token_request_body, token_request_headers), symbolize_names: true)
store_token(response)
response[token_name]
rescue => e
logger.error "Failed to get access token for #{@@params[:token_for]}; #{e.message}"
logger.error e.backtrace
raise
end
end
def token_request_body
@@params[:token_request_body] || { :grant_type => grant_type }.merge(body)
end
def token_request_headers
case @@params[:grant_type].to_sym
when :client_credentials
{ Authorization: "Basic #{Base64.strict_encode64("#{@@params[:body][:client_id]}:#{@@params[:body][:client_secret]}")}" }
else
{}
end.merge(@@params[:headers] || {})
end
def grant_type
@@params[:grant_type].to_sym == :client_credentials_body ? :client_credentials : @@params[:grant_type]
end
def body
case @@params[:grant_type].to_sym
when :password, :client_credentials_body
@@params[:body]
else
{}
end
end
def token_name
@@params[:token_name]&.to_sym || :access_token
end
# need to send '' as token_path for nz couriers because the auth url and data url are different so can't send the url and add /token at end
def token_url
@@params[:url] + (@@params[:token_path] || '/token')
end
def refresh_token token
return unless token[:refresh_token]
begin
response = JSON.parse(RestClient.post(token_url,
{
:grant_type => :refresh_token,
:refresh_token => token[:refresh_token]
}.merge(body)
), symbolize_names: true)
store_token(response)
response
rescue => e
logger.info "requesting new access token"
logger.info e.backtrace
request_access_token
end
end
def token_key
"token:#{@@params[:token_for]}:#{@@params[:body][:client_id]}"
end
def store_token response
redis.set(token_key, response.merge(created_at: Time.now).to_json)
end
def retreive_access_token_from_redis
token = redis.get(token_key)
JSON.parse(token, symbolize_names: true) if token
end
def expired? token
# default of 1 hr set, sometimes medipt send back nil and need to handle it
!!token && ( ( Time.now.to_i - Time.parse(token[:created_at]).to_i ) > ( token[:expires_in] || 3600 ) )
end
def redis
Wilbertils::Redis::Redis.client(@@params[:config])
end
def logger
@@params[:logger]
end
end
end
end
| 28.25 | 145 | 0.593805 |
e8202b65933162523614ea36331acb531437ac58
| 914 |
require 'rails/generators'
require 'rails/generators/migration'
module Camaraderie
module Generators
class InstallGenerator < Rails::Generators::Base
include Rails::Generators::Migration
source_root File.expand_path('../templates', __FILE__)
# Implement the required interface for Rails::Generators::Migration.
# taken from http://github.com/rails/rails/blob/master/activerecord/lib/generators/active_record.rb
def self.next_migration_number(dirname)
if ActiveRecord::Base.timestamped_migrations
Time.now.utc.strftime('%Y%m%d%H%M%S')
else
'%.3d' % (current_migration_number(dirname) + 1)
end
end
def create_migration_file
migration_template 'migration.rb', 'db/migrate/add_camaraderie.rb'
end
def create_model_file
template "model.rb", "app/models/membership.rb"
end
end
end
end
| 30.466667 | 105 | 0.690372 |
f77a82ed557a89988d7b2aff409ca50b0543813c
| 1,156 |
Dado("que estou no site da Submarino") do
@page = PageCommerce.new
@page.load
end
Quando("pesquiso pelo item {string}") do |item|
@page = PageCommerce.new
@page.pesquisar(item)
end
Quando("verifico se a pesquisa retornou o item correto") do
lblproduto = @page.verificar
expect(lblproduto).to have_content "console playstation 4"
end
Quando("seleciono o tipo de produto console") do
@page.checkbox
end
Quando("adiciono ao carrinho") do
@page.adicionar
end
Então("devo verificar quantos itens meu carrinho possui") do
qnt = @page.carrinho
puts "O carrinho possui #{qnt} item(ns)"
end
#Cenário - Produto Inexistente
Quando("eu pesquiso pelo item inexistente {string}") do |prod|
@page.pesquisar(prod)
end
Então("a mensagem {string} deverá aparecer em tela.") do |lblinexistente|
expect(page).to have_content lblinexistente
end
#Cenário - Carrinho vazio
Quando("clicar no carrinho sem nenhum item adicionado") do
@page.compras
end
Então("a mensagem {string} deverá ser apresentada.") do |vazio|
empty = @page.prod_vazio
expect(empty).to have_text vazio
end
| 22.230769 | 73 | 0.702422 |
030059d8f97f0571d5a3e07bb87d1cf4250dd4d6
| 839 |
require "test_helper"
class RedisTest < Minitest::Test
def setup
@client = Vahana::Redis.new
end
def test_method_existance
assert_respond_to @client, :drop
assert_respond_to @client, :all_ids
assert_respond_to @client, :seed
assert_respond_to @client, :insert
assert_respond_to @client, :delete
end
def test_insert
assert_equal @client.insert(Vahana::SingleRecord.new('test', 'test')), "OK"
assert_raises(ArgumentError) { @client.insert(Vahana::SingleRecord.new([], 'test')) }
assert_raises(ArgumentError) { @client.insert(Vahana::SingleRecord.new('test', [])) }
assert_raises(ArgumentError) { @client.insert('test', 'key') }
end
def test_drop
@client.drop
assert_empty @client.all_ids
end
def test_seed
@client.seed
refute_empty @client.all_ids
end
end
| 24.676471 | 89 | 0.703218 |
792bf97b90b959616e6e8952e47fa78991301b43
| 379 |
require 'formula'
class Xsw < Formula
homepage 'http://code.google.com/p/xsw/'
url 'https://xsw.googlecode.com/files/xsw-0.3.5.tar.gz'
sha1 'fe4cffcc8bcd3149f4ecbf2011ad78a8ab7f1dd4'
depends_on 'sdl'
depends_on 'sdl_ttf'
depends_on 'sdl_image'
depends_on 'sdl_gfx'
def install
system "./configure", "--prefix=#{prefix}"
system "make install"
end
end
| 21.055556 | 57 | 0.707124 |
2858183ee471bb2be40ec09c106fe909fb042c00
| 1,077 |
module Watir
class Radio < Input
def initialize(query_scope, selector)
super
@selector[:label] = @selector.delete(:text) if @selector.key?(:text)
end
#
# Selects this radio button.
#
def set
click unless set?
end
alias select set
#
# Is this radio set?
#
# @return [Boolean]
#
def set?
element_call { @element.selected? }
end
alias selected? set?
#
# Returns the text of the associated label.
# Returns empty string if no label is found.
#
# @return [String]
#
def text
l = label()
l.exist? ? l.text : ''
end
end # Radio
module Container
def radio(*args)
Radio.new(self, extract_selector(args).merge(tag_name: 'input', type: 'radio'))
end
def radios(*args)
RadioCollection.new(self, extract_selector(args).merge(tag_name: 'input', type: 'radio'))
end
end # Container
class RadioCollection < InputCollection
private
def element_class
Radio
end
end # RadioCollection
end # Watir
| 18.254237 | 95 | 0.598886 |
2828c543d5cd6cc42ed3c57ca9e021e0f8b6477a
| 18,992 |
# frozen_string_literal: true
require "support/vacols_database_cleaner"
require "rails_helper"
RSpec.feature "Schedule Veteran For A Hearing", :all_dbs do
let!(:current_user) do
user = create(:user, css_id: "BVATWARNER", roles: ["Build HearSched"])
User.authenticate!(user: user)
end
let(:other_user) { create(:user) }
before do
HearingsManagement.singleton.add_user(current_user)
HearingAdmin.singleton.add_user(current_user)
HearingsManagement.singleton.add_user(other_user)
HearingAdmin.singleton.add_user(other_user)
end
context "When creating Caseflow Central hearings" do
let!(:hearing_day) { create(:hearing_day, scheduled_for: Time.zone.today + 30.days) }
let!(:vacols_case) do
create(
:case, :central_office_hearing,
bfcorlid: "123454787S",
bfcurloc: "CASEFLOW"
)
end
let!(:legacy_appeal) { create(:legacy_appeal, vacols_case: vacols_case) }
let!(:schedule_hearing_task) { create(:schedule_hearing_task, appeal: legacy_appeal) }
let!(:veteran) { create(:veteran, file_number: "123454787") }
let!(:hearing_location_dropdown_label) { "Hearing Location" }
let(:appellant_appeal_link_text) do
"#{legacy_appeal.appellant[:first_name]} #{legacy_appeal.appellant[:last_name]} | #{veteran.file_number}"
end
def navigate_to_schedule_veteran_modal
visit "hearings/schedule/assign"
expect(page).to have_content("Regional Office")
click_dropdown(text: "Central")
click_button("Legacy Veterans Waiting")
click_link appellant_appeal_link_text
expect(page).not_to have_content("loading to VACOLS.", wait: 30)
expect(page).to have_content("Currently active tasks", wait: 30)
click_dropdown(text: Constants.TASK_ACTIONS.SCHEDULE_VETERAN.to_h[:label])
expect(page).to have_content("Time")
end
scenario "address from BGS is displayed in schedule veteran modal" do
navigate_to_schedule_veteran_modal
expect(page).to have_content FakeConstants.BGS_SERVICE.DEFAULT_ADDRESS_LINE_1
expect(page).to have_content(
"#{FakeConstants.BGS_SERVICE.DEFAULT_CITY}, " \
"#{FakeConstants.BGS_SERVICE.DEFAULT_STATE} #{FakeConstants.BGS_SERVICE.DEFAULT_ZIP}"
)
end
scenario "Schedule Veteran for central hearing" do
navigate_to_schedule_veteran_modal
# Wait for the contents of the dropdown to finish loading before clicking into the dropdown.
expect(page).to have_content(hearing_location_dropdown_label)
click_dropdown(name: "appealHearingLocation", text: "Holdrege, NE (VHA) 0 miles away")
find("label", text: "9:00 am").click
click_button("Schedule")
click_on "Back to Schedule Veterans"
expect(page).to have_content("Schedule Veterans")
click_button("Scheduled Veterans")
expect(VACOLS::Case.where(bfcorlid: "123454787S"))
click_button("Legacy Veterans Waiting")
expect(page).not_to have_content("123454787S")
expect(page).to have_content("There are no schedulable veterans")
expect(VACOLS::CaseHearing.first.folder_nr).to eq vacols_case.bfkey
end
end
context "when video_hearing_requested" do
let!(:hearing_day) do
create(
:hearing_day,
request_type: HearingDay::REQUEST_TYPES[:video],
scheduled_for: Time.zone.today + 60.days,
regional_office: "RO39"
)
end
let!(:staff) { create(:staff, stafkey: "RO39", stc2: 2, stc3: 3, stc4: 4) }
let!(:vacols_case) do
create(
:case, :video_hearing_requested,
folder: create(:folder, tinum: "docket-number"),
bfcorlid: "123456789S",
bfcurloc: "CASEFLOW",
bfregoff: "RO39"
)
end
let!(:legacy_appeal) do
create(
:legacy_appeal,
vacols_case: vacols_case,
closest_regional_office: "RO39"
)
end
let!(:schedule_hearing_task) do
create(
:schedule_hearing_task, appeal: legacy_appeal
)
end
let!(:veteran) { create(:veteran, file_number: "123456789") }
scenario "Schedule Veteran for video" do
visit "hearings/schedule/assign"
expect(page).to have_content("Regional Office")
click_dropdown(text: "Denver, CO")
click_button("Legacy Veterans Waiting")
appeal_link = page.find(:xpath, "//tbody/tr/td[2]/a")
appeal_link.click
expect(page).not_to have_content("loading to VACOLS.", wait: 30)
expect(page).to have_content("Currently active tasks", wait: 30)
click_dropdown(text: Constants.TASK_ACTIONS.SCHEDULE_VETERAN.to_h[:label])
expect(page).to have_content("Time")
find("label", text: "8:30 am").click
expect(page).not_to have_content("Could not find hearing locations for this veteran", wait: 30)
click_dropdown(name: "appealHearingLocation", text: "Holdrege, NE (VHA) 0 miles away")
click_button("Schedule")
click_on "Back to Schedule Veterans"
expect(page).to have_content("Schedule Veterans")
click_button("Scheduled Veterans")
expect(VACOLS::Case.where(bfcorlid: "123456789S"))
click_button("Legacy Veterans Waiting")
expect(page).not_to have_content("123456789S")
expect(page).to have_content("There are no schedulable veterans")
expect(VACOLS::CaseHearing.first.folder_nr).to eq vacols_case.bfkey
end
context "but facilities api throws an error" do
before do
facilities_response = ExternalApi::VADotGovService::FacilitiesResponse.new(
HTTPI::Response.new(200, {}, {}.to_json)
)
allow(facilities_response).to receive(:data).and_return([])
allow(facilities_response).to receive(:code).and_return(429)
allow(VADotGovService).to receive(:get_distance).and_return(facilities_response)
end
scenario "Schedule Veteran for video erro" do
visit "queue/appeals/#{legacy_appeal.vacols_id}"
click_dropdown(text: Constants.TASK_ACTIONS.SCHEDULE_VETERAN.to_h[:label])
expect(page).to have_content("Mapping service is temporarily unavailable. Please try again later.")
end
end
end
context "when scheduling an AMA hearing" do
let!(:hearing_day) do
create(
:hearing_day,
request_type: HearingDay::REQUEST_TYPES[:video],
scheduled_for: Time.zone.today + 160,
regional_office: "RO39"
)
end
let!(:staff) { create(:staff, stafkey: "RO39", stc2: 2, stc3: 3, stc4: 4) }
let!(:appeal) do
create(
:appeal,
:with_post_intake_tasks,
docket_type: Constants.AMA_DOCKETS.hearing,
closest_regional_office: "RO39",
veteran: create(:veteran)
)
end
let(:incarcerated_veteran_task_instructions) { "Incarcerated veteran task instructions" }
let(:contested_claimant_task_instructions) { "Contested claimant task instructions" }
scenario "Can create multiple admin actions and reassign them" do
visit "hearings/schedule/assign"
expect(page).to have_content("Regional Office")
click_dropdown(text: "Denver")
click_button("AMA Veterans Waiting")
click_on "Bob Smith"
# Case details screen
click_dropdown(text: Constants.TASK_ACTIONS.ADD_ADMIN_ACTION.to_h[:label])
# Admin action screen
# First admin action
expect(page).to have_content("Submit admin action")
click_dropdown(text: HearingAdminActionIncarceratedVeteranTask.label)
fill_in COPY::ADD_COLOCATED_TASK_INSTRUCTIONS_LABEL, with: incarcerated_veteran_task_instructions
# Second admin action
click_on COPY::ADD_COLOCATED_TASK_ANOTHER_BUTTON_LABEL
within all('div[id^="action_"]', count: 2)[1] do
click_dropdown(text: HearingAdminActionContestedClaimantTask.label)
fill_in COPY::ADD_COLOCATED_TASK_INSTRUCTIONS_LABEL, with: contested_claimant_task_instructions
end
click_on "Assign Action"
# The banner has the correct content
expect(page).to have_content(
format(
COPY::ADD_COLOCATED_TASK_CONFIRMATION_TITLE,
"2",
"actions",
[HearingAdminActionIncarceratedVeteranTask.label, HearingAdminActionContestedClaimantTask.label].join(", ")
)
)
# The timeline has the correct content
incarcerated_row = find("dd", text: HearingAdminActionIncarceratedVeteranTask.label).find(:xpath, "ancestor::tr")
incarcerated_row.click_on(
COPY::TASK_SNAPSHOT_VIEW_TASK_INSTRUCTIONS_LABEL
)
expect(incarcerated_row).to have_content incarcerated_veteran_task_instructions
contested_row = find("dd", text: HearingAdminActionContestedClaimantTask.label).find(:xpath, "ancestor::tr")
contested_row.click_on(
COPY::TASK_SNAPSHOT_VIEW_TASK_INSTRUCTIONS_LABEL
)
expect(contested_row).to have_content contested_claimant_task_instructions
within all("div", class: "Select", count: 2).first do
click_dropdown(text: Constants.TASK_ACTIONS.ASSIGN_TO_PERSON.to_h[:label])
end
click_on "Submit"
# Your queue
visit "/queue"
click_on "Bob Smith"
# Reassign
within find("tr", text: "BVATWARNER") do
click_dropdown(text: Constants.TASK_ACTIONS.REASSIGN_TO_PERSON.to_h[:label])
end
click_dropdown(text: other_user.full_name)
fill_in COPY::ADD_COLOCATED_TASK_INSTRUCTIONS_LABEL, with: "Reassign"
click_on "Submit"
# Case should exist in other users' queue
User.authenticate!(user: other_user)
visit "/queue"
expect(page).to have_content("Bob Smith")
end
scenario "Schedule Veteran for a video hearing with admin actions that can be put on hold and completed" do
# Do the first part of the test in the past so we can wait for our hold to complete.
Timecop.travel(20.days.ago) do
visit "hearings/schedule/assign"
expect(page).to have_content("Regional Office")
click_dropdown(text: "Denver")
click_button("AMA Veterans Waiting")
click_on "Bob Smith"
# Case details screen
click_dropdown(text: Constants.TASK_ACTIONS.ADD_ADMIN_ACTION.to_h[:label])
# Admin action screen
# First admin action
expect(page).to have_content("Submit admin action")
click_dropdown(text: HearingAdminActionIncarceratedVeteranTask.label)
fill_in COPY::ADD_COLOCATED_TASK_INSTRUCTIONS_LABEL, with: "Action 1"
click_on "Assign Action"
expect(page).to have_content("You have assigned an administrative action")
click_dropdown(text: Constants.TASK_ACTIONS.ASSIGN_TO_PERSON.to_h[:label])
click_on "Submit"
# Your queue
visit "/queue"
click_on "Bob Smith"
click_dropdown(text: Constants.TASK_ACTIONS.PLACE_TIMED_HOLD.label)
# On hold
click_dropdown(text: "15 days")
fill_in "Notes:", with: "Waiting for response"
click_on(COPY::MODAL_SUBMIT_BUTTON)
expect(page).to have_content("case has been placed on hold")
end
# Refresh the page in the present, and the hold should be completed.
visit "/queue"
click_on "Bob Smith"
# Complete the admin action
click_dropdown(text: Constants.TASK_ACTIONS.MARK_COMPLETE.to_h[:label])
click_on "Mark complete"
expect(page).to have_content("has been marked complete")
# Schedule veteran!
visit "hearings/schedule/assign"
expect(page).to have_content("Regional Office")
click_dropdown(text: "Denver")
click_button("AMA Veterans Waiting")
click_on "Bob Smith"
click_dropdown(text: Constants.TASK_ACTIONS.SCHEDULE_VETERAN.to_h[:label])
click_dropdown({ text: "Denver" }, find(".dropdown-regionalOffice"))
click_dropdown({ index: 1 }, find(".dropdown-hearingDate"))
find("label", text: "8:30 am").click
expect(page).to_not have_content("Finding hearing locations", wait: 30)
click_dropdown(name: "appealHearingLocation", text: "Holdrege, NE (VHA) 0 miles away")
click_on "Schedule"
expect(page).to have_content("You have successfully assigned")
# Ensure the veteran appears on the scheduled page
expect(page).to have_content(appeal.docket_number)
# Ensure the veteran is no longer in the veterans waiting to be scheduled
click_on "Back to Schedule Veterans"
expect(page).to have_content("Regional Office")
click_dropdown(text: "Denver")
click_button("AMA Veterans Waiting")
expect(page).to have_content("There are no schedulable veterans")
end
scenario "Withdraw Veteran's hearing request" do
visit "hearings/schedule/assign"
expect(page).to have_content("Regional Office")
click_dropdown(text: "Denver")
click_button("AMA Veterans Waiting")
click_on "Bob Smith"
click_dropdown(text: Constants.TASK_ACTIONS.WITHDRAW_HEARING.to_h[:label])
click_on "Submit"
expect(page).to have_content("You have successfully withdrawn")
expect(appeal.tasks.where(type: ScheduleHearingTask.name).first.status).to eq(Constants.TASK_STATUSES.cancelled)
expect(appeal.tasks.where(type: EvidenceSubmissionWindowTask.name).count).to eq(1)
click_on "Back to Hearing Schedule"
expect(page).to have_content("Denver")
end
end
context "When list of veterans displays in Legacy Veterans Waiting" do
let!(:hearing_day) { create(:hearing_day, scheduled_for: Time.zone.today + 30) }
let!(:schedule_hearing_task1) do
create(
:schedule_hearing_task, appeal: create(
:legacy_appeal,
vacols_case: create(
:case, :central_office_hearing,
:type_cavc_remand,
bfcorlid: "123454787S",
bfcurloc: "CASEFLOW",
folder: create(
:folder,
ticknum: "91",
tinum: "1545678",
titrnum: "123454787S"
)
)
)
)
end
let!(:veteran1) { create(:veteran, file_number: "123454787") }
let!(:schedule_hearing_task2) do
create(
:schedule_hearing_task, appeal: create(
:legacy_appeal,
vacols_case: create(
:case,
:central_office_hearing,
:aod,
:type_original,
bfcorlid: "123454788S",
bfcurloc: "CASEFLOW",
folder: create(
:folder,
ticknum: "92",
tinum: "1645621",
titrnum: "123454788S"
)
)
)
)
end
let!(:veteran2) { create(:veteran, file_number: "123454788") }
let!(:schedule_hearing_task3) do
create(
:schedule_hearing_task, appeal: create(
:legacy_appeal,
vacols_case: create(
:case,
:central_office_hearing,
:aod,
:type_original,
bfcorlid: "323454787S",
bfcurloc: "CASEFLOW",
folder: create(
:folder,
ticknum: "93",
tinum: "1645678",
titrnum: "323454787S"
)
)
)
)
end
let!(:veteran3) { create(:veteran, file_number: "323454787") }
let!(:schedule_hearing_task4) do
create(
:schedule_hearing_task, appeal: create(
:legacy_appeal,
vacols_case: create(
:case,
:central_office_hearing,
:type_original,
bfcorlid: "123454789S",
bfcurloc: "CASEFLOW",
folder: create(
:folder,
ticknum: "94",
tinum: "1445678",
titrnum: "123454789S"
)
)
)
)
end
let!(:veteran4) { create(:veteran, file_number: "123454789") }
let!(:schedule_hearing_task5) do
create(
:schedule_hearing_task, appeal: create(
:legacy_appeal,
vacols_case: create(
:case,
:central_office_hearing,
:type_original,
bfcorlid: "523454787S",
bfcurloc: "CASEFLOW",
folder: create(
:folder,
ticknum: "95",
tinum: "1445695",
titrnum: "523454787S"
)
)
)
)
end
let!(:veteran5) { create(:veteran, file_number: "523454787") }
scenario "Verify docket order is CVAC, AOD, then regular." do
visit "hearings/schedule/assign"
expect(page).to have_content("Regional Office")
click_dropdown(text: "Central")
click_button("Legacy Veterans Waiting")
table_row = page.find("tr", id: "table-row-0")
expect(table_row).to have_content("1545678", wait: 30)
table_row = page.find("tr", id: "table-row-1")
expect(table_row).to have_content("1645621")
table_row = page.find("tr", id: "table-row-2")
expect(table_row).to have_content("1645678")
table_row = page.find("tr", id: "table-row-3")
expect(table_row).to have_content("1445678")
table_row = page.find("tr", id: "table-row-4")
expect(table_row).to have_content("1445695")
end
end
context "With a full hearing day" do
let(:appeal) { create(:appeal) }
let!(:schedule_hearing_task) { create(:schedule_hearing_task, appeal: appeal) }
let!(:hearing_day) do
create(
:hearing_day,
scheduled_for: Time.zone.today + 5,
request_type: HearingDay::REQUEST_TYPES[:video],
regional_office: "RO17"
)
end
let!(:hearings) do
(1...hearing_day.total_slots + 1).map do |idx|
create(
:hearing,
appeal: create(:appeal, receipt_date: Date.new(2019, 1, idx)),
hearing_day: hearing_day
)
end
end
scenario "can still schedule veteran successfully" do
visit "/queue/appeals/#{appeal.external_id}"
click_dropdown(text: "Schedule Veteran")
click_dropdown(text: RegionalOffice.find!("RO17").city)
click_dropdown(
text: "#{hearing_day.scheduled_for.to_formatted_s(:short_date)} (12/12)",
name: "hearingDate"
)
expect(page).to have_content(COPY::SCHEDULE_VETERAN_FULL_HEARING_DAY_TITLE)
expect(page).to have_content(COPY::SCHEDULE_VETERAN_FULL_HEARING_DAY_MESSAGE_DETAIL)
click_dropdown(
text: "Holdrege, NE (VHA) 0 miles away",
name: "appealHearingLocation"
)
click_dropdown(text: "10:00 am", name: "optionalHearingTime1")
click_button("Schedule")
expect(page).to have_content(COPY::SCHEDULE_VETERAN_SUCCESS_MESSAGE_DETAIL)
end
end
context "No upcoming hearing days" do
scenario "Show status message for empty upcoming hearing days" do
visit "hearings/schedule/assign"
click_dropdown(text: "Winston-Salem, NC")
expect(page).to have_content("No upcoming hearing days")
end
end
end
| 35.833962 | 119 | 0.654381 |
61609fa64b1a802bec7ebfea6d1abd33561c6b09
| 1,151 |
module UserEmailAddressComponent
module Controls
module UserEmailAddress
def self.example(sequence: nil)
user_email_address = UserEmailAddressComponent::UserEmailAddress.build
user_email_address.encoded_email_address = encoded_email_address
user_email_address.sequence = sequence unless sequence.nil?
user_email_address
end
def self.encoded_email_address
downcased_email_address = email_address.downcase
Digest::SHA256.hexdigest(downcased_email_address)
end
def self.email_address
"[email protected]"
end
module New
def self.example
UserEmailAddressComponent::UserEmailAddress.build
end
end
module Claimed
def self.example
user_email_address = UserEmailAddress.example
user_email_address.claimed_time = Time::Effective::Raw.example
user_email_address
end
end
module Sequence
def self.example
sequence = Controls::Sequence.example
UserEmailAddress.example(sequence: sequence)
end
end
end
end
end
| 24.489362 | 78 | 0.675065 |
d5dd0901d8a9db28964e985d050b25f2f5aa593e
| 992 |
class CreateAuthorizedUser < Eldr::Action
include Eldr::Sessions
include Eldr::Responders
set :views_dir, File.join(__dir__, '../../views')
attr_accessor :user, :env
def call(env)
@env = env
auth = env['omniauth.auth']
raise Errors::NotAuthorized, 'Did you login?' unless auth
@identity = Identity.find_or_create_with_omniauth(auth)
@message = 'Signed in!'
if signed_in?
if @identity.user == current_user
@message = 'Already linked that account!'
else
@identity.user = current_user
@identity.save
@message = 'Successfully linked that account!'
end
end
unless @identity.user.present?
user = User.create_with_identity(@identity)
return respond(user, error: 'Invalid User') unless user.valid?
@identity.user = user
@identity.save
end
set_current_user @identity.user
respond(current_user, force_redirect: true, location: '/#buy', message: @message)
end
end
| 25.435897 | 85 | 0.66129 |
034b2884130238476e234e9863e863984f5f1f45
| 2,921 |
require 'rails_helper'
describe Users::WebauthnSetupController do
include WebAuthnHelper
describe 'before_actions' do
it 'includes appropriate before_actions' do
expect(subject).to have_actions(
:before,
:authenticate_user!,
:confirm_user_authenticated_for_2fa_setup,
)
end
end
describe 'when not signed in' do
describe 'GET new' do
it 'redirects to root url' do
get :new
expect(response).to redirect_to(root_url)
end
end
describe 'patch confirm' do
it 'redirects to root url' do
patch :confirm
expect(response).to redirect_to(root_url)
end
end
end
describe 'when signed in and not account creation' do
let(:user) { create(:user, :signed_up, :with_authentication_app) }
before do
stub_analytics
stub_sign_in(user)
end
describe 'GET new' do
it 'tracks page visit' do
stub_sign_in
stub_analytics
expect(@analytics).to receive(:track_event).
with(Analytics::WEBAUTHN_SETUP_VISIT, errors: {}, success: true)
get :new
end
end
describe 'patch confirm' do
let(:params) do
{
attestation_object: attestation_object,
client_data_json: setup_client_data_json,
name: 'mykey',
}
end
before do
allow(Figaro.env).to receive(:domain_name).and_return('localhost:3000')
controller.user_session[:webauthn_challenge] = webauthn_challenge
end
it 'tracks the submission' do
result = {
success: true,
errors: {},
mfa_method_counts: {
auth_app: 1, phone: 1, webauthn: 1, backup_codes: 10
},
multi_factor_auth_method: 'webauthn',
}
expect(@analytics).to receive(:track_event).
with(Analytics::MULTI_FACTOR_AUTH_SETUP, result)
patch :confirm, params: params
end
end
describe 'delete' do
let(:webauthn_configuration) { create(:webauthn_configuration, user: user) }
it 'creates a webauthn key removed event' do
expect(Event).to receive(:create).
with(hash_including(user_id: controller.current_user.id,
event_type: :webauthn_key_removed, ip: '0.0.0.0'))
delete :delete, params: { id: webauthn_configuration.id }
expect(response).to redirect_to(account_url)
expect(flash.now[:success]).to eq t('notices.webauthn_deleted')
expect(WebauthnConfiguration.count).to eq(0)
end
it 'tracks the delete in analytics' do
result = { success: true, mfa_method_counts: { auth_app: 1, phone: 1, backup_codes: 10 } }
expect(@analytics).to receive(:track_event).with(Analytics::WEBAUTHN_DELETED, result)
delete :delete, params: { id: webauthn_configuration.id }
end
end
end
end
| 27.046296 | 98 | 0.627867 |
5d9a2babc07a47da303257f374eddd449aef7fe5
| 1,145 |
class ScribblesController < ApplicationController
before_action :authorize!, except: [:index, :show]
before_action :set_scribble, only: [:show, :edit, :update, :destroy]
def index
scribbles = current_user ? Scribble.all : Scribble.published
@scribbles = scribbles.page params[:page]
end
def show
redirect_to scribbles_path unless @scribble.on || current_user
end
def new
@scribble = Scribble.new
end
def edit
end
def create
@scribble = Scribble.new(scribble_params)
if @scribble.save
redirect_to @scribble, notice: 'Scribble was successfully created.'
else
render :new
end
end
def update
if @scribble.update(scribble_params)
redirect_to @scribble, notice: 'Scribble was successfully updated.'
else
render :edit
end
end
def destroy
@scribble.destroy
redirect_to scribbles_url, notice: 'Scribble was successfully destroyed.'
end
private
def set_scribble
@scribble = Scribble.includes(:comments).friendly.find(params[:id])
end
def scribble_params
params.require(:scribble).permit(:title, :content, :on)
end
end
| 21.203704 | 77 | 0.70131 |
877e8301e885d7154d2389c29ec3a064659e93c5
| 233 |
module VagrantPlugins
module Cosmic
module Cap
class WinRM
def self.winrm_info(machine)
env = machine.action('read_winrm_info')
env[:machine_winrm_info]
end
end
end
end
end
| 17.923077 | 49 | 0.609442 |
e263b0343df61d1b0d6c4ef4bab2d9a7ef76f8b4
| 139 |
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_liveapp_session'
| 34.75 | 77 | 0.805755 |
e92b162271716786e1294d0c81b277a0dc217660
| 2,513 |
require "hbc/artifact/base"
require "hbc/utils/hash_validator"
module Hbc
module Artifact
class Relocated < Base
def summary
{
english_description: self.class.english_description,
contents: @cask.artifacts[self.class.artifact_dsl_key].map(&method(:summarize_artifact)).compact,
}
end
attr_reader :source, :target
def printable_target
target.to_s.sub(/^#{ENV['HOME']}(#{File::SEPARATOR}|$)/, "~/")
end
ALT_NAME_ATTRIBUTE = "com.apple.metadata:kMDItemAlternateNames".freeze
# Try to make the asset searchable under the target name. Spotlight
# respects this attribute for many filetypes, but ignores it for App
# bundles. Alfred 2.2 respects it even for App bundles.
def add_altname_metadata(file, altname)
return if altname.casecmp(file.basename).zero?
odebug "Adding #{ALT_NAME_ATTRIBUTE} metadata"
altnames = @command.run("/usr/bin/xattr",
args: ["-p", ALT_NAME_ATTRIBUTE, file.to_s],
print_stderr: false).stdout.sub(/\A\((.*)\)\Z/, '\1')
odebug "Existing metadata is: '#{altnames}'"
altnames.concat(", ") unless altnames.empty?
altnames.concat(%Q("#{altname}"))
altnames = "(#{altnames})"
# Some packges are shipped as u=rx (e.g. Bitcoin Core)
@command.run!("/bin/chmod", args: ["--", "u+rw", file.to_s, file.realpath.to_s])
@command.run!("/usr/bin/xattr",
args: ["-w", ALT_NAME_ATTRIBUTE, altnames, file.to_s],
print_stderr: false)
end
def each_artifact
# the sort is for predictability between Ruby versions
@cask.artifacts[self.class.artifact_dsl_key].sort.each do |artifact|
load_specification(artifact)
yield
end
end
def load_specification(artifact_spec)
source_string, target_hash = artifact_spec
raise CaskInvalidError if source_string.nil?
@source = @cask.staged_path.join(source_string)
if target_hash
raise CaskInvalidError unless target_hash.respond_to?(:keys)
target_hash.extend(HashValidator).assert_valid_keys(:target)
@target = Hbc.send(self.class.artifact_dirmethod).join(target_hash[:target])
else
@target = Hbc.send(self.class.artifact_dirmethod).join(source.basename)
end
end
end
end
end
| 36.955882 | 118 | 0.616793 |
f8efbe77953f09c3ddf93d90f88e713ed4da9a52
| 2,480 |
# PLEASE DO NOT EDIT THIS CODE
# This code was generated using the UMPLE 1.31.1.5860.78bb27cc6 modeling language!
# NOTE: Ruby generator is experimental and is missing some features available in
# in other Umple generated languages like Java or PHP
module CruiseAttributesTest
require 'time'
require 'date'
class MoreTypeInference
#------------------------
# MEMBER VARIABLES
#------------------------
#MoreTypeInference Attributes - for documentation purposes
#attr_reader :a, :b, :c, :d, :e, :f, :g, :h, :i, :j, :k, :l
#------------------------
# CONSTRUCTOR
#------------------------
def initialize(a_b, a_h)
@initialized = false
@deleted = false
@a = Time.parse("12:12:12")
@b = a_b
@c = "12:12"
@d = Time.parse("12:12:12")
@e = "99:99:99"
@f = "2000:01:01"
@g = Date.parse("2000-01-01")
@h = a_h
@i = "2000-01"
@j = "2000:01:01"
@k = Date.parse("2000-01-01")
@l = new Object()
@initialized = true
end
#------------------------
# INTERFACE
#------------------------
def set_a(a_a)
was_set = false
@a = a_a
was_set = true
was_set
end
def set_b(a_b)
was_set = false
@b = a_b
was_set = true
was_set
end
def set_c(a_c)
was_set = false
@c = a_c
was_set = true
was_set
end
def set_d(a_d)
was_set = false
@d = a_d
was_set = true
was_set
end
def set_e(a_e)
was_set = false
@e = a_e
was_set = true
was_set
end
def set_f(a_f)
was_set = false
@f = a_f
was_set = true
was_set
end
def set_g(a_g)
was_set = false
@g = a_g
was_set = true
was_set
end
def set_h(a_h)
was_set = false
@h = a_h
was_set = true
was_set
end
def set_i(a_i)
was_set = false
@i = a_i
was_set = true
was_set
end
def set_j(a_j)
was_set = false
@j = a_j
was_set = true
was_set
end
def set_k(a_k)
was_set = false
@k = a_k
was_set = true
was_set
end
def set_l(a_l)
was_set = false
@l = a_l
was_set = true
was_set
end
def get_a
@a
end
def get_b
@b
end
def get_c
@c
end
def get_d
@d
end
def get_e
@e
end
def get_f
@f
end
def get_g
@g
end
def get_h
@h
end
def get_i
@i
end
def get_j
@j
end
def get_k
@k
end
def get_l
@l
end
def delete
@deleted = true
end
end
end
| 13.551913 | 82 | 0.529839 |
e8eaf997be9a8958ae4a98ca9ccc0f44a06b9782
| 989 |
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "ai_view_tool/version"
Gem::Specification.new do |spec|
spec.name = "ai_view_tool"
spec.version = AiViewTool::VERSION
spec.authors = ["Shashi Singh"]
spec.email = ["[email protected]"]
spec.summary = %q{Various view specific methods for applications we use.}
spec.description = %q{Provides generated HTML data for Rails applications.}
spec.homepage = "http://shashikashyap.com"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.16"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
end
| 35.321429 | 81 | 0.649141 |
79207b3250c63b25aec511dd40c4a5cbaa021a7b
| 1,670 |
# encoding: utf-8
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# /spec/fixtures/responses/whois.nic.hu/schema-1.99/property_contact_private_person.expected
#
# and regenerate the tests with the following rake task
#
# $ rake spec:generate
#
require 'spec_helper'
require 'whois/record/parser/whois.nic.hu.rb'
describe Whois::Record::Parser::WhoisNicHu, "property_contact_private_person.expected" do
before(:each) do
file = fixture("responses", "whois.nic.hu/schema-1.99/property_contact_private_person.txt")
part = Whois::Record::Part.new(:body => File.read(file))
@parser = klass.new(part)
end
describe "#registrant_contacts" do
it do
@parser.registrant_contacts.should be_a(Array)
@parser.registrant_contacts[0].should be_a(_contact)
@parser.registrant_contacts[0].type.should == Whois::Record::Contact::TYPE_REGISTRANT
@parser.registrant_contacts[0].id.should == nil
@parser.registrant_contacts[0].name.should =~ /Buruzs/
@parser.registrant_contacts[0].organization.should == nil
@parser.registrant_contacts[0].address.should == nil
@parser.registrant_contacts[0].city.should == nil
@parser.registrant_contacts[0].zip.should == nil
@parser.registrant_contacts[0].state.should == nil
@parser.registrant_contacts[0].country_code.should == nil
@parser.registrant_contacts[0].phone.should == nil
@parser.registrant_contacts[0].fax.should == nil
@parser.registrant_contacts[0].email.should == nil
end
end
end
| 38.837209 | 99 | 0.68982 |
e9a9374705c8671952d0419c74b8c203cbdabbb2
| 121 |
class AddPostionToBooks < ActiveRecord::Migration[6.0]
def change
add_column :books, :position, :integer
end
end
| 20.166667 | 54 | 0.743802 |
bfdbde935cb952d5de02224dfe06ed78ecdbd656
| 543 |
RSpec.describe 'ItemReuslt' do
let(:item_dummy) { Struct.new(:number, :html_url, :title) }
let(:item) { item_dummy.new('5', 'http:hogehoge', 'title') }
let(:item_result) { PrGet::ItemResult.new(item) }
describe '#number' do
subject(:number) { item_result.number }
it { is_expected.to eq '5' }
end
describe '#url' do
subject(:url) { item_result.url }
it { is_expected.to eq 'http:hogehoge' }
end
describe '#title' do
subject(:title) { item_result.title }
it { is_expected.to eq 'title' }
end
end
| 22.625 | 62 | 0.639042 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.