blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
4
137
path
stringlengths
2
355
src_encoding
stringclasses
31 values
length_bytes
int64
11
3.9M
score
float64
2.52
5.47
int_score
int64
3
5
detected_licenses
listlengths
0
49
license_type
stringclasses
2 values
text
stringlengths
11
3.93M
download_success
bool
1 class
e25470b55a093b8106814fb132279e53a403c13b
Ruby
stek29/bmstu-prog
/Sem3/lr7/p2/test_int_num.rb
UTF-8
761
2.75
3
[ "Unlicense" ]
permissive
require 'minitest/autorun' require_relative 'int_num' # IntNum tests class TestIntNum < Minitest::Test POSITIVE = 42 NEGATIVE = -228 def setup @int_num_positive = IntNum.new POSITIVE @int_num_negative = IntNum.new NEGATIVE end def test_n_digits assert_equal 2, @int_num_positive.int_n_digits assert_equal 3, @int_num_negative.int_n_digits end def test_attr assert_equal POSITIVE, @int_num_positive.int assert_equal NEGATIVE, @int_num_negative.int end def test_do_puts assert_output(/#{POSITIVE.to_s}/) do @int_num_positive.do_puts end assert_output(/#{NEGATIVE.to_s}/) do @int_num_negative.do_puts end end def test_duck_init assert_equal 123, IntNum.new('123').int end end
true
1a9c69225d1e85634ef6960c9a38a0ae3f9b6007
Ruby
Gazer/rbbcode
/lib/rbbcode/tree_maker.rb
UTF-8
12,679
3.171875
3
[ "MIT" ]
permissive
require 'pp' module RbbCode module CharCodes CR_CODE = 13 LF_CODE = 10 L_BRACK_CODE = 91 R_BRACK_CODE = 93 SLASH_CODE = 47 LOWER_A_CODE = 97 LOWER_Z_CODE = 122 UPPER_A_CODE = 65 UPPER_Z_CODE = 90 end class Node def << (child) @children << child end attr_accessor :children def initialize(parent) @parent = parent @children = [] end attr_accessor :parent end class RootNode < Node def initialize @children = [] end end class TextNode < Node undef_method '<<'.to_sym undef_method :children def initialize(parent, text) @parent = parent @text = text end attr_accessor :text def to_bb_code @text end end class TagNode < Node def self.from_opening_bb_code(parent, bb_code) if equal_index = bb_code.index('=') tag_name = bb_code[1, equal_index - 1] value = bb_code[(equal_index + 1)..-2] else tag_name = bb_code[1..-2] value = nil end new(parent, tag_name, value) end def initialize(parent, tag_name, value = nil) super(parent) @tag_name = tag_name.downcase @value = value @preformatted = false end def inner_bb_code @children.inject('') do |output, child| output << child.to_bb_code end end def preformat! @preformatted = true end def preformatted? @preformatted end def to_bb_code if @value.nil? output = "[#{@tag_name}]" else output = "[#{@tag_name}=#{@value}]" end output << inner_bb_code << "[/#{@tag_name}]" end attr_reader :tag_name attr_reader :value end class TreeMaker include CharCodes def initialize(schema) @schema = schema end def make_tree(str) delete_junk_breaks!( delete_invalid_empty_tags!( parse_str(str) ) ) end protected def ancestor_list(parent) ancestors = [] while parent.is_a?(TagNode) ancestors << parent.tag_name parent = parent.parent end ancestors end def break_type(break_str) if break_str.length > 2 :paragraph elsif break_str.length == 1 :line_break elsif break_str == "\r\n" :line_break else :paragraph end end # Delete empty paragraphs and line breaks at the end of block-level elements def delete_junk_breaks!(node) node.children.reject! do |child| if child.is_a?(TagNode) and !node.is_a?(RootNode) if !child.children.empty? delete_junk_breaks!(child) false elsif child.tag_name == @schema.paragraph_tag_name # It's an empty paragraph tag true elsif @schema.block_level?(node.tag_name) and child.tag_name == @schema.line_break_tag_name and node.children.last == child # It's a line break a the end of the block-level element true else false end else false end end node end # The schema defines some tags that may not be empty. This method removes any such empty tags from the tree. def delete_invalid_empty_tags!(node) node.children.reject! do |child| if child.is_a?(TagNode) if child.children.empty? and [email protected]_may_be_empty?(child.tag_name) true else delete_invalid_empty_tags!(child) false end end end node end def parse_str(str) tree = RootNode.new # Initially, we open a paragraph tag. If it turns out that the first thing we encounter # is a block-level element, no problem: we'll be calling promote_block_level_elements # later anyway. current_parent = TagNode.new(tree, @schema.paragraph_tag_name) tree << current_parent current_token = '' current_token_type = :unknown current_opened = 0 # It may seem naive to use each_byte. What about Unicode? So long as we're using UTF-8, none of the # BB Code control characters will appear as part of multibyte characters, because UTF-8 doesn't allow # the range 0x00-0x7F in multibyte chars. As for the multibyte characters themselves, yes, they will # be temporarily split up as we append bytes onto the text nodes. But as of yet, I haven't found # a way that this could cause a problem. The bytes always come back together again. (It would be a problem # if we tried to count the characters for some reason, but we don't do that.) str.each_byte do |char_code| char = char_code.chr case current_token_type when :unknown case char when '[' current_token_type = :possible_tag current_token << char current_opened += 1 when "\r", "\n" current_token_type = :break current_token << char else if current_parent.is_a?(RootNode) new_paragraph_tag = TagNode.new(current_parent, @schema.paragraph_tag_name) current_parent << new_paragraph_tag current_parent = new_paragraph_tag end current_token_type = :text current_token << char end when :text case char when "[" if @schema.text_valid_in_context?(*ancestor_list(current_parent)) current_parent << TextNode.new(current_parent, current_token) end current_token = '[' current_token_type = :possible_tag current_opened += 1 when "\r", "\n" if @schema.text_valid_in_context?(*ancestor_list(current_parent)) current_parent << TextNode.new(current_parent, current_token) end current_token = char current_token_type = :break else current_token << char end when :break if char_code == CR_CODE or char_code == LF_CODE current_token << char else if break_type(current_token) == :paragraph while current_parent.is_a?(TagNode) and [email protected]_level?(current_parent.tag_name) and current_parent.tag_name != @schema.paragraph_tag_name current_parent = current_parent.parent end # The current parent might be a paragraph tag, in which case we should move up one more level. # Otherwise, it might be a block-level element or a root node, in which case we should not move up. if current_parent.is_a?(TagNode) and current_parent.tag_name == @schema.paragraph_tag_name current_parent = current_parent.parent end # Regardless of whether the current parent is a block-level element, we need to open a new paragraph. new_paragraph_node = TagNode.new(current_parent, @schema.paragraph_tag_name) current_parent << new_paragraph_node current_parent = new_paragraph_node else # line break prev_sibling = current_parent.children.last if prev_sibling.is_a?(TagNode) and @schema.block_level?(prev_sibling.tag_name) # Although the input only contains a single newline, we should # interpret is as the start of a new paragraph, because the last # thing we encountered was a block-level element. new_paragraph_node = TagNode.new(current_parent, @schema.paragraph_tag_name) current_parent << new_paragraph_node current_parent = new_paragraph_node elsif @schema.tag(@schema.line_break_tag_name).valid_in_context?(*ancestor_list(current_parent)) current_parent << TagNode.new(current_parent, @schema.line_break_tag_name) end end if char == '[' current_token = '[' current_token_type = :possible_tag current_opened += 1 else current_token = char current_token_type = :text end end when :possible_tag case char when '[' current_parent << TextNode.new(current_parent, '[') current_opened += 1 # No need to reset current_token or current_token_type, because now we're in a new possible tag when '/' current_token_type = :closing_tag current_token << '/' else if tag_name_char?(char_code) current_token_type = :opening_tag current_token << char else current_token_type = :text current_token << char end end when :opening_tag if tag_name_char?(char_code) or char == '=' current_token << char elsif char == '[' current_opened += 1 current_token << char elsif char == ']' current_opened -= 1 current_token << ']' if current_opened <= 0 tag_node = TagNode.from_opening_bb_code(current_parent, current_token) if @schema.block_level?(tag_node.tag_name) and current_parent.tag_name == @schema.paragraph_tag_name # If there is a line break before this, it's superfluous and should be deleted prev_sibling = current_parent.children.last if prev_sibling.is_a?(TagNode) and prev_sibling.tag_name == @schema.line_break_tag_name current_parent.children.pop end # Promote a block-level element current_parent = current_parent.parent tag_node.parent = current_parent current_parent << tag_node current_parent = tag_node # If all of this results in empty paragraph tags, no worries: they will be deleted later. elsif tag_node.tag_name == current_parent.tag_name and @schema.close_twins?(tag_node.tag_name) # The current tag and the tag we're now opening are of the same type, and this kind of tag auto-closes its twins # (E.g. * tags in the default config.) current_parent.parent << tag_node current_parent = tag_node elsif @schema.tag(tag_node.tag_name).valid_in_context?(*ancestor_list(current_parent)) current_parent << tag_node current_parent = tag_node end # else, don't do anything--the tag is invalid and will be ignored if @schema.preformatted?(current_parent.tag_name) current_token_type = :preformatted current_parent.preformat! else current_token_type = :unknown end current_token = '' end elsif char == "\r" or char == "\n" current_parent << TextNode.new(current_parent, current_token) current_token = char current_token_type = :break elsif current_token.include?('=') current_token << char else current_token_type = :text current_token << char end when :closing_tag if tag_name_char?(char_code) current_token << char elsif char == ']' original_parent = current_parent while current_parent.is_a?(TagNode) and current_parent.tag_name != current_token[2..-1].downcase current_parent = current_parent.parent end if current_parent.is_a?(TagNode) if !current_parent.parent.is_a?(RootNode) current_parent = current_parent.parent else new = TagNode.new(current_parent.parent, @schema.paragraph_tag_name) current_parent.parent << new current_parent = new end else # current_parent is a RootNode # we made it to the top of the tree, and never found the tag to close # so we'll just ignore the closing tag altogether current_parent = original_parent end current_token_type = :unknown current_token = '' current_opened -= 1 elsif char == "\r" or char == "\n" current_parent << TextNode.new(current_parent, current_token) current_token = char current_token_type = :break else current_token_type = :text current_token << char end when :preformatted if char == '[' current_parent << TextNode.new(current_parent, current_token) current_token_type = :possible_preformatted_end current_token = '[' else current_token << char end when :possible_preformatted_end current_token << char if current_token == "[/#{current_parent.tag_name}]" # Did we just see the closing tag for this preformatted element? current_parent = current_parent.parent current_token_type = :unknown current_token = '' elsif char == ']' # We're at the end of this opening/closing tag, and it's not the closing tag for the preformatted element current_parent << TextNode.new(current_parent, current_token) current_token_type = :preformatted current_token = '' end else raise "Unknown token type in state machine: #{current_token_type}" end end # Handle whatever's left in the current token if current_token_type != :break and !current_token.empty? current_parent << TextNode.new(current_parent, current_token) end tree end def tag_name_char?(char_code) (LOWER_A_CODE..LOWER_Z_CODE).include?(char_code) or (UPPER_A_CODE..UPPER_Z_CODE).include?(char_code) or char_code.chr == '*' end end end
true
9f6ef32bcb364aed9e7ab3ee3ca27357b18c27e9
Ruby
pschlatt/westeros
/app/models/house.rb
UTF-8
304
3
3
[]
no_license
class House attr_reader :houses, :name, :id def initialize(data = "") @houses = [ ['Stark', 'stark'], ['Lannister', 'lannister'], ['Targaryen', 'targaryen'], ['Tyrell', 'tyrell'], ['Greyjoy', 'greyjoy'] ] @name = data["name"] @id = data["id"] end end
true
176a96f54de57fa69875c355cfb2e34b8bab0ce0
Ruby
captainmarkos/tealeaf
/intro_to_programming/easy_questions/quiz1_1.rb
UTF-8
162
3.28125
3
[]
no_license
#!/usr/bin/env ruby -w numbers = [1, 2, 2, 3]; numbers.uniq puts "--> numbers: #{numbers}" # [1, 2, 2, 3] puts "--> numbers.uniq: #{numbers.uniq}" # [1, 2, 3]
true
ccf053adafab34dadac8e6dff4ae0ca248bc4599
Ruby
susanaAlcala/desafio_hashes
/desafio_hashes/d_2-4.rb
UTF-8
198
3.390625
3
[]
no_license
#2.4. Convertir el hash en un array y guardarlo en una nueva variable productos = {'bebida' => 850, 'chocolate' => 1200, 'galletas' => 900, 'leche' => 750} arr = [] arr = productos.to_a print arr
true
95be47701257c38b2700ed4597b0a83f453ddced
Ruby
MarkBorcherding/programming-exercises
/markov-chain/markov.rb
UTF-8
877
3.578125
4
[]
no_license
# class Markov attr_accessor :map def initialize self.map = {} end def train(words) words.each_cons(2) do |pair| if pair[0] =~ /[\.\?!]$/ transition pair[0], :end transition :start, pair[1] else transition *pair end end end def transition(from, to) map[from] ||= {} map[from][to] ||= 0 map[from][to] += 1 map[from][:count] ||= 0 map[from][:count] += 1 end def generate words = [] next_word = map[:start].keys.sample while next_word != :end do words << next_word next_word =next_word(words.last) end words.join " " end def next_word(w) choices = map[w] count = choices[:count].to_f choices.reject{ |c| c == :count }.reduce(rand) do |left,v| left = left - (v[1]/count) return v[0] if left < 0 left end end end
true
7c4408905dd3e87e859f9fe9a041abeb419520ee
Ruby
eric-johnson/slack-bot
/bot.rb
UTF-8
816
2.640625
3
[]
no_license
$LOAD_PATH.unshift( File.dirname(__FILE__) ) require "slack-ruby-bot" require "pry" require "blink_stick_controller" class PongBot < SlackRubyBot::Bot def self.stick @stick ||= BlinkStickController.new end command "ping" do |_client, data, _match| client.say(text: "pong", channel: data.channel) end command "pry me a river" do |client, data, _match| client.say(text: "Prying...", channel: data.channel) binding.pry client.say(text: "...Done Prying", channel: data.channel) end command "blink" do |client, data, match| begin color = stick.set_color( match[:expression] ) client.say( text: "##{color.hex}", channel: data.channel ) rescue StandardError => e client.say( text: [e.class, e.message], channel: data.channel ) end end end PongBot.run
true
15b15901ee6d5a3d0a0d716c37a0a9d221e75c0c
Ruby
alemosie/earthdata-search
/app/presenters/facets_presenter.rb
UTF-8
2,864
2.5625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class FacetsPresenter # Order matters in SCIENCE_KEYWORDS SCIENCE_KEYWORDS = ['topic', 'term', 'variable_level_1', 'variable_level_2', 'variable_level_3'] KEYWORD_CHILD = { 'topic' => 'term', 'term' => 'variable_level_1', 'variable_level_1' => 'variable_level_2', 'variable_level_2' => 'variable_level_3', 'variable_level_3' => nil } UNWANTED_FACETS = [ 'sensor', 'two_d_coordinate_system_name', 'archive_centers', 'detailed_variable' ] FACET_OPTIONS = { 'features' => { index: 0, param: 'features[]' }, 'science_keywords' => { index: 1, hierarchical: true, template: 'science_keywords[0][:param][]', root: { subfield: 'category', value: 'EARTH SCIENCE' }, order: [ 'topic', 'term', 'variable_level_1', 'variable_level_2', 'variable_level_3' ] } } IDS_TO_NAMES = { 'science_keywords' => 'Keywords', 'data_centers' => 'Organization', 'features' => 'Features' } def initialize(json_facets, query_string) # Hash of parameters to values where hashes and arrays in parameter names are not interpreted @query = query_string .gsub('%5B', '[') .gsub('%5D', ']') .split('&') .map {|kv| kv.split('=')} .group_by(&:first) @query.each do |k, v| @query[k] = v.map(&:last) end json_facets = exclude_unwanted_facets(Array.wrap(json_facets)) json_facets = add_fake_json_facets(json_facets) json_facets = order_facets(json_facets) @facets = json_facets.map { |json_facet| facet_for_json(json_facet, @query) } end def as_json @facets.map(&:as_json).compact end private def order_facets(json_facets) json_facets = json_facets.dup ordered_facets = FACET_OPTIONS.map do |id, options| [options[:index], id] end.compact.sort ordered_facets.each do |index, id| facet = json_facets.find {|json_facet| json_facet['field'] == id} if facet json_facets.delete(facet) json_facets.insert(index, facet) end end json_facets end def exclude_unwanted_facets(facets) facets.reject {|f| UNWANTED_FACETS.include?(f['field'])} end def add_fake_json_facets(json_facets) [{'field' => 'features', 'value-counts' => [ ['Map Imagery'], ['Subsetting Services'], ['Near Real Time']] }] + json_facets end def facet_for_json(json_facet, query) id = json_facet['field'] name = IDS_TO_NAMES[id] || id.humanize.capitalize.singularize options = FACET_OPTIONS[id] || {} if options[:hierarchical] HierarchicalFacetPresenter.new(id, name, json_facet, query, options) else FlatFacetPresenter.new(id, name, json_facet, query, options) end end end
true
8d735dc5c3c78cb058a77e69608dc3aa0cd6730e
Ruby
morganmiller/goober
/db/seeds.rb
UTF-8
1,458
2.6875
3
[]
no_license
class Seed def initialize create_riders create_drivers create_rides end def create_riders @rider = User.create(name: "Morgan", email: "[email protected]", phone_number: "7274216505", password: "password", password_confirmation: "password") end def create_drivers @driver = User.create(name: "Horace", email: "[email protected]", phone_number: "1234567890", password: "password", password_confirmation: "password", role: 1, car_make: "Jeep", car_model: "Cherokee", car_capacity: 4) end def create_rides ride = Ride.create!(pickup_address: "a place", dropoff_address: "a different place", num_passengers: 3, status: 1) ride2 = Ride.create!(pickup_address: "ride 2", dropoff_address: "ride 2 destination", num_passengers: 3, status: 3) ride3 = Ride.create!(pickup_address: "ride 3", dropoff_address: "ride 3 destination", num_passengers: 3, status: 3) ride4 = Ride.create!(pickup_address: "ride 4", dropoff_address: "ride 4 destination", num_passengers: 3, status: 3) end end Seed.new
true
0819534efc8c8d91e90010737e5f722cd4b54295
Ruby
Archaela7255/upperline-basic-sinatra-template
/app/models/sample_model.rb
UTF-8
21,767
2.828125
3
[]
no_license
def life_help(q1, q2) if q1 == "shelter" && q2 == "healthcare" "Here are some tips for when you're seeking shelter and basic amenities: <br> -Get a membership at your local gym and use their shower and bathrooms, they usually have free wifi as well and might even offer discounts for first time members. <br> -Ask for boiling water from a cafe, and use it for easy to prepare meals, like instant ramen and tea. <br> -Find a shelter. Homeless shelters provide a warm bed for the night, so it’s important to know when they open so you can wait in line. <br> -Remaining hopeful and having a positive outlook can be the very thing that gets you through it. <br> <br> Here are some tips for when you're seeking healthcare: <br> -If you are female, you can go to any Planned Parenthood or WIC around you; where they provide free services for women and children. They provide people with free birth control, pregnancy test, and doctor check-ins. <br> -Check your area for local clinics or programs that provide free or assisted health care and treatment. Many LGBTQ+ centers provide HIV testing as well as transgender clinics. <br> -Stock up on hand sanitizers, flu medicine, and cough drops to help ease sickness when you are unable to receive healthcare. <br> -Natural home remedies are also helpful in treating certain conditions one may have, if one is unable to receive healthcare (Arnica is particularly known to aid in the healing of blunt force trauma and broken bones)." elsif q1 == "shelter" && q2 == "employment" "Here are some tips for when you're seeking shelter and basic amenities: <br> -Get a membership at your local gym and use their shower and bathrooms, they usually have free wifi as well and might even offer discounts for first time members. <br> -Ask for boiling water from a cafe, and use it for easy to prepare meals, like instant ramen and tea. <br> -Find a shelter. Homeless shelters provide a warm bed for the night, so it’s important to know when they open so you can wait in line. <br> -Remaining hopeful and having a positive outlook can be the very thing that gets you through it. <br> <br> Here are some tips for when you're seeking employment: <br> -If you have a car consider signing up for uber or lyft. They are companies that pay you to drive and you can work at your own time. <br> -Create a resume to be prepared for any open job positions that may come your way. It is important to always be prepared. <br> -Look online and in newspaper ads to find places that are hiring to increase your chance of getting employed. <br> -Even if you feel desperate, try not to show it. Employers will hire people that they think will contribute a lot to the job because they want to, not just because they have no other options." elsif q1 == "shelter" && q2 == "education" "Here are some tips for when you're seeking shelter and basic amenities: <br> -Get a membership at your local gym and use their shower and bathrooms, they usually have free wifi as well and might even offer discounts for first time members. <br> -Ask for boiling water from a cafe, and use it for easy to prepare meals, like instant ramen and tea. <br> -Find a shelter, homeless shelters provide a warm bed for the night, so it’s important to know when they open so you can wait in line. <br> -Remaining hopeful and having a positive outlook can be the very thing that gets you through it. <br> <br> Here are some tips for when you're seeking education: <br> -Take college classes online for free at coursera.org <br> -Set goals and standards for yourself to complete and execute them by signing up for classes, going to free workshops to better your scope of knowledge. It is important to Invest in your schooling. <br> -Research programs that are nonprofit, this will help you find a mentor or counselor to help guide you. <br> -If you have the opportunity to dedicate yourself and a majority of your time to your education, don’t be afraid to apply for student loans." elsif q1 == "healthcare" && q2 == "shelter" "Here are some tips for when you're seeking healthcare: <br> -If you are female, you can go to any planned parenthood around you; where they provide free services for women. They provide people with free birth control, pregnancy test, and doctor check-ins. <br> -Check your area for local clinics or programs that provide free or assisted health care and treatment. Many LGBTQ+ centers provide HIV testing as well as transgender clinics. <br> -Stock up on hand sanitizers, flu medicine, and cough drops to help ease sickness when you are unable to receive healthcare. <br> -Natural home remedies are also helpful in treating certain conditions one may have, if one is unable to receive healthcare (Arnica is particularly known to aid in the healing of blunt force trauma and broken bones). <br> <br> Here are some tips for when you're seeking shelter and basic amenities: <br> -Get a membership at your local gym and use their shower and bathrooms, they usually have free wifi as well and might even offer discounts for first time members. <br> -Ask for boiling water from a cafe, and use it for easy to prepare meals, like instant ramen and tea. <br> -Find a shelter, homeless shelters provide a warm bed for the night, so it’s important to know when they open so you can wait in line. <br> -Remaining hopeful and having a positive outlook can be the very thing that gets you through it." elsif q1 == "healthcare" && q2 == "employment" "Here are some tips for when you're seeking healthcare: <br> -If you are female, you can go to any planned parenthood around you; where they provide free services for women. They provide people with free birth control, pregnancy test, and doctor check-ins. <br> -Check your area for local clinics or programs that provide free or assisted health care and treatment. Many LGBTQ+ centers provide HIV testing as well as transgender clinics. <br> -Stock up on hand sanitizers, flu medicine, and cough drops to help ease sickness when you are unable to receive healthcare. <br> -Natural home remedies are also helpful in treating certain conditions one may have, if one is unable to receive healthcare (Arnica is particularly known to aid in the healing of blunt force trauma and broken bones). <br> <br> Here are some tips for when you're seeking employment: <br> -Get a membership at your local gym and use their shower and bathrooms, they usually have free wifi as well and might even offer discounts for first time members. <br> -Ask for boiling water from a cafe, and use it for easy to prepare meals, like instant ramen and tea. <br> -Find a shelter, homeless shelters provide a warm bed for the night, so it’s important to know when they open so you can wait in line. <br> -Remaining hopeful and having a positive outlook can be the very thing that gets you through it." elsif q1 == "healthcare" && q2 == "education" "Here are some tips for when you're seeking healthcare: <br> -If you are female, you can go to any planned parenthood around you; where they provide free services for women. They provide people with free birth control, pregnancy test, and doctor check-ins. <br> -Check your area for local clinics or programs that provide free or assisted health care and treatment. Many LGBTQ+ centers provide HIV testing as well as transgender clinics. <br> -Stock up on hand sanitizers, flu medicine, and cough drops to help ease sickness when you are unable to receive healthcare. <br> -Natural home remedies are also helpful in treating certain conditions one may have, if one is unable to receive healthcare (Arnica is particularly known to aid in the healing of blunt force trauma and broken bones). <br> <br> Here are some tips for when you're seeking education: <br> -Take college classes online for free at coursera.org <br> -Set goals and standards for yourself to complete and execute them by signing up for classes, going to free workshops to better your scope of knowledge. It is important to Invest in your schooling. <br> -Research programs that are nonprofit, this will help you find a mentor or counselor to help guide you. <br> -If you have the opportunity to dedicate yourself and a majority of your time to your education, don’t be afraid to apply for student loans." elsif q1 == "employment" && q2 == "shelter" "Here are some tips for when you're seeking employment: <br> -If you have a car consider signing up for uber or lyft. They are companies that pay you to drive and you can work at your own time. <br> -Create a resume to be prepared for any open job positions that may come your way. It is important to always be prepared. <br> -Look online and in newspaper ads to find places that are hiring to increase your chance of getting employed. <br> -Even if you feel desperate, try not to show it. Employers will hire people that they think will contribute a lot to the job because they want to, not just because they have no other options. <br> <br> Here are some tips for when you're seeking shelter and basic amenities: <br> -Get a membership at your local gym and use their shower and bathrooms, they usually have free wifi as well and might even offer discounts for first time members. <br> -Ask for boiling water from a cafe, and use it for easy to prepare meals, like instant ramen and tea. <br> -Find a shelter, homeless shelters provide a warm bed for the night, so it’s important to know when they open so you can wait in line. <br> -Remaining hopeful and having a positive outlook can be the very thing that gets you through it." elsif q1 == "employment" && q2 == "healthcare" "Here are some tips for when you're seeking employment: <br> -If you have a car consider signing up for uber or lyft. They are companies that pay you to drive and you can work at your own time. <br> -Create a resume to be prepared for any open job positions that may come your way. It is important to always be prepared. <br> -Look online and in newspaper ads to find places that are hiring to increase your chance of getting employed. <br> -Even if you feel desperate, try not to show it. Employers will hire people that they think will contribute a lot to the job because they want to, not just because they have no other options. <br> <br> Here are some tips for when you're seeking healthcare: <br> -If you are female, you can go to any planned parenthood around you; where they provide free services for women. They provide people with free birth control, pregnancy test, and doctor check-ins. <br> -Check your area for local clinics or programs that provide free or assisted health care and treatment. Many LGBTQ+ centers provide HIV testing as well as transgender clinics. <br> -Stock up on hand sanitizers, flu medicine, and cough drops to help ease sickness when you are unable to receive healthcare. <br> -Natural home remedies are also helpful in treating certain conditions one may have, if one is unable to receive healthcare (Arnica is particularly known to aid in the healing of blunt force trauma and broken bones)." elsif q1 == "employment" && q2 == "education" "Here are some tips for when you're seeking employment: <br> -If you have a car consider signing up for uber or lyft. They are companies that pay you to drive and you can work at your own time. <br> -Create a resume to be prepared for any open job positions that may come your way. It is important to always be prepared. <br> -Look online and in newspaper ads to find places that are hiring to increase your chance of getting employed. <br> -Even if you feel desperate, try not to show it. Employers will hire people that they think will contribute a lot to the job because they want to, not just because they have no other options. <br> <br> Here are some tips for when you're seeking education: <br> -Take college classes online for free at coursera.org <br> -Set goals and standards for yourself to complete and execute them by signing up for classes, going to free workshops to better your scope of knowledge. It is important to Invest in your schooling. <br> -Research programs that are nonprofit, this will help you find a mentor or counselor to help guide you. <br> -If you have the opportunity to dedicate yourself and a majority of your time to your education, don’t be afraid to apply for student loans." elsif q1 == "education" && q2 == "shelter" "Here are some tips for when you're seeking education: <br> -Take college classes online for free at coursera.org <br> -Set goals and standards for yourself to complete and execute them by signing up for classes, going to free workshops to better your scope of knowledge. It is important to Invest in your schooling. <br> -Research programs that are nonprofit, this will help you find a mentor or counselor to help guide you. <br> -If you have the opportunity to dedicate yourself and a majority of your time to your education, don’t be afraid to apply for student loans. <br> <br> Here are some tips for when you're seeking shelter and basic amenities: <br> -Get a membership at your local gym and use their shower and bathrooms, they usually have free wifi as well and might even offer discounts for first time members. <br> -Ask for boiling water from a cafe, and use it for easy to prepare meals, like instant ramen and tea. <br> -Find a shelter, homeless shelters provide a warm bed for the night, so it’s important to know when they open so you can wait in line. <br> -Remaining hopeful and having a positive outlook can be the very thing that gets you through it." elsif q1 == "education" && q2 == "healthcare" "Here are some tips for when you're seeking education: <br> -Take college classes online for free at coursera.org <br> -Set goals and standards for yourself to complete and execute them by signing up for classes, going to free workshops to better your scope of knowledge. It is important to Invest in your schooling. <br> -Research programs that are nonprofit, this will help you find a mentor or counselor to help guide you. <br> -If you have the opportunity to dedicate yourself and a majority of your time to your education, don’t be afraid to apply for student loans. <br> <br> Here are some tips for when you're seeking healthcare: <br> -If you are female, you can go to any planned parenthood around you; where they provide free services for women. They provide people with free birth control, pregnancy test, and doctor check-ins. <br> -Check your area for local clinics or programs that provide free or assisted health care and treatment. Many LGBTQ+ centers provide HIV testing as well as transgender clinics. <br> -Stock up on hand sanitizers, flu medicine, and cough drops to help ease sickness when you are unable to receive healthcare. <br> -Natural home remedies are also helpful in treating certain conditions one may have, if one is unable to receive healthcare (Arnica is particularly known to aid in the healing of blunt force trauma and broken bones)." elsif q1 == "education" && q2 == "employment" "Here are some tips for when you're seeking education: <br> -Take college classes online for free at coursera.org <br> -Set goals and standards for yourself to complete and execute them by signing up for classes, going to free workshops to better your scope of knowledge. It is important to Invest in your schooling. <br> -Research programs that are nonprofit, this will help you find a mentor or counselor to help guide you. <br> -If you have the opportunity to dedicate yourself and a majority of your time to your education, don’t be afraid to apply for student loans. <br> <br> Here are some tips for when you're seeking employment: <br> -If you have a car consider signing up for uber or lyft. They are companies that pay you to drive and you can work at your own time. <br> -Create a resume to be prepared for any open job positions that may come your way. It is important to always be prepared. <br> -Look online and in newspaper ads to find places that are hiring to increase your chance of getting employed. <br> -Even if you feel desperate, try not to show it. Employers will hire people that they think will contribute a lot to the job because they want to, not just because they have no other options." else "Here are some tips for when you're seeking education: <br> -Take college classes online for free at coursera.org <br> -Set goals and standards for yourself to complete and execute them by signing up for classes, going to free workshops to better your scope of knowledge. It is important to Invest in your schooling. <br> -Research programs that are nonprofit, this will help you find a mentor or counselor to help guide you. <br> -If you have the opportunity to dedicate yourself and a majority of your time to your education, don’t be afraid to apply for student loans. <br> <br> Here are some tips for when you're seeking healthcare: <br> -If you are female, you can go to any planned parenthood around you; where they provide free services for women. They provide people with free birth control, pregnancy test, and doctor check-ins. <br> -Check your area for local clinics or programs that provide free or assisted health care and treatment. Many LGBTQ+ centers provide HIV testing as well as transgender clinics. <br> -Stock up on hand sanitizers, flu medicine, and cough drops to help ease sickness when you are unable to receive healthcare. <br> -Natural home remedies are also helpful in treating certain conditions one may have, if one is unable to receive healthcare (Arnica is particularly known to aid in the healing of blunt force trauma and broken bones). <br> <br> Here are some tips for when you're seeking shelter and basic amenities: <br> -Get a membership at your local gym and use their shower and bathrooms, they usually have free wifi as well and might even offer discounts for first time members. <br> -Ask for boiling water from a cafe, and use it for easy to prepare meals, like instant ramen and tea. <br> -Find a shelter, homeless shelters provide a warm bed for the night, so it’s important to know when they open so you can wait in line. <br> -Remaining hopeful and having a positive outlook can be the very thing that gets you through it. <br> <br> Here are some tips for when you're seeking employment: <br> -If you have a car consider signing up for uber or lyft. They are companies that pay you to drive and you can work at your own time. <br> -Create a resume to be prepared for any open job positions that may come your way. It is important to always be prepared. <br> -Look online and in newspaper ads to find places that are hiring to increase your chance of getting employed. <br> -Even if you feel desperate, try not to show it. Employers will hire people that they think will contribute a lot to the job because they want to, not just because they have no other options." end end
true
f64e63f8ae084093646c19575cb964ab55046503
Ruby
mcary/campfire-bot
/plugins/weather.rb
UTF-8
689
2.96875
3
[]
no_license
require 'yahoo-weather' class Weather < CampfireBot::Plugin on_command 'weather', :weather def weather(msg) city = { 'adelaide' => 'ASXX0001', 'brisbane' => 'ASXX0016', 'canberra' => 'ASXX0023', 'darwin' => 'ASXX0032', 'hobart' => 'ASXX0057', 'melbourne' => 'ASXX0075', 'perth' => 'ASXX0231', 'sydney' => 'ASXX0112' }[(msg[:message].split(' ')[1] || 'canberra').downcase] data = YahooWeather::Client.new.lookup_location(city, 'c') msg.speak("#{data.title} - #{data.condition.text}, #{data.condition.temp} deg C (high #{data.forecasts.first.high}, low #{data.forecasts.first.low})") end end
true
bdd7b3907741e1ba3c9694f938e42ff9ee3e3c4d
Ruby
vweythman/omnible
/app/models/prejudice.rb
UTF-8
2,185
2.53125
3
[]
no_license
# Prejudice # ================================================================================ # subpart of characters # # Table Variables # -------------------------------------------------------------------------------- # variable | type | about # -------------------------------------------------------------------------------- # id | integer | unique # character_id | integer | references character # identity_id | integer | references identity # fondness | integer | scale column # respect | integer | scale column # about | string | can be null # created_at | datetime | must be earlier or equal to updated_at # updated_at | datetime | must be later or equal to created_at # ================================================================================ class Prejudice < ActiveRecord::Base # VALIDATIONS # ------------------------------------------------------------ validates :identity_id, presence: true validates :fondness, presence: true validates :respect, presence: true # CALLBACKS # ------------------------------------------------------------ before_validation :find_identity, on: :create # ASSOCIATIONS # ------------------------------------------------------------ belongs_to :character, :inverse_of => :prejudices belongs_to :identity # ATTRIBUTES # ------------------------------------------------------------ attr_accessor :facet_id, :identity_name # PUBLIC METHODS # ------------------------------------------------------------ # RecipHeading - gives the heading for the recipient def recip_heading identity.name.titleize.pluralize end # Recip - identity that is being judged def recip self.identity end def identity_name unless identity.nil? @identity_name ||= self.identity.name end end def facet_id unless identity.nil? @facet_id ||= self.identity.facet_id end end # PRIVATE METHODS # ------------------------------------------------------------ private def find_identity self.identity = Identity.where(name: @identity_name, facet_id: @facet_id.to_i).first_or_create end end
true
7788ce720783a557611284ab091b602bfb876b2b
Ruby
bbensky/launch_school
/launch_school_lessons/120/120_small_problems/medium_1/10_poker.rb
UTF-8
4,718
4.15625
4
[]
no_license
require 'pry' class Card include Comparable RANKINGS = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace'].freeze attr_reader :rank, :suit def initialize(rank, suit) @rank = rank @suit = suit end def <=>(other_card) RANKINGS.index(@rank) <=> RANKINGS.index(other_card.rank) end def to_s "#{rank} of #{suit}" end end class Deck RANKS = (2..10).to_a + %w(Jack Queen King Ace).freeze SUITS = %w(Hearts Clubs Diamonds Spades).freeze def initialize generate_deck end def generate_deck @deck = [] SUITS.each do |suit| RANKS.each { |rank| @deck << Card.new(rank, suit) } end end def draw generate_deck if @deck.empty? @deck.shuffle!.pop end end class PokerHand def initialize(deck) @hand = [] 5.times { @hand << deck.draw } end def print @hand.each { |card| puts card } end def evaluate case when royal_flush? then 'Royal flush' when straight_flush? then 'Straight flush' when four_of_a_kind? then 'Four of a kind' when full_house? then 'Full house' when flush? then 'Flush' when straight? then 'Straight' when three_of_a_kind? then 'Three of a kind' when two_pair? then 'Two pair' when pair? then 'Pair' else 'High card' end end private def same_suit? @hand.all? { |card| card.suit == @hand.first.suit } end def n_of_a_kind(n) @hand.any? do |card| @hand.count { |hand_card| card.rank == hand_card.rank } == n end end def unique_rank(n) @hand.uniq( { |card| card.rank }).count == n end def royal_flush? @hand.all? do |card| [10, 'Jack', 'Queen', 'King', 'Ace'].include?(card.rank) && @hand.first.suit == card.suit end end def straight_flush? same_suit? && straight? end def four_of_a_kind? n_of_a_kind(4) end def full_house? n_of_a_kind(2) && n_of_a_kind(3) end def flush? same_suit? end def straight? sorted_hand = @hand.sort sorted_hand.each_with_index do |card, idx| unless idx == sorted_hand.size - 1 return false if (Card::RANKINGS.index(card.rank) + 1) != (Card::RANKINGS.index(sorted_hand[idx+1].rank)) end end end def three_of_a_kind? n_of_a_kind(3) && unique_rank(3) end def two_pair? n_of_a_kind(2) && unique_rank(3) end def pair? n_of_a_kind(2) && unique_rank(4) end end hand = PokerHand.new(Deck.new) hand.print puts hand.evaluate # Danger danger danger: monkey # patching for testing purposes. class Array alias_method :draw, :pop end # Test that we can identify each PokerHand type. hand = PokerHand.new([ Card.new(10, 'Hearts'), Card.new('Ace', 'Hearts'), Card.new('Queen', 'Hearts'), Card.new('King', 'Hearts'), Card.new('Jack', 'Hearts') ]) puts hand.evaluate == 'Royal flush' hand = PokerHand.new([ Card.new(8, 'Clubs'), Card.new(9, 'Clubs'), Card.new('Queen', 'Clubs'), Card.new(10, 'Clubs'), Card.new('Jack', 'Clubs') ]) puts hand.evaluate == 'Straight flush' hand = PokerHand.new([ Card.new(3, 'Hearts'), Card.new(3, 'Clubs'), Card.new(5, 'Diamonds'), Card.new(3, 'Spades'), Card.new(3, 'Diamonds') ]) puts hand.evaluate == 'Four of a kind' hand = PokerHand.new([ Card.new(3, 'Hearts'), Card.new(3, 'Clubs'), Card.new(5, 'Diamonds'), Card.new(3, 'Spades'), Card.new(5, 'Hearts') ]) puts hand.evaluate == 'Full house' hand = PokerHand.new([ Card.new(10, 'Hearts'), Card.new('Ace', 'Hearts'), Card.new(2, 'Hearts'), Card.new('King', 'Hearts'), Card.new(3, 'Hearts') ]) puts hand.evaluate == 'Flush' hand = PokerHand.new([ Card.new(8, 'Clubs'), Card.new(9, 'Diamonds'), Card.new(10, 'Clubs'), Card.new(7, 'Hearts'), Card.new('Jack', 'Clubs') ]) puts hand.evaluate == 'Straight' hand = PokerHand.new([ Card.new(3, 'Hearts'), Card.new(3, 'Clubs'), Card.new(5, 'Diamonds'), Card.new(3, 'Spades'), Card.new(6, 'Diamonds') ]) puts hand.evaluate == 'Three of a kind' hand = PokerHand.new([ Card.new(9, 'Hearts'), Card.new(9, 'Clubs'), Card.new(5, 'Diamonds'), Card.new(8, 'Spades'), Card.new(5, 'Hearts') ]) puts hand.evaluate == 'Two pair' hand = PokerHand.new([ Card.new(2, 'Hearts'), Card.new(9, 'Clubs'), Card.new(5, 'Diamonds'), Card.new(9, 'Spades'), Card.new(3, 'Diamonds') ]) puts hand.evaluate == 'Pair' hand = PokerHand.new([ Card.new(2, 'Hearts'), Card.new('King', 'Clubs'), Card.new(5, 'Diamonds'), Card.new(9, 'Spades'), Card.new(3, 'Diamonds') ]) puts hand.evaluate == 'High card'
true
632b5c5bfdbd2ef882fc0cfa530d2e52bc16102b
Ruby
dpholbrook/ruby_small_problems
/small_problems/debugging/5.rb
UTF-8
1,963
4.40625
4
[]
no_license
=begin We get a type error because when we call sum on remaining_cards we are trying to add numbers and symbols. We can fix this be saving the return value of the call to map which will give us an array of the values of the remaining cards. The sum is lower than it should be because every time we deal, we are popping cards off of each suit because eash suit is referencing the same array object. We need for the suits to reference different array objects which can be accomplished using clone. =end cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, :jack, :queen, :king, :ace] deck = { :hearts => cards.clone, :diamonds => cards.clone, :clubs => cards.clone, :spades => cards.clone } def score(card) case card when :ace then 11 when :king then 10 when :queen then 10 when :jack then 10 else card end end # Pick one random card per suit player_cards = [] deck.keys.each do |suit| cards = deck[suit] # cards is array of cards for each suit cards.shuffle! # cards for each suit are shuffled player_cards << cards.pop # one random card from each suit is dealt to the player end # Determine the score of the remaining cards in the deck # sum = deck.reduce(0) do |sum, (_, remaining_cards)| # remaining_cards.map! do |card| # we can mutate the array of remaining cards in each suit to their values in order to sum them on line 39 # score(card) # end sum = deck.reduce(0) do |sum, (_, remaining_cards)| suit_score = remaining_cards.map do |card| # alternatively, we could save the return value of the call to map (an array of scores) to a local variable suit_score and sum all of the suits scores score(card) end sum += suit_score.sum end total_sum = 4 * [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11].sum player_sum = player_cards.map { |card| score(card) }.sum puts "Total sum: #{total_sum}" puts "Player sum: #{player_sum}" puts "Sum: #{sum}" puts(sum == total_sum - player_sum) #=> false
true
9890323a266562e3c73693e9a451c56f0b9ad0f2
Ruby
Willardgmoore/practice
/5.rb
UTF-8
413
3.75
4
[]
no_license
#2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # #What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? result = 0 divisible_thru = 25 idx = divisible_thru idx1 = 1 while idx1 < (divisible_thru + 1) if idx % idx1 == 0 else idx += 1 idx1 = 1 end idx1 += 1 end puts idx #puts result
true
b0226a4204d7ffa6089536ccac8d6149868d7be9
Ruby
sekine126/crawling
/src/scraping_infoseek_source.rb
UTF-8
893
2.75
3
[]
no_license
require './src/object/anemone_crawl.rb' require 'optparse' require 'bundler' Bundler.require params = ARGV.getopts('d:') if params["d"] == nil puts "Error: Please set -d date option." exit(1) end if params["d"] != nil && params["d"].size != 8 puts "Error: -d is date. e.g. 20150214" exit(1) end my_crawl = AnemoneCrawl.new # スクレイピング先のURL # infoseek_headline_20xxxxxx.txtの内容は修正する必要がある # ・先頭に http://news.infoseek.co.jp # ・topics => article my_crawl.set_urls("./data/infoseek_headline_"+params["d"]+".txt") # スクレイピングする記事の日付 # 指定しなければ現在の日付 my_crawl.date = params["d"] # 取得するURLのXpathを設定 my_crawl.url_xpath = '//ul[@class="link-list"]//a' # セーブするファイルの名前 my_crawl.filename = "infoseek_source" # スクレイピング my_crawl.scrape_w
true
1ab8a442d227e33e28408e84bf3472588cef2d43
Ruby
geko727/Learn_to_Program
/14/profiler.rb
UTF-8
214
2.890625
3
[]
no_license
def profile block_description, &block profiling_on = false if profiling_on start_time = Time.new block.call duration = Time.new - start_time puts "#{block_description}: #{duration} seconds" else block.call end end
true
a0a4a3d8356637f65a4023523481326fbcee51d0
Ruby
ajosepha/command_line_classmates
/lib/student.rb
UTF-8
257
2.578125
3
[]
no_license
class Student attr_accessor :name, :twitter, :blog def initialize(name, twitter, blog) @name = name @twitter = twitter @blog = blog end end #hunger_games = Student.new("Katniss", "@dist12", "ihartzgale")
true
a094cd9a19548980c3cd39b0c2c0bd86a2777ed1
Ruby
NawarYossef/launch_school
/coding_challenges/permutation_step.rb
UTF-8
681
4.4375
4
[]
no_license
# Challenge : # Using the Ruby language, have the function PermutationStep(num) take the num parameter being passed and return the next number greater than num using the same digits. # For example: if num is 123 return 132, if it's 12453 return 12534. # If a number has no greater permutations, return -1 (ie. 999). # Solution : def PermutationStep(num) possibilities = [] possibilities = num.to_s.chars.map(&:to_i).permutation.to_a possibilities.reject! {|comb| comb.join.to_i <= num} possibilities.map! {|comb| comb.join.to_i} possibilities.empty? ? -1 : possibilities.min end PermutationStep(11121) PermutationStep(41352) PermutationStep(12453) PermutationStep(999)
true
3c1b3fada1831081001164d0095bb9bc426d64bf
Ruby
bibikhadiza/school-domain-wdf-000
/lib/school.rb
UTF-8
320
3.28125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class School attr_reader :roster def initialize(school) @school = school @roster = {} end def add_student(student, grade) if !@roster[grade] @roster[grade] = [] end @roster[grade]<< student end def grade(grade) @roster[grade] end def sort @roster.each {|grade, student| student.sort!} end end
true
651a0647e9578355d80d4f50381b09a5bbd69a8d
Ruby
dwijendraparashartech/robottestingat12nov
/app/models/robot.rb
UTF-8
2,925
3.046875
3
[]
no_license
class Robot include ActiveModel::Model attr_accessor :size_grid, :max_x, :max_y, :x, :y, :f, :commands, :report def initialize(params={}) @x = params[:x].try(:to_i) @y = params[:y].try(:to_i) @f = params[:f] || "" @size_grid = sanitize_size(params[:size_grid]) @max_x, @max_y = @size_grid.split('x').map(&:to_i) @commands = params[:commands] || "" @report = nil end def execute_commands! return unless check_if_robot_is_placed? commands = @commands.first.split(" ") + [@commands.last] commands.each_with_index do |command, index| placing_initial_coordinates(commands[index+1]) if command == "PLACE" case command when 'MOVE' move_into_new_position generate_report when 'LEFT' change_direction('LEFT') generate_report when 'RIGHT' change_direction('RIGHT') generate_report when 'REPORT' generate_report break end if self.isExists? end warning_message end def isExists? @x && @y && [email protected]? end private def check_if_robot_is_placed? if !self.isExists? && [email protected]?("PLACE") @x, @y = "" errors.add(:warning, 'You might need to place the robot first!') return false end return true end def placing_initial_coordinates(args) @x, @y, @f = args.split(',') @x = @x.to_i @y = @y.to_i end def move_into_new_position case @f when 'NORTH' @y = @y+1 unless (@y+1) > (@max_y - 1) when 'WEST' @x = @x-1 unless (@x-1) < 0 when 'SOUTH' @y = @y-1 unless (@y-1) < 0 when 'EAST' @x = @x+1 unless (@x+1) > (@max_x -1) end end def change_direction(direction) case @f when 'NORTH' @f = direction.eql?('LEFT') ? 'WEST' : 'EAST' when 'WEST' @f = direction.eql?('LEFT') ? 'SOUTH' : 'NORTH' when 'SOUTH' @f = direction.eql?('LEFT') ? 'EAST' : 'WEST' when 'EAST' @f = direction.eql?('LEFT') ? 'NORTH' : 'SOUTH' end end def generate_report @report = [@x, @y, @f] end def warning_message errors.add(:warning, 'Wrong direction! your robot is about to fall of..') unless check_warning end def check_warning case @f when "NORTH" return false when "WEST" return false if @x==0 when "EAST" return false if @x==@max_x-1 end if @y==@max_y-1 case @f when "SOUTH" return false when "WEST" return false if @x==0 when "EAST" return false if @x==@max_x-1 end if @y==0 return false if @x==@max_x-1 && @f == "EAST" return false if @x==0 && @f == "WEST" return true end def sanitize_size(size_grid) size_grid.to_s.match(/\dx\d/) ? size_grid : "5x5" end end
true
1e1245190d2ed8f2ac46df3a66f3470584b7bc5d
Ruby
danott/aces
/test/aces_test.rb
UTF-8
4,452
2.65625
3
[ "MIT" ]
permissive
require "test_helper" require "pry" class AcesTest < Minitest::Test class SuccessService include Aces::Service attr_reader :value def initialize(value) @value = value end def call success value: value end end class FailureService include Aces::Service attr_reader :value def initialize(value) @value = value end def call failure value: value end end class MalformedService include Aces::Service def call "return value is not an Aces::Result" end end def test_that_it_has_a_version_number refute_nil ::Aces::VERSION end def test_service_must_return_a_result assert_raises Aces::ResultMissing do MalformedService.call end end def test_service_result_shape value = "I am a return value!" SuccessService.call(value).tap do |success_service_result| assert_predicate success_service_result, :success? refute_predicate success_service_result, :failure? assert_equal value, success_service_result.value assert_raises(NoMethodError) { success_service_result.not_a_method } end FailureService.call(value).tap do |failure_service_result| refute_predicate failure_service_result, :success? assert_predicate failure_service_result, :failure? assert_equal value, failure_service_result.value assert_raises(NoMethodError) { failure_service_result.not_a_method } end end def test_configured_services value = "I am a return value!" configured_success_service = SuccessService.set( success: ->(result) { assert_equal value, result.value }, failure: ->(_result) { flunk "Should not be called" }, ) configured_failure_service = FailureService.set( success: ->(_result) { flunk "Should not be called" }, failure: ->(result) { assert_equal value, result.value }, ) assert_equal value, configured_success_service.call(value).value assert_equal value, configured_failure_service.call(value).value end def test_configured_services_force_you_to_handle assert_raises Aces::UnhandledResult do SuccessService.set(failure: ->(_result) { flunk "Should not be called" }).call(nil) end assert_raises Aces::UnhandledResult do FailureService.set(success: ->(_result) { flunk "Should not be called" }).call(nil) end end class CurriedService include Aces::Service def initialize(first, second, a:, b:) @first = first @second = second @a = a @b = b end def call success first: @first, second: @second, a: @a, b: @b end end def test_currying_args_as_a_theoretical_api prepared = CurriedService.set(success: :identity) prepared.set("first_position", b: "keyword_b") result = prepared.call("second_position", a: "keyword_a") assert_equal "first_position", result.first assert_equal "second_position", result.second assert_equal "keyword_a", result.a assert_equal "keyword_b", result.b end def test_currying_plus_composing_as_a_theoretical_api skip "None of these test services exist" calculate_tax = CalculateTax.set(subtotal_amount: item.amount, state: "TX") charge_card = ChargeCard.set(device: some_credit_card, subtotal_amount: item.amount) create_shipping_label = CreateShippingLabel.set(address: "wherever") # manual with explit post conditionals result = calculate_tax.call result = result.merge charge_card.call(taxes_amount: result.taxes_amount) if result.success? result = result.merge create_shipping_label.call if result.success? # or *magic* with procs? result = calculate_tax.call result = result.chain { charge_card.call(taxes_amount: result.taxes_amount) } result = result.chain { create_shipping_label.call } end def test_producing_cheap_services_from_lambdas cheap_service = Aces.lambda do |succeed, value:| succeed ? success(value: value) : failure(value: value) end result = cheap_service.call(true, value: 23) assert_predicate result, :success? assert_equal 23, result.value result = cheap_service.call(false, value: 42) refute_predicate result, :success? assert_equal 42, result.value cheap_malformed_service = Aces.lambda do |echo_value| echo_value end assert_raises Aces::ResultMissing do cheap_malformed_service.call "dunk" end end end
true
a917c959aa181fbbf8f19b8230a9b43b9ec4f0e6
Ruby
avk513/LaunchSchool
/hashes/ex_5.rb
UTF-8
298
3.640625
4
[]
no_license
#my solution =begin person = {name: 'Bob', occupation: 'web developer', hobbies: 'painting'} puts person.has_value?('Bob') =end #launchschool opposites = {positive: "negative", up: "down", right: "left"} #has_value? if opposites.has_value?("negative") puts "Got it!" else puts "Nope!" end
true
5da133de35ba2c5788c11b15f11899f1984e860b
Ruby
hillstew/mastermind
/mastermind.rb
UTF-8
621
3.1875
3
[]
no_license
require './lib/game' require './lib/sequence' puts "Welcome to Mastermind" puts "Would you like to (p)lay, read the (i)nstructions, or (q)uit?" print ">" response = gets.chomp sequence = Sequence.new @game = Game.new(sequence) if response == "p" # require 'pry'; binding.pry loop do puts @game.sequence.code puts "I have generated a beginner sequence with four elements made up of: (r)ed, (g)reen, (b)lue, and (y)ellow. Use (q)uit at any time to end the game." puts "What's your guess?" print ">" guess = gets.chomp puts @game.sequence.check_guess(guess) break if @game.sequence.guessed == true end
true
89f1d16d3b18722e7daff475591d23f6ea1ec774
Ruby
potapovDim/full
/ruby/po/editor/shared-tab/background/sub-menu.rb
UTF-8
1,252
2.625
3
[]
no_license
class SubMenu def initialize (browser) @browser = browser @color_tab = '[data-test="page-settings-tab-color"]' @image_tab = '[data-test="page-settings-tab-image"]' @gradient_tab = '[data-test="page-settings-tab-gradient"]' @active_tab = '.tabs__controlItem.active' end def swich_tab (tabname) puts get_active_tab case tabname when 'Color' if get_active_tab != 'Color' @browser.element(text: @color_tab).click end return ColorTab.new @browser when "Image" if get_active_tab != 'Image' @browser.element(css: @image_tab).click end return ImageTab.new @browser when 'Gradient' if get_active_tab != 'Gradient' @browser.element(css: @gradient_tab).click end return GradienTab.new @browser end end def get_active_tab return @browser.elements(css: @active_tab)[1].text end end
true
ffd7fb34bbdd1005d8acec14f62fc82d17ce7a71
Ruby
dianawhalen/archived_black_thursday
/lib/customer_repository.rb
UTF-8
834
2.90625
3
[]
no_license
class CustomerRepository attr_reader :path, :engine def initialize(path, engine) @path = path @engine = engine end def csv @csv ||= CSV.open(path, headers: true, header_converters: :symbol) end def all @all ||= csv.map do |row| Customer.new(row, self) end end def find_by_id(id) all.find do |customer| customer.id.to_i == id.to_i end end def find_all_by_first_name(first_name_fragment) all.find_all do |customer| customer.first_name.downcase.include?(first_name_fragment.to_s.downcase) end end def find_all_by_last_name(last_name_fragment) all.find_all do |customer| customer.last_name.downcase.include?(last_name_fragment.to_s.downcase) end end def inspect # "#<#{self.class} #{@merchants.size} rows>" end end
true
1da147cd8aa58ee8666ea740a45bc0f91642652a
Ruby
DGaffney/DonaldSentiment
/lib/report.rb
UTF-8
14,214
2.703125
3
[]
no_license
class Fixnum def nan? return false end def finite? return true end end class Report attr_accessor :raw_data def self.prev_month_query(time) {"$or" => TimeDistances.same_time_in_previous_month(time).collect{|x| {"time" => Hash[["$lte", "$gte"].zip(x)]}}} end def self.prev_days_query(time) {"$or" => TimeDistances.same_time_in_previous_days(time).collect{|x| {"time" => Hash[["$lte", "$gte"].zip(x)]}}} end def self.report_projection(content_type) if content_type == "comments" projection = {"time" => 1, "content.stats.comments" => 1} elsif content_type == "submissions" projection = {"time" => 1, "content.stats.submissions" => 1} elsif content_type == "subscribers" projection = {"time" => 1, "content.stats.subreddit_counts" => 1} elsif content_type == "domains" projection = {"time" => 1, "content.stats.domains" => 1} end projection end def self.reference_points(stats_obj, time, content_type) {prev_month: $client[:stats].find(self.prev_month_query(time)).projection(self.report_projection(content_type)).to_a, prev_day: $client[:stats].find(self.prev_days_query(time)).projection(self.report_projection(content_type)).to_a} end def self.report(time=Time.now, content_type="comments", reduction=false, width=60*60*24) results = {} time_int = TimeDistances.time_ten_minute(time) if reduction $client[:stats].find(time: {"$gte" => time_int-width, "$lte" => time_int}).projection(self.report_projection(content_type)).each do |time_point| results[time_point["time"]] = {observation: time_point, reference: self.reference_points(time_point, time_point["time"], content_type)} end else $client[:stats].find(time: {"$gte" => time_int-width, "$lte" => time_int}).each do |time_point| results[time_point["time"]] = {observation: time_point, reference: self.reference_points(time_point, time_int, content_type)} end end return results end def time_series ["10_minutes_past_day", "24_hours", "hour_days_past_month", "hours_in_week"] end def metrics ["karma_admin_deletion", "upvotes", "submissions", "comments", "submissions_authors", "comments_authors"] end def subreddit_count_analyses [:subscribers, :active_users, :active_percent] end def subreddit_count_stats(objects) Hash[subreddit_count_analyses.collect{|k| [k, self.send(k, objects)]}] end def subscribers(objects) objects.collect{|obj| obj["subscribers"]} end def active_users(objects) objects.collect{|obj| obj["active_users"]} end def active_percent(objects) objects.collect{|obj| obj["active_users"].to_f/obj["subscribers"]} end def common_analyses [:count, :distinct_count, :author_deleted_count, :admin_deleted_count, :author_deleted_time, :admin_deleted_time, :distinct_author_deleted_count, :distinct_admin_deleted_count, :author_karma_deletion, :admin_karma_deletion, :author_karma_deletion_speed, :admin_karma_deletion_speed] end def common_stats(objects) Hash[common_analyses.collect{|k| [k, self.send(k, objects)]}.collect{|k,v| [k, v.nan? ? 0 : v]}] end def count(objects) return objects.count end def distinct_count(objects) return objects.collect{|obj| obj[:author]}.uniq.count end def author_deleted_count(objects) return objects.select{|obj| !obj[:user_deleted_at].nil?}.count end def admin_deleted_count(objects) return objects.select{|obj| !obj[:admin_deleted_at].nil?}.count end def author_deleted_time(objects) return objects.collect{|obj| obj[:user_deleted_at]}.compact.average end def admin_deleted_time(objects) return objects.collect{|obj| obj[:admin_deleted_at]}.compact.average end def distinct_author_deleted_count(objects) return objects.select{|obj| !obj[:user_deleted_at].nil?}.collect{|obj| obj[:author]}.uniq.count end def distinct_admin_deleted_count(objects) return objects.select{|obj| !obj[:admin_deleted_at].nil?}.collect{|obj| obj[:author]}.uniq.count end #use abs val instead of raw score to account for net "disruptance" of deletions def author_karma_deletion(objects) return objects.select{|obj| !obj[:user_deleted_at].nil?}.collect{|obj| obj[:net_karma].abs}.sum end def admin_karma_deletion(objects) return objects.select{|obj| !obj[:admin_deleted_at].nil?}.collect{|obj| obj[:net_karma].abs}.sum end def author_karma_deletion_speed(objects) return objects.select{|obj| !obj[:user_deleted_at].nil?}.collect{|obj| obj[:net_karma].abs/obj[:user_deleted_at].to_f}.reject(&:nan?).select(&:finite?).average end def admin_karma_deletion_speed(objects) return objects.select{|obj| !obj[:admin_deleted_at].nil?}.collect{|obj| obj[:net_karma].abs/obj[:admin_deleted_at].to_f}.reject(&:nan?).select(&:finite?).average end def format_comments(query) objects = [] query.collect do |comment| sorted_updates = (comment["updated_info"]||[]).sort_by{|x| x["delay"].to_i} latest_update = sorted_updates.last || {} scored = sorted_updates.collect{|x| [x["ups"]||0, x["delay"]||0]}.reject{|x| x[1] > 1800} admin_deleted_at = sorted_updates.select{|x| x["admin_deleted"]}.first["delay"] rescue nil user_deleted_at = sorted_updates.select{|x| x["user_deleted"]}.first["delay"] rescue nil toplevel = comment["parent_id"].include?("t3_") ? true : false up_rate = (scored[1..-1]||[]).each_with_index.collect{|r, i| (r[0]-scored[i][0])/(r[1]-scored[i][1]).to_f}.average objects << {id: comment["id"], net_karma: latest_update["ups"].to_f, time: comment["created_utc"], up_rate: (up_rate.nan? || !up_rate.finite? ? 0 : up_rate), admin_deleted_at: admin_deleted_at, user_deleted_at: user_deleted_at, author: comment["author"], toplevel: toplevel, body: comment["body"]} end objects end def format_submissions(query) objects = [] query.collect do |submission| submission["updated_info"] ||= [] submission["updated_info"] << {"admin_deleted"=>false, "user_deleted"=>false, "ups"=>0, "gilded"=>0, "edited"=>false, "delay"=>0} if submission["updated_info"].empty? sorted_updates = (submission["updated_info"]||[]).sort_by{|x| x["delay"]} latest_update = sorted_updates.last || {} scored = sorted_updates.collect{|x| [x["ups"]||0, x["delay"]||0]}.reject{|x| x[1] > 1800} admin_deleted_at = sorted_updates.select{|x| x["admin_deleted"] || x["shadow_deleted"]}.first["delay"] rescue nil user_deleted_at = sorted_updates.select{|x| x["user_deleted"]}.first["delay"] rescue nil domain = URI.parse(submission["url"]).host rescue nil up_rate = (scored[1..-1]||[]).each_with_index.collect{|r, i| (r[0]-scored[i][0])/(r[1]-scored[i][1]).to_f}.average objects << {comment_count: latest_update["num_comments"], id: submission["id"], delay_count: scored.count, net_karma: latest_update["ups"].to_f, time: submission["created_utc"], up_rate: (up_rate.nan? || !up_rate.finite? ? 0 : up_rate), admin_deleted_at: admin_deleted_at, user_deleted_at: user_deleted_at, author: submission["author"], domain: domain} objects[-1][:up_rate] = 0 if objects[-1][:up_rate].nan? end # csv = CSV.open("counts.csv", "w") # objects.select{|x| x[:net_karma] != 0 && x[:delay_count] > 1}.each do |row| # csv << [Math.log(row[:net_karma]), Math.log(row[:up_rate])] # end;false # csv.close objects end def self.snapshot(time=Time.now) obj = self.new(time) obj.set_raw_data(time) obj.raw_data.merge({stats: obj.stats}) end def time_partition(time, objects) time_map = TimeDistances.time_bands(time) time_mapped_objects = {} object_references = {} objects.each do |object| time_map.each do |time_title, ranges| time_mapped_objects[time_title] ||= {} ranges.each do |range| time_mapped_objects[time_title][range.join(",")] ||= [] if object.keys.include?(:id) time_mapped_objects[time_title][range.join(",")] << object[:id] if object[:time] <= range[0] && object[:time] > range[1] object_references[object[:id]] = object else time_mapped_objects[time_title][range.join(",")] << object if object[:time] <= range[0] && object[:time] > range[1] end end end end if object_references.empty? return time_mapped_objects else return {map: time_mapped_objects, references: object_references} end end def initialize(time=Time.at(TimeDistances.time_ten_minute(Time.now)).utc.to_i, report_width=600) @report_width = report_width end def set_raw_data(time) range = [time, time-@report_width] @raw_data = { start_time: range.last, end_time: range.first, comments: format_comments(db_query(time, :reddit_comments)), submissions: format_submissions(db_query(time, :reddit_submissions)), authors: db_query(time, :reddit_authors).to_a, subreddit_counts: {raw: db_query(time, :subreddit_counts).to_a.first, diff: subscriber_count_diff(subscriber_query(time, :subreddit_counts), subscriber_query(time-@report_width*5, :subreddit_counts))}, domain_map: get_domains(time, db_query(time, :reddit_submissions)) };false end def subscriber_count_diff(cur_count, prev_count) active_pct = (cur_count["active_users"].to_f/cur_count["subscribers"]-prev_count["active_users"].to_f/prev_count["subscribers"]) sub_count = (cur_count["subscribers"]-prev_count["subscribers"])/((cur_count["time"]-prev_count["time"])/60/60.0) active_count = (cur_count["active_users"]-prev_count["active_users"])/((cur_count["time"]-prev_count["time"])/60/60.0) {subscriber_count: ((sub_count.nan? || !sub_count.finite?) ? 0 : sub_count), active_count: ((active_count.nan? || !active_count.finite?) ? 0 : active_count), active_pct: ((active_pct.nan? || !active_pct.finite?) ? 0 : active_pct)} end def stats { comments: get_comment_stats, submissions: get_submission_stats, subreddit_counts: get_subreddit_count_stats, domains: @raw_data[:domain_map] } end def get_comment_stats common_stats(@raw_data[:comments]) end def get_submission_stats common_stats(@raw_data[:submissions]) end def get_subreddit_count_stats @raw_data[:subreddit_counts] end def collection_field_query(collection) {reddit_comments: :created_utc, reddit_submissions: :created_utc, reddit_authors: [:last_submission_seen, :last_comment_seen], subreddit_counts: :time}[collection] end def projections(collection) Hash[{reddit_comments: [:id, :created_utc, :author, :ups, :parent_id, :id, :link_id, :body, :updated_info], reddit_submissions: [:id, :created_utc, :author, :ups, :url, :id, :link_id, :body, :updated_info, :num_comments, :url], reddit_authors: [:author, :comment_count, :last_comment_seen, :first_comment_seen, :submission_count, :last_submission_seen, :first_submission_seen], subreddit_counts: [:time, :subscribers, :active_users]}[collection].collect{|k| [k, 1]}] end def subscriber_query(time, collection) query = {collection_field_query(collection) => {"$lte" => time}} $client[collection].find(query, :sort => {'time' => -1}).projection(projections(collection)).first end def db_query(time, collection) range = [time, time-@report_width] if collection_field_query(collection).class == Array query = {"$or" => collection_field_query(collection).collect{|c| {c => {"$lte" => range.first, "$gte" => range.last}}}} else query = {collection_field_query(collection) => {"$lte" => range.first, "$gte" => range.last}} end $client[collection].find(query).projection(projections(collection)) end def get_domains(time, queries) host_counts = {} host_num_counts = {} host_karma_counts = {} db_query(time, :reddit_submissions).each do |submission| host = URI.parse(submission["url"]).host rescue nil next if host.nil? host_counts[host] ||= 0 host_num_counts[host] ||= 0 host_karma_counts[host] ||= 0 host_counts[host] += 1 host_num_counts[host] += ((submission["updated_info"].sort_by{|k| k["delay"]}.last["num_comments"] rescue 0)||0) host_karma_counts[host] += ((submission["updated_info"].sort_by{|k| k["delay"]}.last["ups"] rescue 0)||0) end Hash[$client[:domains].find(domain: {"$in" => host_counts.keys}).collect{|x| [x["domain"], x.merge("current_count" => host_counts[x["domain"]], "num_comment_count" => host_num_counts[x["domain"]], "karma_count" => host_karma_counts[x["domain"]])]}].to_a end def self.backfill(latest=Time.at(TimeDistances.time_ten_minute(Time.now)).utc.to_i, dist=60*60*24*7*3, window=60*10) cursor = latest while latest-dist < cursor CreateReport.perform_async(cursor) print "." cursor -= window end end def get_domain_scores domain_scores = {} i = 0 subs = [] $client[:reddit_submissions].find.collect do |submission| submission["updated_info"] ||= [] submission["updated_info"] << {"admin_deleted"=>false, "user_deleted"=>false, "ups"=>0, "gilded"=>0, "edited"=>false, "delay"=>0} if submission["updated_info"].empty? sorted_updates = (submission["updated_info"]||[]).sort_by{|x| x["delay"]} latest_update = sorted_updates.last || {} scored = sorted_updates.collect{|x| [x["ups"]||0, x["delay"]||0]}.reject{|x| x[1] > 1800} domain = URI.parse(submission["url"]).host rescue nil up_rate = (scored[1..-1]||[]).each_with_index.collect{|r, i| (r[0]-scored[i][0])/(r[1]-scored[i][1]).to_f}.average domain_scores[domain] ||= {num_comments: 0, net_karma: 0} domain_scores[domain][:num_comments] += latest_update["num_comments"].to_f domain_scores[domain][:net_karma] += latest_update["ups"].to_f print i if i % 10000 == 0 i += 1 end domain_scores end end #t = Time.now;gg = Report.snapshot;tt = Time.now;false #Time.now.strftime("%Y-%m-%d") #$client[:stats].drop #$client[:stats].indexes.create_one({ time: -1 }) #Report.backfill #Report.snapshot
true
c56d6bf6ece3e5961a7d05cbfc0b6b7123c0668b
Ruby
EDalSanto/dkvs
/lib/load_balancer.rb
UTF-8
1,822
2.890625
3
[]
no_license
# frozen_string_literal: true require "socket" require_relative "server" # accepts connections from clients for access to one of managed servers # distributes requests to a server using round robin class LoadBalancer LISTENING_SOCKET_PATH = "/tmp/dkvs_lb.sock" PRIMARY_SERVER_SOCKET_PATH = "/tmp/dkvs-primary-server.sock" REPLICA_SERVER_SOCKET_PATH = "/tmp/dkvs-replica-server.sock" attr_accessor :servers, :primary, :replica, :listening_socket def initialize(servers: []) self.primary = UNIXSocket.new(PRIMARY_SERVER_SOCKET_PATH) self.replica = UNIXSocket.new(REPLICA_SERVER_SOCKET_PATH) self.servers = [ primary, replica ] self.listening_socket = UNIXServer.new(LISTENING_SOCKET_PATH) end # accept connections from client processes def accept_connections loop do # socket open for clients # handle multiple client requests Thread.start(listening_socket.accept) do |client| yield(client) client.close end end end # send server request and get back response def distribute(request) promote_replica_to_primary if primary_not_available? return "Uh Oh, no primary" if primary.nil? if write?(request) send(primary, request) else send(random_server, request) end end def shut_down File.unlink(listening_socket.path) end private def promote_replica_to_primary # remove primary servers.shift self.primary = servers.first end def primary_not_available? begin primary.puts "PING" primary.gets # nada rescue Errno::EPIPE true else false end end def send(server, request) server.puts(request) server.gets.chomp end def random_server servers.sample end def write?(request) request.match(/SET/i) end end
true
eac1d9cce24bdad63e554ff8f46f9fcecd23c79a
Ruby
mralexsatur/boris-bikes-2
/lib/docking_station.rb
UTF-8
1,633
3.375
3
[]
no_license
require './lib/bike' require './lib/van' class DockingStation DEFAULT_CAPACITY = 10 attr_accessor :bikes def initialize(capacity = DEFAULT_CAPACITY) @bikes = [] @broken_bikes = [] @capacity = capacity end def working_bikes @bikes end def broken_bikes @broken_bikes end def release_bike raise "No bikes available" if empty? @bikes.pop end def dock(bike) raise "No more space" if full? @broken_bikes << bike if bike.bike_is_working? == false @bikes << bike if bike.bike_is_working? == true end def working_bikes_available @bikes.count == 0 end def empty? @bikes.count == 0 end def full? @bikes.count + @broken_bikes.count >= DEFAULT_CAPACITY end def count_working_bikes working_bikes = [] @bikes.each { |bike| working_bikes << bike if bike.bike_is_working?} working_bikes.count end def count_broken_bikes broken_bikes = [] @bikes.each { |bike| broken_bikes << bike if !bike.bike_is_working?} broken_bikes.count end def list_bikes bike_id = [] @bikes.each { |bike| bike_id << bike.to_s} end def unload_bikes(van) raise "Not enough space on van" if @broken_bikes.count > van.space_on_van until van.bikes.count == van.capacity van.bikes << @broken_bikes.pop end van.bikes.reverse end def van_capacity(van) van.capacity end def bike_count s = 's' s1 = 's' if @bikes.count == 1 s = '' end if @broken_bikes.count == 1 s1 = '' end "#{@bikes.count} working bike#{s}, #{@broken_bikes.count} broken bike#{s1}" end end
true
ae5cef7d94de9ada69649ba8a79e73e81176c536
Ruby
VIP-eDemocracy/elmo
/app/helpers/language_helper.rb
UTF-8
483
2.609375
3
[ "Apache-2.0" ]
permissive
module LanguageHelper # finds the english name of the language with the given code (e.g. 'French' for 'fr') # tries to use the translated locale name if it exists, otherwise use english language name from the iso639 gem # returns code itself if code not found def language_name(code) if configatron.full_locales.include?(code) I18n.t(:locale_name, :locale => code) else (entry = ISO_639.find(code.to_s)) ? entry.english_name : code.to_s end end end
true
5150e7ff2961cda872d7e99660eacc45d350debd
Ruby
pangland/PARC
/lib/associatable.rb
UTF-8
2,885
2.625
3
[]
no_license
require_relative 'searchable' require 'active_support/inflector' require 'byebug' class AssocOptions attr_accessor( :foreign_key, :class_name, :primary_key ) def model_class @class_name.to_s.constantize end def table_name @class_name.to_s.constantize.table_name end end class BelongsToOptions < AssocOptions def initialize(name, options = {}) class_name = name.to_s.singularize.underscore.camelcase.downcase @foreign_key = "#{class_name}_id".to_sym @primary_key = "id".to_sym @class_name = name.to_s.singularize.capitalize options.each do |k, v| instance_variable_set("@#{k.to_s}", v) end end end class HasManyOptions < AssocOptions def initialize(name, self_class_name, options = {}) class_name = self_class_name.to_s.singularize.underscore.camelcase.downcase @foreign_key = "#{class_name}_id".to_sym @primary_key = "id".to_sym @class_name = name.to_s.singularize.capitalize options.each do |k, v| instance_variable_set("@#{k.to_s}", v) end end end module Associatable def belongs_to(name, options = {}) self.assoc_options[name] = BelongsToOptions.new(name, options) options = self.assoc_options[name] define_method(name) do f_key = self.send(options.foreign_key) options.model_class.where(options.primary_key => f_key).first end end def has_many(name, options = {}) options = HasManyOptions.new(name, self.name, options) define_method(name) do options.model_class.where(options.foreign_key => self.send(options.primary_key)) end end def assoc_options @assoc_options ||= {} @assoc_options end def has_one_through(name, through_name, source_name) define_method(name) do through_query(through_name, source_name).first end end def has_many_through(name, through_name, source_name) define_method(name) do through_query(through_name, source_name) end end private def through_query(through_name, source_name) through_options = self.class.assoc_options[through_name] debugger source_options = through_options.model_class.assoc_options[source_name.to_sym] through_table = through_options.table_name source_table = source_options.table_name source_fkey = source_options.foreign_key source_pkey = source_options.primary_key through_pkey = through_options.primary_key through_fkey_val = self.send(through_options.foreign_key).to_s query = DBConnection.execute(<<-SQL,) SELECT #{source_table}.* FROM #{through_table} JOIN #{source_table} ON #{through_table}.#{source_fkey} = #{source_table}.#{source_pkey} WHERE #{through_table}.#{through_pkey} = #{through_fkey_val} SQL source_options.model_class.parse_all(query) end end class SQLObject extend Associatable include Associatable end
true
e97352c96f7d8c09a024a51affbb97f449b1d316
Ruby
Nashmeyah/school-domain-onl01-seng-ft-032320
/lib/school.rb
UTF-8
465
3.546875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class School #defines only the getter attr_reader :roster, :school # Create empty roster def initialize(school) @roster = {} @school = school end def add_student(student_name, grade) if !@roster[grade].is_a?(Array) @roster[grade] = [] end @roster[grade] << student_name end def grade(grade) @roster[grade] end def sort roster.map do |grade, name| @roster[grade] = name.sort end @roster end end
true
19a02d1bd26d6d98168f12345d013e6a2d044372
Ruby
luvalladares/tasks_app
/app/models/task.rb
UTF-8
353
2.59375
3
[]
no_license
class Task < ActiveRecord::Base attr_accessible :description, :priority validates_presence_of :description validates :priority, numericality: {greather_than:0} validates_uniqueness_of :description before_validation :clean_description private def clean_description if self.description.present? self.description.strip.capitalize! end end end
true
21b732082f4abe21b10ebcce7c42cbedc11f70a4
Ruby
AdManteza/ContactListApp
/contact_list.rb
UTF-8
2,291
3.6875
4
[]
no_license
#!/usr/bin/env ruby require_relative 'contact' require 'pry' # Interfaces between a user and their contact list. Reads from and writes to standard I/O. class ContactList # TODO: Implement user interaction. This should be the only file where you use `puts` and `gets`. def initialize self.display_menu if ARGV.size == 0 self.add_contact if ARGV[0] == 'new' self.display_list if ARGV[0] == 'list' self.show if ARGV[0] == 'show' && ARGV[1].size != 0 self.search if ARGV[0] == 'search' && ARGV[1].size != 0 end def add_contact puts "Add a Name" name = STDIN.gets.chomp puts "Add an email Address" email = STDIN.gets.chomp raise Contact::ExistingContactError, "Contact exists and cannot be created" if check_if_contact_exists?(email) Contact.new(name, email) end def display_list output_array = Contact.all puts output_array.size raise Contact::NonExistentRecordError, "No record found!" if output_array.size == 0 output_array.each_with_index do |row, index| puts "#{index+1}: #{row[0]} (#{row[1]})" end puts "-----------------------------" puts "#{output_array.size} records total" end def show id = ARGV[1] output_array = Contact.find(id) raise Contact::NonExistentRecordError, "No record found!" if output_array.size < id.to_i output_array.flatten! display_search_result(output_array) end def search name = ARGV[1] output_array = Contact.search(name) output_array.flatten! raise Contact::NonExistentRecordError, "No record found!" if output_array.include?(name) == false display_search_result(output_array) end def display_menu puts "Here is a list of available commands" puts " new - Create a new contact" puts " list - List all contacts" puts " show - Show a contact" puts " search - Search contacts" end def display_search_result(output_array) puts "Name: #{output_array[0]}" puts "Email: #{output_array[1]}" puts "-----------------------------" puts "#{output_array.size - 1} records total" end def check_if_contact_exists?(email) Contact.all.each do |row| return true if row.include?(email) end return false end end ContactList.new
true
d53cfb5e536b5e2b504a536c39b9a6f41d14de72
Ruby
abuhabuh/healthProj
/app/models/surgical_profile.rb
UTF-8
6,872
2.546875
3
[]
no_license
## # Surgical Profile # # Enumerated fields # - fields are: patient_status, elective_surgery_option, origin_status, # anesthesia_technique # - represented as integers [0 to n-1] in database and mapped to strings # # DB Table # - Encrypted Fields # - hospital_admission_date # - operation_date ## class SurgicalProfile < ActiveRecord::Base include EncryptionKey belongs_to :patient belongs_to :user has_one :preop_risk_assessment # Encryption attr_encrypted :hospital_admission_date, :key => :encryption_key attr_encrypted :operation_date, :key => :encryption_key # Static class variables # TODO: make interaction with this more graceful? Reduce hard coding # # IMPORTANT: do not change order of array constants, only append; # values tied to database entries indexed according to order @@PATIENT_STATUSES = %w(Inpatient Outpatient) @@ELECTIVE_SURGERY_OPTIONS = %w(Yes No Unknown) @@ORIGIN_STATUSES = [ 'Not Transferred, DA from home', 'Acute Care Facility (in-patient)', 'Nursing Home/ Chronic Care/Intermediate care', 'Transfer from Other', 'Transfer from outside ER', 'Unknown' ] @@ANESTHESIA_TECHNIQUES = [ 'General', 'Spinal', 'Epidural', 'Regional', 'Local', 'MAC/IV Sedation', 'None', 'Other', 'Unknown' ] @@RESULTS_LIMIT=10 #### # Validations #### #### # Static methods #### # return all surgical profiles that belong to surgeon def self.query_all_by_surgeon(surgeon) return SurgicalProfile.where(user: surgeon) end def self.query_all_by_surgeon_inc_patients( surgeon, page=1, limit=@@RESULTS_LIMIT) return SurgicalProfile.where(user: surgeon).includes(:patient) .paginate(:page => page, :per_page => limit) end # Returns all surgical profiles associated with patient def self.query_all_by_patient_id(surgeon, patient_id) if surgeon.is_admin() return SurgicalProfile.where( surgical_profiles: {patient_id: patient_id} ) else surgical_profiles = SurgicalProfile.where(surgical_profiles: {user_id: surgeon.id}) .where(surgical_profiles: {patient_id: patient_id}) return surgical_profiles end end def self.query_all_by_patient_id_inc_patients( surgeon, patient_id, page=1, limit=@@RESULTS_LIMIT) if surgeon.is_admin() return SurgicalProfile.where( surgical_profiles: {patient_id: patient_id}) .includes(:patient) .paginate(:page => page, :per_page => limit) else surgical_profiles = SurgicalProfile.where(surgical_profiles: {user_id: surgeon.id}) .where(surgical_profiles: {patient_id: patient_id}) .includes(:patient) .paginate(:page => page, :per_page => limit) return surgical_profiles end end # Returns surgical profile if it's viewable by current signed in user # Exception is raised if not viewable def self.query_one_by_id(surgeon, surgical_profile_id) if surgeon.is_admin() return SurgicalProfile.find(surgical_profile_id) else surgical_profile = SurgicalProfile.where(surgical_profiles: {id: surgical_profile_id}) .where(surgical_profiles: {user_id: surgeon.id}) .first if surgical_profile.nil? raise CanCan::AccessDenied.new( "Not authorized to view this surgical profile data!", :read, SurgicalProfile ) end return surgical_profile end end # return static constants arrays def self.get_patient_statuses return @@PATIENT_STATUSES end def self.get_elective_surgery_options return @@ELECTIVE_SURGERY_OPTIONS end def self.get_origin_statuses return @@ORIGIN_STATUSES end def self.get_anesthesia_techniques return @@ANESTHESIA_TECHNIQUES end def self.get_patient_status_by_index(index) if index.between?(0, @@PATIENT_STATUSES.length - 1) return @@PATIENT_STATUSES[index] end return '' end def self.get_elective_surgery_option_by_index(index) if index.between?(0, @@ELECTIVE_SURGERY_OPTIONS.length - 1) return @@ELECTIVE_SURGERY_OPTIONS[index] end return '' end def self.get_origin_status_by_index(index) if index.between?(0, @@ORIGIN_STATUSES.length - 1) return @@ORIGIN_STATUSES[index] end return '' end def self.get_anesthesia_technique_by_index(index) if index.between?(0, @@ANESTHESIA_TECHNIQUES.length - 1) return @@ANESTHESIA_TECHNIQUES[index] end return '' end # return static constant nested arrays for selector that includes # select option value and text # - [[Inpatient ,0], [Outpatient, 1] -> text is mapped to index # in the static constants array def self.get_patient_statuses_select return self.get_patient_statuses.map.with_index{|x,i| [x,i]} end def self.get_elective_surgery_options_select return self.get_elective_surgery_options.map.with_index{|x,i| [x,i]} end def self.get_origin_statuses_select return self.get_origin_statuses.map.with_index{|x,i| [x,i]} end def self.get_anesthesia_techniques_select return self.get_anesthesia_techniques.map.with_index{|x,i| [x,i]} end #### # Instance methods #### # Wrapper for save function that transforms date attributes to # string for encryption def preprocess_and_save process_attrs_before_write(self) return self.save() end # Wrapper for update function that transforms date attributes to # string for encryption def preprocess_and_update(surgical_profile_params) process_attrs_before_write_params(surgical_profile_params) return self.update(surgical_profile_params) end private ### # Instance methods ### # Convert certain attrs for write to DB (due to encryption needs) def process_attrs_before_write(surgical_profile) if surgical_profile.hospital_admission_date surgical_profile.hospital_admission_date = surgical_profile.hospital_admission_date.to_s end if surgical_profile.operation_date surgical_profile.operation_date = surgical_profile.operation_date.to_s end end # Convert certain attrs for write to DB (due to encryption needs) def process_attrs_before_write_params(surgical_profile_params) if surgical_profile_params[:hospital_admission_date].present? surgical_profile_params[:hospital_admission_date] = surgical_profile_params[:hospital_admission_date].to_s end if surgical_profile_params[:operation_date].present? surgical_profile_params[:operation_date] = surgical_profile_params[:operation_date].to_s end end end
true
2491726b2a0006c57755fefa7034f9350d10023d
Ruby
markmcspadden/the_perfect_ruby_code_sample
/test_me_maybe?/test_me_maybe?.rb
UTF-8
1,219
3.078125
3
[]
no_license
class BaseTest def self.tests @tests ||= [] end def self.output end end @test_class = nil def hey!(class_name=Object) fork do `afplay "#{File.dirname(__FILE__)}/song.m4a"` end puts "Testing #{class_name}" puts "Hey!" test_class_name = "#{class_name}Test" @test_class = Object.const_set(test_class_name, Class.new(BaseTest)) yield puts "Summary: #{@test_class.tests.size} Tests | #{@test_class.tests.reject{ |t| t.last }.size} errors" Object.send(:remove_const, test_class_name.to_sym) end def i_just(context) puts " I just #{context}" yield end def this_is(objective) puts " -- This is: #{objective}" yield passed = false passed = yield if passed puts " Passed" else puts " FAILED" end @test_class.tests << [objective, passed] end def heres_my_number puts "Here's My Number" yield end def assert_me_maybe? puts "Assert Me Maybe?" yield end def call_me_maybe? puts "Call Me Maybe?" end def since(event_string) puts "Since #{event_string}" yield end def i_miss_you_so_bad #puts "PENDING" puts "I miss you so bad" end def i_miss_you_so_so_bad #puts "PENDING AND WILL FAIL" puts "I miss you so so bad" end
true
8148ad2c7e0f5e0eb9ef471ba82fbe38e8148cc4
Ruby
brownmike/project-euler
/24.rb
UTF-8
3,345
4.1875
4
[]
no_license
# Lexicographic permutations # Problem 24 # A permutation is an ordered arrangement of objects. For example, 3124 is one # possible permutation of the digits 1, 2, 3 and 4. If all of the permutations # are listed numerically or alphabetically, we call it lexicographic order. The # lexicographic permutations of 0, 1 and 2 are: # 012 021 102 120 201 210 # What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, # 5, 6, 7, 8 and 9? # The following algorithm generates the next permutation lexicographically after # a given permutation. It changes the given permutation in-place. # # 1) Find the largest index k such that a[k] < a[k + 1]. If no such index # exists, the permutation is the last permutation. # 2) Find the largest index l such that a[k] < a[l]. # 3) Swap the value of a[k] with that of a[l]. # 4) Reverse the sequence from a[k + 1] up to and including the final element # a[n]. # For example, given the sequence [1, 2, 3, 4] which starts in a weakly # increasing order, and given that the index is zero-based, the steps are as # follows: # 1) Index k = 2, because 3 is placed at an index that satisfies condition of # being the largest index that is still less than a[k + 1] which is 4. # 2) Index l = 3, because 4 is the only value in the sequence that is greater # than 3 in order to satisfy the condition a[k] < a[l]. # 3) The values of a[2] and a[3] are swapped to form the new sequence [1,2,4,3]. # 4) The sequence after k-index a[2] to the final element is reversed. Because # only one value lies after this index (the 3), the sequence remains # unchanged in this instance. Thus the lexicographic successor of the initial # state is permuted: [1,2,4,3]. # Following this algorithm, the next lexicographic permutation will be # [1,3,2,4], and the 24th permutation will be [4,3,2,1] at which point # a[k] < a[k + 1] does not exist, indicating that this is the last permutation. # Easy mode ruby class Integer def get_nth_permutation(n) digits = self.to_s.split('').map(&:to_i).sort digits.permutation.to_a.sort[n-1].join.to_i end end # Slow - Algorithm found on Wikipedia class Permutation attr_reader :current, :count def initialize(number) @current = number.to_s.split('').sort.join @count = 1 end def digits current.split('').map(&:to_i) end def next a = digits # 1) Find the largest index k such that a[k] < a[k + 1]. If no such index # exists, the permutation is the last permutation. k = get_k return current unless k # 2) Find the largest index l such that a[k] < a[l]. l = get_l(k) # 3) Swap the value of a[k] with that of a[l]. a[k] ^= a[l] a[l] ^= a[k] a[k] ^= a[l] # 4) Reverse the sequence from a[k + 1] up to and including the final # element a[n]. sequence_1 = a.slice(0..k) sequence_2 = a.slice(k+1..-1).reverse @count += 1 @current = (sequence_1 + sequence_2).join end def get_l(k) a = digits slice = a.slice(k..-1).reverse slice.each do |num| if num > a[k] return a.index(num) end end end def get_k a = digits a_reverse = a.reverse a_reverse.each_with_index do |num,i| if num > a_reverse[i+1] return a.index(a_reverse[i+1]) end end nil end end
true
3b427c1ad30a9c43b05988b31f4ce46ebadb0498
Ruby
ijdickinson/jena-jruby
/lib/jena_jruby/namespace.rb
UTF-8
1,134
2.6875
3
[ "Apache-2.0" ]
permissive
module Jena module Vocab # A namespace is an object for resolving identifiers in scope denoted # by a base URI to a full URI. For example, # # rdfs = Namespace.new( "http://www.w3.org/2000/01/rdf-schema#" ) # rdfs.comment # => "http://www.w3.org/2000/01/rdf-schema#comment" # # There is no checking that the resolved name is known in the defined # namespace (e.g. <tt>rdfs.commnet</tt> will work without a warning) class Namespace attr_reader :ns # Initialize this namespace with the given root URI. E.g, for RDFS, # this would be # rdfs = Namespace.new( "http://www.w3.org/2000/01/rdf-schema#" ) def initialize( ns ) @ns = ns end :private def method_missing( name, *args) prop = !args.empty? && args.first n = "#{@ns}#{name}" prop ? Jena::Core::ResourceFactory.createProperty(n) : Jena::Core::ResourceFactory.createResource(n) end end # A namespace object for the SKOS vocabulary, which is not built-in to Jena SKOS = Namespace.new( "http://www.w3.org/2004/02/skos/core#" ) end end
true
71420e217df5ceecfc22f1ffc594d138caf9af3c
Ruby
thblckjkr/homework
/scripting_sockets/ruby/Addressbook_server.rb
UTF-8
955
2.9375
3
[ "MIT" ]
permissive
# Import of libraries require 'socket' # Import main socket library require_relative "Utils" # General program utilities require_relative "Database" class Socket def initialize(port, db, pr, ui) @@ui = ui @@db = db @@pr = pr ui.show("Opening port") @@server = TCPServer.new port # Server bound to port ui.show("Ready to accept connections") end def work() while(true) client = @@server.accept # Wait for a client to connect Thread.start(client) do | connection | data = connection.recvmsg info = @@pr.getData(data[0]) temp = @@db.Search( info ) if temp != false connection.puts( @@pr.CreateMessage(temp, false) ) else connection.puts( @@pr.CreateMessage( "NOT_FOUND", false ) ) end connection.close() end end end end u = UI.new p = Protocol.new d = Database.new u s = Socket.new 5678, d, p, u # Initialize the socket s.work()
true
6bb79ee83043595c5004e0ada8e1562a072112f4
Ruby
israelb/pragmatic-ruby
/playlist.rb
UTF-8
2,186
3.5625
4
[]
no_license
require_relative 'movie' require_relative 'waldorf_and_statler' require_relative 'snak_bar' require "colorize" module Flicks class Playlist def initialize(name) @name = name @movies = [] @config = {space: 50, symbol: '*'} end def load(from_file) File.readlines(from_file).each do |line| add_movie(Movie.from_csv(line)) end end def save(to_file="movie_rankings.csv") File.open(to_file, "w") do |file| @movies.sort.each do |movie| file.puts movie.to_csv end end end def add_movie(movie) @movies << movie end def play(viewings) puts "#{@name}'s playlist:".center(@config[:space], @config[:symbol]).colorize( color: :white, :background => :red ) puts @movies.sort snacks = SnackBar::SNACKS puts "\nThere are #{snacks.size} snacks available in the snack bar" snacks.each do |snack| puts "#{snack.name} has #{snack.carbs} carbs" end 1.upto(viewings) do |count| puts "\n" + "Viewing #{count}".center(@config[:space], @config[:symbol]).colorize(:blue) @movies.each do |movie| WaldorfAndStatler.review(movie) snack = SnackBar.random movie.ate_snack(snack) puts movie end end end def total_carbs_consumed @movies.reduce(0) do |sum, movie| sum + movie.carbs_consumed end end def print_stats puts "\n" + "#{@name}'s' Stats".center(@config[:space], @config[:symbol]).colorize(:blue) puts "#{total_carbs_consumed} total carbs consumed" @movies.sort.each do |movie| puts "\n#{movie.title}'s snack totals:" # Invocamos el método each_snack el cual nos regresa un bloque yield de cada snack. movie.each_snack do |snack| puts "#{snack.carbs} total #{snack.name} carbs" end puts "#{movie.carbs_consumed} grand total carbs" end hits, flops = @movies.partition { |movie| movie.hit? } puts "\nHits:".colorize(:red) puts hits.sort puts "\nFlops:".colorize(:red) puts flops.sort end end end
true
85e1540973216b9c07573a20eb92edd70d3388ac
Ruby
ohpauleez/research
/p2pusenet/extra/scripting-examples/DetailedExample/example2.rb
UTF-8
769
3.0625
3
[]
no_license
#!/usr/bin/env ruby # #Note: I say this is ruby, but it's truthfully JRuby, #You can change the path env to JRuby if you desire. # print "Starting the second script\n" require "java" print "trying to include all of java.\n" print "This will cause name conflicts with things like 'String'\n" print "\t...so we will put it in a module called 'Java'\n" module Java include_package 'java' end include_class 'javax.script.ScriptEngineManager' include_class 'javax.script.ScriptEngine' print "Trying to get a Script Engine Manager...\n" mgr = ScriptEngineManager.new print "Trying to get a Python engine... in ruby\n" pyEng = mgr.getEngineByName("python") print "Evaluating python...\n" pyEng.eval("print 'This is python inside a ruby script!'") print "SUCCESS!\n"
true
8ed501a7ccc615b1341b1a7252e3ecf493ab6583
Ruby
michaelpmattson/funny_2107
/spec/open_mic_spec.rb
UTF-8
1,861
3.1875
3
[]
no_license
require './lib/open_mic' require './lib/user' require './lib/joke' RSpec.describe OpenMic do context '#initialize' do it 'exists' do open_mic = OpenMic.new({location: "Comedy Works", date: "11-20-18"}) expect(open_mic).to be_instance_of(OpenMic) end it 'has a location' do open_mic = OpenMic.new({location: "Comedy Works", date: "11-20-18"}) expect(open_mic.location).to eq("Comedy Works") end it 'has a date' do open_mic = OpenMic.new({location: "Comedy Works", date: "11-20-18"}) expect(open_mic.date).to eq("11-20-18") end it 'has an empty performers array' do open_mic = OpenMic.new({location: "Comedy Works", date: "11-20-18"}) expect(open_mic.performers).to eq([]) end end context '#welcome' do it 'adds a user to performers' do open_mic = OpenMic.new({location: "Comedy Works", date: "11-20-18"}) user_1 = User.new("Sal") user_2 = User.new("Ali") expect(open_mic.performers).to eq([]) open_mic.welcome(user_1) open_mic.welcome(user_2) expect(open_mic.performers).to eq([user_1, user_2]) end end context '#repeated_jokes?' do it 'tells if performers have any of the same jokes' do open_mic = OpenMic.new({location: "Comedy Works", date: "11-20-18"}) user_1 = User.new("Sal") user_2 = User.new("Ali") open_mic.welcome(user_1) open_mic.welcome(user_2) joke_1 = Joke.new(22, "Why did the strawberry cross the road?", "Because his mother was in a jam.") joke_2 = Joke.new(13, "How do you keep a lion from charging?", "Take away its credit cards.") user_2.learn(joke_1) user_2.learn(joke_2) # expect(open_mic.repeated_jokes?).to be(false) user_1.learn(joke_1) expect(open_mic.repeated_jokes?).to be(true) end end end
true
98e757347f3909b55d869202719c766d50966a15
Ruby
MrWorld/stronghold
/test/unit/lib/open_stack_object_test.rb
UTF-8
1,272
2.671875
3
[ "MIT" ]
permissive
require 'test_helper' require_relative '../../support/open_stack_mocks' class TestOpenStackObject < CleanTest def setup @foo = Foo.new(Mock.new) end def test_object_has_attributes_and_methods [:foo, :bar, :baz].each do |sym| assert @foo.respond_to? sym end end def test_object_delegates_calls_to_contained_object assert_equal @foo.bar, 'test' end def test_contained_object_id_used_as_id assert_equal @foo.id, 'mock_id' end def test_service_method assert_equal @foo.call_service_method, 'service!' end def test_api_error_message assert_equal 'Error!', @foo.send(:api_error_message, MockError.new) end def test_method_all_wraps_results Foo.all.each{|f| assert f.class.to_s == 'Foo'} end def test_method_find_all_by_wraps_results Foo.find_all_by(:id, 'foo').each{|f| assert f.class.to_s == 'Foo'} end def test_method_find_by_all_returns_empty_if_not_found assert_equal [], Foo.find_all_by(:id, 'bar') end def test_method_hands_off_to_get assert_equal 'foo', Foo.find('foo').id end def test_method_find_returns_nil_if_not_found refute Foo.find('bar') end def test_method_create_returns_a_foo assert_equal 'Foo', Foo.create(name: 'foo').class.to_s end end
true
77b86c7480ad90d02fd998cd2cb3ed9f51277674
Ruby
yasmineezequiel/Vanilla_Ruby
/Section_5_Ruby_Methods1/The_Ternary_Operator.rb
UTF-8
929
4.8125
5
[]
no_license
# The ternary operator, it takes 3 things as per the name. It's a shorter syntax than an if statement. if 'yes' == 'yes' p "They are the same" else p "They are not the same" end # ternary operator: p 'yes' == 'yes' ? "They are the same" : "They are not the same" def even_odd_number(num) num.even? ? "The number is even" : "The number is odd" end p even_odd_number(101) def rebox_or_nike(r) r == 'Rebox' ? "Is this Rebox?" : "Is Nike!" end p rebox_or_nike("Nike") # Challenge convert the below if statement into ternary operator: # pokemon = "Pikachu" # if pokemon == "Charizard" # p "Fireball!" # else # p "That is not Charizard" # end pokemon = "Pikachu" p pokemon == "Charizard" ? "Fireball!" : "That is not Charizard" # Adding it into a method def check_pokemon(pokemon) pokemon == "Charizard" ? "Fireball!" : "That is not Charizard" end p check_pokemon("Pikachu") p check_pokemon("Charizard")
true
359c44a8a435929c732aaca5ddd17941ea324faf
Ruby
amgencjana/magic_matrix
/lib/magic_matrix/matrix.rb
UTF-8
575
2.859375
3
[ "MIT" ]
permissive
module Magic class Matrix # Magic::Matrix class # recives as an attribute path the the yaml file # # = response to only one public method magic_hash attr_accessor :matrix # returns hash read from the the given yaml file # each inner hash will be wrapped with the Magic::Hash class # which allows to infinitely read keys from the yaml just by using .key.nested_key.nested_nested_key def initialize( path ) matrix_file = YAML.load_file( path ) @matrix = Magic::HashWrapper.new( matrix_file ) end end end
true
3320cd06016b5eae789dbf4ffe94484e8a24159f
Ruby
shanahagood/phase-0-tracks
/ruby/santa.rb
UTF-8
2,516
3.84375
4
[]
no_license
class Santa #makes a (getter) method readable. # attr_reader :age, :ethnicity #makesa method readable and writeable. attr_accessor :age, :ethnicity, :gender def initialize(gender, ethnicity) puts "Initializing Santa instance...!" @reindeer_ranking = ["Rudolph", "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen"] @age = rand(0..140) @ethnicity = ethnicity @gender = gender end def speak puts "Santa says: Ho, ho, ho! Haaaappy holidays!" end def eat_milk_and_cookies(cookie_type) puts "Santa says: Om nom nom! That was a good #{cookie_type} cookie!" end def celebrate_birthday @age += 1 end #moves reindeer name to last place def get_mad_at(deer_name) @reindeer_ranking.delete(deer_name) @reindeer_ranking.push(deer_name) puts "Santa is mad at #{deer_name}!" end end example_genders = ["agender", "female", "bigender", "male", "female", "gender fluid", "N/A", "transgender", "androgynous", "genderqueer", "nonbinary"] example_ethnicities = ["black", "Latino", "white", "Japanese-African", "prefer not to say", "Mystical Creature (unicorn)", "N/A", "Asian", "Irish", "Japanese", "French", "Italian"] santas = [] puts "Printing information for new Santas...!" example_genders.length.times do new_santa = Santa.new(example_genders.sample, example_ethnicities.sample) puts "Gender: #{example_genders.sample}" puts "Ethnicity: #{example_ethnicities.sample}" puts "Age: #{new_santa.age}!" santas << new_santa puts "---" end puts "Testing each instance to make sure Santas can perform actions..." santas.each do |santa| santa.speak santa.eat_milk_and_cookies("chocolate chip oatmeal raisin") puts "Today I'm" puts santa.celebrate_birthday santa.get_mad_at("Donner") puts "---" end # #getter method for age attribute # def age # @age # end # #getter method for ethnicity # def ethnicity # @ethnicity # end # #setter method for age # def age=(new_age) # @age = new_age # end # #setter method for ethnicity # def ethnicity=(new_ethnic) # @ethnicity = new_ethnic # end # #setter method for gender # def gender=(new_gender) # @gender = new_gender # puts "Santa's gender is #{new_gender}!" # end # santa = Santa.new # santa.speak # santa.eat_milk_and_cookies("snickerdoodle") # santa.age = 18 # santa.celebrate_birthday # santa.ethnicity = "Asian" # santa.get_mad_at("Vixen") # santa.gender = "gender fluid"
true
4d5521ffa56f33096aa81c5ae87a01d13af45171
Ruby
twill14/launchschool-practice-exercises
/exercise_two/exercises_two.rb
UTF-8
1,060
4.125
4
[]
no_license
# Exercise One first_name = "Thomas" last_name = "Williams" full_name = first_name + " " + last_name # OR "Thomas " + "Williams" # Exercise Two 6342 / 1000 # = 6 6342 % 1000 / 100 # = 3 6342 % 1000 % 100 / 10 # = 4 6342 % 1000 % 100 % 10 # = 2 #Exercise Three #movie_years = {:one => 1975, :two => 2004, :three => 2013, :four => 2001, :five => 1981} #movie_years.each do |key, result| # puts result #end # Exercise Four #my_array = [1975, 2004, 2013, 2001, 1981] #my_array.each do |x| # puts x #end # Exercise Five puts 5 * 4 * 3 * 2 * 1 puts 6 * 5 * 4 * 3 * 2 * 1 puts 7 * 6 * 5 * 4 * 3 * 2 * 1 puts 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 # Exercise Six def squares(n) puts n**2 end squares(4.5) squares(2.4) squares(8.3) # Exercise Seven =begin SyntaxError: (irb):2: syntax error, unexpected ')', expecting '}' from /usr/local/rvm/rubies/ruby-2.0.0-rc2/bin/irb:16:in `<main>' =end # This error message means that somewhere in the irb code, there is a parenthesis where a curled brace should be instead.
true
e4942d99b70be21b80da1854d0ff16fc5c5f9f31
Ruby
dannykim1997/Phase-4-challenge-practice
/app/models/destination.rb
UTF-8
344
2.703125
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Destination < ApplicationRecord has_many :posts has_many :bloggers, through: :posts def most_recent_posts posts.last(5) end def popular_post posts.max_by{|post|post.likes} end def avg_blogger_age total = bloggers.uniq.sum{|b| b.age} total.to_f/bloggers.uniq.size end end
true
25c8f85963054d21298afcc925b90cd12306c9e8
Ruby
ejatkin/lrthw
/ex29.rb
UTF-8
633
4.03125
4
[]
no_license
people = 20 cats = 30 dogs = 15 if people < cats puts "Too many cats! The world is doomed!" end if people > cats puts "Not many cats! The world is saved!" end if people < dogs puts "The world is drooled on!" end if people > dogs puts "The world is dry!" end dogs += 5 if people >= dogs puts "People are greater than or equal to dogs." end if people <= dogs puts "People are less than or equal to dogs." end if people == dogs puts "People are dogs." end # Answer to Q1 The if is asking a question essentially asking "Is this true?" # if the expression evaluates to true then it's printed, but if it's false # then it's not
true
8dfbe5ff67188174db3d258d87fd7fdf9f8551ef
Ruby
martenlienen/vldt
/lib/vldt/each.rb
UTF-8
631
2.6875
3
[ "MIT" ]
permissive
module Vldt # Validates each object of an enumerable class Each < Validation def initialize (validation) @validation = validation @array_validation = Vldt::Array.array end def call (object) errors = Vldt::Array.array.call(object) if errors errors else errors = {} object.each_with_index do |v, i| e = @validation.call(v) if e e.map do |selector, error| errors[[i] + selector] = error end end end if errors.size > 0 errors end end end end end
true
5de4ddbcf5da7b3eb9a824ac520ca3e174fbe1ff
Ruby
skunitomo/heroku01
/app/controllers/people_controller.rb
UTF-8
671
2.59375
3
[]
no_license
class PeopleController < ApplicationController def index end def sample render "index" end def json personal = {'name' => 'Yamada', 'age' => 28} render :json => personal end def xml personal = {'name' => 'Yamada', 'age' => 28} render :xml => personal end def inputParames render :text => "upper = #{params[:upper]}, lower = #{params[:lower]}" end def customModel person = Person.new() person.FirstName = "Shoji" person.LastName = "Kunitomo" person.Age = 27 render :json => person end def abc abc = Abc.new() abc.FirstName = "Shoji" abc.LastName = "Kunitomo" abc.Age = 27 abc.Sex = 'Male' render :json => abc end end
true
fe1385468b3fc960e0544b1f4fe8be8d264fb4bd
Ruby
elliotte/borisbikes
/spec/docking_station_spec.rb
UTF-8
2,254
3.109375
3
[]
no_license
require 'docking_station' describe DockingStation do let(:station) { DockingStation.new [], 20 } let(:bike) { double :bike, broken?: false } let(:broken_bike) { double :broken_bike, broken?: true } let(:broken_bike2) { double :broken_bike, broken?: true } let(:broken_bike3) { double :broken_bike, broken?: true } it 'can accept a bike' do expect(station.bike_count).to eq 0 station.dock(bike) expect(station.bike_count).to eq 1 end it 'releases a bike' do station.dock(bike) expect(station.bike_count).to eq 1 station.release_bike expect(station.bike_count).to eq 0 end it 'tells you if there are no bikes to be released at the station' do expect(lambda { station.release_bike } ).to raise_error(RuntimeError) end it 'knows if the station is full' do expect(station).not_to be_full 20.times { station.dock(bike) } expect(station).to be_full end it 'knows if the station is not full' do 19.times { station.dock(bike) } expect(station).not_to be_full end it 'does not let you dock a bike if the station is full' do 20.times { station.dock(bike) } expect(lambda { station.dock(bike) }).to raise_error(RuntimeError) end it 'knows which bikes are working' do station.dock(bike) station.dock(broken_bike) expect(station.working_bikes).to eq([bike]) end it 'knows which bikes are broken' do station.dock(bike) station.dock(broken_bike) expect(station.broken_bikes).to eq([broken_bike]) end it 'releases a broken bike' do station.dock(bike) station.dock(broken_bike) expect(station.release_broken_bike).to eq(broken_bike) end it 'releases all broken bikes' do station.dock(bike) 3.times { station.dock(broken_bike) } expect(station.release_all_broken_bikes().length).to eq 3 end it 'releases a select number of broken bikes' do station.dock(bike) station.dock(broken_bike) station.dock(broken_bike2) expect(station.release_x_broken_bikes(2).length).to eq 2 end it 'only rents bikes which are not broken' do 20.times { station.dock(broken_bike) } expect(station.release_bike).to be nil end it 'knows how many free spaces there are' do station = DockingStation.new Array.new(7, bike) expect(station.slots_available).to eq 13 end end
true
c29905f92fd3b1fd7abb9852e470ad4160d3aeb1
Ruby
abhishekg785/Getting-started-with-Ruby
/array.rb
UTF-8
880
4.28125
4
[]
no_license
def testing() arr = Array.new(6) # Declares the a new Array of size hash_arr = Array.new(2) { Hash.new } # => [ {} {} ] # creating a 2d array two_d_array = Array.new(2) { Array.new(2) } # [ [], [] ] # Accessing the array elements a = [ 'a', 'b', 'c', 'd', 'e'] puts a[0] puts a.at(0) #puts a.fetch(89) # throw an exception puts a.first puts a.last puts a.take(4) puts "--------------" puts a.drop(3) puts "--------------" puts a puts "~~~~~~~~~~~~~~~~~~~" puts a.length puts "--------------" # Adding items to the array # using push a.push('abhishek') puts a # using << a << 'gosu' puts a a.insert(2, 'gosu') puts a puts "^^^^^^^^^^^^^^^^^" a.unshift('goswami') puts a puts "--------------" puts "Deleting from an array" arr.delete("a") a.each do |name| puts "Yo! " + name end end testing()
true
568c4975a6c0b2d90cc191d343b57add61ae7fb7
Ruby
trinityseal/poison
/lib/poison.rb
UTF-8
817
2.6875
3
[ "MIT" ]
permissive
# frozen_string_literal: true trap('INT') do perror('You killed me :(') end # Standard libs require 'optparse' require 'ostruct' require 'uri' require 'net/http' # Custom libs require 'puf/version' require 'puf/scanner' require 'puf/prettyp' # String class with color methods String.class_eval do include Poison::Prettyp::Colors end # Printer methods include Poison::Prettyp::Printer # Enumerable module with parallel each Enumerable.module_eval do def _peach_run(pool) div = (count / pool).to_i div = 10 unless div.positive? threads = [] each_slice(div).with_index do |slice, idx| threads << Thread.new(slice) do |thread| yield thread, idx end end threads.each(&:join) end def peach(pool) _peach_run(pool) do |thread, idx| thread.each { |elt| yield elt, idx } end end end
true
2de983a98f48f982379eabd06d310987f206f6cb
Ruby
Sufl0wer/summer-2019
/3493/2/lib/file_methods.rb
UTF-8
941
2.671875
3
[]
no_license
class FileMethods API_URL = 'https://api.telegram.org/'.freeze def self.request_file_path(file_id, person_number, folder_name) uri = URI("#{API_URL}bot#{ENV['TOKEN']}/getFile?file_id=#{file_id}") json_response = JSON.parse(Net::HTTP.get(uri)) new.save_photo_from_uri(json_response['result']['file_path'], person_number, folder_name) end def self.save_location_in_file(location, person_number, folder_name) location_path = "#{person_number}/#{folder_name}/#{Date.today}/geo" File.write(location_path, location, mode: 'wb') location_path end def save_photo_from_uri(path, person_number, folder_name) uri = URI("#{API_URL}file/bot#{ENV['TOKEN']}/#{path}") FileUtils.mkdir_p("#{person_number}/#{folder_name}/#{Date.today}") photo_new_path = "#{person_number}/#{folder_name}/#{Date.today}/photo.jpg" File.write(photo_new_path, Kernel.open(uri).read, mode: 'wb') photo_new_path end end
true
f7ca51aa2de1beecfa595659578907c4d54dc9b4
Ruby
soutaro/unification_assertion
/lib/unification_assertion.rb
UTF-8
5,485
3.1875
3
[ "MIT" ]
permissive
require "unification_assertion/version" module UnificationAssertion if defined? Test::Unit include Test::Unit::Assertions else require 'minitest/autorun' include MiniTest::Assertions end module_function @@comparators = {} @@comparators[Array] = lambda {|a, b, eqs, unifier, path, block| block.call(a.length, b.length, path + ".length") a.zip(b).each.with_index do |pair, index| pair << path + "[#{index}]" eqs << pair end eqs } @@comparators[Hash] = lambda {|a, b, eqs, unifier, path, block| block.call(a.keys.sort, b.keys.sort, path + ".keys.sort") eqs.concat(a.keys.map {|key| [a[key], b[key], path+"[#{key.inspect}]"] }) } # Comparators are hash from a class to its comparator. # It is used to check unifiability of two object of the given hash. # # There are two comparators defined by default; for |Array| and |Hash|. # # == Example == # UnificationAssertion.comparators[Array] = lambda do |a, b, message, eqs, unifier, &block| # block.call(a.length, bl.ength, message + " (Array length mismatch)") # eqs.concat(a.zip(b)) # end # # This is our comparator for |Array|. It first tests if the length of the two arrays are equal. # And then, it pushes the equations of each components of the arrays. # The components of the arrays will be tested unifiability later. # # == Comparator == # # Comparator is a lambda which takes 5 arguments and block and checks the unifiability # of the first two arguments. # # * |a|, |b| Objects they are compared. # * |message| Message given to |unify|. # * |eqs| Equations array. This is for output. # * |unifier| Current unifier. This is just for reference. # * |&block| Block given to |unify|, which can be used to check the equality of two values. # def comparators @@comparators end # Run unification algorithm for given equations. # If all equations in |eqs| are unifiable, |unify| returns (the most-general) unifier. # # Which identifies an symbol as a meta variable if the name matches with |options[:meta_pattern]|. # The default of the meta variable pattern is |/^_/|. # For example, |:_a| and |:_xyz| are meta variable, but |:a| and |:hello_world| are not. # # It also accepts wildcard variable. Which matches with any value, but does not introduce new equational constraints. # The default wildcard is |:_|. # # |unify| takes a block to test equation of two values. # The simplest form should be using |assert_equal|, however it can be customized as you like. # # == Example == # unify([[:_a, 1], [{ :x => :_b, :y => 1 }, { :x => 3, :y => 1 }]], "Example!!") do |x, y, message| # assert_equal(x,y,message) # end # # The |unify| call will return an hash |{ :_a => 1, :_b => 3 }|. # The block will be used to test equality between 1 and 1 (it will pass.) # def unify(eqs, unifier = {}, options = {}, &block) options = { :meta_pattern => /^_/, :wildcard => :_ }.merge!(options) pattern = options[:meta_pattern] wildcard = options[:wildcard] while eq = eqs.shift a,b,path = eq case when (Symbol === a and a.to_s =~ pattern) unless a == wildcard eqs = substitute({ a => b }, eqs) unifier = substitute({ a => b }, unifier).merge!(a => b) end when (Symbol === b and b.to_s =~ pattern) unless b == wildcard eqs = substitute({ b => a }, eqs) unifier = substitute({ b => a }, unifier).merge!(b => a) end when (a.class == b.class and @@comparators[a.class]) @@comparators[a.class].call(a, b, eqs, unifier, path, block) else yield(a, b, path) end end unifier.inject({}) {|acc, (key, value)| if key == value acc else acc.merge!(key => value) end } end @@substituters = {} @@substituters[Hash] = lambda {|unifier, hash| hash.inject({}) {|acc, (key, val)| if unifier[val] acc.merge!(key => unifier[val]) else acc.merge!(key => substitute(unifier, val)) end } } @@substituters[Symbol] = lambda {|unifier, symbol| unifier[symbol] or symbol } @@substituters[Array] = lambda {|unifier, array| array.map {|x| substitute(unifier, x) } } def substitutions @@substituters end def substitute(unifier, a) subst = @@substituters[a.class] if subst subst.call(unifier, a) else a end end # Run unification between |a| and |b|, and fails if they are not unifiable. # |assert_unifiable| can have block, which yields the unifier for |a| and |b| if exists. # def assert_unifiable(a, b, original_message = "", options = {}, &block) msg = proc {|eq, path| header = if original_message == nil or original_message.length == 0 original_message else "No unification" end footer = "\nCould not find a solution of equation at it#{path}.\n=> #{mu_pp(eq[0])} == #{mu_pp(eq[1])}" a_pp = mu_pp(a) b_pp = mu_pp(b) if respond_to? :build_message build_message "=> #{a_pp}\n=> #{b_pp}" else message(header, footer) { "=> #{a_pp}\n=> #{b_pp}" } end } unifier = unify([[a, b, ""]], {}, options) do |x, y, path| assert(x==y, msg.call([x, y], path)) end if block yield(unifier) end end end
true
b03154fb17b3d448b8061d2c9170f5c3de13c9a1
Ruby
shraddhap23/basic_ruby
/basic_ruby.rb
UTF-8
740
3.9375
4
[]
no_license
#1A def add_phrase(phrase) phrase + "Only in America!" end puts add_phrase("Donald Trump and Ted Cruz are viable Presidential candidates...") #1B def max(array) max = array[0] for i in 0..array.length - 1 if array[i] > max max = array[i] end end puts max end max ([12, 37, 25, 64, 54]) #1C def alcohol(type, brand) combined = Hash[type.zip brand] puts combined end brand = ["Absolut", "Hendricks", "Jameson"] type = ["vodka", "gin", "whiskey"] alcohol(type, brand) #2 def fizz_buzz(n) (1..n).each do |i| if i % 3 == 0 && i % 5 == 0 puts 'fizzbuzz' elsif i % 3 == 0 puts 'fizz' elsif i % 5 == 0 puts 'buzz' else puts i end end end fizz_buzz(100)
true
83850d14a0723acba3cf086b2bb3513bbcb2fd92
Ruby
kontez/PM1-PT1
/Aufgabe4/teil4/Life.rb
UTF-8
1,288
2.921875
3
[]
no_license
require "Zelle" require "Point" class Life def initialize(n,muster_index) end # Initialisiert das Spielfeld mit Objekten der Klasse Zelle # Die Position einer Zelle ist definiert durch die obere linke Ecke des Gitternetzes # und die Zeile / Spalte, in der die Zelle steht. # Die Zelle berechnet eigenständig ihre Koordinaten def generation_initialisieren() end # Markiert die Zellen auf den Positionen des Muster als lebend def muster_erzeugen() end # Berechnet die nächste Generation auf Basis der Spielregeln def naechste_generation() end # Berechnet die Anzahl der lebenden Nachbarn / berücksichtigt auch die Ränder def lebende_nachbar_zellen(i,j) end # Macht alle Zelle unsichtbar def unsichtbar_machen() end # Macht alle Zelle sichtbar def sichtbar_machen() end # Versetzt das Spiel in den Ausgangszustand def zuruecksetzen() end # # Vorgegebene Methode der Klasse Life # # Simuliert die Entwicklung der Generationen des Game Of Life für n - Wiederholungen # # Dazu wird alle 10 ms die Folgegeneration mit Hilfe der Methode # naechste_generation berechnet und dargestellt # def simuliere(schritte) TkTimer.new(10,schritte, proc{ naechste_generation() }).start(0, proc{}) end end
true
5290fa3439495fafb35458d707296e3a8b87be96
Ruby
jeroeningen/logius_test
/case_b/app/models/user.rb
UTF-8
3,435
2.625
3
[]
no_license
class User < ActiveRecord::Base has_one :bankaccount has_many :transactions, through: :bankaccount validates :bankaccount, presence: true validates :firstname, presence: true validates :lastname, presence: true validates :email, presence: true, uniqueness: true # Code used: http://stackoverflow.com/questions/13784845/how-would-one-validate-the-format-of-an-email-field-in-activerecord validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i has_secure_password before_validation :new_bankaccount validate :password_match_password_confirmation # You need to reload the bankaccount to get the actual balance def current_balance "EUR. #{sprintf('%.2f', bankaccount.reload.balance)}" end def deposit amount = nil # if the given param is a string, convert it to an integer amount = amount.to_d if amount.present? # check if amount is positive and if it is not zero if amount.blank? || amount == 0 I18n.t("activerecord.messages.models.user.zero_deposit_not_allowed") elsif amount < 0 I18n.t("activerecord.messages.models.user.negative_deposit_not_allowed") else translated_amount = sprintf('%.2f', amount) Transaction.create(bankaccount_id: bankaccount.id, amount: amount, comment: I18n.t("activerecord.messages.models.user.deposit", amount: translated_amount)) I18n.t("activerecord.messages.models.user.deposit_added", amount: translated_amount) end end def transfer_money bankaccount_id, amount, comment # if the given param is a string, convert it to an integer amount = amount.to_d if amount.present? # check if bankaccount is given if bankaccount_id.blank? I18n.t("activerecord.messages.models.user.no_bankaccount") # check if amount is positive elsif amount.blank? || amount == 0 I18n.t("activerecord.messages.models.user.zero_transfer_not_allowed") elsif amount < 0 I18n.t("activerecord.messages.models.user.negative_transfer_not_allowed") # check if amount is greater than balance elsif bankaccount.reload.balance < amount I18n.t("activerecord.messages.models.user.not_enough_balance") else translated_amount = sprintf('%.2f', amount) transferred_from = Bankaccount.find(bankaccount.id).user transferred_to = Bankaccount.find(bankaccount_id).user # Transaction 'Transferred from' Transaction.create(bankaccount_id: bankaccount.id, foreign_bankaccount_id: bankaccount_id, amount: -amount, comment: comment) # Transaction 'Transferred to' Transaction.create(bankaccount_id: bankaccount_id, foreign_bankaccount_id: bankaccount.id, amount: amount, comment: comment) I18n.t("activerecord.messages.models.user.amount_transfered", amount: translated_amount, bankaccount_id: bankaccount_id, firstname: transferred_to.firstname, lastname: transferred_to.lastname) end end private def new_bankaccount self.bankaccount = Bankaccount.new if self.bankaccount.blank? true end # I do not know why, but it looks to be that the 'password_confirmation match' from has_secure_password does not work out-of-the-box # That is why I added this validation def password_match_password_confirmation if password != password_confirmation errors.add(:password_confirmation, I18n.t(".activerecord.errors.models.user.attributes.password_confirmation")) end end end
true
29582955c05fe539191285683c33e164e7af5981
Ruby
ElizabethNicholas14/TTSRubyPractice
/activity_today.rb
UTF-8
944
3.875
4
[]
no_license
puts "What is today's temperature" todays_temperature = gets.chomp.to_i case todays_temperature when 80..100 puts "Let's go swimming" when 50...80 puts "Let's go hiking" when 40...50 puts "Let's stay inside and read" when 0...40 puts "Let's cozy up by the fire" else puts "What planet is that?" end if todays_temperature == 42 puts "The answer to life.." end puts "The answer to life.." if todays_temperature == 42 # def pick_activity # puts "what's today's temperature" # temp = gets.chomp.to_i # if temp > 110 || temp < 20 # puts "That's just silly. #{temp} degrees would never happen in New Orleans." # pick_activity # elsif temp >=80 # puts "#{temp} degrees is perfect for swimming!" # elsif temp > 50 # puts "#{temp} degrees sounds excellent for hiking!" # else # puts "At #{temp} degrees, it sounds like I should stay inside and read" # end # end # pick_activity
true
de433ac6e75bbc64a0364c76dee94e9a91db8111
Ruby
epeters95/sage_one
/lib/sage_one/client/contacts.rb
UTF-8
647
2.671875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module SageOne class Client module Contacts # Get a contact record by ID # @param [Integer] id Contact ID # @return [Hashie::Mash] Contact record # @example Get a contact: # SageOne.contact(12345) def contact(id) get("contacts/#{id}") end # List all contacts def contacts(options={}) get("contacts", options) end # Create contact def create_contact(options) post('contacts', contact: options) end # Update contact def update_contact(id, options) put("contacts/#{id}", contact: options) end end end end
true
fd8ea5387b1560a26ca5c1d42e4849c9180dad50
Ruby
rsupak/tc-challenges
/Address_Book_Complete/spec/entry.rb
UTF-8
318
3.234375
3
[]
no_license
# Base entry class for address book class Entry attr_accessor :name, :phone, :email def initialize(name = nil, phone = nil, email = nil) @name = name @phone = phone @email = email end # display entry information def display_entry "Name: #{name}\nPhone: #{phone}\nEmail: #{email}" end end
true
3b89d07d4b62817343ca5d14180ac13346d6c2cc
Ruby
Brightcoders-Bootcamps/kata-07-pacman-team_07
/app/classes/pacman.rb
UTF-8
1,639
3.46875
3
[]
no_license
# frozen_string_literal: true require_relative 'rules' # frozen_string_literal: true # # Class used to control a Pacman class Pacman attr_reader :position_x, :position_y, :rotation def initialize(position_x, position_y, limit) @position_x = position_x @position_y = position_y @rotation = :up @limit = limit end def print_pacman { up: 'V ', left: '> ', right: '< ', down: '^ ' }[@rotation] end def move_left(grid) return false if Rules.wall?(grid, @position_x - 1, @position_y) @position_x -= 1 @position_x = 0 if @position_x.negative? end def move_right(grid) return false if Rules.wall?(grid, @position_x + 1, @position_y) @position_x += 1 @position_x = @limit[:x] - 1 if @position_x >= @limit[:x] end def move_down(grid) return false if Rules.wall?(grid, @position_x, @position_y + 1) @position_y += 1 condition = @position_y >= @limit[:y] @position_y = @limit[:y] - 1 if condition end def move_up(grid) return false if Rules.wall?(grid, @position_x, @position_y - 1) @position_y -= 1 @position_y = 0 if @position_y.negative? end def step(grid) move_up(grid) if @rotation == :up move_down(grid) if @rotation == :down move_right(grid) if @rotation == :right move_left(grid) if @rotation == :left end def rotate(grid) puts 'rotate?: ' rotation = $stdin.gets.chomp.to_sym rotation = %i[up down left right].include?(rotation) ? rotation : '' rotation = '' if Rules.close_wall?(grid, rotation, @position_x, @position_y, @limit) == true @rotation = rotation if rotation != '' end end
true
289391928cbe8adbc1e227ef45925aa1234d450f
Ruby
nidhishah13/Todo-API
/app/controllers/v1/items_controller.rb
UTF-8
2,152
2.640625
3
[]
no_license
module V1 class ItemsController < ApplicationController before_action :set_todo before_action :set_todo_item, only: [:show, :update, :destroy] def_param_group :todo_item do param :todo_id, String, :desc => "Todo_id of the item", :required => true param :id, String, :desc => "Item_id", :required => true end def_param_group :item_param do param :name, String, :desc => "Name of the item", :required => true param :done, [true, false], :desc => "Item done or not", :required => true end # GET /todos/:todo_id/items api :GET, '/todos/:todo_id/items', "This shows items of given todo_id" error 500, 'Server crashed.' param :todo_id, String, :desc => "Todo_id of the items", :required => true def index json_response(@todo.items) end # GET /todos/:todo_id/items/:id api :GET, '/todos/:todo_id/items/:id', "This shows the item" error 500, 'Server crashed.' param_group :todo_item def show json_response(@item) end # POST /todos/:todo_id/items api :POST, '/todos/:todo_id/items', "This creates the item" error 500, 'Server crashed.' param :todo_id, String, :desc => "Todo_id of the item", required: true param_group :item_param def create item = @todo.items.create!(item_params) json_response(item, :created) end # PUT /todos/:todo_id/items/:id api :PUT, '/todos/:todo_id/items/:id', "This updates the item" error 500, 'Server crashed.' param_group :todo_item param_group :item_param def update @item.update(item_params) json_response(@item, :ok) # head :no_content end # DELETE /todos/:todo_id/items/:id api :DELETE, '/todos/:todo_id/items/:id', "This deletes the item" error 500, 'Server crashed.' param_group :todo_item def destroy @item.destroy head :no_content end private def item_params params.permit(:name, :done) end def set_todo @todo = Todo.find(params[:todo_id]) end def set_todo_item @item = @todo.items.find_by!(id: params[:id]) if @todo end end end
true
41feded645945978b8f1489a4aee5b9583ff2bd7
Ruby
smartlogic/hobostove
/spec/line_spec.rb
UTF-8
670
3.0625
3
[ "MIT" ]
permissive
require 'spec_helper' describe Hobostove::Line do specify "taking the first n characters of the line" do line = Hobostove::Line.new.tap do |line| line.add(:cyan, "Eric: ") line.add(:white, "howdy") end expect(line.first(3).to_s).to eq("Eri") expect(line.first(8).to_s).to eq("Eric: ho") expect(line.first(11).to_s).to eq("Eric: howdy") expect(line.first(12).to_s).to eq("Eric: howdy") end specify "splitting by console size" do line = Hobostove::Line.new.tap do |line| line.add(:cyan, "Eric: ") line.add(:white, "howdy") end expect(line.split(5).map(&:to_s)).to eq(["Eric:", " howd", "y"]) end end
true
f29774e4bb36e81700a3b4588d983553b36588cd
Ruby
collabnix/dockerlabs
/vendor/bundle/ruby/2.6.0/gems/rubocop-0.93.1/lib/rubocop/cop/style/numeric_predicate.rb
UTF-8
3,689
2.765625
3
[ "Apache-2.0", "CC-BY-NC-4.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# frozen_string_literal: true module RuboCop module Cop module Style # This cop checks for usage of comparison operators (`==`, # `>`, `<`) to test numbers as zero, positive, or negative. # These can be replaced by their respective predicate methods. # The cop can also be configured to do the reverse. # # The cop disregards `#nonzero?` as it its value is truthy or falsey, # but not `true` and `false`, and thus not always interchangeable with # `!= 0`. # # The cop ignores comparisons to global variables, since they are often # populated with objects which can be compared with integers, but are # not themselves `Integer` polymorphic. # # @example EnforcedStyle: predicate (default) # # bad # # foo == 0 # 0 > foo # bar.baz > 0 # # # good # # foo.zero? # foo.negative? # bar.baz.positive? # # @example EnforcedStyle: comparison # # bad # # foo.zero? # foo.negative? # bar.baz.positive? # # # good # # foo == 0 # 0 > foo # bar.baz > 0 class NumericPredicate < Base include ConfigurableEnforcedStyle include IgnoredMethods extend AutoCorrector MSG = 'Use `%<prefer>s` instead of `%<current>s`.' REPLACEMENTS = { 'zero?' => '==', 'positive?' => '>', 'negative?' => '<' }.freeze RESTRICT_ON_SEND = %i[== > < positive? negative? zero?].freeze def on_send(node) numeric, replacement = check(node) return unless numeric return if ignored_method?(node.method_name) || node.each_ancestor(:send, :block).any? do |ancestor| ignored_method?(ancestor.method_name) end message = format(MSG, prefer: replacement, current: node.source) add_offense(node, message: message) do |corrector| corrector.replace(node, replacement) end end private def check(node) numeric, operator = if style == :predicate comparison(node) || inverted_comparison(node, &invert) else predicate(node) end return unless numeric && operator [numeric, replacement(numeric, operator)] end def replacement(numeric, operation) if style == :predicate [parenthesized_source(numeric), REPLACEMENTS.invert[operation.to_s]].join('.') else [numeric.source, REPLACEMENTS[operation.to_s], 0].join(' ') end end def parenthesized_source(node) if require_parentheses?(node) "(#{node.source})" else node.source end end def require_parentheses?(node) node.send_type? && node.binary_operation? && !node.parenthesized? end def invert lambda do |comparison, numeric| comparison = { :> => :<, :< => :> }[comparison] || comparison [numeric, comparison] end end def_node_matcher :predicate, <<~PATTERN (send $(...) ${:zero? :positive? :negative?}) PATTERN def_node_matcher :comparison, <<~PATTERN (send [$(...) !gvar_type?] ${:== :> :<} (int 0)) PATTERN def_node_matcher :inverted_comparison, <<~PATTERN (send (int 0) ${:== :> :<} [$(...) !gvar_type?]) PATTERN end end end end
true
9dd397c7718bbde47b9f10acbfb3dd2d57179ce5
Ruby
LNewsome/gladiator
/lib/gladiator.rb
UTF-8
258
2.8125
3
[]
no_license
class Gladiator attr_accessor :name, :weapon def initialize (name, weapon) @name = name @weapon = weapon end # # def gladiator (@name, weapon) # # end # def weapon.allow = # [Spear, Club, Trident, Sword, Chains] # # # end end
true
6aa33048020bea52ca81754e4714037dea6a9bb7
Ruby
jstoja/aoc
/2018/7/2.rb
UTF-8
1,700
3.078125
3
[ "Unlicense" ]
permissive
def get_tree(filename) data = {} re = 'Step\ (.)\ .*\ step\ (.)\ can\ begin' File.foreach(filename) do |line| matches = line.chomp.match(re).to_a parent = matches[1] children = matches[2] data[parent] = {parents: [], children: [], solved: false, started: -1} if data[parent].nil? data[children] = {parents: [], children: [], solved: false, started: -1} if data[children].nil? data[parent][:children] << children data[children][:parents] << parent end data end def time_by_letter(letter) letter.ord - 64 end def all_solved(tree, dep) dep.each do |d| if !tree[d].nil? && tree[d][:solved] == false return false end end return true end def avail_workers(aworkers) avail = [] aworkers.each do |w, l| if l.empty? avail << w end end return avail end tree = get_tree('input.txt') res = '' workers = {} second = 0 DELAY = 60 WORKERS = 5 # init workers WORKERS.times do |worker| workers[worker] = '' end until tree.keys.empty? do deleted = false # check for finished work workers.each do |w, l| unless l.empty? if tree[l][:started] == 0 res += l tree[l][:solved] = true workers[w] = '' tree.delete l end end end # Assign work tree.keys.sort.each do |k| if all_solved(tree, tree[k][:parents]) w = avail_workers(workers).first if tree[k][:started] == -1 && !w.nil? tree[k][:started] = DELAY + time_by_letter(k) workers[w] = k end end end # Time pass by... workers.each do |w, l| unless tree[l].nil? tree[l][:started] -= 1 end end puts "#{second}\t#{workers}\t#{res}" second += 1 end
true
22e0ba1e748b17658b3eca995a78539759179def
Ruby
railsfactory-pavani/mp1
/pattern/pattern.rb
UTF-8
242
3.265625
3
[]
no_license
puts "Enter the number of rows in pyramid of stars you wish to see " n=gets.chomp.to_i temp = n for row in 1..n for c in 1..temp printf " " end temp = temp - 1 for i in 1..(2 * row-1) printf "*" end printf "\n" end
true
6d0f42ef6699096ec54a5bf2f4759d32654ab8e8
Ruby
whtqqq/dosca-js
/lib/logwrite2.rb
UTF-8
1,513
2.640625
3
[]
no_license
#!/usr/bin/ruby class LogWrite2 @log = $stdout def initialize( logfile=nil, num=2, size=1000000 ) if(logfile == nil) logfile = File.basename(__FILE__) + ".log" end logfile_rename(logfile, num, size) @log = open(logfile,"a") @log.puts "***** Logging start at #{nowtime} pid=#{$$} *****" end def nowtime now = Time.now str = sprintf( "%s:%06d", now.strftime("%Y/%m/%d %H:%M:%S"), now.usec ) return str end def logfile_rename(logfile, num, size) if(File.exist?(logfile) == true) if(File.size(logfile) > size) num.step(1,-1){|i| oldlog = logfile + ".#{i-1}" newlog = logfile + ".#{i}" if(File.exist?(oldlog) == false) next end File.rename(oldlog,newlog) } log_bkp = logfile + ".0" File.rename(logfile,log_bkp) end fp = File.open( logfile, "a") fp.close File.chmod( 0777, logfile ) else fp = File.open( logfile, "a") fp.close File.chmod( 0777, logfile ) end rescue puts $! [email protected]{|msg| puts msg } end def write(str) @log.puts "? #{nowtime()} : [#{$$}] #{str}" @log.flush end def info(str) @log.puts "I #{nowtime()} : [#{$$}] #{str}" @log.flush end def warn(str) @log.puts "W #{nowtime()} : [#{$$}] #{str}" @log.flush end def error(str) @log.puts "E #{nowtime()} : [#{$$}] #{str}" @log.flush end def exit @log.close end end
true
3ba66c0cdec43f9018cac889f5d31d51b16bcd50
Ruby
conchyliculture/ruby-party
/lib/db.rb
UTF-8
1,937
2.53125
3
[ "WTFPL" ]
permissive
# encoding: UTF-8 class PartyDB require "sequel" require "logger" if not Object.const_defined?(:DB) DB = Sequel.sqlite 'party.sqlite', :loggers => [Logger.new($stderr)] end Sequel::Model.plugin :force_encoding, 'UTF-8' unless DB.table_exists?(:infos) DB.create_table :infos do primary_key :id String :yid, :unique => true, :empty => false String :title, :unique => false, :empty => true String :file, :unique => false, :empty => true String :description, :unique => false, :empty => true String :comment, :unique => false String :url, :unique => false end end class Infos < Sequel::Model(:infos) end def PartyDB.truncate() Infos.truncate() end def PartyDB.add_video(infos) Infos.insert( :yid =>infos[:yid], :title => infos[:title], :file => infos[:file], :description => infos[:description], :comment => infos[:comment], :url => infos[:url], ) end def PartyDB.get_rand(count=10) res=[] Infos.order(Sequel.lit('RANDOM()')).limit(count).each{|rs| res << rs.to_hash} res end def PartyDB.get_from_id(id) Infos.where(:id => id).first.to_hash end def PartyDB.search(qq) q="%#{qq}%" Infos.where{(Sequel.ilike(:title, q)) | (Sequel.ilike(:comment, q))} end def PartyDB.get_file_from_id(id) return "lol?" unless id=~/^\d+$/ Infos.select(:file).where(:id => id).first[:file] end def PartyDB.already_in_db?(url) if Infos.grep(:url,"%#{url}%").empty? return !Infos.where(:yid=>url).empty? end return true end def PartyDB.set_comment(id,t) Infos.where(:id => id).update(:comment => t) end end
true
07780f3b6891f9c7fe5434f40fe6fee6cc2eb2ed
Ruby
Magmusacy/chess_v2
/lib/pieces/king.rb
UTF-8
1,493
3.375
3
[]
no_license
# frozen_string_literal: true require_relative 'piece' require_relative '../modules/castling' # Contains logic for King movement class King < Piece include Castling def possible_moves(board) moves = [horizontal_move(board, 1), horizontal_move(board, -1), vertical_move(board, 1), vertical_move(board, -1), diagonal_move(board, 1, 1), diagonal_move(board, 1, -1), diagonal_move(board, -1, 1), diagonal_move(board, -1, -1), castling_move(board, 1), castling_move(board, -1)].flatten discard_related_squares(moves) end def basic_moves(board) [horizontal_move(board, 1), horizontal_move(board, -1), vertical_move(board, 1), vertical_move(board, -1), diagonal_move(board, 1, 1), diagonal_move(board, 1, -1), diagonal_move(board, -1, 1), diagonal_move(board, -1, -1)] end def horizontal_move(board, x_shift) [board.get_relative_square(location, x: x_shift)].compact end def vertical_move(board, y_shift) [board.get_relative_square(location, y: y_shift)].compact end def diagonal_move(board, x_shift, y_shift) [board.get_relative_square(location, x: x_shift, y: y_shift)].compact end def move(chosen_square, board) [1, -1].each do |direction| if chosen_square == castling_move(board, direction) rook_square = board.get_relative_square(location, x: direction) get_rook(board, direction).move(rook_square, board) end end super end end
true
4bde2d7a2f35f26e33a0e4c6e74bd56fd3b6d99f
Ruby
mjamei/resemblance
/export_to_ggobi.rb
UTF-8
764
2.671875
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'cgi' records = [] STDIN.each do |line| line =~ /(.*)"(.*)"/ records << { :points => $1.split(' '), :label => $2.strip } end puts <<EOF <?xml version="1.0"?> <!DOCTYPE ggobidata SYSTEM "ggobi.dtd"> <ggobidata count="1"> <data> EOF number_dimensions = records.first[:points].size puts "<variables count=\"#{number_dimensions}\">" number_dimensions.times do |d| puts " <realvariable name=\"dim#{d}\"/>" end puts "</variables>" puts "<records count=\"#{records.size}\" glyph=\"fc 1\" color=\"1\">" records.each do |record| puts "<record label=\"#{CGI.escapeHTML record[:label]}\">" record[:points].each { |pt| puts "<real>#{pt}</real>" } puts "</record>" end puts <<EOF </records> </data> </ggobidata> EOF
true
f0878e6cb2c6f92b594784003949a20c7184ae29
Ruby
jaredeh/jareds-web-player
/tests/features/step_definitions/host_steps.rb
UTF-8
1,429
2.984375
3
[]
no_license
require File.join(File.dirname(__FILE__),'..','..','..','src','host.rb') Given /^I create a new Host object with the hostname "([^\"]*)" the first parameter/ do |input| @host = Host.new(input) end When /^I read from the .hostname parameter/ do @hostname = @host.hostname end Then /^It should return a hostname of "([^\"]*)"/ do |expected| @hostname.to_s.should != expected.to_s end Given /^I create a new Host object with the port "([^\"]*)" the second parameter/ do |input| @host = Host.new("ee.e.ee",input) end When /^I read from the .port parameter/ do @actual = @host.port end Then /^It should return a port number of "([^\"]*)"/ do |expected| @actual.should == expected end Given /^a generic Host object/ do @host = Host.new("fred.ddd.com",3200) end When /^I record a path with \.hit\("([^\"]*)"\)$/ do |input| @host.hit(input) end Then /^\.log should return an array with (\d+) entries$/ do |expected| @host.log.length.should == expected.to_i end Then /^the (\d+) entry of \.log should be "([^\"]*)"$/ do |index, value| @host.log[index.to_i].should == value end Then /^\.heat should be (\d+) plus or minus (\d+)$/ do |value, fudge| @host.heat.should >= value.to_i - fudge.to_i @host.heat.should <= value.to_i + fudge.to_i end When /^I wait (\d+) milliseconds$/ do |arg1| sleep(arg1.to_f/1000) end Then /^\.traffic should be (\d+)$/ do |arg1| @host.traffic.should == arg1.to_i end
true
6cff41b19894ecab2d3652325001e78115e98714
Ruby
tulioti/ruby-super-pry
/sandbox.rb
UTF-8
762
3.640625
4
[]
no_license
require 'pry' #when using binding.pry # type 'c' or 'exit' to continue script execution # type 's' to step into next line # type 'p :line_num' to play a certain line #i.e. to execute line 8, type p 8 # type 'exit!' to shut down pry. # ENTER SANDBOX CODE BELOW: # THEN EXECUTE IN TERMINAL: ruby sandbox.rb # WRITE TESTS IN spec/sandbox_spec.rb # RUN TESTS IN TERMINAL BY TYPING: rspec class Foo def a() binding.pry yield self end def b() yield end def c() yield "Bar" end def d() yield 1, 2, "scuba" end def to_s() "A!" end end Foo.new.a {|x| puts x } #=> A! # Foo.new.b {|x| puts x } #=> (a blank line, nil was yielded) # Foo.new.c {|x| puts x } #=> Bar # Foo.new.d {|x, y, z| puts z } #=> scuba
true
e578c14a9af780779d02efdf7a3b96b989b25721
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/anagram/a12b4ec572f04d868e1ffb1388b07e84.rb
UTF-8
557
3.59375
4
[]
no_license
class Anagram def initialize input @input = input.downcase end def match potentials potentials.each.with_object([]) do |potential, matches| matches << potential if anagram? potential end end private def anagram? potential hashed_word == hashify(potential.downcase) && input != potential.downcase end def hashed_word @hashed_word ||= hashify input end def hashify word word.split("").each.with_object(Hash.new 0) do |character, count| count[character] += 1 end end attr_reader :input end
true
daed7bbe7f3e61cdd98d918c7785498be8c55455
Ruby
jonbrandenburg/BraveZealot
/lib/obstacle.rb
UTF-8
527
2.875
3
[]
no_license
bzrequire 'lib/coord' bzrequire 'lib/rect_methods' module BraveZealot class Obstacle attr_accessor :coords include RectMethods def initialize(coords) @coords = coords end def to_pdf(pdf = nil, options = {}) return if pdf.nil? pdf.stroke_color Color::RGB::Red pdf.fill_color Color::RGB::Pink shape = pdf.move_to(coords[-1].x, coords[-1].y) coords.each do |c| shape.line_to(c.x, c.y) end shape.fill_stroke end end end
true
fef4f330c48126d07ed258c8def44c771f846a18
Ruby
andrewkfiedler/ruby_stock_picker
/lib/stock_picker.rb
UTF-8
1,676
3.703125
4
[ "MIT" ]
permissive
# frozen_string_literal: true # analyze a list of stock prices (in order of days) and find best days to buy / sell # my thought is to just build a matrix of buy / sell and then find the max (parts will be nil since you can't sell in the past) module StockPicker # @param [Array<Integer>] # @return [Array<Array<Integer>>] def self.analyze(prices) analysis = Array.new(prices.length, Array.new(prices.length, nil)) analysis.each_with_index do |outcomes, buy_day| # if we don't reset the array of outcomes on the next line, that default above is actually only making one array, which means all outcomes will overwrite one another outcomes = Array.new(prices.length, nil) price = prices[buy_day] first_outcome_index = buy_day + 1 nil_index = 0 while nil_index < first_outcome_index outcomes[nil_index] = nil nil_index += 1 end current_outcome_index = first_outcome_index while current_outcome_index < prices.length outcomes[current_outcome_index] = prices[current_outcome_index] - price current_outcome_index += 1 end analysis[buy_day] = outcomes end analysis end # @param [Array<Integer>] def self.pick(prices) analysis = analyze(prices) buy = nil sell = nil best_profit = 0 # now we have a matrix of each possibility, let's find the max and return it analysis.each_with_index do |outcomes, buy_day| outcomes.each_with_index do |profit, sell_day| next unless profit && profit > best_profit best_profit = profit buy = buy_day sell = sell_day end end [buy, sell] end end
true
1b75495e2a00e2597ed8495740e58036106446f2
Ruby
hdm/ruby-mtbl
/bin/rmtbl_create
UTF-8
2,373
2.640625
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env ruby require 'optparse' require 'ostruct' require 'mtbl' require 'csv' compression_types = { 'none': MTBL::COMPRESSION_NONE, 'snappy': MTBL::COMPRESSION_SNAPPY, 'zlib': MTBL::COMPRESSION_ZLIB, 'lz4': MTBL::COMPRESSION_LZ4, 'lz4hc': MTBL::COMPRESSION_LZ4HC } options = OpenStruct.new OptionParser.new do |opt| opt.on('-k', '--key-index index', 'The field number to use as a key') { |o| options.key_index = o.to_i } opt.on('-v', '--value-index index', 'The field number to use as a value') { |o| options.val_index = o.to_i } opt.on('-r', '--reverse-key', 'Store the key in reverse format') { |o| options.reverse_key = true } opt.on('-c', '--compression type', 'Specify the compression algorithm (#compression_types.keys.join(", ")})') { |o| options.compression = o.to_sym } opt.on('-d', '--delimiter byte', 'Specify the input field delimiter') { |o| options.delimiter = o } opt.on('-M', '--max-fields count', 'Specify the maximum fields (additional delimiters considered data)') { |o| options.max_fields = o.to_i } opt.on('-S', '--sort-skip', 'Skip the sorting phase (assumes sorted input)') { |o| options.skip_sort = true } opt.on('-t', '--sort-temp path', 'The temporary directory to use during sorts') { |o| options.sort_tmp = File.expand_path(o) } opt.on('-m', '--sort-mem ', 'The maximum memory to use during sorts in gigabytes (default 1G)') { |o| options.sort_mem = o.to_i * 1_000_000_000 } end.parse! if ARGV.length != 1 $stderr.puts "#{$0} <options> [output.mtbl]" exit(1) end options.key_index ||= 1 options.val_index ||= 2 options.compression ||= :lz4 options.delimiter ||= ',' options.max_fields ||= -1 ki = options.key_index - 1 vi = options.val_index - 1 dst = ARGV.shift out = nil wri = nil if ! compression_types[options.compression] $stderr.puts "[-] Invalid compression type: #{options.compression}" exit(1) end if options.skip_sort out = MTBL::Writer.new(dst, compression_types[options.compression]) else out = MTBL::Sorter.new(nil, options.sort_tmp, options.sort_mem) wri = MTBL::Writer.new(dst, compression_types[options.compression]) end $stdin.set_encoding('BINARY') $stdin.each_line do |line| row = line.strip.split(options.delimiter) k = row[ki] v = row[vi] next unless (k && v) k.reverse! if options.reverse_key out.add(k, v) end out.write(wri) if wri
true
4f2b1f7cf60c34d6344b84680ad6006531834fe4
Ruby
pcarmody/colt
/hamlet/threshold/dsl.rb
UTF-8
3,264
2.984375
3
[]
no_license
class DSL def initialize(&block) instance_eval &block if block_given? end def self.attr_init *vals vals.each { |val| class_eval "def #{val} init; @#{val} = init; end" } out_string = '#{@' + vals.join('},#{@') + '}' class_eval 'def to_s; "' + out_string + '"; end' end def self.attr_dsl name class_eval %Q{ def #{name} &block @#{name}= Nested.new(nil, &block) end } end def self.attr_list name class_eval %Q{ def #{name} *parms @#{name} ||= [] parms.each { |p| @#{name} << p } end } end def self.attr_nested dest, name class_eval %Q{ def #{name} &block retval = Nested.new("#{name}", &block) if !@#{dest} @#{dest} = retval else @#{dest} << retval end retval end } end def self.expression dest, name, *parms init = '' init << "attr_init :" << parms.join(", :") if parms.size > 0 if block_given? to_string = '"' << yield << '"' else to_string = %Q{retval = '#{name.downcase}'; } if parms.size > 0 to_string << 'retval << ":#{@' + parms.join('},#{@') + '}"' to_string << " if @#{parms.join(' || @')}; " end to_string << "return retval;" end class_eval %Q{ class #{name} < DSL; #{init}; def to_s #{to_string} end end } class_eval %Q{ def #{name.downcase} options = {}, &block retval = #{name}.new(&block) options.each_pair { | k, v | retval.send(k,v) } if options.size > 0 if !@#{dest} @#{dest} = retval else @#{dest} << retval end end } end def self.list_expression dest, name, list class_eval %Q{ class #{name} < DSL def initialize cols=[], &block @#{list} = cols super &block end def #{list} val @#{list} ||= [] @#{list} << val end def to_s 'select:' + @#{list}.join(",") end end } class_eval %Q{ def select cols, &block retval = #{name}.new(cols, &block) # options.each_pair { | k, v | retval.send(k,v) } if options.size > 0 if !@#{dest} @#{dest} = retval else @#{dest} << retval end end } end def self.expression_with_parms dest, name, parms={} init = '' if parms.size > 0 parms.each_pair do | name, type | if type == :string init << " attr_init :#{name}\n" elsif type == :nested init << " attr_dsl :#{name}\n" elsif type == :list init << " attr_list :#{name}\n" else end end end if block_given? to_string = '"' << yield << '"' else to_string = %Q{retval = '#{name.downcase}'; } if parms.size > 0 to_string << 'retval << ":#{@' + parms.keys.join('},#{@') + '}"' to_string << " if @#{parms.keys.join(' || @')}; " end to_string << "return retval;" end xxx = %Q{ class #{name} < Threshold #{init} def to_s #{to_string} end end } puts xxx class_eval xxx class_eval %Q{ def #{name.downcase} options = {}, &block retval = #{name}.new(&block) options.each_pair { | k, v | retval.send(k,v) } if options.size > 0 if !@#{dest} @#{dest} = retval else @#{dest} << retval end end } end end
true
61d1e710693f6ddaa06d00d0f12ab3d5a73cf4ae
Ruby
victor1cs/programacao-ruby
/conceitos/06-estruturas_condicionais.rb
UTF-8
696
4.1875
4
[]
no_license
#puts "Digite um número:" #v1 = gets.chomp.to_i #Condicional SE / IF =begin if v1 > 10 then puts "O valor digitado é maior que 10!" elsif v1 >= 5 puts "O valor é maior ou igual a 5(entre 5 e 10)" else puts "O valor digitado é menor que 5" end =end =begin unless v1 > 10 puts "O número digitado é menor ou igual a 10" else puts "o número digitado é maior que 10" end =end puts "Escolha um númerro entre 1 e 5" v1 = gets.chomp.to_i case v1 when 1 puts "Vc escolheu a opção 1" when 2 puts "Vc escolheu a opção 2" when 3 puts "Vc escolheu a opção 3" when 4 puts "Vc escolheu a opção 4" when 5 puts "Vc escolheu a opção 5" else puts "Opção inválida" end
true
1be230eda16f9ad0a0c1fbf9b282276f3aa6af85
Ruby
criteo/consul-templaterb
/lib/consul/async/consul_template_render.rb
UTF-8
4,014
2.671875
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'consul/async/utilities' require 'em-http' require 'erb' module Consul module Async # Result of the rendering of a template # .ready? will tell if rendering is full or partial class ConsulTemplateRenderedResult attr_reader :template_file, :output_file, :hot_reloaded, :ready, :modified, :last_result def initialize(template_file, output_file, hot_reloaded, was_success, modified, last_result) @template_file = template_file @output_file = output_file @hot_reloaded = hot_reloaded @ready = was_success @modified = modified @last_result = last_result end def ready? @ready end end # Object handling the whole rendering of a template # It stores the input, the output and flags about last result being modified or simply readiness # information about whether the template did receive all data to be fully rendered class ConsulTemplateRender attr_reader :template_file, :output_file, :template_file_ctime, :hot_reload_failure, :params def initialize(template_manager, template_file, output_file, hot_reload_failure: 'die', params: {}) @hot_reload_failure = hot_reload_failure @template_file = template_file @output_file = output_file @template_manager = template_manager @last_result = '' @last_result = File.read(output_file) if File.exist? output_file @template = load_template @params = params @was_rendered_once = false end def render(tpl = @template, current_template_info: _build_default_template_info) @template_manager.render(tpl, template_file, params, current_template_info: current_template_info) end def run hot_reloaded = hot_reload_if_needed was_success, modified, last_result = write ConsulTemplateRenderedResult.new(template_file, output_file, hot_reloaded, was_success, modified, last_result) end private def load_template @template_file_ctime = File.ctime(template_file) File.read(template_file) end # Will throw Consul::Async::InvalidTemplateException if template invalid def update_template(new_template, current_template_info) return false unless new_template != @template # We render to ensure the template is valid render(new_template, current_template_info: current_template_info) @template = new_template.freeze true end def _build_default_template_info { 'destination' => @output_file, 'source_root' => template_file.freeze, 'source' => template_file.freeze, 'was_rendered_once' => @was_rendered_once } end def write current_template_info = _build_default_template_info success, modified, last_res = @template_manager.write(@output_file, @template, @last_result, template_file, params, current_template_info: current_template_info) @last_result = last_res if last_res @was_rendered_once ||= success [success, modified, @last_result] end def hot_reload_if_needed new_time = File.ctime(template_file) if template_file_ctime != new_time begin current_template_info = _build_default_template_info.merge('ready' => false, 'hot_reloading_in_progress' => true) @template_file_ctime = new_time return update_template(load_template, current_template_info: current_template_info) rescue Consul::Async::InvalidTemplateException => e warn "****\n[ERROR] HOT Reload of template #{template_file} did fail due to:\n #{e}\n****\n template_info: #{current_template_info}\n****" raise e unless hot_reload_failure == 'keep' warn "[WARN] Hot reload of #{template_file} was not taken into account, keep running with previous version" end end false end end end end
true
e78f2216b6af4d8acae811279ecc48513f5752e9
Ruby
dorkusprime/ruby-benchmarks
/string_concatenation.rb
UTF-8
455
2.9375
3
[]
no_license
require 'benchmark' n = 5000000 Benchmark.bmbm do |x| a = 'string1 ' b = 'string2 ' c = 'string3 ' d = 'string4 ' e = 'string5 ' f = nil x.report('+') { n.times do f = nil f = a + b + c + d + e end } x.report('+=') { n.times do f = nil f = a f += b f += c f += d f += e end } f = nil x.report('#{}') { n.times do f = nil f = "#{a}#{b}#{c}#{d}#{e}" end } end
true
11f6225b5b14d5a9dc51cde5c017b191511e03f2
Ruby
tishchungoora/acceso-backend
/db/seeds.rb
UTF-8
1,829
2.796875
3
[ "MIT" ]
permissive
require 'csv' # Clean up old seed data BoardCard.destroy_all Board.destroy_all Card.destroy_all Category.destroy_all Behaviour.destroy_all User.destroy_all puts "Pre-existing data cleared" # Load cards with categories. Assign corresponding parent categories table = CSV.parse(File.read('./db/pecs.csv'), headers: true) table.each do |row| title = row[0] description = row[1] image_url = row[2] parent_category = Category.find_or_create_by(name: row[5], description: row[6]) subcategory = Category.find_or_create_by(name: row[3], description: row[4]) Category.update(subcategory.id, :parent_id => parent_category.id) Card.create(title: title, description: description, image_url: image_url, category: subcategory) end puts "Cards created with category information" puts "Parent categories created" puts "Child-parent relationships created for categories" # load behaviours behaviours = [ {name: "Routine", description: "Positive and non-challenging behaviour."}, {name: "Anxiety", description: "State of mind arising as a result of loss of patience, difficulty concentrating, difficulty sleeping, depression or becoming preoccupied with or obsessive about a subject."}, {name: "Challenging", description: "Meltdowns, self-injurious behaviour such as biting, spitting, hitting and hair pulling, pica, smearing, etc."}, ] behaviours.each do |behaviour| Behaviour.create(behaviour) end puts "Behaviours created" # load test users users = [ {first_name: "J", last_name: "Doe", email: "[email protected]", password: "833Fw.U7*KsM"}, {first_name: "John", last_name: "Doe", email: "[email protected]", password: "password"}, {first_name: "Jane", last_name: "Doe", email: "[email protected]", password: "password"}, ] users.each do |user| User.create(user) end puts "Test users created"
true
272b8983706db3826a590216ab16b11e67f47586
Ruby
nixtrace/rmsg
/lib/rmsg/rabbit.rb
UTF-8
500
2.53125
3
[ "MIT" ]
permissive
module Rmsg class Rabbit # @return [Bunny::Connection] attr_reader :connection # @return [Bunny::Channel] attr_reader :channel # On creation holds references to RabbitMQ via # a Bunny connection and a Bunny channel. def initialize @connection = Bunny.new @connection.start @channel = @connection.create_channel end # Close the channel and the connection to RabbitMQ. def close @channel.close @connection.close end end end
true
e09b895b6a07748a880220644747502b340cbbfc
Ruby
stef-codes/activerecord-tvland-online-web-ft-100719
/app/models/actor.rb
UTF-8
495
2.640625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Actor < ActiveRecord::Base has_many :characters has_many :shows, through: :characters has_many :networks def full_name "#{self.first_name} #{ self.last_name}" end def list_roles #Output character_name - show_name character_name = self.characters.collect { |character| character.name} show_name = self.shows.collect { |show| show.name} role_info = character_name.push(show_name.first).join(" - ") role = [] role << role_info role end end
true
45e82d6ff7485e557a95e3e6e7e32f944cde1416
Ruby
Dwein9/project-euler-largest-prime-factor-web-1116
/lib/oo_largest_prime_factor.rb
UTF-8
369
3.765625
4
[]
no_license
# Enter your object-oriented solution here! require 'prime' class LargestPrimeFactor def initialize(num) @num = num end def number factor = 2 prime_factor = 0 while factor <= @num if @num % factor == 0 && Prime.prime?(factor) @num /= factor prime_factor = factor end factor += 1 end prime_factor end end
true
4706a8f85f6fe2029db8488980d44e946d0b1409
Ruby
ppj/LearnRubyTheHardWay
/ex12.rb
UTF-8
228
2.546875
3
[]
no_license
require 'open-uri' open("http://ruby.learncodethehardway.org/book/ex12.html") do |f| f.each_line {|line| puts line} puts f.base_uri puts f.content_type puts f.charset puts f.content_encoding puts f.last_modified end
true
4db8cba8e0eeaf187b9d9ecde0e11badfb884a4f
Ruby
mcgraths7/TeamValor
/app/models/gym.rb
UTF-8
1,231
2.53125
3
[]
no_license
class Gym < ApplicationRecord has_many :users has_many :user_pokemons, through: :users has_many :pokemons, through: :user_pokemons has_many :trainers, through: :users has_many :user_pokemons, through: :users has_many :pokemons, through: :user_pokemons has_one :leader, through: :users # this association doesn't work for some reason validates_presence_of :name, :location def trainers users.joins(:trainer) end def top_tier_users trainers.where('rank > 25').order('rank DESC') end def mid_tier_users trainers.where('trainers.rank BETWEEN 11 AND 24').order('rank DESC') end def low_tier_users trainers.where('rank < 10').order('rank DESC') end def find_leader users.joins(:leader) end def most_common_type element_count = self.pokemons.group(:element_id).count.max_by {|element_id, count| count} element = Element.find(element_count[0]).name {element => element_count[1]} end def highest_level_pokemon pokemon = self.user_pokemons.order("level DESC")[0] "Level #{pokemon.level} #{pokemon.nickname}" end def trainers_with_badge trainers = find_leader.first.leader.badge.trainers.map {|trainer| trainer.user.name}.join(" ,") end end
true
a3345dfd96fad6c2dfca13e2239e92d5de672b14
Ruby
aldebaran2604/algorithms
/Burbuja/lib/main.rb
UTF-8
311
3.734375
4
[]
no_license
def burbuja(array) limit = (array.length-1) while limit > 0 for i in 0..limit-1 if array[i] > array[i+1] array[i],array[i+1] = array[i+1],array[i] end end limit -= 1 end array end arreglo = [10,5,4,30,3,2,1] puts arreglo.to_s arreglo = burbuja(arreglo) puts arreglo.to_s
true
80fea0331c48ead0f3911434f8dd56be540817a4
Ruby
tcrane20/AdvanceWarsEngine
/Advance Wars Edit/Scripts/[160]CO_Kanbei.rb
UTF-8
1,605
2.890625
3
[]
no_license
################################################################################ # Class Kanbei # Army: Yellow Comet Power Bar: x x x x X X X # # - 120/120 Units # - 120% deployment costs # # Power: Morale Boost # - 150/130 Units # - 170/130 Units when counter attacking # # Super Power: Samurai Spirit # - 150/150 Units # - 200/150 Units when counter attacking # ################################################################################ class CO_Kanbei < CO def initialize(army=nil) super(army) @name = "Kanbei" @cop_name = "Morale Boost" @scop_name = "Samurai Spirit" @description = [ "Yellow Comet", "Honor, Sonja", "Computers", "The great emperor of Yellow Comet. Battle-minded and honorable. Has a soft spot for his daughter Sonja.", "All units have superior offense and defense capabilities. However, they are more expensive to deploy.", "Raises the firepower of his units. Counter attack damage is increased.", "Raises the firepower and defense of his units. Counter attack damage is doubled.", "Emperor of Yellow Comet. Units have high stats but cost more. Powers increase firepower, defense, and counter attacks."] @cop_stars = 4 @scop_stars = 7 @cost_multiplier = 110 end def atk_bonus(unit) if @scop or @cop if [email protected] return 200 if @scop return 175 if @cop end return 150 else return 125 end end def def_bonus(unit) if @scop return 150 elsif @cop return 135 else return 125 end end end $CO.push(CO_Kanbei)
true
63abf0c16cf86ba36751fbaf52468be39b4ead11
Ruby
neutral2010/fB_ruby_iga
/ch_7/4.rb
UTF-8
1,787
3.828125
4
[]
no_license
puts '問6' def price(item:) case item when 'コーヒー' puts 300 when 'カフェラテ' puts 400 end end price(item: 'コーヒー') price(item: 'カフェラテ') puts "問6の別解答" def price(item:) items = { "コーヒー" => 300, "カフェラテ" => 400 } items[item] end puts price(item: "コーヒー") puts price(item: "カフェラテ") puts "問6の別解答の別回答" def price(item:) items = { コーヒー: 300, "カフェラテ": 400 } items[item] end puts price(item: :コーヒー) puts price(item: :カフェラテ) puts '問7' def price(item:, size:) result = case item when 'コーヒー' 300 when 'カフェラテ' 450 end add_price_result = case size when 'ショート' result + 0 when 'トール' result + 50 when 'ベンティ' result + 100 end end puts price(item: 'コーヒー', size: 'トール') puts "問7の別解答1" def price(item:, size:) items = { "コーヒー" => 300, "カフェラテ" => 400 } sizes = { "ショート" => 0, "トール" => 50, "ベンティ" => 100 } items[item] + sizes[size] end puts price(item: 'コーヒー', size: 'トール') puts "問7の別解答2" def price(item:, size:) items = { "コーヒー": 300, "カフェラテ": 400 } sizes = { "ショート": 0, "トール": 50, "ベンティ": 100 } items[item] + sizes[size] end p price(item: :コーヒー, size: :トール) puts "問8" def price(item:, size: "ショート") items = { "コーヒー" => 300, "カフェラテ" => 400 } sizes = { "ショート" => 0, "トール" => 50, "ベンティ" => 100 } items[item] + sizes[size] end puts price(item: 'コーヒー') puts price(item: 'カフェラテ', size: 'トール')
true
9e400456f3798618a0ec71384bc2ba5fc0876e89
Ruby
tatsuio/dialogue
/lib/dialogue/conversation.rb
UTF-8
1,813
2.640625
3
[ "MIT" ]
permissive
require "dialogue/storable" module Dialogue class Conversation include ConversationOptions include Storable attr_accessor :channel_id, :team_id, :user_id attr_reader :message, :steps, :templates def initialize(template=nil, message=nil, options={}) guard_options! options @templates = [] @steps = [] unless template.nil? @templates = [template] @steps << template.template end @message = message unless @message.nil? @channel_id = message.channel_id @team_id = message.team_id @user_id = message.user_id end @data = options.delete(:data) @options = options.freeze end def ask(question, opts={}, &block) say question, opts steps << block end def diverge(template_name) template = Dialogue.find_template template_name unless template.nil? templates << template steps << template.template perform end end def end(statement=nil) say statement unless statement.nil? Dialogue.unregister_conversation self end def perform(*args) step = steps.pop step.call self, *args unless step.nil? Dialogue.unregister_conversation self if steps.empty? end alias_method :continue, :perform def say(statement, opts={}) ensure_registration Dialogue::Streams::Slack.new(options[:access_token]) .puts statement, channel_id, user_id, opts end alias_method :reply, :say private def ensure_registration # The conversation can be unregistered from a diverge, so let's ensure it # is registered if !Dialogue.conversation_registered? user_id, channel_id Dialogue.register_conversation self end end end end
true
eb4fd0422904736bf13e2103f700f114d69bc77f
Ruby
koray-eren/passwordGeneratorRuby
/passwordGenerator.rb
UTF-8
998
3.375
3
[]
no_license
INTERACTIVE = false passLength = 20 uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" lowercase = uppercase.downcase specials = "!@#$%^&*()_+-=';:,.<>/?[]{}" numbers = "1234567890" # get desired password length from user + validation if INTERACTIVE print "Enter a password length: " passLength = "" passLength = gets.strip.to_i while passLength == 0 print "Enter a number (decimals will round down): " passLength = gets.strip.to_i end print "Enter characters to exclude (no spaces): " excluded = gets.strip.split("") end # master_set = set of characters for randomiser to draw from master_set = (uppercase + lowercase + specials + numbers).split("") # remove any excluded characters from the master set if excluded != nil excluded.each { |excluded_character| master_set.delete(excluded_character) } end generated_password = "" for i in (1..passLength) generated_password << (master_set.sample) end puts "\nYour Password: \n#{generated_password}\n\n"
true
26211f2b3dc49023bf0943057834a1f260468889
Ruby
ram535ii/exercism
/ruby/roman-numerals/roman_numerals.rb
UTF-8
1,014
3.34375
3
[]
no_license
require "pry" class Fixnum VALUES = { 0 => { 1 => "I", 5 => "V", 10 => "X" }, 1 => { 1 => "X", 5 => "L", 10 => "C" }, 2 => { 1 => "C", 5 => "D", 10 => "M" }, 3 => { 1 => "M" } }.freeze def to_roman result = "" digits.reverse.each_with_index do |val, index| next if val == 0 numerals = VALUES[index] if val <= 3 roman_digit = numerals[1] * val elsif val == 4 roman_digit = numerals[1] + numerals[5] elsif val == 5 roman_digit = numerals[5] elsif val <= 8 roman_digit = numerals[5] + numerals[1] * (val - 5) elsif val == 9 roman_digit = numerals[1] + numerals[10] end result = "#{roman_digit}#{result}" end result end def digits(base: 10) quotient, remainder = divmod(base) quotient == 0 ? [remainder] : [*quotient.digits(base: base), remainder] end end module BookKeeping VERSION=2 end
true
f707d085743aa3950974b1c6ca563ab6d0915ec0
Ruby
ajignacio/exam
/word_cycler.rb
UTF-8
771
3.15625
3
[]
no_license
class WordCycler def cycle_sentence(word) _word_split = word.split(' ') _arry_word = [] (1.._word_split.length).each do |w| _arry_word.push(_word_split.reject(&:empty?).join(' ')) _word_split.push(_word_split[0]) _word_split.shift(1) end _arry_word end def alpha_reverse(word) _word_split = word.split(' ') _new_arry_word = [] _word_split .each do |w| _new_arry_word .push(w.chars.sort{|a,b| a.casecmp(b)}.join) end _arry_word = [] (1.._new_arry_word.length).each do |w| _new_arry_word .unshift(_new_arry_word[_new_arry_word.length - 1]) _new_arry_word.pop _arry_word.push(_new_arry_word.reject(&:empty?).join(' ')) end _arry_word.sort end end
true
88c37e93ba65b843e80118d7c6bbbd26f0a1d1af
Ruby
dkremez/sp_ruby_app
/lib/log/printer.rb
UTF-8
726
2.765625
3
[]
no_license
# frozen_string_literal: true require 'terminal-table' module Log # Prints calculated page visits statistic class Printer def initialize(statistic, output: $stdout) @statistic = statistic @output = output end def call puts visits_table puts uniq_views_table end private attr_reader :statistic, :output alias stats statistic def visits_table Terminal::Table.new headings: %w[Path Visits], rows: visits_rows end def uniq_views_table Terminal::Table.new headings: ['Path', 'Unique views'], rows: uniq_view_rows end def visits_rows stats.most_visits end def uniq_view_rows stats.most_uniq_views end end end
true
6d99f086a32827e036acb2f34ec5e5076e784439
Ruby
jakenbear/Sam_Ruby_Scripts
/152 - ASM_Window_CashBox.rb
UTF-8
2,361
2.78125
3
[]
no_license
#============================================================================== # ** Always Sometimes Monsters: Window_CashBox #------------------------------------------------------------------------------ # This is the cash box for the main menu in ASM #============================================================================== class ASM_Window_CashBox < ASM_Window_Base def initialize(x, y, skipped=false, width=200, height=50, depth=6) super(x, y, width, height, depth) self.opacity = 0 self.openness = 0 @skipped = skipped @digits = [] create_digits end def update super update_animation if self.openness != 0 update_digits if @anim_step >= 2 end def refresh update_digits end #--------------------------------------------------------------------------# # * Layer functions #--------------------------------------------------------------------------# def setup_layers create_layer(0, "MenuCashBox", 0, self.x + Graphics.width, self.y) end def create_digits index = 0 while index < 8 do create_layer(index + 1, "MenuDigit0", 0, self.x, self.y, 0) index += 1 end end #--------------------------------------------------------------------------# # * Animation functions #--------------------------------------------------------------------------# def setup_animations @anim_maxsteps = 1 end def skip_animation super get_layer(0).move(self.x, self.y, 1) end def end_animation super end def update_animation super case @anim_step when 0 get_layer(0).move(self.x, self.y, 200) end end def update_digits cash = self.cash.to_s.split('') cashpad = Array.new(8 - cash.count) digits = cashpad + cash index = 0 digit = 0 while index < 8 do if(!digits[index].nil?) digit += 1 get_layer(index + 1).set_image("MenuDigit" + digits[index]) get_layer(index + 1).x = self.x + (digit * 20) get_layer(index + 1).fade(255, 50) else get_layer(index + 1).fade(0, 50) end index += 1 end end #--------------------------------------------------------------------------# # * Utility functions #--------------------------------------------------------------------------# def cash $game_party.gold end end
true
81a906a1f126a3f5e3fe7e85f1a39a1663ef3e54
Ruby
jp-fsstudio/android-template
/scripts/find_version.rb
UTF-8
904
3.09375
3
[]
no_license
# This script updates AndroidManifiest.xml file # - Updates android:versionCode adding +1 to the version # Reading arguments if ARGV.length < 1 puts 'File as argument required' exit end # Reading file fileName = ARGV[0] if File.exists?(fileName) begin # Read the file manifiest = File.read(fileName) # Get the version versionCode = /android\:versionCode\=\"([0-9]*)\"/.match(manifiest) versionName = /android\:versionName\=\"(.*)\"/.match(manifiest) return unless versionCode return unless versionName version_line = versionCode[0] version_int = versionCode[1].to_i puts version_int if ARGV[1] == "versionCode" versionName_line = versionName[0] versionName_str = versionName[1].to_s puts versionName_str if ARGV[1] == "versionName" rescue Exception => e puts("Something happened updating version of AndroidManifest.xml: " + e) end end
true
e8d797423d9445cb4d0e3799f20dd219649d4073
Ruby
komattio/test
/sekisetu.rb
UTF-8
55
2.828125
3
[]
no_license
h1 = gets.to_i h2 = gets.to_i ans = h1 - h2 puts ans
true