_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q10800 | Decidim.NewslettersHelper.custom_url_for_mail_root | train | def custom_url_for_mail_root(organization, newsletter_id = nil)
if newsletter_id.present?
decidim.root_url(host: organization.host) + utm_codes(organization.host, newsletter_id.to_s)
else
decidim.root_url(host: organization.host)
end
end | ruby | {
"resource": ""
} |
q10801 | Decidim.LayoutHelper.icon | train | def icon(name, options = {})
html_properties = {}
html_properties["width"] = options[:width]
html_properties["height"] = options[:height]
html_properties["aria-label"] = options[:aria_label]
html_properties["role"] = options[:role]
html_properties["aria-hidden"] = options[:aria_hidden]
html_properties["class"] = (["icon--#{name}"] + _icon_classes(options)).join(" ")
content_tag :svg, html_properties do
content_tag :use, nil, "xlink:href" => "#{asset_path("decidim/icons.svg")}#icon-#{name}"
end
end | ruby | {
"resource": ""
} |
q10802 | Decidim.LayoutHelper.external_icon | train | def external_icon(path, options = {})
classes = _icon_classes(options) + ["external-icon"]
if path.split(".").last == "svg"
asset = Rails.application.assets_manifest.find_sources(path).first
asset.gsub("<svg ", "<svg class=\"#{classes.join(" ")}\" ").html_safe
else
image_tag(path, class: classes.join(" "), style: "display: none")
end
end | ruby | {
"resource": ""
} |
q10803 | Decidim.ContinuityBadgeTracker.track! | train | def track!(date)
@subject.with_lock do
last_session_at = status.try(:last_session_at) || date
current_streak = status.try(:current_streak) || 1
streak = if last_session_at == date
current_streak
elsif last_session_at == date - 1.day
current_streak + 1
else
1
end
update_status(date, streak)
update_badge(streak)
end
end | ruby | {
"resource": ""
} |
q10804 | Decidim.DecidimDeviseMailer.invitation_instructions | train | def invitation_instructions(user, token, opts = {})
with_user(user) do
@token = token
@organization = user.organization
@opts = opts
opts[:subject] = I18n.t("devise.mailer.#{opts[:invitation_instructions]}.subject", organization: user.organization.name) if opts[:invitation_instructions]
end
devise_mail(user, opts[:invitation_instructions] || :invitation_instructions, opts)
end | ruby | {
"resource": ""
} |
q10805 | Decidim.ActivitiesCell.show | train | def show
return if activities.blank?
activities.map do |activity|
activity.organization_lazy
activity.resource_lazy
activity.participatory_space_lazy
activity.component_lazy
end
render
end | ruby | {
"resource": ""
} |
q10806 | Decidim.ComponentPathHelper.main_component_path | train | def main_component_path(component)
current_params = try(:params) || {}
EngineRouter.main_proxy(component).root_path(locale: current_params[:locale])
end | ruby | {
"resource": ""
} |
q10807 | Decidim.ComponentPathHelper.main_component_url | train | def main_component_url(component)
current_params = try(:params) || {}
EngineRouter.main_proxy(component).root_url(locale: current_params[:locale])
end | ruby | {
"resource": ""
} |
q10808 | Decidim.ComponentPathHelper.manage_component_path | train | def manage_component_path(component)
current_params = try(:params) || {}
EngineRouter.admin_proxy(component).root_path(locale: current_params[:locale])
end | ruby | {
"resource": ""
} |
q10809 | Decidim.SearchesHelper.searchable_resource_human_name | train | def searchable_resource_human_name(resource, count: 5)
resource = if resource.is_a?(String)
resource.constantize
else
resource
end
resource.model_name.human(count: count)
end | ruby | {
"resource": ""
} |
q10810 | Decidim.SearchesHelper.search_path_by | train | def search_path_by(resource_type: nil, space_state: nil)
new_params = {
utf8: params[:utf8],
filter: {
decidim_scope_id: params.dig(:filter, :decidim_scope_id),
term: params[:term] || params.dig(:filter, :term)
}
}
new_params[:filter][:resource_type] = resource_type if resource_type.present?
new_params[:filter][:space_state] = space_state if space_state.present?
decidim.search_path(new_params)
end | ruby | {
"resource": ""
} |
q10811 | Decidim.SearchesHelper.search_path_by_state_link | train | def search_path_by_state_link(state)
path = search_path_by(resource_type: params.dig(:filter, :resource_type), space_state: state)
is_active = params.dig(:filter, :space_state).to_s == state.to_s
link_to path, class: "order-by__tab#{" is-active" if is_active}" do
content_tag(:strong, t(state || :all, scope: "decidim.searches.filters.state"))
end
end | ruby | {
"resource": ""
} |
q10812 | Decidim.DecidimFormHelper.decidim_form_for | train | def decidim_form_for(record, options = {}, &block)
options[:data] ||= {}
options[:data].update(abide: true, "live-validate" => true, "validate-on-blur" => true)
options[:html] ||= {}
options[:html].update(novalidate: true)
output = ""
output += base_error_messages(record).to_s
output += form_for(record, options, &block).to_s
output.html_safe
end | ruby | {
"resource": ""
} |
q10813 | Decidim.DecidimFormHelper.editor_field_tag | train | def editor_field_tag(name, value, options = {})
options[:toolbar] ||= "basic"
options[:lines] ||= 10
content_tag(:div, class: "editor") do
template = ""
template += label_tag(name, options[:label]) if options[:label] != false
template += hidden_field_tag(name, value, options)
template += content_tag(:div, nil, class: "editor-container", data: {
toolbar: options[:toolbar]
}, style: "height: #{options[:lines]}rem")
template.html_safe
end
end | ruby | {
"resource": ""
} |
q10814 | Decidim.DecidimFormHelper.scopes_picker_field_tag | train | def scopes_picker_field_tag(name, value, id: nil)
picker_options = {
id: id || sanitize_to_id(name),
class: "picker-single",
name: name
}
prompt_params = yield(nil)
selected_scopes = value ? Decidim::Scope.where(id: value) : []
scopes = selected_scopes.map { |scope| [scope, yield(scope)] }
template = ""
template += render("decidim/scopes/scopes_picker_input",
picker_options: picker_options,
prompt_params: prompt_params,
scopes: scopes,
checkboxes_on_top: true)
template.html_safe
end | ruby | {
"resource": ""
} |
q10815 | Decidim.DecidimFormHelper.translated_field_tag | train | def translated_field_tag(type, object_name, name, value = {}, options = {})
locales = available_locales
field_label = label_tag(name, options[:label])
if locales.count == 1
field_name = "#{name}_#{locales.first.to_s.gsub("-", "__")}"
field_input = send(
type,
"#{object_name}[#{field_name}]",
value[locales.first.to_s]
)
return safe_join [field_label, field_input]
end
tabs_id = options[:tabs_id] || "#{object_name}-#{name}-tabs".underscore
enabled_tabs = options[:enable_tabs].nil? ? true : options[:enable_tabs]
tabs_panels_data = enabled_tabs ? { tabs: true } : {}
label_tabs = content_tag(:div, class: "label--tabs") do
tabs_panels = "".html_safe
if options[:label] != false
tabs_panels = content_tag(:ul, class: "tabs tabs--lang", id: tabs_id, data: tabs_panels_data) do
locales.each_with_index.inject("".html_safe) do |string, (locale, index)|
string + content_tag(:li, class: tab_element_class_for("title", index)) do
title = I18n.with_locale(locale) { I18n.t("name", scope: "locale") }
element_class = nil
element_class = "is-tab-error" if form_field_has_error?(options[:object], name_with_locale(name, locale))
tab_content_id = "#{tabs_id}-#{name}-panel-#{index}"
content_tag(:a, title, href: "##{tab_content_id}", class: element_class)
end
end
end
end
safe_join [field_label, tabs_panels]
end
tabs_content = content_tag(:div, class: "tabs-content", data: { tabs_content: tabs_id }) do
locales.each_with_index.inject("".html_safe) do |string, (locale, index)|
tab_content_id = "#{tabs_id}-#{name}-panel-#{index}"
string + content_tag(:div, class: tab_element_class_for("panel", index), id: tab_content_id) do
send(type, "#{object_name}[#{name_with_locale(name, locale)}]", value[locale.to_s], options.merge(id: "#{tabs_id}_#{name}_#{locale}", label: false))
end
end
end
safe_join [label_tabs, tabs_content]
end | ruby | {
"resource": ""
} |
q10816 | Decidim.DecidimFormHelper.decidim_form_slug_url | train | def decidim_form_slug_url(prepend_path = "", value = "")
prepend_slug_path = if prepend_path.present?
"/#{prepend_path}/"
else
"/"
end
content_tag(:span, class: "slug-url") do
[
request.protocol,
request.host_with_port,
prepend_slug_path
].join("").html_safe +
content_tag(:span, value, class: "slug-url-value")
end
end | ruby | {
"resource": ""
} |
q10817 | Decidim.TraceabilityHelper.render_resource_last_editor | train | def render_resource_last_editor(resource)
render partial: "decidim/shared/version_author",
locals: {
author: Decidim.traceability.last_editor(resource)
}
end | ruby | {
"resource": ""
} |
q10818 | Decidim.TraceabilityHelper.render_resource_editor | train | def render_resource_editor(version)
render partial: "decidim/shared/version_author",
locals: {
author: Decidim.traceability.version_editor(version)
}
end | ruby | {
"resource": ""
} |
q10819 | Decidim.TraceabilityHelper.diff_renderer | train | def diff_renderer
@diff_renderer ||= if current_version.item_type.include? "Decidim::Proposals"
Decidim::Proposals::DiffRenderer.new(current_version)
elsif current_version.item_type.include? "Decidim::Accountability"
Decidim::Accountability::DiffRenderer.new(current_version)
end
end | ruby | {
"resource": ""
} |
q10820 | Decidim.TraceabilityHelper.render_diff_value | train | def render_diff_value(value, type, action, options = {})
return "".html_safe if value.blank?
value_to_render = case type
when :date
l value, format: :long
when :percentage
number_to_percentage value, precision: 2
else
value
end
content_tag(:div, class: "card--list__item #{action}") do
content_tag(:div, class: "card--list__text") do
content_tag(:div, { class: "diff__value" }.merge(options)) do
value_to_render
end
end
end
end | ruby | {
"resource": ""
} |
q10821 | Decidim.ActivityCell.title | train | def title
resource_title = resource.try(:resource_title) || resource.try(:title)
return if resource_title.blank?
if resource_title.is_a?(String)
resource_title
elsif resource_title.is_a?(Hash)
translated_attribute(resource_title)
end
end | ruby | {
"resource": ""
} |
q10822 | Decidim.ActivityCell.description | train | def description
resource_description = resource.try(:resource_description) || resource.try(:description)
return if resource_description.blank?
resource_description = if resource_description.is_a?(String)
resource_description
elsif resource_description.is_a?(Hash)
translated_attribute(resource_description)
end
truncate(strip_tags(resource_description), length: 300)
end | ruby | {
"resource": ""
} |
q10823 | Decidim.CtaButtonHelper.cta_button | train | def cta_button
button_text = translated_attribute(current_organization.cta_button_text).presence || t("decidim.pages.home.hero.participate")
link_to button_text, cta_button_path, class: "hero-cta button expanded large button--sc"
end | ruby | {
"resource": ""
} |
q10824 | Decidim.CtaButtonHelper.cta_button_path | train | def cta_button_path
if current_organization.cta_button_path.present?
current_organization.cta_button_path
elsif Decidim::ParticipatoryProcess.where(organization: current_organization).published.any?
decidim_participatory_processes.participatory_processes_path
elsif current_user
decidim.account_path
elsif current_organization.sign_up_enabled?
decidim.new_user_registration_path
else
decidim.new_user_session_path
end
end | ruby | {
"resource": ""
} |
q10825 | Decidim.DataPortabilityFileReader.file_path | train | def file_path
directory_name = Rails.root.join(Decidim::DataPortabilityUploader.new.store_dir)
FileUtils.mkdir_p(directory_name) unless File.exist?(directory_name)
directory_name + file_name
end | ruby | {
"resource": ""
} |
q10826 | Decidim.FiltersHelper.filter_form_for | train | def filter_form_for(filter, url = url_for)
content_tag :div, class: "filters" do
form_for filter, namespace: filter_form_namespace, builder: FilterFormBuilder, url: url, as: :filter, method: :get, remote: true, html: { id: nil } do |form|
yield form
end
end
end | ruby | {
"resource": ""
} |
q10827 | Decidim.AttachmentUploader.image? | train | def image?(new_file)
content_type = model.content_type || new_file.content_type
content_type.to_s.start_with? "image"
end | ruby | {
"resource": ""
} |
q10828 | Decidim.AttachmentUploader.set_content_type_and_size_in_model | train | def set_content_type_and_size_in_model
model.content_type = file.content_type if file.content_type
model.file_size = file.size
end | ruby | {
"resource": ""
} |
q10829 | Decidim.FilterFormBuilder.collection_radio_buttons | train | def collection_radio_buttons(method, collection, value_method, label_method, options = {}, html_options = {})
fieldset_wrapper options[:legend_title] do
super(method, collection, value_method, label_method, options, html_options) do |builder|
if block_given?
yield builder
else
builder.label { builder.radio_button + builder.text }
end
end
end
end | ruby | {
"resource": ""
} |
q10830 | Decidim.FilterFormBuilder.collection_check_boxes | train | def collection_check_boxes(method, collection, value_method, label_method, options = {}, html_options = {})
fieldset_wrapper options[:legend_title] do
super(method, collection, value_method, label_method, options, html_options) do |builder|
if block_given?
yield builder
else
builder.label { builder.check_box + builder.text }
end
end
end
end | ruby | {
"resource": ""
} |
q10831 | Capistrano.DSL.execute | train | def execute(*)
file, line, = caller.first.split(":")
colors = SSHKit::Color.new($stderr)
$stderr.puts colors.colorize("Warning: `execute' should be wrapped in an `on' scope in #{file}:#{line}.", :red)
$stderr.puts
$stderr.puts " task :example do"
$stderr.puts colors.colorize(" on roles(:app) do", :yellow)
$stderr.puts " execute 'whoami'"
$stderr.puts colors.colorize(" end", :yellow)
$stderr.puts " end"
$stderr.puts
raise NoMethodError, "undefined method `execute' for main:Object"
end | ruby | {
"resource": ""
} |
q10832 | Jets.Preheat.warm_all | train | def warm_all
threads = []
all_functions.each do |function_name|
next if function_name.include?('jets-public_controller') # handled by warm_public_controller_more
next if function_name.include?('jets-rack_controller') # handled by warm_rack_controller_more
threads << Thread.new do
warm(function_name)
end
end
threads.each { |t| t.join }
# Warm the these controllers more since they can be hit more often
warm_public_controller_more
warm_rack_controller_more
# return the funciton names so we can see in the Lambda console
# the functions being prewarmed
all_functions
end | ruby | {
"resource": ""
} |
q10833 | Jets::Job::Dsl.IotEvent.iot_event | train | def iot_event(props={})
if props.is_a?(String) # SQL Statement
props = {sql: props}
topic_props = {topic_rule_payload: props}
elsif props.key?(:topic_rule_payload) # full properties structure
topic_props = props
else # just the topic_rule_payload
topic_props = {topic_rule_payload: props}
end
declare_iot_topic(topic_props)
end | ruby | {
"resource": ""
} |
q10834 | Jets::Resource::Lambda.Function.lookup_class_properties | train | def lookup_class_properties(klass)
all_classes = []
while klass != Object
all_classes << klass
klass = klass.superclass
end
class_properties = {}
# Go back down class heirachry top to down
all_classes.reverse.each do |k|
class_properties.merge!(k.class_properties)
end
class_properties
end | ruby | {
"resource": ""
} |
q10835 | Jets::Resource::Lambda.Function.finalize_properties! | train | def finalize_properties!(props)
handler = full_handler(props)
runtime = get_runtime(props)
managed = {
handler: handler,
runtime: runtime,
description: description,
}
managed[:function_name] = function_name if function_name
layers = get_layers(runtime)
managed[:layers] = layers if layers
props.merge!(managed)
end | ruby | {
"resource": ""
} |
q10836 | Jets::Resource::Iam.PolicyDocument.standardize | train | def standardize(definition)
case definition
when String
# Expands simple string from: logs => logs:*
definition = "#{definition}:*" unless definition.include?(':')
@policy[:statement] << {
action: [definition],
effect: "Allow",
resource: "*",
}
when Hash
definition = definition.stringify_keys
if definition.key?("Version") # special case where we replace the policy entirely
@policy = definition
else
@policy[:statement] << definition
end
end
end | ruby | {
"resource": ""
} |
q10837 | Jets::Controller::Rack.Adapter.process | train | def process
status, headers, body = Jets.application.call(env)
convert_to_api_gateway(status, headers, body)
end | ruby | {
"resource": ""
} |
q10838 | Jets.Router.check_collision! | train | def check_collision!
paths = self.routes.map(&:path)
collision = Jets::Resource::ApiGateway::RestApi::Routes::Collision.new
collide = collision.collision?(paths)
raise collision.exception if collide
end | ruby | {
"resource": ""
} |
q10839 | Jets.Router.resources | train | def resources(name)
get "#{name}", to: "#{name}#index"
get "#{name}/new", to: "#{name}#new" unless api_mode?
get "#{name}/:id", to: "#{name}#show"
post "#{name}", to: "#{name}#create"
get "#{name}/:id/edit", to: "#{name}#edit" unless api_mode?
put "#{name}/:id", to: "#{name}#update"
post "#{name}/:id", to: "#{name}#update" # for binary uploads
patch "#{name}/:id", to: "#{name}#update"
delete "#{name}/:id", to: "#{name}#delete"
end | ruby | {
"resource": ""
} |
q10840 | Jets.Router.all_paths | train | def all_paths
results = []
paths = routes.map(&:path)
paths.each do |p|
sub_paths = []
parts = p.split('/')
until parts.empty?
parts.pop
sub_path = parts.join('/')
sub_paths << sub_path unless sub_path == ''
end
results += sub_paths
end
@all_paths = (results + paths).sort.uniq
end | ruby | {
"resource": ""
} |
q10841 | Jets.Router.ordered_routes | train | def ordered_routes
length = Proc.new { |r| r.path.length * -1 }
capture_routes = routes.select { |r| r.path.include?(':') }.sort_by(&length)
wildcard_routes = routes.select { |r| r.path.include?('*') }.sort_by(&length)
simple_routes = (routes - capture_routes - wildcard_routes).sort_by(&length)
simple_routes + capture_routes + wildcard_routes
end | ruby | {
"resource": ""
} |
q10842 | Jets::Controller::Middleware.Local.routes_table | train | def routes_table
routes = Jets::Router.routes
return "Your routes table is empty." if routes.empty?
text = "Verb | Path | Controller#action\n"
text << "--- | --- | ---\n"
routes.each do |route|
text << "#{route.method} | #{route.path} | #{route.to}\n"
end
html = Kramdown::Document.new(text).to_html
puts html
html
end | ruby | {
"resource": ""
} |
q10843 | Jets::Resource::ApiGateway.Cors.cors_headers | train | def cors_headers
rack = Jets::Controller::Middleware::Cors.new(Jets.application)
rack.cors_headers(true)
end | ruby | {
"resource": ""
} |
q10844 | Jets.RackServer.serve | train | def serve
# Note, looks like stopping jets server with Ctrl-C sends the TERM signal
# down to the sub bin/rackup command cleans up the child process fine.
Bundler.with_clean_env do
args = ''
# only forward the host option, port is always 9292 for simplicity
if @options[:host]
args << " --host #{@options[:host]}"
else
args << " --host 127.0.0.1" # using the default localhost is not starting up https://stackoverflow.com/questions/4356646/address-family-not-supported-by-protocol-family
end
command = "cd #{rack_project} && bin/rackup#{args}" # leads to the same wrapper rack scripts
puts "=> #{command}".color(:green)
system(command)
end
end | ruby | {
"resource": ""
} |
q10845 | Jets.RackServer.wait_for_socket | train | def wait_for_socket
return unless Jets.rack?
retries = 0
max_retries = 30 # 15 seconds at a delay of 0.5s
delay = 0.5
if ENV['C9_USER'] # overrides for local testing
max_retries = 3
delay = 3
end
begin
server = TCPSocket.new('localhost', 9292)
server.close
rescue Errno::ECONNREFUSED
puts "Unable to connect to localhost:9292. Delay for #{delay} and will try to connect again." if ENV['JETS_DEBUG']
sleep(delay)
retries += 1
if retries < max_retries
retry
else
puts "Giving up on trying to connect to localhost:9292"
return false
end
end
puts "Connected to localhost:9292 successfully"
true
end | ruby | {
"resource": ""
} |
q10846 | Jets.Logger.add | train | def add(severity, message = nil, progname = nil)
# Taken from Logger#add source
# https://ruby-doc.org/stdlib-2.5.1/libdoc/logger/rdoc/Logger.html#method-i-add
if message.nil?
if block_given?
message = yield
else
message = progname
progname = @progname
end
end
# Put the message in the Jets::IO.buffer which will get flushed to CloudWatch.
# No need to include timestamp as CloudWatch already has a timestamp.
IO.buffer << message
super # original logical
end | ruby | {
"resource": ""
} |
q10847 | Jets::Commands::Markdown.Page.long_description | train | def long_description
text = @command.long_description
return "" if text.nil? # empty description
lines = text.split("\n")
lines.map do |line|
# In the CLI help, we use 2 spaces to designate commands
# In Markdown we need 4 spaces.
line.sub(/^ \b/, ' ')
end.join("\n")
end | ruby | {
"resource": ""
} |
q10848 | Jets.Rdoc.options | train | def options
exclude = %w[
docs
spec
vendor
core.rb
.js
templates
commands
internal
support
Dockerfile
Dockerfile.base
Gemfile
Gemfile.lock
Guardfile
LICENSE
Procfile
Rakefile
bin
]
exclude = exclude.map { |word| ['-x', word] }.flatten
["-m", "README.md", "--markup", "tomdoc"] + exclude
end | ruby | {
"resource": ""
} |
q10849 | Jets::Middleware.DefaultStack.use_webpacker | train | def use_webpacker(middleware)
return unless Jets.webpacker? # checks for local development if webpacker installed
# Different check for middleware because we need webpacker helpers for url helpers.
# But we dont want to actually serve via webpacker middleware when running on AWS.
# By this time the url helpers are serving assets out of s3.
return if File.exist?("#{Jets.root}/config/disable-webpacker-middleware.txt") # created as part of `jets deploy`
require "jets/controller/middleware/webpacker_setup"
middleware.use Webpacker::DevServerProxy
end | ruby | {
"resource": ""
} |
q10850 | Jets.AwsInfo.account | train | def account
return '123456789' if test?
# ensure region set, required for sts.get_caller_identity.account to work
ENV['AWS_REGION'] ||= region
begin
sts.get_caller_identity.account
rescue Aws::Errors::MissingCredentialsError
puts "INFO: You're missing AWS credentials. Only local services are currently available"
end
end | ruby | {
"resource": ""
} |
q10851 | Jets::Commands.Deploy.check_route_connected_functions | train | def check_route_connected_functions
return if Jets::Router.all_routes_valid
puts "Deploy fail: The jets application contain invalid routes.".color(:red)
puts "Please double check the routes below map to valid controllers:"
Jets::Router.invalid_routes.each do |route|
puts " /#{route.path} => #{route.controller_name}##{route.action_name}"
end
exit 1
end | ruby | {
"resource": ""
} |
q10852 | Jets::Commands.Deploy.minimal_rollback_complete? | train | def minimal_rollback_complete?
stack = find_stack(stack_name)
return false unless stack
return false unless stack.stack_status == 'ROLLBACK_COMPLETE'
# Finally check if all the minimal resources in the parent template have been deleted
resp = cfn.describe_stack_resources(stack_name: stack_name)
resource_statuses = resp.stack_resources.map(&:resource_status).uniq
resource_statuses == ['DELETE_COMPLETE']
end | ruby | {
"resource": ""
} |
q10853 | Jets::Resource::Iam.ClassRole.all_classes | train | def all_classes
klass = @app_class.constantize
all_classes = []
while klass != Object
all_classes << klass
klass = klass.superclass
end
all_classes.reverse
end | ruby | {
"resource": ""
} |
q10854 | Jets::Lambda.FunctionConstructor.adjust_tasks | train | def adjust_tasks(klass)
class_name = @code_path.to_s.sub(/.*\/functions\//,'').sub(/\.rb$/, '')
class_name = class_name.classify
klass.tasks.each do |task|
task.class_name = class_name
task.type = "function"
end
end | ruby | {
"resource": ""
} |
q10855 | GitHubChangelogGenerator.Section.generate_content | train | def generate_content
content = ""
if @issues.any?
content += "#{@prefix}\n\n" unless @options[:simple_list] || @prefix.blank?
@issues.each do |issue|
merge_string = get_string_for_issue(issue)
content += "- " unless @body_only
content += "#{merge_string}\n"
end
content += "\n"
end
content
end | ruby | {
"resource": ""
} |
q10856 | GitHubChangelogGenerator.Section.get_string_for_issue | train | def get_string_for_issue(issue)
encapsulated_title = encapsulate_string issue["title"]
title_with_number = "#{encapsulated_title} [\\##{issue['number']}](#{issue['html_url']})"
title_with_number = "#{title_with_number}#{line_labels_for(issue)}" if @options[:issue_line_labels].present?
line = issue_line_with_user(title_with_number, issue)
issue_line_with_body(line, issue)
end | ruby | {
"resource": ""
} |
q10857 | GitHubChangelogGenerator.Section.encapsulate_string | train | def encapsulate_string(string)
string = string.gsub('\\', '\\\\')
ENCAPSULATED_CHARACTERS.each do |char|
string = string.gsub(char, "\\#{char}")
end
string
end | ruby | {
"resource": ""
} |
q10858 | GitHubChangelogGenerator.Generator.fetch_tags_dates | train | def fetch_tags_dates(tags)
print "Fetching tag dates...\r" if options[:verbose]
i = 0
tags.each do |tag|
get_time_of_tag(tag)
i += 1
end
puts "Fetching tags dates: #{i}/#{tags.count}" if options[:verbose]
end | ruby | {
"resource": ""
} |
q10859 | GitHubChangelogGenerator.Generator.detect_actual_closed_dates | train | def detect_actual_closed_dates(issues)
print "Fetching closed dates for issues...\r" if options[:verbose]
i = 0
issues.each do |issue|
find_closed_date_by_commit(issue)
i += 1
end
puts "Fetching closed dates for issues: #{i}/#{issues.count}" if options[:verbose]
end | ruby | {
"resource": ""
} |
q10860 | GitHubChangelogGenerator.Generator.add_first_occurring_tag_to_prs | train | def add_first_occurring_tag_to_prs(tags, prs)
total = prs.count
prs_left = associate_tagged_prs(tags, prs, total)
prs_left = associate_release_branch_prs(prs_left, total)
prs_left = associate_rebase_comment_prs(tags, prs_left, total) if prs_left.any?
# PRs in prs_left will be untagged, not in release branch, and not
# rebased. They should not be included in the changelog as they probably
# have been merged to a branch other than the release branch.
@pull_requests -= prs_left
Helper.log.info "Associating PRs with tags: #{total}/#{total}"
end | ruby | {
"resource": ""
} |
q10861 | GitHubChangelogGenerator.Generator.associate_tagged_prs | train | def associate_tagged_prs(tags, prs, total)
@fetcher.fetch_tag_shas_async(tags)
i = 0
prs.reject do |pr|
found = false
# XXX Wish I could use merge_commit_sha, but gcg doesn't currently
# fetch that. See
# https://developer.github.com/v3/pulls/#get-a-single-pull-request vs.
# https://developer.github.com/v3/pulls/#list-pull-requests
if pr["events"] && (event = pr["events"].find { |e| e["event"] == "merged" })
# Iterate tags.reverse (oldest to newest) to find first tag of each PR.
if (oldest_tag = tags.reverse.find { |tag| tag["shas_in_tag"].include?(event["commit_id"]) })
pr["first_occurring_tag"] = oldest_tag["name"]
found = true
i += 1
print("Associating PRs with tags: #{i}/#{total}\r") if @options[:verbose]
end
else
# Either there were no events or no merged event. Github's api can be
# weird like that apparently. Check for a rebased comment before erroring.
no_events_pr = associate_rebase_comment_prs(tags, [pr], total)
raise StandardError, "No merge sha found for PR #{pr['number']} via the GitHub API" unless no_events_pr.empty?
found = true
i += 1
print("Associating PRs with tags: #{i}/#{total}\r") if @options[:verbose]
end
found
end
end | ruby | {
"resource": ""
} |
q10862 | GitHubChangelogGenerator.Generator.set_date_from_event | train | def set_date_from_event(event, issue)
if event["commit_id"].nil?
issue["actual_date"] = issue["closed_at"]
else
begin
commit = @fetcher.fetch_commit(event["commit_id"])
issue["actual_date"] = commit["commit"]["author"]["date"]
# issue['actual_date'] = commit['author']['date']
rescue StandardError
puts "Warning: Can't fetch commit #{event['commit_id']}. It is probably referenced from another repo."
issue["actual_date"] = issue["closed_at"]
end
end
end | ruby | {
"resource": ""
} |
q10863 | GitHubChangelogGenerator.OctoFetcher.calculate_pages | train | def calculate_pages(client, method, request_options)
# Makes the first API call so that we can call last_response
check_github_response do
client.send(method, user_project, DEFAULT_REQUEST_OPTIONS.merge(request_options))
end
last_response = client.last_response
if (last_pg = last_response.rels[:last])
querystring_as_hash(last_pg.href)["page"].to_i
else
1
end
end | ruby | {
"resource": ""
} |
q10864 | GitHubChangelogGenerator.OctoFetcher.github_fetch_tags | train | def github_fetch_tags
tags = []
page_i = 0
count_pages = calculate_pages(@client, "tags", {})
iterate_pages(@client, "tags") do |new_tags|
page_i += PER_PAGE_NUMBER
print_in_same_line("Fetching tags... #{page_i}/#{count_pages * PER_PAGE_NUMBER}")
tags.concat(new_tags)
end
print_empty_line
if tags.count == 0
Helper.log.warn "Warning: Can't find any tags in repo. \
Make sure, that you push tags to remote repo via 'git push --tags'"
else
Helper.log.info "Found #{tags.count} tags"
end
# tags are a Sawyer::Resource. Convert to hash
tags.map { |resource| stringify_keys_deep(resource.to_hash) }
end | ruby | {
"resource": ""
} |
q10865 | GitHubChangelogGenerator.OctoFetcher.fetch_events_async | train | def fetch_events_async(issues)
i = 0
threads = []
issues.each_slice(MAX_THREAD_NUMBER) do |issues_slice|
issues_slice.each do |issue|
threads << Thread.new do
issue["events"] = []
iterate_pages(@client, "issue_events", issue["number"]) do |new_event|
issue["events"].concat(new_event)
end
issue["events"] = issue["events"].map { |event| stringify_keys_deep(event.to_hash) }
print_in_same_line("Fetching events for issues and PR: #{i + 1}/#{issues.count}")
i += 1
end
end
threads.each(&:join)
threads = []
end
# to clear line from prev print
print_empty_line
Helper.log.info "Fetching events for issues and PR: #{i}"
end | ruby | {
"resource": ""
} |
q10866 | GitHubChangelogGenerator.OctoFetcher.fetch_comments_async | train | def fetch_comments_async(prs)
threads = []
prs.each_slice(MAX_THREAD_NUMBER) do |prs_slice|
prs_slice.each do |pr|
threads << Thread.new do
pr["comments"] = []
iterate_pages(@client, "issue_comments", pr["number"]) do |new_comment|
pr["comments"].concat(new_comment)
end
pr["comments"] = pr["comments"].map { |comment| stringify_keys_deep(comment.to_hash) }
end
end
threads.each(&:join)
threads = []
end
nil
end | ruby | {
"resource": ""
} |
q10867 | GitHubChangelogGenerator.OctoFetcher.fetch_date_of_tag | train | def fetch_date_of_tag(tag)
commit_data = fetch_commit(tag["commit"]["sha"])
commit_data = stringify_keys_deep(commit_data.to_hash)
commit_data["commit"]["committer"]["date"]
end | ruby | {
"resource": ""
} |
q10868 | GitHubChangelogGenerator.OctoFetcher.fetch_compare | train | def fetch_compare(older, newer)
unless @compares["#{older}...#{newer}"]
compare_data = check_github_response { @client.compare(user_project, older, newer || "HEAD") }
raise StandardError, "Sha #{older} and sha #{newer} are not related; please file a github-changelog-generator issues and describe how to replicate this issue." if compare_data["status"] == "diverged"
@compares["#{older}...#{newer}"] = stringify_keys_deep(compare_data.to_hash)
end
@compares["#{older}...#{newer}"]
end | ruby | {
"resource": ""
} |
q10869 | GitHubChangelogGenerator.OctoFetcher.fetch_commit | train | def fetch_commit(commit_id)
found = commits.find do |commit|
commit["sha"] == commit_id
end
if found
stringify_keys_deep(found.to_hash)
else
# cache miss; don't add to @commits because unsure of order.
check_github_response do
commit = @client.commit(user_project, commit_id)
commit = stringify_keys_deep(commit.to_hash)
commit
end
end
end | ruby | {
"resource": ""
} |
q10870 | GitHubChangelogGenerator.OctoFetcher.fetch_tag_shas_async | train | def fetch_tag_shas_async(tags)
i = 0
threads = []
print_in_same_line("Fetching SHAs for tags: #{i}/#{tags.count}\r") if @options[:verbose]
tags.each_slice(MAX_THREAD_NUMBER) do |tags_slice|
tags_slice.each do |tag|
threads << Thread.new do
# Use oldest commit because comparing two arbitrary tags may be diverged
commits_in_tag = fetch_compare(oldest_commit["sha"], tag["name"])
tag["shas_in_tag"] = commits_in_tag["commits"].collect { |commit| commit["sha"] }
print_in_same_line("Fetching SHAs for tags: #{i + 1}/#{tags.count}") if @options[:verbose]
i += 1
end
end
threads.each(&:join)
threads = []
end
# to clear line from prev print
print_empty_line
Helper.log.info "Fetching SHAs for tags: #{i}"
nil
end | ruby | {
"resource": ""
} |
q10871 | GitHubChangelogGenerator.OctoFetcher.check_github_response | train | def check_github_response
Retriable.retriable(retry_options) do
yield
end
rescue MovedPermanentlyError => e
fail_with_message(e, "The repository has moved, update your configuration")
rescue Octokit::Forbidden => e
fail_with_message(e, "Exceeded retry limit")
rescue Octokit::Unauthorized => e
fail_with_message(e, "Error: wrong GitHub token")
end | ruby | {
"resource": ""
} |
q10872 | GitHubChangelogGenerator.Generator.fetch_and_filter_tags | train | def fetch_and_filter_tags
since_tag
due_tag
all_tags = @fetcher.get_all_tags
fetch_tags_dates(all_tags) # Creates a Hash @tag_times_hash
all_sorted_tags = sort_tags_by_date(all_tags)
@sorted_tags = filter_excluded_tags(all_sorted_tags)
@filtered_tags = get_filtered_tags(@sorted_tags)
# Because we need to properly create compare links, we need a sorted list
# of all filtered tags (including the excluded ones). We'll exclude those
# tags from section headers inside the mapping function.
section_tags = get_filtered_tags(all_sorted_tags)
@tag_section_mapping = build_tag_section_mapping(section_tags, @filtered_tags)
@filtered_tags
end | ruby | {
"resource": ""
} |
q10873 | GitHubChangelogGenerator.Generator.get_time_of_tag | train | def get_time_of_tag(tag_name)
raise ChangelogGeneratorError, "tag_name is nil" if tag_name.nil?
name_of_tag = tag_name.fetch("name")
time_for_tag_name = @tag_times_hash[name_of_tag]
return time_for_tag_name if time_for_tag_name
@fetcher.fetch_date_of_tag(tag_name).tap do |time_string|
@tag_times_hash[name_of_tag] = time_string
end
end | ruby | {
"resource": ""
} |
q10874 | GitHubChangelogGenerator.Generator.detect_link_tag_time | train | def detect_link_tag_time(newer_tag)
# if tag is nil - set current time
newer_tag_time = newer_tag.nil? ? Time.new : get_time_of_tag(newer_tag)
# if it's future release tag - set this value
if newer_tag.nil? && options[:future_release]
newer_tag_name = options[:future_release]
newer_tag_link = options[:future_release]
else
# put unreleased label if there is no name for the tag
newer_tag_name = newer_tag.nil? ? options[:unreleased_label] : newer_tag["name"]
newer_tag_link = newer_tag.nil? ? "HEAD" : newer_tag_name
end
[newer_tag_link, newer_tag_name, newer_tag_time]
end | ruby | {
"resource": ""
} |
q10875 | GitHubChangelogGenerator.Reader.parse_heading | train | def parse_heading(heading)
captures = { "version" => nil, "url" => nil, "date" => nil }
@heading_structures.each do |regexp|
matches = Regexp.new(regexp).match(heading)
if matches
captures.merge!(Hash[matches.names.zip(matches.captures)])
break
end
end
captures
end | ruby | {
"resource": ""
} |
q10876 | GitHubChangelogGenerator.Reader.parse | train | def parse(data)
sections = data.split(/^## .+?$/)
headings = data.scan(/^## .+?$/)
headings.each_with_index.map do |heading, index|
section = parse_heading(heading)
section["content"] = sections.at(index + 1)
section
end
end | ruby | {
"resource": ""
} |
q10877 | GitHubChangelogGenerator.Generator.find_issues_to_add | train | def find_issues_to_add(all_issues, tag_name)
all_issues.select do |issue|
if issue["milestone"].nil?
false
else
# check, that this milestone in tag list:
milestone_is_tag = @filtered_tags.find do |tag|
tag["name"] == issue["milestone"]["title"]
end
if milestone_is_tag.nil?
false
else
issue["milestone"]["title"] == tag_name
end
end
end
end | ruby | {
"resource": ""
} |
q10878 | GitHubChangelogGenerator.Generator.filter_array_by_labels | train | def filter_array_by_labels(all_issues)
filtered_issues = include_issues_by_labels(all_issues)
filtered_issues = exclude_issues_by_labels(filtered_issues)
exclude_issues_without_labels(filtered_issues)
end | ruby | {
"resource": ""
} |
q10879 | GitHubChangelogGenerator.Entry.generate_entry_for_tag | train | def generate_entry_for_tag(pull_requests, issues, newer_tag_name, newer_tag_link, newer_tag_time, older_tag_name) # rubocop:disable Metrics/ParameterLists
github_site = @options[:github_site] || "https://github.com"
project_url = "#{github_site}/#{@options[:user]}/#{@options[:project]}"
create_sections
@content = generate_header(newer_tag_name, newer_tag_link, newer_tag_time, older_tag_name, project_url)
@content += generate_body(pull_requests, issues)
@content
end | ruby | {
"resource": ""
} |
q10880 | GitHubChangelogGenerator.Entry.generate_header | train | def generate_header(newer_tag_name, newer_tag_link, newer_tag_time, older_tag_name, project_url)
header = ""
# Generate date string:
time_string = newer_tag_time.strftime(@options[:date_format])
# Generate tag name and link
release_url = if @options[:release_url]
format(@options[:release_url], newer_tag_link)
else
"#{project_url}/tree/#{newer_tag_link}"
end
header += if newer_tag_name.equal?(@options[:unreleased_label])
"## [#{newer_tag_name}](#{release_url})\n\n"
else
"## [#{newer_tag_name}](#{release_url}) (#{time_string})\n\n"
end
if @options[:compare_link] && older_tag_name
# Generate compare link
header += "[Full Changelog](#{project_url}/compare/#{older_tag_name}...#{newer_tag_link})\n\n"
end
header
end | ruby | {
"resource": ""
} |
q10881 | GitHubChangelogGenerator.Entry.sort_into_sections | train | def sort_into_sections(pull_requests, issues)
if @options[:issues]
unmapped_issues = sort_labeled_issues(issues)
add_unmapped_section(unmapped_issues)
end
if @options[:pulls]
unmapped_pull_requests = sort_labeled_issues(pull_requests)
add_unmapped_section(unmapped_pull_requests)
end
nil
end | ruby | {
"resource": ""
} |
q10882 | GitHubChangelogGenerator.Entry.sort_labeled_issues | train | def sort_labeled_issues(issues)
sorted_issues = []
issues.each do |issue|
label_names = issue["labels"].collect { |l| l["name"] }
# Add PRs in the order of the @sections array. This will either be the
# default sections followed by any --add-sections sections in
# user-defined order, or --configure-sections in user-defined order.
# Ignore the order of the issue labels from github which cannot be
# controled by the user.
@sections.each do |section|
unless (section.labels & label_names).empty?
section.issues << issue
sorted_issues << issue
break
end
end
end
issues - sorted_issues
end | ruby | {
"resource": ""
} |
q10883 | GitHubChangelogGenerator.ParserFile.extract_pair | train | def extract_pair(line)
key, value = line.split("=", 2)
[key.tr("-", "_").to_sym, value.gsub(/[\n\r]+/, "")]
end | ruby | {
"resource": ""
} |
q10884 | GitHubChangelogGenerator.ChangelogGenerator.run | train | def run
log = @generator.compound_changelog
if @options.write_to_file?
output_filename = @options[:output].to_s
File.open(output_filename, "wb") { |file| file.write(log) }
puts "Done!"
puts "Generated log placed in #{Dir.pwd}/#{output_filename}"
else
puts log
end
end | ruby | {
"resource": ""
} |
q10885 | GitHubChangelogGenerator.Generator.generate_entry_between_tags | train | def generate_entry_between_tags(older_tag, newer_tag)
filtered_issues, filtered_pull_requests = filter_issues_for_tags(newer_tag, older_tag)
if newer_tag.nil? && filtered_issues.empty? && filtered_pull_requests.empty?
# do not generate empty unreleased section
return ""
end
newer_tag_link, newer_tag_name, newer_tag_time = detect_link_tag_time(newer_tag)
# If the older tag is nil, go back in time from the latest tag and find
# the SHA for the first commit.
older_tag_name =
if older_tag.nil?
@fetcher.oldest_commit["sha"]
else
older_tag["name"]
end
Entry.new(options).generate_entry_for_tag(filtered_pull_requests, filtered_issues, newer_tag_name, newer_tag_link, newer_tag_time, older_tag_name)
end | ruby | {
"resource": ""
} |
q10886 | GitHubChangelogGenerator.Generator.filter_issues_for_tags | train | def filter_issues_for_tags(newer_tag, older_tag)
filtered_pull_requests = filter_by_tag(@pull_requests, newer_tag)
filtered_issues = delete_by_time(@issues, "actual_date", older_tag, newer_tag)
newer_tag_name = newer_tag.nil? ? nil : newer_tag["name"]
if options[:filter_issues_by_milestone]
# delete excess irrelevant issues (according milestones). Issue #22.
filtered_issues = filter_by_milestone(filtered_issues, newer_tag_name, @issues)
filtered_pull_requests = filter_by_milestone(filtered_pull_requests, newer_tag_name, @pull_requests)
end
[filtered_issues, filtered_pull_requests]
end | ruby | {
"resource": ""
} |
q10887 | GitHubChangelogGenerator.Generator.generate_entries_for_all_tags | train | def generate_entries_for_all_tags
puts "Generating entry..." if options[:verbose]
entries = generate_unreleased_entry
@tag_section_mapping.each_pair do |_tag_section, left_right_tags|
older_tag, newer_tag = left_right_tags
entries += generate_entry_between_tags(older_tag, newer_tag)
end
entries
end | ruby | {
"resource": ""
} |
q10888 | Hanami.Environment.to_options | train | def to_options
@options.merge(
environment: environment,
env_config: env_config,
apps_path: apps_path,
rackup: rackup,
host: host,
port: port
)
end | ruby | {
"resource": ""
} |
q10889 | Hanami.ApplicationConfiguration.root | train | def root(value = nil)
if value
@root = value
else
Utils::Kernel.Pathname(@root || Dir.pwd).realpath
end
end | ruby | {
"resource": ""
} |
q10890 | Hanami.ApplicationConfiguration.routes | train | def routes(path = nil, &blk)
if path or block_given?
@routes = Config::Routes.new(root, path, &blk)
else
@routes
end
end | ruby | {
"resource": ""
} |
q10891 | Hanami.ApplicationConfiguration.port | train | def port(value = nil)
if value
@port = Integer(value)
else
return @port if defined?(@port)
return @env.port unless @env.default_port?
return DEFAULT_SSL_PORT if force_ssl
@env.port
end
end | ruby | {
"resource": ""
} |
q10892 | Hanami.Env.load! | train | def load!(path)
return unless defined?(Dotenv::Parser)
contents = ::File.open(path, "rb:bom|utf-8", &:read)
parsed = Dotenv::Parser.call(contents)
parsed.each do |k, v|
next if @env.has_key?(k)
@env[k] = v
end
nil
end | ruby | {
"resource": ""
} |
q10893 | Hanami.Hanamirc.default_options | train | def default_options
@default_options ||= Utils::Hash.symbolize({
PROJECT_NAME => project_name,
TEST_KEY => DEFAULT_TEST_SUITE,
TEMPLATE_KEY => DEFAULT_TEMPLATE
}).freeze
end | ruby | {
"resource": ""
} |
q10894 | Hanami.Hanamirc.parse_file | train | def parse_file(path)
{}.tap do |hash|
File.readlines(path).each do |line|
key, value = line.split(SEPARATOR)
hash[key] = value.strip
end
end
end | ruby | {
"resource": ""
} |
q10895 | Hanami.MiddlewareStack.load! | train | def load!
load_default_stack
stack.each { |m, args, block| builder.use(load_middleware(m), *args, &block) }
builder.run routes
self
end | ruby | {
"resource": ""
} |
q10896 | Hanami.MiddlewareStack.use | train | def use(middleware, *args, &blk)
stack.push [middleware, args, blk]
stack.uniq!
end | ruby | {
"resource": ""
} |
q10897 | Hanami.MiddlewareStack.prepend | train | def prepend(middleware, *args, &blk)
stack.unshift [middleware, args, blk]
stack.uniq!
end | ruby | {
"resource": ""
} |
q10898 | Hanami.Routes.path | train | def path(name, *args)
Utils::Escape::SafeString.new(@routes.path(name, *args))
end | ruby | {
"resource": ""
} |
q10899 | Hanami.Routes.url | train | def url(name, *args)
Utils::Escape::SafeString.new(@routes.url(name, *args))
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.