repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
nccgroup/BinProxy | lib/binproxy/parsers/zmq.rb | ZMQ.Message.update_state | def update_state
current_state.dup.tap do |s|
src = eval_parameter :src
s[src] = next_state s[src]
end
end | ruby | def update_state
current_state.dup.tap do |s|
src = eval_parameter :src
s[src] = next_state s[src]
end
end | [
"def",
"update_state",
"current_state",
".",
"dup",
".",
"tap",
"do",
"|",
"s",
"|",
"src",
"=",
"eval_parameter",
":src",
"s",
"[",
"src",
"]",
"=",
"next_state",
"s",
"[",
"src",
"]",
"end",
"end"
] | Protocol is symmetrical. Each endpoint has its own state.
This is a bit clunky and maybe should be abstracted into a module?
Or update parser.rb to differentiate between proto-shared and endpoint-separate state? | [
"Protocol",
"is",
"symmetrical",
".",
"Each",
"endpoint",
"has",
"its",
"own",
"state",
".",
"This",
"is",
"a",
"bit",
"clunky",
"and",
"maybe",
"should",
"be",
"abstracted",
"into",
"a",
"module?",
"Or",
"update",
"parser",
".",
"rb",
"to",
"differentiate",
"between",
"proto",
"-",
"shared",
"and",
"endpoint",
"-",
"separate",
"state?"
] | d02fce91a1bd5aa0bd4b99a6f60f65ddc9d33c27 | https://github.com/nccgroup/BinProxy/blob/d02fce91a1bd5aa0bd4b99a6f60f65ddc9d33c27/lib/binproxy/parsers/zmq.rb#L47-L52 | train |
couchbase/couchbase-ruby-client | lib/couchbase/cluster.rb | Couchbase.Cluster.create_bucket | def create_bucket(name, options = {})
defaults = {
:type => "couchbase",
:ram_quota => 100,
:replica_number => 1,
:auth_type => "sasl",
:sasl_password => "",
:proxy_port => nil,
:flush_enabled => false,
:replica_index => true,
:parallel_db_and_view_compaction => false
}
options = defaults.merge(options)
params = {"name" => name}
params["bucketType"] = options[:type]
params["ramQuotaMB"] = options[:ram_quota]
params["replicaNumber"] = options[:replica_number]
params["authType"] = options[:auth_type]
params["saslPassword"] = options[:sasl_password]
params["proxyPort"] = options[:proxy_port]
params["flushEnabled"] = options[:flush_enabled] ? 1 : 0
params["replicaIndex"] = options[:replica_index] ? 1 : 0
params["parallelDBAndViewCompaction"] = !!options[:parallel_db_and_view_compaction]
payload = Utils.encode_params(params.reject! { |_k, v| v.nil? })
response = @connection.send(:__http_query, :management, :post,
"/pools/default/buckets", payload,
"application/x-www-form-urlencoded", nil, nil, nil)
Result.new(response.merge(:operation => :create_bucket))
end | ruby | def create_bucket(name, options = {})
defaults = {
:type => "couchbase",
:ram_quota => 100,
:replica_number => 1,
:auth_type => "sasl",
:sasl_password => "",
:proxy_port => nil,
:flush_enabled => false,
:replica_index => true,
:parallel_db_and_view_compaction => false
}
options = defaults.merge(options)
params = {"name" => name}
params["bucketType"] = options[:type]
params["ramQuotaMB"] = options[:ram_quota]
params["replicaNumber"] = options[:replica_number]
params["authType"] = options[:auth_type]
params["saslPassword"] = options[:sasl_password]
params["proxyPort"] = options[:proxy_port]
params["flushEnabled"] = options[:flush_enabled] ? 1 : 0
params["replicaIndex"] = options[:replica_index] ? 1 : 0
params["parallelDBAndViewCompaction"] = !!options[:parallel_db_and_view_compaction]
payload = Utils.encode_params(params.reject! { |_k, v| v.nil? })
response = @connection.send(:__http_query, :management, :post,
"/pools/default/buckets", payload,
"application/x-www-form-urlencoded", nil, nil, nil)
Result.new(response.merge(:operation => :create_bucket))
end | [
"def",
"create_bucket",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"defaults",
"=",
"{",
":type",
"=>",
"\"couchbase\"",
",",
":ram_quota",
"=>",
"100",
",",
":replica_number",
"=>",
"1",
",",
":auth_type",
"=>",
"\"sasl\"",
",",
":sasl_password",
"=>",
"\"\"",
",",
":proxy_port",
"=>",
"nil",
",",
":flush_enabled",
"=>",
"false",
",",
":replica_index",
"=>",
"true",
",",
":parallel_db_and_view_compaction",
"=>",
"false",
"}",
"options",
"=",
"defaults",
".",
"merge",
"(",
"options",
")",
"params",
"=",
"{",
"\"name\"",
"=>",
"name",
"}",
"params",
"[",
"\"bucketType\"",
"]",
"=",
"options",
"[",
":type",
"]",
"params",
"[",
"\"ramQuotaMB\"",
"]",
"=",
"options",
"[",
":ram_quota",
"]",
"params",
"[",
"\"replicaNumber\"",
"]",
"=",
"options",
"[",
":replica_number",
"]",
"params",
"[",
"\"authType\"",
"]",
"=",
"options",
"[",
":auth_type",
"]",
"params",
"[",
"\"saslPassword\"",
"]",
"=",
"options",
"[",
":sasl_password",
"]",
"params",
"[",
"\"proxyPort\"",
"]",
"=",
"options",
"[",
":proxy_port",
"]",
"params",
"[",
"\"flushEnabled\"",
"]",
"=",
"options",
"[",
":flush_enabled",
"]",
"?",
"1",
":",
"0",
"params",
"[",
"\"replicaIndex\"",
"]",
"=",
"options",
"[",
":replica_index",
"]",
"?",
"1",
":",
"0",
"params",
"[",
"\"parallelDBAndViewCompaction\"",
"]",
"=",
"!",
"!",
"options",
"[",
":parallel_db_and_view_compaction",
"]",
"payload",
"=",
"Utils",
".",
"encode_params",
"(",
"params",
".",
"reject!",
"{",
"|",
"_k",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
")",
"response",
"=",
"@connection",
".",
"send",
"(",
":__http_query",
",",
":management",
",",
":post",
",",
"\"/pools/default/buckets\"",
",",
"payload",
",",
"\"application/x-www-form-urlencoded\"",
",",
"nil",
",",
"nil",
",",
"nil",
")",
"Result",
".",
"new",
"(",
"response",
".",
"merge",
"(",
":operation",
"=>",
":create_bucket",
")",
")",
"end"
] | Establish connection to the cluster for administration
@param [String] connstr ("couchbasae://localhost") connection string
@param [Hash] options The connection parameter
@option options [String] :username The username
@option options [String] :password The password
Create data bucket
@param [String] name The name of the bucket
@param [Hash] options The bucket parameters
@option options [String] :bucket_type ("couchbase") The type of the
bucket. Possible values are "memcached" and "couchbase".
@option options [Fixnum] :ram_quota (100) The RAM quota in megabytes.
@option options [Fixnum] :replica_number (1) The number of replicas of
each document. Minimum 0, maximum 3.
@option options [String] :auth_type ("sasl") The authentication type.
Possible values are "sasl" and "none". Note you should specify free
port for "none"
@option options [Fixnum] :proxy_port The port for moxi
@option options [true, false] :replica_index (true) Disable or
enable indexes for bucket replicas
@option options [true, false] :flush_enabled (false) Enables the
'flush all' functionality on the specified bucket.
@option options [true, false] :parallel_db_and_view_compaction (false)
Indicates whether database and view files on disk can be
compacted simultaneously | [
"Establish",
"connection",
"to",
"the",
"cluster",
"for",
"administration"
] | ecce41a5996d9a97d6182e120bd9b5296707b353 | https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/cluster.rb#L54-L82 | train |
couchbase/couchbase-ruby-client | lib/couchbase/dns.rb | Couchbase.DNS.locate | def locate(name, bootstrap_protocol = :http)
service = case bootstrap_protocol
when :http
"_cbhttp"
when :cccp
"_cbmcd"
else
raise ArgumentError, "unknown bootstrap protocol: #{bootstrap_transports}"
end
hosts = []
Resolv::DNS.open do |dns|
resources = dns.getresources("#{service}._tcp.#{name}", Resolv::DNS::Resource::IN::SRV)
hosts = resources.sort_by(&:priority).map { |res| "#{res.target}:#{res.port}" }
end
hosts
end | ruby | def locate(name, bootstrap_protocol = :http)
service = case bootstrap_protocol
when :http
"_cbhttp"
when :cccp
"_cbmcd"
else
raise ArgumentError, "unknown bootstrap protocol: #{bootstrap_transports}"
end
hosts = []
Resolv::DNS.open do |dns|
resources = dns.getresources("#{service}._tcp.#{name}", Resolv::DNS::Resource::IN::SRV)
hosts = resources.sort_by(&:priority).map { |res| "#{res.target}:#{res.port}" }
end
hosts
end | [
"def",
"locate",
"(",
"name",
",",
"bootstrap_protocol",
"=",
":http",
")",
"service",
"=",
"case",
"bootstrap_protocol",
"when",
":http",
"\"_cbhttp\"",
"when",
":cccp",
"\"_cbmcd\"",
"else",
"raise",
"ArgumentError",
",",
"\"unknown bootstrap protocol: #{bootstrap_transports}\"",
"end",
"hosts",
"=",
"[",
"]",
"Resolv",
"::",
"DNS",
".",
"open",
"do",
"|",
"dns",
"|",
"resources",
"=",
"dns",
".",
"getresources",
"(",
"\"#{service}._tcp.#{name}\"",
",",
"Resolv",
"::",
"DNS",
"::",
"Resource",
"::",
"IN",
"::",
"SRV",
")",
"hosts",
"=",
"resources",
".",
"sort_by",
"(",
":priority",
")",
".",
"map",
"{",
"|",
"res",
"|",
"\"#{res.target}:#{res.port}\"",
"}",
"end",
"hosts",
"end"
] | Locate bootstrap nodes from a DNS SRV record.
@note This is experimental interface. It might change in future
(e.g. service identifiers)
The DNS SRV records need to be configured on a reachable DNS server. An
example configuration could look like the following:
_cbmcd._tcp.example.com. 0 IN SRV 20 0 11210 node2.example.com.
_cbmcd._tcp.example.com. 0 IN SRV 10 0 11210 node1.example.com.
_cbmcd._tcp.example.com. 0 IN SRV 30 0 11210 node3.example.com.
_cbhttp._tcp.example.com. 0 IN SRV 20 0 8091 node2.example.com.
_cbhttp._tcp.example.com. 0 IN SRV 10 0 8091 node1.example.com.
_cbhttp._tcp.example.com. 0 IN SRV 30 0 8091 node3.example.com.
Now if "example.com" is passed in as the argument, the three
nodes configured will be parsed and put in the returned URI list. Note that
the priority is respected (in this example, node1 will be the first one
in the list, followed by node2 and node3). As of now, weighting is not
supported.
@param name the DNS name where SRV records configured
@param bootstrap_protocol (Symbol) the desired protocol for
bootstrapping. See +bootstrap_protocols+ option to
{Couchbase::Bucket#new}. Allowed values +:http, :cccp+
@return a list of ordered boostrap URIs by their weight.
@example Initialize connection using DNS SRV records
nodes = Couchbase::DNS.locate('example.com', :http)
if nodes.empty?
nodes = ["example.com:8091"]
end
Couchbase.connect(:node_list => nodes) | [
"Locate",
"bootstrap",
"nodes",
"from",
"a",
"DNS",
"SRV",
"record",
"."
] | ecce41a5996d9a97d6182e120bd9b5296707b353 | https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/dns.rb#L57-L72 | train |
couchbase/couchbase-ruby-client | lib/couchbase/view.rb | Couchbase.View.fetch | def fetch(params = {})
params = @params.merge(params)
options = {}
options[:include_docs] = params.delete(:include_docs) if params.key?(:include_docs)
options[:format] = params.delete(:format) if params.key?(:format)
options[:transcoder] = params.delete(:transcoder) if params.key?(:transcoder)
options[:spatial] = params.delete(:spatial) if params.key?(:spatial)
body = params.delete(:body) || {}
body = MultiJson.dump(body) unless body.is_a?(String)
res = @bucket.send(:__view_query, @ddoc, @view, Utils.encode_params(params), body, options)
raise res[:error] if res[:error]
meta = MultiJson.load(res[:meta])
send_error(meta[S_ERRORS][S_FROM], meta[S_ERRORS][S_REASON]) if meta[S_ERRORS]
if block_given?
res[:rows].each do |row|
yield @wrapper_class.wrap(row)
end
else
rows = res[:rows].map { |row| @wrapper_class.wrap(row) }
ArrayWithTotalRows.new(rows, meta[S_TOTAL_ROWS])
end
end | ruby | def fetch(params = {})
params = @params.merge(params)
options = {}
options[:include_docs] = params.delete(:include_docs) if params.key?(:include_docs)
options[:format] = params.delete(:format) if params.key?(:format)
options[:transcoder] = params.delete(:transcoder) if params.key?(:transcoder)
options[:spatial] = params.delete(:spatial) if params.key?(:spatial)
body = params.delete(:body) || {}
body = MultiJson.dump(body) unless body.is_a?(String)
res = @bucket.send(:__view_query, @ddoc, @view, Utils.encode_params(params), body, options)
raise res[:error] if res[:error]
meta = MultiJson.load(res[:meta])
send_error(meta[S_ERRORS][S_FROM], meta[S_ERRORS][S_REASON]) if meta[S_ERRORS]
if block_given?
res[:rows].each do |row|
yield @wrapper_class.wrap(row)
end
else
rows = res[:rows].map { |row| @wrapper_class.wrap(row) }
ArrayWithTotalRows.new(rows, meta[S_TOTAL_ROWS])
end
end | [
"def",
"fetch",
"(",
"params",
"=",
"{",
"}",
")",
"params",
"=",
"@params",
".",
"merge",
"(",
"params",
")",
"options",
"=",
"{",
"}",
"options",
"[",
":include_docs",
"]",
"=",
"params",
".",
"delete",
"(",
":include_docs",
")",
"if",
"params",
".",
"key?",
"(",
":include_docs",
")",
"options",
"[",
":format",
"]",
"=",
"params",
".",
"delete",
"(",
":format",
")",
"if",
"params",
".",
"key?",
"(",
":format",
")",
"options",
"[",
":transcoder",
"]",
"=",
"params",
".",
"delete",
"(",
":transcoder",
")",
"if",
"params",
".",
"key?",
"(",
":transcoder",
")",
"options",
"[",
":spatial",
"]",
"=",
"params",
".",
"delete",
"(",
":spatial",
")",
"if",
"params",
".",
"key?",
"(",
":spatial",
")",
"body",
"=",
"params",
".",
"delete",
"(",
":body",
")",
"||",
"{",
"}",
"body",
"=",
"MultiJson",
".",
"dump",
"(",
"body",
")",
"unless",
"body",
".",
"is_a?",
"(",
"String",
")",
"res",
"=",
"@bucket",
".",
"send",
"(",
":__view_query",
",",
"@ddoc",
",",
"@view",
",",
"Utils",
".",
"encode_params",
"(",
"params",
")",
",",
"body",
",",
"options",
")",
"raise",
"res",
"[",
":error",
"]",
"if",
"res",
"[",
":error",
"]",
"meta",
"=",
"MultiJson",
".",
"load",
"(",
"res",
"[",
":meta",
"]",
")",
"send_error",
"(",
"meta",
"[",
"S_ERRORS",
"]",
"[",
"S_FROM",
"]",
",",
"meta",
"[",
"S_ERRORS",
"]",
"[",
"S_REASON",
"]",
")",
"if",
"meta",
"[",
"S_ERRORS",
"]",
"if",
"block_given?",
"res",
"[",
":rows",
"]",
".",
"each",
"do",
"|",
"row",
"|",
"yield",
"@wrapper_class",
".",
"wrap",
"(",
"row",
")",
"end",
"else",
"rows",
"=",
"res",
"[",
":rows",
"]",
".",
"map",
"{",
"|",
"row",
"|",
"@wrapper_class",
".",
"wrap",
"(",
"row",
")",
"}",
"ArrayWithTotalRows",
".",
"new",
"(",
"rows",
",",
"meta",
"[",
"S_TOTAL_ROWS",
"]",
")",
"end",
"end"
] | Performs query to Couchbase view. This method will stream results if block
given or return complete result set otherwise. In latter case it defines
method +total_rows+ returning corresponding entry from
Couchbase result object.
@note Avoid using +$+ symbol as prefix for properties in your
documents, because server marks with it meta fields like flags and
expiration, therefore dollar prefix is some kind of reserved. It
won't hurt your application. Currently the {ViewRow}
class extracts +$flags+, +$cas+ and +$expiration+ properties from
the document and store them in {ViewRow#meta} hash.
@param [Hash] params parameters for Couchbase query.
@option params [true, false] :include_docs (false) Include the
full content of the documents in the return. Note that the document
is fetched from the in memory cache where it may have been changed
or even deleted. See also +:quiet+ parameter below to control error
reporting during fetch.
@option params [true, false] :quiet (true) Do not raise error if
associated document not found in the memory. If the parameter +true+
will use +nil+ value instead.
@option params [true, false] :descending (false) Return the documents
in descending by key order
@option params [String, Fixnum, Hash, Array] :key Return only
documents that match the specified key. Will be JSON encoded.
@option params [Array] :keys The same as +:key+, but will work for
set of keys. Will be JSON encoded.
@option params [String, Fixnum, Hash, Array] :startkey Return
records starting with the specified key. +:start_key+ option should
also work here. Will be JSON encoded.
@option params [String] :startkey_docid Document id to start with
(to allow pagination for duplicate startkeys). +:start_key_doc_id+
also should work.
@option params [String, Fixnum, Hash, Array] :endkey Stop returning
records when the specified key is reached. +:end_key+ option should
also work here. Will be JSON encoded.
@option params [String] :endkey_docid Last document id to include
in the output (to allow pagination for duplicate startkeys).
+:end_key_doc_id+ also should work.
@option params [true, false] :inclusive_end (true) Specifies whether
the specified end key should be included in the result
@option params [Fixnum] :limit Limit the number of documents in the
output.
@option params [Fixnum] :skip Skip this number of records before
starting to return the results.
@option params [String, Symbol] :on_error (:continue) Sets the
response in the event of an error. Supported values:
:continue:: Continue to generate view information in the event of an
error, including the error information in the view
response stream.
:stop:: Stop immediately when an error condition occurs. No
further view information will be returned.
@option params [Fixnum] :connection_timeout (75000) Timeout before the
view request is dropped (milliseconds)
@option params [true, false] :reduce (true) Use the reduction function
@option params [true, false] :group (false) Group the results using
the reduce function to a group or single row.
@option params [Fixnum] :group_level Specify the group level to be
used.
@option params [String, Symbol, false] :stale (:update_after) Allow
the results from a stale view to be used. Supported values:
false:: Force a view update before returning data
:ok:: Allow stale views
:update_after:: Allow stale view, update view after it has been
accessed
@option params [Hash] :body Accepts the same parameters, except
+:body+ of course, but sends them in POST body instead of query
string. It could be useful for really large and complex parameters.
@yieldparam [Couchbase::ViewRow] document
@return [Array] with documents. There will be +total_entries+
method defined on this array if it's possible.
@raise [Couchbase::Error::View] when +on_error+ callback is nil and
error object found in the result stream.
@example Query +recent_posts+ view with key filter
doc.recent_posts(:body => {:keys => ["key1", "key2"]})
@example Fetch second page of result set (splitted in 10 items per page)
page = 2
per_page = 10
doc.recent_posts(:skip => (page - 1) * per_page, :limit => per_page)
@example Simple join using Map/Reduce
# Given the bucket with Posts(:id, :type, :title, :body) and
# Comments(:id, :type, :post_id, :author, :body). The map function
# below (in javascript) will build the View index called
# "recent_posts_with_comments" which will behave like left inner join.
# function(doc) {
# switch (doc.type) {
# case "Post":
# emit([doc.id, 0], null);
# break;
# case "Comment":
# emit([doc.post_id, 1], null);
# break;
# }
# }
post_id = 42
doc.recent_posts_with_comments(:start_key => [post_id, 0],
:end_key => [post_id, 1],
:include_docs => true) | [
"Performs",
"query",
"to",
"Couchbase",
"view",
".",
"This",
"method",
"will",
"stream",
"results",
"if",
"block",
"given",
"or",
"return",
"complete",
"result",
"set",
"otherwise",
".",
"In",
"latter",
"case",
"it",
"defines",
"method",
"+",
"total_rows",
"+",
"returning",
"corresponding",
"entry",
"from",
"Couchbase",
"result",
"object",
"."
] | ecce41a5996d9a97d6182e120bd9b5296707b353 | https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/view.rb#L271-L293 | train |
couchbase/couchbase-ruby-client | lib/couchbase/view_row.rb | Couchbase.DesignDoc.method_missing | def method_missing(meth, *args)
name, options = @all_views[meth.to_s]
if name
View.new(@bucket, @id, name, (args[0] || {}).merge(options))
else
super
end
end | ruby | def method_missing(meth, *args)
name, options = @all_views[meth.to_s]
if name
View.new(@bucket, @id, name, (args[0] || {}).merge(options))
else
super
end
end | [
"def",
"method_missing",
"(",
"meth",
",",
"*",
"args",
")",
"name",
",",
"options",
"=",
"@all_views",
"[",
"meth",
".",
"to_s",
"]",
"if",
"name",
"View",
".",
"new",
"(",
"@bucket",
",",
"@id",
",",
"name",
",",
"(",
"args",
"[",
"0",
"]",
"||",
"{",
"}",
")",
".",
"merge",
"(",
"options",
")",
")",
"else",
"super",
"end",
"end"
] | Initialize the design doc instance
@since 1.2.1
It takes reference to the bucket, data hash. It will define view
methods if the data object looks like design document.
@param [Couchbase::Bucket] bucket the reference to connection
@param [Hash] data the data hash, which was built from JSON document
representation | [
"Initialize",
"the",
"design",
"doc",
"instance"
] | ecce41a5996d9a97d6182e120bd9b5296707b353 | https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/view_row.rb#L198-L205 | train |
couchbase/couchbase-ruby-client | lib/couchbase/bucket.rb | Couchbase.Bucket.cas | def cas(key, options = {})
retries_remaining = options.delete(:retry) || 0
loop do
res = get(key, options)
val = yield(res.value) # get new value from caller
res = set(key, val, options.merge(:cas => res.cas))
if res.error && res.error.code == Couchbase::LibraryError::LCB_KEY_EEXISTS
if retries_remaining > 0
retries_remaining -= 1
next
end
end
return res
end
end | ruby | def cas(key, options = {})
retries_remaining = options.delete(:retry) || 0
loop do
res = get(key, options)
val = yield(res.value) # get new value from caller
res = set(key, val, options.merge(:cas => res.cas))
if res.error && res.error.code == Couchbase::LibraryError::LCB_KEY_EEXISTS
if retries_remaining > 0
retries_remaining -= 1
next
end
end
return res
end
end | [
"def",
"cas",
"(",
"key",
",",
"options",
"=",
"{",
"}",
")",
"retries_remaining",
"=",
"options",
".",
"delete",
"(",
":retry",
")",
"||",
"0",
"loop",
"do",
"res",
"=",
"get",
"(",
"key",
",",
"options",
")",
"val",
"=",
"yield",
"(",
"res",
".",
"value",
")",
"# get new value from caller",
"res",
"=",
"set",
"(",
"key",
",",
"val",
",",
"options",
".",
"merge",
"(",
":cas",
"=>",
"res",
".",
"cas",
")",
")",
"if",
"res",
".",
"error",
"&&",
"res",
".",
"error",
".",
"code",
"==",
"Couchbase",
"::",
"LibraryError",
"::",
"LCB_KEY_EEXISTS",
"if",
"retries_remaining",
">",
"0",
"retries_remaining",
"-=",
"1",
"next",
"end",
"end",
"return",
"res",
"end",
"end"
] | Compare and swap value.
@since 1.0.0
Reads a key's value from the server and yields it to a block. Replaces
the key's value with the result of the block as long as the key hasn't
been updated in the meantime, otherwise raises
{Couchbase::Error::KeyExists}. CAS stands for "compare and swap", and
avoids the need for manual key mutexing. Read more info here:
@see http://couchbase.com/docs/memcached-api/memcached-api-protocol-text_cas.html
Setting the +:retry+ option to a positive number will cause this method
to rescue the {Couchbase::Error::KeyExists} error that happens when
an update collision is detected, and automatically get a fresh copy
of the value and retry the block. This will repeat as long as there
continues to be conflicts, up to the maximum number of retries specified.
@param [String, Symbol] key
@param [Hash] options the options for "swap" part
@option options [Fixnum] :ttl (self.default_ttl) the time to live of this key
@option options [Symbol] :format (self.default_format) format of the value
@option options [Fixnum] :flags (self.default_flags) flags for this key
@option options [Fixnum] :retry (0) maximum number of times to autmatically retry upon update collision
@yieldparam [Object] value old value
@yieldreturn [Object] new value.
@raise [Couchbase::Error::KeyExists] if the key was updated before the the
code in block has been completed (the CAS value has been changed).
@example Implement append to JSON encoded value
c.default_format = :document
c.set("foo", {"bar" => 1})
c.cas("foo") do |val|
val["baz"] = 2
val
end
c.get("foo") #=> {"bar" => 1, "baz" => 2}
@return [Fixnum] the CAS of new value | [
"Compare",
"and",
"swap",
"value",
"."
] | ecce41a5996d9a97d6182e120bd9b5296707b353 | https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/bucket.rb#L63-L77 | train |
couchbase/couchbase-ruby-client | lib/couchbase/bucket.rb | Couchbase.Bucket.design_docs | def design_docs
req = __http_query(:management, :get, "/pools/default/buckets/#{bucket}/ddocs", nil, nil, nil, nil, nil)
docmap = {}
res = MultiJson.load(req[:chunks].join)
res["rows"].each do |obj|
obj['doc']['value'] = obj['doc'].delete('json') if obj['doc']
doc = DesignDoc.new(self, obj)
next if environment == :production && doc.id =~ /dev_/
docmap[doc.id] = doc
end
docmap
end | ruby | def design_docs
req = __http_query(:management, :get, "/pools/default/buckets/#{bucket}/ddocs", nil, nil, nil, nil, nil)
docmap = {}
res = MultiJson.load(req[:chunks].join)
res["rows"].each do |obj|
obj['doc']['value'] = obj['doc'].delete('json') if obj['doc']
doc = DesignDoc.new(self, obj)
next if environment == :production && doc.id =~ /dev_/
docmap[doc.id] = doc
end
docmap
end | [
"def",
"design_docs",
"req",
"=",
"__http_query",
"(",
":management",
",",
":get",
",",
"\"/pools/default/buckets/#{bucket}/ddocs\"",
",",
"nil",
",",
"nil",
",",
"nil",
",",
"nil",
",",
"nil",
")",
"docmap",
"=",
"{",
"}",
"res",
"=",
"MultiJson",
".",
"load",
"(",
"req",
"[",
":chunks",
"]",
".",
"join",
")",
"res",
"[",
"\"rows\"",
"]",
".",
"each",
"do",
"|",
"obj",
"|",
"obj",
"[",
"'doc'",
"]",
"[",
"'value'",
"]",
"=",
"obj",
"[",
"'doc'",
"]",
".",
"delete",
"(",
"'json'",
")",
"if",
"obj",
"[",
"'doc'",
"]",
"doc",
"=",
"DesignDoc",
".",
"new",
"(",
"self",
",",
"obj",
")",
"next",
"if",
"environment",
"==",
":production",
"&&",
"doc",
".",
"id",
"=~",
"/",
"/",
"docmap",
"[",
"doc",
".",
"id",
"]",
"=",
"doc",
"end",
"docmap",
"end"
] | Fetch design docs stored in current bucket
@since 1.2.0
@return [Hash] | [
"Fetch",
"design",
"docs",
"stored",
"in",
"current",
"bucket"
] | ecce41a5996d9a97d6182e120bd9b5296707b353 | https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/bucket.rb#L85-L96 | train |
couchbase/couchbase-ruby-client | lib/couchbase/bucket.rb | Couchbase.Bucket.save_design_doc | def save_design_doc(data)
attrs = case data
when String
MultiJson.load(data)
when IO
MultiJson.load(data.read)
when Hash
data
else
raise ArgumentError, "Document should be Hash, String or IO instance"
end
id = attrs.delete('_id').to_s
attrs['language'] ||= 'javascript'
raise ArgumentError, "'_id' key must be set and start with '_design/'." if id !~ /\A_design\//
res = __http_query(:view, :put, "/#{id}", MultiJson.dump(attrs), 'application/json', nil, nil, nil)
return true if res[:status] == 201
val = MultiJson.load(res[:chunks].join)
raise Error::View.new("save_design_doc", val['error'])
end | ruby | def save_design_doc(data)
attrs = case data
when String
MultiJson.load(data)
when IO
MultiJson.load(data.read)
when Hash
data
else
raise ArgumentError, "Document should be Hash, String or IO instance"
end
id = attrs.delete('_id').to_s
attrs['language'] ||= 'javascript'
raise ArgumentError, "'_id' key must be set and start with '_design/'." if id !~ /\A_design\//
res = __http_query(:view, :put, "/#{id}", MultiJson.dump(attrs), 'application/json', nil, nil, nil)
return true if res[:status] == 201
val = MultiJson.load(res[:chunks].join)
raise Error::View.new("save_design_doc", val['error'])
end | [
"def",
"save_design_doc",
"(",
"data",
")",
"attrs",
"=",
"case",
"data",
"when",
"String",
"MultiJson",
".",
"load",
"(",
"data",
")",
"when",
"IO",
"MultiJson",
".",
"load",
"(",
"data",
".",
"read",
")",
"when",
"Hash",
"data",
"else",
"raise",
"ArgumentError",
",",
"\"Document should be Hash, String or IO instance\"",
"end",
"id",
"=",
"attrs",
".",
"delete",
"(",
"'_id'",
")",
".",
"to_s",
"attrs",
"[",
"'language'",
"]",
"||=",
"'javascript'",
"raise",
"ArgumentError",
",",
"\"'_id' key must be set and start with '_design/'.\"",
"if",
"id",
"!~",
"/",
"\\A",
"\\/",
"/",
"res",
"=",
"__http_query",
"(",
":view",
",",
":put",
",",
"\"/#{id}\"",
",",
"MultiJson",
".",
"dump",
"(",
"attrs",
")",
",",
"'application/json'",
",",
"nil",
",",
"nil",
",",
"nil",
")",
"return",
"true",
"if",
"res",
"[",
":status",
"]",
"==",
"201",
"val",
"=",
"MultiJson",
".",
"load",
"(",
"res",
"[",
":chunks",
"]",
".",
"join",
")",
"raise",
"Error",
"::",
"View",
".",
"new",
"(",
"\"save_design_doc\"",
",",
"val",
"[",
"'error'",
"]",
")",
"end"
] | Update or create design doc with supplied views
@since 1.2.0
@param [Hash, IO, String] data The source object containing JSON
encoded design document. It must have +_id+ key set, this key
should start with +_design/+.
@return [true, false] | [
"Update",
"or",
"create",
"design",
"doc",
"with",
"supplied",
"views"
] | ecce41a5996d9a97d6182e120bd9b5296707b353 | https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/bucket.rb#L107-L125 | train |
couchbase/couchbase-ruby-client | lib/couchbase/bucket.rb | Couchbase.Bucket.delete_design_doc | def delete_design_doc(id, rev = nil)
ddoc = design_docs[id.sub(/^_design\//, '')]
return false unless ddoc
path = Utils.build_query(ddoc.id, :rev => rev || ddoc.meta['rev'])
res = __http_query(:view, :delete, path, nil, nil, nil, nil, nil)
return true if res[:status] == 200
val = MultiJson.load(res[:chunks].join)
raise Error::View.new("delete_design_doc", val['error'])
end | ruby | def delete_design_doc(id, rev = nil)
ddoc = design_docs[id.sub(/^_design\//, '')]
return false unless ddoc
path = Utils.build_query(ddoc.id, :rev => rev || ddoc.meta['rev'])
res = __http_query(:view, :delete, path, nil, nil, nil, nil, nil)
return true if res[:status] == 200
val = MultiJson.load(res[:chunks].join)
raise Error::View.new("delete_design_doc", val['error'])
end | [
"def",
"delete_design_doc",
"(",
"id",
",",
"rev",
"=",
"nil",
")",
"ddoc",
"=",
"design_docs",
"[",
"id",
".",
"sub",
"(",
"/",
"\\/",
"/",
",",
"''",
")",
"]",
"return",
"false",
"unless",
"ddoc",
"path",
"=",
"Utils",
".",
"build_query",
"(",
"ddoc",
".",
"id",
",",
":rev",
"=>",
"rev",
"||",
"ddoc",
".",
"meta",
"[",
"'rev'",
"]",
")",
"res",
"=",
"__http_query",
"(",
":view",
",",
":delete",
",",
"path",
",",
"nil",
",",
"nil",
",",
"nil",
",",
"nil",
",",
"nil",
")",
"return",
"true",
"if",
"res",
"[",
":status",
"]",
"==",
"200",
"val",
"=",
"MultiJson",
".",
"load",
"(",
"res",
"[",
":chunks",
"]",
".",
"join",
")",
"raise",
"Error",
"::",
"View",
".",
"new",
"(",
"\"delete_design_doc\"",
",",
"val",
"[",
"'error'",
"]",
")",
"end"
] | Delete design doc with given id and revision.
@since 1.2.0
@param [String] id Design document id. It might have '_design/'
prefix.
@param [String] rev Document revision. It uses latest revision if
+rev+ parameter is nil.
@return [true, false] | [
"Delete",
"design",
"doc",
"with",
"given",
"id",
"and",
"revision",
"."
] | ecce41a5996d9a97d6182e120bd9b5296707b353 | https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/bucket.rb#L138-L146 | train |
couchbase/couchbase-ruby-client | lib/couchbase/bucket.rb | Couchbase.Bucket.observe_and_wait | def observe_and_wait(*keys, &block)
options = {:timeout => default_observe_timeout}
options.update(keys.pop) if keys.size > 1 && keys.last.is_a?(Hash)
verify_observe_options(options)
raise ArgumentError, "at least one key is required" if keys.empty?
key_cas = if keys.size == 1 && keys[0].is_a?(Hash)
keys[0]
else
keys.flatten.each_with_object({}) do |kk, h|
h[kk] = nil # set CAS to nil
end
end
res = do_observe_and_wait(key_cas, options, &block) while res.nil?
return res.values.first if keys.size == 1 && (keys[0].is_a?(String) || keys[0].is_a?(Symbol))
return res
end | ruby | def observe_and_wait(*keys, &block)
options = {:timeout => default_observe_timeout}
options.update(keys.pop) if keys.size > 1 && keys.last.is_a?(Hash)
verify_observe_options(options)
raise ArgumentError, "at least one key is required" if keys.empty?
key_cas = if keys.size == 1 && keys[0].is_a?(Hash)
keys[0]
else
keys.flatten.each_with_object({}) do |kk, h|
h[kk] = nil # set CAS to nil
end
end
res = do_observe_and_wait(key_cas, options, &block) while res.nil?
return res.values.first if keys.size == 1 && (keys[0].is_a?(String) || keys[0].is_a?(Symbol))
return res
end | [
"def",
"observe_and_wait",
"(",
"*",
"keys",
",",
"&",
"block",
")",
"options",
"=",
"{",
":timeout",
"=>",
"default_observe_timeout",
"}",
"options",
".",
"update",
"(",
"keys",
".",
"pop",
")",
"if",
"keys",
".",
"size",
">",
"1",
"&&",
"keys",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"verify_observe_options",
"(",
"options",
")",
"raise",
"ArgumentError",
",",
"\"at least one key is required\"",
"if",
"keys",
".",
"empty?",
"key_cas",
"=",
"if",
"keys",
".",
"size",
"==",
"1",
"&&",
"keys",
"[",
"0",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"keys",
"[",
"0",
"]",
"else",
"keys",
".",
"flatten",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"kk",
",",
"h",
"|",
"h",
"[",
"kk",
"]",
"=",
"nil",
"# set CAS to nil",
"end",
"end",
"res",
"=",
"do_observe_and_wait",
"(",
"key_cas",
",",
"options",
",",
"block",
")",
"while",
"res",
".",
"nil?",
"return",
"res",
".",
"values",
".",
"first",
"if",
"keys",
".",
"size",
"==",
"1",
"&&",
"(",
"keys",
"[",
"0",
"]",
".",
"is_a?",
"(",
"String",
")",
"||",
"keys",
"[",
"0",
"]",
".",
"is_a?",
"(",
"Symbol",
")",
")",
"return",
"res",
"end"
] | Wait for persistence condition
@since 1.2.0.dp6
This operation is useful when some confidence needed regarding the
state of the keys. With two parameters +:replicated+ and +:persisted+
it allows to set up the waiting rule.
@param [String, Symbol, Array, Hash] keys The list of the keys to
observe. Full form is hash with key-cas value pairs, but there are
also shortcuts like just Array of keys or single key. CAS value
needed to when you need to ensure that the storage persisted exactly
the same version of the key you are asking to observe.
@param [Hash] options The options for operation
@option options [Fixnum] :timeout The timeout in microseconds
@option options [Fixnum] :replicated How many replicas should receive
the copy of the key.
@option options [Fixnum] :persisted How many nodes should store the
key on the disk.
@raise [Couchbase::Error::Timeout] if the given time is up
@return [Fixnum, Hash<String, Fixnum>] will return CAS value just like
mutators or pairs key-cas in case of multiple keys. | [
"Wait",
"for",
"persistence",
"condition"
] | ecce41a5996d9a97d6182e120bd9b5296707b353 | https://github.com/couchbase/couchbase-ruby-client/blob/ecce41a5996d9a97d6182e120bd9b5296707b353/lib/couchbase/bucket.rb#L194-L209 | train |
code-and-effect/effective_resources | app/controllers/concerns/effective/crud_controller.rb | Effective.CrudController.resource_scope | def resource_scope # Thing
@_effective_resource_relation ||= (
relation = case @_effective_resource_scope # If this was initialized by the resource_scope before_filter
when ActiveRecord::Relation
@_effective_resource_scope
when Hash
effective_resource.klass.where(@_effective_resource_scope)
when Symbol
effective_resource.klass.send(@_effective_resource_scope)
when nil
effective_resource.klass.respond_to?(:all) ? effective_resource.klass.all : effective_resource.klass
else
raise "expected resource_scope method to return an ActiveRecord::Relation or Hash"
end
unless relation.kind_of?(ActiveRecord::Relation) || effective_resource.active_model?
raise("unable to build resource_scope for #{effective_resource.klass || 'unknown klass'}. Please name your controller to match an existing model, or manually define a resource_scope.")
end
relation
)
end | ruby | def resource_scope # Thing
@_effective_resource_relation ||= (
relation = case @_effective_resource_scope # If this was initialized by the resource_scope before_filter
when ActiveRecord::Relation
@_effective_resource_scope
when Hash
effective_resource.klass.where(@_effective_resource_scope)
when Symbol
effective_resource.klass.send(@_effective_resource_scope)
when nil
effective_resource.klass.respond_to?(:all) ? effective_resource.klass.all : effective_resource.klass
else
raise "expected resource_scope method to return an ActiveRecord::Relation or Hash"
end
unless relation.kind_of?(ActiveRecord::Relation) || effective_resource.active_model?
raise("unable to build resource_scope for #{effective_resource.klass || 'unknown klass'}. Please name your controller to match an existing model, or manually define a resource_scope.")
end
relation
)
end | [
"def",
"resource_scope",
"# Thing",
"@_effective_resource_relation",
"||=",
"(",
"relation",
"=",
"case",
"@_effective_resource_scope",
"# If this was initialized by the resource_scope before_filter",
"when",
"ActiveRecord",
"::",
"Relation",
"@_effective_resource_scope",
"when",
"Hash",
"effective_resource",
".",
"klass",
".",
"where",
"(",
"@_effective_resource_scope",
")",
"when",
"Symbol",
"effective_resource",
".",
"klass",
".",
"send",
"(",
"@_effective_resource_scope",
")",
"when",
"nil",
"effective_resource",
".",
"klass",
".",
"respond_to?",
"(",
":all",
")",
"?",
"effective_resource",
".",
"klass",
".",
"all",
":",
"effective_resource",
".",
"klass",
"else",
"raise",
"\"expected resource_scope method to return an ActiveRecord::Relation or Hash\"",
"end",
"unless",
"relation",
".",
"kind_of?",
"(",
"ActiveRecord",
"::",
"Relation",
")",
"||",
"effective_resource",
".",
"active_model?",
"raise",
"(",
"\"unable to build resource_scope for #{effective_resource.klass || 'unknown klass'}. Please name your controller to match an existing model, or manually define a resource_scope.\"",
")",
"end",
"relation",
")",
"end"
] | Returns an ActiveRecord relation based on the computed value of `resource_scope` dsl method | [
"Returns",
"an",
"ActiveRecord",
"relation",
"based",
"on",
"the",
"computed",
"value",
"of",
"resource_scope",
"dsl",
"method"
] | eb201dedb4d1480081f8fc466decf6873c1f5bef | https://github.com/code-and-effect/effective_resources/blob/eb201dedb4d1480081f8fc466decf6873c1f5bef/app/controllers/concerns/effective/crud_controller.rb#L83-L104 | train |
tbpgr/tbpgr_utils | lib/template_methodable.rb | TemplateMethodable.ClassMethods.must_impl | def must_impl(*methods)
return if methods.nil?
fail TypeError, "invalid args type #{methods.class}. you must use Array or Symbol" unless methods.class.any_of? Array, Symbol
methods = (methods.class.is_a? Symbol) ? [methods] : methods
methods.each do |method_name|
fail TypeError, "invalid args type #{method_name.class}. you must use Symbol" unless method_name.is_a? Symbol
define_method method_name do |*args|
fail NotImplementedError.new
end
end
end | ruby | def must_impl(*methods)
return if methods.nil?
fail TypeError, "invalid args type #{methods.class}. you must use Array or Symbol" unless methods.class.any_of? Array, Symbol
methods = (methods.class.is_a? Symbol) ? [methods] : methods
methods.each do |method_name|
fail TypeError, "invalid args type #{method_name.class}. you must use Symbol" unless method_name.is_a? Symbol
define_method method_name do |*args|
fail NotImplementedError.new
end
end
end | [
"def",
"must_impl",
"(",
"*",
"methods",
")",
"return",
"if",
"methods",
".",
"nil?",
"fail",
"TypeError",
",",
"\"invalid args type #{methods.class}. you must use Array or Symbol\"",
"unless",
"methods",
".",
"class",
".",
"any_of?",
"Array",
",",
"Symbol",
"methods",
"=",
"(",
"methods",
".",
"class",
".",
"is_a?",
"Symbol",
")",
"?",
"[",
"methods",
"]",
":",
"methods",
"methods",
".",
"each",
"do",
"|",
"method_name",
"|",
"fail",
"TypeError",
",",
"\"invalid args type #{method_name.class}. you must use Symbol\"",
"unless",
"method_name",
".",
"is_a?",
"Symbol",
"define_method",
"method_name",
"do",
"|",
"*",
"args",
"|",
"fail",
"NotImplementedError",
".",
"new",
"end",
"end",
"end"
] | template method force class macro
concrete class must define *methods.
if not define '*method', raise NotImplementedError.
sample BaseClass
require "template_methodable"
class BaseDeveloper
include TemplateMethodable
must_impl :easy_coding, :difficult_coding, :normal_coding
module DIFFICILTY
EASY = 1
NORMAL = 2
DIFFICILT = 3
end
def coding(difficulty)
ret = []
ret << "start coding"
case difficulty
when DIFFICILTY::EASY
ret << easy_coding("hoge", "hige")
when DIFFICILTY::NORMAL
ret << normal_coding("hoge", "hige")
when DIFFICILTY::DIFFICILT
ret << difficult_coding("hoge", "hige")
else
fail 'error'
end
ret << "finish coding"
ret.join("\n")
end
end
sample Concrete Class. if you don't define xxxx_coding method, it raises NotImplementedError.
class StarDeveloper < BaseDeveloper
def easy_coding(hoge, hige)
"complete 1 minutes"
end
def normal_coding(hoge, hige)
"complete 10 minutes"
end
def difficult_coding(hoge, hige)
"complete 59 minutes"
end
end | [
"template",
"method",
"force",
"class",
"macro"
] | 0f7c44478692ada3e1e94ce4aa5182896c4389f1 | https://github.com/tbpgr/tbpgr_utils/blob/0f7c44478692ada3e1e94ce4aa5182896c4389f1/lib/template_methodable.rb#L54-L64 | train |
code-and-effect/effective_resources | app/models/effective/code_reader.rb | Effective.CodeReader.each_with_depth | def each_with_depth(from: nil, to: nil, &block)
Array(lines).each_with_index do |line, index|
next if index < (from || 0)
depth = line.length - line.lstrip.length
block.call(line.strip, depth, index)
break if to == index
end
nil
end | ruby | def each_with_depth(from: nil, to: nil, &block)
Array(lines).each_with_index do |line, index|
next if index < (from || 0)
depth = line.length - line.lstrip.length
block.call(line.strip, depth, index)
break if to == index
end
nil
end | [
"def",
"each_with_depth",
"(",
"from",
":",
"nil",
",",
"to",
":",
"nil",
",",
"&",
"block",
")",
"Array",
"(",
"lines",
")",
".",
"each_with_index",
"do",
"|",
"line",
",",
"index",
"|",
"next",
"if",
"index",
"<",
"(",
"from",
"||",
"0",
")",
"depth",
"=",
"line",
".",
"length",
"-",
"line",
".",
"lstrip",
".",
"length",
"block",
".",
"call",
"(",
"line",
".",
"strip",
",",
"depth",
",",
"index",
")",
"break",
"if",
"to",
"==",
"index",
"end",
"nil",
"end"
] | Iterate over the lines with a depth, and passed the stripped line to the passed block | [
"Iterate",
"over",
"the",
"lines",
"with",
"a",
"depth",
"and",
"passed",
"the",
"stripped",
"line",
"to",
"the",
"passed",
"block"
] | eb201dedb4d1480081f8fc466decf6873c1f5bef | https://github.com/code-and-effect/effective_resources/blob/eb201dedb4d1480081f8fc466decf6873c1f5bef/app/models/effective/code_reader.rb#L11-L22 | train |
code-and-effect/effective_resources | app/models/effective/code_reader.rb | Effective.CodeReader.index | def index(from: nil, to: nil, &block)
each_with_depth(from: from, to: to) do |line, depth, index|
return index if block.call(line, depth, index)
end
end | ruby | def index(from: nil, to: nil, &block)
each_with_depth(from: from, to: to) do |line, depth, index|
return index if block.call(line, depth, index)
end
end | [
"def",
"index",
"(",
"from",
":",
"nil",
",",
"to",
":",
"nil",
",",
"&",
"block",
")",
"each_with_depth",
"(",
"from",
":",
"from",
",",
"to",
":",
"to",
")",
"do",
"|",
"line",
",",
"depth",
",",
"index",
"|",
"return",
"index",
"if",
"block",
".",
"call",
"(",
"line",
",",
"depth",
",",
"index",
")",
"end",
"end"
] | Returns the index of the first line where the passed block returns true | [
"Returns",
"the",
"index",
"of",
"the",
"first",
"line",
"where",
"the",
"passed",
"block",
"returns",
"true"
] | eb201dedb4d1480081f8fc466decf6873c1f5bef | https://github.com/code-and-effect/effective_resources/blob/eb201dedb4d1480081f8fc466decf6873c1f5bef/app/models/effective/code_reader.rb#L25-L29 | train |
code-and-effect/effective_resources | app/models/effective/code_reader.rb | Effective.CodeReader.last | def last(from: nil, to: nil, &block)
retval = nil
each_with_depth(from: from, to: nil) do |line, depth, index|
retval = line if block.call(line, depth, index)
end
retval
end | ruby | def last(from: nil, to: nil, &block)
retval = nil
each_with_depth(from: from, to: nil) do |line, depth, index|
retval = line if block.call(line, depth, index)
end
retval
end | [
"def",
"last",
"(",
"from",
":",
"nil",
",",
"to",
":",
"nil",
",",
"&",
"block",
")",
"retval",
"=",
"nil",
"each_with_depth",
"(",
"from",
":",
"from",
",",
"to",
":",
"nil",
")",
"do",
"|",
"line",
",",
"depth",
",",
"index",
"|",
"retval",
"=",
"line",
"if",
"block",
".",
"call",
"(",
"line",
",",
"depth",
",",
"index",
")",
"end",
"retval",
"end"
] | Returns the stripped contents of the last line where the passed block returns true | [
"Returns",
"the",
"stripped",
"contents",
"of",
"the",
"last",
"line",
"where",
"the",
"passed",
"block",
"returns",
"true"
] | eb201dedb4d1480081f8fc466decf6873c1f5bef | https://github.com/code-and-effect/effective_resources/blob/eb201dedb4d1480081f8fc466decf6873c1f5bef/app/models/effective/code_reader.rb#L40-L48 | train |
code-and-effect/effective_resources | app/models/effective/code_reader.rb | Effective.CodeReader.select | def select(from: nil, to: nil, &block)
retval = []
each_with_depth(from: from, to: to) do |line, depth, index|
retval << line if (block_given? == false || block.call(line, depth, index))
end
retval
end | ruby | def select(from: nil, to: nil, &block)
retval = []
each_with_depth(from: from, to: to) do |line, depth, index|
retval << line if (block_given? == false || block.call(line, depth, index))
end
retval
end | [
"def",
"select",
"(",
"from",
":",
"nil",
",",
"to",
":",
"nil",
",",
"&",
"block",
")",
"retval",
"=",
"[",
"]",
"each_with_depth",
"(",
"from",
":",
"from",
",",
"to",
":",
"to",
")",
"do",
"|",
"line",
",",
"depth",
",",
"index",
"|",
"retval",
"<<",
"line",
"if",
"(",
"block_given?",
"==",
"false",
"||",
"block",
".",
"call",
"(",
"line",
",",
"depth",
",",
"index",
")",
")",
"end",
"retval",
"end"
] | Returns an array of stripped lines for each line where the passed block returns true | [
"Returns",
"an",
"array",
"of",
"stripped",
"lines",
"for",
"each",
"line",
"where",
"the",
"passed",
"block",
"returns",
"true"
] | eb201dedb4d1480081f8fc466decf6873c1f5bef | https://github.com/code-and-effect/effective_resources/blob/eb201dedb4d1480081f8fc466decf6873c1f5bef/app/models/effective/code_reader.rb#L51-L59 | train |
code-and-effect/effective_resources | app/models/concerns/acts_as_statused.rb | ActsAsStatused.CanCan.acts_as_statused | def acts_as_statused(klass, only: nil, except: nil)
raise "klass does not implement acts_as_statused" unless klass.acts_as_statused?
statuses = klass.const_get(:STATUSES)
instance = klass.new
only = Array(only).compact
except = Array(except).compact
statuses.each_with_index do |status, index|
action = status_active_verb(status, instance)
next if action.blank?
next if only.present? && !only.include?(action)
next if except.present? && except.include?(action)
if index == 0
can(action, klass) and next
end
if status == :approved && statuses.include?(:declined)
if (position = statuses.index { |status| (status == :approved || status == :declined) }) > 0
can(action, klass) { |obj| obj.public_send("#{statuses[position-1]}?") || obj.declined? }
next
end
end
if status == :declined && statuses.include?(:approved)
if (position = statuses.index { |status| (status == :approved || status == :declined) }) > 0
can(action, klass) { |obj| obj.public_send("#{statuses[position-1]}?") }
next
end
end
can(action, klass) { |obj| obj.public_send("#{statuses[index-1]}?") }
end
end | ruby | def acts_as_statused(klass, only: nil, except: nil)
raise "klass does not implement acts_as_statused" unless klass.acts_as_statused?
statuses = klass.const_get(:STATUSES)
instance = klass.new
only = Array(only).compact
except = Array(except).compact
statuses.each_with_index do |status, index|
action = status_active_verb(status, instance)
next if action.blank?
next if only.present? && !only.include?(action)
next if except.present? && except.include?(action)
if index == 0
can(action, klass) and next
end
if status == :approved && statuses.include?(:declined)
if (position = statuses.index { |status| (status == :approved || status == :declined) }) > 0
can(action, klass) { |obj| obj.public_send("#{statuses[position-1]}?") || obj.declined? }
next
end
end
if status == :declined && statuses.include?(:approved)
if (position = statuses.index { |status| (status == :approved || status == :declined) }) > 0
can(action, klass) { |obj| obj.public_send("#{statuses[position-1]}?") }
next
end
end
can(action, klass) { |obj| obj.public_send("#{statuses[index-1]}?") }
end
end | [
"def",
"acts_as_statused",
"(",
"klass",
",",
"only",
":",
"nil",
",",
"except",
":",
"nil",
")",
"raise",
"\"klass does not implement acts_as_statused\"",
"unless",
"klass",
".",
"acts_as_statused?",
"statuses",
"=",
"klass",
".",
"const_get",
"(",
":STATUSES",
")",
"instance",
"=",
"klass",
".",
"new",
"only",
"=",
"Array",
"(",
"only",
")",
".",
"compact",
"except",
"=",
"Array",
"(",
"except",
")",
".",
"compact",
"statuses",
".",
"each_with_index",
"do",
"|",
"status",
",",
"index",
"|",
"action",
"=",
"status_active_verb",
"(",
"status",
",",
"instance",
")",
"next",
"if",
"action",
".",
"blank?",
"next",
"if",
"only",
".",
"present?",
"&&",
"!",
"only",
".",
"include?",
"(",
"action",
")",
"next",
"if",
"except",
".",
"present?",
"&&",
"except",
".",
"include?",
"(",
"action",
")",
"if",
"index",
"==",
"0",
"can",
"(",
"action",
",",
"klass",
")",
"and",
"next",
"end",
"if",
"status",
"==",
":approved",
"&&",
"statuses",
".",
"include?",
"(",
":declined",
")",
"if",
"(",
"position",
"=",
"statuses",
".",
"index",
"{",
"|",
"status",
"|",
"(",
"status",
"==",
":approved",
"||",
"status",
"==",
":declined",
")",
"}",
")",
">",
"0",
"can",
"(",
"action",
",",
"klass",
")",
"{",
"|",
"obj",
"|",
"obj",
".",
"public_send",
"(",
"\"#{statuses[position-1]}?\"",
")",
"||",
"obj",
".",
"declined?",
"}",
"next",
"end",
"end",
"if",
"status",
"==",
":declined",
"&&",
"statuses",
".",
"include?",
"(",
":approved",
")",
"if",
"(",
"position",
"=",
"statuses",
".",
"index",
"{",
"|",
"status",
"|",
"(",
"status",
"==",
":approved",
"||",
"status",
"==",
":declined",
")",
"}",
")",
">",
"0",
"can",
"(",
"action",
",",
"klass",
")",
"{",
"|",
"obj",
"|",
"obj",
".",
"public_send",
"(",
"\"#{statuses[position-1]}?\"",
")",
"}",
"next",
"end",
"end",
"can",
"(",
"action",
",",
"klass",
")",
"{",
"|",
"obj",
"|",
"obj",
".",
"public_send",
"(",
"\"#{statuses[index-1]}?\"",
")",
"}",
"end",
"end"
] | The idea here is you can go forward but you can't go back. | [
"The",
"idea",
"here",
"is",
"you",
"can",
"go",
"forward",
"but",
"you",
"can",
"t",
"go",
"back",
"."
] | eb201dedb4d1480081f8fc466decf6873c1f5bef | https://github.com/code-and-effect/effective_resources/blob/eb201dedb4d1480081f8fc466decf6873c1f5bef/app/models/concerns/acts_as_statused.rb#L29-L65 | train |
code-and-effect/effective_resources | app/models/concerns/acts_as_statused.rb | ActsAsStatused.CanCan.status_active_verb | def status_active_verb(status, instance)
status = status.to_s.strip
if status.end_with?('ied')
action = status[0...-3] + 'y'
return action.to_sym if instance.respond_to?(action + '!')
end
# ed, e, ing
[-1, -2, -3].each do |index|
action = status[0...index]
return action.to_sym if instance.respond_to?(action + '!')
end
nil
end | ruby | def status_active_verb(status, instance)
status = status.to_s.strip
if status.end_with?('ied')
action = status[0...-3] + 'y'
return action.to_sym if instance.respond_to?(action + '!')
end
# ed, e, ing
[-1, -2, -3].each do |index|
action = status[0...index]
return action.to_sym if instance.respond_to?(action + '!')
end
nil
end | [
"def",
"status_active_verb",
"(",
"status",
",",
"instance",
")",
"status",
"=",
"status",
".",
"to_s",
".",
"strip",
"if",
"status",
".",
"end_with?",
"(",
"'ied'",
")",
"action",
"=",
"status",
"[",
"0",
"...",
"-",
"3",
"]",
"+",
"'y'",
"return",
"action",
".",
"to_sym",
"if",
"instance",
".",
"respond_to?",
"(",
"action",
"+",
"'!'",
")",
"end",
"# ed, e, ing",
"[",
"-",
"1",
",",
"-",
"2",
",",
"-",
"3",
"]",
".",
"each",
"do",
"|",
"index",
"|",
"action",
"=",
"status",
"[",
"0",
"...",
"index",
"]",
"return",
"action",
".",
"to_sym",
"if",
"instance",
".",
"respond_to?",
"(",
"action",
"+",
"'!'",
")",
"end",
"nil",
"end"
] | requested -> request, approved -> approve, declined -> decline, pending -> pending | [
"requested",
"-",
">",
"request",
"approved",
"-",
">",
"approve",
"declined",
"-",
">",
"decline",
"pending",
"-",
">",
"pending"
] | eb201dedb4d1480081f8fc466decf6873c1f5bef | https://github.com/code-and-effect/effective_resources/blob/eb201dedb4d1480081f8fc466decf6873c1f5bef/app/models/concerns/acts_as_statused.rb#L70-L85 | train |
mlipper/runt | lib/runt/schedule.rb | Runt.Schedule.dates | def dates(event, date_range)
result=[]
date_range.each do |date|
result.push date if include?(event,date)
end
result
end | ruby | def dates(event, date_range)
result=[]
date_range.each do |date|
result.push date if include?(event,date)
end
result
end | [
"def",
"dates",
"(",
"event",
",",
"date_range",
")",
"result",
"=",
"[",
"]",
"date_range",
".",
"each",
"do",
"|",
"date",
"|",
"result",
".",
"push",
"date",
"if",
"include?",
"(",
"event",
",",
"date",
")",
"end",
"result",
"end"
] | For the given date range, returns an Array of PDate objects at which
the supplied event is scheduled to occur. | [
"For",
"the",
"given",
"date",
"range",
"returns",
"an",
"Array",
"of",
"PDate",
"objects",
"at",
"which",
"the",
"supplied",
"event",
"is",
"scheduled",
"to",
"occur",
"."
] | d0dab62fa45571e50e2018dbe1e12a9fe2752f61 | https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/lib/runt/schedule.rb#L26-L32 | train |
mlipper/runt | lib/runt/schedule.rb | Runt.Schedule.include? | def include?(event, date)
return false unless @elems.include?(event)
return 0<(self.select{|ev,xpr| ev.eql?(event)&&xpr.include?(date);}).size
end | ruby | def include?(event, date)
return false unless @elems.include?(event)
return 0<(self.select{|ev,xpr| ev.eql?(event)&&xpr.include?(date);}).size
end | [
"def",
"include?",
"(",
"event",
",",
"date",
")",
"return",
"false",
"unless",
"@elems",
".",
"include?",
"(",
"event",
")",
"return",
"0",
"<",
"(",
"self",
".",
"select",
"{",
"|",
"ev",
",",
"xpr",
"|",
"ev",
".",
"eql?",
"(",
"event",
")",
"&&",
"xpr",
".",
"include?",
"(",
"date",
")",
";",
"}",
")",
".",
"size",
"end"
] | Return true or false depend on if the supplied event is scheduled to occur on the
given date. | [
"Return",
"true",
"or",
"false",
"depend",
"on",
"if",
"the",
"supplied",
"event",
"is",
"scheduled",
"to",
"occur",
"on",
"the",
"given",
"date",
"."
] | d0dab62fa45571e50e2018dbe1e12a9fe2752f61 | https://github.com/mlipper/runt/blob/d0dab62fa45571e50e2018dbe1e12a9fe2752f61/lib/runt/schedule.rb#L40-L43 | train |
Chetane/fixy | lib/fixy/record.rb | Fixy.Record.generate | def generate(debug = false)
decorator = debug ? Fixy::Decorator::Debug : Fixy::Decorator::Default
output = ''
current_position = 1
current_record = 1
while current_position <= self.class.record_length do
field = record_fields[current_position]
raise StandardError, "Undefined field for position #{current_position}" unless field
# We will first retrieve the value, then format it
method = field[:name]
value = send(method)
formatted_value = format_value(value, field[:size], field[:type])
formatted_value = decorator.field(formatted_value, current_record, current_position, method, field[:size], field[:type])
output << formatted_value
current_position = field[:to] + 1
current_record += 1
end
# Documentation mandates that every record ends with new line.
output << line_ending
# All ready. In the words of Mr. Peters: "Take it and go!"
decorator.record(output)
end | ruby | def generate(debug = false)
decorator = debug ? Fixy::Decorator::Debug : Fixy::Decorator::Default
output = ''
current_position = 1
current_record = 1
while current_position <= self.class.record_length do
field = record_fields[current_position]
raise StandardError, "Undefined field for position #{current_position}" unless field
# We will first retrieve the value, then format it
method = field[:name]
value = send(method)
formatted_value = format_value(value, field[:size], field[:type])
formatted_value = decorator.field(formatted_value, current_record, current_position, method, field[:size], field[:type])
output << formatted_value
current_position = field[:to] + 1
current_record += 1
end
# Documentation mandates that every record ends with new line.
output << line_ending
# All ready. In the words of Mr. Peters: "Take it and go!"
decorator.record(output)
end | [
"def",
"generate",
"(",
"debug",
"=",
"false",
")",
"decorator",
"=",
"debug",
"?",
"Fixy",
"::",
"Decorator",
"::",
"Debug",
":",
"Fixy",
"::",
"Decorator",
"::",
"Default",
"output",
"=",
"''",
"current_position",
"=",
"1",
"current_record",
"=",
"1",
"while",
"current_position",
"<=",
"self",
".",
"class",
".",
"record_length",
"do",
"field",
"=",
"record_fields",
"[",
"current_position",
"]",
"raise",
"StandardError",
",",
"\"Undefined field for position #{current_position}\"",
"unless",
"field",
"# We will first retrieve the value, then format it",
"method",
"=",
"field",
"[",
":name",
"]",
"value",
"=",
"send",
"(",
"method",
")",
"formatted_value",
"=",
"format_value",
"(",
"value",
",",
"field",
"[",
":size",
"]",
",",
"field",
"[",
":type",
"]",
")",
"formatted_value",
"=",
"decorator",
".",
"field",
"(",
"formatted_value",
",",
"current_record",
",",
"current_position",
",",
"method",
",",
"field",
"[",
":size",
"]",
",",
"field",
"[",
":type",
"]",
")",
"output",
"<<",
"formatted_value",
"current_position",
"=",
"field",
"[",
":to",
"]",
"+",
"1",
"current_record",
"+=",
"1",
"end",
"# Documentation mandates that every record ends with new line.",
"output",
"<<",
"line_ending",
"# All ready. In the words of Mr. Peters: \"Take it and go!\"",
"decorator",
".",
"record",
"(",
"output",
")",
"end"
] | Generate the entry based on the record structure | [
"Generate",
"the",
"entry",
"based",
"on",
"the",
"record",
"structure"
] | aa5cf89e56cf592fabf5c5695d5d213af157a283 | https://github.com/Chetane/fixy/blob/aa5cf89e56cf592fabf5c5695d5d213af157a283/lib/fixy/record.rb#L122-L149 | train |
walle/gas | lib/gas/users.rb | Gas.Users.exists? | def exists?(nickname)
users.each do |user|
if user.nickname == nickname
return true;
end
end
false
end | ruby | def exists?(nickname)
users.each do |user|
if user.nickname == nickname
return true;
end
end
false
end | [
"def",
"exists?",
"(",
"nickname",
")",
"users",
".",
"each",
"do",
"|",
"user",
"|",
"if",
"user",
".",
"nickname",
"==",
"nickname",
"return",
"true",
";",
"end",
"end",
"false",
"end"
] | Initializes the object. If no users are supplied we look for a config file, if none then create it, and parse it to load users
@param [String] config_file The path to the file that stores users
Checks if a user with _nickname_ exists
@param [String] nickname
@return [Boolean] | [
"Initializes",
"the",
"object",
".",
"If",
"no",
"users",
"are",
"supplied",
"we",
"look",
"for",
"a",
"config",
"file",
"if",
"none",
"then",
"create",
"it",
"and",
"parse",
"it",
"to",
"load",
"users"
] | b27ee21681c1ddbaa15b64ca1b4f359bc26d4876 | https://github.com/walle/gas/blob/b27ee21681c1ddbaa15b64ca1b4f359bc26d4876/lib/gas/users.rb#L21-L29 | train |
walle/gas | lib/gas/users.rb | Gas.Users.get | def get(nickname)
users.each do |user|
if user.nickname == nickname.to_s
return user
end
end
nil
end | ruby | def get(nickname)
users.each do |user|
if user.nickname == nickname.to_s
return user
end
end
nil
end | [
"def",
"get",
"(",
"nickname",
")",
"users",
".",
"each",
"do",
"|",
"user",
"|",
"if",
"user",
".",
"nickname",
"==",
"nickname",
".",
"to_s",
"return",
"user",
"end",
"end",
"nil",
"end"
] | Returns the user with nickname nil if no such user exists
@param [String|Symbol] nickname
@return [User|nil] | [
"Returns",
"the",
"user",
"with",
"nickname",
"nil",
"if",
"no",
"such",
"user",
"exists"
] | b27ee21681c1ddbaa15b64ca1b4f359bc26d4876 | https://github.com/walle/gas/blob/b27ee21681c1ddbaa15b64ca1b4f359bc26d4876/lib/gas/users.rb#L34-L42 | train |
walle/gas | lib/gas/users.rb | Gas.Users.to_s | def to_s
current_user = GitConfig.current_user
users.map do |user|
if current_user == user
" ==> #{user.to_s[5,user.to_s.length]}"
else
user.to_s
end
end.join "\n"
end | ruby | def to_s
current_user = GitConfig.current_user
users.map do |user|
if current_user == user
" ==> #{user.to_s[5,user.to_s.length]}"
else
user.to_s
end
end.join "\n"
end | [
"def",
"to_s",
"current_user",
"=",
"GitConfig",
".",
"current_user",
"users",
".",
"map",
"do",
"|",
"user",
"|",
"if",
"current_user",
"==",
"user",
"\" ==> #{user.to_s[5,user.to_s.length]}\"",
"else",
"user",
".",
"to_s",
"end",
"end",
".",
"join",
"\"\\n\"",
"end"
] | Override to_s to output correct format | [
"Override",
"to_s",
"to",
"output",
"correct",
"format"
] | b27ee21681c1ddbaa15b64ca1b4f359bc26d4876 | https://github.com/walle/gas/blob/b27ee21681c1ddbaa15b64ca1b4f359bc26d4876/lib/gas/users.rb#L73-L82 | train |
dbalmain/ferret | ruby/lib/ferret/field_symbol.rb | Ferret.FieldSymbolMethods.desc | def desc
fsym = FieldSymbol.new(self, respond_to?(:desc?) ? !desc? : true)
fsym.type = respond_to?(:type) ? type : nil
fsym
end | ruby | def desc
fsym = FieldSymbol.new(self, respond_to?(:desc?) ? !desc? : true)
fsym.type = respond_to?(:type) ? type : nil
fsym
end | [
"def",
"desc",
"fsym",
"=",
"FieldSymbol",
".",
"new",
"(",
"self",
",",
"respond_to?",
"(",
":desc?",
")",
"?",
"!",
"desc?",
":",
"true",
")",
"fsym",
".",
"type",
"=",
"respond_to?",
"(",
":type",
")",
"?",
"type",
":",
"nil",
"fsym",
"end"
] | Set a field to be a descending field. This only makes sense in sort
specifications. | [
"Set",
"a",
"field",
"to",
"be",
"a",
"descending",
"field",
".",
"This",
"only",
"makes",
"sense",
"in",
"sort",
"specifications",
"."
] | 2451bc48c3aa162cbb87659b0f460b7821590cd1 | https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/field_symbol.rb#L58-L62 | train |
dbalmain/ferret | ruby/lib/ferret/document.rb | Ferret.Document.to_s | def to_s
buf = ["Document {"]
self.keys.sort_by {|key| key.to_s}.each do |key|
val = self[key]
val_str = if val.instance_of? Array then %{["#{val.join('", "')}"]}
elsif val.is_a? Field then val.to_s
else %{"#{val.to_s}"}
end
buf << " :#{key} => #{val_str}"
end
buf << ["}#{@boost == 1.0 ? "" : "^" + @boost.to_s}"]
return buf.join("\n")
end | ruby | def to_s
buf = ["Document {"]
self.keys.sort_by {|key| key.to_s}.each do |key|
val = self[key]
val_str = if val.instance_of? Array then %{["#{val.join('", "')}"]}
elsif val.is_a? Field then val.to_s
else %{"#{val.to_s}"}
end
buf << " :#{key} => #{val_str}"
end
buf << ["}#{@boost == 1.0 ? "" : "^" + @boost.to_s}"]
return buf.join("\n")
end | [
"def",
"to_s",
"buf",
"=",
"[",
"\"Document {\"",
"]",
"self",
".",
"keys",
".",
"sort_by",
"{",
"|",
"key",
"|",
"key",
".",
"to_s",
"}",
".",
"each",
"do",
"|",
"key",
"|",
"val",
"=",
"self",
"[",
"key",
"]",
"val_str",
"=",
"if",
"val",
".",
"instance_of?",
"Array",
"then",
"%{[\"#{val.join('\", \"')}\"]}",
"elsif",
"val",
".",
"is_a?",
"Field",
"then",
"val",
".",
"to_s",
"else",
"%{\"#{val.to_s}\"}",
"end",
"buf",
"<<",
"\" :#{key} => #{val_str}\"",
"end",
"buf",
"<<",
"[",
"\"}#{@boost == 1.0 ? \"\" : \"^\" + @boost.to_s}\"",
"]",
"return",
"buf",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | Create a string representation of the document | [
"Create",
"a",
"string",
"representation",
"of",
"the",
"document"
] | 2451bc48c3aa162cbb87659b0f460b7821590cd1 | https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/document.rb#L61-L73 | train |
dbalmain/ferret | ruby/lib/ferret/index.rb | Ferret::Index.Index.highlight | def highlight(query, doc_id, options = {})
@dir.synchronize do
ensure_searcher_open()
@searcher.highlight(do_process_query(query),
doc_id,
options[:field]||@options[:default_field],
options)
end
end | ruby | def highlight(query, doc_id, options = {})
@dir.synchronize do
ensure_searcher_open()
@searcher.highlight(do_process_query(query),
doc_id,
options[:field]||@options[:default_field],
options)
end
end | [
"def",
"highlight",
"(",
"query",
",",
"doc_id",
",",
"options",
"=",
"{",
"}",
")",
"@dir",
".",
"synchronize",
"do",
"ensure_searcher_open",
"(",
")",
"@searcher",
".",
"highlight",
"(",
"do_process_query",
"(",
"query",
")",
",",
"doc_id",
",",
"options",
"[",
":field",
"]",
"||",
"@options",
"[",
":default_field",
"]",
",",
"options",
")",
"end",
"end"
] | If you create an Index without any options, it'll simply create an index
in memory. But this class is highly configurable and every option that
you can supply to IndexWriter and QueryParser, you can also set here.
Please look at the options for the constructors to these classes.
=== Options
See;
* QueryParser
* IndexWriter
default_input_field:: Default: "id". This specifies the default field
that will be used when you add a simple string
to the index using #add_document or <<.
id_field:: Default: "id". This field is as the field to
search when doing searches on a term. For
example, if you do a lookup by term "cat", ie
index["cat"], this will be the field that is
searched.
key:: Default: nil. Expert: This should only be used
if you really know what you are doing. Basically
you can set a field or an array of fields to be
the key for the index. So if you add a document
with a same key as an existing document, the
existing document will be replaced by the new
object. Using a multiple field key will slow
down indexing so it should not be done if
performance is a concern. A single field key (or
id) should be find however. Also, you must make
sure that your key/keys are either untokenized
or that they are not broken up by the analyzer.
auto_flush:: Default: false. Set this option to true if you
want the index automatically flushed every time
you do a write (includes delete) to the index.
This is useful if you have multiple processes
accessing the index and you don't want lock
errors. Setting :auto_flush to true has a huge
performance impact so don't use it if you are
concerned about performance. In that case you
should think about setting up a DRb indexing
service.
lock_retry_time:: Default: 2 seconds. This parameter specifies how
long to wait before retrying to obtain the
commit lock when detecting if the IndexReader is
at the latest version.
close_dir:: Default: false. If you explicitly pass a
Directory object to this class and you want
Index to close it when it is closed itself then
set this to true.
use_typed_range_query:: Default: true. Use TypedRangeQuery instead of
the standard RangeQuery when parsing
range queries. This is useful if you have number
fields which you want to perform range queries
on. You won't need to pad or normalize the data
in the field in anyway to get correct results.
However, performance will be a lot slower for
large indexes, hence the default.
== Examples
index = Index::Index.new(:analyzer => WhiteSpaceAnalyzer.new())
index = Index::Index.new(:path => '/path/to/index',
:create_if_missing => false,
:auto_flush => true)
index = Index::Index.new(:dir => directory,
:default_slop => 2,
:handle_parse_errors => false)
You can also pass a block if you like. The index will be yielded and
closed at the index of the box. For example;
Ferret::I.new() do |index|
# do stuff with index. Most of your actions will be cached.
end
Returns an array of strings with the matches highlighted. The +query+ can
either a query String or a Ferret::Search::Query object. The doc_id is
the id of the document you want to highlight (usually returned by the
search methods). There are also a number of options you can pass;
=== Options
field:: Default: @options[:default_field]. The default_field
is the field that is usually highlighted but you can
specify which field you want to highlight here. If
you want to highlight multiple fields then you will
need to call this method multiple times.
excerpt_length:: Default: 150. Length of excerpt to show. Highlighted
terms will be in the centre of the excerpt. Set to
:all to highlight the entire field.
num_excerpts:: Default: 2. Number of excerpts to return.
pre_tag:: Default: "<b>". Tag to place to the left of the
match. You'll probably want to change this to a
"<span>" tag with a class. Try "\033[36m" for use in
a terminal.
post_tag:: Default: "</b>". This tag should close the
+:pre_tag+. Try tag "\033[m" in the terminal.
ellipsis:: Default: "...". This is the string that is appended
at the beginning and end of excerpts (unless the
excerpt hits the start or end of the field.
Alternatively you may want to use the HTML entity
… or the UTF-8 string "\342\200\246". | [
"If",
"you",
"create",
"an",
"Index",
"without",
"any",
"options",
"it",
"ll",
"simply",
"create",
"an",
"index",
"in",
"memory",
".",
"But",
"this",
"class",
"is",
"highly",
"configurable",
"and",
"every",
"option",
"that",
"you",
"can",
"supply",
"to",
"IndexWriter",
"and",
"QueryParser",
"you",
"can",
"also",
"set",
"here",
".",
"Please",
"look",
"at",
"the",
"options",
"for",
"the",
"constructors",
"to",
"these",
"classes",
"."
] | 2451bc48c3aa162cbb87659b0f460b7821590cd1 | https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L191-L199 | train |
dbalmain/ferret | ruby/lib/ferret/index.rb | Ferret::Index.Index.term_vector | def term_vector(id, field)
@dir.synchronize do
ensure_reader_open()
if id.kind_of?(String) or id.kind_of?(Symbol)
term_doc_enum = @reader.term_docs_for(@id_field, id.to_s)
if term_doc_enum.next?
id = term_doc_enum.doc
else
return nil
end
end
return @reader.term_vector(id, field)
end
end | ruby | def term_vector(id, field)
@dir.synchronize do
ensure_reader_open()
if id.kind_of?(String) or id.kind_of?(Symbol)
term_doc_enum = @reader.term_docs_for(@id_field, id.to_s)
if term_doc_enum.next?
id = term_doc_enum.doc
else
return nil
end
end
return @reader.term_vector(id, field)
end
end | [
"def",
"term_vector",
"(",
"id",
",",
"field",
")",
"@dir",
".",
"synchronize",
"do",
"ensure_reader_open",
"(",
")",
"if",
"id",
".",
"kind_of?",
"(",
"String",
")",
"or",
"id",
".",
"kind_of?",
"(",
"Symbol",
")",
"term_doc_enum",
"=",
"@reader",
".",
"term_docs_for",
"(",
"@id_field",
",",
"id",
".",
"to_s",
")",
"if",
"term_doc_enum",
".",
"next?",
"id",
"=",
"term_doc_enum",
".",
"doc",
"else",
"return",
"nil",
"end",
"end",
"return",
"@reader",
".",
"term_vector",
"(",
"id",
",",
"field",
")",
"end",
"end"
] | Retrieves the term_vector for a document. The document can be referenced
by either a string id to match the id field or an integer corresponding
to Ferret's document number.
See Ferret::Index::IndexReader#term_vector | [
"Retrieves",
"the",
"term_vector",
"for",
"a",
"document",
".",
"The",
"document",
"can",
"be",
"referenced",
"by",
"either",
"a",
"string",
"id",
"to",
"match",
"the",
"id",
"field",
"or",
"an",
"integer",
"corresponding",
"to",
"Ferret",
"s",
"document",
"number",
"."
] | 2451bc48c3aa162cbb87659b0f460b7821590cd1 | https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L471-L484 | train |
dbalmain/ferret | ruby/lib/ferret/index.rb | Ferret::Index.Index.query_delete | def query_delete(query)
@dir.synchronize do
ensure_writer_open()
ensure_searcher_open()
query = do_process_query(query)
@searcher.search_each(query, :limit => :all) do |doc, score|
@reader.delete(doc)
end
flush() if @auto_flush
end
end | ruby | def query_delete(query)
@dir.synchronize do
ensure_writer_open()
ensure_searcher_open()
query = do_process_query(query)
@searcher.search_each(query, :limit => :all) do |doc, score|
@reader.delete(doc)
end
flush() if @auto_flush
end
end | [
"def",
"query_delete",
"(",
"query",
")",
"@dir",
".",
"synchronize",
"do",
"ensure_writer_open",
"(",
")",
"ensure_searcher_open",
"(",
")",
"query",
"=",
"do_process_query",
"(",
"query",
")",
"@searcher",
".",
"search_each",
"(",
"query",
",",
":limit",
"=>",
":all",
")",
"do",
"|",
"doc",
",",
"score",
"|",
"@reader",
".",
"delete",
"(",
"doc",
")",
"end",
"flush",
"(",
")",
"if",
"@auto_flush",
"end",
"end"
] | Delete all documents returned by the query.
query:: The query to find documents you wish to delete. Can either be a
string (in which case it is parsed by the standard query parser)
or an actual query object. | [
"Delete",
"all",
"documents",
"returned",
"by",
"the",
"query",
"."
] | 2451bc48c3aa162cbb87659b0f460b7821590cd1 | https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L540-L550 | train |
dbalmain/ferret | ruby/lib/ferret/index.rb | Ferret::Index.Index.update | def update(id, new_doc)
@dir.synchronize do
ensure_writer_open()
delete(id)
if id.is_a?(String) or id.is_a?(Symbol)
@writer.commit
else
ensure_writer_open()
end
@writer << new_doc
flush() if @auto_flush
end
end | ruby | def update(id, new_doc)
@dir.synchronize do
ensure_writer_open()
delete(id)
if id.is_a?(String) or id.is_a?(Symbol)
@writer.commit
else
ensure_writer_open()
end
@writer << new_doc
flush() if @auto_flush
end
end | [
"def",
"update",
"(",
"id",
",",
"new_doc",
")",
"@dir",
".",
"synchronize",
"do",
"ensure_writer_open",
"(",
")",
"delete",
"(",
"id",
")",
"if",
"id",
".",
"is_a?",
"(",
"String",
")",
"or",
"id",
".",
"is_a?",
"(",
"Symbol",
")",
"@writer",
".",
"commit",
"else",
"ensure_writer_open",
"(",
")",
"end",
"@writer",
"<<",
"new_doc",
"flush",
"(",
")",
"if",
"@auto_flush",
"end",
"end"
] | Update the document referenced by the document number +id+ if +id+ is an
integer or all of the documents which have the term +id+ if +id+ is a
term..
For batch update of set of documents, for performance reasons, see batch_update
id:: The number of the document to update. Can also be a string
representing the value in the +id+ field. Also consider using
the :key attribute.
new_doc:: The document to replace the old document with | [
"Update",
"the",
"document",
"referenced",
"by",
"the",
"document",
"number",
"+",
"id",
"+",
"if",
"+",
"id",
"+",
"is",
"an",
"integer",
"or",
"all",
"of",
"the",
"documents",
"which",
"have",
"the",
"term",
"+",
"id",
"+",
"if",
"+",
"id",
"+",
"is",
"a",
"term",
"..",
"For",
"batch",
"update",
"of",
"set",
"of",
"documents",
"for",
"performance",
"reasons",
"see",
"batch_update"
] | 2451bc48c3aa162cbb87659b0f460b7821590cd1 | https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L569-L581 | train |
dbalmain/ferret | ruby/lib/ferret/index.rb | Ferret::Index.Index.batch_update | def batch_update(docs)
@dir.synchronize do
ids = nil
case docs
when Array
ids = docs.collect{|doc| doc[@id_field].to_s}
if ids.include?(nil)
raise ArgumentError, "all documents must have an #{@id_field} "
"field when doing a batch update"
end
when Hash
ids = docs.keys
docs = docs.values
else
raise ArgumentError, "must pass Hash or Array, not #{docs.class}"
end
batch_delete(ids)
ensure_writer_open()
docs.each {|new_doc| @writer << new_doc }
flush()
end
end | ruby | def batch_update(docs)
@dir.synchronize do
ids = nil
case docs
when Array
ids = docs.collect{|doc| doc[@id_field].to_s}
if ids.include?(nil)
raise ArgumentError, "all documents must have an #{@id_field} "
"field when doing a batch update"
end
when Hash
ids = docs.keys
docs = docs.values
else
raise ArgumentError, "must pass Hash or Array, not #{docs.class}"
end
batch_delete(ids)
ensure_writer_open()
docs.each {|new_doc| @writer << new_doc }
flush()
end
end | [
"def",
"batch_update",
"(",
"docs",
")",
"@dir",
".",
"synchronize",
"do",
"ids",
"=",
"nil",
"case",
"docs",
"when",
"Array",
"ids",
"=",
"docs",
".",
"collect",
"{",
"|",
"doc",
"|",
"doc",
"[",
"@id_field",
"]",
".",
"to_s",
"}",
"if",
"ids",
".",
"include?",
"(",
"nil",
")",
"raise",
"ArgumentError",
",",
"\"all documents must have an #{@id_field} \"",
"\"field when doing a batch update\"",
"end",
"when",
"Hash",
"ids",
"=",
"docs",
".",
"keys",
"docs",
"=",
"docs",
".",
"values",
"else",
"raise",
"ArgumentError",
",",
"\"must pass Hash or Array, not #{docs.class}\"",
"end",
"batch_delete",
"(",
"ids",
")",
"ensure_writer_open",
"(",
")",
"docs",
".",
"each",
"{",
"|",
"new_doc",
"|",
"@writer",
"<<",
"new_doc",
"}",
"flush",
"(",
")",
"end",
"end"
] | Batch updates the documents in an index. You can pass either a Hash or
an Array.
=== Array (recommended)
If you pass an Array then each value needs to be a Document or a Hash
and each of those documents must have an +:id_field+ which will be used
to delete the old document that this document is replacing.
=== Hash
If you pass a Hash then the keys of the Hash will be considered the
+id+'s and the values will be the new documents to replace the old ones
with.If the +id+ is an Integer then it is considered a Ferret document
number and the corresponding document will be deleted. If the +id+ is a
String or a Symbol then the +id+ will be considered a term and the
documents that contain that term in the +:id_field+ will be deleted.
Note: No error will be raised if the document does not currently
exist. A new document will simply be created.
== Examples
# will replace the documents with the +id+'s id:133 and id:254
@index.batch_update({
'133' => {:id => '133', :content => 'yada yada yada'},
'253' => {:id => '253', :content => 'bla bla bal'}
})
# will replace the documents with the Ferret Document numbers 2 and 92
@index.batch_update({
2 => {:id => '133', :content => 'yada yada yada'},
92 => {:id => '253', :content => 'bla bla bal'}
})
# will replace the documents with the +id+'s id:133 and id:254
# this is recommended as it guarantees no duplicate keys
@index.batch_update([
{:id => '133', :content => 'yada yada yada'},
{:id => '253', :content => 'bla bla bal'}
])
docs:: A Hash of id/document pairs. The set of documents to be updated | [
"Batch",
"updates",
"the",
"documents",
"in",
"an",
"index",
".",
"You",
"can",
"pass",
"either",
"a",
"Hash",
"or",
"an",
"Array",
"."
] | 2451bc48c3aa162cbb87659b0f460b7821590cd1 | https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L626-L647 | train |
dbalmain/ferret | ruby/lib/ferret/index.rb | Ferret::Index.Index.query_update | def query_update(query, new_val)
@dir.synchronize do
ensure_writer_open()
ensure_searcher_open()
docs_to_add = []
query = do_process_query(query)
@searcher.search_each(query, :limit => :all) do |id, score|
document = @searcher[id].load
if new_val.is_a?(Hash)
document.merge!(new_val)
else new_val.is_a?(String) or new_val.is_a?(Symbol)
document[@default_input_field] = new_val.to_s
end
docs_to_add << document
@reader.delete(id)
end
ensure_writer_open()
docs_to_add.each {|doc| @writer << doc }
flush() if @auto_flush
end
end | ruby | def query_update(query, new_val)
@dir.synchronize do
ensure_writer_open()
ensure_searcher_open()
docs_to_add = []
query = do_process_query(query)
@searcher.search_each(query, :limit => :all) do |id, score|
document = @searcher[id].load
if new_val.is_a?(Hash)
document.merge!(new_val)
else new_val.is_a?(String) or new_val.is_a?(Symbol)
document[@default_input_field] = new_val.to_s
end
docs_to_add << document
@reader.delete(id)
end
ensure_writer_open()
docs_to_add.each {|doc| @writer << doc }
flush() if @auto_flush
end
end | [
"def",
"query_update",
"(",
"query",
",",
"new_val",
")",
"@dir",
".",
"synchronize",
"do",
"ensure_writer_open",
"(",
")",
"ensure_searcher_open",
"(",
")",
"docs_to_add",
"=",
"[",
"]",
"query",
"=",
"do_process_query",
"(",
"query",
")",
"@searcher",
".",
"search_each",
"(",
"query",
",",
":limit",
"=>",
":all",
")",
"do",
"|",
"id",
",",
"score",
"|",
"document",
"=",
"@searcher",
"[",
"id",
"]",
".",
"load",
"if",
"new_val",
".",
"is_a?",
"(",
"Hash",
")",
"document",
".",
"merge!",
"(",
"new_val",
")",
"else",
"new_val",
".",
"is_a?",
"(",
"String",
")",
"or",
"new_val",
".",
"is_a?",
"(",
"Symbol",
")",
"document",
"[",
"@default_input_field",
"]",
"=",
"new_val",
".",
"to_s",
"end",
"docs_to_add",
"<<",
"document",
"@reader",
".",
"delete",
"(",
"id",
")",
"end",
"ensure_writer_open",
"(",
")",
"docs_to_add",
".",
"each",
"{",
"|",
"doc",
"|",
"@writer",
"<<",
"doc",
"}",
"flush",
"(",
")",
"if",
"@auto_flush",
"end",
"end"
] | Update all the documents returned by the query.
query:: The query to find documents you wish to update. Can either be
a string (in which case it is parsed by the standard query
parser) or an actual query object.
new_val:: The values we are updating. This can be a string in which case
the default field is updated, or it can be a hash, in which
case, all fields in the hash are merged into the old hash.
That is, the old fields are replaced by values in the new hash
if they exist.
=== Example
index << {:id => "26", :title => "Babylon", :artist => "David Grey"}
index << {:id => "29", :title => "My Oh My", :artist => "David Grey"}
# correct
index.query_update('artist:"David Grey"', {:artist => "David Gray"})
index["26"]
#=> {:id => "26", :title => "Babylon", :artist => "David Gray"}
index["28"]
#=> {:id => "28", :title => "My Oh My", :artist => "David Gray"} | [
"Update",
"all",
"the",
"documents",
"returned",
"by",
"the",
"query",
"."
] | 2451bc48c3aa162cbb87659b0f460b7821590cd1 | https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L674-L694 | train |
dbalmain/ferret | ruby/lib/ferret/index.rb | Ferret::Index.Index.explain | def explain(query, doc)
@dir.synchronize do
ensure_searcher_open()
query = do_process_query(query)
return @searcher.explain(query, doc)
end
end | ruby | def explain(query, doc)
@dir.synchronize do
ensure_searcher_open()
query = do_process_query(query)
return @searcher.explain(query, doc)
end
end | [
"def",
"explain",
"(",
"query",
",",
"doc",
")",
"@dir",
".",
"synchronize",
"do",
"ensure_searcher_open",
"(",
")",
"query",
"=",
"do_process_query",
"(",
"query",
")",
"return",
"@searcher",
".",
"explain",
"(",
"query",
",",
"doc",
")",
"end",
"end"
] | Returns an Explanation that describes how +doc+ scored against
+query+.
This is intended to be used in developing Similarity implementations,
and, for good performance, should not be displayed with every hit.
Computing an explanation is as expensive as executing the query over the
entire index. | [
"Returns",
"an",
"Explanation",
"that",
"describes",
"how",
"+",
"doc",
"+",
"scored",
"against",
"+",
"query",
"+",
"."
] | 2451bc48c3aa162cbb87659b0f460b7821590cd1 | https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L823-L830 | train |
dbalmain/ferret | ruby/lib/ferret/index.rb | Ferret::Index.Index.ensure_reader_open | def ensure_reader_open(get_latest = true)
raise "tried to use a closed index" if not @open
if @reader
if get_latest
latest = false
begin
latest = @reader.latest?
rescue Lock::LockError
sleep(@options[:lock_retry_time]) # sleep for 2 seconds and try again
latest = @reader.latest?
end
if not latest
@searcher.close if @searcher
@reader.close
return @reader = IndexReader.new(@dir)
end
end
else
if @writer
@writer.close
@writer = nil
end
return @reader = IndexReader.new(@dir)
end
return false
end | ruby | def ensure_reader_open(get_latest = true)
raise "tried to use a closed index" if not @open
if @reader
if get_latest
latest = false
begin
latest = @reader.latest?
rescue Lock::LockError
sleep(@options[:lock_retry_time]) # sleep for 2 seconds and try again
latest = @reader.latest?
end
if not latest
@searcher.close if @searcher
@reader.close
return @reader = IndexReader.new(@dir)
end
end
else
if @writer
@writer.close
@writer = nil
end
return @reader = IndexReader.new(@dir)
end
return false
end | [
"def",
"ensure_reader_open",
"(",
"get_latest",
"=",
"true",
")",
"raise",
"\"tried to use a closed index\"",
"if",
"not",
"@open",
"if",
"@reader",
"if",
"get_latest",
"latest",
"=",
"false",
"begin",
"latest",
"=",
"@reader",
".",
"latest?",
"rescue",
"Lock",
"::",
"LockError",
"sleep",
"(",
"@options",
"[",
":lock_retry_time",
"]",
")",
"# sleep for 2 seconds and try again",
"latest",
"=",
"@reader",
".",
"latest?",
"end",
"if",
"not",
"latest",
"@searcher",
".",
"close",
"if",
"@searcher",
"@reader",
".",
"close",
"return",
"@reader",
"=",
"IndexReader",
".",
"new",
"(",
"@dir",
")",
"end",
"end",
"else",
"if",
"@writer",
"@writer",
".",
"close",
"@writer",
"=",
"nil",
"end",
"return",
"@reader",
"=",
"IndexReader",
".",
"new",
"(",
"@dir",
")",
"end",
"return",
"false",
"end"
] | returns the new reader if one is opened | [
"returns",
"the",
"new",
"reader",
"if",
"one",
"is",
"opened"
] | 2451bc48c3aa162cbb87659b0f460b7821590cd1 | https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L864-L889 | train |
dbalmain/ferret | ruby/lib/ferret/browser.rb | Ferret::Browser.ViewHelper.truncate | def truncate(str, len = 80)
if str and str.length > len and (add = str[len..-1].index(' '))
str = str[0, len + add] + '…'
end
str
end | ruby | def truncate(str, len = 80)
if str and str.length > len and (add = str[len..-1].index(' '))
str = str[0, len + add] + '…'
end
str
end | [
"def",
"truncate",
"(",
"str",
",",
"len",
"=",
"80",
")",
"if",
"str",
"and",
"str",
".",
"length",
">",
"len",
"and",
"(",
"add",
"=",
"str",
"[",
"len",
"..",
"-",
"1",
"]",
".",
"index",
"(",
"' '",
")",
")",
"str",
"=",
"str",
"[",
"0",
",",
"len",
"+",
"add",
"]",
"+",
"'…'",
"end",
"str",
"end"
] | truncates the string at the first space after +len+ characters | [
"truncates",
"the",
"string",
"at",
"the",
"first",
"space",
"after",
"+",
"len",
"+",
"characters"
] | 2451bc48c3aa162cbb87659b0f460b7821590cd1 | https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/browser.rb#L72-L77 | train |
dbalmain/ferret | ruby/lib/ferret/browser.rb | Ferret::Browser.Controller.paginate | def paginate(idx, max, url, &b)
return '' if max == 0
url = url.gsub(%r{^/?(.*?)/?$}, '\1')
b ||= lambda{}
link = lambda {|*args|
i, title, text = args
"<a href=\"/#{url}/#{i}#{'?' + @query_string if @query_string}\" " +
"#{'onclick="return false;"' if (i == idx)} " +
"class=\"#{'disabled ' if (i == idx)}#{b.call(i)}\" " +
"title=\"#{title||"Go to page #{i}"}\">#{text||i}</a>"
}
res = '<div class="nav">'
if (idx > 0)
res << link.call(idx - 1, "Go to previous page", "« Previous")
else
res << "<a href=\"/#{url}/0\" onclick=\"return false;\" " +
"class=\"disabled\" title=\"Disabled\">« Previous</a>"
end
if idx < 10
idx.times {|i| res << link.call(i)}
else
(0..2).each {|i| res << link.call(i)}
res << ' … '
((idx-4)...idx).each {|i| res << link.call(i)}
end
res << link.call(idx, 'Current Page')
if idx > (max - 10)
((idx+1)...max).each {|i| res << link.call(i)}
else
((idx+1)..(idx+4)).each {|i| res << link.call(i)}
res << ' … '
((max-3)...max).each {|i| res << link.call(i)}
end
if (idx < (max - 1))
res << link.call(idx + 1, "Go to next page", "Next »")
else
res << "<a href=\"/#{url}/#{max-1}\" onclick=\"return false;\" " +
"class=\"disabled\" title=\"Disabled\"}\">Next »</a>"
end
res << '</div>'
end | ruby | def paginate(idx, max, url, &b)
return '' if max == 0
url = url.gsub(%r{^/?(.*?)/?$}, '\1')
b ||= lambda{}
link = lambda {|*args|
i, title, text = args
"<a href=\"/#{url}/#{i}#{'?' + @query_string if @query_string}\" " +
"#{'onclick="return false;"' if (i == idx)} " +
"class=\"#{'disabled ' if (i == idx)}#{b.call(i)}\" " +
"title=\"#{title||"Go to page #{i}"}\">#{text||i}</a>"
}
res = '<div class="nav">'
if (idx > 0)
res << link.call(idx - 1, "Go to previous page", "« Previous")
else
res << "<a href=\"/#{url}/0\" onclick=\"return false;\" " +
"class=\"disabled\" title=\"Disabled\">« Previous</a>"
end
if idx < 10
idx.times {|i| res << link.call(i)}
else
(0..2).each {|i| res << link.call(i)}
res << ' … '
((idx-4)...idx).each {|i| res << link.call(i)}
end
res << link.call(idx, 'Current Page')
if idx > (max - 10)
((idx+1)...max).each {|i| res << link.call(i)}
else
((idx+1)..(idx+4)).each {|i| res << link.call(i)}
res << ' … '
((max-3)...max).each {|i| res << link.call(i)}
end
if (idx < (max - 1))
res << link.call(idx + 1, "Go to next page", "Next »")
else
res << "<a href=\"/#{url}/#{max-1}\" onclick=\"return false;\" " +
"class=\"disabled\" title=\"Disabled\"}\">Next »</a>"
end
res << '</div>'
end | [
"def",
"paginate",
"(",
"idx",
",",
"max",
",",
"url",
",",
"&",
"b",
")",
"return",
"''",
"if",
"max",
"==",
"0",
"url",
"=",
"url",
".",
"gsub",
"(",
"%r{",
"}",
",",
"'\\1'",
")",
"b",
"||=",
"lambda",
"{",
"}",
"link",
"=",
"lambda",
"{",
"|",
"*",
"args",
"|",
"i",
",",
"title",
",",
"text",
"=",
"args",
"\"<a href=\\\"/#{url}/#{i}#{'?' + @query_string if @query_string}\\\" \"",
"+",
"\"#{'onclick=\"return false;\"' if (i == idx)} \"",
"+",
"\"class=\\\"#{'disabled ' if (i == idx)}#{b.call(i)}\\\" \"",
"+",
"\"title=\\\"#{title||\"Go to page #{i}\"}\\\">#{text||i}</a>\"",
"}",
"res",
"=",
"'<div class=\"nav\">'",
"if",
"(",
"idx",
">",
"0",
")",
"res",
"<<",
"link",
".",
"call",
"(",
"idx",
"-",
"1",
",",
"\"Go to previous page\"",
",",
"\"« Previous\"",
")",
"else",
"res",
"<<",
"\"<a href=\\\"/#{url}/0\\\" onclick=\\\"return false;\\\" \"",
"+",
"\"class=\\\"disabled\\\" title=\\\"Disabled\\\">« Previous</a>\"",
"end",
"if",
"idx",
"<",
"10",
"idx",
".",
"times",
"{",
"|",
"i",
"|",
"res",
"<<",
"link",
".",
"call",
"(",
"i",
")",
"}",
"else",
"(",
"0",
"..",
"2",
")",
".",
"each",
"{",
"|",
"i",
"|",
"res",
"<<",
"link",
".",
"call",
"(",
"i",
")",
"}",
"res",
"<<",
"' … '",
"(",
"(",
"idx",
"-",
"4",
")",
"...",
"idx",
")",
".",
"each",
"{",
"|",
"i",
"|",
"res",
"<<",
"link",
".",
"call",
"(",
"i",
")",
"}",
"end",
"res",
"<<",
"link",
".",
"call",
"(",
"idx",
",",
"'Current Page'",
")",
"if",
"idx",
">",
"(",
"max",
"-",
"10",
")",
"(",
"(",
"idx",
"+",
"1",
")",
"...",
"max",
")",
".",
"each",
"{",
"|",
"i",
"|",
"res",
"<<",
"link",
".",
"call",
"(",
"i",
")",
"}",
"else",
"(",
"(",
"idx",
"+",
"1",
")",
"..",
"(",
"idx",
"+",
"4",
")",
")",
".",
"each",
"{",
"|",
"i",
"|",
"res",
"<<",
"link",
".",
"call",
"(",
"i",
")",
"}",
"res",
"<<",
"' … '",
"(",
"(",
"max",
"-",
"3",
")",
"...",
"max",
")",
".",
"each",
"{",
"|",
"i",
"|",
"res",
"<<",
"link",
".",
"call",
"(",
"i",
")",
"}",
"end",
"if",
"(",
"idx",
"<",
"(",
"max",
"-",
"1",
")",
")",
"res",
"<<",
"link",
".",
"call",
"(",
"idx",
"+",
"1",
",",
"\"Go to next page\"",
",",
"\"Next »\"",
")",
"else",
"res",
"<<",
"\"<a href=\\\"/#{url}/#{max-1}\\\" onclick=\\\"return false;\\\" \"",
"+",
"\"class=\\\"disabled\\\" title=\\\"Disabled\\\"}\\\">Next »</a>\"",
"end",
"res",
"<<",
"'</div>'",
"end"
] | takes an optional block to set optional attributes in the links | [
"takes",
"an",
"optional",
"block",
"to",
"set",
"optional",
"attributes",
"in",
"the",
"links"
] | 2451bc48c3aa162cbb87659b0f460b7821590cd1 | https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/browser.rb#L126-L166 | train |
clbustos/rubyvis | lib/rubyvis/scene/svg_curve.rb | Rubyvis::SvgScene.PathBasis.weight | def weight(w)
OpenStruct.new({
:x=> w[0] * p0.left + w[1] * p1.left + w[2] * p2.left + w[3] * p3.left,
:y=> w[0] * p0.top + w[1] * p1.top + w[2] * p2.top + w[3] * p3.top
})
end | ruby | def weight(w)
OpenStruct.new({
:x=> w[0] * p0.left + w[1] * p1.left + w[2] * p2.left + w[3] * p3.left,
:y=> w[0] * p0.top + w[1] * p1.top + w[2] * p2.top + w[3] * p3.top
})
end | [
"def",
"weight",
"(",
"w",
")",
"OpenStruct",
".",
"new",
"(",
"{",
":x",
"=>",
"w",
"[",
"0",
"]",
"*",
"p0",
".",
"left",
"+",
"w",
"[",
"1",
"]",
"*",
"p1",
".",
"left",
"+",
"w",
"[",
"2",
"]",
"*",
"p2",
".",
"left",
"+",
"w",
"[",
"3",
"]",
"*",
"p3",
".",
"left",
",",
":y",
"=>",
"w",
"[",
"0",
"]",
"*",
"p0",
".",
"top",
"+",
"w",
"[",
"1",
"]",
"*",
"p1",
".",
"top",
"+",
"w",
"[",
"2",
"]",
"*",
"p2",
".",
"top",
"+",
"w",
"[",
"3",
"]",
"*",
"p3",
".",
"top",
"}",
")",
"end"
] | Returns the point that is the weighted sum of the specified control points,
using the specified weights. This method requires that there are four
weights and four control points. | [
"Returns",
"the",
"point",
"that",
"is",
"the",
"weighted",
"sum",
"of",
"the",
"specified",
"control",
"points",
"using",
"the",
"specified",
"weights",
".",
"This",
"method",
"requires",
"that",
"there",
"are",
"four",
"weights",
"and",
"four",
"control",
"points",
"."
] | 59f5e76f1c352d68dd8f471f77a441ac9aaf784b | https://github.com/clbustos/rubyvis/blob/59f5e76f1c352d68dd8f471f77a441ac9aaf784b/lib/rubyvis/scene/svg_curve.rb#L27-L32 | train |
dejan/espeak-ruby | lib/espeak/speech.rb | ESpeak.Speech.save | def save(filename)
speech = bytes_wav
res = IO.popen(lame_command(filename, command_options), 'r+') do |process|
process.write(speech)
process.close_write
process.read
end
res.to_s
end | ruby | def save(filename)
speech = bytes_wav
res = IO.popen(lame_command(filename, command_options), 'r+') do |process|
process.write(speech)
process.close_write
process.read
end
res.to_s
end | [
"def",
"save",
"(",
"filename",
")",
"speech",
"=",
"bytes_wav",
"res",
"=",
"IO",
".",
"popen",
"(",
"lame_command",
"(",
"filename",
",",
"command_options",
")",
",",
"'r+'",
")",
"do",
"|",
"process",
"|",
"process",
".",
"write",
"(",
"speech",
")",
"process",
".",
"close_write",
"process",
".",
"read",
"end",
"res",
".",
"to_s",
"end"
] | Generates mp3 file as a result of
Text-To-Speech conversion. | [
"Generates",
"mp3",
"file",
"as",
"a",
"result",
"of",
"Text",
"-",
"To",
"-",
"Speech",
"conversion",
"."
] | 96602f68615f9c8c4f5aea58a747de7c69798097 | https://github.com/dejan/espeak-ruby/blob/96602f68615f9c8c4f5aea58a747de7c69798097/lib/espeak/speech.rb#L30-L38 | train |
dejan/espeak-ruby | lib/espeak/speech.rb | ESpeak.Speech.bytes | def bytes()
speech = bytes_wav
res = IO.popen(std_lame_command(command_options), 'r+') do |process|
process.write(speech)
process.close_write
process.read
end
res.to_s
end | ruby | def bytes()
speech = bytes_wav
res = IO.popen(std_lame_command(command_options), 'r+') do |process|
process.write(speech)
process.close_write
process.read
end
res.to_s
end | [
"def",
"bytes",
"(",
")",
"speech",
"=",
"bytes_wav",
"res",
"=",
"IO",
".",
"popen",
"(",
"std_lame_command",
"(",
"command_options",
")",
",",
"'r+'",
")",
"do",
"|",
"process",
"|",
"process",
".",
"write",
"(",
"speech",
")",
"process",
".",
"close_write",
"process",
".",
"read",
"end",
"res",
".",
"to_s",
"end"
] | Returns mp3 file bytes as a result of
Text-To-Speech conversion. | [
"Returns",
"mp3",
"file",
"bytes",
"as",
"a",
"result",
"of",
"Text",
"-",
"To",
"-",
"Speech",
"conversion",
"."
] | 96602f68615f9c8c4f5aea58a747de7c69798097 | https://github.com/dejan/espeak-ruby/blob/96602f68615f9c8c4f5aea58a747de7c69798097/lib/espeak/speech.rb#L43-L51 | train |
clbustos/rubyvis | lib/rubyvis/flatten.rb | Rubyvis.Flatten.array | def array
@entries=[]
@stack=[]
if @leaf
recurse(@map,0)
return @entries
end
visit(@map,0)
@entries.map {|stack|
m={}
@keys.each_with_index {|k,i|
v=stack[i]
m[k.name]=k.value ? k.value.js_call(self,v) : v
}
m
}
end | ruby | def array
@entries=[]
@stack=[]
if @leaf
recurse(@map,0)
return @entries
end
visit(@map,0)
@entries.map {|stack|
m={}
@keys.each_with_index {|k,i|
v=stack[i]
m[k.name]=k.value ? k.value.js_call(self,v) : v
}
m
}
end | [
"def",
"array",
"@entries",
"=",
"[",
"]",
"@stack",
"=",
"[",
"]",
"if",
"@leaf",
"recurse",
"(",
"@map",
",",
"0",
")",
"return",
"@entries",
"end",
"visit",
"(",
"@map",
",",
"0",
")",
"@entries",
".",
"map",
"{",
"|",
"stack",
"|",
"m",
"=",
"{",
"}",
"@keys",
".",
"each_with_index",
"{",
"|",
"k",
",",
"i",
"|",
"v",
"=",
"stack",
"[",
"i",
"]",
"m",
"[",
"k",
".",
"name",
"]",
"=",
"k",
".",
"value",
"?",
"k",
".",
"value",
".",
"js_call",
"(",
"self",
",",
"v",
")",
":",
"v",
"}",
"m",
"}",
"end"
] | Returns the flattened array. Each entry in the array is an object; each
object has attributes corresponding to this flatten operator's keys.
@returns an array of elements from the flattened map. | [
"Returns",
"the",
"flattened",
"array",
".",
"Each",
"entry",
"in",
"the",
"array",
"is",
"an",
"object",
";",
"each",
"object",
"has",
"attributes",
"corresponding",
"to",
"this",
"flatten",
"operator",
"s",
"keys",
"."
] | 59f5e76f1c352d68dd8f471f77a441ac9aaf784b | https://github.com/clbustos/rubyvis/blob/59f5e76f1c352d68dd8f471f77a441ac9aaf784b/lib/rubyvis/flatten.rb#L107-L123 | train |
clbustos/rubyvis | lib/rubyvis/mark/image.rb | Rubyvis.Image.bind | def bind
mark_bind
bind=self.binds
mark=self
begin
binds.image = mark._image
end while(!binds.image and (mark==mark.proto))
end | ruby | def bind
mark_bind
bind=self.binds
mark=self
begin
binds.image = mark._image
end while(!binds.image and (mark==mark.proto))
end | [
"def",
"bind",
"mark_bind",
"bind",
"=",
"self",
".",
"binds",
"mark",
"=",
"self",
"begin",
"binds",
".",
"image",
"=",
"mark",
".",
"_image",
"end",
"while",
"(",
"!",
"binds",
".",
"image",
"and",
"(",
"mark",
"==",
"mark",
".",
"proto",
")",
")",
"end"
] | Scan the proto chain for an image function. | [
"Scan",
"the",
"proto",
"chain",
"for",
"an",
"image",
"function",
"."
] | 59f5e76f1c352d68dd8f471f77a441ac9aaf784b | https://github.com/clbustos/rubyvis/blob/59f5e76f1c352d68dd8f471f77a441ac9aaf784b/lib/rubyvis/mark/image.rb#L74-L81 | train |
clbustos/rubyvis | lib/rubyvis/scale/quantitative.rb | Rubyvis.Scale::Quantitative.scale | def scale(x)
return nil if x.nil?
x=x.to_f
j=Rubyvis.search(@d, x)
j=-j-2 if (j<0)
j=[0,[@i.size-1,j].min].max
# p @l
# puts "Primero #{j}: #{@f.call(x) - @l[j]}"
# puts "Segundo #{(@l[j + 1] - @l[j])}"
@i[j].call((@f.call(x) - @l[j]) .quo(@l[j + 1] - @l[j]));
end | ruby | def scale(x)
return nil if x.nil?
x=x.to_f
j=Rubyvis.search(@d, x)
j=-j-2 if (j<0)
j=[0,[@i.size-1,j].min].max
# p @l
# puts "Primero #{j}: #{@f.call(x) - @l[j]}"
# puts "Segundo #{(@l[j + 1] - @l[j])}"
@i[j].call((@f.call(x) - @l[j]) .quo(@l[j + 1] - @l[j]));
end | [
"def",
"scale",
"(",
"x",
")",
"return",
"nil",
"if",
"x",
".",
"nil?",
"x",
"=",
"x",
".",
"to_f",
"j",
"=",
"Rubyvis",
".",
"search",
"(",
"@d",
",",
"x",
")",
"j",
"=",
"-",
"j",
"-",
"2",
"if",
"(",
"j",
"<",
"0",
")",
"j",
"=",
"[",
"0",
",",
"[",
"@i",
".",
"size",
"-",
"1",
",",
"j",
"]",
".",
"min",
"]",
".",
"max",
"# p @l",
"# puts \"Primero #{j}: #{@f.call(x) - @l[j]}\"",
"# puts \"Segundo #{(@l[j + 1] - @l[j])}\"",
"@i",
"[",
"j",
"]",
".",
"call",
"(",
"(",
"@f",
".",
"call",
"(",
"x",
")",
"-",
"@l",
"[",
"j",
"]",
")",
".",
"quo",
"(",
"@l",
"[",
"j",
"+",
"1",
"]",
"-",
"@l",
"[",
"j",
"]",
")",
")",
";",
"end"
] | Transform value +x+ according to domain and range | [
"Transform",
"value",
"+",
"x",
"+",
"according",
"to",
"domain",
"and",
"range"
] | 59f5e76f1c352d68dd8f471f77a441ac9aaf784b | https://github.com/clbustos/rubyvis/blob/59f5e76f1c352d68dd8f471f77a441ac9aaf784b/lib/rubyvis/scale/quantitative.rb#L94-L104 | train |
clbustos/rubyvis | lib/rubyvis/scale/log.rb | Rubyvis.Scale::Log.ticks | def ticks(subdivisions=nil)
d = domain
n = d[0] < 0
subdivisions||=@b
[email protected]_f / subdivisions
# puts "dom: #{d[0]} -> #{n}"
i = (n ? -log(-d[0]) : log(d[0])).floor
j = (n ? -log(-d[1]) : log(d[1])).ceil
ticks = [];
if n
ticks.push(-pow(-i))
(i..j).each {|ii|
((@b-1)...0).each {|k|
ticks.push(-pow(-ii) * k)
}
}
else
(i...j).each {|ii|
(1..subdivisions).each {|k|
if k==1
ticks.push(pow(ii))
else
next if subdivisions==@b and k==2
ticks.push(pow(ii)*span*(k-1))
end
}
}
ticks.push(pow(j));
end
# for (i = 0; ticks[i] < d[0]; i++); // strip small values
# for (j = ticks.length; ticks[j - 1] > d[1]; j--); // strip big values
# return ticks.slice(i, j);
ticks.find_all {|v| v>=d[0] and v<=d[1]}
end | ruby | def ticks(subdivisions=nil)
d = domain
n = d[0] < 0
subdivisions||=@b
[email protected]_f / subdivisions
# puts "dom: #{d[0]} -> #{n}"
i = (n ? -log(-d[0]) : log(d[0])).floor
j = (n ? -log(-d[1]) : log(d[1])).ceil
ticks = [];
if n
ticks.push(-pow(-i))
(i..j).each {|ii|
((@b-1)...0).each {|k|
ticks.push(-pow(-ii) * k)
}
}
else
(i...j).each {|ii|
(1..subdivisions).each {|k|
if k==1
ticks.push(pow(ii))
else
next if subdivisions==@b and k==2
ticks.push(pow(ii)*span*(k-1))
end
}
}
ticks.push(pow(j));
end
# for (i = 0; ticks[i] < d[0]; i++); // strip small values
# for (j = ticks.length; ticks[j - 1] > d[1]; j--); // strip big values
# return ticks.slice(i, j);
ticks.find_all {|v| v>=d[0] and v<=d[1]}
end | [
"def",
"ticks",
"(",
"subdivisions",
"=",
"nil",
")",
"d",
"=",
"domain",
"n",
"=",
"d",
"[",
"0",
"]",
"<",
"0",
"subdivisions",
"||=",
"@b",
"span",
"=",
"@b",
".",
"to_f",
"/",
"subdivisions",
"# puts \"dom: #{d[0]} -> #{n}\"",
"i",
"=",
"(",
"n",
"?",
"-",
"log",
"(",
"-",
"d",
"[",
"0",
"]",
")",
":",
"log",
"(",
"d",
"[",
"0",
"]",
")",
")",
".",
"floor",
"j",
"=",
"(",
"n",
"?",
"-",
"log",
"(",
"-",
"d",
"[",
"1",
"]",
")",
":",
"log",
"(",
"d",
"[",
"1",
"]",
")",
")",
".",
"ceil",
"ticks",
"=",
"[",
"]",
";",
"if",
"n",
"ticks",
".",
"push",
"(",
"-",
"pow",
"(",
"-",
"i",
")",
")",
"(",
"i",
"..",
"j",
")",
".",
"each",
"{",
"|",
"ii",
"|",
"(",
"(",
"@b",
"-",
"1",
")",
"...",
"0",
")",
".",
"each",
"{",
"|",
"k",
"|",
"ticks",
".",
"push",
"(",
"-",
"pow",
"(",
"-",
"ii",
")",
"*",
"k",
")",
"}",
"}",
"else",
"(",
"i",
"...",
"j",
")",
".",
"each",
"{",
"|",
"ii",
"|",
"(",
"1",
"..",
"subdivisions",
")",
".",
"each",
"{",
"|",
"k",
"|",
"if",
"k",
"==",
"1",
"ticks",
".",
"push",
"(",
"pow",
"(",
"ii",
")",
")",
"else",
"next",
"if",
"subdivisions",
"==",
"@b",
"and",
"k",
"==",
"2",
"ticks",
".",
"push",
"(",
"pow",
"(",
"ii",
")",
"*",
"span",
"(",
"k",
"-",
"1",
")",
")",
"end",
"}",
"}",
"ticks",
".",
"push",
"(",
"pow",
"(",
"j",
")",
")",
";",
"end",
"# for (i = 0; ticks[i] < d[0]; i++); // strip small values",
"# for (j = ticks.length; ticks[j - 1] > d[1]; j--); // strip big values",
"# return ticks.slice(i, j);",
"ticks",
".",
"find_all",
"{",
"|",
"v",
"|",
"v",
">=",
"d",
"[",
"0",
"]",
"and",
"v",
"<=",
"d",
"[",
"1",
"]",
"}",
"end"
] | Returns an array of evenly-spaced, suitably-rounded values in the input
domain. These values are frequently used in conjunction with
Rule to display tick marks or grid lines.
Subdivisions set the number of division inside each base^x
By default, is set to base | [
"Returns",
"an",
"array",
"of",
"evenly",
"-",
"spaced",
"suitably",
"-",
"rounded",
"values",
"in",
"the",
"input",
"domain",
".",
"These",
"values",
"are",
"frequently",
"used",
"in",
"conjunction",
"with",
"Rule",
"to",
"display",
"tick",
"marks",
"or",
"grid",
"lines",
"."
] | 59f5e76f1c352d68dd8f471f77a441ac9aaf784b | https://github.com/clbustos/rubyvis/blob/59f5e76f1c352d68dd8f471f77a441ac9aaf784b/lib/rubyvis/scale/log.rb#L36-L71 | train |
motion-kit/motion-kit | lib/motion-kit/helpers/parent.rb | MotionKit.Parent.try | def try(*method_chain)
obj = self.element
method_chain.each do |m|
# We'll break out and return nil if any part of the chain
# doesn't respond properly.
(obj = nil) && break unless obj.respond_to?(m)
obj = obj.send(m)
end
obj
end | ruby | def try(*method_chain)
obj = self.element
method_chain.each do |m|
# We'll break out and return nil if any part of the chain
# doesn't respond properly.
(obj = nil) && break unless obj.respond_to?(m)
obj = obj.send(m)
end
obj
end | [
"def",
"try",
"(",
"*",
"method_chain",
")",
"obj",
"=",
"self",
".",
"element",
"method_chain",
".",
"each",
"do",
"|",
"m",
"|",
"# We'll break out and return nil if any part of the chain",
"# doesn't respond properly.",
"(",
"obj",
"=",
"nil",
")",
"&&",
"break",
"unless",
"obj",
".",
"respond_to?",
"(",
"m",
")",
"obj",
"=",
"obj",
".",
"send",
"(",
"m",
")",
"end",
"obj",
"end"
] | Convenience method that takes a list of method calls and tries
them end-to-end, returning nil if any fail to respond to that
method name.
Very similar to ActiveSupport's `.try` method. | [
"Convenience",
"method",
"that",
"takes",
"a",
"list",
"of",
"method",
"calls",
"and",
"tries",
"them",
"end",
"-",
"to",
"-",
"end",
"returning",
"nil",
"if",
"any",
"fail",
"to",
"respond",
"to",
"that",
"method",
"name",
".",
"Very",
"similar",
"to",
"ActiveSupport",
"s",
".",
"try",
"method",
"."
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/parent.rb#L59-L68 | train |
motion-kit/motion-kit | lib/motion-kit/helpers/base_layout_class_methods.rb | MotionKit.BaseLayoutClassMethods.memoize | def memoize(klass)
@memoize ||= {}
@memoize[klass] ||= begin
while klass
break if registered_class = target_klasses[klass]
klass = klass.superclass
end
@memoize[klass] = registered_class if registered_class
end
@memoize[klass]
end | ruby | def memoize(klass)
@memoize ||= {}
@memoize[klass] ||= begin
while klass
break if registered_class = target_klasses[klass]
klass = klass.superclass
end
@memoize[klass] = registered_class if registered_class
end
@memoize[klass]
end | [
"def",
"memoize",
"(",
"klass",
")",
"@memoize",
"||=",
"{",
"}",
"@memoize",
"[",
"klass",
"]",
"||=",
"begin",
"while",
"klass",
"break",
"if",
"registered_class",
"=",
"target_klasses",
"[",
"klass",
"]",
"klass",
"=",
"klass",
".",
"superclass",
"end",
"@memoize",
"[",
"klass",
"]",
"=",
"registered_class",
"if",
"registered_class",
"end",
"@memoize",
"[",
"klass",
"]",
"end"
] | Cache registered classes | [
"Cache",
"registered",
"classes"
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/base_layout_class_methods.rb#L31-L41 | train |
motion-kit/motion-kit | lib/motion-kit/helpers/tree_layout.rb | MotionKit.TreeLayout.create | def create(element, element_id=nil, &block)
element = initialize_element(element, element_id)
style_and_context(element, element_id, &block)
element
end | ruby | def create(element, element_id=nil, &block)
element = initialize_element(element, element_id)
style_and_context(element, element_id, &block)
element
end | [
"def",
"create",
"(",
"element",
",",
"element_id",
"=",
"nil",
",",
"&",
"block",
")",
"element",
"=",
"initialize_element",
"(",
"element",
",",
"element_id",
")",
"style_and_context",
"(",
"element",
",",
"element_id",
",",
"block",
")",
"element",
"end"
] | instantiates a view, possibly running a 'layout block' to add child views. | [
"instantiates",
"a",
"view",
"possibly",
"running",
"a",
"layout",
"block",
"to",
"add",
"child",
"views",
"."
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L129-L134 | train |
motion-kit/motion-kit | lib/motion-kit/helpers/tree_layout.rb | MotionKit.TreeLayout.reapply | def reapply(&block)
raise ArgumentError.new('Block required') unless block
raise InvalidDeferredError.new('reapply must be run inside of a context') unless @context
if reapply?
yield
end
block = block.weak!
parent_layout.reapply_blocks << [@context, block]
return self
end | ruby | def reapply(&block)
raise ArgumentError.new('Block required') unless block
raise InvalidDeferredError.new('reapply must be run inside of a context') unless @context
if reapply?
yield
end
block = block.weak!
parent_layout.reapply_blocks << [@context, block]
return self
end | [
"def",
"reapply",
"(",
"&",
"block",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"'Block required'",
")",
"unless",
"block",
"raise",
"InvalidDeferredError",
".",
"new",
"(",
"'reapply must be run inside of a context'",
")",
"unless",
"@context",
"if",
"reapply?",
"yield",
"end",
"block",
"=",
"block",
".",
"weak!",
"parent_layout",
".",
"reapply_blocks",
"<<",
"[",
"@context",
",",
"block",
"]",
"return",
"self",
"end"
] | Blocks passed to `reapply` are only run when `reapply!` is called. | [
"Blocks",
"passed",
"to",
"reapply",
"are",
"only",
"run",
"when",
"reapply!",
"is",
"called",
"."
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L163-L174 | train |
motion-kit/motion-kit | lib/motion-kit/helpers/tree_layout.rb | MotionKit.TreeLayout.get_view | def get_view(element_id)
element = get(element_id)
if element.is_a?(Layout)
element = element.view
end
element
end | ruby | def get_view(element_id)
element = get(element_id)
if element.is_a?(Layout)
element = element.view
end
element
end | [
"def",
"get_view",
"(",
"element_id",
")",
"element",
"=",
"get",
"(",
"element_id",
")",
"if",
"element",
".",
"is_a?",
"(",
"Layout",
")",
"element",
"=",
"element",
".",
"view",
"end",
"element",
"end"
] | Just like `get`, but if `get` returns a Layout, this method returns the
layout's view. | [
"Just",
"like",
"get",
"but",
"if",
"get",
"returns",
"a",
"Layout",
"this",
"method",
"returns",
"the",
"layout",
"s",
"view",
"."
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L252-L258 | train |
motion-kit/motion-kit | lib/motion-kit/helpers/tree_layout.rb | MotionKit.TreeLayout.last_view | def last_view(element_id)
element = last(element_id)
if element.is_a?(Layout)
element = element.view
end
element
end | ruby | def last_view(element_id)
element = last(element_id)
if element.is_a?(Layout)
element = element.view
end
element
end | [
"def",
"last_view",
"(",
"element_id",
")",
"element",
"=",
"last",
"(",
"element_id",
")",
"if",
"element",
".",
"is_a?",
"(",
"Layout",
")",
"element",
"=",
"element",
".",
"view",
"end",
"element",
"end"
] | Just like `last`, but if `last` returns a Layout, this method returns the
layout's view. | [
"Just",
"like",
"last",
"but",
"if",
"last",
"returns",
"a",
"Layout",
"this",
"method",
"returns",
"the",
"layout",
"s",
"view",
"."
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L272-L278 | train |
motion-kit/motion-kit | lib/motion-kit/helpers/tree_layout.rb | MotionKit.TreeLayout.all_views | def all_views(element_id)
element = all(element_id)
if element.is_a?(Layout)
element = element.view
end
element
end | ruby | def all_views(element_id)
element = all(element_id)
if element.is_a?(Layout)
element = element.view
end
element
end | [
"def",
"all_views",
"(",
"element_id",
")",
"element",
"=",
"all",
"(",
"element_id",
")",
"if",
"element",
".",
"is_a?",
"(",
"Layout",
")",
"element",
"=",
"element",
".",
"view",
"end",
"element",
"end"
] | Just like `all`, but if `all` returns a Layout, this method returns the
layout's view. | [
"Just",
"like",
"all",
"but",
"if",
"all",
"returns",
"a",
"Layout",
"this",
"method",
"returns",
"the",
"layout",
"s",
"view",
"."
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L290-L296 | train |
motion-kit/motion-kit | lib/motion-kit/helpers/tree_layout.rb | MotionKit.TreeLayout.nth_view | def nth_view(element_id, index)
element = nth(element_id)
if element.is_a?(Layout)
element = element.view
end
element
end | ruby | def nth_view(element_id, index)
element = nth(element_id)
if element.is_a?(Layout)
element = element.view
end
element
end | [
"def",
"nth_view",
"(",
"element_id",
",",
"index",
")",
"element",
"=",
"nth",
"(",
"element_id",
")",
"if",
"element",
".",
"is_a?",
"(",
"Layout",
")",
"element",
"=",
"element",
".",
"view",
"end",
"element",
"end"
] | Just like `nth`, but if `nth` returns a Layout, this method returns the
layout's view. | [
"Just",
"like",
"nth",
"but",
"if",
"nth",
"returns",
"a",
"Layout",
"this",
"method",
"returns",
"the",
"layout",
"s",
"view",
"."
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L306-L312 | train |
motion-kit/motion-kit | lib/motion-kit/helpers/tree_layout.rb | MotionKit.TreeLayout.forget | def forget(element_id)
unless is_parent_layout?
return parent_layout.remove(element_id)
end
removed = nil
context(self.view) do
removed = all(element_id)
@elements[element_id] = nil
end
removed
end | ruby | def forget(element_id)
unless is_parent_layout?
return parent_layout.remove(element_id)
end
removed = nil
context(self.view) do
removed = all(element_id)
@elements[element_id] = nil
end
removed
end | [
"def",
"forget",
"(",
"element_id",
")",
"unless",
"is_parent_layout?",
"return",
"parent_layout",
".",
"remove",
"(",
"element_id",
")",
"end",
"removed",
"=",
"nil",
"context",
"(",
"self",
".",
"view",
")",
"do",
"removed",
"=",
"all",
"(",
"element_id",
")",
"@elements",
"[",
"element_id",
"]",
"=",
"nil",
"end",
"removed",
"end"
] | Removes a view from the list of elements this layout is "tracking", but
leaves it in the view hierarchy. Returns the views that were removed. | [
"Removes",
"a",
"view",
"from",
"the",
"list",
"of",
"elements",
"this",
"layout",
"is",
"tracking",
"but",
"leaves",
"it",
"in",
"the",
"view",
"hierarchy",
".",
"Returns",
"the",
"views",
"that",
"were",
"removed",
"."
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L450-L460 | train |
motion-kit/motion-kit | lib/motion-kit/helpers/tree_layout.rb | MotionKit.TreeLayout.forget_tree | def forget_tree(element_id, view)
removed = forget_view(element_id, view)
if view.subviews
view.subviews.each do | sub |
if (sub_ids = sub.motion_kit_meta[:motion_kit_ids])
sub_ids.each do | sub_id |
forget_tree(sub_id, sub) || []
end
end
end
end
removed
end | ruby | def forget_tree(element_id, view)
removed = forget_view(element_id, view)
if view.subviews
view.subviews.each do | sub |
if (sub_ids = sub.motion_kit_meta[:motion_kit_ids])
sub_ids.each do | sub_id |
forget_tree(sub_id, sub) || []
end
end
end
end
removed
end | [
"def",
"forget_tree",
"(",
"element_id",
",",
"view",
")",
"removed",
"=",
"forget_view",
"(",
"element_id",
",",
"view",
")",
"if",
"view",
".",
"subviews",
"view",
".",
"subviews",
".",
"each",
"do",
"|",
"sub",
"|",
"if",
"(",
"sub_ids",
"=",
"sub",
".",
"motion_kit_meta",
"[",
":motion_kit_ids",
"]",
")",
"sub_ids",
".",
"each",
"do",
"|",
"sub_id",
"|",
"forget_tree",
"(",
"sub_id",
",",
"sub",
")",
"||",
"[",
"]",
"end",
"end",
"end",
"end",
"removed",
"end"
] | returns the root view that was removed, if any | [
"returns",
"the",
"root",
"view",
"that",
"was",
"removed",
"if",
"any"
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L475-L487 | train |
motion-kit/motion-kit | lib/motion-kit/helpers/tree_layout.rb | MotionKit.TreeLayout.build_view | def build_view
# Only in the 'layout' method will we allow default container to be
# created automatically (when 'add' is called)
@assign_root = true
prev_should_run = @should_run_deferred
@should_run_deferred = true
layout
unless @view
if @assign_root
create_default_root_context
@view = @context
else
NSLog('Warning! No root view was set in TreeLayout#layout. Did you mean to call `root`?')
end
end
run_deferred(@view)
@should_run_deferred = prev_should_run
@assign_root = false
# context can be set via the 'create_default_root_context' method, which
# may be outside a 'context' block, so make sure to restore context to
# it's previous value
@context = nil
if @preset_root
@view = WeakRef.new(@view)
@preset_root = nil
end
@view
end | ruby | def build_view
# Only in the 'layout' method will we allow default container to be
# created automatically (when 'add' is called)
@assign_root = true
prev_should_run = @should_run_deferred
@should_run_deferred = true
layout
unless @view
if @assign_root
create_default_root_context
@view = @context
else
NSLog('Warning! No root view was set in TreeLayout#layout. Did you mean to call `root`?')
end
end
run_deferred(@view)
@should_run_deferred = prev_should_run
@assign_root = false
# context can be set via the 'create_default_root_context' method, which
# may be outside a 'context' block, so make sure to restore context to
# it's previous value
@context = nil
if @preset_root
@view = WeakRef.new(@view)
@preset_root = nil
end
@view
end | [
"def",
"build_view",
"# Only in the 'layout' method will we allow default container to be",
"# created automatically (when 'add' is called)",
"@assign_root",
"=",
"true",
"prev_should_run",
"=",
"@should_run_deferred",
"@should_run_deferred",
"=",
"true",
"layout",
"unless",
"@view",
"if",
"@assign_root",
"create_default_root_context",
"@view",
"=",
"@context",
"else",
"NSLog",
"(",
"'Warning! No root view was set in TreeLayout#layout. Did you mean to call `root`?'",
")",
"end",
"end",
"run_deferred",
"(",
"@view",
")",
"@should_run_deferred",
"=",
"prev_should_run",
"@assign_root",
"=",
"false",
"# context can be set via the 'create_default_root_context' method, which",
"# may be outside a 'context' block, so make sure to restore context to",
"# it's previous value",
"@context",
"=",
"nil",
"if",
"@preset_root",
"@view",
"=",
"WeakRef",
".",
"new",
"(",
"@view",
")",
"@preset_root",
"=",
"nil",
"end",
"@view",
"end"
] | This method builds the layout and returns the root view. | [
"This",
"method",
"builds",
"the",
"layout",
"and",
"returns",
"the",
"root",
"view",
"."
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L504-L533 | train |
motion-kit/motion-kit | lib/motion-kit/helpers/tree_layout.rb | MotionKit.TreeLayout.initialize_element | def initialize_element(elem, element_id)
if elem.is_a?(Class) && elem < TreeLayout
layout = elem.new
elem = layout.view
elsif elem.is_a?(Class)
elem = elem.new
elsif elem.is_a?(TreeLayout)
layout = elem
elem = elem.view
end
if layout
if element_id
name_element(layout, element_id)
end
@child_layouts << layout
elsif element_id
name_element(elem, element_id)
end
return elem
end | ruby | def initialize_element(elem, element_id)
if elem.is_a?(Class) && elem < TreeLayout
layout = elem.new
elem = layout.view
elsif elem.is_a?(Class)
elem = elem.new
elsif elem.is_a?(TreeLayout)
layout = elem
elem = elem.view
end
if layout
if element_id
name_element(layout, element_id)
end
@child_layouts << layout
elsif element_id
name_element(elem, element_id)
end
return elem
end | [
"def",
"initialize_element",
"(",
"elem",
",",
"element_id",
")",
"if",
"elem",
".",
"is_a?",
"(",
"Class",
")",
"&&",
"elem",
"<",
"TreeLayout",
"layout",
"=",
"elem",
".",
"new",
"elem",
"=",
"layout",
".",
"view",
"elsif",
"elem",
".",
"is_a?",
"(",
"Class",
")",
"elem",
"=",
"elem",
".",
"new",
"elsif",
"elem",
".",
"is_a?",
"(",
"TreeLayout",
")",
"layout",
"=",
"elem",
"elem",
"=",
"elem",
".",
"view",
"end",
"if",
"layout",
"if",
"element_id",
"name_element",
"(",
"layout",
",",
"element_id",
")",
"end",
"@child_layouts",
"<<",
"layout",
"elsif",
"element_id",
"name_element",
"(",
"elem",
",",
"element_id",
")",
"end",
"return",
"elem",
"end"
] | Initializes an instance of a view. This will need to be smarter going
forward as `new` isn't always the designated initializer.
Accepts a view instance, a class (which is instantiated with 'new') or a
`ViewLayout`, which returns the root view. | [
"Initializes",
"an",
"instance",
"of",
"a",
"view",
".",
"This",
"will",
"need",
"to",
"be",
"smarter",
"going",
"forward",
"as",
"new",
"isn",
"t",
"always",
"the",
"designated",
"initializer",
"."
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L543-L564 | train |
motion-kit/motion-kit | lib/motion-kit/helpers/tree_layout.rb | MotionKit.TreeLayout.style_and_context | def style_and_context(element, element_id, &block)
style_method = "#{element_id}_style"
if parent_layout.respond_to?(style_method) || block_given?
parent_layout.context(element) do
if parent_layout.respond_to?(style_method)
parent_layout.send(style_method)
end
if block_given?
yield
end
end
end
end | ruby | def style_and_context(element, element_id, &block)
style_method = "#{element_id}_style"
if parent_layout.respond_to?(style_method) || block_given?
parent_layout.context(element) do
if parent_layout.respond_to?(style_method)
parent_layout.send(style_method)
end
if block_given?
yield
end
end
end
end | [
"def",
"style_and_context",
"(",
"element",
",",
"element_id",
",",
"&",
"block",
")",
"style_method",
"=",
"\"#{element_id}_style\"",
"if",
"parent_layout",
".",
"respond_to?",
"(",
"style_method",
")",
"||",
"block_given?",
"parent_layout",
".",
"context",
"(",
"element",
")",
"do",
"if",
"parent_layout",
".",
"respond_to?",
"(",
"style_method",
")",
"parent_layout",
".",
"send",
"(",
"style_method",
")",
"end",
"if",
"block_given?",
"yield",
"end",
"end",
"end",
"end"
] | Calls the `_style` method with the element as the context, and runs the
optional block in that context. This is usually done immediately after
`initialize_element`, except in the case of `add`, which adds the item to
the tree before styling it. | [
"Calls",
"the",
"_style",
"method",
"with",
"the",
"element",
"as",
"the",
"context",
"and",
"runs",
"the",
"optional",
"block",
"in",
"that",
"context",
".",
"This",
"is",
"usually",
"done",
"immediately",
"after",
"initialize_element",
"except",
"in",
"the",
"case",
"of",
"add",
"which",
"adds",
"the",
"item",
"to",
"the",
"tree",
"before",
"styling",
"it",
"."
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L570-L583 | train |
motion-kit/motion-kit | lib/motion-kit/helpers/base_layout.rb | MotionKit.BaseLayout.context | def context(new_target, &block)
return new_target unless block
# this little line is incredibly important; the context is only set on
# the top-level Layout object.
# mp "MOTIONKIT CONTEXT is #{new_target} meta: #{new_target.motion_kit_meta}"
return parent_layout.context(new_target, &block) unless is_parent_layout?
if new_target.is_a?(Symbol)
new_target = self.get_view(new_target)
end
context_was, parent_was, delegate_was = @context, @parent, @layout_delegate
prev_should_run = @should_run_deferred
if @should_run_deferred.nil?
@should_run_deferred = true
else
@should_run_deferred = false
end
@parent = MK::Parent.new(context_was)
@context = new_target
@context.motion_kit_meta[:delegate] ||= Layout.layout_for(@context.class)
@layout_delegate = @context.motion_kit_meta[:delegate]
if @layout_delegate
@layout_delegate.set_parent_layout(parent_layout)
end
yield
@layout_delegate, @context, @parent = delegate_was, context_was, parent_was
if @should_run_deferred
run_deferred(new_target)
end
@should_run_deferred = prev_should_run
new_target
end | ruby | def context(new_target, &block)
return new_target unless block
# this little line is incredibly important; the context is only set on
# the top-level Layout object.
# mp "MOTIONKIT CONTEXT is #{new_target} meta: #{new_target.motion_kit_meta}"
return parent_layout.context(new_target, &block) unless is_parent_layout?
if new_target.is_a?(Symbol)
new_target = self.get_view(new_target)
end
context_was, parent_was, delegate_was = @context, @parent, @layout_delegate
prev_should_run = @should_run_deferred
if @should_run_deferred.nil?
@should_run_deferred = true
else
@should_run_deferred = false
end
@parent = MK::Parent.new(context_was)
@context = new_target
@context.motion_kit_meta[:delegate] ||= Layout.layout_for(@context.class)
@layout_delegate = @context.motion_kit_meta[:delegate]
if @layout_delegate
@layout_delegate.set_parent_layout(parent_layout)
end
yield
@layout_delegate, @context, @parent = delegate_was, context_was, parent_was
if @should_run_deferred
run_deferred(new_target)
end
@should_run_deferred = prev_should_run
new_target
end | [
"def",
"context",
"(",
"new_target",
",",
"&",
"block",
")",
"return",
"new_target",
"unless",
"block",
"# this little line is incredibly important; the context is only set on",
"# the top-level Layout object.",
"# mp \"MOTIONKIT CONTEXT is #{new_target} meta: #{new_target.motion_kit_meta}\"",
"return",
"parent_layout",
".",
"context",
"(",
"new_target",
",",
"block",
")",
"unless",
"is_parent_layout?",
"if",
"new_target",
".",
"is_a?",
"(",
"Symbol",
")",
"new_target",
"=",
"self",
".",
"get_view",
"(",
"new_target",
")",
"end",
"context_was",
",",
"parent_was",
",",
"delegate_was",
"=",
"@context",
",",
"@parent",
",",
"@layout_delegate",
"prev_should_run",
"=",
"@should_run_deferred",
"if",
"@should_run_deferred",
".",
"nil?",
"@should_run_deferred",
"=",
"true",
"else",
"@should_run_deferred",
"=",
"false",
"end",
"@parent",
"=",
"MK",
"::",
"Parent",
".",
"new",
"(",
"context_was",
")",
"@context",
"=",
"new_target",
"@context",
".",
"motion_kit_meta",
"[",
":delegate",
"]",
"||=",
"Layout",
".",
"layout_for",
"(",
"@context",
".",
"class",
")",
"@layout_delegate",
"=",
"@context",
".",
"motion_kit_meta",
"[",
":delegate",
"]",
"if",
"@layout_delegate",
"@layout_delegate",
".",
"set_parent_layout",
"(",
"parent_layout",
")",
"end",
"yield",
"@layout_delegate",
",",
"@context",
",",
"@parent",
"=",
"delegate_was",
",",
"context_was",
",",
"parent_was",
"if",
"@should_run_deferred",
"run_deferred",
"(",
"new_target",
")",
"end",
"@should_run_deferred",
"=",
"prev_should_run",
"new_target",
"end"
] | Runs a block of code with a new object as the 'context'. Methods from the
Layout classes are applied to this target object, and missing methods are
delegated to a new Layout instance that is created based on the new
context.
This method is part of the public API, you can pass in any object to have
it become the 'context'.
Example:
def table_view_style
content = target.contentView
if content
context(content) do
background_color UIColor.clearColor
end
end
# usually you use 'context' automatically via method_missing, by
# passing a block to a method that returns an object. That object becomes
# the new context.
layer do
# target is now a CALayer, and methods are delegated to CALayerHelpers
corner_radius 5
end
end | [
"Runs",
"a",
"block",
"of",
"code",
"with",
"a",
"new",
"object",
"as",
"the",
"context",
".",
"Methods",
"from",
"the",
"Layout",
"classes",
"are",
"applied",
"to",
"this",
"target",
"object",
"and",
"missing",
"methods",
"are",
"delegated",
"to",
"a",
"new",
"Layout",
"instance",
"that",
"is",
"created",
"based",
"on",
"the",
"new",
"context",
"."
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/base_layout.rb#L91-L126 | train |
motion-kit/motion-kit | lib/motion-kit-osx/helpers/nsmenu_helpers.rb | MotionKit.MenuLayout.root | def root(element, element_id=nil, &block)
if element && element.is_a?(NSString)
element = NSMenu.alloc.initWithTitle(element)
end
super(element, element_id, &block)
end | ruby | def root(element, element_id=nil, &block)
if element && element.is_a?(NSString)
element = NSMenu.alloc.initWithTitle(element)
end
super(element, element_id, &block)
end | [
"def",
"root",
"(",
"element",
",",
"element_id",
"=",
"nil",
",",
"&",
"block",
")",
"if",
"element",
"&&",
"element",
".",
"is_a?",
"(",
"NSString",
")",
"element",
"=",
"NSMenu",
".",
"alloc",
".",
"initWithTitle",
"(",
"element",
")",
"end",
"super",
"(",
"element",
",",
"element_id",
",",
"block",
")",
"end"
] | override root to allow a menu title for the top level menu | [
"override",
"root",
"to",
"allow",
"a",
"menu",
"title",
"for",
"the",
"top",
"level",
"menu"
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit-osx/helpers/nsmenu_helpers.rb#L28-L33 | train |
motion-kit/motion-kit | lib/motion-kit-osx/helpers/nsmenu_helpers.rb | MotionKit.MenuLayout.add | def add(title_or_item, element_id=nil, options={}, &block)
if element_id.is_a?(NSDictionary)
options = element_id
element_id = nil
end
if title_or_item.is_a?(NSMenuItem)
item = title_or_item
menu = nil
retval = item
elsif title_or_item.is_a?(NSMenu)
menu = title_or_item
item = self.item(menu.title, options)
item.submenu = menu
retval = menu
else
title = title_or_item
item = self.item(title, options)
if block
menu = create(title)
item.submenu = menu
retval = menu
else
retval = item
end
end
self.apply(:add_child, item)
if menu && block
menuitem_was = @menu_item
@menu_item = item
context(menu, &block)
@menu_item = menuitem_was
end
if element_id
create(retval, element_id)
end
return retval
end | ruby | def add(title_or_item, element_id=nil, options={}, &block)
if element_id.is_a?(NSDictionary)
options = element_id
element_id = nil
end
if title_or_item.is_a?(NSMenuItem)
item = title_or_item
menu = nil
retval = item
elsif title_or_item.is_a?(NSMenu)
menu = title_or_item
item = self.item(menu.title, options)
item.submenu = menu
retval = menu
else
title = title_or_item
item = self.item(title, options)
if block
menu = create(title)
item.submenu = menu
retval = menu
else
retval = item
end
end
self.apply(:add_child, item)
if menu && block
menuitem_was = @menu_item
@menu_item = item
context(menu, &block)
@menu_item = menuitem_was
end
if element_id
create(retval, element_id)
end
return retval
end | [
"def",
"add",
"(",
"title_or_item",
",",
"element_id",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"if",
"element_id",
".",
"is_a?",
"(",
"NSDictionary",
")",
"options",
"=",
"element_id",
"element_id",
"=",
"nil",
"end",
"if",
"title_or_item",
".",
"is_a?",
"(",
"NSMenuItem",
")",
"item",
"=",
"title_or_item",
"menu",
"=",
"nil",
"retval",
"=",
"item",
"elsif",
"title_or_item",
".",
"is_a?",
"(",
"NSMenu",
")",
"menu",
"=",
"title_or_item",
"item",
"=",
"self",
".",
"item",
"(",
"menu",
".",
"title",
",",
"options",
")",
"item",
".",
"submenu",
"=",
"menu",
"retval",
"=",
"menu",
"else",
"title",
"=",
"title_or_item",
"item",
"=",
"self",
".",
"item",
"(",
"title",
",",
"options",
")",
"if",
"block",
"menu",
"=",
"create",
"(",
"title",
")",
"item",
".",
"submenu",
"=",
"menu",
"retval",
"=",
"menu",
"else",
"retval",
"=",
"item",
"end",
"end",
"self",
".",
"apply",
"(",
":add_child",
",",
"item",
")",
"if",
"menu",
"&&",
"block",
"menuitem_was",
"=",
"@menu_item",
"@menu_item",
"=",
"item",
"context",
"(",
"menu",
",",
"block",
")",
"@menu_item",
"=",
"menuitem_was",
"end",
"if",
"element_id",
"create",
"(",
"retval",
",",
"element_id",
")",
"end",
"return",
"retval",
"end"
] | override 'add'; menus are just a horse of a different color. | [
"override",
"add",
";",
"menus",
"are",
"just",
"a",
"horse",
"of",
"a",
"different",
"color",
"."
] | fa01dd08497b0dd01090156e58552be9d3b25ef1 | https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit-osx/helpers/nsmenu_helpers.rb#L36-L78 | train |
cookpad/expeditor | lib/expeditor/command.rb | Expeditor.Command.start_with_retry | def start_with_retry(current_thread: false, **retryable_options)
unless started?
@retryable_options.set(retryable_options)
start(current_thread: current_thread)
end
self
end | ruby | def start_with_retry(current_thread: false, **retryable_options)
unless started?
@retryable_options.set(retryable_options)
start(current_thread: current_thread)
end
self
end | [
"def",
"start_with_retry",
"(",
"current_thread",
":",
"false",
",",
"**",
"retryable_options",
")",
"unless",
"started?",
"@retryable_options",
".",
"set",
"(",
"retryable_options",
")",
"start",
"(",
"current_thread",
":",
"current_thread",
")",
"end",
"self",
"end"
] | Equivalent to retryable gem options | [
"Equivalent",
"to",
"retryable",
"gem",
"options"
] | 1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e | https://github.com/cookpad/expeditor/blob/1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e/lib/expeditor/command.rb#L39-L45 | train |
cookpad/expeditor | lib/expeditor/command.rb | Expeditor.Command.on_complete | def on_complete(&block)
on do |_, value, reason|
block.call(reason == nil, value, reason)
end
end | ruby | def on_complete(&block)
on do |_, value, reason|
block.call(reason == nil, value, reason)
end
end | [
"def",
"on_complete",
"(",
"&",
"block",
")",
"on",
"do",
"|",
"_",
",",
"value",
",",
"reason",
"|",
"block",
".",
"call",
"(",
"reason",
"==",
"nil",
",",
"value",
",",
"reason",
")",
"end",
"end"
] | command.on_complete do |success, value, reason|
...
end | [
"command",
".",
"on_complete",
"do",
"|success",
"value",
"reason|",
"...",
"end"
] | 1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e | https://github.com/cookpad/expeditor/blob/1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e/lib/expeditor/command.rb#L88-L92 | train |
cookpad/expeditor | lib/expeditor/command.rb | Expeditor.Command.on_success | def on_success(&block)
on do |_, value, reason|
block.call(value) unless reason
end
end | ruby | def on_success(&block)
on do |_, value, reason|
block.call(value) unless reason
end
end | [
"def",
"on_success",
"(",
"&",
"block",
")",
"on",
"do",
"|",
"_",
",",
"value",
",",
"reason",
"|",
"block",
".",
"call",
"(",
"value",
")",
"unless",
"reason",
"end",
"end"
] | command.on_success do |value|
...
end | [
"command",
".",
"on_success",
"do",
"|value|",
"...",
"end"
] | 1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e | https://github.com/cookpad/expeditor/blob/1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e/lib/expeditor/command.rb#L97-L101 | train |
cookpad/expeditor | lib/expeditor/command.rb | Expeditor.Command.on_failure | def on_failure(&block)
on do |_, _, reason|
block.call(reason) if reason
end
end | ruby | def on_failure(&block)
on do |_, _, reason|
block.call(reason) if reason
end
end | [
"def",
"on_failure",
"(",
"&",
"block",
")",
"on",
"do",
"|",
"_",
",",
"_",
",",
"reason",
"|",
"block",
".",
"call",
"(",
"reason",
")",
"if",
"reason",
"end",
"end"
] | command.on_failure do |e|
...
end | [
"command",
".",
"on_failure",
"do",
"|e|",
"...",
"end"
] | 1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e | https://github.com/cookpad/expeditor/blob/1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e/lib/expeditor/command.rb#L106-L110 | train |
cookpad/expeditor | lib/expeditor/command.rb | Expeditor.Command.prepare | def prepare(executor = @service.executor)
@normal_future = initial_normal(executor, &@normal_block)
@normal_future.add_observer do |_, value, reason|
if reason # failure
if @fallback_block
future = RichFuture.new(executor: executor) do
success, value, reason = Concurrent::SafeTaskExecutor.new(@fallback_block, rescue_exception: true).execute(reason)
if success
@ivar.set(value)
else
@ivar.fail(reason)
end
end
future.safe_execute
else
@ivar.fail(reason)
end
else # success
@ivar.set(value)
end
end
@dependencies.each(&:start)
end | ruby | def prepare(executor = @service.executor)
@normal_future = initial_normal(executor, &@normal_block)
@normal_future.add_observer do |_, value, reason|
if reason # failure
if @fallback_block
future = RichFuture.new(executor: executor) do
success, value, reason = Concurrent::SafeTaskExecutor.new(@fallback_block, rescue_exception: true).execute(reason)
if success
@ivar.set(value)
else
@ivar.fail(reason)
end
end
future.safe_execute
else
@ivar.fail(reason)
end
else # success
@ivar.set(value)
end
end
@dependencies.each(&:start)
end | [
"def",
"prepare",
"(",
"executor",
"=",
"@service",
".",
"executor",
")",
"@normal_future",
"=",
"initial_normal",
"(",
"executor",
",",
"@normal_block",
")",
"@normal_future",
".",
"add_observer",
"do",
"|",
"_",
",",
"value",
",",
"reason",
"|",
"if",
"reason",
"# failure",
"if",
"@fallback_block",
"future",
"=",
"RichFuture",
".",
"new",
"(",
"executor",
":",
"executor",
")",
"do",
"success",
",",
"value",
",",
"reason",
"=",
"Concurrent",
"::",
"SafeTaskExecutor",
".",
"new",
"(",
"@fallback_block",
",",
"rescue_exception",
":",
"true",
")",
".",
"execute",
"(",
"reason",
")",
"if",
"success",
"@ivar",
".",
"set",
"(",
"value",
")",
"else",
"@ivar",
".",
"fail",
"(",
"reason",
")",
"end",
"end",
"future",
".",
"safe_execute",
"else",
"@ivar",
".",
"fail",
"(",
"reason",
")",
"end",
"else",
"# success",
"@ivar",
".",
"set",
"(",
"value",
")",
"end",
"end",
"@dependencies",
".",
"each",
"(",
":start",
")",
"end"
] | set future
set fallback future as an observer
start dependencies | [
"set",
"future",
"set",
"fallback",
"future",
"as",
"an",
"observer",
"start",
"dependencies"
] | 1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e | https://github.com/cookpad/expeditor/blob/1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e/lib/expeditor/command.rb#L134-L157 | train |
cookpad/expeditor | lib/expeditor/command.rb | Expeditor.Command.initial_normal | def initial_normal(executor, &block)
future = RichFuture.new(executor: executor) do
args = wait_dependencies
timeout_block(args, &block)
end
future.add_observer do |_, _, reason|
metrics(reason)
end
future
end | ruby | def initial_normal(executor, &block)
future = RichFuture.new(executor: executor) do
args = wait_dependencies
timeout_block(args, &block)
end
future.add_observer do |_, _, reason|
metrics(reason)
end
future
end | [
"def",
"initial_normal",
"(",
"executor",
",",
"&",
"block",
")",
"future",
"=",
"RichFuture",
".",
"new",
"(",
"executor",
":",
"executor",
")",
"do",
"args",
"=",
"wait_dependencies",
"timeout_block",
"(",
"args",
",",
"block",
")",
"end",
"future",
".",
"add_observer",
"do",
"|",
"_",
",",
"_",
",",
"reason",
"|",
"metrics",
"(",
"reason",
")",
"end",
"future",
"end"
] | timeout_block do
retryable_block do
breakable_block do
block.call
end
end
end | [
"timeout_block",
"do",
"retryable_block",
"do",
"breakable_block",
"do",
"block",
".",
"call",
"end",
"end",
"end"
] | 1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e | https://github.com/cookpad/expeditor/blob/1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e/lib/expeditor/command.rb#L166-L175 | train |
david942j/gdb-ruby | lib/gdb/eval_context.rb | GDB.EvalContext.invoke_pry | def invoke_pry
org = Pry.config.history.file
# this has no effect if gdb is launched by pry
Pry.config.history.file = '~/.gdb-pry_history'
$stdin.cooked { pry }
Pry.config.history.file = org
end | ruby | def invoke_pry
org = Pry.config.history.file
# this has no effect if gdb is launched by pry
Pry.config.history.file = '~/.gdb-pry_history'
$stdin.cooked { pry }
Pry.config.history.file = org
end | [
"def",
"invoke_pry",
"org",
"=",
"Pry",
".",
"config",
".",
"history",
".",
"file",
"# this has no effect if gdb is launched by pry",
"Pry",
".",
"config",
".",
"history",
".",
"file",
"=",
"'~/.gdb-pry_history'",
"$stdin",
".",
"cooked",
"{",
"pry",
"}",
"Pry",
".",
"config",
".",
"history",
".",
"file",
"=",
"org",
"end"
] | Invoke pry, wrapper with some settings.
@return [void] | [
"Invoke",
"pry",
"wrapper",
"with",
"some",
"settings",
"."
] | 1c6fcca14314dd8289bc3598bdf2b72235bfbb4e | https://github.com/david942j/gdb-ruby/blob/1c6fcca14314dd8289bc3598bdf2b72235bfbb4e/lib/gdb/eval_context.rb#L25-L31 | train |
david942j/gdb-ruby | lib/gdb/gdb.rb | GDB.GDB.text_base | def text_base
check_alive!
base = Integer(execute('info proc stat').scan(/Start of text: (.*)/).flatten.first)
execute("set $text = #{base}")
base
end | ruby | def text_base
check_alive!
base = Integer(execute('info proc stat').scan(/Start of text: (.*)/).flatten.first)
execute("set $text = #{base}")
base
end | [
"def",
"text_base",
"check_alive!",
"base",
"=",
"Integer",
"(",
"execute",
"(",
"'info proc stat'",
")",
".",
"scan",
"(",
"/",
"/",
")",
".",
"flatten",
".",
"first",
")",
"execute",
"(",
"\"set $text = #{base}\"",
")",
"base",
"end"
] | Get the process's text base.
@return [Integer]
The base address.
@note
This will also set a variable +$text+ in gdb. | [
"Get",
"the",
"process",
"s",
"text",
"base",
"."
] | 1c6fcca14314dd8289bc3598bdf2b72235bfbb4e | https://github.com/david942j/gdb-ruby/blob/1c6fcca14314dd8289bc3598bdf2b72235bfbb4e/lib/gdb/gdb.rb#L136-L141 | train |
david942j/gdb-ruby | lib/gdb/gdb.rb | GDB.GDB.read_memory | def read_memory(addr, num_elements, options = {}, &block)
check_alive! # this would set @pid
options[:as] = block if block_given?
MemoryIO.attach(@pid).read(addr, num_elements, **options)
end | ruby | def read_memory(addr, num_elements, options = {}, &block)
check_alive! # this would set @pid
options[:as] = block if block_given?
MemoryIO.attach(@pid).read(addr, num_elements, **options)
end | [
"def",
"read_memory",
"(",
"addr",
",",
"num_elements",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"check_alive!",
"# this would set @pid",
"options",
"[",
":as",
"]",
"=",
"block",
"if",
"block_given?",
"MemoryIO",
".",
"attach",
"(",
"@pid",
")",
".",
"read",
"(",
"addr",
",",
"num_elements",
",",
"**",
"options",
")",
"end"
] | Read current process's memory.
@param [Integer, String] addr
Address to start to read.
+addr+ can be a string like 'heap+0x10'.
Supported variables are names in /proc/$pid/maps such as +heap/libc/stack/ld+.
@param [Integer] num_elements
Number of elements to read.
If +num_elements+ equals to 1, an object read will be returned.
Otherwise, an array with size +num_elements+ will be returned.
@option [Symbol, Class] as
Types that supported by [MemoryIO](https://github.com/david942j/memory_io).
@return [Object, Array<Object>]
Return types are decided by value of +num_elements+ and option +as+.
@yieldparam [IO] io
The +IO+ object that points to +addr+,
read from it.
@yieldreturn [Object]
Whatever you read from +io+.
@example
gdb = GDB::GDB.new('spec/binaries/amd64.elf')
gdb.break('main')
gdb.run
gdb.read_memory('amd64.elf', 4)
#=> "\x7fELF"
@example
# example of fetching argv
gdb = GDB::GDB.new('spec/binaries/amd64.elf')
gdb.break('main')
gdb.run('pusheen the cat')
gdb.read_memory(0x400000, 4)
#=> "\x7fELF"
argc = gdb.register(:rdi)
#=> 4
args = gdb.read_memory(gdb.register(:rsi), argc, as: :u64)
Array.new(3) do |i|
gdb.read_memory(args[i + 1], 1) do |m|
str = ''
loop do
c = m.read(1)
break if c == "\x00"
str << c
end
str
end
end
#=> ["pusheen", "the", "cat"]
# or, use our build-in types of gem +memory_io+.
gdb.read_memory(args[1], 3, as: :c_str)
#=> ["pusheen", "the", "cat"] | [
"Read",
"current",
"process",
"s",
"memory",
"."
] | 1c6fcca14314dd8289bc3598bdf2b72235bfbb4e | https://github.com/david942j/gdb-ruby/blob/1c6fcca14314dd8289bc3598bdf2b72235bfbb4e/lib/gdb/gdb.rb#L255-L259 | train |
david942j/gdb-ruby | lib/gdb/gdb.rb | GDB.GDB.write_memory | def write_memory(addr, objects, options = {}, &block)
check_alive! # this would set @pid
options[:as] = block if block_given?
MemoryIO.attach(@pid).write(addr, objects, **options)
end | ruby | def write_memory(addr, objects, options = {}, &block)
check_alive! # this would set @pid
options[:as] = block if block_given?
MemoryIO.attach(@pid).write(addr, objects, **options)
end | [
"def",
"write_memory",
"(",
"addr",
",",
"objects",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"check_alive!",
"# this would set @pid",
"options",
"[",
":as",
"]",
"=",
"block",
"if",
"block_given?",
"MemoryIO",
".",
"attach",
"(",
"@pid",
")",
".",
"write",
"(",
"addr",
",",
"objects",
",",
"**",
"options",
")",
"end"
] | Write an object to process at specific address.
@param [Integer, String] addr
Target address.
+addr+ can be a string like 'heap+0x10'.
Supported variables are names in +/proc/$pid/maps+ such as +heap/libc/stack/ld+.
@param [Objects, Array<Objects>] objects
Objects to be written.
@option [Symbol, Class] as
See {#read_memory}.
@return [void] | [
"Write",
"an",
"object",
"to",
"process",
"at",
"specific",
"address",
"."
] | 1c6fcca14314dd8289bc3598bdf2b72235bfbb4e | https://github.com/david942j/gdb-ruby/blob/1c6fcca14314dd8289bc3598bdf2b72235bfbb4e/lib/gdb/gdb.rb#L275-L279 | train |
ashfurrow/danger-rubocop | lib/danger_plugin.rb | Danger.DangerRubocop.lint | def lint(config = nil)
config = config.is_a?(Hash) ? config : { files: config }
files = config[:files]
force_exclusion = config[:force_exclusion] || false
report_danger = config[:report_danger] || false
inline_comment = config[:inline_comment] || false
fail_on_inline_comment = config[:fail_on_inline_comment] || false
files_to_lint = fetch_files_to_lint(files)
files_to_report = rubocop(files_to_lint, force_exclusion)
return if files_to_report.empty?
return report_failures files_to_report if report_danger
if inline_comment
add_violation_for_each_line(files_to_report, fail_on_inline_comment)
else
markdown offenses_message(files_to_report)
end
end | ruby | def lint(config = nil)
config = config.is_a?(Hash) ? config : { files: config }
files = config[:files]
force_exclusion = config[:force_exclusion] || false
report_danger = config[:report_danger] || false
inline_comment = config[:inline_comment] || false
fail_on_inline_comment = config[:fail_on_inline_comment] || false
files_to_lint = fetch_files_to_lint(files)
files_to_report = rubocop(files_to_lint, force_exclusion)
return if files_to_report.empty?
return report_failures files_to_report if report_danger
if inline_comment
add_violation_for_each_line(files_to_report, fail_on_inline_comment)
else
markdown offenses_message(files_to_report)
end
end | [
"def",
"lint",
"(",
"config",
"=",
"nil",
")",
"config",
"=",
"config",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"config",
":",
"{",
"files",
":",
"config",
"}",
"files",
"=",
"config",
"[",
":files",
"]",
"force_exclusion",
"=",
"config",
"[",
":force_exclusion",
"]",
"||",
"false",
"report_danger",
"=",
"config",
"[",
":report_danger",
"]",
"||",
"false",
"inline_comment",
"=",
"config",
"[",
":inline_comment",
"]",
"||",
"false",
"fail_on_inline_comment",
"=",
"config",
"[",
":fail_on_inline_comment",
"]",
"||",
"false",
"files_to_lint",
"=",
"fetch_files_to_lint",
"(",
"files",
")",
"files_to_report",
"=",
"rubocop",
"(",
"files_to_lint",
",",
"force_exclusion",
")",
"return",
"if",
"files_to_report",
".",
"empty?",
"return",
"report_failures",
"files_to_report",
"if",
"report_danger",
"if",
"inline_comment",
"add_violation_for_each_line",
"(",
"files_to_report",
",",
"fail_on_inline_comment",
")",
"else",
"markdown",
"offenses_message",
"(",
"files_to_report",
")",
"end",
"end"
] | Runs Ruby files through Rubocop. Generates a `markdown` list of warnings.
@param [String] files
A globbed string which should return the files that you want to
run through, defaults to nil. If nil, modified and added files
from the diff will be used.
@return [void] | [
"Runs",
"Ruby",
"files",
"through",
"Rubocop",
".",
"Generates",
"a",
"markdown",
"list",
"of",
"warnings",
"."
] | 3959cca96dca031a0740576ac22471b80f671b82 | https://github.com/ashfurrow/danger-rubocop/blob/3959cca96dca031a0740576ac22471b80f671b82/lib/danger_plugin.rb#L29-L50 | train |
protobuf-ruby/beefcake | lib/beefcake/generator.rb | Beefcake.Generator.name_for | def name_for(b, mod, val)
b.name_for(mod, val).to_s.gsub(/.*_/, "").downcase
end | ruby | def name_for(b, mod, val)
b.name_for(mod, val).to_s.gsub(/.*_/, "").downcase
end | [
"def",
"name_for",
"(",
"b",
",",
"mod",
",",
"val",
")",
"b",
".",
"name_for",
"(",
"mod",
",",
"val",
")",
".",
"to_s",
".",
"gsub",
"(",
"/",
"/",
",",
"\"\"",
")",
".",
"downcase",
"end"
] | Determines the name for a | [
"Determines",
"the",
"name",
"for",
"a"
] | c0a97e7ca05b4d2f980509e85c4a49dfe7acbc5a | https://github.com/protobuf-ruby/beefcake/blob/c0a97e7ca05b4d2f980509e85c4a49dfe7acbc5a/lib/beefcake/generator.rb#L267-L269 | train |
imikimi/literate_randomizer | lib/literate_randomizer/source_parser.rb | LiterateRandomizer.SourceParser.scrub_sentence | def scrub_sentence(sentence)
sentence.split(/([\s]|--)+/).collect {|a| scrub_word(a)}.select {|a| a.length>0}
end | ruby | def scrub_sentence(sentence)
sentence.split(/([\s]|--)+/).collect {|a| scrub_word(a)}.select {|a| a.length>0}
end | [
"def",
"scrub_sentence",
"(",
"sentence",
")",
"sentence",
".",
"split",
"(",
"/",
"\\s",
"/",
")",
".",
"collect",
"{",
"|",
"a",
"|",
"scrub_word",
"(",
"a",
")",
"}",
".",
"select",
"{",
"|",
"a",
"|",
"a",
".",
"length",
">",
"0",
"}",
"end"
] | clean up all words in a string, returning an array of clean words | [
"clean",
"up",
"all",
"words",
"in",
"a",
"string",
"returning",
"an",
"array",
"of",
"clean",
"words"
] | 55d123f230b13c62de6f815063edf0d9b7dce306 | https://github.com/imikimi/literate_randomizer/blob/55d123f230b13c62de6f815063edf0d9b7dce306/lib/literate_randomizer/source_parser.rb#L44-L46 | train |
imikimi/literate_randomizer | lib/literate_randomizer/markov.rb | LiterateRandomizer.MarkovModel.next_word | def next_word(word,randomizer=@randomizer)
return if !markov_chains[word]
sum = @markov_weighted_sum[word]
random = randomizer.rand(sum)+1
partial_sum = 0
(markov_chains[word].find do |w, count|
partial_sum += count
w!=word && partial_sum >= random
end||[]).first
end | ruby | def next_word(word,randomizer=@randomizer)
return if !markov_chains[word]
sum = @markov_weighted_sum[word]
random = randomizer.rand(sum)+1
partial_sum = 0
(markov_chains[word].find do |w, count|
partial_sum += count
w!=word && partial_sum >= random
end||[]).first
end | [
"def",
"next_word",
"(",
"word",
",",
"randomizer",
"=",
"@randomizer",
")",
"return",
"if",
"!",
"markov_chains",
"[",
"word",
"]",
"sum",
"=",
"@markov_weighted_sum",
"[",
"word",
"]",
"random",
"=",
"randomizer",
".",
"rand",
"(",
"sum",
")",
"+",
"1",
"partial_sum",
"=",
"0",
"(",
"markov_chains",
"[",
"word",
"]",
".",
"find",
"do",
"|",
"w",
",",
"count",
"|",
"partial_sum",
"+=",
"count",
"w!",
"=",
"word",
"&&",
"partial_sum",
">=",
"random",
"end",
"||",
"[",
"]",
")",
".",
"first",
"end"
] | Initialize a new instance.
Options:
* :randomizer => Random.new # must respond to #rand(limit)
* :source_parser => SourceParser.new options
Given a word, return a weighted-randomly selected next-one. | [
"Initialize",
"a",
"new",
"instance",
"."
] | 55d123f230b13c62de6f815063edf0d9b7dce306 | https://github.com/imikimi/literate_randomizer/blob/55d123f230b13c62de6f815063edf0d9b7dce306/lib/literate_randomizer/markov.rb#L99-L108 | train |
imikimi/literate_randomizer | lib/literate_randomizer/randomizer.rb | LiterateRandomizer.Randomizer.extend_trailing_preposition | def extend_trailing_preposition(max_words,words)
while words.length < max_words && words[-1] && words[-1][PREPOSITION_REGEX]
words << model.next_word(words[-1],randomizer)
end
words
end | ruby | def extend_trailing_preposition(max_words,words)
while words.length < max_words && words[-1] && words[-1][PREPOSITION_REGEX]
words << model.next_word(words[-1],randomizer)
end
words
end | [
"def",
"extend_trailing_preposition",
"(",
"max_words",
",",
"words",
")",
"while",
"words",
".",
"length",
"<",
"max_words",
"&&",
"words",
"[",
"-",
"1",
"]",
"&&",
"words",
"[",
"-",
"1",
"]",
"[",
"PREPOSITION_REGEX",
"]",
"words",
"<<",
"model",
".",
"next_word",
"(",
"words",
"[",
"-",
"1",
"]",
",",
"randomizer",
")",
"end",
"words",
"end"
] | Check to see if the sentence ends in a PREPOSITION_REGEX word.
If so, add more words up to max-words until it does. | [
"Check",
"to",
"see",
"if",
"the",
"sentence",
"ends",
"in",
"a",
"PREPOSITION_REGEX",
"word",
".",
"If",
"so",
"add",
"more",
"words",
"up",
"to",
"max",
"-",
"words",
"until",
"it",
"does",
"."
] | 55d123f230b13c62de6f815063edf0d9b7dce306 | https://github.com/imikimi/literate_randomizer/blob/55d123f230b13c62de6f815063edf0d9b7dce306/lib/literate_randomizer/randomizer.rb#L32-L37 | train |
imikimi/literate_randomizer | lib/literate_randomizer/randomizer.rb | LiterateRandomizer.Randomizer.sentence | def sentence(options={})
word = options[:first_word] || self.first_word
num_words_option = options[:words] || (3..15)
count = Util.rand_count(num_words_option,randomizer)
punctuation = options[:punctuation] || self.punctuation
words = count.times.collect do
word.tap {word = model.next_word(word,randomizer)}
end.compact
words = extend_trailing_preposition(Util.max(num_words_option), words)
Util.capitalize words.compact.join(" ") + punctuation
end | ruby | def sentence(options={})
word = options[:first_word] || self.first_word
num_words_option = options[:words] || (3..15)
count = Util.rand_count(num_words_option,randomizer)
punctuation = options[:punctuation] || self.punctuation
words = count.times.collect do
word.tap {word = model.next_word(word,randomizer)}
end.compact
words = extend_trailing_preposition(Util.max(num_words_option), words)
Util.capitalize words.compact.join(" ") + punctuation
end | [
"def",
"sentence",
"(",
"options",
"=",
"{",
"}",
")",
"word",
"=",
"options",
"[",
":first_word",
"]",
"||",
"self",
".",
"first_word",
"num_words_option",
"=",
"options",
"[",
":words",
"]",
"||",
"(",
"3",
"..",
"15",
")",
"count",
"=",
"Util",
".",
"rand_count",
"(",
"num_words_option",
",",
"randomizer",
")",
"punctuation",
"=",
"options",
"[",
":punctuation",
"]",
"||",
"self",
".",
"punctuation",
"words",
"=",
"count",
".",
"times",
".",
"collect",
"do",
"word",
".",
"tap",
"{",
"word",
"=",
"model",
".",
"next_word",
"(",
"word",
",",
"randomizer",
")",
"}",
"end",
".",
"compact",
"words",
"=",
"extend_trailing_preposition",
"(",
"Util",
".",
"max",
"(",
"num_words_option",
")",
",",
"words",
")",
"Util",
".",
"capitalize",
"words",
".",
"compact",
".",
"join",
"(",
"\" \"",
")",
"+",
"punctuation",
"end"
] | return a random sentence
Options:
* :first_word => nil - the start word
* :words => range or int - number of words in sentence
* :punctuation => nil - punction to end the sentence with (nil == randomly selected from punctuation_distribution) | [
"return",
"a",
"random",
"sentence"
] | 55d123f230b13c62de6f815063edf0d9b7dce306 | https://github.com/imikimi/literate_randomizer/blob/55d123f230b13c62de6f815063edf0d9b7dce306/lib/literate_randomizer/randomizer.rb#L96-L109 | train |
imikimi/literate_randomizer | lib/literate_randomizer/randomizer.rb | LiterateRandomizer.Randomizer.paragraph | def paragraph(options={})
count = Util.rand_count(options[:sentences] || (5..15),randomizer)
count.times.collect do |i|
op = options.clone
op.delete :punctuation unless i==count-1
op.delete :first_word unless i==0
sentence op
end.join(" ")
end | ruby | def paragraph(options={})
count = Util.rand_count(options[:sentences] || (5..15),randomizer)
count.times.collect do |i|
op = options.clone
op.delete :punctuation unless i==count-1
op.delete :first_word unless i==0
sentence op
end.join(" ")
end | [
"def",
"paragraph",
"(",
"options",
"=",
"{",
"}",
")",
"count",
"=",
"Util",
".",
"rand_count",
"(",
"options",
"[",
":sentences",
"]",
"||",
"(",
"5",
"..",
"15",
")",
",",
"randomizer",
")",
"count",
".",
"times",
".",
"collect",
"do",
"|",
"i",
"|",
"op",
"=",
"options",
".",
"clone",
"op",
".",
"delete",
":punctuation",
"unless",
"i",
"==",
"count",
"-",
"1",
"op",
".",
"delete",
":first_word",
"unless",
"i",
"==",
"0",
"sentence",
"op",
"end",
".",
"join",
"(",
"\" \"",
")",
"end"
] | return a random paragraph
Options:
* :first_word => nil - the first word of the paragraph
* :words => range or int - number of words in sentence
* :sentences => range or int - number of sentences in paragraph
* :punctuation => nil - punction to end the paragraph with (nil == randomly selected from punctuation_distribution) | [
"return",
"a",
"random",
"paragraph"
] | 55d123f230b13c62de6f815063edf0d9b7dce306 | https://github.com/imikimi/literate_randomizer/blob/55d123f230b13c62de6f815063edf0d9b7dce306/lib/literate_randomizer/randomizer.rb#L119-L128 | train |
imikimi/literate_randomizer | lib/literate_randomizer/randomizer.rb | LiterateRandomizer.Randomizer.paragraphs | def paragraphs(options={})
count = Util.rand_count(options[:paragraphs] || (3..5),randomizer)
join_str = options[:join]
res = count.times.collect do |i|
op = options.clone
op.delete :punctuation unless i==count-1
op.delete :first_word unless i==0
paragraph op
end
join_str!=false ? res.join(join_str || "\n\n") : res
end | ruby | def paragraphs(options={})
count = Util.rand_count(options[:paragraphs] || (3..5),randomizer)
join_str = options[:join]
res = count.times.collect do |i|
op = options.clone
op.delete :punctuation unless i==count-1
op.delete :first_word unless i==0
paragraph op
end
join_str!=false ? res.join(join_str || "\n\n") : res
end | [
"def",
"paragraphs",
"(",
"options",
"=",
"{",
"}",
")",
"count",
"=",
"Util",
".",
"rand_count",
"(",
"options",
"[",
":paragraphs",
"]",
"||",
"(",
"3",
"..",
"5",
")",
",",
"randomizer",
")",
"join_str",
"=",
"options",
"[",
":join",
"]",
"res",
"=",
"count",
".",
"times",
".",
"collect",
"do",
"|",
"i",
"|",
"op",
"=",
"options",
".",
"clone",
"op",
".",
"delete",
":punctuation",
"unless",
"i",
"==",
"count",
"-",
"1",
"op",
".",
"delete",
":first_word",
"unless",
"i",
"==",
"0",
"paragraph",
"op",
"end",
"join_str!",
"=",
"false",
"?",
"res",
".",
"join",
"(",
"join_str",
"||",
"\"\\n\\n\"",
")",
":",
"res",
"end"
] | return random paragraphs
Options:
* :first_word => nil - the first word of the paragraph
* :words => range or int - number of words in sentence
* :sentences => range or int - number of sentences in paragraph
* :paragraphs => range or int - number of paragraphs in paragraph
* :join => "\n\n" - join the paragraphs. if :join => false, returns an array of the paragraphs
* :punctuation => nil - punction to end the paragraph with (nil == randomly selected from punctuation_distribution) | [
"return",
"random",
"paragraphs"
] | 55d123f230b13c62de6f815063edf0d9b7dce306 | https://github.com/imikimi/literate_randomizer/blob/55d123f230b13c62de6f815063edf0d9b7dce306/lib/literate_randomizer/randomizer.rb#L140-L152 | train |
mvz/gir_ffi | lib/ffi-glib/array_methods.rb | GLib.ArrayMethods.index | def index(idx)
unless (0...length).cover? idx
raise IndexError, "Index #{idx} outside of bounds 0..#{length - 1}"
end
ptr = GirFFI::InOutPointer.new element_type, data_ptr + idx * element_size
ptr.to_ruby_value
end | ruby | def index(idx)
unless (0...length).cover? idx
raise IndexError, "Index #{idx} outside of bounds 0..#{length - 1}"
end
ptr = GirFFI::InOutPointer.new element_type, data_ptr + idx * element_size
ptr.to_ruby_value
end | [
"def",
"index",
"(",
"idx",
")",
"unless",
"(",
"0",
"...",
"length",
")",
".",
"cover?",
"idx",
"raise",
"IndexError",
",",
"\"Index #{idx} outside of bounds 0..#{length - 1}\"",
"end",
"ptr",
"=",
"GirFFI",
"::",
"InOutPointer",
".",
"new",
"element_type",
",",
"data_ptr",
"+",
"idx",
"*",
"element_size",
"ptr",
".",
"to_ruby_value",
"end"
] | Re-implementation of the g_array_index and g_ptr_array_index macros | [
"Re",
"-",
"implementation",
"of",
"the",
"g_array_index",
"and",
"g_ptr_array_index",
"macros"
] | 917cd2a5feda2ed9c06404d63b463794761d896f | https://github.com/mvz/gir_ffi/blob/917cd2a5feda2ed9c06404d63b463794761d896f/lib/ffi-glib/array_methods.rb#L7-L14 | train |
opentracing-contrib/ruby-rack-tracer | lib/rack/tracer.rb | Rack.Tracer.call | def call(env)
method = env[REQUEST_METHOD]
context = @tracer.extract(OpenTracing::FORMAT_RACK, env) if @trust_incoming_span
scope = @tracer.start_active_span(
method,
child_of: context,
tags: {
'component' => 'rack',
'span.kind' => 'server',
'http.method' => method,
'http.url' => env[REQUEST_URI]
}
)
span = scope.span
@on_start_span.call(span) if @on_start_span
env['rack.span'] = span
@app.call(env).tap do |status_code, _headers, _body|
span.set_tag('http.status_code', status_code)
route = route_from_env(env)
span.operation_name = route if route
end
rescue *@errors => e
span.set_tag('error', true)
span.log_kv(
event: 'error',
:'error.kind' => e.class.to_s,
:'error.object' => e,
message: e.message,
stack: e.backtrace.join("\n")
)
raise
ensure
begin
scope.close
ensure
@on_finish_span.call(span) if @on_finish_span
end
end | ruby | def call(env)
method = env[REQUEST_METHOD]
context = @tracer.extract(OpenTracing::FORMAT_RACK, env) if @trust_incoming_span
scope = @tracer.start_active_span(
method,
child_of: context,
tags: {
'component' => 'rack',
'span.kind' => 'server',
'http.method' => method,
'http.url' => env[REQUEST_URI]
}
)
span = scope.span
@on_start_span.call(span) if @on_start_span
env['rack.span'] = span
@app.call(env).tap do |status_code, _headers, _body|
span.set_tag('http.status_code', status_code)
route = route_from_env(env)
span.operation_name = route if route
end
rescue *@errors => e
span.set_tag('error', true)
span.log_kv(
event: 'error',
:'error.kind' => e.class.to_s,
:'error.object' => e,
message: e.message,
stack: e.backtrace.join("\n")
)
raise
ensure
begin
scope.close
ensure
@on_finish_span.call(span) if @on_finish_span
end
end | [
"def",
"call",
"(",
"env",
")",
"method",
"=",
"env",
"[",
"REQUEST_METHOD",
"]",
"context",
"=",
"@tracer",
".",
"extract",
"(",
"OpenTracing",
"::",
"FORMAT_RACK",
",",
"env",
")",
"if",
"@trust_incoming_span",
"scope",
"=",
"@tracer",
".",
"start_active_span",
"(",
"method",
",",
"child_of",
":",
"context",
",",
"tags",
":",
"{",
"'component'",
"=>",
"'rack'",
",",
"'span.kind'",
"=>",
"'server'",
",",
"'http.method'",
"=>",
"method",
",",
"'http.url'",
"=>",
"env",
"[",
"REQUEST_URI",
"]",
"}",
")",
"span",
"=",
"scope",
".",
"span",
"@on_start_span",
".",
"call",
"(",
"span",
")",
"if",
"@on_start_span",
"env",
"[",
"'rack.span'",
"]",
"=",
"span",
"@app",
".",
"call",
"(",
"env",
")",
".",
"tap",
"do",
"|",
"status_code",
",",
"_headers",
",",
"_body",
"|",
"span",
".",
"set_tag",
"(",
"'http.status_code'",
",",
"status_code",
")",
"route",
"=",
"route_from_env",
"(",
"env",
")",
"span",
".",
"operation_name",
"=",
"route",
"if",
"route",
"end",
"rescue",
"@errors",
"=>",
"e",
"span",
".",
"set_tag",
"(",
"'error'",
",",
"true",
")",
"span",
".",
"log_kv",
"(",
"event",
":",
"'error'",
",",
":'",
"'",
"=>",
"e",
".",
"class",
".",
"to_s",
",",
":'",
"'",
"=>",
"e",
",",
"message",
":",
"e",
".",
"message",
",",
"stack",
":",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"raise",
"ensure",
"begin",
"scope",
".",
"close",
"ensure",
"@on_finish_span",
".",
"call",
"(",
"span",
")",
"if",
"@on_finish_span",
"end",
"end"
] | Create a new Rack Tracer middleware.
@param app The Rack application/middlewares stack.
@param tracer [OpenTracing::Tracer] A tracer to be used when start_span, and extract
is called.
@param on_start_span [Proc, nil] A callback evaluated after a new span is created.
@param on_finish_span [Proc, nil] A callback evaluated after a span is finished.
@param errors [Array<Class>] An array of error classes to be captured by the tracer
as errors. Errors are **not** muted by the middleware, they're re-raised afterwards. | [
"Create",
"a",
"new",
"Rack",
"Tracer",
"middleware",
"."
] | e0259589a85e3453751806f6fa7425f1c506f399 | https://github.com/opentracing-contrib/ruby-rack-tracer/blob/e0259589a85e3453751806f6fa7425f1c506f399/lib/rack/tracer.rb#L33-L75 | train |
electric-it/minimart | lib/minimart/cli.rb | Minimart.Cli.mirror | def mirror
Minimart::Commands::Mirror.new(options).execute!
rescue Minimart::Error::BaseError => e
Minimart::Error.handle_exception(e)
end | ruby | def mirror
Minimart::Commands::Mirror.new(options).execute!
rescue Minimart::Error::BaseError => e
Minimart::Error.handle_exception(e)
end | [
"def",
"mirror",
"Minimart",
"::",
"Commands",
"::",
"Mirror",
".",
"new",
"(",
"options",
")",
".",
"execute!",
"rescue",
"Minimart",
"::",
"Error",
"::",
"BaseError",
"=>",
"e",
"Minimart",
"::",
"Error",
".",
"handle_exception",
"(",
"e",
")",
"end"
] | Mirror cookbooks specified in an inventory file. | [
"Mirror",
"cookbooks",
"specified",
"in",
"an",
"inventory",
"file",
"."
] | ca64bdc6ebf63a8ae27832ee914f815a160b65dd | https://github.com/electric-it/minimart/blob/ca64bdc6ebf63a8ae27832ee914f815a160b65dd/lib/minimart/cli.rb#L69-L74 | train |
electric-it/minimart | lib/minimart/cli.rb | Minimart.Cli.web | def web
Minimart::Commands::Web.new(options).execute!
rescue Minimart::Error::BaseError => e
Minimart::Error.handle_exception(e)
end | ruby | def web
Minimart::Commands::Web.new(options).execute!
rescue Minimart::Error::BaseError => e
Minimart::Error.handle_exception(e)
end | [
"def",
"web",
"Minimart",
"::",
"Commands",
"::",
"Web",
".",
"new",
"(",
"options",
")",
".",
"execute!",
"rescue",
"Minimart",
"::",
"Error",
"::",
"BaseError",
"=>",
"e",
"Minimart",
"::",
"Error",
".",
"handle_exception",
"(",
"e",
")",
"end"
] | Generate a web interface to download any mirrored cookbooks. | [
"Generate",
"a",
"web",
"interface",
"to",
"download",
"any",
"mirrored",
"cookbooks",
"."
] | ca64bdc6ebf63a8ae27832ee914f815a160b65dd | https://github.com/electric-it/minimart/blob/ca64bdc6ebf63a8ae27832ee914f815a160b65dd/lib/minimart/cli.rb#L103-L108 | train |
yob/em-ftpd | lib/em-ftpd/authentication.rb | EM::FTPD.Authentication.cmd_pass | def cmd_pass(param)
send_response "202 User already logged in" and return unless @user.nil?
send_param_required and return if param.nil?
send_response "530 password with no username" and return if @requested_user.nil?
# return an error message if:
# - the specified username isn't in our system
# - the password is wrong
@driver.authenticate(@requested_user, param) do |result|
if result
@name_prefix = "/"
@user = @requested_user
@requested_user = nil
send_response "230 OK, password correct"
else
@user = nil
send_response "530 incorrect login. not logged in."
end
end
end | ruby | def cmd_pass(param)
send_response "202 User already logged in" and return unless @user.nil?
send_param_required and return if param.nil?
send_response "530 password with no username" and return if @requested_user.nil?
# return an error message if:
# - the specified username isn't in our system
# - the password is wrong
@driver.authenticate(@requested_user, param) do |result|
if result
@name_prefix = "/"
@user = @requested_user
@requested_user = nil
send_response "230 OK, password correct"
else
@user = nil
send_response "530 incorrect login. not logged in."
end
end
end | [
"def",
"cmd_pass",
"(",
"param",
")",
"send_response",
"\"202 User already logged in\"",
"and",
"return",
"unless",
"@user",
".",
"nil?",
"send_param_required",
"and",
"return",
"if",
"param",
".",
"nil?",
"send_response",
"\"530 password with no username\"",
"and",
"return",
"if",
"@requested_user",
".",
"nil?",
"# return an error message if:",
"# - the specified username isn't in our system",
"# - the password is wrong",
"@driver",
".",
"authenticate",
"(",
"@requested_user",
",",
"param",
")",
"do",
"|",
"result",
"|",
"if",
"result",
"@name_prefix",
"=",
"\"/\"",
"@user",
"=",
"@requested_user",
"@requested_user",
"=",
"nil",
"send_response",
"\"230 OK, password correct\"",
"else",
"@user",
"=",
"nil",
"send_response",
"\"530 incorrect login. not logged in.\"",
"end",
"end",
"end"
] | handle the PASS FTP command. This is the second stage of a user logging in | [
"handle",
"the",
"PASS",
"FTP",
"command",
".",
"This",
"is",
"the",
"second",
"stage",
"of",
"a",
"user",
"logging",
"in"
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/authentication.rb#L25-L45 | train |
yob/em-ftpd | lib/em-ftpd/files.rb | EM::FTPD.Files.cmd_dele | def cmd_dele(param)
send_unauthorised and return unless logged_in?
send_param_required and return if param.nil?
path = build_path(param)
@driver.delete_file(path) do |result|
if result
send_response "250 File deleted"
else
send_action_not_taken
end
end
end | ruby | def cmd_dele(param)
send_unauthorised and return unless logged_in?
send_param_required and return if param.nil?
path = build_path(param)
@driver.delete_file(path) do |result|
if result
send_response "250 File deleted"
else
send_action_not_taken
end
end
end | [
"def",
"cmd_dele",
"(",
"param",
")",
"send_unauthorised",
"and",
"return",
"unless",
"logged_in?",
"send_param_required",
"and",
"return",
"if",
"param",
".",
"nil?",
"path",
"=",
"build_path",
"(",
"param",
")",
"@driver",
".",
"delete_file",
"(",
"path",
")",
"do",
"|",
"result",
"|",
"if",
"result",
"send_response",
"\"250 File deleted\"",
"else",
"send_action_not_taken",
"end",
"end",
"end"
] | delete a file | [
"delete",
"a",
"file"
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/files.rb#L7-L20 | train |
yob/em-ftpd | lib/em-ftpd/files.rb | EM::FTPD.Files.cmd_retr | def cmd_retr(param)
send_unauthorised and return unless logged_in?
send_param_required and return if param.nil?
path = build_path(param)
@driver.get_file(path) do |data|
if data
send_response "150 Data transfer starting #{data.size} bytes"
send_outofband_data(data, @restart_pos || 0)
else
send_response "551 file not available"
end
end
end | ruby | def cmd_retr(param)
send_unauthorised and return unless logged_in?
send_param_required and return if param.nil?
path = build_path(param)
@driver.get_file(path) do |data|
if data
send_response "150 Data transfer starting #{data.size} bytes"
send_outofband_data(data, @restart_pos || 0)
else
send_response "551 file not available"
end
end
end | [
"def",
"cmd_retr",
"(",
"param",
")",
"send_unauthorised",
"and",
"return",
"unless",
"logged_in?",
"send_param_required",
"and",
"return",
"if",
"param",
".",
"nil?",
"path",
"=",
"build_path",
"(",
"param",
")",
"@driver",
".",
"get_file",
"(",
"path",
")",
"do",
"|",
"data",
"|",
"if",
"data",
"send_response",
"\"150 Data transfer starting #{data.size} bytes\"",
"send_outofband_data",
"(",
"data",
",",
"@restart_pos",
"||",
"0",
")",
"else",
"send_response",
"\"551 file not available\"",
"end",
"end",
"end"
] | send a file to the client | [
"send",
"a",
"file",
"to",
"the",
"client"
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/files.rb#L33-L47 | train |
yob/em-ftpd | lib/em-ftpd/files.rb | EM::FTPD.Files.cmd_size | def cmd_size(param)
send_unauthorised and return unless logged_in?
send_param_required and return if param.nil?
@driver.bytes(build_path(param)) do |bytes|
if bytes
send_response "213 #{bytes}"
else
send_response "450 file not available"
end
end
end | ruby | def cmd_size(param)
send_unauthorised and return unless logged_in?
send_param_required and return if param.nil?
@driver.bytes(build_path(param)) do |bytes|
if bytes
send_response "213 #{bytes}"
else
send_response "450 file not available"
end
end
end | [
"def",
"cmd_size",
"(",
"param",
")",
"send_unauthorised",
"and",
"return",
"unless",
"logged_in?",
"send_param_required",
"and",
"return",
"if",
"param",
".",
"nil?",
"@driver",
".",
"bytes",
"(",
"build_path",
"(",
"param",
")",
")",
"do",
"|",
"bytes",
"|",
"if",
"bytes",
"send_response",
"\"213 #{bytes}\"",
"else",
"send_response",
"\"450 file not available\"",
"end",
"end",
"end"
] | return the size of a file in bytes | [
"return",
"the",
"size",
"of",
"a",
"file",
"in",
"bytes"
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/files.rb#L73-L84 | train |
yob/em-ftpd | lib/em-ftpd/files.rb | EM::FTPD.Files.cmd_stor | def cmd_stor(param)
send_unauthorised and return unless logged_in?
send_param_required and return if param.nil?
path = build_path(param)
if @driver.respond_to?(:put_file_streamed)
cmd_stor_streamed(path)
elsif @driver.respond_to?(:put_file)
cmd_stor_tempfile(path)
else
raise "driver MUST respond to put_file OR put_file_streamed"
end
end | ruby | def cmd_stor(param)
send_unauthorised and return unless logged_in?
send_param_required and return if param.nil?
path = build_path(param)
if @driver.respond_to?(:put_file_streamed)
cmd_stor_streamed(path)
elsif @driver.respond_to?(:put_file)
cmd_stor_tempfile(path)
else
raise "driver MUST respond to put_file OR put_file_streamed"
end
end | [
"def",
"cmd_stor",
"(",
"param",
")",
"send_unauthorised",
"and",
"return",
"unless",
"logged_in?",
"send_param_required",
"and",
"return",
"if",
"param",
".",
"nil?",
"path",
"=",
"build_path",
"(",
"param",
")",
"if",
"@driver",
".",
"respond_to?",
"(",
":put_file_streamed",
")",
"cmd_stor_streamed",
"(",
"path",
")",
"elsif",
"@driver",
".",
"respond_to?",
"(",
":put_file",
")",
"cmd_stor_tempfile",
"(",
"path",
")",
"else",
"raise",
"\"driver MUST respond to put_file OR put_file_streamed\"",
"end",
"end"
] | save a file from a client | [
"save",
"a",
"file",
"from",
"a",
"client"
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/files.rb#L87-L100 | train |
yob/em-ftpd | lib/em-ftpd/directories.rb | EM::FTPD.Directories.cmd_nlst | def cmd_nlst(param)
send_unauthorised and return unless logged_in?
send_response "150 Opening ASCII mode data connection for file list"
@driver.dir_contents(build_path(param)) do |files|
send_outofband_data(files.map(&:name))
end
end | ruby | def cmd_nlst(param)
send_unauthorised and return unless logged_in?
send_response "150 Opening ASCII mode data connection for file list"
@driver.dir_contents(build_path(param)) do |files|
send_outofband_data(files.map(&:name))
end
end | [
"def",
"cmd_nlst",
"(",
"param",
")",
"send_unauthorised",
"and",
"return",
"unless",
"logged_in?",
"send_response",
"\"150 Opening ASCII mode data connection for file list\"",
"@driver",
".",
"dir_contents",
"(",
"build_path",
"(",
"param",
")",
")",
"do",
"|",
"files",
"|",
"send_outofband_data",
"(",
"files",
".",
"map",
"(",
":name",
")",
")",
"end",
"end"
] | return a listing of the current directory, one per line, each line
separated by the standard FTP EOL sequence. The listing is returned
to the client over a data socket. | [
"return",
"a",
"listing",
"of",
"the",
"current",
"directory",
"one",
"per",
"line",
"each",
"line",
"separated",
"by",
"the",
"standard",
"FTP",
"EOL",
"sequence",
".",
"The",
"listing",
"is",
"returned",
"to",
"the",
"client",
"over",
"a",
"data",
"socket",
"."
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/directories.rb#L49-L56 | train |
yob/em-ftpd | lib/em-ftpd/directories.rb | EM::FTPD.Directories.cmd_list | def cmd_list(param)
send_unauthorised and return unless logged_in?
send_response "150 Opening ASCII mode data connection for file list"
param = '' if param.to_s == '-a'
@driver.dir_contents(build_path(param)) do |files|
now = Time.now
lines = files.map { |item|
sizestr = (item.size || 0).to_s.rjust(12)
"#{item.directory ? 'd' : '-'}#{item.permissions || 'rwxrwxrwx'} 1 #{item.owner || 'owner'} #{item.group || 'group'} #{sizestr} #{(item.time || now).strftime("%b %d %H:%M")} #{item.name}"
}
send_outofband_data(lines)
end
end | ruby | def cmd_list(param)
send_unauthorised and return unless logged_in?
send_response "150 Opening ASCII mode data connection for file list"
param = '' if param.to_s == '-a'
@driver.dir_contents(build_path(param)) do |files|
now = Time.now
lines = files.map { |item|
sizestr = (item.size || 0).to_s.rjust(12)
"#{item.directory ? 'd' : '-'}#{item.permissions || 'rwxrwxrwx'} 1 #{item.owner || 'owner'} #{item.group || 'group'} #{sizestr} #{(item.time || now).strftime("%b %d %H:%M")} #{item.name}"
}
send_outofband_data(lines)
end
end | [
"def",
"cmd_list",
"(",
"param",
")",
"send_unauthorised",
"and",
"return",
"unless",
"logged_in?",
"send_response",
"\"150 Opening ASCII mode data connection for file list\"",
"param",
"=",
"''",
"if",
"param",
".",
"to_s",
"==",
"'-a'",
"@driver",
".",
"dir_contents",
"(",
"build_path",
"(",
"param",
")",
")",
"do",
"|",
"files",
"|",
"now",
"=",
"Time",
".",
"now",
"lines",
"=",
"files",
".",
"map",
"{",
"|",
"item",
"|",
"sizestr",
"=",
"(",
"item",
".",
"size",
"||",
"0",
")",
".",
"to_s",
".",
"rjust",
"(",
"12",
")",
"\"#{item.directory ? 'd' : '-'}#{item.permissions || 'rwxrwxrwx'} 1 #{item.owner || 'owner'} #{item.group || 'group'} #{sizestr} #{(item.time || now).strftime(\"%b %d %H:%M\")} #{item.name}\"",
"}",
"send_outofband_data",
"(",
"lines",
")",
"end",
"end"
] | return a detailed list of files and directories | [
"return",
"a",
"detailed",
"list",
"of",
"files",
"and",
"directories"
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/directories.rb#L67-L81 | train |
yob/em-ftpd | lib/em-ftpd/directories.rb | EM::FTPD.Directories.cmd_rmd | def cmd_rmd(param)
send_unauthorised and return unless logged_in?
send_param_required and return if param.nil?
@driver.delete_dir(build_path(param)) do |result|
if result
send_response "250 Directory deleted."
else
send_action_not_taken
end
end
end | ruby | def cmd_rmd(param)
send_unauthorised and return unless logged_in?
send_param_required and return if param.nil?
@driver.delete_dir(build_path(param)) do |result|
if result
send_response "250 Directory deleted."
else
send_action_not_taken
end
end
end | [
"def",
"cmd_rmd",
"(",
"param",
")",
"send_unauthorised",
"and",
"return",
"unless",
"logged_in?",
"send_param_required",
"and",
"return",
"if",
"param",
".",
"nil?",
"@driver",
".",
"delete_dir",
"(",
"build_path",
"(",
"param",
")",
")",
"do",
"|",
"result",
"|",
"if",
"result",
"send_response",
"\"250 Directory deleted.\"",
"else",
"send_action_not_taken",
"end",
"end",
"end"
] | delete a directory | [
"delete",
"a",
"directory"
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/directories.rb#L93-L104 | train |
yob/em-ftpd | lib/em-ftpd/server.rb | EM::FTPD.Server.parse_request | def parse_request(data)
data.strip!
space = data.index(" ")
if space
cmd = data[0, space]
param = data[space+1, data.length - space]
param = nil if param.strip.size == 0
else
cmd = data
param = nil
end
[cmd.downcase, param]
end | ruby | def parse_request(data)
data.strip!
space = data.index(" ")
if space
cmd = data[0, space]
param = data[space+1, data.length - space]
param = nil if param.strip.size == 0
else
cmd = data
param = nil
end
[cmd.downcase, param]
end | [
"def",
"parse_request",
"(",
"data",
")",
"data",
".",
"strip!",
"space",
"=",
"data",
".",
"index",
"(",
"\" \"",
")",
"if",
"space",
"cmd",
"=",
"data",
"[",
"0",
",",
"space",
"]",
"param",
"=",
"data",
"[",
"space",
"+",
"1",
",",
"data",
".",
"length",
"-",
"space",
"]",
"param",
"=",
"nil",
"if",
"param",
".",
"strip",
".",
"size",
"==",
"0",
"else",
"cmd",
"=",
"data",
"param",
"=",
"nil",
"end",
"[",
"cmd",
".",
"downcase",
",",
"param",
"]",
"end"
] | split a client's request into command and parameter components | [
"split",
"a",
"client",
"s",
"request",
"into",
"command",
"and",
"parameter",
"components"
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L76-L89 | train |
yob/em-ftpd | lib/em-ftpd/server.rb | EM::FTPD.Server.cmd_help | def cmd_help(param)
send_response "214- The following commands are recognized."
commands = COMMANDS
str = ""
commands.sort.each_slice(3) { |slice|
str += " " + slice.join("\t\t") + LBRK
}
send_response str, true
send_response "214 End of list."
end | ruby | def cmd_help(param)
send_response "214- The following commands are recognized."
commands = COMMANDS
str = ""
commands.sort.each_slice(3) { |slice|
str += " " + slice.join("\t\t") + LBRK
}
send_response str, true
send_response "214 End of list."
end | [
"def",
"cmd_help",
"(",
"param",
")",
"send_response",
"\"214- The following commands are recognized.\"",
"commands",
"=",
"COMMANDS",
"str",
"=",
"\"\"",
"commands",
".",
"sort",
".",
"each_slice",
"(",
"3",
")",
"{",
"|",
"slice",
"|",
"str",
"+=",
"\" \"",
"+",
"slice",
".",
"join",
"(",
"\"\\t\\t\"",
")",
"+",
"LBRK",
"}",
"send_response",
"str",
",",
"true",
"send_response",
"\"214 End of list.\"",
"end"
] | handle the HELP FTP command by sending a list of available commands. | [
"handle",
"the",
"HELP",
"FTP",
"command",
"by",
"sending",
"a",
"list",
"of",
"available",
"commands",
"."
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L109-L118 | train |
yob/em-ftpd | lib/em-ftpd/server.rb | EM::FTPD.Server.cmd_pasv | def cmd_pasv(param)
send_unauthorised and return unless logged_in?
host, port = start_passive_socket
p1, p2 = *port.divmod(256)
send_response "227 Entering Passive Mode (" + host.split(".").join(",") + ",#{p1},#{p2})"
end | ruby | def cmd_pasv(param)
send_unauthorised and return unless logged_in?
host, port = start_passive_socket
p1, p2 = *port.divmod(256)
send_response "227 Entering Passive Mode (" + host.split(".").join(",") + ",#{p1},#{p2})"
end | [
"def",
"cmd_pasv",
"(",
"param",
")",
"send_unauthorised",
"and",
"return",
"unless",
"logged_in?",
"host",
",",
"port",
"=",
"start_passive_socket",
"p1",
",",
"p2",
"=",
"port",
".",
"divmod",
"(",
"256",
")",
"send_response",
"\"227 Entering Passive Mode (\"",
"+",
"host",
".",
"split",
"(",
"\".\"",
")",
".",
"join",
"(",
"\",\"",
")",
"+",
"\",#{p1},#{p2})\"",
"end"
] | Passive FTP. At the clients request, listen on a port for an incoming
data connection. The listening socket is opened on a random port, so
the host and port is sent back to the client on the control socket. | [
"Passive",
"FTP",
".",
"At",
"the",
"clients",
"request",
"listen",
"on",
"a",
"port",
"for",
"an",
"incoming",
"data",
"connection",
".",
"The",
"listening",
"socket",
"is",
"opened",
"on",
"a",
"random",
"port",
"so",
"the",
"host",
"and",
"port",
"is",
"sent",
"back",
"to",
"the",
"client",
"on",
"the",
"control",
"socket",
"."
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L156-L164 | train |
yob/em-ftpd | lib/em-ftpd/server.rb | EM::FTPD.Server.cmd_port | def cmd_port(param)
send_unauthorised and return unless logged_in?
send_param_required and return if param.nil?
nums = param.split(',')
port = nums[4].to_i * 256 + nums[5].to_i
host = nums[0..3].join('.')
close_datasocket
puts "connecting to client #{host} on #{port}"
@datasocket = ActiveSocket.open(host, port)
puts "Opened active connection at #{host}:#{port}"
send_response "200 Connection established (#{port})"
rescue
puts "Error opening data connection to #{host}:#{port}"
send_response "425 Data connection failed"
end | ruby | def cmd_port(param)
send_unauthorised and return unless logged_in?
send_param_required and return if param.nil?
nums = param.split(',')
port = nums[4].to_i * 256 + nums[5].to_i
host = nums[0..3].join('.')
close_datasocket
puts "connecting to client #{host} on #{port}"
@datasocket = ActiveSocket.open(host, port)
puts "Opened active connection at #{host}:#{port}"
send_response "200 Connection established (#{port})"
rescue
puts "Error opening data connection to #{host}:#{port}"
send_response "425 Data connection failed"
end | [
"def",
"cmd_port",
"(",
"param",
")",
"send_unauthorised",
"and",
"return",
"unless",
"logged_in?",
"send_param_required",
"and",
"return",
"if",
"param",
".",
"nil?",
"nums",
"=",
"param",
".",
"split",
"(",
"','",
")",
"port",
"=",
"nums",
"[",
"4",
"]",
".",
"to_i",
"*",
"256",
"+",
"nums",
"[",
"5",
"]",
".",
"to_i",
"host",
"=",
"nums",
"[",
"0",
"..",
"3",
"]",
".",
"join",
"(",
"'.'",
")",
"close_datasocket",
"puts",
"\"connecting to client #{host} on #{port}\"",
"@datasocket",
"=",
"ActiveSocket",
".",
"open",
"(",
"host",
",",
"port",
")",
"puts",
"\"Opened active connection at #{host}:#{port}\"",
"send_response",
"\"200 Connection established (#{port})\"",
"rescue",
"puts",
"\"Error opening data connection to #{host}:#{port}\"",
"send_response",
"\"425 Data connection failed\"",
"end"
] | Active FTP. An alternative to Passive FTP. The client has a listening socket
open, waiting for us to connect and establish a data socket. Attempt to
open a connection to the host and port they specify and save the connection,
ready for either end to send something down it. | [
"Active",
"FTP",
".",
"An",
"alternative",
"to",
"Passive",
"FTP",
".",
"The",
"client",
"has",
"a",
"listening",
"socket",
"open",
"waiting",
"for",
"us",
"to",
"connect",
"and",
"establish",
"a",
"data",
"socket",
".",
"Attempt",
"to",
"open",
"a",
"connection",
"to",
"the",
"host",
"and",
"port",
"they",
"specify",
"and",
"save",
"the",
"connection",
"ready",
"for",
"either",
"end",
"to",
"send",
"something",
"down",
"it",
"."
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L178-L195 | train |
yob/em-ftpd | lib/em-ftpd/server.rb | EM::FTPD.Server.cmd_type | def cmd_type(param)
send_unauthorised and return unless logged_in?
send_param_required and return if param.nil?
if param.upcase.eql?("A")
send_response "200 Type set to ASCII"
elsif param.upcase.eql?("I")
send_response "200 Type set to binary"
else
send_response "500 Invalid type"
end
end | ruby | def cmd_type(param)
send_unauthorised and return unless logged_in?
send_param_required and return if param.nil?
if param.upcase.eql?("A")
send_response "200 Type set to ASCII"
elsif param.upcase.eql?("I")
send_response "200 Type set to binary"
else
send_response "500 Invalid type"
end
end | [
"def",
"cmd_type",
"(",
"param",
")",
"send_unauthorised",
"and",
"return",
"unless",
"logged_in?",
"send_param_required",
"and",
"return",
"if",
"param",
".",
"nil?",
"if",
"param",
".",
"upcase",
".",
"eql?",
"(",
"\"A\"",
")",
"send_response",
"\"200 Type set to ASCII\"",
"elsif",
"param",
".",
"upcase",
".",
"eql?",
"(",
"\"I\"",
")",
"send_response",
"\"200 Type set to binary\"",
"else",
"send_response",
"\"500 Invalid type\"",
"end",
"end"
] | like the MODE and STRU commands, TYPE dates back to a time when the FTP
protocol was more aware of the content of the files it was transferring, and
would sometimes be expected to translate things like EOL markers on the fly.
Valid options were A(SCII), I(mage), E(BCDIC) or LN (for local type). Since
we plan to just accept bytes from the client unchanged, I think Image mode is
adequate. The RFC requires we accept ASCII mode however, so accept it, but
ignore it. | [
"like",
"the",
"MODE",
"and",
"STRU",
"commands",
"TYPE",
"dates",
"back",
"to",
"a",
"time",
"when",
"the",
"FTP",
"protocol",
"was",
"more",
"aware",
"of",
"the",
"content",
"of",
"the",
"files",
"it",
"was",
"transferring",
"and",
"would",
"sometimes",
"be",
"expected",
"to",
"translate",
"things",
"like",
"EOL",
"markers",
"on",
"the",
"fly",
"."
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L260-L270 | train |
yob/em-ftpd | lib/em-ftpd/server.rb | EM::FTPD.Server.send_outofband_data | def send_outofband_data(data, restart_pos = 0)
wait_for_datasocket do |datasocket|
if datasocket.nil?
send_response "425 Error establishing connection"
else
if data.is_a?(Array)
data = data.join(LBRK) << LBRK
end
data = StringIO.new(data) if data.kind_of?(String)
data.seek(restart_pos)
if EM.reactor_running?
# send the data out in chunks, as fast as the client can recieve it -- not blocking the reactor in the process
streamer = IOStreamer.new(datasocket, data)
finalize = Proc.new {
close_datasocket
data.close if data.respond_to?(:close) && !data.closed?
}
streamer.callback {
send_response "226 Closing data connection, sent #{streamer.bytes_streamed} bytes"
finalize.call
}
streamer.errback { |ex|
send_response "425 Error while streaming data, sent #{streamer.bytes_streamed} bytes"
finalize.call
raise ex
}
else
# blocks until all data is sent
begin
bytes = 0
data.each do |line|
datasocket.send_data(line)
bytes += line.bytesize
end
send_response "226 Closing data connection, sent #{bytes} bytes"
ensure
close_datasocket
data.close if data.respond_to?(:close)
end
end
end
end
end | ruby | def send_outofband_data(data, restart_pos = 0)
wait_for_datasocket do |datasocket|
if datasocket.nil?
send_response "425 Error establishing connection"
else
if data.is_a?(Array)
data = data.join(LBRK) << LBRK
end
data = StringIO.new(data) if data.kind_of?(String)
data.seek(restart_pos)
if EM.reactor_running?
# send the data out in chunks, as fast as the client can recieve it -- not blocking the reactor in the process
streamer = IOStreamer.new(datasocket, data)
finalize = Proc.new {
close_datasocket
data.close if data.respond_to?(:close) && !data.closed?
}
streamer.callback {
send_response "226 Closing data connection, sent #{streamer.bytes_streamed} bytes"
finalize.call
}
streamer.errback { |ex|
send_response "425 Error while streaming data, sent #{streamer.bytes_streamed} bytes"
finalize.call
raise ex
}
else
# blocks until all data is sent
begin
bytes = 0
data.each do |line|
datasocket.send_data(line)
bytes += line.bytesize
end
send_response "226 Closing data connection, sent #{bytes} bytes"
ensure
close_datasocket
data.close if data.respond_to?(:close)
end
end
end
end
end | [
"def",
"send_outofband_data",
"(",
"data",
",",
"restart_pos",
"=",
"0",
")",
"wait_for_datasocket",
"do",
"|",
"datasocket",
"|",
"if",
"datasocket",
".",
"nil?",
"send_response",
"\"425 Error establishing connection\"",
"else",
"if",
"data",
".",
"is_a?",
"(",
"Array",
")",
"data",
"=",
"data",
".",
"join",
"(",
"LBRK",
")",
"<<",
"LBRK",
"end",
"data",
"=",
"StringIO",
".",
"new",
"(",
"data",
")",
"if",
"data",
".",
"kind_of?",
"(",
"String",
")",
"data",
".",
"seek",
"(",
"restart_pos",
")",
"if",
"EM",
".",
"reactor_running?",
"# send the data out in chunks, as fast as the client can recieve it -- not blocking the reactor in the process",
"streamer",
"=",
"IOStreamer",
".",
"new",
"(",
"datasocket",
",",
"data",
")",
"finalize",
"=",
"Proc",
".",
"new",
"{",
"close_datasocket",
"data",
".",
"close",
"if",
"data",
".",
"respond_to?",
"(",
":close",
")",
"&&",
"!",
"data",
".",
"closed?",
"}",
"streamer",
".",
"callback",
"{",
"send_response",
"\"226 Closing data connection, sent #{streamer.bytes_streamed} bytes\"",
"finalize",
".",
"call",
"}",
"streamer",
".",
"errback",
"{",
"|",
"ex",
"|",
"send_response",
"\"425 Error while streaming data, sent #{streamer.bytes_streamed} bytes\"",
"finalize",
".",
"call",
"raise",
"ex",
"}",
"else",
"# blocks until all data is sent",
"begin",
"bytes",
"=",
"0",
"data",
".",
"each",
"do",
"|",
"line",
"|",
"datasocket",
".",
"send_data",
"(",
"line",
")",
"bytes",
"+=",
"line",
".",
"bytesize",
"end",
"send_response",
"\"226 Closing data connection, sent #{bytes} bytes\"",
"ensure",
"close_datasocket",
"data",
".",
"close",
"if",
"data",
".",
"respond_to?",
"(",
":close",
")",
"end",
"end",
"end",
"end",
"end"
] | send data to the client across the data socket.
The data socket is NOT guaranteed to be setup by the time this method runs.
If it isn't ready yet, exit the method and try again on the next reactor
tick. This is particularly likely with some clients that operate in passive
mode. They get a message on the control port with the data port details, so
they start up a new data connection AND send they command that will use it
in close succession.
The data port setup needs to complete a TCP handshake before it will be
ready to use, so it may take a few RTTs after the command is received at
the server before the data socket is ready. | [
"send",
"data",
"to",
"the",
"client",
"across",
"the",
"data",
"socket",
"."
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L285-L329 | train |
yob/em-ftpd | lib/em-ftpd/server.rb | EM::FTPD.Server.wait_for_datasocket | def wait_for_datasocket(interval = 0.1, &block)
if @datasocket.nil? && interval < 25
if EM.reactor_running?
EventMachine.add_timer(interval) { wait_for_datasocket(interval * 2, &block) }
else
sleep interval
wait_for_datasocket(interval * 2, &block)
end
return
end
yield @datasocket
end | ruby | def wait_for_datasocket(interval = 0.1, &block)
if @datasocket.nil? && interval < 25
if EM.reactor_running?
EventMachine.add_timer(interval) { wait_for_datasocket(interval * 2, &block) }
else
sleep interval
wait_for_datasocket(interval * 2, &block)
end
return
end
yield @datasocket
end | [
"def",
"wait_for_datasocket",
"(",
"interval",
"=",
"0.1",
",",
"&",
"block",
")",
"if",
"@datasocket",
".",
"nil?",
"&&",
"interval",
"<",
"25",
"if",
"EM",
".",
"reactor_running?",
"EventMachine",
".",
"add_timer",
"(",
"interval",
")",
"{",
"wait_for_datasocket",
"(",
"interval",
"*",
"2",
",",
"block",
")",
"}",
"else",
"sleep",
"interval",
"wait_for_datasocket",
"(",
"interval",
"*",
"2",
",",
"block",
")",
"end",
"return",
"end",
"yield",
"@datasocket",
"end"
] | waits for the data socket to be established | [
"waits",
"for",
"the",
"data",
"socket",
"to",
"be",
"established"
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L332-L343 | train |
yob/em-ftpd | lib/em-ftpd/server.rb | EM::FTPD.Server.receive_outofband_data | def receive_outofband_data(&block)
wait_for_datasocket do |datasocket|
if datasocket.nil?
send_response "425 Error establishing connection"
yield false
else
# let the client know we're ready to start
send_response "150 Data transfer starting"
datasocket.callback do |data|
block.call(data)
end
end
end
end | ruby | def receive_outofband_data(&block)
wait_for_datasocket do |datasocket|
if datasocket.nil?
send_response "425 Error establishing connection"
yield false
else
# let the client know we're ready to start
send_response "150 Data transfer starting"
datasocket.callback do |data|
block.call(data)
end
end
end
end | [
"def",
"receive_outofband_data",
"(",
"&",
"block",
")",
"wait_for_datasocket",
"do",
"|",
"datasocket",
"|",
"if",
"datasocket",
".",
"nil?",
"send_response",
"\"425 Error establishing connection\"",
"yield",
"false",
"else",
"# let the client know we're ready to start",
"send_response",
"\"150 Data transfer starting\"",
"datasocket",
".",
"callback",
"do",
"|",
"data",
"|",
"block",
".",
"call",
"(",
"data",
")",
"end",
"end",
"end",
"end"
] | receive a file data from the client across the data socket.
The data socket is NOT guaranteed to be setup by the time this method runs.
If this happens, exit the method early and try again later. See the method
comments to send_outofband_data for further explanation. | [
"receive",
"a",
"file",
"data",
"from",
"the",
"client",
"across",
"the",
"data",
"socket",
"."
] | 27565d7d8ddab17e6538936355c56a9184a97a95 | https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L351-L366 | train |
tyrauber/census_api | lib/census_api/client.rb | CensusApi.Client.where | def where(options={})
options.merge!(key: @api_key, vintage: @api_vintage)
fail "Client requires a dataset (#{DATASETS})." if @dataset.nil?
[:fields, :level].each do |f|
fail ArgumentError, "#{f} is a requied parameter" if options[f].nil?
end
options[:within] = [options[:within]] unless options[:within].nil?
Request.find(dataset, options)
end | ruby | def where(options={})
options.merge!(key: @api_key, vintage: @api_vintage)
fail "Client requires a dataset (#{DATASETS})." if @dataset.nil?
[:fields, :level].each do |f|
fail ArgumentError, "#{f} is a requied parameter" if options[f].nil?
end
options[:within] = [options[:within]] unless options[:within].nil?
Request.find(dataset, options)
end | [
"def",
"where",
"(",
"options",
"=",
"{",
"}",
")",
"options",
".",
"merge!",
"(",
"key",
":",
"@api_key",
",",
"vintage",
":",
"@api_vintage",
")",
"fail",
"\"Client requires a dataset (#{DATASETS}).\"",
"if",
"@dataset",
".",
"nil?",
"[",
":fields",
",",
":level",
"]",
".",
"each",
"do",
"|",
"f",
"|",
"fail",
"ArgumentError",
",",
"\"#{f} is a requied parameter\"",
"if",
"options",
"[",
"f",
"]",
".",
"nil?",
"end",
"options",
"[",
":within",
"]",
"=",
"[",
"options",
"[",
":within",
"]",
"]",
"unless",
"options",
"[",
":within",
"]",
".",
"nil?",
"Request",
".",
"find",
"(",
"dataset",
",",
"options",
")",
"end"
] | can add more datasets as support becomes available | [
"can",
"add",
"more",
"datasets",
"as",
"support",
"becomes",
"available"
] | 0b31e7617287c055afc5ed732e4aadf9213fc8b0 | https://github.com/tyrauber/census_api/blob/0b31e7617287c055afc5ed732e4aadf9213fc8b0/lib/census_api/client.rb#L26-L34 | train |
chrislee35/dnsbl-client | lib/dnsbl/client.rb | DNSBL.Client.add_dnsbl | def add_dnsbl(name,domain,type='ip',codes={"0"=>"OK","127.0.0.2"=>"Blacklisted"})
@dnsbls[name] = codes
@dnsbls[name]['domain'] = domain
@dnsbls[name]['type'] = type
end | ruby | def add_dnsbl(name,domain,type='ip',codes={"0"=>"OK","127.0.0.2"=>"Blacklisted"})
@dnsbls[name] = codes
@dnsbls[name]['domain'] = domain
@dnsbls[name]['type'] = type
end | [
"def",
"add_dnsbl",
"(",
"name",
",",
"domain",
",",
"type",
"=",
"'ip'",
",",
"codes",
"=",
"{",
"\"0\"",
"=>",
"\"OK\"",
",",
"\"127.0.0.2\"",
"=>",
"\"Blacklisted\"",
"}",
")",
"@dnsbls",
"[",
"name",
"]",
"=",
"codes",
"@dnsbls",
"[",
"name",
"]",
"[",
"'domain'",
"]",
"=",
"domain",
"@dnsbls",
"[",
"name",
"]",
"[",
"'type'",
"]",
"=",
"type",
"end"
] | allows the adding of a new DNSBL to the set of configured DNSBLs | [
"allows",
"the",
"adding",
"of",
"a",
"new",
"DNSBL",
"to",
"the",
"set",
"of",
"configured",
"DNSBLs"
] | d88bb5eae3dfd03c418f67ae5767234a862a92b8 | https://github.com/chrislee35/dnsbl-client/blob/d88bb5eae3dfd03c418f67ae5767234a862a92b8/lib/dnsbl/client.rb#L96-L100 | train |
chrislee35/dnsbl-client | lib/dnsbl/client.rb | DNSBL.Client._encode_query | def _encode_query(item,itemtype,domain,apikey=nil)
label = nil
if itemtype == 'ip'
label = item.split(/\./).reverse.join(".")
elsif itemtype == 'domain'
label = normalize(item)
end
lookup = "#{label}.#{domain}"
if apikey
lookup = "#{apikey}.#{lookup}"
end
txid = lookup.sum
message = Resolv::DNS::Message.new(txid)
message.rd = 1
message.add_question(lookup,Resolv::DNS::Resource::IN::A)
message.encode
end | ruby | def _encode_query(item,itemtype,domain,apikey=nil)
label = nil
if itemtype == 'ip'
label = item.split(/\./).reverse.join(".")
elsif itemtype == 'domain'
label = normalize(item)
end
lookup = "#{label}.#{domain}"
if apikey
lookup = "#{apikey}.#{lookup}"
end
txid = lookup.sum
message = Resolv::DNS::Message.new(txid)
message.rd = 1
message.add_question(lookup,Resolv::DNS::Resource::IN::A)
message.encode
end | [
"def",
"_encode_query",
"(",
"item",
",",
"itemtype",
",",
"domain",
",",
"apikey",
"=",
"nil",
")",
"label",
"=",
"nil",
"if",
"itemtype",
"==",
"'ip'",
"label",
"=",
"item",
".",
"split",
"(",
"/",
"\\.",
"/",
")",
".",
"reverse",
".",
"join",
"(",
"\".\"",
")",
"elsif",
"itemtype",
"==",
"'domain'",
"label",
"=",
"normalize",
"(",
"item",
")",
"end",
"lookup",
"=",
"\"#{label}.#{domain}\"",
"if",
"apikey",
"lookup",
"=",
"\"#{apikey}.#{lookup}\"",
"end",
"txid",
"=",
"lookup",
".",
"sum",
"message",
"=",
"Resolv",
"::",
"DNS",
"::",
"Message",
".",
"new",
"(",
"txid",
")",
"message",
".",
"rd",
"=",
"1",
"message",
".",
"add_question",
"(",
"lookup",
",",
"Resolv",
"::",
"DNS",
"::",
"Resource",
"::",
"IN",
"::",
"A",
")",
"message",
".",
"encode",
"end"
] | converts an ip or a hostname into the DNS query packet requires to lookup the result | [
"converts",
"an",
"ip",
"or",
"a",
"hostname",
"into",
"the",
"DNS",
"query",
"packet",
"requires",
"to",
"lookup",
"the",
"result"
] | d88bb5eae3dfd03c418f67ae5767234a862a92b8 | https://github.com/chrislee35/dnsbl-client/blob/d88bb5eae3dfd03c418f67ae5767234a862a92b8/lib/dnsbl/client.rb#L108-L124 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.