_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q12900 | IceCube.Validations::FixedValue.validate_day_lock | train | def validate_day_lock(time, start_time)
days_in_month = TimeUtil.days_in_month(time)
date = Date.new(time.year, time.month, time.day)
if value && value < 0
start = TimeUtil.day_of_month(value, date)
month_overflow = days_in_month - TimeUtil.days_in_next_month(time)
elsif value && value > 0
start = value
month_overflow = 0
else
start = TimeUtil.day_of_month(start_time.day, date)
month_overflow = 0
end
sleeps = start - date.day
if value && value > 0
until_next_month = days_in_month + sleeps
else
until_next_month = start < 28 ? days_in_month : TimeUtil.days_to_next_month(date)
until_next_month += sleeps - month_overflow
end
sleeps >= 0 ? sleeps : until_next_month
end | ruby | {
"resource": ""
} |
q12901 | IceCube.IcalBuilder.to_s | train | def to_s
arr = []
if freq = @hash.delete('FREQ')
arr << "FREQ=#{freq.join(',')}"
end
arr.concat(@hash.map do |key, value|
if value.is_a?(Array)
"#{key}=#{value.join(',')}"
end
end.compact)
arr.join(';')
end | ruby | {
"resource": ""
} |
q12902 | IceCube.Validations::HourOfDay.hour_of_day | train | def hour_of_day(*hours)
hours.flatten.each do |hour|
unless hour.is_a?(Integer)
raise ArgumentError, "expecting Integer value for hour, got #{hour.inspect}"
end
verify_alignment(hour, :hour, :hour_of_day) { |error| raise error }
validations_for(:hour_of_day) << Validation.new(hour)
end
clobber_base_validations(:hour)
self
end | ruby | {
"resource": ""
} |
q12903 | IceCube.Schedule.add_recurrence_time | train | def add_recurrence_time(time)
return if time.nil?
rule = SingleOccurrenceRule.new(time)
add_recurrence_rule rule
time
end | ruby | {
"resource": ""
} |
q12904 | IceCube.Schedule.add_exception_time | train | def add_exception_time(time)
return if time.nil?
rule = SingleOccurrenceRule.new(time)
add_exception_rule rule
time
end | ruby | {
"resource": ""
} |
q12905 | IceCube.Schedule.remove_recurrence_time | train | def remove_recurrence_time(time)
found = false
@all_recurrence_rules.delete_if do |rule|
found = true if rule.is_a?(SingleOccurrenceRule) && rule.time == time
end
time if found
end | ruby | {
"resource": ""
} |
q12906 | IceCube.Schedule.next_occurrences | train | def next_occurrences(num, from = nil, options = {})
from = TimeUtil.match_zone(from, start_time) || TimeUtil.now(start_time)
enumerate_occurrences(from + 1, nil, options).take(num)
end | ruby | {
"resource": ""
} |
q12907 | IceCube.Schedule.previous_occurrence | train | def previous_occurrence(from)
from = TimeUtil.match_zone(from, start_time) or raise ArgumentError, "Time required, got #{from.inspect}"
return nil if from <= start_time
enumerate_occurrences(start_time, from - 1).to_a.last
end | ruby | {
"resource": ""
} |
q12908 | IceCube.Schedule.previous_occurrences | train | def previous_occurrences(num, from)
from = TimeUtil.match_zone(from, start_time) or raise ArgumentError, "Time required, got #{from.inspect}"
return [] if from <= start_time
a = enumerate_occurrences(start_time, from - 1).to_a
a.size > num ? a[-1*num,a.size] : a
end | ruby | {
"resource": ""
} |
q12909 | IceCube.Schedule.occurs_between? | train | def occurs_between?(begin_time, closing_time, options = {})
enumerate_occurrences(begin_time, closing_time, options).next
true
rescue StopIteration
false
end | ruby | {
"resource": ""
} |
q12910 | IceCube.Schedule.occurs_on? | train | def occurs_on?(date)
date = TimeUtil.ensure_date(date)
begin_time = TimeUtil.beginning_of_date(date, start_time)
closing_time = TimeUtil.end_of_date(date, start_time)
occurs_between?(begin_time, closing_time)
end | ruby | {
"resource": ""
} |
q12911 | IceCube.Schedule.occurring_at? | train | def occurring_at?(time)
time = TimeUtil.match_zone(time, start_time) or raise ArgumentError, "Time required, got #{time.inspect}"
if duration > 0
return false if exception_time?(time)
occurs_between?(time - duration + 1, time)
else
occurs_at?(time)
end
end | ruby | {
"resource": ""
} |
q12912 | IceCube.Schedule.conflicts_with? | train | def conflicts_with?(other_schedule, closing_time = nil)
closing_time = TimeUtil.ensure_time(closing_time)
unless terminating? || other_schedule.terminating? || closing_time
raise ArgumentError, "One or both schedules must be terminating to use #conflicts_with?"
end
# Pick the terminating schedule, and other schedule
# No need to reverse if terminating? or there is a closing time
terminating_schedule = self
unless terminating? || closing_time
terminating_schedule, other_schedule = other_schedule, terminating_schedule
end
# Go through each occurrence of the terminating schedule and determine
# if the other occurs at that time
#
last_time = nil
terminating_schedule.each_occurrence do |time|
if closing_time && time > closing_time
last_time = closing_time
break
end
last_time = time
return true if other_schedule.occurring_at?(time)
end
# Due to durations, we need to walk up to the end time, and verify in the
# other direction
if last_time
last_time += terminating_schedule.duration
other_schedule.each_occurrence do |time|
break if time > last_time
return true if terminating_schedule.occurring_at?(time)
end
end
# No conflict, return false
false
end | ruby | {
"resource": ""
} |
q12913 | IceCube.Schedule.first | train | def first(n = nil)
occurrences = enumerate_occurrences(start_time).take(n || 1)
n.nil? ? occurrences.first : occurrences
end | ruby | {
"resource": ""
} |
q12914 | IceCube.Schedule.last | train | def last(n = nil)
require_terminating_rules
occurrences = enumerate_occurrences(start_time).to_a
n.nil? ? occurrences.last : occurrences[-n..-1]
end | ruby | {
"resource": ""
} |
q12915 | IceCube.Schedule.to_ical | train | def to_ical(force_utc = false)
pieces = []
pieces << "DTSTART#{IcalBuilder.ical_format(start_time, force_utc)}"
pieces.concat recurrence_rules.map { |r| "RRULE:#{r.to_ical}" }
pieces.concat exception_rules.map { |r| "EXRULE:#{r.to_ical}" }
pieces.concat recurrence_times_without_start_time.map { |t| "RDATE#{IcalBuilder.ical_format(t, force_utc)}" }
pieces.concat exception_times.map { |t| "EXDATE#{IcalBuilder.ical_format(t, force_utc)}" }
pieces << "DTEND#{IcalBuilder.ical_format(end_time, force_utc)}" if end_time
pieces.join("\n")
end | ruby | {
"resource": ""
} |
q12916 | IceCube.Schedule.to_hash | train | def to_hash
data = {}
data[:start_time] = TimeUtil.serialize_time(start_time)
data[:start_date] = data[:start_time] if IceCube.compatibility <= 11
data[:end_time] = TimeUtil.serialize_time(end_time) if end_time
data[:rrules] = recurrence_rules.map(&:to_hash)
if IceCube.compatibility <= 11 && exception_rules.any?
data[:exrules] = exception_rules.map(&:to_hash)
end
data[:rtimes] = recurrence_times.map do |rt|
TimeUtil.serialize_time(rt)
end
data[:extimes] = exception_times.map do |et|
TimeUtil.serialize_time(et)
end
data
end | ruby | {
"resource": ""
} |
q12917 | IceCube.Schedule.enumerate_occurrences | train | def enumerate_occurrences(opening_time, closing_time = nil, options = {})
opening_time = TimeUtil.match_zone(opening_time, start_time)
closing_time = TimeUtil.match_zone(closing_time, start_time)
opening_time += TimeUtil.subsec(start_time) - TimeUtil.subsec(opening_time)
opening_time = start_time if opening_time < start_time
spans = options[:spans] == true && duration != 0
Enumerator.new do |yielder|
reset
t1 = full_required? ? start_time : opening_time
t1 -= duration if spans
t1 = start_time if t1 < start_time
loop do
break unless (t0 = next_time(t1, closing_time))
break if closing_time && t0 > closing_time
if (spans ? (t0.end_time > opening_time) : (t0 >= opening_time))
yielder << (block_given? ? yield(t0) : t0)
end
t1 = t0 + 1
end
end
end | ruby | {
"resource": ""
} |
q12918 | IceCube.WeeklyRule.wday_offset | train | def wday_offset(step_time, start_time)
return 0 if step_time == start_time
wday_validations = other_interval_validations.select { |v| v.type == :wday }
return 0 if wday_validations.none?
days = step_time.to_date - start_time.to_date
interval = base_interval_validation.validate(step_time, start_time).to_i
min_wday = wday_validations.map { |v| TimeUtil.normalize_wday(v.day, week_start) }.min
step_wday = TimeUtil.normalize_wday(step_time.wday, week_start)
days + interval - step_wday + min_wday
end | ruby | {
"resource": ""
} |
q12919 | Trello.Client.find | train | def find(path, id, params = {})
response = get("/#{path.to_s.pluralize}/#{id}", params)
trello_class = class_from_path(path)
trello_class.parse response do |data|
data.client = self
end
end | ruby | {
"resource": ""
} |
q12920 | Trello.Client.find_many | train | def find_many(trello_class, path, params = {})
response = get(path, params)
trello_class.parse_many response do |data|
data.client = self
end
end | ruby | {
"resource": ""
} |
q12921 | Trello.LabelName.update_fields | train | def update_fields(fields)
attributes[:yellow] = fields['yellow'] || attributes[:yellow]
attributes[:red] = fields['red'] || attributes[:red]
attributes[:orange] = fields['orange'] || attributes[:orange]
attributes[:green] = fields['green'] || attributes[:green]
attributes[:purple] = fields['purple'] || attributes[:purple]
attributes[:blue] = fields['blue'] || attributes[:blue]
attributes[:sky] = fields['sky'] || attributes[:sky]
attributes[:pink] = fields['pink'] || attributes[:pink]
attributes[:lime] = fields['lime'] || attributes[:lime]
attributes[:black] = fields['black'] || attributes[:black]
self
end | ruby | {
"resource": ""
} |
q12922 | Trello.Webhook.save | train | def save
# If we have an id, just update our fields.
return update! if id
from_response client.post("/webhooks", {
description: description,
idModel: id_model,
callbackURL: callback_url
})
end | ruby | {
"resource": ""
} |
q12923 | Trello.Webhook.update! | train | def update!
client.put("/webhooks/#{id}", {
description: description,
idModel: id_model,
callbackURL: callback_url,
active: active
})
end | ruby | {
"resource": ""
} |
q12924 | Trello.PluginDatum.update_fields | train | def update_fields(fields)
attributes[:id] = fields['id'] || attributes[:id]
attributes[:idPlugin] = fields['idPlugin'] || attributes[:idPlugin]
attributes[:scope] = fields['scope'] || attributes[:scope]
attributes[:value] = JSON.parse(fields['value']).presence if fields.has_key?('value')
attributes[:idModel] = fields['idModel'] || attributes[:idModel]
attributes[:access] = fields['access'] || attributes[:access]
self
end | ruby | {
"resource": ""
} |
q12925 | Trello.Card.update_fields | train | def update_fields(fields)
attributes[:id] = fields[SYMBOL_TO_STRING[:id]] || attributes[:id]
attributes[:short_id] = fields[SYMBOL_TO_STRING[:short_id]] || attributes[:short_id]
attributes[:name] = fields[SYMBOL_TO_STRING[:name]] || fields[:name] || attributes[:name]
attributes[:desc] = fields[SYMBOL_TO_STRING[:desc]] || fields[:desc] || attributes[:desc]
attributes[:due] = Time.iso8601(fields[SYMBOL_TO_STRING[:due]]) rescue nil if fields.has_key?(SYMBOL_TO_STRING[:due])
attributes[:due] = fields[:due] if fields.has_key?(:due)
attributes[:due_complete] = fields[SYMBOL_TO_STRING[:due_complete]] if fields.has_key?(SYMBOL_TO_STRING[:due_complete])
attributes[:due_complete] ||= false
attributes[:closed] = fields[SYMBOL_TO_STRING[:closed]] if fields.has_key?(SYMBOL_TO_STRING[:closed])
attributes[:url] = fields[SYMBOL_TO_STRING[:url]] || attributes[:url]
attributes[:short_url] = fields[SYMBOL_TO_STRING[:short_url]] || attributes[:short_url]
attributes[:board_id] = fields[SYMBOL_TO_STRING[:board_id]] || attributes[:board_id]
attributes[:member_ids] = fields[SYMBOL_TO_STRING[:member_ids]] || fields[:member_ids] || attributes[:member_ids]
attributes[:list_id] = fields[SYMBOL_TO_STRING[:list_id]] || fields[:list_id] || attributes[:list_id]
attributes[:pos] = fields[SYMBOL_TO_STRING[:pos]] || fields[:pos] || attributes[:pos]
attributes[:labels] = (fields[SYMBOL_TO_STRING[:labels]] || []).map { |lbl| Trello::Label.new(lbl) }.presence || attributes[:labels].presence || []
attributes[:card_labels] = fields[SYMBOL_TO_STRING[:card_labels]] || fields[:card_labels] || attributes[:card_labels]
attributes[:last_activity_date] = Time.iso8601(fields[SYMBOL_TO_STRING[:last_activity_date]]) rescue nil if fields.has_key?(SYMBOL_TO_STRING[:last_activity_date])
attributes[:cover_image_id] = fields[SYMBOL_TO_STRING[:cover_image_id]] || attributes[:cover_image_id]
attributes[:badges] = fields[SYMBOL_TO_STRING[:badges]] || attributes[:badges]
attributes[:card_members] = fields[SYMBOL_TO_STRING[:card_members]] || attributes[:card_members]
attributes[:source_card_id] = fields[SYMBOL_TO_STRING[:source_card_id]] || fields[:source_card_id] || attributes[:source_card_id]
attributes[:source_card_properties] = fields[SYMBOL_TO_STRING[:source_card_properties]] || fields[:source_card_properties] || attributes[:source_card_properties]
self
end | ruby | {
"resource": ""
} |
q12926 | Trello.Card.update! | train | def update!
@previously_changed = changes
# extract only new values to build payload
payload = Hash[changes.map { |key, values| [SYMBOL_TO_STRING[key.to_sym].to_sym, values[1]] }]
@changed_attributes.clear
client.put("/cards/#{id}", payload)
end | ruby | {
"resource": ""
} |
q12927 | Trello.Card.move_to_list | train | def move_to_list(list)
list_number = list.is_a?(String) ? list : list.id
unless list_id == list_number
client.put("/cards/#{id}/idList", {
value: list_number
})
end
end | ruby | {
"resource": ""
} |
q12928 | Trello.Card.move_to_list_on_any_board | train | def move_to_list_on_any_board(list_id)
list = List.find(list_id)
if board.id == list.board_id
move_to_list(list_id)
else
move_to_board(Board.find(list.board_id), list)
end
end | ruby | {
"resource": ""
} |
q12929 | Trello.Card.upvote | train | def upvote
begin
client.post("/cards/#{id}/membersVoted", {
value: me.id
})
rescue Trello::Error => e
fail e unless e.message =~ /has already voted/i
end
self
end | ruby | {
"resource": ""
} |
q12930 | Trello.Card.remove_upvote | train | def remove_upvote
begin
client.delete("/cards/#{id}/membersVoted/#{me.id}")
rescue Trello::Error => e
fail e unless e.message =~ /has not voted/i
end
self
end | ruby | {
"resource": ""
} |
q12931 | Trello.Card.add_label | train | def add_label(label)
unless label.valid?
errors.add(:label, "is not valid.")
return Trello.logger.warn "Label is not valid." unless label.valid?
end
client.post("/cards/#{id}/idLabels", {value: label.id})
end | ruby | {
"resource": ""
} |
q12932 | Trello.Card.remove_label | train | def remove_label(label)
unless label.valid?
errors.add(:label, "is not valid.")
return Trello.logger.warn "Label is not valid." unless label.valid?
end
client.delete("/cards/#{id}/idLabels/#{label.id}")
end | ruby | {
"resource": ""
} |
q12933 | Trello.Card.add_attachment | train | def add_attachment(attachment, name = '')
# Is it a file object or a string (url)?
if attachment.respond_to?(:path) && attachment.respond_to?(:read)
client.post("/cards/#{id}/attachments", {
file: attachment,
name: name
})
else
client.post("/cards/#{id}/attachments", {
url: attachment,
name: name
})
end
end | ruby | {
"resource": ""
} |
q12934 | Trello.Card.attachments | train | def attachments
attachments = Attachment.from_response client.get("/cards/#{id}/attachments")
MultiAssociation.new(self, attachments).proxy
end | ruby | {
"resource": ""
} |
q12935 | Trello.Organization.boards | train | def boards
boards = Board.from_response client.get("/organizations/#{id}/boards/all")
MultiAssociation.new(self, boards).proxy
end | ruby | {
"resource": ""
} |
q12936 | Trello.Organization.members | train | def members(params = {})
members = Member.from_response client.get("/organizations/#{id}/members/all", params)
MultiAssociation.new(self, members).proxy
end | ruby | {
"resource": ""
} |
q12937 | Trello.Comment.update_fields | train | def update_fields(fields)
attributes[:action_id] = fields['id'] || attributes[:action_id]
attributes[:text] = fields['data']['text'] || attributes[:text]
attributes[:date] = Time.iso8601(fields['date']) if fields.has_key?('date')
attributes[:member_creator_id] = fields['idMemberCreator'] || attributes[:member_creator_id]
self
end | ruby | {
"resource": ""
} |
q12938 | Trello.Attachment.update_fields | train | def update_fields(fields)
attributes[:name] = fields['name'] || attributes[:name]
attributes[:id] = fields['id'] || attributes[:id]
attributes[:pos] = fields['pos'] || attributes[:pos]
attributes[:url] = fields['url'] || attributes[:url]
attributes[:bytes] = fields['bytes'].to_i || attributes[:bytes]
attributes[:member_id] = fields['idMember'] || attributes[:member_id]
attributes[:date] = Time.parse(fields['date']).presence || attributes[:date]
attributes[:is_upload] = fields['isUpload'] if fields.has_key?('isUpload')
attributes[:mime_type] = fields['mimeType'] || attributes[:mime_type]
attributes[:previews] = fields['previews'] if fields.has_key?('previews')
self
end | ruby | {
"resource": ""
} |
q12939 | Trello.CustomFieldItem.option_value | train | def option_value
if option_id
option_endpoint = "/customFields/#{custom_field_id}/options/#{option_id}"
option = CustomFieldOption.from_response client.get(option_endpoint)
option.value
end
end | ruby | {
"resource": ""
} |
q12940 | Trello.Checklist.update_fields | train | def update_fields(fields)
attributes[:id] = fields['id'] || attributes[:id]
attributes[:name] = fields['name'] || fields[:name] || attributes[:name]
attributes[:description] = fields['desc'] || attributes[:description]
attributes[:closed] = fields['closed'] if fields.has_key?('closed')
attributes[:url] = fields['url'] || attributes[:url]
attributes[:check_items] = fields['checkItems'] if fields.has_key?('checkItems')
attributes[:position] = fields['pos'] || attributes[:position]
attributes[:board_id] = fields['idBoard'] || attributes[:board_id]
attributes[:card_id] = fields['idCard'] || fields[:card_id] || attributes[:card_id]
attributes[:list_id] = fields['idList'] || attributes[:list_id]
attributes[:member_ids] = fields['idMembers'] || attributes[:member_ids]
self
end | ruby | {
"resource": ""
} |
q12941 | Trello.Checklist.save | train | def save
return update! if id
from_response(client.post("/checklists", {
name: name,
idCard: card_id
}))
end | ruby | {
"resource": ""
} |
q12942 | Trello.Checklist.members | train | def members
members = member_ids.map do |member_id|
Member.find(member_id)
end
MultiAssociation.new(self, members).proxy
end | ruby | {
"resource": ""
} |
q12943 | Trello.Checklist.add_item | train | def add_item(name, checked = false, position = 'bottom')
client.post("/checklists/#{id}/checkItems", {name: name, checked: checked, pos: position})
end | ruby | {
"resource": ""
} |
q12944 | Trello.HasActions.actions | train | def actions(options = {})
actions = Action.from_response client.get("#{request_prefix}/actions", { filter: :all }.merge(options))
MultiAssociation.new(self, actions).proxy
end | ruby | {
"resource": ""
} |
q12945 | Trello.CheckItemState.update_fields | train | def update_fields(fields)
attributes[:id] = fields['id'] || attributes[:id]
attributes[:state] = fields['state'] || attributes[:state]
attributes[:item_id] = fields['idCheckItem'] || attributes[:item_id]
self
end | ruby | {
"resource": ""
} |
q12946 | PragmaticSegmenter.Cleaner.clean | train | def clean
return unless text
remove_all_newlines
replace_double_newlines
replace_newlines
replace_escaped_newlines
@text.apply(HTML::All)
replace_punctuation_in_brackets
@text.apply(InlineFormattingRule)
clean_quotations
clean_table_of_contents
check_for_no_space_in_between_sentences
clean_consecutive_characters
end | ruby | {
"resource": ""
} |
q12947 | MessageBus.HTTPClient.subscribe | train | def subscribe(channel, last_message_id: nil, &callback)
raise InvalidChannel unless channel.to_s.start_with?("/")
raise MissingBlock unless block_given?
last_message_id = -1 if last_message_id && !last_message_id.is_a?(Integer)
@channels[channel] ||= Channel.new
channel = @channels[channel]
channel.last_message_id = last_message_id if last_message_id
channel.callbacks.push(callback)
start if stopped?
end | ruby | {
"resource": ""
} |
q12948 | MessageBus.HTTPClient.unsubscribe | train | def unsubscribe(channel, &callback)
if callback
@channels[channel].callbacks.delete(callback)
remove_channel(channel) if @channels[channel].callbacks.empty?
else
remove_channel(channel)
end
stop if @channels.empty?
@status
end | ruby | {
"resource": ""
} |
q12949 | AnyCable.RPCHandler.connect | train | def connect(request, _unused_call)
logger.debug("RPC Connect: #{request.inspect}")
socket = build_socket(env: rack_env(request))
connection = factory.call(socket)
connection.handle_open
if socket.closed?
AnyCable::ConnectionResponse.new(status: AnyCable::Status::FAILURE)
else
AnyCable::ConnectionResponse.new(
status: AnyCable::Status::SUCCESS,
identifiers: connection.identifiers_json,
transmissions: socket.transmissions
)
end
rescue StandardError => exp
notify_exception(exp, :connect, request)
AnyCable::ConnectionResponse.new(
status: AnyCable::Status::ERROR,
error_msg: exp.message
)
end | ruby | {
"resource": ""
} |
q12950 | AnyCable.RPCHandler.rack_env | train | def rack_env(request)
uri = URI.parse(request.path)
# Minimum required variables according to Rack Spec
env = {
"REQUEST_METHOD" => "GET",
"SCRIPT_NAME" => "",
"PATH_INFO" => uri.path,
"QUERY_STRING" => uri.query,
"SERVER_NAME" => uri.host,
"SERVER_PORT" => uri.port.to_s,
"HTTP_HOST" => uri.host,
"REMOTE_ADDR" => request.headers.delete("REMOTE_ADDR"),
"rack.url_scheme" => uri.scheme,
"rack.input" => ""
}
env.merge!(build_headers(request.headers))
end | ruby | {
"resource": ""
} |
q12951 | AnyCable.Config.to_grpc_params | train | def to_grpc_params
{
pool_size: rpc_pool_size,
max_waiting_requests: rpc_max_waiting_requests,
poll_period: rpc_poll_period,
pool_keep_alive: rpc_pool_keep_alive,
server_args: rpc_server_args
}
end | ruby | {
"resource": ""
} |
q12952 | AnyCable.Config.to_redis_params | train | def to_redis_params
{ url: redis_url }.tap do |params|
next if redis_sentinels.nil?
raise ArgumentError, "redis_sentinels must be an array; got #{redis_sentinels}" unless
redis_sentinels.is_a?(Array)
next if redis_sentinels.empty?
params[:sentinels] = redis_sentinels.map(&method(:parse_sentinel))
end
end | ruby | {
"resource": ""
} |
q12953 | AnyCable.Server.start | train | def start
return if running?
raise "Cannot re-start stopped server" if stopped?
check_default_host
logger.info "RPC server is starting..."
@start_thread = Thread.new { grpc_server.run }
grpc_server.wait_till_running
logger.info "RPC server is listening on #{host}"
end | ruby | {
"resource": ""
} |
q12954 | Jekyll.TableOfContentsFilter.toc_only | train | def toc_only(html)
Jekyll.logger.warn 'Deprecation: toc_only filter is deprecated and will be remove in jekyll-toc v1.0.',
'Use `{% toc %}` instead of `{{ content | toc_only }}`.'
return '' unless toc_enabled?
TableOfContents::Parser.new(html, toc_config).build_toc
end | ruby | {
"resource": ""
} |
q12955 | PhusionPassenger.Utils.generate_random_id | train | def generate_random_id(method)
data = File.open("/dev/urandom", "rb") do |f|
f.read(64)
end
case method
when :base64
data = base64(data)
data.gsub!("+", '')
data.gsub!("/", '')
data.gsub!(/==$/, '')
return data
when :hex
return data.unpack('H*')[0]
else
raise ArgumentError, "Invalid method #{method.inspect}"
end
end | ruby | {
"resource": ""
} |
q12956 | PhusionPassenger.Utils.print_exception | train | def print_exception(current_location, exception, destination = nil)
if !exception.is_a?(SystemExit)
data = exception.backtrace_string(current_location)
if defined?(DebugLogging) && self.is_a?(DebugLogging)
error(data)
else
destination ||= STDERR
destination.puts(data)
destination.flush if destination.respond_to?(:flush)
end
end
end | ruby | {
"resource": ""
} |
q12957 | PhusionPassenger.Utils.create_thread_and_abort_on_exception | train | def create_thread_and_abort_on_exception(*args)
Thread.new do
Thread.current.abort_on_exception = true
begin
yield(*args)
rescue SystemExit
raise
rescue Exception => e
print_exception(nil, e)
exit(1)
end
end
end | ruby | {
"resource": ""
} |
q12958 | PhusionPassenger.Utils.process_is_alive? | train | def process_is_alive?(pid)
begin
Process.kill(0, pid)
return true
rescue Errno::ESRCH
return false
rescue SystemCallError => e
return true
end
end | ruby | {
"resource": ""
} |
q12959 | PhusionPassenger.Utils.global_backtrace_report | train | def global_backtrace_report
if Kernel.respond_to?(:caller_for_all_threads)
all_thread_stacks = caller_for_all_threads
elsif Thread.respond_to?(:list) && Thread.public_method_defined?(:backtrace)
all_thread_stacks = {}
Thread.list.each do |thread|
all_thread_stacks[thread] = thread.backtrace
end
end
output = "========== Process #{Process.pid}: backtrace dump ==========\n"
if all_thread_stacks
all_thread_stacks.each_pair do |thread, stack|
if thread_name = thread[:name]
thread_name = "(#{thread_name})"
end
stack ||= ["(empty)"]
output << ("-" * 60) << "\n"
output << "# Thread: #{thread.inspect}#{thread_name}, "
if thread == Thread.main
output << "[main thread], "
end
if thread == Thread.current
output << "[current thread], "
end
output << "alive = #{thread.alive?}\n"
output << ("-" * 60) << "\n"
output << " " << stack.join("\n ")
output << "\n\n"
end
else
output << ("-" * 60) << "\n"
output << "# Current thread: #{Thread.current.inspect}\n"
output << ("-" * 60) << "\n"
output << " " << caller.join("\n ")
end
return output
end | ruby | {
"resource": ""
} |
q12960 | PhusionPassenger.NativeSupportLoader.current_user_name_or_id | train | def current_user_name_or_id
require 'etc' if !defined?(Etc)
begin
user = Etc.getpwuid(Process.uid)
rescue ArgumentError
user = nil
end
if user
return user.name
else
return "##{Process.uid}"
end
end | ruby | {
"resource": ""
} |
q12961 | PhusionPassenger.LoaderSharedHelpers.maybe_make_path_relative_to_app_root | train | def maybe_make_path_relative_to_app_root(app_root, abs_path)
if Dir.logical_pwd == app_root && File.dirname(abs_path) == app_root
File.basename(abs_path)
else
abs_path
end
end | ruby | {
"resource": ""
} |
q12962 | PhusionPassenger.LoaderSharedHelpers.before_handling_requests | train | def before_handling_requests(forked, options)
if forked
# Reseed pseudo-random number generator for security reasons.
srand
end
if options["process_title"] && !options["process_title"].empty?
$0 = options["process_title"] + ": " + options["app_group_name"]
end
# If we were forked from a preloader process then clear or
# re-establish ActiveRecord database connections. This prevents
# child processes from concurrently accessing the same
# database connection handles.
if forked && defined?(ActiveRecord::Base)
if ActiveRecord::Base.respond_to?(:clear_all_connections!)
ActiveRecord::Base.clear_all_connections!
elsif ActiveRecord::Base.respond_to?(:clear_active_connections!)
ActiveRecord::Base.clear_active_connections!
elsif ActiveRecord::Base.respond_to?(:connected?) &&
ActiveRecord::Base.connected?
ActiveRecord::Base.establish_connection
end
end
# Fire off events.
PhusionPassenger.call_event(:starting_worker_process, forked)
if options["pool_account_username"] && options["pool_account_password_base64"]
password = options["pool_account_password_base64"].unpack('m').first
PhusionPassenger.call_event(:credentials,
options["pool_account_username"], password)
else
PhusionPassenger.call_event(:credentials, nil, nil)
end
end | ruby | {
"resource": ""
} |
q12963 | PhusionPassenger.MessageChannel.read_hash | train | def read_hash
buffer = new_buffer
if !@io.read(HEADER_SIZE, buffer)
return nil
end
while buffer.size < HEADER_SIZE
tmp = @io.read(HEADER_SIZE - buffer.size)
if tmp.empty?
return nil
else
buffer << tmp
end
end
chunk_size = buffer.unpack(UINT16_PACK_FORMAT)[0]
if !@io.read(chunk_size, buffer)
return nil
end
while buffer.size < chunk_size
tmp = @io.read(chunk_size - buffer.size)
if tmp.empty?
return nil
else
buffer << tmp
end
end
result = {}
offset = 0
delimiter_pos = buffer.index(DELIMITER, offset)
while !delimiter_pos.nil?
if delimiter_pos == 0
name = ""
else
name = buffer[offset .. delimiter_pos - 1]
end
offset = delimiter_pos + 1
delimiter_pos = buffer.index(DELIMITER, offset)
if delimiter_pos.nil?
raise InvalidHashError
elsif delimiter_pos == 0
value = ""
else
value = buffer[offset .. delimiter_pos - 1]
end
result[name] = value
offset = delimiter_pos + 1
delimiter_pos = buffer.index(DELIMITER, offset)
end
return result
rescue Errno::ECONNRESET
return nil
end | ruby | {
"resource": ""
} |
q12964 | PhusionPassenger.MessageChannel.read_scalar | train | def read_scalar(buffer = new_buffer, max_size = nil)
if !@io.read(4, buffer)
return nil
end
while buffer.size < 4
tmp = @io.read(4 - buffer.size)
if tmp.empty?
return nil
else
buffer << tmp
end
end
size = buffer.unpack(UINT32_PACK_FORMAT)[0]
if size == 0
buffer.replace('')
return buffer
else
if !max_size.nil? && size > max_size
raise SecurityError, "Scalar message size (#{size}) " <<
"exceeds maximum allowed size (#{max_size})."
end
if !@io.read(size, buffer)
return nil
end
if buffer.size < size
tmp = ''
while buffer.size < size
if !@io.read(size - buffer.size, tmp)
return nil
else
buffer << tmp
end
end
end
return buffer
end
rescue Errno::ECONNRESET
return nil
end | ruby | {
"resource": ""
} |
q12965 | PhusionPassenger.RequestHandler.cleanup | train | def cleanup
if @main_loop_thread
@main_loop_thread_lock.synchronize do
@graceful_termination_pipe[1].close rescue nil
end
@main_loop_thread.join
end
@server_sockets.each_value do |info|
socket = info[:socket]
type = get_socket_address_type(info[:address])
begin
socket.close if !socket.closed?
rescue Exception => e
# Ignore "stream closed" error, which occurs in some unit tests.
# We catch Exception here instead of IOError because of a Ruby 1.8.7 bug.
if e.to_s !~ /stream closed/ && e.message.to_s !~ /stream closed/
raise e
end
end
if type == :unix
filename = info[:address].sub(/^unix:/, '')
File.unlink(filename) rescue nil
end
end
@owner_pipe.close rescue nil
end | ruby | {
"resource": ""
} |
q12966 | PhusionPassenger.RequestHandler.main_loop | train | def main_loop
debug("Entering request handler main loop")
reset_signal_handlers
begin
@graceful_termination_pipe = IO.pipe
@graceful_termination_pipe[0].close_on_exec!
@graceful_termination_pipe[1].close_on_exec!
@main_loop_thread_lock.synchronize do
@main_loop_generation += 1
@main_loop_running = true
@main_loop_thread_cond.broadcast
@select_timeout = nil
@selectable_sockets = []
@server_sockets.each_value do |value|
socket = value[2]
@selectable_sockets << socket if socket
end
@selectable_sockets << @owner_pipe
@selectable_sockets << @graceful_termination_pipe[0]
end
install_useful_signal_handlers
start_threads
wait_until_termination_requested
wait_until_all_threads_are_idle
terminate_threads
debug("Request handler main loop exited normally")
rescue EOFError
# Exit main loop.
trace(2, "Request handler main loop interrupted by EOFError exception")
rescue Interrupt
# Exit main loop.
trace(2, "Request handler main loop interrupted by Interrupt exception")
rescue SignalException => signal
trace(2, "Request handler main loop interrupted by SignalException")
if signal.message != HARD_TERMINATION_SIGNAL
raise
end
rescue Exception => e
trace(2, "Request handler main loop interrupted by #{e.class} exception")
raise
ensure
debug("Exiting request handler main loop")
revert_signal_handlers
@main_loop_thread_lock.synchronize do
@graceful_termination_pipe[1].close rescue nil
@graceful_termination_pipe[0].close rescue nil
@selectable_sockets = []
@main_loop_generation += 1
@main_loop_running = false
@main_loop_thread_cond.broadcast
end
end
end | ruby | {
"resource": ""
} |
q12967 | PhusionPassenger.RequestHandler.reset_signal_handlers | train | def reset_signal_handlers
Signal.list_trappable.each_key do |signal|
begin
prev_handler = trap(signal, DEFAULT)
if prev_handler != DEFAULT
@previous_signal_handlers[signal] = prev_handler
end
rescue ArgumentError
# Signal cannot be trapped; ignore it.
end
end
trap('HUP', IGNORE)
PhusionPassenger.call_event(:after_installing_signal_handlers)
end | ruby | {
"resource": ""
} |
q12968 | ActiveInteraction.Filter.default | train | def default(context = nil)
raise NoDefaultError, name unless default?
value = raw_default(context)
raise InvalidValueError if value.is_a?(GroupedInput)
cast(value, context)
rescue InvalidNestedValueError => error
raise InvalidDefaultError, "#{name}: #{value.inspect} (#{error})"
rescue InvalidValueError, MissingValueError
raise InvalidDefaultError, "#{name}: #{value.inspect}"
end | ruby | {
"resource": ""
} |
q12969 | ActiveInteraction.ActiveRecordable.column_for_attribute | train | def column_for_attribute(name)
filter = self.class.filters[name]
FilterColumn.intern(filter.database_column_type) if filter
end | ruby | {
"resource": ""
} |
q12970 | Business.Calendar.add_business_days | train | def add_business_days(date, delta)
date = roll_forward(date)
delta.times do
begin
date += day_interval_for(date)
end until business_day?(date)
end
date
end | ruby | {
"resource": ""
} |
q12971 | Business.Calendar.subtract_business_days | train | def subtract_business_days(date, delta)
date = roll_backward(date)
delta.times do
begin
date -= day_interval_for(date)
end until business_day?(date)
end
date
end | ruby | {
"resource": ""
} |
q12972 | Business.Calendar.set_working_days | train | def set_working_days(working_days)
@working_days = (working_days || default_working_days).map do |day|
day.downcase.strip[0..2].tap do |normalised_day|
raise "Invalid day #{day}" unless DAY_NAMES.include?(normalised_day)
end
end
extra_working_dates_names = @extra_working_dates.map { |d| d.strftime("%a").downcase }
return if (extra_working_dates_names & @working_days).none?
raise ArgumentError, 'Extra working dates cannot be on working days'
end | ruby | {
"resource": ""
} |
q12973 | Slanger.Channel.dispatch | train | def dispatch(message, channel)
push(Oj.dump(message, mode: :compat)) unless channel =~ /\Aslanger:/
perform_client_webhook!(message)
end | ruby | {
"resource": ""
} |
q12974 | Slanger.Handler.onmessage | train | def onmessage(msg)
msg = Oj.strict_load(msg)
msg['data'] = Oj.strict_load(msg['data']) if msg['data'].is_a? String
event = msg['event'].gsub(/\Apusher:/, 'pusher_')
if event =~ /\Aclient-/
msg['socket_id'] = connection.socket_id
Channel.send_client_message msg
elsif respond_to? event, true
send event, msg
end
rescue JSON::ParserError
error({ code: 5001, message: "Invalid JSON" })
rescue Exception => e
error({ code: 500, message: "#{e.message}\n #{e.backtrace.join "\n"}" })
end | ruby | {
"resource": ""
} |
q12975 | Slanger.PresenceChannel.dispatch | train | def dispatch(message, channel)
if channel =~ /\Aslanger:/
# Messages received from the Redis channel slanger:* carry info on
# subscriptions. Update our subscribers accordingly.
update_subscribers message
else
push Oj.dump(message, mode: :compat)
end
end | ruby | {
"resource": ""
} |
q12976 | JsonApiClient.Schema.add | train | def add(name, options)
@properties[name.to_sym] = Property.new(name.to_sym, options[:type], options[:default])
end | ruby | {
"resource": ""
} |
q12977 | JsonApiClient.Connection.use | train | def use(middleware, *args, &block)
return if faraday.builder.locked?
faraday.builder.insert_before(Middleware::ParseJson, middleware, *args, &block)
end | ruby | {
"resource": ""
} |
q12978 | JsonApiClient.Resource.destroy | train | def destroy
self.last_result_set = self.class.requestor.destroy(self)
if last_result_set.has_errors?
fill_errors
false
else
mark_as_destroyed!
self.relationships.last_result_set = nil
_clear_cached_relationships
_clear_belongs_to_params
true
end
end | ruby | {
"resource": ""
} |
q12979 | HTMLProofer.UrlValidator.new_url_query_values? | train | def new_url_query_values?(uri, paths_with_queries)
queries = uri.query_values.keys.join('-')
domain_path = extract_domain_path(uri)
if paths_with_queries[domain_path].nil?
paths_with_queries[domain_path] = [queries]
true
elsif !paths_with_queries[domain_path].include?(queries)
paths_with_queries[domain_path] << queries
true
else
false
end
end | ruby | {
"resource": ""
} |
q12980 | HTMLProofer.UrlValidator.external_link_checker | train | def external_link_checker(external_urls)
external_urls = Hash[external_urls.sort]
count = external_urls.length
check_text = pluralize(count, 'external link', 'external links')
@logger.log :info, "Checking #{check_text}..."
# Route log from Typhoeus/Ethon to our own logger
Ethon.logger = @logger
establish_queue(external_urls)
@hydra.run
end | ruby | {
"resource": ""
} |
q12981 | HTMLProofer.UrlValidator.check_hash_in_2xx_response | train | def check_hash_in_2xx_response(href, effective_url, response, filenames)
return false if @options[:only_4xx]
return false unless @options[:check_external_hash]
return false unless (hash = hash?(href))
body_doc = create_nokogiri(response.body)
unencoded_hash = Addressable::URI.unescape(hash)
xpath = %(//*[@name="#{hash}"]|/*[@name="#{unencoded_hash}"]|//*[@id="#{hash}"]|//*[@id="#{unencoded_hash}"])
# user-content is a special addition by GitHub.
if URI.parse(href).host =~ /github\.com/i
xpath << %(|//*[@name="user-content-#{hash}"]|//*[@id="user-content-#{hash}"])
# when linking to a file on GitHub, like #L12-L34, only the first "L" portion
# will be identified as a linkable portion
if hash =~ /\A(L\d)+/
xpath << %(|//td[@id="#{Regexp.last_match[1]}"])
end
end
return unless body_doc.xpath(xpath).empty?
msg = "External link #{href} failed: #{effective_url} exists, but the hash '#{hash}' does not"
add_external_issue(filenames, msg, response.code)
@cache.add(href, filenames, response.code, msg)
true
end | ruby | {
"resource": ""
} |
q12982 | HTMLProofer.Runner.check_files | train | def check_files
@external_urls = {}
process_files.each do |item|
@external_urls.merge!(item[:external_urls])
@failures.concat(item[:failures])
end
# TODO: lazy. if we're checking only external links,
# we'll just trash all the failed tests. really, we should
# just not run those other checks at all.
if @options[:external_only]
@failures = []
validate_urls
elsif !@options[:disable_external]
validate_urls
end
end | ruby | {
"resource": ""
} |
q12983 | HTMLProofer.Runner.process_files | train | def process_files
if @options[:parallel].empty?
files.map { |path| check_path(path) }
else
Parallel.map(files, @options[:parallel]) { |path| check_path(path) }
end
end | ruby | {
"resource": ""
} |
q12984 | Yt.Request.set_request_body! | train | def set_request_body!(request)
case @request_format
when :json then request.body = (camelize_keys! @body).to_json
when :form then request.set_form_data @body
when :file then request.body_stream = @body
end if @body
end | ruby | {
"resource": ""
} |
q12985 | Yt.Request.parse_response! | train | def parse_response!
response.body = case @response_format
when :xml then Hash.from_xml response.body
when :json then JSON response.body
end if response.body
end | ruby | {
"resource": ""
} |
q12986 | Yt.Request.server_errors | train | def server_errors
[
OpenSSL::SSL::SSLError,
Errno::ETIMEDOUT,
Errno::EHOSTUNREACH,
Errno::ENETUNREACH,
Errno::ECONNRESET,
Net::OpenTimeout,
SocketError,
Net::HTTPServerError
] + extra_server_errors
end | ruby | {
"resource": ""
} |
q12987 | Byebug.PryProcessor.perform | train | def perform(action, options = {})
return unless %i[
backtrace
down
finish
frame
next
step
up
].include?(action)
send("perform_#{action}", options)
end | ruby | {
"resource": ""
} |
q12988 | Byebug.PryProcessor.resume_pry | train | def resume_pry
new_binding = frame._binding
run do
if defined?(@pry) && @pry
@pry.repl(new_binding)
else
@pry = Pry.start_without_pry_byebug(new_binding)
end
end
end | ruby | {
"resource": ""
} |
q12989 | Haml.Engine.render | train | def render(scope = Object.new, locals = {}, &block)
parent = scope.instance_variable_defined?(:@haml_buffer) ? scope.instance_variable_get(:@haml_buffer) : nil
buffer = Haml::Buffer.new(parent, @options.for_buffer)
if scope.is_a?(Binding)
scope_object = eval("self", scope)
scope = scope_object.instance_eval{binding} if block_given?
else
scope_object = scope
scope = scope_object.instance_eval{binding}
end
set_locals(locals.merge(:_hamlout => buffer, :_erbout => buffer.buffer), scope, scope_object)
scope_object.extend(Haml::Helpers)
scope_object.instance_variable_set(:@haml_buffer, buffer)
begin
eval(@temple_engine.precompiled_with_return_value, scope, @options.filename, @options.line)
rescue ::SyntaxError => e
raise SyntaxError, e.message
end
ensure
# Get rid of the current buffer
scope_object.instance_variable_set(:@haml_buffer, buffer.upper) if buffer
end | ruby | {
"resource": ""
} |
q12990 | Haml.Engine.render_proc | train | def render_proc(scope = Object.new, *local_names)
if scope.is_a?(Binding)
scope_object = eval("self", scope)
else
scope_object = scope
scope = scope_object.instance_eval{binding}
end
begin
str = @temple_engine.precompiled_with_ambles(local_names)
eval(
"Proc.new { |*_haml_locals| _haml_locals = _haml_locals[0] || {}; #{str}}\n",
scope,
@options.filename,
@options.line
)
rescue ::SyntaxError => e
raise SyntaxError, e.message
end
end | ruby | {
"resource": ""
} |
q12991 | Haml.Engine.def_method | train | def def_method(object, name, *local_names)
method = object.is_a?(Module) ? :module_eval : :instance_eval
object.send(method, "def #{name}(_haml_locals = {}); #{@temple_engine.precompiled_with_ambles(local_names)}; end",
@options.filename, @options.line)
end | ruby | {
"resource": ""
} |
q12992 | Haml.AttributeCompiler.compile_attribute_values | train | def compile_attribute_values(values)
if values.map(&:key).uniq.size == 1
compile_attribute(values.first.key, values)
else
runtime_build(values)
end
end | ruby | {
"resource": ""
} |
q12993 | Haml.AttributeCompiler.static_build | train | def static_build(values)
hash_content = values.group_by(&:key).map do |key, values_for_key|
"#{frozen_string(key)} => #{merged_value(key, values_for_key)}"
end.join(', ')
arguments = [@is_html, @attr_wrapper, @escape_attrs, @hyphenate_data_attrs]
code = "::Haml::AttributeBuilder.build_attributes"\
"(#{arguments.map { |a| Haml::Util.inspect_obj(a) }.join(', ')}, { #{hash_content} })"
[:static, eval(code).to_s]
end | ruby | {
"resource": ""
} |
q12994 | Haml.AttributeCompiler.compile_attribute | train | def compile_attribute(key, values)
if values.all? { |v| Temple::StaticAnalyzer.static?(v.to_literal) }
return static_build(values)
end
case key
when 'id', 'class'
compile_id_or_class_attribute(key, values)
else
compile_common_attribute(key, values)
end
end | ruby | {
"resource": ""
} |
q12995 | Haml.Util.parse_haml_magic_comment | train | def parse_haml_magic_comment(str)
scanner = StringScanner.new(str.dup.force_encoding(Encoding::ASCII_8BIT))
bom = scanner.scan(/\xEF\xBB\xBF/n)
return bom unless scanner.scan(/-\s*#\s*/n)
if coding = try_parse_haml_emacs_magic_comment(scanner)
return bom, coding
end
return bom unless scanner.scan(/.*?coding[=:]\s*([\w-]+)/in)
return bom, scanner[1]
end | ruby | {
"resource": ""
} |
q12996 | Haml.Buffer.rstrip! | train | def rstrip!
if capture_position.nil?
buffer.rstrip!
return
end
buffer << buffer.slice!(capture_position..-1).rstrip
end | ruby | {
"resource": ""
} |
q12997 | Haml.Helpers.preserve | train | def preserve(input = nil, &block)
return preserve(capture_haml(&block)) if block
s = input.to_s.chomp("\n")
s.gsub!(/\n/, '
')
s.delete!("\r")
s
end | ruby | {
"resource": ""
} |
q12998 | Haml.Helpers.capture_haml | train | def capture_haml(*args, &block)
buffer = eval('if defined? _hamlout then _hamlout else nil end', block.binding) || haml_buffer
with_haml_buffer(buffer) do
position = haml_buffer.buffer.length
haml_buffer.capture_position = position
value = block.call(*args)
captured = haml_buffer.buffer.slice!(position..-1)
if captured == '' and value != haml_buffer.buffer
captured = (value.is_a?(String) ? value : nil)
end
captured
end
ensure
haml_buffer.capture_position = nil
end | ruby | {
"resource": ""
} |
q12999 | Haml.Helpers.haml_internal_concat | train | def haml_internal_concat(text = "", newline = true, indent = true)
if haml_buffer.tabulation == 0
haml_buffer.buffer << "#{text}#{"\n" if newline}"
else
haml_buffer.buffer << %[#{haml_indent if indent}#{text.to_s.gsub("\n", "\n#{haml_indent}")}#{"\n" if newline}]
end
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.