_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q12700 | Phonelib.PhoneAnalyzer.all_number_types | train | def all_number_types(phone, data, not_valid = false)
response = { valid: [], possible: [] }
types_for_check(data).each do |type|
possible, valid = get_patterns(data, type)
valid_and_possible, possible_result =
number_valid_and_possible?(phone, possible, valid, not_valid)
response[:possible] << type if possible_result
response[:valid] << type if valid_and_possible
end
sanitize_fixed_mobile(response)
end | ruby | {
"resource": ""
} |
q12701 | Phonelib.PhoneAnalyzer.number_format | train | def number_format(national, format_data)
format_data && format_data.find do |format|
(format[Core::LEADING_DIGITS].nil? || \
national.match(cr("^(#{format[Core::LEADING_DIGITS]})"))) && \
national.match(cr("^(#{format[Core::PATTERN]})$"))
end || Core::DEFAULT_NUMBER_FORMAT
end | ruby | {
"resource": ""
} |
q12702 | Phonelib.PhoneAnalyzer.get_patterns | train | def get_patterns(all_patterns, type)
type = Core::FIXED_LINE if type == Core::FIXED_OR_MOBILE
patterns = all_patterns[type]
if patterns
[
type_regex(patterns, Core::POSSIBLE_PATTERN),
type_regex(patterns, Core::VALID_PATTERN)
]
else
[nil, nil]
end
end | ruby | {
"resource": ""
} |
q12703 | Phonelib.PhoneAnalyzerHelper.vanity_converted | train | def vanity_converted(phone)
return phone unless Phonelib.vanity_conversion
(phone || '').gsub(cr('[a-zA-Z]')) do |c|
c.upcase!
# subtract "A"
n = (c.ord - 65) / 3
# account for #7 & #9 which have 4 chars
n -= 1 if c.match(Core::VANITY_4_LETTERS_KEYS_REGEX)
(n + 2).to_s
end
end | ruby | {
"resource": ""
} |
q12704 | Phonelib.PhoneAnalyzerHelper.passed_country | train | def passed_country(country)
code = country_prefix(country)
if Core::PLUS_SIGN == @original[0] && code && !sanitized.start_with?(code)
# in case number passed with + but it doesn't start with passed
# country prefix
country = nil
end
country
end | ruby | {
"resource": ""
} |
q12705 | Phonelib.PhoneAnalyzerHelper.country_prefix | train | def country_prefix(country)
country = country.to_s.upcase
Phonelib.phone_data[country] && \
Phonelib.phone_data[country][Core::COUNTRY_CODE]
end | ruby | {
"resource": ""
} |
q12706 | Phonelib.PhoneAnalyzerHelper.country_can_dp? | train | def country_can_dp?(country)
Phonelib.phone_data[country] &&
Phonelib.phone_data[country][Core::DOUBLE_COUNTRY_PREFIX_FLAG] &&
!original_starts_with_plus?
end | ruby | {
"resource": ""
} |
q12707 | Phonelib.PhoneAnalyzerHelper.double_prefix_allowed? | train | def double_prefix_allowed?(data, phone, parsed = {})
data[Core::DOUBLE_COUNTRY_PREFIX_FLAG] &&
phone =~ cr("^#{data[Core::COUNTRY_CODE]}") &&
parsed && (parsed[:valid].nil? || parsed[:valid].empty?) &&
!original_starts_with_plus?
end | ruby | {
"resource": ""
} |
q12708 | Phonelib.PhoneAnalyzerHelper.country_or_default_country | train | def country_or_default_country(country)
country ||= (original_starts_with_plus? ? nil : Phonelib.default_country)
country && country.to_s.upcase
end | ruby | {
"resource": ""
} |
q12709 | Phonelib.PhoneAnalyzerHelper.type_regex | train | def type_regex(data, type)
regex = [data[type]]
if Phonelib.parse_special && data[Core::SHORT] && data[Core::SHORT][type]
regex << data[Core::SHORT][type]
end
regex.join('|')
end | ruby | {
"resource": ""
} |
q12710 | Phonelib.PhoneAnalyzerHelper.phone_match_data? | train | def phone_match_data?(phone, data, possible = false)
country_code = "#{data[Core::COUNTRY_CODE]}"
inter_prefix = "(#{data[Core::INTERNATIONAL_PREFIX]})?"
return unless phone.match cr("^0{2}?#{inter_prefix}#{country_code}")
type = possible ? Core::POSSIBLE_PATTERN : Core::VALID_PATTERN
phone.match full_regex_for_data(data, type, false)
end | ruby | {
"resource": ""
} |
q12711 | Phonelib.PhoneAnalyzerHelper.types_for_check | train | def types_for_check(data)
exclude_list = PhoneAnalyzer::NOT_FOR_CHECK
exclude_list += Phonelib::Core::SHORT_CODES unless Phonelib.parse_special
Core::TYPES_DESC.keys - exclude_list + fixed_and_mobile_keys(data)
end | ruby | {
"resource": ""
} |
q12712 | Phonelib.PhoneAnalyzerHelper.fixed_and_mobile_keys | train | def fixed_and_mobile_keys(data)
if data[Core::FIXED_LINE] == data[Core::MOBILE]
[Core::FIXED_OR_MOBILE]
else
[Core::FIXED_LINE, Core::MOBILE]
end
end | ruby | {
"resource": ""
} |
q12713 | Phonelib.PhoneAnalyzerHelper.number_valid_and_possible? | train | def number_valid_and_possible?(number, p_regex, v_regex, not_valid = false)
possible = number_match?(number, p_regex)
return [!not_valid && possible, possible] if p_regex == v_regex
valid = !not_valid && possible && number_match?(number, v_regex)
[valid && possible, possible]
end | ruby | {
"resource": ""
} |
q12714 | Phonelib.PhoneAnalyzerHelper.number_match? | train | def number_match?(number, regex)
match = number.match(cr("^(?:#{regex})$"))
match && match.to_s.length == number.length
end | ruby | {
"resource": ""
} |
q12715 | Phonelib.Phone.local_number | train | def local_number
return national unless possible?
format_match, format_string = formatting_data
if format_string =~ /^.*[0-9]+.*\$1/ && format_match
format_string.gsub(/^.*\$2/, '$2')
.gsub(/\$\d/) { |el| format_match[el[1].to_i] }
else
national
end
end | ruby | {
"resource": ""
} |
q12716 | Phonelib.Phone.valid_for_country? | train | def valid_for_country?(country)
country = country.to_s.upcase
tdata = analyze(sanitized, passed_country(country))
tdata.find do |iso2, data|
country == iso2 && data[:valid].any?
end.is_a? Array
end | ruby | {
"resource": ""
} |
q12717 | Phonelib.DataImporterHelper.save_data_file | train | def save_data_file
File.open(file_path(Phonelib::Core::FILE_MAIN_DATA), 'wb+') do |f|
Marshal.dump(@data, f)
end
end | ruby | {
"resource": ""
} |
q12718 | Phonelib.DataImporterHelper.save_extended_data_file | train | def save_extended_data_file
extended = {
Phonelib::Core::EXT_PREFIXES => @prefixes,
Phonelib::Core::EXT_GEO_NAMES => @geo_names,
Phonelib::Core::EXT_COUNTRY_NAMES => @countries,
Phonelib::Core::EXT_TIMEZONES => @timezones,
Phonelib::Core::EXT_CARRIERS => @carriers
}
File.open(file_path(Phonelib::Core::FILE_EXT_DATA), 'wb+') do |f|
Marshal.dump(extended, f)
end
puts 'DATA SAVED'
end | ruby | {
"resource": ""
} |
q12719 | Phonelib.DataImporterHelper.fill_prefixes | train | def fill_prefixes(key, value, prefix, prefixes)
prefixes = {} if prefixes.nil?
if prefix.size == 1
pr = prefix.to_i
prefixes[pr] ||= {}
prefixes[pr][key] = value
else
pr = prefix[0].to_i
prefixes[pr] = fill_prefixes(key, value, prefix[1..-1], prefixes[pr])
end
prefixes
end | ruby | {
"resource": ""
} |
q12720 | Phonelib.DataImporterHelper.parse_raw_file | train | def parse_raw_file(file)
data = {}
File.readlines(file).each do |line|
line = str_clean line, false
next if line.empty? || line[0] == '#'
prefix, line_data = line.split('|')
data[prefix] = line_data && line_data.strip.split('&')
end
data
end | ruby | {
"resource": ""
} |
q12721 | Phonelib.DataImporterHelper.main_from_xml | train | def main_from_xml(file)
xml_data = File.read(file)
xml_data.force_encoding('utf-8')
doc = Nokogiri::XML(xml_data)
doc.elements.first.elements.first
end | ruby | {
"resource": ""
} |
q12722 | Phonelib.PhoneFormatter.national | train | def national(formatted = true)
return @national_number unless valid?
format_match, format_string = formatting_data
if format_match
out = format_string.gsub(/\$\d/) { |el| format_match[el[1].to_i] }
formatted ? out : out.gsub(/[^0-9]/, '')
else
@national_number
end
end | ruby | {
"resource": ""
} |
q12723 | Phonelib.PhoneFormatter.raw_national | train | def raw_national
return nil if sanitized.nil? || sanitized.empty?
if valid?
@national_number
elsif country_code && sanitized.start_with?(country_code)
sanitized[country_code.size..-1]
else
sanitized
end
end | ruby | {
"resource": ""
} |
q12724 | Phonelib.PhoneFormatter.international | train | def international(formatted = true, prefix = '+')
prefix = formatted if formatted.is_a?(String)
return nil if sanitized.empty?
return "#{prefix}#{country_prefix_or_not}#{sanitized}" unless valid?
return country_code + @national_number unless formatted
fmt = @data[country][:format]
national = @national_number
if (matches = @national_number.match(cr(fmt[Core::PATTERN])))
fmt = fmt[:intl_format] || fmt[:format]
national = fmt.gsub(/\$\d/) { |el| matches[el[1].to_i] } unless fmt == 'NA'
end
"#{prefix}#{country_code} #{national}"
end | ruby | {
"resource": ""
} |
q12725 | Phonelib.PhoneFormatter.area_code | train | def area_code
return nil unless area_code_possible?
format_match, _format_string = formatting_data
take_group = 1
if type == Core::MOBILE && Core::AREA_CODE_MOBILE_TOKENS[country] && \
format_match[1] == Core::AREA_CODE_MOBILE_TOKENS[country]
take_group = 2
end
format_match[take_group]
end | ruby | {
"resource": ""
} |
q12726 | Psych.ScalarScanner.tokenize | train | def tokenize string
return nil if string.empty?
return string if @string_cache.key?(string)
return @symbol_cache[string] if @symbol_cache.key?(string)
case string
# Check for a String type, being careful not to get caught by hash keys, hex values, and
# special floats (e.g., -.inf).
when /^[^\d\.:-]?[A-Za-z_\s!@#\$%\^&\*\(\)\{\}\<\>\|\/\\~;=]+/, /\n/
if string.length > 5
@string_cache[string] = true
return string
end
case string
when /^[^ytonf~]/i
@string_cache[string] = true
string
when '~', /^null$/i
nil
when /^(yes|true|on)$/i
true
when /^(no|false|off)$/i
false
else
@string_cache[string] = true
string
end
when TIME
begin
parse_time string
rescue ArgumentError
string
end
when /^\d{4}-(?:1[012]|0\d|\d)-(?:[12]\d|3[01]|0\d|\d)$/
require 'date'
begin
class_loader.date.strptime(string, '%Y-%m-%d')
rescue ArgumentError
string
end
when /^\.inf$/i
Float::INFINITY
when /^-\.inf$/i
-Float::INFINITY
when /^\.nan$/i
Float::NAN
when /^:./
if string =~ /^:(["'])(.*)\1/
@symbol_cache[string] = class_loader.symbolize($2.sub(/^:/, ''))
else
@symbol_cache[string] = class_loader.symbolize(string.sub(/^:/, ''))
end
when /^[-+]?[0-9][0-9_]*(:[0-5]?[0-9]){1,2}$/
i = 0
string.split(':').each_with_index do |n,e|
i += (n.to_i * 60 ** (e - 2).abs)
end
i
when /^[-+]?[0-9][0-9_]*(:[0-5]?[0-9]){1,2}\.[0-9_]*$/
i = 0
string.split(':').each_with_index do |n,e|
i += (n.to_f * 60 ** (e - 2).abs)
end
i
when FLOAT
if string =~ /\A[-+]?\.\Z/
@string_cache[string] = true
string
else
Float(string.gsub(/[,_]|\.([Ee]|$)/, '\1'))
end
else
int = parse_int string.gsub(/[,_]/, '')
return int if int
@string_cache[string] = true
string
end
end | ruby | {
"resource": ""
} |
q12727 | Psych.ScalarScanner.parse_time | train | def parse_time string
klass = class_loader.load 'Time'
date, time = *(string.split(/[ tT]/, 2))
(yy, m, dd) = date.match(/^(-?\d{4})-(\d{1,2})-(\d{1,2})/).captures.map { |x| x.to_i }
md = time.match(/(\d+:\d+:\d+)(?:\.(\d*))?\s*(Z|[-+]\d+(:\d\d)?)?/)
(hh, mm, ss) = md[1].split(':').map { |x| x.to_i }
us = (md[2] ? Rational("0.#{md[2]}") : 0) * 1000000
time = klass.utc(yy, m, dd, hh, mm, ss, us)
return time if 'Z' == md[3]
return klass.at(time.to_i, us) unless md[3]
tz = md[3].match(/^([+\-]?\d{1,2})\:?(\d{1,2})?$/)[1..-1].compact.map { |digit| Integer(digit, 10) }
offset = tz.first * 3600
if offset < 0
offset -= ((tz[1] || 0) * 60)
else
offset += ((tz[1] || 0) * 60)
end
klass.new(yy, m, dd, hh, mm, ss+us/(1_000_000r), offset)
end | ruby | {
"resource": ""
} |
q12728 | Psych.TreeBuilder.start_document | train | def start_document version, tag_directives, implicit
n = Nodes::Document.new version, tag_directives, implicit
set_start_location(n)
@last.children << n
push n
end | ruby | {
"resource": ""
} |
q12729 | Psych.TreeBuilder.end_document | train | def end_document implicit_end = !streaming?
@last.implicit_end = implicit_end
n = pop
set_end_location(n)
n
end | ruby | {
"resource": ""
} |
q12730 | Pwb.Api::V1::TranslationsController.delete_translation_values | train | def delete_translation_values
field_key = FieldKey.find_by_global_key(params[:i18n_key])
field_key.visible = false
# not convinced it makes sense to delete the associated translations
# phrases = I18n::Backend::ActiveRecord::Translation.where(:key => params[:i18n_key])
# phrases.destroy_all
field_key.save!
render json: { success: true }
end | ruby | {
"resource": ""
} |
q12731 | Pwb.Api::V1::TranslationsController.create_for_locale | train | def create_for_locale
field_key = FieldKey.find_by_global_key(params[:i18n_key])
phrase = I18n::Backend::ActiveRecord::Translation.find_or_create_by(
key: field_key.global_key,
locale: params[:locale]
)
unless phrase.value.present?
I18n.backend.reload!
phrase.value = params[:i18n_value]
phrase.save!
end
render json: { success: true }
end | ruby | {
"resource": ""
} |
q12732 | Pwb.SearchController.buy | train | def buy
@page = Pwb::Page.find_by_slug "buy"
@page_title = @current_agency.company_name
# @content_to_show = []
if @page.present?
@page_title = @page.page_title + ' - ' + @current_agency.company_name
# TODO: - allow addition of custom content
# @page.ordered_visible_page_contents.each do |page_content|
# @content_to_show.push page_content.content.raw
# end
end
# @page_title = I18n.t("searchForProperties")
# in erb template for this action, I have js that will render search_results template
# for properties - like search_ajax action does
@operation_type = "for_sale"
# above used to decide if link to result should be to buy or rent path
@properties = Prop.visible.for_sale.limit 45
# ordering happens clientside
# .order('price_sale_current_cents ASC').limit 35
@prices_from_collection = @current_website.sale_price_options_from
@prices_till_collection = @current_website.sale_price_options_till
# @prices_collection = @current_website.sale_price_options_from
# %W(#{''} 25,000 50,000 75,000 100,000 150,000 250,000 500,000 1,000,000 2,000,000 5,000,000 )
# ..
set_common_search_inputs
set_select_picker_texts
apply_search_filter filtering_params(params)
set_map_markers
# below allows setting in form of any input values that might have been passed by param
@search_defaults = params[:search].present? ? params[:search] : {}
# {"property_type" => ""}
# below won't sort right away as the list of results is loaded by js
# and so won't be ready for sorting when below is called - but will wire up for sorting button
# initial client sort called by INMOAPP.sortSearchResults();
js 'Main/Search#sort' # trigger client-side paloma script
render "/pwb/search/buy"
end | ruby | {
"resource": ""
} |
q12733 | Pwb.Prop.set_features= | train | def set_features=(features_json)
# return unless features_json.class == Hash
features_json.keys.each do |feature_key|
# TODO - create feature_key if its missing
if features_json[feature_key] == "true" || features_json[feature_key] == true
features.find_or_create_by( feature_key: feature_key)
else
features.where( feature_key: feature_key).delete_all
end
end
end | ruby | {
"resource": ""
} |
q12734 | Pwb.Prop.contextual_price_with_currency | train | def contextual_price_with_currency(rent_or_sale)
contextual_price = self.contextual_price rent_or_sale
if contextual_price.zero?
return nil
else
return contextual_price.format(no_cents: true)
end
# return contextual_price.zero? ? nil : contextual_price.format(:no_cents => true)
end | ruby | {
"resource": ""
} |
q12735 | Pwb.Api::V1::WebContentsController.update_photo | train | def update_photo
content_tag = params[:content_tag]
# photo = ContentPhoto.find(params[:id])
# find would throw error if not found
photo = ContentPhoto.find_by_id(params[:id])
unless photo
if content_tag
# where photo has never been set before, associated Content will not exist
content = Content.find_by_key(content_tag) || Content.create({ key: content_tag, tag: 'appearance' })
photo = ContentPhoto.create
if content_tag == "logo"
# TODO: This is a workaround
# need to have a way of determining content that should only have
# one photo and enforcing that
content.content_photos.destroy_all
end
content.content_photos.push photo
end
# TODO: - handle where no photo or content_tag..
end
if params[:file]
photo.image = params[:file]
end
photo.save!
photo.reload
render json: photo.to_json
end | ruby | {
"resource": ""
} |
q12736 | Pwb.Api::V1::WebContentsController.create_content_with_photo | train | def create_content_with_photo
tag = params[:tag]
photo = ContentPhoto.create
key = tag.underscore.camelize + photo.id.to_s
new_content = Content.create(tag: tag, key: key)
# photo.subdomain = subdomain
# photo.folder = current_tenant_model.whitelabel_country_code
# photo.tenant_id = current_tenant_model.id
if params[:file]
photo.image = params[:file]
end
photo.save!
new_content.content_photos.push photo
# http://typeoneerror.com/labs/jsonapi-resources-ember-data/
# resource for model
resource = Api::V1::WebContentResource.new(new_content, nil)
# serializer for resource
serializer = JSONAPI::ResourceSerializer.new(Api::V1::WebContentResource)
# jsonapi-compliant hash (ready to be send to render)
photo.reload
# above needed to ensure image_url is available
# might need below if upload in prod is slow..
# upload_confirmed = false
# tries = 0
# until upload_confirmed
# if photo.image_url.present?
# upload_confirmed = true
# else
# sleep 1
# photo.reload
# tries += 1
# if tries > 5
# upload_confirmed = true
# end
# end
# end
render json: serializer.serialize_to_hash(resource)
# return render json: new_content.to_json
# return render :json => { :error => "Sorry...", :status => "444", :data => "ssss" }, :status => 422
end | ruby | {
"resource": ""
} |
q12737 | Pwb.PagePartManager.seed_container_block_content | train | def seed_container_block_content(locale, seed_content)
page_part_editor_setup = page_part.editor_setup
raise "Invalid editorBlocks for page_part_editor_setup" unless page_part_editor_setup && page_part_editor_setup["editorBlocks"].present?
# page = page_part.page
# page_part_key uniquely identifies a fragment
# page_part_key = page_part.page_part_key
# container for json to be attached to page details
locale_block_content_json = {"blocks" => {}}
# {"blocks"=>{"title_a"=>{"content"=>"about our agency"}, "content_a"=>{"content"=>""}}}
page_part_editor_setup["editorBlocks"].each do |configColBlocks|
configColBlocks.each do |configRowBlock|
row_block_label = configRowBlock["label"]
row_block_content = ""
# find the content for current block from within the seed content
if seed_content[row_block_label]
if configRowBlock["isImage"]
photo = seed_fragment_photo row_block_label, seed_content[row_block_label]
if photo.present? && photo.optimized_image_url.present?
# optimized_image_url is defined in content_photo and will
# return cloudinary url or filesystem url depending on settings
row_block_content = photo.optimized_image_url
else
row_block_content = "http://via.placeholder.com/350x250"
end
else
row_block_content = seed_content[row_block_label]
end
end
locale_block_content_json["blocks"][row_block_label] = {"content" => row_block_content}
end
end
# # save the block contents (in associated page_part model)
# updated_details = container.set_page_part_block_contents page_part_key, locale, locale_block_content_json
# # retrieve the contents saved above and use to rebuild html for that page_part
# # (and save it in associated page_content model)
# fragment_html = container.rebuild_page_content page_part_key, locale
update_page_part_content locale, locale_block_content_json
p " #{page_part_key} content set for #{locale}."
end | ruby | {
"resource": ""
} |
q12738 | Pwb.PagePartManager.set_page_part_block_contents | train | def set_page_part_block_contents(_page_part_key, locale, fragment_details)
# page_part = self.page_parts.find_by_page_part_key page_part_key
if page_part.present?
page_part.block_contents[locale] = fragment_details
page_part.save!
# fragment_details passed in might be a params object
# - retrieving what has just been saved will return it as JSON
fragment_details = page_part.block_contents[locale]
end
fragment_details
end | ruby | {
"resource": ""
} |
q12739 | Pwb.PagePartManager.rebuild_page_content | train | def rebuild_page_content(locale)
unless page_part && page_part.template
raise "page_part with valid template not available"
end
# page_part = self.page_parts.find_by_page_part_key page_part_key
if page_part.present?
l_template = Liquid::Template.parse(page_part.template)
new_fragment_html = l_template.render('page_part' => page_part.block_contents[locale]["blocks"] )
# p "#{page_part_key} content for #{self.slug} page parsed."
# save in content model associated with page
page_fragment_content = find_or_create_content
# container.contents.find_or_create_by(page_part_key: page_part_key)
content_html_col = "raw_" + locale + "="
# above is the col used by globalize gem to store localized data
# page_fragment_content[content_html_col] = new_fragment_html
page_fragment_content.send content_html_col, new_fragment_html
page_fragment_content.save!
# set page_part_key value on join model
page_content_join_model = get_join_model
# page_fragment_content.page_contents.find_by_page_id self.id
page_content_join_model.page_part_key = page_part_key
page_content_join_model.save!
else
new_fragment_html = ""
end
new_fragment_html
end | ruby | {
"resource": ""
} |
q12740 | Pwb.PagePartManager.seed_fragment_photo | train | def seed_fragment_photo(block_label, photo_file)
# content_key = self.slug + "_" + page_part_key
# get in content model associated with page and fragment
# join_model = page_contents.find_or_create_by(page_part_key: page_part_key)
# page_fragment_content = join_model.create_content(page_part_key: page_part_key)
# join_model.save!
# page_fragment_content = contents.find_or_create_by(page_part_key: page_part_key)
page_fragment_content = find_or_create_content
photo = page_fragment_content.content_photos.find_by_block_key(block_label)
if photo.present?
return photo
else
photo = page_fragment_content.content_photos.create(block_key: block_label)
end
if ENV["RAILS_ENV"] == "test"
# don't create photos for tests
return nil
end
begin
# if photo_file.is_a?(String)
# photo.image = photo_file
photo.image = Pwb::Engine.root.join(photo_file).open
photo.save!
print "#{slug}--#{page_part_key} image created: #{photo.optimized_image_url}\n"
# reload the record to ensure that url is available
photo.reload
print "#{slug}--#{page_part_key} image created: #{photo.optimized_image_url}(after reload..)"
rescue Exception => e
# log exception to console
print e
end
photo
end | ruby | {
"resource": ""
} |
q12741 | Pwb.Website.get_element_class | train | def get_element_class(element_name)
style_details = style_variables_for_theme["vic"] || Pwb::PresetStyle.default_values
style_associations = style_details["associations"] || []
style_associations[element_name] || ""
end | ruby | {
"resource": ""
} |
q12742 | Pwb.Website.style_settings_from_preset= | train | def style_settings_from_preset=(preset_style_name)
preset_style = Pwb::PresetStyle.where(name: preset_style_name).first
if preset_style
style_variables_for_theme["vic"] = preset_style.attributes.as_json
end
end | ruby | {
"resource": ""
} |
q12743 | TTY.Prompt.invoke_question | train | def invoke_question(object, message, *args, &block)
options = Utils.extract_options!(args)
options[:messages] = self.class.messages
question = object.new(self, options)
question.(message, &block)
end | ruby | {
"resource": ""
} |
q12744 | TTY.Prompt.invoke_select | train | def invoke_select(object, question, *args, &block)
options = Utils.extract_options!(args)
choices = if block
[]
elsif args.empty?
possible = options.dup
options = {}
possible
elsif args.size == 1 && args[0].is_a?(Hash)
Utils.extract_options!(args)
else
args.flatten
end
list = object.new(self, options)
list.(question, choices, &block)
end | ruby | {
"resource": ""
} |
q12745 | TTY.Prompt.yes? | train | def yes?(message, *args, &block)
defaults = { default: true }
options = Utils.extract_options!(args)
options.merge!(defaults.reject { |k, _| options.key?(k) })
question = ConfirmQuestion.new(self, options)
question.call(message, &block)
end | ruby | {
"resource": ""
} |
q12746 | TTY.Prompt.slider | train | def slider(question, *args, &block)
options = Utils.extract_options!(args)
slider = Slider.new(self, options)
slider.call(question, &block)
end | ruby | {
"resource": ""
} |
q12747 | TTY.Prompt.say | train | def say(message = '', options = {})
message = message.to_s
return if message.empty?
statement = Statement.new(self, options)
statement.call(message)
end | ruby | {
"resource": ""
} |
q12748 | TTY.Prompt.debug | train | def debug(*messages)
longest = messages.max_by(&:length).size
width = TTY::Screen.width - longest
print cursor.save
messages.each_with_index do |msg, i|
print cursor.move_to(width, i)
print cursor.clear_line_after
print msg
end
print cursor.restore
end | ruby | {
"resource": ""
} |
q12749 | TTY.Prompt.suggest | train | def suggest(message, possibilities, options = {})
suggestion = Suggestion.new(options)
say(suggestion.suggest(message, possibilities))
end | ruby | {
"resource": ""
} |
q12750 | TTY.Prompt.collect | train | def collect(options = {}, &block)
collector = AnswersCollector.new(self, options)
collector.call(&block)
end | ruby | {
"resource": ""
} |
q12751 | TTY.Utils.extract_options | train | def extract_options(args)
options = args.last
options.respond_to?(:to_hash) ? options.to_hash.dup : {}
end | ruby | {
"resource": ""
} |
q12752 | TTY.Utils.blank? | train | def blank?(value)
value.nil? ||
value.respond_to?(:empty?) && value.empty? ||
BLANK_REGEX === value
end | ruby | {
"resource": ""
} |
q12753 | Spring.Application.shush_backtraces | train | def shush_backtraces
Kernel.module_eval do
old_raise = Kernel.method(:raise)
remove_method :raise
define_method :raise do |*args|
begin
old_raise.call(*args)
ensure
if $!
lib = File.expand_path("..", __FILE__)
$!.backtrace.reject! { |line| line.start_with?(lib) }
end
end
end
private :raise
end
end | ruby | {
"resource": ""
} |
q12754 | Spring.OkJson.decode | train | def decode(s)
ts = lex(s)
v, ts = textparse(ts)
if ts.length > 0
raise Error, 'trailing garbage'
end
v
end | ruby | {
"resource": ""
} |
q12755 | Spring.OkJson.objparse | train | def objparse(ts)
ts = eat('{', ts)
obj = {}
if ts[0][0] == '}'
return obj, ts[1..-1]
end
k, v, ts = pairparse(ts)
obj[k] = v
if ts[0][0] == '}'
return obj, ts[1..-1]
end
loop do
ts = eat(',', ts)
k, v, ts = pairparse(ts)
obj[k] = v
if ts[0][0] == '}'
return obj, ts[1..-1]
end
end
end | ruby | {
"resource": ""
} |
q12756 | Spring.OkJson.pairparse | train | def pairparse(ts)
(typ, _, k), ts = ts[0], ts[1..-1]
if typ != :str
raise Error, "unexpected #{k.inspect}"
end
ts = eat(':', ts)
v, ts = valparse(ts)
[k, v, ts]
end | ruby | {
"resource": ""
} |
q12757 | Spring.OkJson.arrparse | train | def arrparse(ts)
ts = eat('[', ts)
arr = []
if ts[0][0] == ']'
return arr, ts[1..-1]
end
v, ts = valparse(ts)
arr << v
if ts[0][0] == ']'
return arr, ts[1..-1]
end
loop do
ts = eat(',', ts)
v, ts = valparse(ts)
arr << v
if ts[0][0] == ']'
return arr, ts[1..-1]
end
end
end | ruby | {
"resource": ""
} |
q12758 | Spring.OkJson.tok | train | def tok(s)
case s[0]
when ?{ then ['{', s[0,1], s[0,1]]
when ?} then ['}', s[0,1], s[0,1]]
when ?: then [':', s[0,1], s[0,1]]
when ?, then [',', s[0,1], s[0,1]]
when ?[ then ['[', s[0,1], s[0,1]]
when ?] then [']', s[0,1], s[0,1]]
when ?n then nulltok(s)
when ?t then truetok(s)
when ?f then falsetok(s)
when ?" then strtok(s)
when Spc, ?\t, ?\n, ?\r then [:space, s[0,1], s[0,1]]
else
numtok(s)
end
end | ruby | {
"resource": ""
} |
q12759 | Spring.OkJson.unquote | train | def unquote(q)
q = q[1...-1]
a = q.dup # allocate a big enough string
# In ruby >= 1.9, a[w] is a codepoint, not a byte.
if rubydoesenc?
a.force_encoding('UTF-8')
end
r, w = 0, 0
while r < q.length
c = q[r]
if c == ?\\
r += 1
if r >= q.length
raise Error, "string literal ends with a \"\\\": \"#{q}\""
end
case q[r]
when ?",?\\,?/,?'
a[w] = q[r]
r += 1
w += 1
when ?b,?f,?n,?r,?t
a[w] = Unesc[q[r]]
r += 1
w += 1
when ?u
r += 1
uchar = begin
hexdec4(q[r,4])
rescue RuntimeError => e
raise Error, "invalid escape sequence \\u#{q[r,4]}: #{e}"
end
r += 4
if surrogate? uchar
if q.length >= r+6
uchar1 = hexdec4(q[r+2,4])
uchar = subst(uchar, uchar1)
if uchar != Ucharerr
# A valid pair; consume.
r += 6
end
end
end
if rubydoesenc?
a[w] = '' << uchar
w += 1
else
w += ucharenc(a, w, uchar)
end
else
raise Error, "invalid escape char #{q[r]} in \"#{q}\""
end
elsif c == ?" || c < Spc
raise Error, "invalid character in string literal \"#{q}\""
else
# Copy anything else byte-for-byte.
# Valid UTF-8 will remain valid UTF-8.
# Invalid UTF-8 will remain invalid UTF-8.
# In ruby >= 1.9, c is a codepoint, not a byte,
# in which case this is still what we want.
a[w] = c
r += 1
w += 1
end
end
a[0,w]
end | ruby | {
"resource": ""
} |
q12760 | Spring.OkJson.ucharenc | train | def ucharenc(a, i, u)
if u <= Uchar1max
a[i] = (u & 0xff).chr
1
elsif u <= Uchar2max
a[i+0] = (Utag2 | ((u>>6)&0xff)).chr
a[i+1] = (Utagx | (u&Umaskx)).chr
2
elsif u <= Uchar3max
a[i+0] = (Utag3 | ((u>>12)&0xff)).chr
a[i+1] = (Utagx | ((u>>6)&Umaskx)).chr
a[i+2] = (Utagx | (u&Umaskx)).chr
3
else
a[i+0] = (Utag4 | ((u>>18)&0xff)).chr
a[i+1] = (Utagx | ((u>>12)&Umaskx)).chr
a[i+2] = (Utagx | ((u>>6)&Umaskx)).chr
a[i+3] = (Utagx | (u&Umaskx)).chr
4
end
end | ruby | {
"resource": ""
} |
q12761 | Spring.ApplicationManager.run | train | def run(client)
with_child do
child.send_io client
child.gets or raise Errno::EPIPE
end
pid = child.gets.to_i
unless pid.zero?
log "got worker pid #{pid}"
pid
end
rescue Errno::ECONNRESET, Errno::EPIPE => e
log "#{e} while reading from child; returning no pid"
nil
ensure
client.close
end | ruby | {
"resource": ""
} |
q12762 | Koala.Utils.symbolize_hash | train | def symbolize_hash(hash)
return hash unless hash.is_a?(Hash)
hash.inject({}){ |memo,(key,value)| memo[key.to_sym] = symbolize_hash(value); memo }
end | ruby | {
"resource": ""
} |
q12763 | PublicActivity.ViewHelpers.single_content_for | train | def single_content_for(name, content = nil, &block)
@view_flow.set(name, ActiveSupport::SafeBuffer.new)
content_for(name, content, &block)
end | ruby | {
"resource": ""
} |
q12764 | PublicActivity.Common.create_activity! | train | def create_activity!(*args)
return unless self.public_activity_enabled?
options = prepare_settings(*args)
if call_hook_safe(options[:key].split('.').last)
reset_activity_instance_options
return PublicActivity::Adapter.create_activity!(self, options)
end
end | ruby | {
"resource": ""
} |
q12765 | PublicActivity.Common.prepare_custom_fields | train | def prepare_custom_fields(options)
customs = self.class.activity_custom_fields_global.clone
customs.merge!(self.activity_custom_fields) if self.activity_custom_fields
customs.merge!(options)
customs.each do |k, v|
customs[k] = PublicActivity.resolve_value(self, v)
end
end | ruby | {
"resource": ""
} |
q12766 | PublicActivity.Common.prepare_key | train | def prepare_key(action, options = {})
(
options[:key] ||
self.activity_key ||
((self.class.name.underscore.gsub('/', '_') + "." + action.to_s) if action)
).try(:to_s)
end | ruby | {
"resource": ""
} |
q12767 | PublicActivity.Renderable.text | train | def text(params = {})
# TODO: some helper for key transformation for two supported formats
k = key.split('.')
k.unshift('activity') if k.first != 'activity'
k = k.join('.')
I18n.t(k, parameters.merge(params) || {})
end | ruby | {
"resource": ""
} |
q12768 | PublicActivity.Renderable.render | train | def render(context, params = {})
partial_root = params.delete(:root) || 'public_activity'
partial_path = nil
layout_root = params.delete(:layout_root) || 'layouts'
if params.has_key? :display
if params[:display].to_sym == :"i18n"
text = self.text(params)
return context.render :text => text, :plain => text
else
partial_path = File.join(partial_root, params[:display].to_s)
end
end
context.render(
params.merge({
:partial => prepare_partial(partial_root, partial_path),
:layout => prepare_layout(layout_root, params.delete(:layout)),
:locals => prepare_locals(params)
})
)
end | ruby | {
"resource": ""
} |
q12769 | PublicActivity.Renderable.template_path | train | def template_path(key, partial_root)
path = key.split(".")
path.delete_at(0) if path[0] == "activity"
path.unshift partial_root
path.join("/")
end | ruby | {
"resource": ""
} |
q12770 | Restforce.Collection.each | train | def each
@raw_page['records'].each { |record| yield Restforce::Mash.build(record, @client) }
np = next_page
while np
np.current_page.each { |record| yield record }
np = np.next_page
end
end | ruby | {
"resource": ""
} |
q12771 | Restforce.Middleware::Authentication.encode_www_form | train | def encode_www_form(params)
if URI.respond_to?(:encode_www_form)
URI.encode_www_form(params)
else
params.map do |k, v|
k = CGI.escape(k.to_s)
v = CGI.escape(v.to_s)
"#{k}=#{v}"
end.join('&')
end
end | ruby | {
"resource": ""
} |
q12772 | RMagick.Extconf.have_enum_values | train | def have_enum_values(enum, values, headers = nil, &b)
values.each do |value|
have_enum_value(enum, value, headers, &b)
end
end | ruby | {
"resource": ""
} |
q12773 | Magick.RVG.bgfill | train | def bgfill
if @background_fill.nil?
color = Magick::Pixel.new(0, 0, 0, Magick::TransparentOpacity)
else
color = @background_fill
color.opacity = (1.0 - @background_fill_opacity) * Magick::TransparentOpacity
end
color
end | ruby | {
"resource": ""
} |
q12774 | Magick.RVG.background_image= | train | def background_image=(bg_image)
warn 'background_image= has no effect in nested RVG objects' if @nested
raise ArgumentError, "background image must be an Image (got #{bg_image.class})" if bg_image && !bg_image.is_a?(Magick::Image)
@background_image = bg_image
end | ruby | {
"resource": ""
} |
q12775 | Magick.RVG.add_outermost_primitives | train | def add_outermost_primitives(gc) #:nodoc:
add_transform_primitives(gc)
gc.push
add_viewbox_primitives(@width, @height, gc)
add_style_primitives(gc)
@content.each { |element| element.add_primitives(gc) }
gc.pop
self
end | ruby | {
"resource": ""
} |
q12776 | Magick.RVG.add_primitives | train | def add_primitives(gc) #:nodoc:
raise ArgumentError, 'RVG width or height undefined' if @width.nil? || @height.nil?
return self if @width.zero? || @height.zero?
gc.push
add_outermost_primitives(gc)
gc.pop
end | ruby | {
"resource": ""
} |
q12777 | Magick.Geometry.to_s | train | def to_s
str = ''
if @width > 0
fmt = @width.truncate == @width ? '%d' : '%.2f'
str << format(fmt, @width)
str << '%' if @flag == PercentGeometry
end
str << 'x' if (@width > 0 && @flag != PercentGeometry) || (@height > 0)
if @height > 0
fmt = @height.truncate == @height ? '%d' : '%.2f'
str << format(fmt, @height)
str << '%' if @flag == PercentGeometry
end
str << format('%+d%+d', @x, @y) if @x != 0 || @y != 0
str << FLAGS[@flag.to_i] if @flag != PercentGeometry
str
end | ruby | {
"resource": ""
} |
q12778 | Magick.Draw.arc | train | def arc(start_x, start_y, end_x, end_y, start_degrees, end_degrees)
primitive 'arc ' + format('%g,%g %g,%g %g,%g',
start_x, start_y, end_x, end_y, start_degrees, end_degrees)
end | ruby | {
"resource": ""
} |
q12779 | Magick.Draw.circle | train | def circle(origin_x, origin_y, perim_x, perim_y)
primitive 'circle ' + format('%g,%g %g,%g', origin_x, origin_y, perim_x, perim_y)
end | ruby | {
"resource": ""
} |
q12780 | Magick.Draw.clip_rule | train | def clip_rule(rule)
Kernel.raise ArgumentError, "Unknown clipping rule #{rule}" unless %w[evenodd nonzero].include?(rule.downcase)
primitive "clip-rule #{rule}"
end | ruby | {
"resource": ""
} |
q12781 | Magick.Draw.clip_units | train | def clip_units(unit)
Kernel.raise ArgumentError, "Unknown clip unit #{unit}" unless %w[userspace userspaceonuse objectboundingbox].include?(unit.downcase)
primitive "clip-units #{unit}"
end | ruby | {
"resource": ""
} |
q12782 | Magick.Draw.color | train | def color(x, y, method)
Kernel.raise ArgumentError, "Unknown PaintMethod: #{method}" unless PAINT_METHOD_NAMES.key?(method.to_i)
primitive "color #{x},#{y},#{PAINT_METHOD_NAMES[method.to_i]}"
end | ruby | {
"resource": ""
} |
q12783 | Magick.Draw.ellipse | train | def ellipse(origin_x, origin_y, width, height, arc_start, arc_end)
primitive 'ellipse ' + format('%g,%g %g,%g %g,%g',
origin_x, origin_y, width, height, arc_start, arc_end)
end | ruby | {
"resource": ""
} |
q12784 | Magick.Draw.interline_spacing | train | def interline_spacing(space)
begin
Float(space)
rescue ArgumentError
Kernel.raise ArgumentError, 'invalid value for interline_spacing'
rescue TypeError
Kernel.raise TypeError, "can't convert #{space.class} into Float"
end
primitive "interline-spacing #{space}"
end | ruby | {
"resource": ""
} |
q12785 | Magick.Draw.line | train | def line(start_x, start_y, end_x, end_y)
primitive 'line ' + format('%g,%g %g,%g', start_x, start_y, end_x, end_y)
end | ruby | {
"resource": ""
} |
q12786 | Magick.Draw.opacity | train | def opacity(opacity)
if opacity.is_a?(Numeric)
Kernel.raise ArgumentError, 'opacity must be >= 0 and <= 1.0' if opacity < 0 || opacity > 1.0
end
primitive "opacity #{opacity}"
end | ruby | {
"resource": ""
} |
q12787 | Magick.Draw.pattern | train | def pattern(name, x, y, width, height)
push('defs')
push("pattern #{name} #{x} #{y} #{width} #{height}")
push('graphic-context')
yield
ensure
pop('graphic-context')
pop('pattern')
pop('defs')
end | ruby | {
"resource": ""
} |
q12788 | Magick.Draw.polygon | train | def polygon(*points)
if points.length.zero?
Kernel.raise ArgumentError, 'no points specified'
elsif points.length.odd?
Kernel.raise ArgumentError, 'odd number of points specified'
end
primitive 'polygon ' + points.join(',')
end | ruby | {
"resource": ""
} |
q12789 | Magick.Draw.rectangle | train | def rectangle(upper_left_x, upper_left_y, lower_right_x, lower_right_y)
primitive 'rectangle ' + format('%g,%g %g,%g',
upper_left_x, upper_left_y, lower_right_x, lower_right_y)
end | ruby | {
"resource": ""
} |
q12790 | Magick.Draw.roundrectangle | train | def roundrectangle(center_x, center_y, width, height, corner_width, corner_height)
primitive 'roundrectangle ' + format('%g,%g,%g,%g,%g,%g',
center_x, center_y, width, height, corner_width, corner_height)
end | ruby | {
"resource": ""
} |
q12791 | Magick.Draw.stroke_dasharray | train | def stroke_dasharray(*list)
if list.length.zero?
primitive 'stroke-dasharray none'
else
list.each do |x|
Kernel.raise ArgumentError, "dash array elements must be > 0 (#{x} given)" if x <= 0
end
primitive "stroke-dasharray #{list.join(',')}"
end
end | ruby | {
"resource": ""
} |
q12792 | Magick.Draw.text | train | def text(x, y, text)
Kernel.raise ArgumentError, 'missing text argument' if text.to_s.empty?
if text.length > 2 && /\A(?:\"[^\"]+\"|\'[^\']+\'|\{[^\}]+\})\z/.match(text)
# text already quoted
elsif !text['\'']
text = '\'' + text + '\''
elsif !text['"']
text = '"' + text + '"'
elsif !(text['{'] || text['}'])
text = '{' + text + '}'
else
# escape existing braces, surround with braces
text = '{' + text.gsub(/[}]/) { |b| '\\' + b } + '}'
end
primitive "text #{x},#{y} #{text}"
end | ruby | {
"resource": ""
} |
q12793 | Magick.Draw.text_align | train | def text_align(alignment)
Kernel.raise ArgumentError, "Unknown alignment constant: #{alignment}" unless ALIGN_TYPE_NAMES.key?(alignment.to_i)
primitive "text-align #{ALIGN_TYPE_NAMES[alignment.to_i]}"
end | ruby | {
"resource": ""
} |
q12794 | Magick.Draw.text_anchor | train | def text_anchor(anchor)
Kernel.raise ArgumentError, "Unknown anchor constant: #{anchor}" unless ANCHOR_TYPE_NAMES.key?(anchor.to_i)
primitive "text-anchor #{ANCHOR_TYPE_NAMES[anchor.to_i]}"
end | ruby | {
"resource": ""
} |
q12795 | Magick.Image.color_point | train | def color_point(x, y, fill)
f = copy
f.pixel_color(x, y, fill)
f
end | ruby | {
"resource": ""
} |
q12796 | Magick.Image.color_floodfill | train | def color_floodfill(x, y, fill)
target = pixel_color(x, y)
color_flood_fill(target, fill, x, y, Magick::FloodfillMethod)
end | ruby | {
"resource": ""
} |
q12797 | Magick.Image.color_fill_to_border | train | def color_fill_to_border(x, y, fill)
color_flood_fill(border_color, fill, x, y, Magick::FillToBorderMethod)
end | ruby | {
"resource": ""
} |
q12798 | Magick.Image.each_pixel | train | def each_pixel
get_pixels(0, 0, columns, rows).each_with_index do |p, n|
yield(p, n % columns, n / columns)
end
self
end | ruby | {
"resource": ""
} |
q12799 | Magick.Image.matte_fill_to_border | train | def matte_fill_to_border(x, y)
f = copy
f.opacity = Magick::OpaqueOpacity unless f.alpha?
f.matte_flood_fill(border_color, TransparentOpacity,
x, y, FillToBorderMethod)
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.