code
stringlengths 26
124k
| docstring
stringlengths 23
125k
| func_name
stringlengths 1
98
| language
stringclasses 1
value | repo
stringlengths 5
53
| path
stringlengths 7
151
| url
stringlengths 50
211
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def status
(@remote_job || fetch_job).merge(attributes)
end
|
Return the JSON-ready Job status.
|
status
|
ruby
|
documentcloud/documentcloud
|
app/models/processing_job.rb
|
https://github.com/documentcloud/documentcloud/blob/master/app/models/processing_job.rb
|
MIT
|
def as_json(opts={})
{ 'id' => id,
'title' => title,
'status' => 'loading'
}
end
|
The default JSON of a processing job is just enough to get it polling for
updates again.
|
as_json
|
ruby
|
documentcloud/documentcloud
|
app/models/processing_job.rb
|
https://github.com/documentcloud/documentcloud/blob/master/app/models/processing_job.rb
|
MIT
|
def annotation_count(account=nil)
account ||= self.account
@annotation_count ||= Annotation.count_by_sql <<-EOS
select count(*) from annotations
inner join project_memberships on project_memberships.document_id = annotations.document_id
where project_memberships.project_id = #{id}
and (annotations.access in (#{PUBLIC}, #{EXCLUSIVE}) or
annotations.access = #{PRIVATE} and annotations.account_id = #{account.id})
EOS
end
|
How many annotations belong to documents belonging to this project?
How many of those annotations are accessible to a given account?
TODO: incorporate PREMODERATED and POSTMODERATED comments into counts
|
annotation_count
|
ruby
|
documentcloud/documentcloud
|
app/models/project.rb
|
https://github.com/documentcloud/documentcloud/blob/master/app/models/project.rb
|
MIT
|
def canonical(options={})
data = {
'id' => id,
'title' => title,
'description' => description,
'public_url' => public_url
}
if options.fetch(:include_document_ids, true)
data['document_ids'] = canonical_document_ids
else
data['document_count'] = project_memberships.count
end
data
end
|
Options:
:include_document_ids: if set and false, add a 'document_count' Integer.
Otherwise, add a 'document_ids' Array.
|
canonical
|
ruby
|
documentcloud/documentcloud
|
app/models/project.rb
|
https://github.com/documentcloud/documentcloud/blob/master/app/models/project.rb
|
MIT
|
def canonical
{'title' => title, 'page' => page_number}
end
|
The canonical JSON representation of a section.
|
canonical
|
ruby
|
documentcloud/documentcloud
|
app/models/section.rb
|
https://github.com/documentcloud/documentcloud/blob/master/app/models/section.rb
|
MIT
|
def boot_instance(options)
options = DEFAULT_BOOT_OPTIONS.merge(options)
ssh_config = {
'CheckHostIP' => 'no',
'StrictHostKeyChecking' => 'no',
'UserKnownHostsFile' => '/dev/null',
'User' => 'ubuntu',
'IdentityFile' => "#{Rails.root}/secrets/keys/documentcloud.pem"
}
File.chmod(0600, ssh_config['IdentityFile'])
new_instance = ec2.instances.create({
:image_id => options[:ami],
:count => 1,
:security_groups => ['default'],
:key_name => 'DocumentCloud 2014-04-12',
:instance_type => options[:type],
:availability_zone => DC::CONFIG['aws_zone']
})
if ( name = options[:name] )
new_instance.tag('Name', value: name )
end
# wait until instance is running and get the public dns name
while :pending == new_instance.status
sleep 2
Rails.logger.info "waiting for instance #{new_instance.instance_id} state to become 'running'"
end
# wait until the instance is running sshd
ssh_options = ssh_config.collect {|k,v| "-o #{k}=#{v}"}.join " "
while true do
sleep 2
break if system "ssh -o ConnectTimeout=10 #{ssh_options} #{new_instance.dns_name} exit 0 2>/dev/null"
Rails.logger.info "waiting for instance #{new_instance.instance_id} / #{new_instance.dns_name} to start sshd "
end
# configure new instance with ssh key to access github
system "ssh #{ssh_options} #{new_instance.dns_name} 'test -e .ssh/id_dsa && exit 0; mkdir -p .ssh; while read line; do echo $line; done > .ssh/id_dsa; chmod 0600 .ssh/id_dsa' < #{Rails.root}/secrets/keys/github.pem"
# configure new instance
unless options[:scripts].empty?
options[:scripts].each do |script|
system "ssh #{ssh_options} #{new_instance.dns_name} sudo bash -x < #{script}"
end
end
Rails.logger.info "ssh #{ssh_options} #{new_instance.dns_name}"
return new_instance
end
|
Boot a new instance, given `ami`, `type`, and `scripts` options.
|
boot_instance
|
ruby
|
documentcloud/documentcloud
|
lib/dc/aws.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/aws.rb
|
MIT
|
def execute_on_hosts(script, hosts)
hosts.each do |host|
@threads.push(Thread.new{
command = "ssh #{ssh_options} #{host} \"bash -ls\" <<SCRIPT\n#{script}\nSCRIPT"
puts "SSHing to #{host}:\n" + `#{command}`
})
end
@threads.each{ |t| t.join }
return hosts
end
|
A wrangler will execute a shell script across a a list of hosts
|
execute_on_hosts
|
ruby
|
documentcloud/documentcloud
|
lib/dc/cloud_crowd.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/cloud_crowd.rb
|
MIT
|
def get_hosts_named(pattern=DEFAULT_WORKER_MATCHER)
ec2 = AWS::EC2.new
puts "Fetching worker host names"
instances = ec2.instances.select{ |i| i.status == :running && i.tags["Name"] =~ pattern }
return instances.map{ |i| i.dns_name }
end
|
this method should be abstracted or generalized to take a block, or both.
For DocumentCloud's purposes, we're running on Amazon & name extra nodes "workers"
so we fetch the list of machines using a regexp.
|
get_hosts_named
|
ruby
|
documentcloud/documentcloud
|
lib/dc/cloud_crowd.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/cloud_crowd.rb
|
MIT
|
def launch_nodes(options={})
DC::AWS.new.launch_instances(options) do |instances|
execute_on_hosts(script_contents("startup"), instances.map(&:dns_name))
end
end
|
Start new ec2 instance(s) and provision them as worker nodes.
Options:
:count - Number of nodes to start, defaults to 1
:node_name - What to name the nodes once they're booted, defaults to "worker"
|
launch_nodes
|
ruby
|
documentcloud/documentcloud
|
lib/dc/cloud_crowd.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/cloud_crowd.rb
|
MIT
|
def safe_unescape(s)
unless s.nil?
return CGI.unescape_html(s)
end
s
end
|
Unescape HTML in a safe fashion, allowing nil values to pass through
|
safe_unescape
|
ruby
|
documentcloud/documentcloud
|
lib/dc/sanitized.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/sanitized.rb
|
MIT
|
def text_attr(*attrs)
attrs.each do |att|
class_eval "def #{att}=(val); self[:#{att}] = safe_unescape(strip(val)); end"
end
end
|
Text attributes are stripped of HTML before they are saved.
|
text_attr
|
ruby
|
documentcloud/documentcloud
|
lib/dc/sanitized.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/sanitized.rb
|
MIT
|
def html_attr(*attrs)
options = attrs.extract_options!.reverse_merge({
:level => :super_relaxed
})
attrs.each do |att|
class_eval "def #{att}=(val); self[:#{att}] = sanitize(val, :#{options[:level]}); end"
end
end
|
HTML attributes are sanitized of malicious HTML before being saved.
Accepts a list of attribute names, with optional level specifiied at end.
If not specified, the level defaults to :super_relaxed
html_attr :sanitized_attr, :another_sanitized_attr, :level=>:basic
|
html_attr
|
ruby
|
documentcloud/documentcloud
|
lib/dc/sanitized.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/sanitized.rb
|
MIT
|
def initialize(file, attributes)
@file, @attributes = file, attributes
raise "Documents must have a file and title to be uploaded" unless @file && @attributes[:title]
end
|
Initialize the uploader with the document file, it's title, and the
optional access, source, and description...
|
initialize
|
ruby
|
documentcloud/documentcloud
|
lib/dc/uploader.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/uploader.rb
|
MIT
|
def initialize(resource, embed_config={}, options={})
raise NotImplementedError
end
|
Embed presenters accept
a hash representing a resource,
configuration which specifies how the embed markup/data will be generated
and a set of options specifying how the presenter will behave
|
initialize
|
ruby
|
documentcloud/documentcloud
|
lib/dc/embed/base.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/embed/base.rb
|
MIT
|
def define_attributes
@attributes = {}
@attribute_map = {}
yield # to the user defined block for further instruction
@keys = @attributes.keys.freeze
@attribute_map.freeze
@attributes.freeze
end
|
set up the hashes we'll use to
keep track of the whitelist of attributes
and their types
|
define_attributes
|
ruby
|
documentcloud/documentcloud
|
lib/dc/embed/base.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/embed/base.rb
|
MIT
|
def coerce(value, field_name)
type = self.class.attributes[field_name]
case type
when :boolean
case
when (value.kind_of? TrueClass or value.kind_of? FalseClass); then value
when value == "true"; then true
when (value || '').match(/no|false/); then false # For Overview
else; value
end
when :number
case
when value.kind_of?(Numeric); then value
when value =~ /\A[+-]?\d+\Z/; then value.to_i
when value =~ /\A[+-]?\d+\.\d+\Z/; then value.to_f
else; value
end
when :string
value.to_s unless value.nil?
else
raise ArgumentError, "#{type} isn't supported as a configuration key type."
end
end
|
coerce values according to the type of their field
|
coerce
|
ruby
|
documentcloud/documentcloud
|
lib/dc/embed/base.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/embed/base.rb
|
MIT
|
def initialize(data:{}, options:{map_keys: true})
@options = options
self.class.keys.each{ |attribute| self[attribute] = data[attribute] }
end
|
When initializing search the input arguments for fields which
this configuration class accepts
|
initialize
|
ruby
|
documentcloud/documentcloud
|
lib/dc/embed/base.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/embed/base.rb
|
MIT
|
def calculate_dimensions
embed_dimensions = @note.embed_dimensions
@dimensions = {
height: @embed_config[:maxheight] || (@embed_config[:maxwidth] ? (@embed_config[:maxwidth] / embed_dimensions[:aspect_ratio]).round : embed_dimensions[:height_pixel]),
width: @embed_config[:maxwidth] || (@embed_config[:maxheight] ? (@embed_config[:maxheight] * embed_dimensions[:aspect_ratio]).round : embed_dimensions[:width_pixel])
}
end
|
These won't be accurate, since this is the note image area only. Still,
gives the oEmbed response *some* sense of the scale and aspect ratio.
|
calculate_dimensions
|
ruby
|
documentcloud/documentcloud
|
lib/dc/embed/note.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/embed/note.rb
|
MIT
|
def code
[content_markup, bootstrap_markup].join("\n").squish
end
|
Page embed uses a noscript-style enhancer, which prefers content markup
before bootstrap markup
|
code
|
ruby
|
documentcloud/documentcloud
|
lib/dc/embed/page.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/embed/page.rb
|
MIT
|
def fetch_rdf(text)
rdfs = []
begin
rdfs = split_text(text).map do |chunk|
fetch_rdf_from_calais(chunk)
end
rescue Exception => e
LifecycleMailer.exception_notification(e).deliver_now
end
rdfs
end
|
Fetch the RDF from OpenCalais, splitting it into chunks small enough
for Calais to swallow. Run the chunks in parallel.
|
fetch_rdf
|
ruby
|
documentcloud/documentcloud
|
lib/dc/import/calais_fetcher.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/calais_fetcher.rb
|
MIT
|
def extract_dates( text )
@dates = {}
scan_for(DATE_MATCH, text)
reject_outliers
@dates.values
end
|
Extract the unique dates within the text.
|
extract_dates
|
ruby
|
documentcloud/documentcloud
|
lib/dc/import/date_extractor.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/date_extractor.rb
|
MIT
|
def scan_for(matcher, text)
scanner = TextScanner.new(text)
scanner.scan(matcher) do |match, offset, length|
next unless date = to_date(match)
@dates[date] ||= {:date => date, :occurrences => []}
@dates[date][:occurrences].push(Occurrence.new(offset, length))
end
end
|
Scans for the regex within the text, saving valid dates and occurrences.
|
scan_for
|
ruby
|
documentcloud/documentcloud
|
lib/dc/import/date_extractor.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/date_extractor.rb
|
MIT
|
def reject_outliers
dates = @dates.values.map {|d| d[:date] }
count = dates.length
return true if count < 10 # Not enough dates for detection.
nums = dates.map {|d| d.to_time.to_f.to_i }
mean = nums.inject {|a, b| a + b } / count.to_f
deviation = Math.sqrt(nums.inject(0){|sum, n| sum + (n - mean) ** 2 } / count.to_f)
allowed = ((mean - 3.0 * deviation)..(mean + 3.0 * deviation))
@dates.delete_if {|date, hash| !allowed.include?(date.to_time.to_f) }
end
|
Ignoring dates that are outside of three standard deviations ...
they're probably errors.
|
reject_outliers
|
ruby
|
documentcloud/documentcloud
|
lib/dc/import/date_extractor.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/date_extractor.rb
|
MIT
|
def to_date(string)
list = string.split(SPLITTER)
return nil unless valid_year?(list.first) || valid_year?(list.last)
if @american_format # US format dates need to have month and day swapped for Date.parse
string.sub!( AMERICAN_REGEX ){|m| "#$3-#$1-#$2"}
end
date = Date.parse(string.gsub(SEP_REGEX, '/'), true) rescue nil
date ||= Date.parse(string.gsub(SEP_REGEX, '-'), true) rescue nil
return nil if date && (date.year <= 0 || date.year >= 2100)
date
end
|
ActiveRecord's to_time only supports two-digit years up to 2038.
(because the UNIX epoch overflows 30 bits at that point, probably).
For now, let's ignore dates without centuries,
and dates that are too far into the past or future.
|
to_date
|
ruby
|
documentcloud/documentcloud
|
lib/dc/import/date_extractor.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/date_extractor.rb
|
MIT
|
def extract(document, text)
@entities = {}
if chunks = CalaisFetcher.new.fetch_rdf(text)
chunks.each_with_index do |chunk, i|
next unless chunk
extract_information(document, chunks.first) if document.calais_id.blank?
extract_entities(document, chunk, i)
end
document.entities = @entities.values
document.save
else
# push an entity extraction job onto the queue.
end
end
|
Public API: Pass in a document, either with full_text or rdf already
attached.
|
extract
|
ruby
|
documentcloud/documentcloud
|
lib/dc/import/entity_extractor.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/entity_extractor.rb
|
MIT
|
def extract_information(document, calais)
if calais and calais.raw and calais.raw.body and calais.raw.body.doc
info_elements = calais.raw.body.doc.info
document.title = info_elements.docTitle unless document.titled?
document.language ||= 'en' # TODO: Convert calais.language into an ISO language code.
document.publication_date ||= info_elements.docDate
document.calais_id = File.basename(info_elements.docId) # Match string of characters after the last forward slash to the end of the url to get calais id. example: http://d.opencalais.com/dochash-1/c4d2ae6a-5049-34eb-992c-67881899bccd
end
end
|
Pull out all of the standard, top-level entities, and add it to our
document if it hasn't already been set.
|
extract_information
|
ruby
|
documentcloud/documentcloud
|
lib/dc/import/entity_extractor.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/entity_extractor.rb
|
MIT
|
def extract_entities(document, calais, chunk_number)
offset = chunk_number * MAX_TEXT_SIZE
calais.entities.each do |entity|
kind = Entity.normalize_kind(entity[:type])
value = entity[:name]
next unless kind && value
value = Entity.normalize_value(value)
next if kind == :phone && Validators::PHONE !~ value
next if kind == :email && Validators::EMAIL !~ value
occurrences = entity[:matches].map do |instance|
Occurrence.new(instance[:offset] + offset, instance[:length])
end
model = Entity.new(
:value => value,
:kind => kind.to_s,
:relevance => entity[:score],
:document => document,
:occurrences => Occurrence.to_csv(occurrences),
:calais_id => File.basename(entity[:guid]) # Match string of characters after the last forward slash to the end of the url to get calais id. example: http://d.opencalais.com/comphash-1/7f9f8e5d-782c-357a-b6f3-7a5321f92e13
)
if previous = @entities[model.calais_id]
previous.merge(model)
else
@entities[model.calais_id] = model
end
end
end
|
Extract the entities that Calais discovers in the document, along with
the positions where they occur.
|
extract_entities
|
ruby
|
documentcloud/documentcloud
|
lib/dc/import/entity_extractor.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/entity_extractor.rb
|
MIT
|
def ensure_pdf(file, filename=nil)
Dir.mktmpdir do |temp_dir|
path = file.path
original_filename = filename || file.original_filename
ext = File.extname(original_filename).downcase
name = File.basename(original_filename, File.extname(original_filename)).gsub(/[^a-zA-Z0-9_\-.]/, '-').gsub(/-+/, '-') + ext
if ext == ".pdf" && File.extname(path) != ".pdf"
new_path = File.join(temp_dir, name)
FileUtils.mv(path, new_path)
path = new_path
end
return yield(path) if ext == ".pdf"
begin
doc = File.join(temp_dir, name)
FileUtils.cp(path, doc)
Docsplit.extract_pdf(doc, :output => temp_dir)
yield(File.join(temp_dir, File.basename(name, ext) + '.pdf'))
rescue Exception => e
LifecycleMailer.exception_notification(e).deliver_now
Rails.logger.error("PDF Conversion Failed: " + e.message + "\n" + e.backtrace.join("\n"))
yield path
end
end
end
|
Make sure we're dealing with a PDF. If not, it needs to be
converted first. Yields the path to the converted document to a block.
|
ensure_pdf
|
ruby
|
documentcloud/documentcloud
|
lib/dc/import/pdf_wrangler.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/pdf_wrangler.rb
|
MIT
|
def archive(pages, batch_size=nil)
batch_size ||= DEFAULT_BATCH_SIZE
batches = (pages.length / batch_size.to_f).ceil
batches.times do |batch_num|
tar_path = "#{sprintf('%05d', batch_num)}.tar"
batch_pages = pages[batch_num*batch_size...(batch_num + 1)*batch_size]
`tar -czf #{tar_path} #{batch_pages.join(' ')} 2>&1`
end
Dir["*.tar"]
end
|
Archive a list of PDF pages into TAR archives, grouped by batch_size.
|
archive
|
ruby
|
documentcloud/documentcloud
|
lib/dc/import/pdf_wrangler.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/pdf_wrangler.rb
|
MIT
|
def extract_phone_numbers(text)
@numbers = {}
scanner = TextScanner.new(text)
scanner.scan(PHONE_MATCHER) do |match, offset, length|
next unless number = to_phone_number(match)
@numbers[number] ||= {:number => number, :occurrences => []}
@numbers[number][:occurrences].push(Occurrence.new(offset, length))
end
@numbers.values
end
|
Extracts the unique phone numbers within the text.
|
extract_phone_numbers
|
ruby
|
documentcloud/documentcloud
|
lib/dc/import/phone_extractor.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/phone_extractor.rb
|
MIT
|
def to_phone_number(number)
string, area, trunk, rest, a, b, ext = *number.match(PHONE_MATCHER)
number = "(#{area}) #{trunk}-#{rest}"
number += " x#{ext}" unless ext.blank?
number
end
|
Converts the any-format number into the canonical (xxx) xxx-xxxx format.
|
to_phone_number
|
ruby
|
documentcloud/documentcloud
|
lib/dc/import/phone_extractor.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/phone_extractor.rb
|
MIT
|
def initialize(text)
@text = text
@scanner = StringScanner.new(@text)
end
|
Initialize the **TextScanner** with a string of text.
|
initialize
|
ruby
|
documentcloud/documentcloud
|
lib/dc/import/text_scanner.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/text_scanner.rb
|
MIT
|
def scan(regex)
while @scanner.scan_until(regex)
match = @scanner.matched
position = @scanner.charpos - match.length
yield match, position, match.length
end
end
|
Matches a given **regex** to all of its occurrences within the **text**,
yielding to the block with the matched text, the character offset
and character length of the match.
|
scan
|
ruby
|
documentcloud/documentcloud
|
lib/dc/import/text_scanner.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/text_scanner.rb
|
MIT
|
def parse(query_string='')
@text, @access = nil, nil
@fields, @accounts, @groups, @projects, @project_ids, @doc_ids, @attributes, @filters, @data =
[], [], [], [], [], [], [], [], []
fields = query_string.scan(Matchers::FIELD).map {|m| [m[0], m[3]] }
search_text = query_string.gsub(Matchers::FIELD, '').squeeze(' ').strip
@text = search_text.present? ? search_text : nil
process_fields_and_projects(fields)
Query.new(:text => @text, :fields => @fields, :projects => @projects,
:accounts => @accounts, :groups => @groups, :project_ids => @project_ids,
:doc_ids => @doc_ids, :attributes => @attributes, :access => @access,
:filters => @filters, :data => @data)
end
|
Parse a raw query_string, returning a DC::Search::Query that knows
about the text, fields, projects, and attributes it's composed of.
|
parse
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/parser.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/parser.rb
|
MIT
|
def process_fields_and_projects(fields)
fields.each do |pair|
type = pair.first.gsub(/(^['"]|['"]$)/, '')
value = pair.last.gsub(/(^['"]|['"]$)/, '')
case type.downcase
when 'account' then @accounts << value.to_i
when 'group' then @groups << value.downcase
when 'filter' then @filters << value.downcase.to_sym
when 'access' then @access = ACCESS_MAP[value.strip.to_sym]
when 'project' then @projects << value
when 'projectid' then @project_ids << value.to_i
when 'document' then @doc_ids << value.to_i
else
process_field(type, value)
end
end
end
|
Extract the portions of the query that are fields, attributes,
and projects.
|
process_fields_and_projects
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/parser.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/parser.rb
|
MIT
|
def process_field(kind, value)
field = Field.new(match_kind(kind), value.strip)
return @attributes << field if field.attribute?
return @fields << field if field.entity?
return @data << field
end
|
Convert an individual field or attribute search into a DC::Search::Field.
|
process_field
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/parser.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/parser.rb
|
MIT
|
def match_kind(kind)
DC::VALID_KINDS.detect {|s| s.match(Regexp.new(kind.downcase)) } || kind
end
|
Convert a field kind string into its canonical form, by searching
through all the valid kinds for a match.
|
match_kind
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/parser.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/parser.rb
|
MIT
|
def initialize(opts={})
@text = opts[:text]
@page = opts[:page].to_i
@page = 1 unless @page > 0
@access = opts[:access]
@fields = opts[:fields] || []
@accounts = opts[:accounts] || []
@groups = opts[:groups] || []
@projects = opts[:projects] || []
@project_ids = opts[:project_ids] || []
@doc_ids = opts[:doc_ids] || []
@attributes = opts[:attributes] || []
@filters = opts[:filters] || []
@data = opts[:data] || []
@from, @to, @total = nil, nil, nil
@account, @organization = nil, nil
@data_groups = @data.group_by {|datum| datum.kind }
@per_page = DEFAULT_PER_PAGE
@order = DEFAULT_ORDER
end
|
Queries are created by the Search::Parser, which sets them up with the
appropriate attributes.
|
initialize
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def generate_search
build_text if has_text?
build_fields if has_fields?
build_data if has_data?
build_accounts if has_accounts?
build_groups if has_groups?
build_project_ids if has_project_ids?
build_projects if has_projects?
build_doc_ids if has_doc_ids?
build_attributes if has_attributes?
build_filters if has_filters?
# build_facets if @include_facets
build_access unless @unrestricted
end
|
Generate all of the SQL, including conditions and joins, that is needed
to run the query.
|
generate_search
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def run(o={})
@account, @organization, @unrestricted = o[:account], o[:organization], o[:unrestricted]
@exclude_documents = o[:exclude_documents]
needs_solr? ? run_solr : run_database
populate_annotation_counts
populate_mentions o[:mentions].to_i if o[:mentions]
self
end
|
Runs (at most) two queries -- one to count the total number of results
that match the search, and one that retrieves the documents or notes
for the current page.
|
run
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def needs_solr?
@needs_solr ||= (has_text? || has_fields? || has_attributes?) ||
@data_groups.any? {|kind, list| list.length > 1 }
end
|
Does this query require the Solr index to run?
|
needs_solr?
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def populate_mentions(mentions)
raise "Invalid number of mentions" unless mentions > 0 && mentions <= 10
return false unless has_text? and has_results?
@results.each do |doc|
mention_data = Page.mentions(doc.id, @text, mentions)
doc.mentions = mention_data[:mentions]
doc.total_mentions = mention_data[:total]
end
end
|
If we've got a full text search with results, we can get Postgres to
generate the text mentions for our search results.
|
populate_mentions
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def populate_annotation_counts
return false unless has_results?
Document.populate_annotation_counts(@account, @results)
end
|
Stash the number of notes per-document on the document models.
|
populate_annotation_counts
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def as_json(opts={})
{ 'text' => @text,
'page' => @page,
'from' => @from,
'to' => @to,
'total' => @total,
'fields' => @fields,
'projects' => @projects,
'accounts' => @accounts,
'groups' => @groups,
'project_ids' => @project_ids,
'doc_ids' => @doc_ids,
'attributes' => @attributes,
'data' => @data.map {|f| [f.kind, f.value] }
}
end
|
# Return a hash of facets.
def facets
return {} unless @include_facets
@solr.facets.inject({}) do |hash, facet|
hash[facet.field_name] = facet.rows.map {|row| {:value => row.value, :count => row.count}}
hash
end
end
The JSON representation of a query contains all the structured aspects
of the search.
|
as_json
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def run_solr
@solr = Sunspot.new_search(Document)
generate_search
build_pagination
@solr.execute
@total = @solr.total
@results = @solr.results
end
|
Run the search, using the Solr index.
|
run_solr
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def build_pagination
page = @page
size = @per_page
order = @order.to_sym
direction = [:created_at, :score, :page_count, :hit_count].include?(order) ? :desc : :asc
pagination = {:page => page, :per_page => size}
pagination = EMPTY_PAGINATION if @exclude_documents
@solr.build do
order_by order, direction
order_by :created_at, :desc if order != :created_at
paginate pagination
data_accessor_for(Document).include = [:organization, :account]
end
end
|
Construct the correct pagination for the current query.
|
build_pagination
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def build_text
text = @text
@solr.build do
fulltext text
end
end
|
Build the Solr needed to run a full-text search. Hits the title,
the text content, the entities, etc.
|
build_text
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def build_fields
fields = @fields
@solr.build do
fields.each do |field|
fulltext field.value do
fields field.kind
end
end
end
end
|
Generate the Solr to search across the fielded metadata.
|
build_fields
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def build_projects
return unless @account
project_ids = Project.accessible(@account).where(:title => @projects).pluck(:id)
if project_ids.present?
@populated_projects = true
else
project_ids = [-1]
end
@project_ids = project_ids
build_project_ids
end
|
Lookup projects by title, and delegate to `build_project_ids`.
|
build_projects
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def build_project_ids
ids = @project_ids
if needs_solr?
@solr.build do
with :project_ids, ids
end
else
@sql << 'projects.id in (?)'
@interpolations << @project_ids
@joins << 'inner join project_memberships ON documents.id = project_memberships.document_id
inner join projects on project_memberships.project_id = projects.id'
end
end
|
Generate the Solr or SQL to restrict the search to specific projects.
|
build_project_ids
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def build_doc_ids
ids = @doc_ids
if needs_solr?
@solr.build do
with :id, ids
end
else
@sql << 'documents.id in (?)'
@interpolations << ids
end
end
|
Generate the Solr or SQL to restrict the search to specific documents.
|
build_doc_ids
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def build_accounts
ids = @accounts
if needs_solr?
@solr.build do
with :account_id, ids
end
else
@sql << 'documents.account_id in (?)'
@interpolations << ids
end
end
|
Generate the Solr or SQL to restrict the search to specific acounts.
|
build_accounts
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def build_groups
ids = Organization.where(:slug => @groups).pluck(:id)
if needs_solr?
@solr.build do
with :organization_id, ids
end
else
@sql << 'documents.organization_id in (?)'
@interpolations << ids
end
end
|
Generate the Solr or SQL to restrict the search to specific organizations.
|
build_groups
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def build_attributes
@attributes.each do |field|
@solr.build do
fulltext field.value do
fields field.kind
end
end
end
end
|
Generate the Solr to match document attributes.
|
build_attributes
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def build_data
data = @data
groups = @data_groups
if needs_solr?
@solr.build do
dynamic :data do
groups.each do |kind, data|
any_of do
data.each do |datum|
if datum.value == '*'
without datum.kind, nil
elsif datum.value == '!'
with datum.kind, nil
else
with datum.kind, datum.value
end
end
end
end
end
end
else
hash = {}
data.each do |datum|
if datum.value == '*'
@sql << 'defined(docdata.data, ?)'
@interpolations << datum.kind
elsif datum.value == '!'
@sql << '(docdata.data -> ?) is null'
@interpolations << datum.kind
else
@sql << '(docdata.data -> ?) LIKE ?'
@interpolations += [datum.kind, datum.value.gsub('*', '%')]
end
end
@joins << 'inner join docdata ON documents.id = docdata.document_id'
end
end
|
Generate the Solr or SQL to match user-data queries. If the value
is "*", assume that any document that contains the key will do.
|
build_data
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def build_filters
@filters.each do |filter|
case filter
when :annotated
if needs_solr?
# NB: Solr "greater_than" is actually >=
@solr.build { with(:public_note_count).greater_than(1) }
else
@sql << 'documents.public_note_count > 0'
end
when :popular
@order = :hit_count
if needs_solr?
@solr.build { with(:hit_count).greater_than(Document::MINIMUM_POPULAR) }
else
@sql << 'documents.hit_count > ?'
@interpolations << [Document::MINIMUM_POPULAR]
end
when :published
if needs_solr?
@solr.build { with :published, true }
else
@sql << 'documents.access in (?) and (documents.remote_url is not null or documents.detected_remote_url is not null)'
@interpolations << PUBLIC_LEVELS
end
when :unpublished
if needs_solr?
@solr.build { with :published, false }
else
@sql << 'documents.remote_url is null and documents.detected_remote_url is null'
end
when :restricted
if needs_solr?
@solr.build { with :access, [PRIVATE, ORGANIZATION, PENDING, INVISIBLE, ERROR, DELETED, EXCLUSIVE] }
else
@sql << 'documents.access in (?)'
@interpolations << [PRIVATE, ORGANIZATION, PENDING, INVISIBLE, ERROR, DELETED, EXCLUSIVE]
end
end
end
end
|
Add facet results to the Solr search, if requested.
def build_facets
api = @include_facets == :api
specific = @facet
@solr.build do
if specific
args = [specific.to_sym, FACET_OPTIONS[:specific]]
else
args = DC::ENTITY_KINDS + [FACET_OPTIONS[api ? :api : :all]]
end
facet(*args)
end
end
Filter documents along certain "interesting axes".
|
build_filters
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def build_access
@proxy = Document.accessible(@account, @organization) unless needs_solr?
if has_access?
access = @access
if needs_solr?
@solr.build do
with :access, access
end
else
@sql << 'documents.access = ?'
@interpolations << access
end
end
return unless needs_solr?
return if @populated_projects
account, organization = @account, @organization
accessible_project_ids = has_projects? || has_project_ids? ? [] : (account && account.accessible_project_ids)
@solr.build do
any_of do
with :access, PUBLIC_LEVELS
if account
all_of do
with :access, [PRIVATE, PENDING, ERROR, ORGANIZATION, EXCLUSIVE]
with :account_id, account.id
end
end
if organization && account && !account.freelancer?
all_of do
with :access, [ORGANIZATION, EXCLUSIVE]
with :organization_id, organization.id
end
end
if accessible_project_ids.present?
with :project_ids, accessible_project_ids
end
end
end
end
|
Restrict accessible documents for a given account/organzation.
Either the document itself is public, or it belongs to us, or it belongs to
our organization and we're allowed to see it, or if it belongs to a
project that's been shared with us, or it belongs to a project that
*hasn't* been shared with us, but is public.
|
build_access
|
ruby
|
documentcloud/documentcloud
|
lib/dc/search/query.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb
|
MIT
|
def set_access(document, access)
save_permissions(document.pdf_path, access)
save_permissions(document.full_text_path, access)
document.pages.each do |page|
save_permissions(document.page_text_path(page.page_number), access)
Page::IMAGE_SIZES.keys.each do |size|
save_permissions(document.page_image_path(page.page_number, size), access)
end
end
true
end
|
This is going to be *extremely* expensive. We can thread it, but
there must be a better way somehow. (running in the background for now)
|
set_access
|
ruby
|
documentcloud/documentcloud
|
lib/dc/store/aws_s3_store.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/store/aws_s3_store.rb
|
MIT
|
def copy_assets(source, destination, access)
[:copy_pdf, :copy_images, :copy_text].each do |task|
send(task, source, destination, access)
end
true
end
|
Duplicate all of the assets from one document over to another.
|
copy_assets
|
ruby
|
documentcloud/documentcloud
|
lib/dc/store/aws_s3_store.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/store/aws_s3_store.rb
|
MIT
|
def validate_assets(document)
invalid = []
1.upto(document.page_count) do |pg|
text_path = document.page_text_path(pg)
invalid << text_path unless bucket.objects[text_path].exists?
Page::IMAGE_SIZES.keys.each do |size|
image_path = document.page_image_path(pg, size)
invalid << image_path unless bucket.objects[image_path].exists?
end
end
invalid
end
|
This is a potentially expensive (as in $$) method since S3 charges by the request
returns an array of paths that should exist in the S3 bucket but do not
|
validate_assets
|
ruby
|
documentcloud/documentcloud
|
lib/dc/store/aws_s3_store.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/store/aws_s3_store.rb
|
MIT
|
def save_file(contents, s3_path, access, opts={})
destination = bucket.objects[s3_path]
options = opts.merge(:acl => ACCESS_TO_ACL[access], :content_type => content_type(s3_path))
destination.write(contents, options)
destination.public_url({ :secure => Thread.current[:ssl] }).to_s
end
|
Saves a local file to a location on S3, and returns the public URL.
Set the expires headers for a year, if the file is an image -- text,
HTML and JSON may change.
|
save_file
|
ruby
|
documentcloud/documentcloud
|
lib/dc/store/aws_s3_store.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/store/aws_s3_store.rb
|
MIT
|
def split_occurrences
@split_occurrences ||= Occurrence.from_csv(self.occurrences, self)
end
|
Instead of having a separate table for occurrences, we serialize them to
a CSV format on each Entity. Deserializes.
|
split_occurrences
|
ruby
|
documentcloud/documentcloud
|
lib/dc/store/entity_resource.rb
|
https://github.com/documentcloud/documentcloud/blob/master/lib/dc/store/entity_resource.rb
|
MIT
|
def zip_from_response( response )
Tempfile.open( 'testzip.zip', :encoding=>'binary' ) do | tf |
tf.write response.body
tf.flush
File.open( tf.path ) do | zip_file |
Zip::File.open( zip_file ) do | zf |
yield zf
end
end
end
end
|
RubyZip has a seemingly convenient Zip::ZipFile.open_buffer method - too bad it's totally borked
Various internal methods want the String passed in to have a path, monkey patching that in didn't work either
I would report a bug/pull request on it, but looks like they're in the middle of a pretty major re-write
Plus it doesn't like passing a Tempfile, since it's not a direct instance of IO (it uses DelegateClass)
|
zip_from_response
|
ruby
|
documentcloud/documentcloud
|
test/controllers/download_controller_test.rb
|
https://github.com/documentcloud/documentcloud/blob/master/test/controllers/download_controller_test.rb
|
MIT
|
def open(uri_s, options = {})
leftover = extract_global_options(options)
uri = string_to_uri(uri_s)
if (name = options[:application])
app = app_for_name(name)
end
app = app_for_uri(uri) if app.nil?
app.new.open(uri, leftover)
rescue Launchy::Error => e
raise e
rescue StandardError => e
msg = "Failure in opening uri #{uri_s.inspect} with options #{options.inspect}: #{e}"
raise Launchy::Error, msg
ensure
if $ERROR_INFO && block_given?
yield $ERROR_INFO
# explicitly return here to swallow the errors if there was an error
# and we yielded to the block
# rubocop:disable Lint/EnsureReturn
return
# rubocop:enable Lint/EnsureReturn
end
end
|
Launch an application for the given uri string
|
open
|
ruby
|
copiousfreetime/launchy
|
lib/launchy.rb
|
https://github.com/copiousfreetime/launchy/blob/master/lib/launchy.rb
|
ISC
|
def debug?
@debug || to_bool(ENV.fetch("LAUNCHY_DEBUG", nil))
end
|
we may do logging before a call to 'open', hence the need to check
LAUNCHY_DEBUG here
|
debug?
|
ruby
|
copiousfreetime/launchy
|
lib/launchy.rb
|
https://github.com/copiousfreetime/launchy/blob/master/lib/launchy.rb
|
ISC
|
def handling(uri)
klass = find_child(:handles?, uri)
return klass if klass
raise ApplicationNotFoundError, "No application found to handle '#{uri}'"
end
|
Find the application that handles the given uri.
returns the Class that can handle the uri
|
handling
|
ruby
|
copiousfreetime/launchy
|
lib/launchy/application.rb
|
https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/application.rb
|
ISC
|
def for_name(name)
klass = find_child(:has_name?, name)
return klass if klass
raise ApplicationNotFoundError, "No application found named '#{name}'"
end
|
Find the application with the given name
returns the Class that has the given name
|
for_name
|
ruby
|
copiousfreetime/launchy
|
lib/launchy/application.rb
|
https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/application.rb
|
ISC
|
def find_executable(bin, *paths)
paths = Launchy.path.split(File::PATH_SEPARATOR) if paths.empty?
paths.each do |path|
file = File.join(path, bin)
if File.executable?(file)
Launchy.log "#{name} : found executable #{file}"
return file
end
end
Launchy.log "#{name} : Unable to find `#{bin}' in #{paths.join(', ')}"
nil
end
|
Find the given executable in the available paths
returns the path to the executable or nil if not found
|
find_executable
|
ruby
|
copiousfreetime/launchy
|
lib/launchy/application.rb
|
https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/application.rb
|
ISC
|
def has_name?(qname)
qname.to_s.downcase == name.split("::").last.downcase
end
|
Does this class have the given name-like string?
returns true if the class has the given name
|
has_name?
|
ruby
|
copiousfreetime/launchy
|
lib/launchy/application.rb
|
https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/application.rb
|
ISC
|
def children
@children = [] unless defined? @children
@children
end
|
The list of children that are registered
|
children
|
ruby
|
copiousfreetime/launchy
|
lib/launchy/descendant_tracker.rb
|
https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/descendant_tracker.rb
|
ISC
|
def find_child(method, *args)
children.find do |child|
Launchy.log "Checking if class #{child} is the one for #{method}(#{args.join(', ')})}"
child.send(method, *args)
end
end
|
Find one of the child classes by calling the given method
and passing all the rest of the parameters to that method in
each child
|
find_child
|
ruby
|
copiousfreetime/launchy
|
lib/launchy/descendant_tracker.rb
|
https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/descendant_tracker.rb
|
ISC
|
def shell_commands(cmd, args)
cmdline = [cmd.to_s.shellsplit]
cmdline << args.flatten.collect(&:to_s)
commandline_normalize(cmdline)
end
|
cut it down to just the shell commands that will be passed to exec or
posix_spawn. The cmd argument is split according to shell rules and the
args are not escaped because the whole set is passed to system as *args
and in that case system shell escaping rules are not done.
|
shell_commands
|
ruby
|
copiousfreetime/launchy
|
lib/launchy/runner.rb
|
https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/runner.rb
|
ISC
|
def windows_app_list
['start \\"launchy\\" /b']
end
|
The escaped \\ is necessary so that when shellsplit is done later,
the "launchy", with quotes, goes through to the commandline, since that
|
windows_app_list
|
ruby
|
copiousfreetime/launchy
|
lib/launchy/applications/browser.rb
|
https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/applications/browser.rb
|
ISC
|
def browser_cmdline
browser_env.each do |p|
Launchy.log "#{self.class.name} : possibility from BROWSER environment variable : #{p}"
end
app_list.each do |p|
Launchy.log "#{self.class.name} : possibility from app_list : #{p}"
end
possibilities = (browser_env + app_list).flatten
if (browser = possibilities.shift)
Launchy.log "#{self.class.name} : Using browser value '#{browser}'"
return browser
end
raise Launchy::CommandNotFoundError,
"Unable to find a browser command. If this is unexpected, #{Launchy.bug_report_message}"
end
|
Get the full commandline of what we are going to add the uri to
|
browser_cmdline
|
ruby
|
copiousfreetime/launchy
|
lib/launchy/applications/browser.rb
|
https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/applications/browser.rb
|
ISC
|
def open(uri, options = {})
cmd, args = cmd_and_args(uri, options)
run(cmd, args)
end
|
final assembly of the command and do %s substitution
http://www.catb.org/~esr/BROWSER/index.html
|
open
|
ruby
|
copiousfreetime/launchy
|
lib/launchy/applications/browser.rb
|
https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/applications/browser.rb
|
ISC
|
def version
["lib/#{name}.rb", "lib/#{name}/version.rb"].each do |v|
path = project_path(v)
line = path.read[/^\s*VERSION\s*=\s*.*/]
return line.match(/.*VERSION\s*=\s*['"](.*)['"]/)[1] if line
end
end
|
Public: return the version of ThisProject
Search the ruby files in the project looking for the one that has the
version string in it. This does not eval any code in the project, it parses
the source code looking for the string.
Returns a String version
|
version
|
ruby
|
copiousfreetime/launchy
|
tasks/this.rb
|
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
|
ISC
|
def section_of(file, section_name)
re = /^[=#]+ (.*)$/
sectional = project_path(file)
parts = sectional.read.split(re)[1..]
parts.map!(&:strip)
sections = {}
Hash[*parts].each do |k, v|
sections[k] = v.split("\n\n")
end
sections[section_name]
end
|
Internal: Return a section of an RDoc file with the given section name
path - the relative path in the project of the file to parse
section_name - the section out of the file from which to parse data
Retuns the text of the section as an array of paragrphs.
|
section_of
|
ruby
|
copiousfreetime/launchy
|
tasks/this.rb
|
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
|
ISC
|
def task_warning(task)
warn "WARNING: '#{task}' tasks are not defined. Please run 'bin/setup'"
end
|
Internal: print out a warning about the give task
|
task_warning
|
ruby
|
copiousfreetime/launchy
|
tasks/this.rb
|
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
|
ISC
|
def project_root
this_file_path.ascend do |p|
rakefile = p.join("Rakefile")
return p if rakefile.exist?
end
end
|
Internal: The root directory of this project
This is defined as being the directory that is in the path of this project
that has the first Rakefile
Returns the Pathname of the directory
|
project_root
|
ruby
|
copiousfreetime/launchy
|
tasks/this.rb
|
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
|
ISC
|
def manifest
manifest_file = project_path("Manifest.txt")
abort "You need a Manifest.txt" unless manifest_file.readable?
manifest_file.readlines.map(&:strip)
end
|
Internal: Returns the contents of the Manifest.txt file as an array
Returns an Array of strings
|
manifest
|
ruby
|
copiousfreetime/launchy
|
tasks/this.rb
|
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
|
ISC
|
def platform_gemspec
gemspecs.fetch(platform) { This.ruby_gemspec }
end
|
Internal: Returns the gemspace associated with the current ruby platform
|
platform_gemspec
|
ruby
|
copiousfreetime/launchy
|
tasks/this.rb
|
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
|
ISC
|
def ruby_gemspec(core = core_gemspec, &)
yielding_gemspec("ruby", core, &)
end
|
Internal: Return the gemspec for the ruby platform
|
ruby_gemspec
|
ruby
|
copiousfreetime/launchy
|
tasks/this.rb
|
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
|
ISC
|
def java_gemspec(core = core_gemspec, &)
yielding_gemspec("java", core, &)
end
|
Internal: Return the gemspec for the jruby platform
|
java_gemspec
|
ruby
|
copiousfreetime/launchy
|
tasks/this.rb
|
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
|
ISC
|
def yielding_gemspec(key, core)
spec = gemspecs[key] ||= core.dup
spec.platform = key
yield spec if block_given?
spec
end
|
Internal: give an initial spec and a key, create a new gemspec based off of
it.
This will force the new gemspecs 'platform' to be that of the key, since the
only reason you would have multiple gemspecs at this point is to deal with
different platforms.
|
yielding_gemspec
|
ruby
|
copiousfreetime/launchy
|
tasks/this.rb
|
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
|
ISC
|
def platform
(RUBY_PLATFORM == "java") ? "java" : Gem::Platform::RUBY
end
|
Internal: Return the platform of ThisProject at the current moment in time.
|
platform
|
ruby
|
copiousfreetime/launchy
|
tasks/this.rb
|
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
|
ISC
|
def description_section
section_of("README.md", "DESCRIPTION")
end
|
Internal: Return the DESCRIPTION section of the README.rdoc file
|
description_section
|
ruby
|
copiousfreetime/launchy
|
tasks/this.rb
|
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
|
ISC
|
def description
description_section.join(" ").tr("\n", " ").gsub(/[{}]/, "").gsub(/\[[^\]]+\]/, "") # strip rdoc
end
|
Internal: Return the full description text from the README
|
description
|
ruby
|
copiousfreetime/launchy
|
tasks/this.rb
|
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
|
ISC
|
def configure
yield(configuration); nil
end
|
#
This method is used to configure HireFire
@yield [config] the instance of HireFire::Configuration class
@yieldparam [Fixnum] max_workers default: 1 (set at least 1)
@yieldparam [Array] job_worker_ratio default: see example
@yieldparam [Symbol, nil] environment (:heroku, :local, :noop or nil) - default: nil
@note Every param has it's own defaults. It's best to leave the environment param at "nil".
When environment is set to "nil", it'll default to the :noop environment. This basically means
that you have to run "rake jobs:work" yourself from the console to get the jobs running in development mode.
In production, it'll automatically use :heroku if deployed to the Heroku platform.
@example
HireFire.configure do |config|
config.environment = nil
config.max_workers = 5
config.min_workers = 0
config.job_worker_ratio = [
{ :jobs => 1, :workers => 1 },
{ :jobs => 15, :workers => 2 },
{ :jobs => 35, :workers => 3 },
{ :jobs => 60, :workers => 4 },
{ :jobs => 80, :workers => 5 }
]
end
@return [nil]
|
configure
|
ruby
|
hirefire/hirefire
|
lib/hirefire.rb
|
https://github.com/hirefire/hirefire/blob/master/lib/hirefire.rb
|
MIT
|
def configuration
@configuration ||= HireFire::Configuration.new
end
|
#
Instantiates a new HireFire::Configuration
instance and instance variable caches it
|
configuration
|
ruby
|
hirefire/hirefire
|
lib/hirefire.rb
|
https://github.com/hirefire/hirefire/blob/master/lib/hirefire.rb
|
MIT
|
def initialize
@max_workers = 1
@min_workers = 0
@job_worker_ratio = [
{ :jobs => 1, :workers => 1 },
{ :jobs => 25, :workers => 2 },
{ :jobs => 50, :workers => 3 },
{ :jobs => 75, :workers => 4 },
{ :jobs => 100, :workers => 5 }
]
end
|
#
Instantiates a new HireFire::Configuration object
with the default configuration. These default configurations
may be overwritten using the HireFire.configure class method
@return [HireFire::Configuration]
|
initialize
|
ruby
|
hirefire/hirefire
|
lib/hirefire/configuration.rb
|
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/configuration.rb
|
MIT
|
def environment
@environment ||= HireFire::Environment.const_get(
if environment = HireFire.configuration.environment
environment.to_s.camelize
else
ENV.include?('HEROKU_UPID') ? 'Heroku' : 'Noop'
end
).new
end
|
#
Returns the environment class method (containing an instance of the proper environment class)
for either Delayed::Job or Resque::Job
If HireFire.configuration.environment is nil (the default) then it'll
auto-detect which environment to run in (either Heroku or Noop)
If HireFire.configuration.environment isn't nil (explicitly set) then
it'll run in the specified environment (Heroku, Local or Noop)
@return [HireFire::Environment::Heroku, HireFire::Environment::Local, HireFire::Environment::Noop]
|
environment
|
ruby
|
hirefire/hirefire
|
lib/hirefire/environment.rb
|
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/environment.rb
|
MIT
|
def hirefire_hire
delayed_job = ::Delayed::Job.new
if delayed_job.working == 0 \
or delayed_job.jobs == 1
environment.hire
end
end
|
#
This method is an attempt to improve web-request throughput.
A class method for Delayed::Job which first checks if any worker is currently
running by checking to see if there are any jobs locked by a worker. If there aren't
any jobs locked by a worker there is a high chance that there aren't any workers running.
If this is the case, then we sure also invoke the 'self.class.environment.hire' method
Another check is to see if there is only 1 job (which is the one that
was just added before this callback invoked). If this is the case
then it's very likely there aren't any workers running and we should
invoke the 'self.class.environment.hire' method to make sure this is the case.
@return [nil]
|
hirefire_hire
|
ruby
|
hirefire/hirefire
|
lib/hirefire/environment.rb
|
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/environment.rb
|
MIT
|
def jobs
::Delayed::Job.
where(:failed_at => nil).
where('run_at <= ?', Time.now).count
end
|
#
Counts the amount of queued jobs in the database,
failed jobs are excluded from the sum
@return [Fixnum] the amount of pending jobs
|
jobs
|
ruby
|
hirefire/hirefire
|
lib/hirefire/backend/delayed_job/active_record.rb
|
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/backend/delayed_job/active_record.rb
|
MIT
|
def working
::Delayed::Job.
where('locked_by IS NOT NULL').count
end
|
#
Counts the amount of jobs that are locked by a worker
There is no other performant way to determine the amount
of workers there currently are
@return [Fixnum] the amount of (assumably working) workers
|
working
|
ruby
|
hirefire/hirefire
|
lib/hirefire/backend/delayed_job/active_record.rb
|
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/backend/delayed_job/active_record.rb
|
MIT
|
def jobs
::Delayed::Job.where(
:failed_at => nil,
:run_at.lte => Time.now
).count
end
|
#
Counts the amount of queued jobs in the database,
failed jobs and jobs scheduled for the future are excluded
@return [Fixnum]
|
jobs
|
ruby
|
hirefire/hirefire
|
lib/hirefire/backend/delayed_job/mongoid.rb
|
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/backend/delayed_job/mongoid.rb
|
MIT
|
def hire
jobs_count = jobs
workers_count = workers || return
##
# Use "Standard Notation"
if not ratio.first[:when].respond_to? :call
##
# Since the "Standard Notation" is defined in the in an ascending order
# in the array of hashes, we need to reverse this order in order to properly
# loop through and break out of the array at the correctly matched ratio
ratio.reverse!
##
# Iterates through all the defined job/worker ratio's
# until it finds a match. Then it hires (if necessary) the appropriate
# amount of workers and breaks out of the loop
ratio.each do |ratio|
##
# Standard notation
# This is the code for the default notation
#
# @example
# { :jobs => 35, :workers => 3 }
#
if jobs_count >= ratio[:jobs] and max_workers >= ratio[:workers]
if workers_count < ratio[:workers]
log_and_hire(ratio[:workers])
end
return
end
end
##
# If no match is found in the above job/worker ratio loop, then we'll
# perform one last operation to see whether the the job count is greater
# than the highest job/worker ratio, and if this is the case then we also
# check to see whether the maximum amount of allowed workers is greater
# than the amount that are currently running, if this is the case, we are
# allowed to hire the max amount of workers.
if jobs_count >= ratio.first[:jobs] and max_workers > workers_count
log_and_hire(max_workers)
return
end
end
##
# Use "Functional (Lambda) Notation"
if ratio.first[:when].respond_to? :call
##
# Iterates through all the defined job/worker ratio's
# until it finds a match. Then it hires (if necessary) the appropriate
# amount of workers and breaks out of the loop
ratio.each do |ratio|
##
# Functional (Lambda) Notation
# This is the code for the Lambda notation, more verbose,
# but more humanly understandable
#
# @example
# { :when => lambda {|jobs| jobs < 60 }, :workers => 3 }
#
if ratio[:when].call(jobs_count) and max_workers >= ratio[:workers]
if workers_count < ratio[:workers]
log_and_hire(ratio[:workers])
end
break
end
end
end
##
# Applies only to the Functional (Lambda) Notation
# If the amount of queued jobs exceeds that of which was defined in the
# job/worker ratio array, it will hire the maximum amount of workers
#
# "if statements":
# 1. true if we use the Functional (Lambda) Notation
# 2. true if the last ratio (highest job/worker ratio) was exceeded
# 3. true if the max amount of workers are not yet running
#
# If all the the above statements are true, HireFire will hire the maximum
# amount of workers that were specified in the configuration
#
if ratio.last[:when].respond_to? :call \
and ratio.last[:when].call(jobs_count) === false \
and max_workers != workers_count
log_and_hire(max_workers)
end
end
|
#
This method gets invoked when a new job has been queued
Iterates through the default (or user-defined) job/worker ratio until
it finds a match for the for the current situation (see example).
@example
# Say we have 40 queued jobs, and we configured our job/worker ratio like so:
HireFire.configure do |config|
config.max_workers = 5
config.min_workers = 0
config.job_worker_ratio = [
{ :jobs => 1, :workers => 1 },
{ :jobs => 15, :workers => 2 },
{ :jobs => 35, :workers => 3 },
{ :jobs => 60, :workers => 4 },
{ :jobs => 80, :workers => 5 }
]
end
# It'll match at { :jobs => 35, :workers => 3 }, (35 jobs or more: hire 3 workers)
# meaning that it'll ensure there are 3 workers running.
# If there were already were 3 workers, it'll leave it as is.
# Alternatively, you can use a more functional syntax, which works in the same way.
HireFire.configure do |config|
config.max_workers = 5
config.job_worker_ratio = [
{ :when => lambda {|jobs| jobs < 15 }, :workers => 1 },
{ :when => lambda {|jobs| jobs < 35 }, :workers => 2 },
{ :when => lambda {|jobs| jobs < 60 }, :workers => 3 },
{ :when => lambda {|jobs| jobs < 80 }, :workers => 4 }
]
end
# If there were more than 3 workers running (say, 4 or 5), it will NOT reduce
# the number. This is because when you reduce the number of workers, you cannot
# tell which worker Heroku will shut down, meaning you might interrupt a worker
# that's currently working, causing the job to fail. Also, consider the fact that
# there are, for example, 35 jobs still to be picked up, so the more workers,
# the faster it processes. You aren't even paying more because it doesn't matter whether
# you have 1 worker, or 5 workers processing jobs, because workers are pro-rated to the second.
# So basically 5 workers would cost 5 times more, but will also process 5 times faster.
# Once all jobs finished processing (e.g. Delayed::Job.jobs == 0), HireFire will invoke a signal
# which will set the workers back to 0 and shuts down all the workers simultaneously.
@return [nil]
|
hire
|
ruby
|
hirefire/hirefire
|
lib/hirefire/environment/base.rb
|
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/environment/base.rb
|
MIT
|
def fire
if jobs == 0 and workers > min_workers
Logger.message("All queued jobs have been processed. " + (min_workers > 0 ? "Setting workers to #{min_workers}." : "Firing all workers."))
workers(min_workers)
return true
end
return false
end
|
#
This method gets invoked when a job is either "destroyed"
or "updated, unless the job didn't fail"
If there are workers active, but there are no more pending jobs,
then fire all the workers or set to the minimum_workers
@return [Boolean] if the workers have been fired
|
fire
|
ruby
|
hirefire/hirefire
|
lib/hirefire/environment/base.rb
|
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/environment/base.rb
|
MIT
|
def log_and_hire(amount)
Logger.message("Hiring more workers so we have #{ amount } in total.")
workers(amount)
end
|
#
Helper method for hire that logs the hiring of more workers, then hires those workers.
@return [nil]
|
log_and_hire
|
ruby
|
hirefire/hirefire
|
lib/hirefire/environment/base.rb
|
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/environment/base.rb
|
MIT
|
def workers(amount = nil)
#
# Returns the amount of Delayed Job
# workers that are currently running on Heroku
if amount.nil?
return client.info(ENV['APP_NAME'])[:workers].to_i
end
##
# Sets the amount of Delayed Job
# workers that need to be running on Heroku
client.set_workers(ENV['APP_NAME'], amount)
rescue RestClient::Exception
# Heroku library uses rest-client, currently, and it is quite
# possible to receive RestClient exceptions through the client.
HireFire::Logger.message("Worker query request failed with #{ $!.class.name } #{ $!.message }")
nil
end
|
#
Either retrieves the amount of currently running workers,
or set the amount of workers to a specific amount by providing a value
@overload workers(amount = nil)
@param [Fixnum] amount will tell heroku to run N workers
@return [nil]
@overload workers(amount = nil)
@param [nil] amount
@return [Fixnum] will request the amount of currently running workers from Heroku
|
workers
|
ruby
|
hirefire/hirefire
|
lib/hirefire/environment/heroku.rb
|
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/environment/heroku.rb
|
MIT
|
def client
@client ||= ::Heroku::Client.new(
ENV['HIREFIRE_EMAIL'], ENV['HIREFIRE_PASSWORD']
)
end
|
#
@return [Heroku::Client] instance of the heroku client
|
client
|
ruby
|
hirefire/hirefire
|
lib/hirefire/environment/heroku.rb
|
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/environment/heroku.rb
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.