input stringlengths 109 5.2k | output stringlengths 7 509 |
|---|---|
Summarize the following code: def send_sms_confirmation!
return false if _TC_sms_blocked
return true if sms_confirmed?
return false if _TC_phone_number.blank?
format_phone_number
confirmation_code = TwilioContactable.confirmation_code(self, :sms)
# Use this class' confirmation_mes... | Sends an SMS validation request through the gateway |
Summarize the following code: def send_voice_confirmation!
return false if _TC_voice_blocked
return true if voice_confirmed?
return false if _TC_phone_number.blank?
format_phone_number
confirmation_code = TwilioContactable.confirmation_code(self, :voice)
response = TwilioContactab... | Begins a phone call to the user where they ll need to type their confirmation code |
Summarize the following code: def validate(value, format, raise_error=false)
unless FORMATS.key?(format)
raise FormatError, "Invalid data format: #{format}"
end
result = value =~ FORMATS[format] ? true : false
if raise_error && !result
raise ValidationError, "Invalid value \"#{va... | Validate data against provided format |
Summarize the following code: def call(url, settings, &block)
uri = URI.parse(url)
klass = adapter_class(uri.scheme)
session = klass.new(uri, settings.deep_dup)
session.start(&block)
end | Initiates a new session |
Summarize the following code: def all_fields(table, field_name, value)
body = savon.
call(:get_all_fields_records_given_a_field_name_and_value,
message: {
'strFeatureClassOrTableName' => table,
'strFieldNameToSearchOn' => field_name,
... | Performs a search for geo - attributes . |
Summarize the following code: def WHEN(condition, adjuster)
unless Validation.conditionable? condition
raise TypeError, 'wrong object for condition'
end
unless Validation.adjustable? adjuster
raise TypeError, 'wrong object for adjuster'
end
->v{_valid?(condition, v) ? adj... | Adjuster Builders Apply adjuster when passed condition . |
Summarize the following code: def INJECT(adjuster1, adjuster2, *adjusters)
adjusters = [adjuster1, adjuster2, *adjusters]
unless adjusters.all?{|f|adjustable? f}
raise TypeError, 'wrong object for adjuster'
end
->v{
adjusters.reduce(v){|ret, adjuster|adjuster.call ret}
}
... | Sequencial apply all adjusters . |
Summarize the following code: def PARSE(parser)
if !::Integer.equal?(parser) and !parser.respond_to?(:parse)
raise TypeError, 'wrong object for parser'
end
->v{
if ::Integer.equal? parser
::Kernel.Integer v
else
parser.parse(
case v
... | Accept any parser when that resopond to parse method . |
Summarize the following code: def get_class(name)
@class_list = get_class_list
@class_list.select {|x| x.include?(name)}.collect{|y| y.strip}
end | return the class match by name |
Summarize the following code: def connection
@options[:path] =API_REST + @options[:path]
@options[:headers] = HEADERS.merge({
'X-Megam-Date' => Time.now.strftime("%Y-%m-%d %H:%M")
}).merge(@options[:headers])
text.info("HTTP Request Data:")
text.msg("> HTTP #{@options[:scheme]}:/... | Make a lazy connection . |
Summarize the following code: def wake_deadline(start_time, timeout)
timeout = process_timeout(timeout)
deadline = start_time + timeout if timeout
end | Calculate the desired time to wake up . |
Summarize the following code: def crud_links(model, instance_name, actions, args={})
_html = ""
_options = args.keys.empty? ? '' : ", #{args.map{|k,v| ":#{k} => #{v}"}}"
if use_crud_icons
if actions.include?(:show)
_html << eval("link_to image_tag('/images/icons/view.png', :class ... | Display CRUD icons or links according to setting in use_crud_icons method . |
Summarize the following code: def obfuscated_link_to(path, image, label, args={})
_html = %{<form action="#{path}" method="get" class="obfuscated_link">}
_html << %{ <fieldset><input alt="#{label}" src="#{image}" type="image" /></fieldset>}
args.each{ |k,v| _html << %{ <div><input id="#{k.to_s}" name... | Create a link that is opaque to search engine spiders . |
Summarize the following code: def required_field_helper( model, element, html )
if model && ! model.errors.empty? && element.is_required
return content_tag( :div, html, :class => 'fieldWithErrors' )
else
return html
end
end | Wraps the given HTML in Rails default style to highlight validation errors if any . |
Summarize the following code: def select_tag_for_filter(model, nvpairs, params)
return unless model && nvpairs && ! nvpairs.empty?
options = { :query => params[:query] }
_url = url_for(eval("#{model}_url(options)"))
_html = %{<label for="show">Show:</label><br />}
_html << %{<select name="... | Use on index pages to create dropdown list of filtering criteria . Populate the filter list using a constant in the model corresponding to named scopes . |
Summarize the following code: def sort_link(model, field, params, html_options={})
if (field.to_sym == params[:by] || field == params[:by]) && params[:dir] == "ASC"
classname = "arrow-asc"
dir = "DESC"
elsif (field.to_sym == params[:by] || field == params[:by])
classname = "arrow-des... | Returns a link_to tag with sorting parameters that can be used with ActiveRecord . order_by . |
Summarize the following code: def tag_for_label_with_inline_help( label_text, field_id, help_text )
_html = ""
_html << %{<label for="#{field_id}">#{label_text}}
_html << %{<img src="/images/icons/help_icon.png" onclick="$('#{field_id}_help').toggle();" class='inline_icon' />}
_html << %{</label... | Create a set of tags for displaying a field label with inline help . Field label text is appended with a ? icon which responds to a click by showing or hiding the provided help text . |
Summarize the following code: def key_press(keys)
dump_caller_stack
if keys =~ /^Ctrl\+([A-Z])$/
filtered_keys = "^+#{$1}"
elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/
filtered_keys = "^+#{$1.downcase}"
elsif keys =~ /^Alt+([A-Z])$/
filtered_keys = "!+#{$1}"
elsif ... | wrapper of keyboard operations |
Summarize the following code: def open_file_dialog(title, filepath, text="")
wait_and_focus_window(title)
dialog = RFormSpec::OpenFileDialog.new(title, text)
dialog.enter_filepath(filepath)
sleep 1
dialog.click_open
end | standard open file dialog |
Summarize the following code: def parse(args)
# The options specified on the command line will be collected in
# *options*.
@options = Options.new
opt_parser = OptionParser.new do |parser|
@options.define_options(parser)
end
opt_parser.parse!(args)
@options
end | Return a structure describing the options . |
Summarize the following code: def add(path)
str = "#{path} filter=rgc diff=rgc"
if content.include?(str)
abort "`#{str}\n` is already included in #{@location}."
end
File.open(@location, 'a') do |f|
f.write("#{str}\n")
end
rescue Errno::ENOENT
abort "File #{@locat... | Add new path to the gitattributes file |
Summarize the following code: def run
logger.info("#{self.class.to_s} is starting.")
count_options = self.class.legacy_find_options.dup
count_options.delete(:order)
count_options.delete(:group)
count_options.delete(:limit)
count_options.delete(:offset)
@num_of_records = self.cl... | Runs the migration . |
Summarize the following code: def parents
page, parents = self, Array.new
while page.parent
page = page.parent
parents << page
end
parents
end | List parents closest to furthest . |
Summarize the following code: def extract_search_text(*attributes)
Array(attributes).map { |meth|
Nokogiri::HTML(self.send(meth)).xpath("//text()").
map {|node| text = node.text; text.try(:strip!); text}.join(" ")
}.reject(&:blank?).join("\n")
end | Extract text out of HTML or plain strings . Basically removes html formatting . |
Summarize the following code: def set_query_attributes!
attr_names = self.class.search_query_attributes.map(&:to_s)
self.query = attr_names.inject({}) { |memo, attr|
memo[attr] = self.send(attr)
memo
}
end | Build query attribute hash . |
Summarize the following code: def manager_ws_uri
# convert manager uri to websocket
uri = URI.parse(manager_uri)
uri.scheme = (uri.scheme == "https" ? "wss" : "ws")
uri.path = "/wsapi"
return uri.to_s
end | Get the WebSocket API URI |
Summarize the following code: def parse_config(conffile = nil)
conffile ||= Dir.glob([
"/etc/foreman_hooks-host_rename/settings.yaml",
"#{confdir}/settings.yaml"])[0]
raise "Could not locate the configuration file" if conffile.nil?
# Parse the configuration file
config = {
h... | Parse the configuration file |
Summarize the following code: def check_script(path)
binary=path.split(' ')[0]
raise "#{path} does not exist" unless File.exist? binary
raise "#{path} is not executable" unless File.executable? binary
path
end | Do additional sanity checking on a hook script |
Summarize the following code: def sync_host_table
uri = foreman_uri('/hosts?per_page=9999999')
debug "Loading hosts from #{uri}"
json = RestClient.get uri
debug "Got JSON: #{json}"
JSON.parse(json)['results'].each do |rec|
@db.execute "insert into host (id,name) values ( ?, ? )",
... | Get all the host IDs and FQDNs and populate the host table |
Summarize the following code: def initialize_database
@db = SQLite3::Database.new @database_path
File.chmod 0600, @database_path
begin
@db.execute 'drop table if exists host;'
@db.execute <<-SQL
create table host (
id INT,
name varchar(254)
... | Initialize an empty database |
Summarize the following code: def execute_hook_action
@rename = false
name = @rec['host']['name']
id = @rec['host']['id']
case @action
when 'create'
sql = "insert into host (id, name) values (?, ?)"
params = [id, name]
when 'update'
# Check if we are rena... | Update the database based on the foreman_hook |
Summarize the following code: def read_list(name)
opts = self.class.persisted_attrs[name]
if !lists[name] && opts[:default]
opts[:default]
else
send("#{name}=", lists[name].value) if lists[name].is_a?(Redis::Future)
lists[name]
end
end | Transform and read a list attribute |
Summarize the following code: def read_hash(name)
opts = self.class.persisted_attrs[name]
if !hashes[name] && opts[:default]
opts[:default]
else
self.send("#{name}=", hashes[name].value) if hashes[name].is_a?(Redis::Future)
hashes[name]
end
end | Transform and read a hash attribute |
Summarize the following code: def write_attribute(name, val)
if attributes.is_a?(Redis::Future)
value = attributes.value
self.attributes = value ? Hash[*self.class.fields.keys.zip(value).flatten] : {}
end
attributes[name] = self.class.transform(:to, name, val)
end | Transform and write a standard attribute value |
Summarize the following code: def write_list(name, val)
raise "RedisAssist: tried to store a #{val.class.name} as Array" unless val.is_a?(Array)
lists[name] = val
end | Transform and write a list value |
Summarize the following code: def write_hash(name, val)
raise "RedisAssist: tried to store a #{val.class.name} as Hash" unless val.is_a?(Hash)
hashes[name] = val
end | Transform and write a hash attribute |
Summarize the following code: def update_columns(attrs)
redis.multi do
attrs.each do |attr, value|
if self.class.fields.has_key?(attr)
write_attribute(attr, value)
redis.hset(key_for(:attributes), attr, self.class.transform(:to, attr, value)) unless new_record?
... | Update fields without hitting the callbacks |
Summarize the following code: def filter_authorized!(method, objects, user = current_user)
object_array = Array(objects)
object_array.select do |object|
policy = policy_for(object)
policy.can?(method, user)
end
end | Controller helper method to filter out non - authorized objects from the passed in array |
Summarize the following code: def can?(method, object, user = current_user)
policy = policy_for(object)
policy.can?(method, user)
end | Helper method available in controllers and views that returns the value of the policy method |
Summarize the following code: def nethash interval = 500, start = 0, stop = false
suffixe = stop ? "/#{stop}" : ''
JSON.parse(call_blockchain_api("nethash/#{interval}/#{start}#{suffixe}?format=json"))
end | shows statistics about difficulty and network power |
Summarize the following code: def last(limit=1, offset=0)
from = offset
to = from + limit - 1
members = redis.zrange(index_key_for(:id), (to * -1) + -1, (from * -1) + -1).reverse
find(limit > 1 ? members : members.first)
end | Find the first saved record |
Summarize the following code: def find(ids, opts={})
ids.is_a?(Array) ? find_by_ids(ids, opts) : find_by_id(ids, opts)
end | Find a record by id |
Summarize the following code: def find_in_batches(options={})
start = options[:start] || 0
marker = start
batch_size = options[:batch_size] || 500
record_ids = redis.zrange(index_key_for(:id), marker, marker + batch_size - 1)
while record_ids.length > 0
records_c... | Iterate over all records in batches |
Summarize the following code: def load_keymap(map) #:nodoc:
@maps ||= Hash.new
if @maps[map].nil? && File.file?(File.join(self.storage_path, map.to_s + "_map.yml"))
@maps[map] = YAML.load(File.open(File.join(self.storage_path, map.to_s + "_map.yml")))
logger.debug("#{self.class.to_s} lazy lo... | Lazy loader ... |
Summarize the following code: def mapped_key(map, key)
load_keymap(map.to_s)
@maps[map.to_s][handle_composite(key)]
end | Returns the deserialized mapped key when provided with the former key . |
Summarize the following code: def processor_count
@processor_count ||= begin
os_name = RbConfig::CONFIG["target_os"]
if os_name =~ /mingw|mswin/
require 'win32ole'
result = WIN32OLE.connect("winmgmts://").ExecQuery(
"select NumberOfLogicalProcessors from Win32_Proce... | Number of processors seen by the OS and used for process scheduling . |
Summarize the following code: def physical_processor_count
@physical_processor_count ||= begin
ppc = case RbConfig::CONFIG["target_os"]
when /darwin1/
IO.popen("/usr/sbin/sysctl -n hw.physicalcpu").read.to_i
when /linux/
cores = {} # unique physical ID / core ID combin... | Number of physical processor cores on the current system . |
Summarize the following code: def valid?(options = {})
options = {:input => {}}.merge(options)
errors = []
# initial sandbox
sandbox = _source(options)
# add in inputs
sandbox[:inputs] = options[:input]
validity = @filters.map do |filter_name, filter|
# find input f... | end def run |
Summarize the following code: def reload()
self.clear
self.concat File.read(event_file).split(/\r?\n/).map{|e| Event.new(e)}
end | Reload the events from the event file . Existing events are deleted first . |
Summarize the following code: def followee_of?(model)
0 < self.followers.by_model(model).limit(1).count * model.followees.by_model(self).limit(1).count
end | see if this model is followee of some model |
Summarize the following code: def ever_followed
follow = []
self.followed_history.each do |h|
follow << h.split('_')[0].constantize.find(h.split('_')[1])
end
follow
end | see model s followed history |
Summarize the following code: def wait(mutex, timeout = nil)
validate_mutex(mutex)
validate_timeout(timeout)
waitable = waitable_for_current_thread
@mutex.synchronize do
@waitables.push(waitable)
@waitables_to_resume.push(waitable)
end
waitable.wait(mutex, timeout)
... | Puts this thread to sleep until another thread resumes it . Threads will be woken in the chronological order that this was called . |
Summarize the following code: def validate_timeout(timeout)
unless timeout == nil
raise TypeError, "'timeout' must be nil or a Numeric" unless timeout.is_a?(Numeric)
raise ArgumentError, "'timeout' must not be negative" if timeout.negative?
end
end | Validates a timeout value |
Summarize the following code: def render(template_name, view_handler, locals, &content)
self.erb_source.render(template_name, render_locals(view_handler, locals), &content)
end | render the template including the handler as a local |
Summarize the following code: def run_entry
entry = get_entry()
output = '';
@keys.keys.select { |k| @config['key_fields'][k] && @keys[k] }.each do |key|
output += [ key, @keys[key] ].join(' ') + " "
end
unless entry
$stderr.puts "#{ output } is not supported on #{ @page_n... | this call initiates a race resistant attempt to make sure that there is only 1 clear winner among N potential agents attempting to run the same goal on the same spreadsheet agent s cell |
Summarize the following code: def pick(number, *cards)
ordered = cards.flatten.map do |card|
i = card_preference.map { |preference| card.type == preference }.index(true)
{card: card, index: i}
end
ordered.sort_by { |h| h[:index] || 99 }.first(number).map {|h| h[:card] }
end | you have the option of picking from many cards pick the best one . |
Summarize the following code: def discard
ordered = player.hand.map do |card|
i = card_preference.map { |preference| card.type == preference }.index(true)
{card: card, index: i}
end
ordered.sort_by { |h| h[:index] || 99 }.last.try(:fetch, :card)
end | This method is called if your hand is over the hand limit it returns the card that you would like to discard . Returning nil or a card you don t have is a very bad idea . Bad things will happen to you . |
Summarize the following code: def play
bangs_played = 0
while !player.hand.find_all(&:draws_cards?).empty?
player.hand.find_all(&:draws_cards?).each {|card| player.play_card(card)}
end
play_guns
player.hand.each do |card|
target = find_target(card)
next if skippable... | This is the method that is called on your turn . |
Summarize the following code: def sleep(timeout = nil)
validate_timeout(timeout)
unlock do
if timeout == nil || timeout == Float::INFINITY
elapsed_time = (timer { Thread.stop }).round
else
elapsed_time = Kernel.sleep(timeout)
end
end
end | Releases the lock and puts this thread to sleep . |
Summarize the following code: def temporarily_release(&block)
raise ArgumentError, 'no block given' unless block_given?
unlock
begin
return_value = yield
lock
rescue Exception
lock_immediately
raise
end
return_value
end | Temporarily unlocks it while a block is run . If an error is raised in the block the it will try to be immediately relocked before passing the error up . If unsuccessful a + ThreadError + will be raised to imitate the core s behavior . |
Summarize the following code: def timer(&block)
start_time = Time.now
yield(start_time)
time_elapsed = Time.now - start_time
end | Calculate time elapsed when running block . |
Summarize the following code: def wait
continue = false
trap "SIGINT" do
puts "Continuing..."
continue = true
end
puts "Waiting. Press ^C to continue test..."
wait_until(3600) { continue }
trap "SIGINT", "DEFAULT"
end | stalls test until ^C is hit useful for inspecting page state via firebug |
Summarize the following code: def optional_args_block_call(block, args)
if RUBY_VERSION >= "1.9.0"
if block.arity == 0
block.call
else
block.call(*args)
end
else
block.call(*args)
end
end | Makes a call to a block that accepts optional arguments |
Summarize the following code: def extract_file_rdoc(file, from = nil, reverse = false)
lines = File.readlines(file)
if from.nil? and reverse
lines = lines.reverse
elsif !reverse
lines = lines[(from || 0)..-1]
else
lines = lines[0...(from || -1)].reverse
end
... | Extracts the rdoc of a given ruby file source . |
Summarize the following code: def select(fields)
if (fields == []) || (fields.nil?)
fields = [:_id]
end
clone.tap {|q| q.options[:fields] = fields}
end | Add select method to select the fields to return |
Summarize the following code: def set_pagination_info(page_no, page_size, record_count)
@current_page = page_no
@per_page = page_size
@total_count = record_count
@total_pages = (record_count / page_size.to_f).ceil
extend PaginationMethods
self
end | Sets the pagination info |
Summarize the following code: def echo_uploads_data=(data)
parsed = JSON.parse Base64.decode64(data)
# parsed will look like:
# { 'attr1' => [ {'id' => 1, 'key' => 'abc...'} ] }
unless parsed.is_a? Hash
raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}"
end
p... | Pass in a hash that s been encoded as JSON and then Base64 . |
Summarize the following code: def follower_of?(model)
0 < self.followees.by_model(model).limit(1).count * model.followers.by_model(self).limit(1).count
end | see if this model is follower of some model |
Summarize the following code: def follow(*models)
models.each do |model|
unless model == self or self.follower_of?(model) or model.followee_of?(self) or self.cannot_follow.include?(model.class.name) or model.cannot_followed.include?(self.class.name)
model.followers.create!(:f_type => self.class.... | follow some model |
Summarize the following code: def unfollow(*models)
models.each do |model|
unless model == self or !self.follower_of?(model) or !model.followee_of?(self) or self.cannot_follow.include?(model.class.name) or model.cannot_followed.include?(self.class.name)
model.followers.by_model(self).first.destr... | unfollow some model |
Summarize the following code: def ever_follow
follow = []
self.follow_history.each do |h|
follow << h.split('_')[0].constantize.find(h.split('_')[1])
end
follow
end | see user s follow history |
Summarize the following code: def pop(non_block = false)
@pop_mutex.lock do
@mutex.synchronize do
if empty?
return if closed?
raise ThreadError if non_block
@mutex.unlock
@waiter.wait
@mutex.lock
return if closed?
... | Retrieves an item from it . |
Summarize the following code: def lookup(key, opts={}, &block)
unless addr = cache.has?(key)
addr = link.send('lookup', key, opts, &block)
cache.save(key, addr)
end
yield addr if block_given?
addr
end | Initialize can accept custom configuration parameters Lookup for a specific service key passed block is called with the result values in case of http backend it return the result directly |
Summarize the following code: def announce(key, port, opts={}, &block)
payload = [key,port]
link.send 'announce', payload, opts, &block
if config.auto_announce
periodically(config.auto_announce_interval) do
link.send 'announce', payload, opts, &block
end
end
end | Announce a specific service key available on specific port passed block is called when the announce is sent |
Summarize the following code: def _logical_operator(delegated, *conditions)
unless conditions.all?{|c|conditionable? c}
raise TypeError, 'wrong object for condition'
end
->v{
conditions.__send__(delegated) {|condition|
_valid? condition, v
}
}
end | Condition Builders A innner method for some condition builders . For build conditions AND NAND OR NOR XOR XNOR . |
Summarize the following code: def post_with_signature(opts)
path = opts.fetch(:path)
payload = opts.fetch(:payload)
secret = opts.fetch(:secret)
post path, {payload: payload}, generate_secret_header(secret, URI.encode_www_form(payload: payload))
end | Post to the given path including the correct signature header based on the payload and secret . |
Summarize the following code: def get_height(img)
new_height = (img.height / (img.width.to_f / self.width.to_f)).ceil
end | Finds height of the image relative to provided width |
Summarize the following code: def create_color_string
(0...img.height).map do |y|
(0...img.width).map do |x|
pix = self.img[x,y]
pix_vals = [r(pix), g(pix), b(pix)]
find_closest_term_color(pix_vals)
end
end.join
end | Iterates over each pixel of resized image to find closest color |
Summarize the following code: def find_closest_term_color(pixel_values)
color = ""
lil_dist = 195075
@@palette.each do |col_name, col_values|
dist = find_distance(col_values, pixel_values)
if dist < lil_dist
lil_dist = dist
color = col_name
end
end
... | Iterates over the palette to find the most similar color |
Summarize the following code: def draw_line(pixels)
pix_line = ""
pixels.each do |pixel|
pix_line = pix_line + " ".colorize(:background => find_color(pixel))
end
puts pix_line
end | Takes in a string of colors and puts them out as background colored spaces For example rGK creates a light_red square a green square and a black square |
Summarize the following code: def tree
@tree and return @tree
@tree = []
file_set = version_files
while child = file_set.shift
tree << child #if child.dir?
if child.type == "dir"
file_set.unshift( github.where(child.path).contents ).flatten!
end
end
... | build a depth first tree |
Summarize the following code: def search(options = {})
self.date = options[:date] || date
self.hd = options[:hd] || hd
response = HTTParty.get(DEFAULT_URL, query: attributes)
handle_response(response)
end | Returns APOD info for specified day . |
Summarize the following code: def process_timeout(timeout)
unless timeout == nil
raise TypeError, "'timeout' must be nil or a Numeric" unless timeout.is_a?(Numeric)
raise ArgumentError, "'timeout' must not be negative" if timeout.negative?
end
timeout = nil if timeout == Float::INFINIT... | Validates a timeout value converting to a acceptable value if necessary |
Summarize the following code: def find_or_create_authorization_by_note(note)
found_auth = list_authorizations.find {|auth| auth.note == note}
if found_auth
found_auth.token
else
create_authorization(note)
end
end | If there is already an authorization by this note use it ; otherwise create it |
Summarize the following code: def send(type, payload, opts = {}, &block)
res = http_send type, Oj.dump({"rid" => uuid, "data" => payload})
block.call(res) if block
res
end | Initialize passing configuration Send a message to grape |
Summarize the following code: def jquids_includes(options = {})
# Set the format for the datepickers
Jquids.format = options[:format] if options.has_key?(:format)
html_out = ""
if options.has_key?(:style)
html_out << stylesheet_link_tag(jq_ui_stylesheet(options[:style])) + "\n" unless... | Includes the stylesheets and javescripts into what ever view this is called to . |
Summarize the following code: def method_missing method, *args, &block
if args.empty?
@config.send(method)
else
@config.send("#{method}=", args.first)
end
end | Initialize an empty OpenStruct to hold configuration options To set a config option call the corresponding method with an argument . To retrieve a config option call the corresponding method without an argument . |
Summarize the following code: def to_s
today = arabno_to_hindi(day) + " "
today = today + HijriUmmAlqura::MONTHNAMES[month] + " "
today = today + arabno_to_hindi(year) + " هـ"
end | constructor return hijri date with month and day names |
Summarize the following code: def jd(date = self)
index = (12 * (date.year - 1)) + date.month - 16260
mcjdn = date.day + HijriUmmAlqura::UMMALQURA_DAT[index - 1] - 1
mcjdn = mcjdn + 2400000 - 0.5
return mcjdn
end | Hijri to julian |
Summarize the following code: def gd(date = self)
j_date = jd(date)
g_date = HijriUmmAlqura.jd_to_gd(j_date)
return g_date
end | Hijri to gregorian |
Summarize the following code: def add(date = self, offset, period)
y = period == 'y' ? (date.year + offset) : date.year
m = period == 'm' ? (month_of_year(date.year, date.month) + offset) : month_of_year(date.year, date.month)
d = date.day
begin
if (period == 'd' || period == 'w')
... | Add Days - Weeks - Months - Years |
Summarize the following code: def + (n)
case n
when Numeric then
j_date = jd + n * 1
result = HijriUmmAlqura.jd(j_date)
return result
end
raise TypeError, 'expected numeric'
end | comparison operator return hijri date plus n days |
Summarize the following code: def raise(exception = nil)
exception = case
when exception == nil then StandardError.new
when exception.is_a?(Exception) then exception
when Exception >= exception then exception.new
else
Kernel.raise(TypeError, "'exception' must be nil or an instance ... | Sets it to an error . |
Summarize the following code: def to_hash
index_hash = Hash.new
index_hash["json_claz"] = self.class.name
index_hash["creationDate"] = creationDate
index_hash["admin"] = admin
index_hash["type"] = type
index_hash["password"] = password
index_hash["name"] = name
index_hahs... | Transform the ruby obj - > to a Hash |
Summarize the following code: def site=(site)
if site != self.site
@site = site
uri = URI.parse(site)
@user = URI.decode(uri.user) if(uri.user)
@password = URI.decode(uri.password) if(uri.password)
@resource_class = self.send(:create_resource_class)
end
@site
... | sets the site for the class in which this module is extended |
Summarize the following code: def find(*args)
scope = args.slice!(0)
options = args.slice!(0) || {}
@resource_class.find(scope, options)
end | def all_attributes_set? site && user && password end routes to active resource find |
Summarize the following code: def create_resource_class
raise "Please set the site for #{self} class." unless(self.site)
created_class = Class.new(MingleResource)
created_class.format = :xml
setup_class(created_class)
created_class
end | creates an active resource class dynamically . All the attributes are set automatically . Avoid calling this method directly |
Summarize the following code: def run!
# load agent from config or cli opts
agent = load_agent()
fix_ownership()
# debug mode, stay in front
if @config[:debug] then
Logging::Logger.root.add_appenders("stdout")
return start_websocket_client()
end
# start daemon
validate_arg... | Run the agent app! |
Summarize the following code: def start_websocket_client
# make sure log level is still set correctly here
Bixby::Log.setup_logger(:level => Logging.appenders["file"].level)
logger.info "Started Bixby Agent #{Bixby::Agent::VERSION}"
@client = Bixby::WebSocket::Client.new(Bixby.agent.manager_ws_uri, Agen... | Open the WebSocket channel with the Manager |
Summarize the following code: def fix_ownership
return if Process.uid != 0
begin
uid = Etc.getpwnam("bixby").uid
gid = Etc.getgrnam("bixby").gid
# user/group exists, chown
File.chown(uid, gid, Bixby.path("var"), Bixby.path("etc"))
rescue ArgumentError
end
end | If running as root fix ownership of var and etc dirs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.