repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
seejohnrun/console_tweet
lib/console_tweet/cli.rb
ConsoleTweet.CLI.tweet
def tweet(*args) load_default_token # get it from them directly tweet_text = args.join(' ').strip # or let them append / or pipe tweet_text += (tweet_text.empty? ? '' : ' ') + STDIN.read unless STDIN.tty? # or let them get prompted for it if tweet_text.empty? print 'Tweet (Press return to finish): ' tweet_text = STDIN.gets.strip end return failtown("Empty Tweet") if tweet_text.empty? return failtown("Tweet is too long!") if tweet_text.scan(/./mu).size > 140 return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized? # actually post it @client.update(tweet_text) puts "Tweet Posted!" end
ruby
def tweet(*args) load_default_token # get it from them directly tweet_text = args.join(' ').strip # or let them append / or pipe tweet_text += (tweet_text.empty? ? '' : ' ') + STDIN.read unless STDIN.tty? # or let them get prompted for it if tweet_text.empty? print 'Tweet (Press return to finish): ' tweet_text = STDIN.gets.strip end return failtown("Empty Tweet") if tweet_text.empty? return failtown("Tweet is too long!") if tweet_text.scan(/./mu).size > 140 return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized? # actually post it @client.update(tweet_text) puts "Tweet Posted!" end
[ "def", "tweet", "(", "*", "args", ")", "load_default_token", "tweet_text", "=", "args", ".", "join", "(", "' '", ")", ".", "strip", "tweet_text", "+=", "(", "tweet_text", ".", "empty?", "?", "''", ":", "' '", ")", "+", "STDIN", ".", "read", "unless", "STDIN", ".", "tty?", "if", "tweet_text", ".", "empty?", "print", "'Tweet (Press return to finish): '", "tweet_text", "=", "STDIN", ".", "gets", ".", "strip", "end", "return", "failtown", "(", "\"Empty Tweet\"", ")", "if", "tweet_text", ".", "empty?", "return", "failtown", "(", "\"Tweet is too long!\"", ")", "if", "tweet_text", ".", "scan", "(", "/", "/mu", ")", ".", "size", ">", "140", "return", "failtown", "(", "\"Unauthorized, re-run setup!\"", ")", "unless", "@client", "&&", "@client", ".", "authorized?", "@client", ".", "update", "(", "tweet_text", ")", "puts", "\"Tweet Posted!\"", "end" ]
Send a tweet for the user
[ "Send", "a", "tweet", "for", "the", "user" ]
6920bb0ead3060ac52eb968bc0df3c21b72e1ff6
https://github.com/seejohnrun/console_tweet/blob/6920bb0ead3060ac52eb968bc0df3c21b72e1ff6/lib/console_tweet/cli.rb#L75-L92
train
seejohnrun/console_tweet
lib/console_tweet/cli.rb
ConsoleTweet.CLI.show
def show(args) # If we have no user to get, use the timeline instead return timeline(args) if args.nil? || args.count == 0 target_user = args[0] # Get the timeline and print the tweets if we don't get an error load_default_token # for private tweets res = @client.user_timeline(:screen_name => target_user) return failtown("show :: #{res['error']}") if !res || res.include?('error') print_tweets(res) end
ruby
def show(args) # If we have no user to get, use the timeline instead return timeline(args) if args.nil? || args.count == 0 target_user = args[0] # Get the timeline and print the tweets if we don't get an error load_default_token # for private tweets res = @client.user_timeline(:screen_name => target_user) return failtown("show :: #{res['error']}") if !res || res.include?('error') print_tweets(res) end
[ "def", "show", "(", "args", ")", "return", "timeline", "(", "args", ")", "if", "args", ".", "nil?", "||", "args", ".", "count", "==", "0", "target_user", "=", "args", "[", "0", "]", "load_default_token", "res", "=", "@client", ".", "user_timeline", "(", ":screen_name", "=>", "target_user", ")", "return", "failtown", "(", "\"show :: #{res['error']}\"", ")", "if", "!", "res", "||", "res", ".", "include?", "(", "'error'", ")", "print_tweets", "(", "res", ")", "end" ]
Get 20 most recent statuses of user, or specified user
[ "Get", "20", "most", "recent", "statuses", "of", "user", "or", "specified", "user" ]
6920bb0ead3060ac52eb968bc0df3c21b72e1ff6
https://github.com/seejohnrun/console_tweet/blob/6920bb0ead3060ac52eb968bc0df3c21b72e1ff6/lib/console_tweet/cli.rb#L95-L104
train
seejohnrun/console_tweet
lib/console_tweet/cli.rb
ConsoleTweet.CLI.status
def status(*args) load_default_token return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized? user = @client.info status = user['status'] puts "#{user['name']} (at #{status['created_at']}) #{status['text']}" unless status.nil? end
ruby
def status(*args) load_default_token return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized? user = @client.info status = user['status'] puts "#{user['name']} (at #{status['created_at']}) #{status['text']}" unless status.nil? end
[ "def", "status", "(", "*", "args", ")", "load_default_token", "return", "failtown", "(", "\"Unauthorized, re-run setup!\"", ")", "unless", "@client", "&&", "@client", ".", "authorized?", "user", "=", "@client", ".", "info", "status", "=", "user", "[", "'status'", "]", "puts", "\"#{user['name']} (at #{status['created_at']}) #{status['text']}\"", "unless", "status", ".", "nil?", "end" ]
Get the user's most recent status
[ "Get", "the", "user", "s", "most", "recent", "status" ]
6920bb0ead3060ac52eb968bc0df3c21b72e1ff6
https://github.com/seejohnrun/console_tweet/blob/6920bb0ead3060ac52eb968bc0df3c21b72e1ff6/lib/console_tweet/cli.rb#L107-L113
train
seejohnrun/console_tweet
lib/console_tweet/cli.rb
ConsoleTweet.CLI.setup
def setup(*args) # Keep trying to get the access token until @access_token = self.get_access_token print "Try again? [Y/n] " return false if self.class.get_input.downcase == 'n' end # When we finally get it, record it in a dotfile tokens = {:default => { :token => @access_token.token, :secret => @access_token.secret }} save_tokens(tokens) end
ruby
def setup(*args) # Keep trying to get the access token until @access_token = self.get_access_token print "Try again? [Y/n] " return false if self.class.get_input.downcase == 'n' end # When we finally get it, record it in a dotfile tokens = {:default => { :token => @access_token.token, :secret => @access_token.secret }} save_tokens(tokens) end
[ "def", "setup", "(", "*", "args", ")", "until", "@access_token", "=", "self", ".", "get_access_token", "print", "\"Try again? [Y/n] \"", "return", "false", "if", "self", ".", "class", ".", "get_input", ".", "downcase", "==", "'n'", "end", "tokens", "=", "{", ":default", "=>", "{", ":token", "=>", "@access_token", ".", "token", ",", ":secret", "=>", "@access_token", ".", "secret", "}", "}", "save_tokens", "(", "tokens", ")", "end" ]
Get the access token for the user and save it
[ "Get", "the", "access", "token", "for", "the", "user", "and", "save", "it" ]
6920bb0ead3060ac52eb968bc0df3c21b72e1ff6
https://github.com/seejohnrun/console_tweet/blob/6920bb0ead3060ac52eb968bc0df3c21b72e1ff6/lib/console_tweet/cli.rb#L116-L125
train
seejohnrun/console_tweet
lib/console_tweet/cli.rb
ConsoleTweet.CLI.replies
def replies(*args) load_default_token return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized? # Only send since_id_replies to @client if it's not nil mentions = since_id_replies ? @client.mentions(:since_id => since_id_replies) : @client.mentions if mentions.any? print_tweets(mentions) # Save the last id as since_id self.since_id_replies = mentions.last['id'] end end
ruby
def replies(*args) load_default_token return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized? # Only send since_id_replies to @client if it's not nil mentions = since_id_replies ? @client.mentions(:since_id => since_id_replies) : @client.mentions if mentions.any? print_tweets(mentions) # Save the last id as since_id self.since_id_replies = mentions.last['id'] end end
[ "def", "replies", "(", "*", "args", ")", "load_default_token", "return", "failtown", "(", "\"Unauthorized, re-run setup!\"", ")", "unless", "@client", "&&", "@client", ".", "authorized?", "mentions", "=", "since_id_replies", "?", "@client", ".", "mentions", "(", ":since_id", "=>", "since_id_replies", ")", ":", "@client", ".", "mentions", "if", "mentions", ".", "any?", "print_tweets", "(", "mentions", ")", "self", ".", "since_id_replies", "=", "mentions", ".", "last", "[", "'id'", "]", "end", "end" ]
Returns the 20 most recent @replies / mentions
[ "Returns", "the", "20", "most", "recent" ]
6920bb0ead3060ac52eb968bc0df3c21b72e1ff6
https://github.com/seejohnrun/console_tweet/blob/6920bb0ead3060ac52eb968bc0df3c21b72e1ff6/lib/console_tweet/cli.rb#L128-L138
train
seejohnrun/console_tweet
lib/console_tweet/cli.rb
ConsoleTweet.CLI.help
def help(*args) puts "#{NameColor}console-tweet#{DefaultColor} by John Crepezzi <[email protected]>" puts 'http://github.com/seejohnrun/console-tweet' puts puts "#{CommandColor}twitter#{DefaultColor} View your timeline, since last view" puts "#{CommandColor}twitter setup#{DefaultColor} Setup your account" puts "#{CommandColor}twitter status#{DefaultColor} Get your most recent status" puts "#{CommandColor}twitter tweet \"Hello World\"#{DefaultColor} Send out a tweet" puts "#{CommandColor}twitter show [username]#{DefaultColor} Show the timeline for a user" puts "#{CommandColor}twitter replies#{DefaultColor} Get the most recent @replies and mentions" end
ruby
def help(*args) puts "#{NameColor}console-tweet#{DefaultColor} by John Crepezzi <[email protected]>" puts 'http://github.com/seejohnrun/console-tweet' puts puts "#{CommandColor}twitter#{DefaultColor} View your timeline, since last view" puts "#{CommandColor}twitter setup#{DefaultColor} Setup your account" puts "#{CommandColor}twitter status#{DefaultColor} Get your most recent status" puts "#{CommandColor}twitter tweet \"Hello World\"#{DefaultColor} Send out a tweet" puts "#{CommandColor}twitter show [username]#{DefaultColor} Show the timeline for a user" puts "#{CommandColor}twitter replies#{DefaultColor} Get the most recent @replies and mentions" end
[ "def", "help", "(", "*", "args", ")", "puts", "\"#{NameColor}console-tweet#{DefaultColor} by John Crepezzi <[email protected]>\"", "puts", "'http://github.com/seejohnrun/console-tweet'", "puts", "puts", "\"#{CommandColor}twitter#{DefaultColor} View your timeline, since last view\"", "puts", "\"#{CommandColor}twitter setup#{DefaultColor} Setup your account\"", "puts", "\"#{CommandColor}twitter status#{DefaultColor} Get your most recent status\"", "puts", "\"#{CommandColor}twitter tweet \\\"Hello World\\\"#{DefaultColor} Send out a tweet\"", "puts", "\"#{CommandColor}twitter show [username]#{DefaultColor} Show the timeline for a user\"", "puts", "\"#{CommandColor}twitter replies#{DefaultColor} Get the most recent @replies and mentions\"", "end" ]
Display help section
[ "Display", "help", "section" ]
6920bb0ead3060ac52eb968bc0df3c21b72e1ff6
https://github.com/seejohnrun/console_tweet/blob/6920bb0ead3060ac52eb968bc0df3c21b72e1ff6/lib/console_tweet/cli.rb#L141-L151
train
ubcsanskrit/sanscript.rb
lib/sanscript/benchmark.rb
Sanscript.Benchmark.detect!
def detect!(time = 2, warmup = 1) ::Benchmark.ips do |x| x.config(time: time, warmup: warmup) TEST_STRINGS_FLAT.each do |scheme, string| x.report("Detect #{scheme}") do Sanscript::Detect.detect_scheme(string) end end x.compare! end true end
ruby
def detect!(time = 2, warmup = 1) ::Benchmark.ips do |x| x.config(time: time, warmup: warmup) TEST_STRINGS_FLAT.each do |scheme, string| x.report("Detect #{scheme}") do Sanscript::Detect.detect_scheme(string) end end x.compare! end true end
[ "def", "detect!", "(", "time", "=", "2", ",", "warmup", "=", "1", ")", "::", "Benchmark", ".", "ips", "do", "|", "x", "|", "x", ".", "config", "(", "time", ":", "time", ",", "warmup", ":", "warmup", ")", "TEST_STRINGS_FLAT", ".", "each", "do", "|", "scheme", ",", "string", "|", "x", ".", "report", "(", "\"Detect #{scheme}\"", ")", "do", "Sanscript", "::", "Detect", ".", "detect_scheme", "(", "string", ")", "end", "end", "x", ".", "compare!", "end", "true", "end" ]
Runs benchmark-ips test on detection methods.
[ "Runs", "benchmark", "-", "ips", "test", "on", "detection", "methods", "." ]
0e50c4a856599a7b13c9f0cbc281206245859c71
https://github.com/ubcsanskrit/sanscript.rb/blob/0e50c4a856599a7b13c9f0cbc281206245859c71/lib/sanscript/benchmark.rb#L51-L62
train
ubcsanskrit/sanscript.rb
lib/sanscript/benchmark.rb
Sanscript.Benchmark.transliterate_roman!
def transliterate_roman!(time = 2, warmup = 1) ::Benchmark.ips do |x| x.config(time: time, warmup: warmup) TEST_STRINGS[:roman].to_a.product(TEST_STRINGS_FLAT.keys).each do |(ak, av), bk| next if ak == bk x.report("#{ak} => #{bk}") do Sanscript.transliterate(av, ak, bk) end end x.compare! end true end
ruby
def transliterate_roman!(time = 2, warmup = 1) ::Benchmark.ips do |x| x.config(time: time, warmup: warmup) TEST_STRINGS[:roman].to_a.product(TEST_STRINGS_FLAT.keys).each do |(ak, av), bk| next if ak == bk x.report("#{ak} => #{bk}") do Sanscript.transliterate(av, ak, bk) end end x.compare! end true end
[ "def", "transliterate_roman!", "(", "time", "=", "2", ",", "warmup", "=", "1", ")", "::", "Benchmark", ".", "ips", "do", "|", "x", "|", "x", ".", "config", "(", "time", ":", "time", ",", "warmup", ":", "warmup", ")", "TEST_STRINGS", "[", ":roman", "]", ".", "to_a", ".", "product", "(", "TEST_STRINGS_FLAT", ".", "keys", ")", ".", "each", "do", "|", "(", "ak", ",", "av", ")", ",", "bk", "|", "next", "if", "ak", "==", "bk", "x", ".", "report", "(", "\"#{ak} => #{bk}\"", ")", "do", "Sanscript", ".", "transliterate", "(", "av", ",", "ak", ",", "bk", ")", "end", "end", "x", ".", "compare!", "end", "true", "end" ]
Runs benchmark-ips test on roman-source transliteration methods.
[ "Runs", "benchmark", "-", "ips", "test", "on", "roman", "-", "source", "transliteration", "methods", "." ]
0e50c4a856599a7b13c9f0cbc281206245859c71
https://github.com/ubcsanskrit/sanscript.rb/blob/0e50c4a856599a7b13c9f0cbc281206245859c71/lib/sanscript/benchmark.rb#L65-L77
train
mastahyeti/ifdef
lib/ifdef/logic_processor.rb
Ifdef.LogicProcessor.on_or
def on_or(node) a, b = node.children.map { |c| @truth.fetch(c, process(c)) } if a == :true || b == :true :true elsif a == :false && b == :false :false else nil end end
ruby
def on_or(node) a, b = node.children.map { |c| @truth.fetch(c, process(c)) } if a == :true || b == :true :true elsif a == :false && b == :false :false else nil end end
[ "def", "on_or", "(", "node", ")", "a", ",", "b", "=", "node", ".", "children", ".", "map", "{", "|", "c", "|", "@truth", ".", "fetch", "(", "c", ",", "process", "(", "c", ")", ")", "}", "if", "a", "==", ":true", "||", "b", "==", ":true", ":true", "elsif", "a", "==", ":false", "&&", "b", "==", ":false", ":false", "else", "nil", "end", "end" ]
Handle the `||` statement. node - the node to evaluate. Returns :true if either side is known to be true, :false if both sides are known to be false, and nil otherwise.
[ "Handle", "the", "||", "statement", "." ]
ad19060782b0fb9bf6c345272739b3bf4bd349f6
https://github.com/mastahyeti/ifdef/blob/ad19060782b0fb9bf6c345272739b3bf4bd349f6/lib/ifdef/logic_processor.rb#L33-L43
train
mastahyeti/ifdef
lib/ifdef/logic_processor.rb
Ifdef.LogicProcessor.on_send
def on_send(node) _target, _method, _args = node.children if _method == :! case @truth.fetch(_target, process(_target)) when :true :false when :false :true else nil end else nil end end
ruby
def on_send(node) _target, _method, _args = node.children if _method == :! case @truth.fetch(_target, process(_target)) when :true :false when :false :true else nil end else nil end end
[ "def", "on_send", "(", "node", ")", "_target", ",", "_method", ",", "_args", "=", "node", ".", "children", "if", "_method", "==", ":!", "case", "@truth", ".", "fetch", "(", "_target", ",", "process", "(", "_target", ")", ")", "when", ":true", ":false", "when", ":false", ":true", "else", "nil", "end", "else", "nil", "end", "end" ]
Handles the `!` statement. node - the node to evaluate. Returns the inverse of the child expression.
[ "Handles", "the", "!", "statement", "." ]
ad19060782b0fb9bf6c345272739b3bf4bd349f6
https://github.com/mastahyeti/ifdef/blob/ad19060782b0fb9bf6c345272739b3bf4bd349f6/lib/ifdef/logic_processor.rb#L69-L84
train
mastahyeti/ifdef
lib/ifdef/logic_processor.rb
Ifdef.LogicProcessor.on_begin
def on_begin(node) child, other_children = *node.children # Not sure if this can happen in an `if` statement raise LogicError if other_children case @truth.fetch(child, process(child)) when :true :true when :false :false else nil end end
ruby
def on_begin(node) child, other_children = *node.children # Not sure if this can happen in an `if` statement raise LogicError if other_children case @truth.fetch(child, process(child)) when :true :true when :false :false else nil end end
[ "def", "on_begin", "(", "node", ")", "child", ",", "other_children", "=", "*", "node", ".", "children", "raise", "LogicError", "if", "other_children", "case", "@truth", ".", "fetch", "(", "child", ",", "process", "(", "child", ")", ")", "when", ":true", ":true", "when", ":false", ":false", "else", "nil", "end", "end" ]
Handle logic statements explicitly wrapped in parenthesis. node - the node to evaluate. Returns the result of the statement within the parenthesis.
[ "Handle", "logic", "statements", "explicitly", "wrapped", "in", "parenthesis", "." ]
ad19060782b0fb9bf6c345272739b3bf4bd349f6
https://github.com/mastahyeti/ifdef/blob/ad19060782b0fb9bf6c345272739b3bf4bd349f6/lib/ifdef/logic_processor.rb#L91-L105
train
postmodern/deployml
lib/deployml/environment.rb
DeploYML.Environment.remote_shell
def remote_shell(&block) each_dest.map do |dest| shell = if dest.scheme == 'file' LocalShell else RemoteShell end shell.new(dest,self,&block) end end
ruby
def remote_shell(&block) each_dest.map do |dest| shell = if dest.scheme == 'file' LocalShell else RemoteShell end shell.new(dest,self,&block) end end
[ "def", "remote_shell", "(", "&", "block", ")", "each_dest", ".", "map", "do", "|", "dest", "|", "shell", "=", "if", "dest", ".", "scheme", "==", "'file'", "LocalShell", "else", "RemoteShell", "end", "shell", ".", "new", "(", "dest", ",", "self", ",", "&", "block", ")", "end", "end" ]
Creates a remote shell with the destination server. @yield [shell] If a block is given, it will be passed the new remote shell. @yieldparam [LocalShell, RemoteShell] shell The remote shell. @return [Array<RemoteShell, LocalShell>] The remote shell. If the destination is a local `file://` URI, a local shell will be returned instead. @since 0.3.0
[ "Creates", "a", "remote", "shell", "with", "the", "destination", "server", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/environment.rb#L94-L104
train
postmodern/deployml
lib/deployml/environment.rb
DeploYML.Environment.exec
def exec(command) remote_shell do |shell| shell.cd(shell.uri.path) shell.exec(command) end return true end
ruby
def exec(command) remote_shell do |shell| shell.cd(shell.uri.path) shell.exec(command) end return true end
[ "def", "exec", "(", "command", ")", "remote_shell", "do", "|", "shell", "|", "shell", ".", "cd", "(", "shell", ".", "uri", ".", "path", ")", "shell", ".", "exec", "(", "command", ")", "end", "return", "true", "end" ]
Runs a command on the destination server, in the destination directory. @return [true] @since 0.3.0
[ "Runs", "a", "command", "on", "the", "destination", "server", "in", "the", "destination", "directory", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/environment.rb#L114-L121
train
postmodern/deployml
lib/deployml/environment.rb
DeploYML.Environment.rake
def rake(task,*arguments) remote_shell do |shell| shell.cd(shell.uri.path) shell.rake(task,*arguments) end return true end
ruby
def rake(task,*arguments) remote_shell do |shell| shell.cd(shell.uri.path) shell.rake(task,*arguments) end return true end
[ "def", "rake", "(", "task", ",", "*", "arguments", ")", "remote_shell", "do", "|", "shell", "|", "shell", ".", "cd", "(", "shell", ".", "uri", ".", "path", ")", "shell", ".", "rake", "(", "task", ",", "*", "arguments", ")", "end", "return", "true", "end" ]
Executes a Rake task on the destination server, in the destination directory. @return [true] @since 0.3.0
[ "Executes", "a", "Rake", "task", "on", "the", "destination", "server", "in", "the", "destination", "directory", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/environment.rb#L131-L138
train
postmodern/deployml
lib/deployml/environment.rb
DeploYML.Environment.ssh
def ssh(*arguments) each_dest do |dest| RemoteShell.new(dest).ssh(*arguments) end return true end
ruby
def ssh(*arguments) each_dest do |dest| RemoteShell.new(dest).ssh(*arguments) end return true end
[ "def", "ssh", "(", "*", "arguments", ")", "each_dest", "do", "|", "dest", "|", "RemoteShell", ".", "new", "(", "dest", ")", ".", "ssh", "(", "*", "arguments", ")", "end", "return", "true", "end" ]
Starts an SSH session with the destination server. @param [Array] arguments Additional arguments to pass to SSH. @return [true] @since 0.3.0
[ "Starts", "an", "SSH", "session", "with", "the", "destination", "server", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/environment.rb#L150-L156
train
postmodern/deployml
lib/deployml/environment.rb
DeploYML.Environment.setup
def setup(shell) shell.status "Cloning #{@source} ..." shell.run 'git', 'clone', '--depth', 1, @source, shell.uri.path shell.status "Cloned #{@source}." end
ruby
def setup(shell) shell.status "Cloning #{@source} ..." shell.run 'git', 'clone', '--depth', 1, @source, shell.uri.path shell.status "Cloned #{@source}." end
[ "def", "setup", "(", "shell", ")", "shell", ".", "status", "\"Cloning #{@source} ...\"", "shell", ".", "run", "'git'", ",", "'clone'", ",", "'--depth'", ",", "1", ",", "@source", ",", "shell", ".", "uri", ".", "path", "shell", ".", "status", "\"Cloned #{@source}.\"", "end" ]
Sets up the deployment repository for the project. @param [Shell] shell The remote shell to execute commands through. @since 0.3.0
[ "Sets", "up", "the", "deployment", "repository", "for", "the", "project", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/environment.rb#L166-L172
train
postmodern/deployml
lib/deployml/environment.rb
DeploYML.Environment.update
def update(shell) shell.status "Updating ..." shell.run 'git', 'reset', '--hard', 'HEAD' shell.run 'git', 'pull', '-f' shell.status "Updated." end
ruby
def update(shell) shell.status "Updating ..." shell.run 'git', 'reset', '--hard', 'HEAD' shell.run 'git', 'pull', '-f' shell.status "Updated." end
[ "def", "update", "(", "shell", ")", "shell", ".", "status", "\"Updating ...\"", "shell", ".", "run", "'git'", ",", "'reset'", ",", "'--hard'", ",", "'HEAD'", "shell", ".", "run", "'git'", ",", "'pull'", ",", "'-f'", "shell", ".", "status", "\"Updated.\"", "end" ]
Updates the deployed repository for the project. @param [Shell] shell The remote shell to execute commands through. @since 0.3.0
[ "Updates", "the", "deployed", "repository", "for", "the", "project", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/environment.rb#L182-L189
train
postmodern/deployml
lib/deployml/environment.rb
DeploYML.Environment.invoke_task
def invoke_task(task,shell) unless TASKS.include?(task) raise("invalid task: #{task}") end if @before.has_key?(task) @before[task].each { |command| shell.exec(command) } end send(task,shell) if respond_to?(task) if @after.has_key?(task) @after[task].each { |command| shell.exec(command) } end end
ruby
def invoke_task(task,shell) unless TASKS.include?(task) raise("invalid task: #{task}") end if @before.has_key?(task) @before[task].each { |command| shell.exec(command) } end send(task,shell) if respond_to?(task) if @after.has_key?(task) @after[task].each { |command| shell.exec(command) } end end
[ "def", "invoke_task", "(", "task", ",", "shell", ")", "unless", "TASKS", ".", "include?", "(", "task", ")", "raise", "(", "\"invalid task: #{task}\"", ")", "end", "if", "@before", ".", "has_key?", "(", "task", ")", "@before", "[", "task", "]", ".", "each", "{", "|", "command", "|", "shell", ".", "exec", "(", "command", ")", "}", "end", "send", "(", "task", ",", "shell", ")", "if", "respond_to?", "(", "task", ")", "if", "@after", ".", "has_key?", "(", "task", ")", "@after", "[", "task", "]", ".", "each", "{", "|", "command", "|", "shell", ".", "exec", "(", "command", ")", "}", "end", "end" ]
Invokes a task. @param [Symbol] task The name of the task to run. @param [Shell] shell The shell to run the task in. @raise [RuntimeError] The task name was not known. @since 0.5.0
[ "Invokes", "a", "task", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/environment.rb#L326-L340
train
postmodern/deployml
lib/deployml/environment.rb
DeploYML.Environment.invoke
def invoke(tasks) remote_shell do |shell| # setup the deployment repository invoke_task(:setup,shell) if tasks.include?(:setup) # cd into the deployment repository shell.cd(shell.uri.path) # update the deployment repository invoke_task(:update,shell) if tasks.include?(:update) # framework tasks invoke_task(:install,shell) if tasks.include?(:install) invoke_task(:migrate,shell) if tasks.include?(:migrate) # server tasks if tasks.include?(:config) invoke_task(:config,shell) elsif tasks.include?(:start) invoke_task(:start,shell) elsif tasks.include?(:stop) invoke_task(:stop,shell) elsif tasks.include?(:restart) invoke_task(:restart,shell) end end return true end
ruby
def invoke(tasks) remote_shell do |shell| # setup the deployment repository invoke_task(:setup,shell) if tasks.include?(:setup) # cd into the deployment repository shell.cd(shell.uri.path) # update the deployment repository invoke_task(:update,shell) if tasks.include?(:update) # framework tasks invoke_task(:install,shell) if tasks.include?(:install) invoke_task(:migrate,shell) if tasks.include?(:migrate) # server tasks if tasks.include?(:config) invoke_task(:config,shell) elsif tasks.include?(:start) invoke_task(:start,shell) elsif tasks.include?(:stop) invoke_task(:stop,shell) elsif tasks.include?(:restart) invoke_task(:restart,shell) end end return true end
[ "def", "invoke", "(", "tasks", ")", "remote_shell", "do", "|", "shell", "|", "invoke_task", "(", ":setup", ",", "shell", ")", "if", "tasks", ".", "include?", "(", ":setup", ")", "shell", ".", "cd", "(", "shell", ".", "uri", ".", "path", ")", "invoke_task", "(", ":update", ",", "shell", ")", "if", "tasks", ".", "include?", "(", ":update", ")", "invoke_task", "(", ":install", ",", "shell", ")", "if", "tasks", ".", "include?", "(", ":install", ")", "invoke_task", "(", ":migrate", ",", "shell", ")", "if", "tasks", ".", "include?", "(", ":migrate", ")", "if", "tasks", ".", "include?", "(", ":config", ")", "invoke_task", "(", ":config", ",", "shell", ")", "elsif", "tasks", ".", "include?", "(", ":start", ")", "invoke_task", "(", ":start", ",", "shell", ")", "elsif", "tasks", ".", "include?", "(", ":stop", ")", "invoke_task", "(", ":stop", ",", "shell", ")", "elsif", "tasks", ".", "include?", "(", ":restart", ")", "invoke_task", "(", ":restart", ",", "shell", ")", "end", "end", "return", "true", "end" ]
Deploys the project. @param [Array<Symbol>] tasks The tasks to run during the deployment. @return [true] Indicates that the tasks were successfully completed. @since 0.4.0
[ "Deploys", "the", "project", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/environment.rb#L353-L381
train
postmodern/deployml
lib/deployml/environment.rb
DeploYML.Environment.load_framework!
def load_framework! if @orm unless FRAMEWORKS.has_key?(@framework) raise(UnknownFramework,"Unknown framework #{@framework}",caller) end extend FRAMEWORKS[@framework] initialize_framework if respond_to?(:initialize_framework) end end
ruby
def load_framework! if @orm unless FRAMEWORKS.has_key?(@framework) raise(UnknownFramework,"Unknown framework #{@framework}",caller) end extend FRAMEWORKS[@framework] initialize_framework if respond_to?(:initialize_framework) end end
[ "def", "load_framework!", "if", "@orm", "unless", "FRAMEWORKS", ".", "has_key?", "(", "@framework", ")", "raise", "(", "UnknownFramework", ",", "\"Unknown framework #{@framework}\"", ",", "caller", ")", "end", "extend", "FRAMEWORKS", "[", "@framework", "]", "initialize_framework", "if", "respond_to?", "(", ":initialize_framework", ")", "end", "end" ]
Loads the framework configuration. @since 0.3.0
[ "Loads", "the", "framework", "configuration", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/environment.rb#L510-L520
train
postmodern/deployml
lib/deployml/environment.rb
DeploYML.Environment.load_server!
def load_server! if @server_name unless SERVERS.has_key?(@server_name) raise(UnknownServer,"Unknown server name #{@server_name}",caller) end extend SERVERS[@server_name] initialize_server if respond_to?(:initialize_server) end end
ruby
def load_server! if @server_name unless SERVERS.has_key?(@server_name) raise(UnknownServer,"Unknown server name #{@server_name}",caller) end extend SERVERS[@server_name] initialize_server if respond_to?(:initialize_server) end end
[ "def", "load_server!", "if", "@server_name", "unless", "SERVERS", ".", "has_key?", "(", "@server_name", ")", "raise", "(", "UnknownServer", ",", "\"Unknown server name #{@server_name}\"", ",", "caller", ")", "end", "extend", "SERVERS", "[", "@server_name", "]", "initialize_server", "if", "respond_to?", "(", ":initialize_server", ")", "end", "end" ]
Loads the server configuration. @raise [UnknownServer] @since 0.3.0
[ "Loads", "the", "server", "configuration", "." ]
4369d4ea719e41f0dc3aa6496e6422ad476b0dda
https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/environment.rb#L529-L539
train
ideonetwork/lato-core
lib/lato_core/interfaces/authentication.rb
LatoCore.Interface::Authentication.core__create_superuser_session
def core__create_superuser_session(superuser, lifetime) token = core__encode_token(lifetime, superuser_id: superuser.id) session[:lato_core__superuser_session_token] = token end
ruby
def core__create_superuser_session(superuser, lifetime) token = core__encode_token(lifetime, superuser_id: superuser.id) session[:lato_core__superuser_session_token] = token end
[ "def", "core__create_superuser_session", "(", "superuser", ",", "lifetime", ")", "token", "=", "core__encode_token", "(", "lifetime", ",", "superuser_id", ":", "superuser", ".", "id", ")", "session", "[", ":lato_core__superuser_session_token", "]", "=", "token", "end" ]
This function set a cookie to create the superuser session.
[ "This", "function", "set", "a", "cookie", "to", "create", "the", "superuser", "session", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/authentication.rb#L9-L12
train
ideonetwork/lato-core
lib/lato_core/interfaces/authentication.rb
LatoCore.Interface::Authentication.core__manage_superuser_session
def core__manage_superuser_session(permission = nil) decoded_token = core__decode_token(session[:lato_core__superuser_session_token]) if decoded_token @core__current_superuser = LatoCore::Superuser.find_by(id: decoded_token[:superuser_id]) unless @core__current_superuser core__destroy_superuser_session redirect_to lato_core.login_path end if permission && @core__current_superuser.permission < permission flash[:danger] = 'PERMISSION ERROR' redirect_to lato_core.root_path end else redirect_to lato_core.login_path end end
ruby
def core__manage_superuser_session(permission = nil) decoded_token = core__decode_token(session[:lato_core__superuser_session_token]) if decoded_token @core__current_superuser = LatoCore::Superuser.find_by(id: decoded_token[:superuser_id]) unless @core__current_superuser core__destroy_superuser_session redirect_to lato_core.login_path end if permission && @core__current_superuser.permission < permission flash[:danger] = 'PERMISSION ERROR' redirect_to lato_core.root_path end else redirect_to lato_core.login_path end end
[ "def", "core__manage_superuser_session", "(", "permission", "=", "nil", ")", "decoded_token", "=", "core__decode_token", "(", "session", "[", ":lato_core__superuser_session_token", "]", ")", "if", "decoded_token", "@core__current_superuser", "=", "LatoCore", "::", "Superuser", ".", "find_by", "(", "id", ":", "decoded_token", "[", ":superuser_id", "]", ")", "unless", "@core__current_superuser", "core__destroy_superuser_session", "redirect_to", "lato_core", ".", "login_path", "end", "if", "permission", "&&", "@core__current_superuser", ".", "permission", "<", "permission", "flash", "[", ":danger", "]", "=", "'PERMISSION ERROR'", "redirect_to", "lato_core", ".", "root_path", "end", "else", "redirect_to", "lato_core", ".", "login_path", "end", "end" ]
This function check the session for a superuser and set the variable @core__current_superuser. If session is not valid the user should be redirect to login path.
[ "This", "function", "check", "the", "session", "for", "a", "superuser", "and", "set", "the", "variable" ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/authentication.rb#L28-L45
train
leshill/mongodoc
lib/mongo_doc/matchers.rb
MongoDoc.Matchers.matcher
def matcher(key, value) if value.is_a?(Hash) name = "Mongoid::Matchers::#{value.keys.first.gsub("$", "").camelize}" return name.constantize.new(send(key)) end Mongoid::Matchers::Default.new(send(key)) end
ruby
def matcher(key, value) if value.is_a?(Hash) name = "Mongoid::Matchers::#{value.keys.first.gsub("$", "").camelize}" return name.constantize.new(send(key)) end Mongoid::Matchers::Default.new(send(key)) end
[ "def", "matcher", "(", "key", ",", "value", ")", "if", "value", ".", "is_a?", "(", "Hash", ")", "name", "=", "\"Mongoid::Matchers::#{value.keys.first.gsub(\"$\", \"\").camelize}\"", "return", "name", ".", "constantize", ".", "new", "(", "send", "(", "key", ")", ")", "end", "Mongoid", "::", "Matchers", "::", "Default", ".", "new", "(", "send", "(", "key", ")", ")", "end" ]
Get the matcher for the supplied key and value. Will determine the class name from the key.
[ "Get", "the", "matcher", "for", "the", "supplied", "key", "and", "value", ".", "Will", "determine", "the", "class", "name", "from", "the", "key", "." ]
fb2a4ec456d4c4ae1eb92e117dc73f55951fc3b4
https://github.com/leshill/mongodoc/blob/fb2a4ec456d4c4ae1eb92e117dc73f55951fc3b4/lib/mongo_doc/matchers.rb#L27-L33
train
Sharparam/chatrix
lib/chatrix/user.rb
Chatrix.User.process_power_level
def process_power_level(room, level) membership = (@memberships[room] ||= {}) membership[:power] = level broadcast(:power_level, self, room, level) end
ruby
def process_power_level(room, level) membership = (@memberships[room] ||= {}) membership[:power] = level broadcast(:power_level, self, room, level) end
[ "def", "process_power_level", "(", "room", ",", "level", ")", "membership", "=", "(", "@memberships", "[", "room", "]", "||=", "{", "}", ")", "membership", "[", ":power", "]", "=", "level", "broadcast", "(", ":power_level", ",", "self", ",", "room", ",", "level", ")", "end" ]
Process a power level update in a room. @param room [Room] The room where the level updated. @param level [Fixnum] The new power level.
[ "Process", "a", "power", "level", "update", "in", "a", "room", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/user.rb#L73-L77
train
Sharparam/chatrix
lib/chatrix/user.rb
Chatrix.User.process_invite
def process_invite(room, sender, event) # Return early if we're already part of this room membership = (@memberships[room] ||= {}) return if membership[:type] == :join process_member_event room, event broadcast(:invited, self, room, sender) end
ruby
def process_invite(room, sender, event) # Return early if we're already part of this room membership = (@memberships[room] ||= {}) return if membership[:type] == :join process_member_event room, event broadcast(:invited, self, room, sender) end
[ "def", "process_invite", "(", "room", ",", "sender", ",", "event", ")", "membership", "=", "(", "@memberships", "[", "room", "]", "||=", "{", "}", ")", "return", "if", "membership", "[", ":type", "]", "==", ":join", "process_member_event", "room", ",", "event", "broadcast", "(", ":invited", ",", "self", ",", "room", ",", "sender", ")", "end" ]
Process an invite to a room. @param room [Room] The room the user was invited to. @param sender [User] The user who sent the invite. @param event [Hash] Event data.
[ "Process", "an", "invite", "to", "a", "room", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/user.rb#L83-L89
train
Sharparam/chatrix
lib/chatrix/user.rb
Chatrix.User.update
def update(data) update_avatar(data['avatar_url']) if data.key? 'avatar_url' update_displayname(data['displayname']) if data.key? 'displayname' end
ruby
def update(data) update_avatar(data['avatar_url']) if data.key? 'avatar_url' update_displayname(data['displayname']) if data.key? 'displayname' end
[ "def", "update", "(", "data", ")", "update_avatar", "(", "data", "[", "'avatar_url'", "]", ")", "if", "data", ".", "key?", "'avatar_url'", "update_displayname", "(", "data", "[", "'displayname'", "]", ")", "if", "data", ".", "key?", "'displayname'", "end" ]
Updates metadata for this user. @param data [Hash{String=>String}] User metadata.
[ "Updates", "metadata", "for", "this", "user", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/user.rb#L102-L105
train
kunishi/algebra-ruby2
lib/algebra/algebraic-system.rb
Algebra.AlgebraCreator.wedge
def wedge(otype) # =:= tensor if superior?(otype) self elsif otype.respond_to?(:superior?) && otype.superior?(self) otype else raise "wedge: unknown pair (#{self}) .wedge (#{otype})" end end
ruby
def wedge(otype) # =:= tensor if superior?(otype) self elsif otype.respond_to?(:superior?) && otype.superior?(self) otype else raise "wedge: unknown pair (#{self}) .wedge (#{otype})" end end
[ "def", "wedge", "(", "otype", ")", "if", "superior?", "(", "otype", ")", "self", "elsif", "otype", ".", "respond_to?", "(", ":superior?", ")", "&&", "otype", ".", "superior?", "(", "self", ")", "otype", "else", "raise", "\"wedge: unknown pair (#{self}) .wedge (#{otype})\"", "end", "end" ]
Needed in the type conversion of MatrixAlgebra
[ "Needed", "in", "the", "type", "conversion", "of", "MatrixAlgebra" ]
8976fbaac14933d3206324c845b879bf67fa0cf7
https://github.com/kunishi/algebra-ruby2/blob/8976fbaac14933d3206324c845b879bf67fa0cf7/lib/algebra/algebraic-system.rb#L28-L36
train
Birdie0/qna_maker
lib/qna_maker/endpoints/delete_kb.rb
QnAMaker.Client.delete_kb
def delete_kb response = @http.delete( "#{BASE_URL}/#{knowledgebase_id}" ) case response.code when 204 nil when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] when 403 raise ForbiddenError, response.parse['error']['message'] when 404 raise NotFoundError, response.parse['error']['message'] when 409 raise ConflictError, response.parse['error']['message'] else raise UnknownError, "Oh no! (#{response.code})" end end
ruby
def delete_kb response = @http.delete( "#{BASE_URL}/#{knowledgebase_id}" ) case response.code when 204 nil when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] when 403 raise ForbiddenError, response.parse['error']['message'] when 404 raise NotFoundError, response.parse['error']['message'] when 409 raise ConflictError, response.parse['error']['message'] else raise UnknownError, "Oh no! (#{response.code})" end end
[ "def", "delete_kb", "response", "=", "@http", ".", "delete", "(", "\"#{BASE_URL}/#{knowledgebase_id}\"", ")", "case", "response", ".", "code", "when", "204", "nil", "when", "400", "raise", "BadArgumentError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", ".", "join", "(", "' '", ")", "when", "401", "raise", "UnauthorizedError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "when", "403", "raise", "ForbiddenError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "when", "404", "raise", "NotFoundError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "when", "409", "raise", "ConflictError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "else", "raise", "UnknownError", ",", "\"Oh no! (#{response.code})\"", "end", "end" ]
Deletes the current knowledge base and all data associated with it. @return [nil] on success
[ "Deletes", "the", "current", "knowledge", "base", "and", "all", "data", "associated", "with", "it", "." ]
5ac204ede100355352438b8ff4fe30ad84d9257b
https://github.com/Birdie0/qna_maker/blob/5ac204ede100355352438b8ff4fe30ad84d9257b/lib/qna_maker/endpoints/delete_kb.rb#L8-L29
train
iaintshine/ruby-spanmanager
lib/spanmanager/tracer.rb
SpanManager.Tracer.start_span
def start_span(operation_name, child_of: active_span, **args) span = @tracer.start_span(operation_name, child_of: child_of, **args) @managed_span_source.make_active(span) end
ruby
def start_span(operation_name, child_of: active_span, **args) span = @tracer.start_span(operation_name, child_of: child_of, **args) @managed_span_source.make_active(span) end
[ "def", "start_span", "(", "operation_name", ",", "child_of", ":", "active_span", ",", "**", "args", ")", "span", "=", "@tracer", ".", "start_span", "(", "operation_name", ",", "child_of", ":", "child_of", ",", "**", "args", ")", "@managed_span_source", ".", "make_active", "(", "span", ")", "end" ]
Starts a new active span. @param operation_name [String] The operation name for the Span @param child_of [SpanContext, Span] SpanContext that acts as a parent to the newly-started Span. If default argument is used then the currently active span becomes an implicit parent of a newly-started span. @return [SpanManager::ManagedSpan] The newly-started active Span
[ "Starts", "a", "new", "active", "span", "." ]
95f14b13269f35eacef88d61fa82dac90adde3be
https://github.com/iaintshine/ruby-spanmanager/blob/95f14b13269f35eacef88d61fa82dac90adde3be/lib/spanmanager/tracer.rb#L42-L45
train
jwagener/oauth-active-resource
lib/oauth_active_resource/connection.rb
OAuthActiveResource.Connection.handle_response
def handle_response(response) return super(response) rescue ActiveResource::ClientError => exc begin # ugly code to insert the error_message into response error_message = "#{format.decode response.body}" if not error_message.nil? or error_message == "" exc.response.instance_eval do || @message = error_message end end ensure raise exc end end
ruby
def handle_response(response) return super(response) rescue ActiveResource::ClientError => exc begin # ugly code to insert the error_message into response error_message = "#{format.decode response.body}" if not error_message.nil? or error_message == "" exc.response.instance_eval do || @message = error_message end end ensure raise exc end end
[ "def", "handle_response", "(", "response", ")", "return", "super", "(", "response", ")", "rescue", "ActiveResource", "::", "ClientError", "=>", "exc", "begin", "error_message", "=", "\"#{format.decode response.body}\"", "if", "not", "error_message", ".", "nil?", "or", "error_message", "==", "\"\"", "exc", ".", "response", ".", "instance_eval", "do", "|", "|", "@message", "=", "error_message", "end", "end", "ensure", "raise", "exc", "end", "end" ]
make handle_response public and add error message from body if possible
[ "make", "handle_response", "public", "and", "add", "error", "message", "from", "body", "if", "possible" ]
fc5fc1e1a9fda157c1fc6d792a9cdf2491b59676
https://github.com/jwagener/oauth-active-resource/blob/fc5fc1e1a9fda157c1fc6d792a9cdf2491b59676/lib/oauth_active_resource/connection.rb#L14-L28
train
wordjelly/Auth
app/models/auth/concerns/shopping/product_concern.rb
Auth::Concerns::Shopping::ProductConcern.ClassMethods.add_to_previous_rolling_n_minutes
def add_to_previous_rolling_n_minutes(minutes,origin_epoch,cycle_to_add) ## get all the minutes less than that. rolling_n_minutes_less_than_that = minutes.keys.select{|c| c < origin_epoch} end_min = rolling_n_minutes_less_than_that.size < Auth.configuration.rolling_minutes ? rolling_n_minutes_less_than_that.size : Auth.configuration.rolling_minutes end_min = end_min - 1 end_min = end_min > 0 ? end_min : 0 rolling_n_minutes_less_than_that[0..end_min].each do |epoch| minutes[epoch].cycles << cycle_to_add end end
ruby
def add_to_previous_rolling_n_minutes(minutes,origin_epoch,cycle_to_add) ## get all the minutes less than that. rolling_n_minutes_less_than_that = minutes.keys.select{|c| c < origin_epoch} end_min = rolling_n_minutes_less_than_that.size < Auth.configuration.rolling_minutes ? rolling_n_minutes_less_than_that.size : Auth.configuration.rolling_minutes end_min = end_min - 1 end_min = end_min > 0 ? end_min : 0 rolling_n_minutes_less_than_that[0..end_min].each do |epoch| minutes[epoch].cycles << cycle_to_add end end
[ "def", "add_to_previous_rolling_n_minutes", "(", "minutes", ",", "origin_epoch", ",", "cycle_to_add", ")", "rolling_n_minutes_less_than_that", "=", "minutes", ".", "keys", ".", "select", "{", "|", "c", "|", "c", "<", "origin_epoch", "}", "end_min", "=", "rolling_n_minutes_less_than_that", ".", "size", "<", "Auth", ".", "configuration", ".", "rolling_minutes", "?", "rolling_n_minutes_less_than_that", ".", "size", ":", "Auth", ".", "configuration", ".", "rolling_minutes", "end_min", "=", "end_min", "-", "1", "end_min", "=", "end_min", ">", "0", "?", "end_min", ":", "0", "rolling_n_minutes_less_than_that", "[", "0", "..", "end_min", "]", ".", "each", "do", "|", "epoch", "|", "minutes", "[", "epoch", "]", ".", "cycles", "<<", "cycle_to_add", "end", "end" ]
so we have completed the rolling n minutes.
[ "so", "we", "have", "completed", "the", "rolling", "n", "minutes", "." ]
e1b6697a13c845f57b3cc83bfb79059a09541f47
https://github.com/wordjelly/Auth/blob/e1b6697a13c845f57b3cc83bfb79059a09541f47/app/models/auth/concerns/shopping/product_concern.rb#L121-L135
train
arman000/delorean_lang
lib/delorean/engine.rb
Delorean.Engine.parse_check_defined_node
def parse_check_defined_node(name, flag) isdef = node_defined?(name) if isdef != flag isdef ? err(RedefinedError, "#{name} already defined") : err(UndefinedError, "#{name} not defined yet") end end
ruby
def parse_check_defined_node(name, flag) isdef = node_defined?(name) if isdef != flag isdef ? err(RedefinedError, "#{name} already defined") : err(UndefinedError, "#{name} not defined yet") end end
[ "def", "parse_check_defined_node", "(", "name", ",", "flag", ")", "isdef", "=", "node_defined?", "(", "name", ")", "if", "isdef", "!=", "flag", "isdef", "?", "err", "(", "RedefinedError", ",", "\"#{name} already defined\"", ")", ":", "err", "(", "UndefinedError", ",", "\"#{name} not defined yet\"", ")", "end", "end" ]
Check to see if node with given name is defined. flag tells the method about our expectation. flag=true means that we make sure that name is defined. flag=false is the opposite.
[ "Check", "to", "see", "if", "node", "with", "given", "name", "is", "defined", ".", "flag", "tells", "the", "method", "about", "our", "expectation", ".", "flag", "=", "true", "means", "that", "we", "make", "sure", "that", "name", "is", "defined", ".", "flag", "=", "false", "is", "the", "opposite", "." ]
25ef95238a1e15d5640afa468bd300c80fc68298
https://github.com/arman000/delorean_lang/blob/25ef95238a1e15d5640afa468bd300c80fc68298/lib/delorean/engine.rb#L81-L88
train
arman000/delorean_lang
lib/delorean/engine.rb
Delorean.Engine.parse_call_attr
def parse_call_attr(node_name, attr_name) return [] if comp_set.member?(attr_name) # get the class associated with node klass = @pm.module_eval(node_name) # puts attr_name, "#{attr_name}#{POST}".to_sym, klass.methods.inspect begin klass.send("#{attr_name}#{POST}".to_sym, []) rescue NoMethodError err(UndefinedError, "'#{attr_name}' not defined in #{node_name}") end end
ruby
def parse_call_attr(node_name, attr_name) return [] if comp_set.member?(attr_name) # get the class associated with node klass = @pm.module_eval(node_name) # puts attr_name, "#{attr_name}#{POST}".to_sym, klass.methods.inspect begin klass.send("#{attr_name}#{POST}".to_sym, []) rescue NoMethodError err(UndefinedError, "'#{attr_name}' not defined in #{node_name}") end end
[ "def", "parse_call_attr", "(", "node_name", ",", "attr_name", ")", "return", "[", "]", "if", "comp_set", ".", "member?", "(", "attr_name", ")", "klass", "=", "@pm", ".", "module_eval", "(", "node_name", ")", "begin", "klass", ".", "send", "(", "\"#{attr_name}#{POST}\"", ".", "to_sym", ",", "[", "]", ")", "rescue", "NoMethodError", "err", "(", "UndefinedError", ",", "\"'#{attr_name}' not defined in #{node_name}\"", ")", "end", "end" ]
Parse-time check to see if attr is available. If not, error is raised.
[ "Parse", "-", "time", "check", "to", "see", "if", "attr", "is", "available", ".", "If", "not", "error", "is", "raised", "." ]
25ef95238a1e15d5640afa468bd300c80fc68298
https://github.com/arman000/delorean_lang/blob/25ef95238a1e15d5640afa468bd300c80fc68298/lib/delorean/engine.rb#L118-L131
train
arman000/delorean_lang
lib/delorean/engine.rb
Delorean.Engine.parse_define_attr
def parse_define_attr(name, spec) err(ParseError, "Can't define '#{name}' outside a node") unless @last_node err(RedefinedError, "Can't redefine '#{name}' in node #{@last_node}") if @node_attrs[@last_node].member? name @node_attrs[@last_node] << name checks = spec.map do |a| n = a.index('.') ? a : "#{@last_node}.#{a}" "_x.member?('#{n}') ? raise('#{n}') : #{a}#{POST}(_x + ['#{n}'])" end.join(';') code = "class #{@last_node}; def self.#{name}#{POST}(_x); #{checks}; end; end" # pp code @pm.module_eval(code) begin parse_call_attr(@last_node, name) rescue RuntimeError err(RecursionError, "'#{name}' is recursive") end end
ruby
def parse_define_attr(name, spec) err(ParseError, "Can't define '#{name}' outside a node") unless @last_node err(RedefinedError, "Can't redefine '#{name}' in node #{@last_node}") if @node_attrs[@last_node].member? name @node_attrs[@last_node] << name checks = spec.map do |a| n = a.index('.') ? a : "#{@last_node}.#{a}" "_x.member?('#{n}') ? raise('#{n}') : #{a}#{POST}(_x + ['#{n}'])" end.join(';') code = "class #{@last_node}; def self.#{name}#{POST}(_x); #{checks}; end; end" # pp code @pm.module_eval(code) begin parse_call_attr(@last_node, name) rescue RuntimeError err(RecursionError, "'#{name}' is recursive") end end
[ "def", "parse_define_attr", "(", "name", ",", "spec", ")", "err", "(", "ParseError", ",", "\"Can't define '#{name}' outside a node\"", ")", "unless", "@last_node", "err", "(", "RedefinedError", ",", "\"Can't redefine '#{name}' in node #{@last_node}\"", ")", "if", "@node_attrs", "[", "@last_node", "]", ".", "member?", "name", "@node_attrs", "[", "@last_node", "]", "<<", "name", "checks", "=", "spec", ".", "map", "do", "|", "a", "|", "n", "=", "a", ".", "index", "(", "'.'", ")", "?", "a", ":", "\"#{@last_node}.#{a}\"", "\"_x.member?('#{n}') ? raise('#{n}') : #{a}#{POST}(_x + ['#{n}'])\"", "end", ".", "join", "(", "';'", ")", "code", "=", "\"class #{@last_node}; def self.#{name}#{POST}(_x); #{checks}; end; end\"", "@pm", ".", "module_eval", "(", "code", ")", "begin", "parse_call_attr", "(", "@last_node", ",", "name", ")", "rescue", "RuntimeError", "err", "(", "RecursionError", ",", "\"'#{name}' is recursive\"", ")", "end", "end" ]
parse-time attr definition
[ "parse", "-", "time", "attr", "definition" ]
25ef95238a1e15d5640afa468bd300c80fc68298
https://github.com/arman000/delorean_lang/blob/25ef95238a1e15d5640afa468bd300c80fc68298/lib/delorean/engine.rb#L154-L180
train
arman000/delorean_lang
lib/delorean/engine.rb
Delorean.Engine.enumerate_params_by_node
def enumerate_params_by_node(node) attrs = enumerate_attrs_by_node(node) Set.new(attrs.select { |a| @param_set.include?(a) }) end
ruby
def enumerate_params_by_node(node) attrs = enumerate_attrs_by_node(node) Set.new(attrs.select { |a| @param_set.include?(a) }) end
[ "def", "enumerate_params_by_node", "(", "node", ")", "attrs", "=", "enumerate_attrs_by_node", "(", "node", ")", "Set", ".", "new", "(", "attrs", ".", "select", "{", "|", "a", "|", "@param_set", ".", "include?", "(", "a", ")", "}", ")", "end" ]
enumerate params by a single node
[ "enumerate", "params", "by", "a", "single", "node" ]
25ef95238a1e15d5640afa468bd300c80fc68298
https://github.com/arman000/delorean_lang/blob/25ef95238a1e15d5640afa468bd300c80fc68298/lib/delorean/engine.rb#L358-L361
train
siyegen/instrumentable
lib/instrumentable.rb
Instrumentable.ClassMethods.class_instrument_method
def class_instrument_method(klass, method_to_instrument, event_name, payload={}) class << klass; self; end.class_eval do Instrumentality.begin(self, method_to_instrument, event_name, payload) end end
ruby
def class_instrument_method(klass, method_to_instrument, event_name, payload={}) class << klass; self; end.class_eval do Instrumentality.begin(self, method_to_instrument, event_name, payload) end end
[ "def", "class_instrument_method", "(", "klass", ",", "method_to_instrument", ",", "event_name", ",", "payload", "=", "{", "}", ")", "class", "<<", "klass", ";", "self", ";", "end", ".", "class_eval", "do", "Instrumentality", ".", "begin", "(", "self", ",", "method_to_instrument", ",", "event_name", ",", "payload", ")", "end", "end" ]
Class implementation of +instrument_method+
[ "Class", "implementation", "of", "+", "instrument_method", "+" ]
9180a4661980e88f283dc8c424847f89fbeff2ae
https://github.com/siyegen/instrumentable/blob/9180a4661980e88f283dc8c424847f89fbeff2ae/lib/instrumentable.rb#L63-L67
train
code-and-effect/effective_regions
app/models/effective/region.rb
Effective.Region.snippet_objects
def snippet_objects(locals = {}) locals = {} unless locals.kind_of?(Hash) @snippet_objects ||= snippets.map do |key, snippet| # Key here is 'snippet_1' if snippet['class_name'] klass = "Effective::Snippets::#{snippet['class_name'].classify}".safe_constantize klass.new(snippet.merge!(locals).merge!(:region => self, :id => key)) if klass end end.compact end
ruby
def snippet_objects(locals = {}) locals = {} unless locals.kind_of?(Hash) @snippet_objects ||= snippets.map do |key, snippet| # Key here is 'snippet_1' if snippet['class_name'] klass = "Effective::Snippets::#{snippet['class_name'].classify}".safe_constantize klass.new(snippet.merge!(locals).merge!(:region => self, :id => key)) if klass end end.compact end
[ "def", "snippet_objects", "(", "locals", "=", "{", "}", ")", "locals", "=", "{", "}", "unless", "locals", ".", "kind_of?", "(", "Hash", ")", "@snippet_objects", "||=", "snippets", ".", "map", "do", "|", "key", ",", "snippet", "|", "if", "snippet", "[", "'class_name'", "]", "klass", "=", "\"Effective::Snippets::#{snippet['class_name'].classify}\"", ".", "safe_constantize", "klass", ".", "new", "(", "snippet", ".", "merge!", "(", "locals", ")", ".", "merge!", "(", ":region", "=>", "self", ",", ":id", "=>", "key", ")", ")", "if", "klass", "end", "end", ".", "compact", "end" ]
Hash of the Snippets objectified Returns a Hash of {'snippet_1' => CurrentUserInfo.new(snippets[:key]['options'])}
[ "Hash", "of", "the", "Snippets", "objectified" ]
c24fc30b5012420b81e7d156fd712590f23b9d0c
https://github.com/code-and-effect/effective_regions/blob/c24fc30b5012420b81e7d156fd712590f23b9d0c/app/models/effective/region.rb#L28-L36
train
blahah/biopsy
lib/biopsy/optimisers/tabu_search.rb
Biopsy.Distribution.draw
def draw r = @dist.rng.to_i raise "drawn number must be an integer" unless r.is_a? Integer # keep the value inside the allowed range r = 0 - r if r < 0 if r >= @range.size diff = 1 + r - @range.size r = @range.size - diff end @range[r] end
ruby
def draw r = @dist.rng.to_i raise "drawn number must be an integer" unless r.is_a? Integer # keep the value inside the allowed range r = 0 - r if r < 0 if r >= @range.size diff = 1 + r - @range.size r = @range.size - diff end @range[r] end
[ "def", "draw", "r", "=", "@dist", ".", "rng", ".", "to_i", "raise", "\"drawn number must be an integer\"", "unless", "r", ".", "is_a?", "Integer", "r", "=", "0", "-", "r", "if", "r", "<", "0", "if", "r", ">=", "@range", ".", "size", "diff", "=", "1", "+", "r", "-", "@range", ".", "size", "r", "=", "@range", ".", "size", "-", "diff", "end", "@range", "[", "r", "]", "end" ]
draw from the distribution
[ "draw", "from", "the", "distribution" ]
e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2
https://github.com/blahah/biopsy/blob/e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2/lib/biopsy/optimisers/tabu_search.rb#L69-L79
train
blahah/biopsy
lib/biopsy/optimisers/tabu_search.rb
Biopsy.Hood.generate_neighbour
def generate_neighbour n = 0 begin if n >= 100 # taking too long to generate a neighbour, # loosen the neighbourhood structure so we explore further # debug("loosening distributions") @distributions.each do |param, dist| dist.loosen end end # preform the probabilistic step move for each parameter neighbour = Hash[@distributions.map { |param, dist| [param, dist.draw] }] n += 1 end while self.is_tabu?(neighbour) @tabu << neighbour @members << neighbour end
ruby
def generate_neighbour n = 0 begin if n >= 100 # taking too long to generate a neighbour, # loosen the neighbourhood structure so we explore further # debug("loosening distributions") @distributions.each do |param, dist| dist.loosen end end # preform the probabilistic step move for each parameter neighbour = Hash[@distributions.map { |param, dist| [param, dist.draw] }] n += 1 end while self.is_tabu?(neighbour) @tabu << neighbour @members << neighbour end
[ "def", "generate_neighbour", "n", "=", "0", "begin", "if", "n", ">=", "100", "@distributions", ".", "each", "do", "|", "param", ",", "dist", "|", "dist", ".", "loosen", "end", "end", "neighbour", "=", "Hash", "[", "@distributions", ".", "map", "{", "|", "param", ",", "dist", "|", "[", "param", ",", "dist", ".", "draw", "]", "}", "]", "n", "+=", "1", "end", "while", "self", ".", "is_tabu?", "(", "neighbour", ")", "@tabu", "<<", "neighbour", "@members", "<<", "neighbour", "end" ]
generate a single neighbour
[ "generate", "a", "single", "neighbour" ]
e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2
https://github.com/blahah/biopsy/blob/e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2/lib/biopsy/optimisers/tabu_search.rb#L107-L124
train
blahah/biopsy
lib/biopsy/optimisers/tabu_search.rb
Biopsy.TabuSearch.update_neighbourhood_structure
def update_neighbourhood_structure self.update_recent_scores best = self.backtrack_or_continue unless @distributions.empty? @standard_deviations = Hash[@distributions.map { |k, d| [k, d.sd] }] end best[:parameters].each_pair do |param, value| self.update_distribution(param, value) end end
ruby
def update_neighbourhood_structure self.update_recent_scores best = self.backtrack_or_continue unless @distributions.empty? @standard_deviations = Hash[@distributions.map { |k, d| [k, d.sd] }] end best[:parameters].each_pair do |param, value| self.update_distribution(param, value) end end
[ "def", "update_neighbourhood_structure", "self", ".", "update_recent_scores", "best", "=", "self", ".", "backtrack_or_continue", "unless", "@distributions", ".", "empty?", "@standard_deviations", "=", "Hash", "[", "@distributions", ".", "map", "{", "|", "k", ",", "d", "|", "[", "k", ",", "d", ".", "sd", "]", "}", "]", "end", "best", "[", ":parameters", "]", ".", "each_pair", "do", "|", "param", ",", "value", "|", "self", ".", "update_distribution", "(", "param", ",", "value", ")", "end", "end" ]
update the neighbourhood structure by adjusting the probability distributions according to total performance of each parameter
[ "update", "the", "neighbourhood", "structure", "by", "adjusting", "the", "probability", "distributions", "according", "to", "total", "performance", "of", "each", "parameter" ]
e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2
https://github.com/blahah/biopsy/blob/e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2/lib/biopsy/optimisers/tabu_search.rb#L310-L319
train
blahah/biopsy
lib/biopsy/optimisers/tabu_search.rb
Biopsy.TabuSearch.backtrack_or_continue
def backtrack_or_continue best = nil if (@iterations_since_best / @backtracks) >= @backtrack_cutoff * @max_hood_size self.backtrack best = @best else best = @current_hood.best self.adjust_distributions_using_gradient end if best[:parameters].nil? # this should never happen! best = @best end best end
ruby
def backtrack_or_continue best = nil if (@iterations_since_best / @backtracks) >= @backtrack_cutoff * @max_hood_size self.backtrack best = @best else best = @current_hood.best self.adjust_distributions_using_gradient end if best[:parameters].nil? # this should never happen! best = @best end best end
[ "def", "backtrack_or_continue", "best", "=", "nil", "if", "(", "@iterations_since_best", "/", "@backtracks", ")", ">=", "@backtrack_cutoff", "*", "@max_hood_size", "self", ".", "backtrack", "best", "=", "@best", "else", "best", "=", "@current_hood", ".", "best", "self", ".", "adjust_distributions_using_gradient", "end", "if", "best", "[", ":parameters", "]", ".", "nil?", "best", "=", "@best", "end", "best", "end" ]
return the correct 'best' location to form a new neighbourhood around deciding whether to continue progressing from the current location or to backtrack to a previous good location to explore further
[ "return", "the", "correct", "best", "location", "to", "form", "a", "new", "neighbourhood", "around", "deciding", "whether", "to", "continue", "progressing", "from", "the", "current", "location", "or", "to", "backtrack", "to", "a", "previous", "good", "location", "to", "explore", "further" ]
e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2
https://github.com/blahah/biopsy/blob/e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2/lib/biopsy/optimisers/tabu_search.rb#L341-L355
train
blahah/biopsy
lib/biopsy/optimisers/tabu_search.rb
Biopsy.TabuSearch.adjust_distributions_using_gradient
def adjust_distributions_using_gradient return if @recent_scores.length < 3 vx = (1..@recent_scores.length).to_a.to_numeric vy = @recent_scores.reverse.to_numeric r = Statsample::Regression::Simple.new_from_vectors(vx,vy) slope = r.b if slope > 0 @distributions.each_pair { |k, d| d.tighten slope } elsif slope < 0 @distributions.each_pair { |k, d| d.loosen slope } end end
ruby
def adjust_distributions_using_gradient return if @recent_scores.length < 3 vx = (1..@recent_scores.length).to_a.to_numeric vy = @recent_scores.reverse.to_numeric r = Statsample::Regression::Simple.new_from_vectors(vx,vy) slope = r.b if slope > 0 @distributions.each_pair { |k, d| d.tighten slope } elsif slope < 0 @distributions.each_pair { |k, d| d.loosen slope } end end
[ "def", "adjust_distributions_using_gradient", "return", "if", "@recent_scores", ".", "length", "<", "3", "vx", "=", "(", "1", "..", "@recent_scores", ".", "length", ")", ".", "to_a", ".", "to_numeric", "vy", "=", "@recent_scores", ".", "reverse", ".", "to_numeric", "r", "=", "Statsample", "::", "Regression", "::", "Simple", ".", "new_from_vectors", "(", "vx", ",", "vy", ")", "slope", "=", "r", ".", "b", "if", "slope", ">", "0", "@distributions", ".", "each_pair", "{", "|", "k", ",", "d", "|", "d", ".", "tighten", "slope", "}", "elsif", "slope", "<", "0", "@distributions", ".", "each_pair", "{", "|", "k", ",", "d", "|", "d", ".", "loosen", "slope", "}", "end", "end" ]
use the gradient of recent best scores to update the distributions
[ "use", "the", "gradient", "of", "recent", "best", "scores", "to", "update", "the", "distributions" ]
e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2
https://github.com/blahah/biopsy/blob/e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2/lib/biopsy/optimisers/tabu_search.rb#L369-L380
train
blahah/biopsy
lib/biopsy/optimisers/tabu_search.rb
Biopsy.TabuSearch.finished?
def finished? return false unless @threads.all? do |t| t.recent_scores.size == @jump_cutoff end probabilities = self.recent_scores_combination_test n_significant = 0 probabilities.each do |mann_u, levene| if mann_u <= @adjusted_alpha && levene <= @convergence_alpha n_significant += 1 end end finish = n_significant >= probabilities.size * 0.5 end
ruby
def finished? return false unless @threads.all? do |t| t.recent_scores.size == @jump_cutoff end probabilities = self.recent_scores_combination_test n_significant = 0 probabilities.each do |mann_u, levene| if mann_u <= @adjusted_alpha && levene <= @convergence_alpha n_significant += 1 end end finish = n_significant >= probabilities.size * 0.5 end
[ "def", "finished?", "return", "false", "unless", "@threads", ".", "all?", "do", "|", "t", "|", "t", ".", "recent_scores", ".", "size", "==", "@jump_cutoff", "end", "probabilities", "=", "self", ".", "recent_scores_combination_test", "n_significant", "=", "0", "probabilities", ".", "each", "do", "|", "mann_u", ",", "levene", "|", "if", "mann_u", "<=", "@adjusted_alpha", "&&", "levene", "<=", "@convergence_alpha", "n_significant", "+=", "1", "end", "end", "finish", "=", "n_significant", ">=", "probabilities", ".", "size", "*", "0.5", "end" ]
check termination conditions and return true if met
[ "check", "termination", "conditions", "and", "return", "true", "if", "met" ]
e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2
https://github.com/blahah/biopsy/blob/e46f3d1c75de4da2ec47a377f7e4f0e16a8e03d2/lib/biopsy/optimisers/tabu_search.rb#L403-L415
train
lautis/sweet_notifications
lib/sweet_notifications/railtie.rb
SweetNotifications.Railtie.initialize_rails
def initialize_rails(name, log_subscriber, controller_runtime) log_subscriber.attach_to name.to_sym ActiveSupport.on_load(:action_controller) do include controller_runtime end end
ruby
def initialize_rails(name, log_subscriber, controller_runtime) log_subscriber.attach_to name.to_sym ActiveSupport.on_load(:action_controller) do include controller_runtime end end
[ "def", "initialize_rails", "(", "name", ",", "log_subscriber", ",", "controller_runtime", ")", "log_subscriber", ".", "attach_to", "name", ".", "to_sym", "ActiveSupport", ".", "on_load", "(", ":action_controller", ")", "do", "include", "controller_runtime", "end", "end" ]
Attach LogSubscriber and ControllerRuntime to a notifications namespace @param name [Symbol] Notifications namespace @param log_subscriber [LogSubscriber] subscriber to be attached @param controller_runtime [Module] mixin that logs runtime
[ "Attach", "LogSubscriber", "and", "ControllerRuntime", "to", "a", "notifications", "namespace" ]
fcd137a1b474d24e1bc86619d116fc32caba8c19
https://github.com/lautis/sweet_notifications/blob/fcd137a1b474d24e1bc86619d116fc32caba8c19/lib/sweet_notifications/railtie.rb#L12-L17
train
lautis/sweet_notifications
lib/sweet_notifications/railtie.rb
SweetNotifications.Railtie.railtie
def railtie(name, log_subscriber, controller_runtime) Class.new(Rails::Railtie) do railtie_name name initializer "#{name}.notifications" do SweetNotifications::Railtie.initialize_rails(name, log_subscriber, controller_runtime) end end end
ruby
def railtie(name, log_subscriber, controller_runtime) Class.new(Rails::Railtie) do railtie_name name initializer "#{name}.notifications" do SweetNotifications::Railtie.initialize_rails(name, log_subscriber, controller_runtime) end end end
[ "def", "railtie", "(", "name", ",", "log_subscriber", ",", "controller_runtime", ")", "Class", ".", "new", "(", "Rails", "::", "Railtie", ")", "do", "railtie_name", "name", "initializer", "\"#{name}.notifications\"", "do", "SweetNotifications", "::", "Railtie", ".", "initialize_rails", "(", "name", ",", "log_subscriber", ",", "controller_runtime", ")", "end", "end", "end" ]
Create a Railtie for LogSubscriber and ControllerRuntime mixin @param name [Symbol] Notifications namespace @param log_subscriber [LogSubscriber] subscriber to be attached @param controller_runtime [Module] mixin that logs runtime @return [Rails::Railtie] Rails initializer
[ "Create", "a", "Railtie", "for", "LogSubscriber", "and", "ControllerRuntime", "mixin" ]
fcd137a1b474d24e1bc86619d116fc32caba8c19
https://github.com/lautis/sweet_notifications/blob/fcd137a1b474d24e1bc86619d116fc32caba8c19/lib/sweet_notifications/railtie.rb#L25-L34
train
sinefunc/lunar
lib/lunar/result_set.rb
Lunar.ResultSet.sort
def sort(opts = {}) return [] if not distkey opts[:by] = sortables[opts[:by]] if opts[:by] if opts[:start] && opts[:limit] opts[:limit] = [opts[:start], opts[:limit]] end objects(distkey.sort(opts)) end
ruby
def sort(opts = {}) return [] if not distkey opts[:by] = sortables[opts[:by]] if opts[:by] if opts[:start] && opts[:limit] opts[:limit] = [opts[:start], opts[:limit]] end objects(distkey.sort(opts)) end
[ "def", "sort", "(", "opts", "=", "{", "}", ")", "return", "[", "]", "if", "not", "distkey", "opts", "[", ":by", "]", "=", "sortables", "[", "opts", "[", ":by", "]", "]", "if", "opts", "[", ":by", "]", "if", "opts", "[", ":start", "]", "&&", "opts", "[", ":limit", "]", "opts", "[", ":limit", "]", "=", "[", "opts", "[", ":start", "]", ",", "opts", "[", ":limit", "]", "]", "end", "objects", "(", "distkey", ".", "sort", "(", "opts", ")", ")", "end" ]
Gives the ability to sort the search results via a `sortable` field in your index. @example Lunar.index Gadget do |i| i.id 1001 i.text :title, "Apple Macbook Pro" i.sortable :votes, 10 end Lunar.index Gadget do |i| i.id 1002 i.text :title, "Apple iPad" i.sortable :votes, 50 end results = Lunar.search(Gadget, :q => "apple") sorted = results.sort(:by => :votes, :order => "DESC") sorted == [Gadget[1002], Gadget[1001]] # => true @param [Hash] opts the various opts to pass to Redis SORT command. @option opts [#to_s] :by the field in the namespace you want to sort by. @option opts [#to_s] :order the direction you want to sort i.e. ASC DESC ALPHA @option opts [Array] :limit offset and max results to return. @return [Array] Array of objects as defined by the `finder`. @see http://code.google.com/p/redis/wiki/SortCommand
[ "Gives", "the", "ability", "to", "sort", "the", "search", "results", "via", "a", "sortable", "field", "in", "your", "index", "." ]
efc58f392dd75e771d313eef6cd4ada0d1ac02ff
https://github.com/sinefunc/lunar/blob/efc58f392dd75e771d313eef6cd4ada0d1ac02ff/lib/lunar/result_set.rb#L90-L100
train
scepticulous/crypto-toolbox
lib/crypto-toolbox/crypt_buffer/concerns/padding.rb
CryptBufferConcern.Padding.padding
def padding last = bytes.last subset = subset_padding if subset.all?{|e| e == last } self.class.new(subset) else self.class.new([]) end end
ruby
def padding last = bytes.last subset = subset_padding if subset.all?{|e| e == last } self.class.new(subset) else self.class.new([]) end end
[ "def", "padding", "last", "=", "bytes", ".", "last", "subset", "=", "subset_padding", "if", "subset", ".", "all?", "{", "|", "e", "|", "e", "==", "last", "}", "self", ".", "class", ".", "new", "(", "subset", ")", "else", "self", ".", "class", ".", "new", "(", "[", "]", ")", "end", "end" ]
Return any existing padding
[ "Return", "any", "existing", "padding" ]
cdbe371109e497db2c2af5c1fe0f359612f44816
https://github.com/scepticulous/crypto-toolbox/blob/cdbe371109e497db2c2af5c1fe0f359612f44816/lib/crypto-toolbox/crypt_buffer/concerns/padding.rb#L16-L25
train
scepticulous/crypto-toolbox
lib/crypto-toolbox/crypt_buffer/concerns/padding.rb
CryptBufferConcern.Padding.strip_padding
def strip_padding subset = bytes if padding? pad = padding len = pad.length subset = bytes[0,bytes.length - len] end self.class.new(subset) end
ruby
def strip_padding subset = bytes if padding? pad = padding len = pad.length subset = bytes[0,bytes.length - len] end self.class.new(subset) end
[ "def", "strip_padding", "subset", "=", "bytes", "if", "padding?", "pad", "=", "padding", "len", "=", "pad", ".", "length", "subset", "=", "bytes", "[", "0", ",", "bytes", ".", "length", "-", "len", "]", "end", "self", ".", "class", ".", "new", "(", "subset", ")", "end" ]
Strip the existing padding if present
[ "Strip", "the", "existing", "padding", "if", "present" ]
cdbe371109e497db2c2af5c1fe0f359612f44816
https://github.com/scepticulous/crypto-toolbox/blob/cdbe371109e497db2c2af5c1fe0f359612f44816/lib/crypto-toolbox/crypt_buffer/concerns/padding.rb#L28-L37
train
thinkerbot/configurable
lib/configurable/conversions.rb
Configurable.Conversions.to_parser
def to_parser(*args, &block) parser = ConfigParser.new(*args, &block) traverse do |nesting, config| next if config[:hidden] == true || nesting.any? {|nest| nest[:hidden] == true } nest_keys = nesting.collect {|nest| nest.key } long, short = nesting.collect {|nest| nest.name }.push(config.name).join(':'), nil long, short = short, long if long.length == 1 guess_attrs = { :long => long, :short => short } config_attrs = { :key => config.key, :nest_keys => nest_keys, :default => config.default, :callback => lambda {|value| config.type.cast(value) } } attrs = guess_attrs.merge(config.metadata).merge(config_attrs) parser.on(attrs) end parser.sort_opts! parser end
ruby
def to_parser(*args, &block) parser = ConfigParser.new(*args, &block) traverse do |nesting, config| next if config[:hidden] == true || nesting.any? {|nest| nest[:hidden] == true } nest_keys = nesting.collect {|nest| nest.key } long, short = nesting.collect {|nest| nest.name }.push(config.name).join(':'), nil long, short = short, long if long.length == 1 guess_attrs = { :long => long, :short => short } config_attrs = { :key => config.key, :nest_keys => nest_keys, :default => config.default, :callback => lambda {|value| config.type.cast(value) } } attrs = guess_attrs.merge(config.metadata).merge(config_attrs) parser.on(attrs) end parser.sort_opts! parser end
[ "def", "to_parser", "(", "*", "args", ",", "&", "block", ")", "parser", "=", "ConfigParser", ".", "new", "(", "*", "args", ",", "&", "block", ")", "traverse", "do", "|", "nesting", ",", "config", "|", "next", "if", "config", "[", ":hidden", "]", "==", "true", "||", "nesting", ".", "any?", "{", "|", "nest", "|", "nest", "[", ":hidden", "]", "==", "true", "}", "nest_keys", "=", "nesting", ".", "collect", "{", "|", "nest", "|", "nest", ".", "key", "}", "long", ",", "short", "=", "nesting", ".", "collect", "{", "|", "nest", "|", "nest", ".", "name", "}", ".", "push", "(", "config", ".", "name", ")", ".", "join", "(", "':'", ")", ",", "nil", "long", ",", "short", "=", "short", ",", "long", "if", "long", ".", "length", "==", "1", "guess_attrs", "=", "{", ":long", "=>", "long", ",", ":short", "=>", "short", "}", "config_attrs", "=", "{", ":key", "=>", "config", ".", "key", ",", ":nest_keys", "=>", "nest_keys", ",", ":default", "=>", "config", ".", "default", ",", ":callback", "=>", "lambda", "{", "|", "value", "|", "config", ".", "type", ".", "cast", "(", "value", ")", "}", "}", "attrs", "=", "guess_attrs", ".", "merge", "(", "config", ".", "metadata", ")", ".", "merge", "(", "config_attrs", ")", "parser", ".", "on", "(", "attrs", ")", "end", "parser", ".", "sort_opts!", "parser", "end" ]
Initializes and returns a ConfigParser generated using the configs for self. Arguments given to parser are passed to the ConfigParser initializer.
[ "Initializes", "and", "returns", "a", "ConfigParser", "generated", "using", "the", "configs", "for", "self", ".", "Arguments", "given", "to", "parser", "are", "passed", "to", "the", "ConfigParser", "initializer", "." ]
43c611f767f14194827b1fe31bc72c8bdf54efdf
https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/conversions.rb#L14-L41
train
thinkerbot/configurable
lib/configurable/conversions.rb
Configurable.Conversions.to_default
def to_default default = {} each_pair do |key, config| default[key] = config.default end default end
ruby
def to_default default = {} each_pair do |key, config| default[key] = config.default end default end
[ "def", "to_default", "default", "=", "{", "}", "each_pair", "do", "|", "key", ",", "config", "|", "default", "[", "key", "]", "=", "config", ".", "default", "end", "default", "end" ]
Returns a hash of the default values for each config in self.
[ "Returns", "a", "hash", "of", "the", "default", "values", "for", "each", "config", "in", "self", "." ]
43c611f767f14194827b1fe31bc72c8bdf54efdf
https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/conversions.rb#L44-L50
train
thinkerbot/configurable
lib/configurable/conversions.rb
Configurable.Conversions.traverse
def traverse(nesting=[], &block) each_value do |config| if config.type.kind_of?(NestType) nesting.push config configs = config.type.configurable.class.configs configs.traverse(nesting, &block) nesting.pop else yield(nesting, config) end end end
ruby
def traverse(nesting=[], &block) each_value do |config| if config.type.kind_of?(NestType) nesting.push config configs = config.type.configurable.class.configs configs.traverse(nesting, &block) nesting.pop else yield(nesting, config) end end end
[ "def", "traverse", "(", "nesting", "=", "[", "]", ",", "&", "block", ")", "each_value", "do", "|", "config", "|", "if", "config", ".", "type", ".", "kind_of?", "(", "NestType", ")", "nesting", ".", "push", "config", "configs", "=", "config", ".", "type", ".", "configurable", ".", "class", ".", "configs", "configs", ".", "traverse", "(", "nesting", ",", "&", "block", ")", "nesting", ".", "pop", "else", "yield", "(", "nesting", ",", "config", ")", "end", "end", "end" ]
Yields each config in configs to the block with nesting, after appened self to nesting.
[ "Yields", "each", "config", "in", "configs", "to", "the", "block", "with", "nesting", "after", "appened", "self", "to", "nesting", "." ]
43c611f767f14194827b1fe31bc72c8bdf54efdf
https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/conversions.rb#L78-L89
train
ArchimediaZerogroup/KonoUtils
lib/kono_utils/tmp_file.rb
KonoUtils.TmpFile.clean_tmpdir
def clean_tmpdir self.root_dir.each do |d| if d != '..' and d!='.' if d.to_i < Time.now.to_i-TIME_LIMIT FileUtils.rm_rf(File.join(self.root_dir.path, d)) end end end end
ruby
def clean_tmpdir self.root_dir.each do |d| if d != '..' and d!='.' if d.to_i < Time.now.to_i-TIME_LIMIT FileUtils.rm_rf(File.join(self.root_dir.path, d)) end end end end
[ "def", "clean_tmpdir", "self", ".", "root_dir", ".", "each", "do", "|", "d", "|", "if", "d", "!=", "'..'", "and", "d!", "=", "'.'", "if", "d", ".", "to_i", "<", "Time", ".", "now", ".", "to_i", "-", "TIME_LIMIT", "FileUtils", ".", "rm_rf", "(", "File", ".", "join", "(", "self", ".", "root_dir", ".", "path", ",", "d", ")", ")", "end", "end", "end", "end" ]
Clean the directory
[ "Clean", "the", "directory" ]
a255a30b65e4e0f01cd6236d991da4fd13c64fc6
https://github.com/ArchimediaZerogroup/KonoUtils/blob/a255a30b65e4e0f01cd6236d991da4fd13c64fc6/lib/kono_utils/tmp_file.rb#L70-L78
train
cantino/guess_html_encoding
lib/guess_html_encoding.rb
GuessHtmlEncoding.HTMLScanner.charset_from_meta_content
def charset_from_meta_content(string) charset_match = string.match(/charset\s*\=\s*(.+)/i) if charset_match charset_value = charset_match[1] charset_value[/\A\"(.*)\"/, 1] || charset_value[/\A\'(.*)\'/, 1] || charset_value[/(.*)[\s;]/, 1] || charset_value[/(.*)/, 1] else nil end end
ruby
def charset_from_meta_content(string) charset_match = string.match(/charset\s*\=\s*(.+)/i) if charset_match charset_value = charset_match[1] charset_value[/\A\"(.*)\"/, 1] || charset_value[/\A\'(.*)\'/, 1] || charset_value[/(.*)[\s;]/, 1] || charset_value[/(.*)/, 1] else nil end end
[ "def", "charset_from_meta_content", "(", "string", ")", "charset_match", "=", "string", ".", "match", "(", "/", "\\s", "\\=", "\\s", "/i", ")", "if", "charset_match", "charset_value", "=", "charset_match", "[", "1", "]", "charset_value", "[", "/", "\\A", "\\\"", "\\\"", "/", ",", "1", "]", "||", "charset_value", "[", "/", "\\A", "\\'", "\\'", "/", ",", "1", "]", "||", "charset_value", "[", "/", "\\s", "/", ",", "1", "]", "||", "charset_value", "[", "/", "/", ",", "1", "]", "else", "nil", "end", "end" ]
Given a string representing the 'content' attribute value of a meta tag with an `http-equiv` attribute, returns the charset specified within that value, or nil.
[ "Given", "a", "string", "representing", "the", "content", "attribute", "value", "of", "a", "meta", "tag", "with", "an", "http", "-", "equiv", "attribute", "returns", "the", "charset", "specified", "within", "that", "value", "or", "nil", "." ]
a908233b20b7f3c602cb5b2a7fb57fd3b905f264
https://github.com/cantino/guess_html_encoding/blob/a908233b20b7f3c602cb5b2a7fb57fd3b905f264/lib/guess_html_encoding.rb#L180-L196
train
cantino/guess_html_encoding
lib/guess_html_encoding.rb
GuessHtmlEncoding.HTMLScanner.attribute_value
def attribute_value(string) attribute_value = '' position = 0 length = string.length while position < length # x09 (ASCII TAB), 0x0A (ASCII LF), 0x0C (ASCII FF), 0x0D (ASCII CR), or 0x20 (ASCII space) then advance position to the next byte, then, repeat this step. if string[position] =~ /[\u{09}\u{0A}\u{0C}\u{0D}\u{20}]/ position += 1 elsif string[position] =~ /['"]/ attribute_value, position = quoted_value(string[position, length]) break elsif string[position] == '>' position += 1 break else attribute_value, position = unquoted_value(string[position, length]) break end end [attribute_value, position] end
ruby
def attribute_value(string) attribute_value = '' position = 0 length = string.length while position < length # x09 (ASCII TAB), 0x0A (ASCII LF), 0x0C (ASCII FF), 0x0D (ASCII CR), or 0x20 (ASCII space) then advance position to the next byte, then, repeat this step. if string[position] =~ /[\u{09}\u{0A}\u{0C}\u{0D}\u{20}]/ position += 1 elsif string[position] =~ /['"]/ attribute_value, position = quoted_value(string[position, length]) break elsif string[position] == '>' position += 1 break else attribute_value, position = unquoted_value(string[position, length]) break end end [attribute_value, position] end
[ "def", "attribute_value", "(", "string", ")", "attribute_value", "=", "''", "position", "=", "0", "length", "=", "string", ".", "length", "while", "position", "<", "length", "if", "string", "[", "position", "]", "=~", "/", "\\u{09}", "\\u{0A}", "\\u{0C}", "\\u{0D}", "\\u{20}", "/", "position", "+=", "1", "elsif", "string", "[", "position", "]", "=~", "/", "/", "attribute_value", ",", "position", "=", "quoted_value", "(", "string", "[", "position", ",", "length", "]", ")", "break", "elsif", "string", "[", "position", "]", "==", "'>'", "position", "+=", "1", "break", "else", "attribute_value", ",", "position", "=", "unquoted_value", "(", "string", "[", "position", ",", "length", "]", ")", "break", "end", "end", "[", "attribute_value", ",", "position", "]", "end" ]
Given a string, this returns the attribute value from the start of the string, and the position of the following character in the string
[ "Given", "a", "string", "this", "returns", "the", "attribute", "value", "from", "the", "start", "of", "the", "string", "and", "the", "position", "of", "the", "following", "character", "in", "the", "string" ]
a908233b20b7f3c602cb5b2a7fb57fd3b905f264
https://github.com/cantino/guess_html_encoding/blob/a908233b20b7f3c602cb5b2a7fb57fd3b905f264/lib/guess_html_encoding.rb#L266-L295
train
stuart/oqgraph_rails
lib/oqgraph/node.rb
OQGraph.Node.create_edge_to_and_from
def create_edge_to_and_from(other, weight = 1.0) self.class.edge_class.create!(:from_id => id, :to_id => other.id, :weight => weight) self.class.edge_class.create!(:from_id => other.id, :to_id => id, :weight => weight) end
ruby
def create_edge_to_and_from(other, weight = 1.0) self.class.edge_class.create!(:from_id => id, :to_id => other.id, :weight => weight) self.class.edge_class.create!(:from_id => other.id, :to_id => id, :weight => weight) end
[ "def", "create_edge_to_and_from", "(", "other", ",", "weight", "=", "1.0", ")", "self", ".", "class", ".", "edge_class", ".", "create!", "(", ":from_id", "=>", "id", ",", ":to_id", "=>", "other", ".", "id", ",", ":weight", "=>", "weight", ")", "self", ".", "class", ".", "edge_class", ".", "create!", "(", ":from_id", "=>", "other", ".", "id", ",", ":to_id", "=>", "id", ",", ":weight", "=>", "weight", ")", "end" ]
+other+ graph node to edge to +weight+ positive float denoting edge weight Creates a two way edge between this node and another.
[ "+", "other", "+", "graph", "node", "to", "edge", "to", "+", "weight", "+", "positive", "float", "denoting", "edge", "weight", "Creates", "a", "two", "way", "edge", "between", "this", "node", "and", "another", "." ]
836ccbe770d357f30d71ec30b1dfd5f267624883
https://github.com/stuart/oqgraph_rails/blob/836ccbe770d357f30d71ec30b1dfd5f267624883/lib/oqgraph/node.rb#L56-L59
train
stuart/oqgraph_rails
lib/oqgraph/node.rb
OQGraph.Node.path_weight_to
def path_weight_to(other) shortest_path_to(other,:method => :djikstra).map{|edge| edge.weight.to_f}.sum end
ruby
def path_weight_to(other) shortest_path_to(other,:method => :djikstra).map{|edge| edge.weight.to_f}.sum end
[ "def", "path_weight_to", "(", "other", ")", "shortest_path_to", "(", "other", ",", ":method", "=>", ":djikstra", ")", ".", "map", "{", "|", "edge", "|", "edge", ".", "weight", ".", "to_f", "}", ".", "sum", "end" ]
+other+ The target node to find a route to Gives the path weight as a float of the shortest path to the other
[ "+", "other", "+", "The", "target", "node", "to", "find", "a", "route", "to", "Gives", "the", "path", "weight", "as", "a", "float", "of", "the", "shortest", "path", "to", "the", "other" ]
836ccbe770d357f30d71ec30b1dfd5f267624883
https://github.com/stuart/oqgraph_rails/blob/836ccbe770d357f30d71ec30b1dfd5f267624883/lib/oqgraph/node.rb#L74-L76
train
shanebdavis/gui_geometry
lib/gui_geometry/rectangle.rb
GuiGeo.Rectangle.bound
def bound(val) case val when Rectangle then r = val.clone r.size = r.size.min(size) r.loc = r.loc.bound(loc, loc + size - val.size) r when Point then (val-loc).bound(point, size) + loc else raise ArgumentError.new("wrong type: (#{val.class}) - Rectangle or Point expected") end end
ruby
def bound(val) case val when Rectangle then r = val.clone r.size = r.size.min(size) r.loc = r.loc.bound(loc, loc + size - val.size) r when Point then (val-loc).bound(point, size) + loc else raise ArgumentError.new("wrong type: (#{val.class}) - Rectangle or Point expected") end end
[ "def", "bound", "(", "val", ")", "case", "val", "when", "Rectangle", "then", "r", "=", "val", ".", "clone", "r", ".", "size", "=", "r", ".", "size", ".", "min", "(", "size", ")", "r", ".", "loc", "=", "r", ".", "loc", ".", "bound", "(", "loc", ",", "loc", "+", "size", "-", "val", ".", "size", ")", "r", "when", "Point", "then", "(", "val", "-", "loc", ")", ".", "bound", "(", "point", ",", "size", ")", "+", "loc", "else", "raise", "ArgumentError", ".", "new", "(", "\"wrong type: (#{val.class}) - Rectangle or Point expected\"", ")", "end", "end" ]
val can be a Rectangle or Point returns a Rectangle or Point that is within this Rectangle For Rectangles, the size is only changed if it has to be
[ "val", "can", "be", "a", "Rectangle", "or", "Point", "returns", "a", "Rectangle", "or", "Point", "that", "is", "within", "this", "Rectangle", "For", "Rectangles", "the", "size", "is", "only", "changed", "if", "it", "has", "to", "be" ]
ed0688f7484a31435063c0fa1895ddaf3900d959
https://github.com/shanebdavis/gui_geometry/blob/ed0688f7484a31435063c0fa1895ddaf3900d959/lib/gui_geometry/rectangle.rb#L33-L43
train
shanebdavis/gui_geometry
lib/gui_geometry/rectangle.rb
GuiGeo.Rectangle.disjoint
def disjoint(b) return self if !b || contains(b) return b if b.contains(self) return self,b unless overlaps?(b) tl_contained = contains?(b.tl) ? 1 : 0 tr_contained = contains?(b.tr) ? 1 : 0 bl_contained = contains?(b.bl) ? 1 : 0 br_contained = contains?(b.br) ? 1 : 0 sum = tl_contained + tr_contained + bl_contained + br_contained case sum when 0 # rectangles form a plus "+" if b.y < self.y r1,r2 = b,self else r1,r2 = self,b end tl1 = r1.tl br1 = point(r1.right, r2.top) tl2 = point(r1.left, r2.bottom) br2 = r1.br [ r2, rect(tl1,br1-tl1), rect(tl2,br2-tl2), ] when 1 when 2 else raise "internal error in disjoint - cases 3 and 4 should be taken care of by the return-tests at the top of the method" end end
ruby
def disjoint(b) return self if !b || contains(b) return b if b.contains(self) return self,b unless overlaps?(b) tl_contained = contains?(b.tl) ? 1 : 0 tr_contained = contains?(b.tr) ? 1 : 0 bl_contained = contains?(b.bl) ? 1 : 0 br_contained = contains?(b.br) ? 1 : 0 sum = tl_contained + tr_contained + bl_contained + br_contained case sum when 0 # rectangles form a plus "+" if b.y < self.y r1,r2 = b,self else r1,r2 = self,b end tl1 = r1.tl br1 = point(r1.right, r2.top) tl2 = point(r1.left, r2.bottom) br2 = r1.br [ r2, rect(tl1,br1-tl1), rect(tl2,br2-tl2), ] when 1 when 2 else raise "internal error in disjoint - cases 3 and 4 should be taken care of by the return-tests at the top of the method" end end
[ "def", "disjoint", "(", "b", ")", "return", "self", "if", "!", "b", "||", "contains", "(", "b", ")", "return", "b", "if", "b", ".", "contains", "(", "self", ")", "return", "self", ",", "b", "unless", "overlaps?", "(", "b", ")", "tl_contained", "=", "contains?", "(", "b", ".", "tl", ")", "?", "1", ":", "0", "tr_contained", "=", "contains?", "(", "b", ".", "tr", ")", "?", "1", ":", "0", "bl_contained", "=", "contains?", "(", "b", ".", "bl", ")", "?", "1", ":", "0", "br_contained", "=", "contains?", "(", "b", ".", "br", ")", "?", "1", ":", "0", "sum", "=", "tl_contained", "+", "tr_contained", "+", "bl_contained", "+", "br_contained", "case", "sum", "when", "0", "if", "b", ".", "y", "<", "self", ".", "y", "r1", ",", "r2", "=", "b", ",", "self", "else", "r1", ",", "r2", "=", "self", ",", "b", "end", "tl1", "=", "r1", ".", "tl", "br1", "=", "point", "(", "r1", ".", "right", ",", "r2", ".", "top", ")", "tl2", "=", "point", "(", "r1", ".", "left", ",", "r2", ".", "bottom", ")", "br2", "=", "r1", ".", "br", "[", "r2", ",", "rect", "(", "tl1", ",", "br1", "-", "tl1", ")", ",", "rect", "(", "tl2", ",", "br2", "-", "tl2", ")", ",", "]", "when", "1", "when", "2", "else", "raise", "\"internal error in disjoint - cases 3 and 4 should be taken care of by the return-tests at the top of the method\"", "end", "end" ]
return 1-3 rectangles which, together, cover exactly the same area as self and b, but do not overlapp
[ "return", "1", "-", "3", "rectangles", "which", "together", "cover", "exactly", "the", "same", "area", "as", "self", "and", "b", "but", "do", "not", "overlapp" ]
ed0688f7484a31435063c0fa1895ddaf3900d959
https://github.com/shanebdavis/gui_geometry/blob/ed0688f7484a31435063c0fa1895ddaf3900d959/lib/gui_geometry/rectangle.rb#L117-L150
train
trumant/pogoplug
lib/pogoplug/client.rb
PogoPlug.Client.version
def version response = get('/getVersion', {}, false) ApiVersion.new(response.body['version'], response.body['builddate']) end
ruby
def version response = get('/getVersion', {}, false) ApiVersion.new(response.body['version'], response.body['builddate']) end
[ "def", "version", "response", "=", "get", "(", "'/getVersion'", ",", "{", "}", ",", "false", ")", "ApiVersion", ".", "new", "(", "response", ".", "body", "[", "'version'", "]", ",", "response", ".", "body", "[", "'builddate'", "]", ")", "end" ]
Retrieve the current version information of the service
[ "Retrieve", "the", "current", "version", "information", "of", "the", "service" ]
4b071385945c713fe0f202b366d2a948215329e4
https://github.com/trumant/pogoplug/blob/4b071385945c713fe0f202b366d2a948215329e4/lib/pogoplug/client.rb#L19-L22
train
trumant/pogoplug
lib/pogoplug/client.rb
PogoPlug.Client.devices
def devices response = get('/listDevices') devices = [] response.body['devices'].each do |d| devices << Device.from_json(d, @token, @logger) end devices end
ruby
def devices response = get('/listDevices') devices = [] response.body['devices'].each do |d| devices << Device.from_json(d, @token, @logger) end devices end
[ "def", "devices", "response", "=", "get", "(", "'/listDevices'", ")", "devices", "=", "[", "]", "response", ".", "body", "[", "'devices'", "]", ".", "each", "do", "|", "d", "|", "devices", "<<", "Device", ".", "from_json", "(", "d", ",", "@token", ",", "@logger", ")", "end", "devices", "end" ]
Retrieve a list of devices that are registered with the PogoPlug account
[ "Retrieve", "a", "list", "of", "devices", "that", "are", "registered", "with", "the", "PogoPlug", "account" ]
4b071385945c713fe0f202b366d2a948215329e4
https://github.com/trumant/pogoplug/blob/4b071385945c713fe0f202b366d2a948215329e4/lib/pogoplug/client.rb#L33-L40
train
trumant/pogoplug
lib/pogoplug/client.rb
PogoPlug.Client.services
def services(device_id=nil, shared=false) params = { shared: shared } params[:deviceid] = device_id unless device_id.nil? response = get('/listServices', params) services = [] response.body['services'].each do |s| services << Service.from_json(s, @token, @logger) end services end
ruby
def services(device_id=nil, shared=false) params = { shared: shared } params[:deviceid] = device_id unless device_id.nil? response = get('/listServices', params) services = [] response.body['services'].each do |s| services << Service.from_json(s, @token, @logger) end services end
[ "def", "services", "(", "device_id", "=", "nil", ",", "shared", "=", "false", ")", "params", "=", "{", "shared", ":", "shared", "}", "params", "[", ":deviceid", "]", "=", "device_id", "unless", "device_id", ".", "nil?", "response", "=", "get", "(", "'/listServices'", ",", "params", ")", "services", "=", "[", "]", "response", ".", "body", "[", "'services'", "]", ".", "each", "do", "|", "s", "|", "services", "<<", "Service", ".", "from_json", "(", "s", ",", "@token", ",", "@logger", ")", "end", "services", "end" ]
Retrieve a list of services
[ "Retrieve", "a", "list", "of", "services" ]
4b071385945c713fe0f202b366d2a948215329e4
https://github.com/trumant/pogoplug/blob/4b071385945c713fe0f202b366d2a948215329e4/lib/pogoplug/client.rb#L49-L59
train
aprescott/serif
lib/serif/filters.rb
Serif.FileDigest.render
def render(context) return "" unless ENV["ENV"] == "production" full_path = File.join(context["site"]["__directory"], @path.strip) return @prefix + DIGEST_CACHE[full_path] if DIGEST_CACHE[full_path] digest = Digest::MD5.hexdigest(File.read(full_path)) DIGEST_CACHE[full_path] = digest @prefix + digest end
ruby
def render(context) return "" unless ENV["ENV"] == "production" full_path = File.join(context["site"]["__directory"], @path.strip) return @prefix + DIGEST_CACHE[full_path] if DIGEST_CACHE[full_path] digest = Digest::MD5.hexdigest(File.read(full_path)) DIGEST_CACHE[full_path] = digest @prefix + digest end
[ "def", "render", "(", "context", ")", "return", "\"\"", "unless", "ENV", "[", "\"ENV\"", "]", "==", "\"production\"", "full_path", "=", "File", ".", "join", "(", "context", "[", "\"site\"", "]", "[", "\"__directory\"", "]", ",", "@path", ".", "strip", ")", "return", "@prefix", "+", "DIGEST_CACHE", "[", "full_path", "]", "if", "DIGEST_CACHE", "[", "full_path", "]", "digest", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "File", ".", "read", "(", "full_path", ")", ")", "DIGEST_CACHE", "[", "full_path", "]", "=", "digest", "@prefix", "+", "digest", "end" ]
Takes the given path and returns the MD5 hex digest of the file's contents. The path argument is first stripped, and any leading "/" has no effect.
[ "Takes", "the", "given", "path", "and", "returns", "the", "MD5", "hex", "digest", "of", "the", "file", "s", "contents", "." ]
4798021fe7419b3fc5f458619dd64149e8c5967e
https://github.com/aprescott/serif/blob/4798021fe7419b3fc5f458619dd64149e8c5967e/lib/serif/filters.rb#L59-L70
train
snusnu/substation
lib/substation/dispatcher.rb
Substation.Dispatcher.call
def call(name, input) fetch(name).call(Request.new(name, env, input)) end
ruby
def call(name, input) fetch(name).call(Request.new(name, env, input)) end
[ "def", "call", "(", "name", ",", "input", ")", "fetch", "(", "name", ")", ".", "call", "(", "Request", ".", "new", "(", "name", ",", "env", ",", "input", ")", ")", "end" ]
Invoke the action identified by +name+ @example module App class Environment def initialize(storage, logger) @storage, @logger = storage, logger end end class SomeUseCase def self.call(request) data = perform_work request.success(data) end end end storage = SomeStorageAbstraction.new env = App::Environment.new(storage, Logger.new($stdout)) config = { :some_use_case => { :action => App::SomeUseCase } } dispatcher = Substation::Dispatcher.coerce(config, env) response = dispatcher.call(:some_use_case, :some_input) response.success? # => true @param [Symbol] name a registered action name @param [Object] input the input model instance to pass to the action @return [Response] the response returned when calling the action @raise [UnknownActionError] if no action is registered for +name+ @api public
[ "Invoke", "the", "action", "identified", "by", "+", "name", "+" ]
fabf062a3640f5e82dae68597f0709b63f6b9027
https://github.com/snusnu/substation/blob/fabf062a3640f5e82dae68597f0709b63f6b9027/lib/substation/dispatcher.rb#L66-L68
train
Birdie0/qna_maker
lib/qna_maker/endpoints/create_kb.rb
QnAMaker.Client.create_kb
def create_kb(name, qna_pairs = [], urls = []) response = @http.post( "#{BASE_URL}/create", json: { name: name, qnaPairs: qna_pairs.map { |pair| { question: pair[0], answer: pair[1] } }, urls: urls } ) case response.code when 201 QnAMaker::Client.new( response.parse['kbId'], @subscription_key, response.parse['dataExtractionResults'] ) when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] else raise UnknownError, "Oh no! (#{response.code})" end end
ruby
def create_kb(name, qna_pairs = [], urls = []) response = @http.post( "#{BASE_URL}/create", json: { name: name, qnaPairs: qna_pairs.map { |pair| { question: pair[0], answer: pair[1] } }, urls: urls } ) case response.code when 201 QnAMaker::Client.new( response.parse['kbId'], @subscription_key, response.parse['dataExtractionResults'] ) when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] else raise UnknownError, "Oh no! (#{response.code})" end end
[ "def", "create_kb", "(", "name", ",", "qna_pairs", "=", "[", "]", ",", "urls", "=", "[", "]", ")", "response", "=", "@http", ".", "post", "(", "\"#{BASE_URL}/create\"", ",", "json", ":", "{", "name", ":", "name", ",", "qnaPairs", ":", "qna_pairs", ".", "map", "{", "|", "pair", "|", "{", "question", ":", "pair", "[", "0", "]", ",", "answer", ":", "pair", "[", "1", "]", "}", "}", ",", "urls", ":", "urls", "}", ")", "case", "response", ".", "code", "when", "201", "QnAMaker", "::", "Client", ".", "new", "(", "response", ".", "parse", "[", "'kbId'", "]", ",", "@subscription_key", ",", "response", ".", "parse", "[", "'dataExtractionResults'", "]", ")", "when", "400", "raise", "BadArgumentError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", ".", "join", "(", "' '", ")", "when", "401", "raise", "UnauthorizedError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "else", "raise", "UnknownError", ",", "\"Oh no! (#{response.code})\"", "end", "end" ]
Creates a new knowledge base. @param [String] name friendly name for the knowledge base (Required) @param [Array<Array(String, String)>] qna_pairs list of question and answer pairs to be added to the knowledge base. Max 1000 Q-A pairs per request. @param [Array<String>] urls list of URLs to be processed and indexed in the knowledge base. In case of existing URL, it will be fetched again and KB will be updated with new data. Max 5 urls per request. @return [Client] client object
[ "Creates", "a", "new", "knowledge", "base", "." ]
5ac204ede100355352438b8ff4fe30ad84d9257b
https://github.com/Birdie0/qna_maker/blob/5ac204ede100355352438b8ff4fe30ad84d9257b/lib/qna_maker/endpoints/create_kb.rb#L14-L38
train
leshill/mongodoc
lib/mongo_doc/index.rb
MongoDoc.Index.index
def index(*args) options_and_fields = args.extract_options! if args.any? collection.create_index(args.first, options_and_fields) else fields = options_and_fields.except(*OPTIONS) options = options_and_fields.slice(*OPTIONS) collection.create_index(to_mongo_direction(fields), options) end end
ruby
def index(*args) options_and_fields = args.extract_options! if args.any? collection.create_index(args.first, options_and_fields) else fields = options_and_fields.except(*OPTIONS) options = options_and_fields.slice(*OPTIONS) collection.create_index(to_mongo_direction(fields), options) end end
[ "def", "index", "(", "*", "args", ")", "options_and_fields", "=", "args", ".", "extract_options!", "if", "args", ".", "any?", "collection", ".", "create_index", "(", "args", ".", "first", ",", "options_and_fields", ")", "else", "fields", "=", "options_and_fields", ".", "except", "(", "*", "OPTIONS", ")", "options", "=", "options_and_fields", ".", "slice", "(", "*", "OPTIONS", ")", "collection", ".", "create_index", "(", "to_mongo_direction", "(", "fields", ")", ",", "options", ")", "end", "end" ]
Create an index on a collection. For compound indexes, pass pairs of fields and directions (+:asc+, +:desc+) as a hash. For a unique index, pass the option +:unique => true+. To create the index in the background, pass the options +:background => true+. If you want to remove duplicates from existing records when creating the unique index, pass the option +:dropDups => true+ For GeoIndexing, specify the minimum and maximum longitude and latitude values with the +:min+ and +:max+ options. <tt>Person.index(:last_name)</tt> <tt>Person.index(:ssn, :unique => true)</tt> <tt>Person.index(:first_name => :asc, :last_name => :asc)</tt> <tt>Person.index(:first_name => :asc, :last_name => :asc, :unique => true)</tt>
[ "Create", "an", "index", "on", "a", "collection", "." ]
fb2a4ec456d4c4ae1eb92e117dc73f55951fc3b4
https://github.com/leshill/mongodoc/blob/fb2a4ec456d4c4ae1eb92e117dc73f55951fc3b4/lib/mongo_doc/index.rb#L26-L35
train
koraktor/rubikon
lib/rubikon/progress_bar.rb
Rubikon.ProgressBar.+
def +(value = 1) return if (value <= 0) || (@value == @maximum) @value += value old_progress = @progress add_progress = ((@value - @progress / @factor) * @factor).round @progress += add_progress if @progress > @size @progress = @size add_progress = @size - old_progress end if add_progress > 0 @ostream << @progress_char * add_progress @ostream.flush @ostream.putc 10 if @progress == @size end self end
ruby
def +(value = 1) return if (value <= 0) || (@value == @maximum) @value += value old_progress = @progress add_progress = ((@value - @progress / @factor) * @factor).round @progress += add_progress if @progress > @size @progress = @size add_progress = @size - old_progress end if add_progress > 0 @ostream << @progress_char * add_progress @ostream.flush @ostream.putc 10 if @progress == @size end self end
[ "def", "+", "(", "value", "=", "1", ")", "return", "if", "(", "value", "<=", "0", ")", "||", "(", "@value", "==", "@maximum", ")", "@value", "+=", "value", "old_progress", "=", "@progress", "add_progress", "=", "(", "(", "@value", "-", "@progress", "/", "@factor", ")", "*", "@factor", ")", ".", "round", "@progress", "+=", "add_progress", "if", "@progress", ">", "@size", "@progress", "=", "@size", "add_progress", "=", "@size", "-", "old_progress", "end", "if", "add_progress", ">", "0", "@ostream", "<<", "@progress_char", "*", "add_progress", "@ostream", ".", "flush", "@ostream", ".", "putc", "10", "if", "@progress", "==", "@size", "end", "self", "end" ]
Create a new ProgressBar using the given options. @param [Hash, Numeric] options A Hash of options to customize the progress bar or the maximum value of the progress bar @see Application::InstanceMethods#progress_bar @option options [String] :char ('#') The character used for progress bar display @option options [Numeric] :maximum (100) The maximum value of this progress bar @option options [IO] :ostream ($stdout) The output stream where the progress bar should be displayed @option options [Numeric] :size (20) The actual size of the progress bar @option options [Numeric] :start (0) The start value of the progress bar Add an amount to the current value of the progress bar This triggers a refresh of the progress bar, if the added value actually changes the displayed bar. @param [Numeric] value The amount to add to the progress bar @return [ProgressBar] The progress bar itself @example Different alternatives to increase the progress progress_bar + 1 # (will add 1) progress_bar + 5 # (will add 5) progress_bar.+ # (will add 1)
[ "Create", "a", "new", "ProgressBar", "using", "the", "given", "options", "." ]
c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b
https://github.com/koraktor/rubikon/blob/c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b/lib/rubikon/progress_bar.rb#L67-L86
train
stevenosloan/borrower
lib/borrower/public_api.rb
Borrower.PublicAPI.put
def put content, destination, on_conflict=:overwrite if on_conflict != :overwrite && Content::Item.new( destination ).exists? case on_conflict when :skip then return when :prompt then input = Util.get_input "a file already exists at #{destination}\noverwrite? (y|n): " return unless input.downcase == "y" when :raise_error then raise "File already exists at #{destination}" end end Content.put content, destination end
ruby
def put content, destination, on_conflict=:overwrite if on_conflict != :overwrite && Content::Item.new( destination ).exists? case on_conflict when :skip then return when :prompt then input = Util.get_input "a file already exists at #{destination}\noverwrite? (y|n): " return unless input.downcase == "y" when :raise_error then raise "File already exists at #{destination}" end end Content.put content, destination end
[ "def", "put", "content", ",", "destination", ",", "on_conflict", "=", ":overwrite", "if", "on_conflict", "!=", ":overwrite", "&&", "Content", "::", "Item", ".", "new", "(", "destination", ")", ".", "exists?", "case", "on_conflict", "when", ":skip", "then", "return", "when", ":prompt", "then", "input", "=", "Util", ".", "get_input", "\"a file already exists at #{destination}\\noverwrite? (y|n): \"", "return", "unless", "input", ".", "downcase", "==", "\"y\"", "when", ":raise_error", "then", "raise", "\"File already exists at #{destination}\"", "end", "end", "Content", ".", "put", "content", ",", "destination", "end" ]
write the content to a destination file @param [String] content content for the file @param [String] destination path to write contents to @param [Symbol] on_conflict what to do if the destination exists @return [Void]
[ "write", "the", "content", "to", "a", "destination", "file" ]
cbb71876fe62ee48724cf60307b5b7b5c1e00944
https://github.com/stevenosloan/borrower/blob/cbb71876fe62ee48724cf60307b5b7b5c1e00944/lib/borrower/public_api.rb#L20-L34
train
scepticulous/crypto-toolbox
lib/crypto-toolbox/ciphers/caesar.rb
Ciphers.Caesar.encipher
def encipher(message,shift) assert_valid_shift!(shift) real_shift = convert_shift(shift) message.split("").map do|char| mod = (char =~ /[a-z]/) ? 123 : 91 offset = (char =~ /[a-z]/) ? 97 : 65 (char =~ /[^a-zA-Z]/) ? char : CryptBuffer(char).add(real_shift, mod: mod, offset: offset).str end.join end
ruby
def encipher(message,shift) assert_valid_shift!(shift) real_shift = convert_shift(shift) message.split("").map do|char| mod = (char =~ /[a-z]/) ? 123 : 91 offset = (char =~ /[a-z]/) ? 97 : 65 (char =~ /[^a-zA-Z]/) ? char : CryptBuffer(char).add(real_shift, mod: mod, offset: offset).str end.join end
[ "def", "encipher", "(", "message", ",", "shift", ")", "assert_valid_shift!", "(", "shift", ")", "real_shift", "=", "convert_shift", "(", "shift", ")", "message", ".", "split", "(", "\"\"", ")", ".", "map", "do", "|", "char", "|", "mod", "=", "(", "char", "=~", "/", "/", ")", "?", "123", ":", "91", "offset", "=", "(", "char", "=~", "/", "/", ")", "?", "97", ":", "65", "(", "char", "=~", "/", "/", ")", "?", "char", ":", "CryptBuffer", "(", "char", ")", ".", "add", "(", "real_shift", ",", "mod", ":", "mod", ",", "offset", ":", "offset", ")", ".", "str", "end", ".", "join", "end" ]
=begin Within encipher and decipher we use a regexp comparision. Array lookups are must slower and byte comparision is a little faster, but much more complicated Alphabet letter lookup algorithm comparision: Comparison: (see benchmarks/string_comparision.rb) string.bytes.first == A : 3289762.7 i/s string =~ [A-Za-Z] : 2010285.8 i/s - 1.64x slower Letter Array include?(A): 76997.0 i/s - 42.73x slower =end
[ "=", "begin", "Within", "encipher", "and", "decipher", "we", "use", "a", "regexp", "comparision", ".", "Array", "lookups", "are", "must", "slower", "and", "byte", "comparision", "is", "a", "little", "faster", "but", "much", "more", "complicated" ]
cdbe371109e497db2c2af5c1fe0f359612f44816
https://github.com/scepticulous/crypto-toolbox/blob/cdbe371109e497db2c2af5c1fe0f359612f44816/lib/crypto-toolbox/ciphers/caesar.rb#L27-L37
train
trumant/pogoplug
lib/pogoplug/service_client.rb
PogoPlug.ServiceClient.create_entity
def create_entity(file, io = nil, properties = {}) params = { deviceid: @device_id, serviceid: @service_id, filename: file.name, type: file.type }.merge(properties) params[:parentid] = file.parent_id unless file.parent_id.nil? if params[:properties] params[:properties] = params[:properties].to_json end file_handle = unless file.id response = get('/createFile', params) File.from_json(response.body['file']) else file end if io HttpHelper.send_file(files_url, @token, @device_id, @service_id, file_handle, io, @logger) file_handle.size = io.size end file_handle end
ruby
def create_entity(file, io = nil, properties = {}) params = { deviceid: @device_id, serviceid: @service_id, filename: file.name, type: file.type }.merge(properties) params[:parentid] = file.parent_id unless file.parent_id.nil? if params[:properties] params[:properties] = params[:properties].to_json end file_handle = unless file.id response = get('/createFile', params) File.from_json(response.body['file']) else file end if io HttpHelper.send_file(files_url, @token, @device_id, @service_id, file_handle, io, @logger) file_handle.size = io.size end file_handle end
[ "def", "create_entity", "(", "file", ",", "io", "=", "nil", ",", "properties", "=", "{", "}", ")", "params", "=", "{", "deviceid", ":", "@device_id", ",", "serviceid", ":", "@service_id", ",", "filename", ":", "file", ".", "name", ",", "type", ":", "file", ".", "type", "}", ".", "merge", "(", "properties", ")", "params", "[", ":parentid", "]", "=", "file", ".", "parent_id", "unless", "file", ".", "parent_id", ".", "nil?", "if", "params", "[", ":properties", "]", "params", "[", ":properties", "]", "=", "params", "[", ":properties", "]", ".", "to_json", "end", "file_handle", "=", "unless", "file", ".", "id", "response", "=", "get", "(", "'/createFile'", ",", "params", ")", "File", ".", "from_json", "(", "response", ".", "body", "[", "'file'", "]", ")", "else", "file", "end", "if", "io", "HttpHelper", ".", "send_file", "(", "files_url", ",", "@token", ",", "@device_id", ",", "@service_id", ",", "file_handle", ",", "io", ",", "@logger", ")", "file_handle", ".", "size", "=", "io", ".", "size", "end", "file_handle", "end" ]
Creates a file handle and optionally attach an io. The provided file argument is expected to contain at minimum a name, type and parent_id. If it has a mimetype that will be assumed to match the mimetype of the io.
[ "Creates", "a", "file", "handle", "and", "optionally", "attach", "an", "io", ".", "The", "provided", "file", "argument", "is", "expected", "to", "contain", "at", "minimum", "a", "name", "type", "and", "parent_id", ".", "If", "it", "has", "a", "mimetype", "that", "will", "be", "assumed", "to", "match", "the", "mimetype", "of", "the", "io", "." ]
4b071385945c713fe0f202b366d2a948215329e4
https://github.com/trumant/pogoplug/blob/4b071385945c713fe0f202b366d2a948215329e4/lib/pogoplug/service_client.rb#L25-L46
train
blahah/assemblotron
lib/assemblotron/assemblermanager.rb
Assemblotron.AssemblerManager.load_assemblers
def load_assemblers Biopsy::Settings.instance.target_dir.each do |dir| Dir.chdir dir do Dir['*.yml'].each do |file| name = File.basename(file, '.yml') target = Assembler.new target.load_by_name name unless System.match? target.bindeps[:url] logger.info "Assembler #{target.name} is not available" + " for this operating system" next end bin_paths = target.bindeps[:binaries].map do |bin| Which.which bin end missing_bin = bin_paths.any? { |path| path.empty? } if missing_bin logger.debug "Assembler #{target.name} was not installed" missing = bin_paths .select{ |path| path.empty? } .map.with_index{ |path, i| target.bindeps[:binaries][i] } logger.debug "(missing binaries: #{missing.join(', ')})" @assemblers_uninst << target else @assemblers << target end end end end end
ruby
def load_assemblers Biopsy::Settings.instance.target_dir.each do |dir| Dir.chdir dir do Dir['*.yml'].each do |file| name = File.basename(file, '.yml') target = Assembler.new target.load_by_name name unless System.match? target.bindeps[:url] logger.info "Assembler #{target.name} is not available" + " for this operating system" next end bin_paths = target.bindeps[:binaries].map do |bin| Which.which bin end missing_bin = bin_paths.any? { |path| path.empty? } if missing_bin logger.debug "Assembler #{target.name} was not installed" missing = bin_paths .select{ |path| path.empty? } .map.with_index{ |path, i| target.bindeps[:binaries][i] } logger.debug "(missing binaries: #{missing.join(', ')})" @assemblers_uninst << target else @assemblers << target end end end end end
[ "def", "load_assemblers", "Biopsy", "::", "Settings", ".", "instance", ".", "target_dir", ".", "each", "do", "|", "dir", "|", "Dir", ".", "chdir", "dir", "do", "Dir", "[", "'*.yml'", "]", ".", "each", "do", "|", "file", "|", "name", "=", "File", ".", "basename", "(", "file", ",", "'.yml'", ")", "target", "=", "Assembler", ".", "new", "target", ".", "load_by_name", "name", "unless", "System", ".", "match?", "target", ".", "bindeps", "[", ":url", "]", "logger", ".", "info", "\"Assembler #{target.name} is not available\"", "+", "\" for this operating system\"", "next", "end", "bin_paths", "=", "target", ".", "bindeps", "[", ":binaries", "]", ".", "map", "do", "|", "bin", "|", "Which", ".", "which", "bin", "end", "missing_bin", "=", "bin_paths", ".", "any?", "{", "|", "path", "|", "path", ".", "empty?", "}", "if", "missing_bin", "logger", ".", "debug", "\"Assembler #{target.name} was not installed\"", "missing", "=", "bin_paths", ".", "select", "{", "|", "path", "|", "path", ".", "empty?", "}", ".", "map", ".", "with_index", "{", "|", "path", ",", "i", "|", "target", ".", "bindeps", "[", ":binaries", "]", "[", "i", "]", "}", "logger", ".", "debug", "\"(missing binaries: #{missing.join(', ')})\"", "@assemblers_uninst", "<<", "target", "else", "@assemblers", "<<", "target", "end", "end", "end", "end", "end" ]
Discover and load available assemblers.
[ "Discover", "and", "load", "available", "assemblers", "." ]
475d59c72ba36ebb2799076a0009758d12fa1508
https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/assemblermanager.rb#L15-L44
train
blahah/assemblotron
lib/assemblotron/assemblermanager.rb
Assemblotron.AssemblerManager.assembler_names
def assembler_names a = [] @assemblers.each do |t| a << t.name a << t.shortname if t.shortname end a end
ruby
def assembler_names a = [] @assemblers.each do |t| a << t.name a << t.shortname if t.shortname end a end
[ "def", "assembler_names", "a", "=", "[", "]", "@assemblers", ".", "each", "do", "|", "t", "|", "a", "<<", "t", ".", "name", "a", "<<", "t", ".", "shortname", "if", "t", ".", "shortname", "end", "a", "end" ]
load_assemblers Collect all valid names for available assemblers @return [Array<String>] names and shortnames (if applicable) for available assemblers.
[ "load_assemblers", "Collect", "all", "valid", "names", "for", "available", "assemblers" ]
475d59c72ba36ebb2799076a0009758d12fa1508
https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/assemblermanager.rb#L50-L57
train
blahah/assemblotron
lib/assemblotron/assemblermanager.rb
Assemblotron.AssemblerManager.list_assemblers
def list_assemblers str = "" if @assemblers.empty? str << "\nNo assemblers are currently installed! Please install some.\n" else str << <<-EOS Installed assemblers are listed below. Shortnames are shown in brackets if available. Assemblers installed: EOS @assemblers.each do |a| p = " - #{a.name}" p += " (#{a.shortname})" if a.respond_to? :shortname str << p + "\n" end end if @assemblers_uninst.empty? str << "\nAll available assemblers are already installed!\n" else str << <<-EOS Assemblers that are available to be installed are listed below. To install one, use: atron --install-assemblers <name OR shortname> Assemblers installable: EOS @assemblers_uninst.each do |a| p = " - #{a.name}" p += " (#{a.shortname})" if a.respond_to? :shortname str << p + "\n" end end str + "\n" end
ruby
def list_assemblers str = "" if @assemblers.empty? str << "\nNo assemblers are currently installed! Please install some.\n" else str << <<-EOS Installed assemblers are listed below. Shortnames are shown in brackets if available. Assemblers installed: EOS @assemblers.each do |a| p = " - #{a.name}" p += " (#{a.shortname})" if a.respond_to? :shortname str << p + "\n" end end if @assemblers_uninst.empty? str << "\nAll available assemblers are already installed!\n" else str << <<-EOS Assemblers that are available to be installed are listed below. To install one, use: atron --install-assemblers <name OR shortname> Assemblers installable: EOS @assemblers_uninst.each do |a| p = " - #{a.name}" p += " (#{a.shortname})" if a.respond_to? :shortname str << p + "\n" end end str + "\n" end
[ "def", "list_assemblers", "str", "=", "\"\"", "if", "@assemblers", ".", "empty?", "str", "<<", "\"\\nNo assemblers are currently installed! Please install some.\\n\"", "else", "str", "<<", "<<-EOS", "EOS", "@assemblers", ".", "each", "do", "|", "a", "|", "p", "=", "\" - #{a.name}\"", "p", "+=", "\" (#{a.shortname})\"", "if", "a", ".", "respond_to?", ":shortname", "str", "<<", "p", "+", "\"\\n\"", "end", "end", "if", "@assemblers_uninst", ".", "empty?", "str", "<<", "\"\\nAll available assemblers are already installed!\\n\"", "else", "str", "<<", "<<-EOS", "EOS", "@assemblers_uninst", ".", "each", "do", "|", "a", "|", "p", "=", "\" - #{a.name}\"", "p", "+=", "\" (#{a.shortname})\"", "if", "a", ".", "respond_to?", ":shortname", "str", "<<", "p", "+", "\"\\n\"", "end", "end", "str", "+", "\"\\n\"", "end" ]
assemblers Return a help message listing installed assemblers.
[ "assemblers", "Return", "a", "help", "message", "listing", "installed", "assemblers", "." ]
475d59c72ba36ebb2799076a0009758d12fa1508
https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/assemblermanager.rb#L60-L103
train
blahah/assemblotron
lib/assemblotron/assemblermanager.rb
Assemblotron.AssemblerManager.get_assembler
def get_assembler assembler ret = @assemblers.find do |a| a.name == assembler || a.shortname == assembler end raise "couldn't find assembler #{assembler}" if ret.nil? ret end
ruby
def get_assembler assembler ret = @assemblers.find do |a| a.name == assembler || a.shortname == assembler end raise "couldn't find assembler #{assembler}" if ret.nil? ret end
[ "def", "get_assembler", "assembler", "ret", "=", "@assemblers", ".", "find", "do", "|", "a", "|", "a", ".", "name", "==", "assembler", "||", "a", ".", "shortname", "==", "assembler", "end", "raise", "\"couldn't find assembler #{assembler}\"", "if", "ret", ".", "nil?", "ret", "end" ]
Given the name of an assembler, get the loaded assembler ready for optimisation. @param assembler [String] assembler name or shortname @return [Biopsy::Target] the loaded assembler
[ "Given", "the", "name", "of", "an", "assembler", "get", "the", "loaded", "assembler", "ready", "for", "optimisation", "." ]
475d59c72ba36ebb2799076a0009758d12fa1508
https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/assemblermanager.rb#L157-L164
train
blahah/assemblotron
lib/assemblotron/assemblermanager.rb
Assemblotron.AssemblerManager.run_all_assemblers
def run_all_assemblers options res = {} subset = false unless options[:assemblers] == 'all' subset = options[:assemblers].split(',') missing = [] subset.each do |choice| missing < choice unless @assemblers.any do |a| a.name == choice || a.shortname == choice end end unless missing.empty? log.error "The specified assemblers (#{missing.join(', ')}) were not valid choices" log.error "Please choose from the options in --list-assembler" exit(1) end end unless options[:skip_final] if (File.exist? 'final_assemblies') logger.warn("Directory final_assemblies already exists. Some results may be overwritten.") end FileUtils.mkdir_p('final_assemblies') final_dir = File.expand_path 'final_assemblies' end results_filepath = Time.now.to_s.gsub(/ /, '_') + '.json' @assemblers.each do |assembler| logger.info "Starting optimisation for #{assembler.name}" this_res = run_assembler assembler logger.info "Optimisation of #{assembler.name} finished" # run the final assembly unless options[:skip_final] this_final_dir = File.join(final_dir, assembler.name.downcase) Dir.chdir this_final_dir do logger.info "Running full assembly for #{assembler.name}" + " with optimal parameters" # use the full read set this_res[:left] = options[:left] this_res[:right] = options[:right] this_res[:threads] = options[:threads] final = final_assembly assembler, res this_res[:final] = final end res[assembler.name] = this_res end File.open(results_filepath, 'w') do |out| out.write JSON.pretty_generate(res) end logger.info "Result file updated: #{results_filepath}" end logger.info "All assemblers optimised" res end
ruby
def run_all_assemblers options res = {} subset = false unless options[:assemblers] == 'all' subset = options[:assemblers].split(',') missing = [] subset.each do |choice| missing < choice unless @assemblers.any do |a| a.name == choice || a.shortname == choice end end unless missing.empty? log.error "The specified assemblers (#{missing.join(', ')}) were not valid choices" log.error "Please choose from the options in --list-assembler" exit(1) end end unless options[:skip_final] if (File.exist? 'final_assemblies') logger.warn("Directory final_assemblies already exists. Some results may be overwritten.") end FileUtils.mkdir_p('final_assemblies') final_dir = File.expand_path 'final_assemblies' end results_filepath = Time.now.to_s.gsub(/ /, '_') + '.json' @assemblers.each do |assembler| logger.info "Starting optimisation for #{assembler.name}" this_res = run_assembler assembler logger.info "Optimisation of #{assembler.name} finished" # run the final assembly unless options[:skip_final] this_final_dir = File.join(final_dir, assembler.name.downcase) Dir.chdir this_final_dir do logger.info "Running full assembly for #{assembler.name}" + " with optimal parameters" # use the full read set this_res[:left] = options[:left] this_res[:right] = options[:right] this_res[:threads] = options[:threads] final = final_assembly assembler, res this_res[:final] = final end res[assembler.name] = this_res end File.open(results_filepath, 'w') do |out| out.write JSON.pretty_generate(res) end logger.info "Result file updated: #{results_filepath}" end logger.info "All assemblers optimised" res end
[ "def", "run_all_assemblers", "options", "res", "=", "{", "}", "subset", "=", "false", "unless", "options", "[", ":assemblers", "]", "==", "'all'", "subset", "=", "options", "[", ":assemblers", "]", ".", "split", "(", "','", ")", "missing", "=", "[", "]", "subset", ".", "each", "do", "|", "choice", "|", "missing", "<", "choice", "unless", "@assemblers", ".", "any", "do", "|", "a", "|", "a", ".", "name", "==", "choice", "||", "a", ".", "shortname", "==", "choice", "end", "end", "unless", "missing", ".", "empty?", "log", ".", "error", "\"The specified assemblers (#{missing.join(', ')}) were not valid choices\"", "log", ".", "error", "\"Please choose from the options in --list-assembler\"", "exit", "(", "1", ")", "end", "end", "unless", "options", "[", ":skip_final", "]", "if", "(", "File", ".", "exist?", "'final_assemblies'", ")", "logger", ".", "warn", "(", "\"Directory final_assemblies already exists. Some results may be overwritten.\"", ")", "end", "FileUtils", ".", "mkdir_p", "(", "'final_assemblies'", ")", "final_dir", "=", "File", ".", "expand_path", "'final_assemblies'", "end", "results_filepath", "=", "Time", ".", "now", ".", "to_s", ".", "gsub", "(", "/", "/", ",", "'_'", ")", "+", "'.json'", "@assemblers", ".", "each", "do", "|", "assembler", "|", "logger", ".", "info", "\"Starting optimisation for #{assembler.name}\"", "this_res", "=", "run_assembler", "assembler", "logger", ".", "info", "\"Optimisation of #{assembler.name} finished\"", "unless", "options", "[", ":skip_final", "]", "this_final_dir", "=", "File", ".", "join", "(", "final_dir", ",", "assembler", ".", "name", ".", "downcase", ")", "Dir", ".", "chdir", "this_final_dir", "do", "logger", ".", "info", "\"Running full assembly for #{assembler.name}\"", "+", "\" with optimal parameters\"", "this_res", "[", ":left", "]", "=", "options", "[", ":left", "]", "this_res", "[", ":right", "]", "=", "options", "[", ":right", "]", "this_res", "[", ":threads", "]", "=", "options", "[", ":threads", "]", "final", "=", "final_assembly", "assembler", ",", "res", "this_res", "[", ":final", "]", "=", "final", "end", "res", "[", "assembler", ".", "name", "]", "=", "this_res", "end", "File", ".", "open", "(", "results_filepath", ",", "'w'", ")", "do", "|", "out", "|", "out", ".", "write", "JSON", ".", "pretty_generate", "(", "res", ")", "end", "logger", ".", "info", "\"Result file updated: #{results_filepath}\"", "end", "logger", ".", "info", "\"All assemblers optimised\"", "res", "end" ]
Run optimisation and final assembly for each assembler
[ "Run", "optimisation", "and", "final", "assembly", "for", "each", "assembler" ]
475d59c72ba36ebb2799076a0009758d12fa1508
https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/assemblermanager.rb#L167-L230
train
blahah/assemblotron
lib/assemblotron/assemblermanager.rb
Assemblotron.AssemblerManager.run_assembler
def run_assembler assembler # run the optimisation opts = @options.clone opts[:left] = opts[:left_subset] opts[:right] = opts[:right_subset] if @options[:optimiser] == 'sweep' logger.info("Using full parameter sweep optimiser") algorithm = Biopsy::ParameterSweeper.new(assembler.parameters) elsif @options[:optimiser] == 'tabu' logger.info("Using tabu search optimiser") algorithm = Biopsy::TabuSearch.new(assembler.parameters) else logger.error("Optimiser '#{@options[:optimiser]}' is not a valid optiion") logger.error("Please check the options using --help") exit(1) end exp = Biopsy::Experiment.new(assembler, options: opts, threads: @options[:threads], timelimit: @options[:timelimit], algorithm: algorithm, verbosity: :loud) exp.run end
ruby
def run_assembler assembler # run the optimisation opts = @options.clone opts[:left] = opts[:left_subset] opts[:right] = opts[:right_subset] if @options[:optimiser] == 'sweep' logger.info("Using full parameter sweep optimiser") algorithm = Biopsy::ParameterSweeper.new(assembler.parameters) elsif @options[:optimiser] == 'tabu' logger.info("Using tabu search optimiser") algorithm = Biopsy::TabuSearch.new(assembler.parameters) else logger.error("Optimiser '#{@options[:optimiser]}' is not a valid optiion") logger.error("Please check the options using --help") exit(1) end exp = Biopsy::Experiment.new(assembler, options: opts, threads: @options[:threads], timelimit: @options[:timelimit], algorithm: algorithm, verbosity: :loud) exp.run end
[ "def", "run_assembler", "assembler", "opts", "=", "@options", ".", "clone", "opts", "[", ":left", "]", "=", "opts", "[", ":left_subset", "]", "opts", "[", ":right", "]", "=", "opts", "[", ":right_subset", "]", "if", "@options", "[", ":optimiser", "]", "==", "'sweep'", "logger", ".", "info", "(", "\"Using full parameter sweep optimiser\"", ")", "algorithm", "=", "Biopsy", "::", "ParameterSweeper", ".", "new", "(", "assembler", ".", "parameters", ")", "elsif", "@options", "[", ":optimiser", "]", "==", "'tabu'", "logger", ".", "info", "(", "\"Using tabu search optimiser\"", ")", "algorithm", "=", "Biopsy", "::", "TabuSearch", ".", "new", "(", "assembler", ".", "parameters", ")", "else", "logger", ".", "error", "(", "\"Optimiser '#{@options[:optimiser]}' is not a valid optiion\"", ")", "logger", ".", "error", "(", "\"Please check the options using --help\"", ")", "exit", "(", "1", ")", "end", "exp", "=", "Biopsy", "::", "Experiment", ".", "new", "(", "assembler", ",", "options", ":", "opts", ",", "threads", ":", "@options", "[", ":threads", "]", ",", "timelimit", ":", "@options", "[", ":timelimit", "]", ",", "algorithm", ":", "algorithm", ",", "verbosity", ":", ":loud", ")", "exp", ".", "run", "end" ]
Run optimisation for the named assembler @param [String] assembler name or shortname
[ "Run", "optimisation", "for", "the", "named", "assembler" ]
475d59c72ba36ebb2799076a0009758d12fa1508
https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/assemblermanager.rb#L235-L258
train
Sharparam/chatrix
lib/chatrix/rooms.rb
Chatrix.Rooms.[]
def [](id) return @rooms[id] if id.start_with? '!' if id.start_with? '#' res = @rooms.find { |_, r| r.canonical_alias == id } return res.last if res.respond_to? :last end res = @rooms.find { |_, r| r.name == id } res.last if res.respond_to? :last end
ruby
def [](id) return @rooms[id] if id.start_with? '!' if id.start_with? '#' res = @rooms.find { |_, r| r.canonical_alias == id } return res.last if res.respond_to? :last end res = @rooms.find { |_, r| r.name == id } res.last if res.respond_to? :last end
[ "def", "[]", "(", "id", ")", "return", "@rooms", "[", "id", "]", "if", "id", ".", "start_with?", "'!'", "if", "id", ".", "start_with?", "'#'", "res", "=", "@rooms", ".", "find", "{", "|", "_", ",", "r", "|", "r", ".", "canonical_alias", "==", "id", "}", "return", "res", ".", "last", "if", "res", ".", "respond_to?", ":last", "end", "res", "=", "@rooms", ".", "find", "{", "|", "_", ",", "r", "|", "r", ".", "name", "==", "id", "}", "res", ".", "last", "if", "res", ".", "respond_to?", ":last", "end" ]
Initializes a new Rooms instance. @param users [Users] The User manager. @param matrix [Matrix] The Matrix API instance. Gets a room by its ID, alias, or name. @return [Room,nil] Returns the room instance if the room was found, otherwise `nil`.
[ "Initializes", "a", "new", "Rooms", "instance", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/rooms.rb#L30-L40
train
Sharparam/chatrix
lib/chatrix/rooms.rb
Chatrix.Rooms.process_events
def process_events(events) process_join events['join'] if events.key? 'join' process_invite events['invite'] if events.key? 'invite' process_leave events['leave'] if events.key? 'leave' end
ruby
def process_events(events) process_join events['join'] if events.key? 'join' process_invite events['invite'] if events.key? 'invite' process_leave events['leave'] if events.key? 'leave' end
[ "def", "process_events", "(", "events", ")", "process_join", "events", "[", "'join'", "]", "if", "events", ".", "key?", "'join'", "process_invite", "events", "[", "'invite'", "]", "if", "events", ".", "key?", "'invite'", "process_leave", "events", "[", "'leave'", "]", "if", "events", ".", "key?", "'leave'", "end" ]
Processes a list of room events from syncs. @param events [Hash] A hash of room events as returned from the server.
[ "Processes", "a", "list", "of", "room", "events", "from", "syncs", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/rooms.rb#L54-L58
train
Sharparam/chatrix
lib/chatrix/rooms.rb
Chatrix.Rooms.get_room
def get_room(id) return @rooms[id] if @rooms.key? id room = Room.new id, @users, @matrix @rooms[id] = room broadcast(:added, room) room end
ruby
def get_room(id) return @rooms[id] if @rooms.key? id room = Room.new id, @users, @matrix @rooms[id] = room broadcast(:added, room) room end
[ "def", "get_room", "(", "id", ")", "return", "@rooms", "[", "id", "]", "if", "@rooms", ".", "key?", "id", "room", "=", "Room", ".", "new", "id", ",", "@users", ",", "@matrix", "@rooms", "[", "id", "]", "=", "room", "broadcast", "(", ":added", ",", "room", ")", "room", "end" ]
Gets the Room instance associated with a room ID. If there is no Room instance for the ID, one is created and returned. @param id [String] The room ID to get an instance for. @return [Room] An instance of the Room class for the specified ID.
[ "Gets", "the", "Room", "instance", "associated", "with", "a", "room", "ID", ".", "If", "there", "is", "no", "Room", "instance", "for", "the", "ID", "one", "is", "created", "and", "returned", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/rooms.rb#L67-L73
train
Sharparam/chatrix
lib/chatrix/rooms.rb
Chatrix.Rooms.process_join
def process_join(events) events.each do |room, data| get_room(room).process_join data end end
ruby
def process_join(events) events.each do |room, data| get_room(room).process_join data end end
[ "def", "process_join", "(", "events", ")", "events", ".", "each", "do", "|", "room", ",", "data", "|", "get_room", "(", "room", ")", ".", "process_join", "data", "end", "end" ]
Process `join` room events. @param events [Hash{String=>Hash}] Events to process.
[ "Process", "join", "room", "events", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/rooms.rb#L78-L82
train
Sharparam/chatrix
lib/chatrix/rooms.rb
Chatrix.Rooms.process_invite
def process_invite(events) events.each do |room, data| get_room(room).process_invite data end end
ruby
def process_invite(events) events.each do |room, data| get_room(room).process_invite data end end
[ "def", "process_invite", "(", "events", ")", "events", ".", "each", "do", "|", "room", ",", "data", "|", "get_room", "(", "room", ")", ".", "process_invite", "data", "end", "end" ]
Process `invite` room events. @param events [Hash{String=>Hash}] Events to process.
[ "Process", "invite", "room", "events", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/rooms.rb#L87-L91
train
Sharparam/chatrix
lib/chatrix/rooms.rb
Chatrix.Rooms.process_leave
def process_leave(events) events.each do |room, data| get_room(room).process_leave data end end
ruby
def process_leave(events) events.each do |room, data| get_room(room).process_leave data end end
[ "def", "process_leave", "(", "events", ")", "events", ".", "each", "do", "|", "room", ",", "data", "|", "get_room", "(", "room", ")", ".", "process_leave", "data", "end", "end" ]
Process `leave` room events. @param events [Hash{String=>Hash}] Events to process.
[ "Process", "leave", "room", "events", "." ]
6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34
https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/rooms.rb#L96-L100
train
ianwhite/resources_controller
lib/resources_controller/helper.rb
ResourcesController.Helper.method_missing
def method_missing(method, *args, &block) if controller.resource_named_route_helper_method?(method) self.class.send(:delegate, method, :to => :controller) controller.send(method, *args) else super(method, *args, &block) end end
ruby
def method_missing(method, *args, &block) if controller.resource_named_route_helper_method?(method) self.class.send(:delegate, method, :to => :controller) controller.send(method, *args) else super(method, *args, &block) end end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "if", "controller", ".", "resource_named_route_helper_method?", "(", "method", ")", "self", ".", "class", ".", "send", "(", ":delegate", ",", "method", ",", ":to", "=>", ":controller", ")", "controller", ".", "send", "(", "method", ",", "*", "args", ")", "else", "super", "(", "method", ",", "*", "args", ",", "&", "block", ")", "end", "end" ]
Delegate named_route helper method to the controller. Create the delegation to short circuit the method_missing call for future invocations.
[ "Delegate", "named_route", "helper", "method", "to", "the", "controller", ".", "Create", "the", "delegation", "to", "short", "circuit", "the", "method_missing", "call", "for", "future", "invocations", "." ]
14e76843ccf7d22a6da5da6db81681397c4838c5
https://github.com/ianwhite/resources_controller/blob/14e76843ccf7d22a6da5da6db81681397c4838c5/lib/resources_controller/helper.rb#L81-L88
train
ideonetwork/lato-core
app/cells/lato_core/widgets/index/cell.rb
LatoCore.Widgets::Index::Cell.generate_table_head
def generate_table_head labels = [] if @args[:head] && @args[:head].length > 0 # manage case with custom head labels = [] if @args[:actions_on_start] && @show_row_actions labels.push(LANGUAGES[:lato_core][:mixed][:actions]) end @args[:head].each do |head| if head.is_a?(Hash) sort_value = @args[:records].is_a?(Hash) ? @args[:records][:sort] : '' sort_dir_value = @args[:records].is_a?(Hash) ? @args[:records][:sort_dir] : 'ASC' active_class = sort_value == head[:sort] ? "attr-active attr-sort-#{sort_dir_value}" : '' active_sort = sort_value == head[:sort] ? (sort_dir_value == 'ASC' ? 'DESC' : 'ASC') : sort_dir_value search_value = @args[:records].is_a?(Hash) ? @args[:records][:search] : '' url = core__add_param_to_url(@args[:index_url], 'widget_index[search]', search_value) url = core__add_param_to_url(url, 'widget_index[sort]', head[:sort]) url = core__add_param_to_url(url, 'widget_index[sort_dir]', active_sort) string = "<a href='#{url}' class='#{active_class}'>#{head[:label]}</a>" labels.push(string) else labels.push(head) end end if !@args[:actions_on_start] && @show_row_actions labels.push(LANGUAGES[:lato_core][:mixed][:actions]) end elsif @records&.length > 0 # manage case without custom head labels = [] if @args[:actions_on_start] && @show_row_actions labels.push(LANGUAGES[:lato_core][:mixed][:actions]) end labels = labels + @records.first.attributes.keys.map {|s| s.gsub('_', ' ')} labels = labels.map(&:capitalize) if !@args[:actions_on_start] && @show_row_actions labels.push(LANGUAGES[:lato_core][:mixed][:actions]) end end return LatoCore::Elements::Table::Head::Cell.new(labels: labels) end
ruby
def generate_table_head labels = [] if @args[:head] && @args[:head].length > 0 # manage case with custom head labels = [] if @args[:actions_on_start] && @show_row_actions labels.push(LANGUAGES[:lato_core][:mixed][:actions]) end @args[:head].each do |head| if head.is_a?(Hash) sort_value = @args[:records].is_a?(Hash) ? @args[:records][:sort] : '' sort_dir_value = @args[:records].is_a?(Hash) ? @args[:records][:sort_dir] : 'ASC' active_class = sort_value == head[:sort] ? "attr-active attr-sort-#{sort_dir_value}" : '' active_sort = sort_value == head[:sort] ? (sort_dir_value == 'ASC' ? 'DESC' : 'ASC') : sort_dir_value search_value = @args[:records].is_a?(Hash) ? @args[:records][:search] : '' url = core__add_param_to_url(@args[:index_url], 'widget_index[search]', search_value) url = core__add_param_to_url(url, 'widget_index[sort]', head[:sort]) url = core__add_param_to_url(url, 'widget_index[sort_dir]', active_sort) string = "<a href='#{url}' class='#{active_class}'>#{head[:label]}</a>" labels.push(string) else labels.push(head) end end if !@args[:actions_on_start] && @show_row_actions labels.push(LANGUAGES[:lato_core][:mixed][:actions]) end elsif @records&.length > 0 # manage case without custom head labels = [] if @args[:actions_on_start] && @show_row_actions labels.push(LANGUAGES[:lato_core][:mixed][:actions]) end labels = labels + @records.first.attributes.keys.map {|s| s.gsub('_', ' ')} labels = labels.map(&:capitalize) if !@args[:actions_on_start] && @show_row_actions labels.push(LANGUAGES[:lato_core][:mixed][:actions]) end end return LatoCore::Elements::Table::Head::Cell.new(labels: labels) end
[ "def", "generate_table_head", "labels", "=", "[", "]", "if", "@args", "[", ":head", "]", "&&", "@args", "[", ":head", "]", ".", "length", ">", "0", "labels", "=", "[", "]", "if", "@args", "[", ":actions_on_start", "]", "&&", "@show_row_actions", "labels", ".", "push", "(", "LANGUAGES", "[", ":lato_core", "]", "[", ":mixed", "]", "[", ":actions", "]", ")", "end", "@args", "[", ":head", "]", ".", "each", "do", "|", "head", "|", "if", "head", ".", "is_a?", "(", "Hash", ")", "sort_value", "=", "@args", "[", ":records", "]", ".", "is_a?", "(", "Hash", ")", "?", "@args", "[", ":records", "]", "[", ":sort", "]", ":", "''", "sort_dir_value", "=", "@args", "[", ":records", "]", ".", "is_a?", "(", "Hash", ")", "?", "@args", "[", ":records", "]", "[", ":sort_dir", "]", ":", "'ASC'", "active_class", "=", "sort_value", "==", "head", "[", ":sort", "]", "?", "\"attr-active attr-sort-#{sort_dir_value}\"", ":", "''", "active_sort", "=", "sort_value", "==", "head", "[", ":sort", "]", "?", "(", "sort_dir_value", "==", "'ASC'", "?", "'DESC'", ":", "'ASC'", ")", ":", "sort_dir_value", "search_value", "=", "@args", "[", ":records", "]", ".", "is_a?", "(", "Hash", ")", "?", "@args", "[", ":records", "]", "[", ":search", "]", ":", "''", "url", "=", "core__add_param_to_url", "(", "@args", "[", ":index_url", "]", ",", "'widget_index[search]'", ",", "search_value", ")", "url", "=", "core__add_param_to_url", "(", "url", ",", "'widget_index[sort]'", ",", "head", "[", ":sort", "]", ")", "url", "=", "core__add_param_to_url", "(", "url", ",", "'widget_index[sort_dir]'", ",", "active_sort", ")", "string", "=", "\"<a href='#{url}' class='#{active_class}'>#{head[:label]}</a>\"", "labels", ".", "push", "(", "string", ")", "else", "labels", ".", "push", "(", "head", ")", "end", "end", "if", "!", "@args", "[", ":actions_on_start", "]", "&&", "@show_row_actions", "labels", ".", "push", "(", "LANGUAGES", "[", ":lato_core", "]", "[", ":mixed", "]", "[", ":actions", "]", ")", "end", "elsif", "@records", "&.", "length", ">", "0", "labels", "=", "[", "]", "if", "@args", "[", ":actions_on_start", "]", "&&", "@show_row_actions", "labels", ".", "push", "(", "LANGUAGES", "[", ":lato_core", "]", "[", ":mixed", "]", "[", ":actions", "]", ")", "end", "labels", "=", "labels", "+", "@records", ".", "first", ".", "attributes", ".", "keys", ".", "map", "{", "|", "s", "|", "s", ".", "gsub", "(", "'_'", ",", "' '", ")", "}", "labels", "=", "labels", ".", "map", "(", "&", ":capitalize", ")", "if", "!", "@args", "[", ":actions_on_start", "]", "&&", "@show_row_actions", "labels", ".", "push", "(", "LANGUAGES", "[", ":lato_core", "]", "[", ":mixed", "]", "[", ":actions", "]", ")", "end", "end", "return", "LatoCore", "::", "Elements", "::", "Table", "::", "Head", "::", "Cell", ".", "new", "(", "labels", ":", "labels", ")", "end" ]
This function generate the head for the table.
[ "This", "function", "generate", "the", "head", "for", "the", "table", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L84-L127
train
ideonetwork/lato-core
app/cells/lato_core/widgets/index/cell.rb
LatoCore.Widgets::Index::Cell.generate_table_rows
def generate_table_rows table_rows = [] if @args[:columns] && @args[:columns].length > 0 # manage case with custom columns table_rows = generate_table_rows_from_columns_functions(@args[:columns]) elsif @records && @records.length > 0 # manage case without custom columns table_rows = generate_table_rows_from_columns_functions(@records.first.attributes.keys) end return table_rows end
ruby
def generate_table_rows table_rows = [] if @args[:columns] && @args[:columns].length > 0 # manage case with custom columns table_rows = generate_table_rows_from_columns_functions(@args[:columns]) elsif @records && @records.length > 0 # manage case without custom columns table_rows = generate_table_rows_from_columns_functions(@records.first.attributes.keys) end return table_rows end
[ "def", "generate_table_rows", "table_rows", "=", "[", "]", "if", "@args", "[", ":columns", "]", "&&", "@args", "[", ":columns", "]", ".", "length", ">", "0", "table_rows", "=", "generate_table_rows_from_columns_functions", "(", "@args", "[", ":columns", "]", ")", "elsif", "@records", "&&", "@records", ".", "length", ">", "0", "table_rows", "=", "generate_table_rows_from_columns_functions", "(", "@records", ".", "first", ".", "attributes", ".", "keys", ")", "end", "return", "table_rows", "end" ]
This function generate the rows fr the table.
[ "This", "function", "generate", "the", "rows", "fr", "the", "table", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L137-L149
train
ideonetwork/lato-core
app/cells/lato_core/widgets/index/cell.rb
LatoCore.Widgets::Index::Cell.generate_table_rows_from_columns_functions
def generate_table_rows_from_columns_functions columns_functions table_rows = [] @records.each do |record| labels = [] # add actions to row columns if @args[:actions_on_start] && @show_row_actions labels.push(generate_actions_bottongroup_for_record(record)) end # add function result to row columns columns_functions.each do |column_function| labels.push(record.send(column_function)) end # add actions to row columns if !@args[:actions_on_start] && @show_row_actions labels.push(generate_actions_bottongroup_for_record(record)) end # puts rows on table rows table_rows.push(LatoCore::Elements::Table::Row::Cell.new(labels: labels)) end return table_rows end
ruby
def generate_table_rows_from_columns_functions columns_functions table_rows = [] @records.each do |record| labels = [] # add actions to row columns if @args[:actions_on_start] && @show_row_actions labels.push(generate_actions_bottongroup_for_record(record)) end # add function result to row columns columns_functions.each do |column_function| labels.push(record.send(column_function)) end # add actions to row columns if !@args[:actions_on_start] && @show_row_actions labels.push(generate_actions_bottongroup_for_record(record)) end # puts rows on table rows table_rows.push(LatoCore::Elements::Table::Row::Cell.new(labels: labels)) end return table_rows end
[ "def", "generate_table_rows_from_columns_functions", "columns_functions", "table_rows", "=", "[", "]", "@records", ".", "each", "do", "|", "record", "|", "labels", "=", "[", "]", "if", "@args", "[", ":actions_on_start", "]", "&&", "@show_row_actions", "labels", ".", "push", "(", "generate_actions_bottongroup_for_record", "(", "record", ")", ")", "end", "columns_functions", ".", "each", "do", "|", "column_function", "|", "labels", ".", "push", "(", "record", ".", "send", "(", "column_function", ")", ")", "end", "if", "!", "@args", "[", ":actions_on_start", "]", "&&", "@show_row_actions", "labels", ".", "push", "(", "generate_actions_bottongroup_for_record", "(", "record", ")", ")", "end", "table_rows", ".", "push", "(", "LatoCore", "::", "Elements", "::", "Table", "::", "Row", "::", "Cell", ".", "new", "(", "labels", ":", "labels", ")", ")", "end", "return", "table_rows", "end" ]
This function generate the rows for a list of columns.
[ "This", "function", "generate", "the", "rows", "for", "a", "list", "of", "columns", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L152-L174
train
ideonetwork/lato-core
app/cells/lato_core/widgets/index/cell.rb
LatoCore.Widgets::Index::Cell.generate_actions_bottongroup_for_record
def generate_actions_bottongroup_for_record record action_buttons = [] action_buttons.push(generate_show_button(record.id)) if @args[:actions][:show] action_buttons.push(generate_edit_button(record.id)) if @args[:actions][:edit] action_buttons.push(generate_delete_button(record.id)) if @args[:actions][:delete] return LatoCore::Elements::Buttongroup::Cell.new(buttons: action_buttons) end
ruby
def generate_actions_bottongroup_for_record record action_buttons = [] action_buttons.push(generate_show_button(record.id)) if @args[:actions][:show] action_buttons.push(generate_edit_button(record.id)) if @args[:actions][:edit] action_buttons.push(generate_delete_button(record.id)) if @args[:actions][:delete] return LatoCore::Elements::Buttongroup::Cell.new(buttons: action_buttons) end
[ "def", "generate_actions_bottongroup_for_record", "record", "action_buttons", "=", "[", "]", "action_buttons", ".", "push", "(", "generate_show_button", "(", "record", ".", "id", ")", ")", "if", "@args", "[", ":actions", "]", "[", ":show", "]", "action_buttons", ".", "push", "(", "generate_edit_button", "(", "record", ".", "id", ")", ")", "if", "@args", "[", ":actions", "]", "[", ":edit", "]", "action_buttons", ".", "push", "(", "generate_delete_button", "(", "record", ".", "id", ")", ")", "if", "@args", "[", ":actions", "]", "[", ":delete", "]", "return", "LatoCore", "::", "Elements", "::", "Buttongroup", "::", "Cell", ".", "new", "(", "buttons", ":", "action_buttons", ")", "end" ]
This function generate row actions for a table row.
[ "This", "function", "generate", "row", "actions", "for", "a", "table", "row", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L177-L183
train
ideonetwork/lato-core
app/cells/lato_core/widgets/index/cell.rb
LatoCore.Widgets::Index::Cell.generate_delete_button
def generate_delete_button record_id return unless @args[:index_url] url = @args[:index_url].end_with?('/') ? "#{@args[:index_url].gsub(/\?.*/, '')}#{record_id}" : "#{@args[:index_url].gsub(/\?.*/, '')}/#{record_id}" return LatoCore::Elements::Button::Cell.new(label: LANGUAGES[:lato_core][:mixed][:delete], url: url, method: 'delete', icon: 'trash', style: 'danger', confirmation: { message: LANGUAGES[:lato_core][:mixed][:default_delete_message], positive_response: LANGUAGES[:lato_core][:mixed][:default_delete_positive_response], negative_response: LANGUAGES[:lato_core][:mixed][:default_delete_negative_response] }) end
ruby
def generate_delete_button record_id return unless @args[:index_url] url = @args[:index_url].end_with?('/') ? "#{@args[:index_url].gsub(/\?.*/, '')}#{record_id}" : "#{@args[:index_url].gsub(/\?.*/, '')}/#{record_id}" return LatoCore::Elements::Button::Cell.new(label: LANGUAGES[:lato_core][:mixed][:delete], url: url, method: 'delete', icon: 'trash', style: 'danger', confirmation: { message: LANGUAGES[:lato_core][:mixed][:default_delete_message], positive_response: LANGUAGES[:lato_core][:mixed][:default_delete_positive_response], negative_response: LANGUAGES[:lato_core][:mixed][:default_delete_negative_response] }) end
[ "def", "generate_delete_button", "record_id", "return", "unless", "@args", "[", ":index_url", "]", "url", "=", "@args", "[", ":index_url", "]", ".", "end_with?", "(", "'/'", ")", "?", "\"#{@args[:index_url].gsub(/\\?.*/, '')}#{record_id}\"", ":", "\"#{@args[:index_url].gsub(/\\?.*/, '')}/#{record_id}\"", "return", "LatoCore", "::", "Elements", "::", "Button", "::", "Cell", ".", "new", "(", "label", ":", "LANGUAGES", "[", ":lato_core", "]", "[", ":mixed", "]", "[", ":delete", "]", ",", "url", ":", "url", ",", "method", ":", "'delete'", ",", "icon", ":", "'trash'", ",", "style", ":", "'danger'", ",", "confirmation", ":", "{", "message", ":", "LANGUAGES", "[", ":lato_core", "]", "[", ":mixed", "]", "[", ":default_delete_message", "]", ",", "positive_response", ":", "LANGUAGES", "[", ":lato_core", "]", "[", ":mixed", "]", "[", ":default_delete_positive_response", "]", ",", "negative_response", ":", "LANGUAGES", "[", ":lato_core", "]", "[", ":mixed", "]", "[", ":default_delete_negative_response", "]", "}", ")", "end" ]
This function generate the delete button for a record.
[ "This", "function", "generate", "the", "delete", "button", "for", "a", "record", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L202-L211
train
ideonetwork/lato-core
app/cells/lato_core/widgets/index/cell.rb
LatoCore.Widgets::Index::Cell.generate_new_button
def generate_new_button return unless @args[:index_url] url = "#{@args[:index_url].gsub(/\?.*/, '')}/new" return LatoCore::Elements::Button::Cell.new(label: LANGUAGES[:lato_core][:mixed][:new], url: url, icon: 'plus') end
ruby
def generate_new_button return unless @args[:index_url] url = "#{@args[:index_url].gsub(/\?.*/, '')}/new" return LatoCore::Elements::Button::Cell.new(label: LANGUAGES[:lato_core][:mixed][:new], url: url, icon: 'plus') end
[ "def", "generate_new_button", "return", "unless", "@args", "[", ":index_url", "]", "url", "=", "\"#{@args[:index_url].gsub(/\\?.*/, '')}/new\"", "return", "LatoCore", "::", "Elements", "::", "Button", "::", "Cell", ".", "new", "(", "label", ":", "LANGUAGES", "[", ":lato_core", "]", "[", ":mixed", "]", "[", ":new", "]", ",", "url", ":", "url", ",", "icon", ":", "'plus'", ")", "end" ]
This function generate new button.
[ "This", "function", "generate", "new", "button", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L214-L219
train
ideonetwork/lato-core
app/cells/lato_core/widgets/index/cell.rb
LatoCore.Widgets::Index::Cell.generate_search_input
def generate_search_input search_placeholder = '' if @args[:records].is_a?(Hash) search_placeholder = @args[:records][:search_key].is_a?(Array) ? @args[:records][:search_key].to_sentence : @args[:records][:search_key].humanize end search_value = @args[:records].is_a?(Hash) ? @args[:records][:search] : '' return LatoCore::Inputs::Text::Cell.new(name: 'widget_index[search]', value: search_value, placeholder: search_placeholder) end
ruby
def generate_search_input search_placeholder = '' if @args[:records].is_a?(Hash) search_placeholder = @args[:records][:search_key].is_a?(Array) ? @args[:records][:search_key].to_sentence : @args[:records][:search_key].humanize end search_value = @args[:records].is_a?(Hash) ? @args[:records][:search] : '' return LatoCore::Inputs::Text::Cell.new(name: 'widget_index[search]', value: search_value, placeholder: search_placeholder) end
[ "def", "generate_search_input", "search_placeholder", "=", "''", "if", "@args", "[", ":records", "]", ".", "is_a?", "(", "Hash", ")", "search_placeholder", "=", "@args", "[", ":records", "]", "[", ":search_key", "]", ".", "is_a?", "(", "Array", ")", "?", "@args", "[", ":records", "]", "[", ":search_key", "]", ".", "to_sentence", ":", "@args", "[", ":records", "]", "[", ":search_key", "]", ".", "humanize", "end", "search_value", "=", "@args", "[", ":records", "]", ".", "is_a?", "(", "Hash", ")", "?", "@args", "[", ":records", "]", "[", ":search", "]", ":", "''", "return", "LatoCore", "::", "Inputs", "::", "Text", "::", "Cell", ".", "new", "(", "name", ":", "'widget_index[search]'", ",", "value", ":", "search_value", ",", "placeholder", ":", "search_placeholder", ")", "end" ]
This function generate and return the search input.
[ "This", "function", "generate", "and", "return", "the", "search", "input", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L230-L237
train
ideonetwork/lato-core
app/cells/lato_core/widgets/index/cell.rb
LatoCore.Widgets::Index::Cell.generate_search_submit
def generate_search_submit return LatoCore::Elements::Button::Cell.new(label: ' ', icon: 'search', type: 'submit', icon_align: 'right') end
ruby
def generate_search_submit return LatoCore::Elements::Button::Cell.new(label: ' ', icon: 'search', type: 'submit', icon_align: 'right') end
[ "def", "generate_search_submit", "return", "LatoCore", "::", "Elements", "::", "Button", "::", "Cell", ".", "new", "(", "label", ":", "' '", ",", "icon", ":", "'search'", ",", "type", ":", "'submit'", ",", "icon_align", ":", "'right'", ")", "end" ]
This function generate the search submit button.
[ "This", "function", "generate", "the", "search", "submit", "button", "." ]
c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c
https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L240-L242
train
razor-x/config_curator
lib/config_curator/units/config_file.rb
ConfigCurator.ConfigFile.install_file
def install_file FileUtils.mkdir_p File.dirname(destination_path) FileUtils.copy source_path, destination_path, preserve: true end
ruby
def install_file FileUtils.mkdir_p File.dirname(destination_path) FileUtils.copy source_path, destination_path, preserve: true end
[ "def", "install_file", "FileUtils", ".", "mkdir_p", "File", ".", "dirname", "(", "destination_path", ")", "FileUtils", ".", "copy", "source_path", ",", "destination_path", ",", "preserve", ":", "true", "end" ]
Recursively creates the necessary directories and install the file.
[ "Recursively", "creates", "the", "necessary", "directories", "and", "install", "the", "file", "." ]
b0c0742ba0c36acf66de3eafd23a7d17b210036b
https://github.com/razor-x/config_curator/blob/b0c0742ba0c36acf66de3eafd23a7d17b210036b/lib/config_curator/units/config_file.rb#L61-L64
train
kunishi/algebra-ruby2
lib/algebra/polynomial.rb
Algebra.Polynomial.need_paren_in_coeff?
def need_paren_in_coeff? if constant? c = @coeff[0] if c.respond_to?(:need_paren_in_coeff?) c.need_paren_in_coeff? elsif c.is_a?(Numeric) false else true end elsif !monomial? true else false end end
ruby
def need_paren_in_coeff? if constant? c = @coeff[0] if c.respond_to?(:need_paren_in_coeff?) c.need_paren_in_coeff? elsif c.is_a?(Numeric) false else true end elsif !monomial? true else false end end
[ "def", "need_paren_in_coeff?", "if", "constant?", "c", "=", "@coeff", "[", "0", "]", "if", "c", ".", "respond_to?", "(", ":need_paren_in_coeff?", ")", "c", ".", "need_paren_in_coeff?", "elsif", "c", ".", "is_a?", "(", "Numeric", ")", "false", "else", "true", "end", "elsif", "!", "monomial?", "true", "else", "false", "end", "end" ]
def cont; @coeff.first.gcd_all(* @coeff[1..-1]); end def pp; self / cont; end
[ "def", "cont", ";" ]
8976fbaac14933d3206324c845b879bf67fa0cf7
https://github.com/kunishi/algebra-ruby2/blob/8976fbaac14933d3206324c845b879bf67fa0cf7/lib/algebra/polynomial.rb#L372-L387
train
expresspigeon/expresspigeon-ruby
lib/expresspigeon-ruby/messages.rb
ExpressPigeon.Messages.reports
def reports(from_id, start_date = nil, end_date = nil) params = [] if from_id params << "from_id=#{from_id}" end if start_date and not end_date raise 'must include both start_date and end_date' end if end_date and not start_date raise 'must include both start_date and end_date' end if start_date and end_date params << "start_date=#{start_date.strftime('%FT%T.%L%z')}" params << "end_date=#{end_date.strftime('%FT%T.%L%z')}" end query = "#{@endpoint}?" if params.size > 0 query << params.join('&') end get query end
ruby
def reports(from_id, start_date = nil, end_date = nil) params = [] if from_id params << "from_id=#{from_id}" end if start_date and not end_date raise 'must include both start_date and end_date' end if end_date and not start_date raise 'must include both start_date and end_date' end if start_date and end_date params << "start_date=#{start_date.strftime('%FT%T.%L%z')}" params << "end_date=#{end_date.strftime('%FT%T.%L%z')}" end query = "#{@endpoint}?" if params.size > 0 query << params.join('&') end get query end
[ "def", "reports", "(", "from_id", ",", "start_date", "=", "nil", ",", "end_date", "=", "nil", ")", "params", "=", "[", "]", "if", "from_id", "params", "<<", "\"from_id=#{from_id}\"", "end", "if", "start_date", "and", "not", "end_date", "raise", "'must include both start_date and end_date'", "end", "if", "end_date", "and", "not", "start_date", "raise", "'must include both start_date and end_date'", "end", "if", "start_date", "and", "end_date", "params", "<<", "\"start_date=#{start_date.strftime('%FT%T.%L%z')}\"", "params", "<<", "\"end_date=#{end_date.strftime('%FT%T.%L%z')}\"", "end", "query", "=", "\"#{@endpoint}?\"", "if", "params", ".", "size", ">", "0", "query", "<<", "params", ".", "join", "(", "'&'", ")", "end", "get", "query", "end" ]
Report for a group of messages in a given time period. * +start_date+ is instance of Time * +end_date+ is instance of Time
[ "Report", "for", "a", "group", "of", "messages", "in", "a", "given", "time", "period", "." ]
1cdbd0184c112512724fa827297e7c3880964802
https://github.com/expresspigeon/expresspigeon-ruby/blob/1cdbd0184c112512724fa827297e7c3880964802/lib/expresspigeon-ruby/messages.rb#L61-L87
train
Birdie0/qna_maker
lib/qna_maker/endpoints/train_kb.rb
QnAMaker.Client.train_kb
def train_kb(feedback_records = []) feedback_records = feedback_records.map do |record| { userId: record[0], userQuestion: record[1], kbQuestion: record[2], kbAnswer: record[3] } end response = @http.patch( "#{BASE_URL}/#{@knowledgebase_id}/train", json: { feedbackRecords: feedback_records } ) case response.code when 204 nil when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] when 403 raise ForbiddenError, response.parse['error']['message'] when 404 raise NotFoundError, response.parse['error']['message'] when 408 raise OperationTimeOutError, response.parse['error']['message'] when 429 raise RateLimitExceededError, response.parse['error']['message'] else raise UnknownError, "Oh no! (#{response.code})" end end
ruby
def train_kb(feedback_records = []) feedback_records = feedback_records.map do |record| { userId: record[0], userQuestion: record[1], kbQuestion: record[2], kbAnswer: record[3] } end response = @http.patch( "#{BASE_URL}/#{@knowledgebase_id}/train", json: { feedbackRecords: feedback_records } ) case response.code when 204 nil when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] when 403 raise ForbiddenError, response.parse['error']['message'] when 404 raise NotFoundError, response.parse['error']['message'] when 408 raise OperationTimeOutError, response.parse['error']['message'] when 429 raise RateLimitExceededError, response.parse['error']['message'] else raise UnknownError, "Oh no! (#{response.code})" end end
[ "def", "train_kb", "(", "feedback_records", "=", "[", "]", ")", "feedback_records", "=", "feedback_records", ".", "map", "do", "|", "record", "|", "{", "userId", ":", "record", "[", "0", "]", ",", "userQuestion", ":", "record", "[", "1", "]", ",", "kbQuestion", ":", "record", "[", "2", "]", ",", "kbAnswer", ":", "record", "[", "3", "]", "}", "end", "response", "=", "@http", ".", "patch", "(", "\"#{BASE_URL}/#{@knowledgebase_id}/train\"", ",", "json", ":", "{", "feedbackRecords", ":", "feedback_records", "}", ")", "case", "response", ".", "code", "when", "204", "nil", "when", "400", "raise", "BadArgumentError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", ".", "join", "(", "' '", ")", "when", "401", "raise", "UnauthorizedError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "when", "403", "raise", "ForbiddenError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "when", "404", "raise", "NotFoundError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "when", "408", "raise", "OperationTimeOutError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "when", "429", "raise", "RateLimitExceededError", ",", "response", ".", "parse", "[", "'error'", "]", "[", "'message'", "]", "else", "raise", "UnknownError", ",", "\"Oh no! (#{response.code})\"", "end", "end" ]
The developer of the knowledge base service can use this API to submit user feedback for tuning question-answer matching. QnA Maker uses active learning to learn from the user utterances that come on a published Knowledge base service. @param [Array<Array(String, String, String, String)>] feedback_records \[user_id, user_question, kb_question, kb_answer] @return [nil] on success
[ "The", "developer", "of", "the", "knowledge", "base", "service", "can", "use", "this", "API", "to", "submit", "user", "feedback", "for", "tuning", "question", "-", "answer", "matching", ".", "QnA", "Maker", "uses", "active", "learning", "to", "learn", "from", "the", "user", "utterances", "that", "come", "on", "a", "published", "Knowledge", "base", "service", "." ]
5ac204ede100355352438b8ff4fe30ad84d9257b
https://github.com/Birdie0/qna_maker/blob/5ac204ede100355352438b8ff4fe30ad84d9257b/lib/qna_maker/endpoints/train_kb.rb#L14-L44
train
sawaken/tsparser
lib/definition/arib_time.rb
TSparser.AribTime.convert_mjd_to_date
def convert_mjd_to_date(mjd) y_ = ((mjd - 15078.2) / 365.25).to_i m_ = ((mjd - 14956.1 - (y_ * 365.25).to_i) / 30.6001).to_i d = mjd - 14956 - (y_ * 365.25).to_i - (m_ * 30.6001).to_i k = (m_ == 14 || m_ == 15) ? 1 : 0 y = y_ + k m = m_ - 1 - k * 12 return Date.new(1900 + y, m, d) end
ruby
def convert_mjd_to_date(mjd) y_ = ((mjd - 15078.2) / 365.25).to_i m_ = ((mjd - 14956.1 - (y_ * 365.25).to_i) / 30.6001).to_i d = mjd - 14956 - (y_ * 365.25).to_i - (m_ * 30.6001).to_i k = (m_ == 14 || m_ == 15) ? 1 : 0 y = y_ + k m = m_ - 1 - k * 12 return Date.new(1900 + y, m, d) end
[ "def", "convert_mjd_to_date", "(", "mjd", ")", "y_", "=", "(", "(", "mjd", "-", "15078.2", ")", "/", "365.25", ")", ".", "to_i", "m_", "=", "(", "(", "mjd", "-", "14956.1", "-", "(", "y_", "*", "365.25", ")", ".", "to_i", ")", "/", "30.6001", ")", ".", "to_i", "d", "=", "mjd", "-", "14956", "-", "(", "y_", "*", "365.25", ")", ".", "to_i", "-", "(", "m_", "*", "30.6001", ")", ".", "to_i", "k", "=", "(", "m_", "==", "14", "||", "m_", "==", "15", ")", "?", "1", ":", "0", "y", "=", "y_", "+", "k", "m", "=", "m_", "-", "1", "-", "k", "*", "12", "return", "Date", ".", "new", "(", "1900", "+", "y", ",", "m", ",", "d", ")", "end" ]
ARIB STD-B10 2, appendix-C
[ "ARIB", "STD", "-", "B10", "2", "appendix", "-", "C" ]
069500619eb12528782761356c75e444c328c4e1
https://github.com/sawaken/tsparser/blob/069500619eb12528782761356c75e444c328c4e1/lib/definition/arib_time.rb#L19-L27
train
snusnu/substation
lib/substation/chain.rb
Substation.Chain.call
def call(request) reduce(request) { |result, processor| begin response = processor.call(result) return response unless processor.success?(response) processor.result(response) rescue => exception return on_exception(request, result.data, exception) end } end
ruby
def call(request) reduce(request) { |result, processor| begin response = processor.call(result) return response unless processor.success?(response) processor.result(response) rescue => exception return on_exception(request, result.data, exception) end } end
[ "def", "call", "(", "request", ")", "reduce", "(", "request", ")", "{", "|", "result", ",", "processor", "|", "begin", "response", "=", "processor", ".", "call", "(", "result", ")", "return", "response", "unless", "processor", ".", "success?", "(", "response", ")", "processor", ".", "result", "(", "response", ")", "rescue", "=>", "exception", "return", "on_exception", "(", "request", ",", "result", ".", "data", ",", "exception", ")", "end", "}", "end" ]
Call the chain Invokes all processors and returns either the first {Response::Failure} that it encounters, or if all goes well, the {Response::Success} returned from the last processor. @example module App SOME_ACTION = Substation::Chain.new [ Validator.new(MY_VALIDATOR), Pivot.new(Actions::SOME_ACTION), Presenter.new(Presenters::SomePresenter) ] env = Object.new # your env would obviously differ input = { 'name' => 'John' } request = Substation::Request.new(env, input) response = SOME_ACTION.call(request) if response.success? response.output # => the output wrapped in a presenter else response.output # => if validation, pivot or presenter failed end end @param [Request] request the request to handle @return [Response::Success] the response returned from the last processor @return [Response::Failure] the response returned from the failing processor's failure chain @return [Response::Exception] the response returned from invoking the {#exception_chain} @api public
[ "Call", "the", "chain" ]
fabf062a3640f5e82dae68597f0709b63f6b9027
https://github.com/snusnu/substation/blob/fabf062a3640f5e82dae68597f0709b63f6b9027/lib/substation/chain.rb#L137-L147
train
snusnu/substation
lib/substation/chain.rb
Substation.Chain.on_exception
def on_exception(state, data, exception) response = self.class.exception_response(state, data, exception) exception_chain.call(response) end
ruby
def on_exception(state, data, exception) response = self.class.exception_response(state, data, exception) exception_chain.call(response) end
[ "def", "on_exception", "(", "state", ",", "data", ",", "exception", ")", "response", "=", "self", ".", "class", ".", "exception_response", "(", "state", ",", "data", ",", "exception", ")", "exception_chain", ".", "call", "(", "response", ")", "end" ]
Call the failure chain in case of an uncaught exception @param [Request] request the initial request passed into the chain @param [Object] data the processed data available when the exception was raised @param [Class<StandardError>] exception the exception instance that was raised @return [Response::Exception] @api private
[ "Call", "the", "failure", "chain", "in", "case", "of", "an", "uncaught", "exception" ]
fabf062a3640f5e82dae68597f0709b63f6b9027
https://github.com/snusnu/substation/blob/fabf062a3640f5e82dae68597f0709b63f6b9027/lib/substation/chain.rb#L165-L168
train
mikerodrigues/onkyo_eiscp_ruby
lib/eiscp/receiver.rb
EISCP.Receiver.update_state
def update_state Thread.new do Dictionary.commands.each do |zone, commands| Dictionary.commands[zone].each do |command, info| info[:values].each do |value, _| if value == 'QSTN' send(Parser.parse(command + "QSTN")) # If we send any faster we risk making the stereo drop replies. # A dropped reply is not necessarily indicative of the # receiver's failure to receive the command and change state # accordingly. In this case, we're only making queries, so we do # want to capture every reply. sleep DEFAULT_TIMEOUT end end end end end end
ruby
def update_state Thread.new do Dictionary.commands.each do |zone, commands| Dictionary.commands[zone].each do |command, info| info[:values].each do |value, _| if value == 'QSTN' send(Parser.parse(command + "QSTN")) # If we send any faster we risk making the stereo drop replies. # A dropped reply is not necessarily indicative of the # receiver's failure to receive the command and change state # accordingly. In this case, we're only making queries, so we do # want to capture every reply. sleep DEFAULT_TIMEOUT end end end end end end
[ "def", "update_state", "Thread", ".", "new", "do", "Dictionary", ".", "commands", ".", "each", "do", "|", "zone", ",", "commands", "|", "Dictionary", ".", "commands", "[", "zone", "]", ".", "each", "do", "|", "command", ",", "info", "|", "info", "[", ":values", "]", ".", "each", "do", "|", "value", ",", "_", "|", "if", "value", "==", "'QSTN'", "send", "(", "Parser", ".", "parse", "(", "command", "+", "\"QSTN\"", ")", ")", "sleep", "DEFAULT_TIMEOUT", "end", "end", "end", "end", "end", "end" ]
Runs every command that supports the 'QSTN' value. This is a good way to get the sate of the receiver after connecting.
[ "Runs", "every", "command", "that", "supports", "the", "QSTN", "value", ".", "This", "is", "a", "good", "way", "to", "get", "the", "sate", "of", "the", "receiver", "after", "connecting", "." ]
c51f8b22c74decd88b1d1a91e170885c4ec2a0b0
https://github.com/mikerodrigues/onkyo_eiscp_ruby/blob/c51f8b22c74decd88b1d1a91e170885c4ec2a0b0/lib/eiscp/receiver.rb#L190-L208
train
lautis/sweet_notifications
lib/sweet_notifications/controller_runtime.rb
SweetNotifications.ControllerRuntime.controller_runtime
def controller_runtime(name, log_subscriber) runtime_attr = "#{name.to_s.underscore}_runtime".to_sym Module.new do extend ActiveSupport::Concern attr_internal runtime_attr protected define_method :process_action do |action, *args| log_subscriber.reset_runtime super(action, *args) end define_method :cleanup_view_runtime do |&block| runtime_before_render = log_subscriber.reset_runtime send("#{runtime_attr}=", (send(runtime_attr) || 0) + runtime_before_render) runtime = super(&block) runtime_after_render = log_subscriber.reset_runtime send("#{runtime_attr}=", send(runtime_attr) + runtime_after_render) runtime - runtime_after_render end define_method :append_info_to_payload do |payload| super(payload) runtime = (send(runtime_attr) || 0) + log_subscriber.reset_runtime payload[runtime_attr] = runtime end const_set(:ClassMethods, Module.new do define_method :log_process_action do |payload| messages = super(payload) runtime = payload[runtime_attr] if runtime && runtime != 0 messages << format("#{name}: %.1fms", runtime.to_f) end messages end end) end end
ruby
def controller_runtime(name, log_subscriber) runtime_attr = "#{name.to_s.underscore}_runtime".to_sym Module.new do extend ActiveSupport::Concern attr_internal runtime_attr protected define_method :process_action do |action, *args| log_subscriber.reset_runtime super(action, *args) end define_method :cleanup_view_runtime do |&block| runtime_before_render = log_subscriber.reset_runtime send("#{runtime_attr}=", (send(runtime_attr) || 0) + runtime_before_render) runtime = super(&block) runtime_after_render = log_subscriber.reset_runtime send("#{runtime_attr}=", send(runtime_attr) + runtime_after_render) runtime - runtime_after_render end define_method :append_info_to_payload do |payload| super(payload) runtime = (send(runtime_attr) || 0) + log_subscriber.reset_runtime payload[runtime_attr] = runtime end const_set(:ClassMethods, Module.new do define_method :log_process_action do |payload| messages = super(payload) runtime = payload[runtime_attr] if runtime && runtime != 0 messages << format("#{name}: %.1fms", runtime.to_f) end messages end end) end end
[ "def", "controller_runtime", "(", "name", ",", "log_subscriber", ")", "runtime_attr", "=", "\"#{name.to_s.underscore}_runtime\"", ".", "to_sym", "Module", ".", "new", "do", "extend", "ActiveSupport", "::", "Concern", "attr_internal", "runtime_attr", "protected", "define_method", ":process_action", "do", "|", "action", ",", "*", "args", "|", "log_subscriber", ".", "reset_runtime", "super", "(", "action", ",", "*", "args", ")", "end", "define_method", ":cleanup_view_runtime", "do", "|", "&", "block", "|", "runtime_before_render", "=", "log_subscriber", ".", "reset_runtime", "send", "(", "\"#{runtime_attr}=\"", ",", "(", "send", "(", "runtime_attr", ")", "||", "0", ")", "+", "runtime_before_render", ")", "runtime", "=", "super", "(", "&", "block", ")", "runtime_after_render", "=", "log_subscriber", ".", "reset_runtime", "send", "(", "\"#{runtime_attr}=\"", ",", "send", "(", "runtime_attr", ")", "+", "runtime_after_render", ")", "runtime", "-", "runtime_after_render", "end", "define_method", ":append_info_to_payload", "do", "|", "payload", "|", "super", "(", "payload", ")", "runtime", "=", "(", "send", "(", "runtime_attr", ")", "||", "0", ")", "+", "log_subscriber", ".", "reset_runtime", "payload", "[", "runtime_attr", "]", "=", "runtime", "end", "const_set", "(", ":ClassMethods", ",", "Module", ".", "new", "do", "define_method", ":log_process_action", "do", "|", "payload", "|", "messages", "=", "super", "(", "payload", ")", "runtime", "=", "payload", "[", "runtime_attr", "]", "if", "runtime", "&&", "runtime", "!=", "0", "messages", "<<", "format", "(", "\"#{name}: %.1fms\"", ",", "runtime", ".", "to_f", ")", "end", "messages", "end", "end", ")", "end", "end" ]
Define a controller runtime logger for a LogSusbcriber @param name [String] title for logging @return [Module] controller runtime tracking mixin
[ "Define", "a", "controller", "runtime", "logger", "for", "a", "LogSusbcriber" ]
fcd137a1b474d24e1bc86619d116fc32caba8c19
https://github.com/lautis/sweet_notifications/blob/fcd137a1b474d24e1bc86619d116fc32caba8c19/lib/sweet_notifications/controller_runtime.rb#L11-L51
train