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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
nosolosoftware/runnable
lib/runnable.rb
Runnable.ClassMethods.define_command
def define_command( name, opts = {}, &block ) blocking = opts[:blocking] || false log_path = opts[:log_path] || false commands[name] = { :blocking => blocking } define_method( name ) do |*args| if block run name, block.call(*args), log_path else run name, nil, log_path end join if blocking end end
ruby
def define_command( name, opts = {}, &block ) blocking = opts[:blocking] || false log_path = opts[:log_path] || false commands[name] = { :blocking => blocking } define_method( name ) do |*args| if block run name, block.call(*args), log_path else run name, nil, log_path end join if blocking end end
[ "def", "define_command", "(", "name", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "blocking", "=", "opts", "[", ":blocking", "]", "||", "false", "log_path", "=", "opts", "[", ":log_path", "]", "||", "false", "commands", "[", "name", "]", "=", "{", ":blocking", "=>", "blocking", "}", "define_method", "(", "name", ")", "do", "|", "*", "args", "|", "if", "block", "run", "name", ",", "block", ".", "call", "(", "*", "args", ")", ",", "log_path", "else", "run", "name", ",", "nil", ",", "log_path", "end", "join", "if", "blocking", "end", "end" ]
Create a user definde command @return [nil] @param [Symbol] name The user defined command name @param [Hash] options Options. @option options :blocking (false) Describe if the execution is blocking or non-blocking @option options :log_path (false) Path used to store logs # (dont store logs if no path specified)
[ "Create", "a", "user", "definde", "command" ]
32a03690c24d18122f698519a052f8176ad7044c
https://github.com/nosolosoftware/runnable/blob/32a03690c24d18122f698519a052f8176ad7044c/lib/runnable.rb#L62-L76
train
nosolosoftware/runnable
lib/runnable.rb
Runnable.ClassMethods.method_missing
def method_missing( name, *opts ) raise NoMethodError.new( name.to_s ) unless name.to_s =~ /([a-z]*)_([a-z]*)/ # command_processors if $2 == "processors" commands[$1.to_sym][:outputs] = opts.first[:outputs] commands[$1.to_sym][:exceptions] = opts.first[:exceptions] end end
ruby
def method_missing( name, *opts ) raise NoMethodError.new( name.to_s ) unless name.to_s =~ /([a-z]*)_([a-z]*)/ # command_processors if $2 == "processors" commands[$1.to_sym][:outputs] = opts.first[:outputs] commands[$1.to_sym][:exceptions] = opts.first[:exceptions] end end
[ "def", "method_missing", "(", "name", ",", "*", "opts", ")", "raise", "NoMethodError", ".", "new", "(", "name", ".", "to_s", ")", "unless", "name", ".", "to_s", "=~", "/", "/", "if", "$2", "==", "\"processors\"", "commands", "[", "$1", ".", "to_sym", "]", "[", ":outputs", "]", "=", "opts", ".", "first", "[", ":outputs", "]", "commands", "[", "$1", ".", "to_sym", "]", "[", ":exceptions", "]", "=", "opts", ".", "first", "[", ":exceptions", "]", "end", "end" ]
Method missing processing for the command processors
[ "Method", "missing", "processing", "for", "the", "command", "processors" ]
32a03690c24d18122f698519a052f8176ad7044c
https://github.com/nosolosoftware/runnable/blob/32a03690c24d18122f698519a052f8176ad7044c/lib/runnable.rb#L92-L100
train
sosedoff/grooveshark
lib/grooveshark/user.rb
Grooveshark.User.library_remove
def library_remove(song) fail ArgumentError, 'Song object required' unless song.is_a?(Song) req = { userID: @id, songID: song.id, albumID: song.album_id, artistID: song.artist_id } @client.request('userRemoveSongFromLibrary', req) end
ruby
def library_remove(song) fail ArgumentError, 'Song object required' unless song.is_a?(Song) req = { userID: @id, songID: song.id, albumID: song.album_id, artistID: song.artist_id } @client.request('userRemoveSongFromLibrary', req) end
[ "def", "library_remove", "(", "song", ")", "fail", "ArgumentError", ",", "'Song object required'", "unless", "song", ".", "is_a?", "(", "Song", ")", "req", "=", "{", "userID", ":", "@id", ",", "songID", ":", "song", ".", "id", ",", "albumID", ":", "song", ".", "album_id", ",", "artistID", ":", "song", ".", "artist_id", "}", "@client", ".", "request", "(", "'userRemoveSongFromLibrary'", ",", "req", ")", "end" ]
Remove song from user library
[ "Remove", "song", "from", "user", "library" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/user.rb#L59-L66
train
sosedoff/grooveshark
lib/grooveshark/user.rb
Grooveshark.User.get_playlist
def get_playlist(id) result = playlists.select { |p| p.id == id } result.nil? ? nil : result.first end
ruby
def get_playlist(id) result = playlists.select { |p| p.id == id } result.nil? ? nil : result.first end
[ "def", "get_playlist", "(", "id", ")", "result", "=", "playlists", ".", "select", "{", "|", "p", "|", "p", ".", "id", "==", "id", "}", "result", ".", "nil?", "?", "nil", ":", "result", ".", "first", "end" ]
Get playlist by ID
[ "Get", "playlist", "by", "ID" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/user.rb#L87-L90
train
sosedoff/grooveshark
lib/grooveshark/user.rb
Grooveshark.User.create_playlist
def create_playlist(name, description = '', songs = []) @client.request('createPlaylist', 'playlistName' => name, 'playlistAbout' => description, 'songIDs' => songs.map do |s| s.is_a?(Song) ? s.id : s.to_s end) end
ruby
def create_playlist(name, description = '', songs = []) @client.request('createPlaylist', 'playlistName' => name, 'playlistAbout' => description, 'songIDs' => songs.map do |s| s.is_a?(Song) ? s.id : s.to_s end) end
[ "def", "create_playlist", "(", "name", ",", "description", "=", "''", ",", "songs", "=", "[", "]", ")", "@client", ".", "request", "(", "'createPlaylist'", ",", "'playlistName'", "=>", "name", ",", "'playlistAbout'", "=>", "description", ",", "'songIDs'", "=>", "songs", ".", "map", "do", "|", "s", "|", "s", ".", "is_a?", "(", "Song", ")", "?", "s", ".", "id", ":", "s", ".", "to_s", "end", ")", "end" ]
Create new user playlist
[ "Create", "new", "user", "playlist" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/user.rb#L95-L102
train
sosedoff/grooveshark
lib/grooveshark/user.rb
Grooveshark.User.add_favorite
def add_favorite(song) song_id = song.is_a?(Song) ? song.id : song @client.request('favorite', what: 'Song', ID: song_id) end
ruby
def add_favorite(song) song_id = song.is_a?(Song) ? song.id : song @client.request('favorite', what: 'Song', ID: song_id) end
[ "def", "add_favorite", "(", "song", ")", "song_id", "=", "song", ".", "is_a?", "(", "Song", ")", "?", "song", ".", "id", ":", "song", "@client", ".", "request", "(", "'favorite'", ",", "what", ":", "'Song'", ",", "ID", ":", "song_id", ")", "end" ]
Add song to favorites
[ "Add", "song", "to", "favorites" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/user.rb#L116-L119
train
4rlm/crm_formatter
lib/crm_formatter/phone.rb
CrmFormatter.Phone.check_phone_status
def check_phone_status(hsh) phone = hsh[:phone] phone_f = hsh[:phone_f] status = 'invalid' status = phone != phone_f ? 'formatted' : 'unchanged' if phone && phone_f hsh[:phone_status] = status if status.present? hsh end
ruby
def check_phone_status(hsh) phone = hsh[:phone] phone_f = hsh[:phone_f] status = 'invalid' status = phone != phone_f ? 'formatted' : 'unchanged' if phone && phone_f hsh[:phone_status] = status if status.present? hsh end
[ "def", "check_phone_status", "(", "hsh", ")", "phone", "=", "hsh", "[", ":phone", "]", "phone_f", "=", "hsh", "[", ":phone_f", "]", "status", "=", "'invalid'", "status", "=", "phone", "!=", "phone_f", "?", "'formatted'", ":", "'unchanged'", "if", "phone", "&&", "phone_f", "hsh", "[", ":phone_status", "]", "=", "status", "if", "status", ".", "present?", "hsh", "end" ]
COMPARE ORIGINAL AND FORMATTED PHONE
[ "COMPARE", "ORIGINAL", "AND", "FORMATTED", "PHONE" ]
5060d27552a3871257cd08612c8e93b7b2b6a350
https://github.com/4rlm/crm_formatter/blob/5060d27552a3871257cd08612c8e93b7b2b6a350/lib/crm_formatter/phone.rb#L20-L27
train
arrac/eluka
lib/eluka/model.rb
Eluka.Model.add
def add (data, label) raise "No meaningful label associated with data" unless ([:positive, :negative].include? label) #Create a data point in the vector space from the datum given data_point = Eluka::DataPoint.new(data, @analyzer) #Add the data point to the feature space #Expand the training feature space to include the data point @fv_train.add(data_point.vector, @labels[label]) end
ruby
def add (data, label) raise "No meaningful label associated with data" unless ([:positive, :negative].include? label) #Create a data point in the vector space from the datum given data_point = Eluka::DataPoint.new(data, @analyzer) #Add the data point to the feature space #Expand the training feature space to include the data point @fv_train.add(data_point.vector, @labels[label]) end
[ "def", "add", "(", "data", ",", "label", ")", "raise", "\"No meaningful label associated with data\"", "unless", "(", "[", ":positive", ",", ":negative", "]", ".", "include?", "label", ")", "data_point", "=", "Eluka", "::", "DataPoint", ".", "new", "(", "data", ",", "@analyzer", ")", "@fv_train", ".", "add", "(", "data_point", ".", "vector", ",", "@labels", "[", "label", "]", ")", "end" ]
Initialize the classifier with sane defaults if customised data is not provided Adds a data point to the training data
[ "Initialize", "the", "classifier", "with", "sane", "defaults", "if", "customised", "data", "is", "not", "provided", "Adds", "a", "data", "point", "to", "the", "training", "data" ]
1293f0cc6f9810a1a289ad74c8fab234db786212
https://github.com/arrac/eluka/blob/1293f0cc6f9810a1a289ad74c8fab234db786212/lib/eluka/model.rb#L61-L70
train
rapid7/rex-sslscan
lib/rex/sslscan/result.rb
Rex::SSLScan.Result.add_cipher
def add_cipher(version, cipher, key_length, status) unless @supported_versions.include? version raise ArgumentError, "Must be a supported SSL Version" end unless OpenSSL::SSL::SSLContext.new(version).ciphers.flatten.include?(cipher) || @deprecated_weak_ciphers.include?(cipher) raise ArgumentError, "Must be a valid SSL Cipher for #{version}!" end unless key_length.kind_of? Integer raise ArgumentError, "Must supply a valid key length" end unless [:accepted, :rejected].include? status raise ArgumentError, "Status must be either :accepted or :rejected" end strong_cipher_ctx = OpenSSL::SSL::SSLContext.new(version) # OpenSSL Directive For Strong Ciphers # See: http://www.rapid7.com/vulndb/lookup/ssl-weak-ciphers strong_cipher_ctx.ciphers = "ALL:!aNULL:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM" if strong_cipher_ctx.ciphers.flatten.include? cipher weak = false else weak = true end cipher_details = {:version => version, :cipher => cipher, :key_length => key_length, :weak => weak, :status => status} @ciphers << cipher_details end
ruby
def add_cipher(version, cipher, key_length, status) unless @supported_versions.include? version raise ArgumentError, "Must be a supported SSL Version" end unless OpenSSL::SSL::SSLContext.new(version).ciphers.flatten.include?(cipher) || @deprecated_weak_ciphers.include?(cipher) raise ArgumentError, "Must be a valid SSL Cipher for #{version}!" end unless key_length.kind_of? Integer raise ArgumentError, "Must supply a valid key length" end unless [:accepted, :rejected].include? status raise ArgumentError, "Status must be either :accepted or :rejected" end strong_cipher_ctx = OpenSSL::SSL::SSLContext.new(version) # OpenSSL Directive For Strong Ciphers # See: http://www.rapid7.com/vulndb/lookup/ssl-weak-ciphers strong_cipher_ctx.ciphers = "ALL:!aNULL:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM" if strong_cipher_ctx.ciphers.flatten.include? cipher weak = false else weak = true end cipher_details = {:version => version, :cipher => cipher, :key_length => key_length, :weak => weak, :status => status} @ciphers << cipher_details end
[ "def", "add_cipher", "(", "version", ",", "cipher", ",", "key_length", ",", "status", ")", "unless", "@supported_versions", ".", "include?", "version", "raise", "ArgumentError", ",", "\"Must be a supported SSL Version\"", "end", "unless", "OpenSSL", "::", "SSL", "::", "SSLContext", ".", "new", "(", "version", ")", ".", "ciphers", ".", "flatten", ".", "include?", "(", "cipher", ")", "||", "@deprecated_weak_ciphers", ".", "include?", "(", "cipher", ")", "raise", "ArgumentError", ",", "\"Must be a valid SSL Cipher for #{version}!\"", "end", "unless", "key_length", ".", "kind_of?", "Integer", "raise", "ArgumentError", ",", "\"Must supply a valid key length\"", "end", "unless", "[", ":accepted", ",", ":rejected", "]", ".", "include?", "status", "raise", "ArgumentError", ",", "\"Status must be either :accepted or :rejected\"", "end", "strong_cipher_ctx", "=", "OpenSSL", "::", "SSL", "::", "SSLContext", ".", "new", "(", "version", ")", "strong_cipher_ctx", ".", "ciphers", "=", "\"ALL:!aNULL:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM\"", "if", "strong_cipher_ctx", ".", "ciphers", ".", "flatten", ".", "include?", "cipher", "weak", "=", "false", "else", "weak", "=", "true", "end", "cipher_details", "=", "{", ":version", "=>", "version", ",", ":cipher", "=>", "cipher", ",", ":key_length", "=>", "key_length", ",", ":weak", "=>", "weak", ",", ":status", "=>", "status", "}", "@ciphers", "<<", "cipher_details", "end" ]
Adds the details of a cipher test to the Result object. @param version [Symbol] the SSL Version @param cipher [String] the SSL cipher @param key_length [Integer] the length of encryption key @param status [Symbol] :accepted or :rejected
[ "Adds", "the", "details", "of", "a", "cipher", "test", "to", "the", "Result", "object", "." ]
a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a
https://github.com/rapid7/rex-sslscan/blob/a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a/lib/rex/sslscan/result.rb#L143-L170
train
talis/blueprint_rb
lib/blueprint_ruby_client/api/asset_type_templates_api.rb
BlueprintClient.AssetTypeTemplatesApi.add
def add(namespace, asset_type, template_body, opts = {}) data, _status_code, _headers = add_with_http_info(namespace, asset_type, template_body, opts) return data end
ruby
def add(namespace, asset_type, template_body, opts = {}) data, _status_code, _headers = add_with_http_info(namespace, asset_type, template_body, opts) return data end
[ "def", "add", "(", "namespace", ",", "asset_type", ",", "template_body", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "add_with_http_info", "(", "namespace", ",", "asset_type", ",", "template_body", ",", "opts", ")", "return", "data", "end" ]
Configure a template for a given asset type @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param asset_type subtype of Asset, e.g. &#39;textbooks&#39;, &#39;digitisations&#39;, etc. @param template_body template body @param [Hash] opts the optional parameters @return [TemplateBody]
[ "Configure", "a", "template", "for", "a", "given", "asset", "type" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/asset_type_templates_api.rb#L30-L33
train
talis/blueprint_rb
lib/blueprint_ruby_client/api/asset_type_templates_api.rb
BlueprintClient.AssetTypeTemplatesApi.delete
def delete(namespace, asset_type, opts = {}) data, _status_code, _headers = delete_with_http_info(namespace, asset_type, opts) return data end
ruby
def delete(namespace, asset_type, opts = {}) data, _status_code, _headers = delete_with_http_info(namespace, asset_type, opts) return data end
[ "def", "delete", "(", "namespace", ",", "asset_type", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "delete_with_http_info", "(", "namespace", ",", "asset_type", ",", "opts", ")", "return", "data", "end" ]
Delete a template for a given asset type @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param asset_type subtype of Asset, e.g. &#39;textbooks&#39;, &#39;digitisations&#39;, etc. @param [Hash] opts the optional parameters @return [TemplateBody]
[ "Delete", "a", "template", "for", "a", "given", "asset", "type" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/asset_type_templates_api.rb#L114-L117
train
talis/blueprint_rb
lib/blueprint_ruby_client/api/asset_type_templates_api.rb
BlueprintClient.AssetTypeTemplatesApi.put
def put(namespace, asset_type, template_body, opts = {}) data, _status_code, _headers = put_with_http_info(namespace, asset_type, template_body, opts) return data end
ruby
def put(namespace, asset_type, template_body, opts = {}) data, _status_code, _headers = put_with_http_info(namespace, asset_type, template_body, opts) return data end
[ "def", "put", "(", "namespace", ",", "asset_type", ",", "template_body", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "put_with_http_info", "(", "namespace", ",", "asset_type", ",", "template_body", ",", "opts", ")", "return", "data", "end" ]
update a template for a given asset type @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param asset_type subtype of Asset, e.g. &#39;textbooks&#39;, &#39;digitisations&#39;, etc. @param template_body template body @param [Hash] opts the optional parameters @return [TemplateBody]
[ "update", "a", "template", "for", "a", "given", "asset", "type" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/asset_type_templates_api.rb#L190-L193
train
mikisvaz/rbbt-util
lib/rbbt/util/log/progress/report.rb
Log.ProgressBar.thr_msg
def thr_msg if @history.nil? @history ||= [[@ticks, Time.now] ] else @history << [@ticks, Time.now] max_history ||= case when @ticks > 20 count = @ticks - @last_count count = 1 if count == 0 if @max times = @max / count num = times / 20 num = 2 if num < 2 else num = 10 end count * num else 20 end max_history = 30 if max_history > 30 @history.shift if @history.length > max_history end @mean_max ||= 0 if @history.length > 3 sticks, stime = @history.first ssticks, sstime = @history[-3] lticks, ltime = @history.last mean = @mean = (lticks - sticks).to_f / (ltime - stime) short_mean = (lticks - ssticks).to_f / (ltime - sstime) @mean_max = mean if mean > @mean_max end if short_mean thr = short_mean else thr = begin (@ticks || 1) / (Time.now - @start) rescue 1 end end thr = 0.0000001 if thr == 0 if mean.nil? or mean.to_i > 1 str = "#{ Log.color :blue, thr.to_i.to_s } per sec." #str << " #{ Log.color :yellow, mean.to_i.to_s } avg. #{Log.color :yellow, @mean_max.to_i.to_s} max." if @mean_max > 0 else str = "#{ Log.color :blue, (1/thr).ceil.to_s } secs each" #str << " #{ Log.color :yellow, (1/mean).ceil.to_s } avg. #{Log.color :yellow, (1/@mean_max).ceil.to_s} min." if @mean_max > 0 end str end
ruby
def thr_msg if @history.nil? @history ||= [[@ticks, Time.now] ] else @history << [@ticks, Time.now] max_history ||= case when @ticks > 20 count = @ticks - @last_count count = 1 if count == 0 if @max times = @max / count num = times / 20 num = 2 if num < 2 else num = 10 end count * num else 20 end max_history = 30 if max_history > 30 @history.shift if @history.length > max_history end @mean_max ||= 0 if @history.length > 3 sticks, stime = @history.first ssticks, sstime = @history[-3] lticks, ltime = @history.last mean = @mean = (lticks - sticks).to_f / (ltime - stime) short_mean = (lticks - ssticks).to_f / (ltime - sstime) @mean_max = mean if mean > @mean_max end if short_mean thr = short_mean else thr = begin (@ticks || 1) / (Time.now - @start) rescue 1 end end thr = 0.0000001 if thr == 0 if mean.nil? or mean.to_i > 1 str = "#{ Log.color :blue, thr.to_i.to_s } per sec." #str << " #{ Log.color :yellow, mean.to_i.to_s } avg. #{Log.color :yellow, @mean_max.to_i.to_s} max." if @mean_max > 0 else str = "#{ Log.color :blue, (1/thr).ceil.to_s } secs each" #str << " #{ Log.color :yellow, (1/mean).ceil.to_s } avg. #{Log.color :yellow, (1/@mean_max).ceil.to_s} min." if @mean_max > 0 end str end
[ "def", "thr_msg", "if", "@history", ".", "nil?", "@history", "||=", "[", "[", "@ticks", ",", "Time", ".", "now", "]", "]", "else", "@history", "<<", "[", "@ticks", ",", "Time", ".", "now", "]", "max_history", "||=", "case", "when", "@ticks", ">", "20", "count", "=", "@ticks", "-", "@last_count", "count", "=", "1", "if", "count", "==", "0", "if", "@max", "times", "=", "@max", "/", "count", "num", "=", "times", "/", "20", "num", "=", "2", "if", "num", "<", "2", "else", "num", "=", "10", "end", "count", "*", "num", "else", "20", "end", "max_history", "=", "30", "if", "max_history", ">", "30", "@history", ".", "shift", "if", "@history", ".", "length", ">", "max_history", "end", "@mean_max", "||=", "0", "if", "@history", ".", "length", ">", "3", "sticks", ",", "stime", "=", "@history", ".", "first", "ssticks", ",", "sstime", "=", "@history", "[", "-", "3", "]", "lticks", ",", "ltime", "=", "@history", ".", "last", "mean", "=", "@mean", "=", "(", "lticks", "-", "sticks", ")", ".", "to_f", "/", "(", "ltime", "-", "stime", ")", "short_mean", "=", "(", "lticks", "-", "ssticks", ")", ".", "to_f", "/", "(", "ltime", "-", "sstime", ")", "@mean_max", "=", "mean", "if", "mean", ">", "@mean_max", "end", "if", "short_mean", "thr", "=", "short_mean", "else", "thr", "=", "begin", "(", "@ticks", "||", "1", ")", "/", "(", "Time", ".", "now", "-", "@start", ")", "rescue", "1", "end", "end", "thr", "=", "0.0000001", "if", "thr", "==", "0", "if", "mean", ".", "nil?", "or", "mean", ".", "to_i", ">", "1", "str", "=", "\"#{ Log.color :blue, thr.to_i.to_s } per sec.\"", "else", "str", "=", "\"#{ Log.color :blue, (1/thr).ceil.to_s } secs each\"", "end", "str", "end" ]
def thr count = (@ticks - @last_count).to_f if @last_time.nil? seconds = 0.001 else seconds = Time.now - @last_time end thr = count / seconds end def thr_msg thr = self.thr if @history.nil? @history ||= [thr] else @history << thr max_history ||= case when @ticks > 20 count = @ticks - @last_count if @max times = @max / count num = times / 20 num = 2 if num < 2 else num = 10 end count * num else 20 end max_history = 30 if max_history > 30 max_history = 100 @history.shift if @history.length > max_history end @mean_max ||= 0 if @history.length > 3 w_mean = 0 total_w = 0 @history.each_with_index do |v,i| c = i ** 10 w_mean += v * c total_w += c end mean = @mean = w_mean.to_f / total_w @mean_max = mean if mean > @mean_max end if mean.nil? or mean.to_i > 1 str = "#{ Log.color :blue, thr.to_i.to_s } per sec." str << " #{ Log.color :yellow, mean.to_i.to_s } avg. #{Log.color :yellow, @mean_max.to_i.to_s} max." if @mean_max > 0 else str = "#{ Log.color :blue, (1/thr).ceil.to_s } secs each" str << " #{ Log.color :yellow, (1/mean).ceil.to_s } avg. #{Log.color :yellow, (1/@mean_max).ceil.to_s} min." if @mean_max > 0 end str end
[ "def", "thr", "count", "=", "(" ]
dfa78eea3dfcf4bb40972e8a2a85963d21ce1688
https://github.com/mikisvaz/rbbt-util/blob/dfa78eea3dfcf4bb40972e8a2a85963d21ce1688/lib/rbbt/util/log/progress/report.rb#L75-L133
train
rapid7/rex-sslscan
lib/rex/sslscan/scanner.rb
Rex::SSLScan.Scanner.valid?
def valid? begin @host = Rex::Socket.getaddress(@host, true) rescue return false end @port.kind_of?(Integer) && @port >= 0 && @port <= 65535 && @timeout.kind_of?(Integer) end
ruby
def valid? begin @host = Rex::Socket.getaddress(@host, true) rescue return false end @port.kind_of?(Integer) && @port >= 0 && @port <= 65535 && @timeout.kind_of?(Integer) end
[ "def", "valid?", "begin", "@host", "=", "Rex", "::", "Socket", ".", "getaddress", "(", "@host", ",", "true", ")", "rescue", "return", "false", "end", "@port", ".", "kind_of?", "(", "Integer", ")", "&&", "@port", ">=", "0", "&&", "@port", "<=", "65535", "&&", "@timeout", ".", "kind_of?", "(", "Integer", ")", "end" ]
Initializes the scanner object @param host [String] IP address or hostname to scan @param port [Integer] Port number to scan, default: 443 @param timeout [Integer] Timeout for connections, in seconds. default: 5 @raise [StandardError] Raised when the configuration is invalid Checks whether the scanner option has a valid configuration @return [Boolean] True or False, the configuration is valid.
[ "Initializes", "the", "scanner", "object" ]
a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a
https://github.com/rapid7/rex-sslscan/blob/a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a/lib/rex/sslscan/scanner.rb#L42-L49
train
rapid7/rex-sslscan
lib/rex/sslscan/scanner.rb
Rex::SSLScan.Scanner.scan
def scan scan_result = Rex::SSLScan::Result.new scan_result.openssl_sslv2 = sslv2 # If we can't get any SSL connection, then don't bother testing # individual ciphers. if test_ssl == :rejected and test_tls == :rejected return scan_result end threads = [] ciphers = Queue.new @supported_versions.each do |ssl_version| sslctx = OpenSSL::SSL::SSLContext.new(ssl_version) sslctx.ciphers.each do |cipher_name, ssl_ver, key_length, alg_length| threads << Thread.new do begin status = test_cipher(ssl_version, cipher_name) ciphers << [ssl_version, cipher_name, key_length, status] if status == :accepted and scan_result.cert.nil? scan_result.cert = get_cert(ssl_version, cipher_name) end rescue Rex::SSLScan::Scanner::InvalidCipher next end end end end threads.each { |thr| thr.join } until ciphers.empty? do cipher = ciphers.pop scan_result.add_cipher(*cipher) end scan_result end
ruby
def scan scan_result = Rex::SSLScan::Result.new scan_result.openssl_sslv2 = sslv2 # If we can't get any SSL connection, then don't bother testing # individual ciphers. if test_ssl == :rejected and test_tls == :rejected return scan_result end threads = [] ciphers = Queue.new @supported_versions.each do |ssl_version| sslctx = OpenSSL::SSL::SSLContext.new(ssl_version) sslctx.ciphers.each do |cipher_name, ssl_ver, key_length, alg_length| threads << Thread.new do begin status = test_cipher(ssl_version, cipher_name) ciphers << [ssl_version, cipher_name, key_length, status] if status == :accepted and scan_result.cert.nil? scan_result.cert = get_cert(ssl_version, cipher_name) end rescue Rex::SSLScan::Scanner::InvalidCipher next end end end end threads.each { |thr| thr.join } until ciphers.empty? do cipher = ciphers.pop scan_result.add_cipher(*cipher) end scan_result end
[ "def", "scan", "scan_result", "=", "Rex", "::", "SSLScan", "::", "Result", ".", "new", "scan_result", ".", "openssl_sslv2", "=", "sslv2", "if", "test_ssl", "==", ":rejected", "and", "test_tls", "==", ":rejected", "return", "scan_result", "end", "threads", "=", "[", "]", "ciphers", "=", "Queue", ".", "new", "@supported_versions", ".", "each", "do", "|", "ssl_version", "|", "sslctx", "=", "OpenSSL", "::", "SSL", "::", "SSLContext", ".", "new", "(", "ssl_version", ")", "sslctx", ".", "ciphers", ".", "each", "do", "|", "cipher_name", ",", "ssl_ver", ",", "key_length", ",", "alg_length", "|", "threads", "<<", "Thread", ".", "new", "do", "begin", "status", "=", "test_cipher", "(", "ssl_version", ",", "cipher_name", ")", "ciphers", "<<", "[", "ssl_version", ",", "cipher_name", ",", "key_length", ",", "status", "]", "if", "status", "==", ":accepted", "and", "scan_result", ".", "cert", ".", "nil?", "scan_result", ".", "cert", "=", "get_cert", "(", "ssl_version", ",", "cipher_name", ")", "end", "rescue", "Rex", "::", "SSLScan", "::", "Scanner", "::", "InvalidCipher", "next", "end", "end", "end", "end", "threads", ".", "each", "{", "|", "thr", "|", "thr", ".", "join", "}", "until", "ciphers", ".", "empty?", "do", "cipher", "=", "ciphers", ".", "pop", "scan_result", ".", "add_cipher", "(", "*", "cipher", ")", "end", "scan_result", "end" ]
Initiate the Scan against the target. Will test each cipher one at a time. @return [Result] object containing the details of the scan
[ "Initiate", "the", "Scan", "against", "the", "target", ".", "Will", "test", "each", "cipher", "one", "at", "a", "time", "." ]
a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a
https://github.com/rapid7/rex-sslscan/blob/a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a/lib/rex/sslscan/scanner.rb#L53-L87
train
rapid7/rex-sslscan
lib/rex/sslscan/scanner.rb
Rex::SSLScan.Scanner.get_cert
def get_cert(ssl_version, cipher) validate_params(ssl_version,cipher) begin scan_client = Rex::Socket::Tcp.create( 'PeerHost' => @host, 'PeerPort' => @port, 'SSL' => true, 'SSLVersion' => ssl_version, 'SSLCipher' => cipher, 'Timeout' => @timeout ) cert = scan_client.peer_cert if cert.kind_of? OpenSSL::X509::Certificate return cert else return nil end rescue ::Exception => e return nil ensure if scan_client scan_client.close end end end
ruby
def get_cert(ssl_version, cipher) validate_params(ssl_version,cipher) begin scan_client = Rex::Socket::Tcp.create( 'PeerHost' => @host, 'PeerPort' => @port, 'SSL' => true, 'SSLVersion' => ssl_version, 'SSLCipher' => cipher, 'Timeout' => @timeout ) cert = scan_client.peer_cert if cert.kind_of? OpenSSL::X509::Certificate return cert else return nil end rescue ::Exception => e return nil ensure if scan_client scan_client.close end end end
[ "def", "get_cert", "(", "ssl_version", ",", "cipher", ")", "validate_params", "(", "ssl_version", ",", "cipher", ")", "begin", "scan_client", "=", "Rex", "::", "Socket", "::", "Tcp", ".", "create", "(", "'PeerHost'", "=>", "@host", ",", "'PeerPort'", "=>", "@port", ",", "'SSL'", "=>", "true", ",", "'SSLVersion'", "=>", "ssl_version", ",", "'SSLCipher'", "=>", "cipher", ",", "'Timeout'", "=>", "@timeout", ")", "cert", "=", "scan_client", ".", "peer_cert", "if", "cert", ".", "kind_of?", "OpenSSL", "::", "X509", "::", "Certificate", "return", "cert", "else", "return", "nil", "end", "rescue", "::", "Exception", "=>", "e", "return", "nil", "ensure", "if", "scan_client", "scan_client", ".", "close", "end", "end", "end" ]
Retrieve the X509 Cert from the target service, @param ssl_version [Symbol] The SSL version to use (:SSLv2, :SSLv3, :TLSv1) @param cipher [String] The SSL Cipher to use @return [OpenSSL::X509::Certificate] if the certificate was retrieved @return [Nil] if the cert couldn't be retrieved
[ "Retrieve", "the", "X509", "Cert", "from", "the", "target", "service" ]
a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a
https://github.com/rapid7/rex-sslscan/blob/a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a/lib/rex/sslscan/scanner.rb#L161-L185
train
rapid7/rex-sslscan
lib/rex/sslscan/scanner.rb
Rex::SSLScan.Scanner.validate_params
def validate_params(ssl_version, cipher) raise StandardError, "The scanner configuration is invalid" unless valid? unless @supported_versions.include? ssl_version raise StandardError, "SSL Version must be one of: #{@supported_versions.to_s}" end if ssl_version == :SSLv2 and sslv2 == false raise StandardError, "Your OS hates freedom! Your OpenSSL libs are compiled without SSLv2 support!" else unless OpenSSL::SSL::SSLContext.new(ssl_version).ciphers.flatten.include? cipher raise InvalidCipher, "Must be a valid SSL Cipher for #{ssl_version}!" end end end
ruby
def validate_params(ssl_version, cipher) raise StandardError, "The scanner configuration is invalid" unless valid? unless @supported_versions.include? ssl_version raise StandardError, "SSL Version must be one of: #{@supported_versions.to_s}" end if ssl_version == :SSLv2 and sslv2 == false raise StandardError, "Your OS hates freedom! Your OpenSSL libs are compiled without SSLv2 support!" else unless OpenSSL::SSL::SSLContext.new(ssl_version).ciphers.flatten.include? cipher raise InvalidCipher, "Must be a valid SSL Cipher for #{ssl_version}!" end end end
[ "def", "validate_params", "(", "ssl_version", ",", "cipher", ")", "raise", "StandardError", ",", "\"The scanner configuration is invalid\"", "unless", "valid?", "unless", "@supported_versions", ".", "include?", "ssl_version", "raise", "StandardError", ",", "\"SSL Version must be one of: #{@supported_versions.to_s}\"", "end", "if", "ssl_version", "==", ":SSLv2", "and", "sslv2", "==", "false", "raise", "StandardError", ",", "\"Your OS hates freedom! Your OpenSSL libs are compiled without SSLv2 support!\"", "else", "unless", "OpenSSL", "::", "SSL", "::", "SSLContext", ".", "new", "(", "ssl_version", ")", ".", "ciphers", ".", "flatten", ".", "include?", "cipher", "raise", "InvalidCipher", ",", "\"Must be a valid SSL Cipher for #{ssl_version}!\"", "end", "end", "end" ]
Validates that the SSL Version and Cipher are valid both seperately and together as part of an SSL Context. @param ssl_version [Symbol] The SSL version to use (:SSLv2, :SSLv3, :TLSv1) @param cipher [String] The SSL Cipher to use @raise [StandardError] If an invalid or unsupported SSL Version was supplied @raise [StandardError] If the cipher is not valid for that version of SSL
[ "Validates", "that", "the", "SSL", "Version", "and", "Cipher", "are", "valid", "both", "seperately", "and", "together", "as", "part", "of", "an", "SSL", "Context", "." ]
a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a
https://github.com/rapid7/rex-sslscan/blob/a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a/lib/rex/sslscan/scanner.rb#L196-L208
train
phusion/union_station_hooks_core
lib/union_station_hooks_core/request_reporter/misc.rb
UnionStationHooks.RequestReporter.log_user_activity_begin
def log_user_activity_begin(name) return do_nothing_on_null(:log_user_activity_begin) if null? id = next_user_activity_name @transaction.log_activity_begin(id, UnionStationHooks.now, name) id end
ruby
def log_user_activity_begin(name) return do_nothing_on_null(:log_user_activity_begin) if null? id = next_user_activity_name @transaction.log_activity_begin(id, UnionStationHooks.now, name) id end
[ "def", "log_user_activity_begin", "(", "name", ")", "return", "do_nothing_on_null", "(", ":log_user_activity_begin", ")", "if", "null?", "id", "=", "next_user_activity_name", "@transaction", ".", "log_activity_begin", "(", "id", ",", "UnionStationHooks", ".", "now", ",", "name", ")", "id", "end" ]
Logs the begin of a user-defined activity, for display in the activity timeline. An activity is a block in the activity timeline in the Union Station user interace. It has a name, a begin time and an end time. This form logs only the name and the begin time. You *must* also call {#log_user_activity_end} later with the same name to log the end time. @param name The name that should show up in the activity timeline. It can be any arbitrary name but may not contain newlines. @return id An ID which you must pass to {#log_user_activity_end} later.
[ "Logs", "the", "begin", "of", "a", "user", "-", "defined", "activity", "for", "display", "in", "the", "activity", "timeline", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/request_reporter/misc.rb#L71-L76
train
phusion/union_station_hooks_core
lib/union_station_hooks_core/request_reporter/misc.rb
UnionStationHooks.RequestReporter.log_user_activity_end
def log_user_activity_end(id, has_error = false) return do_nothing_on_null(:log_user_activity_end) if null? @transaction.log_activity_end(id, UnionStationHooks.now, has_error) end
ruby
def log_user_activity_end(id, has_error = false) return do_nothing_on_null(:log_user_activity_end) if null? @transaction.log_activity_end(id, UnionStationHooks.now, has_error) end
[ "def", "log_user_activity_end", "(", "id", ",", "has_error", "=", "false", ")", "return", "do_nothing_on_null", "(", ":log_user_activity_end", ")", "if", "null?", "@transaction", ".", "log_activity_end", "(", "id", ",", "UnionStationHooks", ".", "now", ",", "has_error", ")", "end" ]
Logs the end of a user-defined activity, for display in the activity timeline. An activity is a block in the activity timeline in the Union Station user interace. It has a name, a begin time and an end time. This form logs only the name and the end time. You *must* also have called {#log_user_activity_begin} earlier with the same name to log the begin time. @param id The ID which you obtained from {#log_user_activity_begin} earlier. @param [Boolean] has_error Whether an uncaught exception occurred during the activity.
[ "Logs", "the", "end", "of", "a", "user", "-", "defined", "activity", "for", "display", "in", "the", "activity", "timeline", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/request_reporter/misc.rb#L92-L95
train
phusion/union_station_hooks_core
lib/union_station_hooks_core/request_reporter/misc.rb
UnionStationHooks.RequestReporter.log_user_activity
def log_user_activity(name, begin_time, end_time, has_error = false) return do_nothing_on_null(:log_user_activity) if null? @transaction.log_activity(next_user_activity_name, begin_time, end_time, name, has_error) end
ruby
def log_user_activity(name, begin_time, end_time, has_error = false) return do_nothing_on_null(:log_user_activity) if null? @transaction.log_activity(next_user_activity_name, begin_time, end_time, name, has_error) end
[ "def", "log_user_activity", "(", "name", ",", "begin_time", ",", "end_time", ",", "has_error", "=", "false", ")", "return", "do_nothing_on_null", "(", ":log_user_activity", ")", "if", "null?", "@transaction", ".", "log_activity", "(", "next_user_activity_name", ",", "begin_time", ",", "end_time", ",", "name", ",", "has_error", ")", "end" ]
Logs a user-defined activity, for display in the activity timeline. An activity is a block in the activity timeline in the Union Station user interace. It has a name, a begin time and an end time. Unlike {#log_user_activity_block}, this form does not expect a block. However, you are expected to pass timing information. @param name The name that should show up in the activity timeline. It can be any arbitrary name but may not contain newlines. @param [TimePoint or Time] begin_time The time at which this activity begun. See {UnionStationHooks.now} to learn more. @param [TimePoint or Time] end_time The time at which this activity ended. See {UnionStationHooks.now} to learn more. @param [Boolean] has_error Whether an uncaught exception occurred during the activity.
[ "Logs", "a", "user", "-", "defined", "activity", "for", "display", "in", "the", "activity", "timeline", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/request_reporter/misc.rb#L113-L117
train
phusion/union_station_hooks_core
lib/union_station_hooks_core/request_reporter/misc.rb
UnionStationHooks.RequestReporter.log_exception
def log_exception(exception) transaction = @context.new_transaction( @app_group_name, :exceptions, @key) begin return do_nothing_on_null(:log_exception) if transaction.null? base64_message = exception.message base64_message = exception.to_s if base64_message.empty? base64_message = Utils.base64(base64_message) base64_backtrace = Utils.base64(exception.backtrace.join("\n")) if controller_action_logged? transaction.message("Controller action: #{@controller_action}") end transaction.message("Request transaction ID: #{@txn_id}") transaction.message("Message: #{base64_message}") transaction.message("Class: #{exception.class.name}") transaction.message("Backtrace: #{base64_backtrace}") ensure transaction.close end end
ruby
def log_exception(exception) transaction = @context.new_transaction( @app_group_name, :exceptions, @key) begin return do_nothing_on_null(:log_exception) if transaction.null? base64_message = exception.message base64_message = exception.to_s if base64_message.empty? base64_message = Utils.base64(base64_message) base64_backtrace = Utils.base64(exception.backtrace.join("\n")) if controller_action_logged? transaction.message("Controller action: #{@controller_action}") end transaction.message("Request transaction ID: #{@txn_id}") transaction.message("Message: #{base64_message}") transaction.message("Class: #{exception.class.name}") transaction.message("Backtrace: #{base64_backtrace}") ensure transaction.close end end
[ "def", "log_exception", "(", "exception", ")", "transaction", "=", "@context", ".", "new_transaction", "(", "@app_group_name", ",", ":exceptions", ",", "@key", ")", "begin", "return", "do_nothing_on_null", "(", ":log_exception", ")", "if", "transaction", ".", "null?", "base64_message", "=", "exception", ".", "message", "base64_message", "=", "exception", ".", "to_s", "if", "base64_message", ".", "empty?", "base64_message", "=", "Utils", ".", "base64", "(", "base64_message", ")", "base64_backtrace", "=", "Utils", ".", "base64", "(", "exception", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", ")", "if", "controller_action_logged?", "transaction", ".", "message", "(", "\"Controller action: #{@controller_action}\"", ")", "end", "transaction", ".", "message", "(", "\"Request transaction ID: #{@txn_id}\"", ")", "transaction", ".", "message", "(", "\"Message: #{base64_message}\"", ")", "transaction", ".", "message", "(", "\"Class: #{exception.class.name}\"", ")", "transaction", ".", "message", "(", "\"Backtrace: #{base64_backtrace}\"", ")", "ensure", "transaction", ".", "close", "end", "end" ]
Logs an exception that occurred during a request. If you want to use an exception that occurred outside the request/response cycle, e.g. an exception that occurred in a thread, use {UnionStationHooks.log_exception} instead. If {#log_controller_action_block} or {#log_controller_action} was called during the same request, then the information passed to those methods will be included in the exception report. @param [Exception] exception
[ "Logs", "an", "exception", "that", "occurred", "during", "a", "request", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/request_reporter/misc.rb#L178-L201
train
phusion/union_station_hooks_core
lib/union_station_hooks_core/request_reporter/misc.rb
UnionStationHooks.RequestReporter.log_database_query
def log_database_query(options) return do_nothing_on_null(:log_database_query) if null? Utils.require_key(options, :begin_time) Utils.require_key(options, :end_time) Utils.require_non_empty_key(options, :query) name = options[:name] || 'SQL' begin_time = options[:begin_time] end_time = options[:end_time] query = options[:query] @transaction.log_activity(next_database_query_name, begin_time, end_time, "#{name}\n#{query}") end
ruby
def log_database_query(options) return do_nothing_on_null(:log_database_query) if null? Utils.require_key(options, :begin_time) Utils.require_key(options, :end_time) Utils.require_non_empty_key(options, :query) name = options[:name] || 'SQL' begin_time = options[:begin_time] end_time = options[:end_time] query = options[:query] @transaction.log_activity(next_database_query_name, begin_time, end_time, "#{name}\n#{query}") end
[ "def", "log_database_query", "(", "options", ")", "return", "do_nothing_on_null", "(", ":log_database_query", ")", "if", "null?", "Utils", ".", "require_key", "(", "options", ",", ":begin_time", ")", "Utils", ".", "require_key", "(", "options", ",", ":end_time", ")", "Utils", ".", "require_non_empty_key", "(", "options", ",", ":query", ")", "name", "=", "options", "[", ":name", "]", "||", "'SQL'", "begin_time", "=", "options", "[", ":begin_time", "]", "end_time", "=", "options", "[", ":end_time", "]", "query", "=", "options", "[", ":query", "]", "@transaction", ".", "log_activity", "(", "next_database_query_name", ",", "begin_time", ",", "end_time", ",", "\"#{name}\\n#{query}\"", ")", "end" ]
Logs a database query that was performed during the request. @option options [String] :name (optional) A name for this database query activity. Default: "SQL" @option options [TimePoint or Time] :begin_time The time at which this database query begun. See {UnionStationHooks.now} to learn more. @option options [TimePoint or Time] :end_time The time at which this database query ended. See {UnionStationHooks.now} to learn more. @option options [String] :query The database query string.
[ "Logs", "a", "database", "query", "that", "was", "performed", "during", "the", "request", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/request_reporter/misc.rb#L212-L225
train
coupler/linkage
lib/linkage/matcher.rb
Linkage.Matcher.mean
def mean w = @comparators.collect { |comparator| comparator.weight || 1 } @score_set.open_for_reading @score_set.each_pair do |id_1, id_2, scores| sum = 0 scores.each do |key, value| sum += value * w[key-1] end mean = sum / @comparators.length.to_f if mean >= @threshold changed notify_observers(id_1, id_2, mean) end end @score_set.close end
ruby
def mean w = @comparators.collect { |comparator| comparator.weight || 1 } @score_set.open_for_reading @score_set.each_pair do |id_1, id_2, scores| sum = 0 scores.each do |key, value| sum += value * w[key-1] end mean = sum / @comparators.length.to_f if mean >= @threshold changed notify_observers(id_1, id_2, mean) end end @score_set.close end
[ "def", "mean", "w", "=", "@comparators", ".", "collect", "{", "|", "comparator", "|", "comparator", ".", "weight", "||", "1", "}", "@score_set", ".", "open_for_reading", "@score_set", ".", "each_pair", "do", "|", "id_1", ",", "id_2", ",", "scores", "|", "sum", "=", "0", "scores", ".", "each", "do", "|", "key", ",", "value", "|", "sum", "+=", "value", "*", "w", "[", "key", "-", "1", "]", "end", "mean", "=", "sum", "/", "@comparators", ".", "length", ".", "to_f", "if", "mean", ">=", "@threshold", "changed", "notify_observers", "(", "id_1", ",", "id_2", ",", "mean", ")", "end", "end", "@score_set", ".", "close", "end" ]
Combine scores for each pair of records via mean, then compare the combined score to the threshold. Notify observers if there's a match.
[ "Combine", "scores", "for", "each", "pair", "of", "records", "via", "mean", "then", "compare", "the", "combined", "score", "to", "the", "threshold", ".", "Notify", "observers", "if", "there", "s", "a", "match", "." ]
2f208ae0709a141a6a8e5ba3bc6914677e986cb0
https://github.com/coupler/linkage/blob/2f208ae0709a141a6a8e5ba3bc6914677e986cb0/lib/linkage/matcher.rb#L41-L56
train
blambeau/finitio-rb
lib/finitio/type/sub_type.rb
Finitio.SubType.dress
def dress(value, handler = DressHelper.new) # Check that the supertype is able to dress the value. # Rewrite and set cause to any encountered TypeError. uped = handler.try(self, value) do super_type.dress(value, handler) end # Check each constraint in turn constraints.each do |constraint| next if constraint===uped msg = handler.default_error_message(self, value) if constraint.named? && constraints.size>1 msg << " (not #{constraint.name})" end handler.fail!(msg) end # seems good, return the uped value uped end
ruby
def dress(value, handler = DressHelper.new) # Check that the supertype is able to dress the value. # Rewrite and set cause to any encountered TypeError. uped = handler.try(self, value) do super_type.dress(value, handler) end # Check each constraint in turn constraints.each do |constraint| next if constraint===uped msg = handler.default_error_message(self, value) if constraint.named? && constraints.size>1 msg << " (not #{constraint.name})" end handler.fail!(msg) end # seems good, return the uped value uped end
[ "def", "dress", "(", "value", ",", "handler", "=", "DressHelper", ".", "new", ")", "uped", "=", "handler", ".", "try", "(", "self", ",", "value", ")", "do", "super_type", ".", "dress", "(", "value", ",", "handler", ")", "end", "constraints", ".", "each", "do", "|", "constraint", "|", "next", "if", "constraint", "===", "uped", "msg", "=", "handler", ".", "default_error_message", "(", "self", ",", "value", ")", "if", "constraint", ".", "named?", "&&", "constraints", ".", "size", ">", "1", "msg", "<<", "\" (not #{constraint.name})\"", "end", "handler", ".", "fail!", "(", "msg", ")", "end", "uped", "end" ]
Check that `value` can be uped through the supertype, then verify all constraints. Raise an error if anything goes wrong.
[ "Check", "that", "value", "can", "be", "uped", "through", "the", "supertype", "then", "verify", "all", "constraints", ".", "Raise", "an", "error", "if", "anything", "goes", "wrong", "." ]
c07a3887a6af26b2ed1eb3c50b101e210d3d8b40
https://github.com/blambeau/finitio-rb/blob/c07a3887a6af26b2ed1eb3c50b101e210d3d8b40/lib/finitio/type/sub_type.rb#L63-L82
train
juandebravo/quora-client
lib/quora/auth.rb
Quora.Auth.login
def login(user, password) endpoint = URI.parse(QUORA_URI) http = Net::HTTP.new(endpoint.host, endpoint.port) resp = http.get('/login/') cookie = resp["set-cookie"] # TODO: improve this rubbish # get formkey value start = resp.body.index("Q.formkey") formkey = resp.body[start..start+200].split("\"")[1] # get window value start = resp.body.index("webnode2.windowId") window = resp.body[start..start+200].split("\"")[1] # get __vcon_json value start = resp.body.index("InlineLogin") vcon_json = resp.body[start..start+200] start = vcon_json.index("live") vcon_json = vcon_json[start..-1] vcon_json = vcon_json.split("\"")[0] vcon_json = vcon_json.split(":") vcon_json.map! { |value| "\"#{value}\"" } vcon_json = "[#{vcon_json.join(",")}]" vcon_json = CGI::escape(vcon_json) user = CGI::escape(user) password = CGI::escape(password) body = "json=%7B%22args%22%3A%5B%22#{user}%22%2C%22#{password}%22%2Ctrue%5D%2C%22kwargs%22%3A%7B%7D%7D&formkey=#{formkey}&window_id=#{window}&__vcon_json=#{vcon_json}&__vcon_method=do_login" headers = { "Content-Type" => "application/x-www-form-urlencoded", "X-Requested-With" => "XMLHttpRequest", "Accept" => "application/json, text/javascript, */*", "Cookie" => cookie, "User-Agent" => "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.237 Safari/534.10", "Content-Length" => body.length.to_s, "Accept-Charset" => "ISO-8859-1,utf-8;q=0.7,*;q=0.3", "Accept-Language" => "es-ES,es;q=0.8", "Accept-Encoding" => "gzip,deflate,sdch", "Origin" => "http://www.quora.com", "Host" => "www.quora.com", "Referer" => "http://www.quora.com/login/" } resp = http.post("/webnode2/server_call_POST", body, headers) if resp.code == "200" cookie else "" end end
ruby
def login(user, password) endpoint = URI.parse(QUORA_URI) http = Net::HTTP.new(endpoint.host, endpoint.port) resp = http.get('/login/') cookie = resp["set-cookie"] # TODO: improve this rubbish # get formkey value start = resp.body.index("Q.formkey") formkey = resp.body[start..start+200].split("\"")[1] # get window value start = resp.body.index("webnode2.windowId") window = resp.body[start..start+200].split("\"")[1] # get __vcon_json value start = resp.body.index("InlineLogin") vcon_json = resp.body[start..start+200] start = vcon_json.index("live") vcon_json = vcon_json[start..-1] vcon_json = vcon_json.split("\"")[0] vcon_json = vcon_json.split(":") vcon_json.map! { |value| "\"#{value}\"" } vcon_json = "[#{vcon_json.join(",")}]" vcon_json = CGI::escape(vcon_json) user = CGI::escape(user) password = CGI::escape(password) body = "json=%7B%22args%22%3A%5B%22#{user}%22%2C%22#{password}%22%2Ctrue%5D%2C%22kwargs%22%3A%7B%7D%7D&formkey=#{formkey}&window_id=#{window}&__vcon_json=#{vcon_json}&__vcon_method=do_login" headers = { "Content-Type" => "application/x-www-form-urlencoded", "X-Requested-With" => "XMLHttpRequest", "Accept" => "application/json, text/javascript, */*", "Cookie" => cookie, "User-Agent" => "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.237 Safari/534.10", "Content-Length" => body.length.to_s, "Accept-Charset" => "ISO-8859-1,utf-8;q=0.7,*;q=0.3", "Accept-Language" => "es-ES,es;q=0.8", "Accept-Encoding" => "gzip,deflate,sdch", "Origin" => "http://www.quora.com", "Host" => "www.quora.com", "Referer" => "http://www.quora.com/login/" } resp = http.post("/webnode2/server_call_POST", body, headers) if resp.code == "200" cookie else "" end end
[ "def", "login", "(", "user", ",", "password", ")", "endpoint", "=", "URI", ".", "parse", "(", "QUORA_URI", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "endpoint", ".", "host", ",", "endpoint", ".", "port", ")", "resp", "=", "http", ".", "get", "(", "'/login/'", ")", "cookie", "=", "resp", "[", "\"set-cookie\"", "]", "start", "=", "resp", ".", "body", ".", "index", "(", "\"Q.formkey\"", ")", "formkey", "=", "resp", ".", "body", "[", "start", "..", "start", "+", "200", "]", ".", "split", "(", "\"\\\"\"", ")", "[", "1", "]", "start", "=", "resp", ".", "body", ".", "index", "(", "\"webnode2.windowId\"", ")", "window", "=", "resp", ".", "body", "[", "start", "..", "start", "+", "200", "]", ".", "split", "(", "\"\\\"\"", ")", "[", "1", "]", "start", "=", "resp", ".", "body", ".", "index", "(", "\"InlineLogin\"", ")", "vcon_json", "=", "resp", ".", "body", "[", "start", "..", "start", "+", "200", "]", "start", "=", "vcon_json", ".", "index", "(", "\"live\"", ")", "vcon_json", "=", "vcon_json", "[", "start", "..", "-", "1", "]", "vcon_json", "=", "vcon_json", ".", "split", "(", "\"\\\"\"", ")", "[", "0", "]", "vcon_json", "=", "vcon_json", ".", "split", "(", "\":\"", ")", "vcon_json", ".", "map!", "{", "|", "value", "|", "\"\\\"#{value}\\\"\"", "}", "vcon_json", "=", "\"[#{vcon_json.join(\",\")}]\"", "vcon_json", "=", "CGI", "::", "escape", "(", "vcon_json", ")", "user", "=", "CGI", "::", "escape", "(", "user", ")", "password", "=", "CGI", "::", "escape", "(", "password", ")", "body", "=", "\"json=%7B%22args%22%3A%5B%22#{user}%22%2C%22#{password}%22%2Ctrue%5D%2C%22kwargs%22%3A%7B%7D%7D&formkey=#{formkey}&window_id=#{window}&__vcon_json=#{vcon_json}&__vcon_method=do_login\"", "headers", "=", "{", "\"Content-Type\"", "=>", "\"application/x-www-form-urlencoded\"", ",", "\"X-Requested-With\"", "=>", "\"XMLHttpRequest\"", ",", "\"Accept\"", "=>", "\"application/json, text/javascript, */*\"", ",", "\"Cookie\"", "=>", "cookie", ",", "\"User-Agent\"", "=>", "\"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.237 Safari/534.10\"", ",", "\"Content-Length\"", "=>", "body", ".", "length", ".", "to_s", ",", "\"Accept-Charset\"", "=>", "\"ISO-8859-1,utf-8;q=0.7,*;q=0.3\"", ",", "\"Accept-Language\"", "=>", "\"es-ES,es;q=0.8\"", ",", "\"Accept-Encoding\"", "=>", "\"gzip,deflate,sdch\"", ",", "\"Origin\"", "=>", "\"http://www.quora.com\"", ",", "\"Host\"", "=>", "\"www.quora.com\"", ",", "\"Referer\"", "=>", "\"http://www.quora.com/login/\"", "}", "resp", "=", "http", ".", "post", "(", "\"/webnode2/server_call_POST\"", ",", "body", ",", "headers", ")", "if", "resp", ".", "code", "==", "\"200\"", "cookie", "else", "\"\"", "end", "end" ]
login with Quora user and password
[ "login", "with", "Quora", "user", "and", "password" ]
eb09bbb70aef5c5c77887dc0b689ccb422fba49f
https://github.com/juandebravo/quora-client/blob/eb09bbb70aef5c5c77887dc0b689ccb422fba49f/lib/quora/auth.rb#L24-L79
train
justintanner/column_pack
lib/column_pack/bin_packer.rb
ColumnPack.BinPacker.empty_space
def empty_space pack_all if @needs_packing max = @sizes.each.max space = 0 @sizes.each { |size| space += max - size } space end
ruby
def empty_space pack_all if @needs_packing max = @sizes.each.max space = 0 @sizes.each { |size| space += max - size } space end
[ "def", "empty_space", "pack_all", "if", "@needs_packing", "max", "=", "@sizes", ".", "each", ".", "max", "space", "=", "0", "@sizes", ".", "each", "{", "|", "size", "|", "space", "+=", "max", "-", "size", "}", "space", "end" ]
Total empty space left over by uneven packing.
[ "Total", "empty", "space", "left", "over", "by", "uneven", "packing", "." ]
bffe22f74063718fdcf7b9c5dce1001ceabe8046
https://github.com/justintanner/column_pack/blob/bffe22f74063718fdcf7b9c5dce1001ceabe8046/lib/column_pack/bin_packer.rb#L45-L53
train
justintanner/column_pack
lib/column_pack/bin_packer.rb
ColumnPack.BinPacker.tall_to_middle
def tall_to_middle if (@total_bins > 1) && ((@total_bins % 2) != 0) _, max_col = @sizes.each_with_index.max mid_col = @total_bins / 2 temp = @bins[mid_col].clone @bins[mid_col] = @bins[max_col] @bins[max_col] = temp end end
ruby
def tall_to_middle if (@total_bins > 1) && ((@total_bins % 2) != 0) _, max_col = @sizes.each_with_index.max mid_col = @total_bins / 2 temp = @bins[mid_col].clone @bins[mid_col] = @bins[max_col] @bins[max_col] = temp end end
[ "def", "tall_to_middle", "if", "(", "@total_bins", ">", "1", ")", "&&", "(", "(", "@total_bins", "%", "2", ")", "!=", "0", ")", "_", ",", "max_col", "=", "@sizes", ".", "each_with_index", ".", "max", "mid_col", "=", "@total_bins", "/", "2", "temp", "=", "@bins", "[", "mid_col", "]", ".", "clone", "@bins", "[", "mid_col", "]", "=", "@bins", "[", "max_col", "]", "@bins", "[", "max_col", "]", "=", "temp", "end", "end" ]
moves the tallest bin to the middle
[ "moves", "the", "tallest", "bin", "to", "the", "middle" ]
bffe22f74063718fdcf7b9c5dce1001ceabe8046
https://github.com/justintanner/column_pack/blob/bffe22f74063718fdcf7b9c5dce1001ceabe8046/lib/column_pack/bin_packer.rb#L90-L99
train
LAS-IT/ps_utilities
lib/ps_utilities/connection.rb
PsUtilities.Connection.api
def api(verb, api_path, options={}) count = 0 retries = 3 ps_url = base_uri + api_path options = options.merge(headers) begin HTTParty.send(verb, ps_url, options) rescue Net::ReadTimeout, Net::OpenTimeout if count < retries count += 1 retry else { error: "no response (timeout) from URL: #{url}" } end end end
ruby
def api(verb, api_path, options={}) count = 0 retries = 3 ps_url = base_uri + api_path options = options.merge(headers) begin HTTParty.send(verb, ps_url, options) rescue Net::ReadTimeout, Net::OpenTimeout if count < retries count += 1 retry else { error: "no response (timeout) from URL: #{url}" } end end end
[ "def", "api", "(", "verb", ",", "api_path", ",", "options", "=", "{", "}", ")", "count", "=", "0", "retries", "=", "3", "ps_url", "=", "base_uri", "+", "api_path", "options", "=", "options", ".", "merge", "(", "headers", ")", "begin", "HTTParty", ".", "send", "(", "verb", ",", "ps_url", ",", "options", ")", "rescue", "Net", "::", "ReadTimeout", ",", "Net", "::", "OpenTimeout", "if", "count", "<", "retries", "count", "+=", "1", "retry", "else", "{", "error", ":", "\"no response (timeout) from URL: #{url}\"", "}", "end", "end", "end" ]
Direct API access @param verb [Symbol] hmtl verbs (:delete, :get, :patch, :post, :put) @param options [Hash] allowed keys are {query: {}, body: {}} - uses :query for gets, and use :body for put and post @return [HTTParty] - useful things to access include: obj.parsed_response (to access returned data) & obj.code to be sure the response was successful "200"
[ "Direct", "API", "access" ]
85fbb528d982b66ca706de5fdb70b4410f21e637
https://github.com/LAS-IT/ps_utilities/blob/85fbb528d982b66ca706de5fdb70b4410f21e637/lib/ps_utilities/connection.rb#L89-L104
train
LAS-IT/ps_utilities
lib/ps_utilities/connection.rb
PsUtilities.Connection.authenticate
def authenticate ps_url = base_uri + auth_path response = HTTParty.post( ps_url, { headers: auth_headers, body: 'grant_type=client_credentials'} ) if response.code.to_s.eql? "200" @auth_info = response.parsed_response @auth_info['token_expires'] = Time.now + response.parsed_response['expires_in'].to_i @headers[:headers].merge!('Authorization' => 'Bearer ' + auth_info['access_token']) return auth_info else # throw error if - error returned -- nothing else will work raise AuthError.new("No Auth Token Returned", ps_url, client ) end end
ruby
def authenticate ps_url = base_uri + auth_path response = HTTParty.post( ps_url, { headers: auth_headers, body: 'grant_type=client_credentials'} ) if response.code.to_s.eql? "200" @auth_info = response.parsed_response @auth_info['token_expires'] = Time.now + response.parsed_response['expires_in'].to_i @headers[:headers].merge!('Authorization' => 'Bearer ' + auth_info['access_token']) return auth_info else # throw error if - error returned -- nothing else will work raise AuthError.new("No Auth Token Returned", ps_url, client ) end end
[ "def", "authenticate", "ps_url", "=", "base_uri", "+", "auth_path", "response", "=", "HTTParty", ".", "post", "(", "ps_url", ",", "{", "headers", ":", "auth_headers", ",", "body", ":", "'grant_type=client_credentials'", "}", ")", "if", "response", ".", "code", ".", "to_s", ".", "eql?", "\"200\"", "@auth_info", "=", "response", ".", "parsed_response", "@auth_info", "[", "'token_expires'", "]", "=", "Time", ".", "now", "+", "response", ".", "parsed_response", "[", "'expires_in'", "]", ".", "to_i", "@headers", "[", ":headers", "]", ".", "merge!", "(", "'Authorization'", "=>", "'Bearer '", "+", "auth_info", "[", "'access_token'", "]", ")", "return", "auth_info", "else", "raise", "AuthError", ".", "new", "(", "\"No Auth Token Returned\"", ",", "ps_url", ",", "client", ")", "end", "end" ]
gets API auth token and puts in header HASH for future requests with PS server @return [Hash] - of auth token and time to live from powerschol server {'access_token' => "addsfabe-aads-4444-bbbb-444411ffffbb", 'token_type' => "Bearer", 'expires_in' => "2504956" 'token_expires' => (Time.now + 3600)} @note - to enable PS API - In PowerSchool go to System>System Settings>Plugin Management Configuration>your plugin>Data Provider Configuration to manually check plugin expiration date
[ "gets", "API", "auth", "token", "and", "puts", "in", "header", "HASH", "for", "future", "requests", "with", "PS", "server" ]
85fbb528d982b66ca706de5fdb70b4410f21e637
https://github.com/LAS-IT/ps_utilities/blob/85fbb528d982b66ca706de5fdb70b4410f21e637/lib/ps_utilities/connection.rb#L124-L138
train
TheLevelUp/levelup-sdk-ruby
lib/levelup/api.rb
Levelup.Api.apps
def apps(app_id = nil) if app_id Endpoints::SpecificApp.new(app_id) else Endpoints::Apps.new(app_access_token) end end
ruby
def apps(app_id = nil) if app_id Endpoints::SpecificApp.new(app_id) else Endpoints::Apps.new(app_access_token) end end
[ "def", "apps", "(", "app_id", "=", "nil", ")", "if", "app_id", "Endpoints", "::", "SpecificApp", ".", "new", "(", "app_id", ")", "else", "Endpoints", "::", "Apps", ".", "new", "(", "app_access_token", ")", "end", "end" ]
Generates an interface for the +apps+ endpoint.
[ "Generates", "an", "interface", "for", "the", "+", "apps", "+", "endpoint", "." ]
efe23ddeeec363354c868d0c22d9cfad7a4190af
https://github.com/TheLevelUp/levelup-sdk-ruby/blob/efe23ddeeec363354c868d0c22d9cfad7a4190af/lib/levelup/api.rb#L32-L38
train
TheLevelUp/levelup-sdk-ruby
lib/levelup/api.rb
Levelup.Api.orders
def orders(order_uuid = nil) if order_uuid Endpoints::SpecificOrder.new(order_uuid) else Endpoints::Orders.new end end
ruby
def orders(order_uuid = nil) if order_uuid Endpoints::SpecificOrder.new(order_uuid) else Endpoints::Orders.new end end
[ "def", "orders", "(", "order_uuid", "=", "nil", ")", "if", "order_uuid", "Endpoints", "::", "SpecificOrder", ".", "new", "(", "order_uuid", ")", "else", "Endpoints", "::", "Orders", ".", "new", "end", "end" ]
Generates the interface for the +orders+ endpoint. Supply an order UUID if you would like to access endpoints for a specific order, otherwise, supply no parameters.
[ "Generates", "the", "interface", "for", "the", "+", "orders", "+", "endpoint", ".", "Supply", "an", "order", "UUID", "if", "you", "would", "like", "to", "access", "endpoints", "for", "a", "specific", "order", "otherwise", "supply", "no", "parameters", "." ]
efe23ddeeec363354c868d0c22d9cfad7a4190af
https://github.com/TheLevelUp/levelup-sdk-ruby/blob/efe23ddeeec363354c868d0c22d9cfad7a4190af/lib/levelup/api.rb#L68-L74
train
ChadBowman/kril
lib/kril/consumer.rb
Kril.Consumer.consume_all
def consume_all(topic) config = @config.clone config[:group_id] = SecureRandom.uuid consumer = build_consumer(topic, true, config) consumer.each_message do |message| yield decode(message), consumer end ensure consumer.stop end
ruby
def consume_all(topic) config = @config.clone config[:group_id] = SecureRandom.uuid consumer = build_consumer(topic, true, config) consumer.each_message do |message| yield decode(message), consumer end ensure consumer.stop end
[ "def", "consume_all", "(", "topic", ")", "config", "=", "@config", ".", "clone", "config", "[", ":group_id", "]", "=", "SecureRandom", ".", "uuid", "consumer", "=", "build_consumer", "(", "topic", ",", "true", ",", "config", ")", "consumer", ".", "each_message", "do", "|", "message", "|", "yield", "decode", "(", "message", ")", ",", "consumer", "end", "ensure", "consumer", ".", "stop", "end" ]
Consume all records from a topic. Each record will be yielded to block along with consumer instance. Will listen to topic after all records have been consumed. topic - topic to consume from [String] yields - record, consumer [String, Kafka::Consumer] return - [nil]
[ "Consume", "all", "records", "from", "a", "topic", ".", "Each", "record", "will", "be", "yielded", "to", "block", "along", "with", "consumer", "instance", ".", "Will", "listen", "to", "topic", "after", "all", "records", "have", "been", "consumed", "." ]
3581b77387b0f6d0c0c3a45248ad7d027cd89816
https://github.com/ChadBowman/kril/blob/3581b77387b0f6d0c0c3a45248ad7d027cd89816/lib/kril/consumer.rb#L42-L51
train
beerlington/sudo_attributes
lib/sudo_attributes.rb
SudoAttributes.ClassMethods.sudo_create!
def sudo_create!(attributes = nil, &block) if attributes.is_a?(Array) attributes.collect { |attr| sudo_create!(attr, &block) } else object = sudo_new(attributes) yield(object) if block_given? object.save! object end end
ruby
def sudo_create!(attributes = nil, &block) if attributes.is_a?(Array) attributes.collect { |attr| sudo_create!(attr, &block) } else object = sudo_new(attributes) yield(object) if block_given? object.save! object end end
[ "def", "sudo_create!", "(", "attributes", "=", "nil", ",", "&", "block", ")", "if", "attributes", ".", "is_a?", "(", "Array", ")", "attributes", ".", "collect", "{", "|", "attr", "|", "sudo_create!", "(", "attr", ",", "&", "block", ")", "}", "else", "object", "=", "sudo_new", "(", "attributes", ")", "yield", "(", "object", ")", "if", "block_given?", "object", ".", "save!", "object", "end", "end" ]
Creates an object just like sudo_create but calls save! instead of save so an exception is raised if the record is invalid ==== Example # Create a single new object where admin is a protected attribute User.sudo_create!(:first_name => 'Pete', :admin => true)
[ "Creates", "an", "object", "just", "like", "sudo_create", "but", "calls", "save!", "instead", "of", "save", "so", "an", "exception", "is", "raised", "if", "the", "record", "is", "invalid" ]
3bf0814153c9e8faa9b57c2e6c69fac4ca39e3c8
https://github.com/beerlington/sudo_attributes/blob/3bf0814153c9e8faa9b57c2e6c69fac4ca39e3c8/lib/sudo_attributes.rb#L41-L50
train
coupler/linkage
lib/linkage/field.rb
Linkage.Field.ruby_type
def ruby_type unless @ruby_type hsh = case @schema[:db_type].downcase when /\A(medium|small)?int(?:eger)?(?:\((\d+)\))?( unsigned)?\z/o if !$1 && $2 && $2.to_i >= 10 && $3 # Unsigned integer type with 10 digits can potentially contain values which # don't fit signed integer type, so use bigint type in target database. {:type=>Bignum} else {:type=>Integer} end when /\Atinyint(?:\((\d+)\))?(?: unsigned)?\z/o {:type =>schema[:type] == :boolean ? TrueClass : Integer} when /\Abigint(?:\((?:\d+)\))?(?: unsigned)?\z/o {:type=>Bignum} when /\A(?:real|float|double(?: precision)?|double\(\d+,\d+\)(?: unsigned)?)\z/o {:type=>Float} when 'boolean' {:type=>TrueClass} when /\A(?:(?:tiny|medium|long|n)?text|clob)\z/o {:type=>String, :text=>true} when 'date' {:type=>Date} when /\A(?:small)?datetime\z/o {:type=>DateTime} when /\Atimestamp(?:\((\d+)\))?(?: with(?:out)? time zone)?\z/o {:type=>DateTime, :size=>($1.to_i if $1)} when /\Atime(?: with(?:out)? time zone)?\z/o {:type=>Time, :only_time=>true} when /\An?char(?:acter)?(?:\((\d+)\))?\z/o {:type=>String, :size=>($1.to_i if $1), :fixed=>true} when /\A(?:n?varchar|character varying|bpchar|string)(?:\((\d+)\))?\z/o {:type=>String, :size=>($1.to_i if $1)} when /\A(?:small)?money\z/o {:type=>BigDecimal, :size=>[19,2]} when /\A(?:decimal|numeric|number)(?:\((\d+)(?:,\s*(\d+))?\))?\z/o s = [($1.to_i if $1), ($2.to_i if $2)].compact {:type=>BigDecimal, :size=>(s.empty? ? nil : s)} when /\A(?:bytea|(?:tiny|medium|long)?blob|(?:var)?binary)(?:\((\d+)\))?\z/o {:type=>File, :size=>($1.to_i if $1)} when /\A(?:year|(?:int )?identity)\z/o {:type=>Integer} else {:type=>String} end hsh.delete_if { |k, v| v.nil? } @ruby_type = {:type => hsh.delete(:type)} @ruby_type[:opts] = hsh if !hsh.empty? end @ruby_type end
ruby
def ruby_type unless @ruby_type hsh = case @schema[:db_type].downcase when /\A(medium|small)?int(?:eger)?(?:\((\d+)\))?( unsigned)?\z/o if !$1 && $2 && $2.to_i >= 10 && $3 # Unsigned integer type with 10 digits can potentially contain values which # don't fit signed integer type, so use bigint type in target database. {:type=>Bignum} else {:type=>Integer} end when /\Atinyint(?:\((\d+)\))?(?: unsigned)?\z/o {:type =>schema[:type] == :boolean ? TrueClass : Integer} when /\Abigint(?:\((?:\d+)\))?(?: unsigned)?\z/o {:type=>Bignum} when /\A(?:real|float|double(?: precision)?|double\(\d+,\d+\)(?: unsigned)?)\z/o {:type=>Float} when 'boolean' {:type=>TrueClass} when /\A(?:(?:tiny|medium|long|n)?text|clob)\z/o {:type=>String, :text=>true} when 'date' {:type=>Date} when /\A(?:small)?datetime\z/o {:type=>DateTime} when /\Atimestamp(?:\((\d+)\))?(?: with(?:out)? time zone)?\z/o {:type=>DateTime, :size=>($1.to_i if $1)} when /\Atime(?: with(?:out)? time zone)?\z/o {:type=>Time, :only_time=>true} when /\An?char(?:acter)?(?:\((\d+)\))?\z/o {:type=>String, :size=>($1.to_i if $1), :fixed=>true} when /\A(?:n?varchar|character varying|bpchar|string)(?:\((\d+)\))?\z/o {:type=>String, :size=>($1.to_i if $1)} when /\A(?:small)?money\z/o {:type=>BigDecimal, :size=>[19,2]} when /\A(?:decimal|numeric|number)(?:\((\d+)(?:,\s*(\d+))?\))?\z/o s = [($1.to_i if $1), ($2.to_i if $2)].compact {:type=>BigDecimal, :size=>(s.empty? ? nil : s)} when /\A(?:bytea|(?:tiny|medium|long)?blob|(?:var)?binary)(?:\((\d+)\))?\z/o {:type=>File, :size=>($1.to_i if $1)} when /\A(?:year|(?:int )?identity)\z/o {:type=>Integer} else {:type=>String} end hsh.delete_if { |k, v| v.nil? } @ruby_type = {:type => hsh.delete(:type)} @ruby_type[:opts] = hsh if !hsh.empty? end @ruby_type end
[ "def", "ruby_type", "unless", "@ruby_type", "hsh", "=", "case", "@schema", "[", ":db_type", "]", ".", "downcase", "when", "/", "\\A", "\\(", "\\d", "\\)", "\\z", "/o", "if", "!", "$1", "&&", "$2", "&&", "$2", ".", "to_i", ">=", "10", "&&", "$3", "{", ":type", "=>", "Bignum", "}", "else", "{", ":type", "=>", "Integer", "}", "end", "when", "/", "\\A", "\\(", "\\d", "\\)", "\\z", "/o", "{", ":type", "=>", "schema", "[", ":type", "]", "==", ":boolean", "?", "TrueClass", ":", "Integer", "}", "when", "/", "\\A", "\\(", "\\d", "\\)", "\\z", "/o", "{", ":type", "=>", "Bignum", "}", "when", "/", "\\A", "\\(", "\\d", "\\d", "\\)", "\\z", "/o", "{", ":type", "=>", "Float", "}", "when", "'boolean'", "{", ":type", "=>", "TrueClass", "}", "when", "/", "\\A", "\\z", "/o", "{", ":type", "=>", "String", ",", ":text", "=>", "true", "}", "when", "'date'", "{", ":type", "=>", "Date", "}", "when", "/", "\\A", "\\z", "/o", "{", ":type", "=>", "DateTime", "}", "when", "/", "\\A", "\\(", "\\d", "\\)", "\\z", "/o", "{", ":type", "=>", "DateTime", ",", ":size", "=>", "(", "$1", ".", "to_i", "if", "$1", ")", "}", "when", "/", "\\A", "\\z", "/o", "{", ":type", "=>", "Time", ",", ":only_time", "=>", "true", "}", "when", "/", "\\A", "\\(", "\\d", "\\)", "\\z", "/o", "{", ":type", "=>", "String", ",", ":size", "=>", "(", "$1", ".", "to_i", "if", "$1", ")", ",", ":fixed", "=>", "true", "}", "when", "/", "\\A", "\\(", "\\d", "\\)", "\\z", "/o", "{", ":type", "=>", "String", ",", ":size", "=>", "(", "$1", ".", "to_i", "if", "$1", ")", "}", "when", "/", "\\A", "\\z", "/o", "{", ":type", "=>", "BigDecimal", ",", ":size", "=>", "[", "19", ",", "2", "]", "}", "when", "/", "\\A", "\\(", "\\d", "\\s", "\\d", "\\)", "\\z", "/o", "s", "=", "[", "(", "$1", ".", "to_i", "if", "$1", ")", ",", "(", "$2", ".", "to_i", "if", "$2", ")", "]", ".", "compact", "{", ":type", "=>", "BigDecimal", ",", ":size", "=>", "(", "s", ".", "empty?", "?", "nil", ":", "s", ")", "}", "when", "/", "\\A", "\\(", "\\d", "\\)", "\\z", "/o", "{", ":type", "=>", "File", ",", ":size", "=>", "(", "$1", ".", "to_i", "if", "$1", ")", "}", "when", "/", "\\A", "\\z", "/o", "{", ":type", "=>", "Integer", "}", "else", "{", ":type", "=>", "String", "}", "end", "hsh", ".", "delete_if", "{", "|", "k", ",", "v", "|", "v", ".", "nil?", "}", "@ruby_type", "=", "{", ":type", "=>", "hsh", ".", "delete", "(", ":type", ")", "}", "@ruby_type", "[", ":opts", "]", "=", "hsh", "if", "!", "hsh", ".", "empty?", "end", "@ruby_type", "end" ]
Returns a new instance of Field. @param [Symbol] name The field's name @param [Hash] schema The field's schema information Convert the column schema information to a hash of column options, one of which is `:type`. The other options modify that type (e.g. `:size`). Here are some examples: | Database type | Ruby type | Other modifiers | |------------------|--------------------|-----------------------| | mediumint | Fixnum | | | smallint | Fixnum | | | int | Fixnum | | | int(10) unsigned | Bignum | | | tinyint | TrueClass, Integer | | | bigint | Bignum | | | real | Float | | | float | Float | | | double | Float | | | boolean | TrueClass | | | text | String | text: true | | date | Date | | | datetime | DateTime | | | timestamp | DateTime | | | time | Time | only_time: true | | varchar(255) | String | size: 255 | | char(10) | String | size: 10, fixed: true | | money | BigDecimal | size: [19, 2] | | decimal | BigDecimal | | | numeric | BigDecimal | | | number | BigDecimal | | | blob | File | | | year | Integer | | | identity | Integer | | | **other types** | String | | @note This method is copied from {http://sequel.jeremyevans.net/rdoc-plugins/classes/Sequel/SchemaDumper.html `Sequel::SchemaDumper`}. @return [Hash]
[ "Returns", "a", "new", "instance", "of", "Field", "." ]
2f208ae0709a141a6a8e5ba3bc6914677e986cb0
https://github.com/coupler/linkage/blob/2f208ae0709a141a6a8e5ba3bc6914677e986cb0/lib/linkage/field.rb#L56-L108
train
tylercunnion/crawler
lib/crawler/observer.rb
Crawler.Observer.update
def update(response, url) @log.puts "Scanning: #{url}" if response.kind_of?(Net::HTTPClientError) or response.kind_of?(Net::HTTPServerError) @log.puts "#{response.code} encountered for #{url}" end end
ruby
def update(response, url) @log.puts "Scanning: #{url}" if response.kind_of?(Net::HTTPClientError) or response.kind_of?(Net::HTTPServerError) @log.puts "#{response.code} encountered for #{url}" end end
[ "def", "update", "(", "response", ",", "url", ")", "@log", ".", "puts", "\"Scanning: #{url}\"", "if", "response", ".", "kind_of?", "(", "Net", "::", "HTTPClientError", ")", "or", "response", ".", "kind_of?", "(", "Net", "::", "HTTPServerError", ")", "@log", ".", "puts", "\"#{response.code} encountered for #{url}\"", "end", "end" ]
Creates a new Observer object Called by the Observable module through Webcrawler.
[ "Creates", "a", "new", "Observer", "object", "Called", "by", "the", "Observable", "module", "through", "Webcrawler", "." ]
5ee0358a6c9c6961b88b0366d6f0442c48f5e3c2
https://github.com/tylercunnion/crawler/blob/5ee0358a6c9c6961b88b0366d6f0442c48f5e3c2/lib/crawler/observer.rb#L15-L20
train
Antti/skyper
lib/skyper/skype.rb
Skyper.Skype.answer
def answer(call) cmd = "ALTER CALL #{call.call_id} ANSWER" r = Skype.send_command cmd raise RuntimeError("Failed to answer call. Skype returned '#{r}'") unless r == cmd end
ruby
def answer(call) cmd = "ALTER CALL #{call.call_id} ANSWER" r = Skype.send_command cmd raise RuntimeError("Failed to answer call. Skype returned '#{r}'") unless r == cmd end
[ "def", "answer", "(", "call", ")", "cmd", "=", "\"ALTER CALL #{call.call_id} ANSWER\"", "r", "=", "Skype", ".", "send_command", "cmd", "raise", "RuntimeError", "(", "\"Failed to answer call. Skype returned '#{r}'\"", ")", "unless", "r", "==", "cmd", "end" ]
Answers a call given a skype Call ID. Returns an Array of Call objects.
[ "Answers", "a", "call", "given", "a", "skype", "Call", "ID", ".", "Returns", "an", "Array", "of", "Call", "objects", "." ]
16c1c19a485be24376acfa0b7e0a7775ec16b30c
https://github.com/Antti/skyper/blob/16c1c19a485be24376acfa0b7e0a7775ec16b30c/lib/skyper/skype.rb#L41-L45
train
appoxy/simple_record
lib/simple_record/attributes.rb
SimpleRecord.Attributes.get_attribute
def get_attribute(name) # puts "get_attribute #{name}" # Check if this arg is already converted name_s = name.to_s name = name.to_sym att_meta = get_att_meta(name) # puts "att_meta for #{name}: " + att_meta.inspect if att_meta && att_meta.type == :clob ret = @lobs[name] # puts 'get_attribute clob ' + ret.inspect if ret if ret.is_a? RemoteNil return nil else return ret end end # get it from s3 unless new_record? if self.class.get_sr_config[:single_clob] begin single_clob = s3_bucket(false, :s3_bucket=>:new).get(single_clob_id) single_clob = JSON.parse(single_clob) # puts "single_clob=" + single_clob.inspect single_clob.each_pair do |name2, val| @lobs[name2.to_sym] = val end ret = @lobs[name] SimpleRecord.stats.s3_gets += 1 rescue Aws::AwsError => ex if ex.include?(/NoSuchKey/) || ex.include?(/NoSuchBucket/) ret = nil else raise ex end end else begin ret = s3_bucket.get(s3_lob_id(name)) # puts 'got from s3 ' + ret.inspect SimpleRecord.stats.s3_gets += 1 rescue Aws::AwsError => ex if ex.include?(/NoSuchKey/) || ex.include?(/NoSuchBucket/) ret = nil else raise ex end end end if ret.nil? ret = RemoteNil.new end end @lobs[name] = ret return nil if ret.is_a? RemoteNil return ret else @attributes_rb = {} unless @attributes_rb # was getting errors after upgrade. ret = @attributes_rb[name_s] # instance_variable_get(instance_var) return ret unless ret.nil? return nil if ret.is_a? RemoteNil ret = get_attribute_sdb(name) # p ret ret = sdb_to_ruby(name, ret) # p ret @attributes_rb[name_s] = ret return ret end end
ruby
def get_attribute(name) # puts "get_attribute #{name}" # Check if this arg is already converted name_s = name.to_s name = name.to_sym att_meta = get_att_meta(name) # puts "att_meta for #{name}: " + att_meta.inspect if att_meta && att_meta.type == :clob ret = @lobs[name] # puts 'get_attribute clob ' + ret.inspect if ret if ret.is_a? RemoteNil return nil else return ret end end # get it from s3 unless new_record? if self.class.get_sr_config[:single_clob] begin single_clob = s3_bucket(false, :s3_bucket=>:new).get(single_clob_id) single_clob = JSON.parse(single_clob) # puts "single_clob=" + single_clob.inspect single_clob.each_pair do |name2, val| @lobs[name2.to_sym] = val end ret = @lobs[name] SimpleRecord.stats.s3_gets += 1 rescue Aws::AwsError => ex if ex.include?(/NoSuchKey/) || ex.include?(/NoSuchBucket/) ret = nil else raise ex end end else begin ret = s3_bucket.get(s3_lob_id(name)) # puts 'got from s3 ' + ret.inspect SimpleRecord.stats.s3_gets += 1 rescue Aws::AwsError => ex if ex.include?(/NoSuchKey/) || ex.include?(/NoSuchBucket/) ret = nil else raise ex end end end if ret.nil? ret = RemoteNil.new end end @lobs[name] = ret return nil if ret.is_a? RemoteNil return ret else @attributes_rb = {} unless @attributes_rb # was getting errors after upgrade. ret = @attributes_rb[name_s] # instance_variable_get(instance_var) return ret unless ret.nil? return nil if ret.is_a? RemoteNil ret = get_attribute_sdb(name) # p ret ret = sdb_to_ruby(name, ret) # p ret @attributes_rb[name_s] = ret return ret end end
[ "def", "get_attribute", "(", "name", ")", "name_s", "=", "name", ".", "to_s", "name", "=", "name", ".", "to_sym", "att_meta", "=", "get_att_meta", "(", "name", ")", "if", "att_meta", "&&", "att_meta", ".", "type", "==", ":clob", "ret", "=", "@lobs", "[", "name", "]", "if", "ret", "if", "ret", ".", "is_a?", "RemoteNil", "return", "nil", "else", "return", "ret", "end", "end", "unless", "new_record?", "if", "self", ".", "class", ".", "get_sr_config", "[", ":single_clob", "]", "begin", "single_clob", "=", "s3_bucket", "(", "false", ",", ":s3_bucket", "=>", ":new", ")", ".", "get", "(", "single_clob_id", ")", "single_clob", "=", "JSON", ".", "parse", "(", "single_clob", ")", "single_clob", ".", "each_pair", "do", "|", "name2", ",", "val", "|", "@lobs", "[", "name2", ".", "to_sym", "]", "=", "val", "end", "ret", "=", "@lobs", "[", "name", "]", "SimpleRecord", ".", "stats", ".", "s3_gets", "+=", "1", "rescue", "Aws", "::", "AwsError", "=>", "ex", "if", "ex", ".", "include?", "(", "/", "/", ")", "||", "ex", ".", "include?", "(", "/", "/", ")", "ret", "=", "nil", "else", "raise", "ex", "end", "end", "else", "begin", "ret", "=", "s3_bucket", ".", "get", "(", "s3_lob_id", "(", "name", ")", ")", "SimpleRecord", ".", "stats", ".", "s3_gets", "+=", "1", "rescue", "Aws", "::", "AwsError", "=>", "ex", "if", "ex", ".", "include?", "(", "/", "/", ")", "||", "ex", ".", "include?", "(", "/", "/", ")", "ret", "=", "nil", "else", "raise", "ex", "end", "end", "end", "if", "ret", ".", "nil?", "ret", "=", "RemoteNil", ".", "new", "end", "end", "@lobs", "[", "name", "]", "=", "ret", "return", "nil", "if", "ret", ".", "is_a?", "RemoteNil", "return", "ret", "else", "@attributes_rb", "=", "{", "}", "unless", "@attributes_rb", "ret", "=", "@attributes_rb", "[", "name_s", "]", "return", "ret", "unless", "ret", ".", "nil?", "return", "nil", "if", "ret", ".", "is_a?", "RemoteNil", "ret", "=", "get_attribute_sdb", "(", "name", ")", "ret", "=", "sdb_to_ruby", "(", "name", ",", "ret", ")", "@attributes_rb", "[", "name_s", "]", "=", "ret", "return", "ret", "end", "end" ]
Since SimpleDB supports multiple attributes per value, the values are an array. This method will return the value unwrapped if it's the only, otherwise it will return the array.
[ "Since", "SimpleDB", "supports", "multiple", "attributes", "per", "value", "the", "values", "are", "an", "array", ".", "This", "method", "will", "return", "the", "value", "unwrapped", "if", "it", "s", "the", "only", "otherwise", "it", "will", "return", "the", "array", "." ]
0252a022a938f368d6853ab1ae31f77f80b9f044
https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/attributes.rb#L328-L398
train
OSC/ood_support
lib/ood_support/acl.rb
OodSupport.ACL.ordered_check
def ordered_check(**kwargs) entries.each do |entry| if entry.match(**kwargs) # Check if its an allow or deny acl entry (may not be both) return true if entry.is_allow? return false if entry.is_deny? end end return default # default allow or default deny end
ruby
def ordered_check(**kwargs) entries.each do |entry| if entry.match(**kwargs) # Check if its an allow or deny acl entry (may not be both) return true if entry.is_allow? return false if entry.is_deny? end end return default # default allow or default deny end
[ "def", "ordered_check", "(", "**", "kwargs", ")", "entries", ".", "each", "do", "|", "entry", "|", "if", "entry", ".", "match", "(", "**", "kwargs", ")", "return", "true", "if", "entry", ".", "is_allow?", "return", "false", "if", "entry", ".", "is_deny?", "end", "end", "return", "default", "end" ]
Check each entry in order from array
[ "Check", "each", "entry", "in", "order", "from", "array" ]
a5e42a1b31d90763964f39ebe241e69c15d0f404
https://github.com/OSC/ood_support/blob/a5e42a1b31d90763964f39ebe241e69c15d0f404/lib/ood_support/acl.rb#L78-L87
train
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.ScheduledEvent.inspect
def inspect insp = String.new("#<#{self.class}:#{"0x00%x" % (self.__id__ << 1)} ") insp << "trigger_count=#{@trigger_count} " insp << "config=#{info} " if self.respond_to?(:info, true) insp << "next_scheduled=#{to_time(@next_scheduled)} " insp << "last_scheduled=#{to_time(@last_scheduled)} created=#{to_time(@created)}>" insp end
ruby
def inspect insp = String.new("#<#{self.class}:#{"0x00%x" % (self.__id__ << 1)} ") insp << "trigger_count=#{@trigger_count} " insp << "config=#{info} " if self.respond_to?(:info, true) insp << "next_scheduled=#{to_time(@next_scheduled)} " insp << "last_scheduled=#{to_time(@last_scheduled)} created=#{to_time(@created)}>" insp end
[ "def", "inspect", "insp", "=", "String", ".", "new", "(", "\"#<#{self.class}:#{\"0x00%x\" % (self.__id__ << 1)} \"", ")", "insp", "<<", "\"trigger_count=#{@trigger_count} \"", "insp", "<<", "\"config=#{info} \"", "if", "self", ".", "respond_to?", "(", ":info", ",", "true", ")", "insp", "<<", "\"next_scheduled=#{to_time(@next_scheduled)} \"", "insp", "<<", "\"last_scheduled=#{to_time(@last_scheduled)} created=#{to_time(@created)}>\"", "insp", "end" ]
Provide relevant inspect information
[ "Provide", "relevant", "inspect", "information" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L39-L46
train
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.OneShot.update
def update(time) @last_scheduled = @reactor.now parsed_time = Scheduler.parse_in(time, :quiet) if parsed_time.nil? # Parse at will throw an error if time is invalid parsed_time = Scheduler.parse_at(time) - @scheduler.time_diff else parsed_time += @last_scheduled end @next_scheduled = parsed_time @scheduler.reschedule(self) end
ruby
def update(time) @last_scheduled = @reactor.now parsed_time = Scheduler.parse_in(time, :quiet) if parsed_time.nil? # Parse at will throw an error if time is invalid parsed_time = Scheduler.parse_at(time) - @scheduler.time_diff else parsed_time += @last_scheduled end @next_scheduled = parsed_time @scheduler.reschedule(self) end
[ "def", "update", "(", "time", ")", "@last_scheduled", "=", "@reactor", ".", "now", "parsed_time", "=", "Scheduler", ".", "parse_in", "(", "time", ",", ":quiet", ")", "if", "parsed_time", ".", "nil?", "parsed_time", "=", "Scheduler", ".", "parse_at", "(", "time", ")", "-", "@scheduler", ".", "time_diff", "else", "parsed_time", "+=", "@last_scheduled", "end", "@next_scheduled", "=", "parsed_time", "@scheduler", ".", "reschedule", "(", "self", ")", "end" ]
Updates the scheduled time
[ "Updates", "the", "scheduled", "time" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L81-L94
train
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Repeat.update
def update(every, timezone: nil) time = Scheduler.parse_in(every, :quiet) || Scheduler.parse_cron(every, :quiet, timezone: timezone) raise ArgumentError.new("couldn't parse \"#{o}\"") if time.nil? @every = time reschedule end
ruby
def update(every, timezone: nil) time = Scheduler.parse_in(every, :quiet) || Scheduler.parse_cron(every, :quiet, timezone: timezone) raise ArgumentError.new("couldn't parse \"#{o}\"") if time.nil? @every = time reschedule end
[ "def", "update", "(", "every", ",", "timezone", ":", "nil", ")", "time", "=", "Scheduler", ".", "parse_in", "(", "every", ",", ":quiet", ")", "||", "Scheduler", ".", "parse_cron", "(", "every", ",", ":quiet", ",", "timezone", ":", "timezone", ")", "raise", "ArgumentError", ".", "new", "(", "\"couldn't parse \\\"#{o}\\\"\"", ")", "if", "time", ".", "nil?", "@every", "=", "time", "reschedule", "end" ]
Update the time period of the repeating event @param schedule [String] a standard CRON job line or a human readable string representing a time period.
[ "Update", "the", "time", "period", "of", "the", "repeating", "event" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L114-L120
train
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.every
def every(time) ms = Scheduler.parse_in(time) event = Repeat.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
ruby
def every(time) ms = Scheduler.parse_in(time) event = Repeat.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
[ "def", "every", "(", "time", ")", "ms", "=", "Scheduler", ".", "parse_in", "(", "time", ")", "event", "=", "Repeat", ".", "new", "(", "self", ",", "ms", ")", "event", ".", "progress", "&", "Proc", ".", "new", "if", "block_given?", "schedule", "(", "event", ")", "event", "end" ]
Create a repeating event that occurs each time period @param time [String] a human readable string representing the time period. 3w2d4h1m2s for example. @param callback [Proc] a block or method to execute when the event triggers @return [::UV::Repeat]
[ "Create", "a", "repeating", "event", "that", "occurs", "each", "time", "period" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L213-L219
train
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.in
def in(time) ms = @reactor.now + Scheduler.parse_in(time) event = OneShot.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
ruby
def in(time) ms = @reactor.now + Scheduler.parse_in(time) event = OneShot.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
[ "def", "in", "(", "time", ")", "ms", "=", "@reactor", ".", "now", "+", "Scheduler", ".", "parse_in", "(", "time", ")", "event", "=", "OneShot", ".", "new", "(", "self", ",", "ms", ")", "event", ".", "progress", "&", "Proc", ".", "new", "if", "block_given?", "schedule", "(", "event", ")", "event", "end" ]
Create a one off event that occurs after the time period @param time [String] a human readable string representing the time period. 3w2d4h1m2s for example. @param callback [Proc] a block or method to execute when the event triggers @return [::UV::OneShot]
[ "Create", "a", "one", "off", "event", "that", "occurs", "after", "the", "time", "period" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L226-L232
train
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.at
def at(time) ms = Scheduler.parse_at(time) - @time_diff event = OneShot.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
ruby
def at(time) ms = Scheduler.parse_at(time) - @time_diff event = OneShot.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
[ "def", "at", "(", "time", ")", "ms", "=", "Scheduler", ".", "parse_at", "(", "time", ")", "-", "@time_diff", "event", "=", "OneShot", ".", "new", "(", "self", ",", "ms", ")", "event", ".", "progress", "&", "Proc", ".", "new", "if", "block_given?", "schedule", "(", "event", ")", "event", "end" ]
Create a one off event that occurs at a particular date and time @param time [String, Time] a representation of a date and time that can be parsed @param callback [Proc] a block or method to execute when the event triggers @return [::UV::OneShot]
[ "Create", "a", "one", "off", "event", "that", "occurs", "at", "a", "particular", "date", "and", "time" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L239-L245
train
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.cron
def cron(schedule, timezone: nil) ms = Scheduler.parse_cron(schedule, timezone: timezone) event = Repeat.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
ruby
def cron(schedule, timezone: nil) ms = Scheduler.parse_cron(schedule, timezone: timezone) event = Repeat.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
[ "def", "cron", "(", "schedule", ",", "timezone", ":", "nil", ")", "ms", "=", "Scheduler", ".", "parse_cron", "(", "schedule", ",", "timezone", ":", "timezone", ")", "event", "=", "Repeat", ".", "new", "(", "self", ",", "ms", ")", "event", ".", "progress", "&", "Proc", ".", "new", "if", "block_given?", "schedule", "(", "event", ")", "event", "end" ]
Create a repeating event that uses a CRON line to determine the trigger time @param schedule [String] a standard CRON job line. @param callback [Proc] a block or method to execute when the event triggers @return [::UV::Repeat]
[ "Create", "a", "repeating", "event", "that", "uses", "a", "CRON", "line", "to", "determine", "the", "trigger", "time" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L252-L258
train
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.reschedule
def reschedule(event) # Check promise is not resolved return if event.resolved? @critical.synchronize { # Remove the event from the scheduled list and ensure it is in the schedules set if @schedules.include?(event) remove(event) else @schedules << event end # optimal algorithm for inserting into an already sorted list Bisect.insort(@scheduled, event) # Update the timer check_timer } end
ruby
def reschedule(event) # Check promise is not resolved return if event.resolved? @critical.synchronize { # Remove the event from the scheduled list and ensure it is in the schedules set if @schedules.include?(event) remove(event) else @schedules << event end # optimal algorithm for inserting into an already sorted list Bisect.insort(@scheduled, event) # Update the timer check_timer } end
[ "def", "reschedule", "(", "event", ")", "return", "if", "event", ".", "resolved?", "@critical", ".", "synchronize", "{", "if", "@schedules", ".", "include?", "(", "event", ")", "remove", "(", "event", ")", "else", "@schedules", "<<", "event", "end", "Bisect", ".", "insort", "(", "@scheduled", ",", "event", ")", "check_timer", "}", "end" ]
Schedules an event for execution @param event [ScheduledEvent]
[ "Schedules", "an", "event", "for", "execution" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L263-L281
train
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.unschedule
def unschedule(event) @critical.synchronize { # Only call delete and update the timer when required if @schedules.include?(event) @schedules.delete(event) remove(event) check_timer end } end
ruby
def unschedule(event) @critical.synchronize { # Only call delete and update the timer when required if @schedules.include?(event) @schedules.delete(event) remove(event) check_timer end } end
[ "def", "unschedule", "(", "event", ")", "@critical", ".", "synchronize", "{", "if", "@schedules", ".", "include?", "(", "event", ")", "@schedules", ".", "delete", "(", "event", ")", "remove", "(", "event", ")", "check_timer", "end", "}", "end" ]
Removes an event from the schedule @param event [ScheduledEvent]
[ "Removes", "an", "event", "from", "the", "schedule" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L286-L295
train
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.remove
def remove(obj) position = nil @scheduled.each_index do |i| # object level comparison if obj.equal? @scheduled[i] position = i break end end @scheduled.slice!(position) unless position.nil? end
ruby
def remove(obj) position = nil @scheduled.each_index do |i| # object level comparison if obj.equal? @scheduled[i] position = i break end end @scheduled.slice!(position) unless position.nil? end
[ "def", "remove", "(", "obj", ")", "position", "=", "nil", "@scheduled", ".", "each_index", "do", "|", "i", "|", "if", "obj", ".", "equal?", "@scheduled", "[", "i", "]", "position", "=", "i", "break", "end", "end", "@scheduled", ".", "slice!", "(", "position", ")", "unless", "position", ".", "nil?", "end" ]
Remove an element from the array
[ "Remove", "an", "element", "from", "the", "array" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L302-L314
train
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.check_timer
def check_timer @reactor.update_time existing = @next schedule = @scheduled.first @next = schedule.nil? ? nil : schedule.next_scheduled if existing != @next # lazy load the timer if @timer.nil? new_timer else @timer.stop end if not @next.nil? in_time = @next - @reactor.now # Ensure there are never negative start times if in_time > 3 @timer.start(in_time) else # Effectively next tick @timer.start(0) end end end end
ruby
def check_timer @reactor.update_time existing = @next schedule = @scheduled.first @next = schedule.nil? ? nil : schedule.next_scheduled if existing != @next # lazy load the timer if @timer.nil? new_timer else @timer.stop end if not @next.nil? in_time = @next - @reactor.now # Ensure there are never negative start times if in_time > 3 @timer.start(in_time) else # Effectively next tick @timer.start(0) end end end end
[ "def", "check_timer", "@reactor", ".", "update_time", "existing", "=", "@next", "schedule", "=", "@scheduled", ".", "first", "@next", "=", "schedule", ".", "nil?", "?", "nil", ":", "schedule", ".", "next_scheduled", "if", "existing", "!=", "@next", "if", "@timer", ".", "nil?", "new_timer", "else", "@timer", ".", "stop", "end", "if", "not", "@next", ".", "nil?", "in_time", "=", "@next", "-", "@reactor", ".", "now", "if", "in_time", ">", "3", "@timer", ".", "start", "(", "in_time", ")", "else", "@timer", ".", "start", "(", "0", ")", "end", "end", "end", "end" ]
Ensures the current timer, if any, is still accurate by checking the head of the schedule
[ "Ensures", "the", "current", "timer", "if", "any", "is", "still", "accurate", "by", "checking", "the", "head", "of", "the", "schedule" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L327-L354
train
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.on_timer
def on_timer @critical.synchronize { schedule = @scheduled.shift @schedules.delete(schedule) schedule.trigger # execute schedules that are within 3ms of this event # Basic timer coalescing.. now = @reactor.now + 3 while @scheduled.first && @scheduled.first.next_scheduled <= now schedule = @scheduled.shift @schedules.delete(schedule) schedule.trigger end check_timer } end
ruby
def on_timer @critical.synchronize { schedule = @scheduled.shift @schedules.delete(schedule) schedule.trigger # execute schedules that are within 3ms of this event # Basic timer coalescing.. now = @reactor.now + 3 while @scheduled.first && @scheduled.first.next_scheduled <= now schedule = @scheduled.shift @schedules.delete(schedule) schedule.trigger end check_timer } end
[ "def", "on_timer", "@critical", ".", "synchronize", "{", "schedule", "=", "@scheduled", ".", "shift", "@schedules", ".", "delete", "(", "schedule", ")", "schedule", ".", "trigger", "now", "=", "@reactor", ".", "now", "+", "3", "while", "@scheduled", ".", "first", "&&", "@scheduled", ".", "first", ".", "next_scheduled", "<=", "now", "schedule", "=", "@scheduled", ".", "shift", "@schedules", ".", "delete", "(", "schedule", ")", "schedule", ".", "trigger", "end", "check_timer", "}", "end" ]
Is called when the libuv timer fires
[ "Is", "called", "when", "the", "libuv", "timer", "fires" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L357-L373
train
rtwomey/stately
lib/stately.rb
Stately.Core.stately
def stately(*opts, &block) options = opts.last.is_a?(Hash) ? opts.last : {} options[:attr] ||= :state @stately_machine = Stately::Machine.new(options[:attr], options[:start]) @stately_machine.instance_eval(&block) if block_given? include Stately::InstanceMethods end
ruby
def stately(*opts, &block) options = opts.last.is_a?(Hash) ? opts.last : {} options[:attr] ||= :state @stately_machine = Stately::Machine.new(options[:attr], options[:start]) @stately_machine.instance_eval(&block) if block_given? include Stately::InstanceMethods end
[ "def", "stately", "(", "*", "opts", ",", "&", "block", ")", "options", "=", "opts", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "opts", ".", "last", ":", "{", "}", "options", "[", ":attr", "]", "||=", ":state", "@stately_machine", "=", "Stately", "::", "Machine", ".", "new", "(", "options", "[", ":attr", "]", ",", "options", "[", ":start", "]", ")", "@stately_machine", ".", "instance_eval", "(", "&", "block", ")", "if", "block_given?", "include", "Stately", "::", "InstanceMethods", "end" ]
Define a new Stately state machine. As an example, let's say you have an Order object and you'd like an elegant state machine for it. Here's one way you might set it up: Class Order do stately start: :processing do state :completed do prevent_from :refunded before_transition from: :processing, do: :calculate_total after_transition do: :email_receipt validate :validates_credit_card end state :invalid do prevent_from :completed, :refunded end state :refunded do allow_from :completed after_transition do: :email_receipt end end end This example is doing quite a few things, paraphrased as: * It sets up a new state machine using the default state attribute on Order to store the current state. It also indicates the initial state should be :processing. * It defines three states: :completed, :refunded, and :invalid * Order can transition to the completed state from all but the refunded state. Similar definitions are setup for the other two states. * Callbacks are setup using before_transition and after_transition * Validations are added. If a validation fails, it prevents the transition. Stately tries hard not to surprise you. In a typical Stately implementation, you'll always have an after_transition, primarily to call save (or whatever the equivalent is to store the instance's current state).
[ "Define", "a", "new", "Stately", "state", "machine", "." ]
03c01e21e024e14c5bb93202eea1c85a08e42821
https://github.com/rtwomey/stately/blob/03c01e21e024e14c5bb93202eea1c85a08e42821/lib/stately.rb#L52-L60
train
redding/dk
lib/dk/runner.rb
Dk.Runner.build_local_cmd
def build_local_cmd(task, cmd_str, input, given_opts) Local::Cmd.new(cmd_str, given_opts) end
ruby
def build_local_cmd(task, cmd_str, input, given_opts) Local::Cmd.new(cmd_str, given_opts) end
[ "def", "build_local_cmd", "(", "task", ",", "cmd_str", ",", "input", ",", "given_opts", ")", "Local", "::", "Cmd", ".", "new", "(", "cmd_str", ",", "given_opts", ")", "end" ]
input is needed for the `TestRunner` so it can use it with stubbing otherwise it is ignored when building a local cmd
[ "input", "is", "needed", "for", "the", "TestRunner", "so", "it", "can", "use", "it", "with", "stubbing", "otherwise", "it", "is", "ignored", "when", "building", "a", "local", "cmd" ]
9b6122ce815467c698811014c01518cca539946e
https://github.com/redding/dk/blob/9b6122ce815467c698811014c01518cca539946e/lib/dk/runner.rb#L172-L174
train
redding/dk
lib/dk/runner.rb
Dk.Runner.build_remote_cmd
def build_remote_cmd(task, cmd_str, input, given_opts, ssh_opts) Remote::Cmd.new(cmd_str, ssh_opts) end
ruby
def build_remote_cmd(task, cmd_str, input, given_opts, ssh_opts) Remote::Cmd.new(cmd_str, ssh_opts) end
[ "def", "build_remote_cmd", "(", "task", ",", "cmd_str", ",", "input", ",", "given_opts", ",", "ssh_opts", ")", "Remote", "::", "Cmd", ".", "new", "(", "cmd_str", ",", "ssh_opts", ")", "end" ]
input and given opts are needed for the `TestRunner` so it can use it with stubbing otherwise they are ignored when building a remote cmd
[ "input", "and", "given", "opts", "are", "needed", "for", "the", "TestRunner", "so", "it", "can", "use", "it", "with", "stubbing", "otherwise", "they", "are", "ignored", "when", "building", "a", "remote", "cmd" ]
9b6122ce815467c698811014c01518cca539946e
https://github.com/redding/dk/blob/9b6122ce815467c698811014c01518cca539946e/lib/dk/runner.rb#L193-L195
train
epuber-io/epuber
lib/epuber/book.rb
Epuber.Book.targets
def targets(*names, &block) if names.empty? UI.warning('Book#targets to get all targets is deprecated, use #all_targets instead', location: caller_locations.first) return all_targets end names.map { |name| target(name, &block) } end
ruby
def targets(*names, &block) if names.empty? UI.warning('Book#targets to get all targets is deprecated, use #all_targets instead', location: caller_locations.first) return all_targets end names.map { |name| target(name, &block) } end
[ "def", "targets", "(", "*", "names", ",", "&", "block", ")", "if", "names", ".", "empty?", "UI", ".", "warning", "(", "'Book#targets to get all targets is deprecated, use #all_targets instead'", ",", "location", ":", "caller_locations", ".", "first", ")", "return", "all_targets", "end", "names", ".", "map", "{", "|", "name", "|", "target", "(", "name", ",", "&", "block", ")", "}", "end" ]
Defines several new targets with same configuration @param [Array<String, Symbol>] names @return [Array<Target>] result target
[ "Defines", "several", "new", "targets", "with", "same", "configuration" ]
4d736deb3f18c034fc93fcb95cfb9bf03b63c252
https://github.com/epuber-io/epuber/blob/4d736deb3f18c034fc93fcb95cfb9bf03b63c252/lib/epuber/book.rb#L127-L134
train
zanker/ruby-smugmug
lib/smugmug/http.rb
SmugMug.HTTP.request
def request(api, args) uri = api == :uploading ? UPLOAD_URI : API_URI args[:method] = "smugmug.#{api}" unless api == :uploading http = ::Net::HTTP.new(uri.host, uri.port, @http_proxy_host, @http_proxy_port, @http_proxy_user, @http_proxy_pass) http.set_debug_output(@config[:debug_output]) if @config[:debug_output] # Configure HTTPS if needed if uri.scheme == "https" http.use_ssl = true if @config[:http] and @config[:http][:verify_mode] http.verify_mode = @config[:http][:verify_mode] http.ca_file = @config[:http][:ca_file] http.ca_path = @config[:http][:ca_path] else http.verify_mode = OpenSSL::SSL::VERIFY_NONE end end # Upload request, which requires special handling if api == :uploading postdata = args.delete(:content) headers = @headers.merge("Content-Length" => postdata.length.to_s, "Content-MD5" => Digest::MD5.hexdigest(postdata), "X-Smug-Version" => "1.3.0", "X-Smug-ResponseType" => "JSON") UPLOAD_HEADERS.each do |key| next unless args[key] and args[key] != "" headers["X-Smug-#{key}"] = args[key].to_s end oauth = self.sign_request("POST", uri, nil) headers["Authorization"] = "OAuth oauth_consumer_key=\"#{oauth["oauth_consumer_key"]}\", oauth_nonce=\"#{oauth["oauth_nonce"]}\", oauth_signature_method=\"#{oauth["oauth_signature_method"]}\", oauth_signature=\"#{oauth["oauth_signature"]}\", oauth_timestamp=\"#{oauth["oauth_timestamp"]}\", oauth_version=\"#{oauth["oauth_version"]}\", oauth_token=\"#{oauth["oauth_token"]}\"" # Normal API method else postdata = self.sign_request("POST", uri, args) headers = @headers end response = http.request_post(uri.request_uri, postdata, headers) if response.code == "204" return nil elsif response.code != "200" raise SmugMug::HTTPError.new("HTTP #{response.code}, #{response.message}", response.code, response.message) end # Check for GZIP encoding if response.header["content-encoding"] == "gzip" begin body = Zlib::GzipReader.new(StringIO.new(response.body)).read rescue Zlib::GzipFile::Error raise end else body = response.body end return nil if body == "" data = JSON.parse(body) if data["stat"] == "fail" # Special casing for SmugMug being in Read only mode if data["code"] == 99 raise SmugMug::ReadonlyModeError.new("SmugMug is currently in read only mode, try again later") end klass = OAUTH_ERRORS[data["code"]] ? SmugMug::OAuthError : SmugMug::RequestError raise klass.new("Error ##{data["code"]}, #{data["message"]}", data["code"], data["message"]) end data.delete("stat") data.delete("method") # smugmug.albums.changeSettings at the least doesn't return any data return nil if data.length == 0 # It seems all smugmug APIs only return one hash of data, so this should be fine and not cause issues data.each do |_, value| return value end end
ruby
def request(api, args) uri = api == :uploading ? UPLOAD_URI : API_URI args[:method] = "smugmug.#{api}" unless api == :uploading http = ::Net::HTTP.new(uri.host, uri.port, @http_proxy_host, @http_proxy_port, @http_proxy_user, @http_proxy_pass) http.set_debug_output(@config[:debug_output]) if @config[:debug_output] # Configure HTTPS if needed if uri.scheme == "https" http.use_ssl = true if @config[:http] and @config[:http][:verify_mode] http.verify_mode = @config[:http][:verify_mode] http.ca_file = @config[:http][:ca_file] http.ca_path = @config[:http][:ca_path] else http.verify_mode = OpenSSL::SSL::VERIFY_NONE end end # Upload request, which requires special handling if api == :uploading postdata = args.delete(:content) headers = @headers.merge("Content-Length" => postdata.length.to_s, "Content-MD5" => Digest::MD5.hexdigest(postdata), "X-Smug-Version" => "1.3.0", "X-Smug-ResponseType" => "JSON") UPLOAD_HEADERS.each do |key| next unless args[key] and args[key] != "" headers["X-Smug-#{key}"] = args[key].to_s end oauth = self.sign_request("POST", uri, nil) headers["Authorization"] = "OAuth oauth_consumer_key=\"#{oauth["oauth_consumer_key"]}\", oauth_nonce=\"#{oauth["oauth_nonce"]}\", oauth_signature_method=\"#{oauth["oauth_signature_method"]}\", oauth_signature=\"#{oauth["oauth_signature"]}\", oauth_timestamp=\"#{oauth["oauth_timestamp"]}\", oauth_version=\"#{oauth["oauth_version"]}\", oauth_token=\"#{oauth["oauth_token"]}\"" # Normal API method else postdata = self.sign_request("POST", uri, args) headers = @headers end response = http.request_post(uri.request_uri, postdata, headers) if response.code == "204" return nil elsif response.code != "200" raise SmugMug::HTTPError.new("HTTP #{response.code}, #{response.message}", response.code, response.message) end # Check for GZIP encoding if response.header["content-encoding"] == "gzip" begin body = Zlib::GzipReader.new(StringIO.new(response.body)).read rescue Zlib::GzipFile::Error raise end else body = response.body end return nil if body == "" data = JSON.parse(body) if data["stat"] == "fail" # Special casing for SmugMug being in Read only mode if data["code"] == 99 raise SmugMug::ReadonlyModeError.new("SmugMug is currently in read only mode, try again later") end klass = OAUTH_ERRORS[data["code"]] ? SmugMug::OAuthError : SmugMug::RequestError raise klass.new("Error ##{data["code"]}, #{data["message"]}", data["code"], data["message"]) end data.delete("stat") data.delete("method") # smugmug.albums.changeSettings at the least doesn't return any data return nil if data.length == 0 # It seems all smugmug APIs only return one hash of data, so this should be fine and not cause issues data.each do |_, value| return value end end
[ "def", "request", "(", "api", ",", "args", ")", "uri", "=", "api", "==", ":uploading", "?", "UPLOAD_URI", ":", "API_URI", "args", "[", ":method", "]", "=", "\"smugmug.#{api}\"", "unless", "api", "==", ":uploading", "http", "=", "::", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ",", "@http_proxy_host", ",", "@http_proxy_port", ",", "@http_proxy_user", ",", "@http_proxy_pass", ")", "http", ".", "set_debug_output", "(", "@config", "[", ":debug_output", "]", ")", "if", "@config", "[", ":debug_output", "]", "if", "uri", ".", "scheme", "==", "\"https\"", "http", ".", "use_ssl", "=", "true", "if", "@config", "[", ":http", "]", "and", "@config", "[", ":http", "]", "[", ":verify_mode", "]", "http", ".", "verify_mode", "=", "@config", "[", ":http", "]", "[", ":verify_mode", "]", "http", ".", "ca_file", "=", "@config", "[", ":http", "]", "[", ":ca_file", "]", "http", ".", "ca_path", "=", "@config", "[", ":http", "]", "[", ":ca_path", "]", "else", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "end", "end", "if", "api", "==", ":uploading", "postdata", "=", "args", ".", "delete", "(", ":content", ")", "headers", "=", "@headers", ".", "merge", "(", "\"Content-Length\"", "=>", "postdata", ".", "length", ".", "to_s", ",", "\"Content-MD5\"", "=>", "Digest", "::", "MD5", ".", "hexdigest", "(", "postdata", ")", ",", "\"X-Smug-Version\"", "=>", "\"1.3.0\"", ",", "\"X-Smug-ResponseType\"", "=>", "\"JSON\"", ")", "UPLOAD_HEADERS", ".", "each", "do", "|", "key", "|", "next", "unless", "args", "[", "key", "]", "and", "args", "[", "key", "]", "!=", "\"\"", "headers", "[", "\"X-Smug-#{key}\"", "]", "=", "args", "[", "key", "]", ".", "to_s", "end", "oauth", "=", "self", ".", "sign_request", "(", "\"POST\"", ",", "uri", ",", "nil", ")", "headers", "[", "\"Authorization\"", "]", "=", "\"OAuth oauth_consumer_key=\\\"#{oauth[\"oauth_consumer_key\"]}\\\", oauth_nonce=\\\"#{oauth[\"oauth_nonce\"]}\\\", oauth_signature_method=\\\"#{oauth[\"oauth_signature_method\"]}\\\", oauth_signature=\\\"#{oauth[\"oauth_signature\"]}\\\", oauth_timestamp=\\\"#{oauth[\"oauth_timestamp\"]}\\\", oauth_version=\\\"#{oauth[\"oauth_version\"]}\\\", oauth_token=\\\"#{oauth[\"oauth_token\"]}\\\"\"", "else", "postdata", "=", "self", ".", "sign_request", "(", "\"POST\"", ",", "uri", ",", "args", ")", "headers", "=", "@headers", "end", "response", "=", "http", ".", "request_post", "(", "uri", ".", "request_uri", ",", "postdata", ",", "headers", ")", "if", "response", ".", "code", "==", "\"204\"", "return", "nil", "elsif", "response", ".", "code", "!=", "\"200\"", "raise", "SmugMug", "::", "HTTPError", ".", "new", "(", "\"HTTP #{response.code}, #{response.message}\"", ",", "response", ".", "code", ",", "response", ".", "message", ")", "end", "if", "response", ".", "header", "[", "\"content-encoding\"", "]", "==", "\"gzip\"", "begin", "body", "=", "Zlib", "::", "GzipReader", ".", "new", "(", "StringIO", ".", "new", "(", "response", ".", "body", ")", ")", ".", "read", "rescue", "Zlib", "::", "GzipFile", "::", "Error", "raise", "end", "else", "body", "=", "response", ".", "body", "end", "return", "nil", "if", "body", "==", "\"\"", "data", "=", "JSON", ".", "parse", "(", "body", ")", "if", "data", "[", "\"stat\"", "]", "==", "\"fail\"", "if", "data", "[", "\"code\"", "]", "==", "99", "raise", "SmugMug", "::", "ReadonlyModeError", ".", "new", "(", "\"SmugMug is currently in read only mode, try again later\"", ")", "end", "klass", "=", "OAUTH_ERRORS", "[", "data", "[", "\"code\"", "]", "]", "?", "SmugMug", "::", "OAuthError", ":", "SmugMug", "::", "RequestError", "raise", "klass", ".", "new", "(", "\"Error ##{data[\"code\"]}, #{data[\"message\"]}\"", ",", "data", "[", "\"code\"", "]", ",", "data", "[", "\"message\"", "]", ")", "end", "data", ".", "delete", "(", "\"stat\"", ")", "data", ".", "delete", "(", "\"method\"", ")", "return", "nil", "if", "data", ".", "length", "==", "0", "data", ".", "each", "do", "|", "_", ",", "value", "|", "return", "value", "end", "end" ]
Creates a new HTTP wrapper to handle the network portions of the API requests @param [Hash] args Same as [SmugMug::HTTP]
[ "Creates", "a", "new", "HTTP", "wrapper", "to", "handle", "the", "network", "portions", "of", "the", "API", "requests" ]
97d38e3143ae89efa22bcb81676968da5c6afef5
https://github.com/zanker/ruby-smugmug/blob/97d38e3143ae89efa22bcb81676968da5c6afef5/lib/smugmug/http.rb#L35-L116
train
zanker/ruby-smugmug
lib/smugmug/http.rb
SmugMug.HTTP.sign_request
def sign_request(method, uri, form_args) # Convert non-string keys to strings so the sort works args = {} if form_args form_args.each do |key, value| next unless value and value != "" key = key.to_s unless key.is_a?(String) args[key] = value end end # Add the necessary OAuth args args["oauth_version"] = "1.0" args["oauth_consumer_key"] = @config[:api_key] args["oauth_nonce"] = Digest::MD5.hexdigest("#{Time.now.to_f}#{rand(10 ** 30)}") args["oauth_signature_method"] = "HMAC-SHA1" args["oauth_timestamp"] = Time.now.utc.to_i args["oauth_token"] = @config[:user][:token] # RFC 1738 (http://www.ietf.org/rfc/rfc1738.txt) says: # # Thus, only alphanumerics, the special characters "$-_.+!*'(),", and # reserved characters used for their reserved purposes may be used # unencoded within a URL. # # However, if we don't escape apostrophes and parentheses the SmugMug API fails # with an invalid signature error: # # Error #35, invalid signature (SmugMug::OAuthError) # # To overcome this, define a new unreserved character list and use this in URI::escape unreserved = "\\-_.!~*a-zA-Z\\d" unsafe = Regexp.new("[^#{unreserved}]", false, 'N') # Sort the params sorted_args = [] args.sort.each do |key, value| sorted_args.push("#{key.to_s}=#{URI::escape(value.to_s, unsafe)}") end postdata = sorted_args.join("&") # Final string to hash sig_base = "#{method}&#{URI::escape("#{uri.scheme}://#{uri.host}#{uri.path}", unsafe)}&#{URI::escape(postdata, unsafe)}" signature = OpenSSL::HMAC.digest(@digest, "#{@config[:oauth_secret]}&#{@config[:user][:secret]}", sig_base) signature = URI::escape(Base64.encode64(signature).chomp, unsafe) if uri == API_URI "#{postdata}&oauth_signature=#{signature}" else args["oauth_signature"] = signature args end end
ruby
def sign_request(method, uri, form_args) # Convert non-string keys to strings so the sort works args = {} if form_args form_args.each do |key, value| next unless value and value != "" key = key.to_s unless key.is_a?(String) args[key] = value end end # Add the necessary OAuth args args["oauth_version"] = "1.0" args["oauth_consumer_key"] = @config[:api_key] args["oauth_nonce"] = Digest::MD5.hexdigest("#{Time.now.to_f}#{rand(10 ** 30)}") args["oauth_signature_method"] = "HMAC-SHA1" args["oauth_timestamp"] = Time.now.utc.to_i args["oauth_token"] = @config[:user][:token] # RFC 1738 (http://www.ietf.org/rfc/rfc1738.txt) says: # # Thus, only alphanumerics, the special characters "$-_.+!*'(),", and # reserved characters used for their reserved purposes may be used # unencoded within a URL. # # However, if we don't escape apostrophes and parentheses the SmugMug API fails # with an invalid signature error: # # Error #35, invalid signature (SmugMug::OAuthError) # # To overcome this, define a new unreserved character list and use this in URI::escape unreserved = "\\-_.!~*a-zA-Z\\d" unsafe = Regexp.new("[^#{unreserved}]", false, 'N') # Sort the params sorted_args = [] args.sort.each do |key, value| sorted_args.push("#{key.to_s}=#{URI::escape(value.to_s, unsafe)}") end postdata = sorted_args.join("&") # Final string to hash sig_base = "#{method}&#{URI::escape("#{uri.scheme}://#{uri.host}#{uri.path}", unsafe)}&#{URI::escape(postdata, unsafe)}" signature = OpenSSL::HMAC.digest(@digest, "#{@config[:oauth_secret]}&#{@config[:user][:secret]}", sig_base) signature = URI::escape(Base64.encode64(signature).chomp, unsafe) if uri == API_URI "#{postdata}&oauth_signature=#{signature}" else args["oauth_signature"] = signature args end end
[ "def", "sign_request", "(", "method", ",", "uri", ",", "form_args", ")", "args", "=", "{", "}", "if", "form_args", "form_args", ".", "each", "do", "|", "key", ",", "value", "|", "next", "unless", "value", "and", "value", "!=", "\"\"", "key", "=", "key", ".", "to_s", "unless", "key", ".", "is_a?", "(", "String", ")", "args", "[", "key", "]", "=", "value", "end", "end", "args", "[", "\"oauth_version\"", "]", "=", "\"1.0\"", "args", "[", "\"oauth_consumer_key\"", "]", "=", "@config", "[", ":api_key", "]", "args", "[", "\"oauth_nonce\"", "]", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "\"#{Time.now.to_f}#{rand(10 ** 30)}\"", ")", "args", "[", "\"oauth_signature_method\"", "]", "=", "\"HMAC-SHA1\"", "args", "[", "\"oauth_timestamp\"", "]", "=", "Time", ".", "now", ".", "utc", ".", "to_i", "args", "[", "\"oauth_token\"", "]", "=", "@config", "[", ":user", "]", "[", ":token", "]", "unreserved", "=", "\"\\\\-_.!~*a-zA-Z\\\\d\"", "unsafe", "=", "Regexp", ".", "new", "(", "\"[^#{unreserved}]\"", ",", "false", ",", "'N'", ")", "sorted_args", "=", "[", "]", "args", ".", "sort", ".", "each", "do", "|", "key", ",", "value", "|", "sorted_args", ".", "push", "(", "\"#{key.to_s}=#{URI::escape(value.to_s, unsafe)}\"", ")", "end", "postdata", "=", "sorted_args", ".", "join", "(", "\"&\"", ")", "sig_base", "=", "\"#{method}&#{URI::escape(\"#{uri.scheme}://#{uri.host}#{uri.path}\", unsafe)}&#{URI::escape(postdata, unsafe)}\"", "signature", "=", "OpenSSL", "::", "HMAC", ".", "digest", "(", "@digest", ",", "\"#{@config[:oauth_secret]}&#{@config[:user][:secret]}\"", ",", "sig_base", ")", "signature", "=", "URI", "::", "escape", "(", "Base64", ".", "encode64", "(", "signature", ")", ".", "chomp", ",", "unsafe", ")", "if", "uri", "==", "API_URI", "\"#{postdata}&oauth_signature=#{signature}\"", "else", "args", "[", "\"oauth_signature\"", "]", "=", "signature", "args", "end", "end" ]
Generates an OAuth signature and updates the args with the required fields @param [String] method HTTP method that the request is sent as @param [String] uri Full URL of the request @param [Hash] form_args Args to be passed to the server
[ "Generates", "an", "OAuth", "signature", "and", "updates", "the", "args", "with", "the", "required", "fields" ]
97d38e3143ae89efa22bcb81676968da5c6afef5
https://github.com/zanker/ruby-smugmug/blob/97d38e3143ae89efa22bcb81676968da5c6afef5/lib/smugmug/http.rb#L123-L178
train
sosedoff/grooveshark
lib/grooveshark/client.rb
Grooveshark.Client.get_user_by_id
def get_user_by_id(id) resp = request('getUserByID', userID: id)['user'] resp['user_id'].nil? ? nil : User.new(self, resp) end
ruby
def get_user_by_id(id) resp = request('getUserByID', userID: id)['user'] resp['user_id'].nil? ? nil : User.new(self, resp) end
[ "def", "get_user_by_id", "(", "id", ")", "resp", "=", "request", "(", "'getUserByID'", ",", "userID", ":", "id", ")", "[", "'user'", "]", "resp", "[", "'user_id'", "]", ".", "nil?", "?", "nil", ":", "User", ".", "new", "(", "self", ",", "resp", ")", "end" ]
Find user by ID
[ "Find", "user", "by", "ID" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/client.rb#L26-L29
train
sosedoff/grooveshark
lib/grooveshark/client.rb
Grooveshark.Client.get_user_by_username
def get_user_by_username(name) resp = request('getUserByUsername', username: name)['user'] resp['user_id'].nil? ? nil : User.new(self, resp) end
ruby
def get_user_by_username(name) resp = request('getUserByUsername', username: name)['user'] resp['user_id'].nil? ? nil : User.new(self, resp) end
[ "def", "get_user_by_username", "(", "name", ")", "resp", "=", "request", "(", "'getUserByUsername'", ",", "username", ":", "name", ")", "[", "'user'", "]", "resp", "[", "'user_id'", "]", ".", "nil?", "?", "nil", ":", "User", ".", "new", "(", "self", ",", "resp", ")", "end" ]
Find user by username
[ "Find", "user", "by", "username" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/client.rb#L32-L35
train
sosedoff/grooveshark
lib/grooveshark/client.rb
Grooveshark.Client.popular_songs
def popular_songs(type = 'daily') fail ArgumentError, 'Invalid type' unless %w(daily monthly).include?(type) request('popularGetSongs', type: type)['songs'].map { |s| Song.new(s) } end
ruby
def popular_songs(type = 'daily') fail ArgumentError, 'Invalid type' unless %w(daily monthly).include?(type) request('popularGetSongs', type: type)['songs'].map { |s| Song.new(s) } end
[ "def", "popular_songs", "(", "type", "=", "'daily'", ")", "fail", "ArgumentError", ",", "'Invalid type'", "unless", "%w(", "daily", "monthly", ")", ".", "include?", "(", "type", ")", "request", "(", "'popularGetSongs'", ",", "type", ":", "type", ")", "[", "'songs'", "]", ".", "map", "{", "|", "s", "|", "Song", ".", "new", "(", "s", ")", "}", "end" ]
Get popular songs type => daily, monthly
[ "Get", "popular", "songs", "type", "=", ">", "daily", "monthly" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/client.rb#L47-L50
train
sosedoff/grooveshark
lib/grooveshark/client.rb
Grooveshark.Client.top_broadcasts
def top_broadcasts(count = 10) top_broadcasts = [] request('getTopBroadcastsCombined').each do |key, _val| broadcast_id = key.split(':')[1] top_broadcasts.push(Broadcast.new(self, broadcast_id)) count -= 1 break if count == 0 end top_broadcasts end
ruby
def top_broadcasts(count = 10) top_broadcasts = [] request('getTopBroadcastsCombined').each do |key, _val| broadcast_id = key.split(':')[1] top_broadcasts.push(Broadcast.new(self, broadcast_id)) count -= 1 break if count == 0 end top_broadcasts end
[ "def", "top_broadcasts", "(", "count", "=", "10", ")", "top_broadcasts", "=", "[", "]", "request", "(", "'getTopBroadcastsCombined'", ")", ".", "each", "do", "|", "key", ",", "_val", "|", "broadcast_id", "=", "key", ".", "split", "(", "':'", ")", "[", "1", "]", "top_broadcasts", ".", "push", "(", "Broadcast", ".", "new", "(", "self", ",", "broadcast_id", ")", ")", "count", "-=", "1", "break", "if", "count", "==", "0", "end", "top_broadcasts", "end" ]
Get top broadcasts count => specifies how many broadcasts to get
[ "Get", "top", "broadcasts", "count", "=", ">", "specifies", "how", "many", "broadcasts", "to", "get" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/client.rb#L54-L64
train
sosedoff/grooveshark
lib/grooveshark/client.rb
Grooveshark.Client.search
def search(type, query) results = [] search = request('getResultsFromSearch', type: type, query: query) results = search['result'].map do |data| next Song.new data if type == 'Songs' next Playlist.new(self, data) if type == 'Playlists' data end if search.key?('result') results end
ruby
def search(type, query) results = [] search = request('getResultsFromSearch', type: type, query: query) results = search['result'].map do |data| next Song.new data if type == 'Songs' next Playlist.new(self, data) if type == 'Playlists' data end if search.key?('result') results end
[ "def", "search", "(", "type", ",", "query", ")", "results", "=", "[", "]", "search", "=", "request", "(", "'getResultsFromSearch'", ",", "type", ":", "type", ",", "query", ":", "query", ")", "results", "=", "search", "[", "'result'", "]", ".", "map", "do", "|", "data", "|", "next", "Song", ".", "new", "data", "if", "type", "==", "'Songs'", "next", "Playlist", ".", "new", "(", "self", ",", "data", ")", "if", "type", "==", "'Playlists'", "data", "end", "if", "search", ".", "key?", "(", "'result'", ")", "results", "end" ]
Perform search request for query
[ "Perform", "search", "request", "for", "query" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/client.rb#L67-L76
train
sosedoff/grooveshark
lib/grooveshark/client.rb
Grooveshark.Client.get_stream_auth_by_songid
def get_stream_auth_by_songid(song_id) result = request('getStreamKeyFromSongIDEx', 'type' => 0, 'prefetch' => false, 'songID' => song_id, 'country' => @country, 'mobile' => false) if result == [] fail GeneralError, 'No data for this song. ' \ 'Maybe Grooveshark banned your IP.' end result end
ruby
def get_stream_auth_by_songid(song_id) result = request('getStreamKeyFromSongIDEx', 'type' => 0, 'prefetch' => false, 'songID' => song_id, 'country' => @country, 'mobile' => false) if result == [] fail GeneralError, 'No data for this song. ' \ 'Maybe Grooveshark banned your IP.' end result end
[ "def", "get_stream_auth_by_songid", "(", "song_id", ")", "result", "=", "request", "(", "'getStreamKeyFromSongIDEx'", ",", "'type'", "=>", "0", ",", "'prefetch'", "=>", "false", ",", "'songID'", "=>", "song_id", ",", "'country'", "=>", "@country", ",", "'mobile'", "=>", "false", ")", "if", "result", "==", "[", "]", "fail", "GeneralError", ",", "'No data for this song. '", "'Maybe Grooveshark banned your IP.'", "end", "result", "end" ]
Get stream authentication by song ID
[ "Get", "stream", "authentication", "by", "song", "ID" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/client.rb#L89-L101
train
sosedoff/grooveshark
lib/grooveshark/client.rb
Grooveshark.Client.request
def request(method, params = {}, secure = false) refresh_token if @comm_token url = "#{secure ? 'https' : 'http'}://grooveshark.com/more.php?#{method}" begin data = RestClient.post(url, body(method, params).to_json, 'Content-Type' => 'application/json') rescue StandardError => ex raise GeneralError, ex.message end data = JSON.parse(data) data = data.normalize if data.is_a?(Hash) if data.key?('fault') fail ApiError, data['fault'] else data['result'] end end
ruby
def request(method, params = {}, secure = false) refresh_token if @comm_token url = "#{secure ? 'https' : 'http'}://grooveshark.com/more.php?#{method}" begin data = RestClient.post(url, body(method, params).to_json, 'Content-Type' => 'application/json') rescue StandardError => ex raise GeneralError, ex.message end data = JSON.parse(data) data = data.normalize if data.is_a?(Hash) if data.key?('fault') fail ApiError, data['fault'] else data['result'] end end
[ "def", "request", "(", "method", ",", "params", "=", "{", "}", ",", "secure", "=", "false", ")", "refresh_token", "if", "@comm_token", "url", "=", "\"#{secure ? 'https' : 'http'}://grooveshark.com/more.php?#{method}\"", "begin", "data", "=", "RestClient", ".", "post", "(", "url", ",", "body", "(", "method", ",", "params", ")", ".", "to_json", ",", "'Content-Type'", "=>", "'application/json'", ")", "rescue", "StandardError", "=>", "ex", "raise", "GeneralError", ",", "ex", ".", "message", "end", "data", "=", "JSON", ".", "parse", "(", "data", ")", "data", "=", "data", ".", "normalize", "if", "data", ".", "is_a?", "(", "Hash", ")", "if", "data", ".", "key?", "(", "'fault'", ")", "fail", "ApiError", ",", "data", "[", "'fault'", "]", "else", "data", "[", "'result'", "]", "end", "end" ]
Perform API request
[ "Perform", "API", "request" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/client.rb#L171-L191
train
floriank/oeffi
lib/oeffi.rb
Oeffi.Configuration.provider=
def provider=(sym) klass = "#{sym.to_s.capitalize}Provider" begin java_import "de.schildbach.pte.#{klass}" @provider = Oeffi::const_get(klass).new rescue Exception => e raise "Unknown Provider name: #{klass}" end end
ruby
def provider=(sym) klass = "#{sym.to_s.capitalize}Provider" begin java_import "de.schildbach.pte.#{klass}" @provider = Oeffi::const_get(klass).new rescue Exception => e raise "Unknown Provider name: #{klass}" end end
[ "def", "provider", "=", "(", "sym", ")", "klass", "=", "\"#{sym.to_s.capitalize}Provider\"", "begin", "java_import", "\"de.schildbach.pte.#{klass}\"", "@provider", "=", "Oeffi", "::", "const_get", "(", "klass", ")", ".", "new", "rescue", "Exception", "=>", "e", "raise", "\"Unknown Provider name: #{klass}\"", "end", "end" ]
Configure a provider for the oeffi module Possible providers: :atc, :avv, :bahn, :bayern, :bsag, :bsvag, :bvb, :bvg, :ding, :dsb, :dub, :eireann, :gvh, :invg, :ivb, :kvv, :linz, :location, :lu, :maribor, :met, :mvg, :mvv, :naldo, :nasa, :nri, :ns, :nvbw, :nvv, :oebb, :pl, :rt, :sad, :sbb, :se, :septa, :sf, :sh, :sncb, :stockholm, :stv, :svv, :sydney, :tfi, :tfl, :tlem, :tlsw, :tlwm, :vagfr, :vbb, :vbl, :vbn, :vgn, :vgs, :vmobil, :vms, :vmv, :vor, :vrn, :vrr, :vrt, :vvm, :vvo, :vvs, :vvt, :vvv, :wien, :zvv
[ "Configure", "a", "provider", "for", "the", "oeffi", "module" ]
d129eb8be20ef5a7d4ebe24fc746b62b67de259b
https://github.com/floriank/oeffi/blob/d129eb8be20ef5a7d4ebe24fc746b62b67de259b/lib/oeffi.rb#L42-L50
train
4rlm/crm_formatter
lib/crm_formatter/address.rb
CrmFormatter.Address.check_addr_status
def check_addr_status(hsh) full_addr = hsh[:full_addr] full_addr_f = hsh[:full_addr_f] status = nil if full_addr && full_addr_f status = full_addr != full_addr_f ? 'formatted' : 'unchanged' end hsh[:address_status] = status hsh end
ruby
def check_addr_status(hsh) full_addr = hsh[:full_addr] full_addr_f = hsh[:full_addr_f] status = nil if full_addr && full_addr_f status = full_addr != full_addr_f ? 'formatted' : 'unchanged' end hsh[:address_status] = status hsh end
[ "def", "check_addr_status", "(", "hsh", ")", "full_addr", "=", "hsh", "[", ":full_addr", "]", "full_addr_f", "=", "hsh", "[", ":full_addr_f", "]", "status", "=", "nil", "if", "full_addr", "&&", "full_addr_f", "status", "=", "full_addr", "!=", "full_addr_f", "?", "'formatted'", ":", "'unchanged'", "end", "hsh", "[", ":address_status", "]", "=", "status", "hsh", "end" ]
COMPARE ORIGINAL AND FORMATTED ADR
[ "COMPARE", "ORIGINAL", "AND", "FORMATTED", "ADR" ]
5060d27552a3871257cd08612c8e93b7b2b6a350
https://github.com/4rlm/crm_formatter/blob/5060d27552a3871257cd08612c8e93b7b2b6a350/lib/crm_formatter/address.rb#L20-L31
train
4rlm/crm_formatter
lib/crm_formatter/address.rb
CrmFormatter.Address.make_full_address_original
def make_full_address_original(hsh) full_adr = [hsh[:street], hsh[:city], hsh[:state], hsh[:zip]].compact.join(', ') full_adr end
ruby
def make_full_address_original(hsh) full_adr = [hsh[:street], hsh[:city], hsh[:state], hsh[:zip]].compact.join(', ') full_adr end
[ "def", "make_full_address_original", "(", "hsh", ")", "full_adr", "=", "[", "hsh", "[", ":street", "]", ",", "hsh", "[", ":city", "]", ",", "hsh", "[", ":state", "]", ",", "hsh", "[", ":zip", "]", "]", ".", "compact", ".", "join", "(", "', '", ")", "full_adr", "end" ]
FORMAT FULL ADDRESS
[ "FORMAT", "FULL", "ADDRESS" ]
5060d27552a3871257cd08612c8e93b7b2b6a350
https://github.com/4rlm/crm_formatter/blob/5060d27552a3871257cd08612c8e93b7b2b6a350/lib/crm_formatter/address.rb#L34-L40
train
neopoly/redmine-more_view_hooks
lib/more_view_hooks/hook_collection.rb
MoreViewHooks.HookCollection.add
def add(name, options) fail ArgumentError, "A view hook '#{name}' already exists" if @hooks[name] context = options.delete(:context) hook = @hooks[name] = Hook.new(name, context, options) hook.apply! if @applied end
ruby
def add(name, options) fail ArgumentError, "A view hook '#{name}' already exists" if @hooks[name] context = options.delete(:context) hook = @hooks[name] = Hook.new(name, context, options) hook.apply! if @applied end
[ "def", "add", "(", "name", ",", "options", ")", "fail", "ArgumentError", ",", "\"A view hook '#{name}' already exists\"", "if", "@hooks", "[", "name", "]", "context", "=", "options", ".", "delete", "(", ":context", ")", "hook", "=", "@hooks", "[", "name", "]", "=", "Hook", ".", "new", "(", "name", ",", "context", ",", "options", ")", "hook", ".", "apply!", "if", "@applied", "end" ]
Registers a new view hook @param name [String] @param options [Hash] for Defaced
[ "Registers", "a", "new", "view", "hook" ]
816fff22ede91289cc47b4b80ac2f38873b6c839
https://github.com/neopoly/redmine-more_view_hooks/blob/816fff22ede91289cc47b4b80ac2f38873b6c839/lib/more_view_hooks/hook_collection.rb#L18-L23
train
talis/blueprint_rb
lib/blueprint_ruby_client/api/hierarchy_api.rb
BlueprintClient.HierarchyApi.add_node
def add_node(namespace_inc_global, body, opts = {}) data, _status_code, _headers = add_node_with_http_info(namespace_inc_global, body, opts) return data end
ruby
def add_node(namespace_inc_global, body, opts = {}) data, _status_code, _headers = add_node_with_http_info(namespace_inc_global, body, opts) return data end
[ "def", "add_node", "(", "namespace_inc_global", ",", "body", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "add_node_with_http_info", "(", "namespace_inc_global", ",", "body", ",", "opts", ")", "return", "data", "end" ]
Add a node @param namespace_inc_global identifier namespacing the blueprint. `global` is a special namespace which references data from all blueprints in the call. @param body node @param [Hash] opts the optional parameters @return [NodeBody]
[ "Add", "a", "node" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/hierarchy_api.rb#L29-L32
train
talis/blueprint_rb
lib/blueprint_ruby_client/api/hierarchy_api.rb
BlueprintClient.HierarchyApi.delete_node
def delete_node(namespace, id, type, opts = {}) delete_node_with_http_info(namespace, id, type, opts) return nil end
ruby
def delete_node(namespace, id, type, opts = {}) delete_node_with_http_info(namespace, id, type, opts) return nil end
[ "def", "delete_node", "(", "namespace", ",", "id", ",", "type", ",", "opts", "=", "{", "}", ")", "delete_node_with_http_info", "(", "namespace", ",", "id", ",", "type", ",", "opts", ")", "return", "nil", "end" ]
Delete a node @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param id id identifying a domain model @param type subtype of Node, e.g. &#39;modules&#39;, &#39;departments&#39;, etc. @param [Hash] opts the optional parameters @return [nil]
[ "Delete", "a", "node" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/hierarchy_api.rb#L169-L172
train
talis/blueprint_rb
lib/blueprint_ruby_client/api/hierarchy_api.rb
BlueprintClient.HierarchyApi.get_node
def get_node(namespace, id, type, opts = {}) data, _status_code, _headers = get_node_with_http_info(namespace, id, type, opts) return data end
ruby
def get_node(namespace, id, type, opts = {}) data, _status_code, _headers = get_node_with_http_info(namespace, id, type, opts) return data end
[ "def", "get_node", "(", "namespace", ",", "id", ",", "type", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_node_with_http_info", "(", "namespace", ",", "id", ",", "type", ",", "opts", ")", "return", "data", "end" ]
Get details of a given node @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param id id identifying a domain model @param type subtype of Node, e.g. &#39;modules&#39;, &#39;departments&#39;, etc. @param [Hash] opts the optional parameters @option opts [Array<String>] :include comma separated list of elements to hydrate. Can include children, parents, nodes, and/or assets @return [NodeBody]
[ "Get", "details", "of", "a", "given", "node" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/hierarchy_api.rb#L691-L694
train
talis/blueprint_rb
lib/blueprint_ruby_client/api/hierarchy_api.rb
BlueprintClient.HierarchyApi.replace_node
def replace_node(namespace, id, body, type, opts = {}) data, _status_code, _headers = replace_node_with_http_info(namespace, id, body, type, opts) return data end
ruby
def replace_node(namespace, id, body, type, opts = {}) data, _status_code, _headers = replace_node_with_http_info(namespace, id, body, type, opts) return data end
[ "def", "replace_node", "(", "namespace", ",", "id", ",", "body", ",", "type", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "replace_node_with_http_info", "(", "namespace", ",", "id", ",", "body", ",", "type", ",", "opts", ")", "return", "data", "end" ]
Replaces the node with the data sent in the body @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param id id identifying a domain model @param body node @param type subtype of Node, e.g. &#39;modules&#39;, &#39;departments&#39;, etc. @param [Hash] opts the optional parameters @return [NodeBody]
[ "Replaces", "the", "node", "with", "the", "data", "sent", "in", "the", "body" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/hierarchy_api.rb#L888-L891
train
talis/blueprint_rb
lib/blueprint_ruby_client/api/hierarchy_api.rb
BlueprintClient.HierarchyApi.update_node
def update_node(namespace, id, body, type, opts = {}) data, _status_code, _headers = update_node_with_http_info(namespace, id, body, type, opts) return data end
ruby
def update_node(namespace, id, body, type, opts = {}) data, _status_code, _headers = update_node_with_http_info(namespace, id, body, type, opts) return data end
[ "def", "update_node", "(", "namespace", ",", "id", ",", "body", ",", "type", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "update_node_with_http_info", "(", "namespace", ",", "id", ",", "body", ",", "type", ",", "opts", ")", "return", "data", "end" ]
Perform a partial update of a node @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param id id identifying a domain model @param body node @param type subtype of Node, e.g. &#39;modules&#39;, &#39;departments&#39;, etc. @param [Hash] opts the optional parameters @return [NodeBody]
[ "Perform", "a", "partial", "update", "of", "a", "node" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/hierarchy_api.rb#L1219-L1222
train
berkshelf/berkshelf-hg
lib/berkshelf/locations/hg.rb
Berkshelf.HgLocation.install
def install if cached? # Update and checkout the correct ref Dir.chdir(cache_path) do hg %|pull| end else # Ensure the cache directory is present before doing anything FileUtils.mkdir_p(cache_path) Dir.chdir(cache_path) do hg %|clone #{uri} .| end end Dir.chdir(cache_path) do hg %|update --clean --rev #{revision || ref}| @revision ||= hg %|id -i| end # Gab the path where we should copy from (since it might be relative to # the root). copy_path = rel ? cache_path.join(rel) : cache_path begin # Validate the thing we are copying is a Chef cookbook validate_cached!(copy_path) # Remove the current cookbook at this location (this is required or else # FileUtils will copy into a subdirectory in the next step) FileUtils.rm_rf(install_path) # Create the containing parent directory FileUtils.mkdir_p(install_path.parent) # Copy whatever is in the current cache over to the store FileUtils.cp_r(copy_path, install_path) ensure # Remove the .hg directory to save storage space # TODO this can have huge performance implications, # make it a config option? if (hg_path = install_path.join('.hg')).exist? FileUtils.rm_r(hg_path) end FileUtils.rm_rf (copy_path) end end
ruby
def install if cached? # Update and checkout the correct ref Dir.chdir(cache_path) do hg %|pull| end else # Ensure the cache directory is present before doing anything FileUtils.mkdir_p(cache_path) Dir.chdir(cache_path) do hg %|clone #{uri} .| end end Dir.chdir(cache_path) do hg %|update --clean --rev #{revision || ref}| @revision ||= hg %|id -i| end # Gab the path where we should copy from (since it might be relative to # the root). copy_path = rel ? cache_path.join(rel) : cache_path begin # Validate the thing we are copying is a Chef cookbook validate_cached!(copy_path) # Remove the current cookbook at this location (this is required or else # FileUtils will copy into a subdirectory in the next step) FileUtils.rm_rf(install_path) # Create the containing parent directory FileUtils.mkdir_p(install_path.parent) # Copy whatever is in the current cache over to the store FileUtils.cp_r(copy_path, install_path) ensure # Remove the .hg directory to save storage space # TODO this can have huge performance implications, # make it a config option? if (hg_path = install_path.join('.hg')).exist? FileUtils.rm_r(hg_path) end FileUtils.rm_rf (copy_path) end end
[ "def", "install", "if", "cached?", "Dir", ".", "chdir", "(", "cache_path", ")", "do", "hg", "%|pull|", "end", "else", "FileUtils", ".", "mkdir_p", "(", "cache_path", ")", "Dir", ".", "chdir", "(", "cache_path", ")", "do", "hg", "%|clone #{uri} .|", "end", "end", "Dir", ".", "chdir", "(", "cache_path", ")", "do", "hg", "%|update --clean --rev #{revision || ref}|", "@revision", "||=", "hg", "%|id -i|", "end", "copy_path", "=", "rel", "?", "cache_path", ".", "join", "(", "rel", ")", ":", "cache_path", "begin", "validate_cached!", "(", "copy_path", ")", "FileUtils", ".", "rm_rf", "(", "install_path", ")", "FileUtils", ".", "mkdir_p", "(", "install_path", ".", "parent", ")", "FileUtils", ".", "cp_r", "(", "copy_path", ",", "install_path", ")", "ensure", "if", "(", "hg_path", "=", "install_path", ".", "join", "(", "'.hg'", ")", ")", ".", "exist?", "FileUtils", ".", "rm_r", "(", "hg_path", ")", "end", "FileUtils", ".", "rm_rf", "(", "copy_path", ")", "end", "end" ]
Download the cookbook from the remote hg repository @return void
[ "Download", "the", "cookbook", "from", "the", "remote", "hg", "repository" ]
b60a022d34051533f20903fe8cbe102ac3f8b6b9
https://github.com/berkshelf/berkshelf-hg/blob/b60a022d34051533f20903fe8cbe102ac3f8b6b9/lib/berkshelf/locations/hg.rb#L58-L107
train
berkshelf/berkshelf-hg
lib/berkshelf/locations/hg.rb
Berkshelf.HgLocation.hg
def hg(command, error = true) unless Berkshelf.which('hg') || Berkshelf.which('hg.exe') raise HgNotInstalled.new end Berkshelf.log.debug("Running:hg #{command}") response = shell_out(%|hg #{command}|) Berkshelf.log.debug("response:hg #{response.stdout}") if response.error? raise HgCommandError.new(command, response, cache_path) end response.stdout.strip end
ruby
def hg(command, error = true) unless Berkshelf.which('hg') || Berkshelf.which('hg.exe') raise HgNotInstalled.new end Berkshelf.log.debug("Running:hg #{command}") response = shell_out(%|hg #{command}|) Berkshelf.log.debug("response:hg #{response.stdout}") if response.error? raise HgCommandError.new(command, response, cache_path) end response.stdout.strip end
[ "def", "hg", "(", "command", ",", "error", "=", "true", ")", "unless", "Berkshelf", ".", "which", "(", "'hg'", ")", "||", "Berkshelf", ".", "which", "(", "'hg.exe'", ")", "raise", "HgNotInstalled", ".", "new", "end", "Berkshelf", ".", "log", ".", "debug", "(", "\"Running:hg #{command}\"", ")", "response", "=", "shell_out", "(", "%|hg #{command}|", ")", "Berkshelf", ".", "log", ".", "debug", "(", "\"response:hg #{response.stdout}\"", ")", "if", "response", ".", "error?", "raise", "HgCommandError", ".", "new", "(", "command", ",", "response", ",", "cache_path", ")", "end", "response", ".", "stdout", ".", "strip", "end" ]
Perform a mercurial command. @param [String] command the command to run @param [Boolean] error whether to raise error if the command fails @raise [String] the +$stdout+ from the command
[ "Perform", "a", "mercurial", "command", "." ]
b60a022d34051533f20903fe8cbe102ac3f8b6b9
https://github.com/berkshelf/berkshelf-hg/blob/b60a022d34051533f20903fe8cbe102ac3f8b6b9/lib/berkshelf/locations/hg.rb#L159-L173
train
berkshelf/berkshelf-hg
lib/berkshelf/locations/hg.rb
Berkshelf.HgLocation.cache_path
def cache_path Pathname.new(Berkshelf.berkshelf_path) .join('.cache', 'hg', Digest::SHA1.hexdigest(uri)) end
ruby
def cache_path Pathname.new(Berkshelf.berkshelf_path) .join('.cache', 'hg', Digest::SHA1.hexdigest(uri)) end
[ "def", "cache_path", "Pathname", ".", "new", "(", "Berkshelf", ".", "berkshelf_path", ")", ".", "join", "(", "'.cache'", ",", "'hg'", ",", "Digest", "::", "SHA1", ".", "hexdigest", "(", "uri", ")", ")", "end" ]
The path where this hg repository is cached. @return [Pathname]
[ "The", "path", "where", "this", "hg", "repository", "is", "cached", "." ]
b60a022d34051533f20903fe8cbe102ac3f8b6b9
https://github.com/berkshelf/berkshelf-hg/blob/b60a022d34051533f20903fe8cbe102ac3f8b6b9/lib/berkshelf/locations/hg.rb#L194-L197
train
AgilTec/cadenero
app/controllers/cadenero/v1/account/sessions_controller.rb
Cadenero::V1.Account::SessionsController.create
def create if env['warden'].authenticate(:password, :scope => :user) #return the user JSON on success render json: current_user, status: :created else #return error mesage in a JSON on error render json: {errors: {user:["Invalid email or password"]}}, status: :unprocessable_entity end end
ruby
def create if env['warden'].authenticate(:password, :scope => :user) #return the user JSON on success render json: current_user, status: :created else #return error mesage in a JSON on error render json: {errors: {user:["Invalid email or password"]}}, status: :unprocessable_entity end end
[ "def", "create", "if", "env", "[", "'warden'", "]", ".", "authenticate", "(", ":password", ",", ":scope", "=>", ":user", ")", "render", "json", ":", "current_user", ",", "status", ":", ":created", "else", "render", "json", ":", "{", "errors", ":", "{", "user", ":", "[", "\"Invalid email or password\"", "]", "}", "}", ",", "status", ":", ":unprocessable_entity", "end", "end" ]
create the session for the user using the password strategy and returning the user JSON
[ "create", "the", "session", "for", "the", "user", "using", "the", "password", "strategy", "and", "returning", "the", "user", "JSON" ]
62449f160c48cce51cd8e97e5acad19f4a62be6c
https://github.com/AgilTec/cadenero/blob/62449f160c48cce51cd8e97e5acad19f4a62be6c/app/controllers/cadenero/v1/account/sessions_controller.rb#L7-L15
train
AgilTec/cadenero
app/controllers/cadenero/v1/account/sessions_controller.rb
Cadenero::V1.Account::SessionsController.delete
def delete user = Cadenero::User.find_by_id(params[:id]) if user_signed_in? env['warden'].logout(:user) render json: {message: "Successful logout"}, status: :ok else render json: {message: "Unsuccessful logout user with id"}, status: :forbidden end end
ruby
def delete user = Cadenero::User.find_by_id(params[:id]) if user_signed_in? env['warden'].logout(:user) render json: {message: "Successful logout"}, status: :ok else render json: {message: "Unsuccessful logout user with id"}, status: :forbidden end end
[ "def", "delete", "user", "=", "Cadenero", "::", "User", ".", "find_by_id", "(", "params", "[", ":id", "]", ")", "if", "user_signed_in?", "env", "[", "'warden'", "]", ".", "logout", "(", ":user", ")", "render", "json", ":", "{", "message", ":", "\"Successful logout\"", "}", ",", "status", ":", ":ok", "else", "render", "json", ":", "{", "message", ":", "\"Unsuccessful logout user with id\"", "}", ",", "status", ":", ":forbidden", "end", "end" ]
destroy the session for the user using params id
[ "destroy", "the", "session", "for", "the", "user", "using", "params", "id" ]
62449f160c48cce51cd8e97e5acad19f4a62be6c
https://github.com/AgilTec/cadenero/blob/62449f160c48cce51cd8e97e5acad19f4a62be6c/app/controllers/cadenero/v1/account/sessions_controller.rb#L18-L26
train
bunto/bunto-sitemap
lib/bunto/bunto-sitemap.rb
Bunto.BuntoSitemap.file_exists?
def file_exists?(file_path) if @site.respond_to?(:in_source_dir) File.exist? @site.in_source_dir(file_path) else File.exist? Bunto.sanitized_path(@site.source, file_path) end end
ruby
def file_exists?(file_path) if @site.respond_to?(:in_source_dir) File.exist? @site.in_source_dir(file_path) else File.exist? Bunto.sanitized_path(@site.source, file_path) end end
[ "def", "file_exists?", "(", "file_path", ")", "if", "@site", ".", "respond_to?", "(", ":in_source_dir", ")", "File", ".", "exist?", "@site", ".", "in_source_dir", "(", "file_path", ")", "else", "File", ".", "exist?", "Bunto", ".", "sanitized_path", "(", "@site", ".", "source", ",", "file_path", ")", "end", "end" ]
Checks if a file already exists in the site source
[ "Checks", "if", "a", "file", "already", "exists", "in", "the", "site", "source" ]
0ffa2fb5a1a8fe44815865e4e976d12957565fef
https://github.com/bunto/bunto-sitemap/blob/0ffa2fb5a1a8fe44815865e4e976d12957565fef/lib/bunto/bunto-sitemap.rb#L62-L68
train
riddler/riddler_admin
app/controllers/riddler_admin/steps_controller.rb
RiddlerAdmin.StepsController.internal_preview
def internal_preview @preview_context = ::RiddlerAdmin::PreviewContext.find_by_id params["pctx_id"] if @preview_context.nil? render(status: 400, json: {message: "Invalid pctx_id"}) and return end @use_case = ::Riddler::UseCases::AdminPreviewStep.new @step.definition_hash, preview_context_data: @preview_context.data @preview_hash = @use_case.process end
ruby
def internal_preview @preview_context = ::RiddlerAdmin::PreviewContext.find_by_id params["pctx_id"] if @preview_context.nil? render(status: 400, json: {message: "Invalid pctx_id"}) and return end @use_case = ::Riddler::UseCases::AdminPreviewStep.new @step.definition_hash, preview_context_data: @preview_context.data @preview_hash = @use_case.process end
[ "def", "internal_preview", "@preview_context", "=", "::", "RiddlerAdmin", "::", "PreviewContext", ".", "find_by_id", "params", "[", "\"pctx_id\"", "]", "if", "@preview_context", ".", "nil?", "render", "(", "status", ":", "400", ",", "json", ":", "{", "message", ":", "\"Invalid pctx_id\"", "}", ")", "and", "return", "end", "@use_case", "=", "::", "Riddler", "::", "UseCases", "::", "AdminPreviewStep", ".", "new", "@step", ".", "definition_hash", ",", "preview_context_data", ":", "@preview_context", ".", "data", "@preview_hash", "=", "@use_case", ".", "process", "end" ]
Should always comes from the admin tool
[ "Should", "always", "comes", "from", "the", "admin", "tool" ]
33eda9721e9df44ff0a0b2f2af4b755a2f49048d
https://github.com/riddler/riddler_admin/blob/33eda9721e9df44ff0a0b2f2af4b755a2f49048d/app/controllers/riddler_admin/steps_controller.rb#L35-L45
train
wurmlab/genevalidatorapp
lib/genevalidatorapp/config.rb
GeneValidatorApp.Config.write_config_file
def write_config_file return unless config_file File.open(config_file, 'w') do |f| f.puts(data.delete_if { |_, v| v.nil? }.to_yaml) end end
ruby
def write_config_file return unless config_file File.open(config_file, 'w') do |f| f.puts(data.delete_if { |_, v| v.nil? }.to_yaml) end end
[ "def", "write_config_file", "return", "unless", "config_file", "File", ".", "open", "(", "config_file", ",", "'w'", ")", "do", "|", "f", "|", "f", ".", "puts", "(", "data", ".", "delete_if", "{", "|", "_", ",", "v", "|", "v", ".", "nil?", "}", ".", "to_yaml", ")", "end", "end" ]
Write config data to config file.
[ "Write", "config", "data", "to", "config", "file", "." ]
78c3415a1f7c417b36ebecda753442b6ba6a2417
https://github.com/wurmlab/genevalidatorapp/blob/78c3415a1f7c417b36ebecda753442b6ba6a2417/lib/genevalidatorapp/config.rb#L37-L43
train
wurmlab/genevalidatorapp
lib/genevalidatorapp/config.rb
GeneValidatorApp.Config.symbolise
def symbolise(data) return {} unless data # Symbolize keys. Hash[data.map { |k, v| [k.to_sym, v] }] end
ruby
def symbolise(data) return {} unless data # Symbolize keys. Hash[data.map { |k, v| [k.to_sym, v] }] end
[ "def", "symbolise", "(", "data", ")", "return", "{", "}", "unless", "data", "Hash", "[", "data", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ".", "to_sym", ",", "v", "]", "}", "]", "end" ]
Symbolizes keys. Changes `database` key to `database_dir`.
[ "Symbolizes", "keys", ".", "Changes", "database", "key", "to", "database_dir", "." ]
78c3415a1f7c417b36ebecda753442b6ba6a2417
https://github.com/wurmlab/genevalidatorapp/blob/78c3415a1f7c417b36ebecda753442b6ba6a2417/lib/genevalidatorapp/config.rb#L48-L52
train
wurmlab/genevalidatorapp
lib/genevalidatorapp/config.rb
GeneValidatorApp.Config.defaults
def defaults { num_threads: 1, mafft_threads: 1, port: 5678, ssl: false, host: '0.0.0.0', serve_public_dir: File.join(Dir.home, '.genevalidatorapp/'), max_characters: 'undefined' } end
ruby
def defaults { num_threads: 1, mafft_threads: 1, port: 5678, ssl: false, host: '0.0.0.0', serve_public_dir: File.join(Dir.home, '.genevalidatorapp/'), max_characters: 'undefined' } end
[ "def", "defaults", "{", "num_threads", ":", "1", ",", "mafft_threads", ":", "1", ",", "port", ":", "5678", ",", "ssl", ":", "false", ",", "host", ":", "'0.0.0.0'", ",", "serve_public_dir", ":", "File", ".", "join", "(", "Dir", ".", "home", ",", "'.genevalidatorapp/'", ")", ",", "max_characters", ":", "'undefined'", "}", "end" ]
Default configuration data.
[ "Default", "configuration", "data", "." ]
78c3415a1f7c417b36ebecda753442b6ba6a2417
https://github.com/wurmlab/genevalidatorapp/blob/78c3415a1f7c417b36ebecda753442b6ba6a2417/lib/genevalidatorapp/config.rb#L73-L83
train
orzFly/ruby-ripple-rest
lib/ripple-rest/helpers.rb
RippleRest.Account.trustlines
def trustlines data = RippleRest .get("v1/accounts/#{@address}/trustlines")["trustlines"] .map(&Trustline.method(:new)) obj = Trustlines.new data obj.account = self obj end
ruby
def trustlines data = RippleRest .get("v1/accounts/#{@address}/trustlines")["trustlines"] .map(&Trustline.method(:new)) obj = Trustlines.new data obj.account = self obj end
[ "def", "trustlines", "data", "=", "RippleRest", ".", "get", "(", "\"v1/accounts/#{@address}/trustlines\"", ")", "[", "\"trustlines\"", "]", ".", "map", "(", "&", "Trustline", ".", "method", "(", ":new", ")", ")", "obj", "=", "Trustlines", ".", "new", "data", "obj", ".", "account", "=", "self", "obj", "end" ]
Returns a Trustlines object for this account. @return [Trustlines] @raise [RippleRestError] if RippleRest server returns an error @raise [ProtocolError] if protocol is wrong or network is down
[ "Returns", "a", "Trustlines", "object", "for", "this", "account", "." ]
86c9a49c07fb2068d0bbe0edb2490b65efb6972d
https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/helpers.rb#L31-L38
train
orzFly/ruby-ripple-rest
lib/ripple-rest/helpers.rb
RippleRest.Account.settings
def settings data = RippleRest.get("v1/accounts/#{@address}/settings")["settings"] obj = AccountSettings.new data obj.account = self obj end
ruby
def settings data = RippleRest.get("v1/accounts/#{@address}/settings")["settings"] obj = AccountSettings.new data obj.account = self obj end
[ "def", "settings", "data", "=", "RippleRest", ".", "get", "(", "\"v1/accounts/#{@address}/settings\"", ")", "[", "\"settings\"", "]", "obj", "=", "AccountSettings", ".", "new", "data", "obj", ".", "account", "=", "self", "obj", "end" ]
Returns a AccountSettings object for this account. @return [AccountSettings] @raise [RippleRestError] if RippleRest server returns an error @raise [ProtocolError] if protocol is wrong or network is down
[ "Returns", "a", "AccountSettings", "object", "for", "this", "account", "." ]
86c9a49c07fb2068d0bbe0edb2490b65efb6972d
https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/helpers.rb#L44-L49
train
orzFly/ruby-ripple-rest
lib/ripple-rest/helpers.rb
RippleRest.Account.payments
def payments payments ||= lambda { obj = Payments.new obj.account = self obj }.call end
ruby
def payments payments ||= lambda { obj = Payments.new obj.account = self obj }.call end
[ "def", "payments", "payments", "||=", "lambda", "{", "obj", "=", "Payments", ".", "new", "obj", ".", "account", "=", "self", "obj", "}", ".", "call", "end" ]
Returns a Payments object for this account. @return [Payments]
[ "Returns", "a", "Payments", "object", "for", "this", "account", "." ]
86c9a49c07fb2068d0bbe0edb2490b65efb6972d
https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/helpers.rb#L63-L69
train
orzFly/ruby-ripple-rest
lib/ripple-rest/helpers.rb
RippleRest.Payments.find_path
def find_path destination_account, destination_amount, source_currencies = nil uri = "v1/accounts/#{account.address}/payments/paths/#{destination_account.to_s}/#{destination_amount.to_s}" if source_currencies cur = source_currencies.join(",") uri += "?source_currencies=#{cur}" end RippleRest.get(uri)["payments"].map(&Payment.method(:new)).each do |i| i.account = account end end
ruby
def find_path destination_account, destination_amount, source_currencies = nil uri = "v1/accounts/#{account.address}/payments/paths/#{destination_account.to_s}/#{destination_amount.to_s}" if source_currencies cur = source_currencies.join(",") uri += "?source_currencies=#{cur}" end RippleRest.get(uri)["payments"].map(&Payment.method(:new)).each do |i| i.account = account end end
[ "def", "find_path", "destination_account", ",", "destination_amount", ",", "source_currencies", "=", "nil", "uri", "=", "\"v1/accounts/#{account.address}/payments/paths/#{destination_account.to_s}/#{destination_amount.to_s}\"", "if", "source_currencies", "cur", "=", "source_currencies", ".", "join", "(", "\",\"", ")", "uri", "+=", "\"?source_currencies=#{cur}\"", "end", "RippleRest", ".", "get", "(", "uri", ")", "[", "\"payments\"", "]", ".", "map", "(", "&", "Payment", ".", "method", "(", ":new", ")", ")", ".", "each", "do", "|", "i", "|", "i", ".", "account", "=", "account", "end", "end" ]
Query `rippled` for possible payment "paths" through the Ripple Network to deliver the given amount to the specified `destination_account`. If the `destination_amount` issuer is not specified, paths will be returned for all of the issuers from whom the `destination_account` accepts the given currency. @param destination_account [String, Account] destination account @param destination_amount [String, Amount] destination amount @param source_currencies [Array<String>] an array of source currencies that can be used to constrain the results returned (e.g. `["XRP", "USD+r...", "BTC+r..."]`) Currencies can be denoted by their currency code (e.g. USD) or by their currency code and issuer (e.g. `USD+r...`). If no issuer is specified for a currency other than XRP, the results will be limited to the specified currencies but any issuer for that currency will do. @raise [RippleRestError] if RippleRest server returns an error @raise [ProtocolError] if protocol is wrong or network is down @return [Array<Payment>]
[ "Query", "rippled", "for", "possible", "payment", "paths", "through", "the", "Ripple", "Network", "to", "deliver", "the", "given", "amount", "to", "the", "specified", "destination_account", ".", "If", "the", "destination_amount", "issuer", "is", "not", "specified", "paths", "will", "be", "returned", "for", "all", "of", "the", "issuers", "from", "whom", "the", "destination_account", "accepts", "the", "given", "currency", "." ]
86c9a49c07fb2068d0bbe0edb2490b65efb6972d
https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/helpers.rb#L124-L135
train
orzFly/ruby-ripple-rest
lib/ripple-rest/helpers.rb
RippleRest.Payments.create
def create destination_account, destination_amount payment = Payment.new payment.account = account payment.destination_account = destination_account.to_s payment.destination_amount = Amount.from_string(destination_amount) payment end
ruby
def create destination_account, destination_amount payment = Payment.new payment.account = account payment.destination_account = destination_account.to_s payment.destination_amount = Amount.from_string(destination_amount) payment end
[ "def", "create", "destination_account", ",", "destination_amount", "payment", "=", "Payment", ".", "new", "payment", ".", "account", "=", "account", "payment", ".", "destination_account", "=", "destination_account", ".", "to_s", "payment", ".", "destination_amount", "=", "Amount", ".", "from_string", "(", "destination_amount", ")", "payment", "end" ]
Create a Payment object with some field filled. @return [Payment]
[ "Create", "a", "Payment", "object", "with", "some", "field", "filled", "." ]
86c9a49c07fb2068d0bbe0edb2490b65efb6972d
https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/helpers.rb#L139-L145
train
orzFly/ruby-ripple-rest
lib/ripple-rest/helpers.rb
RippleRest.Payments.query
def query options = {} qs = "" if options && options.size > 0 qs = "?" + options.map { |k,v| "#{k}=#{CGI::escape(v.to_s)}" }.join('&') end uri = "v1/accounts/#{account.address}/payments#{qs}" RippleRest.get(uri)["payments"].map do |i| payment = Payment.new(i["payment"]) payment.client_resource_id = i["client_resource_id"] payment end end
ruby
def query options = {} qs = "" if options && options.size > 0 qs = "?" + options.map { |k,v| "#{k}=#{CGI::escape(v.to_s)}" }.join('&') end uri = "v1/accounts/#{account.address}/payments#{qs}" RippleRest.get(uri)["payments"].map do |i| payment = Payment.new(i["payment"]) payment.client_resource_id = i["client_resource_id"] payment end end
[ "def", "query", "options", "=", "{", "}", "qs", "=", "\"\"", "if", "options", "&&", "options", ".", "size", ">", "0", "qs", "=", "\"?\"", "+", "options", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{k}=#{CGI::escape(v.to_s)}\"", "}", ".", "join", "(", "'&'", ")", "end", "uri", "=", "\"v1/accounts/#{account.address}/payments#{qs}\"", "RippleRest", ".", "get", "(", "uri", ")", "[", "\"payments\"", "]", ".", "map", "do", "|", "i", "|", "payment", "=", "Payment", ".", "new", "(", "i", "[", "\"payment\"", "]", ")", "payment", ".", "client_resource_id", "=", "i", "[", "\"client_resource_id\"", "]", "payment", "end", "end" ]
Browse historical payments in bulk. @option options [String, Account] :source_account If specified, limit the results to payments initiated by a particular account @option options [String, Account] :destination_account If specified, limit the results to payments made to a particular account @option options [Boolean] :exclude_failed if set to true, this will return only payment that were successfully validated and written into the Ripple Ledger @option options [String] :start_ledger If earliest_first is set to true this will be the index number of the earliest ledger queried, or the most recent one if earliest_first is set to false. Defaults to the first ledger the rippled has in its complete ledger. An error will be returned if this value is outside the rippled's complete ledger set @option options [String] :end_ledger If earliest_first is set to true this will be the index number of the most recent ledger queried, or the earliest one if earliest_first is set to false. Defaults to the last ledger the rippled has in its complete ledger. An error will be returned if this value is outside the rippled's complete ledger set @option options [Boolean] :earliest_first Determines the order in which the results should be displayed. Defaults to true @option options [Fixnum] :results_per_page Limits the number of resources displayed per page. Defaults to 20 @option options [Fixnum] :page The page to be displayed. If there are fewer than the results_per_page number displayed, this indicates that this is the last page @raise [RippleRestError] if RippleRest server returns an error @raise [ProtocolError] if protocol is wrong or network is down @return [Array<Payment>]
[ "Browse", "historical", "payments", "in", "bulk", "." ]
86c9a49c07fb2068d0bbe0edb2490b65efb6972d
https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/helpers.rb#L159-L172
train
aaronroyer/qunited
lib/qunited/application.rb
QUnited.Application.handle_options
def handle_options drivers = ::QUnited::Driver.constants.reject { |d| d == :Base } valid_drivers_string = "Valid drivers include: #{drivers.map { |d| d.to_s }.join(', ')}" args_empty = ARGV.empty? # This is a bit of a hack, but OptionParser removes the -- that separates the source # and test files and we need to put it back in the right place. Save the distance from # the end to do this later. double_dash_neg_index = ARGV.find_index('--') && (ARGV.find_index('--') - ARGV.size) optparse = OptionParser.new do |opts| opts.banner = <<-HELP_TEXT Usage: qunited [OPTIONS] [JS_SOURCE_FILES...] -- [JS_TEST_FILES..] Runs JavaScript unit tests with QUnit. JS_SOURCE_FILES are the JavaScript files that you want to test. They will all be loaded for running each test. JS_TEST_FILES are files that contain the QUnit tests to run. Options: HELP_TEXT opts.on('-d', '--driver [NAME]', 'Specify the driver to use in running the tests', valid_drivers_string) do |name| raise UsageError, 'Must specify a driver name with -d or --driver option' unless name names_and_drivers = Hash[drivers.map { |d| d.to_s.downcase }.zip(drivers)] driver = names_and_drivers[name.downcase] raise UsageError, "Invalid driver specified: #{name}\n#{valid_drivers_string}" unless driver options[:driver] = driver end opts.on('--fixtures [FILES]', 'Specify some files to include as html before running the tests') do |files| options[:fixture_files] = files.split(',') end opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end opts.on_tail('--version', 'Print the QUnited version') do puts ::QUnited::VERSION exit end if args_empty puts opts exit 1 end end.parse! # Put the -- back in if we had one initially and it was removed if double_dash_neg_index && !ARGV.include?('--') ARGV.insert(double_dash_neg_index, '--') end end
ruby
def handle_options drivers = ::QUnited::Driver.constants.reject { |d| d == :Base } valid_drivers_string = "Valid drivers include: #{drivers.map { |d| d.to_s }.join(', ')}" args_empty = ARGV.empty? # This is a bit of a hack, but OptionParser removes the -- that separates the source # and test files and we need to put it back in the right place. Save the distance from # the end to do this later. double_dash_neg_index = ARGV.find_index('--') && (ARGV.find_index('--') - ARGV.size) optparse = OptionParser.new do |opts| opts.banner = <<-HELP_TEXT Usage: qunited [OPTIONS] [JS_SOURCE_FILES...] -- [JS_TEST_FILES..] Runs JavaScript unit tests with QUnit. JS_SOURCE_FILES are the JavaScript files that you want to test. They will all be loaded for running each test. JS_TEST_FILES are files that contain the QUnit tests to run. Options: HELP_TEXT opts.on('-d', '--driver [NAME]', 'Specify the driver to use in running the tests', valid_drivers_string) do |name| raise UsageError, 'Must specify a driver name with -d or --driver option' unless name names_and_drivers = Hash[drivers.map { |d| d.to_s.downcase }.zip(drivers)] driver = names_and_drivers[name.downcase] raise UsageError, "Invalid driver specified: #{name}\n#{valid_drivers_string}" unless driver options[:driver] = driver end opts.on('--fixtures [FILES]', 'Specify some files to include as html before running the tests') do |files| options[:fixture_files] = files.split(',') end opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end opts.on_tail('--version', 'Print the QUnited version') do puts ::QUnited::VERSION exit end if args_empty puts opts exit 1 end end.parse! # Put the -- back in if we had one initially and it was removed if double_dash_neg_index && !ARGV.include?('--') ARGV.insert(double_dash_neg_index, '--') end end
[ "def", "handle_options", "drivers", "=", "::", "QUnited", "::", "Driver", ".", "constants", ".", "reject", "{", "|", "d", "|", "d", "==", ":Base", "}", "valid_drivers_string", "=", "\"Valid drivers include: #{drivers.map { |d| d.to_s }.join(', ')}\"", "args_empty", "=", "ARGV", ".", "empty?", "double_dash_neg_index", "=", "ARGV", ".", "find_index", "(", "'--'", ")", "&&", "(", "ARGV", ".", "find_index", "(", "'--'", ")", "-", "ARGV", ".", "size", ")", "optparse", "=", "OptionParser", ".", "new", "do", "|", "opts", "|", "opts", ".", "banner", "=", "<<-HELP_TEXT", "HELP_TEXT", "opts", ".", "on", "(", "'-d'", ",", "'--driver [NAME]'", ",", "'Specify the driver to use in running the tests'", ",", "valid_drivers_string", ")", "do", "|", "name", "|", "raise", "UsageError", ",", "'Must specify a driver name with -d or --driver option'", "unless", "name", "names_and_drivers", "=", "Hash", "[", "drivers", ".", "map", "{", "|", "d", "|", "d", ".", "to_s", ".", "downcase", "}", ".", "zip", "(", "drivers", ")", "]", "driver", "=", "names_and_drivers", "[", "name", ".", "downcase", "]", "raise", "UsageError", ",", "\"Invalid driver specified: #{name}\\n#{valid_drivers_string}\"", "unless", "driver", "options", "[", ":driver", "]", "=", "driver", "end", "opts", ".", "on", "(", "'--fixtures [FILES]'", ",", "'Specify some files to include as html before running the tests'", ")", "do", "|", "files", "|", "options", "[", ":fixture_files", "]", "=", "files", ".", "split", "(", "','", ")", "end", "opts", ".", "on_tail", "(", "'-h'", ",", "'--help'", ",", "'Show this message'", ")", "do", "puts", "opts", "exit", "end", "opts", ".", "on_tail", "(", "'--version'", ",", "'Print the QUnited version'", ")", "do", "puts", "::", "QUnited", "::", "VERSION", "exit", "end", "if", "args_empty", "puts", "opts", "exit", "1", "end", "end", ".", "parse!", "if", "double_dash_neg_index", "&&", "!", "ARGV", ".", "include?", "(", "'--'", ")", "ARGV", ".", "insert", "(", "double_dash_neg_index", ",", "'--'", ")", "end", "end" ]
Parse and handle command line options
[ "Parse", "and", "handle", "command", "line", "options" ]
2a47680a13a49bf8cc0aad2de12e6939e16c1495
https://github.com/aaronroyer/qunited/blob/2a47680a13a49bf8cc0aad2de12e6939e16c1495/lib/qunited/application.rb#L24-L81
train
ample/ample_assets
lib/ample_assets/view_helper.rb
AmpleAssets.ViewHelper.image_asset
def image_asset(object, args={}) # Gracefully handle nil return if object.try(:file).nil? && args[:object].nil? # Define default opts and merge with parameter args opts = { :alt => '', :video_dimensions => '500x350', :encode => :png }.merge(args) # Override alt text with object title if it exists opts[:alt] = escape_javascript(object.title) if object.respond_to?('title') # See if optional file object actually contains a dfly instance if opts[:object] attachment = opts[:object].attachment attachment_gravity = opts[:object].attachment_gravity # Override alt text with attachment alt_text if it exists opts[:alt] = escape_javascript(opts[:object].alt_text) if opts[:object].respond_to?('alt_text') && !opts[:object].send(:alt_text).blank? else attachment = object.file.attachment attachment_gravity = object.file.attachment_gravity # Override alt text with attachment alt_text if it exists opts[:alt] = escape_javascript(object.file.alt_text) if object.file.respond_to?('alt_text') && !object.file.send(:alt_text).blank? end # If this is a crop, try to add gravity if opts.try(:[], :dimensions) && opts[:dimensions].include?('#') # Strip out image geometry opts[:size] = /[0-9]{1,}x[0-9]{1,}/.match(opts[:dimensions]).try(:[], 0) width, height = opts[:size].split('x') image = attachment.process(:resize_and_crop, :width => width, :height => height, :gravity => attachment_gravity).encode(opts[:encode]) else image = opts.try(:[], :dimensions) ? attachment.process(:thumb, opts[:dimensions]).encode(opts[:encode]) : attachment.encode(opts[:encode]) end # Determine which opts ultimately get passed to image_tag valid_opts = [:alt, :class, :style, :title] valid_opts.push(:size) unless args[:size] == false # Create image tag img_tag = image_tag(image.url, opts.slice(*valid_opts)) # If this is a video link if opts[:video] link_to img_tag, opts[:link], :rel => 'facebox', :rev => "iframe|#{opts[:video_dimensions]}" else link_to_if opts[:link], img_tag, opts[:link] end end
ruby
def image_asset(object, args={}) # Gracefully handle nil return if object.try(:file).nil? && args[:object].nil? # Define default opts and merge with parameter args opts = { :alt => '', :video_dimensions => '500x350', :encode => :png }.merge(args) # Override alt text with object title if it exists opts[:alt] = escape_javascript(object.title) if object.respond_to?('title') # See if optional file object actually contains a dfly instance if opts[:object] attachment = opts[:object].attachment attachment_gravity = opts[:object].attachment_gravity # Override alt text with attachment alt_text if it exists opts[:alt] = escape_javascript(opts[:object].alt_text) if opts[:object].respond_to?('alt_text') && !opts[:object].send(:alt_text).blank? else attachment = object.file.attachment attachment_gravity = object.file.attachment_gravity # Override alt text with attachment alt_text if it exists opts[:alt] = escape_javascript(object.file.alt_text) if object.file.respond_to?('alt_text') && !object.file.send(:alt_text).blank? end # If this is a crop, try to add gravity if opts.try(:[], :dimensions) && opts[:dimensions].include?('#') # Strip out image geometry opts[:size] = /[0-9]{1,}x[0-9]{1,}/.match(opts[:dimensions]).try(:[], 0) width, height = opts[:size].split('x') image = attachment.process(:resize_and_crop, :width => width, :height => height, :gravity => attachment_gravity).encode(opts[:encode]) else image = opts.try(:[], :dimensions) ? attachment.process(:thumb, opts[:dimensions]).encode(opts[:encode]) : attachment.encode(opts[:encode]) end # Determine which opts ultimately get passed to image_tag valid_opts = [:alt, :class, :style, :title] valid_opts.push(:size) unless args[:size] == false # Create image tag img_tag = image_tag(image.url, opts.slice(*valid_opts)) # If this is a video link if opts[:video] link_to img_tag, opts[:link], :rel => 'facebox', :rev => "iframe|#{opts[:video_dimensions]}" else link_to_if opts[:link], img_tag, opts[:link] end end
[ "def", "image_asset", "(", "object", ",", "args", "=", "{", "}", ")", "return", "if", "object", ".", "try", "(", ":file", ")", ".", "nil?", "&&", "args", "[", ":object", "]", ".", "nil?", "opts", "=", "{", ":alt", "=>", "''", ",", ":video_dimensions", "=>", "'500x350'", ",", ":encode", "=>", ":png", "}", ".", "merge", "(", "args", ")", "opts", "[", ":alt", "]", "=", "escape_javascript", "(", "object", ".", "title", ")", "if", "object", ".", "respond_to?", "(", "'title'", ")", "if", "opts", "[", ":object", "]", "attachment", "=", "opts", "[", ":object", "]", ".", "attachment", "attachment_gravity", "=", "opts", "[", ":object", "]", ".", "attachment_gravity", "opts", "[", ":alt", "]", "=", "escape_javascript", "(", "opts", "[", ":object", "]", ".", "alt_text", ")", "if", "opts", "[", ":object", "]", ".", "respond_to?", "(", "'alt_text'", ")", "&&", "!", "opts", "[", ":object", "]", ".", "send", "(", ":alt_text", ")", ".", "blank?", "else", "attachment", "=", "object", ".", "file", ".", "attachment", "attachment_gravity", "=", "object", ".", "file", ".", "attachment_gravity", "opts", "[", ":alt", "]", "=", "escape_javascript", "(", "object", ".", "file", ".", "alt_text", ")", "if", "object", ".", "file", ".", "respond_to?", "(", "'alt_text'", ")", "&&", "!", "object", ".", "file", ".", "send", "(", ":alt_text", ")", ".", "blank?", "end", "if", "opts", ".", "try", "(", ":[]", ",", ":dimensions", ")", "&&", "opts", "[", ":dimensions", "]", ".", "include?", "(", "'#'", ")", "opts", "[", ":size", "]", "=", "/", "/", ".", "match", "(", "opts", "[", ":dimensions", "]", ")", ".", "try", "(", ":[]", ",", "0", ")", "width", ",", "height", "=", "opts", "[", ":size", "]", ".", "split", "(", "'x'", ")", "image", "=", "attachment", ".", "process", "(", ":resize_and_crop", ",", ":width", "=>", "width", ",", ":height", "=>", "height", ",", ":gravity", "=>", "attachment_gravity", ")", ".", "encode", "(", "opts", "[", ":encode", "]", ")", "else", "image", "=", "opts", ".", "try", "(", ":[]", ",", ":dimensions", ")", "?", "attachment", ".", "process", "(", ":thumb", ",", "opts", "[", ":dimensions", "]", ")", ".", "encode", "(", "opts", "[", ":encode", "]", ")", ":", "attachment", ".", "encode", "(", "opts", "[", ":encode", "]", ")", "end", "valid_opts", "=", "[", ":alt", ",", ":class", ",", ":style", ",", ":title", "]", "valid_opts", ".", "push", "(", ":size", ")", "unless", "args", "[", ":size", "]", "==", "false", "img_tag", "=", "image_tag", "(", "image", ".", "url", ",", "opts", ".", "slice", "(", "*", "valid_opts", ")", ")", "if", "opts", "[", ":video", "]", "link_to", "img_tag", ",", "opts", "[", ":link", "]", ",", ":rel", "=>", "'facebox'", ",", ":rev", "=>", "\"iframe|#{opts[:video_dimensions]}\"", "else", "link_to_if", "opts", "[", ":link", "]", ",", "img_tag", ",", "opts", "[", ":link", "]", "end", "end" ]
Returns image tag for an object's attachment, with optional link element wrapped around it. @param Object - Required @param String :alt - Defaults to object.title @param String :title @param String :class @param String :style @param String :dimensions - Dragonfly-esque dimensions... @see http://markevans.github.com/dragonfly/file.Processing.html @param String :link - Destination for link_to tag @param Symbol :encode - :gif, :jpg, :png, etc. Defaults to :png @param Object :object - Dragonfly object, defaults to object.file @param Boolean :video - Link to an iframe lightbox? @param String :video_dimensions - (width)x(height), defaults to 500x350
[ "Returns", "image", "tag", "for", "an", "object", "s", "attachment", "with", "optional", "link", "element", "wrapped", "around", "it", "." ]
54264a70f0b1920908d431ec67e73cf9a07844e2
https://github.com/ample/ample_assets/blob/54264a70f0b1920908d431ec67e73cf9a07844e2/lib/ample_assets/view_helper.rb#L26-L79
train
talis/blueprint_rb
lib/blueprint_ruby_client/api/asset_type_configs_api.rb
BlueprintClient.AssetTypeConfigsApi.get
def get(namespace, asset_type, opts = {}) data, _status_code, _headers = get_with_http_info(namespace, asset_type, opts) return data end
ruby
def get(namespace, asset_type, opts = {}) data, _status_code, _headers = get_with_http_info(namespace, asset_type, opts) return data end
[ "def", "get", "(", "namespace", ",", "asset_type", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_with_http_info", "(", "namespace", ",", "asset_type", ",", "opts", ")", "return", "data", "end" ]
get a template for a given asset type @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param asset_type subtype of Asset, e.g. &#39;textbooks&#39;, &#39;digitisations&#39;, etc. @param [Hash] opts the optional parameters @return [TemplateBody]
[ "get", "a", "template", "for", "a", "given", "asset", "type" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/asset_type_configs_api.rb#L29-L32
train
bmulvihill/agglomerative_clustering
lib/agglomerative_clustering/silhouette_coefficient.rb
AgglomerativeClustering.SilhouetteCoefficient.measure
def measure clusters silhouettes = [] average_distances = [] main_cluster.points.each do |point1| a1 = calculate_a1(point1) (clusters - [main_cluster]).each do |cluster| distances = [] cluster.points.each do |point2| distances << euclidean_distance(point1, point2).round(2) end average_distances << distances.inject(:+)/distances.size end b1 = average_distances.min || 0 s1 = (b1 - a1)/[a1,b1].max silhouettes << s1 end (silhouettes.inject(:+) / silhouettes.size).round(2) end
ruby
def measure clusters silhouettes = [] average_distances = [] main_cluster.points.each do |point1| a1 = calculate_a1(point1) (clusters - [main_cluster]).each do |cluster| distances = [] cluster.points.each do |point2| distances << euclidean_distance(point1, point2).round(2) end average_distances << distances.inject(:+)/distances.size end b1 = average_distances.min || 0 s1 = (b1 - a1)/[a1,b1].max silhouettes << s1 end (silhouettes.inject(:+) / silhouettes.size).round(2) end
[ "def", "measure", "clusters", "silhouettes", "=", "[", "]", "average_distances", "=", "[", "]", "main_cluster", ".", "points", ".", "each", "do", "|", "point1", "|", "a1", "=", "calculate_a1", "(", "point1", ")", "(", "clusters", "-", "[", "main_cluster", "]", ")", ".", "each", "do", "|", "cluster", "|", "distances", "=", "[", "]", "cluster", ".", "points", ".", "each", "do", "|", "point2", "|", "distances", "<<", "euclidean_distance", "(", "point1", ",", "point2", ")", ".", "round", "(", "2", ")", "end", "average_distances", "<<", "distances", ".", "inject", "(", ":+", ")", "/", "distances", ".", "size", "end", "b1", "=", "average_distances", ".", "min", "||", "0", "s1", "=", "(", "b1", "-", "a1", ")", "/", "[", "a1", ",", "b1", "]", ".", "max", "silhouettes", "<<", "s1", "end", "(", "silhouettes", ".", "inject", "(", ":+", ")", "/", "silhouettes", ".", "size", ")", ".", "round", "(", "2", ")", "end" ]
Measures the silhouette coefficient of a cluster compared to all other clusters Returns the average silhouette coefficient of a cluster
[ "Measures", "the", "silhouette", "coefficient", "of", "a", "cluster", "compared", "to", "all", "other", "clusters", "Returns", "the", "average", "silhouette", "coefficient", "of", "a", "cluster" ]
bf46dbeebe560c6d6d547ddb2c7a0be2bf5b3b77
https://github.com/bmulvihill/agglomerative_clustering/blob/bf46dbeebe560c6d6d547ddb2c7a0be2bf5b3b77/lib/agglomerative_clustering/silhouette_coefficient.rb#L12-L29
train
bmulvihill/agglomerative_clustering
lib/agglomerative_clustering/silhouette_coefficient.rb
AgglomerativeClustering.SilhouetteCoefficient.calculate_a1
def calculate_a1 point distances = [] main_cluster.points.each do |point1| distances << euclidean_distance(point, point1).round(2) end return 0 if distances.size == 1 (distances.inject(:+)/(distances.size - 1)).round(2) end
ruby
def calculate_a1 point distances = [] main_cluster.points.each do |point1| distances << euclidean_distance(point, point1).round(2) end return 0 if distances.size == 1 (distances.inject(:+)/(distances.size - 1)).round(2) end
[ "def", "calculate_a1", "point", "distances", "=", "[", "]", "main_cluster", ".", "points", ".", "each", "do", "|", "point1", "|", "distances", "<<", "euclidean_distance", "(", "point", ",", "point1", ")", ".", "round", "(", "2", ")", "end", "return", "0", "if", "distances", ".", "size", "==", "1", "(", "distances", ".", "inject", "(", ":+", ")", "/", "(", "distances", ".", "size", "-", "1", ")", ")", ".", "round", "(", "2", ")", "end" ]
Calculates the a1 value of a cluster
[ "Calculates", "the", "a1", "value", "of", "a", "cluster" ]
bf46dbeebe560c6d6d547ddb2c7a0be2bf5b3b77
https://github.com/bmulvihill/agglomerative_clustering/blob/bf46dbeebe560c6d6d547ddb2c7a0be2bf5b3b77/lib/agglomerative_clustering/silhouette_coefficient.rb#L32-L39
train
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/common_methods.rb
ActsAsSolr.CommonMethods.get_solr_field_type
def get_solr_field_type(field_type) if field_type.is_a?(Symbol) t = TypeMapping[field_type] raise "Unknown field_type symbol: #{field_type}" if t.nil? t elsif field_type.is_a?(String) return field_type else raise "Unknown field_type class: #{field_type.class}: #{field_type}" end end
ruby
def get_solr_field_type(field_type) if field_type.is_a?(Symbol) t = TypeMapping[field_type] raise "Unknown field_type symbol: #{field_type}" if t.nil? t elsif field_type.is_a?(String) return field_type else raise "Unknown field_type class: #{field_type.class}: #{field_type}" end end
[ "def", "get_solr_field_type", "(", "field_type", ")", "if", "field_type", ".", "is_a?", "(", "Symbol", ")", "t", "=", "TypeMapping", "[", "field_type", "]", "raise", "\"Unknown field_type symbol: #{field_type}\"", "if", "t", ".", "nil?", "t", "elsif", "field_type", ".", "is_a?", "(", "String", ")", "return", "field_type", "else", "raise", "\"Unknown field_type class: #{field_type.class}: #{field_type}\"", "end", "end" ]
Converts field types into Solr types
[ "Converts", "field", "types", "into", "Solr", "types" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/common_methods.rb#L20-L30
train
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/common_methods.rb
ActsAsSolr.CommonMethods.solr_add
def solr_add(add_xml) ActsAsSolr::Post.execute(Solr::Request::AddDocument.new(add_xml)) end
ruby
def solr_add(add_xml) ActsAsSolr::Post.execute(Solr::Request::AddDocument.new(add_xml)) end
[ "def", "solr_add", "(", "add_xml", ")", "ActsAsSolr", "::", "Post", ".", "execute", "(", "Solr", "::", "Request", "::", "AddDocument", ".", "new", "(", "add_xml", ")", ")", "end" ]
Sends an add command to Solr
[ "Sends", "an", "add", "command", "to", "Solr" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/common_methods.rb#L44-L46
train
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/common_methods.rb
ActsAsSolr.CommonMethods.solr_delete
def solr_delete(solr_ids) ActsAsSolr::Post.execute(Solr::Request::Delete.new(:id => solr_ids)) end
ruby
def solr_delete(solr_ids) ActsAsSolr::Post.execute(Solr::Request::Delete.new(:id => solr_ids)) end
[ "def", "solr_delete", "(", "solr_ids", ")", "ActsAsSolr", "::", "Post", ".", "execute", "(", "Solr", "::", "Request", "::", "Delete", ".", "new", "(", ":id", "=>", "solr_ids", ")", ")", "end" ]
Sends the delete command to Solr
[ "Sends", "the", "delete", "command", "to", "Solr" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/common_methods.rb#L49-L51
train
redding/dk
lib/dk/remote.rb
Dk::Remote.BaseCmd.build_ssh_cmd_str
def build_ssh_cmd_str(cmd_str, host, args, host_args) Dk::Remote.ssh_cmd_str(cmd_str, host, args, host_args) end
ruby
def build_ssh_cmd_str(cmd_str, host, args, host_args) Dk::Remote.ssh_cmd_str(cmd_str, host, args, host_args) end
[ "def", "build_ssh_cmd_str", "(", "cmd_str", ",", "host", ",", "args", ",", "host_args", ")", "Dk", "::", "Remote", ".", "ssh_cmd_str", "(", "cmd_str", ",", "host", ",", "args", ",", "host_args", ")", "end" ]
escape everything properly; run in sh to ensure full profile is loaded
[ "escape", "everything", "properly", ";", "run", "in", "sh", "to", "ensure", "full", "profile", "is", "loaded" ]
9b6122ce815467c698811014c01518cca539946e
https://github.com/redding/dk/blob/9b6122ce815467c698811014c01518cca539946e/lib/dk/remote.rb#L82-L84
train
aaronroyer/qunited
lib/qunited/rake_task.rb
QUnited.RakeTask.files_array
def files_array(files) return [] unless files files.is_a?(Array) ? files : pattern_to_filelist(files.to_s) end
ruby
def files_array(files) return [] unless files files.is_a?(Array) ? files : pattern_to_filelist(files.to_s) end
[ "def", "files_array", "(", "files", ")", "return", "[", "]", "unless", "files", "files", ".", "is_a?", "(", "Array", ")", "?", "files", ":", "pattern_to_filelist", "(", "files", ".", "to_s", ")", "end" ]
Force convert to array of files if glob pattern
[ "Force", "convert", "to", "array", "of", "files", "if", "glob", "pattern" ]
2a47680a13a49bf8cc0aad2de12e6939e16c1495
https://github.com/aaronroyer/qunited/blob/2a47680a13a49bf8cc0aad2de12e6939e16c1495/lib/qunited/rake_task.rb#L151-L154
train
openplacos/openplacos
components/LibComponent.rb
LibComponent.Pin.introspect
def introspect iface = Hash.new pin = Hash.new meth = Array.new if self.respond_to?(:read) meth << "read" end if self.respond_to?(:write) meth << "write" end iface[@interface] = meth pin[@name] = iface return pin end
ruby
def introspect iface = Hash.new pin = Hash.new meth = Array.new if self.respond_to?(:read) meth << "read" end if self.respond_to?(:write) meth << "write" end iface[@interface] = meth pin[@name] = iface return pin end
[ "def", "introspect", "iface", "=", "Hash", ".", "new", "pin", "=", "Hash", ".", "new", "meth", "=", "Array", ".", "new", "if", "self", ".", "respond_to?", "(", ":read", ")", "meth", "<<", "\"read\"", "end", "if", "self", ".", "respond_to?", "(", ":write", ")", "meth", "<<", "\"write\"", "end", "iface", "[", "@interface", "]", "=", "meth", "pin", "[", "@name", "]", "=", "iface", "return", "pin", "end" ]
Return introspect object that can be delivered to openplacos server
[ "Return", "introspect", "object", "that", "can", "be", "delivered", "to", "openplacos", "server" ]
75e1d2862bcf74773b9064f1f59015726ebc5256
https://github.com/openplacos/openplacos/blob/75e1d2862bcf74773b9064f1f59015726ebc5256/components/LibComponent.rb#L27-L41
train
openplacos/openplacos
components/LibComponent.rb
LibComponent.Component.<<
def <<(pin_) if pin_.kind_of?(Input) @inputs << pin_ elsif pin_.kind_of?(Output) @outputs << pin_ elsif pin_.kind_of?(Array) # push an array of pin pin_.each { |p| self << p } end pin_.set_component(self) end
ruby
def <<(pin_) if pin_.kind_of?(Input) @inputs << pin_ elsif pin_.kind_of?(Output) @outputs << pin_ elsif pin_.kind_of?(Array) # push an array of pin pin_.each { |p| self << p } end pin_.set_component(self) end
[ "def", "<<", "(", "pin_", ")", "if", "pin_", ".", "kind_of?", "(", "Input", ")", "@inputs", "<<", "pin_", "elsif", "pin_", ".", "kind_of?", "(", "Output", ")", "@outputs", "<<", "pin_", "elsif", "pin_", ".", "kind_of?", "(", "Array", ")", "pin_", ".", "each", "{", "|", "p", "|", "self", "<<", "p", "}", "end", "pin_", ".", "set_component", "(", "self", ")", "end" ]
Push pin to component
[ "Push", "pin", "to", "component" ]
75e1d2862bcf74773b9064f1f59015726ebc5256
https://github.com/openplacos/openplacos/blob/75e1d2862bcf74773b9064f1f59015726ebc5256/components/LibComponent.rb#L292-L304
train