{"repo": "travis-ci/travis.rb", "path": "lib/travis/cli.rb", "func_name": "Travis.CLI.preparse", "original_string": "def preparse(unparsed, args = [], opts = {})\n case unparsed\n when Hash then opts.merge! unparsed\n when Array then unparsed.each { |e| preparse(e, args, opts) }\n else args << unparsed.to_s\n end\n [args, opts]\n end", "language": "ruby", "code": "def preparse(unparsed, args = [], opts = {})\n case unparsed\n when Hash then opts.merge! unparsed\n when Array then unparsed.each { |e| preparse(e, args, opts) }\n else args << unparsed.to_s\n end\n [args, opts]\n end", "code_tokens": ["def", "preparse", "(", "unparsed", ",", "args", "=", "[", "]", ",", "opts", "=", "{", "}", ")", "case", "unparsed", "when", "Hash", "then", "opts", ".", "merge!", "unparsed", "when", "Array", "then", "unparsed", ".", "each", "{", "|", "e", "|", "preparse", "(", "e", ",", "args", ",", "opts", ")", "}", "else", "args", "<<", "unparsed", ".", "to_s", "end", "[", "args", ",", "opts", "]", "end"], "docstring": "can't use flatten as it will flatten hashes", "docstring_tokens": ["can", "t", "use", "flatten", "as", "it", "will", "flatten", "hashes"], "sha": "6547e3ad1393f508c679236a4b0e5403d2732043", "url": "https://github.com/travis-ci/travis.rb/blob/6547e3ad1393f508c679236a4b0e5403d2732043/lib/travis/cli.rb#L117-L124", "partition": "valid"} {"repo": "github/scientist", "path": "lib/scientist/experiment.rb", "func_name": "Scientist::Experiment.MismatchError.to_s", "original_string": "def to_s\n super + \":\\n\" +\n format_observation(result.control) + \"\\n\" +\n result.candidates.map { |candidate| format_observation(candidate) }.join(\"\\n\") +\n \"\\n\"\n end", "language": "ruby", "code": "def to_s\n super + \":\\n\" +\n format_observation(result.control) + \"\\n\" +\n result.candidates.map { |candidate| format_observation(candidate) }.join(\"\\n\") +\n \"\\n\"\n end", "code_tokens": ["def", "to_s", "super", "+", "\":\\n\"", "+", "format_observation", "(", "result", ".", "control", ")", "+", "\"\\n\"", "+", "result", ".", "candidates", ".", "map", "{", "|", "candidate", "|", "format_observation", "(", "candidate", ")", "}", ".", "join", "(", "\"\\n\"", ")", "+", "\"\\n\"", "end"], "docstring": "The default formatting is nearly unreadable, so make it useful.\n\n The assumption here is that errors raised in a test environment are\n printed out as strings, rather than using #inspect.", "docstring_tokens": ["The", "default", "formatting", "is", "nearly", "unreadable", "so", "make", "it", "useful", "."], "sha": "25a22f733d4be523404b22ad818e520d20b57619", "url": "https://github.com/github/scientist/blob/25a22f733d4be523404b22ad818e520d20b57619/lib/scientist/experiment.rb#L34-L39", "partition": "valid"} {"repo": "rest-client/rest-client", "path": "lib/restclient/request.rb", "func_name": "RestClient.Request.process_url_params", "original_string": "def process_url_params(url, headers)\n url_params = nil\n\n # find and extract/remove \"params\" key if the value is a Hash/ParamsArray\n headers.delete_if do |key, value|\n if key.to_s.downcase == 'params' &&\n (value.is_a?(Hash) || value.is_a?(RestClient::ParamsArray))\n if url_params\n raise ArgumentError.new(\"Multiple 'params' options passed\")\n end\n url_params = value\n true\n else\n false\n end\n end\n\n # build resulting URL with query string\n if url_params && !url_params.empty?\n query_string = RestClient::Utils.encode_query_string(url_params)\n\n if url.include?('?')\n url + '&' + query_string\n else\n url + '?' + query_string\n end\n else\n url\n end\n end", "language": "ruby", "code": "def process_url_params(url, headers)\n url_params = nil\n\n # find and extract/remove \"params\" key if the value is a Hash/ParamsArray\n headers.delete_if do |key, value|\n if key.to_s.downcase == 'params' &&\n (value.is_a?(Hash) || value.is_a?(RestClient::ParamsArray))\n if url_params\n raise ArgumentError.new(\"Multiple 'params' options passed\")\n end\n url_params = value\n true\n else\n false\n end\n end\n\n # build resulting URL with query string\n if url_params && !url_params.empty?\n query_string = RestClient::Utils.encode_query_string(url_params)\n\n if url.include?('?')\n url + '&' + query_string\n else\n url + '?' + query_string\n end\n else\n url\n end\n end", "code_tokens": ["def", "process_url_params", "(", "url", ",", "headers", ")", "url_params", "=", "nil", "# find and extract/remove \"params\" key if the value is a Hash/ParamsArray", "headers", ".", "delete_if", "do", "|", "key", ",", "value", "|", "if", "key", ".", "to_s", ".", "downcase", "==", "'params'", "&&", "(", "value", ".", "is_a?", "(", "Hash", ")", "||", "value", ".", "is_a?", "(", "RestClient", "::", "ParamsArray", ")", ")", "if", "url_params", "raise", "ArgumentError", ".", "new", "(", "\"Multiple 'params' options passed\"", ")", "end", "url_params", "=", "value", "true", "else", "false", "end", "end", "# build resulting URL with query string", "if", "url_params", "&&", "!", "url_params", ".", "empty?", "query_string", "=", "RestClient", "::", "Utils", ".", "encode_query_string", "(", "url_params", ")", "if", "url", ".", "include?", "(", "'?'", ")", "url", "+", "'&'", "+", "query_string", "else", "url", "+", "'?'", "+", "query_string", "end", "else", "url", "end", "end"], "docstring": "Extract the query parameters and append them to the url\n\n Look through the headers hash for a :params option (case-insensitive,\n may be string or symbol). If present and the value is a Hash or\n RestClient::ParamsArray, *delete* the key/value pair from the headers\n hash and encode the value into a query string. Append this query string\n to the URL and return the resulting URL.\n\n @param [String] url\n @param [Hash] headers An options/headers hash to process. Mutation\n warning: the params key may be removed if present!\n\n @return [String] resulting url with query string", "docstring_tokens": ["Extract", "the", "query", "parameters", "and", "append", "them", "to", "the", "url"], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/request.rb#L195-L224", "partition": "valid"} {"repo": "rest-client/rest-client", "path": "lib/restclient/request.rb", "func_name": "RestClient.Request.stringify_headers", "original_string": "def stringify_headers headers\n headers.inject({}) do |result, (key, value)|\n if key.is_a? Symbol\n key = key.to_s.split(/_/).map(&:capitalize).join('-')\n end\n if 'CONTENT-TYPE' == key.upcase\n result[key] = maybe_convert_extension(value.to_s)\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|\n maybe_convert_extension(ext.to_s.strip)\n }.join(', ')\n else\n result[key] = value.to_s\n end\n result\n end\n end", "language": "ruby", "code": "def stringify_headers headers\n headers.inject({}) do |result, (key, value)|\n if key.is_a? Symbol\n key = key.to_s.split(/_/).map(&:capitalize).join('-')\n end\n if 'CONTENT-TYPE' == key.upcase\n result[key] = maybe_convert_extension(value.to_s)\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|\n maybe_convert_extension(ext.to_s.strip)\n }.join(', ')\n else\n result[key] = value.to_s\n end\n result\n end\n end", "code_tokens": ["def", "stringify_headers", "headers", "headers", ".", "inject", "(", "{", "}", ")", "do", "|", "result", ",", "(", "key", ",", "value", ")", "|", "if", "key", ".", "is_a?", "Symbol", "key", "=", "key", ".", "to_s", ".", "split", "(", "/", "/", ")", ".", "map", "(", ":capitalize", ")", ".", "join", "(", "'-'", ")", "end", "if", "'CONTENT-TYPE'", "==", "key", ".", "upcase", "result", "[", "key", "]", "=", "maybe_convert_extension", "(", "value", ".", "to_s", ")", "elsif", "'ACCEPT'", "==", "key", ".", "upcase", "# Accept can be composed of several comma-separated values", "if", "value", ".", "is_a?", "Array", "target_values", "=", "value", "else", "target_values", "=", "value", ".", "to_s", ".", "split", "','", "end", "result", "[", "key", "]", "=", "target_values", ".", "map", "{", "|", "ext", "|", "maybe_convert_extension", "(", "ext", ".", "to_s", ".", "strip", ")", "}", ".", "join", "(", "', '", ")", "else", "result", "[", "key", "]", "=", "value", ".", "to_s", "end", "result", "end", "end"], "docstring": "Return a hash of headers whose keys are capitalized strings\n\n BUG: stringify_headers does not fix the capitalization of headers that\n are already Strings. Leaving this behavior as is for now for\n backwards compatibility.\n https://github.com/rest-client/rest-client/issues/599", "docstring_tokens": ["Return", "a", "hash", "of", "headers", "whose", "keys", "are", "capitalized", "strings"], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/request.rb#L553-L575", "partition": "valid"} {"repo": "rest-client/rest-client", "path": "lib/restclient/request.rb", "func_name": "RestClient.Request.maybe_convert_extension", "original_string": "def maybe_convert_extension(ext)\n unless ext =~ /\\A[a-zA-Z0-9_@-]+\\z/\n # Don't look up strings unless they look like they could be a file\n # extension known to mime-types.\n #\n # There currently isn't any API public way to look up extensions\n # directly out of MIME::Types, but the type_for() method only strips\n # off after a period anyway.\n return ext\n end\n\n types = MIME::Types.type_for(ext)\n if types.empty?\n ext\n else\n types.first.content_type\n end\n end", "language": "ruby", "code": "def maybe_convert_extension(ext)\n unless ext =~ /\\A[a-zA-Z0-9_@-]+\\z/\n # Don't look up strings unless they look like they could be a file\n # extension known to mime-types.\n #\n # There currently isn't any API public way to look up extensions\n # directly out of MIME::Types, but the type_for() method only strips\n # off after a period anyway.\n return ext\n end\n\n types = MIME::Types.type_for(ext)\n if types.empty?\n ext\n else\n types.first.content_type\n end\n end", "code_tokens": ["def", "maybe_convert_extension", "(", "ext", ")", "unless", "ext", "=~", "/", "\\A", "\\z", "/", "# Don't look up strings unless they look like they could be a file", "# extension known to mime-types.", "#", "# There currently isn't any API public way to look up extensions", "# directly out of MIME::Types, but the type_for() method only strips", "# off after a period anyway.", "return", "ext", "end", "types", "=", "MIME", "::", "Types", ".", "type_for", "(", "ext", ")", "if", "types", ".", "empty?", "ext", "else", "types", ".", "first", ".", "content_type", "end", "end"], "docstring": "Given a MIME type or file extension, return either a MIME type or, if\n none is found, the input unchanged.\n\n >> maybe_convert_extension('json')\n => 'application/json'\n\n >> maybe_convert_extension('unknown')\n => 'unknown'\n\n >> maybe_convert_extension('application/xml')\n => 'application/xml'\n\n @param ext [String]\n\n @return [String]", "docstring_tokens": ["Given", "a", "MIME", "type", "or", "file", "extension", "return", "either", "a", "MIME", "type", "or", "if", "none", "is", "found", "the", "input", "unchanged", "."], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/request.rb#L856-L873", "partition": "valid"} {"repo": "rest-client/rest-client", "path": "lib/restclient/resource.rb", "func_name": "RestClient.Resource.[]", "original_string": "def [](suburl, &new_block)\n case\n when block_given? then self.class.new(concat_urls(url, suburl), options, &new_block)\n when block then self.class.new(concat_urls(url, suburl), options, &block)\n else self.class.new(concat_urls(url, suburl), options)\n end\n end", "language": "ruby", "code": "def [](suburl, &new_block)\n case\n when block_given? then self.class.new(concat_urls(url, suburl), options, &new_block)\n when block then self.class.new(concat_urls(url, suburl), options, &block)\n else self.class.new(concat_urls(url, suburl), options)\n end\n end", "code_tokens": ["def", "[]", "(", "suburl", ",", "&", "new_block", ")", "case", "when", "block_given?", "then", "self", ".", "class", ".", "new", "(", "concat_urls", "(", "url", ",", "suburl", ")", ",", "options", ",", "new_block", ")", "when", "block", "then", "self", ".", "class", ".", "new", "(", "concat_urls", "(", "url", ",", "suburl", ")", ",", "options", ",", "block", ")", "else", "self", ".", "class", ".", "new", "(", "concat_urls", "(", "url", ",", "suburl", ")", ",", "options", ")", "end", "end"], "docstring": "Construct a subresource, preserving authentication.\n\n Example:\n\n site = RestClient::Resource.new('http://example.com', 'adam', 'mypasswd')\n site['posts/1/comments'].post 'Good article.', :content_type => 'text/plain'\n\n This is especially useful if you wish to define your site in one place and\n call it in multiple locations:\n\n def orders\n RestClient::Resource.new('http://example.com/orders', 'admin', 'mypasswd')\n end\n\n orders.get # GET http://example.com/orders\n orders['1'].get # GET http://example.com/orders/1\n orders['1/items'].delete # DELETE http://example.com/orders/1/items\n\n Nest resources as far as you want:\n\n site = RestClient::Resource.new('http://example.com')\n posts = site['posts']\n first_post = posts['1']\n comments = first_post['comments']\n comments.post 'Hello', :content_type => 'text/plain'", "docstring_tokens": ["Construct", "a", "subresource", "preserving", "authentication", "."], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/resource.rb#L160-L166", "partition": "valid"} {"repo": "rest-client/rest-client", "path": "lib/restclient/abstract_response.rb", "func_name": "RestClient.AbstractResponse.cookies", "original_string": "def cookies\n hash = {}\n\n cookie_jar.cookies(@request.uri).each do |cookie|\n hash[cookie.name] = cookie.value\n end\n\n hash\n end", "language": "ruby", "code": "def cookies\n hash = {}\n\n cookie_jar.cookies(@request.uri).each do |cookie|\n hash[cookie.name] = cookie.value\n end\n\n hash\n end", "code_tokens": ["def", "cookies", "hash", "=", "{", "}", "cookie_jar", ".", "cookies", "(", "@request", ".", "uri", ")", ".", "each", "do", "|", "cookie", "|", "hash", "[", "cookie", ".", "name", "]", "=", "cookie", ".", "value", "end", "hash", "end"], "docstring": "Hash of cookies extracted from response headers.\n\n NB: This will return only cookies whose domain matches this request, and\n may not even return all of those cookies if there are duplicate names.\n Use the full cookie_jar for more nuanced access.\n\n @see #cookie_jar\n\n @return [Hash]", "docstring_tokens": ["Hash", "of", "cookies", "extracted", "from", "response", "headers", "."], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/abstract_response.rb#L78-L86", "partition": "valid"} {"repo": "rest-client/rest-client", "path": "lib/restclient/abstract_response.rb", "func_name": "RestClient.AbstractResponse.cookie_jar", "original_string": "def cookie_jar\n return @cookie_jar if defined?(@cookie_jar) && @cookie_jar\n\n jar = @request.cookie_jar.dup\n headers.fetch(:set_cookie, []).each do |cookie|\n jar.parse(cookie, @request.uri)\n end\n\n @cookie_jar = jar\n end", "language": "ruby", "code": "def cookie_jar\n return @cookie_jar if defined?(@cookie_jar) && @cookie_jar\n\n jar = @request.cookie_jar.dup\n headers.fetch(:set_cookie, []).each do |cookie|\n jar.parse(cookie, @request.uri)\n end\n\n @cookie_jar = jar\n end", "code_tokens": ["def", "cookie_jar", "return", "@cookie_jar", "if", "defined?", "(", "@cookie_jar", ")", "&&", "@cookie_jar", "jar", "=", "@request", ".", "cookie_jar", ".", "dup", "headers", ".", "fetch", "(", ":set_cookie", ",", "[", "]", ")", ".", "each", "do", "|", "cookie", "|", "jar", ".", "parse", "(", "cookie", ",", "@request", ".", "uri", ")", "end", "@cookie_jar", "=", "jar", "end"], "docstring": "Cookie jar extracted from response headers.\n\n @return [HTTP::CookieJar]", "docstring_tokens": ["Cookie", "jar", "extracted", "from", "response", "headers", "."], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/abstract_response.rb#L92-L101", "partition": "valid"} {"repo": "rest-client/rest-client", "path": "lib/restclient/abstract_response.rb", "func_name": "RestClient.AbstractResponse.follow_get_redirection", "original_string": "def follow_get_redirection(&block)\n new_args = request.args.dup\n new_args[:method] = :get\n new_args.delete(:payload)\n\n _follow_redirection(new_args, &block)\n end", "language": "ruby", "code": "def follow_get_redirection(&block)\n new_args = request.args.dup\n new_args[:method] = :get\n new_args.delete(:payload)\n\n _follow_redirection(new_args, &block)\n end", "code_tokens": ["def", "follow_get_redirection", "(", "&", "block", ")", "new_args", "=", "request", ".", "args", ".", "dup", "new_args", "[", ":method", "]", "=", ":get", "new_args", ".", "delete", "(", ":payload", ")", "_follow_redirection", "(", "new_args", ",", "block", ")", "end"], "docstring": "Follow a redirection response, but change the HTTP method to GET and drop\n the payload from the original request.", "docstring_tokens": ["Follow", "a", "redirection", "response", "but", "change", "the", "HTTP", "method", "to", "GET", "and", "drop", "the", "payload", "from", "the", "original", "request", "."], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/abstract_response.rb#L150-L156", "partition": "valid"} {"repo": "rest-client/rest-client", "path": "lib/restclient/abstract_response.rb", "func_name": "RestClient.AbstractResponse._follow_redirection", "original_string": "def _follow_redirection(new_args, &block)\n\n # parse location header and merge into existing URL\n url = headers[:location]\n\n # cannot follow redirection if there is no location header\n unless url\n raise exception_with_response\n end\n\n # handle relative redirects\n unless url.start_with?('http')\n url = URI.parse(request.url).merge(url).to_s\n end\n new_args[:url] = url\n\n new_args[:password] = request.password\n new_args[:user] = request.user\n new_args[:headers] = request.headers\n new_args[:max_redirects] = request.max_redirects - 1\n\n # pass through our new cookie jar\n new_args[:cookies] = cookie_jar\n\n # prepare new request\n new_req = Request.new(new_args)\n\n # append self to redirection history\n new_req.redirection_history = history + [self]\n\n # execute redirected request\n new_req.execute(&block)\n end", "language": "ruby", "code": "def _follow_redirection(new_args, &block)\n\n # parse location header and merge into existing URL\n url = headers[:location]\n\n # cannot follow redirection if there is no location header\n unless url\n raise exception_with_response\n end\n\n # handle relative redirects\n unless url.start_with?('http')\n url = URI.parse(request.url).merge(url).to_s\n end\n new_args[:url] = url\n\n new_args[:password] = request.password\n new_args[:user] = request.user\n new_args[:headers] = request.headers\n new_args[:max_redirects] = request.max_redirects - 1\n\n # pass through our new cookie jar\n new_args[:cookies] = cookie_jar\n\n # prepare new request\n new_req = Request.new(new_args)\n\n # append self to redirection history\n new_req.redirection_history = history + [self]\n\n # execute redirected request\n new_req.execute(&block)\n end", "code_tokens": ["def", "_follow_redirection", "(", "new_args", ",", "&", "block", ")", "# parse location header and merge into existing URL", "url", "=", "headers", "[", ":location", "]", "# cannot follow redirection if there is no location header", "unless", "url", "raise", "exception_with_response", "end", "# handle relative redirects", "unless", "url", ".", "start_with?", "(", "'http'", ")", "url", "=", "URI", ".", "parse", "(", "request", ".", "url", ")", ".", "merge", "(", "url", ")", ".", "to_s", "end", "new_args", "[", ":url", "]", "=", "url", "new_args", "[", ":password", "]", "=", "request", ".", "password", "new_args", "[", ":user", "]", "=", "request", ".", "user", "new_args", "[", ":headers", "]", "=", "request", ".", "headers", "new_args", "[", ":max_redirects", "]", "=", "request", ".", "max_redirects", "-", "1", "# pass through our new cookie jar", "new_args", "[", ":cookies", "]", "=", "cookie_jar", "# prepare new request", "new_req", "=", "Request", ".", "new", "(", "new_args", ")", "# append self to redirection history", "new_req", ".", "redirection_history", "=", "history", "+", "[", "self", "]", "# execute redirected request", "new_req", ".", "execute", "(", "block", ")", "end"], "docstring": "Follow a redirection\n\n @param new_args [Hash] Start with this hash of arguments for the\n redirection request. The hash will be mutated, so be sure to dup any\n existing hash that should not be modified.", "docstring_tokens": ["Follow", "a", "redirection"], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/abstract_response.rb#L202-L234", "partition": "valid"} {"repo": "omniauth/omniauth", "path": "lib/omniauth/strategy.rb", "func_name": "OmniAuth.Strategy.call!", "original_string": "def call!(env) # rubocop:disable CyclomaticComplexity, PerceivedComplexity\n unless env['rack.session']\n error = OmniAuth::NoSessionError.new('You must provide a session to use OmniAuth.')\n raise(error)\n end\n\n @env = env\n @env['omniauth.strategy'] = self if on_auth_path?\n\n return mock_call!(env) if OmniAuth.config.test_mode\n return options_call if on_auth_path? && options_request?\n return request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym)\n return callback_call if on_callback_path?\n return other_phase if respond_to?(:other_phase)\n\n @app.call(env)\n end", "language": "ruby", "code": "def call!(env) # rubocop:disable CyclomaticComplexity, PerceivedComplexity\n unless env['rack.session']\n error = OmniAuth::NoSessionError.new('You must provide a session to use OmniAuth.')\n raise(error)\n end\n\n @env = env\n @env['omniauth.strategy'] = self if on_auth_path?\n\n return mock_call!(env) if OmniAuth.config.test_mode\n return options_call if on_auth_path? && options_request?\n return request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym)\n return callback_call if on_callback_path?\n return other_phase if respond_to?(:other_phase)\n\n @app.call(env)\n end", "code_tokens": ["def", "call!", "(", "env", ")", "# rubocop:disable CyclomaticComplexity, PerceivedComplexity", "unless", "env", "[", "'rack.session'", "]", "error", "=", "OmniAuth", "::", "NoSessionError", ".", "new", "(", "'You must provide a session to use OmniAuth.'", ")", "raise", "(", "error", ")", "end", "@env", "=", "env", "@env", "[", "'omniauth.strategy'", "]", "=", "self", "if", "on_auth_path?", "return", "mock_call!", "(", "env", ")", "if", "OmniAuth", ".", "config", ".", "test_mode", "return", "options_call", "if", "on_auth_path?", "&&", "options_request?", "return", "request_call", "if", "on_request_path?", "&&", "OmniAuth", ".", "config", ".", "allowed_request_methods", ".", "include?", "(", "request", ".", "request_method", ".", "downcase", ".", "to_sym", ")", "return", "callback_call", "if", "on_callback_path?", "return", "other_phase", "if", "respond_to?", "(", ":other_phase", ")", "@app", ".", "call", "(", "env", ")", "end"], "docstring": "The logic for dispatching any additional actions that need\n to be taken. For instance, calling the request phase if\n the request path is recognized.\n\n @param env [Hash] The Rack environment.", "docstring_tokens": ["The", "logic", "for", "dispatching", "any", "additional", "actions", "that", "need", "to", "be", "taken", ".", "For", "instance", "calling", "the", "request", "phase", "if", "the", "request", "path", "is", "recognized", "."], "sha": "cc0f5522621b4a372f4dff0aa608822aa082cb60", "url": "https://github.com/omniauth/omniauth/blob/cc0f5522621b4a372f4dff0aa608822aa082cb60/lib/omniauth/strategy.rb#L177-L193", "partition": "valid"} {"repo": "omniauth/omniauth", "path": "lib/omniauth/strategy.rb", "func_name": "OmniAuth.Strategy.options_call", "original_string": "def options_call\n OmniAuth.config.before_options_phase.call(env) if OmniAuth.config.before_options_phase\n verbs = OmniAuth.config.allowed_request_methods.collect(&:to_s).collect(&:upcase).join(', ')\n [200, {'Allow' => verbs}, []]\n end", "language": "ruby", "code": "def options_call\n OmniAuth.config.before_options_phase.call(env) if OmniAuth.config.before_options_phase\n verbs = OmniAuth.config.allowed_request_methods.collect(&:to_s).collect(&:upcase).join(', ')\n [200, {'Allow' => verbs}, []]\n end", "code_tokens": ["def", "options_call", "OmniAuth", ".", "config", ".", "before_options_phase", ".", "call", "(", "env", ")", "if", "OmniAuth", ".", "config", ".", "before_options_phase", "verbs", "=", "OmniAuth", ".", "config", ".", "allowed_request_methods", ".", "collect", "(", ":to_s", ")", ".", "collect", "(", ":upcase", ")", ".", "join", "(", "', '", ")", "[", "200", ",", "{", "'Allow'", "=>", "verbs", "}", ",", "[", "]", "]", "end"], "docstring": "Responds to an OPTIONS request.", "docstring_tokens": ["Responds", "to", "an", "OPTIONS", "request", "."], "sha": "cc0f5522621b4a372f4dff0aa608822aa082cb60", "url": "https://github.com/omniauth/omniauth/blob/cc0f5522621b4a372f4dff0aa608822aa082cb60/lib/omniauth/strategy.rb#L196-L200", "partition": "valid"} {"repo": "omniauth/omniauth", "path": "lib/omniauth/strategy.rb", "func_name": "OmniAuth.Strategy.callback_call", "original_string": "def callback_call\n setup_phase\n log :info, 'Callback phase initiated.'\n @env['omniauth.origin'] = session.delete('omniauth.origin')\n @env['omniauth.origin'] = nil if env['omniauth.origin'] == ''\n @env['omniauth.params'] = session.delete('omniauth.params') || {}\n OmniAuth.config.before_callback_phase.call(@env) if OmniAuth.config.before_callback_phase\n callback_phase\n end", "language": "ruby", "code": "def callback_call\n setup_phase\n log :info, 'Callback phase initiated.'\n @env['omniauth.origin'] = session.delete('omniauth.origin')\n @env['omniauth.origin'] = nil if env['omniauth.origin'] == ''\n @env['omniauth.params'] = session.delete('omniauth.params') || {}\n OmniAuth.config.before_callback_phase.call(@env) if OmniAuth.config.before_callback_phase\n callback_phase\n end", "code_tokens": ["def", "callback_call", "setup_phase", "log", ":info", ",", "'Callback phase initiated.'", "@env", "[", "'omniauth.origin'", "]", "=", "session", ".", "delete", "(", "'omniauth.origin'", ")", "@env", "[", "'omniauth.origin'", "]", "=", "nil", "if", "env", "[", "'omniauth.origin'", "]", "==", "''", "@env", "[", "'omniauth.params'", "]", "=", "session", ".", "delete", "(", "'omniauth.params'", ")", "||", "{", "}", "OmniAuth", ".", "config", ".", "before_callback_phase", ".", "call", "(", "@env", ")", "if", "OmniAuth", ".", "config", ".", "before_callback_phase", "callback_phase", "end"], "docstring": "Performs the steps necessary to run the callback phase of a strategy.", "docstring_tokens": ["Performs", "the", "steps", "necessary", "to", "run", "the", "callback", "phase", "of", "a", "strategy", "."], "sha": "cc0f5522621b4a372f4dff0aa608822aa082cb60", "url": "https://github.com/omniauth/omniauth/blob/cc0f5522621b4a372f4dff0aa608822aa082cb60/lib/omniauth/strategy.rb#L231-L239", "partition": "valid"} {"repo": "omniauth/omniauth", "path": "lib/omniauth/strategy.rb", "func_name": "OmniAuth.Strategy.mock_call!", "original_string": "def mock_call!(*)\n return mock_request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym)\n return mock_callback_call if on_callback_path?\n\n call_app!\n end", "language": "ruby", "code": "def mock_call!(*)\n return mock_request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym)\n return mock_callback_call if on_callback_path?\n\n call_app!\n end", "code_tokens": ["def", "mock_call!", "(", "*", ")", "return", "mock_request_call", "if", "on_request_path?", "&&", "OmniAuth", ".", "config", ".", "allowed_request_methods", ".", "include?", "(", "request", ".", "request_method", ".", "downcase", ".", "to_sym", ")", "return", "mock_callback_call", "if", "on_callback_path?", "call_app!", "end"], "docstring": "This is called in lieu of the normal request process\n in the event that OmniAuth has been configured to be\n in test mode.", "docstring_tokens": ["This", "is", "called", "in", "lieu", "of", "the", "normal", "request", "process", "in", "the", "event", "that", "OmniAuth", "has", "been", "configured", "to", "be", "in", "test", "mode", "."], "sha": "cc0f5522621b4a372f4dff0aa608822aa082cb60", "url": "https://github.com/omniauth/omniauth/blob/cc0f5522621b4a372f4dff0aa608822aa082cb60/lib/omniauth/strategy.rb#L270-L275", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_savon/lib/ads_savon/model.rb", "func_name": "GoogleAdsSavon.Model.instance_action_module", "original_string": "def instance_action_module\n @instance_action_module ||= Module.new do\n\n # Returns the GoogleAdsSavon::Client from the class instance.\n def client(&block)\n self.class.client(&block)\n end\n\n end.tap { |mod| include(mod) }\n end", "language": "ruby", "code": "def instance_action_module\n @instance_action_module ||= Module.new do\n\n # Returns the GoogleAdsSavon::Client from the class instance.\n def client(&block)\n self.class.client(&block)\n end\n\n end.tap { |mod| include(mod) }\n end", "code_tokens": ["def", "instance_action_module", "@instance_action_module", "||=", "Module", ".", "new", "do", "# Returns the GoogleAdsSavon::Client from the class instance.", "def", "client", "(", "&", "block", ")", "self", ".", "class", ".", "client", "(", "block", ")", "end", "end", ".", "tap", "{", "|", "mod", "|", "include", "(", "mod", ")", "}", "end"], "docstring": "Instance methods.", "docstring_tokens": ["Instance", "methods", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_savon/lib/ads_savon/model.rb#L90-L99", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api.rb", "func_name": "AdwordsApi.Api.soap_header_handler", "original_string": "def soap_header_handler(auth_handler, version, header_ns, default_ns)\n auth_method = @config.read('authentication.method', :OAUTH2)\n handler_class = case auth_method\n when :OAUTH2, :OAUTH2_SERVICE_ACCOUNT\n AdsCommon::SavonHeaders::OAuthHeaderHandler\n else\n raise AdsCommon::Errors::AuthError,\n \"Unknown auth method: %s\" % auth_method\n end\n return handler_class.new(@credential_handler, auth_handler, header_ns,\n default_ns, version)\n end", "language": "ruby", "code": "def soap_header_handler(auth_handler, version, header_ns, default_ns)\n auth_method = @config.read('authentication.method', :OAUTH2)\n handler_class = case auth_method\n when :OAUTH2, :OAUTH2_SERVICE_ACCOUNT\n AdsCommon::SavonHeaders::OAuthHeaderHandler\n else\n raise AdsCommon::Errors::AuthError,\n \"Unknown auth method: %s\" % auth_method\n end\n return handler_class.new(@credential_handler, auth_handler, header_ns,\n default_ns, version)\n end", "code_tokens": ["def", "soap_header_handler", "(", "auth_handler", ",", "version", ",", "header_ns", ",", "default_ns", ")", "auth_method", "=", "@config", ".", "read", "(", "'authentication.method'", ",", ":OAUTH2", ")", "handler_class", "=", "case", "auth_method", "when", ":OAUTH2", ",", ":OAUTH2_SERVICE_ACCOUNT", "AdsCommon", "::", "SavonHeaders", "::", "OAuthHeaderHandler", "else", "raise", "AdsCommon", "::", "Errors", "::", "AuthError", ",", "\"Unknown auth method: %s\"", "%", "auth_method", "end", "return", "handler_class", ".", "new", "(", "@credential_handler", ",", "auth_handler", ",", "header_ns", ",", "default_ns", ",", "version", ")", "end"], "docstring": "Retrieve correct soap_header_handler.\n\n Args:\n - auth_handler: instance of an AdsCommon::Auth::BaseHandler subclass to\n handle authentication\n - version: intended API version\n - header_ns: header namespace\n - default_ns: default namespace\n\n Returns:\n - SOAP header handler", "docstring_tokens": ["Retrieve", "correct", "soap_header_handler", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api.rb#L66-L77", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api.rb", "func_name": "AdwordsApi.Api.report_utils", "original_string": "def report_utils(version = nil)\n version = api_config.default_version if version.nil?\n # Check if version exists.\n if !api_config.versions.include?(version)\n raise AdsCommon::Errors::Error, \"Unknown version '%s'\" % version\n end\n return AdwordsApi::ReportUtils.new(self, version)\n end", "language": "ruby", "code": "def report_utils(version = nil)\n version = api_config.default_version if version.nil?\n # Check if version exists.\n if !api_config.versions.include?(version)\n raise AdsCommon::Errors::Error, \"Unknown version '%s'\" % version\n end\n return AdwordsApi::ReportUtils.new(self, version)\n end", "code_tokens": ["def", "report_utils", "(", "version", "=", "nil", ")", "version", "=", "api_config", ".", "default_version", "if", "version", ".", "nil?", "# Check if version exists.", "if", "!", "api_config", ".", "versions", ".", "include?", "(", "version", ")", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Unknown version '%s'\"", "%", "version", "end", "return", "AdwordsApi", "::", "ReportUtils", ".", "new", "(", "self", ",", "version", ")", "end"], "docstring": "Returns an instance of ReportUtils object with all utilities relevant to\n the reporting.\n\n Args:\n - version: version of the API to use (optional).", "docstring_tokens": ["Returns", "an", "instance", "of", "ReportUtils", "object", "with", "all", "utilities", "relevant", "to", "the", "reporting", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api.rb#L187-L194", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api.rb", "func_name": "AdwordsApi.Api.batch_job_utils", "original_string": "def batch_job_utils(version = nil)\n version = api_config.default_version if version.nil?\n # Check if version exists.\n if !api_config.versions.include?(version)\n raise AdsCommon::Errors::Error, \"Unknown version '%s'\" % version\n end\n return AdwordsApi::BatchJobUtils.new(self, version)\n end", "language": "ruby", "code": "def batch_job_utils(version = nil)\n version = api_config.default_version if version.nil?\n # Check if version exists.\n if !api_config.versions.include?(version)\n raise AdsCommon::Errors::Error, \"Unknown version '%s'\" % version\n end\n return AdwordsApi::BatchJobUtils.new(self, version)\n end", "code_tokens": ["def", "batch_job_utils", "(", "version", "=", "nil", ")", "version", "=", "api_config", ".", "default_version", "if", "version", ".", "nil?", "# Check if version exists.", "if", "!", "api_config", ".", "versions", ".", "include?", "(", "version", ")", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Unknown version '%s'\"", "%", "version", "end", "return", "AdwordsApi", "::", "BatchJobUtils", ".", "new", "(", "self", ",", "version", ")", "end"], "docstring": "Returns an instance of BatchJobUtils object with all utilities relevant\n to running batch jobs.\n\n Args:\n - version: version of the API to use (optional).", "docstring_tokens": ["Returns", "an", "instance", "of", "BatchJobUtils", "object", "with", "all", "utilities", "relevant", "to", "running", "batch", "jobs", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api.rb#L202-L209", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api.rb", "func_name": "AdwordsApi.Api.run_with_temporary_flag", "original_string": "def run_with_temporary_flag(flag_name, flag_value, block)\n previous = @credential_handler.instance_variable_get(flag_name)\n @credential_handler.instance_variable_set(flag_name, flag_value)\n begin\n return block.call\n ensure\n @credential_handler.instance_variable_set(flag_name, previous)\n end\n end", "language": "ruby", "code": "def run_with_temporary_flag(flag_name, flag_value, block)\n previous = @credential_handler.instance_variable_get(flag_name)\n @credential_handler.instance_variable_set(flag_name, flag_value)\n begin\n return block.call\n ensure\n @credential_handler.instance_variable_set(flag_name, previous)\n end\n end", "code_tokens": ["def", "run_with_temporary_flag", "(", "flag_name", ",", "flag_value", ",", "block", ")", "previous", "=", "@credential_handler", ".", "instance_variable_get", "(", "flag_name", ")", "@credential_handler", ".", "instance_variable_set", "(", "flag_name", ",", "flag_value", ")", "begin", "return", "block", ".", "call", "ensure", "@credential_handler", ".", "instance_variable_set", "(", "flag_name", ",", "previous", ")", "end", "end"], "docstring": "Executes block with a temporary flag set to a given value. Returns block\n result.", "docstring_tokens": ["Executes", "block", "with", "a", "temporary", "flag", "set", "to", "a", "given", "value", ".", "Returns", "block", "result", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api.rb#L227-L235", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.validate_arguments", "original_string": "def validate_arguments(args_hash, fields_list, type_ns = nil)\n check_extra_fields(args_hash, array_from_named_list(fields_list))\n add_order_key(args_hash, fields_list)\n fields_list.each do |field|\n key = field[:name]\n item = args_hash[key]\n check_required_argument_present(item, field)\n unless item.nil?\n original_name = field[:original_name]\n if original_name\n key = handle_name_override(args_hash, key, original_name)\n end\n\n item_type = get_full_type_signature(field[:type])\n item_ns = field[:ns] || type_ns\n key = handle_namespace_override(args_hash, key, item_ns) if item_ns\n\n # Separate validation for choice types as we need to inject nodes into\n # the tree. Validate as usual if not a choice type.\n unless validate_choice_argument(item, args_hash, key, item_type)\n validate_arg(item, args_hash, key, item_type)\n end\n end\n end\n return args_hash\n end", "language": "ruby", "code": "def validate_arguments(args_hash, fields_list, type_ns = nil)\n check_extra_fields(args_hash, array_from_named_list(fields_list))\n add_order_key(args_hash, fields_list)\n fields_list.each do |field|\n key = field[:name]\n item = args_hash[key]\n check_required_argument_present(item, field)\n unless item.nil?\n original_name = field[:original_name]\n if original_name\n key = handle_name_override(args_hash, key, original_name)\n end\n\n item_type = get_full_type_signature(field[:type])\n item_ns = field[:ns] || type_ns\n key = handle_namespace_override(args_hash, key, item_ns) if item_ns\n\n # Separate validation for choice types as we need to inject nodes into\n # the tree. Validate as usual if not a choice type.\n unless validate_choice_argument(item, args_hash, key, item_type)\n validate_arg(item, args_hash, key, item_type)\n end\n end\n end\n return args_hash\n end", "code_tokens": ["def", "validate_arguments", "(", "args_hash", ",", "fields_list", ",", "type_ns", "=", "nil", ")", "check_extra_fields", "(", "args_hash", ",", "array_from_named_list", "(", "fields_list", ")", ")", "add_order_key", "(", "args_hash", ",", "fields_list", ")", "fields_list", ".", "each", "do", "|", "field", "|", "key", "=", "field", "[", ":name", "]", "item", "=", "args_hash", "[", "key", "]", "check_required_argument_present", "(", "item", ",", "field", ")", "unless", "item", ".", "nil?", "original_name", "=", "field", "[", ":original_name", "]", "if", "original_name", "key", "=", "handle_name_override", "(", "args_hash", ",", "key", ",", "original_name", ")", "end", "item_type", "=", "get_full_type_signature", "(", "field", "[", ":type", "]", ")", "item_ns", "=", "field", "[", ":ns", "]", "||", "type_ns", "key", "=", "handle_namespace_override", "(", "args_hash", ",", "key", ",", "item_ns", ")", "if", "item_ns", "# Separate validation for choice types as we need to inject nodes into", "# the tree. Validate as usual if not a choice type.", "unless", "validate_choice_argument", "(", "item", ",", "args_hash", ",", "key", ",", "item_type", ")", "validate_arg", "(", "item", ",", "args_hash", ",", "key", ",", "item_type", ")", "end", "end", "end", "return", "args_hash", "end"], "docstring": "Validates given arguments based on provided fields list.", "docstring_tokens": ["Validates", "given", "arguments", "based", "on", "provided", "fields", "list", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L58-L83", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.validate_choice_argument", "original_string": "def validate_choice_argument(item, parent, key, item_type)\n result = false\n if item_type.kind_of?(Hash) && item_type.include?(:choices)\n # If we have an array of choices, we need to go over them individually.\n # We drop original array and replace it with the generated one that's\n # nested one level more.\n if item.kind_of?(Array)\n parent[key] = []\n item.each do |sub_item|\n unless validate_choice_argument(sub_item, parent, key, item_type)\n validate_arg(sub_item, parent, key, item_type)\n end\n end\n return true\n end\n # New root needed for extra nesting we have (choice field).\n new_root = {}\n choice_items = arrayize(item)\n choice_items.each do |choice_item|\n choice_type = choice_item.delete(:xsi_type)\n choice_item_type =\n find_choice_by_xsi_type(choice_type, item_type[:choices])\n if choice_type.nil? || choice_item_type.nil?\n raise AdsCommon::Errors::TypeMismatchError.new(\n 'choice subtype', choice_type, choice_item.to_s())\n end\n choice_item[:xsi_type] = choice_type\n # Note we use original name that produces a string like\n # \"BasicUserList\". That's needed as the name is generated out of\n # standard naming (\"basicUserList\") which would otherwise be produced.\n choice_key = choice_item_type[:original_name]\n new_root[choice_key] = choice_item\n type_signature = get_full_type_signature(choice_type)\n validate_arg(choice_item, new_root, choice_key, type_signature)\n end\n if parent[key].kind_of?(Array)\n parent[key] << new_root\n else\n parent[key] = new_root\n end\n result = true\n end\n return result\n end", "language": "ruby", "code": "def validate_choice_argument(item, parent, key, item_type)\n result = false\n if item_type.kind_of?(Hash) && item_type.include?(:choices)\n # If we have an array of choices, we need to go over them individually.\n # We drop original array and replace it with the generated one that's\n # nested one level more.\n if item.kind_of?(Array)\n parent[key] = []\n item.each do |sub_item|\n unless validate_choice_argument(sub_item, parent, key, item_type)\n validate_arg(sub_item, parent, key, item_type)\n end\n end\n return true\n end\n # New root needed for extra nesting we have (choice field).\n new_root = {}\n choice_items = arrayize(item)\n choice_items.each do |choice_item|\n choice_type = choice_item.delete(:xsi_type)\n choice_item_type =\n find_choice_by_xsi_type(choice_type, item_type[:choices])\n if choice_type.nil? || choice_item_type.nil?\n raise AdsCommon::Errors::TypeMismatchError.new(\n 'choice subtype', choice_type, choice_item.to_s())\n end\n choice_item[:xsi_type] = choice_type\n # Note we use original name that produces a string like\n # \"BasicUserList\". That's needed as the name is generated out of\n # standard naming (\"basicUserList\") which would otherwise be produced.\n choice_key = choice_item_type[:original_name]\n new_root[choice_key] = choice_item\n type_signature = get_full_type_signature(choice_type)\n validate_arg(choice_item, new_root, choice_key, type_signature)\n end\n if parent[key].kind_of?(Array)\n parent[key] << new_root\n else\n parent[key] = new_root\n end\n result = true\n end\n return result\n end", "code_tokens": ["def", "validate_choice_argument", "(", "item", ",", "parent", ",", "key", ",", "item_type", ")", "result", "=", "false", "if", "item_type", ".", "kind_of?", "(", "Hash", ")", "&&", "item_type", ".", "include?", "(", ":choices", ")", "# If we have an array of choices, we need to go over them individually.", "# We drop original array and replace it with the generated one that's", "# nested one level more.", "if", "item", ".", "kind_of?", "(", "Array", ")", "parent", "[", "key", "]", "=", "[", "]", "item", ".", "each", "do", "|", "sub_item", "|", "unless", "validate_choice_argument", "(", "sub_item", ",", "parent", ",", "key", ",", "item_type", ")", "validate_arg", "(", "sub_item", ",", "parent", ",", "key", ",", "item_type", ")", "end", "end", "return", "true", "end", "# New root needed for extra nesting we have (choice field).", "new_root", "=", "{", "}", "choice_items", "=", "arrayize", "(", "item", ")", "choice_items", ".", "each", "do", "|", "choice_item", "|", "choice_type", "=", "choice_item", ".", "delete", "(", ":xsi_type", ")", "choice_item_type", "=", "find_choice_by_xsi_type", "(", "choice_type", ",", "item_type", "[", ":choices", "]", ")", "if", "choice_type", ".", "nil?", "||", "choice_item_type", ".", "nil?", "raise", "AdsCommon", "::", "Errors", "::", "TypeMismatchError", ".", "new", "(", "'choice subtype'", ",", "choice_type", ",", "choice_item", ".", "to_s", "(", ")", ")", "end", "choice_item", "[", ":xsi_type", "]", "=", "choice_type", "# Note we use original name that produces a string like", "# \"BasicUserList\". That's needed as the name is generated out of", "# standard naming (\"basicUserList\") which would otherwise be produced.", "choice_key", "=", "choice_item_type", "[", ":original_name", "]", "new_root", "[", "choice_key", "]", "=", "choice_item", "type_signature", "=", "get_full_type_signature", "(", "choice_type", ")", "validate_arg", "(", "choice_item", ",", "new_root", ",", "choice_key", ",", "type_signature", ")", "end", "if", "parent", "[", "key", "]", ".", "kind_of?", "(", "Array", ")", "parent", "[", "key", "]", "<<", "new_root", "else", "parent", "[", "key", "]", "=", "new_root", "end", "result", "=", "true", "end", "return", "result", "end"], "docstring": "Special handling for choice types. Goes over each item, checks xsi_type\n is set and correct and injects new node for it into the tree. After that,\n recurces with the correct item type.", "docstring_tokens": ["Special", "handling", "for", "choice", "types", ".", "Goes", "over", "each", "item", "checks", "xsi_type", "is", "set", "and", "correct", "and", "injects", "new", "node", "for", "it", "into", "the", "tree", ".", "After", "that", "recurces", "with", "the", "correct", "item", "type", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L88-L131", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.check_extra_fields", "original_string": "def check_extra_fields(args_hash, known_fields)\n extra_fields = args_hash.keys - known_fields - IGNORED_HASH_KEYS\n unless extra_fields.empty?\n raise AdsCommon::Errors::UnexpectedParametersError.new(extra_fields)\n end\n end", "language": "ruby", "code": "def check_extra_fields(args_hash, known_fields)\n extra_fields = args_hash.keys - known_fields - IGNORED_HASH_KEYS\n unless extra_fields.empty?\n raise AdsCommon::Errors::UnexpectedParametersError.new(extra_fields)\n end\n end", "code_tokens": ["def", "check_extra_fields", "(", "args_hash", ",", "known_fields", ")", "extra_fields", "=", "args_hash", ".", "keys", "-", "known_fields", "-", "IGNORED_HASH_KEYS", "unless", "extra_fields", ".", "empty?", "raise", "AdsCommon", "::", "Errors", "::", "UnexpectedParametersError", ".", "new", "(", "extra_fields", ")", "end", "end"], "docstring": "Checks if no extra fields provided outside of known ones.", "docstring_tokens": ["Checks", "if", "no", "extra", "fields", "provided", "outside", "of", "known", "ones", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L153-L158", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.check_required_argument_present", "original_string": "def check_required_argument_present(arg, field)\n # At least one item required, none passed.\n if field[:min_occurs] > 0 and arg.nil?\n raise AdsCommon::Errors::MissingPropertyError.new(\n field[:name], field[:type])\n end\n # An object passed when an array is expected.\n if (field[:max_occurs] == :unbounded) and\n !(arg.nil? or arg.kind_of?(Array))\n raise AdsCommon::Errors::TypeMismatchError.new(\n Array, arg.class, field[:name])\n end\n # An array passed when an object is expected.\n if (field[:max_occurs] == 1) and arg.kind_of?(Array)\n raise AdsCommon::Errors::TypeMismatchError.new(\n field[:type], Array, field[:name])\n end\n end", "language": "ruby", "code": "def check_required_argument_present(arg, field)\n # At least one item required, none passed.\n if field[:min_occurs] > 0 and arg.nil?\n raise AdsCommon::Errors::MissingPropertyError.new(\n field[:name], field[:type])\n end\n # An object passed when an array is expected.\n if (field[:max_occurs] == :unbounded) and\n !(arg.nil? or arg.kind_of?(Array))\n raise AdsCommon::Errors::TypeMismatchError.new(\n Array, arg.class, field[:name])\n end\n # An array passed when an object is expected.\n if (field[:max_occurs] == 1) and arg.kind_of?(Array)\n raise AdsCommon::Errors::TypeMismatchError.new(\n field[:type], Array, field[:name])\n end\n end", "code_tokens": ["def", "check_required_argument_present", "(", "arg", ",", "field", ")", "# At least one item required, none passed.", "if", "field", "[", ":min_occurs", "]", ">", "0", "and", "arg", ".", "nil?", "raise", "AdsCommon", "::", "Errors", "::", "MissingPropertyError", ".", "new", "(", "field", "[", ":name", "]", ",", "field", "[", ":type", "]", ")", "end", "# An object passed when an array is expected.", "if", "(", "field", "[", ":max_occurs", "]", "==", ":unbounded", ")", "and", "!", "(", "arg", ".", "nil?", "or", "arg", ".", "kind_of?", "(", "Array", ")", ")", "raise", "AdsCommon", "::", "Errors", "::", "TypeMismatchError", ".", "new", "(", "Array", ",", "arg", ".", "class", ",", "field", "[", ":name", "]", ")", "end", "# An array passed when an object is expected.", "if", "(", "field", "[", ":max_occurs", "]", "==", "1", ")", "and", "arg", ".", "kind_of?", "(", "Array", ")", "raise", "AdsCommon", "::", "Errors", "::", "TypeMismatchError", ".", "new", "(", "field", "[", ":type", "]", ",", "Array", ",", "field", "[", ":name", "]", ")", "end", "end"], "docstring": "Checks the provided data structure matches wsdl definition.", "docstring_tokens": ["Checks", "the", "provided", "data", "structure", "matches", "wsdl", "definition", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L169-L186", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.handle_name_override", "original_string": "def handle_name_override(args, key, original_name)\n rename_hash_key(args, key, original_name)\n replace_array_item(args[:order!], key, original_name)\n return original_name\n end", "language": "ruby", "code": "def handle_name_override(args, key, original_name)\n rename_hash_key(args, key, original_name)\n replace_array_item(args[:order!], key, original_name)\n return original_name\n end", "code_tokens": ["def", "handle_name_override", "(", "args", ",", "key", ",", "original_name", ")", "rename_hash_key", "(", "args", ",", "key", ",", "original_name", ")", "replace_array_item", "(", "args", "[", ":order!", "]", ",", "key", ",", "original_name", ")", "return", "original_name", "end"], "docstring": "Overrides non-standard name conversion.", "docstring_tokens": ["Overrides", "non", "-", "standard", "name", "conversion", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L189-L193", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.handle_namespace_override", "original_string": "def handle_namespace_override(args, key, ns)\n add_extra_namespace(ns)\n new_key = prefix_key_with_namespace(key.to_s.lower_camelcase, ns)\n rename_hash_key(args, key, new_key)\n replace_array_item(args[:order!], key, new_key)\n return new_key\n end", "language": "ruby", "code": "def handle_namespace_override(args, key, ns)\n add_extra_namespace(ns)\n new_key = prefix_key_with_namespace(key.to_s.lower_camelcase, ns)\n rename_hash_key(args, key, new_key)\n replace_array_item(args[:order!], key, new_key)\n return new_key\n end", "code_tokens": ["def", "handle_namespace_override", "(", "args", ",", "key", ",", "ns", ")", "add_extra_namespace", "(", "ns", ")", "new_key", "=", "prefix_key_with_namespace", "(", "key", ".", "to_s", ".", "lower_camelcase", ",", "ns", ")", "rename_hash_key", "(", "args", ",", "key", ",", "new_key", ")", "replace_array_item", "(", "args", "[", ":order!", "]", ",", "key", ",", "new_key", ")", "return", "new_key", "end"], "docstring": "Overrides non-default namespace if requested.", "docstring_tokens": ["Overrides", "non", "-", "default", "namespace", "if", "requested", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L196-L202", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.validate_arg", "original_string": "def validate_arg(arg, parent, key, arg_type)\n result = case arg\n when Array\n validate_array_arg(arg, parent, key, arg_type)\n when Hash\n validate_hash_arg(arg, parent, key, arg_type)\n when Time\n arg = validate_time_arg(arg, parent, key)\n validate_hash_arg(arg, parent, key, arg_type)\n else\n arg\n end\n return result\n end", "language": "ruby", "code": "def validate_arg(arg, parent, key, arg_type)\n result = case arg\n when Array\n validate_array_arg(arg, parent, key, arg_type)\n when Hash\n validate_hash_arg(arg, parent, key, arg_type)\n when Time\n arg = validate_time_arg(arg, parent, key)\n validate_hash_arg(arg, parent, key, arg_type)\n else\n arg\n end\n return result\n end", "code_tokens": ["def", "validate_arg", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "result", "=", "case", "arg", "when", "Array", "validate_array_arg", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "when", "Hash", "validate_hash_arg", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "when", "Time", "arg", "=", "validate_time_arg", "(", "arg", ",", "parent", ",", "key", ")", "validate_hash_arg", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "else", "arg", "end", "return", "result", "end"], "docstring": "Validates single argument.", "docstring_tokens": ["Validates", "single", "argument", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L205-L218", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.validate_array_arg", "original_string": "def validate_array_arg(arg, parent, key, arg_type)\n result = arg.map do |item|\n validate_arg(item, parent, key, arg_type)\n end\n return result\n end", "language": "ruby", "code": "def validate_array_arg(arg, parent, key, arg_type)\n result = arg.map do |item|\n validate_arg(item, parent, key, arg_type)\n end\n return result\n end", "code_tokens": ["def", "validate_array_arg", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "result", "=", "arg", ".", "map", "do", "|", "item", "|", "validate_arg", "(", "item", ",", "parent", ",", "key", ",", "arg_type", ")", "end", "return", "result", "end"], "docstring": "Validates Array argument.", "docstring_tokens": ["Validates", "Array", "argument", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L221-L226", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.validate_hash_arg", "original_string": "def validate_hash_arg(arg, parent, key, arg_type)\n arg_type = handle_xsi_type(arg, parent, key, arg_type)\n validate_arguments(arg, arg_type[:fields], arg_type[:ns])\n end", "language": "ruby", "code": "def validate_hash_arg(arg, parent, key, arg_type)\n arg_type = handle_xsi_type(arg, parent, key, arg_type)\n validate_arguments(arg, arg_type[:fields], arg_type[:ns])\n end", "code_tokens": ["def", "validate_hash_arg", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "arg_type", "=", "handle_xsi_type", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "validate_arguments", "(", "arg", ",", "arg_type", "[", ":fields", "]", ",", "arg_type", "[", ":ns", "]", ")", "end"], "docstring": "Validates Hash argument.", "docstring_tokens": ["Validates", "Hash", "argument", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L229-L232", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.validate_time_arg", "original_string": "def validate_time_arg(arg, parent, key)\n xml_value = time_to_xml_hash(arg)\n parent[key] = xml_value\n return xml_value\n end", "language": "ruby", "code": "def validate_time_arg(arg, parent, key)\n xml_value = time_to_xml_hash(arg)\n parent[key] = xml_value\n return xml_value\n end", "code_tokens": ["def", "validate_time_arg", "(", "arg", ",", "parent", ",", "key", ")", "xml_value", "=", "time_to_xml_hash", "(", "arg", ")", "parent", "[", "key", "]", "=", "xml_value", "return", "xml_value", "end"], "docstring": "Validates Time argument.", "docstring_tokens": ["Validates", "Time", "argument", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L235-L239", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.add_attribute", "original_string": "def add_attribute(node, key, name, value)\n node[:attributes!] ||= {}\n node[:attributes!][key] ||= {}\n if node[:attributes!][key].include?(name)\n node[:attributes!][key][name] = arrayize(node[:attributes!][key][name])\n node[:attributes!][key][name] << value\n else\n node[:attributes!][key][name] = value\n end\n end", "language": "ruby", "code": "def add_attribute(node, key, name, value)\n node[:attributes!] ||= {}\n node[:attributes!][key] ||= {}\n if node[:attributes!][key].include?(name)\n node[:attributes!][key][name] = arrayize(node[:attributes!][key][name])\n node[:attributes!][key][name] << value\n else\n node[:attributes!][key][name] = value\n end\n end", "code_tokens": ["def", "add_attribute", "(", "node", ",", "key", ",", "name", ",", "value", ")", "node", "[", ":attributes!", "]", "||=", "{", "}", "node", "[", ":attributes!", "]", "[", "key", "]", "||=", "{", "}", "if", "node", "[", ":attributes!", "]", "[", "key", "]", ".", "include?", "(", "name", ")", "node", "[", ":attributes!", "]", "[", "key", "]", "[", "name", "]", "=", "arrayize", "(", "node", "[", ":attributes!", "]", "[", "key", "]", "[", "name", "]", ")", "node", "[", ":attributes!", "]", "[", "key", "]", "[", "name", "]", "<<", "value", "else", "node", "[", ":attributes!", "]", "[", "key", "]", "[", "name", "]", "=", "value", "end", "end"], "docstring": "Adds Savon attribute for given node, key, name and value.", "docstring_tokens": ["Adds", "Savon", "attribute", "for", "given", "node", "key", "name", "and", "value", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L279-L288", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.prefix_key_with_namespace", "original_string": "def prefix_key_with_namespace(key, ns_index = nil)\n namespace = (ns_index.nil?) ? DEFAULT_NAMESPACE : (\"ns%d\" % ns_index)\n return prefix_key(key, namespace)\n end", "language": "ruby", "code": "def prefix_key_with_namespace(key, ns_index = nil)\n namespace = (ns_index.nil?) ? DEFAULT_NAMESPACE : (\"ns%d\" % ns_index)\n return prefix_key(key, namespace)\n end", "code_tokens": ["def", "prefix_key_with_namespace", "(", "key", ",", "ns_index", "=", "nil", ")", "namespace", "=", "(", "ns_index", ".", "nil?", ")", "?", "DEFAULT_NAMESPACE", ":", "(", "\"ns%d\"", "%", "ns_index", ")", "return", "prefix_key", "(", "key", ",", "namespace", ")", "end"], "docstring": "Prefixes a key with a given namespace index or default namespace.", "docstring_tokens": ["Prefixes", "a", "key", "with", "a", "given", "namespace", "index", "or", "default", "namespace", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L291-L294", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.get_full_type_signature", "original_string": "def get_full_type_signature(type_name)\n result = (type_name.nil?) ? nil : @registry.get_type_signature(type_name)\n result[:fields] = implode_parent(result) if result and result[:base]\n return result\n end", "language": "ruby", "code": "def get_full_type_signature(type_name)\n result = (type_name.nil?) ? nil : @registry.get_type_signature(type_name)\n result[:fields] = implode_parent(result) if result and result[:base]\n return result\n end", "code_tokens": ["def", "get_full_type_signature", "(", "type_name", ")", "result", "=", "(", "type_name", ".", "nil?", ")", "?", "nil", ":", "@registry", ".", "get_type_signature", "(", "type_name", ")", "result", "[", ":fields", "]", "=", "implode_parent", "(", "result", ")", "if", "result", "and", "result", "[", ":base", "]", "return", "result", "end"], "docstring": "Returns type signature with all inherited fields.", "docstring_tokens": ["Returns", "type", "signature", "with", "all", "inherited", "fields", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L312-L316", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.implode_parent", "original_string": "def implode_parent(data_type)\n result = []\n if data_type[:base]\n parent_type = @registry.get_type_signature(data_type[:base])\n result += implode_parent(parent_type)\n end\n data_type[:fields].each do |field|\n # If the parent type includes a field with the same name, overwrite it.\n result.reject! {|parent_field| parent_field[:name].eql?(field[:name])}\n # Storing field's namespace.\n field[:ns] = data_type[:ns] if data_type[:ns]\n result << field\n end\n return result\n end", "language": "ruby", "code": "def implode_parent(data_type)\n result = []\n if data_type[:base]\n parent_type = @registry.get_type_signature(data_type[:base])\n result += implode_parent(parent_type)\n end\n data_type[:fields].each do |field|\n # If the parent type includes a field with the same name, overwrite it.\n result.reject! {|parent_field| parent_field[:name].eql?(field[:name])}\n # Storing field's namespace.\n field[:ns] = data_type[:ns] if data_type[:ns]\n result << field\n end\n return result\n end", "code_tokens": ["def", "implode_parent", "(", "data_type", ")", "result", "=", "[", "]", "if", "data_type", "[", ":base", "]", "parent_type", "=", "@registry", ".", "get_type_signature", "(", "data_type", "[", ":base", "]", ")", "result", "+=", "implode_parent", "(", "parent_type", ")", "end", "data_type", "[", ":fields", "]", ".", "each", "do", "|", "field", "|", "# If the parent type includes a field with the same name, overwrite it.", "result", ".", "reject!", "{", "|", "parent_field", "|", "parent_field", "[", ":name", "]", ".", "eql?", "(", "field", "[", ":name", "]", ")", "}", "# Storing field's namespace.", "field", "[", ":ns", "]", "=", "data_type", "[", ":ns", "]", "if", "data_type", "[", ":ns", "]", "result", "<<", "field", "end", "return", "result", "end"], "docstring": "Returns all inherited fields of superclasses for given type.", "docstring_tokens": ["Returns", "all", "inherited", "fields", "of", "superclasses", "for", "given", "type", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L319-L333", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.time_to_xml_hash", "original_string": "def time_to_xml_hash(time)\n return {\n :hour => time.hour, :minute => time.min, :second => time.sec,\n :date => {:year => time.year, :month => time.month, :day => time.day}\n }\n end", "language": "ruby", "code": "def time_to_xml_hash(time)\n return {\n :hour => time.hour, :minute => time.min, :second => time.sec,\n :date => {:year => time.year, :month => time.month, :day => time.day}\n }\n end", "code_tokens": ["def", "time_to_xml_hash", "(", "time", ")", "return", "{", ":hour", "=>", "time", ".", "hour", ",", ":minute", "=>", "time", ".", "min", ",", ":second", "=>", "time", ".", "sec", ",", ":date", "=>", "{", ":year", "=>", "time", ".", "year", ",", ":month", "=>", "time", ".", "month", ",", ":day", "=>", "time", ".", "day", "}", "}", "end"], "docstring": "Converts Time to a hash for XML marshalling.", "docstring_tokens": ["Converts", "Time", "to", "a", "hash", "for", "XML", "marshalling", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L349-L354", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/config.rb", "func_name": "AdsCommon.Config.load", "original_string": "def load(filename)\n begin\n new_config = YAML::load_file(filename)\n if new_config.kind_of?(Hash)\n @config = new_config\n else\n raise AdsCommon::Errors::Error,\n \"Incorrect configuration file: '%s'\" % filename\n end\n rescue TypeError => e\n raise AdsCommon::Errors::Error,\n \"Error parsing configuration file: '%s' (%s)\" % [filename, e]\n end\n return nil\n end", "language": "ruby", "code": "def load(filename)\n begin\n new_config = YAML::load_file(filename)\n if new_config.kind_of?(Hash)\n @config = new_config\n else\n raise AdsCommon::Errors::Error,\n \"Incorrect configuration file: '%s'\" % filename\n end\n rescue TypeError => e\n raise AdsCommon::Errors::Error,\n \"Error parsing configuration file: '%s' (%s)\" % [filename, e]\n end\n return nil\n end", "code_tokens": ["def", "load", "(", "filename", ")", "begin", "new_config", "=", "YAML", "::", "load_file", "(", "filename", ")", "if", "new_config", ".", "kind_of?", "(", "Hash", ")", "@config", "=", "new_config", "else", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Incorrect configuration file: '%s'\"", "%", "filename", "end", "rescue", "TypeError", "=>", "e", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Error parsing configuration file: '%s' (%s)\"", "%", "[", "filename", ",", "e", "]", "end", "return", "nil", "end"], "docstring": "Reads a configuration file into instance variable as a Ruby structure with\n the complete set of keys and values.\n\n Args:\n - filename: config file to be read (*String*)\n\n Raises:\n - Errno::ENOENT if the file does not exist.", "docstring_tokens": ["Reads", "a", "configuration", "file", "into", "instance", "variable", "as", "a", "Ruby", "structure", "with", "the", "complete", "set", "of", "keys", "and", "values", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/config.rb#L79-L93", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/config.rb", "func_name": "AdsCommon.Config.process_hash_keys", "original_string": "def process_hash_keys(hash)\n return hash.inject({}) do |result, pair|\n key, value = pair\n result[key.to_sym] = value.is_a?(Hash) ?\n process_hash_keys(value) : value\n result\n end\n end", "language": "ruby", "code": "def process_hash_keys(hash)\n return hash.inject({}) do |result, pair|\n key, value = pair\n result[key.to_sym] = value.is_a?(Hash) ?\n process_hash_keys(value) : value\n result\n end\n end", "code_tokens": ["def", "process_hash_keys", "(", "hash", ")", "return", "hash", ".", "inject", "(", "{", "}", ")", "do", "|", "result", ",", "pair", "|", "key", ",", "value", "=", "pair", "result", "[", "key", ".", "to_sym", "]", "=", "value", ".", "is_a?", "(", "Hash", ")", "?", "process_hash_keys", "(", "value", ")", ":", "value", "result", "end", "end"], "docstring": "Auxiliary method to recurse through a hash and convert all the keys to\n symbols.", "docstring_tokens": ["Auxiliary", "method", "to", "recurse", "through", "a", "hash", "and", "convert", "all", "the", "keys", "to", "symbols", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/config.rb#L99-L106", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/config.rb", "func_name": "AdsCommon.Config.find_value", "original_string": "def find_value(data, path)\n return (path.nil? or data.nil?) ? nil :\n path.split('.').inject(data) do |node, section|\n break if node.nil?\n key = section.to_sym\n (node.is_a?(Hash) and node.include?(key)) ? node[key] : nil\n end\n end", "language": "ruby", "code": "def find_value(data, path)\n return (path.nil? or data.nil?) ? nil :\n path.split('.').inject(data) do |node, section|\n break if node.nil?\n key = section.to_sym\n (node.is_a?(Hash) and node.include?(key)) ? node[key] : nil\n end\n end", "code_tokens": ["def", "find_value", "(", "data", ",", "path", ")", "return", "(", "path", ".", "nil?", "or", "data", ".", "nil?", ")", "?", "nil", ":", "path", ".", "split", "(", "'.'", ")", ".", "inject", "(", "data", ")", "do", "|", "node", ",", "section", "|", "break", "if", "node", ".", "nil?", "key", "=", "section", ".", "to_sym", "(", "node", ".", "is_a?", "(", "Hash", ")", "and", "node", ".", "include?", "(", "key", ")", ")", "?", "node", "[", "key", "]", ":", "nil", "end", "end"], "docstring": "Finds a value for string of format 'level1.level2.name' in a given hash.", "docstring_tokens": ["Finds", "a", "value", "for", "string", "of", "format", "level1", ".", "level2", ".", "name", "in", "a", "given", "hash", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/config.rb#L109-L116", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/batch_job_utils.rb", "func_name": "AdwordsApi.BatchJobUtils.initialize_url", "original_string": "def initialize_url(batch_job_url)\n headers = DEFAULT_HEADERS\n headers['Content-Length'] = 0\n headers['x-goog-resumable'] = 'start'\n\n response = AdsCommon::Http.post_response(\n batch_job_url, '', @api.config, headers)\n\n return response.headers['Location']\n end", "language": "ruby", "code": "def initialize_url(batch_job_url)\n headers = DEFAULT_HEADERS\n headers['Content-Length'] = 0\n headers['x-goog-resumable'] = 'start'\n\n response = AdsCommon::Http.post_response(\n batch_job_url, '', @api.config, headers)\n\n return response.headers['Location']\n end", "code_tokens": ["def", "initialize_url", "(", "batch_job_url", ")", "headers", "=", "DEFAULT_HEADERS", "headers", "[", "'Content-Length'", "]", "=", "0", "headers", "[", "'x-goog-resumable'", "]", "=", "'start'", "response", "=", "AdsCommon", "::", "Http", ".", "post_response", "(", "batch_job_url", ",", "''", ",", "@api", ".", "config", ",", "headers", ")", "return", "response", ".", "headers", "[", "'Location'", "]", "end"], "docstring": "Initializes an upload URL to get the actual URL to which to upload\n operations.\n\n Args:\n - batch_job_url: The UploadURL provided by BatchJobService\n\n Returns:\n - The URL that should actually be used to upload operations.", "docstring_tokens": ["Initializes", "an", "upload", "URL", "to", "get", "the", "actual", "URL", "to", "which", "to", "upload", "operations", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/batch_job_utils.rb#L85-L94", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/batch_job_utils.rb", "func_name": "AdwordsApi.BatchJobUtils.put_incremental_operations", "original_string": "def put_incremental_operations(\n operations, batch_job_url, total_content_length = 0,\n is_last_request = false)\n @api.utils_reporter.batch_job_utils_used()\n headers = DEFAULT_HEADERS\n soap_operations = generate_soap_operations(operations)\n request_body = soap_operations.join\n is_first_request = (total_content_length == 0)\n\n if is_first_request\n request_body = (UPLOAD_XML_PREFIX % [@version]) + request_body\n end\n if is_last_request\n request_body += UPLOAD_XML_SUFFIX\n end\n\n request_body = add_padding(request_body)\n content_length = request_body.bytesize\n\n headers['Content-Length'] = content_length\n\n lower_bound = total_content_length\n upper_bound = total_content_length + content_length - 1\n total_bytes = is_last_request ? upper_bound + 1 : '*'\n content_range =\n \"bytes %d-%d/%s\" % [lower_bound, upper_bound, total_bytes]\n\n headers['Content-Range'] = content_range\n\n log_request(batch_job_url, headers, request_body)\n\n # The HTTPI library fails to handle the response when uploading\n # incremental requests. We're not interested in the response, so just\n # ignore the error.\n begin\n AdsCommon::Http.put_response(\n batch_job_url, request_body, @api.config, headers)\n rescue ArgumentError\n end\n\n total_content_length += content_length\n return total_content_length\n end", "language": "ruby", "code": "def put_incremental_operations(\n operations, batch_job_url, total_content_length = 0,\n is_last_request = false)\n @api.utils_reporter.batch_job_utils_used()\n headers = DEFAULT_HEADERS\n soap_operations = generate_soap_operations(operations)\n request_body = soap_operations.join\n is_first_request = (total_content_length == 0)\n\n if is_first_request\n request_body = (UPLOAD_XML_PREFIX % [@version]) + request_body\n end\n if is_last_request\n request_body += UPLOAD_XML_SUFFIX\n end\n\n request_body = add_padding(request_body)\n content_length = request_body.bytesize\n\n headers['Content-Length'] = content_length\n\n lower_bound = total_content_length\n upper_bound = total_content_length + content_length - 1\n total_bytes = is_last_request ? upper_bound + 1 : '*'\n content_range =\n \"bytes %d-%d/%s\" % [lower_bound, upper_bound, total_bytes]\n\n headers['Content-Range'] = content_range\n\n log_request(batch_job_url, headers, request_body)\n\n # The HTTPI library fails to handle the response when uploading\n # incremental requests. We're not interested in the response, so just\n # ignore the error.\n begin\n AdsCommon::Http.put_response(\n batch_job_url, request_body, @api.config, headers)\n rescue ArgumentError\n end\n\n total_content_length += content_length\n return total_content_length\n end", "code_tokens": ["def", "put_incremental_operations", "(", "operations", ",", "batch_job_url", ",", "total_content_length", "=", "0", ",", "is_last_request", "=", "false", ")", "@api", ".", "utils_reporter", ".", "batch_job_utils_used", "(", ")", "headers", "=", "DEFAULT_HEADERS", "soap_operations", "=", "generate_soap_operations", "(", "operations", ")", "request_body", "=", "soap_operations", ".", "join", "is_first_request", "=", "(", "total_content_length", "==", "0", ")", "if", "is_first_request", "request_body", "=", "(", "UPLOAD_XML_PREFIX", "%", "[", "@version", "]", ")", "+", "request_body", "end", "if", "is_last_request", "request_body", "+=", "UPLOAD_XML_SUFFIX", "end", "request_body", "=", "add_padding", "(", "request_body", ")", "content_length", "=", "request_body", ".", "bytesize", "headers", "[", "'Content-Length'", "]", "=", "content_length", "lower_bound", "=", "total_content_length", "upper_bound", "=", "total_content_length", "+", "content_length", "-", "1", "total_bytes", "=", "is_last_request", "?", "upper_bound", "+", "1", ":", "'*'", "content_range", "=", "\"bytes %d-%d/%s\"", "%", "[", "lower_bound", ",", "upper_bound", ",", "total_bytes", "]", "headers", "[", "'Content-Range'", "]", "=", "content_range", "log_request", "(", "batch_job_url", ",", "headers", ",", "request_body", ")", "# The HTTPI library fails to handle the response when uploading", "# incremental requests. We're not interested in the response, so just", "# ignore the error.", "begin", "AdsCommon", "::", "Http", ".", "put_response", "(", "batch_job_url", ",", "request_body", ",", "@api", ".", "config", ",", "headers", ")", "rescue", "ArgumentError", "end", "total_content_length", "+=", "content_length", "return", "total_content_length", "end"], "docstring": "Puts the provided operations to the provided URL, allowing\n for incremental followup puts.\n\n Args:\n - soap_operations: An array including SOAP operations provided by\n generate_soap_operations\n - batch_job_url: The UploadURL provided by BatchJobService\n - total_content_length: The total number of bytes already uploaded\n incrementally. Set this to 0 the first time you call the method.\n - is_last_request: Whether or not this set of uploads will conclude the\n full request.\n\n Returns:\n - total content length, including what was just uploaded. Pass this back\n into this method on subsequent calls.", "docstring_tokens": ["Puts", "the", "provided", "operations", "to", "the", "provided", "URL", "allowing", "for", "incremental", "followup", "puts", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/batch_job_utils.rb#L111-L153", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/batch_job_utils.rb", "func_name": "AdwordsApi.BatchJobUtils.get_job_results", "original_string": "def get_job_results(batch_job_url)\n @api.utils_reporter.batch_job_utils_used()\n xml_response = AdsCommon::Http.get_response(batch_job_url, @api.config)\n begin\n return sanitize_result(\n get_nori().parse(xml_response.body)[:mutate_response][:rval])\n rescue\n return nil\n end\n end", "language": "ruby", "code": "def get_job_results(batch_job_url)\n @api.utils_reporter.batch_job_utils_used()\n xml_response = AdsCommon::Http.get_response(batch_job_url, @api.config)\n begin\n return sanitize_result(\n get_nori().parse(xml_response.body)[:mutate_response][:rval])\n rescue\n return nil\n end\n end", "code_tokens": ["def", "get_job_results", "(", "batch_job_url", ")", "@api", ".", "utils_reporter", ".", "batch_job_utils_used", "(", ")", "xml_response", "=", "AdsCommon", "::", "Http", ".", "get_response", "(", "batch_job_url", ",", "@api", ".", "config", ")", "begin", "return", "sanitize_result", "(", "get_nori", "(", ")", ".", "parse", "(", "xml_response", ".", "body", ")", "[", ":mutate_response", "]", "[", ":rval", "]", ")", "rescue", "return", "nil", "end", "end"], "docstring": "Downloads the results of a batch job from the specified URL.\n\n Args:\n - batch_job_url: The URL provided by BatchJobService to fetch the results\n from\n\n Returns:\n - the results of the batch job, as a ruby hash, or nil if none yet exist", "docstring_tokens": ["Downloads", "the", "results", "of", "a", "batch", "job", "from", "the", "specified", "URL", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/batch_job_utils.rb#L164-L173", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/batch_job_utils.rb", "func_name": "AdwordsApi.BatchJobUtils.extract_soap_operations", "original_string": "def extract_soap_operations(full_soap_xml)\n doc = Nokogiri::XML(full_soap_xml)\n operations = doc.css('wsdl|operations')\n operations.attr('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')\n operations.each do |element|\n check_xsi_type(element)\n end\n return operations.to_s\n end", "language": "ruby", "code": "def extract_soap_operations(full_soap_xml)\n doc = Nokogiri::XML(full_soap_xml)\n operations = doc.css('wsdl|operations')\n operations.attr('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')\n operations.each do |element|\n check_xsi_type(element)\n end\n return operations.to_s\n end", "code_tokens": ["def", "extract_soap_operations", "(", "full_soap_xml", ")", "doc", "=", "Nokogiri", "::", "XML", "(", "full_soap_xml", ")", "operations", "=", "doc", ".", "css", "(", "'wsdl|operations'", ")", "operations", ".", "attr", "(", "'xmlns:xsi'", ",", "'http://www.w3.org/2001/XMLSchema-instance'", ")", "operations", ".", "each", "do", "|", "element", "|", "check_xsi_type", "(", "element", ")", "end", "return", "operations", ".", "to_s", "end"], "docstring": "Given a full SOAP xml string, extract just the operations element\n from the SOAP body as a string.", "docstring_tokens": ["Given", "a", "full", "SOAP", "xml", "string", "extract", "just", "the", "operations", "element", "from", "the", "SOAP", "body", "as", "a", "string", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/batch_job_utils.rb#L257-L265", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/batch_job_utils.rb", "func_name": "AdwordsApi.BatchJobUtils.sanitize_result", "original_string": "def sanitize_result(results)\n if results.is_a?(Array)\n ret = []\n results.each do |result|\n ret << sanitize_result(result)\n end\n return ret\n end\n\n if results.is_a?(Hash)\n ret = {}\n results.each do |k, v|\n v = sanitize_result(v) if v.is_a?(Hash)\n ret[k] = v unless k.to_s.start_with?('@')\n end\n return ret\n end\n\n return results\n end", "language": "ruby", "code": "def sanitize_result(results)\n if results.is_a?(Array)\n ret = []\n results.each do |result|\n ret << sanitize_result(result)\n end\n return ret\n end\n\n if results.is_a?(Hash)\n ret = {}\n results.each do |k, v|\n v = sanitize_result(v) if v.is_a?(Hash)\n ret[k] = v unless k.to_s.start_with?('@')\n end\n return ret\n end\n\n return results\n end", "code_tokens": ["def", "sanitize_result", "(", "results", ")", "if", "results", ".", "is_a?", "(", "Array", ")", "ret", "=", "[", "]", "results", ".", "each", "do", "|", "result", "|", "ret", "<<", "sanitize_result", "(", "result", ")", "end", "return", "ret", "end", "if", "results", ".", "is_a?", "(", "Hash", ")", "ret", "=", "{", "}", "results", ".", "each", "do", "|", "k", ",", "v", "|", "v", "=", "sanitize_result", "(", "v", ")", "if", "v", ".", "is_a?", "(", "Hash", ")", "ret", "[", "k", "]", "=", "v", "unless", "k", ".", "to_s", ".", "start_with?", "(", "'@'", ")", "end", "return", "ret", "end", "return", "results", "end"], "docstring": "Removes extraneous XML information from return hash.", "docstring_tokens": ["Removes", "extraneous", "XML", "information", "from", "return", "hash", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/batch_job_utils.rb#L290-L309", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/query_utils/service_query.rb", "func_name": "AdwordsApi.ServiceQuery.has_next_landscape_page", "original_string": "def has_next_landscape_page(page)\n raise ArgumentError,\n 'Cannot page through query with no LIMIT clause.' if @start_index.nil?\n return false unless page[:entries]\n total_landscape_points_in_page = 0\n page[:entries].each do |landscape|\n total_landscape_points_in_page += landscape[:landscape_points].size\n end\n return total_landscape_points_in_page >= @page_size\n end", "language": "ruby", "code": "def has_next_landscape_page(page)\n raise ArgumentError,\n 'Cannot page through query with no LIMIT clause.' if @start_index.nil?\n return false unless page[:entries]\n total_landscape_points_in_page = 0\n page[:entries].each do |landscape|\n total_landscape_points_in_page += landscape[:landscape_points].size\n end\n return total_landscape_points_in_page >= @page_size\n end", "code_tokens": ["def", "has_next_landscape_page", "(", "page", ")", "raise", "ArgumentError", ",", "'Cannot page through query with no LIMIT clause.'", "if", "@start_index", ".", "nil?", "return", "false", "unless", "page", "[", ":entries", "]", "total_landscape_points_in_page", "=", "0", "page", "[", ":entries", "]", ".", "each", "do", "|", "landscape", "|", "total_landscape_points_in_page", "+=", "landscape", "[", ":landscape_points", "]", ".", "size", "end", "return", "total_landscape_points_in_page", ">=", "@page_size", "end"], "docstring": "Determining whether another page exists when dealing with bid landscapes\n is different from other types of queries. Use this method for those cases.", "docstring_tokens": ["Determining", "whether", "another", "page", "exists", "when", "dealing", "with", "bid", "landscapes", "is", "different", "from", "other", "types", "of", "queries", ".", "Use", "this", "method", "for", "those", "cases", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/query_utils/service_query.rb#L36-L45", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api_config.rb", "func_name": "AdsCommon.ApiConfig.version_has_service", "original_string": "def version_has_service(version, service)\n return service_config.include?(version) &&\n service_config[version].include?(service)\n end", "language": "ruby", "code": "def version_has_service(version, service)\n return service_config.include?(version) &&\n service_config[version].include?(service)\n end", "code_tokens": ["def", "version_has_service", "(", "version", ",", "service", ")", "return", "service_config", ".", "include?", "(", "version", ")", "&&", "service_config", "[", "version", "]", ".", "include?", "(", "service", ")", "end"], "docstring": "Does the given version exist and contain the given service?\n\n Returns:\n Boolean indicating whether the given version exists and contains the\n given service", "docstring_tokens": ["Does", "the", "given", "version", "exist", "and", "contain", "the", "given", "service?"], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api_config.rb#L60-L63", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api_config.rb", "func_name": "AdsCommon.ApiConfig.endpoint", "original_string": "def endpoint(version, service)\n base = get_wsdl_base(version)\n if !subdir_config().nil?\n base = base.to_s + subdir_config()[[version, service]].to_s\n end\n return base.to_s + version.to_s + '/' + service.to_s\n end", "language": "ruby", "code": "def endpoint(version, service)\n base = get_wsdl_base(version)\n if !subdir_config().nil?\n base = base.to_s + subdir_config()[[version, service]].to_s\n end\n return base.to_s + version.to_s + '/' + service.to_s\n end", "code_tokens": ["def", "endpoint", "(", "version", ",", "service", ")", "base", "=", "get_wsdl_base", "(", "version", ")", "if", "!", "subdir_config", "(", ")", ".", "nil?", "base", "=", "base", ".", "to_s", "+", "subdir_config", "(", ")", "[", "[", "version", ",", "service", "]", "]", ".", "to_s", "end", "return", "base", ".", "to_s", "+", "version", ".", "to_s", "+", "'/'", "+", "service", ".", "to_s", "end"], "docstring": "Get the endpoint for a service on a given API version.\n\n Args:\n - version: the API version\n - service: the name of the API service\n\n Returns:\n The endpoint URL", "docstring_tokens": ["Get", "the", "endpoint", "for", "a", "service", "on", "a", "given", "API", "version", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api_config.rb#L110-L116", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api_config.rb", "func_name": "AdsCommon.ApiConfig.do_require", "original_string": "def do_require(version, service)\n filename = [api_path, version.to_s, service.to_s.snakecase].join('/')\n require filename\n return filename\n end", "language": "ruby", "code": "def do_require(version, service)\n filename = [api_path, version.to_s, service.to_s.snakecase].join('/')\n require filename\n return filename\n end", "code_tokens": ["def", "do_require", "(", "version", ",", "service", ")", "filename", "=", "[", "api_path", ",", "version", ".", "to_s", ",", "service", ".", "to_s", ".", "snakecase", "]", ".", "join", "(", "'/'", ")", "require", "filename", "return", "filename", "end"], "docstring": "Perform the loading of the necessary source files for a version.\n\n Args:\n - version: the API version\n - service: service name\n\n Returns:\n The filename that was loaded", "docstring_tokens": ["Perform", "the", "loading", "of", "the", "necessary", "source", "files", "for", "a", "version", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api_config.rb#L141-L145", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api_config.rb", "func_name": "AdsCommon.ApiConfig.module_name", "original_string": "def module_name(version, service)\n return [api_name, version.to_s.upcase, service.to_s].join('::')\n end", "language": "ruby", "code": "def module_name(version, service)\n return [api_name, version.to_s.upcase, service.to_s].join('::')\n end", "code_tokens": ["def", "module_name", "(", "version", ",", "service", ")", "return", "[", "api_name", ",", "version", ".", "to_s", ".", "upcase", ",", "service", ".", "to_s", "]", ".", "join", "(", "'::'", ")", "end"], "docstring": "Returns the full module name for a given service.\n\n Args:\n - version: the API version\n - service: the service name\n\n Returns:\n The full module name for the given service", "docstring_tokens": ["Returns", "the", "full", "module", "name", "for", "a", "given", "service", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api_config.rb#L156-L158", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api_config.rb", "func_name": "AdsCommon.ApiConfig.get_wsdls", "original_string": "def get_wsdls(version)\n res = {}\n wsdl_base = get_wsdl_base(version)\n postfix = wsdl_base.start_with?('http') ? '?wsdl' : '.wsdl'\n services(version).each do |service|\n path = wsdl_base\n if (!subdir_config().nil?)\n subdir_name = subdir(version, service);\n path = path + subdir_name if subdir_name and !subdir_name.empty?\n end\n path = path + version.to_s + '/' + service.to_s + postfix\n res[service.to_s] = path\n end\n return res\n end", "language": "ruby", "code": "def get_wsdls(version)\n res = {}\n wsdl_base = get_wsdl_base(version)\n postfix = wsdl_base.start_with?('http') ? '?wsdl' : '.wsdl'\n services(version).each do |service|\n path = wsdl_base\n if (!subdir_config().nil?)\n subdir_name = subdir(version, service);\n path = path + subdir_name if subdir_name and !subdir_name.empty?\n end\n path = path + version.to_s + '/' + service.to_s + postfix\n res[service.to_s] = path\n end\n return res\n end", "code_tokens": ["def", "get_wsdls", "(", "version", ")", "res", "=", "{", "}", "wsdl_base", "=", "get_wsdl_base", "(", "version", ")", "postfix", "=", "wsdl_base", ".", "start_with?", "(", "'http'", ")", "?", "'?wsdl'", ":", "'.wsdl'", "services", "(", "version", ")", ".", "each", "do", "|", "service", "|", "path", "=", "wsdl_base", "if", "(", "!", "subdir_config", "(", ")", ".", "nil?", ")", "subdir_name", "=", "subdir", "(", "version", ",", "service", ")", ";", "path", "=", "path", "+", "subdir_name", "if", "subdir_name", "and", "!", "subdir_name", ".", "empty?", "end", "path", "=", "path", "+", "version", ".", "to_s", "+", "'/'", "+", "service", ".", "to_s", "+", "postfix", "res", "[", "service", ".", "to_s", "]", "=", "path", "end", "return", "res", "end"], "docstring": "Generates an array of WSDL URLs based on defined Services and version\n supplied. This method is used by generators to determine what service\n wrappers to generate.\n\n Args:\n - version: the API version.\n\n Returns\n hash of pairs Service => WSDL URL", "docstring_tokens": ["Generates", "an", "array", "of", "WSDL", "URLs", "based", "on", "defined", "Services", "and", "version", "supplied", ".", "This", "method", "is", "used", "by", "generators", "to", "determine", "what", "service", "wrappers", "to", "generate", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api_config.rb#L183-L197", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_savon/lib/ads_savon/client.rb", "func_name": "GoogleAdsSavon.Client.process", "original_string": "def process(offset = 0, instance = self, &block)\n block.arity > 0 ? yield_objects(offset, instance, &block) : evaluate(instance, &block)\n end", "language": "ruby", "code": "def process(offset = 0, instance = self, &block)\n block.arity > 0 ? yield_objects(offset, instance, &block) : evaluate(instance, &block)\n end", "code_tokens": ["def", "process", "(", "offset", "=", "0", ",", "instance", "=", "self", ",", "&", "block", ")", "block", ".", "arity", ">", "0", "?", "yield_objects", "(", "offset", ",", "instance", ",", "block", ")", ":", "evaluate", "(", "instance", ",", "block", ")", "end"], "docstring": "Processes a given +block+. Yields objects if the block expects any arguments.\n Otherwise evaluates the block in the context of +instance+.", "docstring_tokens": ["Processes", "a", "given", "+", "block", "+", ".", "Yields", "objects", "if", "the", "block", "expects", "any", "arguments", ".", "Otherwise", "evaluates", "the", "block", "in", "the", "context", "of", "+", "instance", "+", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_savon/lib/ads_savon/client.rb#L121-L123", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_savon/lib/ads_savon/client.rb", "func_name": "GoogleAdsSavon.Client.yield_objects", "original_string": "def yield_objects(offset, instance, &block)\n to_yield = [:soap, :wsdl, :http, :wsse]\n yield *(to_yield[offset, block.arity].map { |obj_name| instance.send(obj_name) })\n end", "language": "ruby", "code": "def yield_objects(offset, instance, &block)\n to_yield = [:soap, :wsdl, :http, :wsse]\n yield *(to_yield[offset, block.arity].map { |obj_name| instance.send(obj_name) })\n end", "code_tokens": ["def", "yield_objects", "(", "offset", ",", "instance", ",", "&", "block", ")", "to_yield", "=", "[", ":soap", ",", ":wsdl", ",", ":http", ",", ":wsse", "]", "yield", "(", "to_yield", "[", "offset", ",", "block", ".", "arity", "]", ".", "map", "{", "|", "obj_name", "|", "instance", ".", "send", "(", "obj_name", ")", "}", ")", "end"], "docstring": "Yields a number of objects to a given +block+ depending on how many arguments\n the block is expecting.", "docstring_tokens": ["Yields", "a", "number", "of", "objects", "to", "a", "given", "+", "block", "+", "depending", "on", "how", "many", "arguments", "the", "block", "is", "expecting", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_savon/lib/ads_savon/client.rb#L127-L130", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_savon/lib/ads_savon/client.rb", "func_name": "GoogleAdsSavon.Client.evaluate", "original_string": "def evaluate(instance, &block)\n original_self = eval \"self\", block.binding\n\n # A proxy that attemps to make method calls on +instance+. If a NoMethodError is\n # raised, the call will be made on +original_self+.\n proxy = Object.new\n proxy.instance_eval do\n class << self\n attr_accessor :original_self, :instance\n end\n\n def method_missing(method, *args, &block)\n instance.send(method, *args, &block)\n rescue NoMethodError\n original_self.send(method, *args, &block)\n end\n end\n\n proxy.instance = instance\n proxy.original_self = original_self\n\n proxy.instance_eval &block\n end", "language": "ruby", "code": "def evaluate(instance, &block)\n original_self = eval \"self\", block.binding\n\n # A proxy that attemps to make method calls on +instance+. If a NoMethodError is\n # raised, the call will be made on +original_self+.\n proxy = Object.new\n proxy.instance_eval do\n class << self\n attr_accessor :original_self, :instance\n end\n\n def method_missing(method, *args, &block)\n instance.send(method, *args, &block)\n rescue NoMethodError\n original_self.send(method, *args, &block)\n end\n end\n\n proxy.instance = instance\n proxy.original_self = original_self\n\n proxy.instance_eval &block\n end", "code_tokens": ["def", "evaluate", "(", "instance", ",", "&", "block", ")", "original_self", "=", "eval", "\"self\"", ",", "block", ".", "binding", "# A proxy that attemps to make method calls on +instance+. If a NoMethodError is", "# raised, the call will be made on +original_self+.", "proxy", "=", "Object", ".", "new", "proxy", ".", "instance_eval", "do", "class", "<<", "self", "attr_accessor", ":original_self", ",", ":instance", "end", "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "instance", ".", "send", "(", "method", ",", "args", ",", "block", ")", "rescue", "NoMethodError", "original_self", ".", "send", "(", "method", ",", "args", ",", "block", ")", "end", "end", "proxy", ".", "instance", "=", "instance", "proxy", ".", "original_self", "=", "original_self", "proxy", ".", "instance_eval", "block", "end"], "docstring": "Evaluates a given +block+ inside +instance+. Stores the original block binding.", "docstring_tokens": ["Evaluates", "a", "given", "+", "block", "+", "inside", "+", "instance", "+", ".", "Stores", "the", "original", "block", "binding", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_savon/lib/ads_savon/client.rb#L133-L155", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_savon/lib/ads_savon/client.rb", "func_name": "GoogleAdsSavon.Client.remove_blank_values", "original_string": "def remove_blank_values(hash)\n hash.delete_if { |_, value| value.respond_to?(:empty?) ? value.empty? : !value }\n end", "language": "ruby", "code": "def remove_blank_values(hash)\n hash.delete_if { |_, value| value.respond_to?(:empty?) ? value.empty? : !value }\n end", "code_tokens": ["def", "remove_blank_values", "(", "hash", ")", "hash", ".", "delete_if", "{", "|", "_", ",", "value", "|", "value", ".", "respond_to?", "(", ":empty?", ")", "?", "value", ".", "empty?", ":", "!", "value", "}", "end"], "docstring": "Removes all blank values from a given +hash+.", "docstring_tokens": ["Removes", "all", "blank", "values", "from", "a", "given", "+", "hash", "+", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_savon/lib/ads_savon/client.rb#L158-L160", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb", "func_name": "AdManagerApi.PQLValues.values", "original_string": "def values()\n # values_array is an Ad-Manager-compliant list of values of the following\n # form: [:key => ..., :value => {:xsi_type => ..., :value => ...}]\n values_array = @values.map do |key, value|\n raise 'Missing value in StatementBuilder.' if value.nil?\n raise 'Misconfigured value in StatementBuilder.' unless value.is_a? Hash\n raise 'Value cannot be nil on StatementBuilder.' if value[:value].nil?\n raise 'Missing value type for %s.' % key if value[:xsi_type].nil?\n unless VALUE_TYPES.values.include?(value[:xsi_type])\n raise 'Unknown value type for %s.' % key\n end\n if value[:xsi_type] == 'SetValue'\n if value[:value].map {|v| v.class}.to_set.size > 1\n raise 'Cannot pass more than one type in set variable, %s.' % key\n end\n end\n if value[:xsi_type] == 'DateTimeValue'\n unless value[:value][:time_zone_id]\n raise 'Missing timezone on DateTimeValue variable, %s.' %key\n end\n end\n {:key => key.to_s(), :value => value}\n end\n return values_array\n end", "language": "ruby", "code": "def values()\n # values_array is an Ad-Manager-compliant list of values of the following\n # form: [:key => ..., :value => {:xsi_type => ..., :value => ...}]\n values_array = @values.map do |key, value|\n raise 'Missing value in StatementBuilder.' if value.nil?\n raise 'Misconfigured value in StatementBuilder.' unless value.is_a? Hash\n raise 'Value cannot be nil on StatementBuilder.' if value[:value].nil?\n raise 'Missing value type for %s.' % key if value[:xsi_type].nil?\n unless VALUE_TYPES.values.include?(value[:xsi_type])\n raise 'Unknown value type for %s.' % key\n end\n if value[:xsi_type] == 'SetValue'\n if value[:value].map {|v| v.class}.to_set.size > 1\n raise 'Cannot pass more than one type in set variable, %s.' % key\n end\n end\n if value[:xsi_type] == 'DateTimeValue'\n unless value[:value][:time_zone_id]\n raise 'Missing timezone on DateTimeValue variable, %s.' %key\n end\n end\n {:key => key.to_s(), :value => value}\n end\n return values_array\n end", "code_tokens": ["def", "values", "(", ")", "# values_array is an Ad-Manager-compliant list of values of the following", "# form: [:key => ..., :value => {:xsi_type => ..., :value => ...}]", "values_array", "=", "@values", ".", "map", "do", "|", "key", ",", "value", "|", "raise", "'Missing value in StatementBuilder.'", "if", "value", ".", "nil?", "raise", "'Misconfigured value in StatementBuilder.'", "unless", "value", ".", "is_a?", "Hash", "raise", "'Value cannot be nil on StatementBuilder.'", "if", "value", "[", ":value", "]", ".", "nil?", "raise", "'Missing value type for %s.'", "%", "key", "if", "value", "[", ":xsi_type", "]", ".", "nil?", "unless", "VALUE_TYPES", ".", "values", ".", "include?", "(", "value", "[", ":xsi_type", "]", ")", "raise", "'Unknown value type for %s.'", "%", "key", "end", "if", "value", "[", ":xsi_type", "]", "==", "'SetValue'", "if", "value", "[", ":value", "]", ".", "map", "{", "|", "v", "|", "v", ".", "class", "}", ".", "to_set", ".", "size", ">", "1", "raise", "'Cannot pass more than one type in set variable, %s.'", "%", "key", "end", "end", "if", "value", "[", ":xsi_type", "]", "==", "'DateTimeValue'", "unless", "value", "[", ":value", "]", "[", ":time_zone_id", "]", "raise", "'Missing timezone on DateTimeValue variable, %s.'", "%", "key", "end", "end", "{", ":key", "=>", "key", ".", "to_s", "(", ")", ",", ":value", "=>", "value", "}", "end", "return", "values_array", "end"], "docstring": "Get values as an array, the format the Ad Manager API expects.", "docstring_tokens": ["Get", "values", "as", "an", "array", "the", "format", "the", "Ad", "Manager", "API", "expects", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb#L65-L89", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb", "func_name": "AdManagerApi.PQLValues.generate_value_object", "original_string": "def generate_value_object(value)\n typeKeyValue = VALUE_TYPES.find {|key, val| value.is_a? key}\n dateTypes = [AdManagerApi::AdManagerDate, AdManagerApi::AdManagerDateTime]\n if dateTypes.include?(value.class)\n value = value.to_h\n end\n return value if typeKeyValue.nil?\n return {:xsi_type => typeKeyValue.last, :value => value}\n end", "language": "ruby", "code": "def generate_value_object(value)\n typeKeyValue = VALUE_TYPES.find {|key, val| value.is_a? key}\n dateTypes = [AdManagerApi::AdManagerDate, AdManagerApi::AdManagerDateTime]\n if dateTypes.include?(value.class)\n value = value.to_h\n end\n return value if typeKeyValue.nil?\n return {:xsi_type => typeKeyValue.last, :value => value}\n end", "code_tokens": ["def", "generate_value_object", "(", "value", ")", "typeKeyValue", "=", "VALUE_TYPES", ".", "find", "{", "|", "key", ",", "val", "|", "value", ".", "is_a?", "key", "}", "dateTypes", "=", "[", "AdManagerApi", "::", "AdManagerDate", ",", "AdManagerApi", "::", "AdManagerDateTime", "]", "if", "dateTypes", ".", "include?", "(", "value", ".", "class", ")", "value", "=", "value", ".", "to_h", "end", "return", "value", "if", "typeKeyValue", ".", "nil?", "return", "{", ":xsi_type", "=>", "typeKeyValue", ".", "last", ",", ":value", "=>", "value", "}", "end"], "docstring": "Create an individual value object by inferring the xsi_type. If the value\n type isn't recognized, return the original value parameter.", "docstring_tokens": ["Create", "an", "individual", "value", "object", "by", "inferring", "the", "xsi_type", ".", "If", "the", "value", "type", "isn", "t", "recognized", "return", "the", "original", "value", "parameter", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb#L93-L101", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb", "func_name": "AdManagerApi.StatementBuilder.validate", "original_string": "def validate()\n if !@select.to_s.strip.empty? and @from.to_s.strip.empty?\n raise 'FROM clause is required with SELECT'\n end\n if !@from.to_s.strip.empty? and @select.to_s.strip.empty?\n raise 'SELECT clause is required with FROM'\n end\n if !@offset.nil? and @limit.nil?\n raise 'LIMIT clause is required with OFFSET'\n end\n unless @limit.is_a? Integer or @limit.nil?\n raise 'LIMIT must be an integer'\n end\n unless @offset.is_a? Integer or @offset.nil?\n raise 'OFFSET must be an integer'\n end\n end", "language": "ruby", "code": "def validate()\n if !@select.to_s.strip.empty? and @from.to_s.strip.empty?\n raise 'FROM clause is required with SELECT'\n end\n if !@from.to_s.strip.empty? and @select.to_s.strip.empty?\n raise 'SELECT clause is required with FROM'\n end\n if !@offset.nil? and @limit.nil?\n raise 'LIMIT clause is required with OFFSET'\n end\n unless @limit.is_a? Integer or @limit.nil?\n raise 'LIMIT must be an integer'\n end\n unless @offset.is_a? Integer or @offset.nil?\n raise 'OFFSET must be an integer'\n end\n end", "code_tokens": ["def", "validate", "(", ")", "if", "!", "@select", ".", "to_s", ".", "strip", ".", "empty?", "and", "@from", ".", "to_s", ".", "strip", ".", "empty?", "raise", "'FROM clause is required with SELECT'", "end", "if", "!", "@from", ".", "to_s", ".", "strip", ".", "empty?", "and", "@select", ".", "to_s", ".", "strip", ".", "empty?", "raise", "'SELECT clause is required with FROM'", "end", "if", "!", "@offset", ".", "nil?", "and", "@limit", ".", "nil?", "raise", "'LIMIT clause is required with OFFSET'", "end", "unless", "@limit", ".", "is_a?", "Integer", "or", "@limit", ".", "nil?", "raise", "'LIMIT must be an integer'", "end", "unless", "@offset", ".", "is_a?", "Integer", "or", "@offset", ".", "nil?", "raise", "'OFFSET must be an integer'", "end", "end"], "docstring": "Return a list of validation errors.", "docstring_tokens": ["Return", "a", "list", "of", "validation", "errors", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb#L160-L176", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb", "func_name": "AdManagerApi.StatementBuilder.to_statement", "original_string": "def to_statement()\n @api.utils_reporter.statement_builder_used()\n validate()\n ordering = @ascending ? 'ASC' : 'DESC'\n pql_query = PQLQuery.new\n pql_query << SELECT % @select unless @select.to_s.empty?\n pql_query << FROM % @from unless @from.to_s.empty?\n pql_query << WHERE % @where unless @where.to_s.empty?\n pql_query << ORDER % [@order_by, ordering] unless @order_by.to_s.empty?\n pql_query << LIMIT % @limit unless @limit.nil?\n pql_query << OFFSET % @offset unless @offset.nil?\n return {:query => pql_query.to_s(), :values => @pql_values.values}\n end", "language": "ruby", "code": "def to_statement()\n @api.utils_reporter.statement_builder_used()\n validate()\n ordering = @ascending ? 'ASC' : 'DESC'\n pql_query = PQLQuery.new\n pql_query << SELECT % @select unless @select.to_s.empty?\n pql_query << FROM % @from unless @from.to_s.empty?\n pql_query << WHERE % @where unless @where.to_s.empty?\n pql_query << ORDER % [@order_by, ordering] unless @order_by.to_s.empty?\n pql_query << LIMIT % @limit unless @limit.nil?\n pql_query << OFFSET % @offset unless @offset.nil?\n return {:query => pql_query.to_s(), :values => @pql_values.values}\n end", "code_tokens": ["def", "to_statement", "(", ")", "@api", ".", "utils_reporter", ".", "statement_builder_used", "(", ")", "validate", "(", ")", "ordering", "=", "@ascending", "?", "'ASC'", ":", "'DESC'", "pql_query", "=", "PQLQuery", ".", "new", "pql_query", "<<", "SELECT", "%", "@select", "unless", "@select", ".", "to_s", ".", "empty?", "pql_query", "<<", "FROM", "%", "@from", "unless", "@from", ".", "to_s", ".", "empty?", "pql_query", "<<", "WHERE", "%", "@where", "unless", "@where", ".", "to_s", ".", "empty?", "pql_query", "<<", "ORDER", "%", "[", "@order_by", ",", "ordering", "]", "unless", "@order_by", ".", "to_s", ".", "empty?", "pql_query", "<<", "LIMIT", "%", "@limit", "unless", "@limit", ".", "nil?", "pql_query", "<<", "OFFSET", "%", "@offset", "unless", "@offset", ".", "nil?", "return", "{", ":query", "=>", "pql_query", ".", "to_s", "(", ")", ",", ":values", "=>", "@pql_values", ".", "values", "}", "end"], "docstring": "Create a statement object that can be sent in a Ad Manager API request.", "docstring_tokens": ["Create", "a", "statement", "object", "that", "can", "be", "sent", "in", "a", "Ad", "Manager", "API", "request", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb#L179-L191", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ad_manager_api/lib/ad_manager_api/ad_manager_api_datetime.rb", "func_name": "AdManagerApi.AdManagerDate.method_missing", "original_string": "def method_missing(name, *args, &block)\n result = @date.send(name, *args, &block)\n return self.class.new(@api, result) if result.is_a? Date\n return result\n end", "language": "ruby", "code": "def method_missing(name, *args, &block)\n result = @date.send(name, *args, &block)\n return self.class.new(@api, result) if result.is_a? Date\n return result\n end", "code_tokens": ["def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "result", "=", "@date", ".", "send", "(", "name", ",", "args", ",", "block", ")", "return", "self", ".", "class", ".", "new", "(", "@api", ",", "result", ")", "if", "result", ".", "is_a?", "Date", "return", "result", "end"], "docstring": "When an unrecognized method is applied to AdManagerDate, pass it through\n to the internal ruby Date.", "docstring_tokens": ["When", "an", "unrecognized", "method", "is", "applied", "to", "AdManagerDate", "pass", "it", "through", "to", "the", "internal", "ruby", "Date", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ad_manager_api/lib/ad_manager_api/ad_manager_api_datetime.rb#L62-L66", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ad_manager_api/lib/ad_manager_api/ad_manager_api_datetime.rb", "func_name": "AdManagerApi.AdManagerDateTime.to_h", "original_string": "def to_h\n {\n :date => AdManagerApi::AdManagerDate.new(\n @api, @time.year, @time.month, @time.day\n ).to_h,\n :hour => @time.hour,\n :minute => @time.min,\n :second => @time.sec,\n :time_zone_id => @timezone.identifier\n }\n end", "language": "ruby", "code": "def to_h\n {\n :date => AdManagerApi::AdManagerDate.new(\n @api, @time.year, @time.month, @time.day\n ).to_h,\n :hour => @time.hour,\n :minute => @time.min,\n :second => @time.sec,\n :time_zone_id => @timezone.identifier\n }\n end", "code_tokens": ["def", "to_h", "{", ":date", "=>", "AdManagerApi", "::", "AdManagerDate", ".", "new", "(", "@api", ",", "@time", ".", "year", ",", "@time", ".", "month", ",", "@time", ".", "day", ")", ".", "to_h", ",", ":hour", "=>", "@time", ".", "hour", ",", ":minute", "=>", "@time", ".", "min", ",", ":second", "=>", "@time", ".", "sec", ",", ":time_zone_id", "=>", "@timezone", ".", "identifier", "}", "end"], "docstring": "Convert AdManagerDateTime into a hash representation which can be consumed\n by the Ad Manager API. E.g., a hash that can be passed as PQL DateTime\n variables.\n\n Returns:\n - ad_manager_datetime_hash: a hash representation of an\n AdManagerDateTime", "docstring_tokens": ["Convert", "AdManagerDateTime", "into", "a", "hash", "representation", "which", "can", "be", "consumed", "by", "the", "Ad", "Manager", "API", ".", "E", ".", "g", ".", "a", "hash", "that", "can", "be", "passed", "as", "PQL", "DateTime", "variables", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ad_manager_api/lib/ad_manager_api/ad_manager_api_datetime.rb#L158-L168", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ad_manager_api/lib/ad_manager_api/ad_manager_api_datetime.rb", "func_name": "AdManagerApi.AdManagerDateTime.method_missing", "original_string": "def method_missing(name, *args, &block)\n # Restrict time zone related functions from being passed to internal ruby\n # Time attribute, since AdManagerDateTime handles timezones its own way.\n restricted_functions = [:dst?, :getgm, :getlocal, :getutc, :gmt,\n :gmtime, :gmtoff, :isdst, :localtime, :utc]\n if restricted_functions.include? name\n raise NoMethodError, 'undefined method %s for %s' % [name, self]\n end\n result = @time.send(name, *args, &block)\n if result.is_a? Time\n return self.class.new(@api, result, @timezone.identifier)\n else\n return result\n end\n end", "language": "ruby", "code": "def method_missing(name, *args, &block)\n # Restrict time zone related functions from being passed to internal ruby\n # Time attribute, since AdManagerDateTime handles timezones its own way.\n restricted_functions = [:dst?, :getgm, :getlocal, :getutc, :gmt,\n :gmtime, :gmtoff, :isdst, :localtime, :utc]\n if restricted_functions.include? name\n raise NoMethodError, 'undefined method %s for %s' % [name, self]\n end\n result = @time.send(name, *args, &block)\n if result.is_a? Time\n return self.class.new(@api, result, @timezone.identifier)\n else\n return result\n end\n end", "code_tokens": ["def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "# Restrict time zone related functions from being passed to internal ruby", "# Time attribute, since AdManagerDateTime handles timezones its own way.", "restricted_functions", "=", "[", ":dst?", ",", ":getgm", ",", ":getlocal", ",", ":getutc", ",", ":gmt", ",", ":gmtime", ",", ":gmtoff", ",", ":isdst", ",", ":localtime", ",", ":utc", "]", "if", "restricted_functions", ".", "include?", "name", "raise", "NoMethodError", ",", "'undefined method %s for %s'", "%", "[", "name", ",", "self", "]", "end", "result", "=", "@time", ".", "send", "(", "name", ",", "args", ",", "block", ")", "if", "result", ".", "is_a?", "Time", "return", "self", ".", "class", ".", "new", "(", "@api", ",", "result", ",", "@timezone", ".", "identifier", ")", "else", "return", "result", "end", "end"], "docstring": "When an unrecognized method is applied to AdManagerDateTime, pass it\n through to the internal ruby Time.", "docstring_tokens": ["When", "an", "unrecognized", "method", "is", "applied", "to", "AdManagerDateTime", "pass", "it", "through", "to", "the", "internal", "ruby", "Time", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ad_manager_api/lib/ad_manager_api/ad_manager_api_datetime.rb#L172-L186", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.create_savon_client", "original_string": "def create_savon_client(endpoint, namespace)\n client = GoogleAdsSavon::Client.new do |wsdl, httpi|\n wsdl.endpoint = endpoint\n wsdl.namespace = namespace\n AdsCommon::Http.configure_httpi(@config, httpi)\n end\n client.config.raise_errors = false\n client.config.logger.subject = NoopLogger.new\n return client\n end", "language": "ruby", "code": "def create_savon_client(endpoint, namespace)\n client = GoogleAdsSavon::Client.new do |wsdl, httpi|\n wsdl.endpoint = endpoint\n wsdl.namespace = namespace\n AdsCommon::Http.configure_httpi(@config, httpi)\n end\n client.config.raise_errors = false\n client.config.logger.subject = NoopLogger.new\n return client\n end", "code_tokens": ["def", "create_savon_client", "(", "endpoint", ",", "namespace", ")", "client", "=", "GoogleAdsSavon", "::", "Client", ".", "new", "do", "|", "wsdl", ",", "httpi", "|", "wsdl", ".", "endpoint", "=", "endpoint", "wsdl", ".", "namespace", "=", "namespace", "AdsCommon", "::", "Http", ".", "configure_httpi", "(", "@config", ",", "httpi", ")", "end", "client", ".", "config", ".", "raise_errors", "=", "false", "client", ".", "config", ".", "logger", ".", "subject", "=", "NoopLogger", ".", "new", "return", "client", "end"], "docstring": "Creates and sets up Savon client.", "docstring_tokens": ["Creates", "and", "sets", "up", "Savon", "client", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L66-L75", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.get_soap_xml", "original_string": "def get_soap_xml(action_name, args)\n registry = get_service_registry()\n validator = ParametersValidator.new(registry)\n args = validator.validate_args(action_name, args)\n return handle_soap_request(\n action_name.to_sym, true, args, validator.extra_namespaces)\n end", "language": "ruby", "code": "def get_soap_xml(action_name, args)\n registry = get_service_registry()\n validator = ParametersValidator.new(registry)\n args = validator.validate_args(action_name, args)\n return handle_soap_request(\n action_name.to_sym, true, args, validator.extra_namespaces)\n end", "code_tokens": ["def", "get_soap_xml", "(", "action_name", ",", "args", ")", "registry", "=", "get_service_registry", "(", ")", "validator", "=", "ParametersValidator", ".", "new", "(", "registry", ")", "args", "=", "validator", ".", "validate_args", "(", "action_name", ",", "args", ")", "return", "handle_soap_request", "(", "action_name", ".", "to_sym", ",", "true", ",", "args", ",", "validator", ".", "extra_namespaces", ")", "end"], "docstring": "Generates and returns SOAP XML for the specified action and args.", "docstring_tokens": ["Generates", "and", "returns", "SOAP", "XML", "for", "the", "specified", "action", "and", "args", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L78-L84", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.execute_action", "original_string": "def execute_action(action_name, args, &block)\n registry = get_service_registry()\n validator = ParametersValidator.new(registry)\n args = validator.validate_args(action_name, args)\n request_info, response = handle_soap_request(\n action_name.to_sym, false, args, validator.extra_namespaces)\n do_logging(action_name, request_info, response)\n handle_errors(response)\n extractor = ResultsExtractor.new(registry)\n result = extractor.extract_result(response, action_name, &block)\n run_user_block(extractor, response, result, &block) if block_given?\n return result\n end", "language": "ruby", "code": "def execute_action(action_name, args, &block)\n registry = get_service_registry()\n validator = ParametersValidator.new(registry)\n args = validator.validate_args(action_name, args)\n request_info, response = handle_soap_request(\n action_name.to_sym, false, args, validator.extra_namespaces)\n do_logging(action_name, request_info, response)\n handle_errors(response)\n extractor = ResultsExtractor.new(registry)\n result = extractor.extract_result(response, action_name, &block)\n run_user_block(extractor, response, result, &block) if block_given?\n return result\n end", "code_tokens": ["def", "execute_action", "(", "action_name", ",", "args", ",", "&", "block", ")", "registry", "=", "get_service_registry", "(", ")", "validator", "=", "ParametersValidator", ".", "new", "(", "registry", ")", "args", "=", "validator", ".", "validate_args", "(", "action_name", ",", "args", ")", "request_info", ",", "response", "=", "handle_soap_request", "(", "action_name", ".", "to_sym", ",", "false", ",", "args", ",", "validator", ".", "extra_namespaces", ")", "do_logging", "(", "action_name", ",", "request_info", ",", "response", ")", "handle_errors", "(", "response", ")", "extractor", "=", "ResultsExtractor", ".", "new", "(", "registry", ")", "result", "=", "extractor", ".", "extract_result", "(", "response", ",", "action_name", ",", "block", ")", "run_user_block", "(", "extractor", ",", "response", ",", "result", ",", "block", ")", "if", "block_given?", "return", "result", "end"], "docstring": "Executes SOAP action specified as a string with given arguments.", "docstring_tokens": ["Executes", "SOAP", "action", "specified", "as", "a", "string", "with", "given", "arguments", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L87-L99", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.handle_soap_request", "original_string": "def handle_soap_request(action, xml_only, args, extra_namespaces)\n original_action_name =\n get_service_registry.get_method_signature(action)[:original_name]\n original_action_name = action if original_action_name.nil?\n request_info = nil\n response = @client.request(original_action_name) do |soap, wsdl, http|\n soap.body = args\n @header_handler.prepare_request(http, soap)\n soap.namespaces.merge!(extra_namespaces) unless extra_namespaces.nil?\n return soap.to_xml if xml_only\n request_info = RequestInfo.new(soap.to_xml, http.headers, http.url)\n end\n return request_info, response\n end", "language": "ruby", "code": "def handle_soap_request(action, xml_only, args, extra_namespaces)\n original_action_name =\n get_service_registry.get_method_signature(action)[:original_name]\n original_action_name = action if original_action_name.nil?\n request_info = nil\n response = @client.request(original_action_name) do |soap, wsdl, http|\n soap.body = args\n @header_handler.prepare_request(http, soap)\n soap.namespaces.merge!(extra_namespaces) unless extra_namespaces.nil?\n return soap.to_xml if xml_only\n request_info = RequestInfo.new(soap.to_xml, http.headers, http.url)\n end\n return request_info, response\n end", "code_tokens": ["def", "handle_soap_request", "(", "action", ",", "xml_only", ",", "args", ",", "extra_namespaces", ")", "original_action_name", "=", "get_service_registry", ".", "get_method_signature", "(", "action", ")", "[", ":original_name", "]", "original_action_name", "=", "action", "if", "original_action_name", ".", "nil?", "request_info", "=", "nil", "response", "=", "@client", ".", "request", "(", "original_action_name", ")", "do", "|", "soap", ",", "wsdl", ",", "http", "|", "soap", ".", "body", "=", "args", "@header_handler", ".", "prepare_request", "(", "http", ",", "soap", ")", "soap", ".", "namespaces", ".", "merge!", "(", "extra_namespaces", ")", "unless", "extra_namespaces", ".", "nil?", "return", "soap", ".", "to_xml", "if", "xml_only", "request_info", "=", "RequestInfo", ".", "new", "(", "soap", ".", "to_xml", ",", "http", ".", "headers", ",", "http", ".", "url", ")", "end", "return", "request_info", ",", "response", "end"], "docstring": "Executes the SOAP request with original SOAP name.", "docstring_tokens": ["Executes", "the", "SOAP", "request", "with", "original", "SOAP", "name", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L102-L115", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.handle_errors", "original_string": "def handle_errors(response)\n if response.soap_fault?\n exception = exception_for_soap_fault(response)\n raise exception\n end\n if response.http_error?\n raise AdsCommon::Errors::HttpError,\n \"HTTP Error occurred: %s\" % response.http_error\n end\n end", "language": "ruby", "code": "def handle_errors(response)\n if response.soap_fault?\n exception = exception_for_soap_fault(response)\n raise exception\n end\n if response.http_error?\n raise AdsCommon::Errors::HttpError,\n \"HTTP Error occurred: %s\" % response.http_error\n end\n end", "code_tokens": ["def", "handle_errors", "(", "response", ")", "if", "response", ".", "soap_fault?", "exception", "=", "exception_for_soap_fault", "(", "response", ")", "raise", "exception", "end", "if", "response", ".", "http_error?", "raise", "AdsCommon", "::", "Errors", "::", "HttpError", ",", "\"HTTP Error occurred: %s\"", "%", "response", ".", "http_error", "end", "end"], "docstring": "Checks for errors in response and raises appropriate exception.", "docstring_tokens": ["Checks", "for", "errors", "in", "response", "and", "raises", "appropriate", "exception", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L118-L127", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.exception_for_soap_fault", "original_string": "def exception_for_soap_fault(response)\n begin\n fault = response[:fault]\n if fault[:detail] and fault[:detail][:api_exception_fault]\n exception_fault = fault[:detail][:api_exception_fault]\n exception_name = (\n exception_fault[:application_exception_type] ||\n FALLBACK_API_ERROR_EXCEPTION)\n exception_class = get_module().const_get(exception_name)\n return exception_class.new(exception_fault)\n elsif fault[:faultstring]\n fault_message = fault[:faultstring]\n return AdsCommon::Errors::ApiException.new(\n \"Unknown exception with error: %s\" % fault_message)\n else\n raise ArgumentError.new(fault.to_s)\n end\n rescue Exception => e\n return AdsCommon::Errors::ApiException.new(\n \"Failed to resolve exception (%s), SOAP fault: %s\" %\n [e.message, response.soap_fault])\n end\n end", "language": "ruby", "code": "def exception_for_soap_fault(response)\n begin\n fault = response[:fault]\n if fault[:detail] and fault[:detail][:api_exception_fault]\n exception_fault = fault[:detail][:api_exception_fault]\n exception_name = (\n exception_fault[:application_exception_type] ||\n FALLBACK_API_ERROR_EXCEPTION)\n exception_class = get_module().const_get(exception_name)\n return exception_class.new(exception_fault)\n elsif fault[:faultstring]\n fault_message = fault[:faultstring]\n return AdsCommon::Errors::ApiException.new(\n \"Unknown exception with error: %s\" % fault_message)\n else\n raise ArgumentError.new(fault.to_s)\n end\n rescue Exception => e\n return AdsCommon::Errors::ApiException.new(\n \"Failed to resolve exception (%s), SOAP fault: %s\" %\n [e.message, response.soap_fault])\n end\n end", "code_tokens": ["def", "exception_for_soap_fault", "(", "response", ")", "begin", "fault", "=", "response", "[", ":fault", "]", "if", "fault", "[", ":detail", "]", "and", "fault", "[", ":detail", "]", "[", ":api_exception_fault", "]", "exception_fault", "=", "fault", "[", ":detail", "]", "[", ":api_exception_fault", "]", "exception_name", "=", "(", "exception_fault", "[", ":application_exception_type", "]", "||", "FALLBACK_API_ERROR_EXCEPTION", ")", "exception_class", "=", "get_module", "(", ")", ".", "const_get", "(", "exception_name", ")", "return", "exception_class", ".", "new", "(", "exception_fault", ")", "elsif", "fault", "[", ":faultstring", "]", "fault_message", "=", "fault", "[", ":faultstring", "]", "return", "AdsCommon", "::", "Errors", "::", "ApiException", ".", "new", "(", "\"Unknown exception with error: %s\"", "%", "fault_message", ")", "else", "raise", "ArgumentError", ".", "new", "(", "fault", ".", "to_s", ")", "end", "rescue", "Exception", "=>", "e", "return", "AdsCommon", "::", "Errors", "::", "ApiException", ".", "new", "(", "\"Failed to resolve exception (%s), SOAP fault: %s\"", "%", "[", "e", ".", "message", ",", "response", ".", "soap_fault", "]", ")", "end", "end"], "docstring": "Finds an exception object for a given response.", "docstring_tokens": ["Finds", "an", "exception", "object", "for", "a", "given", "response", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L130-L152", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.run_user_block", "original_string": "def run_user_block(extractor, response, body, &block)\n header = extractor.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", "language": "ruby", "code": "def run_user_block(extractor, response, body, &block)\n header = extractor.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", "code_tokens": ["def", "run_user_block", "(", "extractor", ",", "response", ",", "body", ",", "&", "block", ")", "header", "=", "extractor", ".", "extract_header_data", "(", "response", ")", "case", "block", ".", "arity", "when", "1", "then", "yield", "(", "header", ")", "when", "2", "then", "yield", "(", "header", ",", "body", ")", "else", "raise", "AdsCommon", "::", "Errors", "::", "ApiException", ",", "\"Wrong number of block parameters: %d\"", "%", "block", ".", "arity", "end", "return", "nil", "end"], "docstring": "Yields to user-specified block with additional information such as\n headers.", "docstring_tokens": ["Yields", "to", "user", "-", "specified", "block", "with", "additional", "information", "such", "as", "headers", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L156-L166", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.do_logging", "original_string": "def do_logging(action, request, response)\n logger = get_logger()\n return unless should_log_summary(logger.level, response.soap_fault?)\n\n response_hash = response.hash\n\n soap_headers = {}\n begin\n soap_headers = response_hash[:envelope][:header][:response_header]\n rescue NoMethodError\n # If there are no headers, just ignore. We'll log what we know.\n end\n\n summary_message = ('ID: %s, URL: %s, Service: %s, Action: %s, Response ' +\n 'time: %sms, Request ID: %s') % [@header_handler.identifier,\n request.url, self.class.to_s.split(\"::\").last, action,\n soap_headers[:response_time], soap_headers[:request_id]]\n if soap_headers[:operations]\n summary_message += ', Operations: %s' % soap_headers[:operations]\n end\n summary_message += ', Is fault: %s' % response.soap_fault?\n\n request_message = nil\n response_message = nil\n\n if should_log_payloads(logger.level, response.soap_fault?)\n request_message = 'Outgoing request: %s %s' %\n [format_headers(request.headers), sanitize_request(request.body)]\n response_message = 'Incoming response: %s %s' %\n [format_headers(response.http.headers), response.http.body]\n end\n\n if response.soap_fault?\n summary_message += ', Fault message: %s' % format_fault(\n response_hash[:envelope][:body][:fault][:faultstring])\n logger.warn(summary_message)\n logger.info(request_message) unless request_message.nil?\n logger.info(response_message) unless response_message.nil?\n else\n logger.info(summary_message)\n logger.debug(request_message) unless request_message.nil?\n logger.debug(response_message) unless response_message.nil?\n end\n end", "language": "ruby", "code": "def do_logging(action, request, response)\n logger = get_logger()\n return unless should_log_summary(logger.level, response.soap_fault?)\n\n response_hash = response.hash\n\n soap_headers = {}\n begin\n soap_headers = response_hash[:envelope][:header][:response_header]\n rescue NoMethodError\n # If there are no headers, just ignore. We'll log what we know.\n end\n\n summary_message = ('ID: %s, URL: %s, Service: %s, Action: %s, Response ' +\n 'time: %sms, Request ID: %s') % [@header_handler.identifier,\n request.url, self.class.to_s.split(\"::\").last, action,\n soap_headers[:response_time], soap_headers[:request_id]]\n if soap_headers[:operations]\n summary_message += ', Operations: %s' % soap_headers[:operations]\n end\n summary_message += ', Is fault: %s' % response.soap_fault?\n\n request_message = nil\n response_message = nil\n\n if should_log_payloads(logger.level, response.soap_fault?)\n request_message = 'Outgoing request: %s %s' %\n [format_headers(request.headers), sanitize_request(request.body)]\n response_message = 'Incoming response: %s %s' %\n [format_headers(response.http.headers), response.http.body]\n end\n\n if response.soap_fault?\n summary_message += ', Fault message: %s' % format_fault(\n response_hash[:envelope][:body][:fault][:faultstring])\n logger.warn(summary_message)\n logger.info(request_message) unless request_message.nil?\n logger.info(response_message) unless response_message.nil?\n else\n logger.info(summary_message)\n logger.debug(request_message) unless request_message.nil?\n logger.debug(response_message) unless response_message.nil?\n end\n end", "code_tokens": ["def", "do_logging", "(", "action", ",", "request", ",", "response", ")", "logger", "=", "get_logger", "(", ")", "return", "unless", "should_log_summary", "(", "logger", ".", "level", ",", "response", ".", "soap_fault?", ")", "response_hash", "=", "response", ".", "hash", "soap_headers", "=", "{", "}", "begin", "soap_headers", "=", "response_hash", "[", ":envelope", "]", "[", ":header", "]", "[", ":response_header", "]", "rescue", "NoMethodError", "# If there are no headers, just ignore. We'll log what we know.", "end", "summary_message", "=", "(", "'ID: %s, URL: %s, Service: %s, Action: %s, Response '", "+", "'time: %sms, Request ID: %s'", ")", "%", "[", "@header_handler", ".", "identifier", ",", "request", ".", "url", ",", "self", ".", "class", ".", "to_s", ".", "split", "(", "\"::\"", ")", ".", "last", ",", "action", ",", "soap_headers", "[", ":response_time", "]", ",", "soap_headers", "[", ":request_id", "]", "]", "if", "soap_headers", "[", ":operations", "]", "summary_message", "+=", "', Operations: %s'", "%", "soap_headers", "[", ":operations", "]", "end", "summary_message", "+=", "', Is fault: %s'", "%", "response", ".", "soap_fault?", "request_message", "=", "nil", "response_message", "=", "nil", "if", "should_log_payloads", "(", "logger", ".", "level", ",", "response", ".", "soap_fault?", ")", "request_message", "=", "'Outgoing request: %s %s'", "%", "[", "format_headers", "(", "request", ".", "headers", ")", ",", "sanitize_request", "(", "request", ".", "body", ")", "]", "response_message", "=", "'Incoming response: %s %s'", "%", "[", "format_headers", "(", "response", ".", "http", ".", "headers", ")", ",", "response", ".", "http", ".", "body", "]", "end", "if", "response", ".", "soap_fault?", "summary_message", "+=", "', Fault message: %s'", "%", "format_fault", "(", "response_hash", "[", ":envelope", "]", "[", ":body", "]", "[", ":fault", "]", "[", ":faultstring", "]", ")", "logger", ".", "warn", "(", "summary_message", ")", "logger", ".", "info", "(", "request_message", ")", "unless", "request_message", ".", "nil?", "logger", ".", "info", "(", "response_message", ")", "unless", "response_message", ".", "nil?", "else", "logger", ".", "info", "(", "summary_message", ")", "logger", ".", "debug", "(", "request_message", ")", "unless", "request_message", ".", "nil?", "logger", ".", "debug", "(", "response_message", ")", "unless", "response_message", ".", "nil?", "end", "end"], "docstring": "Log the request, response, and summary lines.", "docstring_tokens": ["Log", "the", "request", "response", "and", "summary", "lines", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L169-L212", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.format_headers", "original_string": "def format_headers(headers)\n return headers.map do |k, v|\n v = REDACTED_STR if k == 'Authorization'\n [k, v].join(': ')\n end.join(', ')\n end", "language": "ruby", "code": "def format_headers(headers)\n return headers.map do |k, v|\n v = REDACTED_STR if k == 'Authorization'\n [k, v].join(': ')\n end.join(', ')\n end", "code_tokens": ["def", "format_headers", "(", "headers", ")", "return", "headers", ".", "map", "do", "|", "k", ",", "v", "|", "v", "=", "REDACTED_STR", "if", "k", "==", "'Authorization'", "[", "k", ",", "v", "]", ".", "join", "(", "': '", ")", "end", ".", "join", "(", "', '", ")", "end"], "docstring": "Format headers, redacting sensitive information.", "docstring_tokens": ["Format", "headers", "redacting", "sensitive", "information", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L215-L220", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.format_fault", "original_string": "def format_fault(message)\n if message.length > MAX_FAULT_LOG_LENGTH\n message = message[0, MAX_FAULT_LOG_LENGTH]\n end\n return message.gsub(\"\\n\", ' ')\n end", "language": "ruby", "code": "def format_fault(message)\n if message.length > MAX_FAULT_LOG_LENGTH\n message = message[0, MAX_FAULT_LOG_LENGTH]\n end\n return message.gsub(\"\\n\", ' ')\n end", "code_tokens": ["def", "format_fault", "(", "message", ")", "if", "message", ".", "length", ">", "MAX_FAULT_LOG_LENGTH", "message", "=", "message", "[", "0", ",", "MAX_FAULT_LOG_LENGTH", "]", "end", "return", "message", ".", "gsub", "(", "\"\\n\"", ",", "' '", ")", "end"], "docstring": "Format the fault message by capping length and removing newlines.", "docstring_tokens": ["Format", "the", "fault", "message", "by", "capping", "length", "and", "removing", "newlines", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L229-L234", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.should_log_summary", "original_string": "def should_log_summary(level, is_fault)\n # Fault summaries log at WARN.\n return level <= Logger::WARN if is_fault\n # Success summaries log at INFO.\n return level <= Logger::INFO\n end", "language": "ruby", "code": "def should_log_summary(level, is_fault)\n # Fault summaries log at WARN.\n return level <= Logger::WARN if is_fault\n # Success summaries log at INFO.\n return level <= Logger::INFO\n end", "code_tokens": ["def", "should_log_summary", "(", "level", ",", "is_fault", ")", "# Fault summaries log at WARN.", "return", "level", "<=", "Logger", "::", "WARN", "if", "is_fault", "# Success summaries log at INFO.", "return", "level", "<=", "Logger", "::", "INFO", "end"], "docstring": "Check whether or not to log request summaries based on log level.", "docstring_tokens": ["Check", "whether", "or", "not", "to", "log", "request", "summaries", "based", "on", "log", "level", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L237-L242", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.should_log_payloads", "original_string": "def should_log_payloads(level, is_fault)\n # Fault payloads log at INFO.\n return level <= Logger::INFO if is_fault\n # Success payloads log at DEBUG.\n return level <= Logger::DEBUG\n end", "language": "ruby", "code": "def should_log_payloads(level, is_fault)\n # Fault payloads log at INFO.\n return level <= Logger::INFO if is_fault\n # Success payloads log at DEBUG.\n return level <= Logger::DEBUG\n end", "code_tokens": ["def", "should_log_payloads", "(", "level", ",", "is_fault", ")", "# Fault payloads log at INFO.", "return", "level", "<=", "Logger", "::", "INFO", "if", "is_fault", "# Success payloads log at DEBUG.", "return", "level", "<=", "Logger", "::", "DEBUG", "end"], "docstring": "Check whether or not to log payloads based on log level.", "docstring_tokens": ["Check", "whether", "or", "not", "to", "log", "payloads", "based", "on", "log", "level", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L245-L250", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.download_report_as_file", "original_string": "def download_report_as_file(report_definition, path, cid = nil)\n report_body = download_report(report_definition, cid)\n save_to_file(report_body, path)\n return nil\n end", "language": "ruby", "code": "def download_report_as_file(report_definition, path, cid = nil)\n report_body = download_report(report_definition, cid)\n save_to_file(report_body, path)\n return nil\n end", "code_tokens": ["def", "download_report_as_file", "(", "report_definition", ",", "path", ",", "cid", "=", "nil", ")", "report_body", "=", "download_report", "(", "report_definition", ",", "cid", ")", "save_to_file", "(", "report_body", ",", "path", ")", "return", "nil", "end"], "docstring": "Downloads a report and saves it to a file.\n\n Args:\n - report_definition: definition of the report in XML text or hash\n - path: path to save report to\n - cid: optional customer ID to run against\n\n Returns:\n - nil\n\n Raises:\n - AdwordsApi::Errors::InvalidReportDefinitionError if the report\n definition is invalid\n - AdwordsApi::Errors::ReportError if server-side error occurred", "docstring_tokens": ["Downloads", "a", "report", "and", "saves", "it", "to", "a", "file", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L74-L78", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.download_report_as_file_with_awql", "original_string": "def download_report_as_file_with_awql(report_query, format, path, cid = nil)\n report_body = download_report_with_awql(report_query, format, cid)\n save_to_file(report_body, path)\n return nil\n end", "language": "ruby", "code": "def download_report_as_file_with_awql(report_query, format, path, cid = nil)\n report_body = download_report_with_awql(report_query, format, cid)\n save_to_file(report_body, path)\n return nil\n end", "code_tokens": ["def", "download_report_as_file_with_awql", "(", "report_query", ",", "format", ",", "path", ",", "cid", "=", "nil", ")", "report_body", "=", "download_report_with_awql", "(", "report_query", ",", "format", ",", "cid", ")", "save_to_file", "(", "report_body", ",", "path", ")", "return", "nil", "end"], "docstring": "Downloads a report with AWQL and saves it to a file.\n\n Args:\n - report_query: query for the report as string\n - format: format for the report as string\n - path: path to save report to\n - cid: optional customer ID to run report against\n\n Returns:\n - nil\n\n Raises:\n - AdwordsApi::Errors::ReportError if server-side error occurred", "docstring_tokens": ["Downloads", "a", "report", "with", "AWQL", "and", "saves", "it", "to", "a", "file", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L150-L154", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.download_report_as_stream_with_awql", "original_string": "def download_report_as_stream_with_awql(\n report_query, format, cid = nil, &block)\n return get_report_response_with_awql(report_query, format, cid, &block)\n end", "language": "ruby", "code": "def download_report_as_stream_with_awql(\n report_query, format, cid = nil, &block)\n return get_report_response_with_awql(report_query, format, cid, &block)\n end", "code_tokens": ["def", "download_report_as_stream_with_awql", "(", "report_query", ",", "format", ",", "cid", "=", "nil", ",", "&", "block", ")", "return", "get_report_response_with_awql", "(", "report_query", ",", "format", ",", "cid", ",", "block", ")", "end"], "docstring": "Streams a report with AWQL as a string to the given block. This method\n will not do error checking on returned values.\n\n Args:\n - report_query: query for the report as string\n - format: format for the report as string\n - cid: optional customer ID to run report against\n\n Returns:\n - nil", "docstring_tokens": ["Streams", "a", "report", "with", "AWQL", "as", "a", "string", "to", "the", "given", "block", ".", "This", "method", "will", "not", "do", "error", "checking", "on", "returned", "values", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L167-L170", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.get_stream_helper_with_awql", "original_string": "def get_stream_helper_with_awql(report_query, format, cid = nil)\n return AdwordsApi::ReportStream.set_up_with_awql(\n self, report_query, format, cid)\n end", "language": "ruby", "code": "def get_stream_helper_with_awql(report_query, format, cid = nil)\n return AdwordsApi::ReportStream.set_up_with_awql(\n self, report_query, format, cid)\n end", "code_tokens": ["def", "get_stream_helper_with_awql", "(", "report_query", ",", "format", ",", "cid", "=", "nil", ")", "return", "AdwordsApi", "::", "ReportStream", ".", "set_up_with_awql", "(", "self", ",", "report_query", ",", "format", ",", "cid", ")", "end"], "docstring": "Returns a helper object that can manage breaking the streamed report\n results into individual lines.\n\n Args:\n - report_query: query for the report as string\n - format: format for the report as string\n - cid: optional customer ID to run report against\n\n Returns:\n - ReportStream object initialized to begin streaming.", "docstring_tokens": ["Returns", "a", "helper", "object", "that", "can", "manage", "breaking", "the", "streamed", "report", "results", "into", "individual", "lines", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L183-L186", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.get_report_response", "original_string": "def get_report_response(report_definition, cid, &block)\n definition_text = get_report_definition_text(report_definition)\n data = '__rdxml=%s' % CGI.escape(definition_text)\n return make_adhoc_request(data, cid, &block)\n end", "language": "ruby", "code": "def get_report_response(report_definition, cid, &block)\n definition_text = get_report_definition_text(report_definition)\n data = '__rdxml=%s' % CGI.escape(definition_text)\n return make_adhoc_request(data, cid, &block)\n end", "code_tokens": ["def", "get_report_response", "(", "report_definition", ",", "cid", ",", "&", "block", ")", "definition_text", "=", "get_report_definition_text", "(", "report_definition", ")", "data", "=", "'__rdxml=%s'", "%", "CGI", ".", "escape", "(", "definition_text", ")", "return", "make_adhoc_request", "(", "data", ",", "cid", ",", "block", ")", "end"], "docstring": "Send POST request for a report and returns Response object.", "docstring_tokens": ["Send", "POST", "request", "for", "a", "report", "and", "returns", "Response", "object", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L206-L210", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.get_report_response_with_awql", "original_string": "def get_report_response_with_awql(report_query, format, cid, &block)\n data = '__rdquery=%s&__fmt=%s' %\n [CGI.escape(report_query), CGI.escape(format)]\n return make_adhoc_request(data, cid, &block)\n end", "language": "ruby", "code": "def get_report_response_with_awql(report_query, format, cid, &block)\n data = '__rdquery=%s&__fmt=%s' %\n [CGI.escape(report_query), CGI.escape(format)]\n return make_adhoc_request(data, cid, &block)\n end", "code_tokens": ["def", "get_report_response_with_awql", "(", "report_query", ",", "format", ",", "cid", ",", "&", "block", ")", "data", "=", "'__rdquery=%s&__fmt=%s'", "%", "[", "CGI", ".", "escape", "(", "report_query", ")", ",", "CGI", ".", "escape", "(", "format", ")", "]", "return", "make_adhoc_request", "(", "data", ",", "cid", ",", "block", ")", "end"], "docstring": "Send POST request for a report with AWQL and returns Response object.", "docstring_tokens": ["Send", "POST", "request", "for", "a", "report", "with", "AWQL", "and", "returns", "Response", "object", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L213-L217", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.make_adhoc_request", "original_string": "def make_adhoc_request(data, cid, &block)\n @api.utils_reporter.report_utils_used()\n url = @api.api_config.adhoc_report_download_url(@version)\n headers = get_report_request_headers(url, cid)\n log_request(url, headers, data)\n # A given block indicates that we should make a stream request and yield\n # the results, rather than return a full response.\n if block_given?\n AdsCommon::Http.post_stream(url, data, @api.config, headers, &block)\n return nil\n else\n response = AdsCommon::Http.post_response(\n url, data, @api.config, headers)\n log_headers(response.headers)\n check_for_errors(response)\n return response\n end\n end", "language": "ruby", "code": "def make_adhoc_request(data, cid, &block)\n @api.utils_reporter.report_utils_used()\n url = @api.api_config.adhoc_report_download_url(@version)\n headers = get_report_request_headers(url, cid)\n log_request(url, headers, data)\n # A given block indicates that we should make a stream request and yield\n # the results, rather than return a full response.\n if block_given?\n AdsCommon::Http.post_stream(url, data, @api.config, headers, &block)\n return nil\n else\n response = AdsCommon::Http.post_response(\n url, data, @api.config, headers)\n log_headers(response.headers)\n check_for_errors(response)\n return response\n end\n end", "code_tokens": ["def", "make_adhoc_request", "(", "data", ",", "cid", ",", "&", "block", ")", "@api", ".", "utils_reporter", ".", "report_utils_used", "(", ")", "url", "=", "@api", ".", "api_config", ".", "adhoc_report_download_url", "(", "@version", ")", "headers", "=", "get_report_request_headers", "(", "url", ",", "cid", ")", "log_request", "(", "url", ",", "headers", ",", "data", ")", "# A given block indicates that we should make a stream request and yield", "# the results, rather than return a full response.", "if", "block_given?", "AdsCommon", "::", "Http", ".", "post_stream", "(", "url", ",", "data", ",", "@api", ".", "config", ",", "headers", ",", "block", ")", "return", "nil", "else", "response", "=", "AdsCommon", "::", "Http", ".", "post_response", "(", "url", ",", "data", ",", "@api", ".", "config", ",", "headers", ")", "log_headers", "(", "response", ".", "headers", ")", "check_for_errors", "(", "response", ")", "return", "response", "end", "end"], "docstring": "Makes request and AdHoc service and returns response.", "docstring_tokens": ["Makes", "request", "and", "AdHoc", "service", "and", "returns", "response", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L220-L237", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.get_report_request_headers", "original_string": "def get_report_request_headers(url, cid)\n @header_handler ||= AdwordsApi::ReportHeaderHandler.new(\n @api.credential_handler, @api.get_auth_handler(), @api.config)\n return @header_handler.headers(url, cid)\n end", "language": "ruby", "code": "def get_report_request_headers(url, cid)\n @header_handler ||= AdwordsApi::ReportHeaderHandler.new(\n @api.credential_handler, @api.get_auth_handler(), @api.config)\n return @header_handler.headers(url, cid)\n end", "code_tokens": ["def", "get_report_request_headers", "(", "url", ",", "cid", ")", "@header_handler", "||=", "AdwordsApi", "::", "ReportHeaderHandler", ".", "new", "(", "@api", ".", "credential_handler", ",", "@api", ".", "get_auth_handler", "(", ")", ",", "@api", ".", "config", ")", "return", "@header_handler", ".", "headers", "(", "url", ",", "cid", ")", "end"], "docstring": "Prepares headers for report request.", "docstring_tokens": ["Prepares", "headers", "for", "report", "request", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L253-L257", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.save_to_file", "original_string": "def save_to_file(data, path)\n open(path, 'wb') { |file| file.write(data) } if path\n end", "language": "ruby", "code": "def save_to_file(data, path)\n open(path, 'wb') { |file| file.write(data) } if path\n end", "code_tokens": ["def", "save_to_file", "(", "data", ",", "path", ")", "open", "(", "path", ",", "'wb'", ")", "{", "|", "file", "|", "file", ".", "write", "(", "data", ")", "}", "if", "path", "end"], "docstring": "Saves raw data to a file.", "docstring_tokens": ["Saves", "raw", "data", "to", "a", "file", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L260-L262", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.log_headers", "original_string": "def log_headers(headers)\n @api.logger.debug('HTTP headers: [%s]' %\n (headers.map { |k, v| [k, v].join(': ') }.join(', ')))\n end", "language": "ruby", "code": "def log_headers(headers)\n @api.logger.debug('HTTP headers: [%s]' %\n (headers.map { |k, v| [k, v].join(': ') }.join(', ')))\n end", "code_tokens": ["def", "log_headers", "(", "headers", ")", "@api", ".", "logger", ".", "debug", "(", "'HTTP headers: [%s]'", "%", "(", "headers", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ",", "v", "]", ".", "join", "(", "': '", ")", "}", ".", "join", "(", "', '", ")", ")", ")", "end"], "docstring": "Logs HTTP headers on debug level.", "docstring_tokens": ["Logs", "HTTP", "headers", "on", "debug", "level", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L272-L275", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.check_for_errors", "original_string": "def check_for_errors(response)\n # Check for error code.\n if response.code != 200\n # Check for error in body.\n report_body = response.body\n check_for_xml_error(report_body, response.code)\n # No XML error found nor raised, falling back to a default message.\n raise AdwordsApi::Errors::ReportError.new(response.code,\n 'HTTP code: %d, body: %s' % [response.code, response.body])\n end\n return nil\n end", "language": "ruby", "code": "def check_for_errors(response)\n # Check for error code.\n if response.code != 200\n # Check for error in body.\n report_body = response.body\n check_for_xml_error(report_body, response.code)\n # No XML error found nor raised, falling back to a default message.\n raise AdwordsApi::Errors::ReportError.new(response.code,\n 'HTTP code: %d, body: %s' % [response.code, response.body])\n end\n return nil\n end", "code_tokens": ["def", "check_for_errors", "(", "response", ")", "# Check for error code.", "if", "response", ".", "code", "!=", "200", "# Check for error in body.", "report_body", "=", "response", ".", "body", "check_for_xml_error", "(", "report_body", ",", "response", ".", "code", ")", "# No XML error found nor raised, falling back to a default message.", "raise", "AdwordsApi", "::", "Errors", "::", "ReportError", ".", "new", "(", "response", ".", "code", ",", "'HTTP code: %d, body: %s'", "%", "[", "response", ".", "code", ",", "response", ".", "body", "]", ")", "end", "return", "nil", "end"], "docstring": "Checks downloaded data for error signature. Raises ReportError if it\n detects an error.", "docstring_tokens": ["Checks", "downloaded", "data", "for", "error", "signature", ".", "Raises", "ReportError", "if", "it", "detects", "an", "error", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L279-L290", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.check_for_xml_error", "original_string": "def check_for_xml_error(report_body, response_code)\n unless report_body.nil?\n error_response = get_nori().parse(report_body)\n if error_response.include?(:report_download_error) and\n error_response[:report_download_error].include?(:api_error)\n api_error = error_response[:report_download_error][:api_error]\n raise AdwordsApi::Errors::ReportXmlError.new(response_code,\n api_error[:type], api_error[:trigger], api_error[:field_path])\n end\n end\n end", "language": "ruby", "code": "def check_for_xml_error(report_body, response_code)\n unless report_body.nil?\n error_response = get_nori().parse(report_body)\n if error_response.include?(:report_download_error) and\n error_response[:report_download_error].include?(:api_error)\n api_error = error_response[:report_download_error][:api_error]\n raise AdwordsApi::Errors::ReportXmlError.new(response_code,\n api_error[:type], api_error[:trigger], api_error[:field_path])\n end\n end\n end", "code_tokens": ["def", "check_for_xml_error", "(", "report_body", ",", "response_code", ")", "unless", "report_body", ".", "nil?", "error_response", "=", "get_nori", "(", ")", ".", "parse", "(", "report_body", ")", "if", "error_response", ".", "include?", "(", ":report_download_error", ")", "and", "error_response", "[", ":report_download_error", "]", ".", "include?", "(", ":api_error", ")", "api_error", "=", "error_response", "[", ":report_download_error", "]", "[", ":api_error", "]", "raise", "AdwordsApi", "::", "Errors", "::", "ReportXmlError", ".", "new", "(", "response_code", ",", "api_error", "[", ":type", "]", ",", "api_error", "[", ":trigger", "]", ",", "api_error", "[", ":field_path", "]", ")", "end", "end", "end"], "docstring": "Checks for an XML error in the response body and raises an exception if\n it was found.", "docstring_tokens": ["Checks", "for", "an", "XML", "error", "in", "the", "response", "body", "and", "raises", "an", "exception", "if", "it", "was", "found", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L294-L304", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.report_definition_to_xml", "original_string": "def report_definition_to_xml(report_definition)\n check_report_definition_hash(report_definition)\n add_report_definition_hash_order(report_definition)\n begin\n return Gyoku.xml({:report_definition => report_definition})\n rescue ArgumentError => e\n if e.message.include?(\"order!\")\n unknown_fields =\n e.message.slice(e.message.index('['), e.message.length)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n \"Unknown report definition field(s): %s\" % unknown_fields\n end\n raise e\n end\n end", "language": "ruby", "code": "def report_definition_to_xml(report_definition)\n check_report_definition_hash(report_definition)\n add_report_definition_hash_order(report_definition)\n begin\n return Gyoku.xml({:report_definition => report_definition})\n rescue ArgumentError => e\n if e.message.include?(\"order!\")\n unknown_fields =\n e.message.slice(e.message.index('['), e.message.length)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n \"Unknown report definition field(s): %s\" % unknown_fields\n end\n raise e\n end\n end", "code_tokens": ["def", "report_definition_to_xml", "(", "report_definition", ")", "check_report_definition_hash", "(", "report_definition", ")", "add_report_definition_hash_order", "(", "report_definition", ")", "begin", "return", "Gyoku", ".", "xml", "(", "{", ":report_definition", "=>", "report_definition", "}", ")", "rescue", "ArgumentError", "=>", "e", "if", "e", ".", "message", ".", "include?", "(", "\"order!\"", ")", "unknown_fields", "=", "e", ".", "message", ".", "slice", "(", "e", ".", "message", ".", "index", "(", "'['", ")", ",", "e", ".", "message", ".", "length", ")", "raise", "AdwordsApi", "::", "Errors", "::", "InvalidReportDefinitionError", ",", "\"Unknown report definition field(s): %s\"", "%", "unknown_fields", "end", "raise", "e", "end", "end"], "docstring": "Renders a report definition hash into XML text.", "docstring_tokens": ["Renders", "a", "report", "definition", "hash", "into", "XML", "text", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L307-L321", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.check_report_definition_hash", "original_string": "def check_report_definition_hash(report_definition)\n # Minimal set of fields required.\n REQUIRED_FIELDS.each do |field|\n unless report_definition.include?(field)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n \"Required field '%s' is missing in the definition\" % field\n end\n end\n # Fields list is also required.\n unless report_definition[:selector].include?(:fields)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n 'Fields list is required'\n end\n # 'Fields' must be an Array.\n unless report_definition[:selector][:fields].kind_of?(Array)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n 'Fields list must be an array'\n end\n # We should request at least one field.\n if report_definition[:selector][:fields].empty?\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n 'At least one field needs to be requested'\n end\n end", "language": "ruby", "code": "def check_report_definition_hash(report_definition)\n # Minimal set of fields required.\n REQUIRED_FIELDS.each do |field|\n unless report_definition.include?(field)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n \"Required field '%s' is missing in the definition\" % field\n end\n end\n # Fields list is also required.\n unless report_definition[:selector].include?(:fields)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n 'Fields list is required'\n end\n # 'Fields' must be an Array.\n unless report_definition[:selector][:fields].kind_of?(Array)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n 'Fields list must be an array'\n end\n # We should request at least one field.\n if report_definition[:selector][:fields].empty?\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n 'At least one field needs to be requested'\n end\n end", "code_tokens": ["def", "check_report_definition_hash", "(", "report_definition", ")", "# Minimal set of fields required.", "REQUIRED_FIELDS", ".", "each", "do", "|", "field", "|", "unless", "report_definition", ".", "include?", "(", "field", ")", "raise", "AdwordsApi", "::", "Errors", "::", "InvalidReportDefinitionError", ",", "\"Required field '%s' is missing in the definition\"", "%", "field", "end", "end", "# Fields list is also required.", "unless", "report_definition", "[", ":selector", "]", ".", "include?", "(", ":fields", ")", "raise", "AdwordsApi", "::", "Errors", "::", "InvalidReportDefinitionError", ",", "'Fields list is required'", "end", "# 'Fields' must be an Array.", "unless", "report_definition", "[", ":selector", "]", "[", ":fields", "]", ".", "kind_of?", "(", "Array", ")", "raise", "AdwordsApi", "::", "Errors", "::", "InvalidReportDefinitionError", ",", "'Fields list must be an array'", "end", "# We should request at least one field.", "if", "report_definition", "[", ":selector", "]", "[", ":fields", "]", ".", "empty?", "raise", "AdwordsApi", "::", "Errors", "::", "InvalidReportDefinitionError", ",", "'At least one field needs to be requested'", "end", "end"], "docstring": "Checks if the report definition looks correct.", "docstring_tokens": ["Checks", "if", "the", "report", "definition", "looks", "correct", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L324-L347", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.add_report_definition_hash_order", "original_string": "def add_report_definition_hash_order(node, name = :root)\n def_order = REPORT_DEFINITION_ORDER[name]\n var_order = def_order.reject { |field| !node.include?(field) }\n node.keys.each do |key|\n if REPORT_DEFINITION_ORDER.include?(key)\n case node[key]\n when Hash\n add_report_definition_hash_order(node[key], key)\n when Array\n node[key].each do |item|\n add_report_definition_hash_order(item, key)\n end\n end\n end\n end\n node[:order!] = var_order\n return nil\n end", "language": "ruby", "code": "def add_report_definition_hash_order(node, name = :root)\n def_order = REPORT_DEFINITION_ORDER[name]\n var_order = def_order.reject { |field| !node.include?(field) }\n node.keys.each do |key|\n if REPORT_DEFINITION_ORDER.include?(key)\n case node[key]\n when Hash\n add_report_definition_hash_order(node[key], key)\n when Array\n node[key].each do |item|\n add_report_definition_hash_order(item, key)\n end\n end\n end\n end\n node[:order!] = var_order\n return nil\n end", "code_tokens": ["def", "add_report_definition_hash_order", "(", "node", ",", "name", "=", ":root", ")", "def_order", "=", "REPORT_DEFINITION_ORDER", "[", "name", "]", "var_order", "=", "def_order", ".", "reject", "{", "|", "field", "|", "!", "node", ".", "include?", "(", "field", ")", "}", "node", ".", "keys", ".", "each", "do", "|", "key", "|", "if", "REPORT_DEFINITION_ORDER", ".", "include?", "(", "key", ")", "case", "node", "[", "key", "]", "when", "Hash", "add_report_definition_hash_order", "(", "node", "[", "key", "]", ",", "key", ")", "when", "Array", "node", "[", "key", "]", ".", "each", "do", "|", "item", "|", "add_report_definition_hash_order", "(", "item", ",", "key", ")", "end", "end", "end", "end", "node", "[", ":order!", "]", "=", "var_order", "return", "nil", "end"], "docstring": "Adds fields order hint to generator based on specification.", "docstring_tokens": ["Adds", "fields", "order", "hint", "to", "generator", "based", "on", "specification", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L350-L367", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_header_handler.rb", "func_name": "AdwordsApi.ReportHeaderHandler.headers", "original_string": "def headers(url, cid)\n override = (cid.nil?) ? nil : {:client_customer_id => cid}\n credentials = @credential_handler.credentials(override)\n headers = {\n 'Content-Type' => 'application/x-www-form-urlencoded',\n 'Authorization' => @auth_handler.auth_string(credentials),\n 'User-Agent' => @credential_handler.generate_user_agent(),\n 'clientCustomerId' => credentials[:client_customer_id].to_s,\n 'developerToken' => credentials[:developer_token]\n }\n skip_report_header = @config.read('library.skip_report_header')\n unless skip_report_header.nil?\n headers['skipReportHeader'] = skip_report_header.to_s\n end\n skip_report_summary = @config.read('library.skip_report_summary')\n unless skip_report_summary.nil?\n headers['skipReportSummary'] = skip_report_summary.to_s\n end\n skip_column_header = @config.read('library.skip_column_header')\n unless skip_column_header.nil?\n headers['skipColumnHeader'] = skip_column_header.to_s\n end\n include_zero_impressions =\n @config.read('library.include_zero_impressions')\n unless include_zero_impressions.nil?\n headers['includeZeroImpressions'] = include_zero_impressions.to_s\n end\n use_raw_enum_values =\n @config.read('library.use_raw_enum_values')\n unless use_raw_enum_values.nil?\n headers['useRawEnumValues'] = use_raw_enum_values.to_s\n end\n return headers\n end", "language": "ruby", "code": "def headers(url, cid)\n override = (cid.nil?) ? nil : {:client_customer_id => cid}\n credentials = @credential_handler.credentials(override)\n headers = {\n 'Content-Type' => 'application/x-www-form-urlencoded',\n 'Authorization' => @auth_handler.auth_string(credentials),\n 'User-Agent' => @credential_handler.generate_user_agent(),\n 'clientCustomerId' => credentials[:client_customer_id].to_s,\n 'developerToken' => credentials[:developer_token]\n }\n skip_report_header = @config.read('library.skip_report_header')\n unless skip_report_header.nil?\n headers['skipReportHeader'] = skip_report_header.to_s\n end\n skip_report_summary = @config.read('library.skip_report_summary')\n unless skip_report_summary.nil?\n headers['skipReportSummary'] = skip_report_summary.to_s\n end\n skip_column_header = @config.read('library.skip_column_header')\n unless skip_column_header.nil?\n headers['skipColumnHeader'] = skip_column_header.to_s\n end\n include_zero_impressions =\n @config.read('library.include_zero_impressions')\n unless include_zero_impressions.nil?\n headers['includeZeroImpressions'] = include_zero_impressions.to_s\n end\n use_raw_enum_values =\n @config.read('library.use_raw_enum_values')\n unless use_raw_enum_values.nil?\n headers['useRawEnumValues'] = use_raw_enum_values.to_s\n end\n return headers\n end", "code_tokens": ["def", "headers", "(", "url", ",", "cid", ")", "override", "=", "(", "cid", ".", "nil?", ")", "?", "nil", ":", "{", ":client_customer_id", "=>", "cid", "}", "credentials", "=", "@credential_handler", ".", "credentials", "(", "override", ")", "headers", "=", "{", "'Content-Type'", "=>", "'application/x-www-form-urlencoded'", ",", "'Authorization'", "=>", "@auth_handler", ".", "auth_string", "(", "credentials", ")", ",", "'User-Agent'", "=>", "@credential_handler", ".", "generate_user_agent", "(", ")", ",", "'clientCustomerId'", "=>", "credentials", "[", ":client_customer_id", "]", ".", "to_s", ",", "'developerToken'", "=>", "credentials", "[", ":developer_token", "]", "}", "skip_report_header", "=", "@config", ".", "read", "(", "'library.skip_report_header'", ")", "unless", "skip_report_header", ".", "nil?", "headers", "[", "'skipReportHeader'", "]", "=", "skip_report_header", ".", "to_s", "end", "skip_report_summary", "=", "@config", ".", "read", "(", "'library.skip_report_summary'", ")", "unless", "skip_report_summary", ".", "nil?", "headers", "[", "'skipReportSummary'", "]", "=", "skip_report_summary", ".", "to_s", "end", "skip_column_header", "=", "@config", ".", "read", "(", "'library.skip_column_header'", ")", "unless", "skip_column_header", ".", "nil?", "headers", "[", "'skipColumnHeader'", "]", "=", "skip_column_header", ".", "to_s", "end", "include_zero_impressions", "=", "@config", ".", "read", "(", "'library.include_zero_impressions'", ")", "unless", "include_zero_impressions", ".", "nil?", "headers", "[", "'includeZeroImpressions'", "]", "=", "include_zero_impressions", ".", "to_s", "end", "use_raw_enum_values", "=", "@config", ".", "read", "(", "'library.use_raw_enum_values'", ")", "unless", "use_raw_enum_values", ".", "nil?", "headers", "[", "'useRawEnumValues'", "]", "=", "use_raw_enum_values", ".", "to_s", "end", "return", "headers", "end"], "docstring": "Initializes a header handler.\n\n Args:\n - credential_handler: a header with credential data\n - auth_handler: a header with auth data\n - config: API config\n\n Returns the headers set for the report request.\n\n Args:\n - url: URL for the report requests\n - cid: clientCustomerId to use\n\n Returns:\n - a Hash with HTTP headers.", "docstring_tokens": ["Initializes", "a", "header", "handler", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_header_handler.rb#L45-L78", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/credential_handler.rb", "func_name": "AdsCommon.CredentialHandler.credentials", "original_string": "def credentials(credentials_override = nil)\n credentials = @credentials.dup()\n credentials.merge!(credentials_override) unless credentials_override.nil?\n return credentials\n end", "language": "ruby", "code": "def credentials(credentials_override = nil)\n credentials = @credentials.dup()\n credentials.merge!(credentials_override) unless credentials_override.nil?\n return credentials\n end", "code_tokens": ["def", "credentials", "(", "credentials_override", "=", "nil", ")", "credentials", "=", "@credentials", ".", "dup", "(", ")", "credentials", ".", "merge!", "(", "credentials_override", ")", "unless", "credentials_override", ".", "nil?", "return", "credentials", "end"], "docstring": "Initializes CredentialHandler.\n Returns credentials set for the next call.", "docstring_tokens": ["Initializes", "CredentialHandler", ".", "Returns", "credentials", "set", "for", "the", "next", "call", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/credential_handler.rb#L36-L40", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/credential_handler.rb", "func_name": "AdsCommon.CredentialHandler.credentials=", "original_string": "def credentials=(new_credentials)\n # Find new and changed properties.\n diff = new_credentials.inject([]) do |result, (key, value)|\n result << [key, value] if value != @credentials[key]\n result\n end\n\n # Find removed properties.\n diff = @credentials.inject(diff) do |result, (key, _)|\n result << [key, nil] unless new_credentials.include?(key)\n result\n end\n\n # Set each property.\n diff.each { |entry| set_credential(entry[0], entry[1]) }\n\n return nil\n end", "language": "ruby", "code": "def credentials=(new_credentials)\n # Find new and changed properties.\n diff = new_credentials.inject([]) do |result, (key, value)|\n result << [key, value] if value != @credentials[key]\n result\n end\n\n # Find removed properties.\n diff = @credentials.inject(diff) do |result, (key, _)|\n result << [key, nil] unless new_credentials.include?(key)\n result\n end\n\n # Set each property.\n diff.each { |entry| set_credential(entry[0], entry[1]) }\n\n return nil\n end", "code_tokens": ["def", "credentials", "=", "(", "new_credentials", ")", "# Find new and changed properties.", "diff", "=", "new_credentials", ".", "inject", "(", "[", "]", ")", "do", "|", "result", ",", "(", "key", ",", "value", ")", "|", "result", "<<", "[", "key", ",", "value", "]", "if", "value", "!=", "@credentials", "[", "key", "]", "result", "end", "# Find removed properties.", "diff", "=", "@credentials", ".", "inject", "(", "diff", ")", "do", "|", "result", ",", "(", "key", ",", "_", ")", "|", "result", "<<", "[", "key", ",", "nil", "]", "unless", "new_credentials", ".", "include?", "(", "key", ")", "result", "end", "# Set each property.", "diff", ".", "each", "{", "|", "entry", "|", "set_credential", "(", "entry", "[", "0", "]", ",", "entry", "[", "1", "]", ")", "}", "return", "nil", "end"], "docstring": "Set the credentials hash to a new one. Calculate difference, and call the\n AuthHandler callback appropriately.", "docstring_tokens": ["Set", "the", "credentials", "hash", "to", "a", "new", "one", ".", "Calculate", "difference", "and", "call", "the", "AuthHandler", "callback", "appropriately", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/credential_handler.rb#L44-L61", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/credential_handler.rb", "func_name": "AdsCommon.CredentialHandler.generate_user_agent", "original_string": "def generate_user_agent(extra_ids = [], agent_app = nil)\n agent_app ||= File.basename($0)\n agent_data = extra_ids\n agent_data << 'Common-Ruby/%s' % AdsCommon::ApiConfig::CLIENT_LIB_VERSION\n agent_data << 'GoogleAdsSavon/%s' % GoogleAdsSavon::VERSION\n ruby_engine = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby'\n agent_data << [ruby_engine, RUBY_VERSION].join('/')\n agent_data << 'HTTPI/%s' % HTTPI::VERSION\n agent_data << HTTPI::Adapter.use.to_s\n agent_data += get_extra_user_agents()\n return '%s (%s)' % [agent_app, agent_data.join(', ')]\n end", "language": "ruby", "code": "def generate_user_agent(extra_ids = [], agent_app = nil)\n agent_app ||= File.basename($0)\n agent_data = extra_ids\n agent_data << 'Common-Ruby/%s' % AdsCommon::ApiConfig::CLIENT_LIB_VERSION\n agent_data << 'GoogleAdsSavon/%s' % GoogleAdsSavon::VERSION\n ruby_engine = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby'\n agent_data << [ruby_engine, RUBY_VERSION].join('/')\n agent_data << 'HTTPI/%s' % HTTPI::VERSION\n agent_data << HTTPI::Adapter.use.to_s\n agent_data += get_extra_user_agents()\n return '%s (%s)' % [agent_app, agent_data.join(', ')]\n end", "code_tokens": ["def", "generate_user_agent", "(", "extra_ids", "=", "[", "]", ",", "agent_app", "=", "nil", ")", "agent_app", "||=", "File", ".", "basename", "(", "$0", ")", "agent_data", "=", "extra_ids", "agent_data", "<<", "'Common-Ruby/%s'", "%", "AdsCommon", "::", "ApiConfig", "::", "CLIENT_LIB_VERSION", "agent_data", "<<", "'GoogleAdsSavon/%s'", "%", "GoogleAdsSavon", "::", "VERSION", "ruby_engine", "=", "defined?", "(", "RUBY_ENGINE", ")", "?", "RUBY_ENGINE", ":", "'ruby'", "agent_data", "<<", "[", "ruby_engine", ",", "RUBY_VERSION", "]", ".", "join", "(", "'/'", ")", "agent_data", "<<", "'HTTPI/%s'", "%", "HTTPI", "::", "VERSION", "agent_data", "<<", "HTTPI", "::", "Adapter", ".", "use", ".", "to_s", "agent_data", "+=", "get_extra_user_agents", "(", ")", "return", "'%s (%s)'", "%", "[", "agent_app", ",", "agent_data", ".", "join", "(", "', '", ")", "]", "end"], "docstring": "Generates string for UserAgent to put into headers.", "docstring_tokens": ["Generates", "string", "for", "UserAgent", "to", "put", "into", "headers", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/credential_handler.rb#L83-L94", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/credential_handler.rb", "func_name": "AdsCommon.CredentialHandler.get_extra_user_agents", "original_string": "def get_extra_user_agents()\n @extra_user_agents_lock.synchronize do\n user_agents = @extra_user_agents.collect do |k, v|\n v.nil? ? k : '%s/%s' % [k, v]\n end\n @extra_user_agents.clear\n return user_agents\n end\n end", "language": "ruby", "code": "def get_extra_user_agents()\n @extra_user_agents_lock.synchronize do\n user_agents = @extra_user_agents.collect do |k, v|\n v.nil? ? k : '%s/%s' % [k, v]\n end\n @extra_user_agents.clear\n return user_agents\n end\n end", "code_tokens": ["def", "get_extra_user_agents", "(", ")", "@extra_user_agents_lock", ".", "synchronize", "do", "user_agents", "=", "@extra_user_agents", ".", "collect", "do", "|", "k", ",", "v", "|", "v", ".", "nil?", "?", "k", ":", "'%s/%s'", "%", "[", "k", ",", "v", "]", "end", "@extra_user_agents", ".", "clear", "return", "user_agents", "end", "end"], "docstring": "Generates an array of extra user agents to include in the user agent\n string.", "docstring_tokens": ["Generates", "an", "array", "of", "extra", "user", "agents", "to", "include", "in", "the", "user", "agent", "string", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/credential_handler.rb#L116-L124", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.extract_header_data", "original_string": "def extract_header_data(response)\n header_type = get_full_type_signature(:SoapResponseHeader)\n headers = response.header[:response_header].dup\n process_attributes(headers, false)\n headers = normalize_fields(headers, header_type[:fields])\n return headers\n end", "language": "ruby", "code": "def extract_header_data(response)\n header_type = get_full_type_signature(:SoapResponseHeader)\n headers = response.header[:response_header].dup\n process_attributes(headers, false)\n headers = normalize_fields(headers, header_type[:fields])\n return headers\n end", "code_tokens": ["def", "extract_header_data", "(", "response", ")", "header_type", "=", "get_full_type_signature", "(", ":SoapResponseHeader", ")", "headers", "=", "response", ".", "header", "[", ":response_header", "]", ".", "dup", "process_attributes", "(", "headers", ",", "false", ")", "headers", "=", "normalize_fields", "(", "headers", ",", "header_type", "[", ":fields", "]", ")", "return", "headers", "end"], "docstring": "Extracts misc data from response header.", "docstring_tokens": ["Extracts", "misc", "data", "from", "response", "header", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L44-L50", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.extract_exception_data", "original_string": "def extract_exception_data(soap_fault, exception_name)\n exception_type = get_full_type_signature(exception_name)\n process_attributes(soap_fault, false)\n soap_fault = normalize_fields(soap_fault, exception_type[:fields])\n return soap_fault\n end", "language": "ruby", "code": "def extract_exception_data(soap_fault, exception_name)\n exception_type = get_full_type_signature(exception_name)\n process_attributes(soap_fault, false)\n soap_fault = normalize_fields(soap_fault, exception_type[:fields])\n return soap_fault\n end", "code_tokens": ["def", "extract_exception_data", "(", "soap_fault", ",", "exception_name", ")", "exception_type", "=", "get_full_type_signature", "(", "exception_name", ")", "process_attributes", "(", "soap_fault", ",", "false", ")", "soap_fault", "=", "normalize_fields", "(", "soap_fault", ",", "exception_type", "[", ":fields", "]", ")", "return", "soap_fault", "end"], "docstring": "Extracts misc data from SOAP fault.", "docstring_tokens": ["Extracts", "misc", "data", "from", "SOAP", "fault", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L53-L58", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.normalize_fields", "original_string": "def normalize_fields(data, fields)\n fields.each do |field|\n field_name = field[:name]\n if data.include?(field_name)\n field_data = data[field_name]\n field_data = normalize_output_field(field_data, field)\n field_data = check_array_collapse(field_data, field)\n data[field_name] = field_data unless field_data.nil?\n end\n end\n return data\n end", "language": "ruby", "code": "def normalize_fields(data, fields)\n fields.each do |field|\n field_name = field[:name]\n if data.include?(field_name)\n field_data = data[field_name]\n field_data = normalize_output_field(field_data, field)\n field_data = check_array_collapse(field_data, field)\n data[field_name] = field_data unless field_data.nil?\n end\n end\n return data\n end", "code_tokens": ["def", "normalize_fields", "(", "data", ",", "fields", ")", "fields", ".", "each", "do", "|", "field", "|", "field_name", "=", "field", "[", ":name", "]", "if", "data", ".", "include?", "(", "field_name", ")", "field_data", "=", "data", "[", "field_name", "]", "field_data", "=", "normalize_output_field", "(", "field_data", ",", "field", ")", "field_data", "=", "check_array_collapse", "(", "field_data", ",", "field", ")", "data", "[", "field_name", "]", "=", "field_data", "unless", "field_data", ".", "nil?", "end", "end", "return", "data", "end"], "docstring": "Normalizes all fields for the given data based on the fields list\n provided.", "docstring_tokens": ["Normalizes", "all", "fields", "for", "the", "given", "data", "based", "on", "the", "fields", "list", "provided", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L70-L81", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.normalize_output_field", "original_string": "def normalize_output_field(field_data, field_def)\n return case field_data\n when Array\n normalize_array_field(field_data, field_def)\n when Hash\n normalize_hash_field(field_data, field_def)\n else\n normalize_item(field_data, field_def)\n end\n end", "language": "ruby", "code": "def normalize_output_field(field_data, field_def)\n return case field_data\n when Array\n normalize_array_field(field_data, field_def)\n when Hash\n normalize_hash_field(field_data, field_def)\n else\n normalize_item(field_data, field_def)\n end\n end", "code_tokens": ["def", "normalize_output_field", "(", "field_data", ",", "field_def", ")", "return", "case", "field_data", "when", "Array", "normalize_array_field", "(", "field_data", ",", "field_def", ")", "when", "Hash", "normalize_hash_field", "(", "field_data", ",", "field_def", ")", "else", "normalize_item", "(", "field_data", ",", "field_def", ")", "end", "end"], "docstring": "Normalizes one field of a given data recursively.\n\n Args:\n - field_data: XML data to normalize\n - field_def: field type definition for the data", "docstring_tokens": ["Normalizes", "one", "field", "of", "a", "given", "data", "recursively", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L89-L98", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.normalize_array_field", "original_string": "def normalize_array_field(data, field_def)\n result = data\n # Convert a specific structure to a handy hash if detected.\n if check_key_value_struct(result)\n result = convert_key_value_to_hash(result).inject({}) do |s, (k,v)|\n s[k] = normalize_output_field(v, field_def)\n s\n end\n else\n result = data.map {|item| normalize_output_field(item, field_def)}\n end\n return result\n end", "language": "ruby", "code": "def normalize_array_field(data, field_def)\n result = data\n # Convert a specific structure to a handy hash if detected.\n if check_key_value_struct(result)\n result = convert_key_value_to_hash(result).inject({}) do |s, (k,v)|\n s[k] = normalize_output_field(v, field_def)\n s\n end\n else\n result = data.map {|item| normalize_output_field(item, field_def)}\n end\n return result\n end", "code_tokens": ["def", "normalize_array_field", "(", "data", ",", "field_def", ")", "result", "=", "data", "# Convert a specific structure to a handy hash if detected.", "if", "check_key_value_struct", "(", "result", ")", "result", "=", "convert_key_value_to_hash", "(", "result", ")", ".", "inject", "(", "{", "}", ")", "do", "|", "s", ",", "(", "k", ",", "v", ")", "|", "s", "[", "k", "]", "=", "normalize_output_field", "(", "v", ",", "field_def", ")", "s", "end", "else", "result", "=", "data", ".", "map", "{", "|", "item", "|", "normalize_output_field", "(", "item", ",", "field_def", ")", "}", "end", "return", "result", "end"], "docstring": "Normalizes every item of an Array.", "docstring_tokens": ["Normalizes", "every", "item", "of", "an", "Array", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L101-L113", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.normalize_hash_field", "original_string": "def normalize_hash_field(field, field_def)\n process_attributes(field, true)\n field_type = field_def[:type]\n field_def = get_full_type_signature(field_type)\n\n # First checking for xsi:type provided.\n xsi_type_override = determine_xsi_type_override(field, field_def)\n unless xsi_type_override.nil?\n field_def = get_full_type_signature(xsi_type_override)\n return (field_def.nil?) ? field :\n normalize_fields(field, field_def[:fields])\n end\n\n result = field\n\n # Now checking for choice options from wsdl.\n choice_type_override = determine_choice_type_override(field, field_def)\n unless choice_type_override.nil?\n # For overrides we need to process sub-field and than return it\n # in the original structure.\n field_key = field.keys.first\n field_data = field[field_key]\n field_def = get_full_type_signature(choice_type_override)\n if !field_def.nil? and field_data.kind_of?(Hash)\n field_data = normalize_fields(field_data, field_def[:fields])\n end\n result = {field_key => field_data}\n else\n # Otherwise using the best we have.\n unless field_def.nil?\n result = normalize_fields(field, field_def[:fields])\n end\n end\n\n # Convert a single key-value hash to a proper hash if detected.\n if check_key_value_struct(result)\n result = convert_key_value_to_hash(result)\n end\n\n return result\n end", "language": "ruby", "code": "def normalize_hash_field(field, field_def)\n process_attributes(field, true)\n field_type = field_def[:type]\n field_def = get_full_type_signature(field_type)\n\n # First checking for xsi:type provided.\n xsi_type_override = determine_xsi_type_override(field, field_def)\n unless xsi_type_override.nil?\n field_def = get_full_type_signature(xsi_type_override)\n return (field_def.nil?) ? field :\n normalize_fields(field, field_def[:fields])\n end\n\n result = field\n\n # Now checking for choice options from wsdl.\n choice_type_override = determine_choice_type_override(field, field_def)\n unless choice_type_override.nil?\n # For overrides we need to process sub-field and than return it\n # in the original structure.\n field_key = field.keys.first\n field_data = field[field_key]\n field_def = get_full_type_signature(choice_type_override)\n if !field_def.nil? and field_data.kind_of?(Hash)\n field_data = normalize_fields(field_data, field_def[:fields])\n end\n result = {field_key => field_data}\n else\n # Otherwise using the best we have.\n unless field_def.nil?\n result = normalize_fields(field, field_def[:fields])\n end\n end\n\n # Convert a single key-value hash to a proper hash if detected.\n if check_key_value_struct(result)\n result = convert_key_value_to_hash(result)\n end\n\n return result\n end", "code_tokens": ["def", "normalize_hash_field", "(", "field", ",", "field_def", ")", "process_attributes", "(", "field", ",", "true", ")", "field_type", "=", "field_def", "[", ":type", "]", "field_def", "=", "get_full_type_signature", "(", "field_type", ")", "# First checking for xsi:type provided.", "xsi_type_override", "=", "determine_xsi_type_override", "(", "field", ",", "field_def", ")", "unless", "xsi_type_override", ".", "nil?", "field_def", "=", "get_full_type_signature", "(", "xsi_type_override", ")", "return", "(", "field_def", ".", "nil?", ")", "?", "field", ":", "normalize_fields", "(", "field", ",", "field_def", "[", ":fields", "]", ")", "end", "result", "=", "field", "# Now checking for choice options from wsdl.", "choice_type_override", "=", "determine_choice_type_override", "(", "field", ",", "field_def", ")", "unless", "choice_type_override", ".", "nil?", "# For overrides we need to process sub-field and than return it", "# in the original structure.", "field_key", "=", "field", ".", "keys", ".", "first", "field_data", "=", "field", "[", "field_key", "]", "field_def", "=", "get_full_type_signature", "(", "choice_type_override", ")", "if", "!", "field_def", ".", "nil?", "and", "field_data", ".", "kind_of?", "(", "Hash", ")", "field_data", "=", "normalize_fields", "(", "field_data", ",", "field_def", "[", ":fields", "]", ")", "end", "result", "=", "{", "field_key", "=>", "field_data", "}", "else", "# Otherwise using the best we have.", "unless", "field_def", ".", "nil?", "result", "=", "normalize_fields", "(", "field", ",", "field_def", "[", ":fields", "]", ")", "end", "end", "# Convert a single key-value hash to a proper hash if detected.", "if", "check_key_value_struct", "(", "result", ")", "result", "=", "convert_key_value_to_hash", "(", "result", ")", "end", "return", "result", "end"], "docstring": "Normalizes every item of a Hash.", "docstring_tokens": ["Normalizes", "every", "item", "of", "a", "Hash", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L116-L156", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.determine_choice_type_override", "original_string": "def determine_choice_type_override(field_data, field_def)\n result = nil\n if field_data.kind_of?(Hash) and field_def.include?(:choices)\n result = determine_choice(field_data, field_def[:choices])\n end\n return result\n end", "language": "ruby", "code": "def determine_choice_type_override(field_data, field_def)\n result = nil\n if field_data.kind_of?(Hash) and field_def.include?(:choices)\n result = determine_choice(field_data, field_def[:choices])\n end\n return result\n end", "code_tokens": ["def", "determine_choice_type_override", "(", "field_data", ",", "field_def", ")", "result", "=", "nil", "if", "field_data", ".", "kind_of?", "(", "Hash", ")", "and", "field_def", ".", "include?", "(", ":choices", ")", "result", "=", "determine_choice", "(", "field_data", ",", "field_def", "[", ":choices", "]", ")", "end", "return", "result", "end"], "docstring": "Determines a choice type override for for the field. Returns nil if no\n override found.", "docstring_tokens": ["Determines", "a", "choice", "type", "override", "for", "for", "the", "field", ".", "Returns", "nil", "if", "no", "override", "found", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L204-L210", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.determine_choice", "original_string": "def determine_choice(field_data, field_choices)\n result = nil\n key_name = field_data.keys.first\n unless key_name.nil?\n choice = find_named_entry(field_choices, key_name)\n result = choice[:type] unless choice.nil?\n end\n return result\n end", "language": "ruby", "code": "def determine_choice(field_data, field_choices)\n result = nil\n key_name = field_data.keys.first\n unless key_name.nil?\n choice = find_named_entry(field_choices, key_name)\n result = choice[:type] unless choice.nil?\n end\n return result\n end", "code_tokens": ["def", "determine_choice", "(", "field_data", ",", "field_choices", ")", "result", "=", "nil", "key_name", "=", "field_data", ".", "keys", ".", "first", "unless", "key_name", ".", "nil?", "choice", "=", "find_named_entry", "(", "field_choices", ",", "key_name", ")", "result", "=", "choice", "[", ":type", "]", "unless", "choice", ".", "nil?", "end", "return", "result", "end"], "docstring": "Finds the choice option matching data provided.", "docstring_tokens": ["Finds", "the", "choice", "option", "matching", "data", "provided", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L213-L221", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.normalize_item", "original_string": "def normalize_item(item, field_def)\n return case field_def[:type]\n when 'long', 'int' then Integer(item)\n when 'double', 'float' then Float(item)\n when 'boolean' then item.kind_of?(String) ?\n item.casecmp('true') == 0 : item\n else item\n end\n end", "language": "ruby", "code": "def normalize_item(item, field_def)\n return case field_def[:type]\n when 'long', 'int' then Integer(item)\n when 'double', 'float' then Float(item)\n when 'boolean' then item.kind_of?(String) ?\n item.casecmp('true') == 0 : item\n else item\n end\n end", "code_tokens": ["def", "normalize_item", "(", "item", ",", "field_def", ")", "return", "case", "field_def", "[", ":type", "]", "when", "'long'", ",", "'int'", "then", "Integer", "(", "item", ")", "when", "'double'", ",", "'float'", "then", "Float", "(", "item", ")", "when", "'boolean'", "then", "item", ".", "kind_of?", "(", "String", ")", "?", "item", ".", "casecmp", "(", "'true'", ")", "==", "0", ":", "item", "else", "item", "end", "end"], "docstring": "Converts one leaf item to a built-in type.", "docstring_tokens": ["Converts", "one", "leaf", "item", "to", "a", "built", "-", "in", "type", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L230-L238", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.check_array_collapse", "original_string": "def check_array_collapse(data, field_def)\n result = data\n if !field_def[:min_occurs].nil? &&\n (field_def[:max_occurs] == :unbounded ||\n (!field_def[:max_occurs].nil? && field_def[:max_occurs] > 1)) &&\n !(field_def[:type] =~ /MapEntry$/)\n result = arrayize(result)\n end\n return result\n end", "language": "ruby", "code": "def check_array_collapse(data, field_def)\n result = data\n if !field_def[:min_occurs].nil? &&\n (field_def[:max_occurs] == :unbounded ||\n (!field_def[:max_occurs].nil? && field_def[:max_occurs] > 1)) &&\n !(field_def[:type] =~ /MapEntry$/)\n result = arrayize(result)\n end\n return result\n end", "code_tokens": ["def", "check_array_collapse", "(", "data", ",", "field_def", ")", "result", "=", "data", "if", "!", "field_def", "[", ":min_occurs", "]", ".", "nil?", "&&", "(", "field_def", "[", ":max_occurs", "]", "==", ":unbounded", "||", "(", "!", "field_def", "[", ":max_occurs", "]", ".", "nil?", "&&", "field_def", "[", ":max_occurs", "]", ">", "1", ")", ")", "&&", "!", "(", "field_def", "[", ":type", "]", "=~", "/", "/", ")", "result", "=", "arrayize", "(", "result", ")", "end", "return", "result", "end"], "docstring": "Checks if the field signature allows an array and forces array structure\n even for a signle item.", "docstring_tokens": ["Checks", "if", "the", "field", "signature", "allows", "an", "array", "and", "forces", "array", "structure", "even", "for", "a", "signle", "item", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L242-L251", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.process_attributes", "original_string": "def process_attributes(data, keep_xsi_type = false)\n if keep_xsi_type\n xsi_type = data.delete(:\"@xsi:type\")\n data[:xsi_type] = xsi_type if xsi_type\n end\n data.reject! {|key, value| key.to_s.start_with?('@')}\n end", "language": "ruby", "code": "def process_attributes(data, keep_xsi_type = false)\n if keep_xsi_type\n xsi_type = data.delete(:\"@xsi:type\")\n data[:xsi_type] = xsi_type if xsi_type\n end\n data.reject! {|key, value| key.to_s.start_with?('@')}\n end", "code_tokens": ["def", "process_attributes", "(", "data", ",", "keep_xsi_type", "=", "false", ")", "if", "keep_xsi_type", "xsi_type", "=", "data", ".", "delete", "(", ":\"", "\"", ")", "data", "[", ":xsi_type", "]", "=", "xsi_type", "if", "xsi_type", "end", "data", ".", "reject!", "{", "|", "key", ",", "value", "|", "key", ".", "to_s", ".", "start_with?", "(", "'@'", ")", "}", "end"], "docstring": "Handles attributes received from Savon.", "docstring_tokens": ["Handles", "attributes", "received", "from", "Savon", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L282-L288", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.service", "original_string": "def service(name, version = nil)\n name = name.to_sym\n version = (version.nil?) ? api_config.default_version : version.to_sym\n\n # Check if the combination is available.\n validate_service_request(version, name)\n\n # Try to re-use the service for this version if it was requested before.\n wrapper = if @wrappers.include?(version) && @wrappers[version][name]\n @wrappers[version][name]\n else\n @wrappers[version] ||= {}\n @wrappers[version][name] = prepare_wrapper(version, name)\n end\n return wrapper\n end", "language": "ruby", "code": "def service(name, version = nil)\n name = name.to_sym\n version = (version.nil?) ? api_config.default_version : version.to_sym\n\n # Check if the combination is available.\n validate_service_request(version, name)\n\n # Try to re-use the service for this version if it was requested before.\n wrapper = if @wrappers.include?(version) && @wrappers[version][name]\n @wrappers[version][name]\n else\n @wrappers[version] ||= {}\n @wrappers[version][name] = prepare_wrapper(version, name)\n end\n return wrapper\n end", "code_tokens": ["def", "service", "(", "name", ",", "version", "=", "nil", ")", "name", "=", "name", ".", "to_sym", "version", "=", "(", "version", ".", "nil?", ")", "?", "api_config", ".", "default_version", ":", "version", ".", "to_sym", "# Check if the combination is available.", "validate_service_request", "(", "version", ",", "name", ")", "# Try to re-use the service for this version if it was requested before.", "wrapper", "=", "if", "@wrappers", ".", "include?", "(", "version", ")", "&&", "@wrappers", "[", "version", "]", "[", "name", "]", "@wrappers", "[", "version", "]", "[", "name", "]", "else", "@wrappers", "[", "version", "]", "||=", "{", "}", "@wrappers", "[", "version", "]", "[", "name", "]", "=", "prepare_wrapper", "(", "version", ",", "name", ")", "end", "return", "wrapper", "end"], "docstring": "Obtain an API service, given a version and its name.\n\n Args:\n - name: name for the intended service\n - version: intended API version.\n\n Returns:\n - the service wrapper for the intended service.", "docstring_tokens": ["Obtain", "an", "API", "service", "given", "a", "version", "and", "its", "name", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L70-L85", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.authorize", "original_string": "def authorize(parameters = {}, &block)\n parameters.each_pair do |key, value|\n @credential_handler.set_credential(key, value)\n end\n\n auth_handler = get_auth_handler()\n token = auth_handler.get_token()\n\n # If token is invalid ask for a new one.\n if token.nil?\n begin\n credentials = @credential_handler.credentials\n token = auth_handler.get_token(credentials)\n rescue AdsCommon::Errors::OAuth2VerificationRequired => e\n verification_code = (block_given?) ? yield(e.oauth_url) : nil\n # Retry with verification code if one provided.\n if verification_code\n @credential_handler.set_credential(\n :oauth2_verification_code, verification_code)\n retry\n else\n raise e\n end\n end\n end\n return token\n end", "language": "ruby", "code": "def authorize(parameters = {}, &block)\n parameters.each_pair do |key, value|\n @credential_handler.set_credential(key, value)\n end\n\n auth_handler = get_auth_handler()\n token = auth_handler.get_token()\n\n # If token is invalid ask for a new one.\n if token.nil?\n begin\n credentials = @credential_handler.credentials\n token = auth_handler.get_token(credentials)\n rescue AdsCommon::Errors::OAuth2VerificationRequired => e\n verification_code = (block_given?) ? yield(e.oauth_url) : nil\n # Retry with verification code if one provided.\n if verification_code\n @credential_handler.set_credential(\n :oauth2_verification_code, verification_code)\n retry\n else\n raise e\n end\n end\n end\n return token\n end", "code_tokens": ["def", "authorize", "(", "parameters", "=", "{", "}", ",", "&", "block", ")", "parameters", ".", "each_pair", "do", "|", "key", ",", "value", "|", "@credential_handler", ".", "set_credential", "(", "key", ",", "value", ")", "end", "auth_handler", "=", "get_auth_handler", "(", ")", "token", "=", "auth_handler", ".", "get_token", "(", ")", "# If token is invalid ask for a new one.", "if", "token", ".", "nil?", "begin", "credentials", "=", "@credential_handler", ".", "credentials", "token", "=", "auth_handler", ".", "get_token", "(", "credentials", ")", "rescue", "AdsCommon", "::", "Errors", "::", "OAuth2VerificationRequired", "=>", "e", "verification_code", "=", "(", "block_given?", ")", "?", "yield", "(", "e", ".", "oauth_url", ")", ":", "nil", "# Retry with verification code if one provided.", "if", "verification_code", "@credential_handler", ".", "set_credential", "(", ":oauth2_verification_code", ",", "verification_code", ")", "retry", "else", "raise", "e", "end", "end", "end", "return", "token", "end"], "docstring": "Authorize with specified authentication method.\n\n Args:\n - parameters - hash of credentials to add to configuration\n - block - code block to handle auth login url\n\n Returns:\n - Auth token for the method\n\n Throws:\n - AdsCommon::Errors::AuthError or derived if authetication error has\n occured", "docstring_tokens": ["Authorize", "with", "specified", "authentication", "method", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L100-L126", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.save_oauth2_token", "original_string": "def save_oauth2_token(token)\n raise AdsCommon::Errors::Error, \"Can't save nil token\" if token.nil?\n AdsCommon::Utils.save_oauth2_token(\n File.join(ENV['HOME'], api_config.default_config_filename), token)\n end", "language": "ruby", "code": "def save_oauth2_token(token)\n raise AdsCommon::Errors::Error, \"Can't save nil token\" if token.nil?\n AdsCommon::Utils.save_oauth2_token(\n File.join(ENV['HOME'], api_config.default_config_filename), token)\n end", "code_tokens": ["def", "save_oauth2_token", "(", "token", ")", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Can't save nil token\"", "if", "token", ".", "nil?", "AdsCommon", "::", "Utils", ".", "save_oauth2_token", "(", "File", ".", "join", "(", "ENV", "[", "'HOME'", "]", ",", "api_config", ".", "default_config_filename", ")", ",", "token", ")", "end"], "docstring": "Updates default configuration file to include OAuth2 token information.", "docstring_tokens": ["Updates", "default", "configuration", "file", "to", "include", "OAuth2", "token", "information", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L143-L147", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.validate_service_request", "original_string": "def validate_service_request(version, service)\n # Check if the current config supports the requested version.\n unless api_config.has_version(version)\n raise AdsCommon::Errors::Error,\n \"Version '%s' not recognized\" % version.to_s\n end\n\n # Check if the specified version has the requested service.\n unless api_config.version_has_service(version, service)\n raise AdsCommon::Errors::Error,\n \"Version '%s' does not contain service '%s'\" %\n [version.to_s, service.to_s]\n end\n end", "language": "ruby", "code": "def validate_service_request(version, service)\n # Check if the current config supports the requested version.\n unless api_config.has_version(version)\n raise AdsCommon::Errors::Error,\n \"Version '%s' not recognized\" % version.to_s\n end\n\n # Check if the specified version has the requested service.\n unless api_config.version_has_service(version, service)\n raise AdsCommon::Errors::Error,\n \"Version '%s' does not contain service '%s'\" %\n [version.to_s, service.to_s]\n end\n end", "code_tokens": ["def", "validate_service_request", "(", "version", ",", "service", ")", "# Check if the current config supports the requested version.", "unless", "api_config", ".", "has_version", "(", "version", ")", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Version '%s' not recognized\"", "%", "version", ".", "to_s", "end", "# Check if the specified version has the requested service.", "unless", "api_config", ".", "version_has_service", "(", "version", ",", "service", ")", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Version '%s' does not contain service '%s'\"", "%", "[", "version", ".", "to_s", ",", "service", ".", "to_s", "]", "end", "end"], "docstring": "Auxiliary method to test parameters correctness for the service request.", "docstring_tokens": ["Auxiliary", "method", "to", "test", "parameters", "correctness", "for", "the", "service", "request", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L152-L165", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.create_auth_handler", "original_string": "def create_auth_handler()\n auth_method = @config.read('authentication.method', :OAUTH2)\n return case auth_method\n when :OAUTH\n raise AdsCommon::Errors::Error,\n 'OAuth authorization method is deprecated, use OAuth2 instead.'\n when :OAUTH2\n AdsCommon::Auth::OAuth2Handler.new(\n @config,\n api_config.config(:oauth_scope)\n )\n when :OAUTH2_SERVICE_ACCOUNT\n AdsCommon::Auth::OAuth2ServiceAccountHandler.new(\n @config,\n api_config.config(:oauth_scope)\n )\n else\n raise AdsCommon::Errors::Error,\n \"Unknown authentication method '%s'\" % auth_method\n end\n end", "language": "ruby", "code": "def create_auth_handler()\n auth_method = @config.read('authentication.method', :OAUTH2)\n return case auth_method\n when :OAUTH\n raise AdsCommon::Errors::Error,\n 'OAuth authorization method is deprecated, use OAuth2 instead.'\n when :OAUTH2\n AdsCommon::Auth::OAuth2Handler.new(\n @config,\n api_config.config(:oauth_scope)\n )\n when :OAUTH2_SERVICE_ACCOUNT\n AdsCommon::Auth::OAuth2ServiceAccountHandler.new(\n @config,\n api_config.config(:oauth_scope)\n )\n else\n raise AdsCommon::Errors::Error,\n \"Unknown authentication method '%s'\" % auth_method\n end\n end", "code_tokens": ["def", "create_auth_handler", "(", ")", "auth_method", "=", "@config", ".", "read", "(", "'authentication.method'", ",", ":OAUTH2", ")", "return", "case", "auth_method", "when", ":OAUTH", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "'OAuth authorization method is deprecated, use OAuth2 instead.'", "when", ":OAUTH2", "AdsCommon", "::", "Auth", "::", "OAuth2Handler", ".", "new", "(", "@config", ",", "api_config", ".", "config", "(", ":oauth_scope", ")", ")", "when", ":OAUTH2_SERVICE_ACCOUNT", "AdsCommon", "::", "Auth", "::", "OAuth2ServiceAccountHandler", ".", "new", "(", "@config", ",", "api_config", ".", "config", "(", ":oauth_scope", ")", ")", "else", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Unknown authentication method '%s'\"", "%", "auth_method", "end", "end"], "docstring": "Auxiliary method to create an authentication handler.\n\n Returns:\n - auth handler", "docstring_tokens": ["Auxiliary", "method", "to", "create", "an", "authentication", "handler", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L190-L210", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.prepare_wrapper", "original_string": "def prepare_wrapper(version, service)\n api_config.do_require(version, service)\n endpoint = api_config.endpoint(version, service)\n interface_class_name = api_config.interface_name(version, service)\n\n wrapper = class_for_path(interface_class_name).new(@config, endpoint)\n auth_handler = get_auth_handler()\n header_ns = api_config.config(:header_ns) + version.to_s\n soap_handler = soap_header_handler(auth_handler, version, header_ns,\n wrapper.namespace)\n wrapper.header_handler = soap_handler\n\n return wrapper\n end", "language": "ruby", "code": "def prepare_wrapper(version, service)\n api_config.do_require(version, service)\n endpoint = api_config.endpoint(version, service)\n interface_class_name = api_config.interface_name(version, service)\n\n wrapper = class_for_path(interface_class_name).new(@config, endpoint)\n auth_handler = get_auth_handler()\n header_ns = api_config.config(:header_ns) + version.to_s\n soap_handler = soap_header_handler(auth_handler, version, header_ns,\n wrapper.namespace)\n wrapper.header_handler = soap_handler\n\n return wrapper\n end", "code_tokens": ["def", "prepare_wrapper", "(", "version", ",", "service", ")", "api_config", ".", "do_require", "(", "version", ",", "service", ")", "endpoint", "=", "api_config", ".", "endpoint", "(", "version", ",", "service", ")", "interface_class_name", "=", "api_config", ".", "interface_name", "(", "version", ",", "service", ")", "wrapper", "=", "class_for_path", "(", "interface_class_name", ")", ".", "new", "(", "@config", ",", "endpoint", ")", "auth_handler", "=", "get_auth_handler", "(", ")", "header_ns", "=", "api_config", ".", "config", "(", ":header_ns", ")", "+", "version", ".", "to_s", "soap_handler", "=", "soap_header_handler", "(", "auth_handler", ",", "version", ",", "header_ns", ",", "wrapper", ".", "namespace", ")", "wrapper", ".", "header_handler", "=", "soap_handler", "return", "wrapper", "end"], "docstring": "Handle loading of a single service.\n Creates the wrapper, sets up handlers and creates an instance of it.\n\n Args:\n - version: intended API version, must be a symbol\n - service: name for the intended service\n\n Returns:\n - a simplified wrapper generated for the service", "docstring_tokens": ["Handle", "loading", "of", "a", "single", "service", ".", "Creates", "the", "wrapper", "sets", "up", "handlers", "and", "creates", "an", "instance", "of", "it", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L222-L235", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.create_default_logger", "original_string": "def create_default_logger()\n logger = Logger.new(STDOUT)\n logger.level = get_log_level_for_string(\n @config.read('library.log_level', 'INFO'))\n return logger\n end", "language": "ruby", "code": "def create_default_logger()\n logger = Logger.new(STDOUT)\n logger.level = get_log_level_for_string(\n @config.read('library.log_level', 'INFO'))\n return logger\n end", "code_tokens": ["def", "create_default_logger", "(", ")", "logger", "=", "Logger", ".", "new", "(", "STDOUT", ")", "logger", ".", "level", "=", "get_log_level_for_string", "(", "@config", ".", "read", "(", "'library.log_level'", ",", "'INFO'", ")", ")", "return", "logger", "end"], "docstring": "Auxiliary method to create a default Logger.", "docstring_tokens": ["Auxiliary", "method", "to", "create", "a", "default", "Logger", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L238-L243", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.load_config", "original_string": "def load_config(provided_config = nil)\n @config = (provided_config.nil?) ?\n AdsCommon::Config.new(\n File.join(ENV['HOME'], api_config.default_config_filename)) :\n AdsCommon::Config.new(provided_config)\n init_config()\n end", "language": "ruby", "code": "def load_config(provided_config = nil)\n @config = (provided_config.nil?) ?\n AdsCommon::Config.new(\n File.join(ENV['HOME'], api_config.default_config_filename)) :\n AdsCommon::Config.new(provided_config)\n init_config()\n end", "code_tokens": ["def", "load_config", "(", "provided_config", "=", "nil", ")", "@config", "=", "(", "provided_config", ".", "nil?", ")", "?", "AdsCommon", "::", "Config", ".", "new", "(", "File", ".", "join", "(", "ENV", "[", "'HOME'", "]", ",", "api_config", ".", "default_config_filename", ")", ")", ":", "AdsCommon", "::", "Config", ".", "new", "(", "provided_config", ")", "init_config", "(", ")", "end"], "docstring": "Helper method to load the default configuration file or a given config.", "docstring_tokens": ["Helper", "method", "to", "load", "the", "default", "configuration", "file", "or", "a", "given", "config", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L246-L252", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.init_config", "original_string": "def init_config()\n # Set up logger.\n provided_logger = @config.read('library.logger')\n self.logger = (provided_logger.nil?) ?\n create_default_logger() : provided_logger\n\n # Set up default HTTPI adapter.\n provided_adapter = @config.read('connection.adapter')\n @config.set('connection.adapter', :httpclient) if provided_adapter.nil?\n\n # Make sure Auth param is a symbol.\n symbolize_config_value('authentication.method')\n end", "language": "ruby", "code": "def init_config()\n # Set up logger.\n provided_logger = @config.read('library.logger')\n self.logger = (provided_logger.nil?) ?\n create_default_logger() : provided_logger\n\n # Set up default HTTPI adapter.\n provided_adapter = @config.read('connection.adapter')\n @config.set('connection.adapter', :httpclient) if provided_adapter.nil?\n\n # Make sure Auth param is a symbol.\n symbolize_config_value('authentication.method')\n end", "code_tokens": ["def", "init_config", "(", ")", "# Set up logger.", "provided_logger", "=", "@config", ".", "read", "(", "'library.logger'", ")", "self", ".", "logger", "=", "(", "provided_logger", ".", "nil?", ")", "?", "create_default_logger", "(", ")", ":", "provided_logger", "# Set up default HTTPI adapter.", "provided_adapter", "=", "@config", ".", "read", "(", "'connection.adapter'", ")", "@config", ".", "set", "(", "'connection.adapter'", ",", ":httpclient", ")", "if", "provided_adapter", ".", "nil?", "# Make sure Auth param is a symbol.", "symbolize_config_value", "(", "'authentication.method'", ")", "end"], "docstring": "Initializes config with default values and converts existing if required.", "docstring_tokens": ["Initializes", "config", "with", "default", "values", "and", "converts", "existing", "if", "required", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L255-L267", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.symbolize_config_value", "original_string": "def symbolize_config_value(key)\n value_str = @config.read(key).to_s\n if !value_str.nil? and !value_str.empty?\n value = value_str.upcase.to_sym\n @config.set(key, value)\n end\n end", "language": "ruby", "code": "def symbolize_config_value(key)\n value_str = @config.read(key).to_s\n if !value_str.nil? and !value_str.empty?\n value = value_str.upcase.to_sym\n @config.set(key, value)\n end\n end", "code_tokens": ["def", "symbolize_config_value", "(", "key", ")", "value_str", "=", "@config", ".", "read", "(", "key", ")", ".", "to_s", "if", "!", "value_str", ".", "nil?", "and", "!", "value_str", ".", "empty?", "value", "=", "value_str", ".", "upcase", ".", "to_sym", "@config", ".", "set", "(", "key", ",", "value", ")", "end", "end"], "docstring": "Converts value of a config key to uppercase symbol.", "docstring_tokens": ["Converts", "value", "of", "a", "config", "key", "to", "uppercase", "symbol", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L270-L276", "partition": "valid"} {"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.class_for_path", "original_string": "def class_for_path(path)\n path.split('::').inject(Kernel) do |scope, const_name|\n scope.const_get(const_name)\n end\n end", "language": "ruby", "code": "def class_for_path(path)\n path.split('::').inject(Kernel) do |scope, const_name|\n scope.const_get(const_name)\n end\n end", "code_tokens": ["def", "class_for_path", "(", "path", ")", "path", ".", "split", "(", "'::'", ")", ".", "inject", "(", "Kernel", ")", "do", "|", "scope", ",", "const_name", "|", "scope", ".", "const_get", "(", "const_name", ")", "end", "end"], "docstring": "Converts complete class path into class object.", "docstring_tokens": ["Converts", "complete", "class", "path", "into", "class", "object", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L284-L288", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/node/farm.rb", "func_name": "Zold.Farm.to_json", "original_string": "def to_json\n {\n threads: @threads.to_json,\n pipeline: @pipeline.size,\n best: best.map(&:to_mnemo).join(', '),\n farmer: @farmer.class.name\n }\n end", "language": "ruby", "code": "def to_json\n {\n threads: @threads.to_json,\n pipeline: @pipeline.size,\n best: best.map(&:to_mnemo).join(', '),\n farmer: @farmer.class.name\n }\n end", "code_tokens": ["def", "to_json", "{", "threads", ":", "@threads", ".", "to_json", ",", "pipeline", ":", "@pipeline", ".", "size", ",", "best", ":", "best", ".", "map", "(", ":to_mnemo", ")", ".", "join", "(", "', '", ")", ",", "farmer", ":", "@farmer", ".", "class", ".", "name", "}", "end"], "docstring": "Renders the Farm into JSON to show for the end-user in front.rb.", "docstring_tokens": ["Renders", "the", "Farm", "into", "JSON", "to", "show", "for", "the", "end", "-", "user", "in", "front", ".", "rb", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/node/farm.rb#L91-L98", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/node/async_entrance.rb", "func_name": "Zold.AsyncEntrance.exists?", "original_string": "def exists?(id, body)\n DirItems.new(@dir).fetch.each do |f|\n next unless f.start_with?(\"#{id}-\")\n return true if safe_read(File.join(@dir, f)) == body\n end\n false\n end", "language": "ruby", "code": "def exists?(id, body)\n DirItems.new(@dir).fetch.each do |f|\n next unless f.start_with?(\"#{id}-\")\n return true if safe_read(File.join(@dir, f)) == body\n end\n false\n end", "code_tokens": ["def", "exists?", "(", "id", ",", "body", ")", "DirItems", ".", "new", "(", "@dir", ")", ".", "fetch", ".", "each", "do", "|", "f", "|", "next", "unless", "f", ".", "start_with?", "(", "\"#{id}-\"", ")", "return", "true", "if", "safe_read", "(", "File", ".", "join", "(", "@dir", ",", "f", ")", ")", "==", "body", "end", "false", "end"], "docstring": "Returns TRUE if a file for this wallet is already in the queue.", "docstring_tokens": ["Returns", "TRUE", "if", "a", "file", "for", "this", "wallet", "is", "already", "in", "the", "queue", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/node/async_entrance.rb#L116-L122", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/tax.rb", "func_name": "Zold.Tax.exists?", "original_string": "def exists?(details)\n !@wallet.txns.find { |t| t.details.start_with?(\"#{PREFIX} \") && t.details == details }.nil?\n end", "language": "ruby", "code": "def exists?(details)\n !@wallet.txns.find { |t| t.details.start_with?(\"#{PREFIX} \") && t.details == details }.nil?\n end", "code_tokens": ["def", "exists?", "(", "details", ")", "!", "@wallet", ".", "txns", ".", "find", "{", "|", "t", "|", "t", ".", "details", ".", "start_with?", "(", "\"#{PREFIX} \"", ")", "&&", "t", ".", "details", "==", "details", "}", ".", "nil?", "end"], "docstring": "Check whether this tax payment already exists in the wallet.", "docstring_tokens": ["Check", "whether", "this", "tax", "payment", "already", "exists", "in", "the", "wallet", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/tax.rb#L76-L78", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/node/spread_entrance.rb", "func_name": "Zold.SpreadEntrance.push", "original_string": "def push(id, body)\n mods = @entrance.push(id, body)\n return mods if @remotes.all.empty?\n mods.each do |m|\n next if @seen.include?(m)\n @mutex.synchronize { @seen << m }\n @modified.push(m)\n @log.debug(\"Spread-push scheduled for #{m}, queue size is #{@modified.size}\")\n end\n mods\n end", "language": "ruby", "code": "def push(id, body)\n mods = @entrance.push(id, body)\n return mods if @remotes.all.empty?\n mods.each do |m|\n next if @seen.include?(m)\n @mutex.synchronize { @seen << m }\n @modified.push(m)\n @log.debug(\"Spread-push scheduled for #{m}, queue size is #{@modified.size}\")\n end\n mods\n end", "code_tokens": ["def", "push", "(", "id", ",", "body", ")", "mods", "=", "@entrance", ".", "push", "(", "id", ",", "body", ")", "return", "mods", "if", "@remotes", ".", "all", ".", "empty?", "mods", ".", "each", "do", "|", "m", "|", "next", "if", "@seen", ".", "include?", "(", "m", ")", "@mutex", ".", "synchronize", "{", "@seen", "<<", "m", "}", "@modified", ".", "push", "(", "m", ")", "@log", ".", "debug", "(", "\"Spread-push scheduled for #{m}, queue size is #{@modified.size}\"", ")", "end", "mods", "end"], "docstring": "This method is thread-safe", "docstring_tokens": ["This", "method", "is", "thread", "-", "safe"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/node/spread_entrance.rb#L97-L107", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.init", "original_string": "def init(id, pubkey, overwrite: false, network: 'test')\n raise \"File '#{path}' already exists\" if File.exist?(path) && !overwrite\n raise \"Invalid network name '#{network}'\" unless network =~ /^[a-z]{4,16}$/\n FileUtils.mkdir_p(File.dirname(path))\n IO.write(path, \"#{network}\\n#{PROTOCOL}\\n#{id}\\n#{pubkey.to_pub}\\n\\n\")\n @txns.flush\n @head.flush\n end", "language": "ruby", "code": "def init(id, pubkey, overwrite: false, network: 'test')\n raise \"File '#{path}' already exists\" if File.exist?(path) && !overwrite\n raise \"Invalid network name '#{network}'\" unless network =~ /^[a-z]{4,16}$/\n FileUtils.mkdir_p(File.dirname(path))\n IO.write(path, \"#{network}\\n#{PROTOCOL}\\n#{id}\\n#{pubkey.to_pub}\\n\\n\")\n @txns.flush\n @head.flush\n end", "code_tokens": ["def", "init", "(", "id", ",", "pubkey", ",", "overwrite", ":", "false", ",", "network", ":", "'test'", ")", "raise", "\"File '#{path}' already exists\"", "if", "File", ".", "exist?", "(", "path", ")", "&&", "!", "overwrite", "raise", "\"Invalid network name '#{network}'\"", "unless", "network", "=~", "/", "/", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "path", ")", ")", "IO", ".", "write", "(", "path", ",", "\"#{network}\\n#{PROTOCOL}\\n#{id}\\n#{pubkey.to_pub}\\n\\n\"", ")", "@txns", ".", "flush", "@head", ".", "flush", "end"], "docstring": "Creates an empty wallet with the specified ID and public key.", "docstring_tokens": ["Creates", "an", "empty", "wallet", "with", "the", "specified", "ID", "and", "public", "key", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L113-L120", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.balance", "original_string": "def balance\n txns.inject(Amount::ZERO) { |sum, t| sum + t.amount }\n end", "language": "ruby", "code": "def balance\n txns.inject(Amount::ZERO) { |sum, t| sum + t.amount }\n end", "code_tokens": ["def", "balance", "txns", ".", "inject", "(", "Amount", "::", "ZERO", ")", "{", "|", "sum", ",", "t", "|", "sum", "+", "t", ".", "amount", "}", "end"], "docstring": "Returns current wallet balance.", "docstring_tokens": ["Returns", "current", "wallet", "balance", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L133-L135", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.sub", "original_string": "def sub(amount, invoice, pvt, details = '-', time: Time.now)\n raise 'The amount has to be of type Amount' unless amount.is_a?(Amount)\n raise \"The amount can't be negative: #{amount}\" if amount.negative?\n raise 'The pvt has to be of type Key' unless pvt.is_a?(Key)\n prefix, target = invoice.split('@')\n tid = max + 1\n raise 'Too many transactions already, can\\'t add more' if max > 0xffff\n txn = Txn.new(\n tid,\n time,\n amount * -1,\n prefix,\n Id.new(target),\n details\n )\n txn = txn.signed(pvt, id)\n raise \"Invalid private key for the wallet #{id}\" unless Signature.new(network).valid?(key, id, txn)\n add(txn)\n txn\n end", "language": "ruby", "code": "def sub(amount, invoice, pvt, details = '-', time: Time.now)\n raise 'The amount has to be of type Amount' unless amount.is_a?(Amount)\n raise \"The amount can't be negative: #{amount}\" if amount.negative?\n raise 'The pvt has to be of type Key' unless pvt.is_a?(Key)\n prefix, target = invoice.split('@')\n tid = max + 1\n raise 'Too many transactions already, can\\'t add more' if max > 0xffff\n txn = Txn.new(\n tid,\n time,\n amount * -1,\n prefix,\n Id.new(target),\n details\n )\n txn = txn.signed(pvt, id)\n raise \"Invalid private key for the wallet #{id}\" unless Signature.new(network).valid?(key, id, txn)\n add(txn)\n txn\n end", "code_tokens": ["def", "sub", "(", "amount", ",", "invoice", ",", "pvt", ",", "details", "=", "'-'", ",", "time", ":", "Time", ".", "now", ")", "raise", "'The amount has to be of type Amount'", "unless", "amount", ".", "is_a?", "(", "Amount", ")", "raise", "\"The amount can't be negative: #{amount}\"", "if", "amount", ".", "negative?", "raise", "'The pvt has to be of type Key'", "unless", "pvt", ".", "is_a?", "(", "Key", ")", "prefix", ",", "target", "=", "invoice", ".", "split", "(", "'@'", ")", "tid", "=", "max", "+", "1", "raise", "'Too many transactions already, can\\'t add more'", "if", "max", ">", "0xffff", "txn", "=", "Txn", ".", "new", "(", "tid", ",", "time", ",", "amount", "*", "-", "1", ",", "prefix", ",", "Id", ".", "new", "(", "target", ")", ",", "details", ")", "txn", "=", "txn", ".", "signed", "(", "pvt", ",", "id", ")", "raise", "\"Invalid private key for the wallet #{id}\"", "unless", "Signature", ".", "new", "(", "network", ")", ".", "valid?", "(", "key", ",", "id", ",", "txn", ")", "add", "(", "txn", ")", "txn", "end"], "docstring": "Add a payment transaction to the wallet.", "docstring_tokens": ["Add", "a", "payment", "transaction", "to", "the", "wallet", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L138-L157", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.add", "original_string": "def add(txn)\n raise 'The txn has to be of type Txn' unless txn.is_a?(Txn)\n raise \"Wallet #{id} can't pay itself: #{txn}\" if txn.bnf == id\n raise \"The amount can't be zero in #{id}: #{txn}\" if txn.amount.zero?\n if txn.amount.negative? && includes_negative?(txn.id)\n raise \"Negative transaction with the same ID #{txn.id} already exists in #{id}\"\n end\n if txn.amount.positive? && includes_positive?(txn.id, txn.bnf)\n raise \"Positive transaction with the same ID #{txn.id} and BNF #{txn.bnf} already exists in #{id}\"\n end\n raise \"The tax payment already exists in #{id}: #{txn}\" if Tax.new(self).exists?(txn.details)\n File.open(path, 'a') { |f| f.print \"#{txn}\\n\" }\n @txns.flush\n end", "language": "ruby", "code": "def add(txn)\n raise 'The txn has to be of type Txn' unless txn.is_a?(Txn)\n raise \"Wallet #{id} can't pay itself: #{txn}\" if txn.bnf == id\n raise \"The amount can't be zero in #{id}: #{txn}\" if txn.amount.zero?\n if txn.amount.negative? && includes_negative?(txn.id)\n raise \"Negative transaction with the same ID #{txn.id} already exists in #{id}\"\n end\n if txn.amount.positive? && includes_positive?(txn.id, txn.bnf)\n raise \"Positive transaction with the same ID #{txn.id} and BNF #{txn.bnf} already exists in #{id}\"\n end\n raise \"The tax payment already exists in #{id}: #{txn}\" if Tax.new(self).exists?(txn.details)\n File.open(path, 'a') { |f| f.print \"#{txn}\\n\" }\n @txns.flush\n end", "code_tokens": ["def", "add", "(", "txn", ")", "raise", "'The txn has to be of type Txn'", "unless", "txn", ".", "is_a?", "(", "Txn", ")", "raise", "\"Wallet #{id} can't pay itself: #{txn}\"", "if", "txn", ".", "bnf", "==", "id", "raise", "\"The amount can't be zero in #{id}: #{txn}\"", "if", "txn", ".", "amount", ".", "zero?", "if", "txn", ".", "amount", ".", "negative?", "&&", "includes_negative?", "(", "txn", ".", "id", ")", "raise", "\"Negative transaction with the same ID #{txn.id} already exists in #{id}\"", "end", "if", "txn", ".", "amount", ".", "positive?", "&&", "includes_positive?", "(", "txn", ".", "id", ",", "txn", ".", "bnf", ")", "raise", "\"Positive transaction with the same ID #{txn.id} and BNF #{txn.bnf} already exists in #{id}\"", "end", "raise", "\"The tax payment already exists in #{id}: #{txn}\"", "if", "Tax", ".", "new", "(", "self", ")", ".", "exists?", "(", "txn", ".", "details", ")", "File", ".", "open", "(", "path", ",", "'a'", ")", "{", "|", "f", "|", "f", ".", "print", "\"#{txn}\\n\"", "}", "@txns", ".", "flush", "end"], "docstring": "Add a transaction to the wallet.", "docstring_tokens": ["Add", "a", "transaction", "to", "the", "wallet", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L160-L173", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.includes_negative?", "original_string": "def includes_negative?(id, bnf = nil)\n raise 'The txn ID has to be of type Integer' unless id.is_a?(Integer)\n !txns.find { |t| t.id == id && (bnf.nil? || t.bnf == bnf) && t.amount.negative? }.nil?\n end", "language": "ruby", "code": "def includes_negative?(id, bnf = nil)\n raise 'The txn ID has to be of type Integer' unless id.is_a?(Integer)\n !txns.find { |t| t.id == id && (bnf.nil? || t.bnf == bnf) && t.amount.negative? }.nil?\n end", "code_tokens": ["def", "includes_negative?", "(", "id", ",", "bnf", "=", "nil", ")", "raise", "'The txn ID has to be of type Integer'", "unless", "id", ".", "is_a?", "(", "Integer", ")", "!", "txns", ".", "find", "{", "|", "t", "|", "t", ".", "id", "==", "id", "&&", "(", "bnf", ".", "nil?", "||", "t", ".", "bnf", "==", "bnf", ")", "&&", "t", ".", "amount", ".", "negative?", "}", ".", "nil?", "end"], "docstring": "Returns TRUE if the wallet contains a payment sent with the specified\n ID, which was sent to the specified beneficiary.", "docstring_tokens": ["Returns", "TRUE", "if", "the", "wallet", "contains", "a", "payment", "sent", "with", "the", "specified", "ID", "which", "was", "sent", "to", "the", "specified", "beneficiary", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L177-L180", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.includes_positive?", "original_string": "def includes_positive?(id, bnf)\n raise 'The txn ID has to be of type Integer' unless id.is_a?(Integer)\n raise 'The bnf has to be of type Id' unless bnf.is_a?(Id)\n !txns.find { |t| t.id == id && t.bnf == bnf && !t.amount.negative? }.nil?\n end", "language": "ruby", "code": "def includes_positive?(id, bnf)\n raise 'The txn ID has to be of type Integer' unless id.is_a?(Integer)\n raise 'The bnf has to be of type Id' unless bnf.is_a?(Id)\n !txns.find { |t| t.id == id && t.bnf == bnf && !t.amount.negative? }.nil?\n end", "code_tokens": ["def", "includes_positive?", "(", "id", ",", "bnf", ")", "raise", "'The txn ID has to be of type Integer'", "unless", "id", ".", "is_a?", "(", "Integer", ")", "raise", "'The bnf has to be of type Id'", "unless", "bnf", ".", "is_a?", "(", "Id", ")", "!", "txns", ".", "find", "{", "|", "t", "|", "t", ".", "id", "==", "id", "&&", "t", ".", "bnf", "==", "bnf", "&&", "!", "t", ".", "amount", ".", "negative?", "}", ".", "nil?", "end"], "docstring": "Returns TRUE if the wallet contains a payment received with the specified\n ID, which was sent by the specified beneficiary.", "docstring_tokens": ["Returns", "TRUE", "if", "the", "wallet", "contains", "a", "payment", "received", "with", "the", "specified", "ID", "which", "was", "sent", "by", "the", "specified", "beneficiary", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L184-L188", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.age", "original_string": "def age\n list = txns\n list.empty? ? 0 : (Time.now - list.min_by(&:date).date) / (60 * 60)\n end", "language": "ruby", "code": "def age\n list = txns\n list.empty? ? 0 : (Time.now - list.min_by(&:date).date) / (60 * 60)\n end", "code_tokens": ["def", "age", "list", "=", "txns", "list", ".", "empty?", "?", "0", ":", "(", "Time", ".", "now", "-", "list", ".", "min_by", "(", ":date", ")", ".", "date", ")", "/", "(", "60", "*", "60", ")", "end"], "docstring": "Age of wallet in hours.", "docstring_tokens": ["Age", "of", "wallet", "in", "hours", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L212-L215", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.max", "original_string": "def max\n negative = txns.select { |t| t.amount.negative? }\n negative.empty? ? 0 : negative.max_by(&:id).id\n end", "language": "ruby", "code": "def max\n negative = txns.select { |t| t.amount.negative? }\n negative.empty? ? 0 : negative.max_by(&:id).id\n end", "code_tokens": ["def", "max", "negative", "=", "txns", ".", "select", "{", "|", "t", "|", "t", ".", "amount", ".", "negative?", "}", "negative", ".", "empty?", "?", "0", ":", "negative", ".", "max_by", "(", ":id", ")", ".", "id", "end"], "docstring": "Calculate the maximum transaction ID visible currently in the wallet.\n We go through them all and find the largest number. If there are\n no transactions, zero is returned.", "docstring_tokens": ["Calculate", "the", "maximum", "transaction", "ID", "visible", "currently", "in", "the", "wallet", ".", "We", "go", "through", "them", "all", "and", "find", "the", "largest", "number", ".", "If", "there", "are", "no", "transactions", "zero", "is", "returned", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L250-L253", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/commands/propagate.rb", "func_name": "Zold.Propagate.propagate", "original_string": "def propagate(id, _)\n start = Time.now\n modified = []\n total = 0\n network = @wallets.acq(id, &:network)\n @wallets.acq(id, &:txns).select { |t| t.amount.negative? }.each do |t|\n total += 1\n if t.bnf == id\n @log.error(\"Paying itself in #{id}? #{t}\")\n next\n end\n @wallets.acq(t.bnf, exclusive: true) do |target|\n unless target.exists?\n @log.debug(\"#{t.amount * -1} from #{id} to #{t.bnf}: wallet is absent\")\n next\n end\n unless target.network == network\n @log.debug(\"#{t.amount * -1} to #{t.bnf}: network mismatch, '#{target.network}'!='#{network}'\")\n next\n end\n next if target.includes_positive?(t.id, id)\n unless target.prefix?(t.prefix)\n @log.debug(\"#{t.amount * -1} from #{id} to #{t.bnf}: wrong prefix \\\"#{t.prefix}\\\" in \\\"#{t}\\\"\")\n next\n end\n target.add(t.inverse(id))\n @log.info(\"#{t.amount * -1} arrived to #{t.bnf}: #{t.details}\")\n modified << t.bnf\n end\n end\n modified.uniq!\n @log.debug(\"Wallet #{id} propagated successfully, #{total} txns \\\nin #{Age.new(start, limit: 20 + total * 0.005)}, #{modified.count} wallets affected\")\n modified.each do |w|\n @wallets.acq(w, &:refurbish)\n end\n modified\n end", "language": "ruby", "code": "def propagate(id, _)\n start = Time.now\n modified = []\n total = 0\n network = @wallets.acq(id, &:network)\n @wallets.acq(id, &:txns).select { |t| t.amount.negative? }.each do |t|\n total += 1\n if t.bnf == id\n @log.error(\"Paying itself in #{id}? #{t}\")\n next\n end\n @wallets.acq(t.bnf, exclusive: true) do |target|\n unless target.exists?\n @log.debug(\"#{t.amount * -1} from #{id} to #{t.bnf}: wallet is absent\")\n next\n end\n unless target.network == network\n @log.debug(\"#{t.amount * -1} to #{t.bnf}: network mismatch, '#{target.network}'!='#{network}'\")\n next\n end\n next if target.includes_positive?(t.id, id)\n unless target.prefix?(t.prefix)\n @log.debug(\"#{t.amount * -1} from #{id} to #{t.bnf}: wrong prefix \\\"#{t.prefix}\\\" in \\\"#{t}\\\"\")\n next\n end\n target.add(t.inverse(id))\n @log.info(\"#{t.amount * -1} arrived to #{t.bnf}: #{t.details}\")\n modified << t.bnf\n end\n end\n modified.uniq!\n @log.debug(\"Wallet #{id} propagated successfully, #{total} txns \\\nin #{Age.new(start, limit: 20 + total * 0.005)}, #{modified.count} wallets affected\")\n modified.each do |w|\n @wallets.acq(w, &:refurbish)\n end\n modified\n end", "code_tokens": ["def", "propagate", "(", "id", ",", "_", ")", "start", "=", "Time", ".", "now", "modified", "=", "[", "]", "total", "=", "0", "network", "=", "@wallets", ".", "acq", "(", "id", ",", ":network", ")", "@wallets", ".", "acq", "(", "id", ",", ":txns", ")", ".", "select", "{", "|", "t", "|", "t", ".", "amount", ".", "negative?", "}", ".", "each", "do", "|", "t", "|", "total", "+=", "1", "if", "t", ".", "bnf", "==", "id", "@log", ".", "error", "(", "\"Paying itself in #{id}? #{t}\"", ")", "next", "end", "@wallets", ".", "acq", "(", "t", ".", "bnf", ",", "exclusive", ":", "true", ")", "do", "|", "target", "|", "unless", "target", ".", "exists?", "@log", ".", "debug", "(", "\"#{t.amount * -1} from #{id} to #{t.bnf}: wallet is absent\"", ")", "next", "end", "unless", "target", ".", "network", "==", "network", "@log", ".", "debug", "(", "\"#{t.amount * -1} to #{t.bnf}: network mismatch, '#{target.network}'!='#{network}'\"", ")", "next", "end", "next", "if", "target", ".", "includes_positive?", "(", "t", ".", "id", ",", "id", ")", "unless", "target", ".", "prefix?", "(", "t", ".", "prefix", ")", "@log", ".", "debug", "(", "\"#{t.amount * -1} from #{id} to #{t.bnf}: wrong prefix \\\"#{t.prefix}\\\" in \\\"#{t}\\\"\"", ")", "next", "end", "target", ".", "add", "(", "t", ".", "inverse", "(", "id", ")", ")", "@log", ".", "info", "(", "\"#{t.amount * -1} arrived to #{t.bnf}: #{t.details}\"", ")", "modified", "<<", "t", ".", "bnf", "end", "end", "modified", ".", "uniq!", "@log", ".", "debug", "(", "\"Wallet #{id} propagated successfully, #{total} txns \\\nin #{Age.new(start, limit: 20 + total * 0.005)}, #{modified.count} wallets affected\"", ")", "modified", ".", "each", "do", "|", "w", "|", "@wallets", ".", "acq", "(", "w", ",", ":refurbish", ")", "end", "modified", "end"], "docstring": "Returns list of Wallet IDs which were affected", "docstring_tokens": ["Returns", "list", "of", "Wallet", "IDs", "which", "were", "affected"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/commands/propagate.rb#L65-L102", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/commands/node.rb", "func_name": "Zold.Node.exec", "original_string": "def exec(cmd, nohup_log)\n start = Time.now\n Open3.popen2e({ 'MALLOC_ARENA_MAX' => '2' }, cmd) do |stdin, stdout, thr|\n nohup_log.print(\"Started process ##{thr.pid} from process ##{Process.pid}: #{cmd}\\n\")\n stdin.close\n until stdout.eof?\n begin\n line = stdout.gets\n rescue IOError => e\n line = Backtrace.new(e).to_s\n end\n nohup_log.print(line)\n end\n nohup_log.print(\"Nothing else left to read from ##{thr.pid}\\n\")\n code = thr.value.to_i\n nohup_log.print(\"Exit code of process ##{thr.pid} is #{code}, was alive for #{Age.new(start)}: #{cmd}\\n\")\n code\n end\n end", "language": "ruby", "code": "def exec(cmd, nohup_log)\n start = Time.now\n Open3.popen2e({ 'MALLOC_ARENA_MAX' => '2' }, cmd) do |stdin, stdout, thr|\n nohup_log.print(\"Started process ##{thr.pid} from process ##{Process.pid}: #{cmd}\\n\")\n stdin.close\n until stdout.eof?\n begin\n line = stdout.gets\n rescue IOError => e\n line = Backtrace.new(e).to_s\n end\n nohup_log.print(line)\n end\n nohup_log.print(\"Nothing else left to read from ##{thr.pid}\\n\")\n code = thr.value.to_i\n nohup_log.print(\"Exit code of process ##{thr.pid} is #{code}, was alive for #{Age.new(start)}: #{cmd}\\n\")\n code\n end\n end", "code_tokens": ["def", "exec", "(", "cmd", ",", "nohup_log", ")", "start", "=", "Time", ".", "now", "Open3", ".", "popen2e", "(", "{", "'MALLOC_ARENA_MAX'", "=>", "'2'", "}", ",", "cmd", ")", "do", "|", "stdin", ",", "stdout", ",", "thr", "|", "nohup_log", ".", "print", "(", "\"Started process ##{thr.pid} from process ##{Process.pid}: #{cmd}\\n\"", ")", "stdin", ".", "close", "until", "stdout", ".", "eof?", "begin", "line", "=", "stdout", ".", "gets", "rescue", "IOError", "=>", "e", "line", "=", "Backtrace", ".", "new", "(", "e", ")", ".", "to_s", "end", "nohup_log", ".", "print", "(", "line", ")", "end", "nohup_log", ".", "print", "(", "\"Nothing else left to read from ##{thr.pid}\\n\"", ")", "code", "=", "thr", ".", "value", ".", "to_i", "nohup_log", ".", "print", "(", "\"Exit code of process ##{thr.pid} is #{code}, was alive for #{Age.new(start)}: #{cmd}\\n\"", ")", "code", "end", "end"], "docstring": "Returns exit code", "docstring_tokens": ["Returns", "exit", "code"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/commands/node.rb#L374-L392", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/thread_pool.rb", "func_name": "Zold.ThreadPool.add", "original_string": "def add\n raise 'Block must be given to start()' unless block_given?\n latch = Concurrent::CountDownLatch.new(1)\n thread = Thread.start do\n Thread.current.name = @title\n VerboseThread.new(@log).run do\n latch.count_down\n yield\n end\n end\n latch.wait\n Thread.current.thread_variable_set(\n :kids,\n (Thread.current.thread_variable_get(:kids) || []) + [thread]\n )\n @threads << thread\n end", "language": "ruby", "code": "def add\n raise 'Block must be given to start()' unless block_given?\n latch = Concurrent::CountDownLatch.new(1)\n thread = Thread.start do\n Thread.current.name = @title\n VerboseThread.new(@log).run do\n latch.count_down\n yield\n end\n end\n latch.wait\n Thread.current.thread_variable_set(\n :kids,\n (Thread.current.thread_variable_get(:kids) || []) + [thread]\n )\n @threads << thread\n end", "code_tokens": ["def", "add", "raise", "'Block must be given to start()'", "unless", "block_given?", "latch", "=", "Concurrent", "::", "CountDownLatch", ".", "new", "(", "1", ")", "thread", "=", "Thread", ".", "start", "do", "Thread", ".", "current", ".", "name", "=", "@title", "VerboseThread", ".", "new", "(", "@log", ")", ".", "run", "do", "latch", ".", "count_down", "yield", "end", "end", "latch", ".", "wait", "Thread", ".", "current", ".", "thread_variable_set", "(", ":kids", ",", "(", "Thread", ".", "current", ".", "thread_variable_get", "(", ":kids", ")", "||", "[", "]", ")", "+", "[", "thread", "]", ")", "@threads", "<<", "thread", "end"], "docstring": "Add a new thread", "docstring_tokens": ["Add", "a", "new", "thread"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/thread_pool.rb#L42-L58", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/thread_pool.rb", "func_name": "Zold.ThreadPool.kill", "original_string": "def kill\n if @threads.empty?\n @log.debug(\"Thread pool \\\"#{@title}\\\" terminated with no threads\")\n return\n end\n @log.debug(\"Stopping \\\"#{@title}\\\" thread pool with #{@threads.count} threads: \\\n#{@threads.map { |t| \"#{t.name}/#{t.status}\" }.join(', ')}...\")\n start = Time.new\n begin\n join(0.1)\n ensure\n @threads.each do |t|\n (t.thread_variable_get(:kids) || []).each(&:kill)\n t.kill\n sleep(0.001) while t.alive? # I believe it's a bug in Ruby, this line fixes it\n Thread.current.thread_variable_set(\n :kids,\n (Thread.current.thread_variable_get(:kids) || []) - [t]\n )\n end\n @log.debug(\"Thread pool \\\"#{@title}\\\" terminated all threads in #{Age.new(start)}, \\\nit was alive for #{Age.new(@start)}: #{@threads.map { |t| \"#{t.name}/#{t.status}\" }.join(', ')}\")\n @threads.clear\n end\n end", "language": "ruby", "code": "def kill\n if @threads.empty?\n @log.debug(\"Thread pool \\\"#{@title}\\\" terminated with no threads\")\n return\n end\n @log.debug(\"Stopping \\\"#{@title}\\\" thread pool with #{@threads.count} threads: \\\n#{@threads.map { |t| \"#{t.name}/#{t.status}\" }.join(', ')}...\")\n start = Time.new\n begin\n join(0.1)\n ensure\n @threads.each do |t|\n (t.thread_variable_get(:kids) || []).each(&:kill)\n t.kill\n sleep(0.001) while t.alive? # I believe it's a bug in Ruby, this line fixes it\n Thread.current.thread_variable_set(\n :kids,\n (Thread.current.thread_variable_get(:kids) || []) - [t]\n )\n end\n @log.debug(\"Thread pool \\\"#{@title}\\\" terminated all threads in #{Age.new(start)}, \\\nit was alive for #{Age.new(@start)}: #{@threads.map { |t| \"#{t.name}/#{t.status}\" }.join(', ')}\")\n @threads.clear\n end\n end", "code_tokens": ["def", "kill", "if", "@threads", ".", "empty?", "@log", ".", "debug", "(", "\"Thread pool \\\"#{@title}\\\" terminated with no threads\"", ")", "return", "end", "@log", ".", "debug", "(", "\"Stopping \\\"#{@title}\\\" thread pool with #{@threads.count} threads: \\\n#{@threads.map { |t| \"#{t.name}/#{t.status}\" }.join(', ')}...\"", ")", "start", "=", "Time", ".", "new", "begin", "join", "(", "0.1", ")", "ensure", "@threads", ".", "each", "do", "|", "t", "|", "(", "t", ".", "thread_variable_get", "(", ":kids", ")", "||", "[", "]", ")", ".", "each", "(", ":kill", ")", "t", ".", "kill", "sleep", "(", "0.001", ")", "while", "t", ".", "alive?", "# I believe it's a bug in Ruby, this line fixes it", "Thread", ".", "current", ".", "thread_variable_set", "(", ":kids", ",", "(", "Thread", ".", "current", ".", "thread_variable_get", "(", ":kids", ")", "||", "[", "]", ")", "-", "[", "t", "]", ")", "end", "@log", ".", "debug", "(", "\"Thread pool \\\"#{@title}\\\" terminated all threads in #{Age.new(start)}, \\\nit was alive for #{Age.new(@start)}: #{@threads.map { |t| \"#{t.name}/#{t.status}\" }.join(', ')}\"", ")", "@threads", ".", "clear", "end", "end"], "docstring": "Kill them all immediately and close the pool", "docstring_tokens": ["Kill", "them", "all", "immediately", "and", "close", "the", "pool"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/thread_pool.rb#L65-L89", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/thread_pool.rb", "func_name": "Zold.ThreadPool.to_json", "original_string": "def to_json\n @threads.map do |t|\n {\n name: t.name,\n status: t.status,\n alive: t.alive?,\n vars: Hash[t.thread_variables.map { |v| [v.to_s, t.thread_variable_get(v)] }]\n }\n end\n end", "language": "ruby", "code": "def to_json\n @threads.map do |t|\n {\n name: t.name,\n status: t.status,\n alive: t.alive?,\n vars: Hash[t.thread_variables.map { |v| [v.to_s, t.thread_variable_get(v)] }]\n }\n end\n end", "code_tokens": ["def", "to_json", "@threads", ".", "map", "do", "|", "t", "|", "{", "name", ":", "t", ".", "name", ",", "status", ":", "t", ".", "status", ",", "alive", ":", "t", ".", "alive?", ",", "vars", ":", "Hash", "[", "t", ".", "thread_variables", ".", "map", "{", "|", "v", "|", "[", "v", ".", "to_s", ",", "t", ".", "thread_variable_get", "(", "v", ")", "]", "}", "]", "}", "end", "end"], "docstring": "As a hash map", "docstring_tokens": ["As", "a", "hash", "map"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/thread_pool.rb#L107-L116", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/thread_pool.rb", "func_name": "Zold.ThreadPool.to_s", "original_string": "def to_s\n @threads.map do |t|\n [\n \"#{t.name}: status=#{t.status}; alive=#{t.alive?}\",\n 'Vars: ' + t.thread_variables.map { |v| \"#{v}=\\\"#{t.thread_variable_get(v)}\\\"\" }.join('; '),\n t.backtrace.nil? ? 'NO BACKTRACE' : \" #{t.backtrace.join(\"\\n \")}\"\n ].join(\"\\n\")\n end\n end", "language": "ruby", "code": "def to_s\n @threads.map do |t|\n [\n \"#{t.name}: status=#{t.status}; alive=#{t.alive?}\",\n 'Vars: ' + t.thread_variables.map { |v| \"#{v}=\\\"#{t.thread_variable_get(v)}\\\"\" }.join('; '),\n t.backtrace.nil? ? 'NO BACKTRACE' : \" #{t.backtrace.join(\"\\n \")}\"\n ].join(\"\\n\")\n end\n end", "code_tokens": ["def", "to_s", "@threads", ".", "map", "do", "|", "t", "|", "[", "\"#{t.name}: status=#{t.status}; alive=#{t.alive?}\"", ",", "'Vars: '", "+", "t", ".", "thread_variables", ".", "map", "{", "|", "v", "|", "\"#{v}=\\\"#{t.thread_variable_get(v)}\\\"\"", "}", ".", "join", "(", "'; '", ")", ",", "t", ".", "backtrace", ".", "nil?", "?", "'NO BACKTRACE'", ":", "\" #{t.backtrace.join(\"\\n \")}\"", "]", ".", "join", "(", "\"\\n\"", ")", "end", "end"], "docstring": "As a text", "docstring_tokens": ["As", "a", "text"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/thread_pool.rb#L119-L127", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/patch.rb", "func_name": "Zold.Patch.legacy", "original_string": "def legacy(wallet, hours: 24)\n raise 'You can\\'t add legacy to a non-empty patch' unless @id.nil?\n wallet.txns.each do |txn|\n @txns << txn if txn.amount.negative? && txn.date < Time.now - hours * 60 * 60\n end\n end", "language": "ruby", "code": "def legacy(wallet, hours: 24)\n raise 'You can\\'t add legacy to a non-empty patch' unless @id.nil?\n wallet.txns.each do |txn|\n @txns << txn if txn.amount.negative? && txn.date < Time.now - hours * 60 * 60\n end\n end", "code_tokens": ["def", "legacy", "(", "wallet", ",", "hours", ":", "24", ")", "raise", "'You can\\'t add legacy to a non-empty patch'", "unless", "@id", ".", "nil?", "wallet", ".", "txns", ".", "each", "do", "|", "txn", "|", "@txns", "<<", "txn", "if", "txn", ".", "amount", ".", "negative?", "&&", "txn", ".", "date", "<", "Time", ".", "now", "-", "hours", "*", "60", "*", "60", "end", "end"], "docstring": "Add legacy transactions first, since they are negative and can't\n be deleted ever. This method is called by merge.rb in order to add\n legacy negative transactions to the patch before everything else. They\n are not supposed to be disputed, ever.", "docstring_tokens": ["Add", "legacy", "transactions", "first", "since", "they", "are", "negative", "and", "can", "t", "be", "deleted", "ever", ".", "This", "method", "is", "called", "by", "merge", ".", "rb", "in", "order", "to", "add", "legacy", "negative", "transactions", "to", "the", "patch", "before", "everything", "else", ".", "They", "are", "not", "supposed", "to", "be", "disputed", "ever", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/patch.rb#L51-L56", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/patch.rb", "func_name": "Zold.Patch.save", "original_string": "def save(file, overwrite: false, allow_negative_balance: false)\n raise 'You have to join at least one wallet in' if empty?\n before = ''\n wallet = Wallet.new(file)\n before = wallet.digest if wallet.exists?\n Tempfile.open([@id, Wallet::EXT]) do |f|\n temp = Wallet.new(f.path)\n temp.init(@id, @key, overwrite: overwrite, network: @network)\n File.open(f.path, 'a') do |t|\n @txns.each do |txn|\n next if Id::BANNED.include?(txn.bnf.to_s)\n t.print \"#{txn}\\n\"\n end\n end\n temp.refurbish\n if temp.balance.negative? && !temp.id.root? && !allow_negative_balance\n if wallet.exists?\n @log.info(\"The balance is negative, won't merge #{temp.mnemo} on top of #{wallet.mnemo}\")\n else\n @log.info(\"The balance is negative, won't save #{temp.mnemo}\")\n end\n else\n FileUtils.mkdir_p(File.dirname(file))\n IO.write(file, IO.read(f.path))\n end\n end\n before != wallet.digest\n end", "language": "ruby", "code": "def save(file, overwrite: false, allow_negative_balance: false)\n raise 'You have to join at least one wallet in' if empty?\n before = ''\n wallet = Wallet.new(file)\n before = wallet.digest if wallet.exists?\n Tempfile.open([@id, Wallet::EXT]) do |f|\n temp = Wallet.new(f.path)\n temp.init(@id, @key, overwrite: overwrite, network: @network)\n File.open(f.path, 'a') do |t|\n @txns.each do |txn|\n next if Id::BANNED.include?(txn.bnf.to_s)\n t.print \"#{txn}\\n\"\n end\n end\n temp.refurbish\n if temp.balance.negative? && !temp.id.root? && !allow_negative_balance\n if wallet.exists?\n @log.info(\"The balance is negative, won't merge #{temp.mnemo} on top of #{wallet.mnemo}\")\n else\n @log.info(\"The balance is negative, won't save #{temp.mnemo}\")\n end\n else\n FileUtils.mkdir_p(File.dirname(file))\n IO.write(file, IO.read(f.path))\n end\n end\n before != wallet.digest\n end", "code_tokens": ["def", "save", "(", "file", ",", "overwrite", ":", "false", ",", "allow_negative_balance", ":", "false", ")", "raise", "'You have to join at least one wallet in'", "if", "empty?", "before", "=", "''", "wallet", "=", "Wallet", ".", "new", "(", "file", ")", "before", "=", "wallet", ".", "digest", "if", "wallet", ".", "exists?", "Tempfile", ".", "open", "(", "[", "@id", ",", "Wallet", "::", "EXT", "]", ")", "do", "|", "f", "|", "temp", "=", "Wallet", ".", "new", "(", "f", ".", "path", ")", "temp", ".", "init", "(", "@id", ",", "@key", ",", "overwrite", ":", "overwrite", ",", "network", ":", "@network", ")", "File", ".", "open", "(", "f", ".", "path", ",", "'a'", ")", "do", "|", "t", "|", "@txns", ".", "each", "do", "|", "txn", "|", "next", "if", "Id", "::", "BANNED", ".", "include?", "(", "txn", ".", "bnf", ".", "to_s", ")", "t", ".", "print", "\"#{txn}\\n\"", "end", "end", "temp", ".", "refurbish", "if", "temp", ".", "balance", ".", "negative?", "&&", "!", "temp", ".", "id", ".", "root?", "&&", "!", "allow_negative_balance", "if", "wallet", ".", "exists?", "@log", ".", "info", "(", "\"The balance is negative, won't merge #{temp.mnemo} on top of #{wallet.mnemo}\"", ")", "else", "@log", ".", "info", "(", "\"The balance is negative, won't save #{temp.mnemo}\"", ")", "end", "else", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "file", ")", ")", "IO", ".", "write", "(", "file", ",", "IO", ".", "read", "(", "f", ".", "path", ")", ")", "end", "end", "before", "!=", "wallet", ".", "digest", "end"], "docstring": "Returns TRUE if the file was actually modified", "docstring_tokens": ["Returns", "TRUE", "if", "the", "file", "was", "actually", "modified"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/patch.rb#L186-L213", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/copies.rb", "func_name": "Zold.Copies.clean", "original_string": "def clean(max: 24 * 60 * 60)\n Futex.new(file, log: @log).open do\n list = load\n list.reject! do |s|\n if s[:time] >= Time.now - max\n false\n else\n @log.debug(\"Copy ##{s[:name]}/#{s[:host]}:#{s[:port]} is too old, over #{Age.new(s[:time])}\")\n true\n end\n end\n save(list)\n deleted = 0\n files.each do |f|\n next unless list.find { |s| s[:name] == File.basename(f, Copies::EXT) }.nil?\n file = File.join(@dir, f)\n size = File.size(file)\n File.delete(file)\n @log.debug(\"Copy at #{f} deleted: #{Size.new(size)}\")\n deleted += 1\n end\n list.select! do |s|\n cp = File.join(@dir, \"#{s[:name]}#{Copies::EXT}\")\n wallet = Wallet.new(cp)\n begin\n wallet.refurbish\n raise \"Invalid protocol #{wallet.protocol} in #{cp}\" unless wallet.protocol == Zold::PROTOCOL\n true\n rescue StandardError => e\n FileUtils.rm_rf(cp)\n @log.debug(\"Copy at #{cp} deleted: #{Backtrace.new(e)}\")\n deleted += 1\n false\n end\n end\n save(list)\n deleted\n end\n end", "language": "ruby", "code": "def clean(max: 24 * 60 * 60)\n Futex.new(file, log: @log).open do\n list = load\n list.reject! do |s|\n if s[:time] >= Time.now - max\n false\n else\n @log.debug(\"Copy ##{s[:name]}/#{s[:host]}:#{s[:port]} is too old, over #{Age.new(s[:time])}\")\n true\n end\n end\n save(list)\n deleted = 0\n files.each do |f|\n next unless list.find { |s| s[:name] == File.basename(f, Copies::EXT) }.nil?\n file = File.join(@dir, f)\n size = File.size(file)\n File.delete(file)\n @log.debug(\"Copy at #{f} deleted: #{Size.new(size)}\")\n deleted += 1\n end\n list.select! do |s|\n cp = File.join(@dir, \"#{s[:name]}#{Copies::EXT}\")\n wallet = Wallet.new(cp)\n begin\n wallet.refurbish\n raise \"Invalid protocol #{wallet.protocol} in #{cp}\" unless wallet.protocol == Zold::PROTOCOL\n true\n rescue StandardError => e\n FileUtils.rm_rf(cp)\n @log.debug(\"Copy at #{cp} deleted: #{Backtrace.new(e)}\")\n deleted += 1\n false\n end\n end\n save(list)\n deleted\n end\n end", "code_tokens": ["def", "clean", "(", "max", ":", "24", "*", "60", "*", "60", ")", "Futex", ".", "new", "(", "file", ",", "log", ":", "@log", ")", ".", "open", "do", "list", "=", "load", "list", ".", "reject!", "do", "|", "s", "|", "if", "s", "[", ":time", "]", ">=", "Time", ".", "now", "-", "max", "false", "else", "@log", ".", "debug", "(", "\"Copy ##{s[:name]}/#{s[:host]}:#{s[:port]} is too old, over #{Age.new(s[:time])}\"", ")", "true", "end", "end", "save", "(", "list", ")", "deleted", "=", "0", "files", ".", "each", "do", "|", "f", "|", "next", "unless", "list", ".", "find", "{", "|", "s", "|", "s", "[", ":name", "]", "==", "File", ".", "basename", "(", "f", ",", "Copies", "::", "EXT", ")", "}", ".", "nil?", "file", "=", "File", ".", "join", "(", "@dir", ",", "f", ")", "size", "=", "File", ".", "size", "(", "file", ")", "File", ".", "delete", "(", "file", ")", "@log", ".", "debug", "(", "\"Copy at #{f} deleted: #{Size.new(size)}\"", ")", "deleted", "+=", "1", "end", "list", ".", "select!", "do", "|", "s", "|", "cp", "=", "File", ".", "join", "(", "@dir", ",", "\"#{s[:name]}#{Copies::EXT}\"", ")", "wallet", "=", "Wallet", ".", "new", "(", "cp", ")", "begin", "wallet", ".", "refurbish", "raise", "\"Invalid protocol #{wallet.protocol} in #{cp}\"", "unless", "wallet", ".", "protocol", "==", "Zold", "::", "PROTOCOL", "true", "rescue", "StandardError", "=>", "e", "FileUtils", ".", "rm_rf", "(", "cp", ")", "@log", ".", "debug", "(", "\"Copy at #{cp} deleted: #{Backtrace.new(e)}\"", ")", "deleted", "+=", "1", "false", "end", "end", "save", "(", "list", ")", "deleted", "end", "end"], "docstring": "Delete all copies that are older than the \"max\" age provided, in seconds.", "docstring_tokens": ["Delete", "all", "copies", "that", "are", "older", "than", "the", "max", "age", "provided", "in", "seconds", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/copies.rb#L57-L95", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/copies.rb", "func_name": "Zold.Copies.add", "original_string": "def add(content, host, port, score, time: Time.now, master: false)\n raise \"Content can't be empty\" if content.empty?\n raise 'TCP port must be of type Integer' unless port.is_a?(Integer)\n raise \"TCP port can't be negative: #{port}\" if port.negative?\n raise 'Time must be of type Time' unless time.is_a?(Time)\n raise \"Time must be in the past: #{time}\" if time > Time.now\n raise 'Score must be Integer' unless score.is_a?(Integer)\n raise \"Score can't be negative: #{score}\" if score.negative?\n FileUtils.mkdir_p(@dir)\n Futex.new(file, log: @log).open do\n list = load\n target = list.find do |s|\n f = File.join(@dir, \"#{s[:name]}#{Copies::EXT}\")\n digest = OpenSSL::Digest::SHA256.new(content).hexdigest\n File.exist?(f) && OpenSSL::Digest::SHA256.file(f).hexdigest == digest\n end\n if target.nil?\n max = DirItems.new(@dir).fetch\n .select { |f| File.basename(f, Copies::EXT) =~ /^[0-9]+$/ }\n .map(&:to_i)\n .max\n max = 0 if max.nil?\n name = (max + 1).to_s\n IO.write(File.join(@dir, \"#{name}#{Copies::EXT}\"), content)\n else\n name = target[:name]\n end\n list.reject! { |s| s[:host] == host && s[:port] == port }\n list << {\n name: name,\n host: host,\n port: port,\n score: score,\n time: time,\n master: master\n }\n save(list)\n name\n end\n end", "language": "ruby", "code": "def add(content, host, port, score, time: Time.now, master: false)\n raise \"Content can't be empty\" if content.empty?\n raise 'TCP port must be of type Integer' unless port.is_a?(Integer)\n raise \"TCP port can't be negative: #{port}\" if port.negative?\n raise 'Time must be of type Time' unless time.is_a?(Time)\n raise \"Time must be in the past: #{time}\" if time > Time.now\n raise 'Score must be Integer' unless score.is_a?(Integer)\n raise \"Score can't be negative: #{score}\" if score.negative?\n FileUtils.mkdir_p(@dir)\n Futex.new(file, log: @log).open do\n list = load\n target = list.find do |s|\n f = File.join(@dir, \"#{s[:name]}#{Copies::EXT}\")\n digest = OpenSSL::Digest::SHA256.new(content).hexdigest\n File.exist?(f) && OpenSSL::Digest::SHA256.file(f).hexdigest == digest\n end\n if target.nil?\n max = DirItems.new(@dir).fetch\n .select { |f| File.basename(f, Copies::EXT) =~ /^[0-9]+$/ }\n .map(&:to_i)\n .max\n max = 0 if max.nil?\n name = (max + 1).to_s\n IO.write(File.join(@dir, \"#{name}#{Copies::EXT}\"), content)\n else\n name = target[:name]\n end\n list.reject! { |s| s[:host] == host && s[:port] == port }\n list << {\n name: name,\n host: host,\n port: port,\n score: score,\n time: time,\n master: master\n }\n save(list)\n name\n end\n end", "code_tokens": ["def", "add", "(", "content", ",", "host", ",", "port", ",", "score", ",", "time", ":", "Time", ".", "now", ",", "master", ":", "false", ")", "raise", "\"Content can't be empty\"", "if", "content", ".", "empty?", "raise", "'TCP port must be of type Integer'", "unless", "port", ".", "is_a?", "(", "Integer", ")", "raise", "\"TCP port can't be negative: #{port}\"", "if", "port", ".", "negative?", "raise", "'Time must be of type Time'", "unless", "time", ".", "is_a?", "(", "Time", ")", "raise", "\"Time must be in the past: #{time}\"", "if", "time", ">", "Time", ".", "now", "raise", "'Score must be Integer'", "unless", "score", ".", "is_a?", "(", "Integer", ")", "raise", "\"Score can't be negative: #{score}\"", "if", "score", ".", "negative?", "FileUtils", ".", "mkdir_p", "(", "@dir", ")", "Futex", ".", "new", "(", "file", ",", "log", ":", "@log", ")", ".", "open", "do", "list", "=", "load", "target", "=", "list", ".", "find", "do", "|", "s", "|", "f", "=", "File", ".", "join", "(", "@dir", ",", "\"#{s[:name]}#{Copies::EXT}\"", ")", "digest", "=", "OpenSSL", "::", "Digest", "::", "SHA256", ".", "new", "(", "content", ")", ".", "hexdigest", "File", ".", "exist?", "(", "f", ")", "&&", "OpenSSL", "::", "Digest", "::", "SHA256", ".", "file", "(", "f", ")", ".", "hexdigest", "==", "digest", "end", "if", "target", ".", "nil?", "max", "=", "DirItems", ".", "new", "(", "@dir", ")", ".", "fetch", ".", "select", "{", "|", "f", "|", "File", ".", "basename", "(", "f", ",", "Copies", "::", "EXT", ")", "=~", "/", "/", "}", ".", "map", "(", ":to_i", ")", ".", "max", "max", "=", "0", "if", "max", ".", "nil?", "name", "=", "(", "max", "+", "1", ")", ".", "to_s", "IO", ".", "write", "(", "File", ".", "join", "(", "@dir", ",", "\"#{name}#{Copies::EXT}\"", ")", ",", "content", ")", "else", "name", "=", "target", "[", ":name", "]", "end", "list", ".", "reject!", "{", "|", "s", "|", "s", "[", ":host", "]", "==", "host", "&&", "s", "[", ":port", "]", "==", "port", "}", "list", "<<", "{", "name", ":", "name", ",", "host", ":", "host", ",", "port", ":", "port", ",", "score", ":", "score", ",", "time", ":", "time", ",", "master", ":", "master", "}", "save", "(", "list", ")", "name", "end", "end"], "docstring": "Returns the name of the copy", "docstring_tokens": ["Returns", "the", "name", "of", "the", "copy"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/copies.rb#L104-L143", "partition": "valid"} {"repo": "zold-io/zold", "path": "lib/zold/remotes.rb", "func_name": "Zold.Remotes.iterate", "original_string": "def iterate(log, farm: Farm::Empty.new, threads: 1)\n raise 'Log can\\'t be nil' if log.nil?\n raise 'Farm can\\'t be nil' if farm.nil?\n Hands.exec(threads, all) do |r, idx|\n Thread.current.name = \"remotes-#{idx}@#{r[:host]}:#{r[:port]}\"\n start = Time.now\n best = farm.best[0]\n node = RemoteNode.new(\n host: r[:host],\n port: r[:port],\n score: best.nil? ? Score::ZERO : best,\n idx: idx,\n master: master?(r[:host], r[:port]),\n log: log,\n network: @network\n )\n begin\n yield node\n raise 'Took too long to execute' if (Time.now - start).round > @timeout\n unerror(r[:host], r[:port]) if node.touched\n rescue StandardError => e\n error(r[:host], r[:port])\n if e.is_a?(RemoteNode::CantAssert) || e.is_a?(Fetch::Error)\n log.debug(\"#{Rainbow(node).red}: \\\"#{e.message.strip}\\\" in #{Age.new(start)}\")\n else\n log.info(\"#{Rainbow(node).red}: \\\"#{e.message.strip}\\\" in #{Age.new(start)}\")\n log.debug(Backtrace.new(e).to_s)\n end\n remove(r[:host], r[:port]) if r[:errors] > TOLERANCE\n end\n end\n end", "language": "ruby", "code": "def iterate(log, farm: Farm::Empty.new, threads: 1)\n raise 'Log can\\'t be nil' if log.nil?\n raise 'Farm can\\'t be nil' if farm.nil?\n Hands.exec(threads, all) do |r, idx|\n Thread.current.name = \"remotes-#{idx}@#{r[:host]}:#{r[:port]}\"\n start = Time.now\n best = farm.best[0]\n node = RemoteNode.new(\n host: r[:host],\n port: r[:port],\n score: best.nil? ? Score::ZERO : best,\n idx: idx,\n master: master?(r[:host], r[:port]),\n log: log,\n network: @network\n )\n begin\n yield node\n raise 'Took too long to execute' if (Time.now - start).round > @timeout\n unerror(r[:host], r[:port]) if node.touched\n rescue StandardError => e\n error(r[:host], r[:port])\n if e.is_a?(RemoteNode::CantAssert) || e.is_a?(Fetch::Error)\n log.debug(\"#{Rainbow(node).red}: \\\"#{e.message.strip}\\\" in #{Age.new(start)}\")\n else\n log.info(\"#{Rainbow(node).red}: \\\"#{e.message.strip}\\\" in #{Age.new(start)}\")\n log.debug(Backtrace.new(e).to_s)\n end\n remove(r[:host], r[:port]) if r[:errors] > TOLERANCE\n end\n end\n end", "code_tokens": ["def", "iterate", "(", "log", ",", "farm", ":", "Farm", "::", "Empty", ".", "new", ",", "threads", ":", "1", ")", "raise", "'Log can\\'t be nil'", "if", "log", ".", "nil?", "raise", "'Farm can\\'t be nil'", "if", "farm", ".", "nil?", "Hands", ".", "exec", "(", "threads", ",", "all", ")", "do", "|", "r", ",", "idx", "|", "Thread", ".", "current", ".", "name", "=", "\"remotes-#{idx}@#{r[:host]}:#{r[:port]}\"", "start", "=", "Time", ".", "now", "best", "=", "farm", ".", "best", "[", "0", "]", "node", "=", "RemoteNode", ".", "new", "(", "host", ":", "r", "[", ":host", "]", ",", "port", ":", "r", "[", ":port", "]", ",", "score", ":", "best", ".", "nil?", "?", "Score", "::", "ZERO", ":", "best", ",", "idx", ":", "idx", ",", "master", ":", "master?", "(", "r", "[", ":host", "]", ",", "r", "[", ":port", "]", ")", ",", "log", ":", "log", ",", "network", ":", "@network", ")", "begin", "yield", "node", "raise", "'Took too long to execute'", "if", "(", "Time", ".", "now", "-", "start", ")", ".", "round", ">", "@timeout", "unerror", "(", "r", "[", ":host", "]", ",", "r", "[", ":port", "]", ")", "if", "node", ".", "touched", "rescue", "StandardError", "=>", "e", "error", "(", "r", "[", ":host", "]", ",", "r", "[", ":port", "]", ")", "if", "e", ".", "is_a?", "(", "RemoteNode", "::", "CantAssert", ")", "||", "e", ".", "is_a?", "(", "Fetch", "::", "Error", ")", "log", ".", "debug", "(", "\"#{Rainbow(node).red}: \\\"#{e.message.strip}\\\" in #{Age.new(start)}\"", ")", "else", "log", ".", "info", "(", "\"#{Rainbow(node).red}: \\\"#{e.message.strip}\\\" in #{Age.new(start)}\"", ")", "log", ".", "debug", "(", "Backtrace", ".", "new", "(", "e", ")", ".", "to_s", ")", "end", "remove", "(", "r", "[", ":host", "]", ",", "r", "[", ":port", "]", ")", "if", "r", "[", ":errors", "]", ">", "TOLERANCE", "end", "end", "end"], "docstring": "Go through the list of remotes and call a provided block for each\n of them. See how it's used, for example, in fetch.rb.", "docstring_tokens": ["Go", "through", "the", "list", "of", "remotes", "and", "call", "a", "provided", "block", "for", "each", "of", "them", ".", "See", "how", "it", "s", "used", "for", "example", "in", "fetch", ".", "rb", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/remotes.rb#L206-L237", "partition": "valid"} {"repo": "thredded/thredded", "path": "app/models/concerns/thredded/post_common.rb", "func_name": "Thredded.PostCommon.mark_as_unread", "original_string": "def mark_as_unread(user)\n if previous_post.nil?\n read_state = postable.user_read_states.find_by(user_id: user.id)\n read_state.destroy if read_state\n else\n postable.user_read_states.touch!(user.id, previous_post, overwrite_newer: true)\n end\n end", "language": "ruby", "code": "def mark_as_unread(user)\n if previous_post.nil?\n read_state = postable.user_read_states.find_by(user_id: user.id)\n read_state.destroy if read_state\n else\n postable.user_read_states.touch!(user.id, previous_post, overwrite_newer: true)\n end\n end", "code_tokens": ["def", "mark_as_unread", "(", "user", ")", "if", "previous_post", ".", "nil?", "read_state", "=", "postable", ".", "user_read_states", ".", "find_by", "(", "user_id", ":", "user", ".", "id", ")", "read_state", ".", "destroy", "if", "read_state", "else", "postable", ".", "user_read_states", ".", "touch!", "(", "user", ".", "id", ",", "previous_post", ",", "overwrite_newer", ":", "true", ")", "end", "end"], "docstring": "Marks all the posts from the given one as unread for the given user\n @param [Thredded.user_class] user", "docstring_tokens": ["Marks", "all", "the", "posts", "from", "the", "given", "one", "as", "unread", "for", "the", "given", "user"], "sha": "f1874fba333444255979c0789ba17f8dc24a4d6f", "url": "https://github.com/thredded/thredded/blob/f1874fba333444255979c0789ba17f8dc24a4d6f/app/models/concerns/thredded/post_common.rb#L67-L74", "partition": "valid"} {"repo": "thredded/thredded", "path": "app/mailers/thredded/base_mailer.rb", "func_name": "Thredded.BaseMailer.find_record", "original_string": "def find_record(klass, id_or_record)\n # Check by name because in development the Class might have been reloaded after id was initialized\n id_or_record.class.name == klass.name ? id_or_record : klass.find(id_or_record)\n end", "language": "ruby", "code": "def find_record(klass, id_or_record)\n # Check by name because in development the Class might have been reloaded after id was initialized\n id_or_record.class.name == klass.name ? id_or_record : klass.find(id_or_record)\n end", "code_tokens": ["def", "find_record", "(", "klass", ",", "id_or_record", ")", "# Check by name because in development the Class might have been reloaded after id was initialized", "id_or_record", ".", "class", ".", "name", "==", "klass", ".", "name", "?", "id_or_record", ":", "klass", ".", "find", "(", "id_or_record", ")", "end"], "docstring": "Find a record by ID, or return the passed record.\n @param [Class] klass\n @param [Integer, String, klass] id_or_record\n @return [klass]", "docstring_tokens": ["Find", "a", "record", "by", "ID", "or", "return", "the", "passed", "record", "."], "sha": "f1874fba333444255979c0789ba17f8dc24a4d6f", "url": "https://github.com/thredded/thredded/blob/f1874fba333444255979c0789ba17f8dc24a4d6f/app/mailers/thredded/base_mailer.rb#L13-L16", "partition": "valid"} {"repo": "thredded/thredded", "path": "app/models/concerns/thredded/content_moderation_state.rb", "func_name": "Thredded.ContentModerationState.moderation_state_visible_to_user?", "original_string": "def moderation_state_visible_to_user?(user)\n moderation_state_visible_to_all? ||\n (!user.thredded_anonymous? &&\n (user_id == user.id || user.thredded_can_moderate_messageboard?(messageboard)))\n end", "language": "ruby", "code": "def moderation_state_visible_to_user?(user)\n moderation_state_visible_to_all? ||\n (!user.thredded_anonymous? &&\n (user_id == user.id || user.thredded_can_moderate_messageboard?(messageboard)))\n end", "code_tokens": ["def", "moderation_state_visible_to_user?", "(", "user", ")", "moderation_state_visible_to_all?", "||", "(", "!", "user", ".", "thredded_anonymous?", "&&", "(", "user_id", "==", "user", ".", "id", "||", "user", ".", "thredded_can_moderate_messageboard?", "(", "messageboard", ")", ")", ")", "end"], "docstring": "Whether this is visible to the given user based on the moderation state.", "docstring_tokens": ["Whether", "this", "is", "visible", "to", "the", "given", "user", "based", "on", "the", "moderation", "state", "."], "sha": "f1874fba333444255979c0789ba17f8dc24a4d6f", "url": "https://github.com/thredded/thredded/blob/f1874fba333444255979c0789ba17f8dc24a4d6f/app/models/concerns/thredded/content_moderation_state.rb#L55-L59", "partition": "valid"} {"repo": "zdavatz/spreadsheet", "path": "lib/spreadsheet/worksheet.rb", "func_name": "Spreadsheet.Worksheet.protect!", "original_string": "def protect! password = ''\n @protected = true\n password = password.to_s\n if password.size == 0\n @password_hash = 0\n else\n @password_hash = Excel::Password.password_hash password\n end\n end", "language": "ruby", "code": "def protect! password = ''\n @protected = true\n password = password.to_s\n if password.size == 0\n @password_hash = 0\n else\n @password_hash = Excel::Password.password_hash password\n end\n end", "code_tokens": ["def", "protect!", "password", "=", "''", "@protected", "=", "true", "password", "=", "password", ".", "to_s", "if", "password", ".", "size", "==", "0", "@password_hash", "=", "0", "else", "@password_hash", "=", "Excel", "::", "Password", ".", "password_hash", "password", "end", "end"], "docstring": "Set worklist protection", "docstring_tokens": ["Set", "worklist", "protection"], "sha": "0ab10ae72d0c04027168154d938fa9355e478d58", "url": "https://github.com/zdavatz/spreadsheet/blob/0ab10ae72d0c04027168154d938fa9355e478d58/lib/spreadsheet/worksheet.rb#L130-L138", "partition": "valid"} {"repo": "zdavatz/spreadsheet", "path": "lib/spreadsheet/worksheet.rb", "func_name": "Spreadsheet.Worksheet.format_column", "original_string": "def format_column idx, format=nil, opts={}\n opts[:worksheet] = self\n res = case idx\n when Integer\n column = nil\n if format\n column = Column.new(idx, format, opts)\n end\n @columns[idx] = column\n else\n idx.collect do |col| format_column col, format, opts end\n end\n shorten @columns\n res\n end", "language": "ruby", "code": "def format_column idx, format=nil, opts={}\n opts[:worksheet] = self\n res = case idx\n when Integer\n column = nil\n if format\n column = Column.new(idx, format, opts)\n end\n @columns[idx] = column\n else\n idx.collect do |col| format_column col, format, opts end\n end\n shorten @columns\n res\n end", "code_tokens": ["def", "format_column", "idx", ",", "format", "=", "nil", ",", "opts", "=", "{", "}", "opts", "[", ":worksheet", "]", "=", "self", "res", "=", "case", "idx", "when", "Integer", "column", "=", "nil", "if", "format", "column", "=", "Column", ".", "new", "(", "idx", ",", "format", ",", "opts", ")", "end", "@columns", "[", "idx", "]", "=", "column", "else", "idx", ".", "collect", "do", "|", "col", "|", "format_column", "col", ",", "format", ",", "opts", "end", "end", "shorten", "@columns", "res", "end"], "docstring": "Sets the default Format of the column at _idx_.\n\n _idx_ may be an Integer, or an Enumerable that iterates over a number of\n Integers.\n\n _format_ is a Format, or nil if you want to remove the Formatting at _idx_\n\n Returns an instance of Column if _idx_ is an Integer, an Array of Columns\n otherwise.", "docstring_tokens": ["Sets", "the", "default", "Format", "of", "the", "column", "at", "_idx_", "."], "sha": "0ab10ae72d0c04027168154d938fa9355e478d58", "url": "https://github.com/zdavatz/spreadsheet/blob/0ab10ae72d0c04027168154d938fa9355e478d58/lib/spreadsheet/worksheet.rb#L178-L192", "partition": "valid"} {"repo": "zdavatz/spreadsheet", "path": "lib/spreadsheet/worksheet.rb", "func_name": "Spreadsheet.Worksheet.update_row", "original_string": "def update_row idx, *cells\n res = if row = @rows[idx]\n row[0, cells.size] = cells\n row\n else\n Row.new self, idx, cells\n end\n row_updated idx, res\n res\n end", "language": "ruby", "code": "def update_row idx, *cells\n res = if row = @rows[idx]\n row[0, cells.size] = cells\n row\n else\n Row.new self, idx, cells\n end\n row_updated idx, res\n res\n end", "code_tokens": ["def", "update_row", "idx", ",", "*", "cells", "res", "=", "if", "row", "=", "@rows", "[", "idx", "]", "row", "[", "0", ",", "cells", ".", "size", "]", "=", "cells", "row", "else", "Row", ".", "new", "self", ",", "idx", ",", "cells", "end", "row_updated", "idx", ",", "res", "res", "end"], "docstring": "Updates the Row at _idx_ with the following arguments.", "docstring_tokens": ["Updates", "the", "Row", "at", "_idx_", "with", "the", "following", "arguments", "."], "sha": "0ab10ae72d0c04027168154d938fa9355e478d58", "url": "https://github.com/zdavatz/spreadsheet/blob/0ab10ae72d0c04027168154d938fa9355e478d58/lib/spreadsheet/worksheet.rb#L280-L289", "partition": "valid"} {"repo": "zdavatz/spreadsheet", "path": "lib/spreadsheet/worksheet.rb", "func_name": "Spreadsheet.Worksheet.merge_cells", "original_string": "def merge_cells start_row, start_col, end_row, end_col\n # FIXME enlarge or dup check\n @merged_cells.push [start_row, end_row, start_col, end_col]\n end", "language": "ruby", "code": "def merge_cells start_row, start_col, end_row, end_col\n # FIXME enlarge or dup check\n @merged_cells.push [start_row, end_row, start_col, end_col]\n end", "code_tokens": ["def", "merge_cells", "start_row", ",", "start_col", ",", "end_row", ",", "end_col", "# FIXME enlarge or dup check", "@merged_cells", ".", "push", "[", "start_row", ",", "end_row", ",", "start_col", ",", "end_col", "]", "end"], "docstring": "Merges multiple cells into one.", "docstring_tokens": ["Merges", "multiple", "cells", "into", "one", "."], "sha": "0ab10ae72d0c04027168154d938fa9355e478d58", "url": "https://github.com/zdavatz/spreadsheet/blob/0ab10ae72d0c04027168154d938fa9355e478d58/lib/spreadsheet/worksheet.rb#L314-L317", "partition": "valid"} {"repo": "zdavatz/spreadsheet", "path": "lib/spreadsheet/row.rb", "func_name": "Spreadsheet.Row.formatted", "original_string": "def formatted\n copy = dup\n Helpers.rcompact(@formats)\n if copy.length < @formats.size\n copy.concat Array.new(@formats.size - copy.length)\n end\n copy\n end", "language": "ruby", "code": "def formatted\n copy = dup\n Helpers.rcompact(@formats)\n if copy.length < @formats.size\n copy.concat Array.new(@formats.size - copy.length)\n end\n copy\n end", "code_tokens": ["def", "formatted", "copy", "=", "dup", "Helpers", ".", "rcompact", "(", "@formats", ")", "if", "copy", ".", "length", "<", "@formats", ".", "size", "copy", ".", "concat", "Array", ".", "new", "(", "@formats", ".", "size", "-", "copy", ".", "length", ")", "end", "copy", "end"], "docstring": "Returns a copy of self with nil-values appended for empty cells that have\n an associated Format.\n This is primarily a helper-function for the writer classes.", "docstring_tokens": ["Returns", "a", "copy", "of", "self", "with", "nil", "-", "values", "appended", "for", "empty", "cells", "that", "have", "an", "associated", "Format", ".", "This", "is", "primarily", "a", "helper", "-", "function", "for", "the", "writer", "classes", "."], "sha": "0ab10ae72d0c04027168154d938fa9355e478d58", "url": "https://github.com/zdavatz/spreadsheet/blob/0ab10ae72d0c04027168154d938fa9355e478d58/lib/spreadsheet/row.rb#L97-L104", "partition": "valid"} {"repo": "zdavatz/spreadsheet", "path": "lib/spreadsheet/workbook.rb", "func_name": "Spreadsheet.Workbook.set_custom_color", "original_string": "def set_custom_color idx, red, green, blue\n raise 'Invalid format' if [red, green, blue].find { |c| ! (0..255).include?(c) }\n\n @palette[idx] = [red, green, blue]\n end", "language": "ruby", "code": "def set_custom_color idx, red, green, blue\n raise 'Invalid format' if [red, green, blue].find { |c| ! (0..255).include?(c) }\n\n @palette[idx] = [red, green, blue]\n end", "code_tokens": ["def", "set_custom_color", "idx", ",", "red", ",", "green", ",", "blue", "raise", "'Invalid format'", "if", "[", "red", ",", "green", ",", "blue", "]", ".", "find", "{", "|", "c", "|", "!", "(", "0", "..", "255", ")", ".", "include?", "(", "c", ")", "}", "@palette", "[", "idx", "]", "=", "[", "red", ",", "green", ",", "blue", "]", "end"], "docstring": "Change the RGB components of the elements in the colour palette.", "docstring_tokens": ["Change", "the", "RGB", "components", "of", "the", "elements", "in", "the", "colour", "palette", "."], "sha": "0ab10ae72d0c04027168154d938fa9355e478d58", "url": "https://github.com/zdavatz/spreadsheet/blob/0ab10ae72d0c04027168154d938fa9355e478d58/lib/spreadsheet/workbook.rb#L59-L63", "partition": "valid"} {"repo": "zdavatz/spreadsheet", "path": "lib/spreadsheet/workbook.rb", "func_name": "Spreadsheet.Workbook.format", "original_string": "def format idx\n case idx\n when Integer\n @formats[idx] || @default_format || Format.new\n when String\n @formats.find do |fmt| fmt.name == idx end\n end\n end", "language": "ruby", "code": "def format idx\n case idx\n when Integer\n @formats[idx] || @default_format || Format.new\n when String\n @formats.find do |fmt| fmt.name == idx end\n end\n end", "code_tokens": ["def", "format", "idx", "case", "idx", "when", "Integer", "@formats", "[", "idx", "]", "||", "@default_format", "||", "Format", ".", "new", "when", "String", "@formats", ".", "find", "do", "|", "fmt", "|", "fmt", ".", "name", "==", "idx", "end", "end", "end"], "docstring": "The Format at _idx_, or - if _idx_ is a String -\n the Format with name == _idx_", "docstring_tokens": ["The", "Format", "at", "_idx_", "or", "-", "if", "_idx_", "is", "a", "String", "-", "the", "Format", "with", "name", "==", "_idx_"], "sha": "0ab10ae72d0c04027168154d938fa9355e478d58", "url": "https://github.com/zdavatz/spreadsheet/blob/0ab10ae72d0c04027168154d938fa9355e478d58/lib/spreadsheet/workbook.rb#L89-L96", "partition": "valid"} {"repo": "zdavatz/spreadsheet", "path": "lib/spreadsheet/workbook.rb", "func_name": "Spreadsheet.Workbook.worksheet", "original_string": "def worksheet idx\n case idx\n when Integer\n @worksheets[idx]\n when String\n @worksheets.find do |sheet| sheet.name == idx end\n end\n end", "language": "ruby", "code": "def worksheet idx\n case idx\n when Integer\n @worksheets[idx]\n when String\n @worksheets.find do |sheet| sheet.name == idx end\n end\n end", "code_tokens": ["def", "worksheet", "idx", "case", "idx", "when", "Integer", "@worksheets", "[", "idx", "]", "when", "String", "@worksheets", ".", "find", "do", "|", "sheet", "|", "sheet", ".", "name", "==", "idx", "end", "end", "end"], "docstring": "The Worksheet at _idx_, or - if _idx_ is a String -\n the Worksheet with name == _idx_", "docstring_tokens": ["The", "Worksheet", "at", "_idx_", "or", "-", "if", "_idx_", "is", "a", "String", "-", "the", "Worksheet", "with", "name", "==", "_idx_"], "sha": "0ab10ae72d0c04027168154d938fa9355e478d58", "url": "https://github.com/zdavatz/spreadsheet/blob/0ab10ae72d0c04027168154d938fa9355e478d58/lib/spreadsheet/workbook.rb#L114-L121", "partition": "valid"} {"repo": "zdavatz/spreadsheet", "path": "lib/spreadsheet/workbook.rb", "func_name": "Spreadsheet.Workbook.write", "original_string": "def write io_path_or_writer\n if io_path_or_writer.is_a? Writer\n io_path_or_writer.write self\n else\n writer(io_path_or_writer).write(self)\n end\n end", "language": "ruby", "code": "def write io_path_or_writer\n if io_path_or_writer.is_a? Writer\n io_path_or_writer.write self\n else\n writer(io_path_or_writer).write(self)\n end\n end", "code_tokens": ["def", "write", "io_path_or_writer", "if", "io_path_or_writer", ".", "is_a?", "Writer", "io_path_or_writer", ".", "write", "self", "else", "writer", "(", "io_path_or_writer", ")", ".", "write", "(", "self", ")", "end", "end"], "docstring": "Write this Workbook to a File, IO Stream or Writer Object. The latter will\n make more sense once there are more than just an Excel-Writer available.", "docstring_tokens": ["Write", "this", "Workbook", "to", "a", "File", "IO", "Stream", "or", "Writer", "Object", ".", "The", "latter", "will", "make", "more", "sense", "once", "there", "are", "more", "than", "just", "an", "Excel", "-", "Writer", "available", "."], "sha": "0ab10ae72d0c04027168154d938fa9355e478d58", "url": "https://github.com/zdavatz/spreadsheet/blob/0ab10ae72d0c04027168154d938fa9355e478d58/lib/spreadsheet/workbook.rb#L125-L131", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/sideloading.rb", "func_name": "ZendeskAPI.Sideloading._side_load", "original_string": "def _side_load(name, klass, resources)\n associations = klass.associated_with(name)\n\n associations.each do |association|\n association.side_load(resources, @included[name])\n end\n\n resources.each do |resource|\n loaded_associations = resource.loaded_associations\n loaded_associations.each do |association|\n loaded = resource.send(association[:name])\n next unless loaded\n _side_load(name, association[:class], to_array(loaded))\n end\n end\n end", "language": "ruby", "code": "def _side_load(name, klass, resources)\n associations = klass.associated_with(name)\n\n associations.each do |association|\n association.side_load(resources, @included[name])\n end\n\n resources.each do |resource|\n loaded_associations = resource.loaded_associations\n loaded_associations.each do |association|\n loaded = resource.send(association[:name])\n next unless loaded\n _side_load(name, association[:class], to_array(loaded))\n end\n end\n end", "code_tokens": ["def", "_side_load", "(", "name", ",", "klass", ",", "resources", ")", "associations", "=", "klass", ".", "associated_with", "(", "name", ")", "associations", ".", "each", "do", "|", "association", "|", "association", ".", "side_load", "(", "resources", ",", "@included", "[", "name", "]", ")", "end", "resources", ".", "each", "do", "|", "resource", "|", "loaded_associations", "=", "resource", ".", "loaded_associations", "loaded_associations", ".", "each", "do", "|", "association", "|", "loaded", "=", "resource", ".", "send", "(", "association", "[", ":name", "]", ")", "next", "unless", "loaded", "_side_load", "(", "name", ",", "association", "[", ":class", "]", ",", "to_array", "(", "loaded", ")", ")", "end", "end", "end"], "docstring": "Traverses the resource looking for associations\n then descends into those associations and checks for applicable\n resources to side load", "docstring_tokens": ["Traverses", "the", "resource", "looking", "for", "associations", "then", "descends", "into", "those", "associations", "and", "checks", "for", "applicable", "resources", "to", "side", "load"], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/sideloading.rb#L33-L48", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/collection.rb", "func_name": "ZendeskAPI.Collection.<<", "original_string": "def <<(item)\n fetch\n\n if item.is_a?(Resource)\n if item.is_a?(@resource_class)\n @resources << item\n else\n raise \"this collection is for #{@resource_class}\"\n end\n else\n @resources << wrap_resource(item, true)\n end\n end", "language": "ruby", "code": "def <<(item)\n fetch\n\n if item.is_a?(Resource)\n if item.is_a?(@resource_class)\n @resources << item\n else\n raise \"this collection is for #{@resource_class}\"\n end\n else\n @resources << wrap_resource(item, true)\n end\n end", "code_tokens": ["def", "<<", "(", "item", ")", "fetch", "if", "item", ".", "is_a?", "(", "Resource", ")", "if", "item", ".", "is_a?", "(", "@resource_class", ")", "@resources", "<<", "item", "else", "raise", "\"this collection is for #{@resource_class}\"", "end", "else", "@resources", "<<", "wrap_resource", "(", "item", ",", "true", ")", "end", "end"], "docstring": "Adds an item to this collection\n @option item [ZendeskAPI::Data] the resource to add\n @raise [ArgumentError] if the resource doesn't belong in this collection", "docstring_tokens": ["Adds", "an", "item", "to", "this", "collection"], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/collection.rb#L161-L173", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/collection.rb", "func_name": "ZendeskAPI.Collection.fetch!", "original_string": "def fetch!(reload = false)\n if @resources && (!@fetchable || !reload)\n return @resources\n elsif association && association.options.parent && association.options.parent.new_record?\n return (@resources = [])\n end\n\n @response = get_response(@query || path)\n handle_response(@response.body)\n\n @resources\n end", "language": "ruby", "code": "def fetch!(reload = false)\n if @resources && (!@fetchable || !reload)\n return @resources\n elsif association && association.options.parent && association.options.parent.new_record?\n return (@resources = [])\n end\n\n @response = get_response(@query || path)\n handle_response(@response.body)\n\n @resources\n end", "code_tokens": ["def", "fetch!", "(", "reload", "=", "false", ")", "if", "@resources", "&&", "(", "!", "@fetchable", "||", "!", "reload", ")", "return", "@resources", "elsif", "association", "&&", "association", ".", "options", ".", "parent", "&&", "association", ".", "options", ".", "parent", ".", "new_record?", "return", "(", "@resources", "=", "[", "]", ")", "end", "@response", "=", "get_response", "(", "@query", "||", "path", ")", "handle_response", "(", "@response", ".", "body", ")", "@resources", "end"], "docstring": "Executes actual GET from API and loads resources into proper class.\n @param [Boolean] reload Whether to disregard cache", "docstring_tokens": ["Executes", "actual", "GET", "from", "API", "and", "loads", "resources", "into", "proper", "class", "."], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/collection.rb#L182-L193", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/collection.rb", "func_name": "ZendeskAPI.Collection.method_missing", "original_string": "def method_missing(name, *args, &block)\n if resource_methods.include?(name)\n collection_method(name, *args, &block)\n elsif [].respond_to?(name, false)\n array_method(name, *args, &block)\n else\n next_collection(name, *args, &block)\n end\n end", "language": "ruby", "code": "def method_missing(name, *args, &block)\n if resource_methods.include?(name)\n collection_method(name, *args, &block)\n elsif [].respond_to?(name, false)\n array_method(name, *args, &block)\n else\n next_collection(name, *args, &block)\n end\n end", "code_tokens": ["def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "if", "resource_methods", ".", "include?", "(", "name", ")", "collection_method", "(", "name", ",", "args", ",", "block", ")", "elsif", "[", "]", ".", "respond_to?", "(", "name", ",", "false", ")", "array_method", "(", "name", ",", "args", ",", "block", ")", "else", "next_collection", "(", "name", ",", "args", ",", "block", ")", "end", "end"], "docstring": "Sends methods to underlying array of resources.", "docstring_tokens": ["Sends", "methods", "to", "underlying", "array", "of", "resources", "."], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/collection.rb#L294-L302", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/association.rb", "func_name": "ZendeskAPI.Association.side_load", "original_string": "def side_load(resources, side_loads)\n key = \"#{options.name}_id\"\n plural_key = \"#{Inflection.singular options.name.to_s}_ids\"\n\n resources.each do |resource|\n if resource.key?(plural_key) # Grab associations from child_ids field on resource\n side_load_from_child_ids(resource, side_loads, plural_key)\n elsif resource.key?(key) || options.singular\n side_load_from_child_or_parent_id(resource, side_loads, key)\n else # Grab associations from parent_id field from multiple child resources\n side_load_from_parent_id(resource, side_loads, key)\n end\n end\n end", "language": "ruby", "code": "def side_load(resources, side_loads)\n key = \"#{options.name}_id\"\n plural_key = \"#{Inflection.singular options.name.to_s}_ids\"\n\n resources.each do |resource|\n if resource.key?(plural_key) # Grab associations from child_ids field on resource\n side_load_from_child_ids(resource, side_loads, plural_key)\n elsif resource.key?(key) || options.singular\n side_load_from_child_or_parent_id(resource, side_loads, key)\n else # Grab associations from parent_id field from multiple child resources\n side_load_from_parent_id(resource, side_loads, key)\n end\n end\n end", "code_tokens": ["def", "side_load", "(", "resources", ",", "side_loads", ")", "key", "=", "\"#{options.name}_id\"", "plural_key", "=", "\"#{Inflection.singular options.name.to_s}_ids\"", "resources", ".", "each", "do", "|", "resource", "|", "if", "resource", ".", "key?", "(", "plural_key", ")", "# Grab associations from child_ids field on resource", "side_load_from_child_ids", "(", "resource", ",", "side_loads", ",", "plural_key", ")", "elsif", "resource", ".", "key?", "(", "key", ")", "||", "options", ".", "singular", "side_load_from_child_or_parent_id", "(", "resource", ",", "side_loads", ",", "key", ")", "else", "# Grab associations from parent_id field from multiple child resources", "side_load_from_parent_id", "(", "resource", ",", "side_loads", ",", "key", ")", "end", "end", "end"], "docstring": "Tries to place side loads onto given resources.", "docstring_tokens": ["Tries", "to", "place", "side", "loads", "onto", "given", "resources", "."], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/association.rb#L83-L96", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/actions.rb", "func_name": "ZendeskAPI.Save.save", "original_string": "def save(options = {}, &block)\n save!(options, &block)\n rescue ZendeskAPI::Error::RecordInvalid => e\n @errors = e.errors\n false\n rescue ZendeskAPI::Error::ClientError\n false\n end", "language": "ruby", "code": "def save(options = {}, &block)\n save!(options, &block)\n rescue ZendeskAPI::Error::RecordInvalid => e\n @errors = e.errors\n false\n rescue ZendeskAPI::Error::ClientError\n false\n end", "code_tokens": ["def", "save", "(", "options", "=", "{", "}", ",", "&", "block", ")", "save!", "(", "options", ",", "block", ")", "rescue", "ZendeskAPI", "::", "Error", "::", "RecordInvalid", "=>", "e", "@errors", "=", "e", ".", "errors", "false", "rescue", "ZendeskAPI", "::", "Error", "::", "ClientError", "false", "end"], "docstring": "Saves, returning false if it fails and attaching the errors", "docstring_tokens": ["Saves", "returning", "false", "if", "it", "fails", "and", "attaching", "the", "errors"], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/actions.rb#L46-L53", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/actions.rb", "func_name": "ZendeskAPI.Save.save_associations", "original_string": "def save_associations\n self.class.associations.each do |association_data|\n association_name = association_data[:name]\n\n next unless send(\"#{association_name}_used?\") && association = send(association_name)\n\n inline_creation = association_data[:inline] == :create && new_record?\n changed = association.is_a?(Collection) || association.changed?\n\n if association.respond_to?(:save) && changed && !inline_creation && association.save\n send(\"#{association_name}=\", association) # set id/ids columns\n end\n\n if (association_data[:inline] == true || inline_creation) && changed\n attributes[association_name] = association.to_param\n end\n end\n end", "language": "ruby", "code": "def save_associations\n self.class.associations.each do |association_data|\n association_name = association_data[:name]\n\n next unless send(\"#{association_name}_used?\") && association = send(association_name)\n\n inline_creation = association_data[:inline] == :create && new_record?\n changed = association.is_a?(Collection) || association.changed?\n\n if association.respond_to?(:save) && changed && !inline_creation && association.save\n send(\"#{association_name}=\", association) # set id/ids columns\n end\n\n if (association_data[:inline] == true || inline_creation) && changed\n attributes[association_name] = association.to_param\n end\n end\n end", "code_tokens": ["def", "save_associations", "self", ".", "class", ".", "associations", ".", "each", "do", "|", "association_data", "|", "association_name", "=", "association_data", "[", ":name", "]", "next", "unless", "send", "(", "\"#{association_name}_used?\"", ")", "&&", "association", "=", "send", "(", "association_name", ")", "inline_creation", "=", "association_data", "[", ":inline", "]", "==", ":create", "&&", "new_record?", "changed", "=", "association", ".", "is_a?", "(", "Collection", ")", "||", "association", ".", "changed?", "if", "association", ".", "respond_to?", "(", ":save", ")", "&&", "changed", "&&", "!", "inline_creation", "&&", "association", ".", "save", "send", "(", "\"#{association_name}=\"", ",", "association", ")", "# set id/ids columns", "end", "if", "(", "association_data", "[", ":inline", "]", "==", "true", "||", "inline_creation", ")", "&&", "changed", "attributes", "[", "association_name", "]", "=", "association", ".", "to_param", "end", "end", "end"], "docstring": "Saves associations\n Takes into account inlining, collections, and id setting on the parent resource.", "docstring_tokens": ["Saves", "associations", "Takes", "into", "account", "inlining", "collections", "and", "id", "setting", "on", "the", "parent", "resource", "."], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/actions.rb#L65-L82", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/actions.rb", "func_name": "ZendeskAPI.Read.reload!", "original_string": "def reload!\n response = @client.connection.get(path) do |req|\n yield req if block_given?\n end\n\n handle_response(response)\n attributes.clear_changes\n self\n end", "language": "ruby", "code": "def reload!\n response = @client.connection.get(path) do |req|\n yield req if block_given?\n end\n\n handle_response(response)\n attributes.clear_changes\n self\n end", "code_tokens": ["def", "reload!", "response", "=", "@client", ".", "connection", ".", "get", "(", "path", ")", "do", "|", "req", "|", "yield", "req", "if", "block_given?", "end", "handle_response", "(", "response", ")", "attributes", ".", "clear_changes", "self", "end"], "docstring": "Reloads a resource.", "docstring_tokens": ["Reloads", "a", "resource", "."], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/actions.rb#L94-L102", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/actions.rb", "func_name": "ZendeskAPI.CreateMany.create_many!", "original_string": "def create_many!(client, attributes_array, association = Association.new(:class => self))\n response = client.connection.post(\"#{association.generate_path}/create_many\") do |req|\n req.body = { resource_name => attributes_array }\n\n yield req if block_given?\n end\n\n JobStatus.new_from_response(client, response)\n end", "language": "ruby", "code": "def create_many!(client, attributes_array, association = Association.new(:class => self))\n response = client.connection.post(\"#{association.generate_path}/create_many\") do |req|\n req.body = { resource_name => attributes_array }\n\n yield req if block_given?\n end\n\n JobStatus.new_from_response(client, response)\n end", "code_tokens": ["def", "create_many!", "(", "client", ",", "attributes_array", ",", "association", "=", "Association", ".", "new", "(", ":class", "=>", "self", ")", ")", "response", "=", "client", ".", "connection", ".", "post", "(", "\"#{association.generate_path}/create_many\"", ")", "do", "|", "req", "|", "req", ".", "body", "=", "{", "resource_name", "=>", "attributes_array", "}", "yield", "req", "if", "block_given?", "end", "JobStatus", ".", "new_from_response", "(", "client", ",", "response", ")", "end"], "docstring": "Creates multiple resources using the create_many endpoint.\n @param [Client] client The {Client} object to be used\n @param [Array] attributes_array An array of resources to be created.\n @return [JobStatus] the {JobStatus} instance for this create job", "docstring_tokens": ["Creates", "multiple", "resources", "using", "the", "create_many", "endpoint", "."], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/actions.rb#L173-L181", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/actions.rb", "func_name": "ZendeskAPI.CreateOrUpdate.create_or_update!", "original_string": "def create_or_update!(client, attributes, association = Association.new(:class => self))\n response = client.connection.post(\"#{association.generate_path}/create_or_update\") do |req|\n req.body = { resource_name => attributes }\n\n yield req if block_given?\n end\n\n new_from_response(client, response, Array(association.options[:include]))\n end", "language": "ruby", "code": "def create_or_update!(client, attributes, association = Association.new(:class => self))\n response = client.connection.post(\"#{association.generate_path}/create_or_update\") do |req|\n req.body = { resource_name => attributes }\n\n yield req if block_given?\n end\n\n new_from_response(client, response, Array(association.options[:include]))\n end", "code_tokens": ["def", "create_or_update!", "(", "client", ",", "attributes", ",", "association", "=", "Association", ".", "new", "(", ":class", "=>", "self", ")", ")", "response", "=", "client", ".", "connection", ".", "post", "(", "\"#{association.generate_path}/create_or_update\"", ")", "do", "|", "req", "|", "req", ".", "body", "=", "{", "resource_name", "=>", "attributes", "}", "yield", "req", "if", "block_given?", "end", "new_from_response", "(", "client", ",", "response", ",", "Array", "(", "association", ".", "options", "[", ":include", "]", ")", ")", "end"], "docstring": "Creates or updates resource using the create_or_update endpoint.\n @param [Client] client The {Client} object to be used\n @param [Hash] attributes The attributes to create.", "docstring_tokens": ["Creates", "or", "updates", "resource", "using", "the", "create_or_update", "endpoint", "."], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/actions.rb#L188-L196", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/actions.rb", "func_name": "ZendeskAPI.CreateOrUpdateMany.create_or_update_many!", "original_string": "def create_or_update_many!(client, attributes)\n association = Association.new(:class => self)\n\n response = client.connection.post(\"#{association.generate_path}/create_or_update_many\") do |req|\n req.body = { resource_name => attributes }\n\n yield req if block_given?\n end\n\n JobStatus.new_from_response(client, response)\n end", "language": "ruby", "code": "def create_or_update_many!(client, attributes)\n association = Association.new(:class => self)\n\n response = client.connection.post(\"#{association.generate_path}/create_or_update_many\") do |req|\n req.body = { resource_name => attributes }\n\n yield req if block_given?\n end\n\n JobStatus.new_from_response(client, response)\n end", "code_tokens": ["def", "create_or_update_many!", "(", "client", ",", "attributes", ")", "association", "=", "Association", ".", "new", "(", ":class", "=>", "self", ")", "response", "=", "client", ".", "connection", ".", "post", "(", "\"#{association.generate_path}/create_or_update_many\"", ")", "do", "|", "req", "|", "req", ".", "body", "=", "{", "resource_name", "=>", "attributes", "}", "yield", "req", "if", "block_given?", "end", "JobStatus", ".", "new_from_response", "(", "client", ",", "response", ")", "end"], "docstring": "Creates or updates multiple resources using the create_or_update_many endpoint.\n\n @param [Client] client The {Client} object to be used\n @param [Array] attributes The attributes to update resources with\n\n @return [JobStatus] the {JobStatus} instance for this destroy job", "docstring_tokens": ["Creates", "or", "updates", "multiple", "resources", "using", "the", "create_or_update_many", "endpoint", "."], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/actions.rb#L206-L216", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/actions.rb", "func_name": "ZendeskAPI.Destroy.destroy!", "original_string": "def destroy!\n return false if destroyed? || new_record?\n\n @client.connection.delete(url || path) do |req|\n yield req if block_given?\n end\n\n @destroyed = true\n end", "language": "ruby", "code": "def destroy!\n return false if destroyed? || new_record?\n\n @client.connection.delete(url || path) do |req|\n yield req if block_given?\n end\n\n @destroyed = true\n end", "code_tokens": ["def", "destroy!", "return", "false", "if", "destroyed?", "||", "new_record?", "@client", ".", "connection", ".", "delete", "(", "url", "||", "path", ")", "do", "|", "req", "|", "yield", "req", "if", "block_given?", "end", "@destroyed", "=", "true", "end"], "docstring": "If this resource hasn't already been deleted, then do so.\n @return [Boolean] Successful?", "docstring_tokens": ["If", "this", "resource", "hasn", "t", "already", "been", "deleted", "then", "do", "so", "."], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/actions.rb#L231-L239", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/actions.rb", "func_name": "ZendeskAPI.DestroyMany.destroy_many!", "original_string": "def destroy_many!(client, ids, association = Association.new(:class => self))\n response = client.connection.delete(\"#{association.generate_path}/destroy_many\") do |req|\n req.params = { :ids => ids.join(',') }\n\n yield req if block_given?\n end\n\n JobStatus.new_from_response(client, response)\n end", "language": "ruby", "code": "def destroy_many!(client, ids, association = Association.new(:class => self))\n response = client.connection.delete(\"#{association.generate_path}/destroy_many\") do |req|\n req.params = { :ids => ids.join(',') }\n\n yield req if block_given?\n end\n\n JobStatus.new_from_response(client, response)\n end", "code_tokens": ["def", "destroy_many!", "(", "client", ",", "ids", ",", "association", "=", "Association", ".", "new", "(", ":class", "=>", "self", ")", ")", "response", "=", "client", ".", "connection", ".", "delete", "(", "\"#{association.generate_path}/destroy_many\"", ")", "do", "|", "req", "|", "req", ".", "params", "=", "{", ":ids", "=>", "ids", ".", "join", "(", "','", ")", "}", "yield", "req", "if", "block_given?", "end", "JobStatus", ".", "new_from_response", "(", "client", ",", "response", ")", "end"], "docstring": "Destroys multiple resources using the destroy_many endpoint.\n @param [Client] client The {Client} object to be used\n @param [Array] ids An array of ids to destroy\n @return [JobStatus] the {JobStatus} instance for this destroy job", "docstring_tokens": ["Destroys", "multiple", "resources", "using", "the", "destroy_many", "endpoint", "."], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/actions.rb#L272-L280", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/actions.rb", "func_name": "ZendeskAPI.UpdateMany.update_many!", "original_string": "def update_many!(client, ids_or_attributes, attributes = {})\n association = attributes.delete(:association) || Association.new(:class => self)\n\n response = client.connection.put(\"#{association.generate_path}/update_many\") do |req|\n if attributes == {}\n req.body = { resource_name => ids_or_attributes }\n else\n req.params = { :ids => ids_or_attributes.join(',') }\n req.body = { singular_resource_name => attributes }\n end\n\n yield req if block_given?\n end\n\n JobStatus.new_from_response(client, response)\n end", "language": "ruby", "code": "def update_many!(client, ids_or_attributes, attributes = {})\n association = attributes.delete(:association) || Association.new(:class => self)\n\n response = client.connection.put(\"#{association.generate_path}/update_many\") do |req|\n if attributes == {}\n req.body = { resource_name => ids_or_attributes }\n else\n req.params = { :ids => ids_or_attributes.join(',') }\n req.body = { singular_resource_name => attributes }\n end\n\n yield req if block_given?\n end\n\n JobStatus.new_from_response(client, response)\n end", "code_tokens": ["def", "update_many!", "(", "client", ",", "ids_or_attributes", ",", "attributes", "=", "{", "}", ")", "association", "=", "attributes", ".", "delete", "(", ":association", ")", "||", "Association", ".", "new", "(", ":class", "=>", "self", ")", "response", "=", "client", ".", "connection", ".", "put", "(", "\"#{association.generate_path}/update_many\"", ")", "do", "|", "req", "|", "if", "attributes", "==", "{", "}", "req", ".", "body", "=", "{", "resource_name", "=>", "ids_or_attributes", "}", "else", "req", ".", "params", "=", "{", ":ids", "=>", "ids_or_attributes", ".", "join", "(", "','", ")", "}", "req", ".", "body", "=", "{", "singular_resource_name", "=>", "attributes", "}", "end", "yield", "req", "if", "block_given?", "end", "JobStatus", ".", "new_from_response", "(", "client", ",", "response", ")", "end"], "docstring": "Updates multiple resources using the update_many endpoint.\n @param [Client] client The {Client} object to be used\n @param [Array] ids_or_attributes An array of ids or arributes including ids to update\n @param [Hash] attributes The attributes to update resources with\n @return [JobStatus] the {JobStatus} instance for this destroy job", "docstring_tokens": ["Updates", "multiple", "resources", "using", "the", "update_many", "endpoint", "."], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/actions.rb#L317-L332", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/resources.rb", "func_name": "ZendeskAPI.Macro.apply!", "original_string": "def apply!(ticket = nil)\n path = \"#{self.path}/apply\"\n\n if ticket\n path = \"#{ticket.path}/#{path}\"\n end\n\n response = @client.connection.get(path)\n SilentMash.new(response.body.fetch(\"result\", {}))\n end", "language": "ruby", "code": "def apply!(ticket = nil)\n path = \"#{self.path}/apply\"\n\n if ticket\n path = \"#{ticket.path}/#{path}\"\n end\n\n response = @client.connection.get(path)\n SilentMash.new(response.body.fetch(\"result\", {}))\n end", "code_tokens": ["def", "apply!", "(", "ticket", "=", "nil", ")", "path", "=", "\"#{self.path}/apply\"", "if", "ticket", "path", "=", "\"#{ticket.path}/#{path}\"", "end", "response", "=", "@client", ".", "connection", ".", "get", "(", "path", ")", "SilentMash", ".", "new", "(", "response", ".", "body", ".", "fetch", "(", "\"result\"", ",", "{", "}", ")", ")", "end"], "docstring": "Returns the update to a ticket that happens when a macro will be applied.\n @param [Ticket] ticket Optional {Ticket} to apply this macro to.\n @raise [Faraday::Error::ClientError] Raised for any non-200 response.", "docstring_tokens": ["Returns", "the", "update", "to", "a", "ticket", "that", "happens", "when", "a", "macro", "will", "be", "applied", "."], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/resources.rb#L616-L625", "partition": "valid"} {"repo": "zendesk/zendesk_api_client_rb", "path": "lib/zendesk_api/client.rb", "func_name": "ZendeskAPI.Client.method_missing", "original_string": "def method_missing(method, *args, &block)\n method = method.to_s\n options = args.last.is_a?(Hash) ? args.pop : {}\n\n @resource_cache[method] ||= { :class => nil, :cache => ZendeskAPI::LRUCache.new }\n if !options.delete(:reload) && (cached = @resource_cache[method][:cache].read(options.hash))\n cached\n else\n @resource_cache[method][:class] ||= method_as_class(method)\n raise \"Resource for #{method} does not exist\" unless @resource_cache[method][:class]\n @resource_cache[method][:cache].write(options.hash, ZendeskAPI::Collection.new(self, @resource_cache[method][:class], options))\n end\n end", "language": "ruby", "code": "def method_missing(method, *args, &block)\n method = method.to_s\n options = args.last.is_a?(Hash) ? args.pop : {}\n\n @resource_cache[method] ||= { :class => nil, :cache => ZendeskAPI::LRUCache.new }\n if !options.delete(:reload) && (cached = @resource_cache[method][:cache].read(options.hash))\n cached\n else\n @resource_cache[method][:class] ||= method_as_class(method)\n raise \"Resource for #{method} does not exist\" unless @resource_cache[method][:class]\n @resource_cache[method][:cache].write(options.hash, ZendeskAPI::Collection.new(self, @resource_cache[method][:class], options))\n end\n end", "code_tokens": ["def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "method", "=", "method", ".", "to_s", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "@resource_cache", "[", "method", "]", "||=", "{", ":class", "=>", "nil", ",", ":cache", "=>", "ZendeskAPI", "::", "LRUCache", ".", "new", "}", "if", "!", "options", ".", "delete", "(", ":reload", ")", "&&", "(", "cached", "=", "@resource_cache", "[", "method", "]", "[", ":cache", "]", ".", "read", "(", "options", ".", "hash", ")", ")", "cached", "else", "@resource_cache", "[", "method", "]", "[", ":class", "]", "||=", "method_as_class", "(", "method", ")", "raise", "\"Resource for #{method} does not exist\"", "unless", "@resource_cache", "[", "method", "]", "[", ":class", "]", "@resource_cache", "[", "method", "]", "[", ":cache", "]", ".", "write", "(", "options", ".", "hash", ",", "ZendeskAPI", "::", "Collection", ".", "new", "(", "self", ",", "@resource_cache", "[", "method", "]", "[", ":class", "]", ",", "options", ")", ")", "end", "end"], "docstring": "Handles resources such as 'tickets'. Any options are passed to the underlying collection, except reload which disregards\n memoization and creates a new Collection instance.\n @return [Collection] Collection instance for resource", "docstring_tokens": ["Handles", "resources", "such", "as", "tickets", ".", "Any", "options", "are", "passed", "to", "the", "underlying", "collection", "except", "reload", "which", "disregards", "memoization", "and", "creates", "a", "new", "Collection", "instance", "."], "sha": "4237daa923c6e353a888473adae2a808352f4b26", "url": "https://github.com/zendesk/zendesk_api_client_rb/blob/4237daa923c6e353a888473adae2a808352f4b26/lib/zendesk_api/client.rb#L39-L51", "partition": "valid"} {"repo": "interagent/pliny", "path": "lib/pliny/router.rb", "func_name": "Pliny.Router.version", "original_string": "def version(*versions, &block)\n condition = lambda { |env|\n versions.include?(env[\"HTTP_X_API_VERSION\"])\n }\n with_conditions(condition, &block)\n end", "language": "ruby", "code": "def version(*versions, &block)\n condition = lambda { |env|\n versions.include?(env[\"HTTP_X_API_VERSION\"])\n }\n with_conditions(condition, &block)\n end", "code_tokens": ["def", "version", "(", "*", "versions", ",", "&", "block", ")", "condition", "=", "lambda", "{", "|", "env", "|", "versions", ".", "include?", "(", "env", "[", "\"HTTP_X_API_VERSION\"", "]", ")", "}", "with_conditions", "(", "condition", ",", "block", ")", "end"], "docstring": "yield to a builder block in which all defined apps will only respond for\n the given version", "docstring_tokens": ["yield", "to", "a", "builder", "block", "in", "which", "all", "defined", "apps", "will", "only", "respond", "for", "the", "given", "version"], "sha": "8add57f22e7be9404334222bbe7095af83bb8607", "url": "https://github.com/interagent/pliny/blob/8add57f22e7be9404334222bbe7095af83bb8607/lib/pliny/router.rb#L8-L13", "partition": "valid"} {"repo": "assaf/vanity", "path": "lib/vanity/metric/base.rb", "func_name": "Vanity.Metric.track_args", "original_string": "def track_args(args)\n case args\n when Hash\n timestamp, identity, values = args.values_at(:timestamp, :identity, :values)\n when Array\n values = args\n when Numeric\n values = [args]\n end\n identity ||= Vanity.context.vanity_identity rescue nil\n [timestamp || Time.now, identity, values || [1]]\n end", "language": "ruby", "code": "def track_args(args)\n case args\n when Hash\n timestamp, identity, values = args.values_at(:timestamp, :identity, :values)\n when Array\n values = args\n when Numeric\n values = [args]\n end\n identity ||= Vanity.context.vanity_identity rescue nil\n [timestamp || Time.now, identity, values || [1]]\n end", "code_tokens": ["def", "track_args", "(", "args", ")", "case", "args", "when", "Hash", "timestamp", ",", "identity", ",", "values", "=", "args", ".", "values_at", "(", ":timestamp", ",", ":identity", ",", ":values", ")", "when", "Array", "values", "=", "args", "when", "Numeric", "values", "=", "[", "args", "]", "end", "identity", "||=", "Vanity", ".", "context", ".", "vanity_identity", "rescue", "nil", "[", "timestamp", "||", "Time", ".", "now", ",", "identity", ",", "values", "||", "[", "1", "]", "]", "end"], "docstring": "Parses arguments to track! method and return array with timestamp,\n identity and array of values.", "docstring_tokens": ["Parses", "arguments", "to", "track!", "method", "and", "return", "array", "with", "timestamp", "identity", "and", "array", "of", "values", "."], "sha": "5bdd3ab21d3e495fb6e3f2596d2a048c453ca27a", "url": "https://github.com/assaf/vanity/blob/5bdd3ab21d3e495fb6e3f2596d2a048c453ca27a/lib/vanity/metric/base.rb#L146-L157", "partition": "valid"} {"repo": "assaf/vanity", "path": "lib/vanity/commands/report.rb", "func_name": "Vanity.Render.render", "original_string": "def render(path_or_options, locals = {})\n if path_or_options.respond_to?(:keys)\n render_erb(\n path_or_options[:file] || path_or_options[:partial],\n path_or_options[:locals]\n )\n else\n render_erb(path_or_options, locals)\n end\n end", "language": "ruby", "code": "def render(path_or_options, locals = {})\n if path_or_options.respond_to?(:keys)\n render_erb(\n path_or_options[:file] || path_or_options[:partial],\n path_or_options[:locals]\n )\n else\n render_erb(path_or_options, locals)\n end\n end", "code_tokens": ["def", "render", "(", "path_or_options", ",", "locals", "=", "{", "}", ")", "if", "path_or_options", ".", "respond_to?", "(", ":keys", ")", "render_erb", "(", "path_or_options", "[", ":file", "]", "||", "path_or_options", "[", ":partial", "]", ",", "path_or_options", "[", ":locals", "]", ")", "else", "render_erb", "(", "path_or_options", ",", "locals", ")", "end", "end"], "docstring": "Render the named template. Used for reporting and the dashboard.", "docstring_tokens": ["Render", "the", "named", "template", ".", "Used", "for", "reporting", "and", "the", "dashboard", "."], "sha": "5bdd3ab21d3e495fb6e3f2596d2a048c453ca27a", "url": "https://github.com/assaf/vanity/blob/5bdd3ab21d3e495fb6e3f2596d2a048c453ca27a/lib/vanity/commands/report.rb#L11-L20", "partition": "valid"} {"repo": "assaf/vanity", "path": "lib/vanity/commands/report.rb", "func_name": "Vanity.Render.method_missing", "original_string": "def method_missing(method, *args, &block)\n %w(url_for flash).include?(method.to_s) ? ProxyEmpty.new : super\n end", "language": "ruby", "code": "def method_missing(method, *args, &block)\n %w(url_for flash).include?(method.to_s) ? ProxyEmpty.new : super\n end", "code_tokens": ["def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "%w(", "url_for", "flash", ")", ".", "include?", "(", "method", ".", "to_s", ")", "?", "ProxyEmpty", ".", "new", ":", "super", "end"], "docstring": "prevent certain url helper methods from failing so we can run erb templates outside of rails for reports.", "docstring_tokens": ["prevent", "certain", "url", "helper", "methods", "from", "failing", "so", "we", "can", "run", "erb", "templates", "outside", "of", "rails", "for", "reports", "."], "sha": "5bdd3ab21d3e495fb6e3f2596d2a048c453ca27a", "url": "https://github.com/assaf/vanity/blob/5bdd3ab21d3e495fb6e3f2596d2a048c453ca27a/lib/vanity/commands/report.rb#L36-L38", "partition": "valid"} {"repo": "assaf/vanity", "path": "lib/vanity/commands/report.rb", "func_name": "Vanity.Render.vanity_simple_format", "original_string": "def vanity_simple_format(text, options={})\n open = \"

\"\n text = open + text.gsub(/\\r\\n?/, \"\\n\"). # \\r\\n and \\r -> \\n\n gsub(/\\n\\n+/, \"

\\n\\n#{open}\"). # 2+ newline -> paragraph\n gsub(/([^\\n]\\n)(?=[^\\n])/, '\\1
') + # 1 newline -> br\n \"

\"\n end", "language": "ruby", "code": "def vanity_simple_format(text, options={})\n open = \"

\"\n text = open + text.gsub(/\\r\\n?/, \"\\n\"). # \\r\\n and \\r -> \\n\n gsub(/\\n\\n+/, \"

\\n\\n#{open}\"). # 2+ newline -> paragraph\n gsub(/([^\\n]\\n)(?=[^\\n])/, '\\1
') + # 1 newline -> br\n \"

\"\n end", "code_tokens": ["def", "vanity_simple_format", "(", "text", ",", "options", "=", "{", "}", ")", "open", "=", "\"

\"", "text", "=", "open", "+", "text", ".", "gsub", "(", "/", "\\r", "\\n", "/", ",", "\"\\n\"", ")", ".", "# \\r\\n and \\r -> \\n", "gsub", "(", "/", "\\n", "\\n", "/", ",", "\"

\\n\\n#{open}\"", ")", ".", "# 2+ newline -> paragraph", "gsub", "(", "/", "\\n", "\\n", "\\n", "/", ",", "'\\1
'", ")", "+", "# 1 newline -> br", "\"

\"", "end"], "docstring": "Dumbed down from Rails' simple_format.", "docstring_tokens": ["Dumbed", "down", "from", "Rails", "simple_format", "."], "sha": "5bdd3ab21d3e495fb6e3f2596d2a048c453ca27a", "url": "https://github.com/assaf/vanity/blob/5bdd3ab21d3e495fb6e3f2596d2a048c453ca27a/lib/vanity/commands/report.rb#L41-L47", "partition": "valid"} {"repo": "assaf/vanity", "path": "lib/vanity/playground.rb", "func_name": "Vanity.Playground.experiment", "original_string": "def experiment(name)\n id = name.to_s.downcase.gsub(/\\W/, \"_\").to_sym\n Vanity.logger.warn(\"Deprecated: Please call experiment method with experiment identifier (a Ruby symbol)\") unless id == name\n experiments[id.to_sym] or raise NoExperimentError, \"No experiment #{id}\"\n end", "language": "ruby", "code": "def experiment(name)\n id = name.to_s.downcase.gsub(/\\W/, \"_\").to_sym\n Vanity.logger.warn(\"Deprecated: Please call experiment method with experiment identifier (a Ruby symbol)\") unless id == name\n experiments[id.to_sym] or raise NoExperimentError, \"No experiment #{id}\"\n end", "code_tokens": ["def", "experiment", "(", "name", ")", "id", "=", "name", ".", "to_s", ".", "downcase", ".", "gsub", "(", "/", "\\W", "/", ",", "\"_\"", ")", ".", "to_sym", "Vanity", ".", "logger", ".", "warn", "(", "\"Deprecated: Please call experiment method with experiment identifier (a Ruby symbol)\"", ")", "unless", "id", "==", "name", "experiments", "[", "id", ".", "to_sym", "]", "or", "raise", "NoExperimentError", ",", "\"No experiment #{id}\"", "end"], "docstring": "Returns the experiment. You may not have guessed, but this method raises\n an exception if it cannot load the experiment's definition.\n\n @see Vanity::Experiment\n @deprecated", "docstring_tokens": ["Returns", "the", "experiment", ".", "You", "may", "not", "have", "guessed", "but", "this", "method", "raises", "an", "exception", "if", "it", "cannot", "load", "the", "experiment", "s", "definition", "."], "sha": "5bdd3ab21d3e495fb6e3f2596d2a048c453ca27a", "url": "https://github.com/assaf/vanity/blob/5bdd3ab21d3e495fb6e3f2596d2a048c453ca27a/lib/vanity/playground.rb#L180-L184", "partition": "valid"} {"repo": "assaf/vanity", "path": "lib/vanity/templates.rb", "func_name": "Vanity.Templates.custom_template_path_valid?", "original_string": "def custom_template_path_valid?\n Vanity.playground.custom_templates_path &&\n File.exist?(Vanity.playground.custom_templates_path) &&\n !Dir[File.join(Vanity.playground.custom_templates_path, '*')].empty?\n end", "language": "ruby", "code": "def custom_template_path_valid?\n Vanity.playground.custom_templates_path &&\n File.exist?(Vanity.playground.custom_templates_path) &&\n !Dir[File.join(Vanity.playground.custom_templates_path, '*')].empty?\n end", "code_tokens": ["def", "custom_template_path_valid?", "Vanity", ".", "playground", ".", "custom_templates_path", "&&", "File", ".", "exist?", "(", "Vanity", ".", "playground", ".", "custom_templates_path", ")", "&&", "!", "Dir", "[", "File", ".", "join", "(", "Vanity", ".", "playground", ".", "custom_templates_path", ",", "'*'", ")", "]", ".", "empty?", "end"], "docstring": "Check to make sure we set a custome path, it exists, and there are non-\n dotfiles in the directory.", "docstring_tokens": ["Check", "to", "make", "sure", "we", "set", "a", "custome", "path", "it", "exists", "and", "there", "are", "non", "-", "dotfiles", "in", "the", "directory", "."], "sha": "5bdd3ab21d3e495fb6e3f2596d2a048c453ca27a", "url": "https://github.com/assaf/vanity/blob/5bdd3ab21d3e495fb6e3f2596d2a048c453ca27a/lib/vanity/templates.rb#L24-L28", "partition": "valid"} {"repo": "benchmark-driver/benchmark-driver", "path": "lib/benchmark_driver/ruby_interface.rb", "func_name": "BenchmarkDriver.RubyInterface.run", "original_string": "def run\n unless @executables.empty?\n @config.executables = @executables\n end\n\n jobs = @jobs.flat_map do |job|\n BenchmarkDriver::JobParser.parse({\n type: @config.runner_type,\n prelude: @prelude,\n loop_count: @loop_count,\n }.merge!(job))\n end\n BenchmarkDriver::Runner.run(jobs, config: @config)\n end", "language": "ruby", "code": "def run\n unless @executables.empty?\n @config.executables = @executables\n end\n\n jobs = @jobs.flat_map do |job|\n BenchmarkDriver::JobParser.parse({\n type: @config.runner_type,\n prelude: @prelude,\n loop_count: @loop_count,\n }.merge!(job))\n end\n BenchmarkDriver::Runner.run(jobs, config: @config)\n end", "code_tokens": ["def", "run", "unless", "@executables", ".", "empty?", "@config", ".", "executables", "=", "@executables", "end", "jobs", "=", "@jobs", ".", "flat_map", "do", "|", "job", "|", "BenchmarkDriver", "::", "JobParser", ".", "parse", "(", "{", "type", ":", "@config", ".", "runner_type", ",", "prelude", ":", "@prelude", ",", "loop_count", ":", "@loop_count", ",", "}", ".", "merge!", "(", "job", ")", ")", "end", "BenchmarkDriver", "::", "Runner", ".", "run", "(", "jobs", ",", "config", ":", "@config", ")", "end"], "docstring": "Build jobs and run. This is NOT interface for users.", "docstring_tokens": ["Build", "jobs", "and", "run", ".", "This", "is", "NOT", "interface", "for", "users", "."], "sha": "96759fb9f0faf4376d97bfdba1c9e56113531ca3", "url": "https://github.com/benchmark-driver/benchmark-driver/blob/96759fb9f0faf4376d97bfdba1c9e56113531ca3/lib/benchmark_driver/ruby_interface.rb#L8-L21", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_user_configuration.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeUserConfiguration.get_user_configuration", "original_string": "def get_user_configuration(opts)\n opts = opts.clone\n [:user_config_name, :user_config_props].each do |k|\n validate_param(opts, k, true)\n end\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.GetUserConfiguration {|x|\n x.parent.default_namespace = @default_ns\n builder.user_configuration_name!(opts[:user_config_name])\n builder.user_configuration_properties!(opts[:user_config_props])\n }\n end\n end\n do_soap_request(req, response_class: EwsSoapAvailabilityResponse)\n end", "language": "ruby", "code": "def get_user_configuration(opts)\n opts = opts.clone\n [:user_config_name, :user_config_props].each do |k|\n validate_param(opts, k, true)\n end\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.GetUserConfiguration {|x|\n x.parent.default_namespace = @default_ns\n builder.user_configuration_name!(opts[:user_config_name])\n builder.user_configuration_properties!(opts[:user_config_props])\n }\n end\n end\n do_soap_request(req, response_class: EwsSoapAvailabilityResponse)\n end", "code_tokens": ["def", "get_user_configuration", "(", "opts", ")", "opts", "=", "opts", ".", "clone", "[", ":user_config_name", ",", ":user_config_props", "]", ".", "each", "do", "|", "k", "|", "validate_param", "(", "opts", ",", "k", ",", "true", ")", "end", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "if", "(", "type", "==", ":header", ")", "else", "builder", ".", "nbuild", ".", "GetUserConfiguration", "{", "|", "x", "|", "x", ".", "parent", ".", "default_namespace", "=", "@default_ns", "builder", ".", "user_configuration_name!", "(", "opts", "[", ":user_config_name", "]", ")", "builder", ".", "user_configuration_properties!", "(", "opts", "[", ":user_config_props", "]", ")", "}", "end", "end", "do_soap_request", "(", "req", ",", "response_class", ":", "EwsSoapAvailabilityResponse", ")", "end"], "docstring": "The GetUserConfiguration operation gets a user configuration object from\n a folder.\n @see http://msdn.microsoft.com/en-us/library/aa563465.aspx\n @param [Hash] opts\n @option opts [Hash] :user_config_name\n @option opts [String] :user_config_props", "docstring_tokens": ["The", "GetUserConfiguration", "operation", "gets", "a", "user", "configuration", "object", "from", "a", "folder", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_user_configuration.rb#L14-L30", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.folder_shape!", "original_string": "def folder_shape!(folder_shape)\n @nbuild.FolderShape {\n @nbuild.parent.default_namespace = @default_ns\n base_shape!(folder_shape[:base_shape])\n if(folder_shape[:additional_properties])\n additional_properties!(folder_shape[:additional_properties])\n end\n }\n end", "language": "ruby", "code": "def folder_shape!(folder_shape)\n @nbuild.FolderShape {\n @nbuild.parent.default_namespace = @default_ns\n base_shape!(folder_shape[:base_shape])\n if(folder_shape[:additional_properties])\n additional_properties!(folder_shape[:additional_properties])\n end\n }\n end", "code_tokens": ["def", "folder_shape!", "(", "folder_shape", ")", "@nbuild", ".", "FolderShape", "{", "@nbuild", ".", "parent", ".", "default_namespace", "=", "@default_ns", "base_shape!", "(", "folder_shape", "[", ":base_shape", "]", ")", "if", "(", "folder_shape", "[", ":additional_properties", "]", ")", "additional_properties!", "(", "folder_shape", "[", ":additional_properties", "]", ")", "end", "}", "end"], "docstring": "Build the FolderShape element\n @see http://msdn.microsoft.com/en-us/library/aa494311.aspx\n @param [Hash] folder_shape The folder shape structure to build from\n @todo need fully support all options", "docstring_tokens": ["Build", "the", "FolderShape", "element"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L117-L125", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.item_shape!", "original_string": "def item_shape!(item_shape)\n @nbuild[NS_EWS_MESSAGES].ItemShape {\n @nbuild.parent.default_namespace = @default_ns\n base_shape!(item_shape[:base_shape])\n mime_content!(item_shape[:include_mime_content]) if item_shape.has_key?(:include_mime_content)\n body_type!(item_shape[:body_type]) if item_shape[:body_type]\n if(item_shape[:additional_properties])\n additional_properties!(item_shape[:additional_properties])\n end\n }\n end", "language": "ruby", "code": "def item_shape!(item_shape)\n @nbuild[NS_EWS_MESSAGES].ItemShape {\n @nbuild.parent.default_namespace = @default_ns\n base_shape!(item_shape[:base_shape])\n mime_content!(item_shape[:include_mime_content]) if item_shape.has_key?(:include_mime_content)\n body_type!(item_shape[:body_type]) if item_shape[:body_type]\n if(item_shape[:additional_properties])\n additional_properties!(item_shape[:additional_properties])\n end\n }\n end", "code_tokens": ["def", "item_shape!", "(", "item_shape", ")", "@nbuild", "[", "NS_EWS_MESSAGES", "]", ".", "ItemShape", "{", "@nbuild", ".", "parent", ".", "default_namespace", "=", "@default_ns", "base_shape!", "(", "item_shape", "[", ":base_shape", "]", ")", "mime_content!", "(", "item_shape", "[", ":include_mime_content", "]", ")", "if", "item_shape", ".", "has_key?", "(", ":include_mime_content", ")", "body_type!", "(", "item_shape", "[", ":body_type", "]", ")", "if", "item_shape", "[", ":body_type", "]", "if", "(", "item_shape", "[", ":additional_properties", "]", ")", "additional_properties!", "(", "item_shape", "[", ":additional_properties", "]", ")", "end", "}", "end"], "docstring": "Build the ItemShape element\n @see http://msdn.microsoft.com/en-us/library/aa565261.aspx\n @param [Hash] item_shape The item shape structure to build from\n @todo need fully support all options", "docstring_tokens": ["Build", "the", "ItemShape", "element"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L131-L141", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.indexed_page_item_view!", "original_string": "def indexed_page_item_view!(indexed_page_item_view)\n attribs = {}\n indexed_page_item_view.each_pair {|k,v| attribs[camel_case(k)] = v.to_s}\n @nbuild[NS_EWS_MESSAGES].IndexedPageItemView(attribs)\n end", "language": "ruby", "code": "def indexed_page_item_view!(indexed_page_item_view)\n attribs = {}\n indexed_page_item_view.each_pair {|k,v| attribs[camel_case(k)] = v.to_s}\n @nbuild[NS_EWS_MESSAGES].IndexedPageItemView(attribs)\n end", "code_tokens": ["def", "indexed_page_item_view!", "(", "indexed_page_item_view", ")", "attribs", "=", "{", "}", "indexed_page_item_view", ".", "each_pair", "{", "|", "k", ",", "v", "|", "attribs", "[", "camel_case", "(", "k", ")", "]", "=", "v", ".", "to_s", "}", "@nbuild", "[", "NS_EWS_MESSAGES", "]", ".", "IndexedPageItemView", "(", "attribs", ")", "end"], "docstring": "Build the IndexedPageItemView element\n @see http://msdn.microsoft.com/en-us/library/exchange/aa563549(v=exchg.150).aspx\n @todo needs peer check", "docstring_tokens": ["Build", "the", "IndexedPageItemView", "element"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L146-L150", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.folder_ids!", "original_string": "def folder_ids!(fids, act_as=nil)\n ns = @nbuild.parent.name.match(/subscription/i) ? NS_EWS_TYPES : NS_EWS_MESSAGES\n @nbuild[ns].FolderIds {\n fids.each do |fid|\n fid[:act_as] = act_as if act_as != nil\n dispatch_folder_id!(fid)\n end\n }\n end", "language": "ruby", "code": "def folder_ids!(fids, act_as=nil)\n ns = @nbuild.parent.name.match(/subscription/i) ? NS_EWS_TYPES : NS_EWS_MESSAGES\n @nbuild[ns].FolderIds {\n fids.each do |fid|\n fid[:act_as] = act_as if act_as != nil\n dispatch_folder_id!(fid)\n end\n }\n end", "code_tokens": ["def", "folder_ids!", "(", "fids", ",", "act_as", "=", "nil", ")", "ns", "=", "@nbuild", ".", "parent", ".", "name", ".", "match", "(", "/", "/i", ")", "?", "NS_EWS_TYPES", ":", "NS_EWS_MESSAGES", "@nbuild", "[", "ns", "]", ".", "FolderIds", "{", "fids", ".", "each", "do", "|", "fid", "|", "fid", "[", ":act_as", "]", "=", "act_as", "if", "act_as", "!=", "nil", "dispatch_folder_id!", "(", "fid", ")", "end", "}", "end"], "docstring": "Build the FolderIds element\n @see http://msdn.microsoft.com/en-us/library/aa580509.aspx", "docstring_tokens": ["Build", "the", "FolderIds", "element"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L192-L200", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.distinguished_folder_id!", "original_string": "def distinguished_folder_id!(dfid, change_key = nil, act_as = nil)\n attribs = {'Id' => dfid.to_s}\n attribs['ChangeKey'] = change_key if change_key\n @nbuild[NS_EWS_TYPES].DistinguishedFolderId(attribs) {\n if ! act_as.nil?\n mailbox!({:email_address => act_as})\n end\n }\n end", "language": "ruby", "code": "def distinguished_folder_id!(dfid, change_key = nil, act_as = nil)\n attribs = {'Id' => dfid.to_s}\n attribs['ChangeKey'] = change_key if change_key\n @nbuild[NS_EWS_TYPES].DistinguishedFolderId(attribs) {\n if ! act_as.nil?\n mailbox!({:email_address => act_as})\n end\n }\n end", "code_tokens": ["def", "distinguished_folder_id!", "(", "dfid", ",", "change_key", "=", "nil", ",", "act_as", "=", "nil", ")", "attribs", "=", "{", "'Id'", "=>", "dfid", ".", "to_s", "}", "attribs", "[", "'ChangeKey'", "]", "=", "change_key", "if", "change_key", "@nbuild", "[", "NS_EWS_TYPES", "]", ".", "DistinguishedFolderId", "(", "attribs", ")", "{", "if", "!", "act_as", ".", "nil?", "mailbox!", "(", "{", ":email_address", "=>", "act_as", "}", ")", "end", "}", "end"], "docstring": "Build the DistinguishedFolderId element\n @see http://msdn.microsoft.com/en-us/library/aa580808.aspx\n @todo add support for the Mailbox child object", "docstring_tokens": ["Build", "the", "DistinguishedFolderId", "element"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L213-L221", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.folder_id!", "original_string": "def folder_id!(fid, change_key = nil)\n attribs = {'Id' => fid}\n attribs['ChangeKey'] = change_key if change_key\n @nbuild[NS_EWS_TYPES].FolderId(attribs)\n end", "language": "ruby", "code": "def folder_id!(fid, change_key = nil)\n attribs = {'Id' => fid}\n attribs['ChangeKey'] = change_key if change_key\n @nbuild[NS_EWS_TYPES].FolderId(attribs)\n end", "code_tokens": ["def", "folder_id!", "(", "fid", ",", "change_key", "=", "nil", ")", "attribs", "=", "{", "'Id'", "=>", "fid", "}", "attribs", "[", "'ChangeKey'", "]", "=", "change_key", "if", "change_key", "@nbuild", "[", "NS_EWS_TYPES", "]", ".", "FolderId", "(", "attribs", ")", "end"], "docstring": "Build the FolderId element\n @see http://msdn.microsoft.com/en-us/library/aa579461.aspx", "docstring_tokens": ["Build", "the", "FolderId", "element"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L225-L229", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.additional_properties!", "original_string": "def additional_properties!(addprops)\n @nbuild[NS_EWS_TYPES].AdditionalProperties {\n addprops.each_pair {|k,v|\n dispatch_field_uri!({k => v}, NS_EWS_TYPES)\n }\n }\n end", "language": "ruby", "code": "def additional_properties!(addprops)\n @nbuild[NS_EWS_TYPES].AdditionalProperties {\n addprops.each_pair {|k,v|\n dispatch_field_uri!({k => v}, NS_EWS_TYPES)\n }\n }\n end", "code_tokens": ["def", "additional_properties!", "(", "addprops", ")", "@nbuild", "[", "NS_EWS_TYPES", "]", ".", "AdditionalProperties", "{", "addprops", ".", "each_pair", "{", "|", "k", ",", "v", "|", "dispatch_field_uri!", "(", "{", "k", "=>", "v", "}", ",", "NS_EWS_TYPES", ")", "}", "}", "end"], "docstring": "Build the AdditionalProperties element\n @see http://msdn.microsoft.com/en-us/library/aa563810.aspx", "docstring_tokens": ["Build", "the", "AdditionalProperties", "element"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L346-L352", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.mailbox!", "original_string": "def mailbox!(mbox)\n nbuild[NS_EWS_TYPES].Mailbox {\n name!(mbox[:name]) if mbox[:name]\n email_address!(mbox[:email_address]) if mbox[:email_address]\n address!(mbox[:address]) if mbox[:address] # for Availability query\n routing_type!(mbox[:routing_type]) if mbox[:routing_type]\n mailbox_type!(mbox[:mailbox_type]) if mbox[:mailbox_type]\n item_id!(mbox[:item_id]) if mbox[:item_id]\n }\n end", "language": "ruby", "code": "def mailbox!(mbox)\n nbuild[NS_EWS_TYPES].Mailbox {\n name!(mbox[:name]) if mbox[:name]\n email_address!(mbox[:email_address]) if mbox[:email_address]\n address!(mbox[:address]) if mbox[:address] # for Availability query\n routing_type!(mbox[:routing_type]) if mbox[:routing_type]\n mailbox_type!(mbox[:mailbox_type]) if mbox[:mailbox_type]\n item_id!(mbox[:item_id]) if mbox[:item_id]\n }\n end", "code_tokens": ["def", "mailbox!", "(", "mbox", ")", "nbuild", "[", "NS_EWS_TYPES", "]", ".", "Mailbox", "{", "name!", "(", "mbox", "[", ":name", "]", ")", "if", "mbox", "[", ":name", "]", "email_address!", "(", "mbox", "[", ":email_address", "]", ")", "if", "mbox", "[", ":email_address", "]", "address!", "(", "mbox", "[", ":address", "]", ")", "if", "mbox", "[", ":address", "]", "# for Availability query", "routing_type!", "(", "mbox", "[", ":routing_type", "]", ")", "if", "mbox", "[", ":routing_type", "]", "mailbox_type!", "(", "mbox", "[", ":mailbox_type", "]", ")", "if", "mbox", "[", ":mailbox_type", "]", "item_id!", "(", "mbox", "[", ":item_id", "]", ")", "if", "mbox", "[", ":item_id", "]", "}", "end"], "docstring": "Build the Mailbox element.\n This element is commonly used for delegation. Typically passing an\n email_address is sufficient\n @see http://msdn.microsoft.com/en-us/library/aa565036.aspx\n @param [Hash] mailbox A well-formated hash", "docstring_tokens": ["Build", "the", "Mailbox", "element", ".", "This", "element", "is", "commonly", "used", "for", "delegation", ".", "Typically", "passing", "an", "email_address", "is", "sufficient"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L359-L368", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.get_server_time_zones!", "original_string": "def get_server_time_zones!(get_time_zone_options)\n nbuild[NS_EWS_MESSAGES].GetServerTimeZones('ReturnFullTimeZoneData' => get_time_zone_options[:full]) do\n if get_time_zone_options[:ids] && get_time_zone_options[:ids].any?\n nbuild[NS_EWS_MESSAGES].Ids do\n get_time_zone_options[:ids].each do |id|\n nbuild[NS_EWS_TYPES].Id id\n end\n end\n end\n end\n end", "language": "ruby", "code": "def get_server_time_zones!(get_time_zone_options)\n nbuild[NS_EWS_MESSAGES].GetServerTimeZones('ReturnFullTimeZoneData' => get_time_zone_options[:full]) do\n if get_time_zone_options[:ids] && get_time_zone_options[:ids].any?\n nbuild[NS_EWS_MESSAGES].Ids do\n get_time_zone_options[:ids].each do |id|\n nbuild[NS_EWS_TYPES].Id id\n end\n end\n end\n end\n end", "code_tokens": ["def", "get_server_time_zones!", "(", "get_time_zone_options", ")", "nbuild", "[", "NS_EWS_MESSAGES", "]", ".", "GetServerTimeZones", "(", "'ReturnFullTimeZoneData'", "=>", "get_time_zone_options", "[", ":full", "]", ")", "do", "if", "get_time_zone_options", "[", ":ids", "]", "&&", "get_time_zone_options", "[", ":ids", "]", ".", "any?", "nbuild", "[", "NS_EWS_MESSAGES", "]", ".", "Ids", "do", "get_time_zone_options", "[", ":ids", "]", ".", "each", "do", "|", "id", "|", "nbuild", "[", "NS_EWS_TYPES", "]", ".", "Id", "id", "end", "end", "end", "end", "end"], "docstring": "Request all known time_zones from server", "docstring_tokens": ["Request", "all", "known", "time_zones", "from", "server"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L477-L487", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.start_time_zone!", "original_string": "def start_time_zone!(zone)\n attributes = {}\n attributes['Id'] = zone[:id] if zone[:id]\n attributes['Name'] = zone[:name] if zone[:name]\n nbuild[NS_EWS_TYPES].StartTimeZone(attributes)\n end", "language": "ruby", "code": "def start_time_zone!(zone)\n attributes = {}\n attributes['Id'] = zone[:id] if zone[:id]\n attributes['Name'] = zone[:name] if zone[:name]\n nbuild[NS_EWS_TYPES].StartTimeZone(attributes)\n end", "code_tokens": ["def", "start_time_zone!", "(", "zone", ")", "attributes", "=", "{", "}", "attributes", "[", "'Id'", "]", "=", "zone", "[", ":id", "]", "if", "zone", "[", ":id", "]", "attributes", "[", "'Name'", "]", "=", "zone", "[", ":name", "]", "if", "zone", "[", ":name", "]", "nbuild", "[", "NS_EWS_TYPES", "]", ".", "StartTimeZone", "(", "attributes", ")", "end"], "docstring": "Specifies an optional time zone for the start time\n @param [Hash] attributes\n @option attributes :id [String] ID of the Microsoft well known time zone\n @option attributes :name [String] Optional name of the time zone\n @todo Implement sub elements Periods, TransitionsGroups and Transitions to override zone\n @see http://msdn.microsoft.com/en-us/library/exchange/dd899524.aspx", "docstring_tokens": ["Specifies", "an", "optional", "time", "zone", "for", "the", "start", "time"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L495-L500", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.end_time_zone!", "original_string": "def end_time_zone!(zone)\n attributes = {}\n attributes['Id'] = zone[:id] if zone[:id]\n attributes['Name'] = zone[:name] if zone[:name]\n nbuild[NS_EWS_TYPES].EndTimeZone(attributes)\n end", "language": "ruby", "code": "def end_time_zone!(zone)\n attributes = {}\n attributes['Id'] = zone[:id] if zone[:id]\n attributes['Name'] = zone[:name] if zone[:name]\n nbuild[NS_EWS_TYPES].EndTimeZone(attributes)\n end", "code_tokens": ["def", "end_time_zone!", "(", "zone", ")", "attributes", "=", "{", "}", "attributes", "[", "'Id'", "]", "=", "zone", "[", ":id", "]", "if", "zone", "[", ":id", "]", "attributes", "[", "'Name'", "]", "=", "zone", "[", ":name", "]", "if", "zone", "[", ":name", "]", "nbuild", "[", "NS_EWS_TYPES", "]", ".", "EndTimeZone", "(", "attributes", ")", "end"], "docstring": "Specifies an optional time zone for the end time\n @param [Hash] attributes\n @option attributes :id [String] ID of the Microsoft well known time zone\n @option attributes :name [String] Optional name of the time zone\n @todo Implement sub elements Periods, TransitionsGroups and Transitions to override zone\n @see http://msdn.microsoft.com/en-us/library/exchange/dd899434.aspx", "docstring_tokens": ["Specifies", "an", "optional", "time", "zone", "for", "the", "end", "time"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L508-L513", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.time_zone_definition!", "original_string": "def time_zone_definition!(zone)\n attributes = {'Id' => zone[:id]}\n attributes['Name'] = zone[:name] if zone[:name]\n nbuild[NS_EWS_TYPES].TimeZoneDefinition(attributes)\n end", "language": "ruby", "code": "def time_zone_definition!(zone)\n attributes = {'Id' => zone[:id]}\n attributes['Name'] = zone[:name] if zone[:name]\n nbuild[NS_EWS_TYPES].TimeZoneDefinition(attributes)\n end", "code_tokens": ["def", "time_zone_definition!", "(", "zone", ")", "attributes", "=", "{", "'Id'", "=>", "zone", "[", ":id", "]", "}", "attributes", "[", "'Name'", "]", "=", "zone", "[", ":name", "]", "if", "zone", "[", ":name", "]", "nbuild", "[", "NS_EWS_TYPES", "]", ".", "TimeZoneDefinition", "(", "attributes", ")", "end"], "docstring": "Specify a time zone\n @todo Implement subelements Periods, TransitionsGroups and Transitions to override zone\n @see http://msdn.microsoft.com/en-us/library/exchange/dd899488.aspx", "docstring_tokens": ["Specify", "a", "time", "zone"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L518-L522", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.restriction!", "original_string": "def restriction!(restriction)\n @nbuild[NS_EWS_MESSAGES].Restriction {\n restriction.each_pair do |k,v|\n self.send normalize_type(k), v\n end\n }\n end", "language": "ruby", "code": "def restriction!(restriction)\n @nbuild[NS_EWS_MESSAGES].Restriction {\n restriction.each_pair do |k,v|\n self.send normalize_type(k), v\n end\n }\n end", "code_tokens": ["def", "restriction!", "(", "restriction", ")", "@nbuild", "[", "NS_EWS_MESSAGES", "]", ".", "Restriction", "{", "restriction", ".", "each_pair", "do", "|", "k", ",", "v", "|", "self", ".", "send", "normalize_type", "(", "k", ")", ",", "v", "end", "}", "end"], "docstring": "Build the Restriction element\n @see http://msdn.microsoft.com/en-us/library/aa563791.aspx\n @param [Hash] restriction a well-formatted Hash that can be fed to #build_xml!", "docstring_tokens": ["Build", "the", "Restriction", "element"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L527-L533", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.calendar_view!", "original_string": "def calendar_view!(cal_view)\n attribs = {}\n cal_view.each_pair {|k,v| attribs[camel_case(k)] = v.to_s}\n @nbuild[NS_EWS_MESSAGES].CalendarView(attribs)\n end", "language": "ruby", "code": "def calendar_view!(cal_view)\n attribs = {}\n cal_view.each_pair {|k,v| attribs[camel_case(k)] = v.to_s}\n @nbuild[NS_EWS_MESSAGES].CalendarView(attribs)\n end", "code_tokens": ["def", "calendar_view!", "(", "cal_view", ")", "attribs", "=", "{", "}", "cal_view", ".", "each_pair", "{", "|", "k", ",", "v", "|", "attribs", "[", "camel_case", "(", "k", ")", "]", "=", "v", ".", "to_s", "}", "@nbuild", "[", "NS_EWS_MESSAGES", "]", ".", "CalendarView", "(", "attribs", ")", "end"], "docstring": "Build the CalendarView element", "docstring_tokens": ["Build", "the", "CalendarView", "element"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L695-L699", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.contacts_view!", "original_string": "def contacts_view!(con_view)\n attribs = {}\n con_view.each_pair {|k,v| attribs[camel_case(k)] = v.to_s}\n @nbuild[NS_EWS_MESSAGES].ContactsView(attribs)\n end", "language": "ruby", "code": "def contacts_view!(con_view)\n attribs = {}\n con_view.each_pair {|k,v| attribs[camel_case(k)] = v.to_s}\n @nbuild[NS_EWS_MESSAGES].ContactsView(attribs)\n end", "code_tokens": ["def", "contacts_view!", "(", "con_view", ")", "attribs", "=", "{", "}", "con_view", ".", "each_pair", "{", "|", "k", ",", "v", "|", "attribs", "[", "camel_case", "(", "k", ")", "]", "=", "v", ".", "to_s", "}", "@nbuild", "[", "NS_EWS_MESSAGES", "]", ".", "ContactsView", "(", "attribs", ")", "end"], "docstring": "Build the ContactsView element", "docstring_tokens": ["Build", "the", "ContactsView", "element"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L702-L706", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.attachment_ids!", "original_string": "def attachment_ids!(aids)\n @nbuild.AttachmentIds {\n @nbuild.parent.default_namespace = @default_ns\n aids.each do |aid|\n attachment_id!(aid)\n end\n }\n end", "language": "ruby", "code": "def attachment_ids!(aids)\n @nbuild.AttachmentIds {\n @nbuild.parent.default_namespace = @default_ns\n aids.each do |aid|\n attachment_id!(aid)\n end\n }\n end", "code_tokens": ["def", "attachment_ids!", "(", "aids", ")", "@nbuild", ".", "AttachmentIds", "{", "@nbuild", ".", "parent", ".", "default_namespace", "=", "@default_ns", "aids", ".", "each", "do", "|", "aid", "|", "attachment_id!", "(", "aid", ")", "end", "}", "end"], "docstring": "Build the AttachmentIds element\n @see http://msdn.microsoft.com/en-us/library/aa580686.aspx", "docstring_tokens": ["Build", "the", "AttachmentIds", "element"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L1137-L1144", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.dispatch_item_id!", "original_string": "def dispatch_item_id!(iid)\n type = iid.keys.first\n item = iid[type]\n case type\n when :item_id\n item_id!(item)\n when :occurrence_item_id\n occurrence_item_id!(item)\n when :recurring_master_item_id\n recurring_master_item_id!(item)\n else\n raise EwsBadArgumentError, \"Bad ItemId type. #{type}\"\n end\n end", "language": "ruby", "code": "def dispatch_item_id!(iid)\n type = iid.keys.first\n item = iid[type]\n case type\n when :item_id\n item_id!(item)\n when :occurrence_item_id\n occurrence_item_id!(item)\n when :recurring_master_item_id\n recurring_master_item_id!(item)\n else\n raise EwsBadArgumentError, \"Bad ItemId type. #{type}\"\n end\n end", "code_tokens": ["def", "dispatch_item_id!", "(", "iid", ")", "type", "=", "iid", ".", "keys", ".", "first", "item", "=", "iid", "[", "type", "]", "case", "type", "when", ":item_id", "item_id!", "(", "item", ")", "when", ":occurrence_item_id", "occurrence_item_id!", "(", "item", ")", "when", ":recurring_master_item_id", "recurring_master_item_id!", "(", "item", ")", "else", "raise", "EwsBadArgumentError", ",", "\"Bad ItemId type. #{type}\"", "end", "end"], "docstring": "A helper method to dispatch to an ItemId, OccurrenceItemId, or a RecurringMasterItemId\n @param [Hash] iid The item id of some type", "docstring_tokens": ["A", "helper", "method", "to", "dispatch", "to", "an", "ItemId", "OccurrenceItemId", "or", "a", "RecurringMasterItemId"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L1182-L1195", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.dispatch_update_type!", "original_string": "def dispatch_update_type!(update)\n type = update.keys.first\n upd = update[type]\n case type\n when :append_to_item_field\n append_to_item_field!(upd)\n when :set_item_field\n set_item_field!(upd)\n when :delete_item_field\n delete_item_field!(upd)\n else\n raise EwsBadArgumentError, \"Bad Update type. #{type}\"\n end\n end", "language": "ruby", "code": "def dispatch_update_type!(update)\n type = update.keys.first\n upd = update[type]\n case type\n when :append_to_item_field\n append_to_item_field!(upd)\n when :set_item_field\n set_item_field!(upd)\n when :delete_item_field\n delete_item_field!(upd)\n else\n raise EwsBadArgumentError, \"Bad Update type. #{type}\"\n end\n end", "code_tokens": ["def", "dispatch_update_type!", "(", "update", ")", "type", "=", "update", ".", "keys", ".", "first", "upd", "=", "update", "[", "type", "]", "case", "type", "when", ":append_to_item_field", "append_to_item_field!", "(", "upd", ")", "when", ":set_item_field", "set_item_field!", "(", "upd", ")", "when", ":delete_item_field", "delete_item_field!", "(", "upd", ")", "else", "raise", "EwsBadArgumentError", ",", "\"Bad Update type. #{type}\"", "end", "end"], "docstring": "A helper method to dispatch to a AppendToItemField, SetItemField, or\n DeleteItemField\n @param [Hash] update An update of some type", "docstring_tokens": ["A", "helper", "method", "to", "dispatch", "to", "a", "AppendToItemField", "SetItemField", "or", "DeleteItemField"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L1200-L1213", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.dispatch_field_uri!", "original_string": "def dispatch_field_uri!(uri, ns=NS_EWS_MESSAGES)\n type = uri.keys.first\n vals = uri[type].is_a?(Array) ? uri[type] : [uri[type]]\n case type\n when :field_uRI, :field_uri\n vals.each do |val|\n value = val.is_a?(Hash) ? val[type] : val\n nbuild[ns].FieldURI('FieldURI' => value)\n end\n when :indexed_field_uRI, :indexed_field_uri\n vals.each do |val|\n nbuild[ns].IndexedFieldURI(\n 'FieldURI' => (val[:field_uRI] || val[:field_uri]),\n 'FieldIndex' => val[:field_index]\n )\n end\n when :extended_field_uRI, :extended_field_uri\n vals.each do |val|\n nbuild[ns].ExtendedFieldURI {\n nbuild.parent['DistinguishedPropertySetId'] = val[:distinguished_property_set_id] if val[:distinguished_property_set_id]\n nbuild.parent['PropertySetId'] = val[:property_set_id] if val[:property_set_id]\n nbuild.parent['PropertyTag'] = val[:property_tag] if val[:property_tag]\n nbuild.parent['PropertyName'] = val[:property_name] if val[:property_name]\n nbuild.parent['PropertyId'] = val[:property_id] if val[:property_id]\n nbuild.parent['PropertyType'] = val[:property_type] if val[:property_type]\n }\n end\n else\n raise EwsBadArgumentError, \"Bad URI type. #{type}\"\n end\n end", "language": "ruby", "code": "def dispatch_field_uri!(uri, ns=NS_EWS_MESSAGES)\n type = uri.keys.first\n vals = uri[type].is_a?(Array) ? uri[type] : [uri[type]]\n case type\n when :field_uRI, :field_uri\n vals.each do |val|\n value = val.is_a?(Hash) ? val[type] : val\n nbuild[ns].FieldURI('FieldURI' => value)\n end\n when :indexed_field_uRI, :indexed_field_uri\n vals.each do |val|\n nbuild[ns].IndexedFieldURI(\n 'FieldURI' => (val[:field_uRI] || val[:field_uri]),\n 'FieldIndex' => val[:field_index]\n )\n end\n when :extended_field_uRI, :extended_field_uri\n vals.each do |val|\n nbuild[ns].ExtendedFieldURI {\n nbuild.parent['DistinguishedPropertySetId'] = val[:distinguished_property_set_id] if val[:distinguished_property_set_id]\n nbuild.parent['PropertySetId'] = val[:property_set_id] if val[:property_set_id]\n nbuild.parent['PropertyTag'] = val[:property_tag] if val[:property_tag]\n nbuild.parent['PropertyName'] = val[:property_name] if val[:property_name]\n nbuild.parent['PropertyId'] = val[:property_id] if val[:property_id]\n nbuild.parent['PropertyType'] = val[:property_type] if val[:property_type]\n }\n end\n else\n raise EwsBadArgumentError, \"Bad URI type. #{type}\"\n end\n end", "code_tokens": ["def", "dispatch_field_uri!", "(", "uri", ",", "ns", "=", "NS_EWS_MESSAGES", ")", "type", "=", "uri", ".", "keys", ".", "first", "vals", "=", "uri", "[", "type", "]", ".", "is_a?", "(", "Array", ")", "?", "uri", "[", "type", "]", ":", "[", "uri", "[", "type", "]", "]", "case", "type", "when", ":field_uRI", ",", ":field_uri", "vals", ".", "each", "do", "|", "val", "|", "value", "=", "val", ".", "is_a?", "(", "Hash", ")", "?", "val", "[", "type", "]", ":", "val", "nbuild", "[", "ns", "]", ".", "FieldURI", "(", "'FieldURI'", "=>", "value", ")", "end", "when", ":indexed_field_uRI", ",", ":indexed_field_uri", "vals", ".", "each", "do", "|", "val", "|", "nbuild", "[", "ns", "]", ".", "IndexedFieldURI", "(", "'FieldURI'", "=>", "(", "val", "[", ":field_uRI", "]", "||", "val", "[", ":field_uri", "]", ")", ",", "'FieldIndex'", "=>", "val", "[", ":field_index", "]", ")", "end", "when", ":extended_field_uRI", ",", ":extended_field_uri", "vals", ".", "each", "do", "|", "val", "|", "nbuild", "[", "ns", "]", ".", "ExtendedFieldURI", "{", "nbuild", ".", "parent", "[", "'DistinguishedPropertySetId'", "]", "=", "val", "[", ":distinguished_property_set_id", "]", "if", "val", "[", ":distinguished_property_set_id", "]", "nbuild", ".", "parent", "[", "'PropertySetId'", "]", "=", "val", "[", ":property_set_id", "]", "if", "val", "[", ":property_set_id", "]", "nbuild", ".", "parent", "[", "'PropertyTag'", "]", "=", "val", "[", ":property_tag", "]", "if", "val", "[", ":property_tag", "]", "nbuild", ".", "parent", "[", "'PropertyName'", "]", "=", "val", "[", ":property_name", "]", "if", "val", "[", ":property_name", "]", "nbuild", ".", "parent", "[", "'PropertyId'", "]", "=", "val", "[", ":property_id", "]", "if", "val", "[", ":property_id", "]", "nbuild", ".", "parent", "[", "'PropertyType'", "]", "=", "val", "[", ":property_type", "]", "if", "val", "[", ":property_type", "]", "}", "end", "else", "raise", "EwsBadArgumentError", ",", "\"Bad URI type. #{type}\"", "end", "end"], "docstring": "A helper to dispatch to a FieldURI, IndexedFieldURI, or an ExtendedFieldURI\n @todo Implement ExtendedFieldURI", "docstring_tokens": ["A", "helper", "to", "dispatch", "to", "a", "FieldURI", "IndexedFieldURI", "or", "an", "ExtendedFieldURI"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L1217-L1247", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/builders/ews_builder.rb", "func_name": "Viewpoint::EWS::SOAP.EwsBuilder.dispatch_field_item!", "original_string": "def dispatch_field_item!(item, ns_prefix = nil)\n item.values.first[:xmlns_attribute] = ns_prefix if ns_prefix\n build_xml!(item)\n end", "language": "ruby", "code": "def dispatch_field_item!(item, ns_prefix = nil)\n item.values.first[:xmlns_attribute] = ns_prefix if ns_prefix\n build_xml!(item)\n end", "code_tokens": ["def", "dispatch_field_item!", "(", "item", ",", "ns_prefix", "=", "nil", ")", "item", ".", "values", ".", "first", "[", ":xmlns_attribute", "]", "=", "ns_prefix", "if", "ns_prefix", "build_xml!", "(", "item", ")", "end"], "docstring": "Insert item, enforce xmlns attribute if prefix is present", "docstring_tokens": ["Insert", "item", "enforce", "xmlns", "attribute", "if", "prefix", "is", "present"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/builders/ews_builder.rb#L1250-L1253", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/calendar_item.rb", "func_name": "Viewpoint::EWS::Types.CalendarItem.update_item!", "original_string": "def update_item!(updates, options = {})\n item_updates = []\n updates.each do |attribute, value|\n item_field = FIELD_URIS[attribute][:text] if FIELD_URIS.include? attribute\n field = {field_uRI: {field_uRI: item_field}}\n\n if value.nil? && item_field\n # Build DeleteItemField Change\n item_updates << {delete_item_field: field}\n elsif item_field\n # Build SetItemField Change\n item = Viewpoint::EWS::Template::CalendarItem.new(attribute => value)\n\n # Remap attributes because ews_builder #dispatch_field_item! uses #build_xml!\n item_attributes = item.to_ews_item.map do |name, value|\n if value.is_a? String\n {name => {text: value}}\n elsif value.is_a? Hash\n node = {name => {}}\n value.each do |attrib_key, attrib_value|\n attrib_key = camel_case(attrib_key) unless attrib_key == :text\n node[name][attrib_key] = attrib_value\n end\n node\n else\n {name => value}\n end\n end\n\n item_updates << {set_item_field: field.merge(calendar_item: {sub_elements: item_attributes})}\n else\n # Ignore unknown attribute\n end\n end\n\n if item_updates.any?\n data = {}\n data[:conflict_resolution] = options[:conflict_resolution] || 'AutoResolve'\n data[:send_meeting_invitations_or_cancellations] = options[:send_meeting_invitations_or_cancellations] || 'SendToNone'\n data[:item_changes] = [{item_id: self.item_id, updates: item_updates}]\n rm = ews.update_item(data).response_messages.first\n if rm && rm.success?\n self.get_all_properties!\n self\n else\n raise EwsCreateItemError, \"Could not update calendar item. #{rm.code}: #{rm.message_text}\" unless rm\n end\n end\n\n end", "language": "ruby", "code": "def update_item!(updates, options = {})\n item_updates = []\n updates.each do |attribute, value|\n item_field = FIELD_URIS[attribute][:text] if FIELD_URIS.include? attribute\n field = {field_uRI: {field_uRI: item_field}}\n\n if value.nil? && item_field\n # Build DeleteItemField Change\n item_updates << {delete_item_field: field}\n elsif item_field\n # Build SetItemField Change\n item = Viewpoint::EWS::Template::CalendarItem.new(attribute => value)\n\n # Remap attributes because ews_builder #dispatch_field_item! uses #build_xml!\n item_attributes = item.to_ews_item.map do |name, value|\n if value.is_a? String\n {name => {text: value}}\n elsif value.is_a? Hash\n node = {name => {}}\n value.each do |attrib_key, attrib_value|\n attrib_key = camel_case(attrib_key) unless attrib_key == :text\n node[name][attrib_key] = attrib_value\n end\n node\n else\n {name => value}\n end\n end\n\n item_updates << {set_item_field: field.merge(calendar_item: {sub_elements: item_attributes})}\n else\n # Ignore unknown attribute\n end\n end\n\n if item_updates.any?\n data = {}\n data[:conflict_resolution] = options[:conflict_resolution] || 'AutoResolve'\n data[:send_meeting_invitations_or_cancellations] = options[:send_meeting_invitations_or_cancellations] || 'SendToNone'\n data[:item_changes] = [{item_id: self.item_id, updates: item_updates}]\n rm = ews.update_item(data).response_messages.first\n if rm && rm.success?\n self.get_all_properties!\n self\n else\n raise EwsCreateItemError, \"Could not update calendar item. #{rm.code}: #{rm.message_text}\" unless rm\n end\n end\n\n end", "code_tokens": ["def", "update_item!", "(", "updates", ",", "options", "=", "{", "}", ")", "item_updates", "=", "[", "]", "updates", ".", "each", "do", "|", "attribute", ",", "value", "|", "item_field", "=", "FIELD_URIS", "[", "attribute", "]", "[", ":text", "]", "if", "FIELD_URIS", ".", "include?", "attribute", "field", "=", "{", "field_uRI", ":", "{", "field_uRI", ":", "item_field", "}", "}", "if", "value", ".", "nil?", "&&", "item_field", "# Build DeleteItemField Change", "item_updates", "<<", "{", "delete_item_field", ":", "field", "}", "elsif", "item_field", "# Build SetItemField Change", "item", "=", "Viewpoint", "::", "EWS", "::", "Template", "::", "CalendarItem", ".", "new", "(", "attribute", "=>", "value", ")", "# Remap attributes because ews_builder #dispatch_field_item! uses #build_xml!", "item_attributes", "=", "item", ".", "to_ews_item", ".", "map", "do", "|", "name", ",", "value", "|", "if", "value", ".", "is_a?", "String", "{", "name", "=>", "{", "text", ":", "value", "}", "}", "elsif", "value", ".", "is_a?", "Hash", "node", "=", "{", "name", "=>", "{", "}", "}", "value", ".", "each", "do", "|", "attrib_key", ",", "attrib_value", "|", "attrib_key", "=", "camel_case", "(", "attrib_key", ")", "unless", "attrib_key", "==", ":text", "node", "[", "name", "]", "[", "attrib_key", "]", "=", "attrib_value", "end", "node", "else", "{", "name", "=>", "value", "}", "end", "end", "item_updates", "<<", "{", "set_item_field", ":", "field", ".", "merge", "(", "calendar_item", ":", "{", "sub_elements", ":", "item_attributes", "}", ")", "}", "else", "# Ignore unknown attribute", "end", "end", "if", "item_updates", ".", "any?", "data", "=", "{", "}", "data", "[", ":conflict_resolution", "]", "=", "options", "[", ":conflict_resolution", "]", "||", "'AutoResolve'", "data", "[", ":send_meeting_invitations_or_cancellations", "]", "=", "options", "[", ":send_meeting_invitations_or_cancellations", "]", "||", "'SendToNone'", "data", "[", ":item_changes", "]", "=", "[", "{", "item_id", ":", "self", ".", "item_id", ",", "updates", ":", "item_updates", "}", "]", "rm", "=", "ews", ".", "update_item", "(", "data", ")", ".", "response_messages", ".", "first", "if", "rm", "&&", "rm", ".", "success?", "self", ".", "get_all_properties!", "self", "else", "raise", "EwsCreateItemError", ",", "\"Could not update calendar item. #{rm.code}: #{rm.message_text}\"", "unless", "rm", "end", "end", "end"], "docstring": "Updates the specified item attributes\n\n Uses `SetItemField` if value is present and `DeleteItemField` if value is nil\n @param updates [Hash] with (:attribute => value)\n @param options [Hash]\n @option options :conflict_resolution [String] one of 'NeverOverwrite', 'AutoResolve' (default) or 'AlwaysOverwrite'\n @option options :send_meeting_invitations_or_cancellations [String] one of 'SendToNone' (default), 'SendOnlyToAll',\n 'SendOnlyToChanged', 'SendToAllAndSaveCopy' or 'SendToChangedAndSaveCopy'\n @return [CalendarItem, false]\n @example Update Subject and Body\n item = #...\n item.update_item!(subject: 'New subject', body: 'New Body')\n @see http://msdn.microsoft.com/en-us/library/exchange/aa580254.aspx\n @todo AppendToItemField updates not implemented", "docstring_tokens": ["Updates", "the", "specified", "item", "attributes"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/calendar_item.rb#L57-L106", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_synchronization.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeSynchronization.sync_folder_hierarchy", "original_string": "def sync_folder_hierarchy(opts)\n opts = opts.clone\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.SyncFolderHierarchy {\n builder.nbuild.parent.default_namespace = @default_ns\n builder.folder_shape!(opts[:folder_shape])\n builder.sync_folder_id!(opts[:sync_folder_id]) if opts[:sync_folder_id]\n builder.sync_state!(opts[:sync_state]) if opts[:sync_state]\n }\n end\n end\n do_soap_request(req, response_class: EwsResponse)\n end", "language": "ruby", "code": "def sync_folder_hierarchy(opts)\n opts = opts.clone\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.SyncFolderHierarchy {\n builder.nbuild.parent.default_namespace = @default_ns\n builder.folder_shape!(opts[:folder_shape])\n builder.sync_folder_id!(opts[:sync_folder_id]) if opts[:sync_folder_id]\n builder.sync_state!(opts[:sync_state]) if opts[:sync_state]\n }\n end\n end\n do_soap_request(req, response_class: EwsResponse)\n end", "code_tokens": ["def", "sync_folder_hierarchy", "(", "opts", ")", "opts", "=", "opts", ".", "clone", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "if", "(", "type", "==", ":header", ")", "else", "builder", ".", "nbuild", ".", "SyncFolderHierarchy", "{", "builder", ".", "nbuild", ".", "parent", ".", "default_namespace", "=", "@default_ns", "builder", ".", "folder_shape!", "(", "opts", "[", ":folder_shape", "]", ")", "builder", ".", "sync_folder_id!", "(", "opts", "[", ":sync_folder_id", "]", ")", "if", "opts", "[", ":sync_folder_id", "]", "builder", ".", "sync_state!", "(", "opts", "[", ":sync_state", "]", ")", "if", "opts", "[", ":sync_state", "]", "}", "end", "end", "do_soap_request", "(", "req", ",", "response_class", ":", "EwsResponse", ")", "end"], "docstring": "Defines a request to synchronize a folder hierarchy on a client\n @see http://msdn.microsoft.com/en-us/library/aa580990.aspx\n @param [Hash] opts\n @option opts [Hash] :folder_shape The folder shape properties\n Ex: {:base_shape => 'Default', :additional_properties => 'bla bla bla'}\n @option opts [Hash] :sync_folder_id An optional Hash that represents a FolderId or\n DistinguishedFolderId.\n Ex: {:id => :inbox}\n @option opts [Hash] :sync_state The Base64 sync state id. If this is the\n first time syncing this does not need to be passed.", "docstring_tokens": ["Defines", "a", "request", "to", "synchronize", "a", "folder", "hierarchy", "on", "a", "client"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_synchronization.rb#L36-L50", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_synchronization.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeSynchronization.sync_folder_items", "original_string": "def sync_folder_items(opts)\n opts = opts.clone\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.SyncFolderItems {\n builder.nbuild.parent.default_namespace = @default_ns\n builder.item_shape!(opts[:item_shape])\n builder.sync_folder_id!(opts[:sync_folder_id]) if opts[:sync_folder_id]\n builder.sync_state!(opts[:sync_state]) if opts[:sync_state]\n builder.ignore!(opts[:ignore]) if opts[:ignore]\n builder.max_changes_returned!(opts[:max_changes_returned])\n builder.sync_scope!(opts[:sync_scope]) if opts[:sync_scope]\n }\n end\n end\n do_soap_request(req, response_class: EwsResponse)\n end", "language": "ruby", "code": "def sync_folder_items(opts)\n opts = opts.clone\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.SyncFolderItems {\n builder.nbuild.parent.default_namespace = @default_ns\n builder.item_shape!(opts[:item_shape])\n builder.sync_folder_id!(opts[:sync_folder_id]) if opts[:sync_folder_id]\n builder.sync_state!(opts[:sync_state]) if opts[:sync_state]\n builder.ignore!(opts[:ignore]) if opts[:ignore]\n builder.max_changes_returned!(opts[:max_changes_returned])\n builder.sync_scope!(opts[:sync_scope]) if opts[:sync_scope]\n }\n end\n end\n do_soap_request(req, response_class: EwsResponse)\n end", "code_tokens": ["def", "sync_folder_items", "(", "opts", ")", "opts", "=", "opts", ".", "clone", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "if", "(", "type", "==", ":header", ")", "else", "builder", ".", "nbuild", ".", "SyncFolderItems", "{", "builder", ".", "nbuild", ".", "parent", ".", "default_namespace", "=", "@default_ns", "builder", ".", "item_shape!", "(", "opts", "[", ":item_shape", "]", ")", "builder", ".", "sync_folder_id!", "(", "opts", "[", ":sync_folder_id", "]", ")", "if", "opts", "[", ":sync_folder_id", "]", "builder", ".", "sync_state!", "(", "opts", "[", ":sync_state", "]", ")", "if", "opts", "[", ":sync_state", "]", "builder", ".", "ignore!", "(", "opts", "[", ":ignore", "]", ")", "if", "opts", "[", ":ignore", "]", "builder", ".", "max_changes_returned!", "(", "opts", "[", ":max_changes_returned", "]", ")", "builder", ".", "sync_scope!", "(", "opts", "[", ":sync_scope", "]", ")", "if", "opts", "[", ":sync_scope", "]", "}", "end", "end", "do_soap_request", "(", "req", ",", "response_class", ":", "EwsResponse", ")", "end"], "docstring": "Synchronizes items between the Exchange server and the client\n @see http://msdn.microsoft.com/en-us/library/aa563967(v=EXCHG.140).aspx\n @param [Hash] opts\n @option opts [Hash] :item_shape The item shape properties\n Ex: {:base_shape => 'Default', :additional_properties => 'bla bla bla'}\n @option opts [Hash] :sync_folder_id A Hash that represents a FolderId or\n DistinguishedFolderId. [ Ex: {:id => :inbox} ] OPTIONAL\n @option opts [String] :sync_state The Base64 sync state id. If this is the\n first time syncing this does not need to be passed. OPTIONAL on first call\n @option opts [Array ] :ignore An Array of ItemIds for items to ignore\n during the sync process. Ex: [{:id => 'id1', :change_key => 'ck'}, {:id => 'id2'}]\n OPTIONAL\n @option opts [Integer] :max_changes_returned ('required') The amount of items to sync per call.\n @option opts [String] :sync_scope specifies whether just items or items and folder associated\n information are returned. OPTIONAL\n options: 'NormalItems' or 'NormalAndAssociatedItems'\n @example\n { :item_shape => {:base_shape => 'Default'},\n :sync_folder_id => {:id => :inbox},\n :sync_state => myBase64id,\n :max_changes_returned => 256 }", "docstring_tokens": ["Synchronizes", "items", "between", "the", "Exchange", "server", "and", "the", "client"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_synchronization.rb#L73-L90", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/mailbox_user.rb", "func_name": "Viewpoint::EWS::Types.MailboxUser.get_user_availability", "original_string": "def get_user_availability(email_address, start_time, end_time)\n opts = {\n mailbox_data: [ :email =>{:address => email_address} ],\n free_busy_view_options: {\n time_window: {start_time: start_time, end_time: end_time},\n }\n }\n resp = (Viewpoint::EWS::EWS.instance).ews.get_user_availability(opts)\n if(resp.status == 'Success')\n return resp.items\n else\n raise EwsError, \"GetUserAvailability produced an error: #{resp.code}: #{resp.message}\"\n end\n end", "language": "ruby", "code": "def get_user_availability(email_address, start_time, end_time)\n opts = {\n mailbox_data: [ :email =>{:address => email_address} ],\n free_busy_view_options: {\n time_window: {start_time: start_time, end_time: end_time},\n }\n }\n resp = (Viewpoint::EWS::EWS.instance).ews.get_user_availability(opts)\n if(resp.status == 'Success')\n return resp.items\n else\n raise EwsError, \"GetUserAvailability produced an error: #{resp.code}: #{resp.message}\"\n end\n end", "code_tokens": ["def", "get_user_availability", "(", "email_address", ",", "start_time", ",", "end_time", ")", "opts", "=", "{", "mailbox_data", ":", "[", ":email", "=>", "{", ":address", "=>", "email_address", "}", "]", ",", "free_busy_view_options", ":", "{", "time_window", ":", "{", "start_time", ":", "start_time", ",", "end_time", ":", "end_time", "}", ",", "}", "}", "resp", "=", "(", "Viewpoint", "::", "EWS", "::", "EWS", ".", "instance", ")", ".", "ews", ".", "get_user_availability", "(", "opts", ")", "if", "(", "resp", ".", "status", "==", "'Success'", ")", "return", "resp", ".", "items", "else", "raise", "EwsError", ",", "\"GetUserAvailability produced an error: #{resp.code}: #{resp.message}\"", "end", "end"], "docstring": "Get information about when the user with the given email address is available.\n @param [String] email_address The email address of the person to find availability for.\n @param [DateTime] start_time The start of the time range to check as an xs:dateTime.\n @param [DateTime] end_time The end of the time range to check as an xs:dateTime.\n @see http://msdn.microsoft.com/en-us/library/aa563800(v=exchg.140)", "docstring_tokens": ["Get", "information", "about", "when", "the", "user", "with", "the", "given", "email", "address", "is", "available", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/mailbox_user.rb#L64-L77", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/item.rb", "func_name": "Viewpoint::EWS::Types.Item.move!", "original_string": "def move!(new_folder)\n new_folder = new_folder.id if new_folder.kind_of?(GenericFolder)\n move_opts = {\n :to_folder_id => {:id => new_folder},\n :item_ids => [{:item_id => {:id => self.id}}]\n }\n resp = @ews.move_item(move_opts)\n rmsg = resp.response_messages[0]\n\n if rmsg.success?\n obj = rmsg.items.first\n itype = obj.keys.first\n obj[itype][:elems][0][:item_id][:attribs][:id]\n else\n raise EwsError, \"Could not move item. #{resp.code}: #{resp.message}\"\n end\n end", "language": "ruby", "code": "def move!(new_folder)\n new_folder = new_folder.id if new_folder.kind_of?(GenericFolder)\n move_opts = {\n :to_folder_id => {:id => new_folder},\n :item_ids => [{:item_id => {:id => self.id}}]\n }\n resp = @ews.move_item(move_opts)\n rmsg = resp.response_messages[0]\n\n if rmsg.success?\n obj = rmsg.items.first\n itype = obj.keys.first\n obj[itype][:elems][0][:item_id][:attribs][:id]\n else\n raise EwsError, \"Could not move item. #{resp.code}: #{resp.message}\"\n end\n end", "code_tokens": ["def", "move!", "(", "new_folder", ")", "new_folder", "=", "new_folder", ".", "id", "if", "new_folder", ".", "kind_of?", "(", "GenericFolder", ")", "move_opts", "=", "{", ":to_folder_id", "=>", "{", ":id", "=>", "new_folder", "}", ",", ":item_ids", "=>", "[", "{", ":item_id", "=>", "{", ":id", "=>", "self", ".", "id", "}", "}", "]", "}", "resp", "=", "@ews", ".", "move_item", "(", "move_opts", ")", "rmsg", "=", "resp", ".", "response_messages", "[", "0", "]", "if", "rmsg", ".", "success?", "obj", "=", "rmsg", ".", "items", ".", "first", "itype", "=", "obj", ".", "keys", ".", "first", "obj", "[", "itype", "]", "[", ":elems", "]", "[", "0", "]", "[", ":item_id", "]", "[", ":attribs", "]", "[", ":id", "]", "else", "raise", "EwsError", ",", "\"Could not move item. #{resp.code}: #{resp.message}\"", "end", "end"], "docstring": "Move this item to a new folder\n @param [String,Symbol,GenericFolder] new_folder The new folder to move it to. This should\n be a subclass of GenericFolder, a DistinguishedFolderId (must me a Symbol) or a FolderId (String)\n @return [String] the new Id of the moved item", "docstring_tokens": ["Move", "this", "item", "to", "a", "new", "folder"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/item.rb#L137-L153", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/item.rb", "func_name": "Viewpoint::EWS::Types.Item.copy", "original_string": "def copy(new_folder)\n new_folder = new_folder.id if new_folder.kind_of?(GenericFolder)\n copy_opts = {\n :to_folder_id => {:id => new_folder},\n :item_ids => [{:item_id => {:id => self.id}}]\n }\n resp = @ews.copy_item(copy_opts)\n rmsg = resp.response_messages[0]\n\n if rmsg.success?\n obj = rmsg.items.first\n itype = obj.keys.first\n obj[itype][:elems][0][:item_id][:attribs][:id]\n else\n raise EwsError, \"Could not copy item. #{rmsg.response_code}: #{rmsg.message_text}\"\n end\n end", "language": "ruby", "code": "def copy(new_folder)\n new_folder = new_folder.id if new_folder.kind_of?(GenericFolder)\n copy_opts = {\n :to_folder_id => {:id => new_folder},\n :item_ids => [{:item_id => {:id => self.id}}]\n }\n resp = @ews.copy_item(copy_opts)\n rmsg = resp.response_messages[0]\n\n if rmsg.success?\n obj = rmsg.items.first\n itype = obj.keys.first\n obj[itype][:elems][0][:item_id][:attribs][:id]\n else\n raise EwsError, \"Could not copy item. #{rmsg.response_code}: #{rmsg.message_text}\"\n end\n end", "code_tokens": ["def", "copy", "(", "new_folder", ")", "new_folder", "=", "new_folder", ".", "id", "if", "new_folder", ".", "kind_of?", "(", "GenericFolder", ")", "copy_opts", "=", "{", ":to_folder_id", "=>", "{", ":id", "=>", "new_folder", "}", ",", ":item_ids", "=>", "[", "{", ":item_id", "=>", "{", ":id", "=>", "self", ".", "id", "}", "}", "]", "}", "resp", "=", "@ews", ".", "copy_item", "(", "copy_opts", ")", "rmsg", "=", "resp", ".", "response_messages", "[", "0", "]", "if", "rmsg", ".", "success?", "obj", "=", "rmsg", ".", "items", ".", "first", "itype", "=", "obj", ".", "keys", ".", "first", "obj", "[", "itype", "]", "[", ":elems", "]", "[", "0", "]", "[", ":item_id", "]", "[", ":attribs", "]", "[", ":id", "]", "else", "raise", "EwsError", ",", "\"Could not copy item. #{rmsg.response_code}: #{rmsg.message_text}\"", "end", "end"], "docstring": "Copy this item to a new folder\n @param [String,Symbol,GenericFolder] new_folder The new folder to move it to. This should\n be a subclass of GenericFolder, a DistinguishedFolderId (must me a Symbol) or a FolderId (String)\n @return [String] the new Id of the copied item", "docstring_tokens": ["Copy", "this", "item", "to", "a", "new", "folder"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/item.rb#L159-L175", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/item.rb", "func_name": "Viewpoint::EWS::Types.Item.get_item", "original_string": "def get_item(opts = {})\n args = get_item_args(opts)\n resp = ews.get_item(args)\n get_item_parser(resp)\n end", "language": "ruby", "code": "def get_item(opts = {})\n args = get_item_args(opts)\n resp = ews.get_item(args)\n get_item_parser(resp)\n end", "code_tokens": ["def", "get_item", "(", "opts", "=", "{", "}", ")", "args", "=", "get_item_args", "(", "opts", ")", "resp", "=", "ews", ".", "get_item", "(", "args", ")", "get_item_parser", "(", "resp", ")", "end"], "docstring": "Get a specific item by its ID.\n @param [Hash] opts Misc options to control request\n @option opts [String] :base_shape IdOnly/Default/AllProperties\n @raise [EwsError] raised when the backend SOAP method returns an error.", "docstring_tokens": ["Get", "a", "specific", "item", "by", "its", "ID", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/item.rb#L317-L321", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/item.rb", "func_name": "Viewpoint::EWS::Types.Item.dispatch_create_item!", "original_string": "def dispatch_create_item!(msg)\n if msg.has_attachments?\n draft = msg.draft\n msg.draft = true\n resp = validate_created_item(ews.create_item(msg.to_ews))\n msg.file_attachments.each do |f|\n next unless f.kind_of?(File)\n resp.add_file_attachment(f)\n end\n if draft\n resp.submit_attachments!\n resp\n else\n resp.submit!\n end\n else\n resp = ews.create_item(msg.to_ews)\n validate_created_item resp\n end\n end", "language": "ruby", "code": "def dispatch_create_item!(msg)\n if msg.has_attachments?\n draft = msg.draft\n msg.draft = true\n resp = validate_created_item(ews.create_item(msg.to_ews))\n msg.file_attachments.each do |f|\n next unless f.kind_of?(File)\n resp.add_file_attachment(f)\n end\n if draft\n resp.submit_attachments!\n resp\n else\n resp.submit!\n end\n else\n resp = ews.create_item(msg.to_ews)\n validate_created_item resp\n end\n end", "code_tokens": ["def", "dispatch_create_item!", "(", "msg", ")", "if", "msg", ".", "has_attachments?", "draft", "=", "msg", ".", "draft", "msg", ".", "draft", "=", "true", "resp", "=", "validate_created_item", "(", "ews", ".", "create_item", "(", "msg", ".", "to_ews", ")", ")", "msg", ".", "file_attachments", ".", "each", "do", "|", "f", "|", "next", "unless", "f", ".", "kind_of?", "(", "File", ")", "resp", ".", "add_file_attachment", "(", "f", ")", "end", "if", "draft", "resp", ".", "submit_attachments!", "resp", "else", "resp", ".", "submit!", "end", "else", "resp", "=", "ews", ".", "create_item", "(", "msg", ".", "to_ews", ")", "validate_created_item", "resp", "end", "end"], "docstring": "Handles the CreateItem call for Forward, ReplyTo, and ReplyAllTo\n It will handle the neccessary actions for adding attachments.", "docstring_tokens": ["Handles", "the", "CreateItem", "call", "for", "Forward", "ReplyTo", "and", "ReplyAllTo", "It", "will", "handle", "the", "neccessary", "actions", "for", "adding", "attachments", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/item.rb#L405-L424", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/item.rb", "func_name": "Viewpoint::EWS::Types.Item.validate_created_item", "original_string": "def validate_created_item(response)\n msg = response.response_messages[0]\n\n if(msg.status == 'Success')\n msg.items.empty? ? true : parse_created_item(msg.items.first)\n else\n raise EwsCreateItemError, \"#{msg.code}: #{msg.message_text}\"\n end\n end", "language": "ruby", "code": "def validate_created_item(response)\n msg = response.response_messages[0]\n\n if(msg.status == 'Success')\n msg.items.empty? ? true : parse_created_item(msg.items.first)\n else\n raise EwsCreateItemError, \"#{msg.code}: #{msg.message_text}\"\n end\n end", "code_tokens": ["def", "validate_created_item", "(", "response", ")", "msg", "=", "response", ".", "response_messages", "[", "0", "]", "if", "(", "msg", ".", "status", "==", "'Success'", ")", "msg", ".", "items", ".", "empty?", "?", "true", ":", "parse_created_item", "(", "msg", ".", "items", ".", "first", ")", "else", "raise", "EwsCreateItemError", ",", "\"#{msg.code}: #{msg.message_text}\"", "end", "end"], "docstring": "validate the CreateItem response.\n @return [Boolean, Item] returns true if items is empty and status is\n \"Success\" if items is not empty it will return the first Item since\n we are only dealing with single items here.\n @raise EwsCreateItemError on failure", "docstring_tokens": ["validate", "the", "CreateItem", "response", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/item.rb#L431-L439", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/generic_folder.rb", "func_name": "Viewpoint::EWS::Types.GenericFolder.items_since", "original_string": "def items_since(date_time, opts = {})\n opts = opts.clone\n unless date_time.kind_of?(Date)\n raise EwsBadArgumentError, \"First argument must be a Date or DateTime\"\n end\n restr = {:restriction =>\n {:is_greater_than_or_equal_to =>\n [{:field_uRI => {:field_uRI=>'item:DateTimeReceived'}},\n {:field_uRI_or_constant =>{:constant => {:value=>date_time.to_datetime}}}]\n }}\n items(opts.merge(restr))\n end", "language": "ruby", "code": "def items_since(date_time, opts = {})\n opts = opts.clone\n unless date_time.kind_of?(Date)\n raise EwsBadArgumentError, \"First argument must be a Date or DateTime\"\n end\n restr = {:restriction =>\n {:is_greater_than_or_equal_to =>\n [{:field_uRI => {:field_uRI=>'item:DateTimeReceived'}},\n {:field_uRI_or_constant =>{:constant => {:value=>date_time.to_datetime}}}]\n }}\n items(opts.merge(restr))\n end", "code_tokens": ["def", "items_since", "(", "date_time", ",", "opts", "=", "{", "}", ")", "opts", "=", "opts", ".", "clone", "unless", "date_time", ".", "kind_of?", "(", "Date", ")", "raise", "EwsBadArgumentError", ",", "\"First argument must be a Date or DateTime\"", "end", "restr", "=", "{", ":restriction", "=>", "{", ":is_greater_than_or_equal_to", "=>", "[", "{", ":field_uRI", "=>", "{", ":field_uRI", "=>", "'item:DateTimeReceived'", "}", "}", ",", "{", ":field_uRI_or_constant", "=>", "{", ":constant", "=>", "{", ":value", "=>", "date_time", ".", "to_datetime", "}", "}", "}", "]", "}", "}", "items", "(", "opts", ".", "merge", "(", "restr", ")", ")", "end"], "docstring": "Fetch items since a give DateTime\n @param [DateTime] date_time the time to fetch Items since.", "docstring_tokens": ["Fetch", "items", "since", "a", "give", "DateTime"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/generic_folder.rb#L85-L96", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/generic_folder.rb", "func_name": "Viewpoint::EWS::Types.GenericFolder.items_between", "original_string": "def items_between(start_date, end_date, opts={})\n items do |obj|\n obj.restriction = { :and =>\n [\n {:is_greater_than_or_equal_to =>\n [\n {:field_uRI => {:field_uRI=>'item:DateTimeReceived'}},\n {:field_uRI_or_constant=>{:constant => {:value =>start_date}}}\n ]\n },\n {:is_less_than_or_equal_to =>\n [\n {:field_uRI => {:field_uRI=>'item:DateTimeReceived'}},\n {:field_uRI_or_constant=>{:constant => {:value =>end_date}}}\n ]\n }\n ]\n }\n end\n end", "language": "ruby", "code": "def items_between(start_date, end_date, opts={})\n items do |obj|\n obj.restriction = { :and =>\n [\n {:is_greater_than_or_equal_to =>\n [\n {:field_uRI => {:field_uRI=>'item:DateTimeReceived'}},\n {:field_uRI_or_constant=>{:constant => {:value =>start_date}}}\n ]\n },\n {:is_less_than_or_equal_to =>\n [\n {:field_uRI => {:field_uRI=>'item:DateTimeReceived'}},\n {:field_uRI_or_constant=>{:constant => {:value =>end_date}}}\n ]\n }\n ]\n }\n end\n end", "code_tokens": ["def", "items_between", "(", "start_date", ",", "end_date", ",", "opts", "=", "{", "}", ")", "items", "do", "|", "obj", "|", "obj", ".", "restriction", "=", "{", ":and", "=>", "[", "{", ":is_greater_than_or_equal_to", "=>", "[", "{", ":field_uRI", "=>", "{", ":field_uRI", "=>", "'item:DateTimeReceived'", "}", "}", ",", "{", ":field_uRI_or_constant", "=>", "{", ":constant", "=>", "{", ":value", "=>", "start_date", "}", "}", "}", "]", "}", ",", "{", ":is_less_than_or_equal_to", "=>", "[", "{", ":field_uRI", "=>", "{", ":field_uRI", "=>", "'item:DateTimeReceived'", "}", "}", ",", "{", ":field_uRI_or_constant", "=>", "{", ":constant", "=>", "{", ":value", "=>", "end_date", "}", "}", "}", "]", "}", "]", "}", "end", "end"], "docstring": "Fetch items between a given time period\n @param [DateTime] start_date the time to start fetching Items from\n @param [DateTime] end_date the time to stop fetching Items from", "docstring_tokens": ["Fetch", "items", "between", "a", "given", "time", "period"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/generic_folder.rb#L106-L125", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/generic_folder.rb", "func_name": "Viewpoint::EWS::Types.GenericFolder.search_by_subject", "original_string": "def search_by_subject(match_str, exclude_str = nil)\n items do |obj|\n match = {:contains => {\n :containment_mode => 'Substring',\n :containment_comparison => 'IgnoreCase',\n :field_uRI => {:field_uRI=>'item:Subject'},\n :constant => {:value =>match_str}\n }}\n unless exclude_str.nil?\n excl = {:not =>\n {:contains => {\n :containment_mode => 'Substring',\n :containment_comparison => 'IgnoreCase',\n :field_uRI => {:field_uRI=>'item:Subject'},\n :constant => {:value =>exclude_str}\n }}\n }\n\n match[:and] = [{:contains => match.delete(:contains)}, excl]\n end\n obj.restriction = match\n end\n end", "language": "ruby", "code": "def search_by_subject(match_str, exclude_str = nil)\n items do |obj|\n match = {:contains => {\n :containment_mode => 'Substring',\n :containment_comparison => 'IgnoreCase',\n :field_uRI => {:field_uRI=>'item:Subject'},\n :constant => {:value =>match_str}\n }}\n unless exclude_str.nil?\n excl = {:not =>\n {:contains => {\n :containment_mode => 'Substring',\n :containment_comparison => 'IgnoreCase',\n :field_uRI => {:field_uRI=>'item:Subject'},\n :constant => {:value =>exclude_str}\n }}\n }\n\n match[:and] = [{:contains => match.delete(:contains)}, excl]\n end\n obj.restriction = match\n end\n end", "code_tokens": ["def", "search_by_subject", "(", "match_str", ",", "exclude_str", "=", "nil", ")", "items", "do", "|", "obj", "|", "match", "=", "{", ":contains", "=>", "{", ":containment_mode", "=>", "'Substring'", ",", ":containment_comparison", "=>", "'IgnoreCase'", ",", ":field_uRI", "=>", "{", ":field_uRI", "=>", "'item:Subject'", "}", ",", ":constant", "=>", "{", ":value", "=>", "match_str", "}", "}", "}", "unless", "exclude_str", ".", "nil?", "excl", "=", "{", ":not", "=>", "{", ":contains", "=>", "{", ":containment_mode", "=>", "'Substring'", ",", ":containment_comparison", "=>", "'IgnoreCase'", ",", ":field_uRI", "=>", "{", ":field_uRI", "=>", "'item:Subject'", "}", ",", ":constant", "=>", "{", ":value", "=>", "exclude_str", "}", "}", "}", "}", "match", "[", ":and", "]", "=", "[", "{", ":contains", "=>", "match", ".", "delete", "(", ":contains", ")", "}", ",", "excl", "]", "end", "obj", ".", "restriction", "=", "match", "end", "end"], "docstring": "Search on the item subject\n @param [String] match_str A simple string paramater to match against the\n subject. The search ignores case and does not accept regexes... only strings.\n @param [String,nil] exclude_str A string to exclude from matches against\n the subject. This is optional.", "docstring_tokens": ["Search", "on", "the", "item", "subject"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/generic_folder.rb#L132-L154", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/generic_folder.rb", "func_name": "Viewpoint::EWS::Types.GenericFolder.sync_items!", "original_string": "def sync_items!(sync_state = nil, sync_amount = 256, sync_all = false, opts = {})\n item_shape = opts.has_key?(:item_shape) ? opts.delete(:item_shape) : {:base_shape => :default}\n sync_state ||= @sync_state\n\n resp = ews.sync_folder_items item_shape: item_shape,\n sync_folder_id: self.folder_id, max_changes_returned: sync_amount, sync_state: sync_state\n rmsg = resp.response_messages[0]\n\n if rmsg.success?\n @synced = rmsg.includes_last_item_in_range?\n @sync_state = rmsg.sync_state\n rhash = {}\n rmsg.changes.each do |c|\n ctype = c.keys.first\n rhash[ctype] = [] unless rhash.has_key?(ctype)\n if ctype == :delete || ctype == :read_flag_change\n rhash[ctype] << c[ctype][:elems][0][:item_id][:attribs]\n else\n type = c[ctype][:elems][0].keys.first\n item = class_by_name(type).new(ews, c[ctype][:elems][0][type])\n rhash[ctype] << item\n end\n end\n rhash\n else\n raise EwsError, \"Could not synchronize: #{rmsg.code}: #{rmsg.message_text}\"\n end\n end", "language": "ruby", "code": "def sync_items!(sync_state = nil, sync_amount = 256, sync_all = false, opts = {})\n item_shape = opts.has_key?(:item_shape) ? opts.delete(:item_shape) : {:base_shape => :default}\n sync_state ||= @sync_state\n\n resp = ews.sync_folder_items item_shape: item_shape,\n sync_folder_id: self.folder_id, max_changes_returned: sync_amount, sync_state: sync_state\n rmsg = resp.response_messages[0]\n\n if rmsg.success?\n @synced = rmsg.includes_last_item_in_range?\n @sync_state = rmsg.sync_state\n rhash = {}\n rmsg.changes.each do |c|\n ctype = c.keys.first\n rhash[ctype] = [] unless rhash.has_key?(ctype)\n if ctype == :delete || ctype == :read_flag_change\n rhash[ctype] << c[ctype][:elems][0][:item_id][:attribs]\n else\n type = c[ctype][:elems][0].keys.first\n item = class_by_name(type).new(ews, c[ctype][:elems][0][type])\n rhash[ctype] << item\n end\n end\n rhash\n else\n raise EwsError, \"Could not synchronize: #{rmsg.code}: #{rmsg.message_text}\"\n end\n end", "code_tokens": ["def", "sync_items!", "(", "sync_state", "=", "nil", ",", "sync_amount", "=", "256", ",", "sync_all", "=", "false", ",", "opts", "=", "{", "}", ")", "item_shape", "=", "opts", ".", "has_key?", "(", ":item_shape", ")", "?", "opts", ".", "delete", "(", ":item_shape", ")", ":", "{", ":base_shape", "=>", ":default", "}", "sync_state", "||=", "@sync_state", "resp", "=", "ews", ".", "sync_folder_items", "item_shape", ":", "item_shape", ",", "sync_folder_id", ":", "self", ".", "folder_id", ",", "max_changes_returned", ":", "sync_amount", ",", "sync_state", ":", "sync_state", "rmsg", "=", "resp", ".", "response_messages", "[", "0", "]", "if", "rmsg", ".", "success?", "@synced", "=", "rmsg", ".", "includes_last_item_in_range?", "@sync_state", "=", "rmsg", ".", "sync_state", "rhash", "=", "{", "}", "rmsg", ".", "changes", ".", "each", "do", "|", "c", "|", "ctype", "=", "c", ".", "keys", ".", "first", "rhash", "[", "ctype", "]", "=", "[", "]", "unless", "rhash", ".", "has_key?", "(", "ctype", ")", "if", "ctype", "==", ":delete", "||", "ctype", "==", ":read_flag_change", "rhash", "[", "ctype", "]", "<<", "c", "[", "ctype", "]", "[", ":elems", "]", "[", "0", "]", "[", ":item_id", "]", "[", ":attribs", "]", "else", "type", "=", "c", "[", "ctype", "]", "[", ":elems", "]", "[", "0", "]", ".", "keys", ".", "first", "item", "=", "class_by_name", "(", "type", ")", ".", "new", "(", "ews", ",", "c", "[", "ctype", "]", "[", ":elems", "]", "[", "0", "]", "[", "type", "]", ")", "rhash", "[", "ctype", "]", "<<", "item", "end", "end", "rhash", "else", "raise", "EwsError", ",", "\"Could not synchronize: #{rmsg.code}: #{rmsg.message_text}\"", "end", "end"], "docstring": "Syncronize Items in this folder. If this method is issued multiple\n times it will continue where the last sync completed.\n @param [Integer] sync_amount The number of items to synchronize per sync\n @param [Boolean] sync_all Whether to sync all the data by looping through.\n The default is to just sync the first set. You can manually loop through\n with multiple calls to #sync_items!\n @return [Hash] Returns a hash with keys for each change type that ocurred.\n Possible key values are:\n (:create/:udpate/:delete/:read_flag_change).\n For :deleted and :read_flag_change items a simple hash with :id and\n :change_key is returned.\n See: http://msdn.microsoft.com/en-us/library/aa565609.aspx", "docstring_tokens": ["Syncronize", "Items", "in", "this", "folder", ".", "If", "this", "method", "is", "issued", "multiple", "times", "it", "will", "continue", "where", "the", "last", "sync", "completed", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/generic_folder.rb#L186-L213", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/generic_folder.rb", "func_name": "Viewpoint::EWS::Types.GenericFolder.subscribe", "original_string": "def subscribe(evtypes = [:all], watermark = nil, timeout = 240)\n # Refresh the subscription if already subscribed\n unsubscribe if subscribed?\n\n event_types = normalize_event_names(evtypes)\n folder = {id: self.id, change_key: self.change_key}\n resp = ews.pull_subscribe_folder(folder, event_types, timeout, watermark)\n rmsg = resp.response_messages.first\n if rmsg.success?\n @subscription_id = rmsg.subscription_id\n @watermark = rmsg.watermark\n true\n else\n raise EwsSubscriptionError, \"Could not subscribe: #{rmsg.code}: #{rmsg.message_text}\"\n end\n end", "language": "ruby", "code": "def subscribe(evtypes = [:all], watermark = nil, timeout = 240)\n # Refresh the subscription if already subscribed\n unsubscribe if subscribed?\n\n event_types = normalize_event_names(evtypes)\n folder = {id: self.id, change_key: self.change_key}\n resp = ews.pull_subscribe_folder(folder, event_types, timeout, watermark)\n rmsg = resp.response_messages.first\n if rmsg.success?\n @subscription_id = rmsg.subscription_id\n @watermark = rmsg.watermark\n true\n else\n raise EwsSubscriptionError, \"Could not subscribe: #{rmsg.code}: #{rmsg.message_text}\"\n end\n end", "code_tokens": ["def", "subscribe", "(", "evtypes", "=", "[", ":all", "]", ",", "watermark", "=", "nil", ",", "timeout", "=", "240", ")", "# Refresh the subscription if already subscribed", "unsubscribe", "if", "subscribed?", "event_types", "=", "normalize_event_names", "(", "evtypes", ")", "folder", "=", "{", "id", ":", "self", ".", "id", ",", "change_key", ":", "self", ".", "change_key", "}", "resp", "=", "ews", ".", "pull_subscribe_folder", "(", "folder", ",", "event_types", ",", "timeout", ",", "watermark", ")", "rmsg", "=", "resp", ".", "response_messages", ".", "first", "if", "rmsg", ".", "success?", "@subscription_id", "=", "rmsg", ".", "subscription_id", "@watermark", "=", "rmsg", ".", "watermark", "true", "else", "raise", "EwsSubscriptionError", ",", "\"Could not subscribe: #{rmsg.code}: #{rmsg.message_text}\"", "end", "end"], "docstring": "Subscribe this folder to events. This method initiates an Exchange pull\n type subscription.\n\n @param event_types [Array] Which event types to subscribe to. By default\n we subscribe to all Exchange event types: :all, :copied, :created,\n :deleted, :modified, :moved, :new_mail, :free_busy_changed\n @param watermark [String] pass a watermark if you wish to start the\n subscription at a specific point.\n @param timeout [Fixnum] the time in minutes that the subscription can\n remain idle between calls to #get_events. default: 240 minutes\n @return [Boolean] Did the subscription happen successfully?", "docstring_tokens": ["Subscribe", "this", "folder", "to", "events", ".", "This", "method", "initiates", "an", "Exchange", "pull", "type", "subscription", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/generic_folder.rb#L230-L245", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/generic_folder.rb", "func_name": "Viewpoint::EWS::Types.GenericFolder.unsubscribe", "original_string": "def unsubscribe\n return true if @subscription_id.nil?\n\n resp = ews.unsubscribe(@subscription_id)\n rmsg = resp.response_messages.first\n if rmsg.success?\n @subscription_id, @watermark = nil, nil\n true\n else\n raise EwsSubscriptionError, \"Could not unsubscribe: #{rmsg.code}: #{rmsg.message_text}\"\n end\n end", "language": "ruby", "code": "def unsubscribe\n return true if @subscription_id.nil?\n\n resp = ews.unsubscribe(@subscription_id)\n rmsg = resp.response_messages.first\n if rmsg.success?\n @subscription_id, @watermark = nil, nil\n true\n else\n raise EwsSubscriptionError, \"Could not unsubscribe: #{rmsg.code}: #{rmsg.message_text}\"\n end\n end", "code_tokens": ["def", "unsubscribe", "return", "true", "if", "@subscription_id", ".", "nil?", "resp", "=", "ews", ".", "unsubscribe", "(", "@subscription_id", ")", "rmsg", "=", "resp", ".", "response_messages", ".", "first", "if", "rmsg", ".", "success?", "@subscription_id", ",", "@watermark", "=", "nil", ",", "nil", "true", "else", "raise", "EwsSubscriptionError", ",", "\"Could not unsubscribe: #{rmsg.code}: #{rmsg.message_text}\"", "end", "end"], "docstring": "Unsubscribe this folder from further Exchange events.\n @return [Boolean] Did we unsubscribe successfully?", "docstring_tokens": ["Unsubscribe", "this", "folder", "from", "further", "Exchange", "events", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/generic_folder.rb#L270-L281", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/generic_folder.rb", "func_name": "Viewpoint::EWS::Types.GenericFolder.get_events", "original_string": "def get_events\n begin\n if subscribed?\n resp = ews.get_events(@subscription_id, @watermark)\n rmsg = resp.response_messages[0]\n @watermark = rmsg.new_watermark\n # @todo if parms[:more_events] # get more events\n rmsg.events.collect{|ev|\n type = ev.keys.first\n class_by_name(type).new(ews, ev[type])\n }\n else\n raise EwsSubscriptionError, \"Folder <#{self.display_name}> not subscribed to. Issue a Folder#subscribe before checking events.\"\n end\n rescue EwsSubscriptionTimeout => e\n @subscription_id, @watermark = nil, nil\n raise e\n end\n end", "language": "ruby", "code": "def get_events\n begin\n if subscribed?\n resp = ews.get_events(@subscription_id, @watermark)\n rmsg = resp.response_messages[0]\n @watermark = rmsg.new_watermark\n # @todo if parms[:more_events] # get more events\n rmsg.events.collect{|ev|\n type = ev.keys.first\n class_by_name(type).new(ews, ev[type])\n }\n else\n raise EwsSubscriptionError, \"Folder <#{self.display_name}> not subscribed to. Issue a Folder#subscribe before checking events.\"\n end\n rescue EwsSubscriptionTimeout => e\n @subscription_id, @watermark = nil, nil\n raise e\n end\n end", "code_tokens": ["def", "get_events", "begin", "if", "subscribed?", "resp", "=", "ews", ".", "get_events", "(", "@subscription_id", ",", "@watermark", ")", "rmsg", "=", "resp", ".", "response_messages", "[", "0", "]", "@watermark", "=", "rmsg", ".", "new_watermark", "# @todo if parms[:more_events] # get more events", "rmsg", ".", "events", ".", "collect", "{", "|", "ev", "|", "type", "=", "ev", ".", "keys", ".", "first", "class_by_name", "(", "type", ")", ".", "new", "(", "ews", ",", "ev", "[", "type", "]", ")", "}", "else", "raise", "EwsSubscriptionError", ",", "\"Folder <#{self.display_name}> not subscribed to. Issue a Folder#subscribe before checking events.\"", "end", "rescue", "EwsSubscriptionTimeout", "=>", "e", "@subscription_id", ",", "@watermark", "=", "nil", ",", "nil", "raise", "e", "end", "end"], "docstring": "Checks a subscribed folder for events\n @return [Array] An array of Event items", "docstring_tokens": ["Checks", "a", "subscribed", "folder", "for", "events"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/generic_folder.rb#L285-L303", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/generic_folder.rb", "func_name": "Viewpoint::EWS::Types.GenericFolder.get_folder", "original_string": "def get_folder(opts = {})\n args = get_folder_args(opts)\n resp = ews.get_folder(args)\n get_folder_parser(resp)\n end", "language": "ruby", "code": "def get_folder(opts = {})\n args = get_folder_args(opts)\n resp = ews.get_folder(args)\n get_folder_parser(resp)\n end", "code_tokens": ["def", "get_folder", "(", "opts", "=", "{", "}", ")", "args", "=", "get_folder_args", "(", "opts", ")", "resp", "=", "ews", ".", "get_folder", "(", "args", ")", "get_folder_parser", "(", "resp", ")", "end"], "docstring": "Get a specific folder by its ID.\n @param [Hash] opts Misc options to control request\n @option opts [String] :base_shape IdOnly/Default/AllProperties\n @raise [EwsError] raised when the backend SOAP method returns an error.", "docstring_tokens": ["Get", "a", "specific", "folder", "by", "its", "ID", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/generic_folder.rb#L341-L345", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_time_zones.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeTimeZones.get_time_zones", "original_string": "def get_time_zones(full = false, ids = nil)\n req = build_soap! do |type, builder|\n unless type == :header\n builder.get_server_time_zones!(full: full, ids: ids)\n end\n end\n result = do_soap_request req, response_class: EwsSoapResponse\n\n if result.success?\n zones = []\n result.response_messages.each do |message|\n elements = message[:get_server_time_zones_response_message][:elems][:time_zone_definitions][:elems]\n elements.each do |definition|\n data = {\n id: definition[:time_zone_definition][:attribs][:id],\n name: definition[:time_zone_definition][:attribs][:name]\n }\n zones << OpenStruct.new(data)\n end\n end\n zones\n else\n raise EwsError, \"Could not get time zones\"\n end\n end", "language": "ruby", "code": "def get_time_zones(full = false, ids = nil)\n req = build_soap! do |type, builder|\n unless type == :header\n builder.get_server_time_zones!(full: full, ids: ids)\n end\n end\n result = do_soap_request req, response_class: EwsSoapResponse\n\n if result.success?\n zones = []\n result.response_messages.each do |message|\n elements = message[:get_server_time_zones_response_message][:elems][:time_zone_definitions][:elems]\n elements.each do |definition|\n data = {\n id: definition[:time_zone_definition][:attribs][:id],\n name: definition[:time_zone_definition][:attribs][:name]\n }\n zones << OpenStruct.new(data)\n end\n end\n zones\n else\n raise EwsError, \"Could not get time zones\"\n end\n end", "code_tokens": ["def", "get_time_zones", "(", "full", "=", "false", ",", "ids", "=", "nil", ")", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "unless", "type", "==", ":header", "builder", ".", "get_server_time_zones!", "(", "full", ":", "full", ",", "ids", ":", "ids", ")", "end", "end", "result", "=", "do_soap_request", "req", ",", "response_class", ":", "EwsSoapResponse", "if", "result", ".", "success?", "zones", "=", "[", "]", "result", ".", "response_messages", ".", "each", "do", "|", "message", "|", "elements", "=", "message", "[", ":get_server_time_zones_response_message", "]", "[", ":elems", "]", "[", ":time_zone_definitions", "]", "[", ":elems", "]", "elements", ".", "each", "do", "|", "definition", "|", "data", "=", "{", "id", ":", "definition", "[", ":time_zone_definition", "]", "[", ":attribs", "]", "[", ":id", "]", ",", "name", ":", "definition", "[", ":time_zone_definition", "]", "[", ":attribs", "]", "[", ":name", "]", "}", "zones", "<<", "OpenStruct", ".", "new", "(", "data", ")", "end", "end", "zones", "else", "raise", "EwsError", ",", "\"Could not get time zones\"", "end", "end"], "docstring": "Request list of server known time zones\n @param full [Boolean] Request full time zone definition? Returns only name and id if false.\n @param ids [Array] Returns only the specified time zones instead of all if present\n @return [Array] Array of Objects responding to #id() and #name()\n @example Retrieving server time zones\n ews_client = Viewpoint::EWSClient.new # ...\n zones = ews_client.ews.get_time_zones\n @todo Implement TimeZoneDefinition with sub elements Periods, TransitionsGroups and Transitions", "docstring_tokens": ["Request", "list", "of", "server", "known", "time", "zones"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_time_zones.rb#L14-L38", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_data_services.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeDataServices.copy_folder", "original_string": "def copy_folder(to_folder_id, *sources)\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.CopyFolder {\n builder.nbuild.parent.default_namespace = @default_ns\n builder.to_folder_id!(to_folder_id)\n builder.folder_ids!(sources.flatten)\n }\n end\n end\n do_soap_request(req)\n end", "language": "ruby", "code": "def copy_folder(to_folder_id, *sources)\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.CopyFolder {\n builder.nbuild.parent.default_namespace = @default_ns\n builder.to_folder_id!(to_folder_id)\n builder.folder_ids!(sources.flatten)\n }\n end\n end\n do_soap_request(req)\n end", "code_tokens": ["def", "copy_folder", "(", "to_folder_id", ",", "*", "sources", ")", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "if", "(", "type", "==", ":header", ")", "else", "builder", ".", "nbuild", ".", "CopyFolder", "{", "builder", ".", "nbuild", ".", "parent", ".", "default_namespace", "=", "@default_ns", "builder", ".", "to_folder_id!", "(", "to_folder_id", ")", "builder", ".", "folder_ids!", "(", "sources", ".", "flatten", ")", "}", "end", "end", "do_soap_request", "(", "req", ")", "end"], "docstring": "Defines a request to copy folders in the Exchange store\n @see http://msdn.microsoft.com/en-us/library/aa563949.aspx\n @param [Hash] to_folder_id The target FolderId\n {:id => , :change_key => }\n @param [Array] *sources The source Folders\n {:id => , :change_key => },\n {:id => , :change_key => }", "docstring_tokens": ["Defines", "a", "request", "to", "copy", "folders", "in", "the", "Exchange", "store"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_data_services.rb#L428-L440", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_data_services.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeDataServices.move_folder", "original_string": "def move_folder(to_folder_id, *sources)\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.MoveFolder {\n builder.nbuild.parent.default_namespace = @default_ns\n builder.to_folder_id!(to_folder_id)\n builder.folder_ids!(sources.flatten)\n }\n end\n end\n do_soap_request(req)\n end", "language": "ruby", "code": "def move_folder(to_folder_id, *sources)\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.MoveFolder {\n builder.nbuild.parent.default_namespace = @default_ns\n builder.to_folder_id!(to_folder_id)\n builder.folder_ids!(sources.flatten)\n }\n end\n end\n do_soap_request(req)\n end", "code_tokens": ["def", "move_folder", "(", "to_folder_id", ",", "*", "sources", ")", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "if", "(", "type", "==", ":header", ")", "else", "builder", ".", "nbuild", ".", "MoveFolder", "{", "builder", ".", "nbuild", ".", "parent", ".", "default_namespace", "=", "@default_ns", "builder", ".", "to_folder_id!", "(", "to_folder_id", ")", "builder", ".", "folder_ids!", "(", "sources", ".", "flatten", ")", "}", "end", "end", "do_soap_request", "(", "req", ")", "end"], "docstring": "Defines a request to move folders in the Exchange store\n @see http://msdn.microsoft.com/en-us/library/aa566202.aspx\n @param [Hash] to_folder_id The target FolderId\n {:id => , :change_key => }\n @param [Array] *sources The source Folders\n {:id => , :change_key => },\n {:id => , :change_key => }", "docstring_tokens": ["Defines", "a", "request", "to", "move", "folders", "in", "the", "Exchange", "store"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_data_services.rb#L548-L560", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_data_services.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeDataServices.update_folder", "original_string": "def update_folder(folder_changes)\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.UpdateFolder {\n builder.nbuild.parent.default_namespace = @default_ns\n builder.nbuild.FolderChanges {\n folder_changes.each do |fc|\n builder[NS_EWS_TYPES].FolderChange {\n builder.dispatch_folder_id!(fc)\n builder[NS_EWS_TYPES].Updates {\n # @todo finish implementation\n }\n }\n end\n }\n }\n end\n end\n do_soap_request(req)\n end", "language": "ruby", "code": "def update_folder(folder_changes)\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.UpdateFolder {\n builder.nbuild.parent.default_namespace = @default_ns\n builder.nbuild.FolderChanges {\n folder_changes.each do |fc|\n builder[NS_EWS_TYPES].FolderChange {\n builder.dispatch_folder_id!(fc)\n builder[NS_EWS_TYPES].Updates {\n # @todo finish implementation\n }\n }\n end\n }\n }\n end\n end\n do_soap_request(req)\n end", "code_tokens": ["def", "update_folder", "(", "folder_changes", ")", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "if", "(", "type", "==", ":header", ")", "else", "builder", ".", "nbuild", ".", "UpdateFolder", "{", "builder", ".", "nbuild", ".", "parent", ".", "default_namespace", "=", "@default_ns", "builder", ".", "nbuild", ".", "FolderChanges", "{", "folder_changes", ".", "each", "do", "|", "fc", "|", "builder", "[", "NS_EWS_TYPES", "]", ".", "FolderChange", "{", "builder", ".", "dispatch_folder_id!", "(", "fc", ")", "builder", "[", "NS_EWS_TYPES", "]", ".", "Updates", "{", "# @todo finish implementation", "}", "}", "end", "}", "}", "end", "end", "do_soap_request", "(", "req", ")", "end"], "docstring": "Update properties for a specified folder\n There is a lot more building in this method because most of the builders\n are only used for this operation so there was no need to externalize them\n for re-use.\n @see http://msdn.microsoft.com/en-us/library/aa580519(v=EXCHG.140).aspx\n @param [Array] folder_changes an Array of well formatted Hashes", "docstring_tokens": ["Update", "properties", "for", "a", "specified", "folder", "There", "is", "a", "lot", "more", "building", "in", "this", "method", "because", "most", "of", "the", "builders", "are", "only", "used", "for", "this", "operation", "so", "there", "was", "no", "need", "to", "externalize", "them", "for", "re", "-", "use", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_data_services.rb#L568-L588", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_data_services.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeDataServices.empty_folder", "original_string": "def empty_folder(opts)\n validate_version(VERSION_2010_SP1)\n ef_opts = {}\n [:delete_type, :delete_sub_folders].each do |k|\n ef_opts[camel_case(k)] = validate_param(opts, k, true)\n end\n fids = validate_param opts, :folder_ids, true\n\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.EmptyFolder(ef_opts) {|x|\n builder.nbuild.parent.default_namespace = @default_ns\n builder.folder_ids!(fids)\n }\n end\n end\n do_soap_request(req)\n end", "language": "ruby", "code": "def empty_folder(opts)\n validate_version(VERSION_2010_SP1)\n ef_opts = {}\n [:delete_type, :delete_sub_folders].each do |k|\n ef_opts[camel_case(k)] = validate_param(opts, k, true)\n end\n fids = validate_param opts, :folder_ids, true\n\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.EmptyFolder(ef_opts) {|x|\n builder.nbuild.parent.default_namespace = @default_ns\n builder.folder_ids!(fids)\n }\n end\n end\n do_soap_request(req)\n end", "code_tokens": ["def", "empty_folder", "(", "opts", ")", "validate_version", "(", "VERSION_2010_SP1", ")", "ef_opts", "=", "{", "}", "[", ":delete_type", ",", ":delete_sub_folders", "]", ".", "each", "do", "|", "k", "|", "ef_opts", "[", "camel_case", "(", "k", ")", "]", "=", "validate_param", "(", "opts", ",", "k", ",", "true", ")", "end", "fids", "=", "validate_param", "opts", ",", ":folder_ids", ",", "true", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "if", "(", "type", "==", ":header", ")", "else", "builder", ".", "nbuild", ".", "EmptyFolder", "(", "ef_opts", ")", "{", "|", "x", "|", "builder", ".", "nbuild", ".", "parent", ".", "default_namespace", "=", "@default_ns", "builder", ".", "folder_ids!", "(", "fids", ")", "}", "end", "end", "do_soap_request", "(", "req", ")", "end"], "docstring": "Empties folders in a mailbox.\n @see http://msdn.microsoft.com/en-us/library/ff709484.aspx\n @param [Hash] opts\n @option opts [String] :delete_type Must be one of\n ExchangeDataServices::HARD_DELETE, SOFT_DELETE, or MOVE_TO_DELETED_ITEMS\n @option opts [Boolean] :delete_sub_folders\n @option opts [Array] :folder_ids An array of folder_ids in the form:\n [ {:id => 'myfolderID##asdfs', :change_key => 'asdfasdf'},\n {:id => 'blah'} ]\n @todo Finish", "docstring_tokens": ["Empties", "folders", "in", "a", "mailbox", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_data_services.rb#L600-L618", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_data_services.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeDataServices.create_attachment", "original_string": "def create_attachment(opts)\n opts = opts.clone\n [:parent_id].each do |k|\n validate_param(opts, k, true)\n end\n validate_param(opts, :files, false, [])\n validate_param(opts, :items, false, [])\n\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.CreateAttachment {|x|\n builder.nbuild.parent.default_namespace = @default_ns\n builder.parent_item_id!(opts[:parent_id])\n x.Attachments {\n opts[:files].each do |fa|\n builder.file_attachment!(fa)\n end\n opts[:items].each do |ia|\n builder.item_attachment!(ia)\n end\n opts[:inline_files].each do |fi|\n builder.inline_attachment!(fi)\n end\n }\n }\n end\n end\n do_soap_request(req, response_class: EwsResponse)\n end", "language": "ruby", "code": "def create_attachment(opts)\n opts = opts.clone\n [:parent_id].each do |k|\n validate_param(opts, k, true)\n end\n validate_param(opts, :files, false, [])\n validate_param(opts, :items, false, [])\n\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.CreateAttachment {|x|\n builder.nbuild.parent.default_namespace = @default_ns\n builder.parent_item_id!(opts[:parent_id])\n x.Attachments {\n opts[:files].each do |fa|\n builder.file_attachment!(fa)\n end\n opts[:items].each do |ia|\n builder.item_attachment!(ia)\n end\n opts[:inline_files].each do |fi|\n builder.inline_attachment!(fi)\n end\n }\n }\n end\n end\n do_soap_request(req, response_class: EwsResponse)\n end", "code_tokens": ["def", "create_attachment", "(", "opts", ")", "opts", "=", "opts", ".", "clone", "[", ":parent_id", "]", ".", "each", "do", "|", "k", "|", "validate_param", "(", "opts", ",", "k", ",", "true", ")", "end", "validate_param", "(", "opts", ",", ":files", ",", "false", ",", "[", "]", ")", "validate_param", "(", "opts", ",", ":items", ",", "false", ",", "[", "]", ")", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "if", "(", "type", "==", ":header", ")", "else", "builder", ".", "nbuild", ".", "CreateAttachment", "{", "|", "x", "|", "builder", ".", "nbuild", ".", "parent", ".", "default_namespace", "=", "@default_ns", "builder", ".", "parent_item_id!", "(", "opts", "[", ":parent_id", "]", ")", "x", ".", "Attachments", "{", "opts", "[", ":files", "]", ".", "each", "do", "|", "fa", "|", "builder", ".", "file_attachment!", "(", "fa", ")", "end", "opts", "[", ":items", "]", ".", "each", "do", "|", "ia", "|", "builder", ".", "item_attachment!", "(", "ia", ")", "end", "opts", "[", ":inline_files", "]", ".", "each", "do", "|", "fi", "|", "builder", ".", "inline_attachment!", "(", "fi", ")", "end", "}", "}", "end", "end", "do_soap_request", "(", "req", ",", "response_class", ":", "EwsResponse", ")", "end"], "docstring": "Creates either an item or file attachment and attaches it to the specified item.\n @see http://msdn.microsoft.com/en-us/library/aa565877.aspx\n @param [Hash] opts\n @option opts [Hash] :parent_id {id: , change_key: }\n @option opts [Array] :files An Array of Base64 encoded Strings with\n an associated name:\n {:name => , :content => }\n @option opts [Array] :items Exchange Items to attach to this Item\n @todo Need to implement attachment of Item types", "docstring_tokens": ["Creates", "either", "an", "item", "or", "file", "attachment", "and", "attaches", "it", "to", "the", "specified", "item", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_data_services.rb#L657-L686", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_data_services.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeDataServices.resolve_names", "original_string": "def resolve_names(opts)\n opts = opts.clone\n fcd = opts.has_key?(:full_contact_data) ? opts[:full_contact_data] : true\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.ResolveNames {|x|\n x.parent['ReturnFullContactData'] = fcd.to_s\n x.parent['SearchScope'] = opts[:search_scope] if opts[:search_scope]\n x.parent.default_namespace = @default_ns\n # @todo builder.nbuild.ParentFolderIds\n x.UnresolvedEntry(opts[:name])\n }\n end\n end\n do_soap_request(req)\n end", "language": "ruby", "code": "def resolve_names(opts)\n opts = opts.clone\n fcd = opts.has_key?(:full_contact_data) ? opts[:full_contact_data] : true\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.ResolveNames {|x|\n x.parent['ReturnFullContactData'] = fcd.to_s\n x.parent['SearchScope'] = opts[:search_scope] if opts[:search_scope]\n x.parent.default_namespace = @default_ns\n # @todo builder.nbuild.ParentFolderIds\n x.UnresolvedEntry(opts[:name])\n }\n end\n end\n do_soap_request(req)\n end", "code_tokens": ["def", "resolve_names", "(", "opts", ")", "opts", "=", "opts", ".", "clone", "fcd", "=", "opts", ".", "has_key?", "(", ":full_contact_data", ")", "?", "opts", "[", ":full_contact_data", "]", ":", "true", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "if", "(", "type", "==", ":header", ")", "else", "builder", ".", "nbuild", ".", "ResolveNames", "{", "|", "x", "|", "x", ".", "parent", "[", "'ReturnFullContactData'", "]", "=", "fcd", ".", "to_s", "x", ".", "parent", "[", "'SearchScope'", "]", "=", "opts", "[", ":search_scope", "]", "if", "opts", "[", ":search_scope", "]", "x", ".", "parent", ".", "default_namespace", "=", "@default_ns", "# @todo builder.nbuild.ParentFolderIds", "x", ".", "UnresolvedEntry", "(", "opts", "[", ":name", "]", ")", "}", "end", "end", "do_soap_request", "(", "req", ")", "end"], "docstring": "Resolve ambiguous e-mail addresses and display names\n @see http://msdn.microsoft.com/en-us/library/aa565329.aspx ResolveNames\n @see http://msdn.microsoft.com/en-us/library/aa581054.aspx UnresolvedEntry\n @param [Hash] opts\n @option opts [String] :name the unresolved entry\n @option opts [Boolean] :full_contact_data (true) Whether or not to return\n the full contact details.\n @option opts [String] :search_scope where to seach for this entry, one of\n SOAP::Contacts, SOAP::ActiveDirectory, SOAP::ActiveDirectoryContacts\n (default), SOAP::ContactsActiveDirectory\n @option opts [String, FolderId] :parent_folder_id either the name of a\n folder or it's numerical ID.\n @see http://msdn.microsoft.com/en-us/library/aa565998.aspx", "docstring_tokens": ["Resolve", "ambiguous", "e", "-", "mail", "addresses", "and", "display", "names"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_data_services.rb#L732-L748", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_data_services.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeDataServices.convert_id", "original_string": "def convert_id(opts)\n opts = opts.clone\n\n [:id, :format, :destination_format, :mailbox ].each do |k|\n validate_param(opts, k, true)\n end\n\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.ConvertId {|x|\n builder.nbuild.parent.default_namespace = @default_ns\n x.parent['DestinationFormat'] = opts[:destination_format].to_s.camel_case\n x.SourceIds { |x|\n x[NS_EWS_TYPES].AlternateId { |x|\n x.parent['Format'] = opts[:format].to_s.camel_case\n x.parent['Id'] = opts[:id]\n x.parent['Mailbox'] = opts[:mailbox]\n }\n }\n }\n end\n end\n do_soap_request(req, response_class: EwsResponse)\n end", "language": "ruby", "code": "def convert_id(opts)\n opts = opts.clone\n\n [:id, :format, :destination_format, :mailbox ].each do |k|\n validate_param(opts, k, true)\n end\n\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.ConvertId {|x|\n builder.nbuild.parent.default_namespace = @default_ns\n x.parent['DestinationFormat'] = opts[:destination_format].to_s.camel_case\n x.SourceIds { |x|\n x[NS_EWS_TYPES].AlternateId { |x|\n x.parent['Format'] = opts[:format].to_s.camel_case\n x.parent['Id'] = opts[:id]\n x.parent['Mailbox'] = opts[:mailbox]\n }\n }\n }\n end\n end\n do_soap_request(req, response_class: EwsResponse)\n end", "code_tokens": ["def", "convert_id", "(", "opts", ")", "opts", "=", "opts", ".", "clone", "[", ":id", ",", ":format", ",", ":destination_format", ",", ":mailbox", "]", ".", "each", "do", "|", "k", "|", "validate_param", "(", "opts", ",", "k", ",", "true", ")", "end", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "if", "(", "type", "==", ":header", ")", "else", "builder", ".", "nbuild", ".", "ConvertId", "{", "|", "x", "|", "builder", ".", "nbuild", ".", "parent", ".", "default_namespace", "=", "@default_ns", "x", ".", "parent", "[", "'DestinationFormat'", "]", "=", "opts", "[", ":destination_format", "]", ".", "to_s", ".", "camel_case", "x", ".", "SourceIds", "{", "|", "x", "|", "x", "[", "NS_EWS_TYPES", "]", ".", "AlternateId", "{", "|", "x", "|", "x", ".", "parent", "[", "'Format'", "]", "=", "opts", "[", ":format", "]", ".", "to_s", ".", "camel_case", "x", ".", "parent", "[", "'Id'", "]", "=", "opts", "[", ":id", "]", "x", ".", "parent", "[", "'Mailbox'", "]", "=", "opts", "[", ":mailbox", "]", "}", "}", "}", "end", "end", "do_soap_request", "(", "req", ",", "response_class", ":", "EwsResponse", ")", "end"], "docstring": "Converts item and folder identifiers between formats.\n @see http://msdn.microsoft.com/en-us/library/bb799665.aspx\n @todo Needs to be finished", "docstring_tokens": ["Converts", "item", "and", "folder", "identifiers", "between", "formats", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_data_services.rb#L753-L777", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/types/calendar_folder.rb", "func_name": "Viewpoint::EWS::Types.CalendarFolder.create_item", "original_string": "def create_item(attributes, to_ews_create_opts = {})\n template = Viewpoint::EWS::Template::CalendarItem.new attributes\n template.saved_item_folder_id = {id: self.id, change_key: self.change_key}\n rm = ews.create_item(template.to_ews_create(to_ews_create_opts)).response_messages.first\n if rm && rm.success?\n CalendarItem.new ews, rm.items.first[:calendar_item][:elems].first\n else\n raise EwsCreateItemError, \"Could not create item in folder. #{rm.code}: #{rm.message_text}\" unless rm\n end\n end", "language": "ruby", "code": "def create_item(attributes, to_ews_create_opts = {})\n template = Viewpoint::EWS::Template::CalendarItem.new attributes\n template.saved_item_folder_id = {id: self.id, change_key: self.change_key}\n rm = ews.create_item(template.to_ews_create(to_ews_create_opts)).response_messages.first\n if rm && rm.success?\n CalendarItem.new ews, rm.items.first[:calendar_item][:elems].first\n else\n raise EwsCreateItemError, \"Could not create item in folder. #{rm.code}: #{rm.message_text}\" unless rm\n end\n end", "code_tokens": ["def", "create_item", "(", "attributes", ",", "to_ews_create_opts", "=", "{", "}", ")", "template", "=", "Viewpoint", "::", "EWS", "::", "Template", "::", "CalendarItem", ".", "new", "attributes", "template", ".", "saved_item_folder_id", "=", "{", "id", ":", "self", ".", "id", ",", "change_key", ":", "self", ".", "change_key", "}", "rm", "=", "ews", ".", "create_item", "(", "template", ".", "to_ews_create", "(", "to_ews_create_opts", ")", ")", ".", "response_messages", ".", "first", "if", "rm", "&&", "rm", ".", "success?", "CalendarItem", ".", "new", "ews", ",", "rm", ".", "items", ".", "first", "[", ":calendar_item", "]", "[", ":elems", "]", ".", "first", "else", "raise", "EwsCreateItemError", ",", "\"Could not create item in folder. #{rm.code}: #{rm.message_text}\"", "unless", "rm", "end", "end"], "docstring": "Creates a new appointment\n @param attributes [Hash] Parameters of the calendar item. Some example attributes are listed below.\n @option attributes :subject [String]\n @option attributes :start [Time]\n @option attributes :end [Time]\n @return [CalendarItem]\n @see Template::CalendarItem", "docstring_tokens": ["Creates", "a", "new", "appointment"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/types/calendar_folder.rb#L38-L47", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_web_service.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeWebService.get_user_availability", "original_string": "def get_user_availability(opts)\n opts = opts.clone\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.GetUserAvailabilityRequest {|x|\n x.parent.default_namespace = @default_ns\n builder.time_zone!(opts[:time_zone])\n builder.nbuild.MailboxDataArray {\n opts[:mailbox_data].each do |mbd|\n builder.mailbox_data!(mbd)\n end\n }\n builder.free_busy_view_options!(opts[:free_busy_view_options])\n builder.suggestions_view_options!(opts[:suggestions_view_options])\n }\n end\n end\n\n do_soap_request(req, response_class: EwsSoapFreeBusyResponse)\n end", "language": "ruby", "code": "def get_user_availability(opts)\n opts = opts.clone\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.GetUserAvailabilityRequest {|x|\n x.parent.default_namespace = @default_ns\n builder.time_zone!(opts[:time_zone])\n builder.nbuild.MailboxDataArray {\n opts[:mailbox_data].each do |mbd|\n builder.mailbox_data!(mbd)\n end\n }\n builder.free_busy_view_options!(opts[:free_busy_view_options])\n builder.suggestions_view_options!(opts[:suggestions_view_options])\n }\n end\n end\n\n do_soap_request(req, response_class: EwsSoapFreeBusyResponse)\n end", "code_tokens": ["def", "get_user_availability", "(", "opts", ")", "opts", "=", "opts", ".", "clone", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "if", "(", "type", "==", ":header", ")", "else", "builder", ".", "nbuild", ".", "GetUserAvailabilityRequest", "{", "|", "x", "|", "x", ".", "parent", ".", "default_namespace", "=", "@default_ns", "builder", ".", "time_zone!", "(", "opts", "[", ":time_zone", "]", ")", "builder", ".", "nbuild", ".", "MailboxDataArray", "{", "opts", "[", ":mailbox_data", "]", ".", "each", "do", "|", "mbd", "|", "builder", ".", "mailbox_data!", "(", "mbd", ")", "end", "}", "builder", ".", "free_busy_view_options!", "(", "opts", "[", ":free_busy_view_options", "]", ")", "builder", ".", "suggestions_view_options!", "(", "opts", "[", ":suggestions_view_options", "]", ")", "}", "end", "end", "do_soap_request", "(", "req", ",", "response_class", ":", "EwsSoapFreeBusyResponse", ")", "end"], "docstring": "Provides detailed information about the availability of a set of users, rooms, and resources\n within a specified time window.\n @see http://msdn.microsoft.com/en-us/library/aa564001.aspx\n @param [Hash] opts\n @option opts [Hash] :time_zone The TimeZone data\n Example: {:bias => 'UTC offset in minutes',\n :standard_time => {:bias => 480, :time => '02:00:00',\n :day_order => 5, :month => 10, :day_of_week => 'Sunday'},\n :daylight_time => {same options as :standard_time}}\n @option opts [Array] :mailbox_data Data for the mailbox to query\n Example: [{:attendee_type => 'Organizer|Required|Optional|Room|Resource',\n :email =>{:name => 'name', :address => 'email', :routing_type => 'SMTP'},\n :exclude_conflicts => true|false }]\n @option opts [Hash] :free_busy_view_options\n Example: {:time_window => {:start_time => DateTime,:end_time => DateTime},\n :merged_free_busy_interval_in_minutes => minute_int,\n :requested_view => None|MergedOnly|FreeBusy|FreeBusyMerged|Detailed\n |DetailedMerged} (optional)\n @option opts [Hash] :suggestions_view_options (optional)\n @todo Finish out :suggestions_view_options", "docstring_tokens": ["Provides", "detailed", "information", "about", "the", "availability", "of", "a", "set", "of", "users", "rooms", "and", "resources", "within", "a", "specified", "time", "window", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_web_service.rb#L149-L169", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_web_service.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeWebService.get_rooms", "original_string": "def get_rooms(roomDistributionList)\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.GetRooms {|x|\n x.parent.default_namespace = @default_ns\n builder.room_list!(roomDistributionList)\n }\n end\n end\n do_soap_request(req, response_class: EwsSoapRoomResponse)\n end", "language": "ruby", "code": "def get_rooms(roomDistributionList)\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.GetRooms {|x|\n x.parent.default_namespace = @default_ns\n builder.room_list!(roomDistributionList)\n }\n end\n end\n do_soap_request(req, response_class: EwsSoapRoomResponse)\n end", "code_tokens": ["def", "get_rooms", "(", "roomDistributionList", ")", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "if", "(", "type", "==", ":header", ")", "else", "builder", ".", "nbuild", ".", "GetRooms", "{", "|", "x", "|", "x", ".", "parent", ".", "default_namespace", "=", "@default_ns", "builder", ".", "room_list!", "(", "roomDistributionList", ")", "}", "end", "end", "do_soap_request", "(", "req", ",", "response_class", ":", "EwsSoapRoomResponse", ")", "end"], "docstring": "Gets the rooms that are in the specified room distribution list\n @see http://msdn.microsoft.com/en-us/library/aa563465.aspx\n @param [string] roomDistributionList", "docstring_tokens": ["Gets", "the", "rooms", "that", "are", "in", "the", "specified", "room", "distribution", "list"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_web_service.rb#L174-L185", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_web_service.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeWebService.get_room_lists", "original_string": "def get_room_lists\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.room_lists!\n end\n end\n do_soap_request(req, response_class: EwsSoapRoomlistResponse)\n end", "language": "ruby", "code": "def get_room_lists\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.room_lists!\n end\n end\n do_soap_request(req, response_class: EwsSoapRoomlistResponse)\n end", "code_tokens": ["def", "get_room_lists", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "if", "(", "type", "==", ":header", ")", "else", "builder", ".", "room_lists!", "end", "end", "do_soap_request", "(", "req", ",", "response_class", ":", "EwsSoapRoomlistResponse", ")", "end"], "docstring": "Gets the room lists that are available within the Exchange organization.\n @see http://msdn.microsoft.com/en-us/library/aa563465.aspx", "docstring_tokens": ["Gets", "the", "room", "lists", "that", "are", "available", "within", "the", "Exchange", "organization", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_web_service.rb#L189-L197", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_web_service.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeWebService.validate_version", "original_string": "def validate_version(exchange_version)\n if server_version < exchange_version\n msg = 'The operation you are attempting to use is not compatible with'\n msg << \" your configured Exchange Server version(#{server_version}).\"\n msg << \" You must be running at least version (#{exchange_version}).\"\n raise EwsServerVersionError, msg\n end\n end", "language": "ruby", "code": "def validate_version(exchange_version)\n if server_version < exchange_version\n msg = 'The operation you are attempting to use is not compatible with'\n msg << \" your configured Exchange Server version(#{server_version}).\"\n msg << \" You must be running at least version (#{exchange_version}).\"\n raise EwsServerVersionError, msg\n end\n end", "code_tokens": ["def", "validate_version", "(", "exchange_version", ")", "if", "server_version", "<", "exchange_version", "msg", "=", "'The operation you are attempting to use is not compatible with'", "msg", "<<", "\" your configured Exchange Server version(#{server_version}).\"", "msg", "<<", "\" You must be running at least version (#{exchange_version}).\"", "raise", "EwsServerVersionError", ",", "msg", "end", "end"], "docstring": "Some operations only exist for certain versions of Exchange Server.\n This method should be called with the required version and we'll throw\n an exception of the currently set @server_version does not comply.", "docstring_tokens": ["Some", "operations", "only", "exist", "for", "certain", "versions", "of", "Exchange", "Server", ".", "This", "method", "should", "be", "called", "with", "the", "required", "version", "and", "we", "ll", "throw", "an", "exception", "of", "the", "currently", "set"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_web_service.rb#L247-L254", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_web_service.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeWebService.build_soap!", "original_string": "def build_soap!(&block)\n opts = { :server_version => server_version, :impersonation_type => impersonation_type, :impersonation_mail => impersonation_address }\n opts[:time_zone_context] = @time_zone_context if @time_zone_context\n EwsBuilder.new.build!(opts, &block)\n end", "language": "ruby", "code": "def build_soap!(&block)\n opts = { :server_version => server_version, :impersonation_type => impersonation_type, :impersonation_mail => impersonation_address }\n opts[:time_zone_context] = @time_zone_context if @time_zone_context\n EwsBuilder.new.build!(opts, &block)\n end", "code_tokens": ["def", "build_soap!", "(", "&", "block", ")", "opts", "=", "{", ":server_version", "=>", "server_version", ",", ":impersonation_type", "=>", "impersonation_type", ",", ":impersonation_mail", "=>", "impersonation_address", "}", "opts", "[", ":time_zone_context", "]", "=", "@time_zone_context", "if", "@time_zone_context", "EwsBuilder", ".", "new", ".", "build!", "(", "opts", ",", "block", ")", "end"], "docstring": "Build the common elements in the SOAP message and yield to any custom elements.", "docstring_tokens": ["Build", "the", "common", "elements", "in", "the", "SOAP", "message", "and", "yield", "to", "any", "custom", "elements", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_web_service.rb#L257-L261", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/viewpoint/string_utils.rb", "func_name": "Viewpoint.StringUtils.camel_case", "original_string": "def camel_case(input)\n input.to_s.split(/_/).map { |i|\n i.sub(/^./) { |s| s.upcase }\n }.join\n end", "language": "ruby", "code": "def camel_case(input)\n input.to_s.split(/_/).map { |i|\n i.sub(/^./) { |s| s.upcase }\n }.join\n end", "code_tokens": ["def", "camel_case", "(", "input", ")", "input", ".", "to_s", ".", "split", "(", "/", "/", ")", ".", "map", "{", "|", "i", "|", "i", ".", "sub", "(", "/", "/", ")", "{", "|", "s", "|", "s", ".", "upcase", "}", "}", ".", "join", "end"], "docstring": "Change a ruby_cased string to CamelCased", "docstring_tokens": ["Change", "a", "ruby_cased", "string", "to", "CamelCased"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/viewpoint/string_utils.rb#L52-L56", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/viewpoint/string_utils.rb", "func_name": "Viewpoint.StringUtils.iso8601_duration_to_seconds", "original_string": "def iso8601_duration_to_seconds(input)\n return nil if input.nil? || input.empty?\n match_data = DURATION_RE.match(input)\n raise(StringFormatException, \"Invalid duration given\") if match_data.nil?\n duration = 0\n duration += match_data[:weeks].to_i * 604800\n duration += match_data[:days].to_i * 86400\n duration += match_data[:hours].to_i * 3600\n duration += match_data[:minutes].to_i * 60\n duration += match_data[:seconds].to_i\n end", "language": "ruby", "code": "def iso8601_duration_to_seconds(input)\n return nil if input.nil? || input.empty?\n match_data = DURATION_RE.match(input)\n raise(StringFormatException, \"Invalid duration given\") if match_data.nil?\n duration = 0\n duration += match_data[:weeks].to_i * 604800\n duration += match_data[:days].to_i * 86400\n duration += match_data[:hours].to_i * 3600\n duration += match_data[:minutes].to_i * 60\n duration += match_data[:seconds].to_i\n end", "code_tokens": ["def", "iso8601_duration_to_seconds", "(", "input", ")", "return", "nil", "if", "input", ".", "nil?", "||", "input", ".", "empty?", "match_data", "=", "DURATION_RE", ".", "match", "(", "input", ")", "raise", "(", "StringFormatException", ",", "\"Invalid duration given\"", ")", "if", "match_data", ".", "nil?", "duration", "=", "0", "duration", "+=", "match_data", "[", ":weeks", "]", ".", "to_i", "*", "604800", "duration", "+=", "match_data", "[", ":days", "]", ".", "to_i", "*", "86400", "duration", "+=", "match_data", "[", ":hours", "]", ".", "to_i", "*", "3600", "duration", "+=", "match_data", "[", ":minutes", "]", ".", "to_i", "*", "60", "duration", "+=", "match_data", "[", ":seconds", "]", ".", "to_i", "end"], "docstring": "Convert an ISO8601 Duration format to seconds\n @see http://tools.ietf.org/html/rfc2445#section-4.3.6\n @param [String] input\n @return [nil,Fixnum] the number of seconds in this duration\n nil if there is no known duration", "docstring_tokens": ["Convert", "an", "ISO8601", "Duration", "format", "to", "seconds"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/viewpoint/string_utils.rb#L63-L73", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_notification.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeNotification.subscribe", "original_string": "def subscribe(subscriptions)\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.Subscribe {\n builder.nbuild.parent.default_namespace = @default_ns\n subscriptions.each do |sub|\n subtype = sub.keys.first\n if(builder.respond_to?(subtype))\n builder.send subtype, sub[subtype]\n else\n raise EwsBadArgumentError, \"Bad subscription type. #{subtype}\"\n end\n end\n }\n end\n end\n do_soap_request(req, response_class: EwsResponse)\n end", "language": "ruby", "code": "def subscribe(subscriptions)\n req = build_soap! do |type, builder|\n if(type == :header)\n else\n builder.nbuild.Subscribe {\n builder.nbuild.parent.default_namespace = @default_ns\n subscriptions.each do |sub|\n subtype = sub.keys.first\n if(builder.respond_to?(subtype))\n builder.send subtype, sub[subtype]\n else\n raise EwsBadArgumentError, \"Bad subscription type. #{subtype}\"\n end\n end\n }\n end\n end\n do_soap_request(req, response_class: EwsResponse)\n end", "code_tokens": ["def", "subscribe", "(", "subscriptions", ")", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "if", "(", "type", "==", ":header", ")", "else", "builder", ".", "nbuild", ".", "Subscribe", "{", "builder", ".", "nbuild", ".", "parent", ".", "default_namespace", "=", "@default_ns", "subscriptions", ".", "each", "do", "|", "sub", "|", "subtype", "=", "sub", ".", "keys", ".", "first", "if", "(", "builder", ".", "respond_to?", "(", "subtype", ")", ")", "builder", ".", "send", "subtype", ",", "sub", "[", "subtype", "]", "else", "raise", "EwsBadArgumentError", ",", "\"Bad subscription type. #{subtype}\"", "end", "end", "}", "end", "end", "do_soap_request", "(", "req", ",", "response_class", ":", "EwsResponse", ")", "end"], "docstring": "Used to subscribe client applications to either push, pull or stream notifications.\n @see http://msdn.microsoft.com/en-us/library/aa566188(v=EXCHG.140).aspx\n @param [Array] subscriptions An array of Hash objects that describe each\n subscription.\n Ex: [ {:pull_subscription_request => {\n :subscribe_to_all_folders => false,\n :folder_ids => [ {:id => 'id', :change_key => 'ck'} ],\n :event_types=> %w{CopiedEvent CreatedEvent},\n :watermark => 'watermark id',\n :timeout => intval\n }},\n {:push_subscription_request => {\n :subscribe_to_all_folders => true,\n :event_types=> %w{CopiedEvent CreatedEvent},\n :status_frequency => 15,\n :uRL => 'http://my.endpoint.for.updates/',\n }},\n {:streaming_subscription_request => {\n :subscribe_to_all_folders => false,\n :folder_ids => [ {:id => 'id', :change_key => 'ck'} ],\n :event_types=> %w{NewMailEvent DeletedEvent},\n }},\n ]", "docstring_tokens": ["Used", "to", "subscribe", "client", "applications", "to", "either", "push", "pull", "or", "stream", "notifications", "."], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_notification.rb#L49-L67", "partition": "valid"} {"repo": "WinRb/Viewpoint", "path": "lib/ews/soap/exchange_notification.rb", "func_name": "Viewpoint::EWS::SOAP.ExchangeNotification.push_subscribe_folder", "original_string": "def push_subscribe_folder(folder, evtypes, url, status_frequency = nil, watermark = nil)\n status_frequency ||= 30\n psr = {\n :subscribe_to_all_folders => false,\n :folder_ids => [ {:id => folder[:id], :change_key => folder[:change_key]} ],\n :event_types=> evtypes,\n :status_frequency => status_frequency,\n :uRL => url.to_s\n }\n psr[:watermark] = watermark if watermark\n subscribe([{push_subscription_request: psr}])\n end", "language": "ruby", "code": "def push_subscribe_folder(folder, evtypes, url, status_frequency = nil, watermark = nil)\n status_frequency ||= 30\n psr = {\n :subscribe_to_all_folders => false,\n :folder_ids => [ {:id => folder[:id], :change_key => folder[:change_key]} ],\n :event_types=> evtypes,\n :status_frequency => status_frequency,\n :uRL => url.to_s\n }\n psr[:watermark] = watermark if watermark\n subscribe([{push_subscription_request: psr}])\n end", "code_tokens": ["def", "push_subscribe_folder", "(", "folder", ",", "evtypes", ",", "url", ",", "status_frequency", "=", "nil", ",", "watermark", "=", "nil", ")", "status_frequency", "||=", "30", "psr", "=", "{", ":subscribe_to_all_folders", "=>", "false", ",", ":folder_ids", "=>", "[", "{", ":id", "=>", "folder", "[", ":id", "]", ",", ":change_key", "=>", "folder", "[", ":change_key", "]", "}", "]", ",", ":event_types", "=>", "evtypes", ",", ":status_frequency", "=>", "status_frequency", ",", ":uRL", "=>", "url", ".", "to_s", "}", "psr", "[", ":watermark", "]", "=", "watermark", "if", "watermark", "subscribe", "(", "[", "{", "push_subscription_request", ":", "psr", "}", "]", ")", "end"], "docstring": "Create a push subscription to a single folder\n @param folder [Hash] a hash with the folder :id and :change_key\n @param evtypes [Array] the events you would like to subscribe to.\n @param url [String,URI] http://msdn.microsoft.com/en-us/library/aa566309.aspx\n @param watermark [String] http://msdn.microsoft.com/en-us/library/aa565886.aspx\n @param status_frequency [Fixnum] http://msdn.microsoft.com/en-us/library/aa564048.aspx", "docstring_tokens": ["Create", "a", "push", "subscription", "to", "a", "single", "folder"], "sha": "e8fec4ab1af25fc128062cd96770afdb9fc38c68", "url": "https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_notification.rb#L131-L142", "partition": "valid"} {"repo": "contentful/contentful.rb", "path": "lib/contentful/coercions.rb", "func_name": "Contentful.DateCoercion.coerce", "original_string": "def coerce(*)\n return nil if value.nil?\n return value if value.is_a?(Date)\n\n DateTime.parse(value)\n end", "language": "ruby", "code": "def coerce(*)\n return nil if value.nil?\n return value if value.is_a?(Date)\n\n DateTime.parse(value)\n end", "code_tokens": ["def", "coerce", "(", "*", ")", "return", "nil", "if", "value", ".", "nil?", "return", "value", "if", "value", ".", "is_a?", "(", "Date", ")", "DateTime", ".", "parse", "(", "value", ")", "end"], "docstring": "Coerces value to DateTime", "docstring_tokens": ["Coerces", "value", "to", "DateTime"], "sha": "bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7", "url": "https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/coercions.rb#L62-L67", "partition": "valid"} {"repo": "contentful/contentful.rb", "path": "lib/contentful/resource_references.rb", "func_name": "Contentful.ResourceReferences.incoming_references", "original_string": "def incoming_references(client = nil, query = {})\n return false unless client\n\n query = is_a?(Contentful::Entry) ? query.merge(links_to_entry: id) : query.merge(links_to_asset: id)\n\n client.entries(query)\n end", "language": "ruby", "code": "def incoming_references(client = nil, query = {})\n return false unless client\n\n query = is_a?(Contentful::Entry) ? query.merge(links_to_entry: id) : query.merge(links_to_asset: id)\n\n client.entries(query)\n end", "code_tokens": ["def", "incoming_references", "(", "client", "=", "nil", ",", "query", "=", "{", "}", ")", "return", "false", "unless", "client", "query", "=", "is_a?", "(", "Contentful", "::", "Entry", ")", "?", "query", ".", "merge", "(", "links_to_entry", ":", "id", ")", ":", "query", ".", "merge", "(", "links_to_asset", ":", "id", ")", "client", ".", "entries", "(", "query", ")", "end"], "docstring": "Gets a collection of entries which links to current entry\n\n @param [Contentful::Client] client\n @param [Hash] query\n\n @return [Contentful::Array, false]", "docstring_tokens": ["Gets", "a", "collection", "of", "entries", "which", "links", "to", "current", "entry"], "sha": "bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7", "url": "https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/resource_references.rb#L10-L16", "partition": "valid"} {"repo": "contentful/contentful.rb", "path": "lib/contentful/client.rb", "func_name": "Contentful.Client.entry", "original_string": "def entry(id, query = {})\n normalize_select!(query)\n query['sys.id'] = id\n entries = Request.new(self, environment_url('/entries'), query).get\n\n return entries if configuration[:raw_mode]\n\n entries.first\n end", "language": "ruby", "code": "def entry(id, query = {})\n normalize_select!(query)\n query['sys.id'] = id\n entries = Request.new(self, environment_url('/entries'), query).get\n\n return entries if configuration[:raw_mode]\n\n entries.first\n end", "code_tokens": ["def", "entry", "(", "id", ",", "query", "=", "{", "}", ")", "normalize_select!", "(", "query", ")", "query", "[", "'sys.id'", "]", "=", "id", "entries", "=", "Request", ".", "new", "(", "self", ",", "environment_url", "(", "'/entries'", ")", ",", "query", ")", ".", "get", "return", "entries", "if", "configuration", "[", ":raw_mode", "]", "entries", ".", "first", "end"], "docstring": "Gets a specific entry\n\n @param [String] id\n @param [Hash] query\n\n @return [Contentful::Entry]", "docstring_tokens": ["Gets", "a", "specific", "entry"], "sha": "bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7", "url": "https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/client.rb#L170-L178", "partition": "valid"} {"repo": "contentful/contentful.rb", "path": "lib/contentful/client.rb", "func_name": "Contentful.Client.os_info", "original_string": "def os_info\n os_name = case ::RbConfig::CONFIG['host_os']\n when /(cygwin|mingw|mswin|windows)/i then 'Windows'\n when /(darwin|macruby|mac os)/i then 'macOS'\n when /(linux|bsd|aix|solarix)/i then 'Linux'\n end\n { name: os_name, version: Gem::Platform.local.version }\n end", "language": "ruby", "code": "def os_info\n os_name = case ::RbConfig::CONFIG['host_os']\n when /(cygwin|mingw|mswin|windows)/i then 'Windows'\n when /(darwin|macruby|mac os)/i then 'macOS'\n when /(linux|bsd|aix|solarix)/i then 'Linux'\n end\n { name: os_name, version: Gem::Platform.local.version }\n end", "code_tokens": ["def", "os_info", "os_name", "=", "case", "::", "RbConfig", "::", "CONFIG", "[", "'host_os'", "]", "when", "/", "/i", "then", "'Windows'", "when", "/", "/i", "then", "'macOS'", "when", "/", "/i", "then", "'Linux'", "end", "{", "name", ":", "os_name", ",", "version", ":", "Gem", "::", "Platform", ".", "local", ".", "version", "}", "end"], "docstring": "Returns the X-Contentful-User-Agent os data\n @private", "docstring_tokens": ["Returns", "the", "X", "-", "Contentful", "-", "User", "-", "Agent", "os", "data"], "sha": "bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7", "url": "https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/client.rb#L265-L272", "partition": "valid"} {"repo": "contentful/contentful.rb", "path": "lib/contentful/client.rb", "func_name": "Contentful.Client.contentful_user_agent", "original_string": "def contentful_user_agent\n header = {\n 'sdk' => sdk_info,\n 'app' => app_info,\n 'integration' => integration_info,\n 'platform' => platform_info,\n 'os' => os_info\n }\n\n result = []\n header.each do |key, values|\n next unless values[:name]\n result << format_user_agent_header(key, values)\n end\n result.join(' ')\n end", "language": "ruby", "code": "def contentful_user_agent\n header = {\n 'sdk' => sdk_info,\n 'app' => app_info,\n 'integration' => integration_info,\n 'platform' => platform_info,\n 'os' => os_info\n }\n\n result = []\n header.each do |key, values|\n next unless values[:name]\n result << format_user_agent_header(key, values)\n end\n result.join(' ')\n end", "code_tokens": ["def", "contentful_user_agent", "header", "=", "{", "'sdk'", "=>", "sdk_info", ",", "'app'", "=>", "app_info", ",", "'integration'", "=>", "integration_info", ",", "'platform'", "=>", "platform_info", ",", "'os'", "=>", "os_info", "}", "result", "=", "[", "]", "header", ".", "each", "do", "|", "key", ",", "values", "|", "next", "unless", "values", "[", ":name", "]", "result", "<<", "format_user_agent_header", "(", "key", ",", "values", ")", "end", "result", ".", "join", "(", "' '", ")", "end"], "docstring": "Returns the X-Contentful-User-Agent\n @private", "docstring_tokens": ["Returns", "the", "X", "-", "Contentful", "-", "User", "-", "Agent"], "sha": "bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7", "url": "https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/client.rb#L276-L291", "partition": "valid"} {"repo": "contentful/contentful.rb", "path": "lib/contentful/client.rb", "func_name": "Contentful.Client.request_headers", "original_string": "def request_headers\n headers = { 'X-Contentful-User-Agent' => contentful_user_agent }\n headers['Authorization'] = \"Bearer #{configuration[:access_token]}\" if configuration[:authentication_mechanism] == :header\n headers['Content-Type'] = \"application/vnd.contentful.delivery.v#{configuration[:api_version].to_i}+json\" if configuration[:api_version]\n headers['Accept-Encoding'] = 'gzip' if configuration[:gzip_encoded]\n headers\n end", "language": "ruby", "code": "def request_headers\n headers = { 'X-Contentful-User-Agent' => contentful_user_agent }\n headers['Authorization'] = \"Bearer #{configuration[:access_token]}\" if configuration[:authentication_mechanism] == :header\n headers['Content-Type'] = \"application/vnd.contentful.delivery.v#{configuration[:api_version].to_i}+json\" if configuration[:api_version]\n headers['Accept-Encoding'] = 'gzip' if configuration[:gzip_encoded]\n headers\n end", "code_tokens": ["def", "request_headers", "headers", "=", "{", "'X-Contentful-User-Agent'", "=>", "contentful_user_agent", "}", "headers", "[", "'Authorization'", "]", "=", "\"Bearer #{configuration[:access_token]}\"", "if", "configuration", "[", ":authentication_mechanism", "]", "==", ":header", "headers", "[", "'Content-Type'", "]", "=", "\"application/vnd.contentful.delivery.v#{configuration[:api_version].to_i}+json\"", "if", "configuration", "[", ":api_version", "]", "headers", "[", "'Accept-Encoding'", "]", "=", "'gzip'", "if", "configuration", "[", ":gzip_encoded", "]", "headers", "end"], "docstring": "Returns the headers used for the HTTP requests\n @private", "docstring_tokens": ["Returns", "the", "headers", "used", "for", "the", "HTTP", "requests"], "sha": "bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7", "url": "https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/client.rb#L295-L301", "partition": "valid"} {"repo": "contentful/contentful.rb", "path": "lib/contentful/client.rb", "func_name": "Contentful.Client.run_request", "original_string": "def run_request(request)\n url = request.absolute? ? request.url : base_url + request.url\n logger.info(request: { url: url, query: request.query, header: request_headers }) if logger\n Response.new(\n self.class.get_http(\n url,\n request_query(request.query),\n request_headers,\n proxy_params,\n timeout_params\n ), request\n )\n end", "language": "ruby", "code": "def run_request(request)\n url = request.absolute? ? request.url : base_url + request.url\n logger.info(request: { url: url, query: request.query, header: request_headers }) if logger\n Response.new(\n self.class.get_http(\n url,\n request_query(request.query),\n request_headers,\n proxy_params,\n timeout_params\n ), request\n )\n end", "code_tokens": ["def", "run_request", "(", "request", ")", "url", "=", "request", ".", "absolute?", "?", "request", ".", "url", ":", "base_url", "+", "request", ".", "url", "logger", ".", "info", "(", "request", ":", "{", "url", ":", "url", ",", "query", ":", "request", ".", "query", ",", "header", ":", "request_headers", "}", ")", "if", "logger", "Response", ".", "new", "(", "self", ".", "class", ".", "get_http", "(", "url", ",", "request_query", "(", "request", ".", "query", ")", ",", "request_headers", ",", "proxy_params", ",", "timeout_params", ")", ",", "request", ")", "end"], "docstring": "Runs request and parses Response\n @private", "docstring_tokens": ["Runs", "request", "and", "parses", "Response"], "sha": "bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7", "url": "https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/client.rb#L367-L379", "partition": "valid"} {"repo": "contentful/contentful.rb", "path": "lib/contentful/client.rb", "func_name": "Contentful.Client.do_build_resource", "original_string": "def do_build_resource(response)\n logger.debug(response: response) if logger\n configuration[:resource_builder].new(\n response.object,\n configuration.merge(endpoint: response.request.endpoint),\n (response.request.query || {}).fetch(:locale, nil) == '*',\n 0\n ).run\n end", "language": "ruby", "code": "def do_build_resource(response)\n logger.debug(response: response) if logger\n configuration[:resource_builder].new(\n response.object,\n configuration.merge(endpoint: response.request.endpoint),\n (response.request.query || {}).fetch(:locale, nil) == '*',\n 0\n ).run\n end", "code_tokens": ["def", "do_build_resource", "(", "response", ")", "logger", ".", "debug", "(", "response", ":", "response", ")", "if", "logger", "configuration", "[", ":resource_builder", "]", ".", "new", "(", "response", ".", "object", ",", "configuration", ".", "merge", "(", "endpoint", ":", "response", ".", "request", ".", "endpoint", ")", ",", "(", "response", ".", "request", ".", "query", "||", "{", "}", ")", ".", "fetch", "(", ":locale", ",", "nil", ")", "==", "'*'", ",", "0", ")", ".", "run", "end"], "docstring": "Runs Resource Builder\n @private", "docstring_tokens": ["Runs", "Resource", "Builder"], "sha": "bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7", "url": "https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/client.rb#L383-L391", "partition": "valid"} {"repo": "contentful/contentful.rb", "path": "lib/contentful/link.rb", "func_name": "Contentful.Link.resolve", "original_string": "def resolve(client, query = {})\n id_and_query = [(id unless link_type == 'Space')].compact + [query]\n client.public_send(\n Contentful::Support.snakify(link_type).to_sym,\n *id_and_query\n )\n end", "language": "ruby", "code": "def resolve(client, query = {})\n id_and_query = [(id unless link_type == 'Space')].compact + [query]\n client.public_send(\n Contentful::Support.snakify(link_type).to_sym,\n *id_and_query\n )\n end", "code_tokens": ["def", "resolve", "(", "client", ",", "query", "=", "{", "}", ")", "id_and_query", "=", "[", "(", "id", "unless", "link_type", "==", "'Space'", ")", "]", ".", "compact", "+", "[", "query", "]", "client", ".", "public_send", "(", "Contentful", "::", "Support", ".", "snakify", "(", "link_type", ")", ".", "to_sym", ",", "id_and_query", ")", "end"], "docstring": "Queries contentful for the Resource the Link is refering to\n Takes an optional query hash", "docstring_tokens": ["Queries", "contentful", "for", "the", "Resource", "the", "Link", "is", "refering", "to", "Takes", "an", "optional", "query", "hash"], "sha": "bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7", "url": "https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/link.rb#L9-L15", "partition": "valid"} {"repo": "contentful/contentful.rb", "path": "lib/contentful/fields_resource.rb", "func_name": "Contentful.FieldsResource.fields_with_locales", "original_string": "def fields_with_locales\n remapped_fields = {}\n locales.each do |locale|\n fields(locale).each do |name, value|\n remapped_fields[name] ||= {}\n remapped_fields[name][locale.to_sym] = value\n end\n end\n\n remapped_fields\n end", "language": "ruby", "code": "def fields_with_locales\n remapped_fields = {}\n locales.each do |locale|\n fields(locale).each do |name, value|\n remapped_fields[name] ||= {}\n remapped_fields[name][locale.to_sym] = value\n end\n end\n\n remapped_fields\n end", "code_tokens": ["def", "fields_with_locales", "remapped_fields", "=", "{", "}", "locales", ".", "each", "do", "|", "locale", "|", "fields", "(", "locale", ")", ".", "each", "do", "|", "name", ",", "value", "|", "remapped_fields", "[", "name", "]", "||=", "{", "}", "remapped_fields", "[", "name", "]", "[", "locale", ".", "to_sym", "]", "=", "value", "end", "end", "remapped_fields", "end"], "docstring": "Returns all fields of the asset with locales nested by field\n\n @return [Hash] fields for Resource grouped by field name", "docstring_tokens": ["Returns", "all", "fields", "of", "the", "asset", "with", "locales", "nested", "by", "field"], "sha": "bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7", "url": "https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/fields_resource.rb#L32-L42", "partition": "valid"} {"repo": "contentful/contentful.rb", "path": "lib/contentful/base_resource.rb", "func_name": "Contentful.BaseResource.reload", "original_string": "def reload(client = nil)\n return client.send(Support.snakify(self.class.name.split('::').last), id) unless client.nil?\n\n false\n end", "language": "ruby", "code": "def reload(client = nil)\n return client.send(Support.snakify(self.class.name.split('::').last), id) unless client.nil?\n\n false\n end", "code_tokens": ["def", "reload", "(", "client", "=", "nil", ")", "return", "client", ".", "send", "(", "Support", ".", "snakify", "(", "self", ".", "class", ".", "name", ".", "split", "(", "'::'", ")", ".", "last", ")", ",", "id", ")", "unless", "client", ".", "nil?", "false", "end"], "docstring": "Issues the request that was made to fetch this response again.\n Only works for Entry, Asset, ContentType and Space", "docstring_tokens": ["Issues", "the", "request", "that", "was", "made", "to", "fetch", "this", "response", "again", ".", "Only", "works", "for", "Entry", "Asset", "ContentType", "and", "Space"], "sha": "bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7", "url": "https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/base_resource.rb#L52-L56", "partition": "valid"} {"repo": "contentful/contentful.rb", "path": "lib/contentful/content_type.rb", "func_name": "Contentful.ContentType.field_for", "original_string": "def field_for(field_id)\n fields.detect { |f| Support.snakify(f.id) == Support.snakify(field_id) }\n end", "language": "ruby", "code": "def field_for(field_id)\n fields.detect { |f| Support.snakify(f.id) == Support.snakify(field_id) }\n end", "code_tokens": ["def", "field_for", "(", "field_id", ")", "fields", ".", "detect", "{", "|", "f", "|", "Support", ".", "snakify", "(", "f", ".", "id", ")", "==", "Support", ".", "snakify", "(", "field_id", ")", "}", "end"], "docstring": "Field definition for field", "docstring_tokens": ["Field", "definition", "for", "field"], "sha": "bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7", "url": "https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/content_type.rb#L21-L23", "partition": "valid"} {"repo": "contentful/contentful.rb", "path": "lib/contentful/sync.rb", "func_name": "Contentful.Sync.each_page", "original_string": "def each_page\n page = first_page\n yield page if block_given?\n\n until completed?\n page = page.next_page\n yield page if block_given?\n end\n end", "language": "ruby", "code": "def each_page\n page = first_page\n yield page if block_given?\n\n until completed?\n page = page.next_page\n yield page if block_given?\n end\n end", "code_tokens": ["def", "each_page", "page", "=", "first_page", "yield", "page", "if", "block_given?", "until", "completed?", "page", "=", "page", ".", "next_page", "yield", "page", "if", "block_given?", "end", "end"], "docstring": "Iterates over all pages of the current sync\n\n @note Please Keep in Mind: Iterating fires a new request for each page\n\n @yield [Contentful::SyncPage]", "docstring_tokens": ["Iterates", "over", "all", "pages", "of", "the", "current", "sync"], "sha": "bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7", "url": "https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/sync.rb#L23-L31", "partition": "valid"} {"repo": "contentful/contentful.rb", "path": "lib/contentful/field.rb", "func_name": "Contentful.Field.coerce", "original_string": "def coerce(value, configuration)\n return value if type.nil?\n return value if value.nil?\n\n options = {}\n options[:coercion_class] = KNOWN_TYPES[items.type] unless items.nil?\n KNOWN_TYPES[type].new(value, options).coerce(configuration)\n end", "language": "ruby", "code": "def coerce(value, configuration)\n return value if type.nil?\n return value if value.nil?\n\n options = {}\n options[:coercion_class] = KNOWN_TYPES[items.type] unless items.nil?\n KNOWN_TYPES[type].new(value, options).coerce(configuration)\n end", "code_tokens": ["def", "coerce", "(", "value", ",", "configuration", ")", "return", "value", "if", "type", ".", "nil?", "return", "value", "if", "value", ".", "nil?", "options", "=", "{", "}", "options", "[", ":coercion_class", "]", "=", "KNOWN_TYPES", "[", "items", ".", "type", "]", "unless", "items", ".", "nil?", "KNOWN_TYPES", "[", "type", "]", ".", "new", "(", "value", ",", "options", ")", ".", "coerce", "(", "configuration", ")", "end"], "docstring": "Coerces value to proper type", "docstring_tokens": ["Coerces", "value", "to", "proper", "type"], "sha": "bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7", "url": "https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/field.rb#L38-L45", "partition": "valid"} {"repo": "instructure/ims-lti", "path": "lib/ims/lti/services/tool_config.rb", "func_name": "IMS::LTI::Services.ToolConfig.set_ext_params", "original_string": "def set_ext_params(ext_key, ext_params)\n raise ArgumentError unless ext_params.is_a?(Hash)\n @extensions[ext_key] = ext_params\n end", "language": "ruby", "code": "def set_ext_params(ext_key, ext_params)\n raise ArgumentError unless ext_params.is_a?(Hash)\n @extensions[ext_key] = ext_params\n end", "code_tokens": ["def", "set_ext_params", "(", "ext_key", ",", "ext_params", ")", "raise", "ArgumentError", "unless", "ext_params", ".", "is_a?", "(", "Hash", ")", "@extensions", "[", "ext_key", "]", "=", "ext_params", "end"], "docstring": "Set the extension parameters for a specific vendor\n\n @param ext_key [String] The identifier for the vendor-specific parameters\n @param ext_params [Hash] The parameters, this is allowed to be two-levels deep", "docstring_tokens": ["Set", "the", "extension", "parameters", "for", "a", "specific", "vendor"], "sha": "969613a50f3a43345a8b0c92ca5f0e9d0251d5b7", "url": "https://github.com/instructure/ims-lti/blob/969613a50f3a43345a8b0c92ca5f0e9d0251d5b7/lib/ims/lti/services/tool_config.rb#L62-L65", "partition": "valid"} {"repo": "instructure/ims-lti", "path": "lib/ims/lti/services/tool_config.rb", "func_name": "IMS::LTI::Services.ToolConfig.process_xml", "original_string": "def process_xml(xml)\n doc = REXML::Document.new xml\n if root = REXML::XPath.first(doc, 'xmlns:cartridge_basiclti_link')\n @title = get_node_text(root, 'blti:title')\n @description = get_node_text(root, 'blti:description')\n @launch_url = get_node_text(root, 'blti:launch_url')\n @secure_launch_url = get_node_text(root, 'blti:secure_launch_url')\n @icon = get_node_text(root, 'blti:icon')\n @secure_icon = get_node_text(root, 'blti:secure_icon')\n @cartridge_bundle = get_node_att(root, 'xmlns:cartridge_bundle', 'identifierref')\n @cartridge_icon = get_node_att(root, 'xmlns:cartridge_icon', 'identifierref')\n\n if vendor = REXML::XPath.first(root, 'blti:vendor')\n @vendor_code = get_node_text(vendor, 'lticp:code')\n @vendor_description = get_node_text(vendor, 'lticp:description')\n @vendor_name = get_node_text(vendor, 'lticp:name')\n @vendor_url = get_node_text(vendor, 'lticp:url')\n @vendor_contact_email = get_node_text(vendor, '//lticp:contact/lticp:email')\n @vendor_contact_name = get_node_text(vendor, '//lticp:contact/lticp:name')\n end\n\n if custom = REXML::XPath.first(root, 'blti:custom', LTI_NAMESPACES)\n set_properties(@custom_params, custom)\n end\n\n REXML::XPath.each(root, 'blti:extensions', LTI_NAMESPACES) do |vendor_ext_node|\n platform = vendor_ext_node.attributes['platform']\n properties = {}\n set_properties(properties, vendor_ext_node)\n REXML::XPath.each(vendor_ext_node, 'lticm:options', LTI_NAMESPACES) do |options_node|\n opt_name = options_node.attributes['name']\n options = {}\n set_properties(options, options_node)\n properties[opt_name] = options\n end\n\n self.set_ext_params(platform, properties)\n end\n\n end\n end", "language": "ruby", "code": "def process_xml(xml)\n doc = REXML::Document.new xml\n if root = REXML::XPath.first(doc, 'xmlns:cartridge_basiclti_link')\n @title = get_node_text(root, 'blti:title')\n @description = get_node_text(root, 'blti:description')\n @launch_url = get_node_text(root, 'blti:launch_url')\n @secure_launch_url = get_node_text(root, 'blti:secure_launch_url')\n @icon = get_node_text(root, 'blti:icon')\n @secure_icon = get_node_text(root, 'blti:secure_icon')\n @cartridge_bundle = get_node_att(root, 'xmlns:cartridge_bundle', 'identifierref')\n @cartridge_icon = get_node_att(root, 'xmlns:cartridge_icon', 'identifierref')\n\n if vendor = REXML::XPath.first(root, 'blti:vendor')\n @vendor_code = get_node_text(vendor, 'lticp:code')\n @vendor_description = get_node_text(vendor, 'lticp:description')\n @vendor_name = get_node_text(vendor, 'lticp:name')\n @vendor_url = get_node_text(vendor, 'lticp:url')\n @vendor_contact_email = get_node_text(vendor, '//lticp:contact/lticp:email')\n @vendor_contact_name = get_node_text(vendor, '//lticp:contact/lticp:name')\n end\n\n if custom = REXML::XPath.first(root, 'blti:custom', LTI_NAMESPACES)\n set_properties(@custom_params, custom)\n end\n\n REXML::XPath.each(root, 'blti:extensions', LTI_NAMESPACES) do |vendor_ext_node|\n platform = vendor_ext_node.attributes['platform']\n properties = {}\n set_properties(properties, vendor_ext_node)\n REXML::XPath.each(vendor_ext_node, 'lticm:options', LTI_NAMESPACES) do |options_node|\n opt_name = options_node.attributes['name']\n options = {}\n set_properties(options, options_node)\n properties[opt_name] = options\n end\n\n self.set_ext_params(platform, properties)\n end\n\n end\n end", "code_tokens": ["def", "process_xml", "(", "xml", ")", "doc", "=", "REXML", "::", "Document", ".", "new", "xml", "if", "root", "=", "REXML", "::", "XPath", ".", "first", "(", "doc", ",", "'xmlns:cartridge_basiclti_link'", ")", "@title", "=", "get_node_text", "(", "root", ",", "'blti:title'", ")", "@description", "=", "get_node_text", "(", "root", ",", "'blti:description'", ")", "@launch_url", "=", "get_node_text", "(", "root", ",", "'blti:launch_url'", ")", "@secure_launch_url", "=", "get_node_text", "(", "root", ",", "'blti:secure_launch_url'", ")", "@icon", "=", "get_node_text", "(", "root", ",", "'blti:icon'", ")", "@secure_icon", "=", "get_node_text", "(", "root", ",", "'blti:secure_icon'", ")", "@cartridge_bundle", "=", "get_node_att", "(", "root", ",", "'xmlns:cartridge_bundle'", ",", "'identifierref'", ")", "@cartridge_icon", "=", "get_node_att", "(", "root", ",", "'xmlns:cartridge_icon'", ",", "'identifierref'", ")", "if", "vendor", "=", "REXML", "::", "XPath", ".", "first", "(", "root", ",", "'blti:vendor'", ")", "@vendor_code", "=", "get_node_text", "(", "vendor", ",", "'lticp:code'", ")", "@vendor_description", "=", "get_node_text", "(", "vendor", ",", "'lticp:description'", ")", "@vendor_name", "=", "get_node_text", "(", "vendor", ",", "'lticp:name'", ")", "@vendor_url", "=", "get_node_text", "(", "vendor", ",", "'lticp:url'", ")", "@vendor_contact_email", "=", "get_node_text", "(", "vendor", ",", "'//lticp:contact/lticp:email'", ")", "@vendor_contact_name", "=", "get_node_text", "(", "vendor", ",", "'//lticp:contact/lticp:name'", ")", "end", "if", "custom", "=", "REXML", "::", "XPath", ".", "first", "(", "root", ",", "'blti:custom'", ",", "LTI_NAMESPACES", ")", "set_properties", "(", "@custom_params", ",", "custom", ")", "end", "REXML", "::", "XPath", ".", "each", "(", "root", ",", "'blti:extensions'", ",", "LTI_NAMESPACES", ")", "do", "|", "vendor_ext_node", "|", "platform", "=", "vendor_ext_node", ".", "attributes", "[", "'platform'", "]", "properties", "=", "{", "}", "set_properties", "(", "properties", ",", "vendor_ext_node", ")", "REXML", "::", "XPath", ".", "each", "(", "vendor_ext_node", ",", "'lticm:options'", ",", "LTI_NAMESPACES", ")", "do", "|", "options_node", "|", "opt_name", "=", "options_node", ".", "attributes", "[", "'name'", "]", "options", "=", "{", "}", "set_properties", "(", "options", ",", "options_node", ")", "properties", "[", "opt_name", "]", "=", "options", "end", "self", ".", "set_ext_params", "(", "platform", ",", "properties", ")", "end", "end", "end"], "docstring": "Parse tool configuration data out of the Common Cartridge LTI link XML", "docstring_tokens": ["Parse", "tool", "configuration", "data", "out", "of", "the", "Common", "Cartridge", "LTI", "link", "XML"], "sha": "969613a50f3a43345a8b0c92ca5f0e9d0251d5b7", "url": "https://github.com/instructure/ims-lti/blob/969613a50f3a43345a8b0c92ca5f0e9d0251d5b7/lib/ims/lti/services/tool_config.rb#L89-L129", "partition": "valid"} {"repo": "instructure/ims-lti", "path": "lib/ims/lti/services/tool_config.rb", "func_name": "IMS::LTI::Services.ToolConfig.to_xml", "original_string": "def to_xml(opts = {})\n builder = Builder::XmlMarkup.new(:indent => opts[:indent] || 0)\n builder.instruct!\n builder.cartridge_basiclti_link(\"xmlns\" => \"http://www.imsglobal.org/xsd/imslticc_v1p0\",\n \"xmlns:blti\" => 'http://www.imsglobal.org/xsd/imsbasiclti_v1p0',\n \"xmlns:lticm\" => 'http://www.imsglobal.org/xsd/imslticm_v1p0',\n \"xmlns:lticp\" => 'http://www.imsglobal.org/xsd/imslticp_v1p0',\n \"xmlns:xsi\" => \"http://www.w3.org/2001/XMLSchema-instance\",\n \"xsi:schemaLocation\" => \"http://www.imsglobal.org/xsd/imslticc_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticc_v1p0.xsd http://www.imsglobal.org/xsd/imsbasiclti_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imsbasiclti_v1p0p1.xsd http://www.imsglobal.org/xsd/imslticm_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticm_v1p0.xsd http://www.imsglobal.org/xsd/imslticp_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticp_v1p0.xsd\"\n ) do |blti_node|\n\n %w{title description launch_url secure_launch_url icon secure_icon}.each do |key|\n blti_node.blti key.to_sym, self.send(key) if self.send(key)\n end\n\n vendor_keys = %w{name code description url}\n if vendor_keys.any? { |k| self.send(\"vendor_#{k}\") } || vendor_contact_email\n blti_node.blti :vendor do |v_node|\n vendor_keys.each do |key|\n v_node.lticp key.to_sym, self.send(\"vendor_#{key}\") if self.send(\"vendor_#{key}\")\n end\n if vendor_contact_email\n v_node.lticp :contact do |c_node|\n c_node.lticp :name, vendor_contact_name\n c_node.lticp :email, vendor_contact_email\n end\n end\n end\n end\n\n if !@custom_params.empty?\n blti_node.tag!(\"blti:custom\") do |custom_node|\n @custom_params.keys.sort.each do |key|\n val = @custom_params[key]\n custom_node.lticm :property, val, 'name' => key\n end\n end\n end\n\n if !@extensions.empty?\n @extensions.keys.sort.each do |ext_platform|\n ext_params = @extensions[ext_platform]\n blti_node.blti(:extensions, :platform => ext_platform) do |ext_node|\n ext_params.keys.sort.each do |key|\n val = ext_params[key]\n if val.is_a?(Hash)\n ext_node.lticm(:options, :name => key) do |type_node|\n val.keys.sort.each do |p_key|\n p_val = val[p_key]\n type_node.lticm :property, p_val, 'name' => p_key\n end\n end\n else\n ext_node.lticm :property, val, 'name' => key\n end\n end\n end\n end\n end\n\n blti_node.cartridge_bundle(:identifierref => @cartridge_bundle) if @cartridge_bundle\n blti_node.cartridge_icon(:identifierref => @cartridge_icon) if @cartridge_icon\n\n end\n end", "language": "ruby", "code": "def to_xml(opts = {})\n builder = Builder::XmlMarkup.new(:indent => opts[:indent] || 0)\n builder.instruct!\n builder.cartridge_basiclti_link(\"xmlns\" => \"http://www.imsglobal.org/xsd/imslticc_v1p0\",\n \"xmlns:blti\" => 'http://www.imsglobal.org/xsd/imsbasiclti_v1p0',\n \"xmlns:lticm\" => 'http://www.imsglobal.org/xsd/imslticm_v1p0',\n \"xmlns:lticp\" => 'http://www.imsglobal.org/xsd/imslticp_v1p0',\n \"xmlns:xsi\" => \"http://www.w3.org/2001/XMLSchema-instance\",\n \"xsi:schemaLocation\" => \"http://www.imsglobal.org/xsd/imslticc_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticc_v1p0.xsd http://www.imsglobal.org/xsd/imsbasiclti_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imsbasiclti_v1p0p1.xsd http://www.imsglobal.org/xsd/imslticm_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticm_v1p0.xsd http://www.imsglobal.org/xsd/imslticp_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticp_v1p0.xsd\"\n ) do |blti_node|\n\n %w{title description launch_url secure_launch_url icon secure_icon}.each do |key|\n blti_node.blti key.to_sym, self.send(key) if self.send(key)\n end\n\n vendor_keys = %w{name code description url}\n if vendor_keys.any? { |k| self.send(\"vendor_#{k}\") } || vendor_contact_email\n blti_node.blti :vendor do |v_node|\n vendor_keys.each do |key|\n v_node.lticp key.to_sym, self.send(\"vendor_#{key}\") if self.send(\"vendor_#{key}\")\n end\n if vendor_contact_email\n v_node.lticp :contact do |c_node|\n c_node.lticp :name, vendor_contact_name\n c_node.lticp :email, vendor_contact_email\n end\n end\n end\n end\n\n if !@custom_params.empty?\n blti_node.tag!(\"blti:custom\") do |custom_node|\n @custom_params.keys.sort.each do |key|\n val = @custom_params[key]\n custom_node.lticm :property, val, 'name' => key\n end\n end\n end\n\n if !@extensions.empty?\n @extensions.keys.sort.each do |ext_platform|\n ext_params = @extensions[ext_platform]\n blti_node.blti(:extensions, :platform => ext_platform) do |ext_node|\n ext_params.keys.sort.each do |key|\n val = ext_params[key]\n if val.is_a?(Hash)\n ext_node.lticm(:options, :name => key) do |type_node|\n val.keys.sort.each do |p_key|\n p_val = val[p_key]\n type_node.lticm :property, p_val, 'name' => p_key\n end\n end\n else\n ext_node.lticm :property, val, 'name' => key\n end\n end\n end\n end\n end\n\n blti_node.cartridge_bundle(:identifierref => @cartridge_bundle) if @cartridge_bundle\n blti_node.cartridge_icon(:identifierref => @cartridge_icon) if @cartridge_icon\n\n end\n end", "code_tokens": ["def", "to_xml", "(", "opts", "=", "{", "}", ")", "builder", "=", "Builder", "::", "XmlMarkup", ".", "new", "(", ":indent", "=>", "opts", "[", ":indent", "]", "||", "0", ")", "builder", ".", "instruct!", "builder", ".", "cartridge_basiclti_link", "(", "\"xmlns\"", "=>", "\"http://www.imsglobal.org/xsd/imslticc_v1p0\"", ",", "\"xmlns:blti\"", "=>", "'http://www.imsglobal.org/xsd/imsbasiclti_v1p0'", ",", "\"xmlns:lticm\"", "=>", "'http://www.imsglobal.org/xsd/imslticm_v1p0'", ",", "\"xmlns:lticp\"", "=>", "'http://www.imsglobal.org/xsd/imslticp_v1p0'", ",", "\"xmlns:xsi\"", "=>", "\"http://www.w3.org/2001/XMLSchema-instance\"", ",", "\"xsi:schemaLocation\"", "=>", "\"http://www.imsglobal.org/xsd/imslticc_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticc_v1p0.xsd http://www.imsglobal.org/xsd/imsbasiclti_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imsbasiclti_v1p0p1.xsd http://www.imsglobal.org/xsd/imslticm_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticm_v1p0.xsd http://www.imsglobal.org/xsd/imslticp_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticp_v1p0.xsd\"", ")", "do", "|", "blti_node", "|", "%w{", "title", "description", "launch_url", "secure_launch_url", "icon", "secure_icon", "}", ".", "each", "do", "|", "key", "|", "blti_node", ".", "blti", "key", ".", "to_sym", ",", "self", ".", "send", "(", "key", ")", "if", "self", ".", "send", "(", "key", ")", "end", "vendor_keys", "=", "%w{", "name", "code", "description", "url", "}", "if", "vendor_keys", ".", "any?", "{", "|", "k", "|", "self", ".", "send", "(", "\"vendor_#{k}\"", ")", "}", "||", "vendor_contact_email", "blti_node", ".", "blti", ":vendor", "do", "|", "v_node", "|", "vendor_keys", ".", "each", "do", "|", "key", "|", "v_node", ".", "lticp", "key", ".", "to_sym", ",", "self", ".", "send", "(", "\"vendor_#{key}\"", ")", "if", "self", ".", "send", "(", "\"vendor_#{key}\"", ")", "end", "if", "vendor_contact_email", "v_node", ".", "lticp", ":contact", "do", "|", "c_node", "|", "c_node", ".", "lticp", ":name", ",", "vendor_contact_name", "c_node", ".", "lticp", ":email", ",", "vendor_contact_email", "end", "end", "end", "end", "if", "!", "@custom_params", ".", "empty?", "blti_node", ".", "tag!", "(", "\"blti:custom\"", ")", "do", "|", "custom_node", "|", "@custom_params", ".", "keys", ".", "sort", ".", "each", "do", "|", "key", "|", "val", "=", "@custom_params", "[", "key", "]", "custom_node", ".", "lticm", ":property", ",", "val", ",", "'name'", "=>", "key", "end", "end", "end", "if", "!", "@extensions", ".", "empty?", "@extensions", ".", "keys", ".", "sort", ".", "each", "do", "|", "ext_platform", "|", "ext_params", "=", "@extensions", "[", "ext_platform", "]", "blti_node", ".", "blti", "(", ":extensions", ",", ":platform", "=>", "ext_platform", ")", "do", "|", "ext_node", "|", "ext_params", ".", "keys", ".", "sort", ".", "each", "do", "|", "key", "|", "val", "=", "ext_params", "[", "key", "]", "if", "val", ".", "is_a?", "(", "Hash", ")", "ext_node", ".", "lticm", "(", ":options", ",", ":name", "=>", "key", ")", "do", "|", "type_node", "|", "val", ".", "keys", ".", "sort", ".", "each", "do", "|", "p_key", "|", "p_val", "=", "val", "[", "p_key", "]", "type_node", ".", "lticm", ":property", ",", "p_val", ",", "'name'", "=>", "p_key", "end", "end", "else", "ext_node", ".", "lticm", ":property", ",", "val", ",", "'name'", "=>", "key", "end", "end", "end", "end", "end", "blti_node", ".", "cartridge_bundle", "(", ":identifierref", "=>", "@cartridge_bundle", ")", "if", "@cartridge_bundle", "blti_node", ".", "cartridge_icon", "(", ":identifierref", "=>", "@cartridge_icon", ")", "if", "@cartridge_icon", "end", "end"], "docstring": "Generate XML from the current settings", "docstring_tokens": ["Generate", "XML", "from", "the", "current", "settings"], "sha": "969613a50f3a43345a8b0c92ca5f0e9d0251d5b7", "url": "https://github.com/instructure/ims-lti/blob/969613a50f3a43345a8b0c92ca5f0e9d0251d5b7/lib/ims/lti/services/tool_config.rb#L132-L196", "partition": "valid"} {"repo": "mbleigh/seed-fu", "path": "lib/seed-fu/active_record_extension.rb", "func_name": "SeedFu.ActiveRecordExtension.seed", "original_string": "def seed(*args, &block)\n SeedFu::Seeder.new(self, *parse_seed_fu_args(args, block)).seed\n end", "language": "ruby", "code": "def seed(*args, &block)\n SeedFu::Seeder.new(self, *parse_seed_fu_args(args, block)).seed\n end", "code_tokens": ["def", "seed", "(", "*", "args", ",", "&", "block", ")", "SeedFu", "::", "Seeder", ".", "new", "(", "self", ",", "parse_seed_fu_args", "(", "args", ",", "block", ")", ")", ".", "seed", "end"], "docstring": "Load some seed data. There are two ways to do this.\n\n Verbose syntax\n --------------\n\n This will seed a single record. The `:id` parameter ensures that if a record already exists\n in the database with the same id, then it will be updated with the name and age, rather\n than created from scratch.\n\n Person.seed(:id) do |s|\n s.id = 1\n s.name = \"Jon\"\n s.age = 21\n end\n\n Note that `:id` is the default attribute used to identify a seed, so it need not be\n specified.\n\n Terse syntax\n ------------\n\n This is a more succinct way to load multiple records. Note that both `:x` and `:y` are being\n used to identify a seed here.\n\n Point.seed(:x, :y,\n { :x => 3, :y => 10, :name => \"Home\" },\n { :x => 5, :y => 9, :name => \"Office\" }\n )", "docstring_tokens": ["Load", "some", "seed", "data", ".", "There", "are", "two", "ways", "to", "do", "this", "."], "sha": "34c054c914858c3d7685f83d16dea5c0e2114561", "url": "https://github.com/mbleigh/seed-fu/blob/34c054c914858c3d7685f83d16dea5c0e2114561/lib/seed-fu/active_record_extension.rb#L31-L33", "partition": "valid"} {"repo": "janko/image_processing", "path": "lib/image_processing/pipeline.rb", "func_name": "ImageProcessing.Pipeline.call", "original_string": "def call(save: true)\n if save == false\n call_processor\n elsif destination\n handle_destination do\n call_processor(destination: destination)\n end\n else\n create_tempfile do |tempfile|\n call_processor(destination: tempfile.path)\n end\n end\n end", "language": "ruby", "code": "def call(save: true)\n if save == false\n call_processor\n elsif destination\n handle_destination do\n call_processor(destination: destination)\n end\n else\n create_tempfile do |tempfile|\n call_processor(destination: tempfile.path)\n end\n end\n end", "code_tokens": ["def", "call", "(", "save", ":", "true", ")", "if", "save", "==", "false", "call_processor", "elsif", "destination", "handle_destination", "do", "call_processor", "(", "destination", ":", "destination", ")", "end", "else", "create_tempfile", "do", "|", "tempfile", "|", "call_processor", "(", "destination", ":", "tempfile", ".", "path", ")", "end", "end", "end"], "docstring": "Initializes the pipeline with all the processing options.\n Determines the destination and calls the processor.", "docstring_tokens": ["Initializes", "the", "pipeline", "with", "all", "the", "processing", "options", ".", "Determines", "the", "destination", "and", "calls", "the", "processor", "."], "sha": "4b4917d88bab1f73ebdc733f8a583734322e5226", "url": "https://github.com/janko/image_processing/blob/4b4917d88bab1f73ebdc733f8a583734322e5226/lib/image_processing/pipeline.rb#L19-L31", "partition": "valid"} {"repo": "janko/image_processing", "path": "lib/image_processing/pipeline.rb", "func_name": "ImageProcessing.Pipeline.destination_format", "original_string": "def destination_format\n format = File.extname(destination)[1..-1] if destination\n format ||= self.format\n format ||= File.extname(source_path)[1..-1] if source_path\n\n format || DEFAULT_FORMAT\n end", "language": "ruby", "code": "def destination_format\n format = File.extname(destination)[1..-1] if destination\n format ||= self.format\n format ||= File.extname(source_path)[1..-1] if source_path\n\n format || DEFAULT_FORMAT\n end", "code_tokens": ["def", "destination_format", "format", "=", "File", ".", "extname", "(", "destination", ")", "[", "1", "..", "-", "1", "]", "if", "destination", "format", "||=", "self", ".", "format", "format", "||=", "File", ".", "extname", "(", "source_path", ")", "[", "1", "..", "-", "1", "]", "if", "source_path", "format", "||", "DEFAULT_FORMAT", "end"], "docstring": "Determines the appropriate destination image format.", "docstring_tokens": ["Determines", "the", "appropriate", "destination", "image", "format", "."], "sha": "4b4917d88bab1f73ebdc733f8a583734322e5226", "url": "https://github.com/janko/image_processing/blob/4b4917d88bab1f73ebdc733f8a583734322e5226/lib/image_processing/pipeline.rb#L39-L45", "partition": "valid"} {"repo": "janko/image_processing", "path": "lib/image_processing/pipeline.rb", "func_name": "ImageProcessing.Pipeline.create_tempfile", "original_string": "def create_tempfile\n tempfile = Tempfile.new([\"image_processing\", \".#{destination_format}\"], binmode: true)\n\n yield tempfile\n\n tempfile.open\n tempfile\n rescue\n tempfile.close! if tempfile\n raise\n end", "language": "ruby", "code": "def create_tempfile\n tempfile = Tempfile.new([\"image_processing\", \".#{destination_format}\"], binmode: true)\n\n yield tempfile\n\n tempfile.open\n tempfile\n rescue\n tempfile.close! if tempfile\n raise\n end", "code_tokens": ["def", "create_tempfile", "tempfile", "=", "Tempfile", ".", "new", "(", "[", "\"image_processing\"", ",", "\".#{destination_format}\"", "]", ",", "binmode", ":", "true", ")", "yield", "tempfile", "tempfile", ".", "open", "tempfile", "rescue", "tempfile", ".", "close!", "if", "tempfile", "raise", "end"], "docstring": "Creates a new tempfile for the destination file, yields it, and refreshes\n the file descriptor to get the updated file.", "docstring_tokens": ["Creates", "a", "new", "tempfile", "for", "the", "destination", "file", "yields", "it", "and", "refreshes", "the", "file", "descriptor", "to", "get", "the", "updated", "file", "."], "sha": "4b4917d88bab1f73ebdc733f8a583734322e5226", "url": "https://github.com/janko/image_processing/blob/4b4917d88bab1f73ebdc733f8a583734322e5226/lib/image_processing/pipeline.rb#L61-L71", "partition": "valid"} {"repo": "janko/image_processing", "path": "lib/image_processing/pipeline.rb", "func_name": "ImageProcessing.Pipeline.handle_destination", "original_string": "def handle_destination\n destination_existed = File.exist?(destination)\n yield\n rescue\n File.delete(destination) if File.exist?(destination) && !destination_existed\n raise\n end", "language": "ruby", "code": "def handle_destination\n destination_existed = File.exist?(destination)\n yield\n rescue\n File.delete(destination) if File.exist?(destination) && !destination_existed\n raise\n end", "code_tokens": ["def", "handle_destination", "destination_existed", "=", "File", ".", "exist?", "(", "destination", ")", "yield", "rescue", "File", ".", "delete", "(", "destination", ")", "if", "File", ".", "exist?", "(", "destination", ")", "&&", "!", "destination_existed", "raise", "end"], "docstring": "In case of processing errors, both libvips and imagemagick will leave the\n empty destination file they created, so this method makes sure it is\n deleted in case an exception is raised on saving the image.", "docstring_tokens": ["In", "case", "of", "processing", "errors", "both", "libvips", "and", "imagemagick", "will", "leave", "the", "empty", "destination", "file", "they", "created", "so", "this", "method", "makes", "sure", "it", "is", "deleted", "in", "case", "an", "exception", "is", "raised", "on", "saving", "the", "image", "."], "sha": "4b4917d88bab1f73ebdc733f8a583734322e5226", "url": "https://github.com/janko/image_processing/blob/4b4917d88bab1f73ebdc733f8a583734322e5226/lib/image_processing/pipeline.rb#L76-L82", "partition": "valid"} {"repo": "janko/image_processing", "path": "lib/image_processing/chainable.rb", "func_name": "ImageProcessing.Chainable.apply", "original_string": "def apply(operations)\n operations.inject(self) do |builder, (name, argument)|\n if argument == true || argument == nil\n builder.send(name)\n elsif argument.is_a?(Array)\n builder.send(name, *argument)\n else\n builder.send(name, argument)\n end\n end\n end", "language": "ruby", "code": "def apply(operations)\n operations.inject(self) do |builder, (name, argument)|\n if argument == true || argument == nil\n builder.send(name)\n elsif argument.is_a?(Array)\n builder.send(name, *argument)\n else\n builder.send(name, argument)\n end\n end\n end", "code_tokens": ["def", "apply", "(", "operations", ")", "operations", ".", "inject", "(", "self", ")", "do", "|", "builder", ",", "(", "name", ",", "argument", ")", "|", "if", "argument", "==", "true", "||", "argument", "==", "nil", "builder", ".", "send", "(", "name", ")", "elsif", "argument", ".", "is_a?", "(", "Array", ")", "builder", ".", "send", "(", "name", ",", "argument", ")", "else", "builder", ".", "send", "(", "name", ",", "argument", ")", "end", "end", "end"], "docstring": "Add multiple operations as a hash or an array.\n\n .apply(resize_to_limit: [400, 400], strip: true)\n # or\n .apply([[:resize_to_limit, [400, 400]], [:strip, true])", "docstring_tokens": ["Add", "multiple", "operations", "as", "a", "hash", "or", "an", "array", "."], "sha": "4b4917d88bab1f73ebdc733f8a583734322e5226", "url": "https://github.com/janko/image_processing/blob/4b4917d88bab1f73ebdc733f8a583734322e5226/lib/image_processing/chainable.rb#L29-L39", "partition": "valid"} {"repo": "janko/image_processing", "path": "lib/image_processing/chainable.rb", "func_name": "ImageProcessing.Chainable.call", "original_string": "def call(file = nil, destination: nil, **call_options)\n options = {}\n options = options.merge(source: file) if file\n options = options.merge(destination: destination) if destination\n\n branch(options).call!(**call_options)\n end", "language": "ruby", "code": "def call(file = nil, destination: nil, **call_options)\n options = {}\n options = options.merge(source: file) if file\n options = options.merge(destination: destination) if destination\n\n branch(options).call!(**call_options)\n end", "code_tokens": ["def", "call", "(", "file", "=", "nil", ",", "destination", ":", "nil", ",", "**", "call_options", ")", "options", "=", "{", "}", "options", "=", "options", ".", "merge", "(", "source", ":", "file", ")", "if", "file", "options", "=", "options", ".", "merge", "(", "destination", ":", "destination", ")", "if", "destination", "branch", "(", "options", ")", ".", "call!", "(", "**", "call_options", ")", "end"], "docstring": "Call the defined processing and get the result. Allows specifying\n the source file and destination.", "docstring_tokens": ["Call", "the", "defined", "processing", "and", "get", "the", "result", ".", "Allows", "specifying", "the", "source", "file", "and", "destination", "."], "sha": "4b4917d88bab1f73ebdc733f8a583734322e5226", "url": "https://github.com/janko/image_processing/blob/4b4917d88bab1f73ebdc733f8a583734322e5226/lib/image_processing/chainable.rb#L57-L63", "partition": "valid"} {"repo": "janko/image_processing", "path": "lib/image_processing/chainable.rb", "func_name": "ImageProcessing.Chainable.branch", "original_string": "def branch(loader: nil, saver: nil, operations: nil, **other_options)\n options = respond_to?(:options) ? self.options : DEFAULT_OPTIONS\n\n options = options.merge(loader: options[:loader].merge(loader)) if loader\n options = options.merge(saver: options[:saver].merge(saver)) if saver\n options = options.merge(operations: options[:operations] + operations) if operations\n options = options.merge(processor: self::Processor) unless self.is_a?(Builder)\n options = options.merge(other_options)\n\n options.freeze\n\n Builder.new(options)\n end", "language": "ruby", "code": "def branch(loader: nil, saver: nil, operations: nil, **other_options)\n options = respond_to?(:options) ? self.options : DEFAULT_OPTIONS\n\n options = options.merge(loader: options[:loader].merge(loader)) if loader\n options = options.merge(saver: options[:saver].merge(saver)) if saver\n options = options.merge(operations: options[:operations] + operations) if operations\n options = options.merge(processor: self::Processor) unless self.is_a?(Builder)\n options = options.merge(other_options)\n\n options.freeze\n\n Builder.new(options)\n end", "code_tokens": ["def", "branch", "(", "loader", ":", "nil", ",", "saver", ":", "nil", ",", "operations", ":", "nil", ",", "**", "other_options", ")", "options", "=", "respond_to?", "(", ":options", ")", "?", "self", ".", "options", ":", "DEFAULT_OPTIONS", "options", "=", "options", ".", "merge", "(", "loader", ":", "options", "[", ":loader", "]", ".", "merge", "(", "loader", ")", ")", "if", "loader", "options", "=", "options", ".", "merge", "(", "saver", ":", "options", "[", ":saver", "]", ".", "merge", "(", "saver", ")", ")", "if", "saver", "options", "=", "options", ".", "merge", "(", "operations", ":", "options", "[", ":operations", "]", "+", "operations", ")", "if", "operations", "options", "=", "options", ".", "merge", "(", "processor", ":", "self", "::", "Processor", ")", "unless", "self", ".", "is_a?", "(", "Builder", ")", "options", "=", "options", ".", "merge", "(", "other_options", ")", "options", ".", "freeze", "Builder", ".", "new", "(", "options", ")", "end"], "docstring": "Creates a new builder object, merging current options with new options.", "docstring_tokens": ["Creates", "a", "new", "builder", "object", "merging", "current", "options", "with", "new", "options", "."], "sha": "4b4917d88bab1f73ebdc733f8a583734322e5226", "url": "https://github.com/janko/image_processing/blob/4b4917d88bab1f73ebdc733f8a583734322e5226/lib/image_processing/chainable.rb#L66-L78", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/page/cookies.rb", "func_name": "Spidr.Page.cookie_params", "original_string": "def cookie_params\n params = {}\n\n cookies.each do |value|\n value.split(';').each do |param|\n param.strip!\n\n name, value = param.split('=',2)\n\n unless name =~ RESERVED_COOKIE_NAMES\n params[name] = (value || '')\n end\n end\n end\n\n return params\n end", "language": "ruby", "code": "def cookie_params\n params = {}\n\n cookies.each do |value|\n value.split(';').each do |param|\n param.strip!\n\n name, value = param.split('=',2)\n\n unless name =~ RESERVED_COOKIE_NAMES\n params[name] = (value || '')\n end\n end\n end\n\n return params\n end", "code_tokens": ["def", "cookie_params", "params", "=", "{", "}", "cookies", ".", "each", "do", "|", "value", "|", "value", ".", "split", "(", "';'", ")", ".", "each", "do", "|", "param", "|", "param", ".", "strip!", "name", ",", "value", "=", "param", ".", "split", "(", "'='", ",", "2", ")", "unless", "name", "=~", "RESERVED_COOKIE_NAMES", "params", "[", "name", "]", "=", "(", "value", "||", "''", ")", "end", "end", "end", "return", "params", "end"], "docstring": "The Cookie key -> value pairs returned with the response.\n\n @return [Hash{String => String}]\n The cookie keys and values.\n\n @since 0.2.2", "docstring_tokens": ["The", "Cookie", "key", "-", ">", "value", "pairs", "returned", "with", "the", "response", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/cookies.rb#L42-L58", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/session_cache.rb", "func_name": "Spidr.SessionCache.active?", "original_string": "def active?(url)\n # normalize the url\n url = URI(url)\n\n # session key\n key = key_for(url)\n\n return @sessions.has_key?(key)\n end", "language": "ruby", "code": "def active?(url)\n # normalize the url\n url = URI(url)\n\n # session key\n key = key_for(url)\n\n return @sessions.has_key?(key)\n end", "code_tokens": ["def", "active?", "(", "url", ")", "# normalize the url", "url", "=", "URI", "(", "url", ")", "# session key", "key", "=", "key_for", "(", "url", ")", "return", "@sessions", ".", "has_key?", "(", "key", ")", "end"], "docstring": "Creates a new session cache.\n\n @param [Hash] options\n Configuration options.\n\n @option [Hash] :proxy (Spidr.proxy)\n Proxy options.\n\n @option [Integer] :open_timeout (Spidr.open_timeout)\n Optional open timeout.\n\n @option [Integer] :ssl_timeout (Spidr.ssl_timeout)\n Optional ssl timeout.\n\n @option [Integer] :read_timeout (Spidr.read_timeout)\n Optional read timeout.\n\n @option [Integer] :continue_timeout (Spidr.continue_timeout)\n Optional `Continue` timeout.\n\n @option [Integer] :keep_alive_timeout (Spidr.keep_alive_timeout)\n Optional `Keep-Alive` timeout.\n\n @since 0.6.0\n\n\n Determines if there is an active HTTP session for a given URL.\n\n @param [URI::HTTP, String] url\n The URL that represents a session.\n\n @return [Boolean]\n Specifies whether there is an active HTTP session.\n\n @since 0.2.3", "docstring_tokens": ["Creates", "a", "new", "session", "cache", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/session_cache.rb#L66-L74", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/session_cache.rb", "func_name": "Spidr.SessionCache.[]", "original_string": "def [](url)\n # normalize the url\n url = URI(url)\n\n # session key\n key = key_for(url)\n\n unless @sessions[key]\n session = Net::HTTP::Proxy(\n @proxy.host,\n @proxy.port,\n @proxy.user,\n @proxy.password\n ).new(url.host,url.port)\n\n session.open_timeout = @open_timeout if @open_timeout\n session.read_timeout = @read_timeout if @read_timeout\n session.continue_timeout = @continue_timeout if @continue_timeout\n session.keep_alive_timeout = @keep_alive_timeout if @keep_alive_timeout\n\n if url.scheme == 'https'\n session.use_ssl = true\n session.verify_mode = OpenSSL::SSL::VERIFY_NONE\n session.ssl_timeout = @ssl_timeout\n session.start\n end\n\n @sessions[key] = session\n end\n\n return @sessions[key]\n end", "language": "ruby", "code": "def [](url)\n # normalize the url\n url = URI(url)\n\n # session key\n key = key_for(url)\n\n unless @sessions[key]\n session = Net::HTTP::Proxy(\n @proxy.host,\n @proxy.port,\n @proxy.user,\n @proxy.password\n ).new(url.host,url.port)\n\n session.open_timeout = @open_timeout if @open_timeout\n session.read_timeout = @read_timeout if @read_timeout\n session.continue_timeout = @continue_timeout if @continue_timeout\n session.keep_alive_timeout = @keep_alive_timeout if @keep_alive_timeout\n\n if url.scheme == 'https'\n session.use_ssl = true\n session.verify_mode = OpenSSL::SSL::VERIFY_NONE\n session.ssl_timeout = @ssl_timeout\n session.start\n end\n\n @sessions[key] = session\n end\n\n return @sessions[key]\n end", "code_tokens": ["def", "[]", "(", "url", ")", "# normalize the url", "url", "=", "URI", "(", "url", ")", "# session key", "key", "=", "key_for", "(", "url", ")", "unless", "@sessions", "[", "key", "]", "session", "=", "Net", "::", "HTTP", "::", "Proxy", "(", "@proxy", ".", "host", ",", "@proxy", ".", "port", ",", "@proxy", ".", "user", ",", "@proxy", ".", "password", ")", ".", "new", "(", "url", ".", "host", ",", "url", ".", "port", ")", "session", ".", "open_timeout", "=", "@open_timeout", "if", "@open_timeout", "session", ".", "read_timeout", "=", "@read_timeout", "if", "@read_timeout", "session", ".", "continue_timeout", "=", "@continue_timeout", "if", "@continue_timeout", "session", ".", "keep_alive_timeout", "=", "@keep_alive_timeout", "if", "@keep_alive_timeout", "if", "url", ".", "scheme", "==", "'https'", "session", ".", "use_ssl", "=", "true", "session", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "session", ".", "ssl_timeout", "=", "@ssl_timeout", "session", ".", "start", "end", "@sessions", "[", "key", "]", "=", "session", "end", "return", "@sessions", "[", "key", "]", "end"], "docstring": "Provides an active HTTP session for a given URL.\n\n @param [URI::HTTP, String] url\n The URL which will be requested later.\n\n @return [Net::HTTP]\n The active HTTP session object.", "docstring_tokens": ["Provides", "an", "active", "HTTP", "session", "for", "a", "given", "URL", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/session_cache.rb#L85-L116", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/session_cache.rb", "func_name": "Spidr.SessionCache.kill!", "original_string": "def kill!(url)\n # normalize the url\n url = URI(url)\n\n # session key\n key = key_for(url)\n\n if (sess = @sessions[key])\n begin \n sess.finish\n rescue IOError\n end\n\n @sessions.delete(key)\n end\n end", "language": "ruby", "code": "def kill!(url)\n # normalize the url\n url = URI(url)\n\n # session key\n key = key_for(url)\n\n if (sess = @sessions[key])\n begin \n sess.finish\n rescue IOError\n end\n\n @sessions.delete(key)\n end\n end", "code_tokens": ["def", "kill!", "(", "url", ")", "# normalize the url", "url", "=", "URI", "(", "url", ")", "# session key", "key", "=", "key_for", "(", "url", ")", "if", "(", "sess", "=", "@sessions", "[", "key", "]", ")", "begin", "sess", ".", "finish", "rescue", "IOError", "end", "@sessions", ".", "delete", "(", "key", ")", "end", "end"], "docstring": "Destroys an HTTP session for the given scheme, host and port.\n\n @param [URI::HTTP, String] url\n The URL of the requested session.\n\n @return [nil]\n\n @since 0.2.2", "docstring_tokens": ["Destroys", "an", "HTTP", "session", "for", "the", "given", "scheme", "host", "and", "port", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/session_cache.rb#L128-L143", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/agent/sanitizers.rb", "func_name": "Spidr.Agent.sanitize_url", "original_string": "def sanitize_url(url)\n url = URI(url)\n\n url.fragment = nil if @strip_fragments\n url.query = nil if @strip_query\n\n return url\n end", "language": "ruby", "code": "def sanitize_url(url)\n url = URI(url)\n\n url.fragment = nil if @strip_fragments\n url.query = nil if @strip_query\n\n return url\n end", "code_tokens": ["def", "sanitize_url", "(", "url", ")", "url", "=", "URI", "(", "url", ")", "url", ".", "fragment", "=", "nil", "if", "@strip_fragments", "url", ".", "query", "=", "nil", "if", "@strip_query", "return", "url", "end"], "docstring": "Sanitizes a URL based on filtering options.\n\n @param [URI::HTTP, URI::HTTPS, String] url\n The URL to be sanitized\n\n @return [URI::HTTP, URI::HTTPS]\n The new sanitized URL.\n\n @since 0.2.2", "docstring_tokens": ["Sanitizes", "a", "URL", "based", "on", "filtering", "options", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent/sanitizers.rb#L23-L30", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/page.rb", "func_name": "Spidr.Page.doc", "original_string": "def doc\n unless body.empty?\n doc_class = if html?\n Nokogiri::HTML::Document\n elsif rss? || atom? || xml? || xsl?\n Nokogiri::XML::Document\n end\n\n if doc_class\n begin\n @doc ||= doc_class.parse(body, @url.to_s, content_charset)\n rescue\n end\n end\n end\n end", "language": "ruby", "code": "def doc\n unless body.empty?\n doc_class = if html?\n Nokogiri::HTML::Document\n elsif rss? || atom? || xml? || xsl?\n Nokogiri::XML::Document\n end\n\n if doc_class\n begin\n @doc ||= doc_class.parse(body, @url.to_s, content_charset)\n rescue\n end\n end\n end\n end", "code_tokens": ["def", "doc", "unless", "body", ".", "empty?", "doc_class", "=", "if", "html?", "Nokogiri", "::", "HTML", "::", "Document", "elsif", "rss?", "||", "atom?", "||", "xml?", "||", "xsl?", "Nokogiri", "::", "XML", "::", "Document", "end", "if", "doc_class", "begin", "@doc", "||=", "doc_class", ".", "parse", "(", "body", ",", "@url", ".", "to_s", ",", "content_charset", ")", "rescue", "end", "end", "end", "end"], "docstring": "Returns a parsed document object for HTML, XML, RSS and Atom pages.\n\n @return [Nokogiri::HTML::Document, Nokogiri::XML::Document, nil]\n The document that represents HTML or XML pages.\n Returns `nil` if the page is neither HTML, XML, RSS, Atom or if\n the page could not be parsed properly.\n\n @see http://nokogiri.rubyforge.org/nokogiri/Nokogiri/XML/Document.html\n @see http://nokogiri.rubyforge.org/nokogiri/Nokogiri/HTML/Document.html", "docstring_tokens": ["Returns", "a", "parsed", "document", "object", "for", "HTML", "XML", "RSS", "and", "Atom", "pages", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page.rb#L55-L70", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/page/content_types.rb", "func_name": "Spidr.Page.content_charset", "original_string": "def content_charset\n content_types.each do |value|\n if value.include?(';')\n value.split(';').each do |param|\n param.strip!\n\n if param.start_with?('charset=')\n return param.split('=',2).last\n end\n end\n end\n end\n\n return nil\n end", "language": "ruby", "code": "def content_charset\n content_types.each do |value|\n if value.include?(';')\n value.split(';').each do |param|\n param.strip!\n\n if param.start_with?('charset=')\n return param.split('=',2).last\n end\n end\n end\n end\n\n return nil\n end", "code_tokens": ["def", "content_charset", "content_types", ".", "each", "do", "|", "value", "|", "if", "value", ".", "include?", "(", "';'", ")", "value", ".", "split", "(", "';'", ")", ".", "each", "do", "|", "param", "|", "param", ".", "strip!", "if", "param", ".", "start_with?", "(", "'charset='", ")", "return", "param", ".", "split", "(", "'='", ",", "2", ")", ".", "last", "end", "end", "end", "end", "return", "nil", "end"], "docstring": "The charset included in the Content-Type.\n\n @return [String, nil]\n The charset of the content.\n\n @since 0.4.0", "docstring_tokens": ["The", "charset", "included", "in", "the", "Content", "-", "Type", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/content_types.rb#L33-L47", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/page/content_types.rb", "func_name": "Spidr.Page.is_content_type?", "original_string": "def is_content_type?(type)\n if type.include?('/')\n # otherwise only match the first param\n content_types.any? do |value|\n value = value.split(';',2).first\n\n value == type\n end\n else\n # otherwise only match the sub-type\n content_types.any? do |value|\n value = value.split(';',2).first\n value = value.split('/',2).last\n\n value == type\n end\n end\n end", "language": "ruby", "code": "def is_content_type?(type)\n if type.include?('/')\n # otherwise only match the first param\n content_types.any? do |value|\n value = value.split(';',2).first\n\n value == type\n end\n else\n # otherwise only match the sub-type\n content_types.any? do |value|\n value = value.split(';',2).first\n value = value.split('/',2).last\n\n value == type\n end\n end\n end", "code_tokens": ["def", "is_content_type?", "(", "type", ")", "if", "type", ".", "include?", "(", "'/'", ")", "# otherwise only match the first param", "content_types", ".", "any?", "do", "|", "value", "|", "value", "=", "value", ".", "split", "(", "';'", ",", "2", ")", ".", "first", "value", "==", "type", "end", "else", "# otherwise only match the sub-type", "content_types", ".", "any?", "do", "|", "value", "|", "value", "=", "value", ".", "split", "(", "';'", ",", "2", ")", ".", "first", "value", "=", "value", ".", "split", "(", "'/'", ",", "2", ")", ".", "last", "value", "==", "type", "end", "end", "end"], "docstring": "Determines if any of the content-types of the page include a given\n type.\n\n @param [String] type\n The content-type to test for.\n\n @return [Boolean]\n Specifies whether the page includes the given content-type.\n\n @example Match the Content-Type\n page.is_content_type?('application/json')\n\n @example Match the sub-type of the Content-Type\n page.is_content_type?('json')\n\n @since 0.4.0", "docstring_tokens": ["Determines", "if", "any", "of", "the", "content", "-", "types", "of", "the", "page", "include", "a", "given", "type", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/content_types.rb#L67-L84", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/cookie_jar.rb", "func_name": "Spidr.CookieJar.[]=", "original_string": "def []=(host,cookies)\n collected = self[host]\n\n cookies.each do |key,value|\n if collected[key] != value\n collected.merge!(cookies)\n @dirty << host\n\n break\n end\n end\n\n return cookies\n end", "language": "ruby", "code": "def []=(host,cookies)\n collected = self[host]\n\n cookies.each do |key,value|\n if collected[key] != value\n collected.merge!(cookies)\n @dirty << host\n\n break\n end\n end\n\n return cookies\n end", "code_tokens": ["def", "[]=", "(", "host", ",", "cookies", ")", "collected", "=", "self", "[", "host", "]", "cookies", ".", "each", "do", "|", "key", ",", "value", "|", "if", "collected", "[", "key", "]", "!=", "value", "collected", ".", "merge!", "(", "cookies", ")", "@dirty", "<<", "host", "break", "end", "end", "return", "cookies", "end"], "docstring": "Add a cookie to the jar for a particular domain.\n\n @param [String] host\n Host or domain name to associate with the cookie.\n\n @param [Hash{String => String}] cookies\n Cookie params.\n\n @since 0.2.2", "docstring_tokens": ["Add", "a", "cookie", "to", "the", "jar", "for", "a", "particular", "domain", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/cookie_jar.rb#L73-L86", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/cookie_jar.rb", "func_name": "Spidr.CookieJar.from_page", "original_string": "def from_page(page)\n cookies = page.cookie_params\n\n unless cookies.empty?\n self[page.url.host] = cookies\n return true\n end\n\n return false\n end", "language": "ruby", "code": "def from_page(page)\n cookies = page.cookie_params\n\n unless cookies.empty?\n self[page.url.host] = cookies\n return true\n end\n\n return false\n end", "code_tokens": ["def", "from_page", "(", "page", ")", "cookies", "=", "page", ".", "cookie_params", "unless", "cookies", ".", "empty?", "self", "[", "page", ".", "url", ".", "host", "]", "=", "cookies", "return", "true", "end", "return", "false", "end"], "docstring": "Retrieve cookies for a domain from a page response header.\n\n @param [Page] page\n The response page from which to extract cookie data.\n\n @return [Boolean]\n Specifies whether cookies were added from the page.\n\n @since 0.2.2", "docstring_tokens": ["Retrieve", "cookies", "for", "a", "domain", "from", "a", "page", "response", "header", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/cookie_jar.rb#L99-L108", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/cookie_jar.rb", "func_name": "Spidr.CookieJar.for_host", "original_string": "def for_host(host)\n if @dirty.include?(host)\n values = []\n\n cookies_for_host(host).each do |name,value|\n values << \"#{name}=#{value}\"\n end\n\n @cookies[host] = values.join('; ')\n @dirty.delete(host)\n end\n\n return @cookies[host]\n end", "language": "ruby", "code": "def for_host(host)\n if @dirty.include?(host)\n values = []\n\n cookies_for_host(host).each do |name,value|\n values << \"#{name}=#{value}\"\n end\n\n @cookies[host] = values.join('; ')\n @dirty.delete(host)\n end\n\n return @cookies[host]\n end", "code_tokens": ["def", "for_host", "(", "host", ")", "if", "@dirty", ".", "include?", "(", "host", ")", "values", "=", "[", "]", "cookies_for_host", "(", "host", ")", ".", "each", "do", "|", "name", ",", "value", "|", "values", "<<", "\"#{name}=#{value}\"", "end", "@cookies", "[", "host", "]", "=", "values", ".", "join", "(", "'; '", ")", "@dirty", ".", "delete", "(", "host", ")", "end", "return", "@cookies", "[", "host", "]", "end"], "docstring": "Returns the pre-encoded Cookie for a given host.\n\n @param [String] host\n The name of the host.\n\n @return [String]\n The encoded Cookie.\n\n @since 0.2.2", "docstring_tokens": ["Returns", "the", "pre", "-", "encoded", "Cookie", "for", "a", "given", "host", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/cookie_jar.rb#L121-L134", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/auth_store.rb", "func_name": "Spidr.AuthStore.[]", "original_string": "def [](url)\n # normalize the url\n url = URI(url)\n\n key = [url.scheme, url.host, url.port]\n paths = @credentials[key]\n\n return nil unless paths\n\n # longest path first\n ordered_paths = paths.keys.sort_by { |path_key| -path_key.length }\n\n # directories of the path\n path_dirs = URI.expand_path(url.path).split('/')\n\n ordered_paths.each do |path|\n return paths[path] if path_dirs[0,path.length] == path\n end\n\n return nil\n end", "language": "ruby", "code": "def [](url)\n # normalize the url\n url = URI(url)\n\n key = [url.scheme, url.host, url.port]\n paths = @credentials[key]\n\n return nil unless paths\n\n # longest path first\n ordered_paths = paths.keys.sort_by { |path_key| -path_key.length }\n\n # directories of the path\n path_dirs = URI.expand_path(url.path).split('/')\n\n ordered_paths.each do |path|\n return paths[path] if path_dirs[0,path.length] == path\n end\n\n return nil\n end", "code_tokens": ["def", "[]", "(", "url", ")", "# normalize the url", "url", "=", "URI", "(", "url", ")", "key", "=", "[", "url", ".", "scheme", ",", "url", ".", "host", ",", "url", ".", "port", "]", "paths", "=", "@credentials", "[", "key", "]", "return", "nil", "unless", "paths", "# longest path first", "ordered_paths", "=", "paths", ".", "keys", ".", "sort_by", "{", "|", "path_key", "|", "-", "path_key", ".", "length", "}", "# directories of the path", "path_dirs", "=", "URI", ".", "expand_path", "(", "url", ".", "path", ")", ".", "split", "(", "'/'", ")", "ordered_paths", ".", "each", "do", "|", "path", "|", "return", "paths", "[", "path", "]", "if", "path_dirs", "[", "0", ",", "path", ".", "length", "]", "==", "path", "end", "return", "nil", "end"], "docstring": "Creates a new auth store.\n\n @since 0.2.2\n\n\n Given a URL, return the most specific matching auth credential.\n\n @param [URI] url\n A fully qualified url including optional path.\n\n @return [AuthCredential, nil]\n Closest matching {AuthCredential} values for the URL,\n or `nil` if nothing matches.\n\n @since 0.2.2", "docstring_tokens": ["Creates", "a", "new", "auth", "store", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/auth_store.rb#L35-L55", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/auth_store.rb", "func_name": "Spidr.AuthStore.[]=", "original_string": "def []=(url,auth)\n # normalize the url\n url = URI(url)\n\n # normalize the URL path\n path = URI.expand_path(url.path)\n\n key = [url.scheme, url.host, url.port]\n\n @credentials[key] ||= {}\n @credentials[key][path.split('/')] = auth\n return auth\n end", "language": "ruby", "code": "def []=(url,auth)\n # normalize the url\n url = URI(url)\n\n # normalize the URL path\n path = URI.expand_path(url.path)\n\n key = [url.scheme, url.host, url.port]\n\n @credentials[key] ||= {}\n @credentials[key][path.split('/')] = auth\n return auth\n end", "code_tokens": ["def", "[]=", "(", "url", ",", "auth", ")", "# normalize the url", "url", "=", "URI", "(", "url", ")", "# normalize the URL path", "path", "=", "URI", ".", "expand_path", "(", "url", ".", "path", ")", "key", "=", "[", "url", ".", "scheme", ",", "url", ".", "host", ",", "url", ".", "port", "]", "@credentials", "[", "key", "]", "||=", "{", "}", "@credentials", "[", "key", "]", "[", "path", ".", "split", "(", "'/'", ")", "]", "=", "auth", "return", "auth", "end"], "docstring": "Add an auth credential to the store for supplied base URL.\n\n @param [URI] url\n A URL pattern to associate with a set of auth credentials.\n\n @param [AuthCredential] auth\n The auth credential for this URL pattern.\n\n @return [AuthCredential]\n The newly added auth credential.\n\n @since 0.2.2", "docstring_tokens": ["Add", "an", "auth", "credential", "to", "the", "store", "for", "supplied", "base", "URL", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/auth_store.rb#L71-L83", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/agent.rb", "func_name": "Spidr.Agent.run", "original_string": "def run(&block)\n @running = true\n\n until (@queue.empty? || paused? || limit_reached?)\n begin\n visit_page(dequeue,&block)\n rescue Actions::Paused\n return self\n rescue Actions::Action\n end\n end\n\n @running = false\n @sessions.clear\n return self\n end", "language": "ruby", "code": "def run(&block)\n @running = true\n\n until (@queue.empty? || paused? || limit_reached?)\n begin\n visit_page(dequeue,&block)\n rescue Actions::Paused\n return self\n rescue Actions::Action\n end\n end\n\n @running = false\n @sessions.clear\n return self\n end", "code_tokens": ["def", "run", "(", "&", "block", ")", "@running", "=", "true", "until", "(", "@queue", ".", "empty?", "||", "paused?", "||", "limit_reached?", ")", "begin", "visit_page", "(", "dequeue", ",", "block", ")", "rescue", "Actions", "::", "Paused", "return", "self", "rescue", "Actions", "::", "Action", "end", "end", "@running", "=", "false", "@sessions", ".", "clear", "return", "self", "end"], "docstring": "Start spidering until the queue becomes empty or the agent is\n paused.\n\n @yield [page]\n If a block is given, it will be passed every page visited.\n\n @yieldparam [Page] page\n A page which has been visited.", "docstring_tokens": ["Start", "spidering", "until", "the", "queue", "becomes", "empty", "or", "the", "agent", "is", "paused", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L368-L383", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/agent.rb", "func_name": "Spidr.Agent.enqueue", "original_string": "def enqueue(url,level=0)\n url = sanitize_url(url)\n\n if (!(queued?(url)) && visit?(url))\n link = url.to_s\n\n begin\n @every_url_blocks.each { |url_block| url_block.call(url) }\n\n @every_url_like_blocks.each do |pattern,url_blocks|\n match = case pattern\n when Regexp\n link =~ pattern\n else\n (pattern == link) || (pattern == url)\n end\n\n if match\n url_blocks.each { |url_block| url_block.call(url) }\n end\n end\n rescue Actions::Paused => action\n raise(action)\n rescue Actions::SkipLink\n return false\n rescue Actions::Action\n end\n\n @queue << url\n @levels[url] = level\n return true\n end\n\n return false\n end", "language": "ruby", "code": "def enqueue(url,level=0)\n url = sanitize_url(url)\n\n if (!(queued?(url)) && visit?(url))\n link = url.to_s\n\n begin\n @every_url_blocks.each { |url_block| url_block.call(url) }\n\n @every_url_like_blocks.each do |pattern,url_blocks|\n match = case pattern\n when Regexp\n link =~ pattern\n else\n (pattern == link) || (pattern == url)\n end\n\n if match\n url_blocks.each { |url_block| url_block.call(url) }\n end\n end\n rescue Actions::Paused => action\n raise(action)\n rescue Actions::SkipLink\n return false\n rescue Actions::Action\n end\n\n @queue << url\n @levels[url] = level\n return true\n end\n\n return false\n end", "code_tokens": ["def", "enqueue", "(", "url", ",", "level", "=", "0", ")", "url", "=", "sanitize_url", "(", "url", ")", "if", "(", "!", "(", "queued?", "(", "url", ")", ")", "&&", "visit?", "(", "url", ")", ")", "link", "=", "url", ".", "to_s", "begin", "@every_url_blocks", ".", "each", "{", "|", "url_block", "|", "url_block", ".", "call", "(", "url", ")", "}", "@every_url_like_blocks", ".", "each", "do", "|", "pattern", ",", "url_blocks", "|", "match", "=", "case", "pattern", "when", "Regexp", "link", "=~", "pattern", "else", "(", "pattern", "==", "link", ")", "||", "(", "pattern", "==", "url", ")", "end", "if", "match", "url_blocks", ".", "each", "{", "|", "url_block", "|", "url_block", ".", "call", "(", "url", ")", "}", "end", "end", "rescue", "Actions", "::", "Paused", "=>", "action", "raise", "(", "action", ")", "rescue", "Actions", "::", "SkipLink", "return", "false", "rescue", "Actions", "::", "Action", "end", "@queue", "<<", "url", "@levels", "[", "url", "]", "=", "level", "return", "true", "end", "return", "false", "end"], "docstring": "Enqueues a given URL for visiting, only if it passes all of the\n agent's rules for visiting a given URL.\n\n @param [URI::HTTP, String] url\n The URL to enqueue for visiting.\n\n @return [Boolean]\n Specifies whether the URL was enqueued, or ignored.", "docstring_tokens": ["Enqueues", "a", "given", "URL", "for", "visiting", "only", "if", "it", "passes", "all", "of", "the", "agent", "s", "rules", "for", "visiting", "a", "given", "URL", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L534-L568", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/agent.rb", "func_name": "Spidr.Agent.get_page", "original_string": "def get_page(url)\n url = URI(url)\n\n prepare_request(url) do |session,path,headers|\n new_page = Page.new(url,session.get(path,headers))\n\n # save any new cookies\n @cookies.from_page(new_page)\n\n yield new_page if block_given?\n return new_page\n end\n end", "language": "ruby", "code": "def get_page(url)\n url = URI(url)\n\n prepare_request(url) do |session,path,headers|\n new_page = Page.new(url,session.get(path,headers))\n\n # save any new cookies\n @cookies.from_page(new_page)\n\n yield new_page if block_given?\n return new_page\n end\n end", "code_tokens": ["def", "get_page", "(", "url", ")", "url", "=", "URI", "(", "url", ")", "prepare_request", "(", "url", ")", "do", "|", "session", ",", "path", ",", "headers", "|", "new_page", "=", "Page", ".", "new", "(", "url", ",", "session", ".", "get", "(", "path", ",", "headers", ")", ")", "# save any new cookies", "@cookies", ".", "from_page", "(", "new_page", ")", "yield", "new_page", "if", "block_given?", "return", "new_page", "end", "end"], "docstring": "Requests and creates a new Page object from a given URL.\n\n @param [URI::HTTP] url\n The URL to request.\n\n @yield [page]\n If a block is given, it will be passed the page that represents the\n response.\n\n @yieldparam [Page] page\n The page for the response.\n\n @return [Page, nil]\n The page for the response, or `nil` if the request failed.", "docstring_tokens": ["Requests", "and", "creates", "a", "new", "Page", "object", "from", "a", "given", "URL", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L586-L598", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/agent.rb", "func_name": "Spidr.Agent.post_page", "original_string": "def post_page(url,post_data='')\n url = URI(url)\n\n prepare_request(url) do |session,path,headers|\n new_page = Page.new(url,session.post(path,post_data,headers))\n\n # save any new cookies\n @cookies.from_page(new_page)\n\n yield new_page if block_given?\n return new_page\n end\n end", "language": "ruby", "code": "def post_page(url,post_data='')\n url = URI(url)\n\n prepare_request(url) do |session,path,headers|\n new_page = Page.new(url,session.post(path,post_data,headers))\n\n # save any new cookies\n @cookies.from_page(new_page)\n\n yield new_page if block_given?\n return new_page\n end\n end", "code_tokens": ["def", "post_page", "(", "url", ",", "post_data", "=", "''", ")", "url", "=", "URI", "(", "url", ")", "prepare_request", "(", "url", ")", "do", "|", "session", ",", "path", ",", "headers", "|", "new_page", "=", "Page", ".", "new", "(", "url", ",", "session", ".", "post", "(", "path", ",", "post_data", ",", "headers", ")", ")", "# save any new cookies", "@cookies", ".", "from_page", "(", "new_page", ")", "yield", "new_page", "if", "block_given?", "return", "new_page", "end", "end"], "docstring": "Posts supplied form data and creates a new Page object from a given URL.\n\n @param [URI::HTTP] url\n The URL to request.\n\n @param [String] post_data\n Form option data.\n\n @yield [page]\n If a block is given, it will be passed the page that represents the\n response.\n\n @yieldparam [Page] page\n The page for the response.\n\n @return [Page, nil]\n The page for the response, or `nil` if the request failed.\n\n @since 0.2.2", "docstring_tokens": ["Posts", "supplied", "form", "data", "and", "creates", "a", "new", "Page", "object", "from", "a", "given", "URL", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L621-L633", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/agent.rb", "func_name": "Spidr.Agent.visit_page", "original_string": "def visit_page(url)\n url = sanitize_url(url)\n\n get_page(url) do |page|\n @history << page.url\n\n begin\n @every_page_blocks.each { |page_block| page_block.call(page) }\n\n yield page if block_given?\n rescue Actions::Paused => action\n raise(action)\n rescue Actions::SkipPage\n return nil\n rescue Actions::Action\n end\n\n page.each_url do |next_url|\n begin\n @every_link_blocks.each do |link_block|\n link_block.call(page.url,next_url)\n end\n rescue Actions::Paused => action\n raise(action)\n rescue Actions::SkipLink\n next\n rescue Actions::Action\n end\n\n if (@max_depth.nil? || @max_depth > @levels[url])\n enqueue(next_url,@levels[url] + 1)\n end\n end\n end\n end", "language": "ruby", "code": "def visit_page(url)\n url = sanitize_url(url)\n\n get_page(url) do |page|\n @history << page.url\n\n begin\n @every_page_blocks.each { |page_block| page_block.call(page) }\n\n yield page if block_given?\n rescue Actions::Paused => action\n raise(action)\n rescue Actions::SkipPage\n return nil\n rescue Actions::Action\n end\n\n page.each_url do |next_url|\n begin\n @every_link_blocks.each do |link_block|\n link_block.call(page.url,next_url)\n end\n rescue Actions::Paused => action\n raise(action)\n rescue Actions::SkipLink\n next\n rescue Actions::Action\n end\n\n if (@max_depth.nil? || @max_depth > @levels[url])\n enqueue(next_url,@levels[url] + 1)\n end\n end\n end\n end", "code_tokens": ["def", "visit_page", "(", "url", ")", "url", "=", "sanitize_url", "(", "url", ")", "get_page", "(", "url", ")", "do", "|", "page", "|", "@history", "<<", "page", ".", "url", "begin", "@every_page_blocks", ".", "each", "{", "|", "page_block", "|", "page_block", ".", "call", "(", "page", ")", "}", "yield", "page", "if", "block_given?", "rescue", "Actions", "::", "Paused", "=>", "action", "raise", "(", "action", ")", "rescue", "Actions", "::", "SkipPage", "return", "nil", "rescue", "Actions", "::", "Action", "end", "page", ".", "each_url", "do", "|", "next_url", "|", "begin", "@every_link_blocks", ".", "each", "do", "|", "link_block", "|", "link_block", ".", "call", "(", "page", ".", "url", ",", "next_url", ")", "end", "rescue", "Actions", "::", "Paused", "=>", "action", "raise", "(", "action", ")", "rescue", "Actions", "::", "SkipLink", "next", "rescue", "Actions", "::", "Action", "end", "if", "(", "@max_depth", ".", "nil?", "||", "@max_depth", ">", "@levels", "[", "url", "]", ")", "enqueue", "(", "next_url", ",", "@levels", "[", "url", "]", "+", "1", ")", "end", "end", "end", "end"], "docstring": "Visits a given URL, and enqueus the links recovered from the URL\n to be visited later.\n\n @param [URI::HTTP, String] url\n The URL to visit.\n\n @yield [page]\n If a block is given, it will be passed the page which was visited.\n\n @yieldparam [Page] page\n The page which was visited.\n\n @return [Page, nil]\n The page that was visited. If `nil` is returned, either the request\n for the page failed, or the page was skipped.", "docstring_tokens": ["Visits", "a", "given", "URL", "and", "enqueus", "the", "links", "recovered", "from", "the", "URL", "to", "be", "visited", "later", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L652-L686", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/agent.rb", "func_name": "Spidr.Agent.prepare_request_headers", "original_string": "def prepare_request_headers(url)\n # set any additional HTTP headers\n headers = @default_headers.dup\n\n unless @host_headers.empty?\n @host_headers.each do |name,header|\n if url.host.match(name)\n headers['Host'] = header\n break\n end\n end\n end\n\n headers['Host'] ||= @host_header if @host_header\n headers['User-Agent'] = @user_agent if @user_agent\n headers['Referer'] = @referer if @referer\n\n if (authorization = @authorized.for_url(url))\n headers['Authorization'] = \"Basic #{authorization}\"\n end\n\n if (header_cookies = @cookies.for_host(url.host))\n headers['Cookie'] = header_cookies\n end\n\n return headers\n end", "language": "ruby", "code": "def prepare_request_headers(url)\n # set any additional HTTP headers\n headers = @default_headers.dup\n\n unless @host_headers.empty?\n @host_headers.each do |name,header|\n if url.host.match(name)\n headers['Host'] = header\n break\n end\n end\n end\n\n headers['Host'] ||= @host_header if @host_header\n headers['User-Agent'] = @user_agent if @user_agent\n headers['Referer'] = @referer if @referer\n\n if (authorization = @authorized.for_url(url))\n headers['Authorization'] = \"Basic #{authorization}\"\n end\n\n if (header_cookies = @cookies.for_host(url.host))\n headers['Cookie'] = header_cookies\n end\n\n return headers\n end", "code_tokens": ["def", "prepare_request_headers", "(", "url", ")", "# set any additional HTTP headers", "headers", "=", "@default_headers", ".", "dup", "unless", "@host_headers", ".", "empty?", "@host_headers", ".", "each", "do", "|", "name", ",", "header", "|", "if", "url", ".", "host", ".", "match", "(", "name", ")", "headers", "[", "'Host'", "]", "=", "header", "break", "end", "end", "end", "headers", "[", "'Host'", "]", "||=", "@host_header", "if", "@host_header", "headers", "[", "'User-Agent'", "]", "=", "@user_agent", "if", "@user_agent", "headers", "[", "'Referer'", "]", "=", "@referer", "if", "@referer", "if", "(", "authorization", "=", "@authorized", ".", "for_url", "(", "url", ")", ")", "headers", "[", "'Authorization'", "]", "=", "\"Basic #{authorization}\"", "end", "if", "(", "header_cookies", "=", "@cookies", ".", "for_host", "(", "url", ".", "host", ")", ")", "headers", "[", "'Cookie'", "]", "=", "header_cookies", "end", "return", "headers", "end"], "docstring": "Prepares request headers for the given URL.\n\n @param [URI::HTTP] url\n The URL to prepare the request headers for.\n\n @return [Hash{String => String}]\n The prepared headers.\n\n @since 0.6.0", "docstring_tokens": ["Prepares", "request", "headers", "for", "the", "given", "URL", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L712-L738", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/agent.rb", "func_name": "Spidr.Agent.prepare_request", "original_string": "def prepare_request(url,&block)\n path = unless url.path.empty?\n url.path\n else\n '/'\n end\n\n # append the URL query to the path\n path += \"?#{url.query}\" if url.query\n\n headers = prepare_request_headers(url)\n\n begin\n sleep(@delay) if @delay > 0\n\n yield @sessions[url], path, headers\n rescue SystemCallError,\n Timeout::Error,\n SocketError,\n IOError,\n OpenSSL::SSL::SSLError,\n Net::HTTPBadResponse,\n Zlib::Error\n\n @sessions.kill!(url)\n\n failed(url)\n return nil\n end\n end", "language": "ruby", "code": "def prepare_request(url,&block)\n path = unless url.path.empty?\n url.path\n else\n '/'\n end\n\n # append the URL query to the path\n path += \"?#{url.query}\" if url.query\n\n headers = prepare_request_headers(url)\n\n begin\n sleep(@delay) if @delay > 0\n\n yield @sessions[url], path, headers\n rescue SystemCallError,\n Timeout::Error,\n SocketError,\n IOError,\n OpenSSL::SSL::SSLError,\n Net::HTTPBadResponse,\n Zlib::Error\n\n @sessions.kill!(url)\n\n failed(url)\n return nil\n end\n end", "code_tokens": ["def", "prepare_request", "(", "url", ",", "&", "block", ")", "path", "=", "unless", "url", ".", "path", ".", "empty?", "url", ".", "path", "else", "'/'", "end", "# append the URL query to the path", "path", "+=", "\"?#{url.query}\"", "if", "url", ".", "query", "headers", "=", "prepare_request_headers", "(", "url", ")", "begin", "sleep", "(", "@delay", ")", "if", "@delay", ">", "0", "yield", "@sessions", "[", "url", "]", ",", "path", ",", "headers", "rescue", "SystemCallError", ",", "Timeout", "::", "Error", ",", "SocketError", ",", "IOError", ",", "OpenSSL", "::", "SSL", "::", "SSLError", ",", "Net", "::", "HTTPBadResponse", ",", "Zlib", "::", "Error", "@sessions", ".", "kill!", "(", "url", ")", "failed", "(", "url", ")", "return", "nil", "end", "end"], "docstring": "Normalizes the request path and grabs a session to handle page\n get and post requests.\n\n @param [URI::HTTP] url\n The URL to request.\n\n @yield [request]\n A block whose purpose is to make a page request.\n\n @yieldparam [Net::HTTP] session\n An HTTP session object.\n\n @yieldparam [String] path\n Normalized URL string.\n\n @yieldparam [Hash] headers\n A Hash of request header options.\n\n @since 0.2.2", "docstring_tokens": ["Normalizes", "the", "request", "path", "and", "grabs", "a", "session", "to", "handle", "page", "get", "and", "post", "requests", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L761-L790", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/agent.rb", "func_name": "Spidr.Agent.visit?", "original_string": "def visit?(url)\n !visited?(url) &&\n visit_scheme?(url.scheme) &&\n visit_host?(url.host) &&\n visit_port?(url.port) &&\n visit_link?(url.to_s) &&\n visit_url?(url) &&\n visit_ext?(url.path) &&\n robot_allowed?(url.to_s)\n end", "language": "ruby", "code": "def visit?(url)\n !visited?(url) &&\n visit_scheme?(url.scheme) &&\n visit_host?(url.host) &&\n visit_port?(url.port) &&\n visit_link?(url.to_s) &&\n visit_url?(url) &&\n visit_ext?(url.path) &&\n robot_allowed?(url.to_s)\n end", "code_tokens": ["def", "visit?", "(", "url", ")", "!", "visited?", "(", "url", ")", "&&", "visit_scheme?", "(", "url", ".", "scheme", ")", "&&", "visit_host?", "(", "url", ".", "host", ")", "&&", "visit_port?", "(", "url", ".", "port", ")", "&&", "visit_link?", "(", "url", ".", "to_s", ")", "&&", "visit_url?", "(", "url", ")", "&&", "visit_ext?", "(", "url", ".", "path", ")", "&&", "robot_allowed?", "(", "url", ".", "to_s", ")", "end"], "docstring": "Determines if a given URL should be visited.\n\n @param [URI::HTTP] url\n The URL in question.\n\n @return [Boolean]\n Specifies whether the given URL should be visited.", "docstring_tokens": ["Determines", "if", "a", "given", "URL", "should", "be", "visited", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L822-L831", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/rules.rb", "func_name": "Spidr.Rules.accept?", "original_string": "def accept?(data)\n unless @accept.empty?\n @accept.any? { |rule| test_data(data,rule) }\n else\n !@reject.any? { |rule| test_data(data,rule) }\n end\n end", "language": "ruby", "code": "def accept?(data)\n unless @accept.empty?\n @accept.any? { |rule| test_data(data,rule) }\n else\n !@reject.any? { |rule| test_data(data,rule) }\n end\n end", "code_tokens": ["def", "accept?", "(", "data", ")", "unless", "@accept", ".", "empty?", "@accept", ".", "any?", "{", "|", "rule", "|", "test_data", "(", "data", ",", "rule", ")", "}", "else", "!", "@reject", ".", "any?", "{", "|", "rule", "|", "test_data", "(", "data", ",", "rule", ")", "}", "end", "end"], "docstring": "Creates a new Rules object.\n\n @param [Hash] options\n Additional options.\n\n @option options [Array] :accept\n The patterns to accept data with.\n\n @option options [Array] :reject\n The patterns to reject data with.\n\n\n Determines whether the data should be accepted or rejected.\n\n @return [Boolean]\n Specifies whether the given data was accepted, using the rules\n acceptance patterns.", "docstring_tokens": ["Creates", "a", "new", "Rules", "object", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/rules.rb#L41-L47", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/agent/events.rb", "func_name": "Spidr.Agent.every_html_doc", "original_string": "def every_html_doc\n every_page do |page|\n if (block_given? && page.html?)\n if (doc = page.doc)\n yield doc\n end\n end\n end\n end", "language": "ruby", "code": "def every_html_doc\n every_page do |page|\n if (block_given? && page.html?)\n if (doc = page.doc)\n yield doc\n end\n end\n end\n end", "code_tokens": ["def", "every_html_doc", "every_page", "do", "|", "page", "|", "if", "(", "block_given?", "&&", "page", ".", "html?", ")", "if", "(", "doc", "=", "page", ".", "doc", ")", "yield", "doc", "end", "end", "end", "end"], "docstring": "Pass every HTML document that the agent parses to a given block.\n\n @yield [doc]\n The block will be passed every HTML document parsed.\n\n @yieldparam [Nokogiri::HTML::Document] doc\n A parsed HTML document.\n\n @see http://nokogiri.rubyforge.org/nokogiri/Nokogiri/HTML/Document.html", "docstring_tokens": ["Pass", "every", "HTML", "document", "that", "the", "agent", "parses", "to", "a", "given", "block", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent/events.rb#L302-L310", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/agent/events.rb", "func_name": "Spidr.Agent.every_xml_doc", "original_string": "def every_xml_doc\n every_page do |page|\n if (block_given? && page.xml?)\n if (doc = page.doc)\n yield doc\n end\n end\n end\n end", "language": "ruby", "code": "def every_xml_doc\n every_page do |page|\n if (block_given? && page.xml?)\n if (doc = page.doc)\n yield doc\n end\n end\n end\n end", "code_tokens": ["def", "every_xml_doc", "every_page", "do", "|", "page", "|", "if", "(", "block_given?", "&&", "page", ".", "xml?", ")", "if", "(", "doc", "=", "page", ".", "doc", ")", "yield", "doc", "end", "end", "end", "end"], "docstring": "Pass every XML document that the agent parses to a given block.\n\n @yield [doc]\n The block will be passed every XML document parsed.\n\n @yieldparam [Nokogiri::XML::Document] doc\n A parsed XML document.\n\n @see http://nokogiri.rubyforge.org/nokogiri/Nokogiri/XML/Document.html", "docstring_tokens": ["Pass", "every", "XML", "document", "that", "the", "agent", "parses", "to", "a", "given", "block", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent/events.rb#L323-L331", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/agent/events.rb", "func_name": "Spidr.Agent.every_rss_doc", "original_string": "def every_rss_doc\n every_page do |page|\n if (block_given? && page.rss?)\n if (doc = page.doc)\n yield doc\n end\n end\n end\n end", "language": "ruby", "code": "def every_rss_doc\n every_page do |page|\n if (block_given? && page.rss?)\n if (doc = page.doc)\n yield doc\n end\n end\n end\n end", "code_tokens": ["def", "every_rss_doc", "every_page", "do", "|", "page", "|", "if", "(", "block_given?", "&&", "page", ".", "rss?", ")", "if", "(", "doc", "=", "page", ".", "doc", ")", "yield", "doc", "end", "end", "end", "end"], "docstring": "Pass every RSS document that the agent parses to a given block.\n\n @yield [doc]\n The block will be passed every RSS document parsed.\n\n @yieldparam [Nokogiri::XML::Document] doc\n A parsed XML document.\n\n @see http://nokogiri.rubyforge.org/nokogiri/Nokogiri/XML/Document.html", "docstring_tokens": ["Pass", "every", "RSS", "document", "that", "the", "agent", "parses", "to", "a", "given", "block", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent/events.rb#L366-L374", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/agent/events.rb", "func_name": "Spidr.Agent.every_atom_doc", "original_string": "def every_atom_doc\n every_page do |page|\n if (block_given? && page.atom?)\n if (doc = page.doc)\n yield doc\n end\n end\n end\n end", "language": "ruby", "code": "def every_atom_doc\n every_page do |page|\n if (block_given? && page.atom?)\n if (doc = page.doc)\n yield doc\n end\n end\n end\n end", "code_tokens": ["def", "every_atom_doc", "every_page", "do", "|", "page", "|", "if", "(", "block_given?", "&&", "page", ".", "atom?", ")", "if", "(", "doc", "=", "page", ".", "doc", ")", "yield", "doc", "end", "end", "end", "end"], "docstring": "Pass every Atom document that the agent parses to a given block.\n\n @yield [doc]\n The block will be passed every Atom document parsed.\n\n @yieldparam [Nokogiri::XML::Document] doc\n A parsed XML document.\n\n @see http://nokogiri.rubyforge.org/nokogiri/Nokogiri/XML/Document.html", "docstring_tokens": ["Pass", "every", "Atom", "document", "that", "the", "agent", "parses", "to", "a", "given", "block", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent/events.rb#L387-L395", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/agent/filters.rb", "func_name": "Spidr.Agent.initialize_filters", "original_string": "def initialize_filters(options={})\n @schemes = []\n\n if options[:schemes]\n self.schemes = options[:schemes]\n else\n @schemes << 'http'\n\n begin\n require 'net/https'\n\n @schemes << 'https'\n rescue Gem::LoadError => e\n raise(e)\n rescue ::LoadError\n warn \"Warning: cannot load 'net/https', https support disabled\"\n end\n end\n\n @host_rules = Rules.new(\n accept: options[:hosts],\n reject: options[:ignore_hosts]\n )\n @port_rules = Rules.new(\n accept: options[:ports],\n reject: options[:ignore_ports]\n )\n @link_rules = Rules.new(\n accept: options[:links],\n reject: options[:ignore_links]\n )\n @url_rules = Rules.new(\n accept: options[:urls],\n reject: options[:ignore_urls]\n )\n @ext_rules = Rules.new(\n accept: options[:exts],\n reject: options[:ignore_exts]\n )\n\n if options[:host]\n visit_hosts_like(options[:host])\n end\n end", "language": "ruby", "code": "def initialize_filters(options={})\n @schemes = []\n\n if options[:schemes]\n self.schemes = options[:schemes]\n else\n @schemes << 'http'\n\n begin\n require 'net/https'\n\n @schemes << 'https'\n rescue Gem::LoadError => e\n raise(e)\n rescue ::LoadError\n warn \"Warning: cannot load 'net/https', https support disabled\"\n end\n end\n\n @host_rules = Rules.new(\n accept: options[:hosts],\n reject: options[:ignore_hosts]\n )\n @port_rules = Rules.new(\n accept: options[:ports],\n reject: options[:ignore_ports]\n )\n @link_rules = Rules.new(\n accept: options[:links],\n reject: options[:ignore_links]\n )\n @url_rules = Rules.new(\n accept: options[:urls],\n reject: options[:ignore_urls]\n )\n @ext_rules = Rules.new(\n accept: options[:exts],\n reject: options[:ignore_exts]\n )\n\n if options[:host]\n visit_hosts_like(options[:host])\n end\n end", "code_tokens": ["def", "initialize_filters", "(", "options", "=", "{", "}", ")", "@schemes", "=", "[", "]", "if", "options", "[", ":schemes", "]", "self", ".", "schemes", "=", "options", "[", ":schemes", "]", "else", "@schemes", "<<", "'http'", "begin", "require", "'net/https'", "@schemes", "<<", "'https'", "rescue", "Gem", "::", "LoadError", "=>", "e", "raise", "(", "e", ")", "rescue", "::", "LoadError", "warn", "\"Warning: cannot load 'net/https', https support disabled\"", "end", "end", "@host_rules", "=", "Rules", ".", "new", "(", "accept", ":", "options", "[", ":hosts", "]", ",", "reject", ":", "options", "[", ":ignore_hosts", "]", ")", "@port_rules", "=", "Rules", ".", "new", "(", "accept", ":", "options", "[", ":ports", "]", ",", "reject", ":", "options", "[", ":ignore_ports", "]", ")", "@link_rules", "=", "Rules", ".", "new", "(", "accept", ":", "options", "[", ":links", "]", ",", "reject", ":", "options", "[", ":ignore_links", "]", ")", "@url_rules", "=", "Rules", ".", "new", "(", "accept", ":", "options", "[", ":urls", "]", ",", "reject", ":", "options", "[", ":ignore_urls", "]", ")", "@ext_rules", "=", "Rules", ".", "new", "(", "accept", ":", "options", "[", ":exts", "]", ",", "reject", ":", "options", "[", ":ignore_exts", "]", ")", "if", "options", "[", ":host", "]", "visit_hosts_like", "(", "options", "[", ":host", "]", ")", "end", "end"], "docstring": "Initializes filtering rules.\n\n @param [Hash] options\n Additional options.\n\n @option options [Array] :schemes (['http', 'https'])\n The list of acceptable URI schemes to visit.\n The `https` scheme will be ignored if `net/https` cannot be loaded.\n\n @option options [String] :host\n The host-name to visit.\n\n @option options [Array] :hosts\n The patterns which match the host-names to visit.\n\n @option options [Array] :ignore_hosts\n The patterns which match the host-names to not visit.\n\n @option options [Array] :ports\n The patterns which match the ports to visit.\n\n @option options [Array] :ignore_ports\n The patterns which match the ports to not visit.\n\n @option options [Array] :links\n The patterns which match the links to visit.\n\n @option options [Array] :ignore_links\n The patterns which match the links to not visit.\n\n @option options [Array] :urls\n The patterns which match the URLs to visit.\n\n @option options [Array] :ignore_urls\n The patterns which match the URLs to not visit.\n\n @option options [Array] :exts\n The patterns which match the URI path extensions to visit.\n\n @option options [Array] :ignore_exts\n The patterns which match the URI path extensions to not visit.", "docstring_tokens": ["Initializes", "filtering", "rules", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent/filters.rb#L399-L442", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/page/html.rb", "func_name": "Spidr.Page.each_meta_redirect", "original_string": "def each_meta_redirect\n return enum_for(__method__) unless block_given?\n\n if (html? && doc)\n search('//meta[@http-equiv and @content]').each do |node|\n if node.get_attribute('http-equiv') =~ /refresh/i\n content = node.get_attribute('content')\n\n if (redirect = content.match(/url=(\\S+)$/))\n yield redirect[1]\n end\n end\n end\n end\n end", "language": "ruby", "code": "def each_meta_redirect\n return enum_for(__method__) unless block_given?\n\n if (html? && doc)\n search('//meta[@http-equiv and @content]').each do |node|\n if node.get_attribute('http-equiv') =~ /refresh/i\n content = node.get_attribute('content')\n\n if (redirect = content.match(/url=(\\S+)$/))\n yield redirect[1]\n end\n end\n end\n end\n end", "code_tokens": ["def", "each_meta_redirect", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "if", "(", "html?", "&&", "doc", ")", "search", "(", "'//meta[@http-equiv and @content]'", ")", ".", "each", "do", "|", "node", "|", "if", "node", ".", "get_attribute", "(", "'http-equiv'", ")", "=~", "/", "/i", "content", "=", "node", ".", "get_attribute", "(", "'content'", ")", "if", "(", "redirect", "=", "content", ".", "match", "(", "/", "\\S", "/", ")", ")", "yield", "redirect", "[", "1", "]", "end", "end", "end", "end", "end"], "docstring": "Enumerates over the meta-redirect links in the page.\n\n @yield [link]\n If a block is given, it will be passed every meta-redirect link\n from the page.\n\n @yieldparam [String] link\n A meta-redirect link from the page.\n\n @return [Enumerator]\n If no block is given, an enumerator object will be returned.\n\n @since 0.3.0", "docstring_tokens": ["Enumerates", "over", "the", "meta", "-", "redirect", "links", "in", "the", "page", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/html.rb#L35-L49", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/page/html.rb", "func_name": "Spidr.Page.each_redirect", "original_string": "def each_redirect(&block)\n return enum_for(__method__) unless block\n\n if (locations = @response.get_fields('Location'))\n # Location headers override any meta-refresh redirects in the HTML\n locations.each(&block)\n else\n # check page-level meta redirects if there isn't a location header\n each_meta_redirect(&block)\n end\n end", "language": "ruby", "code": "def each_redirect(&block)\n return enum_for(__method__) unless block\n\n if (locations = @response.get_fields('Location'))\n # Location headers override any meta-refresh redirects in the HTML\n locations.each(&block)\n else\n # check page-level meta redirects if there isn't a location header\n each_meta_redirect(&block)\n end\n end", "code_tokens": ["def", "each_redirect", "(", "&", "block", ")", "return", "enum_for", "(", "__method__", ")", "unless", "block", "if", "(", "locations", "=", "@response", ".", "get_fields", "(", "'Location'", ")", ")", "# Location headers override any meta-refresh redirects in the HTML", "locations", ".", "each", "(", "block", ")", "else", "# check page-level meta redirects if there isn't a location header", "each_meta_redirect", "(", "block", ")", "end", "end"], "docstring": "Enumerates over every HTTP or meta-redirect link in the page.\n\n @yield [link]\n The given block will be passed every redirection link from the page.\n\n @yieldparam [String] link\n A HTTP or meta-redirect link from the page.\n\n @return [Enumerator]\n If no block is given, an enumerator object will be returned.\n\n @since 0.3.0", "docstring_tokens": ["Enumerates", "over", "every", "HTTP", "or", "meta", "-", "redirect", "link", "in", "the", "page", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/html.rb#L105-L115", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/page/html.rb", "func_name": "Spidr.Page.each_link", "original_string": "def each_link\n return enum_for(__method__) unless block_given?\n\n filter = lambda { |url|\n yield url unless (url.nil? || url.empty?)\n }\n\n each_redirect(&filter) if is_redirect?\n\n if (html? && doc)\n doc.search('//a[@href]').each do |a|\n filter.call(a.get_attribute('href'))\n end\n\n doc.search('//frame[@src]').each do |iframe|\n filter.call(iframe.get_attribute('src'))\n end\n\n doc.search('//iframe[@src]').each do |iframe|\n filter.call(iframe.get_attribute('src'))\n end\n\n doc.search('//link[@href]').each do |link|\n filter.call(link.get_attribute('href'))\n end\n\n doc.search('//script[@src]').each do |script|\n filter.call(script.get_attribute('src'))\n end\n end\n end", "language": "ruby", "code": "def each_link\n return enum_for(__method__) unless block_given?\n\n filter = lambda { |url|\n yield url unless (url.nil? || url.empty?)\n }\n\n each_redirect(&filter) if is_redirect?\n\n if (html? && doc)\n doc.search('//a[@href]').each do |a|\n filter.call(a.get_attribute('href'))\n end\n\n doc.search('//frame[@src]').each do |iframe|\n filter.call(iframe.get_attribute('src'))\n end\n\n doc.search('//iframe[@src]').each do |iframe|\n filter.call(iframe.get_attribute('src'))\n end\n\n doc.search('//link[@href]').each do |link|\n filter.call(link.get_attribute('href'))\n end\n\n doc.search('//script[@src]').each do |script|\n filter.call(script.get_attribute('src'))\n end\n end\n end", "code_tokens": ["def", "each_link", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "filter", "=", "lambda", "{", "|", "url", "|", "yield", "url", "unless", "(", "url", ".", "nil?", "||", "url", ".", "empty?", ")", "}", "each_redirect", "(", "filter", ")", "if", "is_redirect?", "if", "(", "html?", "&&", "doc", ")", "doc", ".", "search", "(", "'//a[@href]'", ")", ".", "each", "do", "|", "a", "|", "filter", ".", "call", "(", "a", ".", "get_attribute", "(", "'href'", ")", ")", "end", "doc", ".", "search", "(", "'//frame[@src]'", ")", ".", "each", "do", "|", "iframe", "|", "filter", ".", "call", "(", "iframe", ".", "get_attribute", "(", "'src'", ")", ")", "end", "doc", ".", "search", "(", "'//iframe[@src]'", ")", ".", "each", "do", "|", "iframe", "|", "filter", ".", "call", "(", "iframe", ".", "get_attribute", "(", "'src'", ")", ")", "end", "doc", ".", "search", "(", "'//link[@href]'", ")", ".", "each", "do", "|", "link", "|", "filter", ".", "call", "(", "link", ".", "get_attribute", "(", "'href'", ")", ")", "end", "doc", ".", "search", "(", "'//script[@src]'", ")", ".", "each", "do", "|", "script", "|", "filter", ".", "call", "(", "script", ".", "get_attribute", "(", "'src'", ")", ")", "end", "end", "end"], "docstring": "Enumerates over every link in the page.\n\n @yield [link]\n The given block will be passed every non-empty link in the page.\n\n @yieldparam [String] link\n A link in the page.\n\n @return [Enumerator]\n If no block is given, an enumerator object will be returned.\n\n @since 0.3.0", "docstring_tokens": ["Enumerates", "over", "every", "link", "in", "the", "page", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/html.rb#L178-L208", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/page/html.rb", "func_name": "Spidr.Page.each_url", "original_string": "def each_url\n return enum_for(__method__) unless block_given?\n\n each_link do |link|\n if (url = to_absolute(link))\n yield url\n end\n end\n end", "language": "ruby", "code": "def each_url\n return enum_for(__method__) unless block_given?\n\n each_link do |link|\n if (url = to_absolute(link))\n yield url\n end\n end\n end", "code_tokens": ["def", "each_url", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "each_link", "do", "|", "link", "|", "if", "(", "url", "=", "to_absolute", "(", "link", ")", ")", "yield", "url", "end", "end", "end"], "docstring": "Enumerates over every absolute URL in the page.\n\n @yield [url]\n The given block will be passed every URL in the page.\n\n @yieldparam [URI::HTTP] url\n An absolute URL in the page.\n\n @return [Enumerator]\n If no block is given, an enumerator object will be returned.\n\n @since 0.3.0", "docstring_tokens": ["Enumerates", "over", "every", "absolute", "URL", "in", "the", "page", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/html.rb#L235-L243", "partition": "valid"} {"repo": "postmodern/spidr", "path": "lib/spidr/page/html.rb", "func_name": "Spidr.Page.to_absolute", "original_string": "def to_absolute(link)\n link = link.to_s\n new_url = begin\n url.merge(link)\n rescue Exception\n return\n end\n\n if (!new_url.opaque) && (path = new_url.path)\n # ensure that paths begin with a leading '/' for URI::FTP\n if (new_url.scheme == 'ftp' && !path.start_with?('/'))\n path.insert(0,'/')\n end\n\n # make sure the path does not contain any .. or . directories,\n # since URI::Generic#merge cannot normalize paths such as\n # \"/stuff/../\"\n new_url.path = URI.expand_path(path)\n end\n\n return new_url\n end", "language": "ruby", "code": "def to_absolute(link)\n link = link.to_s\n new_url = begin\n url.merge(link)\n rescue Exception\n return\n end\n\n if (!new_url.opaque) && (path = new_url.path)\n # ensure that paths begin with a leading '/' for URI::FTP\n if (new_url.scheme == 'ftp' && !path.start_with?('/'))\n path.insert(0,'/')\n end\n\n # make sure the path does not contain any .. or . directories,\n # since URI::Generic#merge cannot normalize paths such as\n # \"/stuff/../\"\n new_url.path = URI.expand_path(path)\n end\n\n return new_url\n end", "code_tokens": ["def", "to_absolute", "(", "link", ")", "link", "=", "link", ".", "to_s", "new_url", "=", "begin", "url", ".", "merge", "(", "link", ")", "rescue", "Exception", "return", "end", "if", "(", "!", "new_url", ".", "opaque", ")", "&&", "(", "path", "=", "new_url", ".", "path", ")", "# ensure that paths begin with a leading '/' for URI::FTP", "if", "(", "new_url", ".", "scheme", "==", "'ftp'", "&&", "!", "path", ".", "start_with?", "(", "'/'", ")", ")", "path", ".", "insert", "(", "0", ",", "'/'", ")", "end", "# make sure the path does not contain any .. or . directories,", "# since URI::Generic#merge cannot normalize paths such as", "# \"/stuff/../\"", "new_url", ".", "path", "=", "URI", ".", "expand_path", "(", "path", ")", "end", "return", "new_url", "end"], "docstring": "Normalizes and expands a given link into a proper URI.\n\n @param [String] link\n The link to normalize and expand.\n\n @return [URI::HTTP]\n The normalized URI.", "docstring_tokens": ["Normalizes", "and", "expands", "a", "given", "link", "into", "a", "proper", "URI", "."], "sha": "ae885272619f74c69d43ec77852f158768c6d804", "url": "https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/html.rb#L266-L287", "partition": "valid"} {"repo": "trailblazer/roar", "path": "lib/roar/http_verbs.rb", "func_name": "Roar.HttpVerbs.post", "original_string": "def post(options={}, &block)\n response = http.post_uri(options.merge(:body => serialize), &block)\n handle_response(response)\n end", "language": "ruby", "code": "def post(options={}, &block)\n response = http.post_uri(options.merge(:body => serialize), &block)\n handle_response(response)\n end", "code_tokens": ["def", "post", "(", "options", "=", "{", "}", ",", "&", "block", ")", "response", "=", "http", ".", "post_uri", "(", "options", ".", "merge", "(", ":body", "=>", "serialize", ")", ",", "block", ")", "handle_response", "(", "response", ")", "end"], "docstring": "Serializes the object, POSTs it to +url+ with +format+, deserializes the returned document\n and updates properties accordingly.", "docstring_tokens": ["Serializes", "the", "object", "POSTs", "it", "to", "+", "url", "+", "with", "+", "format", "+", "deserializes", "the", "returned", "document", "and", "updates", "properties", "accordingly", "."], "sha": "2dcc627c4884cd87619c321bc98edeb1c5549093", "url": "https://github.com/trailblazer/roar/blob/2dcc627c4884cd87619c321bc98edeb1c5549093/lib/roar/http_verbs.rb#L32-L35", "partition": "valid"} {"repo": "trailblazer/roar", "path": "lib/roar/http_verbs.rb", "func_name": "Roar.HttpVerbs.get", "original_string": "def get(options={}, &block)\n response = http.get_uri(options, &block)\n handle_response(response)\n end", "language": "ruby", "code": "def get(options={}, &block)\n response = http.get_uri(options, &block)\n handle_response(response)\n end", "code_tokens": ["def", "get", "(", "options", "=", "{", "}", ",", "&", "block", ")", "response", "=", "http", ".", "get_uri", "(", "options", ",", "block", ")", "handle_response", "(", "response", ")", "end"], "docstring": "GETs +url+ with +format+, deserializes the returned document and updates properties accordingly.", "docstring_tokens": ["GETs", "+", "url", "+", "with", "+", "format", "+", "deserializes", "the", "returned", "document", "and", "updates", "properties", "accordingly", "."], "sha": "2dcc627c4884cd87619c321bc98edeb1c5549093", "url": "https://github.com/trailblazer/roar/blob/2dcc627c4884cd87619c321bc98edeb1c5549093/lib/roar/http_verbs.rb#L38-L41", "partition": "valid"} {"repo": "trailblazer/roar", "path": "lib/roar/http_verbs.rb", "func_name": "Roar.HttpVerbs.put", "original_string": "def put(options={}, &block)\n response = http.put_uri(options.merge(:body => serialize), &block)\n handle_response(response)\n self\n end", "language": "ruby", "code": "def put(options={}, &block)\n response = http.put_uri(options.merge(:body => serialize), &block)\n handle_response(response)\n self\n end", "code_tokens": ["def", "put", "(", "options", "=", "{", "}", ",", "&", "block", ")", "response", "=", "http", ".", "put_uri", "(", "options", ".", "merge", "(", ":body", "=>", "serialize", ")", ",", "block", ")", "handle_response", "(", "response", ")", "self", "end"], "docstring": "Serializes the object, PUTs it to +url+ with +format+, deserializes the returned document\n and updates properties accordingly.", "docstring_tokens": ["Serializes", "the", "object", "PUTs", "it", "to", "+", "url", "+", "with", "+", "format", "+", "deserializes", "the", "returned", "document", "and", "updates", "properties", "accordingly", "."], "sha": "2dcc627c4884cd87619c321bc98edeb1c5549093", "url": "https://github.com/trailblazer/roar/blob/2dcc627c4884cd87619c321bc98edeb1c5549093/lib/roar/http_verbs.rb#L45-L49", "partition": "valid"} {"repo": "chain/chain", "path": "sdk/ruby/lib/chain/query.rb", "func_name": "Chain.Query.each", "original_string": "def each\n page = fetch(@first_query)\n\n loop do\n if page['items'].empty? # we consume this array as we iterate\n break if page['last_page']\n page = fetch(page['next'])\n\n # The second predicate (empty?) *should* be redundant, but we check it\n # anyway as a defensive measure.\n break if page['items'].empty?\n end\n\n item = page['items'].shift\n yield translate(item)\n end\n end", "language": "ruby", "code": "def each\n page = fetch(@first_query)\n\n loop do\n if page['items'].empty? # we consume this array as we iterate\n break if page['last_page']\n page = fetch(page['next'])\n\n # The second predicate (empty?) *should* be redundant, but we check it\n # anyway as a defensive measure.\n break if page['items'].empty?\n end\n\n item = page['items'].shift\n yield translate(item)\n end\n end", "code_tokens": ["def", "each", "page", "=", "fetch", "(", "@first_query", ")", "loop", "do", "if", "page", "[", "'items'", "]", ".", "empty?", "# we consume this array as we iterate", "break", "if", "page", "[", "'last_page'", "]", "page", "=", "fetch", "(", "page", "[", "'next'", "]", ")", "# The second predicate (empty?) *should* be redundant, but we check it", "# anyway as a defensive measure.", "break", "if", "page", "[", "'items'", "]", ".", "empty?", "end", "item", "=", "page", "[", "'items'", "]", ".", "shift", "yield", "translate", "(", "item", ")", "end", "end"], "docstring": "Iterate through objects in response, fetching the next page of results\n from the API as needed.\n\n Implements required method\n {https://ruby-doc.org/core/Enumerable.html Enumerable#each}.\n @return [void]", "docstring_tokens": ["Iterate", "through", "objects", "in", "response", "fetching", "the", "next", "page", "of", "results", "from", "the", "API", "as", "needed", "."], "sha": "4e9b90d76fe9a4c53adadf03cf8db96a0a5ff38c", "url": "https://github.com/chain/chain/blob/4e9b90d76fe9a4c53adadf03cf8db96a0a5ff38c/sdk/ruby/lib/chain/query.rb#L19-L35", "partition": "valid"} {"repo": "chain/chain", "path": "sdk/ruby/lib/chain/hsm_signer.rb", "func_name": "Chain.HSMSigner.sign", "original_string": "def sign(tx_template)\n return tx_template if @xpubs_by_signer.empty?\n\n @xpubs_by_signer.each do |signer_conn, xpubs|\n tx_template = signer_conn.singleton_batch_request(\n '/sign-transaction',\n transactions: [tx_template],\n xpubs: xpubs,\n ) { |item| Transaction::Template.new(item) }\n end\n\n tx_template\n end", "language": "ruby", "code": "def sign(tx_template)\n return tx_template if @xpubs_by_signer.empty?\n\n @xpubs_by_signer.each do |signer_conn, xpubs|\n tx_template = signer_conn.singleton_batch_request(\n '/sign-transaction',\n transactions: [tx_template],\n xpubs: xpubs,\n ) { |item| Transaction::Template.new(item) }\n end\n\n tx_template\n end", "code_tokens": ["def", "sign", "(", "tx_template", ")", "return", "tx_template", "if", "@xpubs_by_signer", ".", "empty?", "@xpubs_by_signer", ".", "each", "do", "|", "signer_conn", ",", "xpubs", "|", "tx_template", "=", "signer_conn", ".", "singleton_batch_request", "(", "'/sign-transaction'", ",", "transactions", ":", "[", "tx_template", "]", ",", "xpubs", ":", "xpubs", ",", ")", "{", "|", "item", "|", "Transaction", "::", "Template", ".", "new", "(", "item", ")", "}", "end", "tx_template", "end"], "docstring": "Sign a single transaction\n @param [Hash] tx_template\tA single transaction template.", "docstring_tokens": ["Sign", "a", "single", "transaction"], "sha": "4e9b90d76fe9a4c53adadf03cf8db96a0a5ff38c", "url": "https://github.com/chain/chain/blob/4e9b90d76fe9a4c53adadf03cf8db96a0a5ff38c/sdk/ruby/lib/chain/hsm_signer.rb#L25-L37", "partition": "valid"} {"repo": "chain/chain", "path": "sdk/ruby/lib/chain/hsm_signer.rb", "func_name": "Chain.HSMSigner.sign_batch", "original_string": "def sign_batch(tx_templates)\n if @xpubs_by_signer.empty?\n # Treat all templates as if signed successfully.\n successes = tx_templates.each_with_index.reduce({}) do |memo, (t, i)|\n memo[i] = t\n memo\n end\n BatchResponse.new(successes: successes)\n end\n\n # We need to work towards a single, final BatchResponse that uses the\n # original indexes. For the next cycle, we should retain only those\n # templates for which the most recent sign response was successful, and\n # maintain a mapping of each template's index in the upcoming request\n # to its original index.\n\n orig_index = (0...tx_templates.size).to_a\n errors = {}\n\n @xpubs_by_signer.each do |signer_conn, xpubs|\n next_tx_templates = []\n next_orig_index = []\n\n batch = signer_conn.batch_request(\n '/sign-transaction',\n transactions: tx_templates,\n xpubs: xpubs,\n ) { |item| Transaction::Template.new(item) }\n\n batch.successes.each do |i, template|\n next_tx_templates << template\n next_orig_index << orig_index[i]\n end\n\n batch.errors.each do |i, err|\n errors[orig_index[i]] = err\n end\n\n tx_templates = next_tx_templates\n orig_index = next_orig_index\n\n # Early-exit if all templates have encountered an error.\n break if tx_templates.empty?\n end\n\n successes = tx_templates.each_with_index.reduce({}) do |memo, (t, i)|\n memo[orig_index[i]] = t\n memo\n end\n\n BatchResponse.new(\n successes: successes,\n errors: errors,\n )\n end", "language": "ruby", "code": "def sign_batch(tx_templates)\n if @xpubs_by_signer.empty?\n # Treat all templates as if signed successfully.\n successes = tx_templates.each_with_index.reduce({}) do |memo, (t, i)|\n memo[i] = t\n memo\n end\n BatchResponse.new(successes: successes)\n end\n\n # We need to work towards a single, final BatchResponse that uses the\n # original indexes. For the next cycle, we should retain only those\n # templates for which the most recent sign response was successful, and\n # maintain a mapping of each template's index in the upcoming request\n # to its original index.\n\n orig_index = (0...tx_templates.size).to_a\n errors = {}\n\n @xpubs_by_signer.each do |signer_conn, xpubs|\n next_tx_templates = []\n next_orig_index = []\n\n batch = signer_conn.batch_request(\n '/sign-transaction',\n transactions: tx_templates,\n xpubs: xpubs,\n ) { |item| Transaction::Template.new(item) }\n\n batch.successes.each do |i, template|\n next_tx_templates << template\n next_orig_index << orig_index[i]\n end\n\n batch.errors.each do |i, err|\n errors[orig_index[i]] = err\n end\n\n tx_templates = next_tx_templates\n orig_index = next_orig_index\n\n # Early-exit if all templates have encountered an error.\n break if tx_templates.empty?\n end\n\n successes = tx_templates.each_with_index.reduce({}) do |memo, (t, i)|\n memo[orig_index[i]] = t\n memo\n end\n\n BatchResponse.new(\n successes: successes,\n errors: errors,\n )\n end", "code_tokens": ["def", "sign_batch", "(", "tx_templates", ")", "if", "@xpubs_by_signer", ".", "empty?", "# Treat all templates as if signed successfully.", "successes", "=", "tx_templates", ".", "each_with_index", ".", "reduce", "(", "{", "}", ")", "do", "|", "memo", ",", "(", "t", ",", "i", ")", "|", "memo", "[", "i", "]", "=", "t", "memo", "end", "BatchResponse", ".", "new", "(", "successes", ":", "successes", ")", "end", "# We need to work towards a single, final BatchResponse that uses the", "# original indexes. For the next cycle, we should retain only those", "# templates for which the most recent sign response was successful, and", "# maintain a mapping of each template's index in the upcoming request", "# to its original index.", "orig_index", "=", "(", "0", "...", "tx_templates", ".", "size", ")", ".", "to_a", "errors", "=", "{", "}", "@xpubs_by_signer", ".", "each", "do", "|", "signer_conn", ",", "xpubs", "|", "next_tx_templates", "=", "[", "]", "next_orig_index", "=", "[", "]", "batch", "=", "signer_conn", ".", "batch_request", "(", "'/sign-transaction'", ",", "transactions", ":", "tx_templates", ",", "xpubs", ":", "xpubs", ",", ")", "{", "|", "item", "|", "Transaction", "::", "Template", ".", "new", "(", "item", ")", "}", "batch", ".", "successes", ".", "each", "do", "|", "i", ",", "template", "|", "next_tx_templates", "<<", "template", "next_orig_index", "<<", "orig_index", "[", "i", "]", "end", "batch", ".", "errors", ".", "each", "do", "|", "i", ",", "err", "|", "errors", "[", "orig_index", "[", "i", "]", "]", "=", "err", "end", "tx_templates", "=", "next_tx_templates", "orig_index", "=", "next_orig_index", "# Early-exit if all templates have encountered an error.", "break", "if", "tx_templates", ".", "empty?", "end", "successes", "=", "tx_templates", ".", "each_with_index", ".", "reduce", "(", "{", "}", ")", "do", "|", "memo", ",", "(", "t", ",", "i", ")", "|", "memo", "[", "orig_index", "[", "i", "]", "]", "=", "t", "memo", "end", "BatchResponse", ".", "new", "(", "successes", ":", "successes", ",", "errors", ":", "errors", ",", ")", "end"], "docstring": "Sign a batch of transactions\n @param [Array] tx_templates Array of transaction templates.", "docstring_tokens": ["Sign", "a", "batch", "of", "transactions"], "sha": "4e9b90d76fe9a4c53adadf03cf8db96a0a5ff38c", "url": "https://github.com/chain/chain/blob/4e9b90d76fe9a4c53adadf03cf8db96a0a5ff38c/sdk/ruby/lib/chain/hsm_signer.rb#L41-L95", "partition": "valid"} {"repo": "fhir-crucible/fhir_client", "path": "lib/fhir_client/client.rb", "func_name": "FHIR.Client.set_no_auth", "original_string": "def set_no_auth\n FHIR.logger.info 'Configuring the client to use no authentication.'\n @use_oauth2_auth = false\n @use_basic_auth = false\n @security_headers = {}\n @client = RestClient\n @client.proxy = proxy unless proxy.nil?\n @client\n end", "language": "ruby", "code": "def set_no_auth\n FHIR.logger.info 'Configuring the client to use no authentication.'\n @use_oauth2_auth = false\n @use_basic_auth = false\n @security_headers = {}\n @client = RestClient\n @client.proxy = proxy unless proxy.nil?\n @client\n end", "code_tokens": ["def", "set_no_auth", "FHIR", ".", "logger", ".", "info", "'Configuring the client to use no authentication.'", "@use_oauth2_auth", "=", "false", "@use_basic_auth", "=", "false", "@security_headers", "=", "{", "}", "@client", "=", "RestClient", "@client", ".", "proxy", "=", "proxy", "unless", "proxy", ".", "nil?", "@client", "end"], "docstring": "Set the client to use no authentication mechanisms", "docstring_tokens": ["Set", "the", "client", "to", "use", "no", "authentication", "mechanisms"], "sha": "19891520a1af0d42a3a985c9afebc68d717f51cc", "url": "https://github.com/fhir-crucible/fhir_client/blob/19891520a1af0d42a3a985c9afebc68d717f51cc/lib/fhir_client/client.rb#L112-L120", "partition": "valid"} {"repo": "fhir-crucible/fhir_client", "path": "lib/fhir_client/client.rb", "func_name": "FHIR.Client.set_basic_auth", "original_string": "def set_basic_auth(client, secret)\n FHIR.logger.info 'Configuring the client to use HTTP Basic authentication.'\n token = Base64.encode64(\"#{client}:#{secret}\")\n value = \"Basic #{token}\"\n @security_headers = { 'Authorization' => value }\n @use_oauth2_auth = false\n @use_basic_auth = true\n @client = RestClient\n @client.proxy = proxy unless proxy.nil?\n @client\n end", "language": "ruby", "code": "def set_basic_auth(client, secret)\n FHIR.logger.info 'Configuring the client to use HTTP Basic authentication.'\n token = Base64.encode64(\"#{client}:#{secret}\")\n value = \"Basic #{token}\"\n @security_headers = { 'Authorization' => value }\n @use_oauth2_auth = false\n @use_basic_auth = true\n @client = RestClient\n @client.proxy = proxy unless proxy.nil?\n @client\n end", "code_tokens": ["def", "set_basic_auth", "(", "client", ",", "secret", ")", "FHIR", ".", "logger", ".", "info", "'Configuring the client to use HTTP Basic authentication.'", "token", "=", "Base64", ".", "encode64", "(", "\"#{client}:#{secret}\"", ")", "value", "=", "\"Basic #{token}\"", "@security_headers", "=", "{", "'Authorization'", "=>", "value", "}", "@use_oauth2_auth", "=", "false", "@use_basic_auth", "=", "true", "@client", "=", "RestClient", "@client", ".", "proxy", "=", "proxy", "unless", "proxy", ".", "nil?", "@client", "end"], "docstring": "Set the client to use HTTP Basic Authentication", "docstring_tokens": ["Set", "the", "client", "to", "use", "HTTP", "Basic", "Authentication"], "sha": "19891520a1af0d42a3a985c9afebc68d717f51cc", "url": "https://github.com/fhir-crucible/fhir_client/blob/19891520a1af0d42a3a985c9afebc68d717f51cc/lib/fhir_client/client.rb#L123-L133", "partition": "valid"} {"repo": "fhir-crucible/fhir_client", "path": "lib/fhir_client/client.rb", "func_name": "FHIR.Client.set_bearer_token", "original_string": "def set_bearer_token(token)\n FHIR.logger.info 'Configuring the client to use Bearer Token authentication.'\n value = \"Bearer #{token}\"\n @security_headers = { 'Authorization' => value }\n @use_oauth2_auth = false\n @use_basic_auth = true\n @client = RestClient\n @client.proxy = proxy unless proxy.nil?\n @client\n end", "language": "ruby", "code": "def set_bearer_token(token)\n FHIR.logger.info 'Configuring the client to use Bearer Token authentication.'\n value = \"Bearer #{token}\"\n @security_headers = { 'Authorization' => value }\n @use_oauth2_auth = false\n @use_basic_auth = true\n @client = RestClient\n @client.proxy = proxy unless proxy.nil?\n @client\n end", "code_tokens": ["def", "set_bearer_token", "(", "token", ")", "FHIR", ".", "logger", ".", "info", "'Configuring the client to use Bearer Token authentication.'", "value", "=", "\"Bearer #{token}\"", "@security_headers", "=", "{", "'Authorization'", "=>", "value", "}", "@use_oauth2_auth", "=", "false", "@use_basic_auth", "=", "true", "@client", "=", "RestClient", "@client", ".", "proxy", "=", "proxy", "unless", "proxy", ".", "nil?", "@client", "end"], "docstring": "Set the client to use Bearer Token Authentication", "docstring_tokens": ["Set", "the", "client", "to", "use", "Bearer", "Token", "Authentication"], "sha": "19891520a1af0d42a3a985c9afebc68d717f51cc", "url": "https://github.com/fhir-crucible/fhir_client/blob/19891520a1af0d42a3a985c9afebc68d717f51cc/lib/fhir_client/client.rb#L136-L145", "partition": "valid"} {"repo": "fhir-crucible/fhir_client", "path": "lib/fhir_client/client.rb", "func_name": "FHIR.Client.request_payload", "original_string": "def request_payload(resource, headers)\n if headers\n format_specified = headers['Content-Type']\n if format_specified.nil?\n resource.to_xml\n elsif format_specified.downcase.include?('xml')\n resource.to_xml\n elsif format_specified.downcase.include?('json')\n resource.to_json\n else\n resource.to_xml\n end\n else\n resource.to_xml\n end\n end", "language": "ruby", "code": "def request_payload(resource, headers)\n if headers\n format_specified = headers['Content-Type']\n if format_specified.nil?\n resource.to_xml\n elsif format_specified.downcase.include?('xml')\n resource.to_xml\n elsif format_specified.downcase.include?('json')\n resource.to_json\n else\n resource.to_xml\n end\n else\n resource.to_xml\n end\n end", "code_tokens": ["def", "request_payload", "(", "resource", ",", "headers", ")", "if", "headers", "format_specified", "=", "headers", "[", "'Content-Type'", "]", "if", "format_specified", ".", "nil?", "resource", ".", "to_xml", "elsif", "format_specified", ".", "downcase", ".", "include?", "(", "'xml'", ")", "resource", ".", "to_xml", "elsif", "format_specified", ".", "downcase", ".", "include?", "(", "'json'", ")", "resource", ".", "to_json", "else", "resource", ".", "to_xml", "end", "else", "resource", ".", "to_xml", "end", "end"], "docstring": "Extract the request payload in the specified format, defaults to XML", "docstring_tokens": ["Extract", "the", "request", "payload", "in", "the", "specified", "format", "defaults", "to", "XML"], "sha": "19891520a1af0d42a3a985c9afebc68d717f51cc", "url": "https://github.com/fhir-crucible/fhir_client/blob/19891520a1af0d42a3a985c9afebc68d717f51cc/lib/fhir_client/client.rb#L378-L393", "partition": "valid"} {"repo": "ipaddress-gem/ipaddress", "path": "lib/ipaddress/ipv4.rb", "func_name": "IPAddress.IPv4.split", "original_string": "def split(subnets=2)\n unless (1..(2**@prefix.host_prefix)).include? subnets\n raise ArgumentError, \"Value #{subnets} out of range\" \n end\n networks = subnet(newprefix(subnets))\n until networks.size == subnets\n networks = sum_first_found(networks)\n end\n return networks\n end", "language": "ruby", "code": "def split(subnets=2)\n unless (1..(2**@prefix.host_prefix)).include? subnets\n raise ArgumentError, \"Value #{subnets} out of range\" \n end\n networks = subnet(newprefix(subnets))\n until networks.size == subnets\n networks = sum_first_found(networks)\n end\n return networks\n end", "code_tokens": ["def", "split", "(", "subnets", "=", "2", ")", "unless", "(", "1", "..", "(", "2", "**", "@prefix", ".", "host_prefix", ")", ")", ".", "include?", "subnets", "raise", "ArgumentError", ",", "\"Value #{subnets} out of range\"", "end", "networks", "=", "subnet", "(", "newprefix", "(", "subnets", ")", ")", "until", "networks", ".", "size", "==", "subnets", "networks", "=", "sum_first_found", "(", "networks", ")", "end", "return", "networks", "end"], "docstring": "Splits a network into different subnets\n\n If the IP Address is a network, it can be divided into\n multiple networks. If +self+ is not a network, this\n method will calculate the network from the IP and then\n subnet it.\n\n If +subnets+ is an power of two number, the resulting\n networks will be divided evenly from the supernet.\n\n network = IPAddress(\"172.16.10.0/24\")\n\n network / 4 # implies map{|i| i.to_string}\n #=> [\"172.16.10.0/26\",\n #=> \"172.16.10.64/26\",\n #=> \"172.16.10.128/26\",\n #=> \"172.16.10.192/26\"]\n\n If +num+ is any other number, the supernet will be\n divided into some networks with a even number of hosts and\n other networks with the remaining addresses.\n\n network = IPAddress(\"172.16.10.0/24\")\n\n network / 3 # implies map{|i| i.to_string}\n #=> [\"172.16.10.0/26\",\n #=> \"172.16.10.64/26\",\n #=> \"172.16.10.128/25\"]\n\n Returns an array of IPv4 objects", "docstring_tokens": ["Splits", "a", "network", "into", "different", "subnets"], "sha": "a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b", "url": "https://github.com/ipaddress-gem/ipaddress/blob/a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b/lib/ipaddress/ipv4.rb#L734-L743", "partition": "valid"} {"repo": "ipaddress-gem/ipaddress", "path": "lib/ipaddress/ipv4.rb", "func_name": "IPAddress.IPv4.supernet", "original_string": "def supernet(new_prefix)\n raise ArgumentError, \"New prefix must be smaller than existing prefix\" if new_prefix >= @prefix.to_i\n return self.class.new(\"0.0.0.0/0\") if new_prefix < 1\n return self.class.new(@address+\"/#{new_prefix}\").network\n end", "language": "ruby", "code": "def supernet(new_prefix)\n raise ArgumentError, \"New prefix must be smaller than existing prefix\" if new_prefix >= @prefix.to_i\n return self.class.new(\"0.0.0.0/0\") if new_prefix < 1\n return self.class.new(@address+\"/#{new_prefix}\").network\n end", "code_tokens": ["def", "supernet", "(", "new_prefix", ")", "raise", "ArgumentError", ",", "\"New prefix must be smaller than existing prefix\"", "if", "new_prefix", ">=", "@prefix", ".", "to_i", "return", "self", ".", "class", ".", "new", "(", "\"0.0.0.0/0\"", ")", "if", "new_prefix", "<", "1", "return", "self", ".", "class", ".", "new", "(", "@address", "+", "\"/#{new_prefix}\"", ")", ".", "network", "end"], "docstring": "Returns a new IPv4 object from the supernetting\n of the instance network.\n\n Supernetting is similar to subnetting, except\n that you getting as a result a network with a\n smaller prefix (bigger host space). For example,\n given the network\n\n ip = IPAddress(\"172.16.10.0/24\")\n\n you can supernet it with a new /23 prefix\n\n ip.supernet(23).to_string\n #=> \"172.16.10.0/23\"\n\n However if you supernet it with a /22 prefix, the\n network address will change:\n\n ip.supernet(22).to_string\n #=> \"172.16.8.0/22\"\n\n If +new_prefix+ is less than 1, returns 0.0.0.0/0", "docstring_tokens": ["Returns", "a", "new", "IPv4", "object", "from", "the", "supernetting", "of", "the", "instance", "network", "."], "sha": "a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b", "url": "https://github.com/ipaddress-gem/ipaddress/blob/a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b/lib/ipaddress/ipv4.rb#L770-L774", "partition": "valid"} {"repo": "ipaddress-gem/ipaddress", "path": "lib/ipaddress/ipv4.rb", "func_name": "IPAddress.IPv4.subnet", "original_string": "def subnet(subprefix)\n unless ((@prefix.to_i)..32).include? subprefix\n raise ArgumentError, \"New prefix must be between #@prefix and 32\"\n end\n Array.new(2**(subprefix-@prefix.to_i)) do |i|\n self.class.parse_u32(network_u32+(i*(2**(32-subprefix))), subprefix)\n end\n end", "language": "ruby", "code": "def subnet(subprefix)\n unless ((@prefix.to_i)..32).include? subprefix\n raise ArgumentError, \"New prefix must be between #@prefix and 32\"\n end\n Array.new(2**(subprefix-@prefix.to_i)) do |i|\n self.class.parse_u32(network_u32+(i*(2**(32-subprefix))), subprefix)\n end\n end", "code_tokens": ["def", "subnet", "(", "subprefix", ")", "unless", "(", "(", "@prefix", ".", "to_i", ")", "..", "32", ")", ".", "include?", "subprefix", "raise", "ArgumentError", ",", "\"New prefix must be between #@prefix and 32\"", "end", "Array", ".", "new", "(", "2", "**", "(", "subprefix", "-", "@prefix", ".", "to_i", ")", ")", "do", "|", "i", "|", "self", ".", "class", ".", "parse_u32", "(", "network_u32", "+", "(", "i", "(", "2", "**", "(", "32", "-", "subprefix", ")", ")", ")", ",", "subprefix", ")", "end", "end"], "docstring": "This method implements the subnetting function\n similar to the one described in RFC3531.\n\n By specifying a new prefix, the method calculates\n the network number for the given IPv4 object\n and calculates the subnets associated to the new\n prefix.\n\n For example, given the following network:\n\n ip = IPAddress \"172.16.10.0/24\"\n\n we can calculate the subnets with a /26 prefix\n\n ip.subnet(26).map{&:to_string)\n #=> [\"172.16.10.0/26\", \"172.16.10.64/26\",\n \"172.16.10.128/26\", \"172.16.10.192/26\"]\n\n The resulting number of subnets will of course always be\n a power of two.", "docstring_tokens": ["This", "method", "implements", "the", "subnetting", "function", "similar", "to", "the", "one", "described", "in", "RFC3531", "."], "sha": "a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b", "url": "https://github.com/ipaddress-gem/ipaddress/blob/a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b/lib/ipaddress/ipv4.rb#L798-L805", "partition": "valid"} {"repo": "ipaddress-gem/ipaddress", "path": "lib/ipaddress/prefix.rb", "func_name": "IPAddress.Prefix.-", "original_string": "def -(oth)\n if oth.is_a? Integer\n self.prefix - oth\n else\n (self.prefix - oth.prefix).abs\n end\n end", "language": "ruby", "code": "def -(oth)\n if oth.is_a? Integer\n self.prefix - oth\n else\n (self.prefix - oth.prefix).abs\n end\n end", "code_tokens": ["def", "-", "(", "oth", ")", "if", "oth", ".", "is_a?", "Integer", "self", ".", "prefix", "-", "oth", "else", "(", "self", ".", "prefix", "-", "oth", ".", "prefix", ")", ".", "abs", "end", "end"], "docstring": "Returns the difference between two\n prefixes, or a prefix and a number,\n as a Integer", "docstring_tokens": ["Returns", "the", "difference", "between", "two", "prefixes", "or", "a", "prefix", "and", "a", "number", "as", "a", "Integer"], "sha": "a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b", "url": "https://github.com/ipaddress-gem/ipaddress/blob/a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b/lib/ipaddress/prefix.rb#L73-L79", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/dsl.rb", "func_name": "Chatterbot.DSL.bot", "original_string": "def bot\n return @bot unless @bot.nil?\n\n @bot_command = nil\n \n #\n # parse any command-line options and use them to initialize the bot\n #\n params = {}\n\n #:nocov:\n opts = OptionParser.new\n\n opts.banner = \"Usage: #{File.basename($0)} [options]\"\n\n opts.separator \"\"\n opts.separator \"Specific options:\"\n\n\n opts.on('-c', '--config [ARG]', \"Specify a config file to use\") { |c| ENV[\"chatterbot_config\"] = c }\n opts.on('-t', '--test', \"Run the bot without actually sending any tweets\") { params[:debug_mode] = true }\n opts.on('-v', '--verbose', \"verbose output to stdout\") { params[:verbose] = true }\n opts.on('--dry-run', \"Run the bot in test mode, and also don't update the database\") { params[:debug_mode] = true ; params[:no_update] = true }\n\n opts.on('-r', '--reset', \"Reset your bot to ignore old tweets\") {\n @bot_command = :reset_since_id_counters\n }\n\n opts.on('--profile [ARG]', \"get/set your bot's profile text\") { |p| \n @bot_command = :profile_text\n @bot_command_args = [ p ]\n }\n\n opts.on('--website [ARG]', \"get/set your bot's profile URL\") { |u| \n @bot_command = :profile_website\n @bot_command_args = [ u ]\n }\n \n opts.on_tail(\"-h\", \"--help\", \"Show this message\") do\n puts opts\n exit\n end\n\n opts.parse!(ARGV)\n #:nocov:\n\n @bot = Chatterbot::Bot.new(params)\n if @bot_command != nil\n @bot.skip_run = true\n result = @bot.send(@bot_command, *@bot_command_args)\n puts result\n end\n\n @bot\n end", "language": "ruby", "code": "def bot\n return @bot unless @bot.nil?\n\n @bot_command = nil\n \n #\n # parse any command-line options and use them to initialize the bot\n #\n params = {}\n\n #:nocov:\n opts = OptionParser.new\n\n opts.banner = \"Usage: #{File.basename($0)} [options]\"\n\n opts.separator \"\"\n opts.separator \"Specific options:\"\n\n\n opts.on('-c', '--config [ARG]', \"Specify a config file to use\") { |c| ENV[\"chatterbot_config\"] = c }\n opts.on('-t', '--test', \"Run the bot without actually sending any tweets\") { params[:debug_mode] = true }\n opts.on('-v', '--verbose', \"verbose output to stdout\") { params[:verbose] = true }\n opts.on('--dry-run', \"Run the bot in test mode, and also don't update the database\") { params[:debug_mode] = true ; params[:no_update] = true }\n\n opts.on('-r', '--reset', \"Reset your bot to ignore old tweets\") {\n @bot_command = :reset_since_id_counters\n }\n\n opts.on('--profile [ARG]', \"get/set your bot's profile text\") { |p| \n @bot_command = :profile_text\n @bot_command_args = [ p ]\n }\n\n opts.on('--website [ARG]', \"get/set your bot's profile URL\") { |u| \n @bot_command = :profile_website\n @bot_command_args = [ u ]\n }\n \n opts.on_tail(\"-h\", \"--help\", \"Show this message\") do\n puts opts\n exit\n end\n\n opts.parse!(ARGV)\n #:nocov:\n\n @bot = Chatterbot::Bot.new(params)\n if @bot_command != nil\n @bot.skip_run = true\n result = @bot.send(@bot_command, *@bot_command_args)\n puts result\n end\n\n @bot\n end", "code_tokens": ["def", "bot", "return", "@bot", "unless", "@bot", ".", "nil?", "@bot_command", "=", "nil", "#", "# parse any command-line options and use them to initialize the bot", "#", "params", "=", "{", "}", "#:nocov:", "opts", "=", "OptionParser", ".", "new", "opts", ".", "banner", "=", "\"Usage: #{File.basename($0)} [options]\"", "opts", ".", "separator", "\"\"", "opts", ".", "separator", "\"Specific options:\"", "opts", ".", "on", "(", "'-c'", ",", "'--config [ARG]'", ",", "\"Specify a config file to use\"", ")", "{", "|", "c", "|", "ENV", "[", "\"chatterbot_config\"", "]", "=", "c", "}", "opts", ".", "on", "(", "'-t'", ",", "'--test'", ",", "\"Run the bot without actually sending any tweets\"", ")", "{", "params", "[", ":debug_mode", "]", "=", "true", "}", "opts", ".", "on", "(", "'-v'", ",", "'--verbose'", ",", "\"verbose output to stdout\"", ")", "{", "params", "[", ":verbose", "]", "=", "true", "}", "opts", ".", "on", "(", "'--dry-run'", ",", "\"Run the bot in test mode, and also don't update the database\"", ")", "{", "params", "[", ":debug_mode", "]", "=", "true", ";", "params", "[", ":no_update", "]", "=", "true", "}", "opts", ".", "on", "(", "'-r'", ",", "'--reset'", ",", "\"Reset your bot to ignore old tweets\"", ")", "{", "@bot_command", "=", ":reset_since_id_counters", "}", "opts", ".", "on", "(", "'--profile [ARG]'", ",", "\"get/set your bot's profile text\"", ")", "{", "|", "p", "|", "@bot_command", "=", ":profile_text", "@bot_command_args", "=", "[", "p", "]", "}", "opts", ".", "on", "(", "'--website [ARG]'", ",", "\"get/set your bot's profile URL\"", ")", "{", "|", "u", "|", "@bot_command", "=", ":profile_website", "@bot_command_args", "=", "[", "u", "]", "}", "opts", ".", "on_tail", "(", "\"-h\"", ",", "\"--help\"", ",", "\"Show this message\"", ")", "do", "puts", "opts", "exit", "end", "opts", ".", "parse!", "(", "ARGV", ")", "#:nocov:", "@bot", "=", "Chatterbot", "::", "Bot", ".", "new", "(", "params", ")", "if", "@bot_command", "!=", "nil", "@bot", ".", "skip_run", "=", "true", "result", "=", "@bot", ".", "send", "(", "@bot_command", ",", "@bot_command_args", ")", "puts", "result", "end", "@bot", "end"], "docstring": "generate a Bot object. if the DSL is being called from a Bot object, just return it\n otherwise create a bot and return that", "docstring_tokens": ["generate", "a", "Bot", "object", ".", "if", "the", "DSL", "is", "being", "called", "from", "a", "Bot", "object", "just", "return", "it", "otherwise", "create", "a", "bot", "and", "return", "that"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L159-L213", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/dsl.rb", "func_name": "Chatterbot.DSL.blocklist", "original_string": "def blocklist(*args)\n list = flatten_list_of_strings(args)\n\n if list.nil? || list.empty?\n bot.blocklist = []\n else\n bot.blocklist += list\n end\n end", "language": "ruby", "code": "def blocklist(*args)\n list = flatten_list_of_strings(args)\n\n if list.nil? || list.empty?\n bot.blocklist = []\n else\n bot.blocklist += list\n end\n end", "code_tokens": ["def", "blocklist", "(", "*", "args", ")", "list", "=", "flatten_list_of_strings", "(", "args", ")", "if", "list", ".", "nil?", "||", "list", ".", "empty?", "bot", ".", "blocklist", "=", "[", "]", "else", "bot", ".", "blocklist", "+=", "list", "end", "end"], "docstring": "specify a bot-specific blocklist of users. accepts an array, or a\n comma-delimited string. when called, any subsequent calls to\n search or replies will filter out these users.\n\n @param [Array, String] args list of usernames\n @example\n blocklist \"mean_user, private_user\"", "docstring_tokens": ["specify", "a", "bot", "-", "specific", "blocklist", "of", "users", ".", "accepts", "an", "array", "or", "a", "comma", "-", "delimited", "string", ".", "when", "called", "any", "subsequent", "calls", "to", "search", "or", "replies", "will", "filter", "out", "these", "users", "."], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L251-L259", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/dsl.rb", "func_name": "Chatterbot.DSL.safelist", "original_string": "def safelist(*args)\n list = flatten_list_of_strings(args)\n\n if list.nil? || list.empty?\n bot.safelist = []\n else\n bot.safelist += list\n end\n end", "language": "ruby", "code": "def safelist(*args)\n list = flatten_list_of_strings(args)\n\n if list.nil? || list.empty?\n bot.safelist = []\n else\n bot.safelist += list\n end\n end", "code_tokens": ["def", "safelist", "(", "*", "args", ")", "list", "=", "flatten_list_of_strings", "(", "args", ")", "if", "list", ".", "nil?", "||", "list", ".", "empty?", "bot", ".", "safelist", "=", "[", "]", "else", "bot", ".", "safelist", "+=", "list", "end", "end"], "docstring": "specify a bot-specific safelist of users. accepts an array, or a\n comma-delimited string. when called, any subsequent calls to\n search or replies will only act upon these users.\n\n @param [Array, String] args list of usernames or Twitter::User objects\n @example\n safelist \"mean_user, private_user\"", "docstring_tokens": ["specify", "a", "bot", "-", "specific", "safelist", "of", "users", ".", "accepts", "an", "array", "or", "a", "comma", "-", "delimited", "string", ".", "when", "called", "any", "subsequent", "calls", "to", "search", "or", "replies", "will", "only", "act", "upon", "these", "users", "."], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L272-L280", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/dsl.rb", "func_name": "Chatterbot.DSL.exclude", "original_string": "def exclude(*args)\n e = flatten_list_of_strings(args)\n if e.nil? || e.empty?\n bot.exclude = []\n else\n bot.exclude += e\n end\n end", "language": "ruby", "code": "def exclude(*args)\n e = flatten_list_of_strings(args)\n if e.nil? || e.empty?\n bot.exclude = []\n else\n bot.exclude += e\n end\n end", "code_tokens": ["def", "exclude", "(", "*", "args", ")", "e", "=", "flatten_list_of_strings", "(", "args", ")", "if", "e", ".", "nil?", "||", "e", ".", "empty?", "bot", ".", "exclude", "=", "[", "]", "else", "bot", ".", "exclude", "+=", "e", "end", "end"], "docstring": "specify list of strings we will check when deciding to respond\n to a tweet or not. accepts an array or a comma-delimited string.\n when called, any subsequent calls to search or replies will\n filter out tweets with these strings\n\n @param [Array, String] args list of usernames\n @example\n exclude \"spam, junk, something\"", "docstring_tokens": ["specify", "list", "of", "strings", "we", "will", "check", "when", "deciding", "to", "respond", "to", "a", "tweet", "or", "not", ".", "accepts", "an", "array", "or", "a", "comma", "-", "delimited", "string", ".", "when", "called", "any", "subsequent", "calls", "to", "search", "or", "replies", "will", "filter", "out", "tweets", "with", "these", "strings"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L374-L381", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/dsl.rb", "func_name": "Chatterbot.DSL.consumer_secret", "original_string": "def consumer_secret(s)\n bot.deprecated \"Setting consumer_secret outside of your config file is deprecated!\", Kernel.caller.first\n bot.config[:consumer_secret] = s\n end", "language": "ruby", "code": "def consumer_secret(s)\n bot.deprecated \"Setting consumer_secret outside of your config file is deprecated!\", Kernel.caller.first\n bot.config[:consumer_secret] = s\n end", "code_tokens": ["def", "consumer_secret", "(", "s", ")", "bot", ".", "deprecated", "\"Setting consumer_secret outside of your config file is deprecated!\"", ",", "Kernel", ".", "caller", ".", "first", "bot", ".", "config", "[", ":consumer_secret", "]", "=", "s", "end"], "docstring": "set the consumer secret\n @param s [String] the consumer secret", "docstring_tokens": ["set", "the", "consumer", "secret"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L397-L400", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/dsl.rb", "func_name": "Chatterbot.DSL.consumer_key", "original_string": "def consumer_key(k)\n bot.deprecated \"Setting consumer_key outside of your config file is deprecated!\", Kernel.caller.first\n bot.config[:consumer_key] = k\n end", "language": "ruby", "code": "def consumer_key(k)\n bot.deprecated \"Setting consumer_key outside of your config file is deprecated!\", Kernel.caller.first\n bot.config[:consumer_key] = k\n end", "code_tokens": ["def", "consumer_key", "(", "k", ")", "bot", ".", "deprecated", "\"Setting consumer_key outside of your config file is deprecated!\"", ",", "Kernel", ".", "caller", ".", "first", "bot", ".", "config", "[", ":consumer_key", "]", "=", "k", "end"], "docstring": "set the consumer key\n @param k [String] the consumer key", "docstring_tokens": ["set", "the", "consumer", "key"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L405-L408", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/dsl.rb", "func_name": "Chatterbot.DSL.secret", "original_string": "def secret(s)\n bot.deprecated \"Setting access_token_secret outside of your config file is deprecated!\", Kernel.caller.first\n bot.config[:access_token_secret] = s\n end", "language": "ruby", "code": "def secret(s)\n bot.deprecated \"Setting access_token_secret outside of your config file is deprecated!\", Kernel.caller.first\n bot.config[:access_token_secret] = s\n end", "code_tokens": ["def", "secret", "(", "s", ")", "bot", ".", "deprecated", "\"Setting access_token_secret outside of your config file is deprecated!\"", ",", "Kernel", ".", "caller", ".", "first", "bot", ".", "config", "[", ":access_token_secret", "]", "=", "s", "end"], "docstring": "set the secret\n @param s [String] the secret", "docstring_tokens": ["set", "the", "secret"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L413-L416", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/dsl.rb", "func_name": "Chatterbot.DSL.token", "original_string": "def token(s)\n bot.deprecated \"Setting access_token outside of your config file is deprecated!\", Kernel.caller.first\n bot.config[:access_token] = s\n end", "language": "ruby", "code": "def token(s)\n bot.deprecated \"Setting access_token outside of your config file is deprecated!\", Kernel.caller.first\n bot.config[:access_token] = s\n end", "code_tokens": ["def", "token", "(", "s", ")", "bot", ".", "deprecated", "\"Setting access_token outside of your config file is deprecated!\"", ",", "Kernel", ".", "caller", ".", "first", "bot", ".", "config", "[", ":access_token", "]", "=", "s", "end"], "docstring": "set the token\n @param s [String] the token", "docstring_tokens": ["set", "the", "token"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L421-L424", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/dsl.rb", "func_name": "Chatterbot.DSL.flatten_list_of_strings", "original_string": "def flatten_list_of_strings(args)\n args.collect do |b|\n if b.is_a?(String)\n # string, split on commas and turn into array\n b.split(\",\").collect { |s| s.strip }\n else\n # presumably an array\n b\n end\n end.flatten\n end", "language": "ruby", "code": "def flatten_list_of_strings(args)\n args.collect do |b|\n if b.is_a?(String)\n # string, split on commas and turn into array\n b.split(\",\").collect { |s| s.strip }\n else\n # presumably an array\n b\n end\n end.flatten\n end", "code_tokens": ["def", "flatten_list_of_strings", "(", "args", ")", "args", ".", "collect", "do", "|", "b", "|", "if", "b", ".", "is_a?", "(", "String", ")", "# string, split on commas and turn into array", "b", ".", "split", "(", "\",\"", ")", ".", "collect", "{", "|", "s", "|", "s", ".", "strip", "}", "else", "# presumably an array", "b", "end", "end", ".", "flatten", "end"], "docstring": "take a variable list of strings and possibly arrays and turn\n them into a single flat array of strings", "docstring_tokens": ["take", "a", "variable", "list", "of", "strings", "and", "possibly", "arrays", "and", "turn", "them", "into", "a", "single", "flat", "array", "of", "strings"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L447-L457", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/favorite.rb", "func_name": "Chatterbot.Favorite.favorite", "original_string": "def favorite(id=@current_tweet)\n return if require_login == false\n\n id = id_from_tweet(id)\n \n #:nocov:\n if debug_mode?\n debug \"I'm in debug mode, otherwise I would favorite tweet id: #{id}\"\n return\n end\n #:nocov:\n client.favorite id\n end", "language": "ruby", "code": "def favorite(id=@current_tweet)\n return if require_login == false\n\n id = id_from_tweet(id)\n \n #:nocov:\n if debug_mode?\n debug \"I'm in debug mode, otherwise I would favorite tweet id: #{id}\"\n return\n end\n #:nocov:\n client.favorite id\n end", "code_tokens": ["def", "favorite", "(", "id", "=", "@current_tweet", ")", "return", "if", "require_login", "==", "false", "id", "=", "id_from_tweet", "(", "id", ")", "#:nocov:", "if", "debug_mode?", "debug", "\"I'm in debug mode, otherwise I would favorite tweet id: #{id}\"", "return", "end", "#:nocov:", "client", ".", "favorite", "id", "end"], "docstring": "simple wrapper for favoriting a message\n @param [id] id A tweet or the ID of a tweet. if not specified,\n tries to use the current tweet if available", "docstring_tokens": ["simple", "wrapper", "for", "favoriting", "a", "message"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/favorite.rb#L9-L21", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/home_timeline.rb", "func_name": "Chatterbot.HomeTimeline.home_timeline", "original_string": "def home_timeline(*args, &block)\n return unless require_login\n debug \"check for home_timeline tweets since #{since_id_home_timeline}\"\n\n opts = {\n :since_id => since_id_home_timeline,\n :count => 200\n }\n results = client.home_timeline(opts)\n\n @current_tweet = nil\n results.each { |s|\n update_since_id_home_timeline(s)\n if block_given? && valid_tweet?(s)\n @current_tweet = s\n yield s \n end\n }\n @current_tweet = nil\n end", "language": "ruby", "code": "def home_timeline(*args, &block)\n return unless require_login\n debug \"check for home_timeline tweets since #{since_id_home_timeline}\"\n\n opts = {\n :since_id => since_id_home_timeline,\n :count => 200\n }\n results = client.home_timeline(opts)\n\n @current_tweet = nil\n results.each { |s|\n update_since_id_home_timeline(s)\n if block_given? && valid_tweet?(s)\n @current_tweet = s\n yield s \n end\n }\n @current_tweet = nil\n end", "code_tokens": ["def", "home_timeline", "(", "*", "args", ",", "&", "block", ")", "return", "unless", "require_login", "debug", "\"check for home_timeline tweets since #{since_id_home_timeline}\"", "opts", "=", "{", ":since_id", "=>", "since_id_home_timeline", ",", ":count", "=>", "200", "}", "results", "=", "client", ".", "home_timeline", "(", "opts", ")", "@current_tweet", "=", "nil", "results", ".", "each", "{", "|", "s", "|", "update_since_id_home_timeline", "(", "s", ")", "if", "block_given?", "&&", "valid_tweet?", "(", "s", ")", "@current_tweet", "=", "s", "yield", "s", "end", "}", "@current_tweet", "=", "nil", "end"], "docstring": "handle the bots timeline", "docstring_tokens": ["handle", "the", "bots", "timeline"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/home_timeline.rb#L8-L27", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/safelist.rb", "func_name": "Chatterbot.Safelist.on_safelist?", "original_string": "def on_safelist?(s)\n search = from_user(s).downcase\n safelist.any? { |b| search.include?(b.downcase) }\n end", "language": "ruby", "code": "def on_safelist?(s)\n search = from_user(s).downcase\n safelist.any? { |b| search.include?(b.downcase) }\n end", "code_tokens": ["def", "on_safelist?", "(", "s", ")", "search", "=", "from_user", "(", "s", ")", ".", "downcase", "safelist", ".", "any?", "{", "|", "b", "|", "search", ".", "include?", "(", "b", ".", "downcase", ")", "}", "end"], "docstring": "Is this tweet from a user on our safelist?", "docstring_tokens": ["Is", "this", "tweet", "from", "a", "user", "on", "our", "safelist?"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/safelist.rb#L28-L31", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/search.rb", "func_name": "Chatterbot.Search.search", "original_string": "def search(queries, opts = {}, &block)\n debug \"check for tweets since #{since_id}\"\n \n max_tweets = opts.delete(:limit) || MAX_SEARCH_TWEETS\n exact_match = if opts.key?(:exact)\n opts.delete(:exact)\n else\n true\n end\n \n \n if queries.is_a?(String)\n queries = [\n queries\n ]\n end\n\n query = queries.map { |q|\n if exact_match == true\n q = wrap_search_query(q)\n end\n\n q\n }.join(\" OR \")\n \n #\n # search twitter\n #\n\n debug \"search: #{query} #{default_opts.merge(opts)}\"\n @current_tweet = nil\n\n client.search( query, default_opts.merge(opts) ).take(max_tweets).each { |s|\n update_since_id(s)\n debug s.text\n\n if block_given? && valid_tweet?(s)\n @current_tweet = s\n yield s\n end\n }\n @current_tweet = nil\n\n end", "language": "ruby", "code": "def search(queries, opts = {}, &block)\n debug \"check for tweets since #{since_id}\"\n \n max_tweets = opts.delete(:limit) || MAX_SEARCH_TWEETS\n exact_match = if opts.key?(:exact)\n opts.delete(:exact)\n else\n true\n end\n \n \n if queries.is_a?(String)\n queries = [\n queries\n ]\n end\n\n query = queries.map { |q|\n if exact_match == true\n q = wrap_search_query(q)\n end\n\n q\n }.join(\" OR \")\n \n #\n # search twitter\n #\n\n debug \"search: #{query} #{default_opts.merge(opts)}\"\n @current_tweet = nil\n\n client.search( query, default_opts.merge(opts) ).take(max_tweets).each { |s|\n update_since_id(s)\n debug s.text\n\n if block_given? && valid_tweet?(s)\n @current_tweet = s\n yield s\n end\n }\n @current_tweet = nil\n\n end", "code_tokens": ["def", "search", "(", "queries", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "debug", "\"check for tweets since #{since_id}\"", "max_tweets", "=", "opts", ".", "delete", "(", ":limit", ")", "||", "MAX_SEARCH_TWEETS", "exact_match", "=", "if", "opts", ".", "key?", "(", ":exact", ")", "opts", ".", "delete", "(", ":exact", ")", "else", "true", "end", "if", "queries", ".", "is_a?", "(", "String", ")", "queries", "=", "[", "queries", "]", "end", "query", "=", "queries", ".", "map", "{", "|", "q", "|", "if", "exact_match", "==", "true", "q", "=", "wrap_search_query", "(", "q", ")", "end", "q", "}", ".", "join", "(", "\" OR \"", ")", "#", "# search twitter", "#", "debug", "\"search: #{query} #{default_opts.merge(opts)}\"", "@current_tweet", "=", "nil", "client", ".", "search", "(", "query", ",", "default_opts", ".", "merge", "(", "opts", ")", ")", ".", "take", "(", "max_tweets", ")", ".", "each", "{", "|", "s", "|", "update_since_id", "(", "s", ")", "debug", "s", ".", "text", "if", "block_given?", "&&", "valid_tweet?", "(", "s", ")", "@current_tweet", "=", "s", "yield", "s", "end", "}", "@current_tweet", "=", "nil", "end"], "docstring": "internal search code", "docstring_tokens": ["internal", "search", "code"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/search.rb#L44-L87", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/tweet.rb", "func_name": "Chatterbot.Tweet.tweet", "original_string": "def tweet(txt, params = {}, original = nil)\n return if require_login == false\n\n txt = replace_variables(txt, original)\n \n if debug_mode?\n debug \"I'm in debug mode, otherwise I would tweet: #{txt}\"\n else\n debug txt\n if params.has_key?(:media)\n file = params.delete(:media)\n if ! file.is_a?(File)\n file = File.new(file)\n end\n\n client.update_with_media txt, file, params\n else\n client.update txt, params\n end\n end\n rescue Twitter::Error::Forbidden => e\n #:nocov:\n debug e\n false\n #:nocov:\n end", "language": "ruby", "code": "def tweet(txt, params = {}, original = nil)\n return if require_login == false\n\n txt = replace_variables(txt, original)\n \n if debug_mode?\n debug \"I'm in debug mode, otherwise I would tweet: #{txt}\"\n else\n debug txt\n if params.has_key?(:media)\n file = params.delete(:media)\n if ! file.is_a?(File)\n file = File.new(file)\n end\n\n client.update_with_media txt, file, params\n else\n client.update txt, params\n end\n end\n rescue Twitter::Error::Forbidden => e\n #:nocov:\n debug e\n false\n #:nocov:\n end", "code_tokens": ["def", "tweet", "(", "txt", ",", "params", "=", "{", "}", ",", "original", "=", "nil", ")", "return", "if", "require_login", "==", "false", "txt", "=", "replace_variables", "(", "txt", ",", "original", ")", "if", "debug_mode?", "debug", "\"I'm in debug mode, otherwise I would tweet: #{txt}\"", "else", "debug", "txt", "if", "params", ".", "has_key?", "(", ":media", ")", "file", "=", "params", ".", "delete", "(", ":media", ")", "if", "!", "file", ".", "is_a?", "(", "File", ")", "file", "=", "File", ".", "new", "(", "file", ")", "end", "client", ".", "update_with_media", "txt", ",", "file", ",", "params", "else", "client", ".", "update", "txt", ",", "params", "end", "end", "rescue", "Twitter", "::", "Error", "::", "Forbidden", "=>", "e", "#:nocov:", "debug", "e", "false", "#:nocov:", "end"], "docstring": "simple wrapper for sending a message", "docstring_tokens": ["simple", "wrapper", "for", "sending", "a", "message"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/tweet.rb#L7-L32", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/tweet.rb", "func_name": "Chatterbot.Tweet.reply", "original_string": "def reply(txt, source, params = {})\n debug txt\n params = {:in_reply_to_status_id => source.id}.merge(params)\n tweet txt, params, source\n end", "language": "ruby", "code": "def reply(txt, source, params = {})\n debug txt\n params = {:in_reply_to_status_id => source.id}.merge(params)\n tweet txt, params, source\n end", "code_tokens": ["def", "reply", "(", "txt", ",", "source", ",", "params", "=", "{", "}", ")", "debug", "txt", "params", "=", "{", ":in_reply_to_status_id", "=>", "source", ".", "id", "}", ".", "merge", "(", "params", ")", "tweet", "txt", ",", "params", ",", "source", "end"], "docstring": "reply to a tweet", "docstring_tokens": ["reply", "to", "a", "tweet"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/tweet.rb#L36-L40", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/direct_messages.rb", "func_name": "Chatterbot.DirectMessages.direct_message", "original_string": "def direct_message(txt, user=nil)\n return unless require_login\n\n if user.nil?\n user = current_user\n end\n client.create_direct_message(user, txt)\n end", "language": "ruby", "code": "def direct_message(txt, user=nil)\n return unless require_login\n\n if user.nil?\n user = current_user\n end\n client.create_direct_message(user, txt)\n end", "code_tokens": ["def", "direct_message", "(", "txt", ",", "user", "=", "nil", ")", "return", "unless", "require_login", "if", "user", ".", "nil?", "user", "=", "current_user", "end", "client", ".", "create_direct_message", "(", "user", ",", "txt", ")", "end"], "docstring": "send a direct message", "docstring_tokens": ["send", "a", "direct", "message"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/direct_messages.rb#L8-L15", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/direct_messages.rb", "func_name": "Chatterbot.DirectMessages.direct_messages", "original_string": "def direct_messages(opts = {}, &block)\n return unless require_login\n debug \"check for DMs since #{since_id_dm}\"\n \n #\n # search twitter\n #\n\n @current_tweet = nil\n client.direct_messages_received(since_id:since_id_dm, count:200).each { |s|\n update_since_id_dm(s)\n debug s.text\n if has_safelist? && !on_safelist?(s.sender)\n debug \"skipping because user not on safelist\"\n elsif block_given? && !on_blocklist?(s.sender) && !skip_me?(s)\n @current_tweet = s\n yield s\n end\n }\n @current_tweet = nil\n rescue Twitter::Error::Forbidden => e\n puts \"sorry, looks like we're not allowed to check DMs for this account\"\n end", "language": "ruby", "code": "def direct_messages(opts = {}, &block)\n return unless require_login\n debug \"check for DMs since #{since_id_dm}\"\n \n #\n # search twitter\n #\n\n @current_tweet = nil\n client.direct_messages_received(since_id:since_id_dm, count:200).each { |s|\n update_since_id_dm(s)\n debug s.text\n if has_safelist? && !on_safelist?(s.sender)\n debug \"skipping because user not on safelist\"\n elsif block_given? && !on_blocklist?(s.sender) && !skip_me?(s)\n @current_tweet = s\n yield s\n end\n }\n @current_tweet = nil\n rescue Twitter::Error::Forbidden => e\n puts \"sorry, looks like we're not allowed to check DMs for this account\"\n end", "code_tokens": ["def", "direct_messages", "(", "opts", "=", "{", "}", ",", "&", "block", ")", "return", "unless", "require_login", "debug", "\"check for DMs since #{since_id_dm}\"", "#", "# search twitter", "#", "@current_tweet", "=", "nil", "client", ".", "direct_messages_received", "(", "since_id", ":since_id_dm", ",", "count", ":", "200", ")", ".", "each", "{", "|", "s", "|", "update_since_id_dm", "(", "s", ")", "debug", "s", ".", "text", "if", "has_safelist?", "&&", "!", "on_safelist?", "(", "s", ".", "sender", ")", "debug", "\"skipping because user not on safelist\"", "elsif", "block_given?", "&&", "!", "on_blocklist?", "(", "s", ".", "sender", ")", "&&", "!", "skip_me?", "(", "s", ")", "@current_tweet", "=", "s", "yield", "s", "end", "}", "@current_tweet", "=", "nil", "rescue", "Twitter", "::", "Error", "::", "Forbidden", "=>", "e", "puts", "\"sorry, looks like we're not allowed to check DMs for this account\"", "end"], "docstring": "check direct messages for the bot", "docstring_tokens": ["check", "direct", "messages", "for", "the", "bot"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/direct_messages.rb#L20-L42", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/ui.rb", "func_name": "Chatterbot.UI.get_oauth_verifier", "original_string": "def get_oauth_verifier\n green \"****************************************\"\n green \"****************************************\"\n green \"**** BOT AUTH TIME! ****\"\n green \"****************************************\"\n green \"****************************************\" \n\n puts \"You need to authorize your bot with Twitter.\\n\\nPlease login to Twitter under the bot's account. When you're ready, hit Enter.\\n\\nYour browser will open with the following URL, where you can authorize the bot.\\n\\n\"\n\n url = request_token.authorize_url\n\n puts url\n\n puts \"\\nIf that doesn't work, you can open the URL in your browser manually.\"\n\n puts \"\\n\\nHit enter to start.\\n\\n\"\n \n STDIN.readline.chomp\n \n Launchy.open(url)\n\n # sleep here so that if launchy has any output (which it does\n # sometimes), it doesn't interfere with our input prompt\n \n sleep(2)\n\n puts \"Paste your PIN and hit enter when you have completed authorization.\\n\\n\"\n print \"> \"\n\n STDIN.readline.chomp.strip\n rescue Interrupt => e\n exit\n end", "language": "ruby", "code": "def get_oauth_verifier\n green \"****************************************\"\n green \"****************************************\"\n green \"**** BOT AUTH TIME! ****\"\n green \"****************************************\"\n green \"****************************************\" \n\n puts \"You need to authorize your bot with Twitter.\\n\\nPlease login to Twitter under the bot's account. When you're ready, hit Enter.\\n\\nYour browser will open with the following URL, where you can authorize the bot.\\n\\n\"\n\n url = request_token.authorize_url\n\n puts url\n\n puts \"\\nIf that doesn't work, you can open the URL in your browser manually.\"\n\n puts \"\\n\\nHit enter to start.\\n\\n\"\n \n STDIN.readline.chomp\n \n Launchy.open(url)\n\n # sleep here so that if launchy has any output (which it does\n # sometimes), it doesn't interfere with our input prompt\n \n sleep(2)\n\n puts \"Paste your PIN and hit enter when you have completed authorization.\\n\\n\"\n print \"> \"\n\n STDIN.readline.chomp.strip\n rescue Interrupt => e\n exit\n end", "code_tokens": ["def", "get_oauth_verifier", "green", "\"****************************************\"", "green", "\"****************************************\"", "green", "\"**** BOT AUTH TIME! ****\"", "green", "\"****************************************\"", "green", "\"****************************************\"", "puts", "\"You need to authorize your bot with Twitter.\\n\\nPlease login to Twitter under the bot's account. When you're ready, hit Enter.\\n\\nYour browser will open with the following URL, where you can authorize the bot.\\n\\n\"", "url", "=", "request_token", ".", "authorize_url", "puts", "url", "puts", "\"\\nIf that doesn't work, you can open the URL in your browser manually.\"", "puts", "\"\\n\\nHit enter to start.\\n\\n\"", "STDIN", ".", "readline", ".", "chomp", "Launchy", ".", "open", "(", "url", ")", "# sleep here so that if launchy has any output (which it does", "# sometimes), it doesn't interfere with our input prompt", "sleep", "(", "2", ")", "puts", "\"Paste your PIN and hit enter when you have completed authorization.\\n\\n\"", "print", "\"> \"", "STDIN", ".", "readline", ".", "chomp", ".", "strip", "rescue", "Interrupt", "=>", "e", "exit", "end"], "docstring": "print out a message about getting a PIN from twitter, then output\n the URL the user needs to visit to authorize", "docstring_tokens": ["print", "out", "a", "message", "about", "getting", "a", "PIN", "from", "twitter", "then", "output", "the", "URL", "the", "user", "needs", "to", "visit", "to", "authorize"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/ui.rb#L30-L62", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/ui.rb", "func_name": "Chatterbot.UI.get_api_key", "original_string": "def get_api_key\n \n green \"****************************************\"\n green \"****************************************\"\n green \"**** API SETUP TIME! ****\"\n green \"****************************************\"\n green \"****************************************\" \n\n\n puts \"\\n\\nWelcome to Chatterbot. Let's walk through the steps to get a bot running.\\n\\n\"\n\n\n #\n # At this point, we don't have any API credentials at all for\n # this bot, but it's possible the user has already setup an app.\n # Let's ask!\n #\n \n puts \"Hey, looks like you need to get an API key from Twitter before you can get started.\\n\\n\"\n \n app_already_exists = ask_yes_no(\"Have you already set up an app with Twitter?\")\n\n if app_already_exists\n puts \"Terrific! Let's get your bot running!\\n\\n\"\n else\n puts \"OK, I can help with that!\\n\\n\"\n send_to_app_creation\n end\n\n \n print \"\\n\\nPaste the 'Consumer Key' here: \"\n STDOUT.flush\n config[:consumer_key] = STDIN.readline.chomp.strip\n\n print \"Paste the 'Consumer Secret' here: \"\n STDOUT.flush\n config[:consumer_secret] = STDIN.readline.chomp.strip\n\n\n puts \"\\n\\nNow it's time to authorize your bot!\\n\\n\"\n \n if ! app_already_exists && ask_yes_no(\"Do you want to authorize a bot using the account that created the app?\")\n puts \"OK, on the app page, you can click the 'Create my access token' button to proceed.\\n\\n\"\n\n print \"Paste the 'Access Token' here: \"\n STDOUT.flush\n config[:access_token] = STDIN.readline.chomp.strip\n\n\n print \"\\n\\nPaste the 'Access Token Secret' here: \"\n STDOUT.flush\n config[:access_token_secret] = STDIN.readline.chomp.strip\n\n \n # reset the client so we can re-init with new OAuth credentials\n reset_client\n\n # at this point we should have a fully validated client, so grab\n # the screen name\n @screen_name = client.user.screen_name rescue nil\n else\n reset_client\n end\n \n \n #\n # capture ctrl-c and exit without a stack trace\n #\n rescue Interrupt => e\n exit\n end", "language": "ruby", "code": "def get_api_key\n \n green \"****************************************\"\n green \"****************************************\"\n green \"**** API SETUP TIME! ****\"\n green \"****************************************\"\n green \"****************************************\" \n\n\n puts \"\\n\\nWelcome to Chatterbot. Let's walk through the steps to get a bot running.\\n\\n\"\n\n\n #\n # At this point, we don't have any API credentials at all for\n # this bot, but it's possible the user has already setup an app.\n # Let's ask!\n #\n \n puts \"Hey, looks like you need to get an API key from Twitter before you can get started.\\n\\n\"\n \n app_already_exists = ask_yes_no(\"Have you already set up an app with Twitter?\")\n\n if app_already_exists\n puts \"Terrific! Let's get your bot running!\\n\\n\"\n else\n puts \"OK, I can help with that!\\n\\n\"\n send_to_app_creation\n end\n\n \n print \"\\n\\nPaste the 'Consumer Key' here: \"\n STDOUT.flush\n config[:consumer_key] = STDIN.readline.chomp.strip\n\n print \"Paste the 'Consumer Secret' here: \"\n STDOUT.flush\n config[:consumer_secret] = STDIN.readline.chomp.strip\n\n\n puts \"\\n\\nNow it's time to authorize your bot!\\n\\n\"\n \n if ! app_already_exists && ask_yes_no(\"Do you want to authorize a bot using the account that created the app?\")\n puts \"OK, on the app page, you can click the 'Create my access token' button to proceed.\\n\\n\"\n\n print \"Paste the 'Access Token' here: \"\n STDOUT.flush\n config[:access_token] = STDIN.readline.chomp.strip\n\n\n print \"\\n\\nPaste the 'Access Token Secret' here: \"\n STDOUT.flush\n config[:access_token_secret] = STDIN.readline.chomp.strip\n\n \n # reset the client so we can re-init with new OAuth credentials\n reset_client\n\n # at this point we should have a fully validated client, so grab\n # the screen name\n @screen_name = client.user.screen_name rescue nil\n else\n reset_client\n end\n \n \n #\n # capture ctrl-c and exit without a stack trace\n #\n rescue Interrupt => e\n exit\n end", "code_tokens": ["def", "get_api_key", "green", "\"****************************************\"", "green", "\"****************************************\"", "green", "\"**** API SETUP TIME! ****\"", "green", "\"****************************************\"", "green", "\"****************************************\"", "puts", "\"\\n\\nWelcome to Chatterbot. Let's walk through the steps to get a bot running.\\n\\n\"", "#", "# At this point, we don't have any API credentials at all for", "# this bot, but it's possible the user has already setup an app.", "# Let's ask!", "#", "puts", "\"Hey, looks like you need to get an API key from Twitter before you can get started.\\n\\n\"", "app_already_exists", "=", "ask_yes_no", "(", "\"Have you already set up an app with Twitter?\"", ")", "if", "app_already_exists", "puts", "\"Terrific! Let's get your bot running!\\n\\n\"", "else", "puts", "\"OK, I can help with that!\\n\\n\"", "send_to_app_creation", "end", "print", "\"\\n\\nPaste the 'Consumer Key' here: \"", "STDOUT", ".", "flush", "config", "[", ":consumer_key", "]", "=", "STDIN", ".", "readline", ".", "chomp", ".", "strip", "print", "\"Paste the 'Consumer Secret' here: \"", "STDOUT", ".", "flush", "config", "[", ":consumer_secret", "]", "=", "STDIN", ".", "readline", ".", "chomp", ".", "strip", "puts", "\"\\n\\nNow it's time to authorize your bot!\\n\\n\"", "if", "!", "app_already_exists", "&&", "ask_yes_no", "(", "\"Do you want to authorize a bot using the account that created the app?\"", ")", "puts", "\"OK, on the app page, you can click the 'Create my access token' button to proceed.\\n\\n\"", "print", "\"Paste the 'Access Token' here: \"", "STDOUT", ".", "flush", "config", "[", ":access_token", "]", "=", "STDIN", ".", "readline", ".", "chomp", ".", "strip", "print", "\"\\n\\nPaste the 'Access Token Secret' here: \"", "STDOUT", ".", "flush", "config", "[", ":access_token_secret", "]", "=", "STDIN", ".", "readline", ".", "chomp", ".", "strip", "# reset the client so we can re-init with new OAuth credentials", "reset_client", "# at this point we should have a fully validated client, so grab", "# the screen name", "@screen_name", "=", "client", ".", "user", ".", "screen_name", "rescue", "nil", "else", "reset_client", "end", "#", "# capture ctrl-c and exit without a stack trace", "#", "rescue", "Interrupt", "=>", "e", "exit", "end"], "docstring": "Ask the user to get an API key from Twitter.", "docstring_tokens": ["Ask", "the", "user", "to", "get", "an", "API", "key", "from", "Twitter", "."], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/ui.rb#L103-L173", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/config.rb", "func_name": "Chatterbot.Config.max_id_from", "original_string": "def max_id_from(s)\n if ! s.respond_to?(:max)\n if s.respond_to?(:id)\n return s.id\n else\n return s\n end \n end\n \n \n sorted = s.max { |a, b| a.id.to_i <=> b.id.to_i }\n sorted && sorted.id\n end", "language": "ruby", "code": "def max_id_from(s)\n if ! s.respond_to?(:max)\n if s.respond_to?(:id)\n return s.id\n else\n return s\n end \n end\n \n \n sorted = s.max { |a, b| a.id.to_i <=> b.id.to_i }\n sorted && sorted.id\n end", "code_tokens": ["def", "max_id_from", "(", "s", ")", "if", "!", "s", ".", "respond_to?", "(", ":max", ")", "if", "s", ".", "respond_to?", "(", ":id", ")", "return", "s", ".", "id", "else", "return", "s", "end", "end", "sorted", "=", "s", ".", "max", "{", "|", "a", ",", "b", "|", "a", ".", "id", ".", "to_i", "<=>", "b", ".", "id", ".", "to_i", "}", "sorted", "&&", "sorted", ".", "id", "end"], "docstring": "given an array or object, return the highest id we can find\n @param [Enumerable] s the array to check", "docstring_tokens": ["given", "an", "array", "or", "object", "return", "the", "highest", "id", "we", "can", "find"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/config.rb#L125-L137", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/config.rb", "func_name": "Chatterbot.Config.slurp_file", "original_string": "def slurp_file(f)\n f = File.expand_path(f)\n tmp = {}\n\n if File.exist?(f)\n File.open( f ) { |yf| \n tmp = YAML::load( yf ) \n }\n end\n tmp.symbolize_keys! unless tmp == false\n end", "language": "ruby", "code": "def slurp_file(f)\n f = File.expand_path(f)\n tmp = {}\n\n if File.exist?(f)\n File.open( f ) { |yf| \n tmp = YAML::load( yf ) \n }\n end\n tmp.symbolize_keys! unless tmp == false\n end", "code_tokens": ["def", "slurp_file", "(", "f", ")", "f", "=", "File", ".", "expand_path", "(", "f", ")", "tmp", "=", "{", "}", "if", "File", ".", "exist?", "(", "f", ")", "File", ".", "open", "(", "f", ")", "{", "|", "yf", "|", "tmp", "=", "YAML", "::", "load", "(", "yf", ")", "}", "end", "tmp", ".", "symbolize_keys!", "unless", "tmp", "==", "false", "end"], "docstring": "load in a config file", "docstring_tokens": ["load", "in", "a", "config", "file"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/config.rb#L170-L180", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/config.rb", "func_name": "Chatterbot.Config.global_config", "original_string": "def global_config\n tmp = {}\n global_config_files.each { |f|\n tmp.merge!(slurp_file(f) || {}) \n }\n tmp\n end", "language": "ruby", "code": "def global_config\n tmp = {}\n global_config_files.each { |f|\n tmp.merge!(slurp_file(f) || {}) \n }\n tmp\n end", "code_tokens": ["def", "global_config", "tmp", "=", "{", "}", "global_config_files", ".", "each", "{", "|", "f", "|", "tmp", ".", "merge!", "(", "slurp_file", "(", "f", ")", "||", "{", "}", ")", "}", "tmp", "end"], "docstring": "get any config from our global config files", "docstring_tokens": ["get", "any", "config", "from", "our", "global", "config", "files"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/config.rb#L199-L205", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/config.rb", "func_name": "Chatterbot.Config.bot_config", "original_string": "def bot_config\n {\n :consumer_key => ENV[\"chatterbot_consumer_key\"],\n :consumer_secret => ENV[\"chatterbot_consumer_secret\"],\n :access_token => ENV[\"chatterbot_access_token\"],\n :access_token_secret => ENV[\"chatterbot_access_secret\"] || ENV[\"chatterbot_access_token_secret\"]\n }.delete_if { |k, v| v.nil? }.merge(slurp_file(config_file) || {})\n end", "language": "ruby", "code": "def bot_config\n {\n :consumer_key => ENV[\"chatterbot_consumer_key\"],\n :consumer_secret => ENV[\"chatterbot_consumer_secret\"],\n :access_token => ENV[\"chatterbot_access_token\"],\n :access_token_secret => ENV[\"chatterbot_access_secret\"] || ENV[\"chatterbot_access_token_secret\"]\n }.delete_if { |k, v| v.nil? }.merge(slurp_file(config_file) || {})\n end", "code_tokens": ["def", "bot_config", "{", ":consumer_key", "=>", "ENV", "[", "\"chatterbot_consumer_key\"", "]", ",", ":consumer_secret", "=>", "ENV", "[", "\"chatterbot_consumer_secret\"", "]", ",", ":access_token", "=>", "ENV", "[", "\"chatterbot_access_token\"", "]", ",", ":access_token_secret", "=>", "ENV", "[", "\"chatterbot_access_secret\"", "]", "||", "ENV", "[", "\"chatterbot_access_token_secret\"", "]", "}", ".", "delete_if", "{", "|", "k", ",", "v", "|", "v", ".", "nil?", "}", ".", "merge", "(", "slurp_file", "(", "config_file", ")", "||", "{", "}", ")", "end"], "docstring": "bot-specific config settings", "docstring_tokens": ["bot", "-", "specific", "config", "settings"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/config.rb#L209-L216", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/config.rb", "func_name": "Chatterbot.Config.load_config", "original_string": "def load_config(params={})\n read_only_data = global_config.merge(bot_config).merge(params)\n @config = Chatterbot::ConfigManager.new(config_file, read_only_data)\n end", "language": "ruby", "code": "def load_config(params={})\n read_only_data = global_config.merge(bot_config).merge(params)\n @config = Chatterbot::ConfigManager.new(config_file, read_only_data)\n end", "code_tokens": ["def", "load_config", "(", "params", "=", "{", "}", ")", "read_only_data", "=", "global_config", ".", "merge", "(", "bot_config", ")", ".", "merge", "(", "params", ")", "@config", "=", "Chatterbot", "::", "ConfigManager", ".", "new", "(", "config_file", ",", "read_only_data", ")", "end"], "docstring": "load in the config from the assortment of places it can be specified.", "docstring_tokens": ["load", "in", "the", "config", "from", "the", "assortment", "of", "places", "it", "can", "be", "specified", "."], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/config.rb#L221-L224", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/retweet.rb", "func_name": "Chatterbot.Retweet.retweet", "original_string": "def retweet(id=@current_tweet)\n return if require_login == false || id.nil?\n\n id = id_from_tweet(id)\n #:nocov:\n if debug_mode?\n debug \"I'm in debug mode, otherwise I would retweet with tweet id: #{id}\"\n return\n end\n #:nocov:\n \n client.retweet id\n end", "language": "ruby", "code": "def retweet(id=@current_tweet)\n return if require_login == false || id.nil?\n\n id = id_from_tweet(id)\n #:nocov:\n if debug_mode?\n debug \"I'm in debug mode, otherwise I would retweet with tweet id: #{id}\"\n return\n end\n #:nocov:\n \n client.retweet id\n end", "code_tokens": ["def", "retweet", "(", "id", "=", "@current_tweet", ")", "return", "if", "require_login", "==", "false", "||", "id", ".", "nil?", "id", "=", "id_from_tweet", "(", "id", ")", "#:nocov:", "if", "debug_mode?", "debug", "\"I'm in debug mode, otherwise I would retweet with tweet id: #{id}\"", "return", "end", "#:nocov:", "client", ".", "retweet", "id", "end"], "docstring": "simple wrapper for retweeting a message\n @param [id] id A tweet or the ID of a tweet. if not specified,\n tries to use the current tweet if available", "docstring_tokens": ["simple", "wrapper", "for", "retweeting", "a", "message"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/retweet.rb#L9-L21", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/bot.rb", "func_name": "Chatterbot.Bot.run!", "original_string": "def run!\n before_run\n\n HANDLER_CALLS.each { |c|\n if (h = @handlers[c])\n send(c, *(h.opts)) do |obj|\n h.call(obj)\n end\n end\n }\n\n after_run\n end", "language": "ruby", "code": "def run!\n before_run\n\n HANDLER_CALLS.each { |c|\n if (h = @handlers[c])\n send(c, *(h.opts)) do |obj|\n h.call(obj)\n end\n end\n }\n\n after_run\n end", "code_tokens": ["def", "run!", "before_run", "HANDLER_CALLS", ".", "each", "{", "|", "c", "|", "if", "(", "h", "=", "@handlers", "[", "c", "]", ")", "send", "(", "c", ",", "(", "h", ".", "opts", ")", ")", "do", "|", "obj", "|", "h", ".", "call", "(", "obj", ")", "end", "end", "}", "after_run", "end"], "docstring": "run the bot with the REST API", "docstring_tokens": ["run", "the", "bot", "with", "the", "REST", "API"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/bot.rb#L60-L72", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/reply.rb", "func_name": "Chatterbot.Reply.replies", "original_string": "def replies(*args, &block)\n return unless require_login\n\n debug \"check for replies since #{since_id_reply}\"\n\n opts = {\n :since_id => since_id_reply,\n :count => 200\n }\n\n results = client.mentions_timeline(opts)\n @current_tweet = nil\n results.each { |s|\n update_since_id_reply(s)\n if block_given? && valid_tweet?(s)\n @current_tweet = s\n yield s \n end\n }\n @current_tweet = nil\n end", "language": "ruby", "code": "def replies(*args, &block)\n return unless require_login\n\n debug \"check for replies since #{since_id_reply}\"\n\n opts = {\n :since_id => since_id_reply,\n :count => 200\n }\n\n results = client.mentions_timeline(opts)\n @current_tweet = nil\n results.each { |s|\n update_since_id_reply(s)\n if block_given? && valid_tweet?(s)\n @current_tweet = s\n yield s \n end\n }\n @current_tweet = nil\n end", "code_tokens": ["def", "replies", "(", "*", "args", ",", "&", "block", ")", "return", "unless", "require_login", "debug", "\"check for replies since #{since_id_reply}\"", "opts", "=", "{", ":since_id", "=>", "since_id_reply", ",", ":count", "=>", "200", "}", "results", "=", "client", ".", "mentions_timeline", "(", "opts", ")", "@current_tweet", "=", "nil", "results", ".", "each", "{", "|", "s", "|", "update_since_id_reply", "(", "s", ")", "if", "block_given?", "&&", "valid_tweet?", "(", "s", ")", "@current_tweet", "=", "s", "yield", "s", "end", "}", "@current_tweet", "=", "nil", "end"], "docstring": "handle replies for the bot", "docstring_tokens": ["handle", "replies", "for", "the", "bot"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/reply.rb#L8-L28", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/blocklist.rb", "func_name": "Chatterbot.Blocklist.skip_me?", "original_string": "def skip_me?(s)\n search = s.respond_to?(:text) ? s.text : s\n exclude.detect { |e| search.downcase.include?(e) } != nil\n end", "language": "ruby", "code": "def skip_me?(s)\n search = s.respond_to?(:text) ? s.text : s\n exclude.detect { |e| search.downcase.include?(e) } != nil\n end", "code_tokens": ["def", "skip_me?", "(", "s", ")", "search", "=", "s", ".", "respond_to?", "(", ":text", ")", "?", "s", ".", "text", ":", "s", "exclude", ".", "detect", "{", "|", "e", "|", "search", ".", "downcase", ".", "include?", "(", "e", ")", "}", "!=", "nil", "end"], "docstring": "Based on the text of this tweet, should it be skipped?", "docstring_tokens": ["Based", "on", "the", "text", "of", "this", "tweet", "should", "it", "be", "skipped?"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/blocklist.rb#L26-L29", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/blocklist.rb", "func_name": "Chatterbot.Blocklist.on_blocklist?", "original_string": "def on_blocklist?(s)\n search = if s.is_a?(Twitter::User)\n s.name\n elsif s.respond_to?(:user) && !s.is_a?(Twitter::NullObject)\n from_user(s)\n else\n s\n end.downcase\n\n blocklist.any? { |b| search.include?(b.downcase) }\n end", "language": "ruby", "code": "def on_blocklist?(s)\n search = if s.is_a?(Twitter::User)\n s.name\n elsif s.respond_to?(:user) && !s.is_a?(Twitter::NullObject)\n from_user(s)\n else\n s\n end.downcase\n\n blocklist.any? { |b| search.include?(b.downcase) }\n end", "code_tokens": ["def", "on_blocklist?", "(", "s", ")", "search", "=", "if", "s", ".", "is_a?", "(", "Twitter", "::", "User", ")", "s", ".", "name", "elsif", "s", ".", "respond_to?", "(", ":user", ")", "&&", "!", "s", ".", "is_a?", "(", "Twitter", "::", "NullObject", ")", "from_user", "(", "s", ")", "else", "s", "end", ".", "downcase", "blocklist", ".", "any?", "{", "|", "b", "|", "search", ".", "include?", "(", "b", ".", "downcase", ")", "}", "end"], "docstring": "Is this tweet from a user on our blocklist?", "docstring_tokens": ["Is", "this", "tweet", "from", "a", "user", "on", "our", "blocklist?"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/blocklist.rb#L48-L58", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/client.rb", "func_name": "Chatterbot.Client.reset_since_id", "original_string": "def reset_since_id\n config[:since_id] = 1\n # do a search of recent tweets with the letter 'a' in them to\n # get a rough max tweet id\n result = client.search(\"a\", since:Time.now - 10).max_by(&:id)\n update_since_id(result)\n end", "language": "ruby", "code": "def reset_since_id\n config[:since_id] = 1\n # do a search of recent tweets with the letter 'a' in them to\n # get a rough max tweet id\n result = client.search(\"a\", since:Time.now - 10).max_by(&:id)\n update_since_id(result)\n end", "code_tokens": ["def", "reset_since_id", "config", "[", ":since_id", "]", "=", "1", "# do a search of recent tweets with the letter 'a' in them to", "# get a rough max tweet id", "result", "=", "client", ".", "search", "(", "\"a\"", ",", "since", ":", "Time", ".", "now", "-", "10", ")", ".", "max_by", "(", ":id", ")", "update_since_id", "(", "result", ")", "end"], "docstring": "reset the since_id for this bot to the highest since_id we can\n get, by running a really open search and updating config with\n the max_id", "docstring_tokens": ["reset", "the", "since_id", "for", "this", "bot", "to", "the", "highest", "since_id", "we", "can", "get", "by", "running", "a", "really", "open", "search", "and", "updating", "config", "with", "the", "max_id"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/client.rb#L47-L53", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/client.rb", "func_name": "Chatterbot.Client.generate_authorize_url", "original_string": "def generate_authorize_url(request_token)\n request = consumer.create_signed_request(:get,\n consumer.authorize_path, request_token,\n {:oauth_callback => 'oob'})\n\n params = request['Authorization'].sub(/^OAuth\\s+/, '').split(/,\\s+/).map do |param|\n key, value = param.split('=')\n value =~ /\"(.*?)\"/\n \"#{key}=#{CGI::escape($1)}\"\n end.join('&')\n\n \"#{base_url}#{request.path}?#{params}\"\n end", "language": "ruby", "code": "def generate_authorize_url(request_token)\n request = consumer.create_signed_request(:get,\n consumer.authorize_path, request_token,\n {:oauth_callback => 'oob'})\n\n params = request['Authorization'].sub(/^OAuth\\s+/, '').split(/,\\s+/).map do |param|\n key, value = param.split('=')\n value =~ /\"(.*?)\"/\n \"#{key}=#{CGI::escape($1)}\"\n end.join('&')\n\n \"#{base_url}#{request.path}?#{params}\"\n end", "code_tokens": ["def", "generate_authorize_url", "(", "request_token", ")", "request", "=", "consumer", ".", "create_signed_request", "(", ":get", ",", "consumer", ".", "authorize_path", ",", "request_token", ",", "{", ":oauth_callback", "=>", "'oob'", "}", ")", "params", "=", "request", "[", "'Authorization'", "]", ".", "sub", "(", "/", "\\s", "/", ",", "''", ")", ".", "split", "(", "/", "\\s", "/", ")", ".", "map", "do", "|", "param", "|", "key", ",", "value", "=", "param", ".", "split", "(", "'='", ")", "value", "=~", "/", "/", "\"#{key}=#{CGI::escape($1)}\"", "end", ".", "join", "(", "'&'", ")", "\"#{base_url}#{request.path}?#{params}\"", "end"], "docstring": "copied from t, the awesome twitter cli app\n @see https://github.com/sferik/t/blob/master/lib/t/authorizable.rb", "docstring_tokens": ["copied", "from", "t", "the", "awesome", "twitter", "cli", "app"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/client.rb#L143-L155", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/client.rb", "func_name": "Chatterbot.Client.get_screen_name", "original_string": "def get_screen_name(t = @access_token)\n return unless @screen_name.nil?\n return if t.nil?\n\n oauth_response = t.get('/1.1/account/verify_credentials.json')\n @screen_name = JSON.parse(oauth_response.body)[\"screen_name\"]\n end", "language": "ruby", "code": "def get_screen_name(t = @access_token)\n return unless @screen_name.nil?\n return if t.nil?\n\n oauth_response = t.get('/1.1/account/verify_credentials.json')\n @screen_name = JSON.parse(oauth_response.body)[\"screen_name\"]\n end", "code_tokens": ["def", "get_screen_name", "(", "t", "=", "@access_token", ")", "return", "unless", "@screen_name", ".", "nil?", "return", "if", "t", ".", "nil?", "oauth_response", "=", "t", ".", "get", "(", "'/1.1/account/verify_credentials.json'", ")", "@screen_name", "=", "JSON", ".", "parse", "(", "oauth_response", ".", "body", ")", "[", "\"screen_name\"", "]", "end"], "docstring": "query twitter for the bots screen name. we do this during the bot registration process", "docstring_tokens": ["query", "twitter", "for", "the", "bots", "screen", "name", ".", "we", "do", "this", "during", "the", "bot", "registration", "process"], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/client.rb#L165-L171", "partition": "valid"} {"repo": "muffinista/chatterbot", "path": "lib/chatterbot/client.rb", "func_name": "Chatterbot.Client.login", "original_string": "def login(do_update_config=true)\n if needs_api_key?\n get_api_key\n end\n\n if needs_auth_token?\n pin = get_oauth_verifier\n return false if pin.nil?\n\n\n begin\n # this will throw an error that we can try and catch\n @access_token = request_token.get_access_token(:oauth_verifier => pin.chomp)\n get_screen_name\n\n self.config[:access_token] = @access_token.token\n self.config[:access_token_secret] = @access_token.secret\n\n #update_config unless ! do_update_config\n reset_client\n\n rescue OAuth::Unauthorized => e\n display_oauth_error\n warn e.inspect\n return false\n end\n end\n\n return true\n end", "language": "ruby", "code": "def login(do_update_config=true)\n if needs_api_key?\n get_api_key\n end\n\n if needs_auth_token?\n pin = get_oauth_verifier\n return false if pin.nil?\n\n\n begin\n # this will throw an error that we can try and catch\n @access_token = request_token.get_access_token(:oauth_verifier => pin.chomp)\n get_screen_name\n\n self.config[:access_token] = @access_token.token\n self.config[:access_token_secret] = @access_token.secret\n\n #update_config unless ! do_update_config\n reset_client\n\n rescue OAuth::Unauthorized => e\n display_oauth_error\n warn e.inspect\n return false\n end\n end\n\n return true\n end", "code_tokens": ["def", "login", "(", "do_update_config", "=", "true", ")", "if", "needs_api_key?", "get_api_key", "end", "if", "needs_auth_token?", "pin", "=", "get_oauth_verifier", "return", "false", "if", "pin", ".", "nil?", "begin", "# this will throw an error that we can try and catch", "@access_token", "=", "request_token", ".", "get_access_token", "(", ":oauth_verifier", "=>", "pin", ".", "chomp", ")", "get_screen_name", "self", ".", "config", "[", ":access_token", "]", "=", "@access_token", ".", "token", "self", ".", "config", "[", ":access_token_secret", "]", "=", "@access_token", ".", "secret", "#update_config unless ! do_update_config", "reset_client", "rescue", "OAuth", "::", "Unauthorized", "=>", "e", "display_oauth_error", "warn", "e", ".", "inspect", "return", "false", "end", "end", "return", "true", "end"], "docstring": "handle oauth for this request. if the client isn't authorized, print\n out the auth URL and get a pin code back from the user\n If +do_update_config+ is false, don't udpate the bots config\n file after authorization. This defaults to true but\n chatterbot-register will pass in false because it does some\n other work before saving.", "docstring_tokens": ["handle", "oauth", "for", "this", "request", ".", "if", "the", "client", "isn", "t", "authorized", "print", "out", "the", "auth", "URL", "and", "get", "a", "pin", "code", "back", "from", "the", "user", "If", "+", "do_update_config", "+", "is", "false", "don", "t", "udpate", "the", "bots", "config", "file", "after", "authorization", ".", "This", "defaults", "to", "true", "but", "chatterbot", "-", "register", "will", "pass", "in", "false", "because", "it", "does", "some", "other", "work", "before", "saving", "."], "sha": "e98ebb4e23882a9aa078bc5f749a6d045c35e9be", "url": "https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/client.rb#L180-L209", "partition": "valid"} {"repo": "rx/presenters", "path": "lib/voom/container_methods.rb", "func_name": "Voom.ContainerMethods.reset!", "original_string": "def reset!\n registered_keys.each { |key| ClassConstants.new(key).deconstantize }\n @registered_keys = []\n container._container.clear\n end", "language": "ruby", "code": "def reset!\n registered_keys.each { |key| ClassConstants.new(key).deconstantize }\n @registered_keys = []\n container._container.clear\n end", "code_tokens": ["def", "reset!", "registered_keys", ".", "each", "{", "|", "key", "|", "ClassConstants", ".", "new", "(", "key", ")", ".", "deconstantize", "}", "@registered_keys", "=", "[", "]", "container", ".", "_container", ".", "clear", "end"], "docstring": "This method empties out the container\n It should ONLY be used for testing purposes", "docstring_tokens": ["This", "method", "empties", "out", "the", "container", "It", "should", "ONLY", "be", "used", "for", "testing", "purposes"], "sha": "983c151df9d3e633dd772482149e831ab76e69fc", "url": "https://github.com/rx/presenters/blob/983c151df9d3e633dd772482149e831ab76e69fc/lib/voom/container_methods.rb#L35-L39", "partition": "valid"} {"repo": "rx/presenters", "path": "lib/voom/symbol/to_str.rb", "func_name": "Voom.Symbol.class_name", "original_string": "def class_name(classname)\n classname = sym_to_str(classname)\n classname.split('.').map { |m| inflector.camelize(m) }.join('::')\n end", "language": "ruby", "code": "def class_name(classname)\n classname = sym_to_str(classname)\n classname.split('.').map { |m| inflector.camelize(m) }.join('::')\n end", "code_tokens": ["def", "class_name", "(", "classname", ")", "classname", "=", "sym_to_str", "(", "classname", ")", "classname", ".", "split", "(", "'.'", ")", ".", "map", "{", "|", "m", "|", "inflector", ".", "camelize", "(", "m", ")", "}", ".", "join", "(", "'::'", ")", "end"], "docstring": "Converts a namespaced symbol or string to a proper class name with modules", "docstring_tokens": ["Converts", "a", "namespaced", "symbol", "or", "string", "to", "a", "proper", "class", "name", "with", "modules"], "sha": "983c151df9d3e633dd772482149e831ab76e69fc", "url": "https://github.com/rx/presenters/blob/983c151df9d3e633dd772482149e831ab76e69fc/lib/voom/symbol/to_str.rb#L19-L22", "partition": "valid"} {"repo": "javanthropus/archive-zip", "path": "lib/archive/support/zlib.rb", "func_name": "Zlib.ZWriter.close", "original_string": "def close\n flush()\n @deflate_buffer << @deflater.finish unless @deflater.finished?\n begin\n until @deflate_buffer.empty? do\n @deflate_buffer.slice!(0, delegate.write(@deflate_buffer))\n end\n rescue Errno::EAGAIN, Errno::EINTR\n retry if write_ready?\n end\n @checksum = @deflater.adler\n @compressed_size = @deflater.total_out\n @uncompressed_size = @deflater.total_in\n @deflater.close\n super()\n nil\n end", "language": "ruby", "code": "def close\n flush()\n @deflate_buffer << @deflater.finish unless @deflater.finished?\n begin\n until @deflate_buffer.empty? do\n @deflate_buffer.slice!(0, delegate.write(@deflate_buffer))\n end\n rescue Errno::EAGAIN, Errno::EINTR\n retry if write_ready?\n end\n @checksum = @deflater.adler\n @compressed_size = @deflater.total_out\n @uncompressed_size = @deflater.total_in\n @deflater.close\n super()\n nil\n end", "code_tokens": ["def", "close", "flush", "(", ")", "@deflate_buffer", "<<", "@deflater", ".", "finish", "unless", "@deflater", ".", "finished?", "begin", "until", "@deflate_buffer", ".", "empty?", "do", "@deflate_buffer", ".", "slice!", "(", "0", ",", "delegate", ".", "write", "(", "@deflate_buffer", ")", ")", "end", "rescue", "Errno", "::", "EAGAIN", ",", "Errno", "::", "EINTR", "retry", "if", "write_ready?", "end", "@checksum", "=", "@deflater", ".", "adler", "@compressed_size", "=", "@deflater", ".", "total_out", "@uncompressed_size", "=", "@deflater", ".", "total_in", "@deflater", ".", "close", "super", "(", ")", "nil", "end"], "docstring": "Closes the writer by finishing the compressed data and flushing it to the\n delegate.\n\n Raises IOError if called more than once.", "docstring_tokens": ["Closes", "the", "writer", "by", "finishing", "the", "compressed", "data", "and", "flushing", "it", "to", "the", "delegate", "."], "sha": "8dfe4260da2fd74175d0cdf3a5277ed11e709f1a", "url": "https://github.com/javanthropus/archive-zip/blob/8dfe4260da2fd74175d0cdf3a5277ed11e709f1a/lib/archive/support/zlib.rb#L175-L191", "partition": "valid"} {"repo": "javanthropus/archive-zip", "path": "lib/archive/support/time.rb", "func_name": "Archive.DOSTime.to_time", "original_string": "def to_time\n second = ((0b11111 & @dos_time) ) * 2\n minute = ((0b111111 << 5 & @dos_time) >> 5)\n hour = ((0b11111 << 11 & @dos_time) >> 11)\n day = ((0b11111 << 16 & @dos_time) >> 16)\n month = ((0b1111 << 21 & @dos_time) >> 21)\n year = ((0b1111111 << 25 & @dos_time) >> 25) + 1980\n return Time.local(year, month, day, hour, minute, second)\n end", "language": "ruby", "code": "def to_time\n second = ((0b11111 & @dos_time) ) * 2\n minute = ((0b111111 << 5 & @dos_time) >> 5)\n hour = ((0b11111 << 11 & @dos_time) >> 11)\n day = ((0b11111 << 16 & @dos_time) >> 16)\n month = ((0b1111 << 21 & @dos_time) >> 21)\n year = ((0b1111111 << 25 & @dos_time) >> 25) + 1980\n return Time.local(year, month, day, hour, minute, second)\n end", "code_tokens": ["def", "to_time", "second", "=", "(", "(", "0b11111", "&", "@dos_time", ")", ")", "*", "2", "minute", "=", "(", "(", "0b111111", "<<", "5", "&", "@dos_time", ")", ">>", "5", ")", "hour", "=", "(", "(", "0b11111", "<<", "11", "&", "@dos_time", ")", ">>", "11", ")", "day", "=", "(", "(", "0b11111", "<<", "16", "&", "@dos_time", ")", ">>", "16", ")", "month", "=", "(", "(", "0b1111", "<<", "21", "&", "@dos_time", ")", ">>", "21", ")", "year", "=", "(", "(", "0b1111111", "<<", "25", "&", "@dos_time", ")", ">>", "25", ")", "+", "1980", "return", "Time", ".", "local", "(", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", ",", "second", ")", "end"], "docstring": "Returns a Time instance which is equivalent to the time represented by\n this object.", "docstring_tokens": ["Returns", "a", "Time", "instance", "which", "is", "equivalent", "to", "the", "time", "represented", "by", "this", "object", "."], "sha": "8dfe4260da2fd74175d0cdf3a5277ed11e709f1a", "url": "https://github.com/javanthropus/archive-zip/blob/8dfe4260da2fd74175d0cdf3a5277ed11e709f1a/lib/archive/support/time.rb#L82-L90", "partition": "valid"} {"repo": "javanthropus/archive-zip", "path": "lib/archive/zip.rb", "func_name": "Archive.Zip.each", "original_string": "def each(&b)\n raise IOError, 'non-readable archive' unless readable?\n raise IOError, 'closed archive' if closed?\n\n unless @parse_complete then\n parse(@archive)\n @parse_complete = true\n end\n @entries.each(&b)\n end", "language": "ruby", "code": "def each(&b)\n raise IOError, 'non-readable archive' unless readable?\n raise IOError, 'closed archive' if closed?\n\n unless @parse_complete then\n parse(@archive)\n @parse_complete = true\n end\n @entries.each(&b)\n end", "code_tokens": ["def", "each", "(", "&", "b", ")", "raise", "IOError", ",", "'non-readable archive'", "unless", "readable?", "raise", "IOError", ",", "'closed archive'", "if", "closed?", "unless", "@parse_complete", "then", "parse", "(", "@archive", ")", "@parse_complete", "=", "true", "end", "@entries", ".", "each", "(", "b", ")", "end"], "docstring": "Iterates through each entry of a readable ZIP archive in turn yielding\n each one to the given block.\n\n Raises Archive::Zip::IOError if called on a non-readable archive or after\n the archive is closed.", "docstring_tokens": ["Iterates", "through", "each", "entry", "of", "a", "readable", "ZIP", "archive", "in", "turn", "yielding", "each", "one", "to", "the", "given", "block", "."], "sha": "8dfe4260da2fd74175d0cdf3a5277ed11e709f1a", "url": "https://github.com/javanthropus/archive-zip/blob/8dfe4260da2fd74175d0cdf3a5277ed11e709f1a/lib/archive/zip.rb#L205-L214", "partition": "valid"} {"repo": "javanthropus/archive-zip", "path": "lib/archive/zip.rb", "func_name": "Archive.Zip.add_entry", "original_string": "def add_entry(entry)\n raise IOError, 'non-writable archive' unless writable?\n raise IOError, 'closed archive' if closed?\n unless entry.kind_of?(Entry) then\n raise ArgumentError, 'Archive::Zip::Entry instance required'\n end\n\n @entries << entry\n self\n end", "language": "ruby", "code": "def add_entry(entry)\n raise IOError, 'non-writable archive' unless writable?\n raise IOError, 'closed archive' if closed?\n unless entry.kind_of?(Entry) then\n raise ArgumentError, 'Archive::Zip::Entry instance required'\n end\n\n @entries << entry\n self\n end", "code_tokens": ["def", "add_entry", "(", "entry", ")", "raise", "IOError", ",", "'non-writable archive'", "unless", "writable?", "raise", "IOError", ",", "'closed archive'", "if", "closed?", "unless", "entry", ".", "kind_of?", "(", "Entry", ")", "then", "raise", "ArgumentError", ",", "'Archive::Zip::Entry instance required'", "end", "@entries", "<<", "entry", "self", "end"], "docstring": "Adds _entry_ into a writable ZIP archive.\n\n NOTE: No attempt is made to prevent adding multiple entries with\n the same archive path.\n\n Raises Archive::Zip::IOError if called on a non-writable archive or after\n the archive is closed.", "docstring_tokens": ["Adds", "_entry_", "into", "a", "writable", "ZIP", "archive", "."], "sha": "8dfe4260da2fd74175d0cdf3a5277ed11e709f1a", "url": "https://github.com/javanthropus/archive-zip/blob/8dfe4260da2fd74175d0cdf3a5277ed11e709f1a/lib/archive/zip.rb#L223-L232", "partition": "valid"} {"repo": "javanthropus/archive-zip", "path": "lib/archive/zip.rb", "func_name": "Archive.Zip.extract", "original_string": "def extract(destination, options = {})\n raise IOError, 'non-readable archive' unless readable?\n raise IOError, 'closed archive' if closed?\n\n # Ensure that unspecified options have default values.\n options[:directories] = true unless options.has_key?(:directories)\n options[:symlinks] = false unless options.has_key?(:symlinks)\n options[:overwrite] = :all unless options[:overwrite] == :older ||\n options[:overwrite] == :never\n options[:create] = true unless options.has_key?(:create)\n options[:flatten] = false unless options.has_key?(:flatten)\n\n # Flattening the archive structure implies that directory entries are\n # skipped.\n options[:directories] = false if options[:flatten]\n\n # First extract all non-directory entries.\n directories = []\n each do |entry|\n # Compute the target file path.\n file_path = entry.zip_path\n file_path = File.basename(file_path) if options[:flatten]\n file_path = File.join(destination, file_path)\n\n # Cache some information about the file path.\n file_exists = File.exist?(file_path)\n file_mtime = File.mtime(file_path) if file_exists\n\n begin\n # Skip this entry if so directed.\n if (! file_exists && ! options[:create]) ||\n (file_exists &&\n (options[:overwrite] == :never ||\n options[:overwrite] == :older && entry.mtime <= file_mtime)) ||\n (! options[:exclude].nil? && options[:exclude][entry]) then\n next\n end\n\n # Set the decryption key for the entry.\n if options[:password].kind_of?(String) then\n entry.password = options[:password]\n elsif ! options[:password].nil? then\n entry.password = options[:password][entry]\n end\n\n if entry.directory? then\n # Record the directories as they are encountered.\n directories << entry\n elsif entry.file? || (entry.symlink? && options[:symlinks]) then\n # Extract files and symlinks.\n entry.extract(\n options.merge(:file_path => file_path)\n )\n end\n rescue StandardError => error\n unless options[:on_error].nil? then\n case options[:on_error][entry, error]\n when :retry\n retry\n when :skip\n else\n raise\n end\n else\n raise\n end\n end\n end\n\n if options[:directories] then\n # Then extract the directory entries in depth first order so that time\n # stamps, ownerships, and permissions can be properly restored.\n directories.sort { |a, b| b.zip_path <=> a.zip_path }.each do |entry|\n begin\n entry.extract(\n options.merge(\n :file_path => File.join(destination, entry.zip_path)\n )\n )\n rescue StandardError => error\n unless options[:on_error].nil? then\n case options[:on_error][entry, error]\n when :retry\n retry\n when :skip\n else\n raise\n end\n else\n raise\n end\n end\n end\n end\n\n nil\n end", "language": "ruby", "code": "def extract(destination, options = {})\n raise IOError, 'non-readable archive' unless readable?\n raise IOError, 'closed archive' if closed?\n\n # Ensure that unspecified options have default values.\n options[:directories] = true unless options.has_key?(:directories)\n options[:symlinks] = false unless options.has_key?(:symlinks)\n options[:overwrite] = :all unless options[:overwrite] == :older ||\n options[:overwrite] == :never\n options[:create] = true unless options.has_key?(:create)\n options[:flatten] = false unless options.has_key?(:flatten)\n\n # Flattening the archive structure implies that directory entries are\n # skipped.\n options[:directories] = false if options[:flatten]\n\n # First extract all non-directory entries.\n directories = []\n each do |entry|\n # Compute the target file path.\n file_path = entry.zip_path\n file_path = File.basename(file_path) if options[:flatten]\n file_path = File.join(destination, file_path)\n\n # Cache some information about the file path.\n file_exists = File.exist?(file_path)\n file_mtime = File.mtime(file_path) if file_exists\n\n begin\n # Skip this entry if so directed.\n if (! file_exists && ! options[:create]) ||\n (file_exists &&\n (options[:overwrite] == :never ||\n options[:overwrite] == :older && entry.mtime <= file_mtime)) ||\n (! options[:exclude].nil? && options[:exclude][entry]) then\n next\n end\n\n # Set the decryption key for the entry.\n if options[:password].kind_of?(String) then\n entry.password = options[:password]\n elsif ! options[:password].nil? then\n entry.password = options[:password][entry]\n end\n\n if entry.directory? then\n # Record the directories as they are encountered.\n directories << entry\n elsif entry.file? || (entry.symlink? && options[:symlinks]) then\n # Extract files and symlinks.\n entry.extract(\n options.merge(:file_path => file_path)\n )\n end\n rescue StandardError => error\n unless options[:on_error].nil? then\n case options[:on_error][entry, error]\n when :retry\n retry\n when :skip\n else\n raise\n end\n else\n raise\n end\n end\n end\n\n if options[:directories] then\n # Then extract the directory entries in depth first order so that time\n # stamps, ownerships, and permissions can be properly restored.\n directories.sort { |a, b| b.zip_path <=> a.zip_path }.each do |entry|\n begin\n entry.extract(\n options.merge(\n :file_path => File.join(destination, entry.zip_path)\n )\n )\n rescue StandardError => error\n unless options[:on_error].nil? then\n case options[:on_error][entry, error]\n when :retry\n retry\n when :skip\n else\n raise\n end\n else\n raise\n end\n end\n end\n end\n\n nil\n end", "code_tokens": ["def", "extract", "(", "destination", ",", "options", "=", "{", "}", ")", "raise", "IOError", ",", "'non-readable archive'", "unless", "readable?", "raise", "IOError", ",", "'closed archive'", "if", "closed?", "# Ensure that unspecified options have default values.", "options", "[", ":directories", "]", "=", "true", "unless", "options", ".", "has_key?", "(", ":directories", ")", "options", "[", ":symlinks", "]", "=", "false", "unless", "options", ".", "has_key?", "(", ":symlinks", ")", "options", "[", ":overwrite", "]", "=", ":all", "unless", "options", "[", ":overwrite", "]", "==", ":older", "||", "options", "[", ":overwrite", "]", "==", ":never", "options", "[", ":create", "]", "=", "true", "unless", "options", ".", "has_key?", "(", ":create", ")", "options", "[", ":flatten", "]", "=", "false", "unless", "options", ".", "has_key?", "(", ":flatten", ")", "# Flattening the archive structure implies that directory entries are", "# skipped.", "options", "[", ":directories", "]", "=", "false", "if", "options", "[", ":flatten", "]", "# First extract all non-directory entries.", "directories", "=", "[", "]", "each", "do", "|", "entry", "|", "# Compute the target file path.", "file_path", "=", "entry", ".", "zip_path", "file_path", "=", "File", ".", "basename", "(", "file_path", ")", "if", "options", "[", ":flatten", "]", "file_path", "=", "File", ".", "join", "(", "destination", ",", "file_path", ")", "# Cache some information about the file path.", "file_exists", "=", "File", ".", "exist?", "(", "file_path", ")", "file_mtime", "=", "File", ".", "mtime", "(", "file_path", ")", "if", "file_exists", "begin", "# Skip this entry if so directed.", "if", "(", "!", "file_exists", "&&", "!", "options", "[", ":create", "]", ")", "||", "(", "file_exists", "&&", "(", "options", "[", ":overwrite", "]", "==", ":never", "||", "options", "[", ":overwrite", "]", "==", ":older", "&&", "entry", ".", "mtime", "<=", "file_mtime", ")", ")", "||", "(", "!", "options", "[", ":exclude", "]", ".", "nil?", "&&", "options", "[", ":exclude", "]", "[", "entry", "]", ")", "then", "next", "end", "# Set the decryption key for the entry.", "if", "options", "[", ":password", "]", ".", "kind_of?", "(", "String", ")", "then", "entry", ".", "password", "=", "options", "[", ":password", "]", "elsif", "!", "options", "[", ":password", "]", ".", "nil?", "then", "entry", ".", "password", "=", "options", "[", ":password", "]", "[", "entry", "]", "end", "if", "entry", ".", "directory?", "then", "# Record the directories as they are encountered.", "directories", "<<", "entry", "elsif", "entry", ".", "file?", "||", "(", "entry", ".", "symlink?", "&&", "options", "[", ":symlinks", "]", ")", "then", "# Extract files and symlinks.", "entry", ".", "extract", "(", "options", ".", "merge", "(", ":file_path", "=>", "file_path", ")", ")", "end", "rescue", "StandardError", "=>", "error", "unless", "options", "[", ":on_error", "]", ".", "nil?", "then", "case", "options", "[", ":on_error", "]", "[", "entry", ",", "error", "]", "when", ":retry", "retry", "when", ":skip", "else", "raise", "end", "else", "raise", "end", "end", "end", "if", "options", "[", ":directories", "]", "then", "# Then extract the directory entries in depth first order so that time", "# stamps, ownerships, and permissions can be properly restored.", "directories", ".", "sort", "{", "|", "a", ",", "b", "|", "b", ".", "zip_path", "<=>", "a", ".", "zip_path", "}", ".", "each", "do", "|", "entry", "|", "begin", "entry", ".", "extract", "(", "options", ".", "merge", "(", ":file_path", "=>", "File", ".", "join", "(", "destination", ",", "entry", ".", "zip_path", ")", ")", ")", "rescue", "StandardError", "=>", "error", "unless", "options", "[", ":on_error", "]", ".", "nil?", "then", "case", "options", "[", ":on_error", "]", "[", "entry", ",", "error", "]", "when", ":retry", "retry", "when", ":skip", "else", "raise", "end", "else", "raise", "end", "end", "end", "end", "nil", "end"], "docstring": "Extracts the contents of the archive to _destination_, where _destination_\n is a path to a directory which will contain the contents of the archive.\n The destination path will be created if it does not already exist.\n\n _options_ is a Hash optionally containing the following:\n :directories::\n When set to +true+ (the default), entries representing directories in\n the archive are extracted. This happens after all non-directory entries\n are extracted so that directory metadata can be properly updated.\n :symlinks::\n When set to +false+ (the default), entries representing symlinks in the\n archive are skipped. When set to +true+, such entries are extracted.\n Exceptions may be raised on plaforms/file systems which do not support\n symlinks.\n :overwrite::\n When set to :all (the default), files which already exist will\n be replaced. When set to :older, such files will only be\n replaced if they are older according to their last modified times than\n the zip entry which would replace them. When set to :none,\n such files will never be replaced. Any other value is the same as\n :all.\n :create::\n When set to +true+ (the default), files and directories which do not\n already exist will be extracted. When set to +false+, only files and\n directories which already exist will be extracted (depending on the\n setting of :overwrite).\n :flatten::\n When set to +false+ (the default), the directory paths containing\n extracted files will be created within +destination+ in order to contain\n the files. When set to +true+, files are extracted directly to\n +destination+ and directory entries are skipped.\n :exclude::\n Specifies a proc or lambda which takes a single argument containing a\n zip entry and returns +true+ if the entry should be skipped during\n extraction and +false+ if it should be extracted.\n :password::\n Specifies a proc, lambda, or a String. If a proc or lambda is used, it\n must take a single argument containing a zip entry and return a String\n to be used as a decryption key for the entry. If a String is used, it\n will be used as a decryption key for all encrypted entries.\n :on_error::\n Specifies a proc or lambda which is called when an exception is raised\n during the extraction of an entry. It takes two arguments, a zip entry\n and an exception object generated while attempting to extract the entry.\n If :retry is returned, extraction of the entry is attempted\n again. If :skip is returned, the entry is skipped. Otherwise,\n the exception is raised.\n Any other options which are supported by Archive::Zip::Entry#extract are\n also supported.\n\n Raises Archive::Zip::IOError if called on a non-readable archive or after\n the archive is closed.\n\n == Example\n\n An archive, archive.zip, contains:\n zip-test/\n zip-test/dir1/\n zip-test/dir1/file2.txt\n zip-test/dir2/\n zip-test/file1.txt\n\n A directory, extract4, contains:\n zip-test\n +- dir1\n +- file1.txt\n\n Extract the archive:\n Archive::Zip.open('archive.zip') do |z|\n z.extract('extract1')\n end\n\n Archive::Zip.open('archive.zip') do |z|\n z.extract('extract2', :flatten => true)\n end\n\n Archive::Zip.open('archive.zip') do |z|\n z.extract('extract3', :create => false)\n end\n\n Archive::Zip.open('archive.zip') do |z|\n z.extract('extract3', :create => true)\n end\n\n Archive::Zip.open('archive.zip') do |z|\n z.extract( 'extract5', :exclude => lambda { |e| e.file? })\n end\n\n The directories contain:\n extract1 -> zip-test\n +- dir1\n | +- file2.txt\n +- dir2\n +- file1.txt\n\n extract2 -> file2.txt\n file1.txt\n\n extract3 -> \n\n extract4 -> zip-test\n +- dir2\n +- file1.txt <- from archive contents\n\n extract5 -> zip-test\n +- dir1\n +- dir2", "docstring_tokens": ["Extracts", "the", "contents", "of", "the", "archive", "to", "_destination_", "where", "_destination_", "is", "a", "path", "to", "a", "directory", "which", "will", "contain", "the", "contents", "of", "the", "archive", ".", "The", "destination", "path", "will", "be", "created", "if", "it", "does", "not", "already", "exist", "."], "sha": "8dfe4260da2fd74175d0cdf3a5277ed11e709f1a", "url": "https://github.com/javanthropus/archive-zip/blob/8dfe4260da2fd74175d0cdf3a5277ed11e709f1a/lib/archive/zip.rb#L558-L654", "partition": "valid"} {"repo": "javanthropus/archive-zip", "path": "lib/archive/zip.rb", "func_name": "Archive.Zip.find_central_directory", "original_string": "def find_central_directory(io)\n # First find the offset to the end of central directory record.\n # It is expected that the variable length comment field will usually be\n # empty and as a result the initial value of eocd_offset is all that is\n # necessary.\n #\n # NOTE: A cleverly crafted comment could throw this thing off if the\n # comment itself looks like a valid end of central directory record.\n eocd_offset = -22\n loop do\n io.seek(eocd_offset, IO::SEEK_END)\n if IOExtensions.read_exactly(io, 4) == EOCD_SIGNATURE then\n io.seek(16, IO::SEEK_CUR)\n if IOExtensions.read_exactly(io, 2).unpack('v')[0] ==\n (eocd_offset + 22).abs then\n break\n end\n end\n eocd_offset -= 1\n end\n # At this point, eocd_offset should point to the location of the end of\n # central directory record relative to the end of the archive.\n # Now, jump into the location in the record which contains a pointer to\n # the start of the central directory record and return the value.\n io.seek(eocd_offset + 16, IO::SEEK_END)\n return IOExtensions.read_exactly(io, 4).unpack('V')[0]\n rescue Errno::EINVAL\n raise Zip::UnzipError, 'unable to locate end-of-central-directory record'\n end", "language": "ruby", "code": "def find_central_directory(io)\n # First find the offset to the end of central directory record.\n # It is expected that the variable length comment field will usually be\n # empty and as a result the initial value of eocd_offset is all that is\n # necessary.\n #\n # NOTE: A cleverly crafted comment could throw this thing off if the\n # comment itself looks like a valid end of central directory record.\n eocd_offset = -22\n loop do\n io.seek(eocd_offset, IO::SEEK_END)\n if IOExtensions.read_exactly(io, 4) == EOCD_SIGNATURE then\n io.seek(16, IO::SEEK_CUR)\n if IOExtensions.read_exactly(io, 2).unpack('v')[0] ==\n (eocd_offset + 22).abs then\n break\n end\n end\n eocd_offset -= 1\n end\n # At this point, eocd_offset should point to the location of the end of\n # central directory record relative to the end of the archive.\n # Now, jump into the location in the record which contains a pointer to\n # the start of the central directory record and return the value.\n io.seek(eocd_offset + 16, IO::SEEK_END)\n return IOExtensions.read_exactly(io, 4).unpack('V')[0]\n rescue Errno::EINVAL\n raise Zip::UnzipError, 'unable to locate end-of-central-directory record'\n end", "code_tokens": ["def", "find_central_directory", "(", "io", ")", "# First find the offset to the end of central directory record.", "# It is expected that the variable length comment field will usually be", "# empty and as a result the initial value of eocd_offset is all that is", "# necessary.", "#", "# NOTE: A cleverly crafted comment could throw this thing off if the", "# comment itself looks like a valid end of central directory record.", "eocd_offset", "=", "-", "22", "loop", "do", "io", ".", "seek", "(", "eocd_offset", ",", "IO", "::", "SEEK_END", ")", "if", "IOExtensions", ".", "read_exactly", "(", "io", ",", "4", ")", "==", "EOCD_SIGNATURE", "then", "io", ".", "seek", "(", "16", ",", "IO", "::", "SEEK_CUR", ")", "if", "IOExtensions", ".", "read_exactly", "(", "io", ",", "2", ")", ".", "unpack", "(", "'v'", ")", "[", "0", "]", "==", "(", "eocd_offset", "+", "22", ")", ".", "abs", "then", "break", "end", "end", "eocd_offset", "-=", "1", "end", "# At this point, eocd_offset should point to the location of the end of", "# central directory record relative to the end of the archive.", "# Now, jump into the location in the record which contains a pointer to", "# the start of the central directory record and return the value.", "io", ".", "seek", "(", "eocd_offset", "+", "16", ",", "IO", "::", "SEEK_END", ")", "return", "IOExtensions", ".", "read_exactly", "(", "io", ",", "4", ")", ".", "unpack", "(", "'V'", ")", "[", "0", "]", "rescue", "Errno", "::", "EINVAL", "raise", "Zip", "::", "UnzipError", ",", "'unable to locate end-of-central-directory record'", "end"], "docstring": "Returns the file offset of the first record in the central directory.\n _io_ must be a seekable, readable, IO-like object.\n\n Raises Archive::Zip::UnzipError if the end of central directory signature\n is not found where expected or at all.", "docstring_tokens": ["Returns", "the", "file", "offset", "of", "the", "first", "record", "in", "the", "central", "directory", ".", "_io_", "must", "be", "a", "seekable", "readable", "IO", "-", "like", "object", "."], "sha": "8dfe4260da2fd74175d0cdf3a5277ed11e709f1a", "url": "https://github.com/javanthropus/archive-zip/blob/8dfe4260da2fd74175d0cdf3a5277ed11e709f1a/lib/archive/zip.rb#L678-L706", "partition": "valid"} {"repo": "javanthropus/archive-zip", "path": "lib/archive/zip.rb", "func_name": "Archive.Zip.dump", "original_string": "def dump(io)\n bytes_written = 0\n @entries.each do |entry|\n bytes_written += entry.dump_local_file_record(io, bytes_written)\n end\n central_directory_offset = bytes_written\n @entries.each do |entry|\n bytes_written += entry.dump_central_file_record(io)\n end\n central_directory_length = bytes_written - central_directory_offset\n bytes_written += io.write(EOCD_SIGNATURE)\n bytes_written += io.write(\n [\n 0,\n 0,\n @entries.length,\n @entries.length,\n central_directory_length,\n central_directory_offset,\n comment.bytesize\n ].pack('vvvvVVv')\n )\n bytes_written += io.write(comment)\n\n bytes_written\n end", "language": "ruby", "code": "def dump(io)\n bytes_written = 0\n @entries.each do |entry|\n bytes_written += entry.dump_local_file_record(io, bytes_written)\n end\n central_directory_offset = bytes_written\n @entries.each do |entry|\n bytes_written += entry.dump_central_file_record(io)\n end\n central_directory_length = bytes_written - central_directory_offset\n bytes_written += io.write(EOCD_SIGNATURE)\n bytes_written += io.write(\n [\n 0,\n 0,\n @entries.length,\n @entries.length,\n central_directory_length,\n central_directory_offset,\n comment.bytesize\n ].pack('vvvvVVv')\n )\n bytes_written += io.write(comment)\n\n bytes_written\n end", "code_tokens": ["def", "dump", "(", "io", ")", "bytes_written", "=", "0", "@entries", ".", "each", "do", "|", "entry", "|", "bytes_written", "+=", "entry", ".", "dump_local_file_record", "(", "io", ",", "bytes_written", ")", "end", "central_directory_offset", "=", "bytes_written", "@entries", ".", "each", "do", "|", "entry", "|", "bytes_written", "+=", "entry", ".", "dump_central_file_record", "(", "io", ")", "end", "central_directory_length", "=", "bytes_written", "-", "central_directory_offset", "bytes_written", "+=", "io", ".", "write", "(", "EOCD_SIGNATURE", ")", "bytes_written", "+=", "io", ".", "write", "(", "[", "0", ",", "0", ",", "@entries", ".", "length", ",", "@entries", ".", "length", ",", "central_directory_length", ",", "central_directory_offset", ",", "comment", ".", "bytesize", "]", ".", "pack", "(", "'vvvvVVv'", ")", ")", "bytes_written", "+=", "io", ".", "write", "(", "comment", ")", "bytes_written", "end"], "docstring": "Writes all the entries of this archive to _io_. _io_ must be a writable,\n IO-like object providing a _write_ method. Returns the total number of\n bytes written.", "docstring_tokens": ["Writes", "all", "the", "entries", "of", "this", "archive", "to", "_io_", ".", "_io_", "must", "be", "a", "writable", "IO", "-", "like", "object", "providing", "a", "_write_", "method", ".", "Returns", "the", "total", "number", "of", "bytes", "written", "."], "sha": "8dfe4260da2fd74175d0cdf3a5277ed11e709f1a", "url": "https://github.com/javanthropus/archive-zip/blob/8dfe4260da2fd74175d0cdf3a5277ed11e709f1a/lib/archive/zip.rb#L711-L736", "partition": "valid"} {"repo": "code-and-effect/effective_datatables", "path": "app/models/effective/datatable.rb", "func_name": "Effective.Datatable.view=", "original_string": "def view=(view)\n @view = (view.respond_to?(:view_context) ? view.view_context : view)\n raise 'expected view to respond to params' unless @view.respond_to?(:params)\n\n load_cookie!\n assert_cookie!\n load_attributes!\n\n # We need early access to filter and scope, to define defaults from the model first\n # This means filters do knows about attributes but not about columns.\n initialize_filters if respond_to?(:initialize_filters)\n load_filters!\n load_state!\n\n # Bulk actions called first so it can add the bulk_actions_col first\n initialize_bulk_actions if respond_to?(:initialize_bulk_actions)\n\n # Now we initialize all the columns. columns knows about attributes and filters and scope\n initialize_datatable if respond_to?(:initialize_datatable)\n load_columns!\n\n # Execute any additional DSL methods\n initialize_charts if respond_to?(:initialize_charts)\n\n # Load the collection. This is the first time def collection is called on the Datatable itself\n initialize_collection if respond_to?(:initialize_collection)\n load_collection!\n\n # Figure out the class, and if it's activerecord, do all the resource discovery on it\n load_resource!\n apply_belongs_to_attributes!\n load_resource_search!\n\n # Check everything is okay\n validate_datatable!\n\n # Save for next time\n save_cookie!\n end", "language": "ruby", "code": "def view=(view)\n @view = (view.respond_to?(:view_context) ? view.view_context : view)\n raise 'expected view to respond to params' unless @view.respond_to?(:params)\n\n load_cookie!\n assert_cookie!\n load_attributes!\n\n # We need early access to filter and scope, to define defaults from the model first\n # This means filters do knows about attributes but not about columns.\n initialize_filters if respond_to?(:initialize_filters)\n load_filters!\n load_state!\n\n # Bulk actions called first so it can add the bulk_actions_col first\n initialize_bulk_actions if respond_to?(:initialize_bulk_actions)\n\n # Now we initialize all the columns. columns knows about attributes and filters and scope\n initialize_datatable if respond_to?(:initialize_datatable)\n load_columns!\n\n # Execute any additional DSL methods\n initialize_charts if respond_to?(:initialize_charts)\n\n # Load the collection. This is the first time def collection is called on the Datatable itself\n initialize_collection if respond_to?(:initialize_collection)\n load_collection!\n\n # Figure out the class, and if it's activerecord, do all the resource discovery on it\n load_resource!\n apply_belongs_to_attributes!\n load_resource_search!\n\n # Check everything is okay\n validate_datatable!\n\n # Save for next time\n save_cookie!\n end", "code_tokens": ["def", "view", "=", "(", "view", ")", "@view", "=", "(", "view", ".", "respond_to?", "(", ":view_context", ")", "?", "view", ".", "view_context", ":", "view", ")", "raise", "'expected view to respond to params'", "unless", "@view", ".", "respond_to?", "(", ":params", ")", "load_cookie!", "assert_cookie!", "load_attributes!", "# We need early access to filter and scope, to define defaults from the model first", "# This means filters do knows about attributes but not about columns.", "initialize_filters", "if", "respond_to?", "(", ":initialize_filters", ")", "load_filters!", "load_state!", "# Bulk actions called first so it can add the bulk_actions_col first", "initialize_bulk_actions", "if", "respond_to?", "(", ":initialize_bulk_actions", ")", "# Now we initialize all the columns. columns knows about attributes and filters and scope", "initialize_datatable", "if", "respond_to?", "(", ":initialize_datatable", ")", "load_columns!", "# Execute any additional DSL methods", "initialize_charts", "if", "respond_to?", "(", ":initialize_charts", ")", "# Load the collection. This is the first time def collection is called on the Datatable itself", "initialize_collection", "if", "respond_to?", "(", ":initialize_collection", ")", "load_collection!", "# Figure out the class, and if it's activerecord, do all the resource discovery on it", "load_resource!", "apply_belongs_to_attributes!", "load_resource_search!", "# Check everything is okay", "validate_datatable!", "# Save for next time", "save_cookie!", "end"], "docstring": "Once the view is assigned, we initialize everything", "docstring_tokens": ["Once", "the", "view", "is", "assigned", "we", "initialize", "everything"], "sha": "fed6c03fe583b8ccb937d15377dc5aac666a5151", "url": "https://github.com/code-and-effect/effective_datatables/blob/fed6c03fe583b8ccb937d15377dc5aac666a5151/app/models/effective/datatable.rb#L53-L91", "partition": "valid"} {"repo": "code-and-effect/effective_datatables", "path": "app/controllers/effective/datatables_controller.rb", "func_name": "Effective.DatatablesController.show", "original_string": "def show\n begin\n @datatable = EffectiveDatatables.find(params[:id])\n @datatable.view = view_context\n\n EffectiveDatatables.authorize!(self, :index, @datatable.collection_class)\n\n render json: @datatable.to_json\n rescue => e\n EffectiveDatatables.authorized?(self, :index, @datatable.try(:collection_class))\n render json: error_json(e)\n\n ExceptionNotifier.notify_exception(e) if defined?(ExceptionNotifier)\n raise e if Rails.env.development?\n end\n end", "language": "ruby", "code": "def show\n begin\n @datatable = EffectiveDatatables.find(params[:id])\n @datatable.view = view_context\n\n EffectiveDatatables.authorize!(self, :index, @datatable.collection_class)\n\n render json: @datatable.to_json\n rescue => e\n EffectiveDatatables.authorized?(self, :index, @datatable.try(:collection_class))\n render json: error_json(e)\n\n ExceptionNotifier.notify_exception(e) if defined?(ExceptionNotifier)\n raise e if Rails.env.development?\n end\n end", "code_tokens": ["def", "show", "begin", "@datatable", "=", "EffectiveDatatables", ".", "find", "(", "params", "[", ":id", "]", ")", "@datatable", ".", "view", "=", "view_context", "EffectiveDatatables", ".", "authorize!", "(", "self", ",", ":index", ",", "@datatable", ".", "collection_class", ")", "render", "json", ":", "@datatable", ".", "to_json", "rescue", "=>", "e", "EffectiveDatatables", ".", "authorized?", "(", "self", ",", ":index", ",", "@datatable", ".", "try", "(", ":collection_class", ")", ")", "render", "json", ":", "error_json", "(", "e", ")", "ExceptionNotifier", ".", "notify_exception", "(", "e", ")", "if", "defined?", "(", "ExceptionNotifier", ")", "raise", "e", "if", "Rails", ".", "env", ".", "development?", "end", "end"], "docstring": "This will respond to both a GET and a POST", "docstring_tokens": ["This", "will", "respond", "to", "both", "a", "GET", "and", "a", "POST"], "sha": "fed6c03fe583b8ccb937d15377dc5aac666a5151", "url": "https://github.com/code-and-effect/effective_datatables/blob/fed6c03fe583b8ccb937d15377dc5aac666a5151/app/controllers/effective/datatables_controller.rb#L6-L21", "partition": "valid"} {"repo": "boazsegev/plezi", "path": "lib/plezi/render/render.rb", "func_name": "Plezi.Renderer.register", "original_string": "def register(extention, handler = nil, &block)\n handler ||= block\n raise 'Handler or block required.' unless handler\n @render_library[extention.to_s] = handler\n handler\n end", "language": "ruby", "code": "def register(extention, handler = nil, &block)\n handler ||= block\n raise 'Handler or block required.' unless handler\n @render_library[extention.to_s] = handler\n handler\n end", "code_tokens": ["def", "register", "(", "extention", ",", "handler", "=", "nil", ",", "&", "block", ")", "handler", "||=", "block", "raise", "'Handler or block required.'", "unless", "handler", "@render_library", "[", "extention", ".", "to_s", "]", "=", "handler", "handler", "end"], "docstring": "Registers a rendering extention.\n\n Slim, Markdown, ERB and SASS are registered by default.\n\n extention:: a Symbol or String representing the extention of the file to be rendered. i.e. 'slim', 'md', 'erb', etc'\n handler :: a Proc or other object that answers to call(filename, context, &block) and returnes the rendered string.\n The block accepted by the handler is for chaining rendered actions (allowing for `yield` within templates)\n and the context is the object within which the rendering should be performed (if `binding` handling is\n supported by the engine). `filename` might not point to an existing or valid file.\n\n If a block is passed to the `register_hook` method with no handler defined, it will act as the handler.", "docstring_tokens": ["Registers", "a", "rendering", "extention", "."], "sha": "8f6b1a4e7874746267751cfaa71db7ad3851993a", "url": "https://github.com/boazsegev/plezi/blob/8f6b1a4e7874746267751cfaa71db7ad3851993a/lib/plezi/render/render.rb#L20-L25", "partition": "valid"} {"repo": "boazsegev/plezi", "path": "lib/plezi/controller/controller.rb", "func_name": "Plezi.Controller.requested_method", "original_string": "def requested_method\n params['_method'.freeze] = (params['_method'.freeze] || request.request_method.downcase).to_sym\n self.class._pl_params2method(params, request.env)\n end", "language": "ruby", "code": "def requested_method\n params['_method'.freeze] = (params['_method'.freeze] || request.request_method.downcase).to_sym\n self.class._pl_params2method(params, request.env)\n end", "code_tokens": ["def", "requested_method", "params", "[", "'_method'", ".", "freeze", "]", "=", "(", "params", "[", "'_method'", ".", "freeze", "]", "||", "request", ".", "request_method", ".", "downcase", ")", ".", "to_sym", "self", ".", "class", ".", "_pl_params2method", "(", "params", ",", "request", ".", "env", ")", "end"], "docstring": "Returns the method that was called by the HTTP request.\n\n It's possible to override this method to change the default Controller behavior.\n\n For Websocket connections this method is most likely to return :preform_upgrade", "docstring_tokens": ["Returns", "the", "method", "that", "was", "called", "by", "the", "HTTP", "request", "."], "sha": "8f6b1a4e7874746267751cfaa71db7ad3851993a", "url": "https://github.com/boazsegev/plezi/blob/8f6b1a4e7874746267751cfaa71db7ad3851993a/lib/plezi/controller/controller.rb#L64-L67", "partition": "valid"} {"repo": "boazsegev/plezi", "path": "lib/plezi/controller/controller.rb", "func_name": "Plezi.Controller.send_data", "original_string": "def send_data(data, options = {})\n response.write data if data\n filename = options[:filename]\n # set headers\n content_disposition = options[:inline] ? 'inline'.dup : 'attachment'.dup\n content_disposition << \"; filename=#{::File.basename(options[:filename])}\" if filename\n cont_type = (options[:mime] ||= filename && Rack::Mime.mime_type(::File.extname(filename)))\n response['content-type'.freeze] = cont_type if cont_type\n response['content-disposition'.freeze] = content_disposition\n true\n end", "language": "ruby", "code": "def send_data(data, options = {})\n response.write data if data\n filename = options[:filename]\n # set headers\n content_disposition = options[:inline] ? 'inline'.dup : 'attachment'.dup\n content_disposition << \"; filename=#{::File.basename(options[:filename])}\" if filename\n cont_type = (options[:mime] ||= filename && Rack::Mime.mime_type(::File.extname(filename)))\n response['content-type'.freeze] = cont_type if cont_type\n response['content-disposition'.freeze] = content_disposition\n true\n end", "code_tokens": ["def", "send_data", "(", "data", ",", "options", "=", "{", "}", ")", "response", ".", "write", "data", "if", "data", "filename", "=", "options", "[", ":filename", "]", "# set headers", "content_disposition", "=", "options", "[", ":inline", "]", "?", "'inline'", ".", "dup", ":", "'attachment'", ".", "dup", "content_disposition", "<<", "\"; filename=#{::File.basename(options[:filename])}\"", "if", "filename", "cont_type", "=", "(", "options", "[", ":mime", "]", "||=", "filename", "&&", "Rack", "::", "Mime", ".", "mime_type", "(", "::", "File", ".", "extname", "(", "filename", ")", ")", ")", "response", "[", "'content-type'", ".", "freeze", "]", "=", "cont_type", "if", "cont_type", "response", "[", "'content-disposition'", ".", "freeze", "]", "=", "content_disposition", "true", "end"], "docstring": "Sends a block of data, setting a file name, mime type and content disposition headers when possible. This should also be a good choice when sending large amounts of data.\n\n By default, `send_data` sends the data as an attachment, unless `inline: true` was set.\n\n If a mime type is provided, it will be used to set the Content-Type header. i.e. `mime: \"text/plain\"`\n\n If a file name was provided, Rack will be used to find the correct mime type (unless provided). i.e. `filename: \"sample.pdf\"` will set the mime type to `application/pdf`\n\n Available options: `:inline` (`true` / `false`), `:filename`, `:mime`.", "docstring_tokens": ["Sends", "a", "block", "of", "data", "setting", "a", "file", "name", "mime", "type", "and", "content", "disposition", "headers", "when", "possible", ".", "This", "should", "also", "be", "a", "good", "choice", "when", "sending", "large", "amounts", "of", "data", "."], "sha": "8f6b1a4e7874746267751cfaa71db7ad3851993a", "url": "https://github.com/boazsegev/plezi/blob/8f6b1a4e7874746267751cfaa71db7ad3851993a/lib/plezi/controller/controller.rb#L97-L107", "partition": "valid"} {"repo": "ManageIQ/inventory_refresh", "path": "lib/inventory_refresh/graph.rb", "func_name": "InventoryRefresh.Graph.build_feedback_edge_set", "original_string": "def build_feedback_edge_set(edges, fixed_edges)\n edges = edges.dup\n acyclic_edges = fixed_edges.dup\n feedback_edge_set = []\n\n while edges.present?\n edge = edges.shift\n if detect_cycle(edge, acyclic_edges)\n feedback_edge_set << edge\n else\n acyclic_edges << edge\n end\n end\n\n feedback_edge_set\n end", "language": "ruby", "code": "def build_feedback_edge_set(edges, fixed_edges)\n edges = edges.dup\n acyclic_edges = fixed_edges.dup\n feedback_edge_set = []\n\n while edges.present?\n edge = edges.shift\n if detect_cycle(edge, acyclic_edges)\n feedback_edge_set << edge\n else\n acyclic_edges << edge\n end\n end\n\n feedback_edge_set\n end", "code_tokens": ["def", "build_feedback_edge_set", "(", "edges", ",", "fixed_edges", ")", "edges", "=", "edges", ".", "dup", "acyclic_edges", "=", "fixed_edges", ".", "dup", "feedback_edge_set", "=", "[", "]", "while", "edges", ".", "present?", "edge", "=", "edges", ".", "shift", "if", "detect_cycle", "(", "edge", ",", "acyclic_edges", ")", "feedback_edge_set", "<<", "edge", "else", "acyclic_edges", "<<", "edge", "end", "end", "feedback_edge_set", "end"], "docstring": "Builds a feedback edge set, which is a set of edges creating a cycle\n\n @param edges [Array] List of edges, where edge is defined as [InventoryCollection, InventoryCollection],\n these are all edges except fixed_edges\n @param fixed_edges [Array] List of edges, where edge is defined as [InventoryCollection, InventoryCollection],\n fixed edges are those that can't be moved", "docstring_tokens": ["Builds", "a", "feedback", "edge", "set", "which", "is", "a", "set", "of", "edges", "creating", "a", "cycle"], "sha": "8367841fd967a8294385d57f4b20891ff9b0958f", "url": "https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/graph.rb#L73-L88", "partition": "valid"} {"repo": "ManageIQ/inventory_refresh", "path": "lib/inventory_refresh/graph.rb", "func_name": "InventoryRefresh.Graph.detect_cycle", "original_string": "def detect_cycle(edge, acyclic_edges, escalation = nil)\n # Test if adding edge creates a cycle, ew will traverse the graph from edge Node, through all it's\n # dependencies\n starting_node = edge.second\n edges = [edge] + acyclic_edges\n traverse_dependecies([], starting_node, starting_node, edges, node_edges(edges, starting_node), escalation)\n end", "language": "ruby", "code": "def detect_cycle(edge, acyclic_edges, escalation = nil)\n # Test if adding edge creates a cycle, ew will traverse the graph from edge Node, through all it's\n # dependencies\n starting_node = edge.second\n edges = [edge] + acyclic_edges\n traverse_dependecies([], starting_node, starting_node, edges, node_edges(edges, starting_node), escalation)\n end", "code_tokens": ["def", "detect_cycle", "(", "edge", ",", "acyclic_edges", ",", "escalation", "=", "nil", ")", "# Test if adding edge creates a cycle, ew will traverse the graph from edge Node, through all it's", "# dependencies", "starting_node", "=", "edge", ".", "second", "edges", "=", "[", "edge", "]", "+", "acyclic_edges", "traverse_dependecies", "(", "[", "]", ",", "starting_node", ",", "starting_node", ",", "edges", ",", "node_edges", "(", "edges", ",", "starting_node", ")", ",", "escalation", ")", "end"], "docstring": "Detects a cycle. Based on escalation returns true or raises exception if there is a cycle\n\n @param edge [Array(InventoryRefresh::InventoryCollection, InventoryRefresh::InventoryCollection)] Edge we are\n inspecting for cycle\n @param acyclic_edges [Array] Starting with fixed edges that can't have cycle, these are edges without cycle\n @param escalation [Symbol] If :exception, this method throws exception when it finds a cycle\n @return [Boolean, Exception] Based on escalation returns true or raises exception if there is a cycle", "docstring_tokens": ["Detects", "a", "cycle", ".", "Based", "on", "escalation", "returns", "true", "or", "raises", "exception", "if", "there", "is", "a", "cycle"], "sha": "8367841fd967a8294385d57f4b20891ff9b0958f", "url": "https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/graph.rb#L97-L103", "partition": "valid"} {"repo": "ManageIQ/inventory_refresh", "path": "lib/inventory_refresh/graph.rb", "func_name": "InventoryRefresh.Graph.traverse_dependecies", "original_string": "def traverse_dependecies(traversed_nodes, starting_node, current_node, edges, dependencies, escalation)\n dependencies.each do |node_edge|\n node = node_edge.first\n traversed_nodes << node\n if traversed_nodes.include?(starting_node)\n if escalation == :exception\n raise \"Cycle from #{current_node} to #{node}, starting from #{starting_node} passing #{traversed_nodes}\"\n else\n return true\n end\n end\n return true if traverse_dependecies(traversed_nodes, starting_node, node, edges, node_edges(edges, node), escalation)\n end\n\n false\n end", "language": "ruby", "code": "def traverse_dependecies(traversed_nodes, starting_node, current_node, edges, dependencies, escalation)\n dependencies.each do |node_edge|\n node = node_edge.first\n traversed_nodes << node\n if traversed_nodes.include?(starting_node)\n if escalation == :exception\n raise \"Cycle from #{current_node} to #{node}, starting from #{starting_node} passing #{traversed_nodes}\"\n else\n return true\n end\n end\n return true if traverse_dependecies(traversed_nodes, starting_node, node, edges, node_edges(edges, node), escalation)\n end\n\n false\n end", "code_tokens": ["def", "traverse_dependecies", "(", "traversed_nodes", ",", "starting_node", ",", "current_node", ",", "edges", ",", "dependencies", ",", "escalation", ")", "dependencies", ".", "each", "do", "|", "node_edge", "|", "node", "=", "node_edge", ".", "first", "traversed_nodes", "<<", "node", "if", "traversed_nodes", ".", "include?", "(", "starting_node", ")", "if", "escalation", "==", ":exception", "raise", "\"Cycle from #{current_node} to #{node}, starting from #{starting_node} passing #{traversed_nodes}\"", "else", "return", "true", "end", "end", "return", "true", "if", "traverse_dependecies", "(", "traversed_nodes", ",", "starting_node", ",", "node", ",", "edges", ",", "node_edges", "(", "edges", ",", "node", ")", ",", "escalation", ")", "end", "false", "end"], "docstring": "Recursive method for traversing dependencies and finding a cycle\n\n @param traversed_nodes [Array Already traversed nodes\n @param starting_node [InventoryRefresh::InventoryCollection] Node we've started the traversal on\n @param current_node [InventoryRefresh::InventoryCollection] Node we are currently on\n @param edges [Array] All graph edges\n @param dependencies [Array Dependencies of the current node\n @param escalation [Symbol] If :exception, this method throws exception when it finds a cycle\n @return [Boolean, Exception] Based on escalation returns true or raises exception if there is a cycle", "docstring_tokens": ["Recursive", "method", "for", "traversing", "dependencies", "and", "finding", "a", "cycle"], "sha": "8367841fd967a8294385d57f4b20891ff9b0958f", "url": "https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/graph.rb#L114-L129", "partition": "valid"} {"repo": "ManageIQ/inventory_refresh", "path": "lib/inventory_refresh/application_record_iterator.rb", "func_name": "InventoryRefresh.ApplicationRecordIterator.find_in_batches", "original_string": "def find_in_batches(batch_size: 1000, attributes_index: {})\n attributes_index.each_slice(batch_size) do |batch|\n yield(inventory_collection.db_collection_for_comparison_for(batch))\n end\n end", "language": "ruby", "code": "def find_in_batches(batch_size: 1000, attributes_index: {})\n attributes_index.each_slice(batch_size) do |batch|\n yield(inventory_collection.db_collection_for_comparison_for(batch))\n end\n end", "code_tokens": ["def", "find_in_batches", "(", "batch_size", ":", "1000", ",", "attributes_index", ":", "{", "}", ")", "attributes_index", ".", "each_slice", "(", "batch_size", ")", "do", "|", "batch", "|", "yield", "(", "inventory_collection", ".", "db_collection_for_comparison_for", "(", "batch", ")", ")", "end", "end"], "docstring": "An iterator that can fetch batches of the AR objects based on a set of attribute_indexes\n\n @param inventory_collection [InventoryRefresh::InventoryCollection] Inventory collection owning the iterator\n Iterator that mimics find_in_batches of ActiveRecord::Relation. This iterator serves for making more optimized query\n since e.g. having 1500 ids if objects we want to return. Doing relation.where(:id => 1500ids).find_each would\n always search for all 1500 ids, then return on limit 1000.\n\n With this iterator we build queries using only batch of ids, so find_each will cause relation.where(:id => 1000ids)\n and relation.where(:id => 500ids)\n\n @param batch_size [Integer] A batch size we want to fetch from DB\n @param attributes_index [Hash{String => Hash}] Indexed hash with data we will be saving\n @yield Code processing the batches", "docstring_tokens": ["An", "iterator", "that", "can", "fetch", "batches", "of", "the", "AR", "objects", "based", "on", "a", "set", "of", "attribute_indexes"], "sha": "8367841fd967a8294385d57f4b20891ff9b0958f", "url": "https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/application_record_iterator.rb#L22-L26", "partition": "valid"} {"repo": "ManageIQ/inventory_refresh", "path": "lib/inventory_refresh/inventory_object.rb", "func_name": "InventoryRefresh.InventoryObject.assign_attributes", "original_string": "def assign_attributes(attributes)\n attributes.each do |k, v|\n # We don't want timestamps or resource versions to be overwritten here, since those are driving the conditions\n next if %i(resource_timestamps resource_timestamps_max resource_timestamp).include?(k)\n next if %i(resource_counters resource_counters_max resource_counter).include?(k)\n\n if data[:resource_timestamp] && attributes[:resource_timestamp]\n assign_only_newest(:resource_timestamp, :resource_timestamps, attributes, data, k, v)\n elsif data[:resource_counter] && attributes[:resource_counter]\n assign_only_newest(:resource_counter, :resource_counters, attributes, data, k, v)\n else\n public_send(\"#{k}=\", v)\n end\n end\n\n if attributes[:resource_timestamp]\n assign_full_row_version_attr(:resource_timestamp, attributes, data)\n elsif attributes[:resource_counter]\n assign_full_row_version_attr(:resource_counter, attributes, data)\n end\n\n self\n end", "language": "ruby", "code": "def assign_attributes(attributes)\n attributes.each do |k, v|\n # We don't want timestamps or resource versions to be overwritten here, since those are driving the conditions\n next if %i(resource_timestamps resource_timestamps_max resource_timestamp).include?(k)\n next if %i(resource_counters resource_counters_max resource_counter).include?(k)\n\n if data[:resource_timestamp] && attributes[:resource_timestamp]\n assign_only_newest(:resource_timestamp, :resource_timestamps, attributes, data, k, v)\n elsif data[:resource_counter] && attributes[:resource_counter]\n assign_only_newest(:resource_counter, :resource_counters, attributes, data, k, v)\n else\n public_send(\"#{k}=\", v)\n end\n end\n\n if attributes[:resource_timestamp]\n assign_full_row_version_attr(:resource_timestamp, attributes, data)\n elsif attributes[:resource_counter]\n assign_full_row_version_attr(:resource_counter, attributes, data)\n end\n\n self\n end", "code_tokens": ["def", "assign_attributes", "(", "attributes", ")", "attributes", ".", "each", "do", "|", "k", ",", "v", "|", "# We don't want timestamps or resource versions to be overwritten here, since those are driving the conditions", "next", "if", "%i(", "resource_timestamps", "resource_timestamps_max", "resource_timestamp", ")", ".", "include?", "(", "k", ")", "next", "if", "%i(", "resource_counters", "resource_counters_max", "resource_counter", ")", ".", "include?", "(", "k", ")", "if", "data", "[", ":resource_timestamp", "]", "&&", "attributes", "[", ":resource_timestamp", "]", "assign_only_newest", "(", ":resource_timestamp", ",", ":resource_timestamps", ",", "attributes", ",", "data", ",", "k", ",", "v", ")", "elsif", "data", "[", ":resource_counter", "]", "&&", "attributes", "[", ":resource_counter", "]", "assign_only_newest", "(", ":resource_counter", ",", ":resource_counters", ",", "attributes", ",", "data", ",", "k", ",", "v", ")", "else", "public_send", "(", "\"#{k}=\"", ",", "v", ")", "end", "end", "if", "attributes", "[", ":resource_timestamp", "]", "assign_full_row_version_attr", "(", ":resource_timestamp", ",", "attributes", ",", "data", ")", "elsif", "attributes", "[", ":resource_counter", "]", "assign_full_row_version_attr", "(", ":resource_counter", ",", "attributes", ",", "data", ")", "end", "self", "end"], "docstring": "Given hash of attributes, we assign them to InventoryObject object using its public writers\n\n @param attributes [Hash] attributes we want to assign\n @return [InventoryRefresh::InventoryObject] self", "docstring_tokens": ["Given", "hash", "of", "attributes", "we", "assign", "them", "to", "InventoryObject", "object", "using", "its", "public", "writers"], "sha": "8367841fd967a8294385d57f4b20891ff9b0958f", "url": "https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_object.rb#L96-L118", "partition": "valid"} {"repo": "ManageIQ/inventory_refresh", "path": "lib/inventory_refresh/inventory_object.rb", "func_name": "InventoryRefresh.InventoryObject.assign_only_newest", "original_string": "def assign_only_newest(full_row_version_attr, partial_row_version_attr, attributes, data, k, v)\n # If timestamps are in play, we will set only attributes that are newer\n specific_attr_timestamp = attributes[partial_row_version_attr].try(:[], k)\n specific_data_timestamp = data[partial_row_version_attr].try(:[], k)\n\n assign = if !specific_attr_timestamp\n # Data have no timestamp, we will ignore the check\n true\n elsif specific_attr_timestamp && !specific_data_timestamp\n # Data specific timestamp is nil and we have new specific timestamp\n if data.key?(k)\n if attributes[full_row_version_attr] >= data[full_row_version_attr]\n # We can save if the full timestamp is bigger, if the data already contains the attribute\n true\n end\n else\n # Data do not contain the attribute, so we are saving the newest\n true\n end\n true\n elsif specific_attr_timestamp > specific_data_timestamp\n # both partial timestamps are there, newer must be bigger\n true\n end\n\n if assign\n public_send(\"#{k}=\", v) # Attribute is newer than current one, lets use it\n (data[partial_row_version_attr] ||= {})[k] = specific_attr_timestamp if specific_attr_timestamp # and set the latest timestamp\n end\n end", "language": "ruby", "code": "def assign_only_newest(full_row_version_attr, partial_row_version_attr, attributes, data, k, v)\n # If timestamps are in play, we will set only attributes that are newer\n specific_attr_timestamp = attributes[partial_row_version_attr].try(:[], k)\n specific_data_timestamp = data[partial_row_version_attr].try(:[], k)\n\n assign = if !specific_attr_timestamp\n # Data have no timestamp, we will ignore the check\n true\n elsif specific_attr_timestamp && !specific_data_timestamp\n # Data specific timestamp is nil and we have new specific timestamp\n if data.key?(k)\n if attributes[full_row_version_attr] >= data[full_row_version_attr]\n # We can save if the full timestamp is bigger, if the data already contains the attribute\n true\n end\n else\n # Data do not contain the attribute, so we are saving the newest\n true\n end\n true\n elsif specific_attr_timestamp > specific_data_timestamp\n # both partial timestamps are there, newer must be bigger\n true\n end\n\n if assign\n public_send(\"#{k}=\", v) # Attribute is newer than current one, lets use it\n (data[partial_row_version_attr] ||= {})[k] = specific_attr_timestamp if specific_attr_timestamp # and set the latest timestamp\n end\n end", "code_tokens": ["def", "assign_only_newest", "(", "full_row_version_attr", ",", "partial_row_version_attr", ",", "attributes", ",", "data", ",", "k", ",", "v", ")", "# If timestamps are in play, we will set only attributes that are newer", "specific_attr_timestamp", "=", "attributes", "[", "partial_row_version_attr", "]", ".", "try", "(", ":[]", ",", "k", ")", "specific_data_timestamp", "=", "data", "[", "partial_row_version_attr", "]", ".", "try", "(", ":[]", ",", "k", ")", "assign", "=", "if", "!", "specific_attr_timestamp", "# Data have no timestamp, we will ignore the check", "true", "elsif", "specific_attr_timestamp", "&&", "!", "specific_data_timestamp", "# Data specific timestamp is nil and we have new specific timestamp", "if", "data", ".", "key?", "(", "k", ")", "if", "attributes", "[", "full_row_version_attr", "]", ">=", "data", "[", "full_row_version_attr", "]", "# We can save if the full timestamp is bigger, if the data already contains the attribute", "true", "end", "else", "# Data do not contain the attribute, so we are saving the newest", "true", "end", "true", "elsif", "specific_attr_timestamp", ">", "specific_data_timestamp", "# both partial timestamps are there, newer must be bigger", "true", "end", "if", "assign", "public_send", "(", "\"#{k}=\"", ",", "v", ")", "# Attribute is newer than current one, lets use it", "(", "data", "[", "partial_row_version_attr", "]", "||=", "{", "}", ")", "[", "k", "]", "=", "specific_attr_timestamp", "if", "specific_attr_timestamp", "# and set the latest timestamp", "end", "end"], "docstring": "Assigns value based on the version attributes. If versions are specified, it asigns attribute only if it's\n newer than existing attribute.\n\n @param full_row_version_attr [Symbol] Attr name for full rows, allowed values are\n [:resource_timestamp, :resource_counter]\n @param partial_row_version_attr [Symbol] Attr name for partial rows, allowed values are\n [:resource_timestamps, :resource_counters]\n @param attributes [Hash] New attributes we are assigning\n @param data [Hash] Existing attributes of the InventoryObject\n @param k [Symbol] Name of the attribute we are assigning\n @param v [Object] Value of the attribute we are assigning", "docstring_tokens": ["Assigns", "value", "based", "on", "the", "version", "attributes", ".", "If", "versions", "are", "specified", "it", "asigns", "attribute", "only", "if", "it", "s", "newer", "than", "existing", "attribute", "."], "sha": "8367841fd967a8294385d57f4b20891ff9b0958f", "url": "https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_object.rb#L200-L229", "partition": "valid"} {"repo": "ManageIQ/inventory_refresh", "path": "lib/inventory_refresh/inventory_object.rb", "func_name": "InventoryRefresh.InventoryObject.assign_full_row_version_attr", "original_string": "def assign_full_row_version_attr(full_row_version_attr, attributes, data)\n if attributes[full_row_version_attr] && data[full_row_version_attr]\n # If both timestamps are present, store the bigger one\n data[full_row_version_attr] = attributes[full_row_version_attr] if attributes[full_row_version_attr] > data[full_row_version_attr]\n elsif attributes[full_row_version_attr] && !data[full_row_version_attr]\n # We are assigning timestamp that was missing\n data[full_row_version_attr] = attributes[full_row_version_attr]\n end\n end", "language": "ruby", "code": "def assign_full_row_version_attr(full_row_version_attr, attributes, data)\n if attributes[full_row_version_attr] && data[full_row_version_attr]\n # If both timestamps are present, store the bigger one\n data[full_row_version_attr] = attributes[full_row_version_attr] if attributes[full_row_version_attr] > data[full_row_version_attr]\n elsif attributes[full_row_version_attr] && !data[full_row_version_attr]\n # We are assigning timestamp that was missing\n data[full_row_version_attr] = attributes[full_row_version_attr]\n end\n end", "code_tokens": ["def", "assign_full_row_version_attr", "(", "full_row_version_attr", ",", "attributes", ",", "data", ")", "if", "attributes", "[", "full_row_version_attr", "]", "&&", "data", "[", "full_row_version_attr", "]", "# If both timestamps are present, store the bigger one", "data", "[", "full_row_version_attr", "]", "=", "attributes", "[", "full_row_version_attr", "]", "if", "attributes", "[", "full_row_version_attr", "]", ">", "data", "[", "full_row_version_attr", "]", "elsif", "attributes", "[", "full_row_version_attr", "]", "&&", "!", "data", "[", "full_row_version_attr", "]", "# We are assigning timestamp that was missing", "data", "[", "full_row_version_attr", "]", "=", "attributes", "[", "full_row_version_attr", "]", "end", "end"], "docstring": "Assigns attribute representing version of the whole row\n\n @param full_row_version_attr [Symbol] Attr name for full rows, allowed values are\n [:resource_timestamp, :resource_counter]\n @param attributes [Hash] New attributes we are assigning\n @param data [Hash] Existing attributes of the InventoryObject", "docstring_tokens": ["Assigns", "attribute", "representing", "version", "of", "the", "whole", "row"], "sha": "8367841fd967a8294385d57f4b20891ff9b0958f", "url": "https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_object.rb#L237-L245", "partition": "valid"} {"repo": "ManageIQ/inventory_refresh", "path": "lib/inventory_refresh/inventory_collection.rb", "func_name": "InventoryRefresh.InventoryCollection.uniq_keys_candidates", "original_string": "def uniq_keys_candidates(keys)\n # Find all uniq indexes that that are covering our keys\n uniq_key_candidates = unique_indexes.each_with_object([]) { |i, obj| obj << i if (keys - i.columns.map(&:to_sym)).empty? }\n\n if unique_indexes.blank? || uniq_key_candidates.blank?\n raise \"#{self} and its table #{model_class.table_name} must have a unique index defined \"\\\n \"covering columns #{keys} to be able to use saver_strategy :concurrent_safe_batch.\"\n end\n\n uniq_key_candidates\n end", "language": "ruby", "code": "def uniq_keys_candidates(keys)\n # Find all uniq indexes that that are covering our keys\n uniq_key_candidates = unique_indexes.each_with_object([]) { |i, obj| obj << i if (keys - i.columns.map(&:to_sym)).empty? }\n\n if unique_indexes.blank? || uniq_key_candidates.blank?\n raise \"#{self} and its table #{model_class.table_name} must have a unique index defined \"\\\n \"covering columns #{keys} to be able to use saver_strategy :concurrent_safe_batch.\"\n end\n\n uniq_key_candidates\n end", "code_tokens": ["def", "uniq_keys_candidates", "(", "keys", ")", "# Find all uniq indexes that that are covering our keys", "uniq_key_candidates", "=", "unique_indexes", ".", "each_with_object", "(", "[", "]", ")", "{", "|", "i", ",", "obj", "|", "obj", "<<", "i", "if", "(", "keys", "-", "i", ".", "columns", ".", "map", "(", ":to_sym", ")", ")", ".", "empty?", "}", "if", "unique_indexes", ".", "blank?", "||", "uniq_key_candidates", ".", "blank?", "raise", "\"#{self} and its table #{model_class.table_name} must have a unique index defined \"", "\"covering columns #{keys} to be able to use saver_strategy :concurrent_safe_batch.\"", "end", "uniq_key_candidates", "end"], "docstring": "Find candidates for unique key. Candidate must cover all columns we are passing as keys.\n\n @param keys [Array]\n @raise [Exception] if the unique index for the columns was not found\n @return [Array] Array of unique indexes fitting the keys", "docstring_tokens": ["Find", "candidates", "for", "unique", "key", ".", "Candidate", "must", "cover", "all", "columns", "we", "are", "passing", "as", "keys", "."], "sha": "8367841fd967a8294385d57f4b20891ff9b0958f", "url": "https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_collection.rb#L236-L246", "partition": "valid"} {"repo": "ManageIQ/inventory_refresh", "path": "lib/inventory_refresh/inventory_collection.rb", "func_name": "InventoryRefresh.InventoryCollection.filtered_dependency_attributes", "original_string": "def filtered_dependency_attributes\n filtered_attributes = dependency_attributes\n\n if attributes_blacklist.present?\n filtered_attributes = filtered_attributes.reject { |key, _value| attributes_blacklist.include?(key) }\n end\n\n if attributes_whitelist.present?\n filtered_attributes = filtered_attributes.select { |key, _value| attributes_whitelist.include?(key) }\n end\n\n filtered_attributes\n end", "language": "ruby", "code": "def filtered_dependency_attributes\n filtered_attributes = dependency_attributes\n\n if attributes_blacklist.present?\n filtered_attributes = filtered_attributes.reject { |key, _value| attributes_blacklist.include?(key) }\n end\n\n if attributes_whitelist.present?\n filtered_attributes = filtered_attributes.select { |key, _value| attributes_whitelist.include?(key) }\n end\n\n filtered_attributes\n end", "code_tokens": ["def", "filtered_dependency_attributes", "filtered_attributes", "=", "dependency_attributes", "if", "attributes_blacklist", ".", "present?", "filtered_attributes", "=", "filtered_attributes", ".", "reject", "{", "|", "key", ",", "_value", "|", "attributes_blacklist", ".", "include?", "(", "key", ")", "}", "end", "if", "attributes_whitelist", ".", "present?", "filtered_attributes", "=", "filtered_attributes", ".", "select", "{", "|", "key", ",", "_value", "|", "attributes_whitelist", ".", "include?", "(", "key", ")", "}", "end", "filtered_attributes", "end"], "docstring": "List attributes causing a dependency and filters them by attributes_blacklist and attributes_whitelist\n\n @return [Hash{Symbol => Set}] attributes causing a dependency and filtered by blacklist and whitelist", "docstring_tokens": ["List", "attributes", "causing", "a", "dependency", "and", "filters", "them", "by", "attributes_blacklist", "and", "attributes_whitelist"], "sha": "8367841fd967a8294385d57f4b20891ff9b0958f", "url": "https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_collection.rb#L326-L338", "partition": "valid"} {"repo": "ManageIQ/inventory_refresh", "path": "lib/inventory_refresh/inventory_collection.rb", "func_name": "InventoryRefresh.InventoryCollection.fixed_attributes", "original_string": "def fixed_attributes\n if model_class\n presence_validators = model_class.validators.detect { |x| x.kind_of?(ActiveRecord::Validations::PresenceValidator) }\n end\n # Attributes that has to be always on the entity, so attributes making unique index of the record + attributes\n # that have presence validation\n fixed_attributes = manager_ref\n fixed_attributes += presence_validators.attributes if presence_validators.present?\n fixed_attributes\n end", "language": "ruby", "code": "def fixed_attributes\n if model_class\n presence_validators = model_class.validators.detect { |x| x.kind_of?(ActiveRecord::Validations::PresenceValidator) }\n end\n # Attributes that has to be always on the entity, so attributes making unique index of the record + attributes\n # that have presence validation\n fixed_attributes = manager_ref\n fixed_attributes += presence_validators.attributes if presence_validators.present?\n fixed_attributes\n end", "code_tokens": ["def", "fixed_attributes", "if", "model_class", "presence_validators", "=", "model_class", ".", "validators", ".", "detect", "{", "|", "x", "|", "x", ".", "kind_of?", "(", "ActiveRecord", "::", "Validations", "::", "PresenceValidator", ")", "}", "end", "# Attributes that has to be always on the entity, so attributes making unique index of the record + attributes", "# that have presence validation", "fixed_attributes", "=", "manager_ref", "fixed_attributes", "+=", "presence_validators", ".", "attributes", "if", "presence_validators", ".", "present?", "fixed_attributes", "end"], "docstring": "Attributes that are needed to be able to save the record, i.e. attributes that are part of the unique index\n and attributes with presence validation or NOT NULL constraint\n\n @return [Array] attributes that are needed for saving of the record", "docstring_tokens": ["Attributes", "that", "are", "needed", "to", "be", "able", "to", "save", "the", "record", "i", ".", "e", ".", "attributes", "that", "are", "part", "of", "the", "unique", "index", "and", "attributes", "with", "presence", "validation", "or", "NOT", "NULL", "constraint"], "sha": "8367841fd967a8294385d57f4b20891ff9b0958f", "url": "https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_collection.rb#L344-L353", "partition": "valid"} {"repo": "ManageIQ/inventory_refresh", "path": "lib/inventory_refresh/inventory_collection.rb", "func_name": "InventoryRefresh.InventoryCollection.fixed_dependencies", "original_string": "def fixed_dependencies\n fixed_attrs = fixed_attributes\n\n filtered_dependency_attributes.each_with_object(Set.new) do |(key, value), fixed_deps|\n fixed_deps.merge(value) if fixed_attrs.include?(key)\n end.reject(&:saved?)\n end", "language": "ruby", "code": "def fixed_dependencies\n fixed_attrs = fixed_attributes\n\n filtered_dependency_attributes.each_with_object(Set.new) do |(key, value), fixed_deps|\n fixed_deps.merge(value) if fixed_attrs.include?(key)\n end.reject(&:saved?)\n end", "code_tokens": ["def", "fixed_dependencies", "fixed_attrs", "=", "fixed_attributes", "filtered_dependency_attributes", ".", "each_with_object", "(", "Set", ".", "new", ")", "do", "|", "(", "key", ",", "value", ")", ",", "fixed_deps", "|", "fixed_deps", ".", "merge", "(", "value", ")", "if", "fixed_attrs", ".", "include?", "(", "key", ")", "end", ".", "reject", "(", ":saved?", ")", "end"], "docstring": "Returns fixed dependencies, which are the ones we can't move, because we wouldn't be able to save the data\n\n @returns [Set] all unique non saved fixed dependencies", "docstring_tokens": ["Returns", "fixed", "dependencies", "which", "are", "the", "ones", "we", "can", "t", "move", "because", "we", "wouldn", "t", "be", "able", "to", "save", "the", "data"], "sha": "8367841fd967a8294385d57f4b20891ff9b0958f", "url": "https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_collection.rb#L358-L364", "partition": "valid"} {"repo": "ManageIQ/inventory_refresh", "path": "lib/inventory_refresh/inventory_collection.rb", "func_name": "InventoryRefresh.InventoryCollection.dependency_attributes_for", "original_string": "def dependency_attributes_for(inventory_collections)\n attributes = Set.new\n inventory_collections.each do |inventory_collection|\n attributes += filtered_dependency_attributes.select { |_key, value| value.include?(inventory_collection) }.keys\n end\n attributes\n end", "language": "ruby", "code": "def dependency_attributes_for(inventory_collections)\n attributes = Set.new\n inventory_collections.each do |inventory_collection|\n attributes += filtered_dependency_attributes.select { |_key, value| value.include?(inventory_collection) }.keys\n end\n attributes\n end", "code_tokens": ["def", "dependency_attributes_for", "(", "inventory_collections", ")", "attributes", "=", "Set", ".", "new", "inventory_collections", ".", "each", "do", "|", "inventory_collection", "|", "attributes", "+=", "filtered_dependency_attributes", ".", "select", "{", "|", "_key", ",", "value", "|", "value", ".", "include?", "(", "inventory_collection", ")", "}", ".", "keys", "end", "attributes", "end"], "docstring": "Returns what attributes are causing a dependencies to certain InventoryCollection objects.\n\n @param inventory_collections [Array]\n @return [Array] attributes causing the dependencies to certain\n InventoryCollection objects", "docstring_tokens": ["Returns", "what", "attributes", "are", "causing", "a", "dependencies", "to", "certain", "InventoryCollection", "objects", "."], "sha": "8367841fd967a8294385d57f4b20891ff9b0958f", "url": "https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_collection.rb#L376-L382", "partition": "valid"} {"repo": "ManageIQ/inventory_refresh", "path": "lib/inventory_refresh/inventory_collection.rb", "func_name": "InventoryRefresh.InventoryCollection.records_identities", "original_string": "def records_identities(records)\n records = [records] unless records.respond_to?(:map)\n records.map { |record| record_identity(record) }\n end", "language": "ruby", "code": "def records_identities(records)\n records = [records] unless records.respond_to?(:map)\n records.map { |record| record_identity(record) }\n end", "code_tokens": ["def", "records_identities", "(", "records", ")", "records", "=", "[", "records", "]", "unless", "records", ".", "respond_to?", "(", ":map", ")", "records", ".", "map", "{", "|", "record", "|", "record_identity", "(", "record", ")", "}", "end"], "docstring": "Returns array of records identities\n\n @param records [Array, Array[Hash]] list of stored records\n @return [Array] array of records identities", "docstring_tokens": ["Returns", "array", "of", "records", "identities"], "sha": "8367841fd967a8294385d57f4b20891ff9b0958f", "url": "https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_collection.rb#L553-L556", "partition": "valid"} {"repo": "ManageIQ/inventory_refresh", "path": "lib/inventory_refresh/inventory_collection.rb", "func_name": "InventoryRefresh.InventoryCollection.record_identity", "original_string": "def record_identity(record)\n identity = record.try(:[], :id) || record.try(:[], \"id\") || record.try(:id)\n raise \"Cannot obtain identity of the #{record}\" if identity.blank?\n {\n :id => identity\n }\n end", "language": "ruby", "code": "def record_identity(record)\n identity = record.try(:[], :id) || record.try(:[], \"id\") || record.try(:id)\n raise \"Cannot obtain identity of the #{record}\" if identity.blank?\n {\n :id => identity\n }\n end", "code_tokens": ["def", "record_identity", "(", "record", ")", "identity", "=", "record", ".", "try", "(", ":[]", ",", ":id", ")", "||", "record", ".", "try", "(", ":[]", ",", "\"id\"", ")", "||", "record", ".", "try", "(", ":id", ")", "raise", "\"Cannot obtain identity of the #{record}\"", "if", "identity", ".", "blank?", "{", ":id", "=>", "identity", "}", "end"], "docstring": "Returns a hash with a simple record identity\n\n @param record [ApplicationRecord, Hash] list of stored records\n @return [Hash{Symbol => Bigint}] record identity", "docstring_tokens": ["Returns", "a", "hash", "with", "a", "simple", "record", "identity"], "sha": "8367841fd967a8294385d57f4b20891ff9b0958f", "url": "https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_collection.rb#L562-L568", "partition": "valid"} {"repo": "artofhuman/activeadmin_settings_cached", "path": "lib/activeadmin_settings_cached/dsl.rb", "func_name": "ActiveadminSettingsCached.DSL.active_admin_settings_page", "original_string": "def active_admin_settings_page(options = {}, &block)\n options.assert_valid_keys(*ActiveadminSettingsCached::Options::VALID_OPTIONS)\n\n options = ActiveadminSettingsCached::Options.options_for(options)\n coercion =\n ActiveadminSettingsCached::Coercions.new(options[:template_object].defaults, options[:template_object].display)\n\n content title: options[:title] do\n render partial: options[:template], locals: { settings_model: options[:template_object] }\n end\n\n page_action :update, method: :post do\n settings_params = params.require(:settings).permit!\n\n coercion.cast_params(settings_params) do |name, value|\n options[:template_object].save(name, value)\n end\n\n flash[:success] = t('activeadmin_settings_cached.settings.update.success'.freeze)\n Rails.version.to_i >= 5 ? redirect_back(fallback_location: admin_root_path) : redirect_to(:back)\n options[:after_save].call if options[:after_save].respond_to?(:call)\n end\n\n instance_eval(&block) if block_given?\n end", "language": "ruby", "code": "def active_admin_settings_page(options = {}, &block)\n options.assert_valid_keys(*ActiveadminSettingsCached::Options::VALID_OPTIONS)\n\n options = ActiveadminSettingsCached::Options.options_for(options)\n coercion =\n ActiveadminSettingsCached::Coercions.new(options[:template_object].defaults, options[:template_object].display)\n\n content title: options[:title] do\n render partial: options[:template], locals: { settings_model: options[:template_object] }\n end\n\n page_action :update, method: :post do\n settings_params = params.require(:settings).permit!\n\n coercion.cast_params(settings_params) do |name, value|\n options[:template_object].save(name, value)\n end\n\n flash[:success] = t('activeadmin_settings_cached.settings.update.success'.freeze)\n Rails.version.to_i >= 5 ? redirect_back(fallback_location: admin_root_path) : redirect_to(:back)\n options[:after_save].call if options[:after_save].respond_to?(:call)\n end\n\n instance_eval(&block) if block_given?\n end", "code_tokens": ["def", "active_admin_settings_page", "(", "options", "=", "{", "}", ",", "&", "block", ")", "options", ".", "assert_valid_keys", "(", "ActiveadminSettingsCached", "::", "Options", "::", "VALID_OPTIONS", ")", "options", "=", "ActiveadminSettingsCached", "::", "Options", ".", "options_for", "(", "options", ")", "coercion", "=", "ActiveadminSettingsCached", "::", "Coercions", ".", "new", "(", "options", "[", ":template_object", "]", ".", "defaults", ",", "options", "[", ":template_object", "]", ".", "display", ")", "content", "title", ":", "options", "[", ":title", "]", "do", "render", "partial", ":", "options", "[", ":template", "]", ",", "locals", ":", "{", "settings_model", ":", "options", "[", ":template_object", "]", "}", "end", "page_action", ":update", ",", "method", ":", ":post", "do", "settings_params", "=", "params", ".", "require", "(", ":settings", ")", ".", "permit!", "coercion", ".", "cast_params", "(", "settings_params", ")", "do", "|", "name", ",", "value", "|", "options", "[", ":template_object", "]", ".", "save", "(", "name", ",", "value", ")", "end", "flash", "[", ":success", "]", "=", "t", "(", "'activeadmin_settings_cached.settings.update.success'", ".", "freeze", ")", "Rails", ".", "version", ".", "to_i", ">=", "5", "?", "redirect_back", "(", "fallback_location", ":", "admin_root_path", ")", ":", "redirect_to", "(", ":back", ")", "options", "[", ":after_save", "]", ".", "call", "if", "options", "[", ":after_save", "]", ".", "respond_to?", "(", ":call", ")", "end", "instance_eval", "(", "block", ")", "if", "block_given?", "end"], "docstring": "Declares settings function.\n\n @api public\n\n @param [Hash] options\n @option options [String] :model_name, settings model name override (default: uses name from global config.)\n @option options [String] :starting_with, each key must starting with, (default: nil)\n @option options [String] :key, root key can be replacement for starting_with, (default: nil)\n @option options [String] :template custom, template rendering (default: 'admin/settings/index')\n @option options [String] :template_object, object to use in templates (default: ActiveadminSettingsCached::Model instance)\n @option options [String] :display, display settings override (default: nil)\n @option options [String] :title, title value override (default: I18n.t('settings.menu.label'))\n @option options [Proc] :after_save, callback for action after page update, (default: nil)", "docstring_tokens": ["Declares", "settings", "function", "."], "sha": "00c4131e5afd12af657cac0f68a4d62c223d3850", "url": "https://github.com/artofhuman/activeadmin_settings_cached/blob/00c4131e5afd12af657cac0f68a4d62c223d3850/lib/activeadmin_settings_cached/dsl.rb#L18-L42", "partition": "valid"} {"repo": "pzol/monadic", "path": "lib/monadic/either.rb", "func_name": "Monadic.Either.or", "original_string": "def or(value=nil, &block)\n return Failure(block.call(@value)) if failure? && block_given?\n return Failure(value) if failure?\n return self\n end", "language": "ruby", "code": "def or(value=nil, &block)\n return Failure(block.call(@value)) if failure? && block_given?\n return Failure(value) if failure?\n return self\n end", "code_tokens": ["def", "or", "(", "value", "=", "nil", ",", "&", "block", ")", "return", "Failure", "(", "block", ".", "call", "(", "@value", ")", ")", "if", "failure?", "&&", "block_given?", "return", "Failure", "(", "value", ")", "if", "failure?", "return", "self", "end"], "docstring": "If it is a Failure it will return a new Failure with the provided value\n @return [Success, Failure]", "docstring_tokens": ["If", "it", "is", "a", "Failure", "it", "will", "return", "a", "new", "Failure", "with", "the", "provided", "value"], "sha": "50669c95f93013df6576c86e32ea9aeffd8a548e", "url": "https://github.com/pzol/monadic/blob/50669c95f93013df6576c86e32ea9aeffd8a548e/lib/monadic/either.rb#L39-L43", "partition": "valid"} {"repo": "SciRuby/rubex", "path": "lib/rubex/code_writer.rb", "func_name": "Rubex.CodeWriter.write_func_declaration", "original_string": "def write_func_declaration type:, c_name:, args: [], static: true\n write_func_prototype type, c_name, args, static: static\n @code << \";\"\n new_line\n end", "language": "ruby", "code": "def write_func_declaration type:, c_name:, args: [], static: true\n write_func_prototype type, c_name, args, static: static\n @code << \";\"\n new_line\n end", "code_tokens": ["def", "write_func_declaration", "type", ":", ",", "c_name", ":", ",", "args", ":", "[", "]", ",", "static", ":", "true", "write_func_prototype", "type", ",", "c_name", ",", "args", ",", "static", ":", "static", "@code", "<<", "\";\"", "new_line", "end"], "docstring": "type - Return type of the method.\n c_name - C Name.\n args - Array of Arrays containing data type and variable name.", "docstring_tokens": ["type", "-", "Return", "type", "of", "the", "method", ".", "c_name", "-", "C", "Name", ".", "args", "-", "Array", "of", "Arrays", "containing", "data", "type", "and", "variable", "name", "."], "sha": "bf5ee9365e1b93ae58c97827c1a6ef6c04cb5f33", "url": "https://github.com/SciRuby/rubex/blob/bf5ee9365e1b93ae58c97827c1a6ef6c04cb5f33/lib/rubex/code_writer.rb#L32-L36", "partition": "valid"} {"repo": "piotrmurach/benchmark-trend", "path": "lib/benchmark/trend.rb", "func_name": "Benchmark.Trend.range", "original_string": "def range(start, limit, ratio: 8)\n check_greater(start, 0)\n check_greater(limit, start)\n check_greater(ratio, 2)\n\n items = []\n count = start\n items << count\n (limit / ratio).times do\n count *= ratio\n break if count >= limit\n items << count\n end\n items << limit if start != limit\n items\n end", "language": "ruby", "code": "def range(start, limit, ratio: 8)\n check_greater(start, 0)\n check_greater(limit, start)\n check_greater(ratio, 2)\n\n items = []\n count = start\n items << count\n (limit / ratio).times do\n count *= ratio\n break if count >= limit\n items << count\n end\n items << limit if start != limit\n items\n end", "code_tokens": ["def", "range", "(", "start", ",", "limit", ",", "ratio", ":", "8", ")", "check_greater", "(", "start", ",", "0", ")", "check_greater", "(", "limit", ",", "start", ")", "check_greater", "(", "ratio", ",", "2", ")", "items", "=", "[", "]", "count", "=", "start", "items", "<<", "count", "(", "limit", "/", "ratio", ")", ".", "times", "do", "count", "*=", "ratio", "break", "if", "count", ">=", "limit", "items", "<<", "count", "end", "items", "<<", "limit", "if", "start", "!=", "limit", "items", "end"], "docstring": "Generate a range of inputs spaced by powers.\n\n The default range is generated in the multiples of 8.\n\n @example\n Benchmark::Trend.range(8, 8 << 10)\n # => [8, 64, 512, 4096, 8192]\n\n @param [Integer] start\n @param [Integer] limit\n @param [Integer] ratio\n\n @api public", "docstring_tokens": ["Generate", "a", "range", "of", "inputs", "spaced", "by", "powers", "."], "sha": "7f565cb6a09667b4e7cf7d7741b5a604076b447e", "url": "https://github.com/piotrmurach/benchmark-trend/blob/7f565cb6a09667b4e7cf7d7741b5a604076b447e/lib/benchmark/trend.rb#L55-L70", "partition": "valid"} {"repo": "piotrmurach/benchmark-trend", "path": "lib/benchmark/trend.rb", "func_name": "Benchmark.Trend.measure_execution_time", "original_string": "def measure_execution_time(data = nil, repeat: 1, &work)\n inputs = data || range(1, 10_000)\n times = []\n\n inputs.each_with_index do |input, i|\n GC.start\n measurements = []\n\n repeat.times do\n measurements << clock_time { work.(input, i) }\n end\n\n times << measurements.reduce(&:+).to_f / measurements.size\n end\n [inputs, times]\n end", "language": "ruby", "code": "def measure_execution_time(data = nil, repeat: 1, &work)\n inputs = data || range(1, 10_000)\n times = []\n\n inputs.each_with_index do |input, i|\n GC.start\n measurements = []\n\n repeat.times do\n measurements << clock_time { work.(input, i) }\n end\n\n times << measurements.reduce(&:+).to_f / measurements.size\n end\n [inputs, times]\n end", "code_tokens": ["def", "measure_execution_time", "(", "data", "=", "nil", ",", "repeat", ":", "1", ",", "&", "work", ")", "inputs", "=", "data", "||", "range", "(", "1", ",", "10_000", ")", "times", "=", "[", "]", "inputs", ".", "each_with_index", "do", "|", "input", ",", "i", "|", "GC", ".", "start", "measurements", "=", "[", "]", "repeat", ".", "times", "do", "measurements", "<<", "clock_time", "{", "work", ".", "(", "input", ",", "i", ")", "}", "end", "times", "<<", "measurements", ".", "reduce", "(", ":+", ")", ".", "to_f", "/", "measurements", ".", "size", "end", "[", "inputs", ",", "times", "]", "end"], "docstring": "Gather times for each input against an algorithm\n\n @param [Array[Numeric]] data\n the data to run measurements for\n\n @param [Integer] repeat\n nubmer of times work is called to compute execution time\n\n @return [Array[Array, Array]]\n\n @api public", "docstring_tokens": ["Gather", "times", "for", "each", "input", "against", "an", "algorithm"], "sha": "7f565cb6a09667b4e7cf7d7741b5a604076b447e", "url": "https://github.com/piotrmurach/benchmark-trend/blob/7f565cb6a09667b4e7cf7d7741b5a604076b447e/lib/benchmark/trend.rb#L100-L115", "partition": "valid"} {"repo": "piotrmurach/benchmark-trend", "path": "lib/benchmark/trend.rb", "func_name": "Benchmark.Trend.fit_logarithmic", "original_string": "def fit_logarithmic(xs, ys)\n fit(xs, ys, tran_x: ->(x) { Math.log(x) })\n end", "language": "ruby", "code": "def fit_logarithmic(xs, ys)\n fit(xs, ys, tran_x: ->(x) { Math.log(x) })\n end", "code_tokens": ["def", "fit_logarithmic", "(", "xs", ",", "ys", ")", "fit", "(", "xs", ",", "ys", ",", "tran_x", ":", "->", "(", "x", ")", "{", "Math", ".", "log", "(", "x", ")", "}", ")", "end"], "docstring": "Find a line of best fit that approximates logarithmic function\n\n Model form: y = a*lnx + b\n\n @param [Array[Numeric]] xs\n the data points along X axis\n\n @param [Array[Numeric]] ys\n the data points along Y axis\n\n @return [Numeric, Numeric, Numeric]\n returns a, b, and rr values\n\n @api public", "docstring_tokens": ["Find", "a", "line", "of", "best", "fit", "that", "approximates", "logarithmic", "function"], "sha": "7f565cb6a09667b4e7cf7d7741b5a604076b447e", "url": "https://github.com/piotrmurach/benchmark-trend/blob/7f565cb6a09667b4e7cf7d7741b5a604076b447e/lib/benchmark/trend.rb#L151-L153", "partition": "valid"} {"repo": "piotrmurach/benchmark-trend", "path": "lib/benchmark/trend.rb", "func_name": "Benchmark.Trend.fit_power", "original_string": "def fit_power(xs, ys)\n a, b, rr = fit(xs, ys, tran_x: ->(x) { Math.log(x) },\n tran_y: ->(y) { Math.log(y) })\n\n [a, Math.exp(b), rr]\n end", "language": "ruby", "code": "def fit_power(xs, ys)\n a, b, rr = fit(xs, ys, tran_x: ->(x) { Math.log(x) },\n tran_y: ->(y) { Math.log(y) })\n\n [a, Math.exp(b), rr]\n end", "code_tokens": ["def", "fit_power", "(", "xs", ",", "ys", ")", "a", ",", "b", ",", "rr", "=", "fit", "(", "xs", ",", "ys", ",", "tran_x", ":", "->", "(", "x", ")", "{", "Math", ".", "log", "(", "x", ")", "}", ",", "tran_y", ":", "->", "(", "y", ")", "{", "Math", ".", "log", "(", "y", ")", "}", ")", "[", "a", ",", "Math", ".", "exp", "(", "b", ")", ",", "rr", "]", "end"], "docstring": "Finds a line of best fit that approxmimates power function\n\n Function form: y = bx^a\n\n @return [Numeric, Numeric, Numeric]\n returns a, b, and rr values\n\n @api public", "docstring_tokens": ["Finds", "a", "line", "of", "best", "fit", "that", "approxmimates", "power", "function"], "sha": "7f565cb6a09667b4e7cf7d7741b5a604076b447e", "url": "https://github.com/piotrmurach/benchmark-trend/blob/7f565cb6a09667b4e7cf7d7741b5a604076b447e/lib/benchmark/trend.rb#L167-L172", "partition": "valid"} {"repo": "piotrmurach/benchmark-trend", "path": "lib/benchmark/trend.rb", "func_name": "Benchmark.Trend.fit_exponential", "original_string": "def fit_exponential(xs, ys)\n a, b, rr = fit(xs, ys, tran_y: ->(y) { Math.log(y) })\n\n [Math.exp(a), Math.exp(b), rr]\n end", "language": "ruby", "code": "def fit_exponential(xs, ys)\n a, b, rr = fit(xs, ys, tran_y: ->(y) { Math.log(y) })\n\n [Math.exp(a), Math.exp(b), rr]\n end", "code_tokens": ["def", "fit_exponential", "(", "xs", ",", "ys", ")", "a", ",", "b", ",", "rr", "=", "fit", "(", "xs", ",", "ys", ",", "tran_y", ":", "->", "(", "y", ")", "{", "Math", ".", "log", "(", "y", ")", "}", ")", "[", "Math", ".", "exp", "(", "a", ")", ",", "Math", ".", "exp", "(", "b", ")", ",", "rr", "]", "end"], "docstring": "Find a line of best fit that approximates exponential function\n\n Model form: y = ab^x\n\n @return [Numeric, Numeric, Numeric]\n returns a, b, and rr values\n\n @api public", "docstring_tokens": ["Find", "a", "line", "of", "best", "fit", "that", "approximates", "exponential", "function"], "sha": "7f565cb6a09667b4e7cf7d7741b5a604076b447e", "url": "https://github.com/piotrmurach/benchmark-trend/blob/7f565cb6a09667b4e7cf7d7741b5a604076b447e/lib/benchmark/trend.rb#L183-L187", "partition": "valid"} {"repo": "piotrmurach/benchmark-trend", "path": "lib/benchmark/trend.rb", "func_name": "Benchmark.Trend.fit", "original_string": "def fit(xs, ys, tran_x: ->(x) { x }, tran_y: ->(y) { y })\n eps = (10 ** -10)\n n = 0\n sum_x = 0.0\n sum_x2 = 0.0\n sum_y = 0.0\n sum_y2 = 0.0\n sum_xy = 0.0\n\n xs.zip(ys).each do |x, y|\n n += 1\n sum_x += tran_x.(x)\n sum_y += tran_y.(y)\n sum_x2 += tran_x.(x) ** 2\n sum_y2 += tran_y.(y) ** 2\n sum_xy += tran_x.(x) * tran_y.(y)\n end\n\n txy = n * sum_xy - sum_x * sum_y\n tx = n * sum_x2 - sum_x ** 2\n ty = n * sum_y2 - sum_y ** 2\n\n is_linear = tran_x.(Math::E) * tran_y.(Math::E) == Math::E ** 2\n\n if tx.abs < eps # no variation in xs\n raise ArgumentError, \"No variation in data #{xs}\"\n elsif ty.abs < eps && is_linear # no variation in ys - constant fit\n slope = 0\n intercept = sum_y / n\n residual_sq = 1 # doesn't exist\n else\n slope = txy / tx\n intercept = (sum_y - slope * sum_x) / n\n residual_sq = (txy ** 2) / (tx * ty)\n end\n\n [slope, intercept, residual_sq]\n end", "language": "ruby", "code": "def fit(xs, ys, tran_x: ->(x) { x }, tran_y: ->(y) { y })\n eps = (10 ** -10)\n n = 0\n sum_x = 0.0\n sum_x2 = 0.0\n sum_y = 0.0\n sum_y2 = 0.0\n sum_xy = 0.0\n\n xs.zip(ys).each do |x, y|\n n += 1\n sum_x += tran_x.(x)\n sum_y += tran_y.(y)\n sum_x2 += tran_x.(x) ** 2\n sum_y2 += tran_y.(y) ** 2\n sum_xy += tran_x.(x) * tran_y.(y)\n end\n\n txy = n * sum_xy - sum_x * sum_y\n tx = n * sum_x2 - sum_x ** 2\n ty = n * sum_y2 - sum_y ** 2\n\n is_linear = tran_x.(Math::E) * tran_y.(Math::E) == Math::E ** 2\n\n if tx.abs < eps # no variation in xs\n raise ArgumentError, \"No variation in data #{xs}\"\n elsif ty.abs < eps && is_linear # no variation in ys - constant fit\n slope = 0\n intercept = sum_y / n\n residual_sq = 1 # doesn't exist\n else\n slope = txy / tx\n intercept = (sum_y - slope * sum_x) / n\n residual_sq = (txy ** 2) / (tx * ty)\n end\n\n [slope, intercept, residual_sq]\n end", "code_tokens": ["def", "fit", "(", "xs", ",", "ys", ",", "tran_x", ":", "->", "(", "x", ")", "{", "x", "}", ",", "tran_y", ":", "->", "(", "y", ")", "{", "y", "}", ")", "eps", "=", "(", "10", "**", "-", "10", ")", "n", "=", "0", "sum_x", "=", "0.0", "sum_x2", "=", "0.0", "sum_y", "=", "0.0", "sum_y2", "=", "0.0", "sum_xy", "=", "0.0", "xs", ".", "zip", "(", "ys", ")", ".", "each", "do", "|", "x", ",", "y", "|", "n", "+=", "1", "sum_x", "+=", "tran_x", ".", "(", "x", ")", "sum_y", "+=", "tran_y", ".", "(", "y", ")", "sum_x2", "+=", "tran_x", ".", "(", "x", ")", "**", "2", "sum_y2", "+=", "tran_y", ".", "(", "y", ")", "**", "2", "sum_xy", "+=", "tran_x", ".", "(", "x", ")", "*", "tran_y", ".", "(", "y", ")", "end", "txy", "=", "n", "*", "sum_xy", "-", "sum_x", "*", "sum_y", "tx", "=", "n", "*", "sum_x2", "-", "sum_x", "**", "2", "ty", "=", "n", "*", "sum_y2", "-", "sum_y", "**", "2", "is_linear", "=", "tran_x", ".", "(", "Math", "::", "E", ")", "*", "tran_y", ".", "(", "Math", "::", "E", ")", "==", "Math", "::", "E", "**", "2", "if", "tx", ".", "abs", "<", "eps", "# no variation in xs", "raise", "ArgumentError", ",", "\"No variation in data #{xs}\"", "elsif", "ty", ".", "abs", "<", "eps", "&&", "is_linear", "# no variation in ys - constant fit", "slope", "=", "0", "intercept", "=", "sum_y", "/", "n", "residual_sq", "=", "1", "# doesn't exist", "else", "slope", "=", "txy", "/", "tx", "intercept", "=", "(", "sum_y", "-", "slope", "*", "sum_x", ")", "/", "n", "residual_sq", "=", "(", "txy", "**", "2", ")", "/", "(", "tx", "*", "ty", ")", "end", "[", "slope", ",", "intercept", ",", "residual_sq", "]", "end"], "docstring": "Fit the performance measurements to construct a model with\n slope and intercept parameters that minimize the error.\n\n @param [Array[Numeric]] xs\n the data points along X axis\n\n @param [Array[Numeric]] ys\n the data points along Y axis\n\n @return [Array[Numeric, Numeric, Numeric]\n returns slope, intercept and model's goodness-of-fit\n\n @api public", "docstring_tokens": ["Fit", "the", "performance", "measurements", "to", "construct", "a", "model", "with", "slope", "and", "intercept", "parameters", "that", "minimize", "the", "error", "."], "sha": "7f565cb6a09667b4e7cf7d7741b5a604076b447e", "url": "https://github.com/piotrmurach/benchmark-trend/blob/7f565cb6a09667b4e7cf7d7741b5a604076b447e/lib/benchmark/trend.rb#L206-L243", "partition": "valid"} {"repo": "piotrmurach/benchmark-trend", "path": "lib/benchmark/trend.rb", "func_name": "Benchmark.Trend.fit_at", "original_string": "def fit_at(type, slope: nil, intercept: nil, n: nil)\n raise ArgumentError, \"Incorrect input size: #{n}\" unless n > 0\n\n case type\n when :logarithmic, :log\n intercept + slope * Math.log(n)\n when :linear\n intercept + slope * n\n when :power\n intercept * (n ** slope)\n when :exponential, :exp\n intercept * (slope ** n)\n else\n raise ArgumentError, \"Unknown fit type: #{type}\"\n end\n end", "language": "ruby", "code": "def fit_at(type, slope: nil, intercept: nil, n: nil)\n raise ArgumentError, \"Incorrect input size: #{n}\" unless n > 0\n\n case type\n when :logarithmic, :log\n intercept + slope * Math.log(n)\n when :linear\n intercept + slope * n\n when :power\n intercept * (n ** slope)\n when :exponential, :exp\n intercept * (slope ** n)\n else\n raise ArgumentError, \"Unknown fit type: #{type}\"\n end\n end", "code_tokens": ["def", "fit_at", "(", "type", ",", "slope", ":", "nil", ",", "intercept", ":", "nil", ",", "n", ":", "nil", ")", "raise", "ArgumentError", ",", "\"Incorrect input size: #{n}\"", "unless", "n", ">", "0", "case", "type", "when", ":logarithmic", ",", ":log", "intercept", "+", "slope", "*", "Math", ".", "log", "(", "n", ")", "when", ":linear", "intercept", "+", "slope", "*", "n", "when", ":power", "intercept", "*", "(", "n", "**", "slope", ")", "when", ":exponential", ",", ":exp", "intercept", "*", "(", "slope", "**", "n", ")", "else", "raise", "ArgumentError", ",", "\"Unknown fit type: #{type}\"", "end", "end"], "docstring": "Take a fit and estimate behaviour at input size n\n\n @example\n fit_at(:power, slope: 1.5, intercept: 2, n: 10)\n\n @return\n fit model value for input n\n\n @api public", "docstring_tokens": ["Take", "a", "fit", "and", "estimate", "behaviour", "at", "input", "size", "n"], "sha": "7f565cb6a09667b4e7cf7d7741b5a604076b447e", "url": "https://github.com/piotrmurach/benchmark-trend/blob/7f565cb6a09667b4e7cf7d7741b5a604076b447e/lib/benchmark/trend.rb#L255-L270", "partition": "valid"} {"repo": "digital-fabric/modulation", "path": "lib/modulation/module_mixin.rb", "func_name": "Modulation.ModuleMixin.export", "original_string": "def export(*symbols)\n symbols = symbols.first if symbols.first.is_a?(Array)\n __exported_symbols.concat(symbols)\n end", "language": "ruby", "code": "def export(*symbols)\n symbols = symbols.first if symbols.first.is_a?(Array)\n __exported_symbols.concat(symbols)\n end", "code_tokens": ["def", "export", "(", "*", "symbols", ")", "symbols", "=", "symbols", ".", "first", "if", "symbols", ".", "first", ".", "is_a?", "(", "Array", ")", "__exported_symbols", ".", "concat", "(", "symbols", ")", "end"], "docstring": "Adds given symbols to the exported_symbols array\n @param symbols [Array] array of symbols\n @return [void]", "docstring_tokens": ["Adds", "given", "symbols", "to", "the", "exported_symbols", "array"], "sha": "28cd3f02f32da25ec7cf156c4df0ccfcb0294124", "url": "https://github.com/digital-fabric/modulation/blob/28cd3f02f32da25ec7cf156c4df0ccfcb0294124/lib/modulation/module_mixin.rb#L12-L15", "partition": "valid"} {"repo": "digital-fabric/modulation", "path": "lib/modulation/module_mixin.rb", "func_name": "Modulation.ModuleMixin.__expose!", "original_string": "def __expose!\n singleton = singleton_class\n\n singleton.private_instance_methods.each do |sym|\n singleton.send(:public, sym)\n end\n \n __module_info[:private_constants].each do |sym|\n const_set(sym, singleton.const_get(sym))\n end\n\n self\n end", "language": "ruby", "code": "def __expose!\n singleton = singleton_class\n\n singleton.private_instance_methods.each do |sym|\n singleton.send(:public, sym)\n end\n \n __module_info[:private_constants].each do |sym|\n const_set(sym, singleton.const_get(sym))\n end\n\n self\n end", "code_tokens": ["def", "__expose!", "singleton", "=", "singleton_class", "singleton", ".", "private_instance_methods", ".", "each", "do", "|", "sym", "|", "singleton", ".", "send", "(", ":public", ",", "sym", ")", "end", "__module_info", "[", ":private_constants", "]", ".", "each", "do", "|", "sym", "|", "const_set", "(", "sym", ",", "singleton", ".", "const_get", "(", "sym", ")", ")", "end", "self", "end"], "docstring": "Exposes all private methods and private constants as public\n @return [Module] self", "docstring_tokens": ["Exposes", "all", "private", "methods", "and", "private", "constants", "as", "public"], "sha": "28cd3f02f32da25ec7cf156c4df0ccfcb0294124", "url": "https://github.com/digital-fabric/modulation/blob/28cd3f02f32da25ec7cf156c4df0ccfcb0294124/lib/modulation/module_mixin.rb#L85-L97", "partition": "valid"} {"repo": "jeremyevans/rack-unreloader", "path": "lib/rack/unreloader.rb", "func_name": "Rack.Unreloader.require", "original_string": "def require(paths, &block)\n if @reloader\n @reloader.require_dependencies(paths, &block)\n else\n Unreloader.expand_directory_paths(paths).each{|f| super(f)}\n end\n end", "language": "ruby", "code": "def require(paths, &block)\n if @reloader\n @reloader.require_dependencies(paths, &block)\n else\n Unreloader.expand_directory_paths(paths).each{|f| super(f)}\n end\n end", "code_tokens": ["def", "require", "(", "paths", ",", "&", "block", ")", "if", "@reloader", "@reloader", ".", "require_dependencies", "(", "paths", ",", "block", ")", "else", "Unreloader", ".", "expand_directory_paths", "(", "paths", ")", ".", "each", "{", "|", "f", "|", "super", "(", "f", ")", "}", "end", "end"], "docstring": "Add a file glob or array of file globs to monitor for changes.", "docstring_tokens": ["Add", "a", "file", "glob", "or", "array", "of", "file", "globs", "to", "monitor", "for", "changes", "."], "sha": "f9295c8fbd7e643100eba47b6eaa1e84ad466290", "url": "https://github.com/jeremyevans/rack-unreloader/blob/f9295c8fbd7e643100eba47b6eaa1e84ad466290/lib/rack/unreloader.rb#L88-L94", "partition": "valid"} {"repo": "jeremyevans/rack-unreloader", "path": "lib/rack/unreloader.rb", "func_name": "Rack.Unreloader.record_dependency", "original_string": "def record_dependency(dependency, *files)\n if @reloader\n files = Unreloader.expand_paths(files)\n Unreloader.expand_paths(dependency).each do |path|\n @reloader.record_dependency(path, files)\n end\n end\n end", "language": "ruby", "code": "def record_dependency(dependency, *files)\n if @reloader\n files = Unreloader.expand_paths(files)\n Unreloader.expand_paths(dependency).each do |path|\n @reloader.record_dependency(path, files)\n end\n end\n end", "code_tokens": ["def", "record_dependency", "(", "dependency", ",", "*", "files", ")", "if", "@reloader", "files", "=", "Unreloader", ".", "expand_paths", "(", "files", ")", "Unreloader", ".", "expand_paths", "(", "dependency", ")", ".", "each", "do", "|", "path", "|", "@reloader", ".", "record_dependency", "(", "path", ",", "files", ")", "end", "end", "end"], "docstring": "Records that each path in +files+ depends on +dependency+. If there\n is a modification to +dependency+, all related files will be reloaded\n after +dependency+ is reloaded. Both +dependency+ and each entry in +files+\n can be an array of path globs.", "docstring_tokens": ["Records", "that", "each", "path", "in", "+", "files", "+", "depends", "on", "+", "dependency", "+", ".", "If", "there", "is", "a", "modification", "to", "+", "dependency", "+", "all", "related", "files", "will", "be", "reloaded", "after", "+", "dependency", "+", "is", "reloaded", ".", "Both", "+", "dependency", "+", "and", "each", "entry", "in", "+", "files", "+", "can", "be", "an", "array", "of", "path", "globs", "."], "sha": "f9295c8fbd7e643100eba47b6eaa1e84ad466290", "url": "https://github.com/jeremyevans/rack-unreloader/blob/f9295c8fbd7e643100eba47b6eaa1e84ad466290/lib/rack/unreloader.rb#L100-L107", "partition": "valid"} {"repo": "jeremyevans/rack-unreloader", "path": "lib/rack/unreloader.rb", "func_name": "Rack.Unreloader.record_split_class", "original_string": "def record_split_class(main_file, *files)\n if @reloader\n files = Unreloader.expand_paths(files)\n files.each do |file|\n record_dependency(file, main_file)\n end\n @reloader.skip_reload(files)\n end\n end", "language": "ruby", "code": "def record_split_class(main_file, *files)\n if @reloader\n files = Unreloader.expand_paths(files)\n files.each do |file|\n record_dependency(file, main_file)\n end\n @reloader.skip_reload(files)\n end\n end", "code_tokens": ["def", "record_split_class", "(", "main_file", ",", "*", "files", ")", "if", "@reloader", "files", "=", "Unreloader", ".", "expand_paths", "(", "files", ")", "files", ".", "each", "do", "|", "file", "|", "record_dependency", "(", "file", ",", "main_file", ")", "end", "@reloader", ".", "skip_reload", "(", "files", ")", "end", "end"], "docstring": "Record that a class is split into multiple files. +main_file+ should be\n the main file for the class, which should require all of the other\n files. +files+ should be a list of all other files that make up the class.", "docstring_tokens": ["Record", "that", "a", "class", "is", "split", "into", "multiple", "files", ".", "+", "main_file", "+", "should", "be", "the", "main", "file", "for", "the", "class", "which", "should", "require", "all", "of", "the", "other", "files", ".", "+", "files", "+", "should", "be", "a", "list", "of", "all", "other", "files", "that", "make", "up", "the", "class", "."], "sha": "f9295c8fbd7e643100eba47b6eaa1e84ad466290", "url": "https://github.com/jeremyevans/rack-unreloader/blob/f9295c8fbd7e643100eba47b6eaa1e84ad466290/lib/rack/unreloader.rb#L112-L120", "partition": "valid"} {"repo": "hirefire/hirefire-resource", "path": "lib/hirefire/middleware.rb", "func_name": "HireFire.Middleware.get_queue", "original_string": "def get_queue(value)\n ms = (Time.now.to_f * 1000).to_i - value.to_i\n ms < 0 ? 0 : ms\n end", "language": "ruby", "code": "def get_queue(value)\n ms = (Time.now.to_f * 1000).to_i - value.to_i\n ms < 0 ? 0 : ms\n end", "code_tokens": ["def", "get_queue", "(", "value", ")", "ms", "=", "(", "Time", ".", "now", ".", "to_f", "*", "1000", ")", ".", "to_i", "-", "value", ".", "to_i", "ms", "<", "0", "?", "0", ":", "ms", "end"], "docstring": "Calculates the difference, in milliseconds, between the\n HTTP_X_REQUEST_START time and the current time.\n\n @param [String] the timestamp from HTTP_X_REQUEST_START.\n @return [Integer] the queue time in milliseconds.", "docstring_tokens": ["Calculates", "the", "difference", "in", "milliseconds", "between", "the", "HTTP_X_REQUEST_START", "time", "and", "the", "current", "time", "."], "sha": "9f8bc1885ba73e9d5cf39d34fe4f15905ded3753", "url": "https://github.com/hirefire/hirefire-resource/blob/9f8bc1885ba73e9d5cf39d34fe4f15905ded3753/lib/hirefire/middleware.rb#L128-L131", "partition": "valid"} {"repo": "infosimples/two_captcha", "path": "lib/two_captcha/client.rb", "func_name": "TwoCaptcha.Client.decode", "original_string": "def decode(options = {})\n decode!(options)\n rescue TwoCaptcha::Error => ex\n TwoCaptcha::Captcha.new\n end", "language": "ruby", "code": "def decode(options = {})\n decode!(options)\n rescue TwoCaptcha::Error => ex\n TwoCaptcha::Captcha.new\n end", "code_tokens": ["def", "decode", "(", "options", "=", "{", "}", ")", "decode!", "(", "options", ")", "rescue", "TwoCaptcha", "::", "Error", "=>", "ex", "TwoCaptcha", "::", "Captcha", ".", "new", "end"], "docstring": "Create a TwoCaptcha API client.\n\n @param [String] Captcha key of the TwoCaptcha account.\n @param [Hash] options Options hash.\n @option options [Integer] :timeout (60) Seconds before giving up of a\n captcha being solved.\n @option options [Integer] :polling (5) Seconds before check_answer again\n\n @return [TwoCaptcha::Client] A Client instance.\n\n Decode the text from an image (i.e. solve a captcha).\n\n @param [Hash] options Options hash. Check docs for the method decode!.\n\n @return [TwoCaptcha::Captcha] The captcha (with solution) or an empty\n captcha instance if something goes wrong.", "docstring_tokens": ["Create", "a", "TwoCaptcha", "API", "client", "."], "sha": "60bc263c75a542a2416de46574a1b4982a6a2772", "url": "https://github.com/infosimples/two_captcha/blob/60bc263c75a542a2416de46574a1b4982a6a2772/lib/two_captcha/client.rb#L33-L37", "partition": "valid"} {"repo": "infosimples/two_captcha", "path": "lib/two_captcha/client.rb", "func_name": "TwoCaptcha.Client.upload", "original_string": "def upload(options = {})\n args = {}\n args[:body] = options[:raw64] if options[:raw64]\n args[:method] = options[:method] || 'base64'\n args.merge!(options)\n response = request('in', :multipart, args)\n\n unless response.match(/\\AOK\\|/)\n fail(TwoCaptcha::Error, 'Unexpected API Response')\n end\n\n TwoCaptcha::Captcha.new(\n id: response.split('|', 2)[1],\n api_response: response\n )\n end", "language": "ruby", "code": "def upload(options = {})\n args = {}\n args[:body] = options[:raw64] if options[:raw64]\n args[:method] = options[:method] || 'base64'\n args.merge!(options)\n response = request('in', :multipart, args)\n\n unless response.match(/\\AOK\\|/)\n fail(TwoCaptcha::Error, 'Unexpected API Response')\n end\n\n TwoCaptcha::Captcha.new(\n id: response.split('|', 2)[1],\n api_response: response\n )\n end", "code_tokens": ["def", "upload", "(", "options", "=", "{", "}", ")", "args", "=", "{", "}", "args", "[", ":body", "]", "=", "options", "[", ":raw64", "]", "if", "options", "[", ":raw64", "]", "args", "[", ":method", "]", "=", "options", "[", ":method", "]", "||", "'base64'", "args", ".", "merge!", "(", "options", ")", "response", "=", "request", "(", "'in'", ",", ":multipart", ",", "args", ")", "unless", "response", ".", "match", "(", "/", "\\A", "\\|", "/", ")", "fail", "(", "TwoCaptcha", "::", "Error", ",", "'Unexpected API Response'", ")", "end", "TwoCaptcha", "::", "Captcha", ".", "new", "(", "id", ":", "response", ".", "split", "(", "'|'", ",", "2", ")", "[", "1", "]", ",", "api_response", ":", "response", ")", "end"], "docstring": "Upload a captcha to 2Captcha.\n\n This method will not return the solution. It helps on separating concerns.\n\n @return [TwoCaptcha::Captcha] The captcha object (not solved yet).", "docstring_tokens": ["Upload", "a", "captcha", "to", "2Captcha", "."], "sha": "60bc263c75a542a2416de46574a1b4982a6a2772", "url": "https://github.com/infosimples/two_captcha/blob/60bc263c75a542a2416de46574a1b4982a6a2772/lib/two_captcha/client.rb#L131-L146", "partition": "valid"} {"repo": "infosimples/two_captcha", "path": "lib/two_captcha/client.rb", "func_name": "TwoCaptcha.Client.captcha", "original_string": "def captcha(captcha_id)\n response = request('res', :get, action: 'get', id: captcha_id)\n\n decoded_captcha = TwoCaptcha::Captcha.new(id: captcha_id)\n decoded_captcha.api_response = response\n\n if response.match(/\\AOK\\|/)\n decoded_captcha.text = response.split('|', 2)[1]\n end\n\n decoded_captcha\n end", "language": "ruby", "code": "def captcha(captcha_id)\n response = request('res', :get, action: 'get', id: captcha_id)\n\n decoded_captcha = TwoCaptcha::Captcha.new(id: captcha_id)\n decoded_captcha.api_response = response\n\n if response.match(/\\AOK\\|/)\n decoded_captcha.text = response.split('|', 2)[1]\n end\n\n decoded_captcha\n end", "code_tokens": ["def", "captcha", "(", "captcha_id", ")", "response", "=", "request", "(", "'res'", ",", ":get", ",", "action", ":", "'get'", ",", "id", ":", "captcha_id", ")", "decoded_captcha", "=", "TwoCaptcha", "::", "Captcha", ".", "new", "(", "id", ":", "captcha_id", ")", "decoded_captcha", ".", "api_response", "=", "response", "if", "response", ".", "match", "(", "/", "\\A", "\\|", "/", ")", "decoded_captcha", ".", "text", "=", "response", ".", "split", "(", "'|'", ",", "2", ")", "[", "1", "]", "end", "decoded_captcha", "end"], "docstring": "Retrieve information from an uploaded captcha.\n\n @param [Integer] captcha_id Numeric ID of the captcha.\n\n @return [TwoCaptcha::Captcha] The captcha object.", "docstring_tokens": ["Retrieve", "information", "from", "an", "uploaded", "captcha", "."], "sha": "60bc263c75a542a2416de46574a1b4982a6a2772", "url": "https://github.com/infosimples/two_captcha/blob/60bc263c75a542a2416de46574a1b4982a6a2772/lib/two_captcha/client.rb#L154-L165", "partition": "valid"} {"repo": "infosimples/two_captcha", "path": "lib/two_captcha/client.rb", "func_name": "TwoCaptcha.Client.load_captcha", "original_string": "def load_captcha(options)\n if options[:raw64]\n options[:raw64]\n elsif options[:raw]\n Base64.encode64(options[:raw])\n elsif options[:file]\n Base64.encode64(options[:file].read)\n elsif options[:path]\n Base64.encode64(File.open(options[:path], 'rb').read)\n elsif options[:url]\n Base64.encode64(TwoCaptcha::HTTP.open_url(options[:url]))\n else\n fail TwoCaptcha::ArgumentError, 'Illegal image format'\n end\n rescue\n raise TwoCaptcha::InvalidCaptcha\n end", "language": "ruby", "code": "def load_captcha(options)\n if options[:raw64]\n options[:raw64]\n elsif options[:raw]\n Base64.encode64(options[:raw])\n elsif options[:file]\n Base64.encode64(options[:file].read)\n elsif options[:path]\n Base64.encode64(File.open(options[:path], 'rb').read)\n elsif options[:url]\n Base64.encode64(TwoCaptcha::HTTP.open_url(options[:url]))\n else\n fail TwoCaptcha::ArgumentError, 'Illegal image format'\n end\n rescue\n raise TwoCaptcha::InvalidCaptcha\n end", "code_tokens": ["def", "load_captcha", "(", "options", ")", "if", "options", "[", ":raw64", "]", "options", "[", ":raw64", "]", "elsif", "options", "[", ":raw", "]", "Base64", ".", "encode64", "(", "options", "[", ":raw", "]", ")", "elsif", "options", "[", ":file", "]", "Base64", ".", "encode64", "(", "options", "[", ":file", "]", ".", "read", ")", "elsif", "options", "[", ":path", "]", "Base64", ".", "encode64", "(", "File", ".", "open", "(", "options", "[", ":path", "]", ",", "'rb'", ")", ".", "read", ")", "elsif", "options", "[", ":url", "]", "Base64", ".", "encode64", "(", "TwoCaptcha", "::", "HTTP", ".", "open_url", "(", "options", "[", ":url", "]", ")", ")", "else", "fail", "TwoCaptcha", "::", "ArgumentError", ",", "'Illegal image format'", "end", "rescue", "raise", "TwoCaptcha", "::", "InvalidCaptcha", "end"], "docstring": "Load a captcha raw content encoded in base64 from options.\n\n @param [Hash] options Options hash.\n @option options [String] :url URL of the image to be decoded.\n @option options [String] :path File path of the image to be decoded.\n @option options [File] :file File instance with image to be decoded.\n @option options [String] :raw Binary content of the image to bedecoded.\n @option options [String] :raw64 Binary content encoded in base64 of the\n image to be decoded.\n\n @return [String] The binary image base64 encoded.", "docstring_tokens": ["Load", "a", "captcha", "raw", "content", "encoded", "in", "base64", "from", "options", "."], "sha": "60bc263c75a542a2416de46574a1b4982a6a2772", "url": "https://github.com/infosimples/two_captcha/blob/60bc263c75a542a2416de46574a1b4982a6a2772/lib/two_captcha/client.rb#L218-L234", "partition": "valid"} {"repo": "infosimples/two_captcha", "path": "lib/two_captcha/client.rb", "func_name": "TwoCaptcha.Client.request", "original_string": "def request(action, method = :get, payload = {})\n res = TwoCaptcha::HTTP.request(\n url: BASE_URL.gsub(':action', action),\n timeout: timeout,\n method: method,\n payload: payload.merge(key: key, soft_id: 800)\n )\n validate_response(res)\n res\n end", "language": "ruby", "code": "def request(action, method = :get, payload = {})\n res = TwoCaptcha::HTTP.request(\n url: BASE_URL.gsub(':action', action),\n timeout: timeout,\n method: method,\n payload: payload.merge(key: key, soft_id: 800)\n )\n validate_response(res)\n res\n end", "code_tokens": ["def", "request", "(", "action", ",", "method", "=", ":get", ",", "payload", "=", "{", "}", ")", "res", "=", "TwoCaptcha", "::", "HTTP", ".", "request", "(", "url", ":", "BASE_URL", ".", "gsub", "(", "':action'", ",", "action", ")", ",", "timeout", ":", "timeout", ",", "method", ":", "method", ",", "payload", ":", "payload", ".", "merge", "(", "key", ":", "key", ",", "soft_id", ":", "800", ")", ")", "validate_response", "(", "res", ")", "res", "end"], "docstring": "Perform an HTTP request to the 2Captcha API.\n\n @param [String] action API method name.\n @param [Symbol] method HTTP method (:get, :post, :multipart).\n @param [Hash] payload Data to be sent through the HTTP request.\n\n @return [String] Response from the TwoCaptcha API.", "docstring_tokens": ["Perform", "an", "HTTP", "request", "to", "the", "2Captcha", "API", "."], "sha": "60bc263c75a542a2416de46574a1b4982a6a2772", "url": "https://github.com/infosimples/two_captcha/blob/60bc263c75a542a2416de46574a1b4982a6a2772/lib/two_captcha/client.rb#L244-L253", "partition": "valid"} {"repo": "infosimples/two_captcha", "path": "lib/two_captcha/client.rb", "func_name": "TwoCaptcha.Client.validate_response", "original_string": "def validate_response(response)\n if (error = TwoCaptcha::RESPONSE_ERRORS[response])\n fail(error)\n elsif response.to_s.empty? || response.match(/\\AERROR\\_/)\n fail(TwoCaptcha::Error, response)\n end\n end", "language": "ruby", "code": "def validate_response(response)\n if (error = TwoCaptcha::RESPONSE_ERRORS[response])\n fail(error)\n elsif response.to_s.empty? || response.match(/\\AERROR\\_/)\n fail(TwoCaptcha::Error, response)\n end\n end", "code_tokens": ["def", "validate_response", "(", "response", ")", "if", "(", "error", "=", "TwoCaptcha", "::", "RESPONSE_ERRORS", "[", "response", "]", ")", "fail", "(", "error", ")", "elsif", "response", ".", "to_s", ".", "empty?", "||", "response", ".", "match", "(", "/", "\\A", "\\_", "/", ")", "fail", "(", "TwoCaptcha", "::", "Error", ",", "response", ")", "end", "end"], "docstring": "Fail if the response has errors.\n\n @param [String] response The body response from TwoCaptcha API.", "docstring_tokens": ["Fail", "if", "the", "response", "has", "errors", "."], "sha": "60bc263c75a542a2416de46574a1b4982a6a2772", "url": "https://github.com/infosimples/two_captcha/blob/60bc263c75a542a2416de46574a1b4982a6a2772/lib/two_captcha/client.rb#L259-L265", "partition": "valid"} {"repo": "github/github-ldap", "path": "lib/github/ldap.rb", "func_name": "GitHub.Ldap.search", "original_string": "def search(options, &block)\n instrument \"search.github_ldap\", options.dup do |payload|\n result =\n if options[:base]\n @connection.search(options, &block)\n else\n search_domains.each_with_object([]) do |base, result|\n rs = @connection.search(options.merge(:base => base), &block)\n result.concat Array(rs) unless rs == false\n end\n end\n\n return [] if result == false\n Array(result)\n end\n end", "language": "ruby", "code": "def search(options, &block)\n instrument \"search.github_ldap\", options.dup do |payload|\n result =\n if options[:base]\n @connection.search(options, &block)\n else\n search_domains.each_with_object([]) do |base, result|\n rs = @connection.search(options.merge(:base => base), &block)\n result.concat Array(rs) unless rs == false\n end\n end\n\n return [] if result == false\n Array(result)\n end\n end", "code_tokens": ["def", "search", "(", "options", ",", "&", "block", ")", "instrument", "\"search.github_ldap\"", ",", "options", ".", "dup", "do", "|", "payload", "|", "result", "=", "if", "options", "[", ":base", "]", "@connection", ".", "search", "(", "options", ",", "block", ")", "else", "search_domains", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "base", ",", "result", "|", "rs", "=", "@connection", ".", "search", "(", "options", ".", "merge", "(", ":base", "=>", "base", ")", ",", "block", ")", "result", ".", "concat", "Array", "(", "rs", ")", "unless", "rs", "==", "false", "end", "end", "return", "[", "]", "if", "result", "==", "false", "Array", "(", "result", ")", "end", "end"], "docstring": "Public - Search entries in the ldap server.\n\n options: is a hash with the same options that Net::LDAP::Connection#search supports.\n block: is an optional block to pass to the search.\n\n Returns an Array of Net::LDAP::Entry.", "docstring_tokens": ["Public", "-", "Search", "entries", "in", "the", "ldap", "server", "."], "sha": "34c2685bd07ae79c6283f14f1263d1276a162f28", "url": "https://github.com/github/github-ldap/blob/34c2685bd07ae79c6283f14f1263d1276a162f28/lib/github/ldap.rb#L205-L220", "partition": "valid"} {"repo": "github/github-ldap", "path": "lib/github/ldap.rb", "func_name": "GitHub.Ldap.check_encryption", "original_string": "def check_encryption(encryption, tls_options = {})\n return unless encryption\n\n tls_options ||= {}\n case encryption.downcase.to_sym\n when :ssl, :simple_tls\n { method: :simple_tls, tls_options: tls_options }\n when :tls, :start_tls\n { method: :start_tls, tls_options: tls_options }\n end\n end", "language": "ruby", "code": "def check_encryption(encryption, tls_options = {})\n return unless encryption\n\n tls_options ||= {}\n case encryption.downcase.to_sym\n when :ssl, :simple_tls\n { method: :simple_tls, tls_options: tls_options }\n when :tls, :start_tls\n { method: :start_tls, tls_options: tls_options }\n end\n end", "code_tokens": ["def", "check_encryption", "(", "encryption", ",", "tls_options", "=", "{", "}", ")", "return", "unless", "encryption", "tls_options", "||=", "{", "}", "case", "encryption", ".", "downcase", ".", "to_sym", "when", ":ssl", ",", ":simple_tls", "{", "method", ":", ":simple_tls", ",", "tls_options", ":", "tls_options", "}", "when", ":tls", ",", ":start_tls", "{", "method", ":", ":start_tls", ",", "tls_options", ":", "tls_options", "}", "end", "end"], "docstring": "Internal - Determine whether to use encryption or not.\n\n encryption: is the encryption method, either 'ssl', 'tls', 'simple_tls' or 'start_tls'.\n tls_options: is the options hash for tls encryption method\n\n Returns the real encryption type.", "docstring_tokens": ["Internal", "-", "Determine", "whether", "to", "use", "encryption", "or", "not", "."], "sha": "34c2685bd07ae79c6283f14f1263d1276a162f28", "url": "https://github.com/github/github-ldap/blob/34c2685bd07ae79c6283f14f1263d1276a162f28/lib/github/ldap.rb#L245-L255", "partition": "valid"} {"repo": "github/github-ldap", "path": "lib/github/ldap.rb", "func_name": "GitHub.Ldap.configure_virtual_attributes", "original_string": "def configure_virtual_attributes(attributes)\n @virtual_attributes = if attributes == true\n VirtualAttributes.new(true)\n elsif attributes.is_a?(Hash)\n VirtualAttributes.new(true, attributes)\n else\n VirtualAttributes.new(false)\n end\n end", "language": "ruby", "code": "def configure_virtual_attributes(attributes)\n @virtual_attributes = if attributes == true\n VirtualAttributes.new(true)\n elsif attributes.is_a?(Hash)\n VirtualAttributes.new(true, attributes)\n else\n VirtualAttributes.new(false)\n end\n end", "code_tokens": ["def", "configure_virtual_attributes", "(", "attributes", ")", "@virtual_attributes", "=", "if", "attributes", "==", "true", "VirtualAttributes", ".", "new", "(", "true", ")", "elsif", "attributes", ".", "is_a?", "(", "Hash", ")", "VirtualAttributes", ".", "new", "(", "true", ",", "attributes", ")", "else", "VirtualAttributes", ".", "new", "(", "false", ")", "end", "end"], "docstring": "Internal - Configure virtual attributes for this server.\n If the option is `true`, we'll use the default virual attributes.\n If it's a Hash we'll map the attributes in the hash.\n\n attributes: is the option set when Ldap is initialized.\n\n Returns a VirtualAttributes.", "docstring_tokens": ["Internal", "-", "Configure", "virtual", "attributes", "for", "this", "server", ".", "If", "the", "option", "is", "true", "we", "ll", "use", "the", "default", "virual", "attributes", ".", "If", "it", "s", "a", "Hash", "we", "ll", "map", "the", "attributes", "in", "the", "hash", "."], "sha": "34c2685bd07ae79c6283f14f1263d1276a162f28", "url": "https://github.com/github/github-ldap/blob/34c2685bd07ae79c6283f14f1263d1276a162f28/lib/github/ldap.rb#L264-L272", "partition": "valid"} {"repo": "detunized/lastpass-ruby", "path": "lib/lastpass/vault.rb", "func_name": "LastPass.Vault.complete?", "original_string": "def complete? chunks\n !chunks.empty? && chunks.last.id == \"ENDM\" && chunks.last.payload == \"OK\"\n end", "language": "ruby", "code": "def complete? chunks\n !chunks.empty? && chunks.last.id == \"ENDM\" && chunks.last.payload == \"OK\"\n end", "code_tokens": ["def", "complete?", "chunks", "!", "chunks", ".", "empty?", "&&", "chunks", ".", "last", ".", "id", "==", "\"ENDM\"", "&&", "chunks", ".", "last", ".", "payload", "==", "\"OK\"", "end"], "docstring": "This more of an internal method, use one of the static constructors instead", "docstring_tokens": ["This", "more", "of", "an", "internal", "method", "use", "one", "of", "the", "static", "constructors", "instead"], "sha": "3212ff17c7dd370807f688a3875a6f21b44dcb2a", "url": "https://github.com/detunized/lastpass-ruby/blob/3212ff17c7dd370807f688a3875a6f21b44dcb2a/lib/lastpass/vault.rb#L43-L45", "partition": "valid"} {"repo": "savonrb/gyoku", "path": "lib/gyoku/prettifier.rb", "func_name": "Gyoku.Prettifier.prettify", "original_string": "def prettify(xml)\n result = ''\n formatter = REXML::Formatters::Pretty.new indent\n formatter.compact = compact\n doc = REXML::Document.new xml\n formatter.write doc, result\n result\n end", "language": "ruby", "code": "def prettify(xml)\n result = ''\n formatter = REXML::Formatters::Pretty.new indent\n formatter.compact = compact\n doc = REXML::Document.new xml\n formatter.write doc, result\n result\n end", "code_tokens": ["def", "prettify", "(", "xml", ")", "result", "=", "''", "formatter", "=", "REXML", "::", "Formatters", "::", "Pretty", ".", "new", "indent", "formatter", ".", "compact", "=", "compact", "doc", "=", "REXML", "::", "Document", ".", "new", "xml", "formatter", ".", "write", "doc", ",", "result", "result", "end"], "docstring": "Adds intendations and newlines to +xml+ to make it more readable", "docstring_tokens": ["Adds", "intendations", "and", "newlines", "to", "+", "xml", "+", "to", "make", "it", "more", "readable"], "sha": "954d002b7c88e826492a7989d44e2b08a8e980e4", "url": "https://github.com/savonrb/gyoku/blob/954d002b7c88e826492a7989d44e2b08a8e980e4/lib/gyoku/prettifier.rb#L20-L27", "partition": "valid"} {"repo": "MindscapeHQ/raygun4ruby", "path": "lib/raygun/sidekiq.rb", "func_name": "Raygun.SidekiqMiddleware.call", "original_string": "def call(worker, message, queue)\n begin\n yield\n rescue Exception => ex\n raise ex if [Interrupt, SystemExit, SignalException].include?(ex.class)\n SidekiqReporter.call(ex, worker: worker, message: message, queue: queue)\n raise ex\n end\n end", "language": "ruby", "code": "def call(worker, message, queue)\n begin\n yield\n rescue Exception => ex\n raise ex if [Interrupt, SystemExit, SignalException].include?(ex.class)\n SidekiqReporter.call(ex, worker: worker, message: message, queue: queue)\n raise ex\n end\n end", "code_tokens": ["def", "call", "(", "worker", ",", "message", ",", "queue", ")", "begin", "yield", "rescue", "Exception", "=>", "ex", "raise", "ex", "if", "[", "Interrupt", ",", "SystemExit", ",", "SignalException", "]", ".", "include?", "(", "ex", ".", "class", ")", "SidekiqReporter", ".", "call", "(", "ex", ",", "worker", ":", "worker", ",", "message", ":", "message", ",", "queue", ":", "queue", ")", "raise", "ex", "end", "end"], "docstring": "Used for Sidekiq 2.x only", "docstring_tokens": ["Used", "for", "Sidekiq", "2", ".", "x", "only"], "sha": "62029ccab220ed6f5ef55399088fccfa8938aab6", "url": "https://github.com/MindscapeHQ/raygun4ruby/blob/62029ccab220ed6f5ef55399088fccfa8938aab6/lib/raygun/sidekiq.rb#L9-L17", "partition": "valid"} {"repo": "mloughran/em-hiredis", "path": "lib/em-hiredis/lock.rb", "func_name": "EM::Hiredis.Lock.acquire", "original_string": "def acquire\n df = EM::DefaultDeferrable.new\n @redis.lock_acquire([@key], [@token, @timeout]).callback { |success|\n if (success)\n EM::Hiredis.logger.debug \"#{to_s} acquired\"\n\n EM.cancel_timer(@expire_timer) if @expire_timer\n @expire_timer = EM.add_timer(@timeout - 1) {\n EM::Hiredis.logger.debug \"#{to_s} Expires in 1s\"\n @onexpire.call if @onexpire\n }\n\n df.succeed\n else\n EM::Hiredis.logger.debug \"#{to_s} failed to acquire\"\n df.fail(\"Lock is not available\")\n end\n }.errback { |e|\n EM::Hiredis.logger.error \"#{to_s} Error acquiring lock #{e}\"\n df.fail(e)\n }\n df\n end", "language": "ruby", "code": "def acquire\n df = EM::DefaultDeferrable.new\n @redis.lock_acquire([@key], [@token, @timeout]).callback { |success|\n if (success)\n EM::Hiredis.logger.debug \"#{to_s} acquired\"\n\n EM.cancel_timer(@expire_timer) if @expire_timer\n @expire_timer = EM.add_timer(@timeout - 1) {\n EM::Hiredis.logger.debug \"#{to_s} Expires in 1s\"\n @onexpire.call if @onexpire\n }\n\n df.succeed\n else\n EM::Hiredis.logger.debug \"#{to_s} failed to acquire\"\n df.fail(\"Lock is not available\")\n end\n }.errback { |e|\n EM::Hiredis.logger.error \"#{to_s} Error acquiring lock #{e}\"\n df.fail(e)\n }\n df\n end", "code_tokens": ["def", "acquire", "df", "=", "EM", "::", "DefaultDeferrable", ".", "new", "@redis", ".", "lock_acquire", "(", "[", "@key", "]", ",", "[", "@token", ",", "@timeout", "]", ")", ".", "callback", "{", "|", "success", "|", "if", "(", "success", ")", "EM", "::", "Hiredis", ".", "logger", ".", "debug", "\"#{to_s} acquired\"", "EM", ".", "cancel_timer", "(", "@expire_timer", ")", "if", "@expire_timer", "@expire_timer", "=", "EM", ".", "add_timer", "(", "@timeout", "-", "1", ")", "{", "EM", "::", "Hiredis", ".", "logger", ".", "debug", "\"#{to_s} Expires in 1s\"", "@onexpire", ".", "call", "if", "@onexpire", "}", "df", ".", "succeed", "else", "EM", "::", "Hiredis", ".", "logger", ".", "debug", "\"#{to_s} failed to acquire\"", "df", ".", "fail", "(", "\"Lock is not available\"", ")", "end", "}", ".", "errback", "{", "|", "e", "|", "EM", "::", "Hiredis", ".", "logger", ".", "error", "\"#{to_s} Error acquiring lock #{e}\"", "df", ".", "fail", "(", "e", ")", "}", "df", "end"], "docstring": "Acquire the lock\n\n This is a re-entrant lock, re-acquiring will succeed and extend the timeout\n\n Returns a deferrable which either succeeds if the lock can be acquired, or fails if it cannot.", "docstring_tokens": ["Acquire", "the", "lock"], "sha": "c9eac4b938a1c3d4fda1ccfad6e0373037fbee99", "url": "https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/lock.rb#L28-L50", "partition": "valid"} {"repo": "mloughran/em-hiredis", "path": "lib/em-hiredis/lock.rb", "func_name": "EM::Hiredis.Lock.unlock", "original_string": "def unlock\n EM.cancel_timer(@expire_timer) if @expire_timer\n\n df = EM::DefaultDeferrable.new\n @redis.lock_release([@key], [@token]).callback { |keys_removed|\n if keys_removed > 0\n EM::Hiredis.logger.debug \"#{to_s} released\"\n df.succeed\n else\n EM::Hiredis.logger.debug \"#{to_s} could not release, not held\"\n df.fail(\"Cannot release a lock we do not hold\")\n end\n }.errback { |e|\n EM::Hiredis.logger.error \"#{to_s} Error releasing lock #{e}\"\n df.fail(e)\n }\n df\n end", "language": "ruby", "code": "def unlock\n EM.cancel_timer(@expire_timer) if @expire_timer\n\n df = EM::DefaultDeferrable.new\n @redis.lock_release([@key], [@token]).callback { |keys_removed|\n if keys_removed > 0\n EM::Hiredis.logger.debug \"#{to_s} released\"\n df.succeed\n else\n EM::Hiredis.logger.debug \"#{to_s} could not release, not held\"\n df.fail(\"Cannot release a lock we do not hold\")\n end\n }.errback { |e|\n EM::Hiredis.logger.error \"#{to_s} Error releasing lock #{e}\"\n df.fail(e)\n }\n df\n end", "code_tokens": ["def", "unlock", "EM", ".", "cancel_timer", "(", "@expire_timer", ")", "if", "@expire_timer", "df", "=", "EM", "::", "DefaultDeferrable", ".", "new", "@redis", ".", "lock_release", "(", "[", "@key", "]", ",", "[", "@token", "]", ")", ".", "callback", "{", "|", "keys_removed", "|", "if", "keys_removed", ">", "0", "EM", "::", "Hiredis", ".", "logger", ".", "debug", "\"#{to_s} released\"", "df", ".", "succeed", "else", "EM", "::", "Hiredis", ".", "logger", ".", "debug", "\"#{to_s} could not release, not held\"", "df", ".", "fail", "(", "\"Cannot release a lock we do not hold\"", ")", "end", "}", ".", "errback", "{", "|", "e", "|", "EM", "::", "Hiredis", ".", "logger", ".", "error", "\"#{to_s} Error releasing lock #{e}\"", "df", ".", "fail", "(", "e", ")", "}", "df", "end"], "docstring": "Release the lock\n\n Returns a deferrable", "docstring_tokens": ["Release", "the", "lock"], "sha": "c9eac4b938a1c3d4fda1ccfad6e0373037fbee99", "url": "https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/lock.rb#L55-L72", "partition": "valid"} {"repo": "mloughran/em-hiredis", "path": "spec/support/redis_mock.rb", "func_name": "RedisMock.Helper.redis_mock", "original_string": "def redis_mock(replies = {})\n begin\n pid = fork do\n trap(\"TERM\") { exit }\n\n RedisMock.start do |command, *args|\n (replies[command.to_sym] || lambda { |*_| \"+OK\" }).call(*args)\n end\n end\n\n sleep 1 # Give time for the socket to start listening.\n\n yield\n\n ensure\n if pid\n Process.kill(\"TERM\", pid)\n Process.wait(pid)\n end\n end\n end", "language": "ruby", "code": "def redis_mock(replies = {})\n begin\n pid = fork do\n trap(\"TERM\") { exit }\n\n RedisMock.start do |command, *args|\n (replies[command.to_sym] || lambda { |*_| \"+OK\" }).call(*args)\n end\n end\n\n sleep 1 # Give time for the socket to start listening.\n\n yield\n\n ensure\n if pid\n Process.kill(\"TERM\", pid)\n Process.wait(pid)\n end\n end\n end", "code_tokens": ["def", "redis_mock", "(", "replies", "=", "{", "}", ")", "begin", "pid", "=", "fork", "do", "trap", "(", "\"TERM\"", ")", "{", "exit", "}", "RedisMock", ".", "start", "do", "|", "command", ",", "*", "args", "|", "(", "replies", "[", "command", ".", "to_sym", "]", "||", "lambda", "{", "|", "*", "_", "|", "\"+OK\"", "}", ")", ".", "call", "(", "args", ")", "end", "end", "sleep", "1", "# Give time for the socket to start listening.", "yield", "ensure", "if", "pid", "Process", ".", "kill", "(", "\"TERM\"", ",", "pid", ")", "Process", ".", "wait", "(", "pid", ")", "end", "end", "end"], "docstring": "Forks the current process and starts a new mock Redis server on\n port 6380.\n\n The server will reply with a `+OK` to all commands, but you can\n customize it by providing a hash. For example:\n\n redis_mock(:ping => lambda { \"+PONG\" }) do\n assert_equal \"PONG\", Redis.new(:port => 6380).ping\n end", "docstring_tokens": ["Forks", "the", "current", "process", "and", "starts", "a", "new", "mock", "Redis", "server", "on", "port", "6380", "."], "sha": "c9eac4b938a1c3d4fda1ccfad6e0373037fbee99", "url": "https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/spec/support/redis_mock.rb#L43-L63", "partition": "valid"} {"repo": "mloughran/em-hiredis", "path": "lib/em-hiredis/base_client.rb", "func_name": "EventMachine::Hiredis.BaseClient.configure", "original_string": "def configure(uri_string)\n uri = URI(uri_string)\n\n if uri.scheme == \"unix\"\n @host = uri.path\n @port = nil\n else\n @host = uri.host\n @port = uri.port\n @password = uri.password\n path = uri.path[1..-1]\n @db = path.to_i # Empty path => 0\n end\n end", "language": "ruby", "code": "def configure(uri_string)\n uri = URI(uri_string)\n\n if uri.scheme == \"unix\"\n @host = uri.path\n @port = nil\n else\n @host = uri.host\n @port = uri.port\n @password = uri.password\n path = uri.path[1..-1]\n @db = path.to_i # Empty path => 0\n end\n end", "code_tokens": ["def", "configure", "(", "uri_string", ")", "uri", "=", "URI", "(", "uri_string", ")", "if", "uri", ".", "scheme", "==", "\"unix\"", "@host", "=", "uri", ".", "path", "@port", "=", "nil", "else", "@host", "=", "uri", ".", "host", "@port", "=", "uri", ".", "port", "@password", "=", "uri", ".", "password", "path", "=", "uri", ".", "path", "[", "1", "..", "-", "1", "]", "@db", "=", "path", ".", "to_i", "# Empty path => 0", "end", "end"], "docstring": "Configure the redis connection to use\n\n In usual operation, the uri should be passed to initialize. This method\n is useful for example when failing over to a slave connection at runtime", "docstring_tokens": ["Configure", "the", "redis", "connection", "to", "use"], "sha": "c9eac4b938a1c3d4fda1ccfad6e0373037fbee99", "url": "https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/base_client.rb#L44-L57", "partition": "valid"} {"repo": "mloughran/em-hiredis", "path": "lib/em-hiredis/base_client.rb", "func_name": "EventMachine::Hiredis.BaseClient.reconnect!", "original_string": "def reconnect!(new_uri = nil)\n @connection.close_connection\n configure(new_uri) if new_uri\n @auto_reconnect = true\n EM.next_tick { reconnect_connection }\n end", "language": "ruby", "code": "def reconnect!(new_uri = nil)\n @connection.close_connection\n configure(new_uri) if new_uri\n @auto_reconnect = true\n EM.next_tick { reconnect_connection }\n end", "code_tokens": ["def", "reconnect!", "(", "new_uri", "=", "nil", ")", "@connection", ".", "close_connection", "configure", "(", "new_uri", ")", "if", "new_uri", "@auto_reconnect", "=", "true", "EM", ".", "next_tick", "{", "reconnect_connection", "}", "end"], "docstring": "Disconnect then reconnect the redis connection.\n\n Pass optional uri - e.g. to connect to a different redis server.\n Any pending redis commands will be failed, but during the reconnection\n new commands will be queued and sent after connected.", "docstring_tokens": ["Disconnect", "then", "reconnect", "the", "redis", "connection", "."], "sha": "c9eac4b938a1c3d4fda1ccfad6e0373037fbee99", "url": "https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/base_client.rb#L65-L70", "partition": "valid"} {"repo": "mloughran/em-hiredis", "path": "lib/em-hiredis/base_client.rb", "func_name": "EventMachine::Hiredis.BaseClient.configure_inactivity_check", "original_string": "def configure_inactivity_check(trigger_secs, response_timeout)\n raise ArgumentError('trigger_secs must be > 0') unless trigger_secs.to_i > 0\n raise ArgumentError('response_timeout must be > 0') unless response_timeout.to_i > 0\n\n @inactivity_trigger_secs = trigger_secs.to_i\n @inactivity_response_timeout = response_timeout.to_i\n\n # Start the inactivity check now only if we're already conected, otherwise\n # the connected event will schedule it.\n schedule_inactivity_checks if @connected\n end", "language": "ruby", "code": "def configure_inactivity_check(trigger_secs, response_timeout)\n raise ArgumentError('trigger_secs must be > 0') unless trigger_secs.to_i > 0\n raise ArgumentError('response_timeout must be > 0') unless response_timeout.to_i > 0\n\n @inactivity_trigger_secs = trigger_secs.to_i\n @inactivity_response_timeout = response_timeout.to_i\n\n # Start the inactivity check now only if we're already conected, otherwise\n # the connected event will schedule it.\n schedule_inactivity_checks if @connected\n end", "code_tokens": ["def", "configure_inactivity_check", "(", "trigger_secs", ",", "response_timeout", ")", "raise", "ArgumentError", "(", "'trigger_secs must be > 0'", ")", "unless", "trigger_secs", ".", "to_i", ">", "0", "raise", "ArgumentError", "(", "'response_timeout must be > 0'", ")", "unless", "response_timeout", ".", "to_i", ">", "0", "@inactivity_trigger_secs", "=", "trigger_secs", ".", "to_i", "@inactivity_response_timeout", "=", "response_timeout", ".", "to_i", "# Start the inactivity check now only if we're already conected, otherwise", "# the connected event will schedule it.", "schedule_inactivity_checks", "if", "@connected", "end"], "docstring": "Starts an inactivity checker which will ping redis if nothing has been\n heard on the connection for `trigger_secs` seconds and forces a reconnect\n after a further `response_timeout` seconds if we still don't hear anything.", "docstring_tokens": ["Starts", "an", "inactivity", "checker", "which", "will", "ping", "redis", "if", "nothing", "has", "been", "heard", "on", "the", "connection", "for", "trigger_secs", "seconds", "and", "forces", "a", "reconnect", "after", "a", "further", "response_timeout", "seconds", "if", "we", "still", "don", "t", "hear", "anything", "."], "sha": "c9eac4b938a1c3d4fda1ccfad6e0373037fbee99", "url": "https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/base_client.rb#L193-L203", "partition": "valid"} {"repo": "mloughran/em-hiredis", "path": "lib/em-hiredis/pubsub_client.rb", "func_name": "EventMachine::Hiredis.PubsubClient.subscribe", "original_string": "def subscribe(channel, proc = nil, &block)\n if cb = proc || block\n @sub_callbacks[channel] << cb\n end\n @subs << channel\n raw_send_command(:subscribe, [channel])\n return pubsub_deferrable(channel)\n end", "language": "ruby", "code": "def subscribe(channel, proc = nil, &block)\n if cb = proc || block\n @sub_callbacks[channel] << cb\n end\n @subs << channel\n raw_send_command(:subscribe, [channel])\n return pubsub_deferrable(channel)\n end", "code_tokens": ["def", "subscribe", "(", "channel", ",", "proc", "=", "nil", ",", "&", "block", ")", "if", "cb", "=", "proc", "||", "block", "@sub_callbacks", "[", "channel", "]", "<<", "cb", "end", "@subs", "<<", "channel", "raw_send_command", "(", ":subscribe", ",", "[", "channel", "]", ")", "return", "pubsub_deferrable", "(", "channel", ")", "end"], "docstring": "Subscribe to a pubsub channel\n\n If an optional proc / block is provided then it will be called when a\n message is received on this channel\n\n @return [Deferrable] Redis subscribe call", "docstring_tokens": ["Subscribe", "to", "a", "pubsub", "channel"], "sha": "c9eac4b938a1c3d4fda1ccfad6e0373037fbee99", "url": "https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/pubsub_client.rb#L33-L40", "partition": "valid"} {"repo": "mloughran/em-hiredis", "path": "lib/em-hiredis/pubsub_client.rb", "func_name": "EventMachine::Hiredis.PubsubClient.unsubscribe", "original_string": "def unsubscribe(channel)\n @sub_callbacks.delete(channel)\n @subs.delete(channel)\n raw_send_command(:unsubscribe, [channel])\n return pubsub_deferrable(channel)\n end", "language": "ruby", "code": "def unsubscribe(channel)\n @sub_callbacks.delete(channel)\n @subs.delete(channel)\n raw_send_command(:unsubscribe, [channel])\n return pubsub_deferrable(channel)\n end", "code_tokens": ["def", "unsubscribe", "(", "channel", ")", "@sub_callbacks", ".", "delete", "(", "channel", ")", "@subs", ".", "delete", "(", "channel", ")", "raw_send_command", "(", ":unsubscribe", ",", "[", "channel", "]", ")", "return", "pubsub_deferrable", "(", "channel", ")", "end"], "docstring": "Unsubscribe all callbacks for a given channel\n\n @return [Deferrable] Redis unsubscribe call", "docstring_tokens": ["Unsubscribe", "all", "callbacks", "for", "a", "given", "channel"], "sha": "c9eac4b938a1c3d4fda1ccfad6e0373037fbee99", "url": "https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/pubsub_client.rb#L46-L51", "partition": "valid"} {"repo": "mloughran/em-hiredis", "path": "lib/em-hiredis/pubsub_client.rb", "func_name": "EventMachine::Hiredis.PubsubClient.unsubscribe_proc", "original_string": "def unsubscribe_proc(channel, proc)\n df = EM::DefaultDeferrable.new\n if @sub_callbacks[channel].delete(proc)\n if @sub_callbacks[channel].any?\n # Succeed deferrable immediately - no need to unsubscribe\n df.succeed\n else\n unsubscribe(channel).callback { |_|\n df.succeed\n }\n end\n else\n df.fail\n end\n return df\n end", "language": "ruby", "code": "def unsubscribe_proc(channel, proc)\n df = EM::DefaultDeferrable.new\n if @sub_callbacks[channel].delete(proc)\n if @sub_callbacks[channel].any?\n # Succeed deferrable immediately - no need to unsubscribe\n df.succeed\n else\n unsubscribe(channel).callback { |_|\n df.succeed\n }\n end\n else\n df.fail\n end\n return df\n end", "code_tokens": ["def", "unsubscribe_proc", "(", "channel", ",", "proc", ")", "df", "=", "EM", "::", "DefaultDeferrable", ".", "new", "if", "@sub_callbacks", "[", "channel", "]", ".", "delete", "(", "proc", ")", "if", "@sub_callbacks", "[", "channel", "]", ".", "any?", "# Succeed deferrable immediately - no need to unsubscribe", "df", ".", "succeed", "else", "unsubscribe", "(", "channel", ")", ".", "callback", "{", "|", "_", "|", "df", ".", "succeed", "}", "end", "else", "df", ".", "fail", "end", "return", "df", "end"], "docstring": "Unsubscribe a given callback from a channel. Will unsubscribe from redis\n if there are no remaining subscriptions on this channel\n\n @return [Deferrable] Succeeds when the unsubscribe has completed or\n fails if callback could not be found. Note that success may happen\n immediately in the case that there are other callbacks for the same\n channel (and therefore no unsubscription from redis is necessary)", "docstring_tokens": ["Unsubscribe", "a", "given", "callback", "from", "a", "channel", ".", "Will", "unsubscribe", "from", "redis", "if", "there", "are", "no", "remaining", "subscriptions", "on", "this", "channel"], "sha": "c9eac4b938a1c3d4fda1ccfad6e0373037fbee99", "url": "https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/pubsub_client.rb#L61-L76", "partition": "valid"} {"repo": "mloughran/em-hiredis", "path": "lib/em-hiredis/pubsub_client.rb", "func_name": "EventMachine::Hiredis.PubsubClient.psubscribe", "original_string": "def psubscribe(pattern, proc = nil, &block)\n if cb = proc || block\n @psub_callbacks[pattern] << cb\n end\n @psubs << pattern\n raw_send_command(:psubscribe, [pattern])\n return pubsub_deferrable(pattern)\n end", "language": "ruby", "code": "def psubscribe(pattern, proc = nil, &block)\n if cb = proc || block\n @psub_callbacks[pattern] << cb\n end\n @psubs << pattern\n raw_send_command(:psubscribe, [pattern])\n return pubsub_deferrable(pattern)\n end", "code_tokens": ["def", "psubscribe", "(", "pattern", ",", "proc", "=", "nil", ",", "&", "block", ")", "if", "cb", "=", "proc", "||", "block", "@psub_callbacks", "[", "pattern", "]", "<<", "cb", "end", "@psubs", "<<", "pattern", "raw_send_command", "(", ":psubscribe", ",", "[", "pattern", "]", ")", "return", "pubsub_deferrable", "(", "pattern", ")", "end"], "docstring": "Pattern subscribe to a pubsub channel\n\n If an optional proc / block is provided then it will be called (with the\n channel name and message) when a message is received on a matching\n channel\n\n @return [Deferrable] Redis psubscribe call", "docstring_tokens": ["Pattern", "subscribe", "to", "a", "pubsub", "channel"], "sha": "c9eac4b938a1c3d4fda1ccfad6e0373037fbee99", "url": "https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/pubsub_client.rb#L86-L93", "partition": "valid"} {"repo": "mloughran/em-hiredis", "path": "lib/em-hiredis/pubsub_client.rb", "func_name": "EventMachine::Hiredis.PubsubClient.punsubscribe", "original_string": "def punsubscribe(pattern)\n @psub_callbacks.delete(pattern)\n @psubs.delete(pattern)\n raw_send_command(:punsubscribe, [pattern])\n return pubsub_deferrable(pattern)\n end", "language": "ruby", "code": "def punsubscribe(pattern)\n @psub_callbacks.delete(pattern)\n @psubs.delete(pattern)\n raw_send_command(:punsubscribe, [pattern])\n return pubsub_deferrable(pattern)\n end", "code_tokens": ["def", "punsubscribe", "(", "pattern", ")", "@psub_callbacks", ".", "delete", "(", "pattern", ")", "@psubs", ".", "delete", "(", "pattern", ")", "raw_send_command", "(", ":punsubscribe", ",", "[", "pattern", "]", ")", "return", "pubsub_deferrable", "(", "pattern", ")", "end"], "docstring": "Pattern unsubscribe all callbacks for a given pattern\n\n @return [Deferrable] Redis punsubscribe call", "docstring_tokens": ["Pattern", "unsubscribe", "all", "callbacks", "for", "a", "given", "pattern"], "sha": "c9eac4b938a1c3d4fda1ccfad6e0373037fbee99", "url": "https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/pubsub_client.rb#L99-L104", "partition": "valid"} {"repo": "mloughran/em-hiredis", "path": "lib/em-hiredis/pubsub_client.rb", "func_name": "EventMachine::Hiredis.PubsubClient.punsubscribe_proc", "original_string": "def punsubscribe_proc(pattern, proc)\n df = EM::DefaultDeferrable.new\n if @psub_callbacks[pattern].delete(proc)\n if @psub_callbacks[pattern].any?\n # Succeed deferrable immediately - no need to punsubscribe\n df.succeed\n else\n punsubscribe(pattern).callback { |_|\n df.succeed\n }\n end\n else\n df.fail\n end\n return df\n end", "language": "ruby", "code": "def punsubscribe_proc(pattern, proc)\n df = EM::DefaultDeferrable.new\n if @psub_callbacks[pattern].delete(proc)\n if @psub_callbacks[pattern].any?\n # Succeed deferrable immediately - no need to punsubscribe\n df.succeed\n else\n punsubscribe(pattern).callback { |_|\n df.succeed\n }\n end\n else\n df.fail\n end\n return df\n end", "code_tokens": ["def", "punsubscribe_proc", "(", "pattern", ",", "proc", ")", "df", "=", "EM", "::", "DefaultDeferrable", ".", "new", "if", "@psub_callbacks", "[", "pattern", "]", ".", "delete", "(", "proc", ")", "if", "@psub_callbacks", "[", "pattern", "]", ".", "any?", "# Succeed deferrable immediately - no need to punsubscribe", "df", ".", "succeed", "else", "punsubscribe", "(", "pattern", ")", ".", "callback", "{", "|", "_", "|", "df", ".", "succeed", "}", "end", "else", "df", ".", "fail", "end", "return", "df", "end"], "docstring": "Unsubscribe a given callback from a pattern. Will unsubscribe from redis\n if there are no remaining subscriptions on this pattern\n\n @return [Deferrable] Succeeds when the punsubscribe has completed or\n fails if callback could not be found. Note that success may happen\n immediately in the case that there are other callbacks for the same\n pattern (and therefore no punsubscription from redis is necessary)", "docstring_tokens": ["Unsubscribe", "a", "given", "callback", "from", "a", "pattern", ".", "Will", "unsubscribe", "from", "redis", "if", "there", "are", "no", "remaining", "subscriptions", "on", "this", "pattern"], "sha": "c9eac4b938a1c3d4fda1ccfad6e0373037fbee99", "url": "https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/pubsub_client.rb#L114-L129", "partition": "valid"} {"repo": "mloughran/em-hiredis", "path": "lib/em-hiredis/pubsub_client.rb", "func_name": "EventMachine::Hiredis.PubsubClient.raw_send_command", "original_string": "def raw_send_command(sym, args)\n if @connected\n @connection.send_command(sym, args)\n else\n callback do\n @connection.send_command(sym, args)\n end\n end\n return nil\n end", "language": "ruby", "code": "def raw_send_command(sym, args)\n if @connected\n @connection.send_command(sym, args)\n else\n callback do\n @connection.send_command(sym, args)\n end\n end\n return nil\n end", "code_tokens": ["def", "raw_send_command", "(", "sym", ",", "args", ")", "if", "@connected", "@connection", ".", "send_command", "(", "sym", ",", "args", ")", "else", "callback", "do", "@connection", ".", "send_command", "(", "sym", ",", "args", ")", "end", "end", "return", "nil", "end"], "docstring": "Send a command to redis without adding a deferrable for it. This is\n useful for commands for which replies work or need to be treated\n differently", "docstring_tokens": ["Send", "a", "command", "to", "redis", "without", "adding", "a", "deferrable", "for", "it", ".", "This", "is", "useful", "for", "commands", "for", "which", "replies", "work", "or", "need", "to", "be", "treated", "differently"], "sha": "c9eac4b938a1c3d4fda1ccfad6e0373037fbee99", "url": "https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/pubsub_client.rb#L149-L158", "partition": "valid"} {"repo": "alphagov/gds-api-adapters", "path": "lib/gds_api/search.rb", "func_name": "GdsApi.Search.batch_search", "original_string": "def batch_search(searches, additional_headers = {})\n url_friendly_searches = searches.each_with_index.map do |search, index|\n { index => search }\n end\n searches_query = { search: url_friendly_searches }\n request_url = \"#{base_url}/batch_search.json?#{Rack::Utils.build_nested_query(searches_query)}\"\n get_json(request_url, additional_headers)\n end", "language": "ruby", "code": "def batch_search(searches, additional_headers = {})\n url_friendly_searches = searches.each_with_index.map do |search, index|\n { index => search }\n end\n searches_query = { search: url_friendly_searches }\n request_url = \"#{base_url}/batch_search.json?#{Rack::Utils.build_nested_query(searches_query)}\"\n get_json(request_url, additional_headers)\n end", "code_tokens": ["def", "batch_search", "(", "searches", ",", "additional_headers", "=", "{", "}", ")", "url_friendly_searches", "=", "searches", ".", "each_with_index", ".", "map", "do", "|", "search", ",", "index", "|", "{", "index", "=>", "search", "}", "end", "searches_query", "=", "{", "search", ":", "url_friendly_searches", "}", "request_url", "=", "\"#{base_url}/batch_search.json?#{Rack::Utils.build_nested_query(searches_query)}\"", "get_json", "(", "request_url", ",", "additional_headers", ")", "end"], "docstring": "Perform a batch search.\n\n @param searches [Array] An array valid search queries. Maximum of 6. See search-api documentation for options.\n\n # @see https://github.com/alphagov/search-api/blob/master/doc/search-api.md", "docstring_tokens": ["Perform", "a", "batch", "search", "."], "sha": "94bb27e154907939d4d96d3ab330a61c8bdf1fb5", "url": "https://github.com/alphagov/gds-api-adapters/blob/94bb27e154907939d4d96d3ab330a61c8bdf1fb5/lib/gds_api/search.rb#L81-L88", "partition": "valid"} {"repo": "alphagov/gds-api-adapters", "path": "lib/gds_api/search.rb", "func_name": "GdsApi.Search.search_enum", "original_string": "def search_enum(args, page_size: 100, additional_headers: {})\n Enumerator.new do |yielder|\n (0..Float::INFINITY).step(page_size).each do |index|\n search_params = args.merge(start: index.to_i, count: page_size)\n results = search(search_params, additional_headers).to_h.fetch('results', [])\n results.each do |result|\n yielder << result\n end\n if results.count < page_size\n break\n end\n end\n end\n end", "language": "ruby", "code": "def search_enum(args, page_size: 100, additional_headers: {})\n Enumerator.new do |yielder|\n (0..Float::INFINITY).step(page_size).each do |index|\n search_params = args.merge(start: index.to_i, count: page_size)\n results = search(search_params, additional_headers).to_h.fetch('results', [])\n results.each do |result|\n yielder << result\n end\n if results.count < page_size\n break\n end\n end\n end\n end", "code_tokens": ["def", "search_enum", "(", "args", ",", "page_size", ":", "100", ",", "additional_headers", ":", "{", "}", ")", "Enumerator", ".", "new", "do", "|", "yielder", "|", "(", "0", "..", "Float", "::", "INFINITY", ")", ".", "step", "(", "page_size", ")", ".", "each", "do", "|", "index", "|", "search_params", "=", "args", ".", "merge", "(", "start", ":", "index", ".", "to_i", ",", "count", ":", "page_size", ")", "results", "=", "search", "(", "search_params", ",", "additional_headers", ")", ".", "to_h", ".", "fetch", "(", "'results'", ",", "[", "]", ")", "results", ".", "each", "do", "|", "result", "|", "yielder", "<<", "result", "end", "if", "results", ".", "count", "<", "page_size", "break", "end", "end", "end", "end"], "docstring": "Perform a search, returning the results as an enumerator.\n\n The enumerator abstracts away search-api's pagination and fetches new pages when\n necessary.\n\n @param args [Hash] A valid search query. See search-api documentation for options.\n @param page_size [Integer] Number of results in each page.\n\n @see https://github.com/alphagov/search-api/blob/master/doc/search-api.md", "docstring_tokens": ["Perform", "a", "search", "returning", "the", "results", "as", "an", "enumerator", "."], "sha": "94bb27e154907939d4d96d3ab330a61c8bdf1fb5", "url": "https://github.com/alphagov/gds-api-adapters/blob/94bb27e154907939d4d96d3ab330a61c8bdf1fb5/lib/gds_api/search.rb#L99-L112", "partition": "valid"} {"repo": "alphagov/gds-api-adapters", "path": "lib/gds_api/search.rb", "func_name": "GdsApi.Search.advanced_search", "original_string": "def advanced_search(args)\n raise ArgumentError.new(\"Args cannot be blank\") if args.nil? || args.empty?\n\n request_path = \"#{base_url}/advanced_search?#{Rack::Utils.build_nested_query(args)}\"\n get_json(request_path)\n end", "language": "ruby", "code": "def advanced_search(args)\n raise ArgumentError.new(\"Args cannot be blank\") if args.nil? || args.empty?\n\n request_path = \"#{base_url}/advanced_search?#{Rack::Utils.build_nested_query(args)}\"\n get_json(request_path)\n end", "code_tokens": ["def", "advanced_search", "(", "args", ")", "raise", "ArgumentError", ".", "new", "(", "\"Args cannot be blank\"", ")", "if", "args", ".", "nil?", "||", "args", ".", "empty?", "request_path", "=", "\"#{base_url}/advanced_search?#{Rack::Utils.build_nested_query(args)}\"", "get_json", "(", "request_path", ")", "end"], "docstring": "Advanced search.\n\n @deprecated Only in use by Whitehall. Use the `#search` method.", "docstring_tokens": ["Advanced", "search", "."], "sha": "94bb27e154907939d4d96d3ab330a61c8bdf1fb5", "url": "https://github.com/alphagov/gds-api-adapters/blob/94bb27e154907939d4d96d3ab330a61c8bdf1fb5/lib/gds_api/search.rb#L117-L122", "partition": "valid"} {"repo": "bitpay/ruby-client", "path": "lib/bitpay/rest_connector.rb", "func_name": "BitPay.RestConnector.process_request", "original_string": "def process_request(request)\n request['User-Agent'] = @user_agent\n request['Content-Type'] = 'application/json'\n request['X-BitPay-Plugin-Info'] = 'Rubylib' + VERSION\n\n begin\n response = @https.request request\n rescue => error\n raise BitPay::ConnectionError, \"#{error.message}\"\n end\n\n if response.kind_of? Net::HTTPSuccess\n return JSON.parse(response.body)\n elsif JSON.parse(response.body)[\"error\"]\n raise(BitPayError, \"#{response.code}: #{JSON.parse(response.body)['error']}\")\n else\n raise BitPayError, \"#{response.code}: #{JSON.parse(response.body)}\"\n end\n\n end", "language": "ruby", "code": "def process_request(request)\n request['User-Agent'] = @user_agent\n request['Content-Type'] = 'application/json'\n request['X-BitPay-Plugin-Info'] = 'Rubylib' + VERSION\n\n begin\n response = @https.request request\n rescue => error\n raise BitPay::ConnectionError, \"#{error.message}\"\n end\n\n if response.kind_of? Net::HTTPSuccess\n return JSON.parse(response.body)\n elsif JSON.parse(response.body)[\"error\"]\n raise(BitPayError, \"#{response.code}: #{JSON.parse(response.body)['error']}\")\n else\n raise BitPayError, \"#{response.code}: #{JSON.parse(response.body)}\"\n end\n\n end", "code_tokens": ["def", "process_request", "(", "request", ")", "request", "[", "'User-Agent'", "]", "=", "@user_agent", "request", "[", "'Content-Type'", "]", "=", "'application/json'", "request", "[", "'X-BitPay-Plugin-Info'", "]", "=", "'Rubylib'", "+", "VERSION", "begin", "response", "=", "@https", ".", "request", "request", "rescue", "=>", "error", "raise", "BitPay", "::", "ConnectionError", ",", "\"#{error.message}\"", "end", "if", "response", ".", "kind_of?", "Net", "::", "HTTPSuccess", "return", "JSON", ".", "parse", "(", "response", ".", "body", ")", "elsif", "JSON", ".", "parse", "(", "response", ".", "body", ")", "[", "\"error\"", "]", "raise", "(", "BitPayError", ",", "\"#{response.code}: #{JSON.parse(response.body)['error']}\"", ")", "else", "raise", "BitPayError", ",", "\"#{response.code}: #{JSON.parse(response.body)}\"", "end", "end"], "docstring": "Processes HTTP Request and returns parsed response\n Otherwise throws error", "docstring_tokens": ["Processes", "HTTP", "Request", "and", "returns", "parsed", "response", "Otherwise", "throws", "error"], "sha": "019140f04959589e7137c9b81cc1b848e15ebbe6", "url": "https://github.com/bitpay/ruby-client/blob/019140f04959589e7137c9b81cc1b848e15ebbe6/lib/bitpay/rest_connector.rb#L59-L78", "partition": "valid"} {"repo": "bitpay/ruby-client", "path": "lib/bitpay/rest_connector.rb", "func_name": "BitPay.RestConnector.refresh_tokens", "original_string": "def refresh_tokens\n response = get(path: 'tokens')[\"data\"]\n token_array = response || {}\n tokens = {}\n token_array.each do |t|\n tokens[t.keys.first] = t.values.first\n end\n @tokens = tokens\n return tokens\n end", "language": "ruby", "code": "def refresh_tokens\n response = get(path: 'tokens')[\"data\"]\n token_array = response || {}\n tokens = {}\n token_array.each do |t|\n tokens[t.keys.first] = t.values.first\n end\n @tokens = tokens\n return tokens\n end", "code_tokens": ["def", "refresh_tokens", "response", "=", "get", "(", "path", ":", "'tokens'", ")", "[", "\"data\"", "]", "token_array", "=", "response", "||", "{", "}", "tokens", "=", "{", "}", "token_array", ".", "each", "do", "|", "t", "|", "tokens", "[", "t", ".", "keys", ".", "first", "]", "=", "t", ".", "values", ".", "first", "end", "@tokens", "=", "tokens", "return", "tokens", "end"], "docstring": "Fetches the tokens hash from the server and\n updates @tokens", "docstring_tokens": ["Fetches", "the", "tokens", "hash", "from", "the", "server", "and", "updates"], "sha": "019140f04959589e7137c9b81cc1b848e15ebbe6", "url": "https://github.com/bitpay/ruby-client/blob/019140f04959589e7137c9b81cc1b848e15ebbe6/lib/bitpay/rest_connector.rb#L83-L92", "partition": "valid"} {"repo": "rdy/fixture_builder", "path": "lib/fixture_builder/builder.rb", "func_name": "FixtureBuilder.Builder.fixtures_class", "original_string": "def fixtures_class\n if defined?(ActiveRecord::FixtureSet)\n ActiveRecord::FixtureSet\n elsif defined?(ActiveRecord::Fixtures)\n ActiveRecord::Fixtures\n else\n ::Fixtures\n end\n end", "language": "ruby", "code": "def fixtures_class\n if defined?(ActiveRecord::FixtureSet)\n ActiveRecord::FixtureSet\n elsif defined?(ActiveRecord::Fixtures)\n ActiveRecord::Fixtures\n else\n ::Fixtures\n end\n end", "code_tokens": ["def", "fixtures_class", "if", "defined?", "(", "ActiveRecord", "::", "FixtureSet", ")", "ActiveRecord", "::", "FixtureSet", "elsif", "defined?", "(", "ActiveRecord", "::", "Fixtures", ")", "ActiveRecord", "::", "Fixtures", "else", "::", "Fixtures", "end", "end"], "docstring": "Rails 3.0 and 3.1+ support", "docstring_tokens": ["Rails", "3", ".", "0", "and", "3", ".", "1", "+", "support"], "sha": "35d3ebd7851125bd1fcfd3a71b97dc71b8c64622", "url": "https://github.com/rdy/fixture_builder/blob/35d3ebd7851125bd1fcfd3a71b97dc71b8c64622/lib/fixture_builder/builder.rb#L36-L44", "partition": "valid"} {"repo": "stevenallen05/osbourne", "path": "lib/osbourne/message.rb", "func_name": "Osbourne.Message.sns?", "original_string": "def sns?\n json_body.is_a?(Hash) && (%w[Message Type TopicArn MessageId] - json_body.keys).empty?\n end", "language": "ruby", "code": "def sns?\n json_body.is_a?(Hash) && (%w[Message Type TopicArn MessageId] - json_body.keys).empty?\n end", "code_tokens": ["def", "sns?", "json_body", ".", "is_a?", "(", "Hash", ")", "&&", "(", "%w[", "Message", "Type", "TopicArn", "MessageId", "]", "-", "json_body", ".", "keys", ")", ".", "empty?", "end"], "docstring": "Just because a message was recieved via SQS, doesn't mean it was originally broadcast via SNS\n @return [Boolean] Was the message broadcast via SNS?", "docstring_tokens": ["Just", "because", "a", "message", "was", "recieved", "via", "SQS", "doesn", "t", "mean", "it", "was", "originally", "broadcast", "via", "SNS"], "sha": "b28c46ceb6e60bd685e4063d7634f5ae2e7192c9", "url": "https://github.com/stevenallen05/osbourne/blob/b28c46ceb6e60bd685e4063d7634f5ae2e7192c9/lib/osbourne/message.rb#L78-L80", "partition": "valid"} {"repo": "jemmyw/Qif", "path": "lib/qif/transaction.rb", "func_name": "Qif.Transaction.to_s", "original_string": "def to_s(format = 'dd/mm/yyyy')\n SUPPORTED_FIELDS.collect do |k,v|\n next unless current = instance_variable_get(\"@#{k}\")\n field = v.keys.first\n case current.class.to_s\n when \"Time\", \"Date\", \"DateTime\"\n \"#{field}#{DateFormat.new(format).format(current)}\"\n when \"Float\"\n \"#{field}#{'%.2f'%current}\"\n when \"String\"\n current.split(\"\\n\").collect {|x| \"#{field}#{x}\" }\n else\n \"#{field}#{current}\"\n end\n end.concat(@splits.collect{|s| s.to_s}).flatten.compact.join(\"\\n\")\n end", "language": "ruby", "code": "def to_s(format = 'dd/mm/yyyy')\n SUPPORTED_FIELDS.collect do |k,v|\n next unless current = instance_variable_get(\"@#{k}\")\n field = v.keys.first\n case current.class.to_s\n when \"Time\", \"Date\", \"DateTime\"\n \"#{field}#{DateFormat.new(format).format(current)}\"\n when \"Float\"\n \"#{field}#{'%.2f'%current}\"\n when \"String\"\n current.split(\"\\n\").collect {|x| \"#{field}#{x}\" }\n else\n \"#{field}#{current}\"\n end\n end.concat(@splits.collect{|s| s.to_s}).flatten.compact.join(\"\\n\")\n end", "code_tokens": ["def", "to_s", "(", "format", "=", "'dd/mm/yyyy'", ")", "SUPPORTED_FIELDS", ".", "collect", "do", "|", "k", ",", "v", "|", "next", "unless", "current", "=", "instance_variable_get", "(", "\"@#{k}\"", ")", "field", "=", "v", ".", "keys", ".", "first", "case", "current", ".", "class", ".", "to_s", "when", "\"Time\"", ",", "\"Date\"", ",", "\"DateTime\"", "\"#{field}#{DateFormat.new(format).format(current)}\"", "when", "\"Float\"", "\"#{field}#{'%.2f'%current}\"", "when", "\"String\"", "current", ".", "split", "(", "\"\\n\"", ")", ".", "collect", "{", "|", "x", "|", "\"#{field}#{x}\"", "}", "else", "\"#{field}#{current}\"", "end", "end", ".", "concat", "(", "@splits", ".", "collect", "{", "|", "s", "|", "s", ".", "to_s", "}", ")", ".", "flatten", ".", "compact", ".", "join", "(", "\"\\n\"", ")", "end"], "docstring": "Returns a representation of the transaction as it\n would appear in a qif file.", "docstring_tokens": ["Returns", "a", "representation", "of", "the", "transaction", "as", "it", "would", "appear", "in", "a", "qif", "file", "."], "sha": "87fe5ba13b980617a8b517c3f49885c6ea1b3993", "url": "https://github.com/jemmyw/Qif/blob/87fe5ba13b980617a8b517c3f49885c6ea1b3993/lib/qif/transaction.rb#L43-L58", "partition": "valid"} {"repo": "zendesk/samlr", "path": "lib/samlr/signature.rb", "func_name": "Samlr.Signature.verify_digests!", "original_string": "def verify_digests!\n references.each do |reference|\n node = referenced_node(reference.uri)\n canoned = node.canonicalize(C14N, reference.namespaces)\n digest = reference.digest_method.digest(canoned)\n\n if digest != reference.decoded_digest_value\n raise SignatureError.new(\"Reference validation error: Digest mismatch for #{reference.uri}\")\n end\n end\n end", "language": "ruby", "code": "def verify_digests!\n references.each do |reference|\n node = referenced_node(reference.uri)\n canoned = node.canonicalize(C14N, reference.namespaces)\n digest = reference.digest_method.digest(canoned)\n\n if digest != reference.decoded_digest_value\n raise SignatureError.new(\"Reference validation error: Digest mismatch for #{reference.uri}\")\n end\n end\n end", "code_tokens": ["def", "verify_digests!", "references", ".", "each", "do", "|", "reference", "|", "node", "=", "referenced_node", "(", "reference", ".", "uri", ")", "canoned", "=", "node", ".", "canonicalize", "(", "C14N", ",", "reference", ".", "namespaces", ")", "digest", "=", "reference", ".", "digest_method", ".", "digest", "(", "canoned", ")", "if", "digest", "!=", "reference", ".", "decoded_digest_value", "raise", "SignatureError", ".", "new", "(", "\"Reference validation error: Digest mismatch for #{reference.uri}\"", ")", "end", "end", "end"], "docstring": "Tests that the document content has not been edited", "docstring_tokens": ["Tests", "that", "the", "document", "content", "has", "not", "been", "edited"], "sha": "521b5bfe4a35b6d72a780ab610dc7229294b2ea8", "url": "https://github.com/zendesk/samlr/blob/521b5bfe4a35b6d72a780ab610dc7229294b2ea8/lib/samlr/signature.rb#L68-L78", "partition": "valid"} {"repo": "zendesk/samlr", "path": "lib/samlr/signature.rb", "func_name": "Samlr.Signature.referenced_node", "original_string": "def referenced_node(id)\n nodes = document.xpath(\"//*[@ID='#{id}']\")\n\n if nodes.size != 1\n raise SignatureError.new(\"Reference validation error: Invalid element references\", \"Expected 1 element with id #{id}, found #{nodes.size}\")\n end\n\n nodes.first\n end", "language": "ruby", "code": "def referenced_node(id)\n nodes = document.xpath(\"//*[@ID='#{id}']\")\n\n if nodes.size != 1\n raise SignatureError.new(\"Reference validation error: Invalid element references\", \"Expected 1 element with id #{id}, found #{nodes.size}\")\n end\n\n nodes.first\n end", "code_tokens": ["def", "referenced_node", "(", "id", ")", "nodes", "=", "document", ".", "xpath", "(", "\"//*[@ID='#{id}']\"", ")", "if", "nodes", ".", "size", "!=", "1", "raise", "SignatureError", ".", "new", "(", "\"Reference validation error: Invalid element references\"", ",", "\"Expected 1 element with id #{id}, found #{nodes.size}\"", ")", "end", "nodes", ".", "first", "end"], "docstring": "Looks up node by id, checks that there's only a single node with a given id", "docstring_tokens": ["Looks", "up", "node", "by", "id", "checks", "that", "there", "s", "only", "a", "single", "node", "with", "a", "given", "id"], "sha": "521b5bfe4a35b6d72a780ab610dc7229294b2ea8", "url": "https://github.com/zendesk/samlr/blob/521b5bfe4a35b6d72a780ab610dc7229294b2ea8/lib/samlr/signature.rb#L91-L99", "partition": "valid"} {"repo": "zendesk/samlr", "path": "lib/samlr/response.rb", "func_name": "Samlr.Response.verify!", "original_string": "def verify!\n if signature.missing? && assertion.signature.missing?\n raise Samlr::SignatureError.new(\"Neither response nor assertion signed with a certificate\")\n end\n\n signature.verify! unless signature.missing?\n assertion.verify!\n\n true\n end", "language": "ruby", "code": "def verify!\n if signature.missing? && assertion.signature.missing?\n raise Samlr::SignatureError.new(\"Neither response nor assertion signed with a certificate\")\n end\n\n signature.verify! unless signature.missing?\n assertion.verify!\n\n true\n end", "code_tokens": ["def", "verify!", "if", "signature", ".", "missing?", "&&", "assertion", ".", "signature", ".", "missing?", "raise", "Samlr", "::", "SignatureError", ".", "new", "(", "\"Neither response nor assertion signed with a certificate\"", ")", "end", "signature", ".", "verify!", "unless", "signature", ".", "missing?", "assertion", ".", "verify!", "true", "end"], "docstring": "The verification process assumes that all signatures are enveloped. Since this process\n is destructive the document needs to verify itself first, and then any signed assertions", "docstring_tokens": ["The", "verification", "process", "assumes", "that", "all", "signatures", "are", "enveloped", ".", "Since", "this", "process", "is", "destructive", "the", "document", "needs", "to", "verify", "itself", "first", "and", "then", "any", "signed", "assertions"], "sha": "521b5bfe4a35b6d72a780ab610dc7229294b2ea8", "url": "https://github.com/zendesk/samlr/blob/521b5bfe4a35b6d72a780ab610dc7229294b2ea8/lib/samlr/response.rb#L20-L29", "partition": "valid"} {"repo": "saveriomiroddi/simple_scripting", "path": "lib/simple_scripting/argv.rb", "func_name": "SimpleScripting.Argv.decode_definition_and_options", "original_string": "def decode_definition_and_options(definition_and_options)\n # Only a hash (commands)\n if definition_and_options.size == 1 && definition_and_options.first.is_a?(Hash)\n options = definition_and_options.first.each_with_object({}) do |(key, value), current_options|\n current_options[key] = definition_and_options.first.delete(key) if key.is_a?(Symbol)\n end\n\n # If there is an empty hash left, we remove it, so it's not considered commands.\n #\n definition_and_options = [] if definition_and_options.first.empty?\n # Options passed\n elsif definition_and_options.last.is_a?(Hash)\n options = definition_and_options.pop\n # No options passed\n else\n options = {}\n end\n\n [definition_and_options, options]\n end", "language": "ruby", "code": "def decode_definition_and_options(definition_and_options)\n # Only a hash (commands)\n if definition_and_options.size == 1 && definition_and_options.first.is_a?(Hash)\n options = definition_and_options.first.each_with_object({}) do |(key, value), current_options|\n current_options[key] = definition_and_options.first.delete(key) if key.is_a?(Symbol)\n end\n\n # If there is an empty hash left, we remove it, so it's not considered commands.\n #\n definition_and_options = [] if definition_and_options.first.empty?\n # Options passed\n elsif definition_and_options.last.is_a?(Hash)\n options = definition_and_options.pop\n # No options passed\n else\n options = {}\n end\n\n [definition_and_options, options]\n end", "code_tokens": ["def", "decode_definition_and_options", "(", "definition_and_options", ")", "# Only a hash (commands)", "if", "definition_and_options", ".", "size", "==", "1", "&&", "definition_and_options", ".", "first", ".", "is_a?", "(", "Hash", ")", "options", "=", "definition_and_options", ".", "first", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "key", ",", "value", ")", ",", "current_options", "|", "current_options", "[", "key", "]", "=", "definition_and_options", ".", "first", ".", "delete", "(", "key", ")", "if", "key", ".", "is_a?", "(", "Symbol", ")", "end", "# If there is an empty hash left, we remove it, so it's not considered commands.", "#", "definition_and_options", "=", "[", "]", "if", "definition_and_options", ".", "first", ".", "empty?", "# Options passed", "elsif", "definition_and_options", ".", "last", ".", "is_a?", "(", "Hash", ")", "options", "=", "definition_and_options", ".", "pop", "# No options passed", "else", "options", "=", "{", "}", "end", "[", "definition_and_options", ",", "options", "]", "end"], "docstring": "This is trivial to define with named arguments, however, Ruby 2.6 removed the support for\n mixing strings and symbols as argument keys, so we're forced to perform manual decoding.\n The complexity of this code supports the rationale for the removal of the functionality.", "docstring_tokens": ["This", "is", "trivial", "to", "define", "with", "named", "arguments", "however", "Ruby", "2", ".", "6", "removed", "the", "support", "for", "mixing", "strings", "and", "symbols", "as", "argument", "keys", "so", "we", "re", "forced", "to", "perform", "manual", "decoding", ".", "The", "complexity", "of", "this", "code", "supports", "the", "rationale", "for", "the", "removal", "of", "the", "functionality", "."], "sha": "41f16671fe0611598741c1e719f884e057d276cd", "url": "https://github.com/saveriomiroddi/simple_scripting/blob/41f16671fe0611598741c1e719f884e057d276cd/lib/simple_scripting/argv.rb#L80-L99", "partition": "valid"} {"repo": "saveriomiroddi/simple_scripting", "path": "lib/simple_scripting/tab_completion.rb", "func_name": "SimpleScripting.TabCompletion.complete", "original_string": "def complete(execution_target, source_commandline=ENV.fetch('COMP_LINE'), cursor_position=ENV.fetch('COMP_POINT').to_i)\n commandline_processor = CommandlineProcessor.process_commandline(source_commandline, cursor_position, @switches_definition)\n\n if commandline_processor.completing_an_option?\n complete_option(commandline_processor, execution_target)\n elsif commandline_processor.parsing_error?\n return\n else # completing_a_value?\n complete_value(commandline_processor, execution_target)\n end\n end", "language": "ruby", "code": "def complete(execution_target, source_commandline=ENV.fetch('COMP_LINE'), cursor_position=ENV.fetch('COMP_POINT').to_i)\n commandline_processor = CommandlineProcessor.process_commandline(source_commandline, cursor_position, @switches_definition)\n\n if commandline_processor.completing_an_option?\n complete_option(commandline_processor, execution_target)\n elsif commandline_processor.parsing_error?\n return\n else # completing_a_value?\n complete_value(commandline_processor, execution_target)\n end\n end", "code_tokens": ["def", "complete", "(", "execution_target", ",", "source_commandline", "=", "ENV", ".", "fetch", "(", "'COMP_LINE'", ")", ",", "cursor_position", "=", "ENV", ".", "fetch", "(", "'COMP_POINT'", ")", ".", "to_i", ")", "commandline_processor", "=", "CommandlineProcessor", ".", "process_commandline", "(", "source_commandline", ",", "cursor_position", ",", "@switches_definition", ")", "if", "commandline_processor", ".", "completing_an_option?", "complete_option", "(", "commandline_processor", ",", "execution_target", ")", "elsif", "commandline_processor", ".", "parsing_error?", "return", "else", "# completing_a_value?", "complete_value", "(", "commandline_processor", ",", "execution_target", ")", "end", "end"], "docstring": "Currently, any completion suffix is ignored and stripped.", "docstring_tokens": ["Currently", "any", "completion", "suffix", "is", "ignored", "and", "stripped", "."], "sha": "41f16671fe0611598741c1e719f884e057d276cd", "url": "https://github.com/saveriomiroddi/simple_scripting/blob/41f16671fe0611598741c1e719f884e057d276cd/lib/simple_scripting/tab_completion.rb#L28-L38", "partition": "valid"} {"repo": "Malinskiy/danger-jacoco", "path": "lib/jacoco/plugin.rb", "func_name": "Danger.DangerJacoco.report", "original_string": "def report(path, report_url = '', delimiter = %r{\\/java\\/|\\/kotlin\\/})\n setup\n classes = classes(delimiter)\n\n parser = Jacoco::SAXParser.new(classes)\n Nokogiri::XML::SAX::Parser.new(parser).parse(File.open(path))\n\n total_covered = total_coverage(path)\n\n report_markdown = \"### JaCoCO Code Coverage #{total_covered[:covered]}% #{total_covered[:status]}\\n\"\n report_markdown << \"| Class | Covered | Meta | Status |\\n\"\n report_markdown << \"|:---|:---:|:---:|:---:|\\n\"\n class_coverage_above_minimum = markdown_class(parser, report_markdown, report_url)\n markdown(report_markdown)\n\n report_fails(class_coverage_above_minimum, total_covered)\n end", "language": "ruby", "code": "def report(path, report_url = '', delimiter = %r{\\/java\\/|\\/kotlin\\/})\n setup\n classes = classes(delimiter)\n\n parser = Jacoco::SAXParser.new(classes)\n Nokogiri::XML::SAX::Parser.new(parser).parse(File.open(path))\n\n total_covered = total_coverage(path)\n\n report_markdown = \"### JaCoCO Code Coverage #{total_covered[:covered]}% #{total_covered[:status]}\\n\"\n report_markdown << \"| Class | Covered | Meta | Status |\\n\"\n report_markdown << \"|:---|:---:|:---:|:---:|\\n\"\n class_coverage_above_minimum = markdown_class(parser, report_markdown, report_url)\n markdown(report_markdown)\n\n report_fails(class_coverage_above_minimum, total_covered)\n end", "code_tokens": ["def", "report", "(", "path", ",", "report_url", "=", "''", ",", "delimiter", "=", "%r{", "\\/", "\\/", "\\/", "\\/", "}", ")", "setup", "classes", "=", "classes", "(", "delimiter", ")", "parser", "=", "Jacoco", "::", "SAXParser", ".", "new", "(", "classes", ")", "Nokogiri", "::", "XML", "::", "SAX", "::", "Parser", ".", "new", "(", "parser", ")", ".", "parse", "(", "File", ".", "open", "(", "path", ")", ")", "total_covered", "=", "total_coverage", "(", "path", ")", "report_markdown", "=", "\"### JaCoCO Code Coverage #{total_covered[:covered]}% #{total_covered[:status]}\\n\"", "report_markdown", "<<", "\"| Class | Covered | Meta | Status |\\n\"", "report_markdown", "<<", "\"|:---|:---:|:---:|:---:|\\n\"", "class_coverage_above_minimum", "=", "markdown_class", "(", "parser", ",", "report_markdown", ",", "report_url", ")", "markdown", "(", "report_markdown", ")", "report_fails", "(", "class_coverage_above_minimum", ",", "total_covered", ")", "end"], "docstring": "This is a fast report based on SAX parser\n\n @path path to the xml output of jacoco\n @report_url URL where html report hosted\n @delimiter git.modified_files returns full paths to the\n changed files. We need to get the class from this path to check the\n Jacoco report,\n\n e.g. src/java/com/example/SomeJavaClass.java -> com/example/SomeJavaClass\n e.g. src/kotlin/com/example/SomeKotlinClass.kt -> com/example/SomeKotlinClass\n\n The default value supposes that you're using gradle structure,\n that is your path to source files is something like\n\n Java => blah/blah/java/slashed_package/Source.java\n Kotlin => blah/blah/kotlin/slashed_package/Source.kt", "docstring_tokens": ["This", "is", "a", "fast", "report", "based", "on", "SAX", "parser"], "sha": "a3ef27173e5b231204409cb8a8eb40e9662cd161", "url": "https://github.com/Malinskiy/danger-jacoco/blob/a3ef27173e5b231204409cb8a8eb40e9662cd161/lib/jacoco/plugin.rb#L47-L63", "partition": "valid"} {"repo": "Malinskiy/danger-jacoco", "path": "lib/jacoco/plugin.rb", "func_name": "Danger.DangerJacoco.classes", "original_string": "def classes(delimiter)\n git = @dangerfile.git\n affected_files = git.modified_files + git.added_files\n affected_files.select { |file| files_extension.reduce(false) { |state, el| state || file.end_with?(el) } }\n .map { |file| file.split('.').first.split(delimiter)[1] }\n end", "language": "ruby", "code": "def classes(delimiter)\n git = @dangerfile.git\n affected_files = git.modified_files + git.added_files\n affected_files.select { |file| files_extension.reduce(false) { |state, el| state || file.end_with?(el) } }\n .map { |file| file.split('.').first.split(delimiter)[1] }\n end", "code_tokens": ["def", "classes", "(", "delimiter", ")", "git", "=", "@dangerfile", ".", "git", "affected_files", "=", "git", ".", "modified_files", "+", "git", ".", "added_files", "affected_files", ".", "select", "{", "|", "file", "|", "files_extension", ".", "reduce", "(", "false", ")", "{", "|", "state", ",", "el", "|", "state", "||", "file", ".", "end_with?", "(", "el", ")", "}", "}", ".", "map", "{", "|", "file", "|", "file", ".", "split", "(", "'.'", ")", ".", "first", ".", "split", "(", "delimiter", ")", "[", "1", "]", "}", "end"], "docstring": "Select modified and added files in this PR", "docstring_tokens": ["Select", "modified", "and", "added", "files", "in", "this", "PR"], "sha": "a3ef27173e5b231204409cb8a8eb40e9662cd161", "url": "https://github.com/Malinskiy/danger-jacoco/blob/a3ef27173e5b231204409cb8a8eb40e9662cd161/lib/jacoco/plugin.rb#L66-L71", "partition": "valid"} {"repo": "Malinskiy/danger-jacoco", "path": "lib/jacoco/plugin.rb", "func_name": "Danger.DangerJacoco.report_class", "original_string": "def report_class(jacoco_class)\n counter = coverage_counter(jacoco_class)\n coverage = (counter.covered.fdiv(counter.covered + counter.missed) * 100).floor\n required_coverage = minimum_class_coverage_map[jacoco_class.name]\n required_coverage = minimum_class_coverage_percentage if required_coverage.nil?\n status = coverage_status(coverage, required_coverage)\n\n {\n covered: coverage,\n status: status,\n required_coverage_percentage: required_coverage\n }\n end", "language": "ruby", "code": "def report_class(jacoco_class)\n counter = coverage_counter(jacoco_class)\n coverage = (counter.covered.fdiv(counter.covered + counter.missed) * 100).floor\n required_coverage = minimum_class_coverage_map[jacoco_class.name]\n required_coverage = minimum_class_coverage_percentage if required_coverage.nil?\n status = coverage_status(coverage, required_coverage)\n\n {\n covered: coverage,\n status: status,\n required_coverage_percentage: required_coverage\n }\n end", "code_tokens": ["def", "report_class", "(", "jacoco_class", ")", "counter", "=", "coverage_counter", "(", "jacoco_class", ")", "coverage", "=", "(", "counter", ".", "covered", ".", "fdiv", "(", "counter", ".", "covered", "+", "counter", ".", "missed", ")", "*", "100", ")", ".", "floor", "required_coverage", "=", "minimum_class_coverage_map", "[", "jacoco_class", ".", "name", "]", "required_coverage", "=", "minimum_class_coverage_percentage", "if", "required_coverage", ".", "nil?", "status", "=", "coverage_status", "(", "coverage", ",", "required_coverage", ")", "{", "covered", ":", "coverage", ",", "status", ":", "status", ",", "required_coverage_percentage", ":", "required_coverage", "}", "end"], "docstring": "It returns a specific class code coverage and an emoji status as well", "docstring_tokens": ["It", "returns", "a", "specific", "class", "code", "coverage", "and", "an", "emoji", "status", "as", "well"], "sha": "a3ef27173e5b231204409cb8a8eb40e9662cd161", "url": "https://github.com/Malinskiy/danger-jacoco/blob/a3ef27173e5b231204409cb8a8eb40e9662cd161/lib/jacoco/plugin.rb#L74-L86", "partition": "valid"} {"repo": "Malinskiy/danger-jacoco", "path": "lib/jacoco/plugin.rb", "func_name": "Danger.DangerJacoco.total_coverage", "original_string": "def total_coverage(report_path)\n jacoco_report = Nokogiri::XML(File.open(report_path))\n\n report = jacoco_report.xpath('report/counter').select { |item| item['type'] == 'INSTRUCTION' }\n missed_instructions = report.first['missed'].to_f\n covered_instructions = report.first['covered'].to_f\n total_instructions = missed_instructions + covered_instructions\n covered_percentage = (covered_instructions * 100 / total_instructions).round(2)\n coverage_status = coverage_status(covered_percentage, minimum_project_coverage_percentage)\n\n {\n covered: covered_percentage,\n status: coverage_status\n }\n end", "language": "ruby", "code": "def total_coverage(report_path)\n jacoco_report = Nokogiri::XML(File.open(report_path))\n\n report = jacoco_report.xpath('report/counter').select { |item| item['type'] == 'INSTRUCTION' }\n missed_instructions = report.first['missed'].to_f\n covered_instructions = report.first['covered'].to_f\n total_instructions = missed_instructions + covered_instructions\n covered_percentage = (covered_instructions * 100 / total_instructions).round(2)\n coverage_status = coverage_status(covered_percentage, minimum_project_coverage_percentage)\n\n {\n covered: covered_percentage,\n status: coverage_status\n }\n end", "code_tokens": ["def", "total_coverage", "(", "report_path", ")", "jacoco_report", "=", "Nokogiri", "::", "XML", "(", "File", ".", "open", "(", "report_path", ")", ")", "report", "=", "jacoco_report", ".", "xpath", "(", "'report/counter'", ")", ".", "select", "{", "|", "item", "|", "item", "[", "'type'", "]", "==", "'INSTRUCTION'", "}", "missed_instructions", "=", "report", ".", "first", "[", "'missed'", "]", ".", "to_f", "covered_instructions", "=", "report", ".", "first", "[", "'covered'", "]", ".", "to_f", "total_instructions", "=", "missed_instructions", "+", "covered_instructions", "covered_percentage", "=", "(", "covered_instructions", "*", "100", "/", "total_instructions", ")", ".", "round", "(", "2", ")", "coverage_status", "=", "coverage_status", "(", "covered_percentage", ",", "minimum_project_coverage_percentage", ")", "{", "covered", ":", "covered_percentage", ",", "status", ":", "coverage_status", "}", "end"], "docstring": "It returns total of project code coverage and an emoji status as well", "docstring_tokens": ["It", "returns", "total", "of", "project", "code", "coverage", "and", "an", "emoji", "status", "as", "well"], "sha": "a3ef27173e5b231204409cb8a8eb40e9662cd161", "url": "https://github.com/Malinskiy/danger-jacoco/blob/a3ef27173e5b231204409cb8a8eb40e9662cd161/lib/jacoco/plugin.rb#L97-L111", "partition": "valid"} {"repo": "matadon/mizuno", "path": "lib/mizuno/server.rb", "func_name": "Mizuno.Server.rewindable", "original_string": "def rewindable(request)\n input = request.getInputStream\n\n @options[:rewindable] ?\n Rack::RewindableInput.new(input.to_io.binmode) :\n RewindableInputStream.new(input).to_io.binmode\n end", "language": "ruby", "code": "def rewindable(request)\n input = request.getInputStream\n\n @options[:rewindable] ?\n Rack::RewindableInput.new(input.to_io.binmode) :\n RewindableInputStream.new(input).to_io.binmode\n end", "code_tokens": ["def", "rewindable", "(", "request", ")", "input", "=", "request", ".", "getInputStream", "@options", "[", ":rewindable", "]", "?", "Rack", "::", "RewindableInput", ".", "new", "(", "input", ".", "to_io", ".", "binmode", ")", ":", "RewindableInputStream", ".", "new", "(", "input", ")", ".", "to_io", ".", "binmode", "end"], "docstring": "Wraps the Java InputStream for the level of Rack compliance\n desired.", "docstring_tokens": ["Wraps", "the", "Java", "InputStream", "for", "the", "level", "of", "Rack", "compliance", "desired", "."], "sha": "506beb09571f0398d5851366d3c9779c14b061fb", "url": "https://github.com/matadon/mizuno/blob/506beb09571f0398d5851366d3c9779c14b061fb/lib/mizuno/server.rb#L145-L151", "partition": "valid"} {"repo": "matadon/mizuno", "path": "lib/mizuno/rack_handler.rb", "func_name": "Mizuno.RackHandler.servlet_to_rack", "original_string": "def servlet_to_rack(request)\n # The Rack request that we will pass on.\n env = Hash.new\n\n # Map Servlet bits to Rack bits.\n env['REQUEST_METHOD'] = request.getMethod\n env['QUERY_STRING'] = request.getQueryString.to_s\n env['SERVER_NAME'] = request.getServerName\n env['SERVER_PORT'] = request.getServerPort.to_s\n env['rack.version'] = Rack::VERSION\n env['rack.url_scheme'] = request.getScheme\n env['HTTP_VERSION'] = request.getProtocol\n env[\"SERVER_PROTOCOL\"] = request.getProtocol\n env['REMOTE_ADDR'] = request.getRemoteAddr\n env['REMOTE_HOST'] = request.getRemoteHost\n\n # request.getPathInfo seems to be blank, so we're using the URI.\n env['REQUEST_PATH'] = request.getRequestURI\n env['PATH_INFO'] = request.getRequestURI\n env['SCRIPT_NAME'] = \"\"\n\n # Rack says URI, but it hands off a URL.\n env['REQUEST_URI'] = request.getRequestURL.to_s\n\n # Java chops off the query string, but a Rack application will\n # expect it, so we'll add it back if present\n env['REQUEST_URI'] << \"?#{env['QUERY_STRING']}\" \\\n if env['QUERY_STRING']\n\n # JRuby is like the matrix, only there's no spoon or fork().\n env['rack.multiprocess'] = false\n env['rack.multithread'] = true\n env['rack.run_once'] = false\n\n # The input stream is a wrapper around the Java InputStream.\n env['rack.input'] = @server.rewindable(request)\n\n # Force encoding if we're on Ruby 1.9\n env['rack.input'].set_encoding(Encoding.find(\"ASCII-8BIT\")) \\\n if env['rack.input'].respond_to?(:set_encoding)\n\n # Populate the HTTP headers.\n request.getHeaderNames.each do |header_name|\n header = header_name.to_s.upcase.tr('-', '_')\n env[\"HTTP_#{header}\"] = request.getHeader(header_name)\n end\n\n # Rack Weirdness: HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH\n # both need to have the HTTP_ part dropped.\n env[\"CONTENT_TYPE\"] = env.delete(\"HTTP_CONTENT_TYPE\") \\\n if env[\"HTTP_CONTENT_TYPE\"]\n env[\"CONTENT_LENGTH\"] = env.delete(\"HTTP_CONTENT_LENGTH\") \\\n if env[\"HTTP_CONTENT_LENGTH\"]\n\n # Route errors through the logger.\n env['rack.errors'] ||= @server.logger\n env['rack.logger'] ||= @server.logger\n\n # All done, hand back the Rack request.\n return(env)\n end", "language": "ruby", "code": "def servlet_to_rack(request)\n # The Rack request that we will pass on.\n env = Hash.new\n\n # Map Servlet bits to Rack bits.\n env['REQUEST_METHOD'] = request.getMethod\n env['QUERY_STRING'] = request.getQueryString.to_s\n env['SERVER_NAME'] = request.getServerName\n env['SERVER_PORT'] = request.getServerPort.to_s\n env['rack.version'] = Rack::VERSION\n env['rack.url_scheme'] = request.getScheme\n env['HTTP_VERSION'] = request.getProtocol\n env[\"SERVER_PROTOCOL\"] = request.getProtocol\n env['REMOTE_ADDR'] = request.getRemoteAddr\n env['REMOTE_HOST'] = request.getRemoteHost\n\n # request.getPathInfo seems to be blank, so we're using the URI.\n env['REQUEST_PATH'] = request.getRequestURI\n env['PATH_INFO'] = request.getRequestURI\n env['SCRIPT_NAME'] = \"\"\n\n # Rack says URI, but it hands off a URL.\n env['REQUEST_URI'] = request.getRequestURL.to_s\n\n # Java chops off the query string, but a Rack application will\n # expect it, so we'll add it back if present\n env['REQUEST_URI'] << \"?#{env['QUERY_STRING']}\" \\\n if env['QUERY_STRING']\n\n # JRuby is like the matrix, only there's no spoon or fork().\n env['rack.multiprocess'] = false\n env['rack.multithread'] = true\n env['rack.run_once'] = false\n\n # The input stream is a wrapper around the Java InputStream.\n env['rack.input'] = @server.rewindable(request)\n\n # Force encoding if we're on Ruby 1.9\n env['rack.input'].set_encoding(Encoding.find(\"ASCII-8BIT\")) \\\n if env['rack.input'].respond_to?(:set_encoding)\n\n # Populate the HTTP headers.\n request.getHeaderNames.each do |header_name|\n header = header_name.to_s.upcase.tr('-', '_')\n env[\"HTTP_#{header}\"] = request.getHeader(header_name)\n end\n\n # Rack Weirdness: HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH\n # both need to have the HTTP_ part dropped.\n env[\"CONTENT_TYPE\"] = env.delete(\"HTTP_CONTENT_TYPE\") \\\n if env[\"HTTP_CONTENT_TYPE\"]\n env[\"CONTENT_LENGTH\"] = env.delete(\"HTTP_CONTENT_LENGTH\") \\\n if env[\"HTTP_CONTENT_LENGTH\"]\n\n # Route errors through the logger.\n env['rack.errors'] ||= @server.logger\n env['rack.logger'] ||= @server.logger\n\n # All done, hand back the Rack request.\n return(env)\n end", "code_tokens": ["def", "servlet_to_rack", "(", "request", ")", "# The Rack request that we will pass on.", "env", "=", "Hash", ".", "new", "# Map Servlet bits to Rack bits.", "env", "[", "'REQUEST_METHOD'", "]", "=", "request", ".", "getMethod", "env", "[", "'QUERY_STRING'", "]", "=", "request", ".", "getQueryString", ".", "to_s", "env", "[", "'SERVER_NAME'", "]", "=", "request", ".", "getServerName", "env", "[", "'SERVER_PORT'", "]", "=", "request", ".", "getServerPort", ".", "to_s", "env", "[", "'rack.version'", "]", "=", "Rack", "::", "VERSION", "env", "[", "'rack.url_scheme'", "]", "=", "request", ".", "getScheme", "env", "[", "'HTTP_VERSION'", "]", "=", "request", ".", "getProtocol", "env", "[", "\"SERVER_PROTOCOL\"", "]", "=", "request", ".", "getProtocol", "env", "[", "'REMOTE_ADDR'", "]", "=", "request", ".", "getRemoteAddr", "env", "[", "'REMOTE_HOST'", "]", "=", "request", ".", "getRemoteHost", "# request.getPathInfo seems to be blank, so we're using the URI.", "env", "[", "'REQUEST_PATH'", "]", "=", "request", ".", "getRequestURI", "env", "[", "'PATH_INFO'", "]", "=", "request", ".", "getRequestURI", "env", "[", "'SCRIPT_NAME'", "]", "=", "\"\"", "# Rack says URI, but it hands off a URL.", "env", "[", "'REQUEST_URI'", "]", "=", "request", ".", "getRequestURL", ".", "to_s", "# Java chops off the query string, but a Rack application will", "# expect it, so we'll add it back if present", "env", "[", "'REQUEST_URI'", "]", "<<", "\"?#{env['QUERY_STRING']}\"", "if", "env", "[", "'QUERY_STRING'", "]", "# JRuby is like the matrix, only there's no spoon or fork().", "env", "[", "'rack.multiprocess'", "]", "=", "false", "env", "[", "'rack.multithread'", "]", "=", "true", "env", "[", "'rack.run_once'", "]", "=", "false", "# The input stream is a wrapper around the Java InputStream.", "env", "[", "'rack.input'", "]", "=", "@server", ".", "rewindable", "(", "request", ")", "# Force encoding if we're on Ruby 1.9", "env", "[", "'rack.input'", "]", ".", "set_encoding", "(", "Encoding", ".", "find", "(", "\"ASCII-8BIT\"", ")", ")", "if", "env", "[", "'rack.input'", "]", ".", "respond_to?", "(", ":set_encoding", ")", "# Populate the HTTP headers.", "request", ".", "getHeaderNames", ".", "each", "do", "|", "header_name", "|", "header", "=", "header_name", ".", "to_s", ".", "upcase", ".", "tr", "(", "'-'", ",", "'_'", ")", "env", "[", "\"HTTP_#{header}\"", "]", "=", "request", ".", "getHeader", "(", "header_name", ")", "end", "# Rack Weirdness: HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH", "# both need to have the HTTP_ part dropped.", "env", "[", "\"CONTENT_TYPE\"", "]", "=", "env", ".", "delete", "(", "\"HTTP_CONTENT_TYPE\"", ")", "if", "env", "[", "\"HTTP_CONTENT_TYPE\"", "]", "env", "[", "\"CONTENT_LENGTH\"", "]", "=", "env", ".", "delete", "(", "\"HTTP_CONTENT_LENGTH\"", ")", "if", "env", "[", "\"HTTP_CONTENT_LENGTH\"", "]", "# Route errors through the logger.", "env", "[", "'rack.errors'", "]", "||=", "@server", ".", "logger", "env", "[", "'rack.logger'", "]", "||=", "@server", ".", "logger", "# All done, hand back the Rack request.", "return", "(", "env", ")", "end"], "docstring": "Turns a Servlet request into a Rack request hash.", "docstring_tokens": ["Turns", "a", "Servlet", "request", "into", "a", "Rack", "request", "hash", "."], "sha": "506beb09571f0398d5851366d3c9779c14b061fb", "url": "https://github.com/matadon/mizuno/blob/506beb09571f0398d5851366d3c9779c14b061fb/lib/mizuno/rack_handler.rb#L100-L160", "partition": "valid"} {"repo": "matadon/mizuno", "path": "lib/mizuno/rack_handler.rb", "func_name": "Mizuno.RackHandler.handle_exceptions", "original_string": "def handle_exceptions(response)\n begin\n yield\n rescue => error\n message = \"Exception: #{error}\"\n message << \"\\n#{error.backtrace.join(\"\\n\")}\" \\\n if (error.respond_to?(:backtrace))\n Server.logger.error(message)\n return if response.isCommitted\n response.reset\n response.setStatus(500)\n end\n end", "language": "ruby", "code": "def handle_exceptions(response)\n begin\n yield\n rescue => error\n message = \"Exception: #{error}\"\n message << \"\\n#{error.backtrace.join(\"\\n\")}\" \\\n if (error.respond_to?(:backtrace))\n Server.logger.error(message)\n return if response.isCommitted\n response.reset\n response.setStatus(500)\n end\n end", "code_tokens": ["def", "handle_exceptions", "(", "response", ")", "begin", "yield", "rescue", "=>", "error", "message", "=", "\"Exception: #{error}\"", "message", "<<", "\"\\n#{error.backtrace.join(\"\\n\")}\"", "if", "(", "error", ".", "respond_to?", "(", ":backtrace", ")", ")", "Server", ".", "logger", ".", "error", "(", "message", ")", "return", "if", "response", ".", "isCommitted", "response", ".", "reset", "response", ".", "setStatus", "(", "500", ")", "end", "end"], "docstring": "Handle exceptions, returning a generic 500 error response.", "docstring_tokens": ["Handle", "exceptions", "returning", "a", "generic", "500", "error", "response", "."], "sha": "506beb09571f0398d5851366d3c9779c14b061fb", "url": "https://github.com/matadon/mizuno/blob/506beb09571f0398d5851366d3c9779c14b061fb/lib/mizuno/rack_handler.rb#L244-L256", "partition": "valid"} {"repo": "matadon/mizuno", "path": "lib/mizuno/reloader.rb", "func_name": "Mizuno.Reloader.find_files_for_reload", "original_string": "def find_files_for_reload\n paths = [ './', *$LOAD_PATH ].uniq\n [ $0, *$LOADED_FEATURES ].uniq.map do |file|\n next if file =~ /\\.(so|bundle)$/\n yield(find(file, paths))\n end\n end", "language": "ruby", "code": "def find_files_for_reload\n paths = [ './', *$LOAD_PATH ].uniq\n [ $0, *$LOADED_FEATURES ].uniq.map do |file|\n next if file =~ /\\.(so|bundle)$/\n yield(find(file, paths))\n end\n end", "code_tokens": ["def", "find_files_for_reload", "paths", "=", "[", "'./'", ",", "$LOAD_PATH", "]", ".", "uniq", "[", "$0", ",", "$LOADED_FEATURES", "]", ".", "uniq", ".", "map", "do", "|", "file", "|", "next", "if", "file", "=~", "/", "\\.", "/", "yield", "(", "find", "(", "file", ",", "paths", ")", ")", "end", "end"], "docstring": "Walk through the list of every file we've loaded.", "docstring_tokens": ["Walk", "through", "the", "list", "of", "every", "file", "we", "ve", "loaded", "."], "sha": "506beb09571f0398d5851366d3c9779c14b061fb", "url": "https://github.com/matadon/mizuno/blob/506beb09571f0398d5851366d3c9779c14b061fb/lib/mizuno/reloader.rb#L91-L97", "partition": "valid"} {"repo": "matadon/mizuno", "path": "lib/mizuno/reloader.rb", "func_name": "Mizuno.Reloader.find", "original_string": "def find(file, paths)\n if(Pathname.new(file).absolute?)\n return unless (timestamp = mtime(file))\n @logger.debug(\"Found #{file}\")\n [ file, timestamp ]\n else\n paths.each do |path|\n fullpath = File.expand_path((File.join(path, file)))\n next unless (timestamp = mtime(fullpath))\n @logger.debug(\"Found #{file} in #{fullpath}\")\n return([ fullpath, timestamp ])\n end\n return(nil)\n end\n end", "language": "ruby", "code": "def find(file, paths)\n if(Pathname.new(file).absolute?)\n return unless (timestamp = mtime(file))\n @logger.debug(\"Found #{file}\")\n [ file, timestamp ]\n else\n paths.each do |path|\n fullpath = File.expand_path((File.join(path, file)))\n next unless (timestamp = mtime(fullpath))\n @logger.debug(\"Found #{file} in #{fullpath}\")\n return([ fullpath, timestamp ])\n end\n return(nil)\n end\n end", "code_tokens": ["def", "find", "(", "file", ",", "paths", ")", "if", "(", "Pathname", ".", "new", "(", "file", ")", ".", "absolute?", ")", "return", "unless", "(", "timestamp", "=", "mtime", "(", "file", ")", ")", "@logger", ".", "debug", "(", "\"Found #{file}\"", ")", "[", "file", ",", "timestamp", "]", "else", "paths", ".", "each", "do", "|", "path", "|", "fullpath", "=", "File", ".", "expand_path", "(", "(", "File", ".", "join", "(", "path", ",", "file", ")", ")", ")", "next", "unless", "(", "timestamp", "=", "mtime", "(", "fullpath", ")", ")", "@logger", ".", "debug", "(", "\"Found #{file} in #{fullpath}\"", ")", "return", "(", "[", "fullpath", ",", "timestamp", "]", ")", "end", "return", "(", "nil", ")", "end", "end"], "docstring": "Takes a relative or absolute +file+ name, a couple possible\n +paths+ that the +file+ might reside in. Returns a tuple of\n the full path where the file was found and its modification\n time, or nil if not found.", "docstring_tokens": ["Takes", "a", "relative", "or", "absolute", "+", "file", "+", "name", "a", "couple", "possible", "+", "paths", "+", "that", "the", "+", "file", "+", "might", "reside", "in", ".", "Returns", "a", "tuple", "of", "the", "full", "path", "where", "the", "file", "was", "found", "and", "its", "modification", "time", "or", "nil", "if", "not", "found", "."], "sha": "506beb09571f0398d5851366d3c9779c14b061fb", "url": "https://github.com/matadon/mizuno/blob/506beb09571f0398d5851366d3c9779c14b061fb/lib/mizuno/reloader.rb#L120-L134", "partition": "valid"} {"repo": "matadon/mizuno", "path": "lib/mizuno/reloader.rb", "func_name": "Mizuno.Reloader.mtime", "original_string": "def mtime(file)\n begin\n return unless file\n stat = File.stat(file)\n stat.file? ? stat.mtime.to_i : nil\n rescue Errno::ENOENT, Errno::ENOTDIR, Errno::ESRCH\n nil\n end\n end", "language": "ruby", "code": "def mtime(file)\n begin\n return unless file\n stat = File.stat(file)\n stat.file? ? stat.mtime.to_i : nil\n rescue Errno::ENOENT, Errno::ENOTDIR, Errno::ESRCH\n nil\n end\n end", "code_tokens": ["def", "mtime", "(", "file", ")", "begin", "return", "unless", "file", "stat", "=", "File", ".", "stat", "(", "file", ")", "stat", ".", "file?", "?", "stat", ".", "mtime", ".", "to_i", ":", "nil", "rescue", "Errno", "::", "ENOENT", ",", "Errno", "::", "ENOTDIR", ",", "Errno", "::", "ESRCH", "nil", "end", "end"], "docstring": "Returns the modification time of _file_.", "docstring_tokens": ["Returns", "the", "modification", "time", "of", "_file_", "."], "sha": "506beb09571f0398d5851366d3c9779c14b061fb", "url": "https://github.com/matadon/mizuno/blob/506beb09571f0398d5851366d3c9779c14b061fb/lib/mizuno/reloader.rb#L139-L147", "partition": "valid"} {"repo": "namely/ruby-client", "path": "lib/namely/collection.rb", "func_name": "Namely.Collection.find", "original_string": "def find(id)\n build(resource_gateway.json_show(id))\n rescue RestClient::ResourceNotFound\n raise NoSuchModelError, \"Can't find any #{endpoint} with id \\\"#{id}\\\"\"\n end", "language": "ruby", "code": "def find(id)\n build(resource_gateway.json_show(id))\n rescue RestClient::ResourceNotFound\n raise NoSuchModelError, \"Can't find any #{endpoint} with id \\\"#{id}\\\"\"\n end", "code_tokens": ["def", "find", "(", "id", ")", "build", "(", "resource_gateway", ".", "json_show", "(", "id", ")", ")", "rescue", "RestClient", "::", "ResourceNotFound", "raise", "NoSuchModelError", ",", "\"Can't find any #{endpoint} with id \\\"#{id}\\\"\"", "end"], "docstring": "Fetch a model from the server by its ID.\n\n @param [#to_s] id\n\n @raise [NoSuchModelError] if the model wasn't found.\n\n @return [Model]", "docstring_tokens": ["Fetch", "a", "model", "from", "the", "server", "by", "its", "ID", "."], "sha": "6483b15ebbe12c1c1312cf558023f9244146e103", "url": "https://github.com/namely/ruby-client/blob/6483b15ebbe12c1c1312cf558023f9244146e103/lib/namely/collection.rb#L68-L72", "partition": "valid"} {"repo": "namely/ruby-client", "path": "lib/namely/authenticator.rb", "func_name": "Namely.Authenticator.authorization_code_url", "original_string": "def authorization_code_url(options)\n URL.new(options.merge(\n path: \"/api/v1/oauth2/authorize\",\n params: {\n response_type: \"code\",\n approve: \"true\",\n client_id: client_id,\n },\n )).to_s\n end", "language": "ruby", "code": "def authorization_code_url(options)\n URL.new(options.merge(\n path: \"/api/v1/oauth2/authorize\",\n params: {\n response_type: \"code\",\n approve: \"true\",\n client_id: client_id,\n },\n )).to_s\n end", "code_tokens": ["def", "authorization_code_url", "(", "options", ")", "URL", ".", "new", "(", "options", ".", "merge", "(", "path", ":", "\"/api/v1/oauth2/authorize\"", ",", "params", ":", "{", "response_type", ":", "\"code\"", ",", "approve", ":", "\"true\"", ",", "client_id", ":", "client_id", ",", "}", ",", ")", ")", ".", "to_s", "end"], "docstring": "Return a new Authenticator instance.\n\n @param [Hash] options\n @option options [String] client_id\n @option options [String] client_secret\n\n @example\n authenticator = Authenticator.new(\n client_id: \"my-client-id\",\n client_secret: \"my-client-secret\"\n )\n\n @return [Authenticator]\n Returns a URL to begin the authorization code workflow. If you\n provide a redirect_uri you can receive the server's response.\n\n @param [Hash] options\n @option options [String] host (optional)\n @option options [String] protocol (optional, defaults to \"https\")\n @option options [String] subdomain (required)\n @option options [String] redirect_uri (optional)\n\n @return [String]", "docstring_tokens": ["Return", "a", "new", "Authenticator", "instance", "."], "sha": "6483b15ebbe12c1c1312cf558023f9244146e103", "url": "https://github.com/namely/ruby-client/blob/6483b15ebbe12c1c1312cf558023f9244146e103/lib/namely/authenticator.rb#L33-L42", "partition": "valid"} {"repo": "namely/ruby-client", "path": "lib/namely/authenticator.rb", "func_name": "Namely.Authenticator.current_user", "original_string": "def current_user(options)\n access_token = options.fetch(:access_token)\n subdomain = options.fetch(:subdomain)\n\n user_url = URL.new(options.merge(\n params: {\n access_token: access_token,\n },\n path: \"/api/v1/profiles/me\",\n )).to_s\n\n response = RestClient.get(\n user_url,\n accept: :json,\n )\n build_profile(\n access_token,\n subdomain,\n JSON.parse(response)[\"profiles\"].first\n )\n end", "language": "ruby", "code": "def current_user(options)\n access_token = options.fetch(:access_token)\n subdomain = options.fetch(:subdomain)\n\n user_url = URL.new(options.merge(\n params: {\n access_token: access_token,\n },\n path: \"/api/v1/profiles/me\",\n )).to_s\n\n response = RestClient.get(\n user_url,\n accept: :json,\n )\n build_profile(\n access_token,\n subdomain,\n JSON.parse(response)[\"profiles\"].first\n )\n end", "code_tokens": ["def", "current_user", "(", "options", ")", "access_token", "=", "options", ".", "fetch", "(", ":access_token", ")", "subdomain", "=", "options", ".", "fetch", "(", ":subdomain", ")", "user_url", "=", "URL", ".", "new", "(", "options", ".", "merge", "(", "params", ":", "{", "access_token", ":", "access_token", ",", "}", ",", "path", ":", "\"/api/v1/profiles/me\"", ",", ")", ")", ".", "to_s", "response", "=", "RestClient", ".", "get", "(", "user_url", ",", "accept", ":", ":json", ",", ")", "build_profile", "(", "access_token", ",", "subdomain", ",", "JSON", ".", "parse", "(", "response", ")", "[", "\"profiles\"", "]", ".", "first", ")", "end"], "docstring": "Return the profile of the user accessing the API.\n\n @param [Hash] options\n @option options [String] access_token (required)\n @option options [String] subdomain (required)\n\n @return [Model] the profile of the current user.", "docstring_tokens": ["Return", "the", "profile", "of", "the", "user", "accessing", "the", "API", "."], "sha": "6483b15ebbe12c1c1312cf558023f9244146e103", "url": "https://github.com/namely/ruby-client/blob/6483b15ebbe12c1c1312cf558023f9244146e103/lib/namely/authenticator.rb#L116-L136", "partition": "valid"} {"repo": "namely/ruby-client", "path": "lib/namely/model.rb", "func_name": "Namely.Model.save!", "original_string": "def save!\n if persisted?\n update(to_h)\n else\n self.id = resource_gateway.create(to_h)\n end\n self\n rescue RestClient::Exception => e\n raise_failed_request_error(e)\n end", "language": "ruby", "code": "def save!\n if persisted?\n update(to_h)\n else\n self.id = resource_gateway.create(to_h)\n end\n self\n rescue RestClient::Exception => e\n raise_failed_request_error(e)\n end", "code_tokens": ["def", "save!", "if", "persisted?", "update", "(", "to_h", ")", "else", "self", ".", "id", "=", "resource_gateway", ".", "create", "(", "to_h", ")", "end", "self", "rescue", "RestClient", "::", "Exception", "=>", "e", "raise_failed_request_error", "(", "e", ")", "end"], "docstring": "Try to persist the current object to the server by creating a\n new resource or updating an existing one. Raise an error if the\n object can't be saved.\n\n @raise [FailedRequestError] if the request failed for any reason.\n\n @return [Model] the model itself, if saving succeeded.", "docstring_tokens": ["Try", "to", "persist", "the", "current", "object", "to", "the", "server", "by", "creating", "a", "new", "resource", "or", "updating", "an", "existing", "one", ".", "Raise", "an", "error", "if", "the", "object", "can", "t", "be", "saved", "."], "sha": "6483b15ebbe12c1c1312cf558023f9244146e103", "url": "https://github.com/namely/ruby-client/blob/6483b15ebbe12c1c1312cf558023f9244146e103/lib/namely/model.rb#L17-L26", "partition": "valid"} {"repo": "namely/ruby-client", "path": "lib/namely/model.rb", "func_name": "Namely.Model.update", "original_string": "def update(attributes)\n attributes.each do |key, value|\n self[key] = value\n end\n\n begin\n resource_gateway.update(id, attributes)\n rescue RestClient::Exception => e\n raise_failed_request_error(e)\n end\n\n self\n end", "language": "ruby", "code": "def update(attributes)\n attributes.each do |key, value|\n self[key] = value\n end\n\n begin\n resource_gateway.update(id, attributes)\n rescue RestClient::Exception => e\n raise_failed_request_error(e)\n end\n\n self\n end", "code_tokens": ["def", "update", "(", "attributes", ")", "attributes", ".", "each", "do", "|", "key", ",", "value", "|", "self", "[", "key", "]", "=", "value", "end", "begin", "resource_gateway", ".", "update", "(", "id", ",", "attributes", ")", "rescue", "RestClient", "::", "Exception", "=>", "e", "raise_failed_request_error", "(", "e", ")", "end", "self", "end"], "docstring": "Update the attributes of this model. Assign the attributes\n according to the hash, then persist those changes on the server.\n\n @param [Hash] attributes the attributes to be updated on the model.\n\n @example\n my_profile.update(\n middle_name: \"Ludwig\"\n )\n\n @raise [FailedRequestError] if the request failed for any reason.\n\n @return [Model] the updated model.", "docstring_tokens": ["Update", "the", "attributes", "of", "this", "model", ".", "Assign", "the", "attributes", "according", "to", "the", "hash", "then", "persist", "those", "changes", "on", "the", "server", "."], "sha": "6483b15ebbe12c1c1312cf558023f9244146e103", "url": "https://github.com/namely/ruby-client/blob/6483b15ebbe12c1c1312cf558023f9244146e103/lib/namely/model.rb#L41-L53", "partition": "valid"} {"repo": "leviwilson/mohawk", "path": "lib/mohawk/accessors.rb", "func_name": "Mohawk.Accessors.text", "original_string": "def text(name, locator)\r\n define_method(\"#{name}\") do\r\n adapter.text(locator).value\r\n end\r\n define_method(\"#{name}=\") do |text|\r\n adapter.text(locator).set text\r\n end\r\n define_method(\"clear_#{name}\") do\r\n adapter.text(locator).clear\r\n end\r\n define_method(\"enter_#{name}\") do |text|\r\n adapter.text(locator).enter text\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.text(locator).view\r\n end\r\n end", "language": "ruby", "code": "def text(name, locator)\r\n define_method(\"#{name}\") do\r\n adapter.text(locator).value\r\n end\r\n define_method(\"#{name}=\") do |text|\r\n adapter.text(locator).set text\r\n end\r\n define_method(\"clear_#{name}\") do\r\n adapter.text(locator).clear\r\n end\r\n define_method(\"enter_#{name}\") do |text|\r\n adapter.text(locator).enter text\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.text(locator).view\r\n end\r\n end", "code_tokens": ["def", "text", "(", "name", ",", "locator", ")", "define_method", "(", "\"#{name}\"", ")", "do", "adapter", ".", "text", "(", "locator", ")", ".", "value", "end", "define_method", "(", "\"#{name}=\"", ")", "do", "|", "text", "|", "adapter", ".", "text", "(", "locator", ")", ".", "set", "text", "end", "define_method", "(", "\"clear_#{name}\"", ")", "do", "adapter", ".", "text", "(", "locator", ")", ".", "clear", "end", "define_method", "(", "\"enter_#{name}\"", ")", "do", "|", "text", "|", "adapter", ".", "text", "(", "locator", ")", ".", "enter", "text", "end", "define_method", "(", "\"#{name}_view\"", ")", "do", "adapter", ".", "text", "(", "locator", ")", ".", "view", "end", "end"], "docstring": "Generates methods to enter text into a text field, get its value\n and clear the text field\n\n @example\n text(:first_name, :id => 'textFieldId')\n # will generate 'first_name', 'first_name=' and 'clear_first_name' methods\n\n @param [String] the name used for the generated methods\n @param [Hash] locator for how the text is found", "docstring_tokens": ["Generates", "methods", "to", "enter", "text", "into", "a", "text", "field", "get", "its", "value", "and", "clear", "the", "text", "field"], "sha": "cacef0429cac39fecc1af1863c9c557bbd09efe7", "url": "https://github.com/leviwilson/mohawk/blob/cacef0429cac39fecc1af1863c9c557bbd09efe7/lib/mohawk/accessors.rb#L58-L74", "partition": "valid"} {"repo": "leviwilson/mohawk", "path": "lib/mohawk/accessors.rb", "func_name": "Mohawk.Accessors.button", "original_string": "def button(name, locator)\r\n define_method(\"#{name}\") do |&block|\r\n adapter.button(locator).click &block\r\n end\r\n define_method(\"#{name}_value\") do\r\n adapter.button(locator).value\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.button(locator).view\r\n end\r\n end", "language": "ruby", "code": "def button(name, locator)\r\n define_method(\"#{name}\") do |&block|\r\n adapter.button(locator).click &block\r\n end\r\n define_method(\"#{name}_value\") do\r\n adapter.button(locator).value\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.button(locator).view\r\n end\r\n end", "code_tokens": ["def", "button", "(", "name", ",", "locator", ")", "define_method", "(", "\"#{name}\"", ")", "do", "|", "&", "block", "|", "adapter", ".", "button", "(", "locator", ")", ".", "click", "block", "end", "define_method", "(", "\"#{name}_value\"", ")", "do", "adapter", ".", "button", "(", "locator", ")", ".", "value", "end", "define_method", "(", "\"#{name}_view\"", ")", "do", "adapter", ".", "button", "(", "locator", ")", ".", "view", "end", "end"], "docstring": "Generates methods to click on a button as well as get the value of\n the button text\n\n @example\n button(:close, :value => '&Close')\n # will generate 'close' and 'close_value' methods\n\n @param [String] the name used for the generated methods\n @param [Hash] locator for how the button is found", "docstring_tokens": ["Generates", "methods", "to", "click", "on", "a", "button", "as", "well", "as", "get", "the", "value", "of", "the", "button", "text"], "sha": "cacef0429cac39fecc1af1863c9c557bbd09efe7", "url": "https://github.com/leviwilson/mohawk/blob/cacef0429cac39fecc1af1863c9c557bbd09efe7/lib/mohawk/accessors.rb#L87-L97", "partition": "valid"} {"repo": "leviwilson/mohawk", "path": "lib/mohawk/accessors.rb", "func_name": "Mohawk.Accessors.combo_box", "original_string": "def combo_box(name, locator)\r\n define_method(\"#{name}\") do\r\n adapter.combo(locator).value\r\n end\r\n define_method(\"clear_#{name}\") do |item|\r\n adapter.combo(locator).clear item\r\n end\r\n define_method(\"#{name}_selections\") do\r\n adapter.combo(locator).values\r\n end\r\n\r\n define_method(\"#{name}=\") do |item|\r\n adapter.combo(locator).set item\r\n end\r\n alias_method \"select_#{name}\", \"#{name}=\"\r\n\r\n define_method(\"#{name}_options\") do\r\n adapter.combo(locator).options\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.combo(locator).view\r\n end\r\n end", "language": "ruby", "code": "def combo_box(name, locator)\r\n define_method(\"#{name}\") do\r\n adapter.combo(locator).value\r\n end\r\n define_method(\"clear_#{name}\") do |item|\r\n adapter.combo(locator).clear item\r\n end\r\n define_method(\"#{name}_selections\") do\r\n adapter.combo(locator).values\r\n end\r\n\r\n define_method(\"#{name}=\") do |item|\r\n adapter.combo(locator).set item\r\n end\r\n alias_method \"select_#{name}\", \"#{name}=\"\r\n\r\n define_method(\"#{name}_options\") do\r\n adapter.combo(locator).options\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.combo(locator).view\r\n end\r\n end", "code_tokens": ["def", "combo_box", "(", "name", ",", "locator", ")", "define_method", "(", "\"#{name}\"", ")", "do", "adapter", ".", "combo", "(", "locator", ")", ".", "value", "end", "define_method", "(", "\"clear_#{name}\"", ")", "do", "|", "item", "|", "adapter", ".", "combo", "(", "locator", ")", ".", "clear", "item", "end", "define_method", "(", "\"#{name}_selections\"", ")", "do", "adapter", ".", "combo", "(", "locator", ")", ".", "values", "end", "define_method", "(", "\"#{name}=\"", ")", "do", "|", "item", "|", "adapter", ".", "combo", "(", "locator", ")", ".", "set", "item", "end", "alias_method", "\"select_#{name}\"", ",", "\"#{name}=\"", "define_method", "(", "\"#{name}_options\"", ")", "do", "adapter", ".", "combo", "(", "locator", ")", ".", "options", "end", "define_method", "(", "\"#{name}_view\"", ")", "do", "adapter", ".", "combo", "(", "locator", ")", ".", "view", "end", "end"], "docstring": "Generates methods to get the value of a combo box, set the selected\n item by both index and value as well as to see the available options\n\n @example\n combo_box(:status, :id => 'statusComboBox')\n # will generate 'status', 'status_selections', 'status=', 'select_status','clear_status' and 'status_options' methods\n\n @param [String] the name used for the generated methods\n @param [Hash] locator for how the combo box is found\n\n === Aliases\n * combobox\n * dropdown / drop_down\n * select_list", "docstring_tokens": ["Generates", "methods", "to", "get", "the", "value", "of", "a", "combo", "box", "set", "the", "selected", "item", "by", "both", "index", "and", "value", "as", "well", "as", "to", "see", "the", "available", "options"], "sha": "cacef0429cac39fecc1af1863c9c557bbd09efe7", "url": "https://github.com/leviwilson/mohawk/blob/cacef0429cac39fecc1af1863c9c557bbd09efe7/lib/mohawk/accessors.rb#L115-L137", "partition": "valid"} {"repo": "leviwilson/mohawk", "path": "lib/mohawk/accessors.rb", "func_name": "Mohawk.Accessors.radio", "original_string": "def radio(name, locator)\r\n define_method(\"#{name}\") do\r\n adapter.radio(locator).set\r\n end\r\n define_method(\"#{name}?\") do\r\n adapter.radio(locator).set?\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.radio(locator).view\r\n end\r\n end", "language": "ruby", "code": "def radio(name, locator)\r\n define_method(\"#{name}\") do\r\n adapter.radio(locator).set\r\n end\r\n define_method(\"#{name}?\") do\r\n adapter.radio(locator).set?\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.radio(locator).view\r\n end\r\n end", "code_tokens": ["def", "radio", "(", "name", ",", "locator", ")", "define_method", "(", "\"#{name}\"", ")", "do", "adapter", ".", "radio", "(", "locator", ")", ".", "set", "end", "define_method", "(", "\"#{name}?\"", ")", "do", "adapter", ".", "radio", "(", "locator", ")", ".", "set?", "end", "define_method", "(", "\"#{name}_view\"", ")", "do", "adapter", ".", "radio", "(", "locator", ")", ".", "view", "end", "end"], "docstring": "Generates methods to set a radio button as well as see if one\n is selected\n\n @example\n radio(:morning, :id => 'morningRadio')\n # will generate 'morning' and 'morning?' methods\n\n @param [String] the name used for the generated methods\n @param [Hash] locator for how the radio is found", "docstring_tokens": ["Generates", "methods", "to", "set", "a", "radio", "button", "as", "well", "as", "see", "if", "one", "is", "selected"], "sha": "cacef0429cac39fecc1af1863c9c557bbd09efe7", "url": "https://github.com/leviwilson/mohawk/blob/cacef0429cac39fecc1af1863c9c557bbd09efe7/lib/mohawk/accessors.rb#L176-L186", "partition": "valid"} {"repo": "leviwilson/mohawk", "path": "lib/mohawk/accessors.rb", "func_name": "Mohawk.Accessors.label", "original_string": "def label(name, locator)\r\n define_method(\"#{name}\") do\r\n adapter.label(locator).value\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.label(locator).view\r\n end\r\n end", "language": "ruby", "code": "def label(name, locator)\r\n define_method(\"#{name}\") do\r\n adapter.label(locator).value\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.label(locator).view\r\n end\r\n end", "code_tokens": ["def", "label", "(", "name", ",", "locator", ")", "define_method", "(", "\"#{name}\"", ")", "do", "adapter", ".", "label", "(", "locator", ")", ".", "value", "end", "define_method", "(", "\"#{name}_view\"", ")", "do", "adapter", ".", "label", "(", "locator", ")", ".", "view", "end", "end"], "docstring": "Generates methods to get the value of a label control\n\n @example\n label(:login_info, :id => 'loginInfoLabel')\n # will generate a 'login_info' method\n\n @param [String] the name used for the generated methods\n @param [Hash] locator for how the label is found", "docstring_tokens": ["Generates", "methods", "to", "get", "the", "value", "of", "a", "label", "control"], "sha": "cacef0429cac39fecc1af1863c9c557bbd09efe7", "url": "https://github.com/leviwilson/mohawk/blob/cacef0429cac39fecc1af1863c9c557bbd09efe7/lib/mohawk/accessors.rb#L198-L205", "partition": "valid"} {"repo": "leviwilson/mohawk", "path": "lib/mohawk/accessors.rb", "func_name": "Mohawk.Accessors.link", "original_string": "def link(name, locator)\r\n define_method(\"#{name}_text\") do\r\n adapter.link(locator).value\r\n end\r\n define_method(\"click_#{name}\") do\r\n adapter.link(locator).click\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.link(locator).view\r\n end\r\n end", "language": "ruby", "code": "def link(name, locator)\r\n define_method(\"#{name}_text\") do\r\n adapter.link(locator).value\r\n end\r\n define_method(\"click_#{name}\") do\r\n adapter.link(locator).click\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.link(locator).view\r\n end\r\n end", "code_tokens": ["def", "link", "(", "name", ",", "locator", ")", "define_method", "(", "\"#{name}_text\"", ")", "do", "adapter", ".", "link", "(", "locator", ")", ".", "value", "end", "define_method", "(", "\"click_#{name}\"", ")", "do", "adapter", ".", "link", "(", "locator", ")", ".", "click", "end", "define_method", "(", "\"#{name}_view\"", ")", "do", "adapter", ".", "link", "(", "locator", ")", ".", "view", "end", "end"], "docstring": "Generates methods to work with link controls\n\n @example\n link(:send_info_link, :id => 'sendInfoId')\n # will generate 'send_info_link_text' and 'click_send_info_link' methods\n\n @param [String] the name used for the generated methods\n @param [Hash] locator for how the label is found", "docstring_tokens": ["Generates", "methods", "to", "work", "with", "link", "controls"], "sha": "cacef0429cac39fecc1af1863c9c557bbd09efe7", "url": "https://github.com/leviwilson/mohawk/blob/cacef0429cac39fecc1af1863c9c557bbd09efe7/lib/mohawk/accessors.rb#L217-L227", "partition": "valid"} {"repo": "leviwilson/mohawk", "path": "lib/mohawk/accessors.rb", "func_name": "Mohawk.Accessors.menu_item", "original_string": "def menu_item(name, locator)\r\n define_method(\"#{name}\") do\r\n adapter.menu_item(locator).select\r\n end\r\n define_method(\"click_#{name}\") do\r\n adapter.menu_item(locator).click\r\n end\r\n end", "language": "ruby", "code": "def menu_item(name, locator)\r\n define_method(\"#{name}\") do\r\n adapter.menu_item(locator).select\r\n end\r\n define_method(\"click_#{name}\") do\r\n adapter.menu_item(locator).click\r\n end\r\n end", "code_tokens": ["def", "menu_item", "(", "name", ",", "locator", ")", "define_method", "(", "\"#{name}\"", ")", "do", "adapter", ".", "menu_item", "(", "locator", ")", ".", "select", "end", "define_method", "(", "\"click_#{name}\"", ")", "do", "adapter", ".", "menu_item", "(", "locator", ")", ".", "click", "end", "end"], "docstring": "Generates methods to work with menu items\n\n @example\n menu_item(:some_menu_item, :path => [\"Path\", \"To\", \"A\", \"Menu Item\"])\n # will generate a 'some_menu_item' method to select a menu item\n\n @param [String] the name used for the generated methods\n @param [Hash] locator for how the label is found", "docstring_tokens": ["Generates", "methods", "to", "work", "with", "menu", "items"], "sha": "cacef0429cac39fecc1af1863c9c557bbd09efe7", "url": "https://github.com/leviwilson/mohawk/blob/cacef0429cac39fecc1af1863c9c557bbd09efe7/lib/mohawk/accessors.rb#L238-L245", "partition": "valid"} {"repo": "leviwilson/mohawk", "path": "lib/mohawk/accessors.rb", "func_name": "Mohawk.Accessors.table", "original_string": "def table(name, locator)\r\n define_method(\"#{name}\") do\r\n adapter.table(locator)\r\n end\r\n define_method(\"#{name}=\") do |which_item|\r\n adapter.table(locator).select which_item\r\n end\r\n define_method(\"add_#{name}\") do |hash_info|\r\n adapter.table(locator).add hash_info\r\n end\r\n define_method(\"select_#{name}\") do |hash_info|\r\n adapter.table(locator).select hash_info\r\n end\r\n define_method(\"find_#{name}\") do |hash_info|\r\n adapter.table(locator).find_row_with hash_info\r\n end\r\n define_method(\"clear_#{name}\") do |hash_info|\r\n adapter.table(locator).clear hash_info\r\n end\r\n define_method(\"#{name}_headers\") do\r\n adapter.table(locator).headers\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.table(locator).view\r\n end\r\n end", "language": "ruby", "code": "def table(name, locator)\r\n define_method(\"#{name}\") do\r\n adapter.table(locator)\r\n end\r\n define_method(\"#{name}=\") do |which_item|\r\n adapter.table(locator).select which_item\r\n end\r\n define_method(\"add_#{name}\") do |hash_info|\r\n adapter.table(locator).add hash_info\r\n end\r\n define_method(\"select_#{name}\") do |hash_info|\r\n adapter.table(locator).select hash_info\r\n end\r\n define_method(\"find_#{name}\") do |hash_info|\r\n adapter.table(locator).find_row_with hash_info\r\n end\r\n define_method(\"clear_#{name}\") do |hash_info|\r\n adapter.table(locator).clear hash_info\r\n end\r\n define_method(\"#{name}_headers\") do\r\n adapter.table(locator).headers\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.table(locator).view\r\n end\r\n end", "code_tokens": ["def", "table", "(", "name", ",", "locator", ")", "define_method", "(", "\"#{name}\"", ")", "do", "adapter", ".", "table", "(", "locator", ")", "end", "define_method", "(", "\"#{name}=\"", ")", "do", "|", "which_item", "|", "adapter", ".", "table", "(", "locator", ")", ".", "select", "which_item", "end", "define_method", "(", "\"add_#{name}\"", ")", "do", "|", "hash_info", "|", "adapter", ".", "table", "(", "locator", ")", ".", "add", "hash_info", "end", "define_method", "(", "\"select_#{name}\"", ")", "do", "|", "hash_info", "|", "adapter", ".", "table", "(", "locator", ")", ".", "select", "hash_info", "end", "define_method", "(", "\"find_#{name}\"", ")", "do", "|", "hash_info", "|", "adapter", ".", "table", "(", "locator", ")", ".", "find_row_with", "hash_info", "end", "define_method", "(", "\"clear_#{name}\"", ")", "do", "|", "hash_info", "|", "adapter", ".", "table", "(", "locator", ")", ".", "clear", "hash_info", "end", "define_method", "(", "\"#{name}_headers\"", ")", "do", "adapter", ".", "table", "(", "locator", ")", ".", "headers", "end", "define_method", "(", "\"#{name}_view\"", ")", "do", "adapter", ".", "table", "(", "locator", ")", ".", "view", "end", "end"], "docstring": "Generates methods for working with table or list view controls\n\n @example\n table(:some_table, :id => \"tableId\")\n # will generate 'some_table', 'some_table=', 'some_table_headers', 'select_some_table', 'clear_some_table',\n # find_some_table and 'some_table_view' methods to get an Enumerable of table rows,\n # select a table item, clear a table item, return all of the headers and get the raw view\n\n @param [String] the name used for the generated methods\n @param [Hash] locator for how the label is found\n\n === Aliases\n * listview\n * list_view", "docstring_tokens": ["Generates", "methods", "for", "working", "with", "table", "or", "list", "view", "controls"], "sha": "cacef0429cac39fecc1af1863c9c557bbd09efe7", "url": "https://github.com/leviwilson/mohawk/blob/cacef0429cac39fecc1af1863c9c557bbd09efe7/lib/mohawk/accessors.rb#L262-L287", "partition": "valid"} {"repo": "leviwilson/mohawk", "path": "lib/mohawk/accessors.rb", "func_name": "Mohawk.Accessors.tree_view", "original_string": "def tree_view(name, locator)\r\n define_method(\"#{name}\") do\r\n adapter.tree_view(locator).value\r\n end\r\n define_method(\"#{name}=\") do |which_item|\r\n adapter.tree_view(locator).select which_item\r\n end\r\n define_method(\"#{name}_items\") do\r\n adapter.tree_view(locator).items\r\n end\r\n define_method(\"expand_#{name}_item\") do |which_item|\r\n adapter.tree_view(locator).expand which_item\r\n end\r\n define_method(\"collapse_#{name}_item\") do |which_item|\r\n adapter.tree_view(locator).collapse which_item\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.tree_view(locator).view\r\n end\r\n end", "language": "ruby", "code": "def tree_view(name, locator)\r\n define_method(\"#{name}\") do\r\n adapter.tree_view(locator).value\r\n end\r\n define_method(\"#{name}=\") do |which_item|\r\n adapter.tree_view(locator).select which_item\r\n end\r\n define_method(\"#{name}_items\") do\r\n adapter.tree_view(locator).items\r\n end\r\n define_method(\"expand_#{name}_item\") do |which_item|\r\n adapter.tree_view(locator).expand which_item\r\n end\r\n define_method(\"collapse_#{name}_item\") do |which_item|\r\n adapter.tree_view(locator).collapse which_item\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.tree_view(locator).view\r\n end\r\n end", "code_tokens": ["def", "tree_view", "(", "name", ",", "locator", ")", "define_method", "(", "\"#{name}\"", ")", "do", "adapter", ".", "tree_view", "(", "locator", ")", ".", "value", "end", "define_method", "(", "\"#{name}=\"", ")", "do", "|", "which_item", "|", "adapter", ".", "tree_view", "(", "locator", ")", ".", "select", "which_item", "end", "define_method", "(", "\"#{name}_items\"", ")", "do", "adapter", ".", "tree_view", "(", "locator", ")", ".", "items", "end", "define_method", "(", "\"expand_#{name}_item\"", ")", "do", "|", "which_item", "|", "adapter", ".", "tree_view", "(", "locator", ")", ".", "expand", "which_item", "end", "define_method", "(", "\"collapse_#{name}_item\"", ")", "do", "|", "which_item", "|", "adapter", ".", "tree_view", "(", "locator", ")", ".", "collapse", "which_item", "end", "define_method", "(", "\"#{name}_view\"", ")", "do", "adapter", ".", "tree_view", "(", "locator", ")", ".", "view", "end", "end"], "docstring": "Generates methods for working with tree view controls\n\n @example\n tree_view(:tree, :id => \"treeId\")\n # will generate 'tree', 'tree=', 'tree_items', 'expand_tree_item' and 'collapse_tree_item'\n # methods to get the tree value, set the tree value (index or string), get all of the\n # items, expand an item (index or string) and collapse an item (index or string)\n\n @param [String] the name used for the generated methods\n @param [Hash] locator for how the label is found\n\n === Aliases\n * treeview\n * tree", "docstring_tokens": ["Generates", "methods", "for", "working", "with", "tree", "view", "controls"], "sha": "cacef0429cac39fecc1af1863c9c557bbd09efe7", "url": "https://github.com/leviwilson/mohawk/blob/cacef0429cac39fecc1af1863c9c557bbd09efe7/lib/mohawk/accessors.rb#L304-L323", "partition": "valid"} {"repo": "leviwilson/mohawk", "path": "lib/mohawk/accessors.rb", "func_name": "Mohawk.Accessors.spinner", "original_string": "def spinner(name, locator)\r\n define_method(name) do\r\n adapter.spinner(locator).value\r\n end\r\n define_method(\"#{name}=\") do |value|\r\n adapter.spinner(locator).value = value\r\n end\r\n define_method(\"increment_#{name}\") do\r\n adapter.spinner(locator).increment\r\n end\r\n define_method(\"decrement_#{name}\") do\r\n adapter.spinner(locator).decrement\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.spinner(locator).view\r\n end\r\n end", "language": "ruby", "code": "def spinner(name, locator)\r\n define_method(name) do\r\n adapter.spinner(locator).value\r\n end\r\n define_method(\"#{name}=\") do |value|\r\n adapter.spinner(locator).value = value\r\n end\r\n define_method(\"increment_#{name}\") do\r\n adapter.spinner(locator).increment\r\n end\r\n define_method(\"decrement_#{name}\") do\r\n adapter.spinner(locator).decrement\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.spinner(locator).view\r\n end\r\n end", "code_tokens": ["def", "spinner", "(", "name", ",", "locator", ")", "define_method", "(", "name", ")", "do", "adapter", ".", "spinner", "(", "locator", ")", ".", "value", "end", "define_method", "(", "\"#{name}=\"", ")", "do", "|", "value", "|", "adapter", ".", "spinner", "(", "locator", ")", ".", "value", "=", "value", "end", "define_method", "(", "\"increment_#{name}\"", ")", "do", "adapter", ".", "spinner", "(", "locator", ")", ".", "increment", "end", "define_method", "(", "\"decrement_#{name}\"", ")", "do", "adapter", ".", "spinner", "(", "locator", ")", ".", "decrement", "end", "define_method", "(", "\"#{name}_view\"", ")", "do", "adapter", ".", "spinner", "(", "locator", ")", ".", "view", "end", "end"], "docstring": "Generates methods for working with spinner controls\n\n @example\n spinner(:age, :id => \"ageId\")\n # will generate 'age', 'age=' methods to get the spinner value and\n # set the spinner value.\n\n @param [String] the name used for the generated methods\n @param [Hash] locator for how the spinner control is found", "docstring_tokens": ["Generates", "methods", "for", "working", "with", "spinner", "controls"], "sha": "cacef0429cac39fecc1af1863c9c557bbd09efe7", "url": "https://github.com/leviwilson/mohawk/blob/cacef0429cac39fecc1af1863c9c557bbd09efe7/lib/mohawk/accessors.rb#L335-L351", "partition": "valid"} {"repo": "leviwilson/mohawk", "path": "lib/mohawk/accessors.rb", "func_name": "Mohawk.Accessors.tabs", "original_string": "def tabs(name, locator)\r\n define_method(name) do\r\n adapter.tab_control(locator).value\r\n end\r\n define_method(\"#{name}=\") do |which|\r\n adapter.tab_control(locator).selected_tab = which\r\n end\r\n define_method(\"#{name}_items\") do\r\n adapter.tab_control(locator).items\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.tab_control(locator)\r\n end\r\n end", "language": "ruby", "code": "def tabs(name, locator)\r\n define_method(name) do\r\n adapter.tab_control(locator).value\r\n end\r\n define_method(\"#{name}=\") do |which|\r\n adapter.tab_control(locator).selected_tab = which\r\n end\r\n define_method(\"#{name}_items\") do\r\n adapter.tab_control(locator).items\r\n end\r\n define_method(\"#{name}_view\") do\r\n adapter.tab_control(locator)\r\n end\r\n end", "code_tokens": ["def", "tabs", "(", "name", ",", "locator", ")", "define_method", "(", "name", ")", "do", "adapter", ".", "tab_control", "(", "locator", ")", ".", "value", "end", "define_method", "(", "\"#{name}=\"", ")", "do", "|", "which", "|", "adapter", ".", "tab_control", "(", "locator", ")", ".", "selected_tab", "=", "which", "end", "define_method", "(", "\"#{name}_items\"", ")", "do", "adapter", ".", "tab_control", "(", "locator", ")", ".", "items", "end", "define_method", "(", "\"#{name}_view\"", ")", "do", "adapter", ".", "tab_control", "(", "locator", ")", "end", "end"], "docstring": "Generates methods for working with tab controls\n\n @example\n tabs(:tab, :id => \"tableId\")\n # will generate 'tab', 'tab=' and 'tab_items' methods to get the current tab,\n # set the currently selected tab (Fixnum, String or RegEx) and to get the\n # available tabs to be selected\n\n @param [String] the name used for the generated methods\n @param [Hash] locator for how the tab control is found", "docstring_tokens": ["Generates", "methods", "for", "working", "with", "tab", "controls"], "sha": "cacef0429cac39fecc1af1863c9c557bbd09efe7", "url": "https://github.com/leviwilson/mohawk/blob/cacef0429cac39fecc1af1863c9c557bbd09efe7/lib/mohawk/accessors.rb#L364-L377", "partition": "valid"} {"repo": "sgruhier/foundation_rails_helper", "path": "lib/foundation_rails_helper/flash_helper.rb", "func_name": "FoundationRailsHelper.FlashHelper.display_flash_messages", "original_string": "def display_flash_messages(closable: true, key_matching: {})\n key_matching = DEFAULT_KEY_MATCHING.merge(key_matching)\n key_matching.default = :primary\n\n capture do\n flash.each do |key, value|\n next if ignored_key?(key.to_sym)\n\n alert_class = key_matching[key.to_sym]\n concat alert_box(value, alert_class, closable)\n end\n end\n end", "language": "ruby", "code": "def display_flash_messages(closable: true, key_matching: {})\n key_matching = DEFAULT_KEY_MATCHING.merge(key_matching)\n key_matching.default = :primary\n\n capture do\n flash.each do |key, value|\n next if ignored_key?(key.to_sym)\n\n alert_class = key_matching[key.to_sym]\n concat alert_box(value, alert_class, closable)\n end\n end\n end", "code_tokens": ["def", "display_flash_messages", "(", "closable", ":", "true", ",", "key_matching", ":", "{", "}", ")", "key_matching", "=", "DEFAULT_KEY_MATCHING", ".", "merge", "(", "key_matching", ")", "key_matching", ".", "default", "=", ":primary", "capture", "do", "flash", ".", "each", "do", "|", "key", ",", "value", "|", "next", "if", "ignored_key?", "(", "key", ".", "to_sym", ")", "alert_class", "=", "key_matching", "[", "key", ".", "to_sym", "]", "concat", "alert_box", "(", "value", ",", "alert_class", ",", "closable", ")", "end", "end", "end"], "docstring": "Displays the flash messages found in ActionDispatch's +flash+ hash using\n Foundation's +callout+ component.\n\n Parameters:\n * +closable+ - A boolean to determine whether the displayed flash messages\n should be closable by the user. Defaults to true.\n * +key_matching+ - A Hash of key/value pairs mapping flash keys to the\n corresponding class to use for the callout box.", "docstring_tokens": ["Displays", "the", "flash", "messages", "found", "in", "ActionDispatch", "s", "+", "flash", "+", "hash", "using", "Foundation", "s", "+", "callout", "+", "component", "."], "sha": "8a4b53d9b348bbf49c3608aea811fe17b9282e4c", "url": "https://github.com/sgruhier/foundation_rails_helper/blob/8a4b53d9b348bbf49c3608aea811fe17b9282e4c/lib/foundation_rails_helper/flash_helper.rb#L31-L43", "partition": "valid"} {"repo": "tigris/pin_payment", "path": "lib/pin_payment/charge.rb", "func_name": "PinPayment.Charge.refunds", "original_string": "def refunds\n response = Charge.get(URI.parse(PinPayment.api_url).tap{|uri| uri.path = \"/1/charges/#{token}/refunds\" })\n response.map{|x| Refund.new(x.delete('token'), x) }\n end", "language": "ruby", "code": "def refunds\n response = Charge.get(URI.parse(PinPayment.api_url).tap{|uri| uri.path = \"/1/charges/#{token}/refunds\" })\n response.map{|x| Refund.new(x.delete('token'), x) }\n end", "code_tokens": ["def", "refunds", "response", "=", "Charge", ".", "get", "(", "URI", ".", "parse", "(", "PinPayment", ".", "api_url", ")", ".", "tap", "{", "|", "uri", "|", "uri", ".", "path", "=", "\"/1/charges/#{token}/refunds\"", "}", ")", "response", ".", "map", "{", "|", "x", "|", "Refund", ".", "new", "(", "x", ".", "delete", "(", "'token'", ")", ",", "x", ")", "}", "end"], "docstring": "Fetches all refunds of your charge using the pin API.\n\n @return [Array]\n TODO: pagination", "docstring_tokens": ["Fetches", "all", "refunds", "of", "your", "charge", "using", "the", "pin", "API", "."], "sha": "3f1acd823fe3eb1b05a7447ac6018ff37f914b9d", "url": "https://github.com/tigris/pin_payment/blob/3f1acd823fe3eb1b05a7447ac6018ff37f914b9d/lib/pin_payment/charge.rb#L54-L57", "partition": "valid"} {"repo": "tigris/pin_payment", "path": "lib/pin_payment/recipient.rb", "func_name": "PinPayment.Recipient.update", "original_string": "def update email, account_or_token = nil\n attributes = self.class.attributes - [:token, :created_at]\n options = self.class.parse_options_for_request(attributes, email: email, bank_account: account_or_token)\n response = self.class.put(URI.parse(PinPayment.api_url).tap{|uri| uri.path = \"/1/recipients/#{token}\" }, options)\n self.email = response['email']\n self.bank_account = response['bank_account']\n self\n end", "language": "ruby", "code": "def update email, account_or_token = nil\n attributes = self.class.attributes - [:token, :created_at]\n options = self.class.parse_options_for_request(attributes, email: email, bank_account: account_or_token)\n response = self.class.put(URI.parse(PinPayment.api_url).tap{|uri| uri.path = \"/1/recipients/#{token}\" }, options)\n self.email = response['email']\n self.bank_account = response['bank_account']\n self\n end", "code_tokens": ["def", "update", "email", ",", "account_or_token", "=", "nil", "attributes", "=", "self", ".", "class", ".", "attributes", "-", "[", ":token", ",", ":created_at", "]", "options", "=", "self", ".", "class", ".", "parse_options_for_request", "(", "attributes", ",", "email", ":", "email", ",", "bank_account", ":", "account_or_token", ")", "response", "=", "self", ".", "class", ".", "put", "(", "URI", ".", "parse", "(", "PinPayment", ".", "api_url", ")", ".", "tap", "{", "|", "uri", "|", "uri", ".", "path", "=", "\"/1/recipients/#{token}\"", "}", ",", "options", ")", "self", ".", "email", "=", "response", "[", "'email'", "]", "self", ".", "bank_account", "=", "response", "[", "'bank_account'", "]", "self", "end"], "docstring": "Update a recipient using the pin API.\n\n @param [String] email the recipients's new email address\n @param [String, PinPayment::BankAccount, Hash] account_or_token the recipient's new bank account details\n @return [PinPayment::Customer]", "docstring_tokens": ["Update", "a", "recipient", "using", "the", "pin", "API", "."], "sha": "3f1acd823fe3eb1b05a7447ac6018ff37f914b9d", "url": "https://github.com/tigris/pin_payment/blob/3f1acd823fe3eb1b05a7447ac6018ff37f914b9d/lib/pin_payment/recipient.rb#L54-L61", "partition": "valid"} {"repo": "tigris/pin_payment", "path": "lib/pin_payment/customer.rb", "func_name": "PinPayment.Customer.update", "original_string": "def update email, card_or_token = nil\n attributes = self.class.attributes - [:token, :created_at]\n options = self.class.parse_options_for_request(attributes, email: email, card: card_or_token)\n response = self.class.put(URI.parse(PinPayment.api_url).tap{|uri| uri.path = \"/1/customers/#{token}\" }, options)\n self.email = response['email']\n self.card = response['card']\n self\n end", "language": "ruby", "code": "def update email, card_or_token = nil\n attributes = self.class.attributes - [:token, :created_at]\n options = self.class.parse_options_for_request(attributes, email: email, card: card_or_token)\n response = self.class.put(URI.parse(PinPayment.api_url).tap{|uri| uri.path = \"/1/customers/#{token}\" }, options)\n self.email = response['email']\n self.card = response['card']\n self\n end", "code_tokens": ["def", "update", "email", ",", "card_or_token", "=", "nil", "attributes", "=", "self", ".", "class", ".", "attributes", "-", "[", ":token", ",", ":created_at", "]", "options", "=", "self", ".", "class", ".", "parse_options_for_request", "(", "attributes", ",", "email", ":", "email", ",", "card", ":", "card_or_token", ")", "response", "=", "self", ".", "class", ".", "put", "(", "URI", ".", "parse", "(", "PinPayment", ".", "api_url", ")", ".", "tap", "{", "|", "uri", "|", "uri", ".", "path", "=", "\"/1/customers/#{token}\"", "}", ",", "options", ")", "self", ".", "email", "=", "response", "[", "'email'", "]", "self", ".", "card", "=", "response", "[", "'card'", "]", "self", "end"], "docstring": "Update a customer using the pin API.\n\n @param [String] email the customer's new email address\n @param [String, PinPayment::Card, Hash] card_or_token the customer's new credit card details\n @return [PinPayment::Customer]", "docstring_tokens": ["Update", "a", "customer", "using", "the", "pin", "API", "."], "sha": "3f1acd823fe3eb1b05a7447ac6018ff37f914b9d", "url": "https://github.com/tigris/pin_payment/blob/3f1acd823fe3eb1b05a7447ac6018ff37f914b9d/lib/pin_payment/customer.rb#L55-L62", "partition": "valid"} {"repo": "NetcomKassel/smb-client", "path": "lib/smb/client/client_helper.rb", "func_name": "SMB.ClientHelper.ls", "original_string": "def ls(mask = '', raise = true)\n ls_items = []\n mask = '\"' + mask + '\"' if mask.include? ' '\n output = exec 'ls ' + mask\n output.lines.each do |line|\n ls_item = LsItem.from_line(line)\n ls_items << ls_item if ls_item\n end\n ls_items\n rescue Client::RuntimeError => e\n raise e if raise\n []\n end", "language": "ruby", "code": "def ls(mask = '', raise = true)\n ls_items = []\n mask = '\"' + mask + '\"' if mask.include? ' '\n output = exec 'ls ' + mask\n output.lines.each do |line|\n ls_item = LsItem.from_line(line)\n ls_items << ls_item if ls_item\n end\n ls_items\n rescue Client::RuntimeError => e\n raise e if raise\n []\n end", "code_tokens": ["def", "ls", "(", "mask", "=", "''", ",", "raise", "=", "true", ")", "ls_items", "=", "[", "]", "mask", "=", "'\"'", "+", "mask", "+", "'\"'", "if", "mask", ".", "include?", "' '", "output", "=", "exec", "'ls '", "+", "mask", "output", ".", "lines", ".", "each", "do", "|", "line", "|", "ls_item", "=", "LsItem", ".", "from_line", "(", "line", ")", "ls_items", "<<", "ls_item", "if", "ls_item", "end", "ls_items", "rescue", "Client", "::", "RuntimeError", "=>", "e", "raise", "e", "if", "raise", "[", "]", "end"], "docstring": "List contents of a remote directory\n @param [String] mask The matching mask\n @param [Boolean] raise If set, an error will be raised. If set to\n +false+, an empty array will be returned\n @return [Array] List of +mask+ matching LsItems", "docstring_tokens": ["List", "contents", "of", "a", "remote", "directory"], "sha": "5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd", "url": "https://github.com/NetcomKassel/smb-client/blob/5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd/lib/smb/client/client_helper.rb#L14-L26", "partition": "valid"} {"repo": "NetcomKassel/smb-client", "path": "lib/smb/client/client_helper.rb", "func_name": "SMB.ClientHelper.put", "original_string": "def put(from, to, overwrite = false, raise = true)\n ls_items = ls to, false\n if !overwrite && !ls_items.empty?\n raise Client::RuntimeError, \"File [#{to}] already exist\"\n end\n from = '\"' + from + '\"' if from.include? ' '\n to = '\"' + to + '\"' if to.include? ' '\n exec 'put ' + from + ' ' + to\n true\n rescue Client::RuntimeError => e\n raise e if raise\n false\n end", "language": "ruby", "code": "def put(from, to, overwrite = false, raise = true)\n ls_items = ls to, false\n if !overwrite && !ls_items.empty?\n raise Client::RuntimeError, \"File [#{to}] already exist\"\n end\n from = '\"' + from + '\"' if from.include? ' '\n to = '\"' + to + '\"' if to.include? ' '\n exec 'put ' + from + ' ' + to\n true\n rescue Client::RuntimeError => e\n raise e if raise\n false\n end", "code_tokens": ["def", "put", "(", "from", ",", "to", ",", "overwrite", "=", "false", ",", "raise", "=", "true", ")", "ls_items", "=", "ls", "to", ",", "false", "if", "!", "overwrite", "&&", "!", "ls_items", ".", "empty?", "raise", "Client", "::", "RuntimeError", ",", "\"File [#{to}] already exist\"", "end", "from", "=", "'\"'", "+", "from", "+", "'\"'", "if", "from", ".", "include?", "' '", "to", "=", "'\"'", "+", "to", "+", "'\"'", "if", "to", ".", "include?", "' '", "exec", "'put '", "+", "from", "+", "' '", "+", "to", "true", "rescue", "Client", "::", "RuntimeError", "=>", "e", "raise", "e", "if", "raise", "false", "end"], "docstring": "Upload a local file\n @param [String] from The source file path (on local machine)\n @param [String] to The destination file path\n @param [Boolean] overwrite Overwrite if exist on server?\n @param [Boolean] raise raise Error or just return +false+\n @return [Boolean] true on success", "docstring_tokens": ["Upload", "a", "local", "file"], "sha": "5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd", "url": "https://github.com/NetcomKassel/smb-client/blob/5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd/lib/smb/client/client_helper.rb#L63-L75", "partition": "valid"} {"repo": "NetcomKassel/smb-client", "path": "lib/smb/client/client_helper.rb", "func_name": "SMB.ClientHelper.write", "original_string": "def write(content, to, overwrite = false, raise = true)\n # This is just a hack around +put+\n tempfile = Tempfile.new\n tempfile.write content\n tempfile.close\n\n put tempfile.path, to, overwrite, raise\n end", "language": "ruby", "code": "def write(content, to, overwrite = false, raise = true)\n # This is just a hack around +put+\n tempfile = Tempfile.new\n tempfile.write content\n tempfile.close\n\n put tempfile.path, to, overwrite, raise\n end", "code_tokens": ["def", "write", "(", "content", ",", "to", ",", "overwrite", "=", "false", ",", "raise", "=", "true", ")", "# This is just a hack around +put+", "tempfile", "=", "Tempfile", ".", "new", "tempfile", ".", "write", "content", "tempfile", ".", "close", "put", "tempfile", ".", "path", ",", "to", ",", "overwrite", ",", "raise", "end"], "docstring": "Writes content to remote file\n @param [String] content The content to be written\n @param [String] to The destination file path\n @param [Boolean] overwrite Overwrite if exist on server?\n @param [Boolean] raise raise Error or just return +false+\n @return [Boolean] true on success", "docstring_tokens": ["Writes", "content", "to", "remote", "file"], "sha": "5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd", "url": "https://github.com/NetcomKassel/smb-client/blob/5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd/lib/smb/client/client_helper.rb#L83-L90", "partition": "valid"} {"repo": "NetcomKassel/smb-client", "path": "lib/smb/client/client_helper.rb", "func_name": "SMB.ClientHelper.del", "original_string": "def del(path, raise = true)\n path = '\"' + path + '\"' if path.include? ' '\n exec 'del ' + path\n true\n rescue Client::RuntimeError => e\n raise e if raise\n false\n end", "language": "ruby", "code": "def del(path, raise = true)\n path = '\"' + path + '\"' if path.include? ' '\n exec 'del ' + path\n true\n rescue Client::RuntimeError => e\n raise e if raise\n false\n end", "code_tokens": ["def", "del", "(", "path", ",", "raise", "=", "true", ")", "path", "=", "'\"'", "+", "path", "+", "'\"'", "if", "path", ".", "include?", "' '", "exec", "'del '", "+", "path", "true", "rescue", "Client", "::", "RuntimeError", "=>", "e", "raise", "e", "if", "raise", "false", "end"], "docstring": "Delete a remote file\n @param [String] path The remote file to be deleted\n @param [Boolean] raise raise raise Error or just return +false+\n @return [Boolean] true on success", "docstring_tokens": ["Delete", "a", "remote", "file"], "sha": "5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd", "url": "https://github.com/NetcomKassel/smb-client/blob/5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd/lib/smb/client/client_helper.rb#L96-L103", "partition": "valid"} {"repo": "NetcomKassel/smb-client", "path": "lib/smb/client/client_helper.rb", "func_name": "SMB.ClientHelper.get", "original_string": "def get(from, to = nil, overwrite = false, raise = true)\n # Create a new tempfile but delete it\n # The tempfile.path should be free to use now\n tempfile = Tempfile.new\n to ||= tempfile.path\n tempfile.unlink\n\n if !overwrite && File.exist?(to)\n raise Client::RuntimeError, \"File [#{to}] already exist locally\"\n end\n from = '\"' + from + '\"' if from.include? ' '\n exec 'get ' + from + ' ' + to\n to\n rescue Client::RuntimeError => e\n raise e if raise\n false\n end", "language": "ruby", "code": "def get(from, to = nil, overwrite = false, raise = true)\n # Create a new tempfile but delete it\n # The tempfile.path should be free to use now\n tempfile = Tempfile.new\n to ||= tempfile.path\n tempfile.unlink\n\n if !overwrite && File.exist?(to)\n raise Client::RuntimeError, \"File [#{to}] already exist locally\"\n end\n from = '\"' + from + '\"' if from.include? ' '\n exec 'get ' + from + ' ' + to\n to\n rescue Client::RuntimeError => e\n raise e if raise\n false\n end", "code_tokens": ["def", "get", "(", "from", ",", "to", "=", "nil", ",", "overwrite", "=", "false", ",", "raise", "=", "true", ")", "# Create a new tempfile but delete it", "# The tempfile.path should be free to use now", "tempfile", "=", "Tempfile", ".", "new", "to", "||=", "tempfile", ".", "path", "tempfile", ".", "unlink", "if", "!", "overwrite", "&&", "File", ".", "exist?", "(", "to", ")", "raise", "Client", "::", "RuntimeError", ",", "\"File [#{to}] already exist locally\"", "end", "from", "=", "'\"'", "+", "from", "+", "'\"'", "if", "from", ".", "include?", "' '", "exec", "'get '", "+", "from", "+", "' '", "+", "to", "to", "rescue", "Client", "::", "RuntimeError", "=>", "e", "raise", "e", "if", "raise", "false", "end"], "docstring": "Receive a file from the smb server to local.\n If +to+ was not passed, a tempfile will be generated.\n @param [String] from The remote file to be read\n @param [String] to local file path to be created\n @param [Boolean] overwrite Overwrite if exist locally?\n @param [Boolean] raise raise Error or just return +false+\n @return [String] path to local file", "docstring_tokens": ["Receive", "a", "file", "from", "the", "smb", "server", "to", "local", ".", "If", "+", "to", "+", "was", "not", "passed", "a", "tempfile", "will", "be", "generated", "."], "sha": "5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd", "url": "https://github.com/NetcomKassel/smb-client/blob/5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd/lib/smb/client/client_helper.rb#L115-L131", "partition": "valid"} {"repo": "NetcomKassel/smb-client", "path": "lib/smb/client/client_helper.rb", "func_name": "SMB.ClientHelper.read", "original_string": "def read(from, overwrite = false, raise = true)\n tempfile = Tempfile.new\n to = tempfile.path\n tempfile.unlink\n get from, to, overwrite, raise\n File.read to\n end", "language": "ruby", "code": "def read(from, overwrite = false, raise = true)\n tempfile = Tempfile.new\n to = tempfile.path\n tempfile.unlink\n get from, to, overwrite, raise\n File.read to\n end", "code_tokens": ["def", "read", "(", "from", ",", "overwrite", "=", "false", ",", "raise", "=", "true", ")", "tempfile", "=", "Tempfile", ".", "new", "to", "=", "tempfile", ".", "path", "tempfile", ".", "unlink", "get", "from", ",", "to", ",", "overwrite", ",", "raise", "File", ".", "read", "to", "end"], "docstring": "Reads a remote file and return its content\n @param [String] from The file to be read from server\n @param [Boolean] overwrite Overwrite if exist locally?\n @param [Boolean] raise raise Error or just return +false+\n @return [String] The content of the remote file", "docstring_tokens": ["Reads", "a", "remote", "file", "and", "return", "its", "content"], "sha": "5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd", "url": "https://github.com/NetcomKassel/smb-client/blob/5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd/lib/smb/client/client_helper.rb#L138-L144", "partition": "valid"} {"repo": "NetcomKassel/smb-client", "path": "lib/smb/client/client.rb", "func_name": "SMB.Client.exec", "original_string": "def exec(cmd)\n # Send command\n @write1.puts cmd\n\n # Wait for response\n text = @read2.read\n\n # Close previous pipe\n @read2.close\n\n # Create new pipe\n @read2, @write2 = IO.pipe\n\n # Raise at the end to support continuing\n raise Client::RuntimeError, text if text.start_with? 'NT_STATUS_'\n\n text\n end", "language": "ruby", "code": "def exec(cmd)\n # Send command\n @write1.puts cmd\n\n # Wait for response\n text = @read2.read\n\n # Close previous pipe\n @read2.close\n\n # Create new pipe\n @read2, @write2 = IO.pipe\n\n # Raise at the end to support continuing\n raise Client::RuntimeError, text if text.start_with? 'NT_STATUS_'\n\n text\n end", "code_tokens": ["def", "exec", "(", "cmd", ")", "# Send command", "@write1", ".", "puts", "cmd", "# Wait for response", "text", "=", "@read2", ".", "read", "# Close previous pipe", "@read2", ".", "close", "# Create new pipe", "@read2", ",", "@write2", "=", "IO", ".", "pipe", "# Raise at the end to support continuing", "raise", "Client", "::", "RuntimeError", ",", "text", "if", "text", ".", "start_with?", "'NT_STATUS_'", "text", "end"], "docstring": "Execute a smbclient command\n @param [String] cmd The command to be executed", "docstring_tokens": ["Execute", "a", "smbclient", "command"], "sha": "5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd", "url": "https://github.com/NetcomKassel/smb-client/blob/5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd/lib/smb/client/client.rb#L54-L71", "partition": "valid"} {"repo": "NetcomKassel/smb-client", "path": "lib/smb/client/client.rb", "func_name": "SMB.Client.connect", "original_string": "def connect\n # Run +@executable+ in a separate thread to talk to hin asynchronously\n Thread.start do\n # Spawn the actual +@executable+ pty with +input+ and +output+ handle\n begin\n PTY.spawn(@executable + ' ' + params) do |output, input, pid|\n @pid = pid\n output.sync = true\n input.sync = true\n\n # Write inputs to pty from +exec+ method\n Thread.start do\n while (line = @read1.readline)\n input.puts line\n end\n end\n\n # Wait for responses ending with input prompt\n loop do\n output.expect(/smb: \\\\>$/) { |text| handle_response text }\n end\n end\n rescue Errno::EIO => e\n unless @shutdown_in_progress\n if @connection_established\n raise StandardError, \"Unexpected error: [#{e.message}]\"\n else\n raise Client::ConnectionError, 'Cannot connect to SMB server'\n end\n end\n end\n end\n end", "language": "ruby", "code": "def connect\n # Run +@executable+ in a separate thread to talk to hin asynchronously\n Thread.start do\n # Spawn the actual +@executable+ pty with +input+ and +output+ handle\n begin\n PTY.spawn(@executable + ' ' + params) do |output, input, pid|\n @pid = pid\n output.sync = true\n input.sync = true\n\n # Write inputs to pty from +exec+ method\n Thread.start do\n while (line = @read1.readline)\n input.puts line\n end\n end\n\n # Wait for responses ending with input prompt\n loop do\n output.expect(/smb: \\\\>$/) { |text| handle_response text }\n end\n end\n rescue Errno::EIO => e\n unless @shutdown_in_progress\n if @connection_established\n raise StandardError, \"Unexpected error: [#{e.message}]\"\n else\n raise Client::ConnectionError, 'Cannot connect to SMB server'\n end\n end\n end\n end\n end", "code_tokens": ["def", "connect", "# Run +@executable+ in a separate thread to talk to hin asynchronously", "Thread", ".", "start", "do", "# Spawn the actual +@executable+ pty with +input+ and +output+ handle", "begin", "PTY", ".", "spawn", "(", "@executable", "+", "' '", "+", "params", ")", "do", "|", "output", ",", "input", ",", "pid", "|", "@pid", "=", "pid", "output", ".", "sync", "=", "true", "input", ".", "sync", "=", "true", "# Write inputs to pty from +exec+ method", "Thread", ".", "start", "do", "while", "(", "line", "=", "@read1", ".", "readline", ")", "input", ".", "puts", "line", "end", "end", "# Wait for responses ending with input prompt", "loop", "do", "output", ".", "expect", "(", "/", "\\\\", "/", ")", "{", "|", "text", "|", "handle_response", "text", "}", "end", "end", "rescue", "Errno", "::", "EIO", "=>", "e", "unless", "@shutdown_in_progress", "if", "@connection_established", "raise", "StandardError", ",", "\"Unexpected error: [#{e.message}]\"", "else", "raise", "Client", "::", "ConnectionError", ",", "'Cannot connect to SMB server'", "end", "end", "end", "end", "end"], "docstring": "Connect to the server using separate threads and pipe for communications", "docstring_tokens": ["Connect", "to", "the", "server", "using", "separate", "threads", "and", "pipe", "for", "communications"], "sha": "5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd", "url": "https://github.com/NetcomKassel/smb-client/blob/5f6a24e5e7cc279ec5bb09f42efa1f4184444bcd/lib/smb/client/client.rb#L76-L108", "partition": "valid"} {"repo": "metanorma/iso-bib-item", "path": "lib/iso_bib_item/iso_bibliographic_item.rb", "func_name": "IsoBibItem.IsoBibliographicItem.to_all_parts", "original_string": "def to_all_parts\n me = DeepClone.clone(self)\n me.disable_id_attribute\n @relations << DocumentRelation.new(type: \"partOf\", identifier: nil, url: nil, bibitem: me)\n @title.each(&:remove_part)\n @abstract = []\n @docidentifier.each(&:remove_part)\n @docidentifier.each(&:all_parts)\n @all_parts = true\n end", "language": "ruby", "code": "def to_all_parts\n me = DeepClone.clone(self)\n me.disable_id_attribute\n @relations << DocumentRelation.new(type: \"partOf\", identifier: nil, url: nil, bibitem: me)\n @title.each(&:remove_part)\n @abstract = []\n @docidentifier.each(&:remove_part)\n @docidentifier.each(&:all_parts)\n @all_parts = true\n end", "code_tokens": ["def", "to_all_parts", "me", "=", "DeepClone", ".", "clone", "(", "self", ")", "me", ".", "disable_id_attribute", "@relations", "<<", "DocumentRelation", ".", "new", "(", "type", ":", "\"partOf\"", ",", "identifier", ":", "nil", ",", "url", ":", "nil", ",", "bibitem", ":", "me", ")", "@title", ".", "each", "(", ":remove_part", ")", "@abstract", "=", "[", "]", "@docidentifier", ".", "each", "(", ":remove_part", ")", "@docidentifier", ".", "each", "(", ":all_parts", ")", "@all_parts", "=", "true", "end"], "docstring": "remove title part components and abstract", "docstring_tokens": ["remove", "title", "part", "components", "and", "abstract"], "sha": "205ef2b5e4ce626cf9b65f3c39f613825b10db03", "url": "https://github.com/metanorma/iso-bib-item/blob/205ef2b5e4ce626cf9b65f3c39f613825b10db03/lib/iso_bib_item/iso_bibliographic_item.rb#L201-L210", "partition": "valid"} {"repo": "jico/automata", "path": "lib/automata/dfa.rb", "func_name": "Automata.DFA.valid?", "original_string": "def valid?\n # @todo Check that each state is connected.\n # Iterate through each states to verify the graph\n # is not disjoint.\n @transitions.each do |key, val|\n @alphabet.each do |a| \n return false unless @transitions[key].has_key? a.to_s\n end\n end\n return true\n end", "language": "ruby", "code": "def valid?\n # @todo Check that each state is connected.\n # Iterate through each states to verify the graph\n # is not disjoint.\n @transitions.each do |key, val|\n @alphabet.each do |a| \n return false unless @transitions[key].has_key? a.to_s\n end\n end\n return true\n end", "code_tokens": ["def", "valid?", "# @todo Check that each state is connected.", "# Iterate through each states to verify the graph", "# is not disjoint.", "@transitions", ".", "each", "do", "|", "key", ",", "val", "|", "@alphabet", ".", "each", "do", "|", "a", "|", "return", "false", "unless", "@transitions", "[", "key", "]", ".", "has_key?", "a", ".", "to_s", "end", "end", "return", "true", "end"], "docstring": "Verifies that the initialized DFA is valid.\n Checks that each state has a transition for each\n symbol in the alphabet.\n\n @return [Boolean] whether or not the DFA is valid.", "docstring_tokens": ["Verifies", "that", "the", "initialized", "DFA", "is", "valid", ".", "Checks", "that", "each", "state", "has", "a", "transition", "for", "each", "symbol", "in", "the", "alphabet", "."], "sha": "177cea186de1d55be2f1d2ed1a78c313f74945a1", "url": "https://github.com/jico/automata/blob/177cea186de1d55be2f1d2ed1a78c313f74945a1/lib/automata/dfa.rb#L9-L19", "partition": "valid"} {"repo": "jico/automata", "path": "lib/automata/dfa.rb", "func_name": "Automata.DFA.feed", "original_string": "def feed(input)\n head = @start.to_s\n input.each_char { |symbol| head = @transitions[head][symbol] }\n accept = is_accept_state? head\n resp = {\n input: input,\n accept: accept,\n head: head \n }\n resp\n end", "language": "ruby", "code": "def feed(input)\n head = @start.to_s\n input.each_char { |symbol| head = @transitions[head][symbol] }\n accept = is_accept_state? head\n resp = {\n input: input,\n accept: accept,\n head: head \n }\n resp\n end", "code_tokens": ["def", "feed", "(", "input", ")", "head", "=", "@start", ".", "to_s", "input", ".", "each_char", "{", "|", "symbol", "|", "head", "=", "@transitions", "[", "head", "]", "[", "symbol", "]", "}", "accept", "=", "is_accept_state?", "head", "resp", "=", "{", "input", ":", "input", ",", "accept", ":", "accept", ",", "head", ":", "head", "}", "resp", "end"], "docstring": "Runs the input on the machine and returns a Hash describing\n the machine's final state after running.\n\n @param [String] input the string to use as input for the DFA\n @return [Hash] a hash describing the DFA state after running\n * :input [String] the original input string\n * :accept [Boolean] whether or not the DFA accepted the string\n * :head [String] the state which the head is currently on", "docstring_tokens": ["Runs", "the", "input", "on", "the", "machine", "and", "returns", "a", "Hash", "describing", "the", "machine", "s", "final", "state", "after", "running", "."], "sha": "177cea186de1d55be2f1d2ed1a78c313f74945a1", "url": "https://github.com/jico/automata/blob/177cea186de1d55be2f1d2ed1a78c313f74945a1/lib/automata/dfa.rb#L29-L39", "partition": "valid"} {"repo": "bmuller/hbaserb", "path": "lib/hbaserb/table.rb", "func_name": "HBaseRb.Table.create_scanner", "original_string": "def create_scanner(start_row=nil, end_row=nil, *columns, &block)\n columns = (columns.length > 0) ? columns : column_families.keys \n\n sid = call :scannerOpenWithStop, start_row.to_s, end_row.to_s, columns\n Scanner.new @client, sid, &block\n end", "language": "ruby", "code": "def create_scanner(start_row=nil, end_row=nil, *columns, &block)\n columns = (columns.length > 0) ? columns : column_families.keys \n\n sid = call :scannerOpenWithStop, start_row.to_s, end_row.to_s, columns\n Scanner.new @client, sid, &block\n end", "code_tokens": ["def", "create_scanner", "(", "start_row", "=", "nil", ",", "end_row", "=", "nil", ",", "*", "columns", ",", "&", "block", ")", "columns", "=", "(", "columns", ".", "length", ">", "0", ")", "?", "columns", ":", "column_families", ".", "keys", "sid", "=", "call", ":scannerOpenWithStop", ",", "start_row", ".", "to_s", ",", "end_row", ".", "to_s", ",", "columns", "Scanner", ".", "new", "@client", ",", "sid", ",", "block", "end"], "docstring": "pass in no params to scan whole table", "docstring_tokens": ["pass", "in", "no", "params", "to", "scan", "whole", "table"], "sha": "cc8a323daef375b63382259f7dc85d00e2727531", "url": "https://github.com/bmuller/hbaserb/blob/cc8a323daef375b63382259f7dc85d00e2727531/lib/hbaserb/table.rb#L49-L54", "partition": "valid"} {"repo": "jico/automata", "path": "lib/automata/turing.rb", "func_name": "Automata.Tape.transition", "original_string": "def transition(read, write, move)\n if read == @memory[@head]\n @memory[@head] = write\n case move\n when 'R'\n # Move right\n @memory << '@' if @memory[@head + 1]\n @head += 1\n when 'L'\n # Move left\n @memory.unshift('@') if @head == 0\n @head -= 1\n end\n return true\n else\n return false\n end\n end", "language": "ruby", "code": "def transition(read, write, move)\n if read == @memory[@head]\n @memory[@head] = write\n case move\n when 'R'\n # Move right\n @memory << '@' if @memory[@head + 1]\n @head += 1\n when 'L'\n # Move left\n @memory.unshift('@') if @head == 0\n @head -= 1\n end\n return true\n else\n return false\n end\n end", "code_tokens": ["def", "transition", "(", "read", ",", "write", ",", "move", ")", "if", "read", "==", "@memory", "[", "@head", "]", "@memory", "[", "@head", "]", "=", "write", "case", "move", "when", "'R'", "# Move right", "@memory", "<<", "'@'", "if", "@memory", "[", "@head", "+", "1", "]", "@head", "+=", "1", "when", "'L'", "# Move left", "@memory", ".", "unshift", "(", "'@'", ")", "if", "@head", "==", "0", "@head", "-=", "1", "end", "return", "true", "else", "return", "false", "end", "end"], "docstring": "Creates a new tape.\n\n @param [String] string the input string\n Transitions the tape.\n\n @param [String] read the input symbol read\n @param [String] write the symbol to write\n @param [String] move Either 'L', 'R', or 'S' (default) to\n move left, right, or stay, respectively.\n @return [Boolean] whether the transition succeeded", "docstring_tokens": ["Creates", "a", "new", "tape", "."], "sha": "177cea186de1d55be2f1d2ed1a78c313f74945a1", "url": "https://github.com/jico/automata/blob/177cea186de1d55be2f1d2ed1a78c313f74945a1/lib/automata/turing.rb#L130-L147", "partition": "valid"} {"repo": "jico/automata", "path": "lib/automata/pda.rb", "func_name": "Automata.PDA.feed", "original_string": "def feed(input)\n heads, @stack, accept = [@start], [], false\n \n # Move any initial e-transitions\n eTrans = transition(@start, '&') if has_transition?(@start, '&')\n heads += eTrans\n\n puts \"initial heads: #{heads}\"\n puts \"initial stack: #{@stack}\"\n\n # Iterate through each symbol of input string\n input.each_char do |symbol|\n newHeads = []\n \n puts \"Reading symbol: #{symbol}\"\n\n heads.each do |head|\n puts \"At head #{head}\"\n\n # Check if head can transition read symbol\n # Head dies if no transition for symbol\n if has_transition?(head, symbol)\n puts \"Head #{head} transitions #{symbol}\"\n puts \"stack: #{@stack}\"\n transition(head, symbol).each { |t| newHeads << t }\n puts \"heads: #{newHeads}\"\n puts \"stack: #{@stack}\"\n end\n\n end\n \n heads = newHeads\n break if heads.empty?\n end\n\n puts \"Loop finished\"\n \n accept = includes_accept_state? heads\n\n puts \"heads: #{heads}\"\n puts \"stack: #{stack}\"\n puts \"accept: #{accept}\"\n\n resp = {\n input: input,\n accept: accept,\n heads: heads,\n stack: stack\n }\n end", "language": "ruby", "code": "def feed(input)\n heads, @stack, accept = [@start], [], false\n \n # Move any initial e-transitions\n eTrans = transition(@start, '&') if has_transition?(@start, '&')\n heads += eTrans\n\n puts \"initial heads: #{heads}\"\n puts \"initial stack: #{@stack}\"\n\n # Iterate through each symbol of input string\n input.each_char do |symbol|\n newHeads = []\n \n puts \"Reading symbol: #{symbol}\"\n\n heads.each do |head|\n puts \"At head #{head}\"\n\n # Check if head can transition read symbol\n # Head dies if no transition for symbol\n if has_transition?(head, symbol)\n puts \"Head #{head} transitions #{symbol}\"\n puts \"stack: #{@stack}\"\n transition(head, symbol).each { |t| newHeads << t }\n puts \"heads: #{newHeads}\"\n puts \"stack: #{@stack}\"\n end\n\n end\n \n heads = newHeads\n break if heads.empty?\n end\n\n puts \"Loop finished\"\n \n accept = includes_accept_state? heads\n\n puts \"heads: #{heads}\"\n puts \"stack: #{stack}\"\n puts \"accept: #{accept}\"\n\n resp = {\n input: input,\n accept: accept,\n heads: heads,\n stack: stack\n }\n end", "code_tokens": ["def", "feed", "(", "input", ")", "heads", ",", "@stack", ",", "accept", "=", "[", "@start", "]", ",", "[", "]", ",", "false", "# Move any initial e-transitions", "eTrans", "=", "transition", "(", "@start", ",", "'&'", ")", "if", "has_transition?", "(", "@start", ",", "'&'", ")", "heads", "+=", "eTrans", "puts", "\"initial heads: #{heads}\"", "puts", "\"initial stack: #{@stack}\"", "# Iterate through each symbol of input string", "input", ".", "each_char", "do", "|", "symbol", "|", "newHeads", "=", "[", "]", "puts", "\"Reading symbol: #{symbol}\"", "heads", ".", "each", "do", "|", "head", "|", "puts", "\"At head #{head}\"", "# Check if head can transition read symbol", "# Head dies if no transition for symbol", "if", "has_transition?", "(", "head", ",", "symbol", ")", "puts", "\"Head #{head} transitions #{symbol}\"", "puts", "\"stack: #{@stack}\"", "transition", "(", "head", ",", "symbol", ")", ".", "each", "{", "|", "t", "|", "newHeads", "<<", "t", "}", "puts", "\"heads: #{newHeads}\"", "puts", "\"stack: #{@stack}\"", "end", "end", "heads", "=", "newHeads", "break", "if", "heads", ".", "empty?", "end", "puts", "\"Loop finished\"", "accept", "=", "includes_accept_state?", "heads", "puts", "\"heads: #{heads}\"", "puts", "\"stack: #{stack}\"", "puts", "\"accept: #{accept}\"", "resp", "=", "{", "input", ":", "input", ",", "accept", ":", "accept", ",", "heads", ":", "heads", ",", "stack", ":", "stack", "}", "end"], "docstring": "Initialize a PDA object.\n Runs the input on the machine and returns a Hash describing\n the machine's final state after running.\n\n @param [String] input the string to use as input for the PDA\n @return [Hash] a hash describing the PDA state after running\n * :input [String] the original input string\n * :accept [Boolean] whether or not the PDA accepted the string\n * :heads [Array] the state which the head is currently on", "docstring_tokens": ["Initialize", "a", "PDA", "object", ".", "Runs", "the", "input", "on", "the", "machine", "and", "returns", "a", "Hash", "describing", "the", "machine", "s", "final", "state", "after", "running", "."], "sha": "177cea186de1d55be2f1d2ed1a78c313f74945a1", "url": "https://github.com/jico/automata/blob/177cea186de1d55be2f1d2ed1a78c313f74945a1/lib/automata/pda.rb#L21-L70", "partition": "valid"} {"repo": "jico/automata", "path": "lib/automata/pda.rb", "func_name": "Automata.PDA.has_transition?", "original_string": "def has_transition?(state, symbol)\n return false unless @transitions.has_key? state\n if @transitions[state].has_key? symbol\n actions = @transitions[state][symbol]\n return false if actions['pop'] && @stack.last != actions['pop']\n return true\n else\n return false\n end\n end", "language": "ruby", "code": "def has_transition?(state, symbol)\n return false unless @transitions.has_key? state\n if @transitions[state].has_key? symbol\n actions = @transitions[state][symbol]\n return false if actions['pop'] && @stack.last != actions['pop']\n return true\n else\n return false\n end\n end", "code_tokens": ["def", "has_transition?", "(", "state", ",", "symbol", ")", "return", "false", "unless", "@transitions", ".", "has_key?", "state", "if", "@transitions", "[", "state", "]", ".", "has_key?", "symbol", "actions", "=", "@transitions", "[", "state", "]", "[", "symbol", "]", "return", "false", "if", "actions", "[", "'pop'", "]", "&&", "@stack", ".", "last", "!=", "actions", "[", "'pop'", "]", "return", "true", "else", "return", "false", "end", "end"], "docstring": "Determines whether or not any transition states exist\n given a beginning state and input symbol pair.\n\n @param (see #transition)\n @return [Boolean] Whether or not a transition exists.", "docstring_tokens": ["Determines", "whether", "or", "not", "any", "transition", "states", "exist", "given", "a", "beginning", "state", "and", "input", "symbol", "pair", "."], "sha": "177cea186de1d55be2f1d2ed1a78c313f74945a1", "url": "https://github.com/jico/automata/blob/177cea186de1d55be2f1d2ed1a78c313f74945a1/lib/automata/pda.rb#L135-L144", "partition": "valid"} {"repo": "kickstarter/amazon_flex_pay", "path": "lib/amazon_flex_pay/model.rb", "func_name": "AmazonFlexPay.Model.to_hash", "original_string": "def to_hash\n self.class.attribute_names.inject({}) do |hash, name|\n val = format_value(send(name.underscore))\n val.empty? ? hash : hash.merge(format_key(name) => val)\n end\n end", "language": "ruby", "code": "def to_hash\n self.class.attribute_names.inject({}) do |hash, name|\n val = format_value(send(name.underscore))\n val.empty? ? hash : hash.merge(format_key(name) => val)\n end\n end", "code_tokens": ["def", "to_hash", "self", ".", "class", ".", "attribute_names", ".", "inject", "(", "{", "}", ")", "do", "|", "hash", ",", "name", "|", "val", "=", "format_value", "(", "send", "(", "name", ".", "underscore", ")", ")", "val", ".", "empty?", "?", "hash", ":", "hash", ".", "merge", "(", "format_key", "(", "name", ")", "=>", "val", ")", "end", "end"], "docstring": "Formats all attributes into a hash of parameters.", "docstring_tokens": ["Formats", "all", "attributes", "into", "a", "hash", "of", "parameters", "."], "sha": "5a4cbc608b41858a2db2f6a44884aa4efee77c1e", "url": "https://github.com/kickstarter/amazon_flex_pay/blob/5a4cbc608b41858a2db2f6a44884aa4efee77c1e/lib/amazon_flex_pay/model.rb#L100-L105", "partition": "valid"} {"repo": "kickstarter/amazon_flex_pay", "path": "lib/amazon_flex_pay/model.rb", "func_name": "AmazonFlexPay.Model.format_value", "original_string": "def format_value(val)\n case val\n when AmazonFlexPay::Model\n val.to_hash\n\n when Time\n val.utc.strftime('%Y-%m-%dT%H:%M:%SZ')\n\n when TrueClass, FalseClass\n val.to_s.capitalize\n\n when Array\n val.join(',')\n\n else\n val.to_s\n end\n end", "language": "ruby", "code": "def format_value(val)\n case val\n when AmazonFlexPay::Model\n val.to_hash\n\n when Time\n val.utc.strftime('%Y-%m-%dT%H:%M:%SZ')\n\n when TrueClass, FalseClass\n val.to_s.capitalize\n\n when Array\n val.join(',')\n\n else\n val.to_s\n end\n end", "code_tokens": ["def", "format_value", "(", "val", ")", "case", "val", "when", "AmazonFlexPay", "::", "Model", "val", ".", "to_hash", "when", "Time", "val", ".", "utc", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", "when", "TrueClass", ",", "FalseClass", "val", ".", "to_s", ".", "capitalize", "when", "Array", "val", ".", "join", "(", "','", ")", "else", "val", ".", "to_s", "end", "end"], "docstring": "Formats times and booleans as Amazon desires them.", "docstring_tokens": ["Formats", "times", "and", "booleans", "as", "Amazon", "desires", "them", "."], "sha": "5a4cbc608b41858a2db2f6a44884aa4efee77c1e", "url": "https://github.com/kickstarter/amazon_flex_pay/blob/5a4cbc608b41858a2db2f6a44884aa4efee77c1e/lib/amazon_flex_pay/model.rb#L115-L132", "partition": "valid"} {"repo": "kickstarter/amazon_flex_pay", "path": "lib/amazon_flex_pay/model.rb", "func_name": "AmazonFlexPay.Model.assign", "original_string": "def assign(hash)\n hash.each do |k, v|\n send(\"#{k.to_s.underscore}=\", v.respond_to?(:strip) ? v.strip : v)\n end\n end", "language": "ruby", "code": "def assign(hash)\n hash.each do |k, v|\n send(\"#{k.to_s.underscore}=\", v.respond_to?(:strip) ? v.strip : v)\n end\n end", "code_tokens": ["def", "assign", "(", "hash", ")", "hash", ".", "each", "do", "|", "k", ",", "v", "|", "send", "(", "\"#{k.to_s.underscore}=\"", ",", "v", ".", "respond_to?", "(", ":strip", ")", "?", "v", ".", "strip", ":", "v", ")", "end", "end"], "docstring": "Allows easy initialization for a model by assigning attributes from a hash.", "docstring_tokens": ["Allows", "easy", "initialization", "for", "a", "model", "by", "assigning", "attributes", "from", "a", "hash", "."], "sha": "5a4cbc608b41858a2db2f6a44884aa4efee77c1e", "url": "https://github.com/kickstarter/amazon_flex_pay/blob/5a4cbc608b41858a2db2f6a44884aa4efee77c1e/lib/amazon_flex_pay/model.rb#L135-L139", "partition": "valid"} {"repo": "kickstarter/amazon_flex_pay", "path": "lib/amazon_flex_pay/pipelines.rb", "func_name": "AmazonFlexPay.Pipelines.edit_token_pipeline", "original_string": "def edit_token_pipeline(caller_reference, return_url, options = {})\n cbui EditToken.new(options.merge(:caller_reference => caller_reference, :return_url => return_url))\n end", "language": "ruby", "code": "def edit_token_pipeline(caller_reference, return_url, options = {})\n cbui EditToken.new(options.merge(:caller_reference => caller_reference, :return_url => return_url))\n end", "code_tokens": ["def", "edit_token_pipeline", "(", "caller_reference", ",", "return_url", ",", "options", "=", "{", "}", ")", "cbui", "EditToken", ".", "new", "(", "options", ".", "merge", "(", ":caller_reference", "=>", "caller_reference", ",", ":return_url", "=>", "return_url", ")", ")", "end"], "docstring": "Creates a pipeline that may be used to change the payment method of a token.\n\n Note that this does not allow changing a token's limits or recipients or really anything but the method.\n\n See http://docs.amazonwebservices.com/AmazonFPS/latest/FPSAdvancedGuide/EditTokenPipeline.html", "docstring_tokens": ["Creates", "a", "pipeline", "that", "may", "be", "used", "to", "change", "the", "payment", "method", "of", "a", "token", "."], "sha": "5a4cbc608b41858a2db2f6a44884aa4efee77c1e", "url": "https://github.com/kickstarter/amazon_flex_pay/blob/5a4cbc608b41858a2db2f6a44884aa4efee77c1e/lib/amazon_flex_pay/pipelines.rb#L11-L13", "partition": "valid"} {"repo": "kickstarter/amazon_flex_pay", "path": "lib/amazon_flex_pay/pipelines.rb", "func_name": "AmazonFlexPay.Pipelines.multi_use_pipeline", "original_string": "def multi_use_pipeline(caller_reference, return_url, options = {})\n cbui MultiUse.new(options.merge(:caller_reference => caller_reference, :return_url => return_url))\n end", "language": "ruby", "code": "def multi_use_pipeline(caller_reference, return_url, options = {})\n cbui MultiUse.new(options.merge(:caller_reference => caller_reference, :return_url => return_url))\n end", "code_tokens": ["def", "multi_use_pipeline", "(", "caller_reference", ",", "return_url", ",", "options", "=", "{", "}", ")", "cbui", "MultiUse", ".", "new", "(", "options", ".", "merge", "(", ":caller_reference", "=>", "caller_reference", ",", ":return_url", "=>", "return_url", ")", ")", "end"], "docstring": "Creates a pipeline that will authorize you to send money _from_ the user multiple times.\n\n This is also necessary to create sender tokens that are valid for a long period of time, even if\n you only plan to collect from the token once.\n\n See http://docs.amazonwebservices.com/AmazonFPS/latest/FPSAdvancedGuide/MultiUsePipeline.html", "docstring_tokens": ["Creates", "a", "pipeline", "that", "will", "authorize", "you", "to", "send", "money", "_from_", "the", "user", "multiple", "times", "."], "sha": "5a4cbc608b41858a2db2f6a44884aa4efee77c1e", "url": "https://github.com/kickstarter/amazon_flex_pay/blob/5a4cbc608b41858a2db2f6a44884aa4efee77c1e/lib/amazon_flex_pay/pipelines.rb#L21-L23", "partition": "valid"} {"repo": "kickstarter/amazon_flex_pay", "path": "lib/amazon_flex_pay/pipelines.rb", "func_name": "AmazonFlexPay.Pipelines.recipient_pipeline", "original_string": "def recipient_pipeline(caller_reference, return_url, options = {})\n cbui Recipient.new(options.merge(:caller_reference => caller_reference, :return_url => return_url))\n end", "language": "ruby", "code": "def recipient_pipeline(caller_reference, return_url, options = {})\n cbui Recipient.new(options.merge(:caller_reference => caller_reference, :return_url => return_url))\n end", "code_tokens": ["def", "recipient_pipeline", "(", "caller_reference", ",", "return_url", ",", "options", "=", "{", "}", ")", "cbui", "Recipient", ".", "new", "(", "options", ".", "merge", "(", ":caller_reference", "=>", "caller_reference", ",", ":return_url", "=>", "return_url", ")", ")", "end"], "docstring": "Creates a pipeline that will authorize you to send money _to_ the user.\n\n See http://docs.amazonwebservices.com/AmazonFPS/latest/FPSAdvancedGuide/CBUIapiMerchant.html", "docstring_tokens": ["Creates", "a", "pipeline", "that", "will", "authorize", "you", "to", "send", "money", "_to_", "the", "user", "."], "sha": "5a4cbc608b41858a2db2f6a44884aa4efee77c1e", "url": "https://github.com/kickstarter/amazon_flex_pay/blob/5a4cbc608b41858a2db2f6a44884aa4efee77c1e/lib/amazon_flex_pay/pipelines.rb#L28-L30", "partition": "valid"} {"repo": "kickstarter/amazon_flex_pay", "path": "lib/amazon_flex_pay/pipelines.rb", "func_name": "AmazonFlexPay.Pipelines.single_use_pipeline", "original_string": "def single_use_pipeline(caller_reference, return_url, options = {})\n cbui SingleUse.new(options.merge(:caller_reference => caller_reference, :return_url => return_url))\n end", "language": "ruby", "code": "def single_use_pipeline(caller_reference, return_url, options = {})\n cbui SingleUse.new(options.merge(:caller_reference => caller_reference, :return_url => return_url))\n end", "code_tokens": ["def", "single_use_pipeline", "(", "caller_reference", ",", "return_url", ",", "options", "=", "{", "}", ")", "cbui", "SingleUse", ".", "new", "(", "options", ".", "merge", "(", ":caller_reference", "=>", "caller_reference", ",", ":return_url", "=>", "return_url", ")", ")", "end"], "docstring": "Creates a pipeline that will authorize you to send money _from_ the user one time.\n\n Note that if this payment fails, you must create another pipeline to get another token.\n\n See http://docs.amazonwebservices.com/AmazonFPS/2010-08-28/FPSBasicGuide/SingleUsePipeline.html", "docstring_tokens": ["Creates", "a", "pipeline", "that", "will", "authorize", "you", "to", "send", "money", "_from_", "the", "user", "one", "time", "."], "sha": "5a4cbc608b41858a2db2f6a44884aa4efee77c1e", "url": "https://github.com/kickstarter/amazon_flex_pay/blob/5a4cbc608b41858a2db2f6a44884aa4efee77c1e/lib/amazon_flex_pay/pipelines.rb#L37-L39", "partition": "valid"} {"repo": "kickstarter/amazon_flex_pay", "path": "lib/amazon_flex_pay/pipelines/base.rb", "func_name": "AmazonFlexPay::Pipelines.Base.to_param", "original_string": "def to_param\n params = to_hash.merge(\n 'callerKey' => AmazonFlexPay.access_key,\n 'signatureVersion' => 2,\n 'signatureMethod' => 'HmacSHA256'\n )\n params['signature'] = AmazonFlexPay.sign(AmazonFlexPay.pipeline_endpoint, params)\n AmazonFlexPay::Util.query_string(params)\n end", "language": "ruby", "code": "def to_param\n params = to_hash.merge(\n 'callerKey' => AmazonFlexPay.access_key,\n 'signatureVersion' => 2,\n 'signatureMethod' => 'HmacSHA256'\n )\n params['signature'] = AmazonFlexPay.sign(AmazonFlexPay.pipeline_endpoint, params)\n AmazonFlexPay::Util.query_string(params)\n end", "code_tokens": ["def", "to_param", "params", "=", "to_hash", ".", "merge", "(", "'callerKey'", "=>", "AmazonFlexPay", ".", "access_key", ",", "'signatureVersion'", "=>", "2", ",", "'signatureMethod'", "=>", "'HmacSHA256'", ")", "params", "[", "'signature'", "]", "=", "AmazonFlexPay", ".", "sign", "(", "AmazonFlexPay", ".", "pipeline_endpoint", ",", "params", ")", "AmazonFlexPay", "::", "Util", ".", "query_string", "(", "params", ")", "end"], "docstring": "Converts the Pipeline object into parameters and signs them.", "docstring_tokens": ["Converts", "the", "Pipeline", "object", "into", "parameters", "and", "signs", "them", "."], "sha": "5a4cbc608b41858a2db2f6a44884aa4efee77c1e", "url": "https://github.com/kickstarter/amazon_flex_pay/blob/5a4cbc608b41858a2db2f6a44884aa4efee77c1e/lib/amazon_flex_pay/pipelines/base.rb#L15-L23", "partition": "valid"} {"repo": "kickstarter/amazon_flex_pay", "path": "lib/amazon_flex_pay/api.rb", "func_name": "AmazonFlexPay.API.get_account_activity", "original_string": "def get_account_activity(start_date, end_date, options = {})\n submit GetAccountActivity.new(options.merge(:start_date => start_date, :end_date => end_date))\n end", "language": "ruby", "code": "def get_account_activity(start_date, end_date, options = {})\n submit GetAccountActivity.new(options.merge(:start_date => start_date, :end_date => end_date))\n end", "code_tokens": ["def", "get_account_activity", "(", "start_date", ",", "end_date", ",", "options", "=", "{", "}", ")", "submit", "GetAccountActivity", ".", "new", "(", "options", ".", "merge", "(", ":start_date", "=>", "start_date", ",", ":end_date", "=>", "end_date", ")", ")", "end"], "docstring": "Searches through transactions on your account. Helpful if you want to compare vs your own records,\n or print an admin report.\n\n See http://docs.amazonwebservices.com/AmazonFPS/latest/FPSAccountManagementGuide/GetAccountActivity.html", "docstring_tokens": ["Searches", "through", "transactions", "on", "your", "account", ".", "Helpful", "if", "you", "want", "to", "compare", "vs", "your", "own", "records", "or", "print", "an", "admin", "report", "."], "sha": "5a4cbc608b41858a2db2f6a44884aa4efee77c1e", "url": "https://github.com/kickstarter/amazon_flex_pay/blob/5a4cbc608b41858a2db2f6a44884aa4efee77c1e/lib/amazon_flex_pay/api.rb#L24-L26", "partition": "valid"} {"repo": "kickstarter/amazon_flex_pay", "path": "lib/amazon_flex_pay/api.rb", "func_name": "AmazonFlexPay.API.refund", "original_string": "def refund(transaction_id, caller_reference, options = {})\n submit Refund.new(options.merge(:transaction_id => transaction_id, :caller_reference => caller_reference))\n end", "language": "ruby", "code": "def refund(transaction_id, caller_reference, options = {})\n submit Refund.new(options.merge(:transaction_id => transaction_id, :caller_reference => caller_reference))\n end", "code_tokens": ["def", "refund", "(", "transaction_id", ",", "caller_reference", ",", "options", "=", "{", "}", ")", "submit", "Refund", ".", "new", "(", "options", ".", "merge", "(", ":transaction_id", "=>", "transaction_id", ",", ":caller_reference", "=>", "caller_reference", ")", ")", "end"], "docstring": "Refunds a transaction. By default it will refund the entire transaction, but you can\n provide an amount for partial refunds.\n\n Sign up for Instant Payment Notifications to be told when this has finished.\n\n See http://docs.amazonwebservices.com/AmazonFPS/latest/FPSAdvancedGuide/Refund.html", "docstring_tokens": ["Refunds", "a", "transaction", ".", "By", "default", "it", "will", "refund", "the", "entire", "transaction", "but", "you", "can", "provide", "an", "amount", "for", "partial", "refunds", "."], "sha": "5a4cbc608b41858a2db2f6a44884aa4efee77c1e", "url": "https://github.com/kickstarter/amazon_flex_pay/blob/5a4cbc608b41858a2db2f6a44884aa4efee77c1e/lib/amazon_flex_pay/api.rb#L128-L130", "partition": "valid"} {"repo": "kickstarter/amazon_flex_pay", "path": "lib/amazon_flex_pay/api.rb", "func_name": "AmazonFlexPay.API.verify_request", "original_string": "def verify_request(request)\n verify_signature(\n # url without query string\n request.protocol + request.host_with_port + request.path,\n # raw parameters\n request.get? ? request.query_string : request.raw_post\n )\n end", "language": "ruby", "code": "def verify_request(request)\n verify_signature(\n # url without query string\n request.protocol + request.host_with_port + request.path,\n # raw parameters\n request.get? ? request.query_string : request.raw_post\n )\n end", "code_tokens": ["def", "verify_request", "(", "request", ")", "verify_signature", "(", "# url without query string", "request", ".", "protocol", "+", "request", ".", "host_with_port", "+", "request", ".", "path", ",", "# raw parameters", "request", ".", "get?", "?", "request", ".", "query_string", ":", "request", ".", "raw_post", ")", "end"], "docstring": "This is how you verify IPNs and pipeline responses.\n Pass the entire request object.", "docstring_tokens": ["This", "is", "how", "you", "verify", "IPNs", "and", "pipeline", "responses", ".", "Pass", "the", "entire", "request", "object", "."], "sha": "5a4cbc608b41858a2db2f6a44884aa4efee77c1e", "url": "https://github.com/kickstarter/amazon_flex_pay/blob/5a4cbc608b41858a2db2f6a44884aa4efee77c1e/lib/amazon_flex_pay/api.rb#L143-L150", "partition": "valid"} {"repo": "kickstarter/amazon_flex_pay", "path": "lib/amazon_flex_pay/api.rb", "func_name": "AmazonFlexPay.API.submit", "original_string": "def submit(request)\n url = request.to_url\n ActiveSupport::Notifications.instrument(\"amazon_flex_pay.api\", :action => request.action_name, :request => url) do |payload|\n begin\n http = RestClient.get(url)\n\n payload[:response] = http.body\n payload[:code] = http.code\n\n response = request.class::Response.from_xml(http.body)\n response.request = request\n response\n\n rescue RestClient::BadRequest, RestClient::Unauthorized, RestClient::Forbidden => e\n payload[:response] = e.http_body\n payload[:code] = e.http_code\n\n er = AmazonFlexPay::API::BaseRequest::ErrorResponse.from_xml(e.response.body)\n klass = AmazonFlexPay::API.const_get(er.errors.first.code)\n raise klass.new(er.errors.first.code, er.errors.first.message, er.request_id, request)\n end\n end\n end", "language": "ruby", "code": "def submit(request)\n url = request.to_url\n ActiveSupport::Notifications.instrument(\"amazon_flex_pay.api\", :action => request.action_name, :request => url) do |payload|\n begin\n http = RestClient.get(url)\n\n payload[:response] = http.body\n payload[:code] = http.code\n\n response = request.class::Response.from_xml(http.body)\n response.request = request\n response\n\n rescue RestClient::BadRequest, RestClient::Unauthorized, RestClient::Forbidden => e\n payload[:response] = e.http_body\n payload[:code] = e.http_code\n\n er = AmazonFlexPay::API::BaseRequest::ErrorResponse.from_xml(e.response.body)\n klass = AmazonFlexPay::API.const_get(er.errors.first.code)\n raise klass.new(er.errors.first.code, er.errors.first.message, er.request_id, request)\n end\n end\n end", "code_tokens": ["def", "submit", "(", "request", ")", "url", "=", "request", ".", "to_url", "ActiveSupport", "::", "Notifications", ".", "instrument", "(", "\"amazon_flex_pay.api\"", ",", ":action", "=>", "request", ".", "action_name", ",", ":request", "=>", "url", ")", "do", "|", "payload", "|", "begin", "http", "=", "RestClient", ".", "get", "(", "url", ")", "payload", "[", ":response", "]", "=", "http", ".", "body", "payload", "[", ":code", "]", "=", "http", ".", "code", "response", "=", "request", ".", "class", "::", "Response", ".", "from_xml", "(", "http", ".", "body", ")", "response", ".", "request", "=", "request", "response", "rescue", "RestClient", "::", "BadRequest", ",", "RestClient", "::", "Unauthorized", ",", "RestClient", "::", "Forbidden", "=>", "e", "payload", "[", ":response", "]", "=", "e", ".", "http_body", "payload", "[", ":code", "]", "=", "e", ".", "http_code", "er", "=", "AmazonFlexPay", "::", "API", "::", "BaseRequest", "::", "ErrorResponse", ".", "from_xml", "(", "e", ".", "response", ".", "body", ")", "klass", "=", "AmazonFlexPay", "::", "API", ".", "const_get", "(", "er", ".", "errors", ".", "first", ".", "code", ")", "raise", "klass", ".", "new", "(", "er", ".", "errors", ".", "first", ".", "code", ",", "er", ".", "errors", ".", "first", ".", "message", ",", "er", ".", "request_id", ",", "request", ")", "end", "end", "end"], "docstring": "This compiles an API request object into a URL, sends it to Amazon, and processes\n the response.", "docstring_tokens": ["This", "compiles", "an", "API", "request", "object", "into", "a", "URL", "sends", "it", "to", "Amazon", "and", "processes", "the", "response", "."], "sha": "5a4cbc608b41858a2db2f6a44884aa4efee77c1e", "url": "https://github.com/kickstarter/amazon_flex_pay/blob/5a4cbc608b41858a2db2f6a44884aa4efee77c1e/lib/amazon_flex_pay/api.rb#L163-L185", "partition": "valid"} {"repo": "jsmestad/jsonapi-consumer", "path": "lib/jsonapi/consumer/resource.rb", "func_name": "JSONAPI::Consumer.Resource.save", "original_string": "def save\n return false unless valid?\n\n self.last_result_set = if persisted?\n self.class.requestor.update(self)\n else\n self.class.requestor.create(self)\n end\n\n if last_result_set.has_errors?\n fill_errors\n false\n else\n self.errors.clear if self.errors\n mark_as_persisted!\n if updated = last_result_set.first\n self.attributes = updated.attributes\n self.links.attributes = updated.links.attributes\n self.relationships.attributes = updated.relationships.attributes\n clear_changes_information\n end\n true\n end\n end", "language": "ruby", "code": "def save\n return false unless valid?\n\n self.last_result_set = if persisted?\n self.class.requestor.update(self)\n else\n self.class.requestor.create(self)\n end\n\n if last_result_set.has_errors?\n fill_errors\n false\n else\n self.errors.clear if self.errors\n mark_as_persisted!\n if updated = last_result_set.first\n self.attributes = updated.attributes\n self.links.attributes = updated.links.attributes\n self.relationships.attributes = updated.relationships.attributes\n clear_changes_information\n end\n true\n end\n end", "code_tokens": ["def", "save", "return", "false", "unless", "valid?", "self", ".", "last_result_set", "=", "if", "persisted?", "self", ".", "class", ".", "requestor", ".", "update", "(", "self", ")", "else", "self", ".", "class", ".", "requestor", ".", "create", "(", "self", ")", "end", "if", "last_result_set", ".", "has_errors?", "fill_errors", "false", "else", "self", ".", "errors", ".", "clear", "if", "self", ".", "errors", "mark_as_persisted!", "if", "updated", "=", "last_result_set", ".", "first", "self", ".", "attributes", "=", "updated", ".", "attributes", "self", ".", "links", ".", "attributes", "=", "updated", ".", "links", ".", "attributes", "self", ".", "relationships", ".", "attributes", "=", "updated", ".", "relationships", ".", "attributes", "clear_changes_information", "end", "true", "end", "end"], "docstring": "Commit the current changes to the resource to the remote server.\n If the resource was previously loaded from the server, we will\n try to update the record. Otherwise if it's a new record, then\n we will try to create it\n\n @return [Boolean] Whether or not the save succeeded", "docstring_tokens": ["Commit", "the", "current", "changes", "to", "the", "resource", "to", "the", "remote", "server", ".", "If", "the", "resource", "was", "previously", "loaded", "from", "the", "server", "we", "will", "try", "to", "update", "the", "record", ".", "Otherwise", "if", "it", "s", "a", "new", "record", "then", "we", "will", "try", "to", "create", "it"], "sha": "6ba07d613c4e1fc2bbac3ac26f89241e82cf1551", "url": "https://github.com/jsmestad/jsonapi-consumer/blob/6ba07d613c4e1fc2bbac3ac26f89241e82cf1551/lib/jsonapi/consumer/resource.rb#L439-L462", "partition": "valid"} {"repo": "jsmestad/jsonapi-consumer", "path": "lib/jsonapi/consumer/resource.rb", "func_name": "JSONAPI::Consumer.Resource.destroy", "original_string": "def destroy\n self.last_result_set = self.class.requestor.destroy(self)\n if last_result_set.has_errors?\n fill_errors\n false\n else\n self.attributes.clear\n true\n end\n end", "language": "ruby", "code": "def destroy\n self.last_result_set = self.class.requestor.destroy(self)\n if last_result_set.has_errors?\n fill_errors\n false\n else\n self.attributes.clear\n true\n end\n end", "code_tokens": ["def", "destroy", "self", ".", "last_result_set", "=", "self", ".", "class", ".", "requestor", ".", "destroy", "(", "self", ")", "if", "last_result_set", ".", "has_errors?", "fill_errors", "false", "else", "self", ".", "attributes", ".", "clear", "true", "end", "end"], "docstring": "Try to destroy this resource\n\n @return [Boolean] Whether or not the destroy succeeded", "docstring_tokens": ["Try", "to", "destroy", "this", "resource"], "sha": "6ba07d613c4e1fc2bbac3ac26f89241e82cf1551", "url": "https://github.com/jsmestad/jsonapi-consumer/blob/6ba07d613c4e1fc2bbac3ac26f89241e82cf1551/lib/jsonapi/consumer/resource.rb#L467-L476", "partition": "valid"} {"repo": "dmitrypol/redi_search_rails", "path": "lib/redi_search_rails.rb", "func_name": "RediSearchRails.ClassMethods.redi_search_schema", "original_string": "def redi_search_schema(schema)\n @schema = schema.to_a.flatten\n @fields = schema.keys\n @model = self.name.constantize\n @index_name = @model.to_s\n @score = 1\n end", "language": "ruby", "code": "def redi_search_schema(schema)\n @schema = schema.to_a.flatten\n @fields = schema.keys\n @model = self.name.constantize\n @index_name = @model.to_s\n @score = 1\n end", "code_tokens": ["def", "redi_search_schema", "(", "schema", ")", "@schema", "=", "schema", ".", "to_a", ".", "flatten", "@fields", "=", "schema", ".", "keys", "@model", "=", "self", ".", "name", ".", "constantize", "@index_name", "=", "@model", ".", "to_s", "@score", "=", "1", "end"], "docstring": "will configure the RediSearch for the specific model\n\n @see https://github.com/dmitrypol/redi_search_rails\n @param schema [Hash] name: 'TEXT', age: 'NUMERIC'", "docstring_tokens": ["will", "configure", "the", "RediSearch", "for", "the", "specific", "model"], "sha": "3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6", "url": "https://github.com/dmitrypol/redi_search_rails/blob/3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6/lib/redi_search_rails.rb#L17-L23", "partition": "valid"} {"repo": "dmitrypol/redi_search_rails", "path": "lib/redi_search_rails.rb", "func_name": "RediSearchRails.ClassMethods.ft_search_count", "original_string": "def ft_search_count(args)\n ft_search(args).first\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "language": "ruby", "code": "def ft_search_count(args)\n ft_search(args).first\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "code_tokens": ["def", "ft_search_count", "(", "args", ")", "ft_search", "(", "args", ")", ".", "first", "rescue", "Exception", "=>", "e", "Rails", ".", "logger", ".", "error", "e", "if", "defined?", "Rails", "return", "e", ".", "message", "end"], "docstring": "number of records found for keywords\n\n @param keyword [Hash] keyword that gets passed to ft_search\n @return [Integer] number of results matching the search", "docstring_tokens": ["number", "of", "records", "found", "for", "keywords"], "sha": "3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6", "url": "https://github.com/dmitrypol/redi_search_rails/blob/3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6/lib/redi_search_rails.rb#L79-L84", "partition": "valid"} {"repo": "dmitrypol/redi_search_rails", "path": "lib/redi_search_rails.rb", "func_name": "RediSearchRails.ClassMethods.ft_add_all", "original_string": "def ft_add_all\n @model.all.each {|record| ft_add(record: record) }\n ft_optimize\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "language": "ruby", "code": "def ft_add_all\n @model.all.each {|record| ft_add(record: record) }\n ft_optimize\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "code_tokens": ["def", "ft_add_all", "@model", ".", "all", ".", "each", "{", "|", "record", "|", "ft_add", "(", "record", ":", "record", ")", "}", "ft_optimize", "rescue", "Exception", "=>", "e", "Rails", ".", "logger", ".", "error", "e", "if", "defined?", "Rails", "return", "e", ".", "message", "end"], "docstring": "index all records in specific model\n\n @return [String]", "docstring_tokens": ["index", "all", "records", "in", "specific", "model"], "sha": "3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6", "url": "https://github.com/dmitrypol/redi_search_rails/blob/3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6/lib/redi_search_rails.rb#L103-L109", "partition": "valid"} {"repo": "dmitrypol/redi_search_rails", "path": "lib/redi_search_rails.rb", "func_name": "RediSearchRails.ClassMethods.ft_add", "original_string": "def ft_add record:\n fields = []\n @fields.each { |field| fields.push(field, record.send(field)) }\n REDI_SEARCH.call('FT.ADD', @index_name, record.to_global_id.to_s, @score,\n 'REPLACE',\n 'FIELDS', fields\n #'NOSAVE', 'PAYLOAD', 'LANGUAGE'\n )\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "language": "ruby", "code": "def ft_add record:\n fields = []\n @fields.each { |field| fields.push(field, record.send(field)) }\n REDI_SEARCH.call('FT.ADD', @index_name, record.to_global_id.to_s, @score,\n 'REPLACE',\n 'FIELDS', fields\n #'NOSAVE', 'PAYLOAD', 'LANGUAGE'\n )\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "code_tokens": ["def", "ft_add", "record", ":", "fields", "=", "[", "]", "@fields", ".", "each", "{", "|", "field", "|", "fields", ".", "push", "(", "field", ",", "record", ".", "send", "(", "field", ")", ")", "}", "REDI_SEARCH", ".", "call", "(", "'FT.ADD'", ",", "@index_name", ",", "record", ".", "to_global_id", ".", "to_s", ",", "@score", ",", "'REPLACE'", ",", "'FIELDS'", ",", "fields", "#'NOSAVE', 'PAYLOAD', 'LANGUAGE'", ")", "rescue", "Exception", "=>", "e", "Rails", ".", "logger", ".", "error", "e", "if", "defined?", "Rails", "return", "e", ".", "message", "end"], "docstring": "index specific record\n\n @param record [Object] Object to index\n @return [String]", "docstring_tokens": ["index", "specific", "record"], "sha": "3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6", "url": "https://github.com/dmitrypol/redi_search_rails/blob/3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6/lib/redi_search_rails.rb#L115-L126", "partition": "valid"} {"repo": "dmitrypol/redi_search_rails", "path": "lib/redi_search_rails.rb", "func_name": "RediSearchRails.ClassMethods.ft_addhash", "original_string": "def ft_addhash redis_key:\n REDI_SEARCH.call('FT.ADDHASH', @index_name, redis_key, @score, 'REPLACE')\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "language": "ruby", "code": "def ft_addhash redis_key:\n REDI_SEARCH.call('FT.ADDHASH', @index_name, redis_key, @score, 'REPLACE')\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "code_tokens": ["def", "ft_addhash", "redis_key", ":", "REDI_SEARCH", ".", "call", "(", "'FT.ADDHASH'", ",", "@index_name", ",", "redis_key", ",", "@score", ",", "'REPLACE'", ")", "rescue", "Exception", "=>", "e", "Rails", ".", "logger", ".", "error", "e", "if", "defined?", "Rails", "return", "e", ".", "message", "end"], "docstring": "index existing Hash\n\n @param record [string] key of existing HASH key in Redis that will hold the fields the index needs.\n @return [String]", "docstring_tokens": ["index", "existing", "Hash"], "sha": "3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6", "url": "https://github.com/dmitrypol/redi_search_rails/blob/3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6/lib/redi_search_rails.rb#L132-L137", "partition": "valid"} {"repo": "dmitrypol/redi_search_rails", "path": "lib/redi_search_rails.rb", "func_name": "RediSearchRails.ClassMethods.ft_del_all", "original_string": "def ft_del_all\n @model.all.each {|record| ft_del(record: record) }\n ft_optimize\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "language": "ruby", "code": "def ft_del_all\n @model.all.each {|record| ft_del(record: record) }\n ft_optimize\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "code_tokens": ["def", "ft_del_all", "@model", ".", "all", ".", "each", "{", "|", "record", "|", "ft_del", "(", "record", ":", "record", ")", "}", "ft_optimize", "rescue", "Exception", "=>", "e", "Rails", ".", "logger", ".", "error", "e", "if", "defined?", "Rails", "return", "e", ".", "message", "end"], "docstring": "delete all records in specific model\n\n @return [String]", "docstring_tokens": ["delete", "all", "records", "in", "specific", "model"], "sha": "3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6", "url": "https://github.com/dmitrypol/redi_search_rails/blob/3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6/lib/redi_search_rails.rb#L142-L148", "partition": "valid"} {"repo": "dmitrypol/redi_search_rails", "path": "lib/redi_search_rails.rb", "func_name": "RediSearchRails.ClassMethods.ft_del", "original_string": "def ft_del record:\n doc_id = record.to_global_id\n REDI_SEARCH.call('FT.DEL', @index_name, doc_id)\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "language": "ruby", "code": "def ft_del record:\n doc_id = record.to_global_id\n REDI_SEARCH.call('FT.DEL', @index_name, doc_id)\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "code_tokens": ["def", "ft_del", "record", ":", "doc_id", "=", "record", ".", "to_global_id", "REDI_SEARCH", ".", "call", "(", "'FT.DEL'", ",", "@index_name", ",", "doc_id", ")", "rescue", "Exception", "=>", "e", "Rails", ".", "logger", ".", "error", "e", "if", "defined?", "Rails", "return", "e", ".", "message", "end"], "docstring": "delete specific document from index\n\n @param record [Object] Object to delete\n @return [String]", "docstring_tokens": ["delete", "specific", "document", "from", "index"], "sha": "3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6", "url": "https://github.com/dmitrypol/redi_search_rails/blob/3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6/lib/redi_search_rails.rb#L154-L160", "partition": "valid"} {"repo": "dmitrypol/redi_search_rails", "path": "lib/redi_search_rails.rb", "func_name": "RediSearchRails.ClassMethods.ft_info", "original_string": "def ft_info\n REDI_SEARCH.call('FT.INFO', @index_name)\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "language": "ruby", "code": "def ft_info\n REDI_SEARCH.call('FT.INFO', @index_name)\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "code_tokens": ["def", "ft_info", "REDI_SEARCH", ".", "call", "(", "'FT.INFO'", ",", "@index_name", ")", "rescue", "Exception", "=>", "e", "Rails", ".", "logger", ".", "error", "e", "if", "defined?", "Rails", "return", "e", ".", "message", "end"], "docstring": "get info about specific index\n\n @return [String]", "docstring_tokens": ["get", "info", "about", "specific", "index"], "sha": "3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6", "url": "https://github.com/dmitrypol/redi_search_rails/blob/3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6/lib/redi_search_rails.rb#L185-L190", "partition": "valid"} {"repo": "dmitrypol/redi_search_rails", "path": "lib/redi_search_rails.rb", "func_name": "RediSearchRails.ClassMethods.ft_sugadd_all", "original_string": "def ft_sugadd_all (attribute:)\n @model.all.each {|record| ft_sugadd(record: record, attribute: attribute) }\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "language": "ruby", "code": "def ft_sugadd_all (attribute:)\n @model.all.each {|record| ft_sugadd(record: record, attribute: attribute) }\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "code_tokens": ["def", "ft_sugadd_all", "(", "attribute", ":", ")", "@model", ".", "all", ".", "each", "{", "|", "record", "|", "ft_sugadd", "(", "record", ":", "record", ",", "attribute", ":", "attribute", ")", "}", "rescue", "Exception", "=>", "e", "Rails", ".", "logger", ".", "error", "e", "if", "defined?", "Rails", "return", "e", ".", "message", "end"], "docstring": "add all values for a model attribute to autocomplete\n\n @param attribute [String] - name, email, etc", "docstring_tokens": ["add", "all", "values", "for", "a", "model", "attribute", "to", "autocomplete"], "sha": "3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6", "url": "https://github.com/dmitrypol/redi_search_rails/blob/3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6/lib/redi_search_rails.rb#L195-L200", "partition": "valid"} {"repo": "dmitrypol/redi_search_rails", "path": "lib/redi_search_rails.rb", "func_name": "RediSearchRails.ClassMethods.ft_sugadd", "original_string": "def ft_sugadd (record:, attribute:, score: 1)\n # => combine model with attribute to create unique key like user_name\n key = \"#{@model.to_s}:#{attribute}\"\n string = record.send(attribute)\n REDI_SEARCH.call('FT.SUGADD', key, string, score)\n # => INCR\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "language": "ruby", "code": "def ft_sugadd (record:, attribute:, score: 1)\n # => combine model with attribute to create unique key like user_name\n key = \"#{@model.to_s}:#{attribute}\"\n string = record.send(attribute)\n REDI_SEARCH.call('FT.SUGADD', key, string, score)\n # => INCR\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "code_tokens": ["def", "ft_sugadd", "(", "record", ":", ",", "attribute", ":", ",", "score", ":", "1", ")", "# => combine model with attribute to create unique key like user_name", "key", "=", "\"#{@model.to_s}:#{attribute}\"", "string", "=", "record", ".", "send", "(", "attribute", ")", "REDI_SEARCH", ".", "call", "(", "'FT.SUGADD'", ",", "key", ",", "string", ",", "score", ")", "# => INCR", "rescue", "Exception", "=>", "e", "Rails", ".", "logger", ".", "error", "e", "if", "defined?", "Rails", "return", "e", ".", "message", "end"], "docstring": "add string to autocomplete dictionary\n\n @param record [Object] object\n @param attribute [String] - name, email, etc\n @param score [Integer] - score\n @return [Integer] - current size of the dictionary", "docstring_tokens": ["add", "string", "to", "autocomplete", "dictionary"], "sha": "3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6", "url": "https://github.com/dmitrypol/redi_search_rails/blob/3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6/lib/redi_search_rails.rb#L208-L217", "partition": "valid"} {"repo": "dmitrypol/redi_search_rails", "path": "lib/redi_search_rails.rb", "func_name": "RediSearchRails.ClassMethods.ft_sugget", "original_string": "def ft_sugget (attribute:, prefix:)\n key = \"#{@model}:#{attribute}\"\n REDI_SEARCH.call('FT.SUGGET', key, prefix)\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "language": "ruby", "code": "def ft_sugget (attribute:, prefix:)\n key = \"#{@model}:#{attribute}\"\n REDI_SEARCH.call('FT.SUGGET', key, prefix)\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "code_tokens": ["def", "ft_sugget", "(", "attribute", ":", ",", "prefix", ":", ")", "key", "=", "\"#{@model}:#{attribute}\"", "REDI_SEARCH", ".", "call", "(", "'FT.SUGGET'", ",", "key", ",", "prefix", ")", "rescue", "Exception", "=>", "e", "Rails", ".", "logger", ".", "error", "e", "if", "defined?", "Rails", "return", "e", ".", "message", "end"], "docstring": "query dictionary for suggestion\n\n @param attribute [String] - name, email, etc\n @param prefix [String] - prefix to query dictionary\n @return [Array] - suggestions for prefix", "docstring_tokens": ["query", "dictionary", "for", "suggestion"], "sha": "3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6", "url": "https://github.com/dmitrypol/redi_search_rails/blob/3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6/lib/redi_search_rails.rb#L224-L230", "partition": "valid"} {"repo": "dmitrypol/redi_search_rails", "path": "lib/redi_search_rails.rb", "func_name": "RediSearchRails.ClassMethods.ft_sugdel_all", "original_string": "def ft_sugdel_all (attribute:)\n @model.all.each {|record| ft_sugdel(record: record, attribute: attribute) }\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "language": "ruby", "code": "def ft_sugdel_all (attribute:)\n @model.all.each {|record| ft_sugdel(record: record, attribute: attribute) }\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "code_tokens": ["def", "ft_sugdel_all", "(", "attribute", ":", ")", "@model", ".", "all", ".", "each", "{", "|", "record", "|", "ft_sugdel", "(", "record", ":", "record", ",", "attribute", ":", "attribute", ")", "}", "rescue", "Exception", "=>", "e", "Rails", ".", "logger", ".", "error", "e", "if", "defined?", "Rails", "return", "e", ".", "message", "end"], "docstring": "delete all values for a model attribute to autocomplete\n\n @param attribute [String] - name, email, etc", "docstring_tokens": ["delete", "all", "values", "for", "a", "model", "attribute", "to", "autocomplete"], "sha": "3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6", "url": "https://github.com/dmitrypol/redi_search_rails/blob/3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6/lib/redi_search_rails.rb#L235-L240", "partition": "valid"} {"repo": "dmitrypol/redi_search_rails", "path": "lib/redi_search_rails.rb", "func_name": "RediSearchRails.ClassMethods.ft_suglen", "original_string": "def ft_suglen (attribute:)\n key = \"#{@model}:#{attribute}\"\n REDI_SEARCH.call('FT.SUGLEN', key)\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "language": "ruby", "code": "def ft_suglen (attribute:)\n key = \"#{@model}:#{attribute}\"\n REDI_SEARCH.call('FT.SUGLEN', key)\n rescue Exception => e\n Rails.logger.error e if defined? Rails\n return e.message\n end", "code_tokens": ["def", "ft_suglen", "(", "attribute", ":", ")", "key", "=", "\"#{@model}:#{attribute}\"", "REDI_SEARCH", ".", "call", "(", "'FT.SUGLEN'", ",", "key", ")", "rescue", "Exception", "=>", "e", "Rails", ".", "logger", ".", "error", "e", "if", "defined?", "Rails", "return", "e", ".", "message", "end"], "docstring": "size of dictionary\n\n @param attribute [String]\n @return [Integer] - number of possible suggestions", "docstring_tokens": ["size", "of", "dictionary"], "sha": "3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6", "url": "https://github.com/dmitrypol/redi_search_rails/blob/3f08a4a5a3c9e32c0d8b7007bc13a76cbc82d7e6/lib/redi_search_rails.rb#L260-L266", "partition": "valid"} {"repo": "realityforge/zapwhite", "path": "lib/reality/zapwhite.rb", "func_name": "Reality.Zapwhite.run", "original_string": "def run\n normalize_count = 0\n\n if generate_gitattributes?\n output_options = {:prefix => '# DO NOT EDIT: File is auto-generated', :normalize => true}\n new_gitattributes = generate_gitattributes!\n new_content = new_gitattributes.as_file_contents(output_options)\n old_content = File.exist?(@attributes.attributes_file) ? IO.read(@attributes.attributes_file) : nil\n if new_content != old_content\n @attributes = new_gitattributes\n if check_only?\n puts 'Non-normalized .gitattributes file'\n else\n puts 'Fixing: .gitattributes'\n @attributes.write(output_options)\n end\n normalize_count += 1\n end\n end\n\n files = {}\n\n collect_file_attributes(files)\n\n files.each_pair do |filename, config|\n full_filename = \"#{@base_directory}/#{filename}\"\n original_bin_content = File.binread(full_filename)\n\n encoding = config[:encoding].nil? ? 'utf-8' : config[:encoding].gsub(/^UTF/,'utf-')\n\n content = File.read(full_filename, :encoding => \"bom|#{encoding}\")\n\n content =\n config[:dos] ?\n clean_dos_whitespace(filename, content, config[:eofnl], config[:allow_empty]) :\n clean_whitespace(filename, content, config[:eofnl], config[:allow_empty])\n if config[:nodupnl]\n while content.gsub!(/\\n\\n\\n/, \"\\n\\n\")\n # Keep removing duplicate new lines till they have gone\n end\n end\n if content.bytes != original_bin_content.bytes\n normalize_count += 1\n if check_only?\n puts \"Non-normalized whitespace in #{filename}\"\n else\n puts \"Fixing: #{filename}\"\n File.open(full_filename, 'wb') do |out|\n out.write content\n end\n end\n end\n end\n\n normalize_count\n end", "language": "ruby", "code": "def run\n normalize_count = 0\n\n if generate_gitattributes?\n output_options = {:prefix => '# DO NOT EDIT: File is auto-generated', :normalize => true}\n new_gitattributes = generate_gitattributes!\n new_content = new_gitattributes.as_file_contents(output_options)\n old_content = File.exist?(@attributes.attributes_file) ? IO.read(@attributes.attributes_file) : nil\n if new_content != old_content\n @attributes = new_gitattributes\n if check_only?\n puts 'Non-normalized .gitattributes file'\n else\n puts 'Fixing: .gitattributes'\n @attributes.write(output_options)\n end\n normalize_count += 1\n end\n end\n\n files = {}\n\n collect_file_attributes(files)\n\n files.each_pair do |filename, config|\n full_filename = \"#{@base_directory}/#{filename}\"\n original_bin_content = File.binread(full_filename)\n\n encoding = config[:encoding].nil? ? 'utf-8' : config[:encoding].gsub(/^UTF/,'utf-')\n\n content = File.read(full_filename, :encoding => \"bom|#{encoding}\")\n\n content =\n config[:dos] ?\n clean_dos_whitespace(filename, content, config[:eofnl], config[:allow_empty]) :\n clean_whitespace(filename, content, config[:eofnl], config[:allow_empty])\n if config[:nodupnl]\n while content.gsub!(/\\n\\n\\n/, \"\\n\\n\")\n # Keep removing duplicate new lines till they have gone\n end\n end\n if content.bytes != original_bin_content.bytes\n normalize_count += 1\n if check_only?\n puts \"Non-normalized whitespace in #{filename}\"\n else\n puts \"Fixing: #{filename}\"\n File.open(full_filename, 'wb') do |out|\n out.write content\n end\n end\n end\n end\n\n normalize_count\n end", "code_tokens": ["def", "run", "normalize_count", "=", "0", "if", "generate_gitattributes?", "output_options", "=", "{", ":prefix", "=>", "'# DO NOT EDIT: File is auto-generated'", ",", ":normalize", "=>", "true", "}", "new_gitattributes", "=", "generate_gitattributes!", "new_content", "=", "new_gitattributes", ".", "as_file_contents", "(", "output_options", ")", "old_content", "=", "File", ".", "exist?", "(", "@attributes", ".", "attributes_file", ")", "?", "IO", ".", "read", "(", "@attributes", ".", "attributes_file", ")", ":", "nil", "if", "new_content", "!=", "old_content", "@attributes", "=", "new_gitattributes", "if", "check_only?", "puts", "'Non-normalized .gitattributes file'", "else", "puts", "'Fixing: .gitattributes'", "@attributes", ".", "write", "(", "output_options", ")", "end", "normalize_count", "+=", "1", "end", "end", "files", "=", "{", "}", "collect_file_attributes", "(", "files", ")", "files", ".", "each_pair", "do", "|", "filename", ",", "config", "|", "full_filename", "=", "\"#{@base_directory}/#{filename}\"", "original_bin_content", "=", "File", ".", "binread", "(", "full_filename", ")", "encoding", "=", "config", "[", ":encoding", "]", ".", "nil?", "?", "'utf-8'", ":", "config", "[", ":encoding", "]", ".", "gsub", "(", "/", "/", ",", "'utf-'", ")", "content", "=", "File", ".", "read", "(", "full_filename", ",", ":encoding", "=>", "\"bom|#{encoding}\"", ")", "content", "=", "config", "[", ":dos", "]", "?", "clean_dos_whitespace", "(", "filename", ",", "content", ",", "config", "[", ":eofnl", "]", ",", "config", "[", ":allow_empty", "]", ")", ":", "clean_whitespace", "(", "filename", ",", "content", ",", "config", "[", ":eofnl", "]", ",", "config", "[", ":allow_empty", "]", ")", "if", "config", "[", ":nodupnl", "]", "while", "content", ".", "gsub!", "(", "/", "\\n", "\\n", "\\n", "/", ",", "\"\\n\\n\"", ")", "# Keep removing duplicate new lines till they have gone", "end", "end", "if", "content", ".", "bytes", "!=", "original_bin_content", ".", "bytes", "normalize_count", "+=", "1", "if", "check_only?", "puts", "\"Non-normalized whitespace in #{filename}\"", "else", "puts", "\"Fixing: #{filename}\"", "File", ".", "open", "(", "full_filename", ",", "'wb'", ")", "do", "|", "out", "|", "out", ".", "write", "content", "end", "end", "end", "end", "normalize_count", "end"], "docstring": "Run normalization process across directory.\n Return the number of files that need normalization", "docstring_tokens": ["Run", "normalization", "process", "across", "directory", ".", "Return", "the", "number", "of", "files", "that", "need", "normalization"], "sha": "d34a56d4ca574c679dd8aad8a315e21093db86a5", "url": "https://github.com/realityforge/zapwhite/blob/d34a56d4ca574c679dd8aad8a315e21093db86a5/lib/reality/zapwhite.rb#L49-L104", "partition": "valid"} {"repo": "realityforge/zapwhite", "path": "lib/reality/zapwhite.rb", "func_name": "Reality.Zapwhite.in_dir", "original_string": "def in_dir(dir, &block)\n original_dir = Dir.pwd\n begin\n Dir.chdir(dir)\n block.call\n ensure\n Dir.chdir(original_dir)\n end\n end", "language": "ruby", "code": "def in_dir(dir, &block)\n original_dir = Dir.pwd\n begin\n Dir.chdir(dir)\n block.call\n ensure\n Dir.chdir(original_dir)\n end\n end", "code_tokens": ["def", "in_dir", "(", "dir", ",", "&", "block", ")", "original_dir", "=", "Dir", ".", "pwd", "begin", "Dir", ".", "chdir", "(", "dir", ")", "block", ".", "call", "ensure", "Dir", ".", "chdir", "(", "original_dir", ")", "end", "end"], "docstring": "Evaluate block after changing directory to specified directory", "docstring_tokens": ["Evaluate", "block", "after", "changing", "directory", "to", "specified", "directory"], "sha": "d34a56d4ca574c679dd8aad8a315e21093db86a5", "url": "https://github.com/realityforge/zapwhite/blob/d34a56d4ca574c679dd8aad8a315e21093db86a5/lib/reality/zapwhite.rb#L186-L194", "partition": "valid"} {"repo": "aptible/fridge", "path": "lib/fridge/rails_helpers.rb", "func_name": "Fridge.RailsHelpers.validate_token", "original_string": "def validate_token(access_token)\n validator = Fridge.configuration.validator\n validator.call(access_token) && access_token\n rescue\n false\n end", "language": "ruby", "code": "def validate_token(access_token)\n validator = Fridge.configuration.validator\n validator.call(access_token) && access_token\n rescue\n false\n end", "code_tokens": ["def", "validate_token", "(", "access_token", ")", "validator", "=", "Fridge", ".", "configuration", ".", "validator", "validator", ".", "call", "(", "access_token", ")", "&&", "access_token", "rescue", "false", "end"], "docstring": "Validates token, and returns the token, or nil", "docstring_tokens": ["Validates", "token", "and", "returns", "the", "token", "or", "nil"], "sha": "e93ac76d75228d2e5a15851f5ac7ab99b20c94fe", "url": "https://github.com/aptible/fridge/blob/e93ac76d75228d2e5a15851f5ac7ab99b20c94fe/lib/fridge/rails_helpers.rb#L52-L57", "partition": "valid"} {"repo": "aptible/fridge", "path": "lib/fridge/rails_helpers.rb", "func_name": "Fridge.RailsHelpers.validate_token!", "original_string": "def validate_token!(access_token)\n validator = Fridge.configuration.validator\n if validator.call(access_token)\n access_token\n else\n raise InvalidToken, 'Rejected by validator'\n end\n end", "language": "ruby", "code": "def validate_token!(access_token)\n validator = Fridge.configuration.validator\n if validator.call(access_token)\n access_token\n else\n raise InvalidToken, 'Rejected by validator'\n end\n end", "code_tokens": ["def", "validate_token!", "(", "access_token", ")", "validator", "=", "Fridge", ".", "configuration", ".", "validator", "if", "validator", ".", "call", "(", "access_token", ")", "access_token", "else", "raise", "InvalidToken", ",", "'Rejected by validator'", "end", "end"], "docstring": "Validates token, and raises an exception if invalid", "docstring_tokens": ["Validates", "token", "and", "raises", "an", "exception", "if", "invalid"], "sha": "e93ac76d75228d2e5a15851f5ac7ab99b20c94fe", "url": "https://github.com/aptible/fridge/blob/e93ac76d75228d2e5a15851f5ac7ab99b20c94fe/lib/fridge/rails_helpers.rb#L60-L67", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/subscriber.rb", "func_name": "CreateSend.Subscriber.update", "original_string": "def update(new_email_address, name, custom_fields, resubscribe, \n consent_to_track, restart_subscription_based_autoresponders=false)\n options = {\n :query => { :email => @email_address },\n :body => {\n :EmailAddress => new_email_address,\n :Name => name,\n :CustomFields => custom_fields,\n :Resubscribe => resubscribe,\n :RestartSubscriptionBasedAutoresponders => \n restart_subscription_based_autoresponders,\n :ConsentToTrack => consent_to_track }.to_json }\n put \"/subscribers/#{@list_id}.json\", options\n # Update @email_address, so this object can continue to be used reliably\n @email_address = new_email_address\n end", "language": "ruby", "code": "def update(new_email_address, name, custom_fields, resubscribe, \n consent_to_track, restart_subscription_based_autoresponders=false)\n options = {\n :query => { :email => @email_address },\n :body => {\n :EmailAddress => new_email_address,\n :Name => name,\n :CustomFields => custom_fields,\n :Resubscribe => resubscribe,\n :RestartSubscriptionBasedAutoresponders => \n restart_subscription_based_autoresponders,\n :ConsentToTrack => consent_to_track }.to_json }\n put \"/subscribers/#{@list_id}.json\", options\n # Update @email_address, so this object can continue to be used reliably\n @email_address = new_email_address\n end", "code_tokens": ["def", "update", "(", "new_email_address", ",", "name", ",", "custom_fields", ",", "resubscribe", ",", "consent_to_track", ",", "restart_subscription_based_autoresponders", "=", "false", ")", "options", "=", "{", ":query", "=>", "{", ":email", "=>", "@email_address", "}", ",", ":body", "=>", "{", ":EmailAddress", "=>", "new_email_address", ",", ":Name", "=>", "name", ",", ":CustomFields", "=>", "custom_fields", ",", ":Resubscribe", "=>", "resubscribe", ",", ":RestartSubscriptionBasedAutoresponders", "=>", "restart_subscription_based_autoresponders", ",", ":ConsentToTrack", "=>", "consent_to_track", "}", ".", "to_json", "}", "put", "\"/subscribers/#{@list_id}.json\"", ",", "options", "# Update @email_address, so this object can continue to be used reliably", "@email_address", "=", "new_email_address", "end"], "docstring": "Updates any aspect of a subscriber, including email address, name, and\n custom field data if supplied.", "docstring_tokens": ["Updates", "any", "aspect", "of", "a", "subscriber", "including", "email", "address", "name", "and", "custom", "field", "data", "if", "supplied", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/subscriber.rb#L72-L87", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/subscriber.rb", "func_name": "CreateSend.Subscriber.history", "original_string": "def history\n options = { :query => { :email => @email_address } }\n response = cs_get \"/subscribers/#{@list_id}/history.json\", options\n response.map{|item| Hashie::Mash.new(item)}\n end", "language": "ruby", "code": "def history\n options = { :query => { :email => @email_address } }\n response = cs_get \"/subscribers/#{@list_id}/history.json\", options\n response.map{|item| Hashie::Mash.new(item)}\n end", "code_tokens": ["def", "history", "options", "=", "{", ":query", "=>", "{", ":email", "=>", "@email_address", "}", "}", "response", "=", "cs_get", "\"/subscribers/#{@list_id}/history.json\"", ",", "options", "response", ".", "map", "{", "|", "item", "|", "Hashie", "::", "Mash", ".", "new", "(", "item", ")", "}", "end"], "docstring": "Gets the historical record of this subscriber's trackable actions.", "docstring_tokens": ["Gets", "the", "historical", "record", "of", "this", "subscriber", "s", "trackable", "actions", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/subscriber.rb#L97-L101", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/segment.rb", "func_name": "CreateSend.Segment.subscribers", "original_string": "def subscribers(date=\"\", page=1, page_size=1000, order_field=\"email\",\n order_direction=\"asc\", include_tracking_preference=false)\n options = { :query => {\n :date => date,\n :page => page,\n :pagesize => page_size,\n :orderfield => order_field,\n :orderdirection => order_direction,\n :includetrackingpreference => include_tracking_preference } }\n response = get \"active\", options\n Hashie::Mash.new(response)\n end", "language": "ruby", "code": "def subscribers(date=\"\", page=1, page_size=1000, order_field=\"email\",\n order_direction=\"asc\", include_tracking_preference=false)\n options = { :query => {\n :date => date,\n :page => page,\n :pagesize => page_size,\n :orderfield => order_field,\n :orderdirection => order_direction,\n :includetrackingpreference => include_tracking_preference } }\n response = get \"active\", options\n Hashie::Mash.new(response)\n end", "code_tokens": ["def", "subscribers", "(", "date", "=", "\"\"", ",", "page", "=", "1", ",", "page_size", "=", "1000", ",", "order_field", "=", "\"email\"", ",", "order_direction", "=", "\"asc\"", ",", "include_tracking_preference", "=", "false", ")", "options", "=", "{", ":query", "=>", "{", ":date", "=>", "date", ",", ":page", "=>", "page", ",", ":pagesize", "=>", "page_size", ",", ":orderfield", "=>", "order_field", ",", ":orderdirection", "=>", "order_direction", ",", ":includetrackingpreference", "=>", "include_tracking_preference", "}", "}", "response", "=", "get", "\"active\"", ",", "options", "Hashie", "::", "Mash", ".", "new", "(", "response", ")", "end"], "docstring": "Gets the active subscribers in this segment.", "docstring_tokens": ["Gets", "the", "active", "subscribers", "in", "this", "segment", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/segment.rb#L37-L48", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/template.rb", "func_name": "CreateSend.Template.update", "original_string": "def update(name, html_url, zip_url)\n options = { :body => {\n :Name => name,\n :HtmlPageURL => html_url,\n :ZipFileURL => zip_url }.to_json }\n put \"/templates/#{template_id}.json\", options\n end", "language": "ruby", "code": "def update(name, html_url, zip_url)\n options = { :body => {\n :Name => name,\n :HtmlPageURL => html_url,\n :ZipFileURL => zip_url }.to_json }\n put \"/templates/#{template_id}.json\", options\n end", "code_tokens": ["def", "update", "(", "name", ",", "html_url", ",", "zip_url", ")", "options", "=", "{", ":body", "=>", "{", ":Name", "=>", "name", ",", ":HtmlPageURL", "=>", "html_url", ",", ":ZipFileURL", "=>", "zip_url", "}", ".", "to_json", "}", "put", "\"/templates/#{template_id}.json\"", ",", "options", "end"], "docstring": "Updates this email template.", "docstring_tokens": ["Updates", "this", "email", "template", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/template.rb#L29-L35", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/createsend.rb", "func_name": "CreateSend.CreateSend.clients", "original_string": "def clients\n response = get('/clients.json')\n response.map{|item| Hashie::Mash.new(item)}\n end", "language": "ruby", "code": "def clients\n response = get('/clients.json')\n response.map{|item| Hashie::Mash.new(item)}\n end", "code_tokens": ["def", "clients", "response", "=", "get", "(", "'/clients.json'", ")", "response", ".", "map", "{", "|", "item", "|", "Hashie", "::", "Mash", ".", "new", "(", "item", ")", "}", "end"], "docstring": "Gets your clients.", "docstring_tokens": ["Gets", "your", "clients", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/createsend.rb#L143-L146", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/createsend.rb", "func_name": "CreateSend.CreateSend.administrators", "original_string": "def administrators\n response = get('/admins.json')\n response.map{|item| Hashie::Mash.new(item)}\n end", "language": "ruby", "code": "def administrators\n response = get('/admins.json')\n response.map{|item| Hashie::Mash.new(item)}\n end", "code_tokens": ["def", "administrators", "response", "=", "get", "(", "'/admins.json'", ")", "response", ".", "map", "{", "|", "item", "|", "Hashie", "::", "Mash", ".", "new", "(", "item", ")", "}", "end"], "docstring": "Gets the administrators for the account.", "docstring_tokens": ["Gets", "the", "administrators", "for", "the", "account", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/createsend.rb#L173-L176", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/createsend.rb", "func_name": "CreateSend.CreateSend.set_primary_contact", "original_string": "def set_primary_contact(email)\n options = { :query => { :email => email } }\n response = put(\"/primarycontact.json\", options)\n Hashie::Mash.new(response)\n end", "language": "ruby", "code": "def set_primary_contact(email)\n options = { :query => { :email => email } }\n response = put(\"/primarycontact.json\", options)\n Hashie::Mash.new(response)\n end", "code_tokens": ["def", "set_primary_contact", "(", "email", ")", "options", "=", "{", ":query", "=>", "{", ":email", "=>", "email", "}", "}", "response", "=", "put", "(", "\"/primarycontact.json\"", ",", "options", ")", "Hashie", "::", "Mash", ".", "new", "(", "response", ")", "end"], "docstring": "Set the primary contect for the account.", "docstring_tokens": ["Set", "the", "primary", "contect", "for", "the", "account", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/createsend.rb#L185-L189", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/list.rb", "func_name": "CreateSend.List.create_custom_field", "original_string": "def create_custom_field(field_name, data_type, options=[],\n visible_in_preference_center=true)\n options = { :body => {\n :FieldName => field_name,\n :DataType => data_type,\n :Options => options,\n :VisibleInPreferenceCenter => visible_in_preference_center }.to_json }\n response = post \"customfields\", options\n response.parsed_response\n end", "language": "ruby", "code": "def create_custom_field(field_name, data_type, options=[],\n visible_in_preference_center=true)\n options = { :body => {\n :FieldName => field_name,\n :DataType => data_type,\n :Options => options,\n :VisibleInPreferenceCenter => visible_in_preference_center }.to_json }\n response = post \"customfields\", options\n response.parsed_response\n end", "code_tokens": ["def", "create_custom_field", "(", "field_name", ",", "data_type", ",", "options", "=", "[", "]", ",", "visible_in_preference_center", "=", "true", ")", "options", "=", "{", ":body", "=>", "{", ":FieldName", "=>", "field_name", ",", ":DataType", "=>", "data_type", ",", ":Options", "=>", "options", ",", ":VisibleInPreferenceCenter", "=>", "visible_in_preference_center", "}", ".", "to_json", "}", "response", "=", "post", "\"customfields\"", ",", "options", "response", ".", "parsed_response", "end"], "docstring": "Creates a new custom field for this list.\n field_name - String representing the name to be given to the field\n data_type - String representing the data type of the field. Valid data\n types are 'Text', 'Number', 'MultiSelectOne', 'MultiSelectMany',\n 'Date', 'Country', and 'USState'.\n options - Array of Strings representing the options for the field if it\n is of type 'MultiSelectOne' or 'MultiSelectMany'.\n visible_in_preference_center - Boolean indicating whether or not the\n field should be visible in the subscriber preference center", "docstring_tokens": ["Creates", "a", "new", "custom", "field", "for", "this", "list", ".", "field_name", "-", "String", "representing", "the", "name", "to", "be", "given", "to", "the", "field", "data_type", "-", "String", "representing", "the", "data", "type", "of", "the", "field", ".", "Valid", "data", "types", "are", "Text", "Number", "MultiSelectOne", "MultiSelectMany", "Date", "Country", "and", "USState", ".", "options", "-", "Array", "of", "Strings", "representing", "the", "options", "for", "the", "field", "if", "it", "is", "of", "type", "MultiSelectOne", "or", "MultiSelectMany", ".", "visible_in_preference_center", "-", "Boolean", "indicating", "whether", "or", "not", "the", "field", "should", "be", "visible", "in", "the", "subscriber", "preference", "center"], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/list.rb#L51-L60", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/list.rb", "func_name": "CreateSend.List.update_custom_field", "original_string": "def update_custom_field(custom_field_key, field_name,\n visible_in_preference_center)\n custom_field_key = CGI.escape(custom_field_key)\n options = { :body => {\n :FieldName => field_name,\n :VisibleInPreferenceCenter => visible_in_preference_center }.to_json }\n response = put \"customfields/#{custom_field_key}\", options\n response.parsed_response\n end", "language": "ruby", "code": "def update_custom_field(custom_field_key, field_name,\n visible_in_preference_center)\n custom_field_key = CGI.escape(custom_field_key)\n options = { :body => {\n :FieldName => field_name,\n :VisibleInPreferenceCenter => visible_in_preference_center }.to_json }\n response = put \"customfields/#{custom_field_key}\", options\n response.parsed_response\n end", "code_tokens": ["def", "update_custom_field", "(", "custom_field_key", ",", "field_name", ",", "visible_in_preference_center", ")", "custom_field_key", "=", "CGI", ".", "escape", "(", "custom_field_key", ")", "options", "=", "{", ":body", "=>", "{", ":FieldName", "=>", "field_name", ",", ":VisibleInPreferenceCenter", "=>", "visible_in_preference_center", "}", ".", "to_json", "}", "response", "=", "put", "\"customfields/#{custom_field_key}\"", ",", "options", "response", ".", "parsed_response", "end"], "docstring": "Updates a custom field belonging to this list.\n custom_field_key - String which represents the key for the custom field\n field_name - String representing the name to be given to the field\n visible_in_preference_center - Boolean indicating whether or not the\n field should be visible in the subscriber preference center", "docstring_tokens": ["Updates", "a", "custom", "field", "belonging", "to", "this", "list", ".", "custom_field_key", "-", "String", "which", "represents", "the", "key", "for", "the", "custom", "field", "field_name", "-", "String", "representing", "the", "name", "to", "be", "given", "to", "the", "field", "visible_in_preference_center", "-", "Boolean", "indicating", "whether", "or", "not", "the", "field", "should", "be", "visible", "in", "the", "subscriber", "preference", "center"], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/list.rb#L67-L75", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/list.rb", "func_name": "CreateSend.List.update_custom_field_options", "original_string": "def update_custom_field_options(custom_field_key, new_options,\n keep_existing_options)\n custom_field_key = CGI.escape(custom_field_key)\n options = { :body => {\n :Options => new_options,\n :KeepExistingOptions => keep_existing_options }.to_json }\n put \"customfields/#{custom_field_key}/options\", options\n end", "language": "ruby", "code": "def update_custom_field_options(custom_field_key, new_options,\n keep_existing_options)\n custom_field_key = CGI.escape(custom_field_key)\n options = { :body => {\n :Options => new_options,\n :KeepExistingOptions => keep_existing_options }.to_json }\n put \"customfields/#{custom_field_key}/options\", options\n end", "code_tokens": ["def", "update_custom_field_options", "(", "custom_field_key", ",", "new_options", ",", "keep_existing_options", ")", "custom_field_key", "=", "CGI", ".", "escape", "(", "custom_field_key", ")", "options", "=", "{", ":body", "=>", "{", ":Options", "=>", "new_options", ",", ":KeepExistingOptions", "=>", "keep_existing_options", "}", ".", "to_json", "}", "put", "\"customfields/#{custom_field_key}/options\"", ",", "options", "end"], "docstring": "Updates the options of a multi-optioned custom field on this list.", "docstring_tokens": ["Updates", "the", "options", "of", "a", "multi", "-", "optioned", "custom", "field", "on", "this", "list", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/list.rb#L84-L91", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/list.rb", "func_name": "CreateSend.List.custom_fields", "original_string": "def custom_fields\n response = get \"customfields\"\n response.map{|item| Hashie::Mash.new(item)}\n end", "language": "ruby", "code": "def custom_fields\n response = get \"customfields\"\n response.map{|item| Hashie::Mash.new(item)}\n end", "code_tokens": ["def", "custom_fields", "response", "=", "get", "\"customfields\"", "response", ".", "map", "{", "|", "item", "|", "Hashie", "::", "Mash", ".", "new", "(", "item", ")", "}", "end"], "docstring": "Gets the custom fields for this list.", "docstring_tokens": ["Gets", "the", "custom", "fields", "for", "this", "list", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/list.rb#L100-L103", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/list.rb", "func_name": "CreateSend.List.segments", "original_string": "def segments\n response = get \"segments\"\n response.map{|item| Hashie::Mash.new(item)}\n end", "language": "ruby", "code": "def segments\n response = get \"segments\"\n response.map{|item| Hashie::Mash.new(item)}\n end", "code_tokens": ["def", "segments", "response", "=", "get", "\"segments\"", "response", ".", "map", "{", "|", "item", "|", "Hashie", "::", "Mash", ".", "new", "(", "item", ")", "}", "end"], "docstring": "Gets the segments for this list.", "docstring_tokens": ["Gets", "the", "segments", "for", "this", "list", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/list.rb#L106-L109", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/list.rb", "func_name": "CreateSend.List.active", "original_string": "def active(date=\"\", page=1, page_size=1000, order_field=\"email\",\n order_direction=\"asc\", include_tracking_preference=false)\n paged_result_by_date(\"active\", date, page, page_size, order_field,\n order_direction, include_tracking_preference)\n end", "language": "ruby", "code": "def active(date=\"\", page=1, page_size=1000, order_field=\"email\",\n order_direction=\"asc\", include_tracking_preference=false)\n paged_result_by_date(\"active\", date, page, page_size, order_field,\n order_direction, include_tracking_preference)\n end", "code_tokens": ["def", "active", "(", "date", "=", "\"\"", ",", "page", "=", "1", ",", "page_size", "=", "1000", ",", "order_field", "=", "\"email\"", ",", "order_direction", "=", "\"asc\"", ",", "include_tracking_preference", "=", "false", ")", "paged_result_by_date", "(", "\"active\"", ",", "date", ",", "page", ",", "page_size", ",", "order_field", ",", "order_direction", ",", "include_tracking_preference", ")", "end"], "docstring": "Gets the active subscribers for this list.", "docstring_tokens": ["Gets", "the", "active", "subscribers", "for", "this", "list", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/list.rb#L118-L122", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/list.rb", "func_name": "CreateSend.List.webhooks", "original_string": "def webhooks\n response = get \"webhooks\"\n response.map{|item| Hashie::Mash.new(item)}\n end", "language": "ruby", "code": "def webhooks\n response = get \"webhooks\"\n response.map{|item| Hashie::Mash.new(item)}\n end", "code_tokens": ["def", "webhooks", "response", "=", "get", "\"webhooks\"", "response", ".", "map", "{", "|", "item", "|", "Hashie", "::", "Mash", ".", "new", "(", "item", ")", "}", "end"], "docstring": "Gets the webhooks for this list.", "docstring_tokens": ["Gets", "the", "webhooks", "for", "this", "list", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/list.rb#L184-L187", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/person.rb", "func_name": "CreateSend.Person.update", "original_string": "def update(new_email_address, name, access_level, password)\n options = {\n :query => { :email => @email_address },\n :body => {\n :EmailAddress => new_email_address,\n :Name => name,\n :AccessLevel => access_level,\n :Password => password }.to_json }\n put uri_for(client_id), options\n # Update @email_address, so this object can continue to be used reliably\n @email_address = new_email_address\n end", "language": "ruby", "code": "def update(new_email_address, name, access_level, password)\n options = {\n :query => { :email => @email_address },\n :body => {\n :EmailAddress => new_email_address,\n :Name => name,\n :AccessLevel => access_level,\n :Password => password }.to_json }\n put uri_for(client_id), options\n # Update @email_address, so this object can continue to be used reliably\n @email_address = new_email_address\n end", "code_tokens": ["def", "update", "(", "new_email_address", ",", "name", ",", "access_level", ",", "password", ")", "options", "=", "{", ":query", "=>", "{", ":email", "=>", "@email_address", "}", ",", ":body", "=>", "{", ":EmailAddress", "=>", "new_email_address", ",", ":Name", "=>", "name", ",", ":AccessLevel", "=>", "access_level", ",", ":Password", "=>", "password", "}", ".", "to_json", "}", "put", "uri_for", "(", "client_id", ")", ",", "options", "# Update @email_address, so this object can continue to be used reliably", "@email_address", "=", "new_email_address", "end"], "docstring": "Updates the person details. password is optional and will only be\n updated if supplied", "docstring_tokens": ["Updates", "the", "person", "details", ".", "password", "is", "optional", "and", "will", "only", "be", "updated", "if", "supplied"], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/person.rb#L36-L47", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/client.rb", "func_name": "CreateSend.Client.campaigns", "original_string": "def campaigns\n response = get 'campaigns'\n response.map{|item| Hashie::Mash.new(item)}\n end", "language": "ruby", "code": "def campaigns\n response = get 'campaigns'\n response.map{|item| Hashie::Mash.new(item)}\n end", "code_tokens": ["def", "campaigns", "response", "=", "get", "'campaigns'", "response", ".", "map", "{", "|", "item", "|", "Hashie", "::", "Mash", ".", "new", "(", "item", ")", "}", "end"], "docstring": "Gets the sent campaigns belonging to this client.", "docstring_tokens": ["Gets", "the", "sent", "campaigns", "belonging", "to", "this", "client", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/client.rb#L28-L31", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/client.rb", "func_name": "CreateSend.Client.scheduled", "original_string": "def scheduled\n response = get 'scheduled'\n response.map{|item| Hashie::Mash.new(item)}\n end", "language": "ruby", "code": "def scheduled\n response = get 'scheduled'\n response.map{|item| Hashie::Mash.new(item)}\n end", "code_tokens": ["def", "scheduled", "response", "=", "get", "'scheduled'", "response", ".", "map", "{", "|", "item", "|", "Hashie", "::", "Mash", ".", "new", "(", "item", ")", "}", "end"], "docstring": "Gets the currently scheduled campaigns belonging to this client.", "docstring_tokens": ["Gets", "the", "currently", "scheduled", "campaigns", "belonging", "to", "this", "client", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/client.rb#L34-L37", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/client.rb", "func_name": "CreateSend.Client.drafts", "original_string": "def drafts\n response = get 'drafts'\n response.map{|item| Hashie::Mash.new(item)}\n end", "language": "ruby", "code": "def drafts\n response = get 'drafts'\n response.map{|item| Hashie::Mash.new(item)}\n end", "code_tokens": ["def", "drafts", "response", "=", "get", "'drafts'", "response", ".", "map", "{", "|", "item", "|", "Hashie", "::", "Mash", ".", "new", "(", "item", ")", "}", "end"], "docstring": "Gets the draft campaigns belonging to this client.", "docstring_tokens": ["Gets", "the", "draft", "campaigns", "belonging", "to", "this", "client", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/client.rb#L40-L43", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/client.rb", "func_name": "CreateSend.Client.lists", "original_string": "def lists\n response = get 'lists'\n response.map{|item| Hashie::Mash.new(item)}\n end", "language": "ruby", "code": "def lists\n response = get 'lists'\n response.map{|item| Hashie::Mash.new(item)}\n end", "code_tokens": ["def", "lists", "response", "=", "get", "'lists'", "response", ".", "map", "{", "|", "item", "|", "Hashie", "::", "Mash", ".", "new", "(", "item", ")", "}", "end"], "docstring": "Gets the subscriber lists belonging to this client.", "docstring_tokens": ["Gets", "the", "subscriber", "lists", "belonging", "to", "this", "client", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/client.rb#L46-L49", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/client.rb", "func_name": "CreateSend.Client.lists_for_email", "original_string": "def lists_for_email(email_address)\n options = { :query => { :email => email_address } }\n response = get 'listsforemail', options\n response.map{|item| Hashie::Mash.new(item)}\n end", "language": "ruby", "code": "def lists_for_email(email_address)\n options = { :query => { :email => email_address } }\n response = get 'listsforemail', options\n response.map{|item| Hashie::Mash.new(item)}\n end", "code_tokens": ["def", "lists_for_email", "(", "email_address", ")", "options", "=", "{", ":query", "=>", "{", ":email", "=>", "email_address", "}", "}", "response", "=", "get", "'listsforemail'", ",", "options", "response", ".", "map", "{", "|", "item", "|", "Hashie", "::", "Mash", ".", "new", "(", "item", ")", "}", "end"], "docstring": "Gets the lists across a client, to which a subscriber with a particular\n email address belongs.\n email_address - A String representing the subcriber's email address", "docstring_tokens": ["Gets", "the", "lists", "across", "a", "client", "to", "which", "a", "subscriber", "with", "a", "particular", "email", "address", "belongs", ".", "email_address", "-", "A", "String", "representing", "the", "subcriber", "s", "email", "address"], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/client.rb#L54-L58", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/client.rb", "func_name": "CreateSend.Client.people", "original_string": "def people\n response = get \"people\"\n response.map{|item| Hashie::Mash.new(item)}\n end", "language": "ruby", "code": "def people\n response = get \"people\"\n response.map{|item| Hashie::Mash.new(item)}\n end", "code_tokens": ["def", "people", "response", "=", "get", "\"people\"", "response", ".", "map", "{", "|", "item", "|", "Hashie", "::", "Mash", ".", "new", "(", "item", ")", "}", "end"], "docstring": "Gets the people associated with this client", "docstring_tokens": ["Gets", "the", "people", "associated", "with", "this", "client"], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/client.rb#L67-L70", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/client.rb", "func_name": "CreateSend.Client.suppressionlist", "original_string": "def suppressionlist(page=1, page_size=1000, order_field=\"email\",\n order_direction=\"asc\")\n options = { :query => {\n :page => page,\n :pagesize => page_size,\n :orderfield => order_field,\n :orderdirection => order_direction } }\n response = get 'suppressionlist', options\n Hashie::Mash.new(response)\n end", "language": "ruby", "code": "def suppressionlist(page=1, page_size=1000, order_field=\"email\",\n order_direction=\"asc\")\n options = { :query => {\n :page => page,\n :pagesize => page_size,\n :orderfield => order_field,\n :orderdirection => order_direction } }\n response = get 'suppressionlist', options\n Hashie::Mash.new(response)\n end", "code_tokens": ["def", "suppressionlist", "(", "page", "=", "1", ",", "page_size", "=", "1000", ",", "order_field", "=", "\"email\"", ",", "order_direction", "=", "\"asc\"", ")", "options", "=", "{", ":query", "=>", "{", ":page", "=>", "page", ",", ":pagesize", "=>", "page_size", ",", ":orderfield", "=>", "order_field", ",", ":orderdirection", "=>", "order_direction", "}", "}", "response", "=", "get", "'suppressionlist'", ",", "options", "Hashie", "::", "Mash", ".", "new", "(", "response", ")", "end"], "docstring": "Gets this client's suppression list.", "docstring_tokens": ["Gets", "this", "client", "s", "suppression", "list", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/client.rb#L84-L93", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/client.rb", "func_name": "CreateSend.Client.suppress", "original_string": "def suppress(emails)\n options = { :body => {\n :EmailAddresses => emails.kind_of?(String) ?\n [ emails ] : emails }.to_json }\n post \"suppress\", options\n end", "language": "ruby", "code": "def suppress(emails)\n options = { :body => {\n :EmailAddresses => emails.kind_of?(String) ?\n [ emails ] : emails }.to_json }\n post \"suppress\", options\n end", "code_tokens": ["def", "suppress", "(", "emails", ")", "options", "=", "{", ":body", "=>", "{", ":EmailAddresses", "=>", "emails", ".", "kind_of?", "(", "String", ")", "?", "[", "emails", "]", ":", "emails", "}", ".", "to_json", "}", "post", "\"suppress\"", ",", "options", "end"], "docstring": "Adds email addresses to a client's suppression list", "docstring_tokens": ["Adds", "email", "addresses", "to", "a", "client", "s", "suppression", "list"], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/client.rb#L96-L101", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/client.rb", "func_name": "CreateSend.Client.templates", "original_string": "def templates\n response = get 'templates'\n response.map{|item| Hashie::Mash.new(item)}\n end", "language": "ruby", "code": "def templates\n response = get 'templates'\n response.map{|item| Hashie::Mash.new(item)}\n end", "code_tokens": ["def", "templates", "response", "=", "get", "'templates'", "response", ".", "map", "{", "|", "item", "|", "Hashie", "::", "Mash", ".", "new", "(", "item", ")", "}", "end"], "docstring": "Gets the templates belonging to this client.", "docstring_tokens": ["Gets", "the", "templates", "belonging", "to", "this", "client", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/client.rb#L111-L114", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/client.rb", "func_name": "CreateSend.Client.set_basics", "original_string": "def set_basics(company, timezone, country)\n options = { :body => {\n :CompanyName => company,\n :TimeZone => timezone,\n :Country => country }.to_json }\n put 'setbasics', options\n end", "language": "ruby", "code": "def set_basics(company, timezone, country)\n options = { :body => {\n :CompanyName => company,\n :TimeZone => timezone,\n :Country => country }.to_json }\n put 'setbasics', options\n end", "code_tokens": ["def", "set_basics", "(", "company", ",", "timezone", ",", "country", ")", "options", "=", "{", ":body", "=>", "{", ":CompanyName", "=>", "company", ",", ":TimeZone", "=>", "timezone", ",", ":Country", "=>", "country", "}", ".", "to_json", "}", "put", "'setbasics'", ",", "options", "end"], "docstring": "Sets the basic details for this client.", "docstring_tokens": ["Sets", "the", "basic", "details", "for", "this", "client", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/client.rb#L117-L123", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/client.rb", "func_name": "CreateSend.Client.set_payg_billing", "original_string": "def set_payg_billing(currency, can_purchase_credits, client_pays,\n markup_percentage, markup_on_delivery=0, markup_per_recipient=0,\n markup_on_design_spam_test=0)\n options = { :body => {\n :Currency => currency,\n :CanPurchaseCredits => can_purchase_credits,\n :ClientPays => client_pays,\n :MarkupPercentage => markup_percentage,\n :MarkupOnDelivery => markup_on_delivery,\n :MarkupPerRecipient => markup_per_recipient,\n :MarkupOnDesignSpamTest => markup_on_design_spam_test }.to_json }\n put 'setpaygbilling', options\n end", "language": "ruby", "code": "def set_payg_billing(currency, can_purchase_credits, client_pays,\n markup_percentage, markup_on_delivery=0, markup_per_recipient=0,\n markup_on_design_spam_test=0)\n options = { :body => {\n :Currency => currency,\n :CanPurchaseCredits => can_purchase_credits,\n :ClientPays => client_pays,\n :MarkupPercentage => markup_percentage,\n :MarkupOnDelivery => markup_on_delivery,\n :MarkupPerRecipient => markup_per_recipient,\n :MarkupOnDesignSpamTest => markup_on_design_spam_test }.to_json }\n put 'setpaygbilling', options\n end", "code_tokens": ["def", "set_payg_billing", "(", "currency", ",", "can_purchase_credits", ",", "client_pays", ",", "markup_percentage", ",", "markup_on_delivery", "=", "0", ",", "markup_per_recipient", "=", "0", ",", "markup_on_design_spam_test", "=", "0", ")", "options", "=", "{", ":body", "=>", "{", ":Currency", "=>", "currency", ",", ":CanPurchaseCredits", "=>", "can_purchase_credits", ",", ":ClientPays", "=>", "client_pays", ",", ":MarkupPercentage", "=>", "markup_percentage", ",", ":MarkupOnDelivery", "=>", "markup_on_delivery", ",", ":MarkupPerRecipient", "=>", "markup_per_recipient", ",", ":MarkupOnDesignSpamTest", "=>", "markup_on_design_spam_test", "}", ".", "to_json", "}", "put", "'setpaygbilling'", ",", "options", "end"], "docstring": "Sets the PAYG billing settings for this client.", "docstring_tokens": ["Sets", "the", "PAYG", "billing", "settings", "for", "this", "client", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/client.rb#L126-L138", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/client.rb", "func_name": "CreateSend.Client.set_monthly_billing", "original_string": "def set_monthly_billing(currency, client_pays, markup_percentage,\n monthly_scheme = nil)\n options = { :body => {\n :Currency => currency,\n :ClientPays => client_pays,\n :MarkupPercentage => markup_percentage,\n :MonthlyScheme => monthly_scheme }.to_json }\n put 'setmonthlybilling', options\n end", "language": "ruby", "code": "def set_monthly_billing(currency, client_pays, markup_percentage,\n monthly_scheme = nil)\n options = { :body => {\n :Currency => currency,\n :ClientPays => client_pays,\n :MarkupPercentage => markup_percentage,\n :MonthlyScheme => monthly_scheme }.to_json }\n put 'setmonthlybilling', options\n end", "code_tokens": ["def", "set_monthly_billing", "(", "currency", ",", "client_pays", ",", "markup_percentage", ",", "monthly_scheme", "=", "nil", ")", "options", "=", "{", ":body", "=>", "{", ":Currency", "=>", "currency", ",", ":ClientPays", "=>", "client_pays", ",", ":MarkupPercentage", "=>", "markup_percentage", ",", ":MonthlyScheme", "=>", "monthly_scheme", "}", ".", "to_json", "}", "put", "'setmonthlybilling'", ",", "options", "end"], "docstring": "Sets the monthly billing settings for this client.\n monthly_scheme must be nil, Basic or Unlimited", "docstring_tokens": ["Sets", "the", "monthly", "billing", "settings", "for", "this", "client", ".", "monthly_scheme", "must", "be", "nil", "Basic", "or", "Unlimited"], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/client.rb#L142-L150", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/client.rb", "func_name": "CreateSend.Client.transfer_credits", "original_string": "def transfer_credits(credits, can_use_my_credits_when_they_run_out)\n options = { :body => {\n :Credits => credits,\n :CanUseMyCreditsWhenTheyRunOut => can_use_my_credits_when_they_run_out\n }.to_json }\n response = post 'credits', options\n Hashie::Mash.new(response)\n end", "language": "ruby", "code": "def transfer_credits(credits, can_use_my_credits_when_they_run_out)\n options = { :body => {\n :Credits => credits,\n :CanUseMyCreditsWhenTheyRunOut => can_use_my_credits_when_they_run_out\n }.to_json }\n response = post 'credits', options\n Hashie::Mash.new(response)\n end", "code_tokens": ["def", "transfer_credits", "(", "credits", ",", "can_use_my_credits_when_they_run_out", ")", "options", "=", "{", ":body", "=>", "{", ":Credits", "=>", "credits", ",", ":CanUseMyCreditsWhenTheyRunOut", "=>", "can_use_my_credits_when_they_run_out", "}", ".", "to_json", "}", "response", "=", "post", "'credits'", ",", "options", "Hashie", "::", "Mash", ".", "new", "(", "response", ")", "end"], "docstring": "Transfer credits to or from this client.\n\n credits - An Integer representing the number of credits to transfer.\n This value may be either positive if you want to allocate credits from\n your account to the client, or negative if you want to deduct credits\n from the client back into your account.\n can_use_my_credits_when_they_run_out - A Boolean value representing\n which, if set to true, will allow the client to continue sending using\n your credits or payment details once they run out of credits, and if\n set to false, will prevent the client from using your credits to\n continue sending until you allocate more credits to them.\n\n Returns an object of the following form representing the result:\n {\n AccountCredits # Integer representing credits in your account now\n ClientCredits # Integer representing credits in this client's\n account now\n }", "docstring_tokens": ["Transfer", "credits", "to", "or", "from", "this", "client", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/client.rb#L170-L177", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/campaign.rb", "func_name": "CreateSend.Campaign.send_preview", "original_string": "def send_preview(recipients, personalize=\"fallback\")\n options = { :body => {\n :PreviewRecipients => recipients.kind_of?(String) ?\n [ recipients ] : recipients,\n :Personalize => personalize }.to_json }\n post \"sendpreview\", options\n end", "language": "ruby", "code": "def send_preview(recipients, personalize=\"fallback\")\n options = { :body => {\n :PreviewRecipients => recipients.kind_of?(String) ?\n [ recipients ] : recipients,\n :Personalize => personalize }.to_json }\n post \"sendpreview\", options\n end", "code_tokens": ["def", "send_preview", "(", "recipients", ",", "personalize", "=", "\"fallback\"", ")", "options", "=", "{", ":body", "=>", "{", ":PreviewRecipients", "=>", "recipients", ".", "kind_of?", "(", "String", ")", "?", "[", "recipients", "]", ":", "recipients", ",", ":Personalize", "=>", "personalize", "}", ".", "to_json", "}", "post", "\"sendpreview\"", ",", "options", "end"], "docstring": "Sends a preview of this campaign.", "docstring_tokens": ["Sends", "a", "preview", "of", "this", "campaign", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/campaign.rb#L82-L88", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/campaign.rb", "func_name": "CreateSend.Campaign.email_client_usage", "original_string": "def email_client_usage\n response = get \"emailclientusage\", {}\n response.map{|item| Hashie::Mash.new(item)}\n end", "language": "ruby", "code": "def email_client_usage\n response = get \"emailclientusage\", {}\n response.map{|item| Hashie::Mash.new(item)}\n end", "code_tokens": ["def", "email_client_usage", "response", "=", "get", "\"emailclientusage\"", ",", "{", "}", "response", ".", "map", "{", "|", "item", "|", "Hashie", "::", "Mash", ".", "new", "(", "item", ")", "}", "end"], "docstring": "Gets the email clients that subscribers used to open the campaign", "docstring_tokens": ["Gets", "the", "email", "clients", "that", "subscribers", "used", "to", "open", "the", "campaign"], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/campaign.rb#L116-L119", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/campaign.rb", "func_name": "CreateSend.Campaign.opens", "original_string": "def opens(date=\"\", page=1, page_size=1000, order_field=\"date\",\n order_direction=\"asc\")\n paged_result_by_date(\"opens\", date, page, page_size, order_field,\n order_direction)\n end", "language": "ruby", "code": "def opens(date=\"\", page=1, page_size=1000, order_field=\"date\",\n order_direction=\"asc\")\n paged_result_by_date(\"opens\", date, page, page_size, order_field,\n order_direction)\n end", "code_tokens": ["def", "opens", "(", "date", "=", "\"\"", ",", "page", "=", "1", ",", "page_size", "=", "1000", ",", "order_field", "=", "\"date\"", ",", "order_direction", "=", "\"asc\"", ")", "paged_result_by_date", "(", "\"opens\"", ",", "date", ",", "page", ",", "page_size", ",", "order_field", ",", "order_direction", ")", "end"], "docstring": "Retrieves the opens for this campaign.", "docstring_tokens": ["Retrieves", "the", "opens", "for", "this", "campaign", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/campaign.rb#L141-L145", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/campaign.rb", "func_name": "CreateSend.Campaign.clicks", "original_string": "def clicks(date=\"\", page=1, page_size=1000, order_field=\"date\",\n order_direction=\"asc\")\n paged_result_by_date(\"clicks\", date, page, page_size, order_field,\n order_direction)\n end", "language": "ruby", "code": "def clicks(date=\"\", page=1, page_size=1000, order_field=\"date\",\n order_direction=\"asc\")\n paged_result_by_date(\"clicks\", date, page, page_size, order_field,\n order_direction)\n end", "code_tokens": ["def", "clicks", "(", "date", "=", "\"\"", ",", "page", "=", "1", ",", "page_size", "=", "1000", ",", "order_field", "=", "\"date\"", ",", "order_direction", "=", "\"asc\"", ")", "paged_result_by_date", "(", "\"clicks\"", ",", "date", ",", "page", ",", "page_size", ",", "order_field", ",", "order_direction", ")", "end"], "docstring": "Retrieves the subscriber clicks for this campaign.", "docstring_tokens": ["Retrieves", "the", "subscriber", "clicks", "for", "this", "campaign", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/campaign.rb#L148-L152", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/campaign.rb", "func_name": "CreateSend.Campaign.unsubscribes", "original_string": "def unsubscribes(date=\"\", page=1, page_size=1000, order_field=\"date\",\n order_direction=\"asc\")\n paged_result_by_date(\"unsubscribes\", date, page, page_size, order_field,\n order_direction)\n end", "language": "ruby", "code": "def unsubscribes(date=\"\", page=1, page_size=1000, order_field=\"date\",\n order_direction=\"asc\")\n paged_result_by_date(\"unsubscribes\", date, page, page_size, order_field,\n order_direction)\n end", "code_tokens": ["def", "unsubscribes", "(", "date", "=", "\"\"", ",", "page", "=", "1", ",", "page_size", "=", "1000", ",", "order_field", "=", "\"date\"", ",", "order_direction", "=", "\"asc\"", ")", "paged_result_by_date", "(", "\"unsubscribes\"", ",", "date", ",", "page", ",", "page_size", ",", "order_field", ",", "order_direction", ")", "end"], "docstring": "Retrieves the unsubscribes for this campaign.", "docstring_tokens": ["Retrieves", "the", "unsubscribes", "for", "this", "campaign", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/campaign.rb#L155-L159", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/campaign.rb", "func_name": "CreateSend.Campaign.spam", "original_string": "def spam(date=\"\", page=1, page_size=1000, order_field=\"date\",\n order_direction=\"asc\")\n paged_result_by_date(\"spam\", date, page, page_size, order_field,\n order_direction)\n end", "language": "ruby", "code": "def spam(date=\"\", page=1, page_size=1000, order_field=\"date\",\n order_direction=\"asc\")\n paged_result_by_date(\"spam\", date, page, page_size, order_field,\n order_direction)\n end", "code_tokens": ["def", "spam", "(", "date", "=", "\"\"", ",", "page", "=", "1", ",", "page_size", "=", "1000", ",", "order_field", "=", "\"date\"", ",", "order_direction", "=", "\"asc\"", ")", "paged_result_by_date", "(", "\"spam\"", ",", "date", ",", "page", ",", "page_size", ",", "order_field", ",", "order_direction", ")", "end"], "docstring": "Retrieves the spam complaints for this campaign.", "docstring_tokens": ["Retrieves", "the", "spam", "complaints", "for", "this", "campaign", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/campaign.rb#L162-L166", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/campaign.rb", "func_name": "CreateSend.Campaign.bounces", "original_string": "def bounces(date=\"\", page=1, page_size=1000, order_field=\"date\",\n order_direction=\"asc\")\n paged_result_by_date(\"bounces\", date, page, page_size, order_field,\n order_direction)\n end", "language": "ruby", "code": "def bounces(date=\"\", page=1, page_size=1000, order_field=\"date\",\n order_direction=\"asc\")\n paged_result_by_date(\"bounces\", date, page, page_size, order_field,\n order_direction)\n end", "code_tokens": ["def", "bounces", "(", "date", "=", "\"\"", ",", "page", "=", "1", ",", "page_size", "=", "1000", ",", "order_field", "=", "\"date\"", ",", "order_direction", "=", "\"asc\"", ")", "paged_result_by_date", "(", "\"bounces\"", ",", "date", ",", "page", ",", "page_size", ",", "order_field", ",", "order_direction", ")", "end"], "docstring": "Retrieves the bounces for this campaign.", "docstring_tokens": ["Retrieves", "the", "bounces", "for", "this", "campaign", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/campaign.rb#L169-L173", "partition": "valid"} {"repo": "campaignmonitor/createsend-ruby", "path": "lib/createsend/administrator.rb", "func_name": "CreateSend.Administrator.update", "original_string": "def update(new_email_address, name)\n options = {\n :query => { :email => @email_address },\n :body => {\n :EmailAddress => new_email_address,\n :Name => name\n }.to_json }\n put '/admins.json', options\n # Update @email_address, so this object can continue to be used reliably\n @email_address = new_email_address\n end", "language": "ruby", "code": "def update(new_email_address, name)\n options = {\n :query => { :email => @email_address },\n :body => {\n :EmailAddress => new_email_address,\n :Name => name\n }.to_json }\n put '/admins.json', options\n # Update @email_address, so this object can continue to be used reliably\n @email_address = new_email_address\n end", "code_tokens": ["def", "update", "(", "new_email_address", ",", "name", ")", "options", "=", "{", ":query", "=>", "{", ":email", "=>", "@email_address", "}", ",", ":body", "=>", "{", ":EmailAddress", "=>", "new_email_address", ",", ":Name", "=>", "name", "}", ".", "to_json", "}", "put", "'/admins.json'", ",", "options", "# Update @email_address, so this object can continue to be used reliably", "@email_address", "=", "new_email_address", "end"], "docstring": "Updates the administator details.", "docstring_tokens": ["Updates", "the", "administator", "details", "."], "sha": "8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5", "url": "https://github.com/campaignmonitor/createsend-ruby/blob/8ef7eb1a048363e3557dedbb2e666c4e5b1ccbe5/lib/createsend/administrator.rb#L31-L41", "partition": "valid"} {"repo": "snowplow/snowplow-ruby-tracker", "path": "lib/snowplow-tracker/emitters.rb", "func_name": "SnowplowTracker.AsyncEmitter.flush", "original_string": "def flush(async=true)\n loop do\n @lock.synchronize do\n @queue.synchronize do\n @results_unprocessed += 1\n end\n @queue << @buffer\n @buffer = []\n end\n if not async\n LOGGER.info('Starting synchronous flush')\n @queue.synchronize do\n @all_processed_condition.wait_while { @results_unprocessed > 0 }\n LOGGER.info('Finished synchronous flush')\n end\n end\n break if @buffer.size < 1\n end\n end", "language": "ruby", "code": "def flush(async=true)\n loop do\n @lock.synchronize do\n @queue.synchronize do\n @results_unprocessed += 1\n end\n @queue << @buffer\n @buffer = []\n end\n if not async\n LOGGER.info('Starting synchronous flush')\n @queue.synchronize do\n @all_processed_condition.wait_while { @results_unprocessed > 0 }\n LOGGER.info('Finished synchronous flush')\n end\n end\n break if @buffer.size < 1\n end\n end", "code_tokens": ["def", "flush", "(", "async", "=", "true", ")", "loop", "do", "@lock", ".", "synchronize", "do", "@queue", ".", "synchronize", "do", "@results_unprocessed", "+=", "1", "end", "@queue", "<<", "@buffer", "@buffer", "=", "[", "]", "end", "if", "not", "async", "LOGGER", ".", "info", "(", "'Starting synchronous flush'", ")", "@queue", ".", "synchronize", "do", "@all_processed_condition", ".", "wait_while", "{", "@results_unprocessed", ">", "0", "}", "LOGGER", ".", "info", "(", "'Finished synchronous flush'", ")", "end", "end", "break", "if", "@buffer", ".", "size", "<", "1", "end", "end"], "docstring": "Flush the buffer\n If async is false, block until the queue is empty", "docstring_tokens": ["Flush", "the", "buffer", "If", "async", "is", "false", "block", "until", "the", "queue", "is", "empty"], "sha": "39fcfa2be793f2e25e73087a9700abc93f43b5e8", "url": "https://github.com/snowplow/snowplow-ruby-tracker/blob/39fcfa2be793f2e25e73087a9700abc93f43b5e8/lib/snowplow-tracker/emitters.rb#L259-L277", "partition": "valid"} {"repo": "abrom/rocketchat-ruby", "path": "lib/rocket_chat/util.rb", "func_name": "RocketChat.Util.stringify_hash_keys", "original_string": "def stringify_hash_keys(hash)\n new_hash = {}\n hash.each do |key, value|\n new_hash[key.to_s] =\n if value.is_a? Hash\n stringify_hash_keys value\n else\n value\n end\n end\n new_hash\n end", "language": "ruby", "code": "def stringify_hash_keys(hash)\n new_hash = {}\n hash.each do |key, value|\n new_hash[key.to_s] =\n if value.is_a? Hash\n stringify_hash_keys value\n else\n value\n end\n end\n new_hash\n end", "code_tokens": ["def", "stringify_hash_keys", "(", "hash", ")", "new_hash", "=", "{", "}", "hash", ".", "each", "do", "|", "key", ",", "value", "|", "new_hash", "[", "key", ".", "to_s", "]", "=", "if", "value", ".", "is_a?", "Hash", "stringify_hash_keys", "value", "else", "value", "end", "end", "new_hash", "end"], "docstring": "Stringify symbolized hash keys\n @param [Hash] hash A string/symbol keyed hash\n @return Stringified hash", "docstring_tokens": ["Stringify", "symbolized", "hash", "keys"], "sha": "4664693217c5e6142a873710a8867757ba84ca16", "url": "https://github.com/abrom/rocketchat-ruby/blob/4664693217c5e6142a873710a8867757ba84ca16/lib/rocket_chat/util.rb#L13-L24", "partition": "valid"} {"repo": "abrom/rocketchat-ruby", "path": "lib/rocket_chat/util.rb", "func_name": "RocketChat.Util.slice_hash", "original_string": "def slice_hash(hash, *keys)\n return {} if keys.length.zero?\n\n new_hash = {}\n hash.each do |key, value|\n new_hash[key] = value if keys.include? key\n end\n new_hash\n end", "language": "ruby", "code": "def slice_hash(hash, *keys)\n return {} if keys.length.zero?\n\n new_hash = {}\n hash.each do |key, value|\n new_hash[key] = value if keys.include? key\n end\n new_hash\n end", "code_tokens": ["def", "slice_hash", "(", "hash", ",", "*", "keys", ")", "return", "{", "}", "if", "keys", ".", "length", ".", "zero?", "new_hash", "=", "{", "}", "hash", ".", "each", "do", "|", "key", ",", "value", "|", "new_hash", "[", "key", "]", "=", "value", "if", "keys", ".", "include?", "key", "end", "new_hash", "end"], "docstring": "Slice keys from hash\n @param [Hash] hash A hash to slice key/value pairs from\n @param [Array] *keys The keys to be sliced\n @return Hash filtered by keys", "docstring_tokens": ["Slice", "keys", "from", "hash"], "sha": "4664693217c5e6142a873710a8867757ba84ca16", "url": "https://github.com/abrom/rocketchat-ruby/blob/4664693217c5e6142a873710a8867757ba84ca16/lib/rocket_chat/util.rb#L32-L40", "partition": "valid"} {"repo": "abrom/rocketchat-ruby", "path": "lib/rocket_chat/server.rb", "func_name": "RocketChat.Server.login", "original_string": "def login(username, password)\n response = request_json(\n '/api/v1/login',\n method: :post,\n body: {\n username: username,\n password: password\n }\n )\n Session.new self, Token.new(response['data'])\n end", "language": "ruby", "code": "def login(username, password)\n response = request_json(\n '/api/v1/login',\n method: :post,\n body: {\n username: username,\n password: password\n }\n )\n Session.new self, Token.new(response['data'])\n end", "code_tokens": ["def", "login", "(", "username", ",", "password", ")", "response", "=", "request_json", "(", "'/api/v1/login'", ",", "method", ":", ":post", ",", "body", ":", "{", "username", ":", "username", ",", "password", ":", "password", "}", ")", "Session", ".", "new", "self", ",", "Token", ".", "new", "(", "response", "[", "'data'", "]", ")", "end"], "docstring": "Login REST API\n @param [String] username Username\n @param [String] password Password\n @return [Session] Rocket.Chat Session\n @raise [HTTPError, StatusError]", "docstring_tokens": ["Login", "REST", "API"], "sha": "4664693217c5e6142a873710a8867757ba84ca16", "url": "https://github.com/abrom/rocketchat-ruby/blob/4664693217c5e6142a873710a8867757ba84ca16/lib/rocket_chat/server.rb#L37-L47", "partition": "valid"} {"repo": "spovich/mandrill_dm", "path": "lib/mandrill_dm/message.rb", "func_name": "MandrillDm.Message.attachments", "original_string": "def attachments\n regular_attachments = mail.attachments.reject(&:inline?)\n regular_attachments.collect do |attachment|\n {\n name: attachment.filename,\n type: attachment.mime_type,\n content: Base64.encode64(attachment.body.decoded)\n }\n end\n end", "language": "ruby", "code": "def attachments\n regular_attachments = mail.attachments.reject(&:inline?)\n regular_attachments.collect do |attachment|\n {\n name: attachment.filename,\n type: attachment.mime_type,\n content: Base64.encode64(attachment.body.decoded)\n }\n end\n end", "code_tokens": ["def", "attachments", "regular_attachments", "=", "mail", ".", "attachments", ".", "reject", "(", ":inline?", ")", "regular_attachments", ".", "collect", "do", "|", "attachment", "|", "{", "name", ":", "attachment", ".", "filename", ",", "type", ":", "attachment", ".", "mime_type", ",", "content", ":", "Base64", ".", "encode64", "(", "attachment", ".", "body", ".", "decoded", ")", "}", "end", "end"], "docstring": "Returns a Mandrill API compatible attachment hash", "docstring_tokens": ["Returns", "a", "Mandrill", "API", "compatible", "attachment", "hash"], "sha": "0636a9969292d3c545df111c296361af47f6373b", "url": "https://github.com/spovich/mandrill_dm/blob/0636a9969292d3c545df111c296361af47f6373b/lib/mandrill_dm/message.rb#L12-L21", "partition": "valid"} {"repo": "spovich/mandrill_dm", "path": "lib/mandrill_dm/message.rb", "func_name": "MandrillDm.Message.images", "original_string": "def images\n inline_attachments = mail.attachments.select(&:inline?)\n inline_attachments.collect do |attachment|\n {\n name: attachment.cid,\n type: attachment.mime_type,\n content: Base64.encode64(attachment.body.decoded)\n }\n end\n end", "language": "ruby", "code": "def images\n inline_attachments = mail.attachments.select(&:inline?)\n inline_attachments.collect do |attachment|\n {\n name: attachment.cid,\n type: attachment.mime_type,\n content: Base64.encode64(attachment.body.decoded)\n }\n end\n end", "code_tokens": ["def", "images", "inline_attachments", "=", "mail", ".", "attachments", ".", "select", "(", ":inline?", ")", "inline_attachments", ".", "collect", "do", "|", "attachment", "|", "{", "name", ":", "attachment", ".", "cid", ",", "type", ":", "attachment", ".", "mime_type", ",", "content", ":", "Base64", ".", "encode64", "(", "attachment", ".", "body", ".", "decoded", ")", "}", "end", "end"], "docstring": "Mandrill uses a different hash for inlined image attachments", "docstring_tokens": ["Mandrill", "uses", "a", "different", "hash", "for", "inlined", "image", "attachments"], "sha": "0636a9969292d3c545df111c296361af47f6373b", "url": "https://github.com/spovich/mandrill_dm/blob/0636a9969292d3c545df111c296361af47f6373b/lib/mandrill_dm/message.rb#L24-L33", "partition": "valid"} {"repo": "denniskuczynski/beanstalkd_view", "path": "lib/beanstalkd_view/beanstalkd_utils.rb", "func_name": "BeanstalkdView.BeanstalkdUtils.get_chart_data_hash", "original_string": "def get_chart_data_hash(tubes)\n chart_data = {}\n chart_data[\"total_jobs_data\"] = Hash.new\n chart_data[\"buried_jobs_data\"] = Hash.new\n chart_data[\"total_jobs_data\"][\"items\"] = Array.new\n chart_data[\"buried_jobs_data\"][\"items\"] = Array.new \n tubes.each do |tube|\n stats = tube.stats\n add_chart_data_to_hash(tube, stats[:total_jobs], chart_data[\"total_jobs_data\"][\"items\"])\n add_chart_data_to_hash(tube, stats[:current_jobs_buried], chart_data[\"buried_jobs_data\"][\"items\"])\n end\n chart_data\n end", "language": "ruby", "code": "def get_chart_data_hash(tubes)\n chart_data = {}\n chart_data[\"total_jobs_data\"] = Hash.new\n chart_data[\"buried_jobs_data\"] = Hash.new\n chart_data[\"total_jobs_data\"][\"items\"] = Array.new\n chart_data[\"buried_jobs_data\"][\"items\"] = Array.new \n tubes.each do |tube|\n stats = tube.stats\n add_chart_data_to_hash(tube, stats[:total_jobs], chart_data[\"total_jobs_data\"][\"items\"])\n add_chart_data_to_hash(tube, stats[:current_jobs_buried], chart_data[\"buried_jobs_data\"][\"items\"])\n end\n chart_data\n end", "code_tokens": ["def", "get_chart_data_hash", "(", "tubes", ")", "chart_data", "=", "{", "}", "chart_data", "[", "\"total_jobs_data\"", "]", "=", "Hash", ".", "new", "chart_data", "[", "\"buried_jobs_data\"", "]", "=", "Hash", ".", "new", "chart_data", "[", "\"total_jobs_data\"", "]", "[", "\"items\"", "]", "=", "Array", ".", "new", "chart_data", "[", "\"buried_jobs_data\"", "]", "[", "\"items\"", "]", "=", "Array", ".", "new", "tubes", ".", "each", "do", "|", "tube", "|", "stats", "=", "tube", ".", "stats", "add_chart_data_to_hash", "(", "tube", ",", "stats", "[", ":total_jobs", "]", ",", "chart_data", "[", "\"total_jobs_data\"", "]", "[", "\"items\"", "]", ")", "add_chart_data_to_hash", "(", "tube", ",", "stats", "[", ":current_jobs_buried", "]", ",", "chart_data", "[", "\"buried_jobs_data\"", "]", "[", "\"items\"", "]", ")", "end", "chart_data", "end"], "docstring": "Return the stats data in a format for the Bluff JS UI Charts", "docstring_tokens": ["Return", "the", "stats", "data", "in", "a", "format", "for", "the", "Bluff", "JS", "UI", "Charts"], "sha": "0ab71a552d91f9ef22e704e45f72007fe92e57c9", "url": "https://github.com/denniskuczynski/beanstalkd_view/blob/0ab71a552d91f9ef22e704e45f72007fe92e57c9/lib/beanstalkd_view/beanstalkd_utils.rb#L39-L51", "partition": "valid"} {"repo": "denniskuczynski/beanstalkd_view", "path": "lib/beanstalkd_view/beanstalkd_utils.rb", "func_name": "BeanstalkdView.BeanstalkdUtils.guess_min_peek_range", "original_string": "def guess_min_peek_range(tubes)\n min = 0\n tubes.each do |tube|\n response = tube.peek('ready')\n if response\n if min == 0\n min = response.id.to_i\n else\n min = [min, response.id.to_i].min\n end\n end\n end\n # Add some jitter in the opposite direction of 1/4 range\n jitter_min = (min-(GUESS_PEEK_RANGE*0.25)).to_i\n [1, jitter_min].max\n end", "language": "ruby", "code": "def guess_min_peek_range(tubes)\n min = 0\n tubes.each do |tube|\n response = tube.peek('ready')\n if response\n if min == 0\n min = response.id.to_i\n else\n min = [min, response.id.to_i].min\n end\n end\n end\n # Add some jitter in the opposite direction of 1/4 range\n jitter_min = (min-(GUESS_PEEK_RANGE*0.25)).to_i\n [1, jitter_min].max\n end", "code_tokens": ["def", "guess_min_peek_range", "(", "tubes", ")", "min", "=", "0", "tubes", ".", "each", "do", "|", "tube", "|", "response", "=", "tube", ".", "peek", "(", "'ready'", ")", "if", "response", "if", "min", "==", "0", "min", "=", "response", ".", "id", ".", "to_i", "else", "min", "=", "[", "min", ",", "response", ".", "id", ".", "to_i", "]", ".", "min", "end", "end", "end", "# Add some jitter in the opposite direction of 1/4 range", "jitter_min", "=", "(", "min", "-", "(", "GUESS_PEEK_RANGE", "0.25", ")", ")", ".", "to_i", "[", "1", ",", "jitter_min", "]", ".", "max", "end"], "docstring": "Pick a Minimum Peek Range Based on minumum ready jobs on all tubes", "docstring_tokens": ["Pick", "a", "Minimum", "Peek", "Range", "Based", "on", "minumum", "ready", "jobs", "on", "all", "tubes"], "sha": "0ab71a552d91f9ef22e704e45f72007fe92e57c9", "url": "https://github.com/denniskuczynski/beanstalkd_view/blob/0ab71a552d91f9ef22e704e45f72007fe92e57c9/lib/beanstalkd_view/beanstalkd_utils.rb#L63-L78", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/pages.rb", "func_name": "Foursquare2.Pages.page_venues", "original_string": "def page_venues(page_id, options={})\n response = connection.get do |req|\n req.url \"pages/#{page_id}/venues\", options\n end\n venues = return_error_or_body(response, response.body.response.venues)\n venues = Foursquare2.filter(venues, options[:query]) if options.has_key? :query\n venues\n end", "language": "ruby", "code": "def page_venues(page_id, options={})\n response = connection.get do |req|\n req.url \"pages/#{page_id}/venues\", options\n end\n venues = return_error_or_body(response, response.body.response.venues)\n venues = Foursquare2.filter(venues, options[:query]) if options.has_key? :query\n venues\n end", "code_tokens": ["def", "page_venues", "(", "page_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"pages/#{page_id}/venues\"", ",", "options", "end", "venues", "=", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "venues", ")", "venues", "=", "Foursquare2", ".", "filter", "(", "venues", ",", "options", "[", ":query", "]", ")", "if", "options", ".", "has_key?", ":query", "venues", "end"], "docstring": "Get all venues for a given page.\n\n @param [String] page_id - The page to retrieve venues for.\n @param [Hash] options\n @option options Integer :limit\n @option options Integer :offset - For paging through results\n @option options String :ll - Latitude and longitude in format LAT,LON - Limit results to venues near this latitude and longitude. NOT VALID with NE or SW (see after).\n @option String :radius - Can be used when including ll. Limit results to venues within this many meters of the specified ll. Not valid with ne or sw.\n @option String :sw - With ne, limits results to the bounding quadrangle defined by the latitude and longitude given by sw as its south-west corner, and ne as its north-east corner. Not valid with ll or radius.\n @option String :ne - See sw", "docstring_tokens": ["Get", "all", "venues", "for", "a", "given", "page", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/pages.rb#L43-L50", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/pages.rb", "func_name": "Foursquare2.Pages.managed_pages", "original_string": "def managed_pages(options={})\n response = connection.get do |req|\n req.url \"pages/managing\", options\n end\n return_error_or_body(response, response.body.response.managing)\n end", "language": "ruby", "code": "def managed_pages(options={})\n response = connection.get do |req|\n req.url \"pages/managing\", options\n end\n return_error_or_body(response, response.body.response.managing)\n end", "code_tokens": ["def", "managed_pages", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"pages/managing\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "managing", ")", "end"], "docstring": "Returns a list of managed pages.", "docstring_tokens": ["Returns", "a", "list", "of", "managed", "pages", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/pages.rb#L57-L62", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/users.rb", "func_name": "Foursquare2.Users.search_users_by_tip", "original_string": "def search_users_by_tip(options={})\n name = options.delete(:name)\n options[:limit] = 500\n tips = search_tips(options)\n user = []\n tips.each do |tip|\n user << tip['user'] if check_name(tip['user'], name)\n end\n user.uniq\n end", "language": "ruby", "code": "def search_users_by_tip(options={})\n name = options.delete(:name)\n options[:limit] = 500\n tips = search_tips(options)\n user = []\n tips.each do |tip|\n user << tip['user'] if check_name(tip['user'], name)\n end\n user.uniq\n end", "code_tokens": ["def", "search_users_by_tip", "(", "options", "=", "{", "}", ")", "name", "=", "options", ".", "delete", "(", ":name", ")", "options", "[", ":limit", "]", "=", "500", "tips", "=", "search_tips", "(", "options", ")", "user", "=", "[", "]", "tips", ".", "each", "do", "|", "tip", "|", "user", "<<", "tip", "[", "'user'", "]", "if", "check_name", "(", "tip", "[", "'user'", "]", ",", "name", ")", "end", "user", ".", "uniq", "end"], "docstring": "Search for users by tip\n @param [Hash] options\n @option options String :ll - Latitude and longitude in format LAT,LON\n @option options Integer :limit - The limit of results to return.\n @option options Integer :offset - Used to page through results.\n @option options String :filter - Set to 'friends' to limit tips to those from friends.\n @option options String :query - Only find tips matching this term.\n @option options String :name - Match on name", "docstring_tokens": ["Search", "for", "users", "by", "tip"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/users.rb#L52-L61", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/users.rb", "func_name": "Foursquare2.Users.user_requests", "original_string": "def user_requests(options={})\n response = connection.get do |req|\n req.url \"users/requests\", options\n end\n return_error_or_body(response, response.body.response.requests)\n end", "language": "ruby", "code": "def user_requests(options={})\n response = connection.get do |req|\n req.url \"users/requests\", options\n end\n return_error_or_body(response, response.body.response.requests)\n end", "code_tokens": ["def", "user_requests", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"users/requests\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "requests", ")", "end"], "docstring": "Get all pending friend requests for the authenticated user", "docstring_tokens": ["Get", "all", "pending", "friend", "requests", "for", "the", "authenticated", "user"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/users.rb#L70-L75", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/users.rb", "func_name": "Foursquare2.Users.user_checkins", "original_string": "def user_checkins(options={})\n response = connection.get do |req|\n req.url \"users/self/checkins\", options\n end\n return_error_or_body(response, response.body.response.checkins)\n end", "language": "ruby", "code": "def user_checkins(options={})\n response = connection.get do |req|\n req.url \"users/self/checkins\", options\n end\n return_error_or_body(response, response.body.response.checkins)\n end", "code_tokens": ["def", "user_checkins", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"users/self/checkins\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "checkins", ")", "end"], "docstring": "Get checkins for the authenticated user\n @param [Hash] options\n @option options Integer :limit\n @option options Integer :offest - For paging through results\n @option options String :sort - \"newestfirst\" or \"oldestfirst\"\n @option options Integer :afterTimestamp - Get all checkins after this epoch time.\n @option options Integer :beforeTimestamp - Get all checkins before this epoch time.", "docstring_tokens": ["Get", "checkins", "for", "the", "authenticated", "user"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/users.rb#L96-L101", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/users.rb", "func_name": "Foursquare2.Users.user_friends", "original_string": "def user_friends(user_id, options={})\n response = connection.get do |req|\n req.url \"users/#{user_id}/friends\", options\n end\n return_error_or_body(response, response.body.response.friends)\n end", "language": "ruby", "code": "def user_friends(user_id, options={})\n response = connection.get do |req|\n req.url \"users/#{user_id}/friends\", options\n end\n return_error_or_body(response, response.body.response.friends)\n end", "code_tokens": ["def", "user_friends", "(", "user_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"users/#{user_id}/friends\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "friends", ")", "end"], "docstring": "Get all friends for a given user.\n\n @param [String] user_id - The user to retrieve friends for.\n @param [Hash] options\n @option options Integer :limit\n @option options Integer :offest - For paging through results", "docstring_tokens": ["Get", "all", "friends", "for", "a", "given", "user", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/users.rb#L110-L115", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/users.rb", "func_name": "Foursquare2.Users.user_tips", "original_string": "def user_tips(user_id, options={})\n response = connection.get do |req|\n req.url \"users/#{user_id}/tips\", options\n end\n tips = return_error_or_body(response, response.body.response.tips)\n tips = Foursquare2.filter(tips, options[:query]) if options.has_key? :query\n tips\n end", "language": "ruby", "code": "def user_tips(user_id, options={})\n response = connection.get do |req|\n req.url \"users/#{user_id}/tips\", options\n end\n tips = return_error_or_body(response, response.body.response.tips)\n tips = Foursquare2.filter(tips, options[:query]) if options.has_key? :query\n tips\n end", "code_tokens": ["def", "user_tips", "(", "user_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"users/#{user_id}/tips\"", ",", "options", "end", "tips", "=", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "tips", ")", "tips", "=", "Foursquare2", ".", "filter", "(", "tips", ",", "options", "[", ":query", "]", ")", "if", "options", ".", "has_key?", ":query", "tips", "end"], "docstring": "Get all tips for a given user, optionally filtering by text.\n\n @param [String] user_id - The user to retrieve friends for.\n @param [Hash] options\n @option options Integer :limit\n @option options Integer :offest - For paging through results\n @option options String :sort - One of recent, nearby, popular\n @option options String :ll - Latitude and longitude in format LAT,LON - required for nearby sort option.\n @option String :query - Only find tips matching this term.", "docstring_tokens": ["Get", "all", "tips", "for", "a", "given", "user", "optionally", "filtering", "by", "text", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/users.rb#L127-L134", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/users.rb", "func_name": "Foursquare2.Users.user_todos", "original_string": "def user_todos(user_id, options={})\n response = connection.get do |req|\n req.url \"users/#{user_id}/todos\", options\n end\n return_error_or_body(response, response.body.response.todos)\n end", "language": "ruby", "code": "def user_todos(user_id, options={})\n response = connection.get do |req|\n req.url \"users/#{user_id}/todos\", options\n end\n return_error_or_body(response, response.body.response.todos)\n end", "code_tokens": ["def", "user_todos", "(", "user_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"users/#{user_id}/todos\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "todos", ")", "end"], "docstring": "Get all todos for a given user.\n\n @param [String] user_id - The user to retrieve friends for.\n @param [Hash] options\n @option options String :sort - One of recent, nearby, popular\n @option options String :ll - Latitude and longitude in format LAT,LON - required for nearby sort option.", "docstring_tokens": ["Get", "all", "todos", "for", "a", "given", "user", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/users.rb#L144-L149", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/users.rb", "func_name": "Foursquare2.Users.user_photos", "original_string": "def user_photos(options={})\n response = connection.get do |req|\n req.url \"users/self/photos\", options\n end\n return_error_or_body(response, response.body.response.photos)\n end", "language": "ruby", "code": "def user_photos(options={})\n response = connection.get do |req|\n req.url \"users/self/photos\", options\n end\n return_error_or_body(response, response.body.response.photos)\n end", "code_tokens": ["def", "user_photos", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"users/self/photos\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "photos", ")", "end"], "docstring": "Get the photos for the authenticated user.\n\n @param [Hash] options\n @option options Integer :limit - The limit of results to return.\n @option options Integer :offset - Used to page through results.", "docstring_tokens": ["Get", "the", "photos", "for", "the", "authenticated", "user", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/users.rb#L158-L163", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/users.rb", "func_name": "Foursquare2.Users.user_venue_history", "original_string": "def user_venue_history(options={})\n response = connection.get do |req|\n req.url \"users/self/venuehistory\", options\n end\n return_error_or_body(response, response.body.response.venues)\n end", "language": "ruby", "code": "def user_venue_history(options={})\n response = connection.get do |req|\n req.url \"users/self/venuehistory\", options\n end\n return_error_or_body(response, response.body.response.venues)\n end", "code_tokens": ["def", "user_venue_history", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"users/self/venuehistory\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "venues", ")", "end"], "docstring": "Get the venue history for the authenticated user.\n\n @param [Hash] options\n @option options Integer :afterTimestamp - Get all venues after this epoch time.\n @option options Integer :beforeTimestamp - Get all venues before this epoch time.", "docstring_tokens": ["Get", "the", "venue", "history", "for", "the", "authenticated", "user", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/users.rb#L172-L177", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/users.rb", "func_name": "Foursquare2.Users.user_mayorships", "original_string": "def user_mayorships(user_id, options={})\n response = connection.get do |req|\n req.url \"users/#{user_id}/mayorships\", options\n end\n return_error_or_body(response, response.body.response.mayorships)\n end", "language": "ruby", "code": "def user_mayorships(user_id, options={})\n response = connection.get do |req|\n req.url \"users/#{user_id}/mayorships\", options\n end\n return_error_or_body(response, response.body.response.mayorships)\n end", "code_tokens": ["def", "user_mayorships", "(", "user_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"users/#{user_id}/mayorships\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "mayorships", ")", "end"], "docstring": "Get the mayorships for a given user.\n\n @param [String] user_id - The user to retrieve friends for.", "docstring_tokens": ["Get", "the", "mayorships", "for", "a", "given", "user", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/users.rb#L183-L188", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/users.rb", "func_name": "Foursquare2.Users.user_lists", "original_string": "def user_lists(user_id, options={})\n response = connection.get do |req|\n req.url \"users/#{user_id}/lists\", options\n end\n return_error_or_body(response, response.body.response.lists)\n end", "language": "ruby", "code": "def user_lists(user_id, options={})\n response = connection.get do |req|\n req.url \"users/#{user_id}/lists\", options\n end\n return_error_or_body(response, response.body.response.lists)\n end", "code_tokens": ["def", "user_lists", "(", "user_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"users/#{user_id}/lists\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "lists", ")", "end"], "docstring": "Get the lists for a given user.\n\n @param [String] user_id - The user to retrieve lists for.\n @param [Hash] options\n @option options String :group - One of: created, edited, followed, friends, or suggestions\n @option options String :ll - Location of the user, required in order to receive the suggested group.", "docstring_tokens": ["Get", "the", "lists", "for", "a", "given", "user", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/users.rb#L197-L202", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/users.rb", "func_name": "Foursquare2.Users.user_friend_request", "original_string": "def user_friend_request(user_id, options={})\n response = connection.post do |req|\n req.url \"users/#{user_id}/request\", options\n end\n return_error_or_body(response, response.body.response)\n end", "language": "ruby", "code": "def user_friend_request(user_id, options={})\n response = connection.post do |req|\n req.url \"users/#{user_id}/request\", options\n end\n return_error_or_body(response, response.body.response)\n end", "code_tokens": ["def", "user_friend_request", "(", "user_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"users/#{user_id}/request\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ")", "end"], "docstring": "Request friendship with a user\n\n @param [String] user_id - The user to request friendship with.", "docstring_tokens": ["Request", "friendship", "with", "a", "user"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/users.rb#L208-L213", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/users.rb", "func_name": "Foursquare2.Users.user_set_friend_pings", "original_string": "def user_set_friend_pings(user_id, value)\n response = connection.post do |req|\n req.url \"users/#{user_id}/setpings\", value\n end\n return_error_or_body(response, response.body.response)\n end", "language": "ruby", "code": "def user_set_friend_pings(user_id, value)\n response = connection.post do |req|\n req.url \"users/#{user_id}/setpings\", value\n end\n return_error_or_body(response, response.body.response)\n end", "code_tokens": ["def", "user_set_friend_pings", "(", "user_id", ",", "value", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"users/#{user_id}/setpings\"", ",", "value", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ")", "end"], "docstring": "Set pings for a friend\n\n @param [String] user_id - The user to set pings for\n @param [String] value - The value of ping setting for this friend, either true or false.", "docstring_tokens": ["Set", "pings", "for", "a", "friend"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/users.rb#L253-L258", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/tips.rb", "func_name": "Foursquare2.Tips.tip", "original_string": "def tip(tip_id, options={})\n response = connection.get do |req|\n req.url \"tips/#{tip_id}\", options\n end\n return_error_or_body(response, response.body.response.tip)\n end", "language": "ruby", "code": "def tip(tip_id, options={})\n response = connection.get do |req|\n req.url \"tips/#{tip_id}\", options\n end\n return_error_or_body(response, response.body.response.tip)\n end", "code_tokens": ["def", "tip", "(", "tip_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"tips/#{tip_id}\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "tip", ")", "end"], "docstring": "Retrieve information about a tip.\n\n param [String] tip_id - The id of the tip to retrieve.", "docstring_tokens": ["Retrieve", "information", "about", "a", "tip", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/tips.rb#L8-L13", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/tips.rb", "func_name": "Foursquare2.Tips.search_tips", "original_string": "def search_tips(options={})\n response = connection.get do |req|\n req.url \"tips/search\", options\n end\n return_error_or_body(response, response.body.response.tips)\n end", "language": "ruby", "code": "def search_tips(options={})\n response = connection.get do |req|\n req.url \"tips/search\", options\n end\n return_error_or_body(response, response.body.response.tips)\n end", "code_tokens": ["def", "search_tips", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"tips/search\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "tips", ")", "end"], "docstring": "Search for tips.\n\n @param [Hash] options\n @option options String :ll - Latitude and longitude in format LAT,LON\n @option options Integer :limit - The limit of results to return.\n @option options Integer :offset - Used to page through results.\n @option options String :filter - Set to 'friends' to limit tips to those from friends.\n @option options String :query - Only find tips matching this term.", "docstring_tokens": ["Search", "for", "tips", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/tips.rb#L24-L29", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/tips.rb", "func_name": "Foursquare2.Tips.venue_tips", "original_string": "def venue_tips(venue_id, options={})\n query = options.delete(:query)\n response = connection.get do |req|\n req.url \"venues/#{venue_id}/tips\", options\n end\n tips = return_error_or_body(response, response.body.response.tips)\n tips = Foursquare2.filter(tips, query) if query\n tips\n end", "language": "ruby", "code": "def venue_tips(venue_id, options={})\n query = options.delete(:query)\n response = connection.get do |req|\n req.url \"venues/#{venue_id}/tips\", options\n end\n tips = return_error_or_body(response, response.body.response.tips)\n tips = Foursquare2.filter(tips, query) if query\n tips\n end", "code_tokens": ["def", "venue_tips", "(", "venue_id", ",", "options", "=", "{", "}", ")", "query", "=", "options", ".", "delete", "(", ":query", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"venues/#{venue_id}/tips\"", ",", "options", "end", "tips", "=", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "tips", ")", "tips", "=", "Foursquare2", ".", "filter", "(", "tips", ",", "query", ")", "if", "query", "tips", "end"], "docstring": "Search for tips from a venue.\n\n @param [String] venue_id - Venue id to flag, required.\n @param [Hash] options\n @option options String :sort [recent] One of recent or popular.\n @option options Integer :limit [100] Number of results to return, up to 500.\n @option options Integer :offset [100] Used to page through results\n @option options String :query - Only find tips matching this term.", "docstring_tokens": ["Search", "for", "tips", "from", "a", "venue", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/tips.rb#L40-L48", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/tips.rb", "func_name": "Foursquare2.Tips.add_tip", "original_string": "def add_tip(options={})\n response = connection.post do |req|\n req.url \"tips/add\", options\n end\n return_error_or_body(response, response.body.response.tip)\n end", "language": "ruby", "code": "def add_tip(options={})\n response = connection.post do |req|\n req.url \"tips/add\", options\n end\n return_error_or_body(response, response.body.response.tip)\n end", "code_tokens": ["def", "add_tip", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"tips/add\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "tip", ")", "end"], "docstring": "Add a tip\n\n @param [Hash] options\n @option options String :venueId - Required, which venue to add the tip to.\n @option options String :text - The text of the tip.\n @option options String :url - Optionally associated url.", "docstring_tokens": ["Add", "a", "tip"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/tips.rb#L57-L62", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/tips.rb", "func_name": "Foursquare2.Tips.mark_tip_todo", "original_string": "def mark_tip_todo(tip_id, options={})\n response = connection.post do |req|\n req.url \"tips/#{tip_id}/marktodo\", options\n end\n return_error_or_body(response, response.body.response)\n end", "language": "ruby", "code": "def mark_tip_todo(tip_id, options={})\n response = connection.post do |req|\n req.url \"tips/#{tip_id}/marktodo\", options\n end\n return_error_or_body(response, response.body.response)\n end", "code_tokens": ["def", "mark_tip_todo", "(", "tip_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"tips/#{tip_id}/marktodo\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ")", "end"], "docstring": "Mark a tip todo for the authenticated user.\n\n param [String] tip_id - The id of the tip to mark.", "docstring_tokens": ["Mark", "a", "tip", "todo", "for", "the", "authenticated", "user", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/tips.rb#L68-L73", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/events.rb", "func_name": "Foursquare2.Events.event", "original_string": "def event(event_id, options={})\n response = connection.get do |req|\n req.url \"events/#{event_id}\", options\n end\n return_error_or_body(response, response.body.response.event)\n end", "language": "ruby", "code": "def event(event_id, options={})\n response = connection.get do |req|\n req.url \"events/#{event_id}\", options\n end\n return_error_or_body(response, response.body.response.event)\n end", "code_tokens": ["def", "event", "(", "event_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"events/#{event_id}\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "event", ")", "end"], "docstring": "Retrieve information about an event\n\n param [String] event_id The ID of the event", "docstring_tokens": ["Retrieve", "information", "about", "an", "event"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/events.rb#L8-L13", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/campaigns.rb", "func_name": "Foursquare2.Campaigns.campaign", "original_string": "def campaign(campaign_id, options={})\n response = connection.get do |req|\n req.url \"campaigns/#{campaign_id}\", options\n end\n return_error_or_body(response, response.body.response.campaign)\n end", "language": "ruby", "code": "def campaign(campaign_id, options={})\n response = connection.get do |req|\n req.url \"campaigns/#{campaign_id}\", options\n end\n return_error_or_body(response, response.body.response.campaign)\n end", "code_tokens": ["def", "campaign", "(", "campaign_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"campaigns/#{campaign_id}\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "campaign", ")", "end"], "docstring": "Retrieve information about a campaign\n\n param [String] campaign_id The ID of the venue", "docstring_tokens": ["Retrieve", "information", "about", "a", "campaign"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/campaigns.rb#L7-L12", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/client.rb", "func_name": "Foursquare2.Client.connection", "original_string": "def connection\n params = {}\n params[:client_id] = @client_id if @client_id\n params[:client_secret] = @client_secret if @client_secret\n params[:oauth_token] = @oauth_token if @oauth_token\n params[:v] = @api_version if @api_version\n params[:locale] = @locale if @locale\n @connection ||= Faraday::Connection.new(:url => api_url, :ssl => @ssl, :params => params, :headers => default_headers) do |builder|\n @connection_middleware.each do |middleware|\n builder.use *middleware\n end\n builder.adapter Faraday.default_adapter\n end\n end", "language": "ruby", "code": "def connection\n params = {}\n params[:client_id] = @client_id if @client_id\n params[:client_secret] = @client_secret if @client_secret\n params[:oauth_token] = @oauth_token if @oauth_token\n params[:v] = @api_version if @api_version\n params[:locale] = @locale if @locale\n @connection ||= Faraday::Connection.new(:url => api_url, :ssl => @ssl, :params => params, :headers => default_headers) do |builder|\n @connection_middleware.each do |middleware|\n builder.use *middleware\n end\n builder.adapter Faraday.default_adapter\n end\n end", "code_tokens": ["def", "connection", "params", "=", "{", "}", "params", "[", ":client_id", "]", "=", "@client_id", "if", "@client_id", "params", "[", ":client_secret", "]", "=", "@client_secret", "if", "@client_secret", "params", "[", ":oauth_token", "]", "=", "@oauth_token", "if", "@oauth_token", "params", "[", ":v", "]", "=", "@api_version", "if", "@api_version", "params", "[", ":locale", "]", "=", "@locale", "if", "@locale", "@connection", "||=", "Faraday", "::", "Connection", ".", "new", "(", ":url", "=>", "api_url", ",", ":ssl", "=>", "@ssl", ",", ":params", "=>", "params", ",", ":headers", "=>", "default_headers", ")", "do", "|", "builder", "|", "@connection_middleware", ".", "each", "do", "|", "middleware", "|", "builder", ".", "use", "middleware", "end", "builder", ".", "adapter", "Faraday", ".", "default_adapter", "end", "end"], "docstring": "Sets up the connection to be used for all requests based on options passed during initialization.", "docstring_tokens": ["Sets", "up", "the", "connection", "to", "be", "used", "for", "all", "requests", "based", "on", "options", "passed", "during", "initialization", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/client.rb#L58-L71", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/client.rb", "func_name": "Foursquare2.Client.return_error_or_body", "original_string": "def return_error_or_body(response, response_body)\n if response.body['meta'].code == 200\n response_body\n else\n raise Foursquare2::APIError.new(response.body['meta'], response.body['response'])\n end\n end", "language": "ruby", "code": "def return_error_or_body(response, response_body)\n if response.body['meta'].code == 200\n response_body\n else\n raise Foursquare2::APIError.new(response.body['meta'], response.body['response'])\n end\n end", "code_tokens": ["def", "return_error_or_body", "(", "response", ",", "response_body", ")", "if", "response", ".", "body", "[", "'meta'", "]", ".", "code", "==", "200", "response_body", "else", "raise", "Foursquare2", "::", "APIError", ".", "new", "(", "response", ".", "body", "[", "'meta'", "]", ",", "response", ".", "body", "[", "'response'", "]", ")", "end", "end"], "docstring": "Helper method to return errors or desired response data as appropriate.\n\n Added just for convenience to avoid having to traverse farther down the response just to get to returned data.", "docstring_tokens": ["Helper", "method", "to", "return", "errors", "or", "desired", "response", "data", "as", "appropriate", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/client.rb#L83-L89", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/checkins.rb", "func_name": "Foursquare2.Checkins.checkin", "original_string": "def checkin(checkin_id, options={})\n response = connection.get do |req|\n req.url \"checkins/#{checkin_id}\", options\n end\n return_error_or_body(response, response.body.response.checkin)\n end", "language": "ruby", "code": "def checkin(checkin_id, options={})\n response = connection.get do |req|\n req.url \"checkins/#{checkin_id}\", options\n end\n return_error_or_body(response, response.body.response.checkin)\n end", "code_tokens": ["def", "checkin", "(", "checkin_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"checkins/#{checkin_id}\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "checkin", ")", "end"], "docstring": "Retrive information about a single checkin.\n\n @param [String] checkin_id the ID of the checkin.\n @param [Hash] options\n @option options String :signature - Signature allowing users to bypass the friends-only access check on checkins", "docstring_tokens": ["Retrive", "information", "about", "a", "single", "checkin", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/checkins.rb#L10-L15", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/checkins.rb", "func_name": "Foursquare2.Checkins.recent_checkins", "original_string": "def recent_checkins(options={})\n response = connection.get do |req|\n req.url \"checkins/recent\", options\n end\n return_error_or_body(response, response.body.response.recent)\n end", "language": "ruby", "code": "def recent_checkins(options={})\n response = connection.get do |req|\n req.url \"checkins/recent\", options\n end\n return_error_or_body(response, response.body.response.recent)\n end", "code_tokens": ["def", "recent_checkins", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"checkins/recent\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "recent", ")", "end"], "docstring": "Retrive a list of recent checkins from friends.\n\n @param [Hash] options\n @option options String :ll - Latitude and longitude in format LAT,LON\n @option options String :limit - Maximum results to return (max 100)\n @option options Integer :afterTimestamp - Seconds after which to look for checkins", "docstring_tokens": ["Retrive", "a", "list", "of", "recent", "checkins", "from", "friends", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/checkins.rb#L24-L29", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/checkins.rb", "func_name": "Foursquare2.Checkins.add_checkin", "original_string": "def add_checkin(options={})\n response = connection.post do |req|\n req.url \"checkins/add\", options\n end\n return_error_or_body(response, response.body.response.checkin)\n end", "language": "ruby", "code": "def add_checkin(options={})\n response = connection.post do |req|\n req.url \"checkins/add\", options\n end\n return_error_or_body(response, response.body.response.checkin)\n end", "code_tokens": ["def", "add_checkin", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"checkins/add\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "checkin", ")", "end"], "docstring": "Checkin on behalf of the user.\n\n @param [Hash] options\n @option options String :venueId - Venue for the checkin.\n @option options String :venue - For venueless checkins (name or other identifier)\n @option options String :shout - Message to be included with the checkin.\n @option options String :broadcast - Required, one or more of private,public,facebook,twitter. Comma-separated.\n @option options String :ll - Latitude and longitude in format LAT,LON\n @option options Integer :llAcc - Accuracy of the lat/lon in meters.\n @option options Integer :alt - Altitude in meters\n @option options Integer :altAcc - Accuracy of the altitude in meters", "docstring_tokens": ["Checkin", "on", "behalf", "of", "the", "user", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/checkins.rb#L43-L48", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/checkins.rb", "func_name": "Foursquare2.Checkins.add_checkin_comment", "original_string": "def add_checkin_comment(checkin_id, options={})\n response = connection.post do |req|\n req.url \"checkins/#{checkin_id}/addcomment\", options\n end\n return_error_or_body(response, response.body.response) \n end", "language": "ruby", "code": "def add_checkin_comment(checkin_id, options={})\n response = connection.post do |req|\n req.url \"checkins/#{checkin_id}/addcomment\", options\n end\n return_error_or_body(response, response.body.response) \n end", "code_tokens": ["def", "add_checkin_comment", "(", "checkin_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"checkins/#{checkin_id}/addcomment\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ")", "end"], "docstring": "Add a comment to a checkin.\n\n @param [String] checkin_id the ID of the checkin.\n @param [Hash] options\n @option options String :text - Text of the comment to add, 200 character max.", "docstring_tokens": ["Add", "a", "comment", "to", "a", "checkin", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/checkins.rb#L56-L61", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/checkins.rb", "func_name": "Foursquare2.Checkins.add_checkin_reply", "original_string": "def add_checkin_reply(checkin_id, options={})\n response = connection.post do |req|\n req.url \"checkins/#{checkin_id}/reply\", options\n end\n return_error_or_body(response, response.body.response.reply) \n end", "language": "ruby", "code": "def add_checkin_reply(checkin_id, options={})\n response = connection.post do |req|\n req.url \"checkins/#{checkin_id}/reply\", options\n end\n return_error_or_body(response, response.body.response.reply) \n end", "code_tokens": ["def", "add_checkin_reply", "(", "checkin_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"checkins/#{checkin_id}/reply\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "reply", ")", "end"], "docstring": "Add a reply to a checkin.\n\n @param [String] checkin_id the ID of the checkin.\n @param [Hash] options\n @option options String :text - The text of the post, up to 200 characters.\n @option options String :url - Link for more details. This page will be opened in an embedded web view in the foursquare application, unless contentId is specified and a native link handler is registered and present. We support the following URL schemes: http, https, foursquare, mailto, tel, and sms.\n @option options String :contentId - Identifier for the post to be used in a native link, up to 50 characters. A url must also be specified in the request.", "docstring_tokens": ["Add", "a", "reply", "to", "a", "checkin", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/checkins.rb#L99-L104", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/venuegroups.rb", "func_name": "Foursquare2.Venuegroups.venuegroup", "original_string": "def venuegroup(group_id, options={})\n response = connection.get do |req|\n req.url \"venuegroups/#{group_id}\", options\n end\n return_error_or_body(response, response.body.response.venueGroup)\n end", "language": "ruby", "code": "def venuegroup(group_id, options={})\n response = connection.get do |req|\n req.url \"venuegroups/#{group_id}\", options\n end\n return_error_or_body(response, response.body.response.venueGroup)\n end", "code_tokens": ["def", "venuegroup", "(", "group_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"venuegroups/#{group_id}\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "venueGroup", ")", "end"], "docstring": "Retrieve information about a venuegroup\n\n param [String] group_id The ID of the venuegroup", "docstring_tokens": ["Retrieve", "information", "about", "a", "venuegroup"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/venuegroups.rb#L8-L13", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/venuegroups.rb", "func_name": "Foursquare2.Venuegroups.add_venuegroup", "original_string": "def add_venuegroup(options={})\n response = connection.post do |req|\n req.url \"venuegroups/add\", options\n end\n return_error_or_body(response, response.body.response.venueGroup)\n end", "language": "ruby", "code": "def add_venuegroup(options={})\n response = connection.post do |req|\n req.url \"venuegroups/add\", options\n end\n return_error_or_body(response, response.body.response.venueGroup)\n end", "code_tokens": ["def", "add_venuegroup", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"venuegroups/add\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "venueGroup", ")", "end"], "docstring": "Create a venue group. If the venueId parameter is specified,\n then the endpoint will add the specified venues to the venue group.\n If it is not possible to add all of the specified venues to the group,\n then creation of the venue group will fail entirely.\n @param [Hash] options\n @option options String :name - Required. The name to give the group.\n @option options String :venueId - Comma-delimited list of venue IDs to add to the group. If this parameter is not specified, then the venue group will initially be empty.", "docstring_tokens": ["Create", "a", "venue", "group", ".", "If", "the", "venueId", "parameter", "is", "specified", "then", "the", "endpoint", "will", "add", "the", "specified", "venues", "to", "the", "venue", "group", ".", "If", "it", "is", "not", "possible", "to", "add", "all", "of", "the", "specified", "venues", "to", "the", "group", "then", "creation", "of", "the", "venue", "group", "will", "fail", "entirely", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/venuegroups.rb#L23-L28", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/venuegroups.rb", "func_name": "Foursquare2.Venuegroups.venuegroup_update", "original_string": "def venuegroup_update(group_id, options={})\n response = connection.post do |req|\n req.url \"venuegroups/#{group_id}/update\", options\n end\n return_error_or_body(response, response.body.response.venueGroup)\n end", "language": "ruby", "code": "def venuegroup_update(group_id, options={})\n response = connection.post do |req|\n req.url \"venuegroups/#{group_id}/update\", options\n end\n return_error_or_body(response, response.body.response.venueGroup)\n end", "code_tokens": ["def", "venuegroup_update", "(", "group_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"venuegroups/#{group_id}/update\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "venueGroup", ")", "end"], "docstring": "Updates a venue group. At least one of the name and venueId parameters must be specified.\n @param [String] group_id - required The ID of the venue group to modify\n @param [Hash] options\n @option options String :name - If specified, the new name to give to the group.\n @option options String :venueId - If specified, a comma-delimited list of venue IDs that will become the new set of venue IDs for the group.", "docstring_tokens": ["Updates", "a", "venue", "group", ".", "At", "least", "one", "of", "the", "name", "and", "venueId", "parameters", "must", "be", "specified", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/venuegroups.rb#L37-L42", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/venuegroups.rb", "func_name": "Foursquare2.Venuegroups.list_venuegroup", "original_string": "def list_venuegroup(options={})\n response = connection.get do |req|\n req.url \"venuegroups/list\", options\n end\n return_error_or_body(response, response.body.response.venueGroups)\n end", "language": "ruby", "code": "def list_venuegroup(options={})\n response = connection.get do |req|\n req.url \"venuegroups/list\", options\n end\n return_error_or_body(response, response.body.response.venueGroups)\n end", "code_tokens": ["def", "list_venuegroup", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"venuegroups/list\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "venueGroups", ")", "end"], "docstring": "List all venue groups owned by the user.", "docstring_tokens": ["List", "all", "venue", "groups", "owned", "by", "the", "user", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/venuegroups.rb#L46-L51", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/specials.rb", "func_name": "Foursquare2.Specials.special", "original_string": "def special(special_id, options={})\n response = connection.get do |req|\n req.url \"specials/#{special_id}\", options\n end\n return_error_or_body(response, response.body.response.special)\n end", "language": "ruby", "code": "def special(special_id, options={})\n response = connection.get do |req|\n req.url \"specials/#{special_id}\", options\n end\n return_error_or_body(response, response.body.response.special)\n end", "code_tokens": ["def", "special", "(", "special_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"specials/#{special_id}\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "special", ")", "end"], "docstring": "Retrieve information about a special\n\n param [String] special_id The ID of the special", "docstring_tokens": ["Retrieve", "information", "about", "a", "special"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/specials.rb#L8-L13", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/specials.rb", "func_name": "Foursquare2.Specials.search_specials", "original_string": "def search_specials(options={})\n response = connection.get do |req|\n req.url \"specials/search\", options\n end\n return_error_or_body(response, response.body.response.specials.items)\n end", "language": "ruby", "code": "def search_specials(options={})\n response = connection.get do |req|\n req.url \"specials/search\", options\n end\n return_error_or_body(response, response.body.response.specials.items)\n end", "code_tokens": ["def", "search_specials", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"specials/search\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "specials", ".", "items", ")", "end"], "docstring": "Search for specials\n\n @param [Hash] options\n @option options String :ll - Latitude and longitude in format LAT,LON\n @option options Integer :llAcc - Accuracy of the lat/lon in meters.\n @option options Integer :alt - Altitude in meters\n @option options Integer :altAcc - Accuracy of the altitude in meters\n @option options Integer :limit - The limit of results to return.", "docstring_tokens": ["Search", "for", "specials"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/specials.rb#L24-L29", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/lists.rb", "func_name": "Foursquare2.Lists.list", "original_string": "def list(list_id, options={})\n response = connection.get do |req|\n req.url \"lists/#{list_id}\", options\n end\n return_error_or_body(response, response.body.response.list)\n end", "language": "ruby", "code": "def list(list_id, options={})\n response = connection.get do |req|\n req.url \"lists/#{list_id}\", options\n end\n return_error_or_body(response, response.body.response.list)\n end", "code_tokens": ["def", "list", "(", "list_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"lists/#{list_id}\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "list", ")", "end"], "docstring": "Retrieve information about a list.\n\n @param [String] list_id - The id of the list to retrieve.\n @param [Hash] options\n @option options Integer :limit - Number of results to return, up to 200.\n @option options Integer :offset - The number of results to skip. Used to page through results.", "docstring_tokens": ["Retrieve", "information", "about", "a", "list", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/lists.rb#L11-L16", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/venues.rb", "func_name": "Foursquare2.Venues.trending_venues", "original_string": "def trending_venues(ll, options={})\n options[:ll] = ll\n response = connection.get do |req|\n req.url \"venues/trending\", options\n end\n return_error_or_body(response, response.body.response)\n end", "language": "ruby", "code": "def trending_venues(ll, options={})\n options[:ll] = ll\n response = connection.get do |req|\n req.url \"venues/trending\", options\n end\n return_error_or_body(response, response.body.response)\n end", "code_tokens": ["def", "trending_venues", "(", "ll", ",", "options", "=", "{", "}", ")", "options", "[", ":ll", "]", "=", "ll", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"venues/trending\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ")", "end"], "docstring": "Search for trending venues\n\n @param [String] :ll Latitude and longitude in format LAT,LON\n @param [Hash] options\n @option options Integer :limit - Number of results to return, up to 50.\n @option options Integer :radius - Radius in meters, up to approximately 2000 meters.", "docstring_tokens": ["Search", "for", "trending", "venues"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/venues.rb#L40-L46", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/venues.rb", "func_name": "Foursquare2.Venues.search_venues_by_tip", "original_string": "def search_venues_by_tip(options={})\n tips = search_tips(options)\n venues = []\n tips.each do |tip|\n venues << tip['venue']\n end\n venues\n end", "language": "ruby", "code": "def search_venues_by_tip(options={})\n tips = search_tips(options)\n venues = []\n tips.each do |tip|\n venues << tip['venue']\n end\n venues\n end", "code_tokens": ["def", "search_venues_by_tip", "(", "options", "=", "{", "}", ")", "tips", "=", "search_tips", "(", "options", ")", "venues", "=", "[", "]", "tips", ".", "each", "do", "|", "tip", "|", "venues", "<<", "tip", "[", "'venue'", "]", "end", "venues", "end"], "docstring": "Search for venues by tip\n\n @param [Hash] options\n @option options String :ll - Latitude and longitude in format LAT,LON\n @option options Integer :limit - The limit of results to return.\n @option options Integer :offset - Used to page through results.\n @option options String :filter - Set to 'friends' to limit tips to those from friends.\n @option options String :query - Only find tips matching this term.", "docstring_tokens": ["Search", "for", "venues", "by", "tip"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/venues.rb#L57-L64", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/venues.rb", "func_name": "Foursquare2.Venues.venue_categories", "original_string": "def venue_categories(options={})\n response = connection.get do |req|\n req.url \"venues/categories\", options\n end\n return_error_or_body(response, response.body.response.categories)\n end", "language": "ruby", "code": "def venue_categories(options={})\n response = connection.get do |req|\n req.url \"venues/categories\", options\n end\n return_error_or_body(response, response.body.response.categories)\n end", "code_tokens": ["def", "venue_categories", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"venues/categories\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "categories", ")", "end"], "docstring": "Retrieve information about all venue categories.", "docstring_tokens": ["Retrieve", "information", "about", "all", "venue", "categories", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/venues.rb#L68-L73", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/venues.rb", "func_name": "Foursquare2.Venues.venue_links", "original_string": "def venue_links(venue_id, options={})\n response = connection.get do |req|\n req.url \"venues/#{venue_id}/links\", options\n end\n return_error_or_body(response, response.body.response.links)\n end", "language": "ruby", "code": "def venue_links(venue_id, options={})\n response = connection.get do |req|\n req.url \"venues/#{venue_id}/links\", options\n end\n return_error_or_body(response, response.body.response.links)\n end", "code_tokens": ["def", "venue_links", "(", "venue_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"venues/#{venue_id}/links\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "links", ")", "end"], "docstring": "Retrieve links for a venue.\n\n param [String] venue_id The ID of the venue", "docstring_tokens": ["Retrieve", "links", "for", "a", "venue", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/venues.rb#L79-L84", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/venues.rb", "func_name": "Foursquare2.Venues.add_venue", "original_string": "def add_venue(options={})\n response = connection.post do |req|\n req.url \"venues/add\", options\n end\n return_error_or_body(response, response.body.response.venue)\n end", "language": "ruby", "code": "def add_venue(options={})\n response = connection.post do |req|\n req.url \"venues/add\", options\n end\n return_error_or_body(response, response.body.response.venue)\n end", "code_tokens": ["def", "add_venue", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"venues/add\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "venue", ")", "end"], "docstring": "Add a venue\n @param [Hash] options\n @option options String :name - Name of the venue (required)\n @option options String :address\n @option options String :crossStreet\n @option options String :city\n @option options String :state\n @option options String :zip\n @option options String :phone\n @option options String :ll - Latitude and longitude in format LAT,LON\n @option options String :primaryCategoryId - Main category for the venue, must be in the list of venue categories.", "docstring_tokens": ["Add", "a", "venue"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/venues.rb#L98-L103", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/venues.rb", "func_name": "Foursquare2.Venues.mark_venue_todo", "original_string": "def mark_venue_todo(venue_id, options={})\n response = connection.post do |req|\n req.url \"venues/#{venue_id}/marktodo\", options\n end\n return_error_or_body(response, response.body.response)\n end", "language": "ruby", "code": "def mark_venue_todo(venue_id, options={})\n response = connection.post do |req|\n req.url \"venues/#{venue_id}/marktodo\", options\n end\n return_error_or_body(response, response.body.response)\n end", "code_tokens": ["def", "mark_venue_todo", "(", "venue_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"venues/#{venue_id}/marktodo\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ")", "end"], "docstring": "Mark a venue as todo for the authenticated user\n\n @param [String] venue_id - Venue id to mark todo, required.\n @param [Hash] options\n @option options String :text - Text for the tip/todo", "docstring_tokens": ["Mark", "a", "venue", "as", "todo", "for", "the", "authenticated", "user"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/venues.rb#L111-L116", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/venues.rb", "func_name": "Foursquare2.Venues.suggest_completion_venues", "original_string": "def suggest_completion_venues(options={})\n response = connection.get do |req|\n req.url \"venues/suggestCompletion\", options\n end\n return_error_or_body(response, response.body.response)\n end", "language": "ruby", "code": "def suggest_completion_venues(options={})\n response = connection.get do |req|\n req.url \"venues/suggestCompletion\", options\n end\n return_error_or_body(response, response.body.response)\n end", "code_tokens": ["def", "suggest_completion_venues", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"venues/suggestCompletion\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ")", "end"], "docstring": "Suggest venue completions. Returns a list of mini-venues partially matching the search term, near the location.\n\n @param [Hash] options\n @option options String :ll - Latitude and longitude in format LAT,LON\n @option options Integer :llAcc - Accuracy of the lat/lon in meters.\n @option options Integer :alt - Altitude in meters\n @option options Integer :altAcc - Accuracy of the altitude in meters\n @option options String :query - Query to match venues on.\n @option options Integer :limit - The limit of results to return.", "docstring_tokens": ["Suggest", "venue", "completions", ".", "Returns", "a", "list", "of", "mini", "-", "venues", "partially", "matching", "the", "search", "term", "near", "the", "location", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/venues.rb#L208-L213", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/venues.rb", "func_name": "Foursquare2.Venues.venue_menus", "original_string": "def venue_menus(venue_id, options={})\n response = connection.get do |req|\n req.url \"venues/#{venue_id}/menu\", options\n end\n return_error_or_body(response, response.body.response)\n end", "language": "ruby", "code": "def venue_menus(venue_id, options={})\n response = connection.get do |req|\n req.url \"venues/#{venue_id}/menu\", options\n end\n return_error_or_body(response, response.body.response)\n end", "code_tokens": ["def", "venue_menus", "(", "venue_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"venues/#{venue_id}/menu\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ")", "end"], "docstring": "Retrieve menus for a venue.\n\n param [String] venue_id The ID of the venue", "docstring_tokens": ["Retrieve", "menus", "for", "a", "venue", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/venues.rb#L219-L224", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/venues.rb", "func_name": "Foursquare2.Venues.venues_timeseries", "original_string": "def venues_timeseries(options={})\n options[:venueId] = options[:venueId].join(',') # Transforms the array into a 'comma-separated list' of ids.\n response = connection.get do |req|\n req.url \"venues/timeseries\", options\n end\n return_error_or_body(response, response.body.response)\n end", "language": "ruby", "code": "def venues_timeseries(options={})\n options[:venueId] = options[:venueId].join(',') # Transforms the array into a 'comma-separated list' of ids.\n response = connection.get do |req|\n req.url \"venues/timeseries\", options\n end\n return_error_or_body(response, response.body.response)\n end", "code_tokens": ["def", "venues_timeseries", "(", "options", "=", "{", "}", ")", "options", "[", ":venueId", "]", "=", "options", "[", ":venueId", "]", ".", "join", "(", "','", ")", "# Transforms the array into a 'comma-separated list' of ids.", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"venues/timeseries\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ")", "end"], "docstring": "Get daily venue stats for a list of venues over a time range.\n Client instance should represent an OAuth user who is the venues owner.\n\n @param [Hash] options\n @option options Array[String] :venueId - A list of venue ids to retrieve series data for.\n @option options Integer :startAt - Required. The start of the time range to retrieve stats for (seconds since epoch).\n @option options Integer :endAt - The end of the time range to retrieve stats for (seconds since epoch). If omitted, the current time is assumed.\n @option options String :fields - Specifies which fields to return. May be one or more of totalCheckins, newCheckins, uniqueVisitors, sharing, genders, ages, hours, separated by commas.", "docstring_tokens": ["Get", "daily", "venue", "stats", "for", "a", "list", "of", "venues", "over", "a", "time", "range", ".", "Client", "instance", "should", "represent", "an", "OAuth", "user", "who", "is", "the", "venues", "owner", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/venues.rb#L276-L282", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/settings.rb", "func_name": "Foursquare2.Settings.update_setting", "original_string": "def update_setting(setting, value, options={})\n response = connection.post do |req|\n req.url \"settings/#{setting}/set\", {:value => value}.merge(options)\n end\n return_error_or_body(response, response.body.response)\n end", "language": "ruby", "code": "def update_setting(setting, value, options={})\n response = connection.post do |req|\n req.url \"settings/#{setting}/set\", {:value => value}.merge(options)\n end\n return_error_or_body(response, response.body.response)\n end", "code_tokens": ["def", "update_setting", "(", "setting", ",", "value", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"settings/#{setting}/set\"", ",", "{", ":value", "=>", "value", "}", ".", "merge", "(", "options", ")", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ")", "end"], "docstring": "Update a single setting for the authenticated user.\n\n @param [String] setting - The name of the setting to update, one of sendtotwitter, sendtofacebook, pings.\n @param [String] value - One of '1','0'", "docstring_tokens": ["Update", "a", "single", "setting", "for", "the", "authenticated", "user", "."], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/settings.rb#L29-L34", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/photos.rb", "func_name": "Foursquare2.Photos.photo", "original_string": "def photo(photo_id, options={})\n response = connection.get do |req|\n req.url \"photos/#{photo_id}\", options\n end\n return_error_or_body(response, response.body.response.photo)\n end", "language": "ruby", "code": "def photo(photo_id, options={})\n response = connection.get do |req|\n req.url \"photos/#{photo_id}\", options\n end\n return_error_or_body(response, response.body.response.photo)\n end", "code_tokens": ["def", "photo", "(", "photo_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"photos/#{photo_id}\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "photo", ")", "end"], "docstring": "Retrieve a photo\n\n @params [String] photo_id - The ID of the photo", "docstring_tokens": ["Retrieve", "a", "photo"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/photos.rb#L8-L13", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/photos.rb", "func_name": "Foursquare2.Photos.add_photo", "original_string": "def add_photo(options={})\n response = connection.post('photos/add', options)\n return_error_or_body(response, response.body.response.photo)\n end", "language": "ruby", "code": "def add_photo(options={})\n response = connection.post('photos/add', options)\n return_error_or_body(response, response.body.response.photo)\n end", "code_tokens": ["def", "add_photo", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "(", "'photos/add'", ",", "options", ")", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "photo", ")", "end"], "docstring": "Add a photo\n\n @param [Hash] options\n @option options UploadIO :photo - the photo. Like Faraday::UploadIO.new('pic_path', 'image/jpeg')\n @option options String :checkinId - the ID of a checkin owned by the user\n @option options String :tipId - the ID of a tip owned by the user\n @option options String :venueId - the ID of a venue\n @option options String :broadcast - Required, one or more of private,public,facebook,twitter. Comma-separated.\n @option options String :ll - Latitude and longitude in format LAT,LON\n @option options Integer :llAcc - Accuracy of the lat/lon in meters.\n @option options Integer :alt - Altitude in meters\n @option options Integer :altAcc - Accuracy of the altitude in meters", "docstring_tokens": ["Add", "a", "photo"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/photos.rb#L27-L30", "partition": "valid"} {"repo": "mattmueller/foursquare2", "path": "lib/foursquare2/photos.rb", "func_name": "Foursquare2.Photos.venue_photos", "original_string": "def venue_photos(venue_id, options = {:group => 'venue'})\n response = connection.get do |req|\n req.url \"venues/#{venue_id}/photos\", options\n end\n return_error_or_body(response, response.body.response.photos)\n end", "language": "ruby", "code": "def venue_photos(venue_id, options = {:group => 'venue'})\n response = connection.get do |req|\n req.url \"venues/#{venue_id}/photos\", options\n end\n return_error_or_body(response, response.body.response.photos)\n end", "code_tokens": ["def", "venue_photos", "(", "venue_id", ",", "options", "=", "{", ":group", "=>", "'venue'", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"venues/#{venue_id}/photos\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ".", "response", ".", "photos", ")", "end"], "docstring": "Retrieve photos for a venue\n\n @params [String] venue_id - The ID of the venue\n @param [Hash] options\n @option options String :group - Pass checkin for photos added by friends (including on their recent checkins). Pass venue for public photos added to the venue by non-friends. Use multi to fetch both. Default - venue\n @option options Integer :limit - Number of results to return, up to 500.\n @option options Integer :offset - Used to page through results.", "docstring_tokens": ["Retrieve", "photos", "for", "a", "venue"], "sha": "0affc7d4bd5a3aea51e16782def38f589d16e60a", "url": "https://github.com/mattmueller/foursquare2/blob/0affc7d4bd5a3aea51e16782def38f589d16e60a/lib/foursquare2/photos.rb#L39-L44", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/associations/collection_proxy.rb", "func_name": "Parse.CollectionProxy.forward", "original_string": "def forward(method, params = nil)\n return unless @delegate && @delegate.respond_to?(method)\n params.nil? ? @delegate.send(method) : @delegate.send(method, params)\n end", "language": "ruby", "code": "def forward(method, params = nil)\n return unless @delegate && @delegate.respond_to?(method)\n params.nil? ? @delegate.send(method) : @delegate.send(method, params)\n end", "code_tokens": ["def", "forward", "(", "method", ",", "params", "=", "nil", ")", "return", "unless", "@delegate", "&&", "@delegate", ".", "respond_to?", "(", "method", ")", "params", ".", "nil?", "?", "@delegate", ".", "send", "(", "method", ")", ":", "@delegate", ".", "send", "(", "method", ",", "params", ")", "end"], "docstring": "Forward a method call to the delegate.\n @param method [Symbol] the name of the method to forward\n @param params [Object] method parameters\n @return [Object] the return value from the forwarded method.", "docstring_tokens": ["Forward", "a", "method", "call", "to", "the", "delegate", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/associations/collection_proxy.rb#L78-L81", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/associations/collection_proxy.rb", "func_name": "Parse.CollectionProxy.add", "original_string": "def add(*items)\n notify_will_change! if items.count > 0\n items.each do |item|\n collection.push item\n end\n @collection\n end", "language": "ruby", "code": "def add(*items)\n notify_will_change! if items.count > 0\n items.each do |item|\n collection.push item\n end\n @collection\n end", "code_tokens": ["def", "add", "(", "*", "items", ")", "notify_will_change!", "if", "items", ".", "count", ">", "0", "items", ".", "each", "do", "|", "item", "|", "collection", ".", "push", "item", "end", "@collection", "end"], "docstring": "Add items to the collection\n @param items [Array] items to add", "docstring_tokens": ["Add", "items", "to", "the", "collection"], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/associations/collection_proxy.rb#L143-L149", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/associations/collection_proxy.rb", "func_name": "Parse.CollectionProxy.<<", "original_string": "def <<(*list)\n if list.count > 0\n notify_will_change!\n list.flatten.each { |e| collection.push(e) }\n end\n end", "language": "ruby", "code": "def <<(*list)\n if list.count > 0\n notify_will_change!\n list.flatten.each { |e| collection.push(e) }\n end\n end", "code_tokens": ["def", "<<", "(", "*", "list", ")", "if", "list", ".", "count", ">", "0", "notify_will_change!", "list", ".", "flatten", ".", "each", "{", "|", "e", "|", "collection", ".", "push", "(", "e", ")", "}", "end", "end"], "docstring": "Append items to the collection", "docstring_tokens": ["Append", "items", "to", "the", "collection"], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/associations/collection_proxy.rb#L314-L319", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/core/properties.rb", "func_name": "Parse.Properties.format_value", "original_string": "def format_value(key, val, data_type = nil)\n # if data_type wasn't passed, then get the data_type from the fields hash\n data_type ||= self.fields[key]\n\n val = format_operation(key, val, data_type)\n\n case data_type\n when :object\n val = val.with_indifferent_access if val.is_a?(Hash)\n when :array\n # All \"array\" types use a collection proxy\n val = val.to_a if val.is_a?(Parse::CollectionProxy) #all objects must be in array form\n val = [val] unless val.is_a?(Array) #all objects must be in array form\n val.compact! #remove any nil\n val = Parse::CollectionProxy.new val, delegate: self, key: key\n when :geopoint\n val = Parse::GeoPoint.new(val) unless val.blank?\n when :file\n val = Parse::File.new(val) unless val.blank?\n when :bytes\n val = Parse::Bytes.new(val) unless val.blank?\n when :integer\n if val.nil? || val.respond_to?(:to_i) == false\n val = nil\n else\n val = val.to_i\n end\n when :boolean\n if val.nil?\n val = nil\n else\n val = val ? true : false\n end\n when :string\n val = val.to_s unless val.blank?\n when :float\n val = val.to_f unless val.blank?\n when :acl\n # ACL types go through a special conversion\n val = ACL.typecast(val, self)\n when :date\n # if it respond to parse_date, then use that as the conversion.\n if val.respond_to?(:parse_date) && val.is_a?(Parse::Date) == false\n val = val.parse_date\n # if the value is a hash, then it may be the Parse hash format for an iso date.\n elsif val.is_a?(Hash) # val.respond_to?(:iso8601)\n val = Parse::Date.parse(val[\"iso\"] || val[:iso])\n elsif val.is_a?(String)\n # if it's a string, try parsing the date\n val = Parse::Date.parse val\n #elsif val.present?\n # pus \"[Parse::Stack] Invalid date value '#{val}' assigned to #{self.class}##{key}, it should be a Parse::Date or DateTime.\"\n # raise ValueError, \"Invalid date value '#{val}' assigned to #{self.class}##{key}, it should be a Parse::Date or DateTime.\"\n end\n when :timezone\n val = Parse::TimeZone.new(val) if val.present?\n else\n # You can provide a specific class instead of a symbol format\n if data_type.respond_to?(:typecast)\n val = data_type.typecast(val)\n else\n warn \"Property :#{key}: :#{data_type} has no valid data type\"\n val = val #default\n end\n end\n val\n end", "language": "ruby", "code": "def format_value(key, val, data_type = nil)\n # if data_type wasn't passed, then get the data_type from the fields hash\n data_type ||= self.fields[key]\n\n val = format_operation(key, val, data_type)\n\n case data_type\n when :object\n val = val.with_indifferent_access if val.is_a?(Hash)\n when :array\n # All \"array\" types use a collection proxy\n val = val.to_a if val.is_a?(Parse::CollectionProxy) #all objects must be in array form\n val = [val] unless val.is_a?(Array) #all objects must be in array form\n val.compact! #remove any nil\n val = Parse::CollectionProxy.new val, delegate: self, key: key\n when :geopoint\n val = Parse::GeoPoint.new(val) unless val.blank?\n when :file\n val = Parse::File.new(val) unless val.blank?\n when :bytes\n val = Parse::Bytes.new(val) unless val.blank?\n when :integer\n if val.nil? || val.respond_to?(:to_i) == false\n val = nil\n else\n val = val.to_i\n end\n when :boolean\n if val.nil?\n val = nil\n else\n val = val ? true : false\n end\n when :string\n val = val.to_s unless val.blank?\n when :float\n val = val.to_f unless val.blank?\n when :acl\n # ACL types go through a special conversion\n val = ACL.typecast(val, self)\n when :date\n # if it respond to parse_date, then use that as the conversion.\n if val.respond_to?(:parse_date) && val.is_a?(Parse::Date) == false\n val = val.parse_date\n # if the value is a hash, then it may be the Parse hash format for an iso date.\n elsif val.is_a?(Hash) # val.respond_to?(:iso8601)\n val = Parse::Date.parse(val[\"iso\"] || val[:iso])\n elsif val.is_a?(String)\n # if it's a string, try parsing the date\n val = Parse::Date.parse val\n #elsif val.present?\n # pus \"[Parse::Stack] Invalid date value '#{val}' assigned to #{self.class}##{key}, it should be a Parse::Date or DateTime.\"\n # raise ValueError, \"Invalid date value '#{val}' assigned to #{self.class}##{key}, it should be a Parse::Date or DateTime.\"\n end\n when :timezone\n val = Parse::TimeZone.new(val) if val.present?\n else\n # You can provide a specific class instead of a symbol format\n if data_type.respond_to?(:typecast)\n val = data_type.typecast(val)\n else\n warn \"Property :#{key}: :#{data_type} has no valid data type\"\n val = val #default\n end\n end\n val\n end", "code_tokens": ["def", "format_value", "(", "key", ",", "val", ",", "data_type", "=", "nil", ")", "# if data_type wasn't passed, then get the data_type from the fields hash", "data_type", "||=", "self", ".", "fields", "[", "key", "]", "val", "=", "format_operation", "(", "key", ",", "val", ",", "data_type", ")", "case", "data_type", "when", ":object", "val", "=", "val", ".", "with_indifferent_access", "if", "val", ".", "is_a?", "(", "Hash", ")", "when", ":array", "# All \"array\" types use a collection proxy", "val", "=", "val", ".", "to_a", "if", "val", ".", "is_a?", "(", "Parse", "::", "CollectionProxy", ")", "#all objects must be in array form", "val", "=", "[", "val", "]", "unless", "val", ".", "is_a?", "(", "Array", ")", "#all objects must be in array form", "val", ".", "compact!", "#remove any nil", "val", "=", "Parse", "::", "CollectionProxy", ".", "new", "val", ",", "delegate", ":", "self", ",", "key", ":", "key", "when", ":geopoint", "val", "=", "Parse", "::", "GeoPoint", ".", "new", "(", "val", ")", "unless", "val", ".", "blank?", "when", ":file", "val", "=", "Parse", "::", "File", ".", "new", "(", "val", ")", "unless", "val", ".", "blank?", "when", ":bytes", "val", "=", "Parse", "::", "Bytes", ".", "new", "(", "val", ")", "unless", "val", ".", "blank?", "when", ":integer", "if", "val", ".", "nil?", "||", "val", ".", "respond_to?", "(", ":to_i", ")", "==", "false", "val", "=", "nil", "else", "val", "=", "val", ".", "to_i", "end", "when", ":boolean", "if", "val", ".", "nil?", "val", "=", "nil", "else", "val", "=", "val", "?", "true", ":", "false", "end", "when", ":string", "val", "=", "val", ".", "to_s", "unless", "val", ".", "blank?", "when", ":float", "val", "=", "val", ".", "to_f", "unless", "val", ".", "blank?", "when", ":acl", "# ACL types go through a special conversion", "val", "=", "ACL", ".", "typecast", "(", "val", ",", "self", ")", "when", ":date", "# if it respond to parse_date, then use that as the conversion.", "if", "val", ".", "respond_to?", "(", ":parse_date", ")", "&&", "val", ".", "is_a?", "(", "Parse", "::", "Date", ")", "==", "false", "val", "=", "val", ".", "parse_date", "# if the value is a hash, then it may be the Parse hash format for an iso date.", "elsif", "val", ".", "is_a?", "(", "Hash", ")", "# val.respond_to?(:iso8601)", "val", "=", "Parse", "::", "Date", ".", "parse", "(", "val", "[", "\"iso\"", "]", "||", "val", "[", ":iso", "]", ")", "elsif", "val", ".", "is_a?", "(", "String", ")", "# if it's a string, try parsing the date", "val", "=", "Parse", "::", "Date", ".", "parse", "val", "#elsif val.present?", "# pus \"[Parse::Stack] Invalid date value '#{val}' assigned to #{self.class}##{key}, it should be a Parse::Date or DateTime.\"", "# raise ValueError, \"Invalid date value '#{val}' assigned to #{self.class}##{key}, it should be a Parse::Date or DateTime.\"", "end", "when", ":timezone", "val", "=", "Parse", "::", "TimeZone", ".", "new", "(", "val", ")", "if", "val", ".", "present?", "else", "# You can provide a specific class instead of a symbol format", "if", "data_type", ".", "respond_to?", "(", ":typecast", ")", "val", "=", "data_type", ".", "typecast", "(", "val", ")", "else", "warn", "\"Property :#{key}: :#{data_type} has no valid data type\"", "val", "=", "val", "#default", "end", "end", "val", "end"], "docstring": "this method takes an input value and transforms it to the proper local format\n depending on the data type that was set for a particular property key.\n Return the internal representation of a property value for a given data type.\n @param key [Symbol] the name of the property\n @param val [Object] the value to format.\n @param data_type [Symbol] provide a hint to the data_type of this value.\n @return [Object]", "docstring_tokens": ["this", "method", "takes", "an", "input", "value", "and", "transforms", "it", "to", "the", "proper", "local", "format", "depending", "on", "the", "data", "type", "that", "was", "set", "for", "a", "particular", "property", "key", ".", "Return", "the", "internal", "representation", "of", "a", "property", "value", "for", "a", "given", "data", "type", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/core/properties.rb#L549-L615", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/associations/relation_collection_proxy.rb", "func_name": "Parse.RelationCollectionProxy.all", "original_string": "def all(constraints = {})\n q = query( {limit: :max}.merge(constraints) )\n if block_given?\n # if we have a query, then use the Proc with it (more efficient)\n return q.present? ? q.results(&Proc.new) : collection.each(&Proc.new)\n end\n # if no block given, get all the results\n q.present? ? q.results : collection\n end", "language": "ruby", "code": "def all(constraints = {})\n q = query( {limit: :max}.merge(constraints) )\n if block_given?\n # if we have a query, then use the Proc with it (more efficient)\n return q.present? ? q.results(&Proc.new) : collection.each(&Proc.new)\n end\n # if no block given, get all the results\n q.present? ? q.results : collection\n end", "code_tokens": ["def", "all", "(", "constraints", "=", "{", "}", ")", "q", "=", "query", "(", "{", "limit", ":", ":max", "}", ".", "merge", "(", "constraints", ")", ")", "if", "block_given?", "# if we have a query, then use the Proc with it (more efficient)", "return", "q", ".", "present?", "?", "q", ".", "results", "(", "Proc", ".", "new", ")", ":", "collection", ".", "each", "(", "Proc", ".", "new", ")", "end", "# if no block given, get all the results", "q", ".", "present?", "?", "q", ".", "results", ":", "collection", "end"], "docstring": "You can get items within the collection relation filtered by a specific set\n of query constraints.", "docstring_tokens": ["You", "can", "get", "items", "within", "the", "collection", "relation", "filtered", "by", "a", "specific", "set", "of", "query", "constraints", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/associations/relation_collection_proxy.rb#L57-L65", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/object.rb", "func_name": "Parse.Object.twin", "original_string": "def twin\n h = self.as_json\n h.delete(Parse::Model::OBJECT_ID)\n h.delete(:objectId)\n h.delete(:id)\n self.class.new h\n end", "language": "ruby", "code": "def twin\n h = self.as_json\n h.delete(Parse::Model::OBJECT_ID)\n h.delete(:objectId)\n h.delete(:id)\n self.class.new h\n end", "code_tokens": ["def", "twin", "h", "=", "self", ".", "as_json", "h", ".", "delete", "(", "Parse", "::", "Model", "::", "OBJECT_ID", ")", "h", ".", "delete", "(", ":objectId", ")", "h", ".", "delete", "(", ":id", ")", "self", ".", "class", ".", "new", "h", "end"], "docstring": "This method creates a new object of the same instance type with a copy of\n all the properties of the current instance. This is useful when you want\n to create a duplicate record.\n @return [Parse::Object] a twin copy of the object without the objectId", "docstring_tokens": ["This", "method", "creates", "a", "new", "object", "of", "the", "same", "instance", "type", "with", "a", "copy", "of", "all", "the", "properties", "of", "the", "current", "instance", ".", "This", "is", "useful", "when", "you", "want", "to", "create", "a", "duplicate", "record", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/object.rb#L428-L434", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/file.rb", "func_name": "Parse.File.save", "original_string": "def save\n unless saved? || @contents.nil? || @name.nil?\n response = client.create_file(@name, @contents, @mime_type)\n unless response.error?\n result = response.result\n @name = result[FIELD_NAME] || File.basename(result[FIELD_URL])\n @url = result[FIELD_URL]\n end\n end\n saved?\n end", "language": "ruby", "code": "def save\n unless saved? || @contents.nil? || @name.nil?\n response = client.create_file(@name, @contents, @mime_type)\n unless response.error?\n result = response.result\n @name = result[FIELD_NAME] || File.basename(result[FIELD_URL])\n @url = result[FIELD_URL]\n end\n end\n saved?\n end", "code_tokens": ["def", "save", "unless", "saved?", "||", "@contents", ".", "nil?", "||", "@name", ".", "nil?", "response", "=", "client", ".", "create_file", "(", "@name", ",", "@contents", ",", "@mime_type", ")", "unless", "response", ".", "error?", "result", "=", "response", ".", "result", "@name", "=", "result", "[", "FIELD_NAME", "]", "||", "File", ".", "basename", "(", "result", "[", "FIELD_URL", "]", ")", "@url", "=", "result", "[", "FIELD_URL", "]", "end", "end", "saved?", "end"], "docstring": "Save the file by uploading it to Parse and creating a file pointer.\n @return [Boolean] true if successfully uploaded and saved.", "docstring_tokens": ["Save", "the", "file", "by", "uploading", "it", "to", "Parse", "and", "creating", "a", "file", "pointer", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/file.rb#L171-L181", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/push.rb", "func_name": "Parse.Push.where", "original_string": "def where(constraints = nil)\n return query.compile_where unless constraints.is_a?(Hash)\n query.where constraints\n query\n end", "language": "ruby", "code": "def where(constraints = nil)\n return query.compile_where unless constraints.is_a?(Hash)\n query.where constraints\n query\n end", "code_tokens": ["def", "where", "(", "constraints", "=", "nil", ")", "return", "query", ".", "compile_where", "unless", "constraints", ".", "is_a?", "(", "Hash", ")", "query", ".", "where", "constraints", "query", "end"], "docstring": "Apply a set of constraints.\n @param constraints [Hash] the set of {Parse::Query} cosntraints\n @return [Hash] if no constraints were passed, returns a compiled query.\n @return [Parse::Query] if constraints were passed, returns the chainable query.", "docstring_tokens": ["Apply", "a", "set", "of", "constraints", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/push.rb#L102-L106", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/push.rb", "func_name": "Parse.Push.payload", "original_string": "def payload\n msg = {\n data: {\n alert: alert,\n badge: badge || \"Increment\"\n }\n }\n msg[:data][:sound] = sound if sound.present?\n msg[:data][:title] = title if title.present?\n msg[:data].merge! @data if @data.is_a?(Hash)\n\n\n if @expiration_time.present?\n msg[:expiration_time] = @expiration_time.respond_to?(:iso8601) ? @expiration_time.iso8601(3) : @expiration_time\n end\n if @push_time.present?\n msg[:push_time] = @push_time.respond_to?(:iso8601) ? @push_time.iso8601(3) : @push_time\n end\n\n if @expiration_interval.is_a?(Numeric)\n msg[:expiration_interval] = @expiration_interval.to_i\n end\n\n if query.where.present?\n q = @query.dup\n if @channels.is_a?(Array) && @channels.empty? == false\n q.where :channels.in => @channels\n end\n msg[:where] = q.compile_where unless q.where.empty?\n elsif @channels.is_a?(Array) && @channels.empty? == false\n msg[:channels] = @channels\n end\n msg\n end", "language": "ruby", "code": "def payload\n msg = {\n data: {\n alert: alert,\n badge: badge || \"Increment\"\n }\n }\n msg[:data][:sound] = sound if sound.present?\n msg[:data][:title] = title if title.present?\n msg[:data].merge! @data if @data.is_a?(Hash)\n\n\n if @expiration_time.present?\n msg[:expiration_time] = @expiration_time.respond_to?(:iso8601) ? @expiration_time.iso8601(3) : @expiration_time\n end\n if @push_time.present?\n msg[:push_time] = @push_time.respond_to?(:iso8601) ? @push_time.iso8601(3) : @push_time\n end\n\n if @expiration_interval.is_a?(Numeric)\n msg[:expiration_interval] = @expiration_interval.to_i\n end\n\n if query.where.present?\n q = @query.dup\n if @channels.is_a?(Array) && @channels.empty? == false\n q.where :channels.in => @channels\n end\n msg[:where] = q.compile_where unless q.where.empty?\n elsif @channels.is_a?(Array) && @channels.empty? == false\n msg[:channels] = @channels\n end\n msg\n end", "code_tokens": ["def", "payload", "msg", "=", "{", "data", ":", "{", "alert", ":", "alert", ",", "badge", ":", "badge", "||", "\"Increment\"", "}", "}", "msg", "[", ":data", "]", "[", ":sound", "]", "=", "sound", "if", "sound", ".", "present?", "msg", "[", ":data", "]", "[", ":title", "]", "=", "title", "if", "title", ".", "present?", "msg", "[", ":data", "]", ".", "merge!", "@data", "if", "@data", ".", "is_a?", "(", "Hash", ")", "if", "@expiration_time", ".", "present?", "msg", "[", ":expiration_time", "]", "=", "@expiration_time", ".", "respond_to?", "(", ":iso8601", ")", "?", "@expiration_time", ".", "iso8601", "(", "3", ")", ":", "@expiration_time", "end", "if", "@push_time", ".", "present?", "msg", "[", ":push_time", "]", "=", "@push_time", ".", "respond_to?", "(", ":iso8601", ")", "?", "@push_time", ".", "iso8601", "(", "3", ")", ":", "@push_time", "end", "if", "@expiration_interval", ".", "is_a?", "(", "Numeric", ")", "msg", "[", ":expiration_interval", "]", "=", "@expiration_interval", ".", "to_i", "end", "if", "query", ".", "where", ".", "present?", "q", "=", "@query", ".", "dup", "if", "@channels", ".", "is_a?", "(", "Array", ")", "&&", "@channels", ".", "empty?", "==", "false", "q", ".", "where", ":channels", ".", "in", "=>", "@channels", "end", "msg", "[", ":where", "]", "=", "q", ".", "compile_where", "unless", "q", ".", "where", ".", "empty?", "elsif", "@channels", ".", "is_a?", "(", "Array", ")", "&&", "@channels", ".", "empty?", "==", "false", "msg", "[", ":channels", "]", "=", "@channels", "end", "msg", "end"], "docstring": "This method takes all the parameters of the instance and creates a proper\n hash structure, required by Parse, in order to process the push notification.\n @return [Hash] the prepared push payload to be used in the request.", "docstring_tokens": ["This", "method", "takes", "all", "the", "parameters", "of", "the", "instance", "and", "creates", "a", "proper", "hash", "structure", "required", "by", "Parse", "in", "order", "to", "process", "the", "push", "notification", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/push.rb#L133-L166", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/push.rb", "func_name": "Parse.Push.send", "original_string": "def send(message = nil)\n @alert = message if message.is_a?(String)\n @data = message if message.is_a?(Hash)\n client.push( payload.as_json )\n end", "language": "ruby", "code": "def send(message = nil)\n @alert = message if message.is_a?(String)\n @data = message if message.is_a?(Hash)\n client.push( payload.as_json )\n end", "code_tokens": ["def", "send", "(", "message", "=", "nil", ")", "@alert", "=", "message", "if", "message", ".", "is_a?", "(", "String", ")", "@data", "=", "message", "if", "message", ".", "is_a?", "(", "Hash", ")", "client", ".", "push", "(", "payload", ".", "as_json", ")", "end"], "docstring": "helper method to send a message\n @param message [String] the message to send", "docstring_tokens": ["helper", "method", "to", "send", "a", "message"], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/push.rb#L170-L174", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/query.rb", "func_name": "Parse.Query.distinct", "original_string": "def distinct(field)\n if field.nil? == false && field.respond_to?(:to_s)\n # disable counting if it was enabled.\n old_count_value = @count\n @count = nil\n compile_query = compile # temporary store\n # add distinct field\n compile_query[:distinct] = Query.format_field(field).to_sym\n @count = old_count_value\n # perform aggregation\n return client.aggregate_objects(@table, compile_query.as_json, _opts ).result\n else\n raise ArgumentError, \"Invalid field name passed to `distinct`.\"\n end\n end", "language": "ruby", "code": "def distinct(field)\n if field.nil? == false && field.respond_to?(:to_s)\n # disable counting if it was enabled.\n old_count_value = @count\n @count = nil\n compile_query = compile # temporary store\n # add distinct field\n compile_query[:distinct] = Query.format_field(field).to_sym\n @count = old_count_value\n # perform aggregation\n return client.aggregate_objects(@table, compile_query.as_json, _opts ).result\n else\n raise ArgumentError, \"Invalid field name passed to `distinct`.\"\n end\n end", "code_tokens": ["def", "distinct", "(", "field", ")", "if", "field", ".", "nil?", "==", "false", "&&", "field", ".", "respond_to?", "(", ":to_s", ")", "# disable counting if it was enabled.", "old_count_value", "=", "@count", "@count", "=", "nil", "compile_query", "=", "compile", "# temporary store", "# add distinct field", "compile_query", "[", ":distinct", "]", "=", "Query", ".", "format_field", "(", "field", ")", ".", "to_sym", "@count", "=", "old_count_value", "# perform aggregation", "return", "client", ".", "aggregate_objects", "(", "@table", ",", "compile_query", ".", "as_json", ",", "_opts", ")", ".", "result", "else", "raise", "ArgumentError", ",", "\"Invalid field name passed to `distinct`.\"", "end", "end"], "docstring": "Queries can be made using distinct, allowing you find unique values for a specified field.\n For this to be performant, please remember to index your database.\n @example\n # Return a set of unique city names\n # for users who are greater than 21 years old\n Parse::Query.all(distinct: :age)\n query = Parse::Query.new(\"_User\")\n query.where :age.gt => 21\n # triggers query\n query.distinct(:city) #=> [\"San Diego\", \"Los Angeles\", \"San Juan\"]\n @note This feature requires use of the Master Key in the API.\n @param field [Symbol|String] The name of the field used for filtering.\n @version 1.8.0", "docstring_tokens": ["Queries", "can", "be", "made", "using", "distinct", "allowing", "you", "find", "unique", "values", "for", "a", "specified", "field", ".", "For", "this", "to", "be", "performant", "please", "remember", "to", "index", "your", "database", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/query.rb#L628-L642", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/query.rb", "func_name": "Parse.Query.fetch!", "original_string": "def fetch!(compiled_query)\n\n response = client.find_objects(@table, compiled_query.as_json, _opts )\n if response.error?\n puts \"[ParseQuery] #{response.error}\"\n end\n response\n end", "language": "ruby", "code": "def fetch!(compiled_query)\n\n response = client.find_objects(@table, compiled_query.as_json, _opts )\n if response.error?\n puts \"[ParseQuery] #{response.error}\"\n end\n response\n end", "code_tokens": ["def", "fetch!", "(", "compiled_query", ")", "response", "=", "client", ".", "find_objects", "(", "@table", ",", "compiled_query", ".", "as_json", ",", "_opts", ")", "if", "response", ".", "error?", "puts", "\"[ParseQuery] #{response.error}\"", "end", "response", "end"], "docstring": "Performs the fetch request for the query.\n @param compiled_query [Hash] the compiled query\n @return [Parse::Response] a response for a query request.", "docstring_tokens": ["Performs", "the", "fetch", "request", "for", "the", "query", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/query.rb#L768-L775", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/query.rb", "func_name": "Parse.Query.decode", "original_string": "def decode(list)\n list.map { |m| Parse::Object.build(m, @table) }.compact\n end", "language": "ruby", "code": "def decode(list)\n list.map { |m| Parse::Object.build(m, @table) }.compact\n end", "code_tokens": ["def", "decode", "(", "list", ")", "list", ".", "map", "{", "|", "m", "|", "Parse", "::", "Object", ".", "build", "(", "m", ",", "@table", ")", "}", ".", "compact", "end"], "docstring": "Builds objects based on the set of Parse JSON hashes in an array.\n @param list [Array] a list of Parse JSON hashes\n @return [Array] an array of Parse::Object subclasses.", "docstring_tokens": ["Builds", "objects", "based", "on", "the", "set", "of", "Parse", "JSON", "hashes", "in", "an", "array", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/query.rb#L833-L835", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/query.rb", "func_name": "Parse.Query.compile", "original_string": "def compile(encode: true, includeClassName: false)\n run_callbacks :prepare do\n q = {} #query\n q[:limit] = @limit if @limit.is_a?(Numeric) && @limit > 0\n q[:skip] = @skip if @skip > 0\n\n q[:include] = @includes.join(',') unless @includes.empty?\n q[:keys] = @keys.join(',') unless @keys.empty?\n q[:order] = @order.join(',') unless @order.empty?\n unless @where.empty?\n q[:where] = Parse::Query.compile_where(@where)\n q[:where] = q[:where].to_json if encode\n end\n\n if @count && @count > 0\n # if count is requested\n q[:limit] = 0\n q[:count] = 1\n end\n if includeClassName\n q[:className] = @table\n end\n q\n end\n end", "language": "ruby", "code": "def compile(encode: true, includeClassName: false)\n run_callbacks :prepare do\n q = {} #query\n q[:limit] = @limit if @limit.is_a?(Numeric) && @limit > 0\n q[:skip] = @skip if @skip > 0\n\n q[:include] = @includes.join(',') unless @includes.empty?\n q[:keys] = @keys.join(',') unless @keys.empty?\n q[:order] = @order.join(',') unless @order.empty?\n unless @where.empty?\n q[:where] = Parse::Query.compile_where(@where)\n q[:where] = q[:where].to_json if encode\n end\n\n if @count && @count > 0\n # if count is requested\n q[:limit] = 0\n q[:count] = 1\n end\n if includeClassName\n q[:className] = @table\n end\n q\n end\n end", "code_tokens": ["def", "compile", "(", "encode", ":", "true", ",", "includeClassName", ":", "false", ")", "run_callbacks", ":prepare", "do", "q", "=", "{", "}", "#query", "q", "[", ":limit", "]", "=", "@limit", "if", "@limit", ".", "is_a?", "(", "Numeric", ")", "&&", "@limit", ">", "0", "q", "[", ":skip", "]", "=", "@skip", "if", "@skip", ">", "0", "q", "[", ":include", "]", "=", "@includes", ".", "join", "(", "','", ")", "unless", "@includes", ".", "empty?", "q", "[", ":keys", "]", "=", "@keys", ".", "join", "(", "','", ")", "unless", "@keys", ".", "empty?", "q", "[", ":order", "]", "=", "@order", ".", "join", "(", "','", ")", "unless", "@order", ".", "empty?", "unless", "@where", ".", "empty?", "q", "[", ":where", "]", "=", "Parse", "::", "Query", ".", "compile_where", "(", "@where", ")", "q", "[", ":where", "]", "=", "q", "[", ":where", "]", ".", "to_json", "if", "encode", "end", "if", "@count", "&&", "@count", ">", "0", "# if count is requested", "q", "[", ":limit", "]", "=", "0", "q", "[", ":count", "]", "=", "1", "end", "if", "includeClassName", "q", "[", ":className", "]", "=", "@table", "end", "q", "end", "end"], "docstring": "Complies the query and runs all prepare callbacks.\n @param encode [Boolean] whether to encode the `where` clause to a JSON string.\n @param includeClassName [Boolean] whether to include the class name of the collection.\n @return [Hash] a hash representing the prepared query request.\n @see #before_prepare\n @see #after_prepare", "docstring_tokens": ["Complies", "the", "query", "and", "runs", "all", "prepare", "callbacks", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/query.rb#L856-L880", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/client.rb", "func_name": "Parse.Client.get", "original_string": "def get(uri, query = nil, headers = {})\n request :get, uri, query: query, headers: headers\n end", "language": "ruby", "code": "def get(uri, query = nil, headers = {})\n request :get, uri, query: query, headers: headers\n end", "code_tokens": ["def", "get", "(", "uri", ",", "query", "=", "nil", ",", "headers", "=", "{", "}", ")", "request", ":get", ",", "uri", ",", "query", ":", "query", ",", "headers", ":", "headers", "end"], "docstring": "Send a GET request.\n @param uri [String] the uri path for this request.\n @param query [Hash] the set of url query parameters.\n @param headers [Hash] additional headers to send in this request.\n @return (see #request)", "docstring_tokens": ["Send", "a", "GET", "request", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/client.rb#L496-L498", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/client.rb", "func_name": "Parse.Client.post", "original_string": "def post(uri, body = nil, headers = {} )\n request :post, uri, body: body, headers: headers\n end", "language": "ruby", "code": "def post(uri, body = nil, headers = {} )\n request :post, uri, body: body, headers: headers\n end", "code_tokens": ["def", "post", "(", "uri", ",", "body", "=", "nil", ",", "headers", "=", "{", "}", ")", "request", ":post", ",", "uri", ",", "body", ":", "body", ",", "headers", ":", "headers", "end"], "docstring": "Send a POST request.\n @param uri (see #get)\n @param body [Hash] a hash that will be JSON encoded for the body of this request.\n @param headers (see #get)\n @return (see #request)", "docstring_tokens": ["Send", "a", "POST", "request", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/client.rb#L505-L507", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/client.rb", "func_name": "Parse.Client.put", "original_string": "def put(uri, body = nil, headers = {})\n request :put, uri, body: body, headers: headers\n end", "language": "ruby", "code": "def put(uri, body = nil, headers = {})\n request :put, uri, body: body, headers: headers\n end", "code_tokens": ["def", "put", "(", "uri", ",", "body", "=", "nil", ",", "headers", "=", "{", "}", ")", "request", ":put", ",", "uri", ",", "body", ":", "body", ",", "headers", ":", "headers", "end"], "docstring": "Send a PUT request.\n @param uri (see #post)\n @param body (see #post)\n @param headers (see #post)\n @return (see #request)", "docstring_tokens": ["Send", "a", "PUT", "request", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/client.rb#L514-L516", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/client.rb", "func_name": "Parse.Client.delete", "original_string": "def delete(uri, body = nil, headers = {})\n request :delete, uri, body: body, headers: headers\n end", "language": "ruby", "code": "def delete(uri, body = nil, headers = {})\n request :delete, uri, body: body, headers: headers\n end", "code_tokens": ["def", "delete", "(", "uri", ",", "body", "=", "nil", ",", "headers", "=", "{", "}", ")", "request", ":delete", ",", "uri", ",", "body", ":", "body", ",", "headers", ":", "headers", "end"], "docstring": "Send a DELETE request.\n @param uri (see #post)\n @param body (see #post)\n @param headers (see #post)\n @return (see #request)", "docstring_tokens": ["Send", "a", "DELETE", "request", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/client.rb#L523-L525", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/acl.rb", "func_name": "Parse.ACL.delete", "original_string": "def delete(id)\n id = id.id if id.is_a?(Parse::Pointer)\n if id.present? && permissions.has_key?(id)\n will_change!\n permissions.delete(id)\n end\n end", "language": "ruby", "code": "def delete(id)\n id = id.id if id.is_a?(Parse::Pointer)\n if id.present? && permissions.has_key?(id)\n will_change!\n permissions.delete(id)\n end\n end", "code_tokens": ["def", "delete", "(", "id", ")", "id", "=", "id", ".", "id", "if", "id", ".", "is_a?", "(", "Parse", "::", "Pointer", ")", "if", "id", ".", "present?", "&&", "permissions", ".", "has_key?", "(", "id", ")", "will_change!", "permissions", ".", "delete", "(", "id", ")", "end", "end"], "docstring": "Removes a permission for an objectId or user.\n @overload delete(object)\n @param object [Parse::User] the user to revoke permissions.\n @overload delete(id)\n @param id [String] the objectId to revoke permissions.", "docstring_tokens": ["Removes", "a", "permission", "for", "an", "objectId", "or", "user", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/acl.rb#L211-L217", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/acl.rb", "func_name": "Parse.ACL.all_read!", "original_string": "def all_read!\n will_change!\n permissions.keys.each do |perm|\n permissions[perm].read! true\n end\n end", "language": "ruby", "code": "def all_read!\n will_change!\n permissions.keys.each do |perm|\n permissions[perm].read! true\n end\n end", "code_tokens": ["def", "all_read!", "will_change!", "permissions", ".", "keys", ".", "each", "do", "|", "perm", "|", "permissions", "[", "perm", "]", ".", "read!", "true", "end", "end"], "docstring": "Grants read permission on all existing users and roles attached to this object.\n @example\n object.acl\n # { \"*\": { \"read\" : true },\n # \"3KmCvT7Zsb\": { \"read\" : true, \"write\": true },\n # \"role:Admins\": { \"write\": true }\n # }\n object.acl.all_read!\n # Outcome:\n # { \"*\": { \"read\" : true },\n # \"3KmCvT7Zsb\": { \"read\" : true, \"write\": true },\n # \"role:Admins\": { \"read\" : true, \"write\": true}\n # }\n @version 1.7.2\n @return [Array] list of ACL keys", "docstring_tokens": ["Grants", "read", "permission", "on", "all", "existing", "users", "and", "roles", "attached", "to", "this", "object", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/acl.rb#L350-L355", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/acl.rb", "func_name": "Parse.ACL.all_write!", "original_string": "def all_write!\n will_change!\n permissions.keys.each do |perm|\n permissions[perm].write! true\n end\n end", "language": "ruby", "code": "def all_write!\n will_change!\n permissions.keys.each do |perm|\n permissions[perm].write! true\n end\n end", "code_tokens": ["def", "all_write!", "will_change!", "permissions", ".", "keys", ".", "each", "do", "|", "perm", "|", "permissions", "[", "perm", "]", ".", "write!", "true", "end", "end"], "docstring": "Grants write permission on all existing users and roles attached to this object.\n @example\n object.acl\n # { \"*\": { \"read\" : true },\n # \"3KmCvT7Zsb\": { \"read\" : true, \"write\": true },\n # \"role:Admins\": { \"write\": true }\n # }\n object.acl.all_write!\n # Outcome:\n # { \"*\": { \"read\" : true, \"write\": true },\n # \"3KmCvT7Zsb\": { \"read\" : true, \"write\": true },\n # \"role:Admins\": { \"write\": true }\n # }\n @version 1.7.2\n @return [Array] list of ACL keys", "docstring_tokens": ["Grants", "write", "permission", "on", "all", "existing", "users", "and", "roles", "attached", "to", "this", "object", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/acl.rb#L372-L377", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/acl.rb", "func_name": "Parse.ACL.no_read!", "original_string": "def no_read!\n will_change!\n permissions.keys.each do |perm|\n permissions[perm].read! false\n end\n end", "language": "ruby", "code": "def no_read!\n will_change!\n permissions.keys.each do |perm|\n permissions[perm].read! false\n end\n end", "code_tokens": ["def", "no_read!", "will_change!", "permissions", ".", "keys", ".", "each", "do", "|", "perm", "|", "permissions", "[", "perm", "]", ".", "read!", "false", "end", "end"], "docstring": "Denies read permission on all existing users and roles attached to this object.\n @example\n object.acl\n # { \"*\": { \"read\" : true },\n # \"3KmCvT7Zsb\": { \"read\" : true, \"write\": true },\n # \"role:Admins\": { \"write\": true }\n # }\n object.acl.no_read!\n # Outcome:\n # { \"*\": nil,\n # \"3KmCvT7Zsb\": { \"write\": true },\n # \"role:Admins\": { \"write\": true }\n # }\n @version 1.7.2\n @return [Array] list of ACL keys", "docstring_tokens": ["Denies", "read", "permission", "on", "all", "existing", "users", "and", "roles", "attached", "to", "this", "object", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/acl.rb#L394-L399", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/acl.rb", "func_name": "Parse.ACL.no_write!", "original_string": "def no_write!\n will_change!\n permissions.keys.each do |perm|\n permissions[perm].write! false\n end\n end", "language": "ruby", "code": "def no_write!\n will_change!\n permissions.keys.each do |perm|\n permissions[perm].write! false\n end\n end", "code_tokens": ["def", "no_write!", "will_change!", "permissions", ".", "keys", ".", "each", "do", "|", "perm", "|", "permissions", "[", "perm", "]", ".", "write!", "false", "end", "end"], "docstring": "Denies write permission on all existing users and roles attached to this object.\n @example\n object.acl\n # { \"*\": { \"read\" : true },\n # \"3KmCvT7Zsb\": { \"read\" : true, \"write\": true },\n # \"role:Admins\": { \"write\": true }\n # }\n object.acl.no_write!\n # Outcome:\n # { \"*\": { \"read\" : true },\n # \"3KmCvT7Zsb\": { \"read\" : true },\n # \"role:Admins\": nil\n # }\n @version 1.7.2\n @return [Array] list of ACL keys", "docstring_tokens": ["Denies", "write", "permission", "on", "all", "existing", "users", "and", "roles", "attached", "to", "this", "object", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/acl.rb#L416-L421", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/client/response.rb", "func_name": "Parse.Response.batch_responses", "original_string": "def batch_responses\n\n return [@result] unless @batch_response\n # if batch response, generate array based on the response hash.\n @result.map do |r|\n next r unless r.is_a?(Hash)\n hash = r[SUCCESS] || r[ERROR]\n Parse::Response.new hash\n end\n end", "language": "ruby", "code": "def batch_responses\n\n return [@result] unless @batch_response\n # if batch response, generate array based on the response hash.\n @result.map do |r|\n next r unless r.is_a?(Hash)\n hash = r[SUCCESS] || r[ERROR]\n Parse::Response.new hash\n end\n end", "code_tokens": ["def", "batch_responses", "return", "[", "@result", "]", "unless", "@batch_response", "# if batch response, generate array based on the response hash.", "@result", ".", "map", "do", "|", "r", "|", "next", "r", "unless", "r", ".", "is_a?", "(", "Hash", ")", "hash", "=", "r", "[", "SUCCESS", "]", "||", "r", "[", "ERROR", "]", "Parse", "::", "Response", ".", "new", "hash", "end", "end"], "docstring": "If it is a batch respnose, we'll create an array of Response objects for each\n of the ones in the batch.\n @return [Array] an array of Response objects.", "docstring_tokens": ["If", "it", "is", "a", "batch", "respnose", "we", "ll", "create", "an", "array", "of", "Response", "objects", "for", "each", "of", "the", "ones", "in", "the", "batch", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/client/response.rb#L100-L109", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/client/response.rb", "func_name": "Parse.Response.parse_result!", "original_string": "def parse_result!(h)\n @result = {}\n return unless h.is_a?(Hash)\n @code = h[CODE]\n @error = h[ERROR]\n if h[RESULTS].is_a?(Array)\n @result = h[RESULTS]\n @count = h[COUNT] || @result.count\n else\n @result = h\n @count = 1\n end\n\n end", "language": "ruby", "code": "def parse_result!(h)\n @result = {}\n return unless h.is_a?(Hash)\n @code = h[CODE]\n @error = h[ERROR]\n if h[RESULTS].is_a?(Array)\n @result = h[RESULTS]\n @count = h[COUNT] || @result.count\n else\n @result = h\n @count = 1\n end\n\n end", "code_tokens": ["def", "parse_result!", "(", "h", ")", "@result", "=", "{", "}", "return", "unless", "h", ".", "is_a?", "(", "Hash", ")", "@code", "=", "h", "[", "CODE", "]", "@error", "=", "h", "[", "ERROR", "]", "if", "h", "[", "RESULTS", "]", ".", "is_a?", "(", "Array", ")", "@result", "=", "h", "[", "RESULTS", "]", "@count", "=", "h", "[", "COUNT", "]", "||", "@result", ".", "count", "else", "@result", "=", "h", "@count", "=", "1", "end", "end"], "docstring": "This method takes the result hash and determines if it is a regular\n parse query result, object result or a count result. The response should\n be a hash either containing the result data or the error.", "docstring_tokens": ["This", "method", "takes", "the", "result", "hash", "and", "determines", "if", "it", "is", "a", "regular", "parse", "query", "result", "object", "result", "or", "a", "count", "result", ".", "The", "response", "should", "be", "a", "hash", "either", "containing", "the", "result", "data", "or", "the", "error", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/client/response.rb#L114-L127", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/classes/user.rb", "func_name": "Parse.User.link_auth_data!", "original_string": "def link_auth_data!(service_name, **data)\n response = client.set_service_auth_data(id, service_name, data)\n raise Parse::Client::ResponseError, response if response.error?\n apply_attributes!(response.result)\n end", "language": "ruby", "code": "def link_auth_data!(service_name, **data)\n response = client.set_service_auth_data(id, service_name, data)\n raise Parse::Client::ResponseError, response if response.error?\n apply_attributes!(response.result)\n end", "code_tokens": ["def", "link_auth_data!", "(", "service_name", ",", "**", "data", ")", "response", "=", "client", ".", "set_service_auth_data", "(", "id", ",", "service_name", ",", "data", ")", "raise", "Parse", "::", "Client", "::", "ResponseError", ",", "response", "if", "response", ".", "error?", "apply_attributes!", "(", "response", ".", "result", ")", "end"], "docstring": "Adds the third-party authentication data to for a given service.\n @param service_name [Symbol] The name of the service (ex. :facebook)\n @param data [Hash] The body of the OAuth data. Dependent on each service.\n @raise [Parse::Client::ResponseError] If user was not successfully linked", "docstring_tokens": ["Adds", "the", "third", "-", "party", "authentication", "data", "to", "for", "a", "given", "service", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/classes/user.rb#L199-L203", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/classes/user.rb", "func_name": "Parse.User.signup!", "original_string": "def signup!(passwd = nil)\n self.password = passwd || password\n if username.blank?\n raise Parse::Error::UsernameMissingError, \"Signup requires a username.\"\n end\n\n if password.blank?\n raise Parse::Error::PasswordMissingError, \"Signup requires a password.\"\n end\n\n signup_attrs = attribute_updates\n signup_attrs.except! *Parse::Properties::BASE_FIELD_MAP.flatten\n\n # first signup the user, then save any additional attributes\n response = client.create_user signup_attrs\n\n if response.success?\n apply_attributes! response.result\n return true\n end\n\n case response.code\n when Parse::Response::ERROR_USERNAME_MISSING\n raise Parse::Error::UsernameMissingError, response\n when Parse::Response::ERROR_PASSWORD_MISSING\n raise Parse::Error::PasswordMissingError, response\n when Parse::Response::ERROR_USERNAME_TAKEN\n raise Parse::Error::UsernameTakenError, response\n when Parse::Response::ERROR_EMAIL_TAKEN\n raise Parse::Error::EmailTakenError, response\n when Parse::Response::ERROR_EMAIL_INVALID\n raise Parse::Error::InvalidEmailAddress, response\n end\n raise Parse::Client::ResponseError, response\n end", "language": "ruby", "code": "def signup!(passwd = nil)\n self.password = passwd || password\n if username.blank?\n raise Parse::Error::UsernameMissingError, \"Signup requires a username.\"\n end\n\n if password.blank?\n raise Parse::Error::PasswordMissingError, \"Signup requires a password.\"\n end\n\n signup_attrs = attribute_updates\n signup_attrs.except! *Parse::Properties::BASE_FIELD_MAP.flatten\n\n # first signup the user, then save any additional attributes\n response = client.create_user signup_attrs\n\n if response.success?\n apply_attributes! response.result\n return true\n end\n\n case response.code\n when Parse::Response::ERROR_USERNAME_MISSING\n raise Parse::Error::UsernameMissingError, response\n when Parse::Response::ERROR_PASSWORD_MISSING\n raise Parse::Error::PasswordMissingError, response\n when Parse::Response::ERROR_USERNAME_TAKEN\n raise Parse::Error::UsernameTakenError, response\n when Parse::Response::ERROR_EMAIL_TAKEN\n raise Parse::Error::EmailTakenError, response\n when Parse::Response::ERROR_EMAIL_INVALID\n raise Parse::Error::InvalidEmailAddress, response\n end\n raise Parse::Client::ResponseError, response\n end", "code_tokens": ["def", "signup!", "(", "passwd", "=", "nil", ")", "self", ".", "password", "=", "passwd", "||", "password", "if", "username", ".", "blank?", "raise", "Parse", "::", "Error", "::", "UsernameMissingError", ",", "\"Signup requires a username.\"", "end", "if", "password", ".", "blank?", "raise", "Parse", "::", "Error", "::", "PasswordMissingError", ",", "\"Signup requires a password.\"", "end", "signup_attrs", "=", "attribute_updates", "signup_attrs", ".", "except!", "Parse", "::", "Properties", "::", "BASE_FIELD_MAP", ".", "flatten", "# first signup the user, then save any additional attributes", "response", "=", "client", ".", "create_user", "signup_attrs", "if", "response", ".", "success?", "apply_attributes!", "response", ".", "result", "return", "true", "end", "case", "response", ".", "code", "when", "Parse", "::", "Response", "::", "ERROR_USERNAME_MISSING", "raise", "Parse", "::", "Error", "::", "UsernameMissingError", ",", "response", "when", "Parse", "::", "Response", "::", "ERROR_PASSWORD_MISSING", "raise", "Parse", "::", "Error", "::", "PasswordMissingError", ",", "response", "when", "Parse", "::", "Response", "::", "ERROR_USERNAME_TAKEN", "raise", "Parse", "::", "Error", "::", "UsernameTakenError", ",", "response", "when", "Parse", "::", "Response", "::", "ERROR_EMAIL_TAKEN", "raise", "Parse", "::", "Error", "::", "EmailTakenError", ",", "response", "when", "Parse", "::", "Response", "::", "ERROR_EMAIL_INVALID", "raise", "Parse", "::", "Error", "::", "InvalidEmailAddress", ",", "response", "end", "raise", "Parse", "::", "Client", "::", "ResponseError", ",", "response", "end"], "docstring": "You may set a password for this user when you are creating them. Parse never returns a\n @param passwd The user's password to be used for signing up.\n @raise [Parse::Error::UsernameMissingError] If username is missing.\n @raise [Parse::Error::PasswordMissingError] If password is missing.\n @raise [Parse::Error::UsernameTakenError] If the username has already been taken.\n @raise [Parse::Error::EmailTakenError] If the email has already been taken (or exists in the system).\n @raise [Parse::Error::InvalidEmailAddress] If the email is invalid.\n @raise [Parse::Client::ResponseError] An unknown error occurred.\n @return [Boolean] True if signup it was successful. If it fails an exception is thrown.", "docstring_tokens": ["You", "may", "set", "a", "password", "for", "this", "user", "when", "you", "are", "creating", "them", ".", "Parse", "never", "returns", "a"], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/classes/user.rb#L245-L279", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/classes/user.rb", "func_name": "Parse.User.login!", "original_string": "def login!(passwd = nil)\n self.password = passwd || self.password\n response = client.login(username.to_s, password.to_s)\n apply_attributes! response.result\n self.session_token.present?\n end", "language": "ruby", "code": "def login!(passwd = nil)\n self.password = passwd || self.password\n response = client.login(username.to_s, password.to_s)\n apply_attributes! response.result\n self.session_token.present?\n end", "code_tokens": ["def", "login!", "(", "passwd", "=", "nil", ")", "self", ".", "password", "=", "passwd", "||", "self", ".", "password", "response", "=", "client", ".", "login", "(", "username", ".", "to_s", ",", "password", ".", "to_s", ")", "apply_attributes!", "response", ".", "result", "self", ".", "session_token", ".", "present?", "end"], "docstring": "Login and get a session token for this user.\n @param passwd [String] The password for this user.\n @return [Boolean] True/false if we received a valid session token.", "docstring_tokens": ["Login", "and", "get", "a", "session", "token", "for", "this", "user", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/classes/user.rb#L284-L289", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/classes/user.rb", "func_name": "Parse.User.logout", "original_string": "def logout\n return true if self.session_token.blank?\n client.logout session_token\n self.session_token = nil\n true\n rescue => e\n false\n end", "language": "ruby", "code": "def logout\n return true if self.session_token.blank?\n client.logout session_token\n self.session_token = nil\n true\n rescue => e\n false\n end", "code_tokens": ["def", "logout", "return", "true", "if", "self", ".", "session_token", ".", "blank?", "client", ".", "logout", "session_token", "self", ".", "session_token", "=", "nil", "true", "rescue", "=>", "e", "false", "end"], "docstring": "Invalid the current session token for this logged in user.\n @return [Boolean] True/false if successful", "docstring_tokens": ["Invalid", "the", "current", "session", "token", "for", "this", "logged", "in", "user", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/classes/user.rb#L293-L300", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/core/actions.rb", "func_name": "Parse.Query.first_or_create", "original_string": "def first_or_create(query_attrs = {}, resource_attrs = {})\n conditions(query_attrs)\n klass = Parse::Model.find_class self.table\n if klass.blank?\n raise ArgumentError, \"Parse model with class name #{self.table} is not registered.\"\n end\n hash_constraints = constraints(true)\n klass.first_or_create(hash_constraints, resource_attrs)\n end", "language": "ruby", "code": "def first_or_create(query_attrs = {}, resource_attrs = {})\n conditions(query_attrs)\n klass = Parse::Model.find_class self.table\n if klass.blank?\n raise ArgumentError, \"Parse model with class name #{self.table} is not registered.\"\n end\n hash_constraints = constraints(true)\n klass.first_or_create(hash_constraints, resource_attrs)\n end", "code_tokens": ["def", "first_or_create", "(", "query_attrs", "=", "{", "}", ",", "resource_attrs", "=", "{", "}", ")", "conditions", "(", "query_attrs", ")", "klass", "=", "Parse", "::", "Model", ".", "find_class", "self", ".", "table", "if", "klass", ".", "blank?", "raise", "ArgumentError", ",", "\"Parse model with class name #{self.table} is not registered.\"", "end", "hash_constraints", "=", "constraints", "(", "true", ")", "klass", ".", "first_or_create", "(", "hash_constraints", ",", "resource_attrs", ")", "end"], "docstring": "Supporting the `first_or_create` class method to be used in scope chaining with queries.\n @!visibility private", "docstring_tokens": ["Supporting", "the", "first_or_create", "class", "method", "to", "be", "used", "in", "scope", "chaining", "with", "queries", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/core/actions.rb#L29-L37", "partition": "valid"} {"repo": "modernistik/parse-stack", "path": "lib/parse/model/core/actions.rb", "func_name": "Parse.Query.save_all", "original_string": "def save_all(expressions = {})\n conditions(expressions)\n klass = Parse::Model.find_class self.table\n if klass.blank?\n raise ArgumentError, \"Parse model with class name #{self.table} is not registered.\"\n end\n hash_constraints = constraints(true)\n\n klass.save_all(hash_constraints, &Proc.new) if block_given?\n klass.save_all(hash_constraints)\n end", "language": "ruby", "code": "def save_all(expressions = {})\n conditions(expressions)\n klass = Parse::Model.find_class self.table\n if klass.blank?\n raise ArgumentError, \"Parse model with class name #{self.table} is not registered.\"\n end\n hash_constraints = constraints(true)\n\n klass.save_all(hash_constraints, &Proc.new) if block_given?\n klass.save_all(hash_constraints)\n end", "code_tokens": ["def", "save_all", "(", "expressions", "=", "{", "}", ")", "conditions", "(", "expressions", ")", "klass", "=", "Parse", "::", "Model", ".", "find_class", "self", ".", "table", "if", "klass", ".", "blank?", "raise", "ArgumentError", ",", "\"Parse model with class name #{self.table} is not registered.\"", "end", "hash_constraints", "=", "constraints", "(", "true", ")", "klass", ".", "save_all", "(", "hash_constraints", ",", "Proc", ".", "new", ")", "if", "block_given?", "klass", ".", "save_all", "(", "hash_constraints", ")", "end"], "docstring": "Supporting the `save_all` method to be used in scope chaining with queries.\n @!visibility private", "docstring_tokens": ["Supporting", "the", "save_all", "method", "to", "be", "used", "in", "scope", "chaining", "with", "queries", "."], "sha": "23730f8faa20ff90d994cdb5771096c9a9a5bdff", "url": "https://github.com/modernistik/parse-stack/blob/23730f8faa20ff90d994cdb5771096c9a9a5bdff/lib/parse/model/core/actions.rb#L41-L51", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/font.rb", "func_name": "RTF.FontTable.add", "original_string": "def add(font)\r\n if font.instance_of?(Font)\r\n @fonts.push(font) if @fonts.index(font).nil?\r\n end\r\n self\r\n end", "language": "ruby", "code": "def add(font)\r\n if font.instance_of?(Font)\r\n @fonts.push(font) if @fonts.index(font).nil?\r\n end\r\n self\r\n end", "code_tokens": ["def", "add", "(", "font", ")", "if", "font", ".", "instance_of?", "(", "Font", ")", "@fonts", ".", "push", "(", "font", ")", "if", "@fonts", ".", "index", "(", "font", ")", ".", "nil?", "end", "self", "end"], "docstring": "This method adds a font to a FontTable instance. This method returns\n a reference to the FontTable object updated.\n\n ==== Parameters\n font:: A reference to the font to be added. If this is not a Font\n object or already exists in the table it will be ignored.", "docstring_tokens": ["This", "method", "adds", "a", "font", "to", "a", "FontTable", "instance", ".", "This", "method", "returns", "a", "reference", "to", "the", "FontTable", "object", "updated", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/font.rb#L109-L114", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/font.rb", "func_name": "RTF.FontTable.to_rtf", "original_string": "def to_rtf(indent=0)\r\n prefix = indent > 0 ? ' ' * indent : ''\r\n text = StringIO.new\r\n text << \"#{prefix}{\\\\fonttbl\"\r\n @fonts.each_index do |index|\r\n text << \"\\n#{prefix}{\\\\f#{index}#{@fonts[index].to_rtf}}\"\r\n end\r\n text << \"\\n#{prefix}}\"\r\n text.string\r\n end", "language": "ruby", "code": "def to_rtf(indent=0)\r\n prefix = indent > 0 ? ' ' * indent : ''\r\n text = StringIO.new\r\n text << \"#{prefix}{\\\\fonttbl\"\r\n @fonts.each_index do |index|\r\n text << \"\\n#{prefix}{\\\\f#{index}#{@fonts[index].to_rtf}}\"\r\n end\r\n text << \"\\n#{prefix}}\"\r\n text.string\r\n end", "code_tokens": ["def", "to_rtf", "(", "indent", "=", "0", ")", "prefix", "=", "indent", ">", "0", "?", "' '", "*", "indent", ":", "''", "text", "=", "StringIO", ".", "new", "text", "<<", "\"#{prefix}{\\\\fonttbl\"", "@fonts", ".", "each_index", "do", "|", "index", "|", "text", "<<", "\"\\n#{prefix}{\\\\f#{index}#{@fonts[index].to_rtf}}\"", "end", "text", "<<", "\"\\n#{prefix}}\"", "text", ".", "string", "end"], "docstring": "This method generates the RTF text for a FontTable object.\n\n ==== Parameters\n indent:: The number of spaces to prefix to the lines generated by the\n method. Defaults to zero.", "docstring_tokens": ["This", "method", "generates", "the", "RTF", "text", "for", "a", "FontTable", "object", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/font.rb#L160-L169", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.Node.previous_node", "original_string": "def previous_node\n peer = nil\n if !parent.nil? and parent.respond_to?(:children)\n index = parent.children.index(self)\n peer = index > 0 ? parent.children[index - 1] : nil\n end\n peer\n end", "language": "ruby", "code": "def previous_node\n peer = nil\n if !parent.nil? and parent.respond_to?(:children)\n index = parent.children.index(self)\n peer = index > 0 ? parent.children[index - 1] : nil\n end\n peer\n end", "code_tokens": ["def", "previous_node", "peer", "=", "nil", "if", "!", "parent", ".", "nil?", "and", "parent", ".", "respond_to?", "(", ":children", ")", "index", "=", "parent", ".", "children", ".", "index", "(", "self", ")", "peer", "=", "index", ">", "0", "?", "parent", ".", "children", "[", "index", "-", "1", "]", ":", "nil", "end", "peer", "end"], "docstring": "Constructor for the Node class.\n\n ==== Parameters\n parent:: A reference to the Node that owns the new Node. May be nil\n to indicate a base or root node.\n This method retrieves a Node objects previous peer node, returning nil\n if the Node has no previous peer.", "docstring_tokens": ["Constructor", "for", "the", "Node", "class", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L23-L30", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.Node.next_node", "original_string": "def next_node\n peer = nil\n if !parent.nil? and parent.respond_to?(:children)\n index = parent.children.index(self)\n peer = parent.children[index + 1]\n end\n peer\n end", "language": "ruby", "code": "def next_node\n peer = nil\n if !parent.nil? and parent.respond_to?(:children)\n index = parent.children.index(self)\n peer = parent.children[index + 1]\n end\n peer\n end", "code_tokens": ["def", "next_node", "peer", "=", "nil", "if", "!", "parent", ".", "nil?", "and", "parent", ".", "respond_to?", "(", ":children", ")", "index", "=", "parent", ".", "children", ".", "index", "(", "self", ")", "peer", "=", "parent", ".", "children", "[", "index", "+", "1", "]", "end", "peer", "end"], "docstring": "This method retrieves a Node objects next peer node, returning nil\n if the Node has no previous peer.", "docstring_tokens": ["This", "method", "retrieves", "a", "Node", "objects", "next", "peer", "node", "returning", "nil", "if", "the", "Node", "has", "no", "previous", "peer", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L34-L41", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.TextNode.insert", "original_string": "def insert(text, offset)\n if !@text.nil?\n @text = @text[0, offset] + text.to_s + @text[offset, @text.length]\n else\n @text = text.to_s\n end\n end", "language": "ruby", "code": "def insert(text, offset)\n if !@text.nil?\n @text = @text[0, offset] + text.to_s + @text[offset, @text.length]\n else\n @text = text.to_s\n end\n end", "code_tokens": ["def", "insert", "(", "text", ",", "offset", ")", "if", "!", "@text", ".", "nil?", "@text", "=", "@text", "[", "0", ",", "offset", "]", "+", "text", ".", "to_s", "+", "@text", "[", "offset", ",", "@text", ".", "length", "]", "else", "@text", "=", "text", ".", "to_s", "end", "end"], "docstring": "This method inserts a String into the existing text within a TextNode\n object. If the TextNode contains no text then it is simply set to the\n text passed in. If the offset specified is past the end of the nodes\n text then it is simply appended to the end.\n\n ==== Parameters\n text:: A String containing the text to be added.\n offset:: The numbers of characters from the first character to insert\n the new text at.", "docstring_tokens": ["This", "method", "inserts", "a", "String", "into", "the", "existing", "text", "within", "a", "TextNode", "object", ".", "If", "the", "TextNode", "contains", "no", "text", "then", "it", "is", "simply", "set", "to", "the", "text", "passed", "in", ".", "If", "the", "offset", "specified", "is", "past", "the", "end", "of", "the", "nodes", "text", "then", "it", "is", "simply", "appended", "to", "the", "end", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L102-L108", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.TextNode.to_rtf", "original_string": "def to_rtf\n rtf=(@text.nil? ? '' : @text.gsub(\"{\", \"\\\\{\").gsub(\"}\", \"\\\\}\").gsub(\"\\\\\", \"\\\\\\\\\"))\n # This is from lfarcy / rtf-extensions\n # I don't see the point of coding different 128\"1.9.0\"\n return rtf.encode(\"UTF-16LE\", :undef=>:replace).each_codepoint.map(&f).join('')\n else\n # You SHOULD use UTF-8 as input, ok?\n return rtf.unpack('U*').map(&f).join('')\n end\n end", "language": "ruby", "code": "def to_rtf\n rtf=(@text.nil? ? '' : @text.gsub(\"{\", \"\\\\{\").gsub(\"}\", \"\\\\}\").gsub(\"\\\\\", \"\\\\\\\\\"))\n # This is from lfarcy / rtf-extensions\n # I don't see the point of coding different 128\"1.9.0\"\n return rtf.encode(\"UTF-16LE\", :undef=>:replace).each_codepoint.map(&f).join('')\n else\n # You SHOULD use UTF-8 as input, ok?\n return rtf.unpack('U*').map(&f).join('')\n end\n end", "code_tokens": ["def", "to_rtf", "rtf", "=", "(", "@text", ".", "nil?", "?", "''", ":", "@text", ".", "gsub", "(", "\"{\"", ",", "\"\\\\{\"", ")", ".", "gsub", "(", "\"}\"", ",", "\"\\\\}\"", ")", ".", "gsub", "(", "\"\\\\\"", ",", "\"\\\\\\\\\"", ")", ")", "# This is from lfarcy / rtf-extensions", "# I don't see the point of coding different 128", "\"1.9.0\"", "return", "rtf", ".", "encode", "(", "\"UTF-16LE\"", ",", ":undef", "=>", ":replace", ")", ".", "each_codepoint", ".", "map", "(", "f", ")", ".", "join", "(", "''", ")", "else", "# You SHOULD use UTF-8 as input, ok?", "return", "rtf", ".", "unpack", "(", "'U*'", ")", ".", "map", "(", "f", ")", ".", "join", "(", "''", ")", "end", "end"], "docstring": "This method generates the RTF equivalent for a TextNode object. This\n method escapes any special sequences that appear in the text.", "docstring_tokens": ["This", "method", "generates", "the", "RTF", "equivalent", "for", "a", "TextNode", "object", ".", "This", "method", "escapes", "any", "special", "sequences", "that", "appear", "in", "the", "text", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L112-L129", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.ContainerNode.store", "original_string": "def store(node)\n if !node.nil?\n @children.push(node) if !@children.include?(Node)\n node.parent = self if node.parent != self\n end\n node\n end", "language": "ruby", "code": "def store(node)\n if !node.nil?\n @children.push(node) if !@children.include?(Node)\n node.parent = self if node.parent != self\n end\n node\n end", "code_tokens": ["def", "store", "(", "node", ")", "if", "!", "node", ".", "nil?", "@children", ".", "push", "(", "node", ")", "if", "!", "@children", ".", "include?", "(", "Node", ")", "node", ".", "parent", "=", "self", "if", "node", ".", "parent", "!=", "self", "end", "node", "end"], "docstring": "This is the constructor for the ContainerNode class.\n\n ==== Parameters\n parent:: A reference to the parent node that owners the new\n ContainerNode object.\n This method adds a new node element to the end of the list of nodes\n maintained by a ContainerNode object. Nil objects are ignored.\n\n ==== Parameters\n node:: A reference to the Node object to be added.", "docstring_tokens": ["This", "is", "the", "constructor", "for", "the", "ContainerNode", "class", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L157-L163", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.<<", "original_string": "def <<(text)\n if !last.nil? and last.respond_to?(:text=)\n last.append(text)\n else\n self.store(TextNode.new(self, text))\n end\n end", "language": "ruby", "code": "def <<(text)\n if !last.nil? and last.respond_to?(:text=)\n last.append(text)\n else\n self.store(TextNode.new(self, text))\n end\n end", "code_tokens": ["def", "<<", "(", "text", ")", "if", "!", "last", ".", "nil?", "and", "last", ".", "respond_to?", "(", ":text=", ")", "last", ".", "append", "(", "text", ")", "else", "self", ".", "store", "(", "TextNode", ".", "new", "(", "self", ",", "text", ")", ")", "end", "end"], "docstring": "This is the constructor for the CommandNode class.\n\n ==== Parameters\n parent:: A reference to the node that owns the new node.\n prefix:: A String containing the prefix text for the command.\n suffix:: A String containing the suffix text for the command. Defaults\n to nil.\n split:: A boolean to indicate whether the prefix and suffix should\n be written to separate lines whether the node is converted\n to RTF. Defaults to true.\n wrap:: A boolean to indicate whether the prefix and suffix should\n be wrapped in curly braces. Defaults to true.\n This method adds text to a command node. If the last child node of the\n target node is a TextNode then the text is appended to that. Otherwise\n a new TextNode is created and append to the node.\n\n ==== Parameters\n text:: The String of text to be written to the node.", "docstring_tokens": ["This", "is", "the", "constructor", "for", "the", "CommandNode", "class", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L250-L256", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.to_rtf", "original_string": "def to_rtf\n text = StringIO.new\n\n text << '{' if wrap?\n text << @prefix if @prefix\n\n self.each do |entry|\n text << \"\\n\" if split?\n text << entry.to_rtf\n end\n\n text << \"\\n\" if split?\n text << @suffix if @suffix\n text << '}' if wrap?\n\n text.string\n end", "language": "ruby", "code": "def to_rtf\n text = StringIO.new\n\n text << '{' if wrap?\n text << @prefix if @prefix\n\n self.each do |entry|\n text << \"\\n\" if split?\n text << entry.to_rtf\n end\n\n text << \"\\n\" if split?\n text << @suffix if @suffix\n text << '}' if wrap?\n\n text.string\n end", "code_tokens": ["def", "to_rtf", "text", "=", "StringIO", ".", "new", "text", "<<", "'{'", "if", "wrap?", "text", "<<", "@prefix", "if", "@prefix", "self", ".", "each", "do", "|", "entry", "|", "text", "<<", "\"\\n\"", "if", "split?", "text", "<<", "entry", ".", "to_rtf", "end", "text", "<<", "\"\\n\"", "if", "split?", "text", "<<", "@suffix", "if", "@suffix", "text", "<<", "'}'", "if", "wrap?", "text", ".", "string", "end"], "docstring": "This method generates the RTF text for a CommandNode object.", "docstring_tokens": ["This", "method", "generates", "the", "RTF", "text", "for", "a", "CommandNode", "object", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L259-L275", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.paragraph", "original_string": "def paragraph(style=nil)\n node = ParagraphNode.new(self, style)\n yield node if block_given?\n self.store(node)\n end", "language": "ruby", "code": "def paragraph(style=nil)\n node = ParagraphNode.new(self, style)\n yield node if block_given?\n self.store(node)\n end", "code_tokens": ["def", "paragraph", "(", "style", "=", "nil", ")", "node", "=", "ParagraphNode", ".", "new", "(", "self", ",", "style", ")", "yield", "node", "if", "block_given?", "self", ".", "store", "(", "node", ")", "end"], "docstring": "This method provides a short cut means of creating a paragraph command\n node. The method accepts a block that will be passed a single parameter\n which will be a reference to the paragraph node created. After the\n block is complete the paragraph node is appended to the end of the child\n nodes on the object that the method is called against.\n\n ==== Parameters\n style:: A reference to a ParagraphStyle object that defines the style\n for the new paragraph. Defaults to nil to indicate that the\n currently applied paragraph styling should be used.", "docstring_tokens": ["This", "method", "provides", "a", "short", "cut", "means", "of", "creating", "a", "paragraph", "command", "node", ".", "The", "method", "accepts", "a", "block", "that", "will", "be", "passed", "a", "single", "parameter", "which", "will", "be", "a", "reference", "to", "the", "paragraph", "node", "created", ".", "After", "the", "block", "is", "complete", "the", "paragraph", "node", "is", "appended", "to", "the", "end", "of", "the", "child", "nodes", "on", "the", "object", "that", "the", "method", "is", "called", "against", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L287-L291", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.list", "original_string": "def list(kind=:bullets)\n node = ListNode.new(self)\n yield node.list(kind)\n self.store(node)\n end", "language": "ruby", "code": "def list(kind=:bullets)\n node = ListNode.new(self)\n yield node.list(kind)\n self.store(node)\n end", "code_tokens": ["def", "list", "(", "kind", "=", ":bullets", ")", "node", "=", "ListNode", ".", "new", "(", "self", ")", "yield", "node", ".", "list", "(", "kind", ")", "self", ".", "store", "(", "node", ")", "end"], "docstring": "This method provides a short cut means of creating a new ordered or\n unordered list. The method requires a block that will be passed a\n single parameter that'll be a reference to the first level of the\n list. See the +ListLevelNode+ doc for more information.\n\n Example usage:\n\n rtf.list do |level1|\n level1.item do |li|\n li << 'some text'\n li.apply(some_style) {|x| x << 'some styled text'}\n end\n\n level1.list(:decimal) do |level2|\n level2.item {|li| li << 'some other text in a decimal list'}\n level2.item {|li| li << 'and here we go'}\n end\n end", "docstring_tokens": ["This", "method", "provides", "a", "short", "cut", "means", "of", "creating", "a", "new", "ordered", "or", "unordered", "list", ".", "The", "method", "requires", "a", "block", "that", "will", "be", "passed", "a", "single", "parameter", "that", "ll", "be", "a", "reference", "to", "the", "first", "level", "of", "the", "list", ".", "See", "the", "+", "ListLevelNode", "+", "doc", "for", "more", "information", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L312-L316", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.footnote", "original_string": "def footnote(text)\n if !text.nil? and text != ''\n mark = CommandNode.new(self, '\\fs16\\up6\\chftn', nil, false)\n note = CommandNode.new(self, '\\footnote {\\fs16\\up6\\chftn}', nil, false)\n note.paragraph << text\n self.store(mark)\n self.store(note)\n end\n end", "language": "ruby", "code": "def footnote(text)\n if !text.nil? and text != ''\n mark = CommandNode.new(self, '\\fs16\\up6\\chftn', nil, false)\n note = CommandNode.new(self, '\\footnote {\\fs16\\up6\\chftn}', nil, false)\n note.paragraph << text\n self.store(mark)\n self.store(note)\n end\n end", "code_tokens": ["def", "footnote", "(", "text", ")", "if", "!", "text", ".", "nil?", "and", "text", "!=", "''", "mark", "=", "CommandNode", ".", "new", "(", "self", ",", "'\\fs16\\up6\\chftn'", ",", "nil", ",", "false", ")", "note", "=", "CommandNode", ".", "new", "(", "self", ",", "'\\footnote {\\fs16\\up6\\chftn}'", ",", "nil", ",", "false", ")", "note", ".", "paragraph", "<<", "text", "self", ".", "store", "(", "mark", ")", "self", ".", "store", "(", "note", ")", "end", "end"], "docstring": "This method inserts a footnote at the current position in a node.\n\n ==== Parameters\n text:: A string containing the text for the footnote.", "docstring_tokens": ["This", "method", "inserts", "a", "footnote", "at", "the", "current", "position", "in", "a", "node", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L337-L345", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.apply", "original_string": "def apply(style)\n # Check the input style.\n if !style.is_character_style?\n RTFError.fire(\"Non-character style specified to the \"\\\n \"CommandNode#apply() method.\")\n end\n\n # Store fonts and colours.\n root.colours << style.foreground unless style.foreground.nil?\n root.colours << style.background unless style.background.nil?\n root.fonts << style.font unless style.font.nil?\n\n # Generate the command node.\n node = CommandNode.new(self, style.prefix(root.fonts, root.colours))\n yield node if block_given?\n self.store(node)\n end", "language": "ruby", "code": "def apply(style)\n # Check the input style.\n if !style.is_character_style?\n RTFError.fire(\"Non-character style specified to the \"\\\n \"CommandNode#apply() method.\")\n end\n\n # Store fonts and colours.\n root.colours << style.foreground unless style.foreground.nil?\n root.colours << style.background unless style.background.nil?\n root.fonts << style.font unless style.font.nil?\n\n # Generate the command node.\n node = CommandNode.new(self, style.prefix(root.fonts, root.colours))\n yield node if block_given?\n self.store(node)\n end", "code_tokens": ["def", "apply", "(", "style", ")", "# Check the input style.", "if", "!", "style", ".", "is_character_style?", "RTFError", ".", "fire", "(", "\"Non-character style specified to the \"", "\"CommandNode#apply() method.\"", ")", "end", "# Store fonts and colours.", "root", ".", "colours", "<<", "style", ".", "foreground", "unless", "style", ".", "foreground", ".", "nil?", "root", ".", "colours", "<<", "style", ".", "background", "unless", "style", ".", "background", ".", "nil?", "root", ".", "fonts", "<<", "style", ".", "font", "unless", "style", ".", "font", ".", "nil?", "# Generate the command node.", "node", "=", "CommandNode", ".", "new", "(", "self", ",", "style", ".", "prefix", "(", "root", ".", "fonts", ",", "root", ".", "colours", ")", ")", "yield", "node", "if", "block_given?", "self", ".", "store", "(", "node", ")", "end"], "docstring": "This method provides a short cut means for applying multiple styles via\n single command node. The method accepts a block that will be passed a\n reference to the node created. Once the block is complete the new node\n will be append as the last child of the CommandNode the method is called\n on.\n\n ==== Parameters\n style:: A reference to a CharacterStyle object that contains the style\n settings to be applied.\n\n ==== Exceptions\n RTFError:: Generated whenever a non-character style is specified to\n the method.", "docstring_tokens": ["This", "method", "provides", "a", "short", "cut", "means", "for", "applying", "multiple", "styles", "via", "single", "command", "node", ".", "The", "method", "accepts", "a", "block", "that", "will", "be", "passed", "a", "reference", "to", "the", "node", "created", ".", "Once", "the", "block", "is", "complete", "the", "new", "node", "will", "be", "append", "as", "the", "last", "child", "of", "the", "CommandNode", "the", "method", "is", "called", "on", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L373-L389", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.bold", "original_string": "def bold\n style = CharacterStyle.new\n style.bold = true\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "language": "ruby", "code": "def bold\n style = CharacterStyle.new\n style.bold = true\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "code_tokens": ["def", "bold", "style", "=", "CharacterStyle", ".", "new", "style", ".", "bold", "=", "true", "if", "block_given?", "apply", "(", "style", ")", "{", "|", "node", "|", "yield", "node", "}", "else", "apply", "(", "style", ")", "end", "end"], "docstring": "This method provides a short cut means of creating a bold command node.\n The method accepts a block that will be passed a single parameter which\n will be a reference to the bold node created. After the block is\n complete the bold node is appended to the end of the child nodes on\n the object that the method is call against.", "docstring_tokens": ["This", "method", "provides", "a", "short", "cut", "means", "of", "creating", "a", "bold", "command", "node", ".", "The", "method", "accepts", "a", "block", "that", "will", "be", "passed", "a", "single", "parameter", "which", "will", "be", "a", "reference", "to", "the", "bold", "node", "created", ".", "After", "the", "block", "is", "complete", "the", "bold", "node", "is", "appended", "to", "the", "end", "of", "the", "child", "nodes", "on", "the", "object", "that", "the", "method", "is", "call", "against", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L396-L404", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.italic", "original_string": "def italic\n style = CharacterStyle.new\n style.italic = true\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "language": "ruby", "code": "def italic\n style = CharacterStyle.new\n style.italic = true\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "code_tokens": ["def", "italic", "style", "=", "CharacterStyle", ".", "new", "style", ".", "italic", "=", "true", "if", "block_given?", "apply", "(", "style", ")", "{", "|", "node", "|", "yield", "node", "}", "else", "apply", "(", "style", ")", "end", "end"], "docstring": "This method provides a short cut means of creating an italic command\n node. The method accepts a block that will be passed a single parameter\n which will be a reference to the italic node created. After the block is\n complete the italic node is appended to the end of the child nodes on\n the object that the method is call against.", "docstring_tokens": ["This", "method", "provides", "a", "short", "cut", "means", "of", "creating", "an", "italic", "command", "node", ".", "The", "method", "accepts", "a", "block", "that", "will", "be", "passed", "a", "single", "parameter", "which", "will", "be", "a", "reference", "to", "the", "italic", "node", "created", ".", "After", "the", "block", "is", "complete", "the", "italic", "node", "is", "appended", "to", "the", "end", "of", "the", "child", "nodes", "on", "the", "object", "that", "the", "method", "is", "call", "against", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L411-L419", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.underline", "original_string": "def underline\n style = CharacterStyle.new\n style.underline = true\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "language": "ruby", "code": "def underline\n style = CharacterStyle.new\n style.underline = true\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "code_tokens": ["def", "underline", "style", "=", "CharacterStyle", ".", "new", "style", ".", "underline", "=", "true", "if", "block_given?", "apply", "(", "style", ")", "{", "|", "node", "|", "yield", "node", "}", "else", "apply", "(", "style", ")", "end", "end"], "docstring": "This method provides a short cut means of creating an underline command\n node. The method accepts a block that will be passed a single parameter\n which will be a reference to the underline node created. After the block\n is complete the underline node is appended to the end of the child nodes\n on the object that the method is call against.", "docstring_tokens": ["This", "method", "provides", "a", "short", "cut", "means", "of", "creating", "an", "underline", "command", "node", ".", "The", "method", "accepts", "a", "block", "that", "will", "be", "passed", "a", "single", "parameter", "which", "will", "be", "a", "reference", "to", "the", "underline", "node", "created", ".", "After", "the", "block", "is", "complete", "the", "underline", "node", "is", "appended", "to", "the", "end", "of", "the", "child", "nodes", "on", "the", "object", "that", "the", "method", "is", "call", "against", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L426-L434", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.subscript", "original_string": "def subscript\n style = CharacterStyle.new\n style.subscript = true\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "language": "ruby", "code": "def subscript\n style = CharacterStyle.new\n style.subscript = true\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "code_tokens": ["def", "subscript", "style", "=", "CharacterStyle", ".", "new", "style", ".", "subscript", "=", "true", "if", "block_given?", "apply", "(", "style", ")", "{", "|", "node", "|", "yield", "node", "}", "else", "apply", "(", "style", ")", "end", "end"], "docstring": "This method provides a short cut means of creating a subscript command\n node. The method accepts a block that will be passed a single parameter\n which will be a reference to the subscript node created. After the\n block is complete the subscript node is appended to the end of the\n child nodes on the object that the method is call against.", "docstring_tokens": ["This", "method", "provides", "a", "short", "cut", "means", "of", "creating", "a", "subscript", "command", "node", ".", "The", "method", "accepts", "a", "block", "that", "will", "be", "passed", "a", "single", "parameter", "which", "will", "be", "a", "reference", "to", "the", "subscript", "node", "created", ".", "After", "the", "block", "is", "complete", "the", "subscript", "node", "is", "appended", "to", "the", "end", "of", "the", "child", "nodes", "on", "the", "object", "that", "the", "method", "is", "call", "against", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L441-L449", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.superscript", "original_string": "def superscript\n style = CharacterStyle.new\n style.superscript = true\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "language": "ruby", "code": "def superscript\n style = CharacterStyle.new\n style.superscript = true\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "code_tokens": ["def", "superscript", "style", "=", "CharacterStyle", ".", "new", "style", ".", "superscript", "=", "true", "if", "block_given?", "apply", "(", "style", ")", "{", "|", "node", "|", "yield", "node", "}", "else", "apply", "(", "style", ")", "end", "end"], "docstring": "This method provides a short cut means of creating a superscript command\n node. The method accepts a block that will be passed a single parameter\n which will be a reference to the superscript node created. After the\n block is complete the superscript node is appended to the end of the\n child nodes on the object that the method is call against.", "docstring_tokens": ["This", "method", "provides", "a", "short", "cut", "means", "of", "creating", "a", "superscript", "command", "node", ".", "The", "method", "accepts", "a", "block", "that", "will", "be", "passed", "a", "single", "parameter", "which", "will", "be", "a", "reference", "to", "the", "superscript", "node", "created", ".", "After", "the", "block", "is", "complete", "the", "superscript", "node", "is", "appended", "to", "the", "end", "of", "the", "child", "nodes", "on", "the", "object", "that", "the", "method", "is", "call", "against", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L456-L464", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.strike", "original_string": "def strike\n style = CharacterStyle.new\n style.strike = true\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "language": "ruby", "code": "def strike\n style = CharacterStyle.new\n style.strike = true\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "code_tokens": ["def", "strike", "style", "=", "CharacterStyle", ".", "new", "style", ".", "strike", "=", "true", "if", "block_given?", "apply", "(", "style", ")", "{", "|", "node", "|", "yield", "node", "}", "else", "apply", "(", "style", ")", "end", "end"], "docstring": "This method provides a short cut means of creating a strike command\n node. The method accepts a block that will be passed a single parameter\n which will be a reference to the strike node created. After the\n block is complete the strike node is appended to the end of the\n child nodes on the object that the method is call against.", "docstring_tokens": ["This", "method", "provides", "a", "short", "cut", "means", "of", "creating", "a", "strike", "command", "node", ".", "The", "method", "accepts", "a", "block", "that", "will", "be", "passed", "a", "single", "parameter", "which", "will", "be", "a", "reference", "to", "the", "strike", "node", "created", ".", "After", "the", "block", "is", "complete", "the", "strike", "node", "is", "appended", "to", "the", "end", "of", "the", "child", "nodes", "on", "the", "object", "that", "the", "method", "is", "call", "against", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L471-L479", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.font", "original_string": "def font(font, size=nil)\n style = CharacterStyle.new\n style.font = font\n style.font_size = size\n root.fonts << font\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "language": "ruby", "code": "def font(font, size=nil)\n style = CharacterStyle.new\n style.font = font\n style.font_size = size\n root.fonts << font\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "code_tokens": ["def", "font", "(", "font", ",", "size", "=", "nil", ")", "style", "=", "CharacterStyle", ".", "new", "style", ".", "font", "=", "font", "style", ".", "font_size", "=", "size", "root", ".", "fonts", "<<", "font", "if", "block_given?", "apply", "(", "style", ")", "{", "|", "node", "|", "yield", "node", "}", "else", "apply", "(", "style", ")", "end", "end"], "docstring": "This method provides a short cut means of creating a font command node.\n The method accepts a block that will be passed a single parameter which\n will be a reference to the font node created. After the block is\n complete the font node is appended to the end of the child nodes on the\n object that the method is called against.\n\n ==== Parameters\n font:: A reference to font object that represents the font to be used\n within the node.\n size:: An integer size setting for the font. Defaults to nil to\n indicate that the current font size should be used.", "docstring_tokens": ["This", "method", "provides", "a", "short", "cut", "means", "of", "creating", "a", "font", "command", "node", ".", "The", "method", "accepts", "a", "block", "that", "will", "be", "passed", "a", "single", "parameter", "which", "will", "be", "a", "reference", "to", "the", "font", "node", "created", ".", "After", "the", "block", "is", "complete", "the", "font", "node", "is", "appended", "to", "the", "end", "of", "the", "child", "nodes", "on", "the", "object", "that", "the", "method", "is", "called", "against", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L492-L502", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.foreground", "original_string": "def foreground(colour)\n style = CharacterStyle.new\n style.foreground = colour\n root.colours << colour\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "language": "ruby", "code": "def foreground(colour)\n style = CharacterStyle.new\n style.foreground = colour\n root.colours << colour\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "code_tokens": ["def", "foreground", "(", "colour", ")", "style", "=", "CharacterStyle", ".", "new", "style", ".", "foreground", "=", "colour", "root", ".", "colours", "<<", "colour", "if", "block_given?", "apply", "(", "style", ")", "{", "|", "node", "|", "yield", "node", "}", "else", "apply", "(", "style", ")", "end", "end"], "docstring": "This method provides a short cut means of creating a foreground colour\n command node. The method accepts a block that will be passed a single\n parameter which will be a reference to the foreground colour node\n created. After the block is complete the foreground colour node is\n appended to the end of the child nodes on the object that the method\n is called against.\n\n ==== Parameters\n colour:: The foreground colour to be applied by the command.", "docstring_tokens": ["This", "method", "provides", "a", "short", "cut", "means", "of", "creating", "a", "foreground", "colour", "command", "node", ".", "The", "method", "accepts", "a", "block", "that", "will", "be", "passed", "a", "single", "parameter", "which", "will", "be", "a", "reference", "to", "the", "foreground", "colour", "node", "created", ".", "After", "the", "block", "is", "complete", "the", "foreground", "colour", "node", "is", "appended", "to", "the", "end", "of", "the", "child", "nodes", "on", "the", "object", "that", "the", "method", "is", "called", "against", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L513-L522", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.colour", "original_string": "def colour(fore, back)\n style = CharacterStyle.new\n style.foreground = fore\n style.background = back\n root.colours << fore\n root.colours << back\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "language": "ruby", "code": "def colour(fore, back)\n style = CharacterStyle.new\n style.foreground = fore\n style.background = back\n root.colours << fore\n root.colours << back\n if block_given?\n apply(style) {|node| yield node}\n else\n apply(style)\n end\n end", "code_tokens": ["def", "colour", "(", "fore", ",", "back", ")", "style", "=", "CharacterStyle", ".", "new", "style", ".", "foreground", "=", "fore", "style", ".", "background", "=", "back", "root", ".", "colours", "<<", "fore", "root", ".", "colours", "<<", "back", "if", "block_given?", "apply", "(", "style", ")", "{", "|", "node", "|", "yield", "node", "}", "else", "apply", "(", "style", ")", "end", "end"], "docstring": "This method provides a short cut menas of creating a colour node that\n deals with foreground and background colours. The method accepts a\n block that will be passed a single parameter which will be a reference\n to the colour node created. After the block is complete the colour node\n is append to the end of the child nodes on the object that the method\n is called against.\n\n ==== Parameters\n fore:: The foreground colour to be applied by the command.\n back:: The background colour to be applied by the command.", "docstring_tokens": ["This", "method", "provides", "a", "short", "cut", "menas", "of", "creating", "a", "colour", "node", "that", "deals", "with", "foreground", "and", "background", "colours", ".", "The", "method", "accepts", "a", "block", "that", "will", "be", "passed", "a", "single", "parameter", "which", "will", "be", "a", "reference", "to", "the", "colour", "node", "created", ".", "After", "the", "block", "is", "complete", "the", "colour", "node", "is", "append", "to", "the", "end", "of", "the", "child", "nodes", "on", "the", "object", "that", "the", "method", "is", "called", "against", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L554-L565", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.CommandNode.table", "original_string": "def table(rows, columns, *widths)\n node = TableNode.new(self, rows, columns, *widths)\n yield node if block_given?\n store(node)\n node\n end", "language": "ruby", "code": "def table(rows, columns, *widths)\n node = TableNode.new(self, rows, columns, *widths)\n yield node if block_given?\n store(node)\n node\n end", "code_tokens": ["def", "table", "(", "rows", ",", "columns", ",", "*", "widths", ")", "node", "=", "TableNode", ".", "new", "(", "self", ",", "rows", ",", "columns", ",", "widths", ")", "yield", "node", "if", "block_given?", "store", "(", "node", ")", "node", "end"], "docstring": "This method creates a new table node and returns it. The method accepts\n a block that will be passed the table as a parameter. The node is added\n to the node the method is called upon after the block is complete.\n\n ==== Parameters\n rows:: The number of rows that the table contains.\n columns:: The number of columns that the table contains.\n *widths:: One or more integers representing the widths for the table\n columns.", "docstring_tokens": ["This", "method", "creates", "a", "new", "table", "node", "and", "returns", "it", ".", "The", "method", "accepts", "a", "block", "that", "will", "be", "passed", "the", "table", "as", "a", "parameter", ".", "The", "node", "is", "added", "to", "the", "node", "the", "method", "is", "called", "upon", "after", "the", "block", "is", "complete", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L576-L581", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.ListLevelNode.list", "original_string": "def list(kind=@kind)\n node = ListLevelNode.new(self, @template, kind, @level.level+1)\n yield node\n self.store(node)\n end", "language": "ruby", "code": "def list(kind=@kind)\n node = ListLevelNode.new(self, @template, kind, @level.level+1)\n yield node\n self.store(node)\n end", "code_tokens": ["def", "list", "(", "kind", "=", "@kind", ")", "node", "=", "ListLevelNode", ".", "new", "(", "self", ",", "@template", ",", "kind", ",", "@level", ".", "level", "+", "1", ")", "yield", "node", "self", ".", "store", "(", "node", ")", "end"], "docstring": "Creates a new +ListLevelNode+ to implement nested lists", "docstring_tokens": ["Creates", "a", "new", "+", "ListLevelNode", "+", "to", "implement", "nested", "lists"], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L664-L668", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.TableNode.column_shading_colour", "original_string": "def column_shading_colour(index, colour)\n self.each do |row|\n cell = row[index]\n cell.shading_colour = colour if cell != nil\n end\n end", "language": "ruby", "code": "def column_shading_colour(index, colour)\n self.each do |row|\n cell = row[index]\n cell.shading_colour = colour if cell != nil\n end\n end", "code_tokens": ["def", "column_shading_colour", "(", "index", ",", "colour", ")", "self", ".", "each", "do", "|", "row", "|", "cell", "=", "row", "[", "index", "]", "cell", ".", "shading_colour", "=", "colour", "if", "cell", "!=", "nil", "end", "end"], "docstring": "This method assigns a shading colour to a specified column within a\n TableNode object.\n\n ==== Parameters\n index:: The offset from the first column of the column to have shading\n applied to it.\n colour:: A reference to a Colour object representing the shading colour\n to be used. Set to nil to clear shading.", "docstring_tokens": ["This", "method", "assigns", "a", "shading", "colour", "to", "a", "specified", "column", "within", "a", "TableNode", "object", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L776-L781", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.TableNode.shading_colour", "original_string": "def shading_colour(colour)\n if block_given?\n 0.upto(self.size - 1) do |x|\n row = self[x]\n 0.upto(row.size - 1) do |y|\n apply = yield row[y], x, y\n row[y].shading_colour = colour if apply\n end\n end\n end\n end", "language": "ruby", "code": "def shading_colour(colour)\n if block_given?\n 0.upto(self.size - 1) do |x|\n row = self[x]\n 0.upto(row.size - 1) do |y|\n apply = yield row[y], x, y\n row[y].shading_colour = colour if apply\n end\n end\n end\n end", "code_tokens": ["def", "shading_colour", "(", "colour", ")", "if", "block_given?", "0", ".", "upto", "(", "self", ".", "size", "-", "1", ")", "do", "|", "x", "|", "row", "=", "self", "[", "x", "]", "0", ".", "upto", "(", "row", ".", "size", "-", "1", ")", "do", "|", "y", "|", "apply", "=", "yield", "row", "[", "y", "]", ",", "x", ",", "y", "row", "[", "y", "]", ".", "shading_colour", "=", "colour", "if", "apply", "end", "end", "end", "end"], "docstring": "This method provides a means of assigning a shading colour to a\n selection of cells within a table. The method accepts a block that\n takes three parameters - a TableCellNode representing a cell within the\n table, an integer representing the x offset of the cell and an integer\n representing the y offset of the cell. If the block returns true then\n shading will be applied to the cell.\n\n ==== Parameters\n colour:: A reference to a Colour object representing the shading colour\n to be applied. Set to nil to remove shading.", "docstring_tokens": ["This", "method", "provides", "a", "means", "of", "assigning", "a", "shading", "colour", "to", "a", "selection", "of", "cells", "within", "a", "table", ".", "The", "method", "accepts", "a", "block", "that", "takes", "three", "parameters", "-", "a", "TableCellNode", "representing", "a", "cell", "within", "the", "table", "an", "integer", "representing", "the", "x", "offset", "of", "the", "cell", "and", "an", "integer", "representing", "the", "y", "offset", "of", "the", "cell", ".", "If", "the", "block", "returns", "true", "then", "shading", "will", "be", "applied", "to", "the", "cell", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L793-L803", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.TableRowNode.to_rtf", "original_string": "def to_rtf\n text = StringIO.new\n temp = StringIO.new\n offset = 0\n\n text << \"\\\\trowd\\\\tgraph#{parent.cell_margin}\"\n self.each do |entry|\n widths = entry.border_widths\n colour = entry.shading_colour\n\n text << \"\\n\"\n text << \"\\\\clbrdrt\\\\brdrw#{widths[0]}\\\\brdrs\" if widths[0] != 0\n text << \"\\\\clbrdrl\\\\brdrw#{widths[3]}\\\\brdrs\" if widths[3] != 0\n text << \"\\\\clbrdrb\\\\brdrw#{widths[2]}\\\\brdrs\" if widths[2] != 0\n text << \"\\\\clbrdrr\\\\brdrw#{widths[1]}\\\\brdrs\" if widths[1] != 0\n text << \"\\\\clcbpat#{root.colours.index(colour)}\" if colour != nil\n text << \"\\\\cellx#{entry.width + offset}\"\n temp << \"\\n#{entry.to_rtf}\"\n offset += entry.width\n end\n text << \"#{temp.string}\\n\\\\row\"\n\n text.string\n end", "language": "ruby", "code": "def to_rtf\n text = StringIO.new\n temp = StringIO.new\n offset = 0\n\n text << \"\\\\trowd\\\\tgraph#{parent.cell_margin}\"\n self.each do |entry|\n widths = entry.border_widths\n colour = entry.shading_colour\n\n text << \"\\n\"\n text << \"\\\\clbrdrt\\\\brdrw#{widths[0]}\\\\brdrs\" if widths[0] != 0\n text << \"\\\\clbrdrl\\\\brdrw#{widths[3]}\\\\brdrs\" if widths[3] != 0\n text << \"\\\\clbrdrb\\\\brdrw#{widths[2]}\\\\brdrs\" if widths[2] != 0\n text << \"\\\\clbrdrr\\\\brdrw#{widths[1]}\\\\brdrs\" if widths[1] != 0\n text << \"\\\\clcbpat#{root.colours.index(colour)}\" if colour != nil\n text << \"\\\\cellx#{entry.width + offset}\"\n temp << \"\\n#{entry.to_rtf}\"\n offset += entry.width\n end\n text << \"#{temp.string}\\n\\\\row\"\n\n text.string\n end", "code_tokens": ["def", "to_rtf", "text", "=", "StringIO", ".", "new", "temp", "=", "StringIO", ".", "new", "offset", "=", "0", "text", "<<", "\"\\\\trowd\\\\tgraph#{parent.cell_margin}\"", "self", ".", "each", "do", "|", "entry", "|", "widths", "=", "entry", ".", "border_widths", "colour", "=", "entry", ".", "shading_colour", "text", "<<", "\"\\n\"", "text", "<<", "\"\\\\clbrdrt\\\\brdrw#{widths[0]}\\\\brdrs\"", "if", "widths", "[", "0", "]", "!=", "0", "text", "<<", "\"\\\\clbrdrl\\\\brdrw#{widths[3]}\\\\brdrs\"", "if", "widths", "[", "3", "]", "!=", "0", "text", "<<", "\"\\\\clbrdrb\\\\brdrw#{widths[2]}\\\\brdrs\"", "if", "widths", "[", "2", "]", "!=", "0", "text", "<<", "\"\\\\clbrdrr\\\\brdrw#{widths[1]}\\\\brdrs\"", "if", "widths", "[", "1", "]", "!=", "0", "text", "<<", "\"\\\\clcbpat#{root.colours.index(colour)}\"", "if", "colour", "!=", "nil", "text", "<<", "\"\\\\cellx#{entry.width + offset}\"", "temp", "<<", "\"\\n#{entry.to_rtf}\"", "offset", "+=", "entry", ".", "width", "end", "text", "<<", "\"#{temp.string}\\n\\\\row\"", "text", ".", "string", "end"], "docstring": "This method overloads the store method inherited from the ContainerNode\n class to forbid addition of further nodes.\n\n ==== Parameters\n node:: A reference to the node to be added.\ndef store(node)\n RTFError.fire(\"Table row nodes cannot have nodes added to.\")\nend\n This method generates the RTF document text for a TableCellNode object.", "docstring_tokens": ["This", "method", "overloads", "the", "store", "method", "inherited", "from", "the", "ContainerNode", "class", "to", "forbid", "addition", "of", "further", "nodes", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L902-L925", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.TableCellNode.border_width=", "original_string": "def border_width=(width)\n size = width.nil? ? 0 : width\n if size > 0\n @borders[TOP] = @borders[RIGHT] = @borders[BOTTOM] = @borders[LEFT] = size.to_i\n else\n @borders = [nil, nil, nil, nil]\n end\n end", "language": "ruby", "code": "def border_width=(width)\n size = width.nil? ? 0 : width\n if size > 0\n @borders[TOP] = @borders[RIGHT] = @borders[BOTTOM] = @borders[LEFT] = size.to_i\n else\n @borders = [nil, nil, nil, nil]\n end\n end", "code_tokens": ["def", "border_width", "=", "(", "width", ")", "size", "=", "width", ".", "nil?", "?", "0", ":", "width", "if", "size", ">", "0", "@borders", "[", "TOP", "]", "=", "@borders", "[", "RIGHT", "]", "=", "@borders", "[", "BOTTOM", "]", "=", "@borders", "[", "LEFT", "]", "=", "size", ".", "to_i", "else", "@borders", "=", "[", "nil", ",", "nil", ",", "nil", ",", "nil", "]", "end", "end"], "docstring": "This method assigns a width, in twips, for the borders on all sides of\n the cell. Negative widths will be ignored and a width of zero will\n switch the border off.\n\n ==== Parameters\n width:: The setting for the width of the border.", "docstring_tokens": ["This", "method", "assigns", "a", "width", "in", "twips", "for", "the", "borders", "on", "all", "sides", "of", "the", "cell", ".", "Negative", "widths", "will", "be", "ignored", "and", "a", "width", "of", "zero", "will", "switch", "the", "border", "off", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1005-L1012", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.TableCellNode.top_border_width=", "original_string": "def top_border_width=(width)\n size = width.nil? ? 0 : width\n if size > 0\n @borders[TOP] = size.to_i\n else\n @borders[TOP] = nil\n end\n end", "language": "ruby", "code": "def top_border_width=(width)\n size = width.nil? ? 0 : width\n if size > 0\n @borders[TOP] = size.to_i\n else\n @borders[TOP] = nil\n end\n end", "code_tokens": ["def", "top_border_width", "=", "(", "width", ")", "size", "=", "width", ".", "nil?", "?", "0", ":", "width", "if", "size", ">", "0", "@borders", "[", "TOP", "]", "=", "size", ".", "to_i", "else", "@borders", "[", "TOP", "]", "=", "nil", "end", "end"], "docstring": "This method assigns a border width to the top side of a table cell.\n Negative values are ignored and a value of 0 switches the border off.\n\n ==== Parameters\n width:: The new border width setting.", "docstring_tokens": ["This", "method", "assigns", "a", "border", "width", "to", "the", "top", "side", "of", "a", "table", "cell", ".", "Negative", "values", "are", "ignored", "and", "a", "value", "of", "0", "switches", "the", "border", "off", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1019-L1026", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.TableCellNode.right_border_width=", "original_string": "def right_border_width=(width)\n size = width.nil? ? 0 : width\n if size > 0\n @borders[RIGHT] = size.to_i\n else\n @borders[RIGHT] = nil\n end\n end", "language": "ruby", "code": "def right_border_width=(width)\n size = width.nil? ? 0 : width\n if size > 0\n @borders[RIGHT] = size.to_i\n else\n @borders[RIGHT] = nil\n end\n end", "code_tokens": ["def", "right_border_width", "=", "(", "width", ")", "size", "=", "width", ".", "nil?", "?", "0", ":", "width", "if", "size", ">", "0", "@borders", "[", "RIGHT", "]", "=", "size", ".", "to_i", "else", "@borders", "[", "RIGHT", "]", "=", "nil", "end", "end"], "docstring": "This method assigns a border width to the right side of a table cell.\n Negative values are ignored and a value of 0 switches the border off.\n\n ==== Parameters\n width:: The new border width setting.", "docstring_tokens": ["This", "method", "assigns", "a", "border", "width", "to", "the", "right", "side", "of", "a", "table", "cell", ".", "Negative", "values", "are", "ignored", "and", "a", "value", "of", "0", "switches", "the", "border", "off", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1033-L1040", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.TableCellNode.bottom_border_width=", "original_string": "def bottom_border_width=(width)\n size = width.nil? ? 0 : width\n if size > 0\n @borders[BOTTOM] = size.to_i\n else\n @borders[BOTTOM] = nil\n end\n end", "language": "ruby", "code": "def bottom_border_width=(width)\n size = width.nil? ? 0 : width\n if size > 0\n @borders[BOTTOM] = size.to_i\n else\n @borders[BOTTOM] = nil\n end\n end", "code_tokens": ["def", "bottom_border_width", "=", "(", "width", ")", "size", "=", "width", ".", "nil?", "?", "0", ":", "width", "if", "size", ">", "0", "@borders", "[", "BOTTOM", "]", "=", "size", ".", "to_i", "else", "@borders", "[", "BOTTOM", "]", "=", "nil", "end", "end"], "docstring": "This method assigns a border width to the bottom side of a table cell.\n Negative values are ignored and a value of 0 switches the border off.\n\n ==== Parameters\n width:: The new border width setting.", "docstring_tokens": ["This", "method", "assigns", "a", "border", "width", "to", "the", "bottom", "side", "of", "a", "table", "cell", ".", "Negative", "values", "are", "ignored", "and", "a", "value", "of", "0", "switches", "the", "border", "off", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1047-L1054", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.TableCellNode.left_border_width=", "original_string": "def left_border_width=(width)\n size = width.nil? ? 0 : width\n if size > 0\n @borders[LEFT] = size.to_i\n else\n @borders[LEFT] = nil\n end\n end", "language": "ruby", "code": "def left_border_width=(width)\n size = width.nil? ? 0 : width\n if size > 0\n @borders[LEFT] = size.to_i\n else\n @borders[LEFT] = nil\n end\n end", "code_tokens": ["def", "left_border_width", "=", "(", "width", ")", "size", "=", "width", ".", "nil?", "?", "0", ":", "width", "if", "size", ">", "0", "@borders", "[", "LEFT", "]", "=", "size", ".", "to_i", "else", "@borders", "[", "LEFT", "]", "=", "nil", "end", "end"], "docstring": "This method assigns a border width to the left side of a table cell.\n Negative values are ignored and a value of 0 switches the border off.\n\n ==== Parameters\n width:: The new border width setting.", "docstring_tokens": ["This", "method", "assigns", "a", "border", "width", "to", "the", "left", "side", "of", "a", "table", "cell", ".", "Negative", "values", "are", "ignored", "and", "a", "value", "of", "0", "switches", "the", "border", "off", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1061-L1068", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.TableCellNode.border_widths", "original_string": "def border_widths\n widths = []\n @borders.each {|entry| widths.push(entry.nil? ? 0 : entry)}\n widths\n end", "language": "ruby", "code": "def border_widths\n widths = []\n @borders.each {|entry| widths.push(entry.nil? ? 0 : entry)}\n widths\n end", "code_tokens": ["def", "border_widths", "widths", "=", "[", "]", "@borders", ".", "each", "{", "|", "entry", "|", "widths", ".", "push", "(", "entry", ".", "nil?", "?", "0", ":", "entry", ")", "}", "widths", "end"], "docstring": "This method retrieves an array with the cell border width settings.\n The values are inserted in top, right, bottom, left order.", "docstring_tokens": ["This", "method", "retrieves", "an", "array", "with", "the", "cell", "border", "width", "settings", ".", "The", "values", "are", "inserted", "in", "top", "right", "bottom", "left", "order", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1083-L1087", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.ImageNode.get_file_type", "original_string": "def get_file_type\n type = nil\n read = []\n open_file do |file|\n\n # Check if the file is a JPEG.\n read_source(file, read, 2)\n if read[0,2] == [255, 216]\n type = JPEG\n else\n # Check if it's a PNG.\n read_source(file, read, 6)\n if read[0,8] == [137, 80, 78, 71, 13, 10, 26, 10]\n type = PNG\n else\n # Check if its a bitmap.\n if read[0,2] == [66, 77]\n size = to_integer(read[2,4])\n type = BITMAP if size == File.size(@source)\n end\n end\n end\n\n end\n\n type\n end", "language": "ruby", "code": "def get_file_type\n type = nil\n read = []\n open_file do |file|\n\n # Check if the file is a JPEG.\n read_source(file, read, 2)\n if read[0,2] == [255, 216]\n type = JPEG\n else\n # Check if it's a PNG.\n read_source(file, read, 6)\n if read[0,8] == [137, 80, 78, 71, 13, 10, 26, 10]\n type = PNG\n else\n # Check if its a bitmap.\n if read[0,2] == [66, 77]\n size = to_integer(read[2,4])\n type = BITMAP if size == File.size(@source)\n end\n end\n end\n\n end\n\n type\n end", "code_tokens": ["def", "get_file_type", "type", "=", "nil", "read", "=", "[", "]", "open_file", "do", "|", "file", "|", "# Check if the file is a JPEG.", "read_source", "(", "file", ",", "read", ",", "2", ")", "if", "read", "[", "0", ",", "2", "]", "==", "[", "255", ",", "216", "]", "type", "=", "JPEG", "else", "# Check if it's a PNG.", "read_source", "(", "file", ",", "read", ",", "6", ")", "if", "read", "[", "0", ",", "8", "]", "==", "[", "137", ",", "80", ",", "78", ",", "71", ",", "13", ",", "10", ",", "26", ",", "10", "]", "type", "=", "PNG", "else", "# Check if its a bitmap.", "if", "read", "[", "0", ",", "2", "]", "==", "[", "66", ",", "77", "]", "size", "=", "to_integer", "(", "read", "[", "2", ",", "4", "]", ")", "type", "=", "BITMAP", "if", "size", "==", "File", ".", "size", "(", "@source", ")", "end", "end", "end", "end", "type", "end"], "docstring": "This method attempts to determine the image type associated with a\n file, returning nil if it fails to make the determination.", "docstring_tokens": ["This", "method", "attempts", "to", "determine", "the", "image", "type", "associated", "with", "a", "file", "returning", "nil", "if", "it", "fails", "to", "make", "the", "determination", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1345-L1371", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.ImageNode.to_rtf", "original_string": "def to_rtf\n text = StringIO.new\n count = 0\n \n #text << '{\\pard{\\*\\shppict{\\pict'\n text << '{\\*\\shppict{\\pict'\n text << \"\\\\picscalex#{@x_scaling}\" if @x_scaling != nil\n text << \"\\\\picscaley#{@y_scaling}\" if @y_scaling != nil\n text << \"\\\\piccropl#{@left_crop}\" if @left_crop != nil\n text << \"\\\\piccropr#{@right_crop}\" if @right_crop != nil\n text << \"\\\\piccropt#{@top_crop}\" if @top_crop != nil\n text << \"\\\\piccropb#{@bottom_crop}\" if @bottom_crop != nil\n text << \"\\\\picwgoal#{@displayed_width}\" if @displayed_width != nil\n text << \"\\\\pichgoal#{@displayed_height}\" if @displayed_height != nil \n text << \"\\\\picw#{@width}\\\\pich#{@height}\\\\bliptag#{@id}\"\n text << \"\\\\#{@type.id2name}\\n\"\n \n open_file do |file|\n file.each_byte do |byte|\n hex_str = byte.to_s(16)\n hex_str.insert(0,'0') if hex_str.length == 1\n text << hex_str \n count += 1\n if count == 40\n text << \"\\n\"\n count = 0\n end\n end\n end\n #text << \"\\n}}\\\\par}\"\n text << \"\\n}}\"\n\n text.string\n end", "language": "ruby", "code": "def to_rtf\n text = StringIO.new\n count = 0\n \n #text << '{\\pard{\\*\\shppict{\\pict'\n text << '{\\*\\shppict{\\pict'\n text << \"\\\\picscalex#{@x_scaling}\" if @x_scaling != nil\n text << \"\\\\picscaley#{@y_scaling}\" if @y_scaling != nil\n text << \"\\\\piccropl#{@left_crop}\" if @left_crop != nil\n text << \"\\\\piccropr#{@right_crop}\" if @right_crop != nil\n text << \"\\\\piccropt#{@top_crop}\" if @top_crop != nil\n text << \"\\\\piccropb#{@bottom_crop}\" if @bottom_crop != nil\n text << \"\\\\picwgoal#{@displayed_width}\" if @displayed_width != nil\n text << \"\\\\pichgoal#{@displayed_height}\" if @displayed_height != nil \n text << \"\\\\picw#{@width}\\\\pich#{@height}\\\\bliptag#{@id}\"\n text << \"\\\\#{@type.id2name}\\n\"\n \n open_file do |file|\n file.each_byte do |byte|\n hex_str = byte.to_s(16)\n hex_str.insert(0,'0') if hex_str.length == 1\n text << hex_str \n count += 1\n if count == 40\n text << \"\\n\"\n count = 0\n end\n end\n end\n #text << \"\\n}}\\\\par}\"\n text << \"\\n}}\"\n\n text.string\n end", "code_tokens": ["def", "to_rtf", "text", "=", "StringIO", ".", "new", "count", "=", "0", "#text << '{\\pard{\\*\\shppict{\\pict'", "text", "<<", "'{\\*\\shppict{\\pict'", "text", "<<", "\"\\\\picscalex#{@x_scaling}\"", "if", "@x_scaling", "!=", "nil", "text", "<<", "\"\\\\picscaley#{@y_scaling}\"", "if", "@y_scaling", "!=", "nil", "text", "<<", "\"\\\\piccropl#{@left_crop}\"", "if", "@left_crop", "!=", "nil", "text", "<<", "\"\\\\piccropr#{@right_crop}\"", "if", "@right_crop", "!=", "nil", "text", "<<", "\"\\\\piccropt#{@top_crop}\"", "if", "@top_crop", "!=", "nil", "text", "<<", "\"\\\\piccropb#{@bottom_crop}\"", "if", "@bottom_crop", "!=", "nil", "text", "<<", "\"\\\\picwgoal#{@displayed_width}\"", "if", "@displayed_width", "!=", "nil", "text", "<<", "\"\\\\pichgoal#{@displayed_height}\"", "if", "@displayed_height", "!=", "nil", "text", "<<", "\"\\\\picw#{@width}\\\\pich#{@height}\\\\bliptag#{@id}\"", "text", "<<", "\"\\\\#{@type.id2name}\\n\"", "open_file", "do", "|", "file", "|", "file", ".", "each_byte", "do", "|", "byte", "|", "hex_str", "=", "byte", ".", "to_s", "(", "16", ")", "hex_str", ".", "insert", "(", "0", ",", "'0'", ")", "if", "hex_str", ".", "length", "==", "1", "text", "<<", "hex_str", "count", "+=", "1", "if", "count", "==", "40", "text", "<<", "\"\\n\"", "count", "=", "0", "end", "end", "end", "#text << \"\\n}}\\\\par}\"", "text", "<<", "\"\\n}}\"", "text", ".", "string", "end"], "docstring": "This method generates the RTF for an ImageNode object.", "docstring_tokens": ["This", "method", "generates", "the", "RTF", "for", "an", "ImageNode", "object", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1374-L1407", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.ImageNode.to_integer", "original_string": "def to_integer(array, signed=false)\n from = nil\n to = nil\n data = []\n\n if array.size == 2\n data.concat(get_endian == BIG_ENDIAN ? array.reverse : array)\n from = 'C2'\n to = signed ? 's' : 'S'\n else\n data.concat(get_endian == BIG_ENDIAN ? array[0,4].reverse : array)\n from = 'C4'\n to = signed ? 'l' : 'L'\n end\n data.pack(from).unpack(to)[0]\n end", "language": "ruby", "code": "def to_integer(array, signed=false)\n from = nil\n to = nil\n data = []\n\n if array.size == 2\n data.concat(get_endian == BIG_ENDIAN ? array.reverse : array)\n from = 'C2'\n to = signed ? 's' : 'S'\n else\n data.concat(get_endian == BIG_ENDIAN ? array[0,4].reverse : array)\n from = 'C4'\n to = signed ? 'l' : 'L'\n end\n data.pack(from).unpack(to)[0]\n end", "code_tokens": ["def", "to_integer", "(", "array", ",", "signed", "=", "false", ")", "from", "=", "nil", "to", "=", "nil", "data", "=", "[", "]", "if", "array", ".", "size", "==", "2", "data", ".", "concat", "(", "get_endian", "==", "BIG_ENDIAN", "?", "array", ".", "reverse", ":", "array", ")", "from", "=", "'C2'", "to", "=", "signed", "?", "'s'", ":", "'S'", "else", "data", ".", "concat", "(", "get_endian", "==", "BIG_ENDIAN", "?", "array", "[", "0", ",", "4", "]", ".", "reverse", ":", "array", ")", "from", "=", "'C4'", "to", "=", "signed", "?", "'l'", ":", "'L'", "end", "data", ".", "pack", "(", "from", ")", ".", "unpack", "(", "to", ")", "[", "0", "]", "end"], "docstring": "This method converts an array to an integer. The array must be either\n two or four bytes in length.\n\n ==== Parameters\n array:: A reference to the array containing the data to be converted.\n signed:: A boolean to indicate whether the value is signed. Defaults\n to false.", "docstring_tokens": ["This", "method", "converts", "an", "array", "to", "an", "integer", ".", "The", "array", "must", "be", "either", "two", "or", "four", "bytes", "in", "length", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1422-L1437", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.ImageNode.read_source", "original_string": "def read_source(file, read, size=nil)\n if block_given?\n done = false\n\n while !done and !file.eof?\n read << file.getbyte\n done = yield read[-1]\n end\n else\n if size != nil\n if size > 0\n total = 0\n while !file.eof? and total < size\n read << file.getbyte\n total += 1\n end\n end\n else\n file.each_byte {|byte| read << byte}\n end\n end\n end", "language": "ruby", "code": "def read_source(file, read, size=nil)\n if block_given?\n done = false\n\n while !done and !file.eof?\n read << file.getbyte\n done = yield read[-1]\n end\n else\n if size != nil\n if size > 0\n total = 0\n while !file.eof? and total < size\n read << file.getbyte\n total += 1\n end\n end\n else\n file.each_byte {|byte| read << byte}\n end\n end\n end", "code_tokens": ["def", "read_source", "(", "file", ",", "read", ",", "size", "=", "nil", ")", "if", "block_given?", "done", "=", "false", "while", "!", "done", "and", "!", "file", ".", "eof?", "read", "<<", "file", ".", "getbyte", "done", "=", "yield", "read", "[", "-", "1", "]", "end", "else", "if", "size", "!=", "nil", "if", "size", ">", "0", "total", "=", "0", "while", "!", "file", ".", "eof?", "and", "total", "<", "size", "read", "<<", "file", ".", "getbyte", "total", "+=", "1", "end", "end", "else", "file", ".", "each_byte", "{", "|", "byte", "|", "read", "<<", "byte", "}", "end", "end", "end"], "docstring": "This method loads the data for an image from its source. The method\n accepts two call approaches. If called without a block then the method\n considers the size parameter it is passed. If called with a block the\n method executes until the block returns true.\n\n ==== Parameters\n size:: The maximum number of bytes to be read from the file. Defaults\n to nil to indicate that the remainder of the file should be read\n in.", "docstring_tokens": ["This", "method", "loads", "the", "data", "for", "an", "image", "from", "its", "source", ".", "The", "method", "accepts", "two", "call", "approaches", ".", "If", "called", "without", "a", "block", "then", "the", "method", "considers", "the", "size", "parameter", "it", "is", "passed", ".", "If", "called", "with", "a", "block", "the", "method", "executes", "until", "the", "block", "returns", "true", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1448-L1469", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.ImageNode.get_dimensions", "original_string": "def get_dimensions\n dimensions = nil\n\n open_file do |file|\n file.pos = DIMENSIONS_OFFSET[@type]\n read = []\n\n # Check the image type.\n if @type == JPEG\n # Read until we can't anymore or we've found what we're looking for.\n done = false\n while !file.eof? and !done\n # Read to the next marker.\n read_source(file,read) {|c| c == 0xff} # Read to the marker.\n read_source(file,read) {|c| c != 0xff} # Skip any padding.\n\n if read[-1] >= 0xc0 && read[-1] <= 0xc3\n # Read in the width and height details.\n read_source(file, read, 7)\n dimensions = read[-4,4].pack('C4').unpack('nn').reverse\n done = true\n else\n # Skip the marker block.\n read_source(file, read, 2)\n read_source(file, read, read[-2,2].pack('C2').unpack('n')[0] - 2)\n end\n end\n elsif @type == PNG\n # Read in the data to contain the width and height.\n read_source(file, read, 16)\n dimensions = read[-8,8].pack('C8').unpack('N2')\n elsif @type == BITMAP\n # Read in the data to contain the width and height.\n read_source(file, read, 18)\n dimensions = [to_integer(read[-8,4]), to_integer(read[-4,4])]\n end\n end\n\n dimensions\n end", "language": "ruby", "code": "def get_dimensions\n dimensions = nil\n\n open_file do |file|\n file.pos = DIMENSIONS_OFFSET[@type]\n read = []\n\n # Check the image type.\n if @type == JPEG\n # Read until we can't anymore or we've found what we're looking for.\n done = false\n while !file.eof? and !done\n # Read to the next marker.\n read_source(file,read) {|c| c == 0xff} # Read to the marker.\n read_source(file,read) {|c| c != 0xff} # Skip any padding.\n\n if read[-1] >= 0xc0 && read[-1] <= 0xc3\n # Read in the width and height details.\n read_source(file, read, 7)\n dimensions = read[-4,4].pack('C4').unpack('nn').reverse\n done = true\n else\n # Skip the marker block.\n read_source(file, read, 2)\n read_source(file, read, read[-2,2].pack('C2').unpack('n')[0] - 2)\n end\n end\n elsif @type == PNG\n # Read in the data to contain the width and height.\n read_source(file, read, 16)\n dimensions = read[-8,8].pack('C8').unpack('N2')\n elsif @type == BITMAP\n # Read in the data to contain the width and height.\n read_source(file, read, 18)\n dimensions = [to_integer(read[-8,4]), to_integer(read[-4,4])]\n end\n end\n\n dimensions\n end", "code_tokens": ["def", "get_dimensions", "dimensions", "=", "nil", "open_file", "do", "|", "file", "|", "file", ".", "pos", "=", "DIMENSIONS_OFFSET", "[", "@type", "]", "read", "=", "[", "]", "# Check the image type.", "if", "@type", "==", "JPEG", "# Read until we can't anymore or we've found what we're looking for.", "done", "=", "false", "while", "!", "file", ".", "eof?", "and", "!", "done", "# Read to the next marker.", "read_source", "(", "file", ",", "read", ")", "{", "|", "c", "|", "c", "==", "0xff", "}", "# Read to the marker.", "read_source", "(", "file", ",", "read", ")", "{", "|", "c", "|", "c", "!=", "0xff", "}", "# Skip any padding.", "if", "read", "[", "-", "1", "]", ">=", "0xc0", "&&", "read", "[", "-", "1", "]", "<=", "0xc3", "# Read in the width and height details.", "read_source", "(", "file", ",", "read", ",", "7", ")", "dimensions", "=", "read", "[", "-", "4", ",", "4", "]", ".", "pack", "(", "'C4'", ")", ".", "unpack", "(", "'nn'", ")", ".", "reverse", "done", "=", "true", "else", "# Skip the marker block.", "read_source", "(", "file", ",", "read", ",", "2", ")", "read_source", "(", "file", ",", "read", ",", "read", "[", "-", "2", ",", "2", "]", ".", "pack", "(", "'C2'", ")", ".", "unpack", "(", "'n'", ")", "[", "0", "]", "-", "2", ")", "end", "end", "elsif", "@type", "==", "PNG", "# Read in the data to contain the width and height.", "read_source", "(", "file", ",", "read", ",", "16", ")", "dimensions", "=", "read", "[", "-", "8", ",", "8", "]", ".", "pack", "(", "'C8'", ")", ".", "unpack", "(", "'N2'", ")", "elsif", "@type", "==", "BITMAP", "# Read in the data to contain the width and height.", "read_source", "(", "file", ",", "read", ",", "18", ")", "dimensions", "=", "[", "to_integer", "(", "read", "[", "-", "8", ",", "4", "]", ")", ",", "to_integer", "(", "read", "[", "-", "4", ",", "4", "]", ")", "]", "end", "end", "dimensions", "end"], "docstring": "This method fetches details of the dimensions associated with an image.", "docstring_tokens": ["This", "method", "fetches", "details", "of", "the", "dimensions", "associated", "with", "an", "image", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1473-L1512", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.Document.header=", "original_string": "def header=(header)\n if header.type == HeaderNode::UNIVERSAL\n @headers[0] = header\n elsif header.type == HeaderNode::LEFT_PAGE\n @headers[1] = header\n elsif header.type == HeaderNode::RIGHT_PAGE\n @headers[2] = header\n elsif header.type == HeaderNode::FIRST_PAGE\n @headers[3] = header\n end\n end", "language": "ruby", "code": "def header=(header)\n if header.type == HeaderNode::UNIVERSAL\n @headers[0] = header\n elsif header.type == HeaderNode::LEFT_PAGE\n @headers[1] = header\n elsif header.type == HeaderNode::RIGHT_PAGE\n @headers[2] = header\n elsif header.type == HeaderNode::FIRST_PAGE\n @headers[3] = header\n end\n end", "code_tokens": ["def", "header", "=", "(", "header", ")", "if", "header", ".", "type", "==", "HeaderNode", "::", "UNIVERSAL", "@headers", "[", "0", "]", "=", "header", "elsif", "header", ".", "type", "==", "HeaderNode", "::", "LEFT_PAGE", "@headers", "[", "1", "]", "=", "header", "elsif", "header", ".", "type", "==", "HeaderNode", "::", "RIGHT_PAGE", "@headers", "[", "2", "]", "=", "header", "elsif", "header", ".", "type", "==", "HeaderNode", "::", "FIRST_PAGE", "@headers", "[", "3", "]", "=", "header", "end", "end"], "docstring": "This method assigns a new header to a document. A Document object can\n have up to four header - a default header, a header for left pages, a\n header for right pages and a header for the first page. The method\n checks the header type and stores it appropriately.\n\n ==== Parameters\n header:: A reference to the header object to be stored. Existing header\n objects are overwritten.", "docstring_tokens": ["This", "method", "assigns", "a", "new", "header", "to", "a", "document", ".", "A", "Document", "object", "can", "have", "up", "to", "four", "header", "-", "a", "default", "header", "a", "header", "for", "left", "pages", "a", "header", "for", "right", "pages", "and", "a", "header", "for", "the", "first", "page", ".", "The", "method", "checks", "the", "header", "type", "and", "stores", "it", "appropriately", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1719-L1729", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.Document.footer=", "original_string": "def footer=(footer)\n if footer.type == FooterNode::UNIVERSAL\n @footers[0] = footer\n elsif footer.type == FooterNode::LEFT_PAGE\n @footers[1] = footer\n elsif footer.type == FooterNode::RIGHT_PAGE\n @footers[2] = footer\n elsif footer.type == FooterNode::FIRST_PAGE\n @footers[3] = footer\n end\n end", "language": "ruby", "code": "def footer=(footer)\n if footer.type == FooterNode::UNIVERSAL\n @footers[0] = footer\n elsif footer.type == FooterNode::LEFT_PAGE\n @footers[1] = footer\n elsif footer.type == FooterNode::RIGHT_PAGE\n @footers[2] = footer\n elsif footer.type == FooterNode::FIRST_PAGE\n @footers[3] = footer\n end\n end", "code_tokens": ["def", "footer", "=", "(", "footer", ")", "if", "footer", ".", "type", "==", "FooterNode", "::", "UNIVERSAL", "@footers", "[", "0", "]", "=", "footer", "elsif", "footer", ".", "type", "==", "FooterNode", "::", "LEFT_PAGE", "@footers", "[", "1", "]", "=", "footer", "elsif", "footer", ".", "type", "==", "FooterNode", "::", "RIGHT_PAGE", "@footers", "[", "2", "]", "=", "footer", "elsif", "footer", ".", "type", "==", "FooterNode", "::", "FIRST_PAGE", "@footers", "[", "3", "]", "=", "footer", "end", "end"], "docstring": "This method assigns a new footer to a document. A Document object can\n have up to four footers - a default footer, a footer for left pages, a\n footer for right pages and a footer for the first page. The method\n checks the footer type and stores it appropriately.\n\n ==== Parameters\n footer:: A reference to the footer object to be stored. Existing footer\n objects are overwritten.", "docstring_tokens": ["This", "method", "assigns", "a", "new", "footer", "to", "a", "document", ".", "A", "Document", "object", "can", "have", "up", "to", "four", "footers", "-", "a", "default", "footer", "a", "footer", "for", "left", "pages", "a", "footer", "for", "right", "pages", "and", "a", "footer", "for", "the", "first", "page", ".", "The", "method", "checks", "the", "footer", "type", "and", "stores", "it", "appropriately", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1739-L1749", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.Document.header", "original_string": "def header(type=HeaderNode::UNIVERSAL)\n index = 0\n if type == HeaderNode::LEFT_PAGE\n index = 1\n elsif type == HeaderNode::RIGHT_PAGE\n index = 2\n elsif type == HeaderNode::FIRST_PAGE\n index = 3\n end\n @headers[index]\n end", "language": "ruby", "code": "def header(type=HeaderNode::UNIVERSAL)\n index = 0\n if type == HeaderNode::LEFT_PAGE\n index = 1\n elsif type == HeaderNode::RIGHT_PAGE\n index = 2\n elsif type == HeaderNode::FIRST_PAGE\n index = 3\n end\n @headers[index]\n end", "code_tokens": ["def", "header", "(", "type", "=", "HeaderNode", "::", "UNIVERSAL", ")", "index", "=", "0", "if", "type", "==", "HeaderNode", "::", "LEFT_PAGE", "index", "=", "1", "elsif", "type", "==", "HeaderNode", "::", "RIGHT_PAGE", "index", "=", "2", "elsif", "type", "==", "HeaderNode", "::", "FIRST_PAGE", "index", "=", "3", "end", "@headers", "[", "index", "]", "end"], "docstring": "This method fetches a header from a Document object.\n\n ==== Parameters\n type:: One of the header types defined in the header class. Defaults to\n HeaderNode::UNIVERSAL.", "docstring_tokens": ["This", "method", "fetches", "a", "header", "from", "a", "Document", "object", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1756-L1766", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.Document.footer", "original_string": "def footer(type=FooterNode::UNIVERSAL)\n index = 0\n if type == FooterNode::LEFT_PAGE\n index = 1\n elsif type == FooterNode::RIGHT_PAGE\n index = 2\n elsif type == FooterNode::FIRST_PAGE\n index = 3\n end\n @footers[index]\n end", "language": "ruby", "code": "def footer(type=FooterNode::UNIVERSAL)\n index = 0\n if type == FooterNode::LEFT_PAGE\n index = 1\n elsif type == FooterNode::RIGHT_PAGE\n index = 2\n elsif type == FooterNode::FIRST_PAGE\n index = 3\n end\n @footers[index]\n end", "code_tokens": ["def", "footer", "(", "type", "=", "FooterNode", "::", "UNIVERSAL", ")", "index", "=", "0", "if", "type", "==", "FooterNode", "::", "LEFT_PAGE", "index", "=", "1", "elsif", "type", "==", "FooterNode", "::", "RIGHT_PAGE", "index", "=", "2", "elsif", "type", "==", "FooterNode", "::", "FIRST_PAGE", "index", "=", "3", "end", "@footers", "[", "index", "]", "end"], "docstring": "This method fetches a footer from a Document object.\n\n ==== Parameters\n type:: One of the footer types defined in the footer class. Defaults to\n FooterNode::UNIVERSAL.", "docstring_tokens": ["This", "method", "fetches", "a", "footer", "from", "a", "Document", "object", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1773-L1783", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/node.rb", "func_name": "RTF.Document.to_rtf", "original_string": "def to_rtf\n text = StringIO.new\n\n text << \"{#{prefix}\\\\#{@character_set.id2name}\"\n text << \"\\\\deff#{@default_font}\"\n text << \"\\\\deflang#{@language}\" if !@language.nil?\n text << \"\\\\plain\\\\fs24\\\\fet1\"\n text << \"\\n#{@fonts.to_rtf}\"\n text << \"\\n#{@colours.to_rtf}\" if @colours.size > 0\n text << \"\\n#{@information.to_rtf}\"\n text << \"\\n#{@lists.to_rtf}\"\n if @headers.compact != []\n text << \"\\n#{@headers[3].to_rtf}\" if !@headers[3].nil?\n text << \"\\n#{@headers[2].to_rtf}\" if !@headers[2].nil?\n text << \"\\n#{@headers[1].to_rtf}\" if !@headers[1].nil?\n if @headers[1].nil? or @headers[2].nil?\n text << \"\\n#{@headers[0].to_rtf}\"\n end\n end\n if @footers.compact != []\n text << \"\\n#{@footers[3].to_rtf}\" if !@footers[3].nil?\n text << \"\\n#{@footers[2].to_rtf}\" if !@footers[2].nil?\n text << \"\\n#{@footers[1].to_rtf}\" if !@footers[1].nil?\n if @footers[1].nil? or @footers[2].nil?\n text << \"\\n#{@footers[0].to_rtf}\"\n end\n end\n text << \"\\n#{@style.prefix(self)}\" if !@style.nil?\n self.each {|entry| text << \"\\n#{entry.to_rtf}\"}\n text << \"\\n}\"\n\n text.string\n end", "language": "ruby", "code": "def to_rtf\n text = StringIO.new\n\n text << \"{#{prefix}\\\\#{@character_set.id2name}\"\n text << \"\\\\deff#{@default_font}\"\n text << \"\\\\deflang#{@language}\" if !@language.nil?\n text << \"\\\\plain\\\\fs24\\\\fet1\"\n text << \"\\n#{@fonts.to_rtf}\"\n text << \"\\n#{@colours.to_rtf}\" if @colours.size > 0\n text << \"\\n#{@information.to_rtf}\"\n text << \"\\n#{@lists.to_rtf}\"\n if @headers.compact != []\n text << \"\\n#{@headers[3].to_rtf}\" if !@headers[3].nil?\n text << \"\\n#{@headers[2].to_rtf}\" if !@headers[2].nil?\n text << \"\\n#{@headers[1].to_rtf}\" if !@headers[1].nil?\n if @headers[1].nil? or @headers[2].nil?\n text << \"\\n#{@headers[0].to_rtf}\"\n end\n end\n if @footers.compact != []\n text << \"\\n#{@footers[3].to_rtf}\" if !@footers[3].nil?\n text << \"\\n#{@footers[2].to_rtf}\" if !@footers[2].nil?\n text << \"\\n#{@footers[1].to_rtf}\" if !@footers[1].nil?\n if @footers[1].nil? or @footers[2].nil?\n text << \"\\n#{@footers[0].to_rtf}\"\n end\n end\n text << \"\\n#{@style.prefix(self)}\" if !@style.nil?\n self.each {|entry| text << \"\\n#{entry.to_rtf}\"}\n text << \"\\n}\"\n\n text.string\n end", "code_tokens": ["def", "to_rtf", "text", "=", "StringIO", ".", "new", "text", "<<", "\"{#{prefix}\\\\#{@character_set.id2name}\"", "text", "<<", "\"\\\\deff#{@default_font}\"", "text", "<<", "\"\\\\deflang#{@language}\"", "if", "!", "@language", ".", "nil?", "text", "<<", "\"\\\\plain\\\\fs24\\\\fet1\"", "text", "<<", "\"\\n#{@fonts.to_rtf}\"", "text", "<<", "\"\\n#{@colours.to_rtf}\"", "if", "@colours", ".", "size", ">", "0", "text", "<<", "\"\\n#{@information.to_rtf}\"", "text", "<<", "\"\\n#{@lists.to_rtf}\"", "if", "@headers", ".", "compact", "!=", "[", "]", "text", "<<", "\"\\n#{@headers[3].to_rtf}\"", "if", "!", "@headers", "[", "3", "]", ".", "nil?", "text", "<<", "\"\\n#{@headers[2].to_rtf}\"", "if", "!", "@headers", "[", "2", "]", ".", "nil?", "text", "<<", "\"\\n#{@headers[1].to_rtf}\"", "if", "!", "@headers", "[", "1", "]", ".", "nil?", "if", "@headers", "[", "1", "]", ".", "nil?", "or", "@headers", "[", "2", "]", ".", "nil?", "text", "<<", "\"\\n#{@headers[0].to_rtf}\"", "end", "end", "if", "@footers", ".", "compact", "!=", "[", "]", "text", "<<", "\"\\n#{@footers[3].to_rtf}\"", "if", "!", "@footers", "[", "3", "]", ".", "nil?", "text", "<<", "\"\\n#{@footers[2].to_rtf}\"", "if", "!", "@footers", "[", "2", "]", ".", "nil?", "text", "<<", "\"\\n#{@footers[1].to_rtf}\"", "if", "!", "@footers", "[", "1", "]", ".", "nil?", "if", "@footers", "[", "1", "]", ".", "nil?", "or", "@footers", "[", "2", "]", ".", "nil?", "text", "<<", "\"\\n#{@footers[0].to_rtf}\"", "end", "end", "text", "<<", "\"\\n#{@style.prefix(self)}\"", "if", "!", "@style", ".", "nil?", "self", ".", "each", "{", "|", "entry", "|", "text", "<<", "\"\\n#{entry.to_rtf}\"", "}", "text", "<<", "\"\\n}\"", "text", ".", "string", "end"], "docstring": "This method generates the RTF text for a Document object.", "docstring_tokens": ["This", "method", "generates", "the", "RTF", "text", "for", "a", "Document", "object", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/node.rb#L1831-L1863", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/colour.rb", "func_name": "RTF.ColourTable.add", "original_string": "def add(colour)\r\n if colour.instance_of?(Colour)\r\n @colours.push(colour) if @colours.index(colour).nil?\r\n end\r\n self\r\n end", "language": "ruby", "code": "def add(colour)\r\n if colour.instance_of?(Colour)\r\n @colours.push(colour) if @colours.index(colour).nil?\r\n end\r\n self\r\n end", "code_tokens": ["def", "add", "(", "colour", ")", "if", "colour", ".", "instance_of?", "(", "Colour", ")", "@colours", ".", "push", "(", "colour", ")", "if", "@colours", ".", "index", "(", "colour", ")", ".", "nil?", "end", "self", "end"], "docstring": "This method adds a new colour to a ColourTable object. If the colour\n already exists within the table or is not a Colour object then this\n method does nothing.\n\n ==== Parameters\n colour:: The colour to be added to the table.", "docstring_tokens": ["This", "method", "adds", "a", "new", "colour", "to", "a", "ColourTable", "object", ".", "If", "the", "colour", "already", "exists", "within", "the", "table", "or", "is", "not", "a", "Colour", "object", "then", "this", "method", "does", "nothing", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/colour.rb#L103-L108", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/colour.rb", "func_name": "RTF.ColourTable.to_s", "original_string": "def to_s(indent=0)\r\n prefix = indent > 0 ? ' ' * indent : ''\r\n text = StringIO.new\r\n\r\n text << \"#{prefix}Colour Table (#{@colours.size} colours)\"\r\n @colours.each {|colour| text << \"\\n#{prefix} #{colour}\"}\r\n\r\n text.string\r\n end", "language": "ruby", "code": "def to_s(indent=0)\r\n prefix = indent > 0 ? ' ' * indent : ''\r\n text = StringIO.new\r\n\r\n text << \"#{prefix}Colour Table (#{@colours.size} colours)\"\r\n @colours.each {|colour| text << \"\\n#{prefix} #{colour}\"}\r\n\r\n text.string\r\n end", "code_tokens": ["def", "to_s", "(", "indent", "=", "0", ")", "prefix", "=", "indent", ">", "0", "?", "' '", "*", "indent", ":", "''", "text", "=", "StringIO", ".", "new", "text", "<<", "\"#{prefix}Colour Table (#{@colours.size} colours)\"", "@colours", ".", "each", "{", "|", "colour", "|", "text", "<<", "\"\\n#{prefix} #{colour}\"", "}", "text", ".", "string", "end"], "docstring": "This method generates a textual description for a ColourTable object.\n\n ==== Parameters\n indent:: The number of spaces to prefix to the lines generated by the\n method. Defaults to zero.", "docstring_tokens": ["This", "method", "generates", "a", "textual", "description", "for", "a", "ColourTable", "object", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/colour.rb#L145-L153", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/information.rb", "func_name": "RTF.Information.created=", "original_string": "def created=(setting)\r\n if setting.instance_of?(Time)\r\n @created = setting\r\n else\r\n datetime = Date._parse(setting.to_s).values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :wday)\r\n if datetime == nil\r\n RTFError.fire(\"Invalid document creation date/time information \"\\\r\n \"specified.\")\r\n end\r\n @created = Time.local(datetime[0], datetime[1], datetime[2],\r\n datetime[3], datetime[4], datetime[5])\r\n end\r\n end", "language": "ruby", "code": "def created=(setting)\r\n if setting.instance_of?(Time)\r\n @created = setting\r\n else\r\n datetime = Date._parse(setting.to_s).values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :wday)\r\n if datetime == nil\r\n RTFError.fire(\"Invalid document creation date/time information \"\\\r\n \"specified.\")\r\n end\r\n @created = Time.local(datetime[0], datetime[1], datetime[2],\r\n datetime[3], datetime[4], datetime[5])\r\n end\r\n end", "code_tokens": ["def", "created", "=", "(", "setting", ")", "if", "setting", ".", "instance_of?", "(", "Time", ")", "@created", "=", "setting", "else", "datetime", "=", "Date", ".", "_parse", "(", "setting", ".", "to_s", ")", ".", "values_at", "(", ":year", ",", ":mon", ",", ":mday", ",", ":hour", ",", ":min", ",", ":sec", ",", ":zone", ",", ":wday", ")", "if", "datetime", "==", "nil", "RTFError", ".", "fire", "(", "\"Invalid document creation date/time information \"", "\"specified.\"", ")", "end", "@created", "=", "Time", ".", "local", "(", "datetime", "[", "0", "]", ",", "datetime", "[", "1", "]", ",", "datetime", "[", "2", "]", ",", "datetime", "[", "3", "]", ",", "datetime", "[", "4", "]", ",", "datetime", "[", "5", "]", ")", "end", "end"], "docstring": "This is the constructor for the Information class.\n\n ==== Parameters\n title:: A string containing the document title information. Defaults\n to nil.\n author:: A string containing the document author information.\n Defaults to nil.\n company:: A string containing the company name information. Defaults\n to nil.\n comments:: A string containing the information comments. Defaults to\n nil to indicate no comments.\n creation:: A Time object or a String that can be parsed into a Time\n object (using ParseDate) indicating the document creation\n date and time. Defaults to nil to indicate the current\n date and time.\n\n ==== Exceptions\n RTFError:: Generated whenever invalid creation date/time details are\n specified.\n This method provides the created attribute mutator for the Information\n class.\n\n ==== Parameters\n setting:: The new creation date/time setting for the object. This\n should be either a Time object or a string containing\n date/time details that can be parsed into a Time object\n (using the parsedate method).\n\n ==== Exceptions\n RTFError:: Generated whenever invalid creation date/time details are\n specified.", "docstring_tokens": ["This", "is", "the", "constructor", "for", "the", "Information", "class", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/information.rb#L54-L66", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/information.rb", "func_name": "RTF.Information.to_s", "original_string": "def to_s(indent=0)\r\n prefix = indent > 0 ? ' ' * indent : ''\r\n text = StringIO.new\r\n\r\n text << \"#{prefix}Information\"\r\n text << \"\\n#{prefix} Title: #{@title}\" unless @title.nil?\r\n text << \"\\n#{prefix} Author: #{@author}\" unless @author.nil?\r\n text << \"\\n#{prefix} Company: #{@company}\" unless @company.nil?\r\n text << \"\\n#{prefix} Comments: #{@comments}\" unless @comments.nil?\r\n text << \"\\n#{prefix} Created: #{@created}\" unless @created.nil?\r\n\r\n text.string\r\n end", "language": "ruby", "code": "def to_s(indent=0)\r\n prefix = indent > 0 ? ' ' * indent : ''\r\n text = StringIO.new\r\n\r\n text << \"#{prefix}Information\"\r\n text << \"\\n#{prefix} Title: #{@title}\" unless @title.nil?\r\n text << \"\\n#{prefix} Author: #{@author}\" unless @author.nil?\r\n text << \"\\n#{prefix} Company: #{@company}\" unless @company.nil?\r\n text << \"\\n#{prefix} Comments: #{@comments}\" unless @comments.nil?\r\n text << \"\\n#{prefix} Created: #{@created}\" unless @created.nil?\r\n\r\n text.string\r\n end", "code_tokens": ["def", "to_s", "(", "indent", "=", "0", ")", "prefix", "=", "indent", ">", "0", "?", "' '", "*", "indent", ":", "''", "text", "=", "StringIO", ".", "new", "text", "<<", "\"#{prefix}Information\"", "text", "<<", "\"\\n#{prefix} Title: #{@title}\"", "unless", "@title", ".", "nil?", "text", "<<", "\"\\n#{prefix} Author: #{@author}\"", "unless", "@author", ".", "nil?", "text", "<<", "\"\\n#{prefix} Company: #{@company}\"", "unless", "@company", ".", "nil?", "text", "<<", "\"\\n#{prefix} Comments: #{@comments}\"", "unless", "@comments", ".", "nil?", "text", "<<", "\"\\n#{prefix} Created: #{@created}\"", "unless", "@created", ".", "nil?", "text", ".", "string", "end"], "docstring": "This method creates a textual description for an Information object.\n\n ==== Parameters\n indent:: The number of spaces to prefix to the lines generated by the\n method. Defaults to zero.", "docstring_tokens": ["This", "method", "creates", "a", "textual", "description", "for", "an", "Information", "object", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/information.rb#L73-L85", "partition": "valid"} {"repo": "thechrisoshow/rtf", "path": "lib/rtf/information.rb", "func_name": "RTF.Information.to_rtf", "original_string": "def to_rtf(indent=0)\r\n prefix = indent > 0 ? ' ' * indent : ''\r\n text = StringIO.new\r\n\r\n text << \"#{prefix}{\\\\info\"\r\n text << \"\\n#{prefix}{\\\\title #{@title}}\" unless @title.nil?\r\n text << \"\\n#{prefix}{\\\\author #{@author}}\" unless @author.nil?\r\n text << \"\\n#{prefix}{\\\\company #{@company}}\" unless @company.nil?\r\n text << \"\\n#{prefix}{\\\\doccomm #{@comments}}\" unless @comments.nil?\r\n unless @created.nil?\r\n text << \"\\n#{prefix}{\\\\createim\\\\yr#{@created.year}\"\r\n text << \"\\\\mo#{@created.month}\\\\dy#{@created.day}\"\r\n text << \"\\\\hr#{@created.hour}\\\\min#{@created.min}}\"\r\n end\r\n text << \"\\n#{prefix}}\"\r\n\r\n text.string\r\n end", "language": "ruby", "code": "def to_rtf(indent=0)\r\n prefix = indent > 0 ? ' ' * indent : ''\r\n text = StringIO.new\r\n\r\n text << \"#{prefix}{\\\\info\"\r\n text << \"\\n#{prefix}{\\\\title #{@title}}\" unless @title.nil?\r\n text << \"\\n#{prefix}{\\\\author #{@author}}\" unless @author.nil?\r\n text << \"\\n#{prefix}{\\\\company #{@company}}\" unless @company.nil?\r\n text << \"\\n#{prefix}{\\\\doccomm #{@comments}}\" unless @comments.nil?\r\n unless @created.nil?\r\n text << \"\\n#{prefix}{\\\\createim\\\\yr#{@created.year}\"\r\n text << \"\\\\mo#{@created.month}\\\\dy#{@created.day}\"\r\n text << \"\\\\hr#{@created.hour}\\\\min#{@created.min}}\"\r\n end\r\n text << \"\\n#{prefix}}\"\r\n\r\n text.string\r\n end", "code_tokens": ["def", "to_rtf", "(", "indent", "=", "0", ")", "prefix", "=", "indent", ">", "0", "?", "' '", "*", "indent", ":", "''", "text", "=", "StringIO", ".", "new", "text", "<<", "\"#{prefix}{\\\\info\"", "text", "<<", "\"\\n#{prefix}{\\\\title #{@title}}\"", "unless", "@title", ".", "nil?", "text", "<<", "\"\\n#{prefix}{\\\\author #{@author}}\"", "unless", "@author", ".", "nil?", "text", "<<", "\"\\n#{prefix}{\\\\company #{@company}}\"", "unless", "@company", ".", "nil?", "text", "<<", "\"\\n#{prefix}{\\\\doccomm #{@comments}}\"", "unless", "@comments", ".", "nil?", "unless", "@created", ".", "nil?", "text", "<<", "\"\\n#{prefix}{\\\\createim\\\\yr#{@created.year}\"", "text", "<<", "\"\\\\mo#{@created.month}\\\\dy#{@created.day}\"", "text", "<<", "\"\\\\hr#{@created.hour}\\\\min#{@created.min}}\"", "end", "text", "<<", "\"\\n#{prefix}}\"", "text", ".", "string", "end"], "docstring": "This method generates the RTF text for an Information object.\n\n ==== Parameters\n indent:: The number of spaces to prefix to the lines generated by the\n method. Defaults to zero.", "docstring_tokens": ["This", "method", "generates", "the", "RTF", "text", "for", "an", "Information", "object", "."], "sha": "d6455933262a25628006101be802d7f7b2c3feb7", "url": "https://github.com/thechrisoshow/rtf/blob/d6455933262a25628006101be802d7f7b2c3feb7/lib/rtf/information.rb#L92-L109", "partition": "valid"} {"repo": "cotag/spider-gazelle", "path": "lib/spider-gazelle/signaller.rb", "func_name": "SpiderGazelle.Signaller.process_request", "original_string": "def process_request(data, client)\n validated = @validated.include?(client)\n parser = @validating[client.object_id]\n\n if validated\n parser.process data\n else\n result = parser.signal(data)\n\n case result\n when :validated\n @validated.each do |old|\n old.write \"\\x02update\\x03\"\n end\n @validated << client\n if @validated.length > 1\n client.write \"\\x02wait\\x03\"\n else\n client.write \"\\x02ready\\x03\"\n end\n @logger.verbose { \"Client <0x#{client.object_id.to_s(16)}> connection was validated\" }\n when :close_connection\n client.close\n @logger.warn \"Client <0x#{client.object_id.to_s(16)}> connection was closed due to bad credentials\"\n end\n end\n end", "language": "ruby", "code": "def process_request(data, client)\n validated = @validated.include?(client)\n parser = @validating[client.object_id]\n\n if validated\n parser.process data\n else\n result = parser.signal(data)\n\n case result\n when :validated\n @validated.each do |old|\n old.write \"\\x02update\\x03\"\n end\n @validated << client\n if @validated.length > 1\n client.write \"\\x02wait\\x03\"\n else\n client.write \"\\x02ready\\x03\"\n end\n @logger.verbose { \"Client <0x#{client.object_id.to_s(16)}> connection was validated\" }\n when :close_connection\n client.close\n @logger.warn \"Client <0x#{client.object_id.to_s(16)}> connection was closed due to bad credentials\"\n end\n end\n end", "code_tokens": ["def", "process_request", "(", "data", ",", "client", ")", "validated", "=", "@validated", ".", "include?", "(", "client", ")", "parser", "=", "@validating", "[", "client", ".", "object_id", "]", "if", "validated", "parser", ".", "process", "data", "else", "result", "=", "parser", ".", "signal", "(", "data", ")", "case", "result", "when", ":validated", "@validated", ".", "each", "do", "|", "old", "|", "old", ".", "write", "\"\\x02update\\x03\"", "end", "@validated", "<<", "client", "if", "@validated", ".", "length", ">", "1", "client", ".", "write", "\"\\x02wait\\x03\"", "else", "client", ".", "write", "\"\\x02ready\\x03\"", "end", "@logger", ".", "verbose", "{", "\"Client <0x#{client.object_id.to_s(16)}> connection was validated\"", "}", "when", ":close_connection", "client", ".", "close", "@logger", ".", "warn", "\"Client <0x#{client.object_id.to_s(16)}> connection was closed due to bad credentials\"", "end", "end", "end"], "docstring": "The server processes requests here", "docstring_tokens": ["The", "server", "processes", "requests", "here"], "sha": "9eb8ffdf713f66e06579d1a9170618f457e1065c", "url": "https://github.com/cotag/spider-gazelle/blob/9eb8ffdf713f66e06579d1a9170618f457e1065c/lib/spider-gazelle/signaller.rb#L188-L214", "partition": "valid"} {"repo": "cotag/spider-gazelle", "path": "lib/spider-gazelle/reactor.rb", "func_name": "SpiderGazelle.Reactor.log", "original_string": "def log(error, context, trace = nil)\n msg = String.new\n if error.respond_to?(:backtrace)\n msg << \"unhandled exception: #{error.message} (#{context})\"\n backtrace = error.backtrace\n msg << \"\\n#{backtrace.join(\"\\n\")}\" if backtrace\n msg << \"\\n#{trace.join(\"\\n\")}\" if trace\n else\n msg << \"unhandled exception: #{args}\"\n end\n @logger.error msg\n end", "language": "ruby", "code": "def log(error, context, trace = nil)\n msg = String.new\n if error.respond_to?(:backtrace)\n msg << \"unhandled exception: #{error.message} (#{context})\"\n backtrace = error.backtrace\n msg << \"\\n#{backtrace.join(\"\\n\")}\" if backtrace\n msg << \"\\n#{trace.join(\"\\n\")}\" if trace\n else\n msg << \"unhandled exception: #{args}\"\n end\n @logger.error msg\n end", "code_tokens": ["def", "log", "(", "error", ",", "context", ",", "trace", "=", "nil", ")", "msg", "=", "String", ".", "new", "if", "error", ".", "respond_to?", "(", ":backtrace", ")", "msg", "<<", "\"unhandled exception: #{error.message} (#{context})\"", "backtrace", "=", "error", ".", "backtrace", "msg", "<<", "\"\\n#{backtrace.join(\"\\n\")}\"", "if", "backtrace", "msg", "<<", "\"\\n#{trace.join(\"\\n\")}\"", "if", "trace", "else", "msg", "<<", "\"unhandled exception: #{args}\"", "end", "@logger", ".", "error", "msg", "end"], "docstring": "This is an unhandled error on the Libuv Event loop", "docstring_tokens": ["This", "is", "an", "unhandled", "error", "on", "the", "Libuv", "Event", "loop"], "sha": "9eb8ffdf713f66e06579d1a9170618f457e1065c", "url": "https://github.com/cotag/spider-gazelle/blob/9eb8ffdf713f66e06579d1a9170618f457e1065c/lib/spider-gazelle/reactor.rb#L54-L65", "partition": "valid"} {"repo": "cotag/spider-gazelle", "path": "lib/spider-gazelle/spider.rb", "func_name": "SpiderGazelle.Spider.ready", "original_string": "def ready\n load_promise = load_applications\n load_promise.then do\n # Check a shutdown request didn't occur as we were loading\n if @running\n @logger.verbose \"All gazelles running\"\n\n # This happends on the master thread so we don't need to check\n # for the shutdown events here\n @loaded = true\n bind_application_ports unless @delay_port_binding\n else\n @logger.warn \"A shutdown event occured while loading\"\n perform_shutdown\n end\n end\n\n # Provide applications with a load complete callback\n @load_complete.resolve(load_promise)\n end", "language": "ruby", "code": "def ready\n load_promise = load_applications\n load_promise.then do\n # Check a shutdown request didn't occur as we were loading\n if @running\n @logger.verbose \"All gazelles running\"\n\n # This happends on the master thread so we don't need to check\n # for the shutdown events here\n @loaded = true\n bind_application_ports unless @delay_port_binding\n else\n @logger.warn \"A shutdown event occured while loading\"\n perform_shutdown\n end\n end\n\n # Provide applications with a load complete callback\n @load_complete.resolve(load_promise)\n end", "code_tokens": ["def", "ready", "load_promise", "=", "load_applications", "load_promise", ".", "then", "do", "# Check a shutdown request didn't occur as we were loading", "if", "@running", "@logger", ".", "verbose", "\"All gazelles running\"", "# This happends on the master thread so we don't need to check", "# for the shutdown events here", "@loaded", "=", "true", "bind_application_ports", "unless", "@delay_port_binding", "else", "@logger", ".", "warn", "\"A shutdown event occured while loading\"", "perform_shutdown", "end", "end", "# Provide applications with a load complete callback", "@load_complete", ".", "resolve", "(", "load_promise", ")", "end"], "docstring": "Load gazelles and make the required bindings", "docstring_tokens": ["Load", "gazelles", "and", "make", "the", "required", "bindings"], "sha": "9eb8ffdf713f66e06579d1a9170618f457e1065c", "url": "https://github.com/cotag/spider-gazelle/blob/9eb8ffdf713f66e06579d1a9170618f457e1065c/lib/spider-gazelle/spider.rb#L66-L85", "partition": "valid"} {"repo": "barkerest/hidapi", "path": "lib/hidapi/engine.rb", "func_name": "HIDAPI.Engine.enumerate", "original_string": "def enumerate(vendor_id = 0, product_id = 0, options = {})\n raise HIDAPI::HidApiError, 'not initialized' unless @context\n\n if vendor_id.is_a?(Hash) || (vendor_id.is_a?(String) && options.empty?)\n options = vendor_id\n vendor_id = 0\n product_id = 0\n end\n\n if product_id.is_a?(Hash) || (product_id.is_a?(String) && options.empty?)\n options = product_id\n product_id = 0\n end\n\n if options.is_a?(String) || options.is_a?(Symbol)\n options = { as: options }\n end\n\n unless options.nil? || options.is_a?(Hash)\n raise ArgumentError, 'options hash is invalid'\n end\n\n klass = (options || {}).delete(:as) || 'HIDAPI::Device'\n klass = Object.const_get(klass) unless klass == :no_mapping\n\n filters = { bClass: HID_CLASS }\n\n unless vendor_id.nil? || vendor_id.to_i == 0\n filters[:idVendor] = vendor_id.to_i\n end\n unless product_id.nil? || product_id.to_i == 0\n filters[:idProduct] = product_id.to_i\n end\n\n list = @context.devices(filters)\n\n if klass != :no_mapping\n list.to_a.map{ |dev| klass.new(dev) }\n else\n list.to_a\n end\n end", "language": "ruby", "code": "def enumerate(vendor_id = 0, product_id = 0, options = {})\n raise HIDAPI::HidApiError, 'not initialized' unless @context\n\n if vendor_id.is_a?(Hash) || (vendor_id.is_a?(String) && options.empty?)\n options = vendor_id\n vendor_id = 0\n product_id = 0\n end\n\n if product_id.is_a?(Hash) || (product_id.is_a?(String) && options.empty?)\n options = product_id\n product_id = 0\n end\n\n if options.is_a?(String) || options.is_a?(Symbol)\n options = { as: options }\n end\n\n unless options.nil? || options.is_a?(Hash)\n raise ArgumentError, 'options hash is invalid'\n end\n\n klass = (options || {}).delete(:as) || 'HIDAPI::Device'\n klass = Object.const_get(klass) unless klass == :no_mapping\n\n filters = { bClass: HID_CLASS }\n\n unless vendor_id.nil? || vendor_id.to_i == 0\n filters[:idVendor] = vendor_id.to_i\n end\n unless product_id.nil? || product_id.to_i == 0\n filters[:idProduct] = product_id.to_i\n end\n\n list = @context.devices(filters)\n\n if klass != :no_mapping\n list.to_a.map{ |dev| klass.new(dev) }\n else\n list.to_a\n end\n end", "code_tokens": ["def", "enumerate", "(", "vendor_id", "=", "0", ",", "product_id", "=", "0", ",", "options", "=", "{", "}", ")", "raise", "HIDAPI", "::", "HidApiError", ",", "'not initialized'", "unless", "@context", "if", "vendor_id", ".", "is_a?", "(", "Hash", ")", "||", "(", "vendor_id", ".", "is_a?", "(", "String", ")", "&&", "options", ".", "empty?", ")", "options", "=", "vendor_id", "vendor_id", "=", "0", "product_id", "=", "0", "end", "if", "product_id", ".", "is_a?", "(", "Hash", ")", "||", "(", "product_id", ".", "is_a?", "(", "String", ")", "&&", "options", ".", "empty?", ")", "options", "=", "product_id", "product_id", "=", "0", "end", "if", "options", ".", "is_a?", "(", "String", ")", "||", "options", ".", "is_a?", "(", "Symbol", ")", "options", "=", "{", "as", ":", "options", "}", "end", "unless", "options", ".", "nil?", "||", "options", ".", "is_a?", "(", "Hash", ")", "raise", "ArgumentError", ",", "'options hash is invalid'", "end", "klass", "=", "(", "options", "||", "{", "}", ")", ".", "delete", "(", ":as", ")", "||", "'HIDAPI::Device'", "klass", "=", "Object", ".", "const_get", "(", "klass", ")", "unless", "klass", "==", ":no_mapping", "filters", "=", "{", "bClass", ":", "HID_CLASS", "}", "unless", "vendor_id", ".", "nil?", "||", "vendor_id", ".", "to_i", "==", "0", "filters", "[", ":idVendor", "]", "=", "vendor_id", ".", "to_i", "end", "unless", "product_id", ".", "nil?", "||", "product_id", ".", "to_i", "==", "0", "filters", "[", ":idProduct", "]", "=", "product_id", ".", "to_i", "end", "list", "=", "@context", ".", "devices", "(", "filters", ")", "if", "klass", "!=", ":no_mapping", "list", ".", "to_a", ".", "map", "{", "|", "dev", "|", "klass", ".", "new", "(", "dev", ")", "}", "else", "list", ".", "to_a", "end", "end"], "docstring": "Creates a new engine.\n\n Enumerates the HID devices matching the vendor and product IDs.\n\n Both vendor_id and product_id are optional. They will act as a wild card if set to 0 (the default).", "docstring_tokens": ["Creates", "a", "new", "engine", "."], "sha": "d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7", "url": "https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/engine.rb#L23-L64", "partition": "valid"} {"repo": "barkerest/hidapi", "path": "lib/hidapi/engine.rb", "func_name": "HIDAPI.Engine.get_device", "original_string": "def get_device(vendor_id, product_id, serial_number = nil, options = {})\n raise ArgumentError, 'vendor_id must be provided' if vendor_id.to_i == 0\n raise ArgumentError, 'product_id must be provided' if product_id.to_i == 0\n\n if serial_number.is_a?(Hash)\n options = serial_number\n serial_number = nil\n end\n\n klass = (options || {}).delete(:as) || 'HIDAPI::Device'\n klass = Object.const_get(klass) unless klass == :no_mapping\n\n list = enumerate(vendor_id, product_id, as: :no_mapping)\n return nil unless list && list.count > 0\n if serial_number.to_s == ''\n if klass != :no_mapping\n return klass.new(list.first)\n else\n return list.first\n end\n end\n list.each do |dev|\n if dev.serial_number == serial_number\n if klass != :no_mapping\n return klass.new(dev)\n else\n return dev\n end\n end\n end\n nil\n end", "language": "ruby", "code": "def get_device(vendor_id, product_id, serial_number = nil, options = {})\n raise ArgumentError, 'vendor_id must be provided' if vendor_id.to_i == 0\n raise ArgumentError, 'product_id must be provided' if product_id.to_i == 0\n\n if serial_number.is_a?(Hash)\n options = serial_number\n serial_number = nil\n end\n\n klass = (options || {}).delete(:as) || 'HIDAPI::Device'\n klass = Object.const_get(klass) unless klass == :no_mapping\n\n list = enumerate(vendor_id, product_id, as: :no_mapping)\n return nil unless list && list.count > 0\n if serial_number.to_s == ''\n if klass != :no_mapping\n return klass.new(list.first)\n else\n return list.first\n end\n end\n list.each do |dev|\n if dev.serial_number == serial_number\n if klass != :no_mapping\n return klass.new(dev)\n else\n return dev\n end\n end\n end\n nil\n end", "code_tokens": ["def", "get_device", "(", "vendor_id", ",", "product_id", ",", "serial_number", "=", "nil", ",", "options", "=", "{", "}", ")", "raise", "ArgumentError", ",", "'vendor_id must be provided'", "if", "vendor_id", ".", "to_i", "==", "0", "raise", "ArgumentError", ",", "'product_id must be provided'", "if", "product_id", ".", "to_i", "==", "0", "if", "serial_number", ".", "is_a?", "(", "Hash", ")", "options", "=", "serial_number", "serial_number", "=", "nil", "end", "klass", "=", "(", "options", "||", "{", "}", ")", ".", "delete", "(", ":as", ")", "||", "'HIDAPI::Device'", "klass", "=", "Object", ".", "const_get", "(", "klass", ")", "unless", "klass", "==", ":no_mapping", "list", "=", "enumerate", "(", "vendor_id", ",", "product_id", ",", "as", ":", ":no_mapping", ")", "return", "nil", "unless", "list", "&&", "list", ".", "count", ">", "0", "if", "serial_number", ".", "to_s", "==", "''", "if", "klass", "!=", ":no_mapping", "return", "klass", ".", "new", "(", "list", ".", "first", ")", "else", "return", "list", ".", "first", "end", "end", "list", ".", "each", "do", "|", "dev", "|", "if", "dev", ".", "serial_number", "==", "serial_number", "if", "klass", "!=", ":no_mapping", "return", "klass", ".", "new", "(", "dev", ")", "else", "return", "dev", "end", "end", "end", "nil", "end"], "docstring": "Gets the first device with the specified vendor_id, product_id, and optionally serial_number.", "docstring_tokens": ["Gets", "the", "first", "device", "with", "the", "specified", "vendor_id", "product_id", "and", "optionally", "serial_number", "."], "sha": "d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7", "url": "https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/engine.rb#L68-L99", "partition": "valid"} {"repo": "barkerest/hidapi", "path": "lib/hidapi/engine.rb", "func_name": "HIDAPI.Engine.open", "original_string": "def open(vendor_id, product_id, serial_number = nil, options = {})\n dev = get_device(vendor_id, product_id, serial_number, options)\n dev.open if dev\n end", "language": "ruby", "code": "def open(vendor_id, product_id, serial_number = nil, options = {})\n dev = get_device(vendor_id, product_id, serial_number, options)\n dev.open if dev\n end", "code_tokens": ["def", "open", "(", "vendor_id", ",", "product_id", ",", "serial_number", "=", "nil", ",", "options", "=", "{", "}", ")", "dev", "=", "get_device", "(", "vendor_id", ",", "product_id", ",", "serial_number", ",", "options", ")", "dev", ".", "open", "if", "dev", "end"], "docstring": "Opens the first device with the specified vendor_id, product_id, and optionally serial_number.", "docstring_tokens": ["Opens", "the", "first", "device", "with", "the", "specified", "vendor_id", "product_id", "and", "optionally", "serial_number", "."], "sha": "d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7", "url": "https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/engine.rb#L103-L106", "partition": "valid"} {"repo": "barkerest/hidapi", "path": "lib/hidapi/engine.rb", "func_name": "HIDAPI.Engine.get_device_by_path", "original_string": "def get_device_by_path(path, options = {})\n\n # Our linux setup routine creates convenient /dev/hidapi/* links.\n # If the user wants to open one of those, we can simple parse the link to generate\n # the path that the library expects.\n if File.exist?(path)\n\n hidapi_regex = /^\\/dev\\/hidapi\\//\n usb_bus_regex = /^\\/dev\\/bus\\/usb\\/(?\\d+)\\/(?\\d+)$/\n\n if hidapi_regex.match(path)\n path = File.expand_path(File.readlink(path), File.dirname(path))\n elsif !usb_bus_regex.match(path)\n raise HIDAPI::DevicePathInvalid, 'Cannot open file paths other than /dev/hidapi/XXX or /dev/bus/usb/XXX/XXX paths.'\n end\n\n # path should now be in the form /dev/bus/usb/AAA/BBB\n match = usb_bus_regex.match(path)\n\n raise HIDAPI::DevicePathInvalid, \"Link target does not appear valid (#{path}).\" unless match\n\n interface = (options.delete(:interface) || 0).to_s(16)\n\n path = HIDAPI::Device.validate_path(\"#{match['BUS']}:#{match['ADDR']}:#{interface}\")\n end\n\n valid_path = HIDAPI::Device.validate_path(path)\n raise HIDAPI::DevicePathInvalid, \"Path should be in BUS:ADDRESS:INTERFACE format with each value being in hexadecimal (ie - 0001:01A:00), not #{path}.\" unless valid_path\n path = valid_path\n\n klass = (options || {}).delete(:as) || 'HIDAPI::Device'\n klass = Object.const_get(klass) unless klass == :no_mapping\n\n enumerate(as: :no_mapping).each do |usb_dev|\n usb_dev.settings.each do |intf_desc|\n if intf_desc.bInterfaceClass == HID_CLASS\n dev_path = HIDAPI::Device.make_path(usb_dev, intf_desc.bInterfaceNumber)\n if dev_path == path\n if klass != :no_mapping\n return klass.new(usb_dev, intf_desc.bInterfaceNumber)\n else\n return usb_dev\n end\n end\n end\n end\n end\n end", "language": "ruby", "code": "def get_device_by_path(path, options = {})\n\n # Our linux setup routine creates convenient /dev/hidapi/* links.\n # If the user wants to open one of those, we can simple parse the link to generate\n # the path that the library expects.\n if File.exist?(path)\n\n hidapi_regex = /^\\/dev\\/hidapi\\//\n usb_bus_regex = /^\\/dev\\/bus\\/usb\\/(?\\d+)\\/(?\\d+)$/\n\n if hidapi_regex.match(path)\n path = File.expand_path(File.readlink(path), File.dirname(path))\n elsif !usb_bus_regex.match(path)\n raise HIDAPI::DevicePathInvalid, 'Cannot open file paths other than /dev/hidapi/XXX or /dev/bus/usb/XXX/XXX paths.'\n end\n\n # path should now be in the form /dev/bus/usb/AAA/BBB\n match = usb_bus_regex.match(path)\n\n raise HIDAPI::DevicePathInvalid, \"Link target does not appear valid (#{path}).\" unless match\n\n interface = (options.delete(:interface) || 0).to_s(16)\n\n path = HIDAPI::Device.validate_path(\"#{match['BUS']}:#{match['ADDR']}:#{interface}\")\n end\n\n valid_path = HIDAPI::Device.validate_path(path)\n raise HIDAPI::DevicePathInvalid, \"Path should be in BUS:ADDRESS:INTERFACE format with each value being in hexadecimal (ie - 0001:01A:00), not #{path}.\" unless valid_path\n path = valid_path\n\n klass = (options || {}).delete(:as) || 'HIDAPI::Device'\n klass = Object.const_get(klass) unless klass == :no_mapping\n\n enumerate(as: :no_mapping).each do |usb_dev|\n usb_dev.settings.each do |intf_desc|\n if intf_desc.bInterfaceClass == HID_CLASS\n dev_path = HIDAPI::Device.make_path(usb_dev, intf_desc.bInterfaceNumber)\n if dev_path == path\n if klass != :no_mapping\n return klass.new(usb_dev, intf_desc.bInterfaceNumber)\n else\n return usb_dev\n end\n end\n end\n end\n end\n end", "code_tokens": ["def", "get_device_by_path", "(", "path", ",", "options", "=", "{", "}", ")", "# Our linux setup routine creates convenient /dev/hidapi/* links.", "# If the user wants to open one of those, we can simple parse the link to generate", "# the path that the library expects.", "if", "File", ".", "exist?", "(", "path", ")", "hidapi_regex", "=", "/", "\\/", "\\/", "\\/", "/", "usb_bus_regex", "=", "/", "\\/", "\\/", "\\/", "\\/", "\\d", "\\/", "\\d", "/", "if", "hidapi_regex", ".", "match", "(", "path", ")", "path", "=", "File", ".", "expand_path", "(", "File", ".", "readlink", "(", "path", ")", ",", "File", ".", "dirname", "(", "path", ")", ")", "elsif", "!", "usb_bus_regex", ".", "match", "(", "path", ")", "raise", "HIDAPI", "::", "DevicePathInvalid", ",", "'Cannot open file paths other than /dev/hidapi/XXX or /dev/bus/usb/XXX/XXX paths.'", "end", "# path should now be in the form /dev/bus/usb/AAA/BBB", "match", "=", "usb_bus_regex", ".", "match", "(", "path", ")", "raise", "HIDAPI", "::", "DevicePathInvalid", ",", "\"Link target does not appear valid (#{path}).\"", "unless", "match", "interface", "=", "(", "options", ".", "delete", "(", ":interface", ")", "||", "0", ")", ".", "to_s", "(", "16", ")", "path", "=", "HIDAPI", "::", "Device", ".", "validate_path", "(", "\"#{match['BUS']}:#{match['ADDR']}:#{interface}\"", ")", "end", "valid_path", "=", "HIDAPI", "::", "Device", ".", "validate_path", "(", "path", ")", "raise", "HIDAPI", "::", "DevicePathInvalid", ",", "\"Path should be in BUS:ADDRESS:INTERFACE format with each value being in hexadecimal (ie - 0001:01A:00), not #{path}.\"", "unless", "valid_path", "path", "=", "valid_path", "klass", "=", "(", "options", "||", "{", "}", ")", ".", "delete", "(", ":as", ")", "||", "'HIDAPI::Device'", "klass", "=", "Object", ".", "const_get", "(", "klass", ")", "unless", "klass", "==", ":no_mapping", "enumerate", "(", "as", ":", ":no_mapping", ")", ".", "each", "do", "|", "usb_dev", "|", "usb_dev", ".", "settings", ".", "each", "do", "|", "intf_desc", "|", "if", "intf_desc", ".", "bInterfaceClass", "==", "HID_CLASS", "dev_path", "=", "HIDAPI", "::", "Device", ".", "make_path", "(", "usb_dev", ",", "intf_desc", ".", "bInterfaceNumber", ")", "if", "dev_path", "==", "path", "if", "klass", "!=", ":no_mapping", "return", "klass", ".", "new", "(", "usb_dev", ",", "intf_desc", ".", "bInterfaceNumber", ")", "else", "return", "usb_dev", "end", "end", "end", "end", "end", "end"], "docstring": "Gets the device with the specified path.", "docstring_tokens": ["Gets", "the", "device", "with", "the", "specified", "path", "."], "sha": "d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7", "url": "https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/engine.rb#L110-L157", "partition": "valid"} {"repo": "barkerest/hidapi", "path": "lib/hidapi/engine.rb", "func_name": "HIDAPI.Engine.open_path", "original_string": "def open_path(path, options = {})\n dev = get_device_by_path(path, options)\n dev.open if dev\n end", "language": "ruby", "code": "def open_path(path, options = {})\n dev = get_device_by_path(path, options)\n dev.open if dev\n end", "code_tokens": ["def", "open_path", "(", "path", ",", "options", "=", "{", "}", ")", "dev", "=", "get_device_by_path", "(", "path", ",", "options", ")", "dev", ".", "open", "if", "dev", "end"], "docstring": "Opens the device with the specified path.", "docstring_tokens": ["Opens", "the", "device", "with", "the", "specified", "path", "."], "sha": "d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7", "url": "https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/engine.rb#L161-L164", "partition": "valid"} {"repo": "barkerest/hidapi", "path": "lib/hidapi/engine.rb", "func_name": "HIDAPI.Engine.usb_code_for_current_locale", "original_string": "def usb_code_for_current_locale\n @usb_code_for_current_locale ||=\n begin\n locale = I18n.locale\n if locale\n locale = locale.to_s.partition('.')[0] # remove encoding\n result = HIDAPI::Language.get_by_code(locale)\n unless result\n locale = locale.partition('_')[0] # chop off extra specification\n result = HIDAPI::Language.get_by_code(locale)\n end\n result ? result[:usb_code] : 0\n else\n 0\n end\n end\n end", "language": "ruby", "code": "def usb_code_for_current_locale\n @usb_code_for_current_locale ||=\n begin\n locale = I18n.locale\n if locale\n locale = locale.to_s.partition('.')[0] # remove encoding\n result = HIDAPI::Language.get_by_code(locale)\n unless result\n locale = locale.partition('_')[0] # chop off extra specification\n result = HIDAPI::Language.get_by_code(locale)\n end\n result ? result[:usb_code] : 0\n else\n 0\n end\n end\n end", "code_tokens": ["def", "usb_code_for_current_locale", "@usb_code_for_current_locale", "||=", "begin", "locale", "=", "I18n", ".", "locale", "if", "locale", "locale", "=", "locale", ".", "to_s", ".", "partition", "(", "'.'", ")", "[", "0", "]", "# remove encoding", "result", "=", "HIDAPI", "::", "Language", ".", "get_by_code", "(", "locale", ")", "unless", "result", "locale", "=", "locale", ".", "partition", "(", "'_'", ")", "[", "0", "]", "# chop off extra specification", "result", "=", "HIDAPI", "::", "Language", ".", "get_by_code", "(", "locale", ")", "end", "result", "?", "result", "[", ":usb_code", "]", ":", "0", "else", "0", "end", "end", "end"], "docstring": "Gets the USB code for the current locale.", "docstring_tokens": ["Gets", "the", "USB", "code", "for", "the", "current", "locale", "."], "sha": "d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7", "url": "https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/engine.rb#L168-L184", "partition": "valid"} {"repo": "barkerest/hidapi", "path": "lib/hidapi/device.rb", "func_name": "HIDAPI.Device.open", "original_string": "def open\n if open?\n self.open_count += 1\n if open_count < 1\n HIDAPI.debug \"open_count for open device #{path} is #{open_count}\"\n self.open_count = 1\n end\n return self\n end\n self.open_count = 0\n begin\n self.handle = usb_device.open\n raise 'no handle returned' unless handle\n\n begin\n if handle.kernel_driver_active?(interface)\n handle.detach_kernel_driver(interface)\n end\n rescue LIBUSB::ERROR_NOT_SUPPORTED\n HIDAPI.debug 'cannot determine kernel driver status, continuing to open device'\n end\n\n handle.claim_interface(interface)\n\n self.input_endpoint = self.output_endpoint = nil\n\n # now we need to find the endpoints.\n usb_device.settings\n .keep_if {|item| item.bInterfaceNumber == interface}\n .each do |intf_desc|\n intf_desc.endpoints.each do |ep|\n if ep.transfer_type == :interrupt\n if input_endpoint.nil? && ep.direction == :in\n self.input_endpoint = ep.bEndpointAddress\n self.input_ep_max_packet_size = ep.wMaxPacketSize\n end\n if output_endpoint.nil? && ep.direction == :out\n self.output_endpoint = ep.bEndpointAddress\n end\n end\n break if input_endpoint && output_endpoint\n end\n end\n\n # output_ep is optional, input_ep is required\n raise 'failed to locate input endpoint' unless input_endpoint\n\n # start the read thread\n self.input_reports = []\n self.thread_initialized = false\n self.shutdown_thread = false\n self.thread = Thread.start(self) { |dev| dev.send(:execute_read_thread) }\n sleep 0.001 until thread_initialized\n\n rescue =>e\n handle.close rescue nil\n self.handle = nil\n HIDAPI.debug \"failed to open device #{path}: #{e.inspect}\"\n raise DeviceOpenFailed, e.inspect\n end\n HIDAPI.debug \"opened device #{path}\"\n self.open_count = 1\n self\n end", "language": "ruby", "code": "def open\n if open?\n self.open_count += 1\n if open_count < 1\n HIDAPI.debug \"open_count for open device #{path} is #{open_count}\"\n self.open_count = 1\n end\n return self\n end\n self.open_count = 0\n begin\n self.handle = usb_device.open\n raise 'no handle returned' unless handle\n\n begin\n if handle.kernel_driver_active?(interface)\n handle.detach_kernel_driver(interface)\n end\n rescue LIBUSB::ERROR_NOT_SUPPORTED\n HIDAPI.debug 'cannot determine kernel driver status, continuing to open device'\n end\n\n handle.claim_interface(interface)\n\n self.input_endpoint = self.output_endpoint = nil\n\n # now we need to find the endpoints.\n usb_device.settings\n .keep_if {|item| item.bInterfaceNumber == interface}\n .each do |intf_desc|\n intf_desc.endpoints.each do |ep|\n if ep.transfer_type == :interrupt\n if input_endpoint.nil? && ep.direction == :in\n self.input_endpoint = ep.bEndpointAddress\n self.input_ep_max_packet_size = ep.wMaxPacketSize\n end\n if output_endpoint.nil? && ep.direction == :out\n self.output_endpoint = ep.bEndpointAddress\n end\n end\n break if input_endpoint && output_endpoint\n end\n end\n\n # output_ep is optional, input_ep is required\n raise 'failed to locate input endpoint' unless input_endpoint\n\n # start the read thread\n self.input_reports = []\n self.thread_initialized = false\n self.shutdown_thread = false\n self.thread = Thread.start(self) { |dev| dev.send(:execute_read_thread) }\n sleep 0.001 until thread_initialized\n\n rescue =>e\n handle.close rescue nil\n self.handle = nil\n HIDAPI.debug \"failed to open device #{path}: #{e.inspect}\"\n raise DeviceOpenFailed, e.inspect\n end\n HIDAPI.debug \"opened device #{path}\"\n self.open_count = 1\n self\n end", "code_tokens": ["def", "open", "if", "open?", "self", ".", "open_count", "+=", "1", "if", "open_count", "<", "1", "HIDAPI", ".", "debug", "\"open_count for open device #{path} is #{open_count}\"", "self", ".", "open_count", "=", "1", "end", "return", "self", "end", "self", ".", "open_count", "=", "0", "begin", "self", ".", "handle", "=", "usb_device", ".", "open", "raise", "'no handle returned'", "unless", "handle", "begin", "if", "handle", ".", "kernel_driver_active?", "(", "interface", ")", "handle", ".", "detach_kernel_driver", "(", "interface", ")", "end", "rescue", "LIBUSB", "::", "ERROR_NOT_SUPPORTED", "HIDAPI", ".", "debug", "'cannot determine kernel driver status, continuing to open device'", "end", "handle", ".", "claim_interface", "(", "interface", ")", "self", ".", "input_endpoint", "=", "self", ".", "output_endpoint", "=", "nil", "# now we need to find the endpoints.", "usb_device", ".", "settings", ".", "keep_if", "{", "|", "item", "|", "item", ".", "bInterfaceNumber", "==", "interface", "}", ".", "each", "do", "|", "intf_desc", "|", "intf_desc", ".", "endpoints", ".", "each", "do", "|", "ep", "|", "if", "ep", ".", "transfer_type", "==", ":interrupt", "if", "input_endpoint", ".", "nil?", "&&", "ep", ".", "direction", "==", ":in", "self", ".", "input_endpoint", "=", "ep", ".", "bEndpointAddress", "self", ".", "input_ep_max_packet_size", "=", "ep", ".", "wMaxPacketSize", "end", "if", "output_endpoint", ".", "nil?", "&&", "ep", ".", "direction", "==", ":out", "self", ".", "output_endpoint", "=", "ep", ".", "bEndpointAddress", "end", "end", "break", "if", "input_endpoint", "&&", "output_endpoint", "end", "end", "# output_ep is optional, input_ep is required", "raise", "'failed to locate input endpoint'", "unless", "input_endpoint", "# start the read thread", "self", ".", "input_reports", "=", "[", "]", "self", ".", "thread_initialized", "=", "false", "self", ".", "shutdown_thread", "=", "false", "self", ".", "thread", "=", "Thread", ".", "start", "(", "self", ")", "{", "|", "dev", "|", "dev", ".", "send", "(", ":execute_read_thread", ")", "}", "sleep", "0.001", "until", "thread_initialized", "rescue", "=>", "e", "handle", ".", "close", "rescue", "nil", "self", ".", "handle", "=", "nil", "HIDAPI", ".", "debug", "\"failed to open device #{path}: #{e.inspect}\"", "raise", "DeviceOpenFailed", ",", "e", ".", "inspect", "end", "HIDAPI", ".", "debug", "\"opened device #{path}\"", "self", ".", "open_count", "=", "1", "self", "end"], "docstring": "Opens the device.\n\n Returns the device.", "docstring_tokens": ["Opens", "the", "device", "."], "sha": "d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7", "url": "https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/device.rb#L193-L256", "partition": "valid"} {"repo": "barkerest/hidapi", "path": "lib/hidapi/device.rb", "func_name": "HIDAPI.Device.read_timeout", "original_string": "def read_timeout(milliseconds)\n raise DeviceNotOpen unless open?\n\n mutex.synchronize do\n if input_reports.count > 0\n data = input_reports.delete_at(0)\n HIDAPI.debug \"read data from device #{path}: #{data.inspect}\"\n return data\n end\n\n if shutdown_thread\n HIDAPI.debug \"read thread for device #{path} is not running\"\n return nil\n end\n end\n\n # no data to return, do not block.\n return '' if milliseconds == 0\n\n if milliseconds < 0\n # wait forever (as long as the read thread doesn't die)\n until shutdown_thread\n mutex.synchronize do\n if input_reports.count > 0\n data = input_reports.delete_at(0)\n HIDAPI.debug \"read data from device #{path}: #{data.inspect}\"\n return data\n end\n end\n sleep 0.001\n end\n\n # error, return nil\n HIDAPI.debug \"read thread ended while waiting on device #{path}\"\n nil\n else\n # wait up to so many milliseconds for input.\n stop_at = Time.now + (milliseconds * 0.001)\n while Time.now < stop_at\n mutex.synchronize do\n if input_reports.count > 0\n data = input_reports.delete_at(0)\n HIDAPI.debug \"read data from device #{path}: #{data.inspect}\"\n return data\n end\n end\n sleep 0.001\n end\n\n # no input, return empty.\n ''\n end\n end", "language": "ruby", "code": "def read_timeout(milliseconds)\n raise DeviceNotOpen unless open?\n\n mutex.synchronize do\n if input_reports.count > 0\n data = input_reports.delete_at(0)\n HIDAPI.debug \"read data from device #{path}: #{data.inspect}\"\n return data\n end\n\n if shutdown_thread\n HIDAPI.debug \"read thread for device #{path} is not running\"\n return nil\n end\n end\n\n # no data to return, do not block.\n return '' if milliseconds == 0\n\n if milliseconds < 0\n # wait forever (as long as the read thread doesn't die)\n until shutdown_thread\n mutex.synchronize do\n if input_reports.count > 0\n data = input_reports.delete_at(0)\n HIDAPI.debug \"read data from device #{path}: #{data.inspect}\"\n return data\n end\n end\n sleep 0.001\n end\n\n # error, return nil\n HIDAPI.debug \"read thread ended while waiting on device #{path}\"\n nil\n else\n # wait up to so many milliseconds for input.\n stop_at = Time.now + (milliseconds * 0.001)\n while Time.now < stop_at\n mutex.synchronize do\n if input_reports.count > 0\n data = input_reports.delete_at(0)\n HIDAPI.debug \"read data from device #{path}: #{data.inspect}\"\n return data\n end\n end\n sleep 0.001\n end\n\n # no input, return empty.\n ''\n end\n end", "code_tokens": ["def", "read_timeout", "(", "milliseconds", ")", "raise", "DeviceNotOpen", "unless", "open?", "mutex", ".", "synchronize", "do", "if", "input_reports", ".", "count", ">", "0", "data", "=", "input_reports", ".", "delete_at", "(", "0", ")", "HIDAPI", ".", "debug", "\"read data from device #{path}: #{data.inspect}\"", "return", "data", "end", "if", "shutdown_thread", "HIDAPI", ".", "debug", "\"read thread for device #{path} is not running\"", "return", "nil", "end", "end", "# no data to return, do not block.", "return", "''", "if", "milliseconds", "==", "0", "if", "milliseconds", "<", "0", "# wait forever (as long as the read thread doesn't die)", "until", "shutdown_thread", "mutex", ".", "synchronize", "do", "if", "input_reports", ".", "count", ">", "0", "data", "=", "input_reports", ".", "delete_at", "(", "0", ")", "HIDAPI", ".", "debug", "\"read data from device #{path}: #{data.inspect}\"", "return", "data", "end", "end", "sleep", "0.001", "end", "# error, return nil", "HIDAPI", ".", "debug", "\"read thread ended while waiting on device #{path}\"", "nil", "else", "# wait up to so many milliseconds for input.", "stop_at", "=", "Time", ".", "now", "+", "(", "milliseconds", "*", "0.001", ")", "while", "Time", ".", "now", "<", "stop_at", "mutex", ".", "synchronize", "do", "if", "input_reports", ".", "count", ">", "0", "data", "=", "input_reports", ".", "delete_at", "(", "0", ")", "HIDAPI", ".", "debug", "\"read data from device #{path}: #{data.inspect}\"", "return", "data", "end", "end", "sleep", "0.001", "end", "# no input, return empty.", "''", "end", "end"], "docstring": "Attempts to read from the device, waiting up to +milliseconds+ before returning.\n\n If milliseconds is less than 1, it will wait forever.\n If milliseconds is 0, then it will return immediately.\n\n Returns the next report on success. If no report is available and it is not waiting\n forever, it will return an empty string.\n\n Returns nil on error.", "docstring_tokens": ["Attempts", "to", "read", "from", "the", "device", "waiting", "up", "to", "+", "milliseconds", "+", "before", "returning", "."], "sha": "d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7", "url": "https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/device.rb#L301-L353", "partition": "valid"} {"repo": "barkerest/hidapi", "path": "lib/hidapi/device.rb", "func_name": "HIDAPI.Device.send_feature_report", "original_string": "def send_feature_report(data)\n raise ArgumentError, 'data must not be blank' if data.nil? || data.length < 1\n raise HIDAPI::DeviceNotOpen unless open?\n\n data, report_number, skipped_report_id = clean_output_data(data)\n\n mutex.synchronize do\n handle.control_transfer(\n bmRequestType: LIBUSB::REQUEST_TYPE_CLASS | LIBUSB::RECIPIENT_INTERFACE | LIBUSB::ENDPOINT_OUT,\n bRequest: 0x09, # HID Set_Report\n wValue: (3 << 8) | report_number, # HID feature = 3\n wIndex: interface,\n dataOut: data\n )\n end\n\n data.length + (skipped_report_id ? 1 : 0)\n end", "language": "ruby", "code": "def send_feature_report(data)\n raise ArgumentError, 'data must not be blank' if data.nil? || data.length < 1\n raise HIDAPI::DeviceNotOpen unless open?\n\n data, report_number, skipped_report_id = clean_output_data(data)\n\n mutex.synchronize do\n handle.control_transfer(\n bmRequestType: LIBUSB::REQUEST_TYPE_CLASS | LIBUSB::RECIPIENT_INTERFACE | LIBUSB::ENDPOINT_OUT,\n bRequest: 0x09, # HID Set_Report\n wValue: (3 << 8) | report_number, # HID feature = 3\n wIndex: interface,\n dataOut: data\n )\n end\n\n data.length + (skipped_report_id ? 1 : 0)\n end", "code_tokens": ["def", "send_feature_report", "(", "data", ")", "raise", "ArgumentError", ",", "'data must not be blank'", "if", "data", ".", "nil?", "||", "data", ".", "length", "<", "1", "raise", "HIDAPI", "::", "DeviceNotOpen", "unless", "open?", "data", ",", "report_number", ",", "skipped_report_id", "=", "clean_output_data", "(", "data", ")", "mutex", ".", "synchronize", "do", "handle", ".", "control_transfer", "(", "bmRequestType", ":", "LIBUSB", "::", "REQUEST_TYPE_CLASS", "|", "LIBUSB", "::", "RECIPIENT_INTERFACE", "|", "LIBUSB", "::", "ENDPOINT_OUT", ",", "bRequest", ":", "0x09", ",", "# HID Set_Report", "wValue", ":", "(", "3", "<<", "8", ")", "|", "report_number", ",", "# HID feature = 3", "wIndex", ":", "interface", ",", "dataOut", ":", "data", ")", "end", "data", ".", "length", "+", "(", "skipped_report_id", "?", "1", ":", "0", ")", "end"], "docstring": "Sends a feature report to the device.", "docstring_tokens": ["Sends", "a", "feature", "report", "to", "the", "device", "."], "sha": "d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7", "url": "https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/device.rb#L374-L391", "partition": "valid"} {"repo": "barkerest/hidapi", "path": "lib/hidapi/device.rb", "func_name": "HIDAPI.Device.get_feature_report", "original_string": "def get_feature_report(report_number, buffer_size = nil)\n\n buffer_size ||= input_ep_max_packet_size\n\n mutex.synchronize do\n handle.control_transfer(\n bmRequestType: LIBUSB::REQUEST_TYPE_CLASS | LIBUSB::RECIPIENT_INTERFACE | LIBUSB::ENDPOINT_IN,\n bRequest: 0x01, # HID Get_Report\n wValue: (3 << 8) | report_number,\n wIndex: interface,\n dataIn: buffer_size\n )\n end\n\n end", "language": "ruby", "code": "def get_feature_report(report_number, buffer_size = nil)\n\n buffer_size ||= input_ep_max_packet_size\n\n mutex.synchronize do\n handle.control_transfer(\n bmRequestType: LIBUSB::REQUEST_TYPE_CLASS | LIBUSB::RECIPIENT_INTERFACE | LIBUSB::ENDPOINT_IN,\n bRequest: 0x01, # HID Get_Report\n wValue: (3 << 8) | report_number,\n wIndex: interface,\n dataIn: buffer_size\n )\n end\n\n end", "code_tokens": ["def", "get_feature_report", "(", "report_number", ",", "buffer_size", "=", "nil", ")", "buffer_size", "||=", "input_ep_max_packet_size", "mutex", ".", "synchronize", "do", "handle", ".", "control_transfer", "(", "bmRequestType", ":", "LIBUSB", "::", "REQUEST_TYPE_CLASS", "|", "LIBUSB", "::", "RECIPIENT_INTERFACE", "|", "LIBUSB", "::", "ENDPOINT_IN", ",", "bRequest", ":", "0x01", ",", "# HID Get_Report", "wValue", ":", "(", "3", "<<", "8", ")", "|", "report_number", ",", "wIndex", ":", "interface", ",", "dataIn", ":", "buffer_size", ")", "end", "end"], "docstring": "Gets a feature report from the device.", "docstring_tokens": ["Gets", "a", "feature", "report", "from", "the", "device", "."], "sha": "d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7", "url": "https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/device.rb#L395-L409", "partition": "valid"} {"repo": "barkerest/hidapi", "path": "lib/hidapi/device.rb", "func_name": "HIDAPI.Device.read_string", "original_string": "def read_string(index, on_failure = '')\n begin\n # does not require an interface, so open from the usb_dev instead of using our open method.\n data = mutex.synchronize do\n if open?\n handle.string_descriptor_ascii(index)\n else\n usb_device.open { |handle| handle.string_descriptor_ascii(index) }\n end\n end\n\n HIDAPI.debug(\"read string at index #{index} for device #{path}: #{data.inspect}\")\n data\n rescue =>e\n HIDAPI.debug(\"failed to read string at index #{index} for device #{path}: #{e.inspect}\")\n on_failure || ''\n end\n end", "language": "ruby", "code": "def read_string(index, on_failure = '')\n begin\n # does not require an interface, so open from the usb_dev instead of using our open method.\n data = mutex.synchronize do\n if open?\n handle.string_descriptor_ascii(index)\n else\n usb_device.open { |handle| handle.string_descriptor_ascii(index) }\n end\n end\n\n HIDAPI.debug(\"read string at index #{index} for device #{path}: #{data.inspect}\")\n data\n rescue =>e\n HIDAPI.debug(\"failed to read string at index #{index} for device #{path}: #{e.inspect}\")\n on_failure || ''\n end\n end", "code_tokens": ["def", "read_string", "(", "index", ",", "on_failure", "=", "''", ")", "begin", "# does not require an interface, so open from the usb_dev instead of using our open method.", "data", "=", "mutex", ".", "synchronize", "do", "if", "open?", "handle", ".", "string_descriptor_ascii", "(", "index", ")", "else", "usb_device", ".", "open", "{", "|", "handle", "|", "handle", ".", "string_descriptor_ascii", "(", "index", ")", "}", "end", "end", "HIDAPI", ".", "debug", "(", "\"read string at index #{index} for device #{path}: #{data.inspect}\"", ")", "data", "rescue", "=>", "e", "HIDAPI", ".", "debug", "(", "\"failed to read string at index #{index} for device #{path}: #{e.inspect}\"", ")", "on_failure", "||", "''", "end", "end"], "docstring": "Reads a string descriptor from the USB device.", "docstring_tokens": ["Reads", "a", "string", "descriptor", "from", "the", "USB", "device", "."], "sha": "d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7", "url": "https://github.com/barkerest/hidapi/blob/d4e8b7db3b0a742071b50fc282bdf8d7a3e062a7/lib/hidapi/device.rb#L452-L469", "partition": "valid"} {"repo": "gtarnovan/simple_audit", "path": "lib/simple_audit/audit.rb", "func_name": "SimpleAudit.Audit.delta", "original_string": "def delta(other_audit)\n \n return self.change_log if other_audit.nil?\n \n {}.tap do |d|\n \n # first for keys present only in this audit\n (self.change_log.keys - other_audit.change_log.keys).each do |k|\n d[k] = [nil, self.change_log[k]]\n end\n \n # .. then for keys present only in other audit\n (other_audit.change_log.keys - self.change_log.keys).each do |k|\n d[k] = [other_audit.change_log[k], nil]\n end\n \n # .. finally for keys present in both, but with different values\n self.change_log.keys.each do |k|\n if self.change_log[k] != other_audit.change_log[k]\n d[k] = [other_audit.change_log[k], self.change_log[k]]\n end\n end\n \n end\n\n end", "language": "ruby", "code": "def delta(other_audit)\n \n return self.change_log if other_audit.nil?\n \n {}.tap do |d|\n \n # first for keys present only in this audit\n (self.change_log.keys - other_audit.change_log.keys).each do |k|\n d[k] = [nil, self.change_log[k]]\n end\n \n # .. then for keys present only in other audit\n (other_audit.change_log.keys - self.change_log.keys).each do |k|\n d[k] = [other_audit.change_log[k], nil]\n end\n \n # .. finally for keys present in both, but with different values\n self.change_log.keys.each do |k|\n if self.change_log[k] != other_audit.change_log[k]\n d[k] = [other_audit.change_log[k], self.change_log[k]]\n end\n end\n \n end\n\n end", "code_tokens": ["def", "delta", "(", "other_audit", ")", "return", "self", ".", "change_log", "if", "other_audit", ".", "nil?", "{", "}", ".", "tap", "do", "|", "d", "|", "# first for keys present only in this audit", "(", "self", ".", "change_log", ".", "keys", "-", "other_audit", ".", "change_log", ".", "keys", ")", ".", "each", "do", "|", "k", "|", "d", "[", "k", "]", "=", "[", "nil", ",", "self", ".", "change_log", "[", "k", "]", "]", "end", "# .. then for keys present only in other audit", "(", "other_audit", ".", "change_log", ".", "keys", "-", "self", ".", "change_log", ".", "keys", ")", ".", "each", "do", "|", "k", "|", "d", "[", "k", "]", "=", "[", "other_audit", ".", "change_log", "[", "k", "]", ",", "nil", "]", "end", "# .. finally for keys present in both, but with different values", "self", ".", "change_log", ".", "keys", ".", "each", "do", "|", "k", "|", "if", "self", ".", "change_log", "[", "k", "]", "!=", "other_audit", ".", "change_log", "[", "k", "]", "d", "[", "k", "]", "=", "[", "other_audit", ".", "change_log", "[", "k", "]", ",", "self", ".", "change_log", "[", "k", "]", "]", "end", "end", "end", "end"], "docstring": "Computes the differences of the change logs between two audits.\n\n Returns a hash containing arrays of the form\n {\n :key_1 => [, ],\n :key_2 => [, ],\n }", "docstring_tokens": ["Computes", "the", "differences", "of", "the", "change", "logs", "between", "two", "audits", "."], "sha": "c68b8b30c51117c75a838d066b60e31213598471", "url": "https://github.com/gtarnovan/simple_audit/blob/c68b8b30c51117c75a838d066b60e31213598471/lib/simple_audit/audit.rb#L16-L41", "partition": "valid"} {"repo": "gtarnovan/simple_audit", "path": "lib/simple_audit/helper.rb", "func_name": "SimpleAudit.Helper.render_audits", "original_string": "def render_audits(audited_model)\n return '' unless audited_model.respond_to?(:audits)\n audits = (audited_model.audits || []).dup.sort{|a,b| b.created_at <=> a.created_at}\n res = ''\n audits.each_with_index do |audit, index|\n older_audit = audits[index + 1]\n res += content_tag(:div, :class => 'audit') do\n content_tag(:div, audit.action, :class => \"action #{audit.action}\") +\n content_tag(:div, audit.username, :class => \"user\") + \n content_tag(:div, l(audit.created_at), :class => \"timestamp\") + \n content_tag(:div, :class => 'changes') do\n changes = if older_audit.present?\n audit.delta(older_audit).sort{|x,y| audited_model.class.human_attribute_name(x.first) <=> audited_model.class.human_attribute_name(y.first)}.collect do |k, v| \n next if k.to_s == 'created_at' || k.to_s == 'updated_at'\n \"\\n\" + \n audited_model.class.human_attribute_name(k) +\n \":\" +\n content_tag(:span, v.last, :class => 'current') +\n content_tag(:span, v.first, :class => 'previous')\n end\n else\n audit.change_log.sort{|x,y| audited_model.class.human_attribute_name(x.first) <=> audited_model.class.human_attribute_name(y.first)}.reject{|k, v| v.blank?}.collect {|k, v| \"\\n#{audited_model.class.human_attribute_name(k)}: #{v}\"}\n end\n raw changes.join\n end \n end\n end\n raw res\n end", "language": "ruby", "code": "def render_audits(audited_model)\n return '' unless audited_model.respond_to?(:audits)\n audits = (audited_model.audits || []).dup.sort{|a,b| b.created_at <=> a.created_at}\n res = ''\n audits.each_with_index do |audit, index|\n older_audit = audits[index + 1]\n res += content_tag(:div, :class => 'audit') do\n content_tag(:div, audit.action, :class => \"action #{audit.action}\") +\n content_tag(:div, audit.username, :class => \"user\") + \n content_tag(:div, l(audit.created_at), :class => \"timestamp\") + \n content_tag(:div, :class => 'changes') do\n changes = if older_audit.present?\n audit.delta(older_audit).sort{|x,y| audited_model.class.human_attribute_name(x.first) <=> audited_model.class.human_attribute_name(y.first)}.collect do |k, v| \n next if k.to_s == 'created_at' || k.to_s == 'updated_at'\n \"\\n\" + \n audited_model.class.human_attribute_name(k) +\n \":\" +\n content_tag(:span, v.last, :class => 'current') +\n content_tag(:span, v.first, :class => 'previous')\n end\n else\n audit.change_log.sort{|x,y| audited_model.class.human_attribute_name(x.first) <=> audited_model.class.human_attribute_name(y.first)}.reject{|k, v| v.blank?}.collect {|k, v| \"\\n#{audited_model.class.human_attribute_name(k)}: #{v}\"}\n end\n raw changes.join\n end \n end\n end\n raw res\n end", "code_tokens": ["def", "render_audits", "(", "audited_model", ")", "return", "''", "unless", "audited_model", ".", "respond_to?", "(", ":audits", ")", "audits", "=", "(", "audited_model", ".", "audits", "||", "[", "]", ")", ".", "dup", ".", "sort", "{", "|", "a", ",", "b", "|", "b", ".", "created_at", "<=>", "a", ".", "created_at", "}", "res", "=", "''", "audits", ".", "each_with_index", "do", "|", "audit", ",", "index", "|", "older_audit", "=", "audits", "[", "index", "+", "1", "]", "res", "+=", "content_tag", "(", ":div", ",", ":class", "=>", "'audit'", ")", "do", "content_tag", "(", ":div", ",", "audit", ".", "action", ",", ":class", "=>", "\"action #{audit.action}\"", ")", "+", "content_tag", "(", ":div", ",", "audit", ".", "username", ",", ":class", "=>", "\"user\"", ")", "+", "content_tag", "(", ":div", ",", "l", "(", "audit", ".", "created_at", ")", ",", ":class", "=>", "\"timestamp\"", ")", "+", "content_tag", "(", ":div", ",", ":class", "=>", "'changes'", ")", "do", "changes", "=", "if", "older_audit", ".", "present?", "audit", ".", "delta", "(", "older_audit", ")", ".", "sort", "{", "|", "x", ",", "y", "|", "audited_model", ".", "class", ".", "human_attribute_name", "(", "x", ".", "first", ")", "<=>", "audited_model", ".", "class", ".", "human_attribute_name", "(", "y", ".", "first", ")", "}", ".", "collect", "do", "|", "k", ",", "v", "|", "next", "if", "k", ".", "to_s", "==", "'created_at'", "||", "k", ".", "to_s", "==", "'updated_at'", "\"\\n\"", "+", "audited_model", ".", "class", ".", "human_attribute_name", "(", "k", ")", "+", "\":\"", "+", "content_tag", "(", ":span", ",", "v", ".", "last", ",", ":class", "=>", "'current'", ")", "+", "content_tag", "(", ":span", ",", "v", ".", "first", ",", ":class", "=>", "'previous'", ")", "end", "else", "audit", ".", "change_log", ".", "sort", "{", "|", "x", ",", "y", "|", "audited_model", ".", "class", ".", "human_attribute_name", "(", "x", ".", "first", ")", "<=>", "audited_model", ".", "class", ".", "human_attribute_name", "(", "y", ".", "first", ")", "}", ".", "reject", "{", "|", "k", ",", "v", "|", "v", ".", "blank?", "}", ".", "collect", "{", "|", "k", ",", "v", "|", "\"\\n#{audited_model.class.human_attribute_name(k)}: #{v}\"", "}", "end", "raw", "changes", ".", "join", "end", "end", "end", "raw", "res", "end"], "docstring": "Render the change log for the given audited model", "docstring_tokens": ["Render", "the", "change", "log", "for", "the", "given", "audited", "model"], "sha": "c68b8b30c51117c75a838d066b60e31213598471", "url": "https://github.com/gtarnovan/simple_audit/blob/c68b8b30c51117c75a838d066b60e31213598471/lib/simple_audit/helper.rb#L6-L34", "partition": "valid"} {"repo": "guard/guard-haml", "path": "lib/guard/haml.rb", "func_name": "Guard.Haml._output_paths", "original_string": "def _output_paths(file)\n input_file_dir = File.dirname(file)\n file_name = _output_filename(file)\n file_name = \"#{file_name}.html\" if _append_html_ext_to_output_path?(file_name)\n input_file_dir = input_file_dir.gsub(Regexp.new(\"#{options[:input]}(\\/){0,1}\"), '') if options[:input]\n\n if options[:output]\n Array(options[:output]).map do |output_dir|\n File.join(output_dir, input_file_dir, file_name)\n end\n else\n if input_file_dir == ''\n [file_name]\n else\n [File.join(input_file_dir, file_name)]\n end\n end\n end", "language": "ruby", "code": "def _output_paths(file)\n input_file_dir = File.dirname(file)\n file_name = _output_filename(file)\n file_name = \"#{file_name}.html\" if _append_html_ext_to_output_path?(file_name)\n input_file_dir = input_file_dir.gsub(Regexp.new(\"#{options[:input]}(\\/){0,1}\"), '') if options[:input]\n\n if options[:output]\n Array(options[:output]).map do |output_dir|\n File.join(output_dir, input_file_dir, file_name)\n end\n else\n if input_file_dir == ''\n [file_name]\n else\n [File.join(input_file_dir, file_name)]\n end\n end\n end", "code_tokens": ["def", "_output_paths", "(", "file", ")", "input_file_dir", "=", "File", ".", "dirname", "(", "file", ")", "file_name", "=", "_output_filename", "(", "file", ")", "file_name", "=", "\"#{file_name}.html\"", "if", "_append_html_ext_to_output_path?", "(", "file_name", ")", "input_file_dir", "=", "input_file_dir", ".", "gsub", "(", "Regexp", ".", "new", "(", "\"#{options[:input]}(\\/){0,1}\"", ")", ",", "''", ")", "if", "options", "[", ":input", "]", "if", "options", "[", ":output", "]", "Array", "(", "options", "[", ":output", "]", ")", ".", "map", "do", "|", "output_dir", "|", "File", ".", "join", "(", "output_dir", ",", "input_file_dir", ",", "file_name", ")", "end", "else", "if", "input_file_dir", "==", "''", "[", "file_name", "]", "else", "[", "File", ".", "join", "(", "input_file_dir", ",", "file_name", ")", "]", "end", "end", "end"], "docstring": "Get the file path to output the html based on the file being\n built. The output path is relative to where guard is being run.\n\n @param file [String, Array] path to file being built\n @return [Array] path(s) to file where output should be written", "docstring_tokens": ["Get", "the", "file", "path", "to", "output", "the", "html", "based", "on", "the", "file", "being", "built", ".", "The", "output", "path", "is", "relative", "to", "where", "guard", "is", "being", "run", "."], "sha": "ea981b68ce86ff7dac1972b1c303b3426d2d263e", "url": "https://github.com/guard/guard-haml/blob/ea981b68ce86ff7dac1972b1c303b3426d2d263e/lib/guard/haml.rb#L84-L101", "partition": "valid"} {"repo": "guard/guard-haml", "path": "lib/guard/haml.rb", "func_name": "Guard.Haml._output_filename", "original_string": "def _output_filename(file)\n sub_strings = File.basename(file).split('.')\n base_name, extensions = sub_strings.first, sub_strings[1..-1]\n\n if extensions.last == 'haml'\n extensions.pop\n if extensions.empty?\n [base_name, options[:default_ext]].join('.')\n else\n [base_name, extensions].flatten.join('.')\n end\n else\n [base_name, extensions, options[:default_ext]].flatten.compact.join('.')\n end\n end", "language": "ruby", "code": "def _output_filename(file)\n sub_strings = File.basename(file).split('.')\n base_name, extensions = sub_strings.first, sub_strings[1..-1]\n\n if extensions.last == 'haml'\n extensions.pop\n if extensions.empty?\n [base_name, options[:default_ext]].join('.')\n else\n [base_name, extensions].flatten.join('.')\n end\n else\n [base_name, extensions, options[:default_ext]].flatten.compact.join('.')\n end\n end", "code_tokens": ["def", "_output_filename", "(", "file", ")", "sub_strings", "=", "File", ".", "basename", "(", "file", ")", ".", "split", "(", "'.'", ")", "base_name", ",", "extensions", "=", "sub_strings", ".", "first", ",", "sub_strings", "[", "1", "..", "-", "1", "]", "if", "extensions", ".", "last", "==", "'haml'", "extensions", ".", "pop", "if", "extensions", ".", "empty?", "[", "base_name", ",", "options", "[", ":default_ext", "]", "]", ".", "join", "(", "'.'", ")", "else", "[", "base_name", ",", "extensions", "]", ".", "flatten", ".", "join", "(", "'.'", ")", "end", "else", "[", "base_name", ",", "extensions", ",", "options", "[", ":default_ext", "]", "]", ".", "flatten", ".", "compact", ".", "join", "(", "'.'", ")", "end", "end"], "docstring": "Generate a file name based on the provided file path.\n Provide a logical extension.\n\n Examples:\n \"path/foo.haml\" -> \"foo.html\"\n \"path/foo\" -> \"foo.html\"\n \"path/foo.bar\" -> \"foo.bar.html\"\n \"path/foo.bar.haml\" -> \"foo.bar\"\n\n @param file String path to file\n @return String file name including extension", "docstring_tokens": ["Generate", "a", "file", "name", "based", "on", "the", "provided", "file", "path", ".", "Provide", "a", "logical", "extension", "."], "sha": "ea981b68ce86ff7dac1972b1c303b3426d2d263e", "url": "https://github.com/guard/guard-haml/blob/ea981b68ce86ff7dac1972b1c303b3426d2d263e/lib/guard/haml.rb#L115-L129", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vapp.rb", "func_name": "VCloudClient.Connection.get_vapp_by_name", "original_string": "def get_vapp_by_name(organization, vdcName, vAppName)\n result = nil\n\n get_vdc_by_name(organization, vdcName)[:vapps].each do |vapp|\n if vapp[0].downcase == vAppName.downcase\n result = get_vapp(vapp[1])\n end\n end\n\n result\n end", "language": "ruby", "code": "def get_vapp_by_name(organization, vdcName, vAppName)\n result = nil\n\n get_vdc_by_name(organization, vdcName)[:vapps].each do |vapp|\n if vapp[0].downcase == vAppName.downcase\n result = get_vapp(vapp[1])\n end\n end\n\n result\n end", "code_tokens": ["def", "get_vapp_by_name", "(", "organization", ",", "vdcName", ",", "vAppName", ")", "result", "=", "nil", "get_vdc_by_name", "(", "organization", ",", "vdcName", ")", "[", ":vapps", "]", ".", "each", "do", "|", "vapp", "|", "if", "vapp", "[", "0", "]", ".", "downcase", "==", "vAppName", ".", "downcase", "result", "=", "get_vapp", "(", "vapp", "[", "1", "]", ")", "end", "end", "result", "end"], "docstring": "Friendly helper method to fetch a vApp by name\n - Organization object\n - Organization VDC Name\n - vApp name", "docstring_tokens": ["Friendly", "helper", "method", "to", "fetch", "a", "vApp", "by", "name", "-", "Organization", "object", "-", "Organization", "VDC", "Name", "-", "vApp", "name"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp.rb#L117-L127", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vapp.rb", "func_name": "VCloudClient.Connection.poweroff_vapp", "original_string": "def poweroff_vapp(vAppId)\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.UndeployVAppParams(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\") {\n xml.UndeployPowerAction 'powerOff'\n }\n end\n\n params = {\n 'method' => :post,\n 'command' => \"/vApp/vapp-#{vAppId}/action/undeploy\"\n }\n\n response, headers = send_request(params, builder.to_xml,\n \"application/vnd.vmware.vcloud.undeployVAppParams+xml\")\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "language": "ruby", "code": "def poweroff_vapp(vAppId)\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.UndeployVAppParams(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\") {\n xml.UndeployPowerAction 'powerOff'\n }\n end\n\n params = {\n 'method' => :post,\n 'command' => \"/vApp/vapp-#{vAppId}/action/undeploy\"\n }\n\n response, headers = send_request(params, builder.to_xml,\n \"application/vnd.vmware.vcloud.undeployVAppParams+xml\")\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "code_tokens": ["def", "poweroff_vapp", "(", "vAppId", ")", "builder", "=", "Nokogiri", "::", "XML", "::", "Builder", ".", "new", "do", "|", "xml", "|", "xml", ".", "UndeployVAppParams", "(", "\"xmlns\"", "=>", "\"http://www.vmware.com/vcloud/v1.5\"", ")", "{", "xml", ".", "UndeployPowerAction", "'powerOff'", "}", "end", "params", "=", "{", "'method'", "=>", ":post", ",", "'command'", "=>", "\"/vApp/vapp-#{vAppId}/action/undeploy\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ",", "builder", ".", "to_xml", ",", "\"application/vnd.vmware.vcloud.undeployVAppParams+xml\"", ")", "task_id", "=", "headers", "[", ":location", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "task_id", "end"], "docstring": "Shutdown a given vapp", "docstring_tokens": ["Shutdown", "a", "given", "vapp"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp.rb#L145-L162", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vapp.rb", "func_name": "VCloudClient.Connection.create_vapp_from_template", "original_string": "def create_vapp_from_template(vdc, vapp_name, vapp_description, vapp_templateid, poweron=false)\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.InstantiateVAppTemplateParams(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\",\n \"xmlns:xsi\" => \"http://www.w3.org/2001/XMLSchema-instance\",\n \"xmlns:ovf\" => \"http://schemas.dmtf.org/ovf/envelope/1\",\n \"name\" => vapp_name,\n \"deploy\" => \"true\",\n \"powerOn\" => poweron) {\n xml.Description vapp_description\n xml.Source(\"href\" => \"#{@api_url}/vAppTemplate/#{vapp_templateid}\")\n }\n end\n\n params = {\n \"method\" => :post,\n \"command\" => \"/vdc/#{vdc}/action/instantiateVAppTemplate\"\n }\n\n response, headers = send_request(params, builder.to_xml, \"application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml\")\n\n vapp_id = headers[:location].gsub(/.*\\/vApp\\/vapp\\-/, \"\")\n task = response.css(\"VApp Task[operationName='vdcInstantiateVapp']\").first\n task_id = task[\"href\"].gsub(/.*\\/task\\//, \"\")\n\n { :vapp_id => vapp_id, :task_id => task_id }\n end", "language": "ruby", "code": "def create_vapp_from_template(vdc, vapp_name, vapp_description, vapp_templateid, poweron=false)\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.InstantiateVAppTemplateParams(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\",\n \"xmlns:xsi\" => \"http://www.w3.org/2001/XMLSchema-instance\",\n \"xmlns:ovf\" => \"http://schemas.dmtf.org/ovf/envelope/1\",\n \"name\" => vapp_name,\n \"deploy\" => \"true\",\n \"powerOn\" => poweron) {\n xml.Description vapp_description\n xml.Source(\"href\" => \"#{@api_url}/vAppTemplate/#{vapp_templateid}\")\n }\n end\n\n params = {\n \"method\" => :post,\n \"command\" => \"/vdc/#{vdc}/action/instantiateVAppTemplate\"\n }\n\n response, headers = send_request(params, builder.to_xml, \"application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml\")\n\n vapp_id = headers[:location].gsub(/.*\\/vApp\\/vapp\\-/, \"\")\n task = response.css(\"VApp Task[operationName='vdcInstantiateVapp']\").first\n task_id = task[\"href\"].gsub(/.*\\/task\\//, \"\")\n\n { :vapp_id => vapp_id, :task_id => task_id }\n end", "code_tokens": ["def", "create_vapp_from_template", "(", "vdc", ",", "vapp_name", ",", "vapp_description", ",", "vapp_templateid", ",", "poweron", "=", "false", ")", "builder", "=", "Nokogiri", "::", "XML", "::", "Builder", ".", "new", "do", "|", "xml", "|", "xml", ".", "InstantiateVAppTemplateParams", "(", "\"xmlns\"", "=>", "\"http://www.vmware.com/vcloud/v1.5\"", ",", "\"xmlns:xsi\"", "=>", "\"http://www.w3.org/2001/XMLSchema-instance\"", ",", "\"xmlns:ovf\"", "=>", "\"http://schemas.dmtf.org/ovf/envelope/1\"", ",", "\"name\"", "=>", "vapp_name", ",", "\"deploy\"", "=>", "\"true\"", ",", "\"powerOn\"", "=>", "poweron", ")", "{", "xml", ".", "Description", "vapp_description", "xml", ".", "Source", "(", "\"href\"", "=>", "\"#{@api_url}/vAppTemplate/#{vapp_templateid}\"", ")", "}", "end", "params", "=", "{", "\"method\"", "=>", ":post", ",", "\"command\"", "=>", "\"/vdc/#{vdc}/action/instantiateVAppTemplate\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ",", "builder", ".", "to_xml", ",", "\"application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml\"", ")", "vapp_id", "=", "headers", "[", ":location", "]", ".", "gsub", "(", "/", "\\/", "\\/", "\\-", "/", ",", "\"\"", ")", "task", "=", "response", ".", "css", "(", "\"VApp Task[operationName='vdcInstantiateVapp']\"", ")", ".", "first", "task_id", "=", "task", "[", "\"href\"", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "{", ":vapp_id", "=>", "vapp_id", ",", ":task_id", "=>", "task_id", "}", "end"], "docstring": "Create a vapp starting from a template\n\n Params:\n - vdc: the associated VDC\n - vapp_name: name of the target vapp\n - vapp_description: description of the target vapp\n - vapp_templateid: ID of the vapp template", "docstring_tokens": ["Create", "a", "vapp", "starting", "from", "a", "template"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp.rb#L207-L233", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vapp.rb", "func_name": "VCloudClient.Connection.compose_vapp_from_vm", "original_string": "def compose_vapp_from_vm(vdc, vapp_name, vapp_description, vm_list={}, network_config={})\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.ComposeVAppParams(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\",\n \"xmlns:ovf\" => \"http://schemas.dmtf.org/ovf/envelope/1\",\n \"name\" => vapp_name) {\n xml.Description vapp_description\n xml.InstantiationParams {\n xml.NetworkConfigSection {\n xml['ovf'].Info \"Configuration parameters for logical networks\"\n xml.NetworkConfig(\"networkName\" => network_config[:name]) {\n xml.Configuration {\n xml.IpScopes {\n xml.IpScope {\n xml.IsInherited(network_config[:is_inherited] || \"false\")\n xml.Gateway network_config[:gateway]\n xml.Netmask network_config[:netmask]\n xml.Dns1 network_config[:dns1] if network_config[:dns1]\n xml.Dns2 network_config[:dns2] if network_config[:dns2]\n xml.DnsSuffix network_config[:dns_suffix] if network_config[:dns_suffix]\n xml.IpRanges {\n xml.IpRange {\n xml.StartAddress network_config[:start_address]\n xml.EndAddress network_config[:end_address]\n }\n }\n }\n }\n xml.ParentNetwork(\"href\" => \"#{@api_url}/network/#{network_config[:parent_network]}\")\n xml.FenceMode network_config[:fence_mode]\n\n xml.Features {\n xml.FirewallService {\n xml.IsEnabled(network_config[:enable_firewall] || \"false\")\n }\n if network_config.has_key? :nat_type\n xml.NatService {\n xml.IsEnabled \"true\"\n xml.NatType network_config[:nat_type]\n xml.Policy(network_config[:nat_policy_type] || \"allowTraffic\")\n }\n end\n }\n }\n }\n }\n }\n vm_list.each do |vm_name, vm_id|\n xml.SourcedItem {\n xml.Source(\"href\" => \"#{@api_url}/vAppTemplate/vm-#{vm_id}\", \"name\" => vm_name)\n xml.InstantiationParams {\n xml.NetworkConnectionSection(\n \"xmlns:ovf\" => \"http://schemas.dmtf.org/ovf/envelope/1\",\n \"type\" => \"application/vnd.vmware.vcloud.networkConnectionSection+xml\",\n \"href\" => \"#{@api_url}/vAppTemplate/vm-#{vm_id}/networkConnectionSection/\") {\n xml['ovf'].Info \"Network config for sourced item\"\n xml.PrimaryNetworkConnectionIndex \"0\"\n xml.NetworkConnection(\"network\" => network_config[:name]) {\n xml.NetworkConnectionIndex \"0\"\n xml.IsConnected \"true\"\n xml.IpAddressAllocationMode(network_config[:ip_allocation_mode] || \"POOL\")\n }\n }\n }\n xml.NetworkAssignment(\"containerNetwork\" => network_config[:name], \"innerNetwork\" => network_config[:name])\n }\n end\n xml.AllEULAsAccepted \"true\"\n }\n end\n\n params = {\n \"method\" => :post,\n \"command\" => \"/vdc/#{vdc}/action/composeVApp\"\n }\n\n response, headers = send_request(params, builder.to_xml, \"application/vnd.vmware.vcloud.composeVAppParams+xml\")\n\n vapp_id = headers[:location].gsub(/.*\\/vApp\\/vapp\\-/, \"\")\n\n task = response.css(\"VApp Task[operationName='vdcComposeVapp']\").first\n task_id = task[\"href\"].gsub(/.*\\/task\\//, \"\")\n\n { :vapp_id => vapp_id, :task_id => task_id }\n end", "language": "ruby", "code": "def compose_vapp_from_vm(vdc, vapp_name, vapp_description, vm_list={}, network_config={})\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.ComposeVAppParams(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\",\n \"xmlns:ovf\" => \"http://schemas.dmtf.org/ovf/envelope/1\",\n \"name\" => vapp_name) {\n xml.Description vapp_description\n xml.InstantiationParams {\n xml.NetworkConfigSection {\n xml['ovf'].Info \"Configuration parameters for logical networks\"\n xml.NetworkConfig(\"networkName\" => network_config[:name]) {\n xml.Configuration {\n xml.IpScopes {\n xml.IpScope {\n xml.IsInherited(network_config[:is_inherited] || \"false\")\n xml.Gateway network_config[:gateway]\n xml.Netmask network_config[:netmask]\n xml.Dns1 network_config[:dns1] if network_config[:dns1]\n xml.Dns2 network_config[:dns2] if network_config[:dns2]\n xml.DnsSuffix network_config[:dns_suffix] if network_config[:dns_suffix]\n xml.IpRanges {\n xml.IpRange {\n xml.StartAddress network_config[:start_address]\n xml.EndAddress network_config[:end_address]\n }\n }\n }\n }\n xml.ParentNetwork(\"href\" => \"#{@api_url}/network/#{network_config[:parent_network]}\")\n xml.FenceMode network_config[:fence_mode]\n\n xml.Features {\n xml.FirewallService {\n xml.IsEnabled(network_config[:enable_firewall] || \"false\")\n }\n if network_config.has_key? :nat_type\n xml.NatService {\n xml.IsEnabled \"true\"\n xml.NatType network_config[:nat_type]\n xml.Policy(network_config[:nat_policy_type] || \"allowTraffic\")\n }\n end\n }\n }\n }\n }\n }\n vm_list.each do |vm_name, vm_id|\n xml.SourcedItem {\n xml.Source(\"href\" => \"#{@api_url}/vAppTemplate/vm-#{vm_id}\", \"name\" => vm_name)\n xml.InstantiationParams {\n xml.NetworkConnectionSection(\n \"xmlns:ovf\" => \"http://schemas.dmtf.org/ovf/envelope/1\",\n \"type\" => \"application/vnd.vmware.vcloud.networkConnectionSection+xml\",\n \"href\" => \"#{@api_url}/vAppTemplate/vm-#{vm_id}/networkConnectionSection/\") {\n xml['ovf'].Info \"Network config for sourced item\"\n xml.PrimaryNetworkConnectionIndex \"0\"\n xml.NetworkConnection(\"network\" => network_config[:name]) {\n xml.NetworkConnectionIndex \"0\"\n xml.IsConnected \"true\"\n xml.IpAddressAllocationMode(network_config[:ip_allocation_mode] || \"POOL\")\n }\n }\n }\n xml.NetworkAssignment(\"containerNetwork\" => network_config[:name], \"innerNetwork\" => network_config[:name])\n }\n end\n xml.AllEULAsAccepted \"true\"\n }\n end\n\n params = {\n \"method\" => :post,\n \"command\" => \"/vdc/#{vdc}/action/composeVApp\"\n }\n\n response, headers = send_request(params, builder.to_xml, \"application/vnd.vmware.vcloud.composeVAppParams+xml\")\n\n vapp_id = headers[:location].gsub(/.*\\/vApp\\/vapp\\-/, \"\")\n\n task = response.css(\"VApp Task[operationName='vdcComposeVapp']\").first\n task_id = task[\"href\"].gsub(/.*\\/task\\//, \"\")\n\n { :vapp_id => vapp_id, :task_id => task_id }\n end", "code_tokens": ["def", "compose_vapp_from_vm", "(", "vdc", ",", "vapp_name", ",", "vapp_description", ",", "vm_list", "=", "{", "}", ",", "network_config", "=", "{", "}", ")", "builder", "=", "Nokogiri", "::", "XML", "::", "Builder", ".", "new", "do", "|", "xml", "|", "xml", ".", "ComposeVAppParams", "(", "\"xmlns\"", "=>", "\"http://www.vmware.com/vcloud/v1.5\"", ",", "\"xmlns:ovf\"", "=>", "\"http://schemas.dmtf.org/ovf/envelope/1\"", ",", "\"name\"", "=>", "vapp_name", ")", "{", "xml", ".", "Description", "vapp_description", "xml", ".", "InstantiationParams", "{", "xml", ".", "NetworkConfigSection", "{", "xml", "[", "'ovf'", "]", ".", "Info", "\"Configuration parameters for logical networks\"", "xml", ".", "NetworkConfig", "(", "\"networkName\"", "=>", "network_config", "[", ":name", "]", ")", "{", "xml", ".", "Configuration", "{", "xml", ".", "IpScopes", "{", "xml", ".", "IpScope", "{", "xml", ".", "IsInherited", "(", "network_config", "[", ":is_inherited", "]", "||", "\"false\"", ")", "xml", ".", "Gateway", "network_config", "[", ":gateway", "]", "xml", ".", "Netmask", "network_config", "[", ":netmask", "]", "xml", ".", "Dns1", "network_config", "[", ":dns1", "]", "if", "network_config", "[", ":dns1", "]", "xml", ".", "Dns2", "network_config", "[", ":dns2", "]", "if", "network_config", "[", ":dns2", "]", "xml", ".", "DnsSuffix", "network_config", "[", ":dns_suffix", "]", "if", "network_config", "[", ":dns_suffix", "]", "xml", ".", "IpRanges", "{", "xml", ".", "IpRange", "{", "xml", ".", "StartAddress", "network_config", "[", ":start_address", "]", "xml", ".", "EndAddress", "network_config", "[", ":end_address", "]", "}", "}", "}", "}", "xml", ".", "ParentNetwork", "(", "\"href\"", "=>", "\"#{@api_url}/network/#{network_config[:parent_network]}\"", ")", "xml", ".", "FenceMode", "network_config", "[", ":fence_mode", "]", "xml", ".", "Features", "{", "xml", ".", "FirewallService", "{", "xml", ".", "IsEnabled", "(", "network_config", "[", ":enable_firewall", "]", "||", "\"false\"", ")", "}", "if", "network_config", ".", "has_key?", ":nat_type", "xml", ".", "NatService", "{", "xml", ".", "IsEnabled", "\"true\"", "xml", ".", "NatType", "network_config", "[", ":nat_type", "]", "xml", ".", "Policy", "(", "network_config", "[", ":nat_policy_type", "]", "||", "\"allowTraffic\"", ")", "}", "end", "}", "}", "}", "}", "}", "vm_list", ".", "each", "do", "|", "vm_name", ",", "vm_id", "|", "xml", ".", "SourcedItem", "{", "xml", ".", "Source", "(", "\"href\"", "=>", "\"#{@api_url}/vAppTemplate/vm-#{vm_id}\"", ",", "\"name\"", "=>", "vm_name", ")", "xml", ".", "InstantiationParams", "{", "xml", ".", "NetworkConnectionSection", "(", "\"xmlns:ovf\"", "=>", "\"http://schemas.dmtf.org/ovf/envelope/1\"", ",", "\"type\"", "=>", "\"application/vnd.vmware.vcloud.networkConnectionSection+xml\"", ",", "\"href\"", "=>", "\"#{@api_url}/vAppTemplate/vm-#{vm_id}/networkConnectionSection/\"", ")", "{", "xml", "[", "'ovf'", "]", ".", "Info", "\"Network config for sourced item\"", "xml", ".", "PrimaryNetworkConnectionIndex", "\"0\"", "xml", ".", "NetworkConnection", "(", "\"network\"", "=>", "network_config", "[", ":name", "]", ")", "{", "xml", ".", "NetworkConnectionIndex", "\"0\"", "xml", ".", "IsConnected", "\"true\"", "xml", ".", "IpAddressAllocationMode", "(", "network_config", "[", ":ip_allocation_mode", "]", "||", "\"POOL\"", ")", "}", "}", "}", "xml", ".", "NetworkAssignment", "(", "\"containerNetwork\"", "=>", "network_config", "[", ":name", "]", ",", "\"innerNetwork\"", "=>", "network_config", "[", ":name", "]", ")", "}", "end", "xml", ".", "AllEULAsAccepted", "\"true\"", "}", "end", "params", "=", "{", "\"method\"", "=>", ":post", ",", "\"command\"", "=>", "\"/vdc/#{vdc}/action/composeVApp\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ",", "builder", ".", "to_xml", ",", "\"application/vnd.vmware.vcloud.composeVAppParams+xml\"", ")", "vapp_id", "=", "headers", "[", ":location", "]", ".", "gsub", "(", "/", "\\/", "\\/", "\\-", "/", ",", "\"\"", ")", "task", "=", "response", ".", "css", "(", "\"VApp Task[operationName='vdcComposeVapp']\"", ")", ".", "first", "task_id", "=", "task", "[", "\"href\"", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "{", ":vapp_id", "=>", "vapp_id", ",", ":task_id", "=>", "task_id", "}", "end"], "docstring": "Compose a vapp using existing virtual machines\n\n Params:\n - vdc: the associated VDC\n - vapp_name: name of the target vapp\n - vapp_description: description of the target vapp\n - vm_list: hash with IDs of the VMs to be used in the composing process\n - network_config: hash of the network configuration for the vapp", "docstring_tokens": ["Compose", "a", "vapp", "using", "existing", "virtual", "machines"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp.rb#L244-L328", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vapp.rb", "func_name": "VCloudClient.Connection.add_vm_to_vapp", "original_string": "def add_vm_to_vapp(vapp, vm, network_config={})\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.RecomposeVAppParams(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\",\n \"xmlns:ovf\" => \"http://schemas.dmtf.org/ovf/envelope/1\",\n \"name\" => vapp[:name]) {\n xml.SourcedItem {\n xml.Source(\"href\" => \"#{@api_url}/vAppTemplate/vm-#{vm[:template_id]}\", \"name\" => vm[:vm_name])\n xml.InstantiationParams {\n xml.NetworkConnectionSection(\n \"xmlns:ovf\" => \"http://schemas.dmtf.org/ovf/envelope/1\",\n \"type\" => \"application/vnd.vmware.vcloud.networkConnectionSection+xml\",\n \"href\" => \"#{@api_url}/vAppTemplate/vm-#{vm[:template_id]}/networkConnectionSection/\") {\n xml['ovf'].Info \"Network config for sourced item\"\n xml.PrimaryNetworkConnectionIndex \"0\"\n xml.NetworkConnection(\"network\" => network_config[:name]) {\n xml.NetworkConnectionIndex \"0\"\n xml.IsConnected \"true\"\n xml.IpAddressAllocationMode(network_config[:ip_allocation_mode] || \"POOL\")\n }\n }\n }\n xml.NetworkAssignment(\"containerNetwork\" => network_config[:name], \"innerNetwork\" => network_config[:name])\n }\n xml.AllEULAsAccepted \"true\"\n }\n end\n\n params = {\n \"method\" => :post,\n \"command\" => \"/vApp/vapp-#{vapp[:id]}/action/recomposeVApp\"\n }\n\n response, headers = send_request(params, builder.to_xml, \"application/vnd.vmware.vcloud.recomposeVAppParams+xml\")\n\n task = response.css(\"Task[operationName='vdcRecomposeVapp']\").first\n task_id = task[\"href\"].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "language": "ruby", "code": "def add_vm_to_vapp(vapp, vm, network_config={})\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.RecomposeVAppParams(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\",\n \"xmlns:ovf\" => \"http://schemas.dmtf.org/ovf/envelope/1\",\n \"name\" => vapp[:name]) {\n xml.SourcedItem {\n xml.Source(\"href\" => \"#{@api_url}/vAppTemplate/vm-#{vm[:template_id]}\", \"name\" => vm[:vm_name])\n xml.InstantiationParams {\n xml.NetworkConnectionSection(\n \"xmlns:ovf\" => \"http://schemas.dmtf.org/ovf/envelope/1\",\n \"type\" => \"application/vnd.vmware.vcloud.networkConnectionSection+xml\",\n \"href\" => \"#{@api_url}/vAppTemplate/vm-#{vm[:template_id]}/networkConnectionSection/\") {\n xml['ovf'].Info \"Network config for sourced item\"\n xml.PrimaryNetworkConnectionIndex \"0\"\n xml.NetworkConnection(\"network\" => network_config[:name]) {\n xml.NetworkConnectionIndex \"0\"\n xml.IsConnected \"true\"\n xml.IpAddressAllocationMode(network_config[:ip_allocation_mode] || \"POOL\")\n }\n }\n }\n xml.NetworkAssignment(\"containerNetwork\" => network_config[:name], \"innerNetwork\" => network_config[:name])\n }\n xml.AllEULAsAccepted \"true\"\n }\n end\n\n params = {\n \"method\" => :post,\n \"command\" => \"/vApp/vapp-#{vapp[:id]}/action/recomposeVApp\"\n }\n\n response, headers = send_request(params, builder.to_xml, \"application/vnd.vmware.vcloud.recomposeVAppParams+xml\")\n\n task = response.css(\"Task[operationName='vdcRecomposeVapp']\").first\n task_id = task[\"href\"].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "code_tokens": ["def", "add_vm_to_vapp", "(", "vapp", ",", "vm", ",", "network_config", "=", "{", "}", ")", "builder", "=", "Nokogiri", "::", "XML", "::", "Builder", ".", "new", "do", "|", "xml", "|", "xml", ".", "RecomposeVAppParams", "(", "\"xmlns\"", "=>", "\"http://www.vmware.com/vcloud/v1.5\"", ",", "\"xmlns:ovf\"", "=>", "\"http://schemas.dmtf.org/ovf/envelope/1\"", ",", "\"name\"", "=>", "vapp", "[", ":name", "]", ")", "{", "xml", ".", "SourcedItem", "{", "xml", ".", "Source", "(", "\"href\"", "=>", "\"#{@api_url}/vAppTemplate/vm-#{vm[:template_id]}\"", ",", "\"name\"", "=>", "vm", "[", ":vm_name", "]", ")", "xml", ".", "InstantiationParams", "{", "xml", ".", "NetworkConnectionSection", "(", "\"xmlns:ovf\"", "=>", "\"http://schemas.dmtf.org/ovf/envelope/1\"", ",", "\"type\"", "=>", "\"application/vnd.vmware.vcloud.networkConnectionSection+xml\"", ",", "\"href\"", "=>", "\"#{@api_url}/vAppTemplate/vm-#{vm[:template_id]}/networkConnectionSection/\"", ")", "{", "xml", "[", "'ovf'", "]", ".", "Info", "\"Network config for sourced item\"", "xml", ".", "PrimaryNetworkConnectionIndex", "\"0\"", "xml", ".", "NetworkConnection", "(", "\"network\"", "=>", "network_config", "[", ":name", "]", ")", "{", "xml", ".", "NetworkConnectionIndex", "\"0\"", "xml", ".", "IsConnected", "\"true\"", "xml", ".", "IpAddressAllocationMode", "(", "network_config", "[", ":ip_allocation_mode", "]", "||", "\"POOL\"", ")", "}", "}", "}", "xml", ".", "NetworkAssignment", "(", "\"containerNetwork\"", "=>", "network_config", "[", ":name", "]", ",", "\"innerNetwork\"", "=>", "network_config", "[", ":name", "]", ")", "}", "xml", ".", "AllEULAsAccepted", "\"true\"", "}", "end", "params", "=", "{", "\"method\"", "=>", ":post", ",", "\"command\"", "=>", "\"/vApp/vapp-#{vapp[:id]}/action/recomposeVApp\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ",", "builder", ".", "to_xml", ",", "\"application/vnd.vmware.vcloud.recomposeVAppParams+xml\"", ")", "task", "=", "response", ".", "css", "(", "\"Task[operationName='vdcRecomposeVapp']\"", ")", ".", "first", "task_id", "=", "task", "[", "\"href\"", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "task_id", "end"], "docstring": "Create a new virtual machine from a template in an existing vApp.\n\n Params:\n - vapp: the target vapp\n - vm: hash with template ID and new VM name\n - network_config: hash of the network configuration for the VM", "docstring_tokens": ["Create", "a", "new", "virtual", "machine", "from", "a", "template", "in", "an", "existing", "vApp", "."], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp.rb#L337-L375", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vapp.rb", "func_name": "VCloudClient.Connection.clone_vapp", "original_string": "def clone_vapp(vdc_id, source_vapp_id, name, deploy=\"true\", poweron=\"false\", linked=\"false\", delete_source=\"false\")\n params = {\n \"method\" => :post,\n \"command\" => \"/vdc/#{vdc_id}/action/cloneVApp\"\n }\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.CloneVAppParams(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\",\n \"name\" => name,\n \"deploy\"=> deploy,\n \"linkedClone\"=> linked,\n \"powerOn\"=> poweron\n ) {\n xml.Source \"href\" => \"#{@api_url}/vApp/vapp-#{source_vapp_id}\"\n xml.IsSourceDelete delete_source\n }\n end\n response, headers = send_request(params, builder.to_xml, \"application/vnd.vmware.vcloud.cloneVAppParams+xml\")\n\n vapp_id = headers[:location].gsub(/.*\\/vApp\\/vapp\\-/, \"\")\n\n task = response.css(\"VApp Task[operationName='vdcCopyVapp']\").first\n task_id = task[\"href\"].gsub(/.*\\/task\\//, \"\")\n\n {:vapp_id => vapp_id, :task_id => task_id}\n end", "language": "ruby", "code": "def clone_vapp(vdc_id, source_vapp_id, name, deploy=\"true\", poweron=\"false\", linked=\"false\", delete_source=\"false\")\n params = {\n \"method\" => :post,\n \"command\" => \"/vdc/#{vdc_id}/action/cloneVApp\"\n }\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.CloneVAppParams(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\",\n \"name\" => name,\n \"deploy\"=> deploy,\n \"linkedClone\"=> linked,\n \"powerOn\"=> poweron\n ) {\n xml.Source \"href\" => \"#{@api_url}/vApp/vapp-#{source_vapp_id}\"\n xml.IsSourceDelete delete_source\n }\n end\n response, headers = send_request(params, builder.to_xml, \"application/vnd.vmware.vcloud.cloneVAppParams+xml\")\n\n vapp_id = headers[:location].gsub(/.*\\/vApp\\/vapp\\-/, \"\")\n\n task = response.css(\"VApp Task[operationName='vdcCopyVapp']\").first\n task_id = task[\"href\"].gsub(/.*\\/task\\//, \"\")\n\n {:vapp_id => vapp_id, :task_id => task_id}\n end", "code_tokens": ["def", "clone_vapp", "(", "vdc_id", ",", "source_vapp_id", ",", "name", ",", "deploy", "=", "\"true\"", ",", "poweron", "=", "\"false\"", ",", "linked", "=", "\"false\"", ",", "delete_source", "=", "\"false\"", ")", "params", "=", "{", "\"method\"", "=>", ":post", ",", "\"command\"", "=>", "\"/vdc/#{vdc_id}/action/cloneVApp\"", "}", "builder", "=", "Nokogiri", "::", "XML", "::", "Builder", ".", "new", "do", "|", "xml", "|", "xml", ".", "CloneVAppParams", "(", "\"xmlns\"", "=>", "\"http://www.vmware.com/vcloud/v1.5\"", ",", "\"name\"", "=>", "name", ",", "\"deploy\"", "=>", "deploy", ",", "\"linkedClone\"", "=>", "linked", ",", "\"powerOn\"", "=>", "poweron", ")", "{", "xml", ".", "Source", "\"href\"", "=>", "\"#{@api_url}/vApp/vapp-#{source_vapp_id}\"", "xml", ".", "IsSourceDelete", "delete_source", "}", "end", "response", ",", "headers", "=", "send_request", "(", "params", ",", "builder", ".", "to_xml", ",", "\"application/vnd.vmware.vcloud.cloneVAppParams+xml\"", ")", "vapp_id", "=", "headers", "[", ":location", "]", ".", "gsub", "(", "/", "\\/", "\\/", "\\-", "/", ",", "\"\"", ")", "task", "=", "response", ".", "css", "(", "\"VApp Task[operationName='vdcCopyVapp']\"", ")", ".", "first", "task_id", "=", "task", "[", "\"href\"", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "{", ":vapp_id", "=>", "vapp_id", ",", ":task_id", "=>", "task_id", "}", "end"], "docstring": "Clone a vapp in a given VDC to a new Vapp", "docstring_tokens": ["Clone", "a", "vapp", "in", "a", "given", "VDC", "to", "a", "new", "Vapp"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp.rb#L413-L438", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vapp_networking.rb", "func_name": "VCloudClient.Connection.set_vapp_network_config", "original_string": "def set_vapp_network_config(vappid, network, config={})\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vapp-#{vappid}/networkConfigSection\"\n }\n\n netconfig_response, headers = send_request(params)\n\n picked_network = netconfig_response.css(\"NetworkConfig\").select do |net|\n net.attribute('networkName').text == network[:name]\n end.first\n\n raise WrongItemIDError, \"Network named #{network[:name]} not found.\" unless picked_network\n\n picked_network.css('FenceMode').first.content = config[:fence_mode] if config[:fence_mode]\n picked_network.css('IsInherited').first.content = \"true\"\n picked_network.css('RetainNetInfoAcrossDeployments').first.content = config[:retain_network] if config[:retain_network]\n\n if config[:parent_network]\n parent_network = picked_network.css('ParentNetwork').first\n new_parent = false\n\n unless parent_network\n new_parent = true\n ipscopes = picked_network.css('IpScopes').first\n parent_network = Nokogiri::XML::Node.new \"ParentNetwork\", ipscopes.parent\n end\n\n parent_network[\"name\"] = \"#{config[:parent_network][:name]}\"\n parent_network[\"id\"] = \"#{config[:parent_network][:id]}\"\n parent_network[\"href\"] = \"#{@api_url}/admin/network/#{config[:parent_network][:id]}\"\n ipscopes.add_next_sibling(parent_network) if new_parent\n end\n\n data = netconfig_response.to_xml\n\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vapp-#{vappid}/networkConfigSection\"\n }\n\n response, headers = send_request(params, data, \"application/vnd.vmware.vcloud.networkConfigSection+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "language": "ruby", "code": "def set_vapp_network_config(vappid, network, config={})\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vapp-#{vappid}/networkConfigSection\"\n }\n\n netconfig_response, headers = send_request(params)\n\n picked_network = netconfig_response.css(\"NetworkConfig\").select do |net|\n net.attribute('networkName').text == network[:name]\n end.first\n\n raise WrongItemIDError, \"Network named #{network[:name]} not found.\" unless picked_network\n\n picked_network.css('FenceMode').first.content = config[:fence_mode] if config[:fence_mode]\n picked_network.css('IsInherited').first.content = \"true\"\n picked_network.css('RetainNetInfoAcrossDeployments').first.content = config[:retain_network] if config[:retain_network]\n\n if config[:parent_network]\n parent_network = picked_network.css('ParentNetwork').first\n new_parent = false\n\n unless parent_network\n new_parent = true\n ipscopes = picked_network.css('IpScopes').first\n parent_network = Nokogiri::XML::Node.new \"ParentNetwork\", ipscopes.parent\n end\n\n parent_network[\"name\"] = \"#{config[:parent_network][:name]}\"\n parent_network[\"id\"] = \"#{config[:parent_network][:id]}\"\n parent_network[\"href\"] = \"#{@api_url}/admin/network/#{config[:parent_network][:id]}\"\n ipscopes.add_next_sibling(parent_network) if new_parent\n end\n\n data = netconfig_response.to_xml\n\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vapp-#{vappid}/networkConfigSection\"\n }\n\n response, headers = send_request(params, data, \"application/vnd.vmware.vcloud.networkConfigSection+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "code_tokens": ["def", "set_vapp_network_config", "(", "vappid", ",", "network", ",", "config", "=", "{", "}", ")", "params", "=", "{", "'method'", "=>", ":get", ",", "'command'", "=>", "\"/vApp/vapp-#{vappid}/networkConfigSection\"", "}", "netconfig_response", ",", "headers", "=", "send_request", "(", "params", ")", "picked_network", "=", "netconfig_response", ".", "css", "(", "\"NetworkConfig\"", ")", ".", "select", "do", "|", "net", "|", "net", ".", "attribute", "(", "'networkName'", ")", ".", "text", "==", "network", "[", ":name", "]", "end", ".", "first", "raise", "WrongItemIDError", ",", "\"Network named #{network[:name]} not found.\"", "unless", "picked_network", "picked_network", ".", "css", "(", "'FenceMode'", ")", ".", "first", ".", "content", "=", "config", "[", ":fence_mode", "]", "if", "config", "[", ":fence_mode", "]", "picked_network", ".", "css", "(", "'IsInherited'", ")", ".", "first", ".", "content", "=", "\"true\"", "picked_network", ".", "css", "(", "'RetainNetInfoAcrossDeployments'", ")", ".", "first", ".", "content", "=", "config", "[", ":retain_network", "]", "if", "config", "[", ":retain_network", "]", "if", "config", "[", ":parent_network", "]", "parent_network", "=", "picked_network", ".", "css", "(", "'ParentNetwork'", ")", ".", "first", "new_parent", "=", "false", "unless", "parent_network", "new_parent", "=", "true", "ipscopes", "=", "picked_network", ".", "css", "(", "'IpScopes'", ")", ".", "first", "parent_network", "=", "Nokogiri", "::", "XML", "::", "Node", ".", "new", "\"ParentNetwork\"", ",", "ipscopes", ".", "parent", "end", "parent_network", "[", "\"name\"", "]", "=", "\"#{config[:parent_network][:name]}\"", "parent_network", "[", "\"id\"", "]", "=", "\"#{config[:parent_network][:id]}\"", "parent_network", "[", "\"href\"", "]", "=", "\"#{@api_url}/admin/network/#{config[:parent_network][:id]}\"", "ipscopes", ".", "add_next_sibling", "(", "parent_network", ")", "if", "new_parent", "end", "data", "=", "netconfig_response", ".", "to_xml", "params", "=", "{", "'method'", "=>", ":put", ",", "'command'", "=>", "\"/vApp/vapp-#{vappid}/networkConfigSection\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ",", "data", ",", "\"application/vnd.vmware.vcloud.networkConfigSection+xml\"", ")", "task_id", "=", "headers", "[", ":location", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "task_id", "end"], "docstring": "Set vApp Network Config\n\n Retrieve the existing network config section and edit it\n to ensure settings are not lost", "docstring_tokens": ["Set", "vApp", "Network", "Config"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L8-L53", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vapp_networking.rb", "func_name": "VCloudClient.Connection.set_vapp_port_forwarding_rules", "original_string": "def set_vapp_port_forwarding_rules(vappid, network_name, config={})\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.NetworkConfigSection(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\",\n \"xmlns:ovf\" => \"http://schemas.dmtf.org/ovf/envelope/1\") {\n xml['ovf'].Info \"Network configuration\"\n xml.NetworkConfig(\"networkName\" => network_name) {\n xml.Configuration {\n xml.ParentNetwork(\"href\" => \"#{@api_url}/network/#{config[:parent_network]}\")\n xml.FenceMode(config[:fence_mode] || 'isolated')\n xml.Features {\n xml.NatService {\n xml.IsEnabled \"true\"\n xml.NatType \"portForwarding\"\n xml.Policy(config[:nat_policy_type] || \"allowTraffic\")\n config[:nat_rules].each do |nat_rule|\n xml.NatRule {\n xml.VmRule {\n xml.ExternalPort nat_rule[:nat_external_port]\n xml.VAppScopedVmId nat_rule[:vm_scoped_local_id]\n xml.VmNicId(nat_rule[:nat_vmnic_id] || \"0\")\n xml.InternalPort nat_rule[:nat_internal_port]\n xml.Protocol(nat_rule[:nat_protocol] || \"TCP\")\n }\n }\n end\n }\n }\n }\n }\n }\n end\n\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vapp-#{vappid}/networkConfigSection\"\n }\n\n response, headers = send_request(params, builder.to_xml, \"application/vnd.vmware.vcloud.networkConfigSection+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "language": "ruby", "code": "def set_vapp_port_forwarding_rules(vappid, network_name, config={})\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.NetworkConfigSection(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\",\n \"xmlns:ovf\" => \"http://schemas.dmtf.org/ovf/envelope/1\") {\n xml['ovf'].Info \"Network configuration\"\n xml.NetworkConfig(\"networkName\" => network_name) {\n xml.Configuration {\n xml.ParentNetwork(\"href\" => \"#{@api_url}/network/#{config[:parent_network]}\")\n xml.FenceMode(config[:fence_mode] || 'isolated')\n xml.Features {\n xml.NatService {\n xml.IsEnabled \"true\"\n xml.NatType \"portForwarding\"\n xml.Policy(config[:nat_policy_type] || \"allowTraffic\")\n config[:nat_rules].each do |nat_rule|\n xml.NatRule {\n xml.VmRule {\n xml.ExternalPort nat_rule[:nat_external_port]\n xml.VAppScopedVmId nat_rule[:vm_scoped_local_id]\n xml.VmNicId(nat_rule[:nat_vmnic_id] || \"0\")\n xml.InternalPort nat_rule[:nat_internal_port]\n xml.Protocol(nat_rule[:nat_protocol] || \"TCP\")\n }\n }\n end\n }\n }\n }\n }\n }\n end\n\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vapp-#{vappid}/networkConfigSection\"\n }\n\n response, headers = send_request(params, builder.to_xml, \"application/vnd.vmware.vcloud.networkConfigSection+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "code_tokens": ["def", "set_vapp_port_forwarding_rules", "(", "vappid", ",", "network_name", ",", "config", "=", "{", "}", ")", "builder", "=", "Nokogiri", "::", "XML", "::", "Builder", ".", "new", "do", "|", "xml", "|", "xml", ".", "NetworkConfigSection", "(", "\"xmlns\"", "=>", "\"http://www.vmware.com/vcloud/v1.5\"", ",", "\"xmlns:ovf\"", "=>", "\"http://schemas.dmtf.org/ovf/envelope/1\"", ")", "{", "xml", "[", "'ovf'", "]", ".", "Info", "\"Network configuration\"", "xml", ".", "NetworkConfig", "(", "\"networkName\"", "=>", "network_name", ")", "{", "xml", ".", "Configuration", "{", "xml", ".", "ParentNetwork", "(", "\"href\"", "=>", "\"#{@api_url}/network/#{config[:parent_network]}\"", ")", "xml", ".", "FenceMode", "(", "config", "[", ":fence_mode", "]", "||", "'isolated'", ")", "xml", ".", "Features", "{", "xml", ".", "NatService", "{", "xml", ".", "IsEnabled", "\"true\"", "xml", ".", "NatType", "\"portForwarding\"", "xml", ".", "Policy", "(", "config", "[", ":nat_policy_type", "]", "||", "\"allowTraffic\"", ")", "config", "[", ":nat_rules", "]", ".", "each", "do", "|", "nat_rule", "|", "xml", ".", "NatRule", "{", "xml", ".", "VmRule", "{", "xml", ".", "ExternalPort", "nat_rule", "[", ":nat_external_port", "]", "xml", ".", "VAppScopedVmId", "nat_rule", "[", ":vm_scoped_local_id", "]", "xml", ".", "VmNicId", "(", "nat_rule", "[", ":nat_vmnic_id", "]", "||", "\"0\"", ")", "xml", ".", "InternalPort", "nat_rule", "[", ":nat_internal_port", "]", "xml", ".", "Protocol", "(", "nat_rule", "[", ":nat_protocol", "]", "||", "\"TCP\"", ")", "}", "}", "end", "}", "}", "}", "}", "}", "end", "params", "=", "{", "'method'", "=>", ":put", ",", "'command'", "=>", "\"/vApp/vapp-#{vappid}/networkConfigSection\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ",", "builder", ".", "to_xml", ",", "\"application/vnd.vmware.vcloud.networkConfigSection+xml\"", ")", "task_id", "=", "headers", "[", ":location", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "task_id", "end"], "docstring": "Set vApp port forwarding rules\n\n - vappid: id of the vapp to be modified\n - network_name: name of the vapp network to be modified\n - config: hash with network configuration specifications, must contain an array inside :nat_rules with the nat rules to be applied.", "docstring_tokens": ["Set", "vApp", "port", "forwarding", "rules"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L107-L149", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vapp_networking.rb", "func_name": "VCloudClient.Connection.get_vapp_port_forwarding_rules", "original_string": "def get_vapp_port_forwarding_rules(vAppId)\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vapp-#{vAppId}/networkConfigSection\"\n }\n\n response, headers = send_request(params)\n\n # FIXME: this will return nil if the vApp uses multiple vApp Networks\n # with Edge devices in natRouted/portForwarding mode.\n config = response.css('NetworkConfigSection/NetworkConfig/Configuration')\n fenceMode = config.css('/FenceMode').text\n natType = config.css('/Features/NatService/NatType').text\n\n raise InvalidStateError, \"Invalid request because FenceMode must be set to natRouted.\" unless fenceMode == \"natRouted\"\n raise InvalidStateError, \"Invalid request because NatType must be set to portForwarding.\" unless natType == \"portForwarding\"\n\n nat_rules = {}\n config.css('/Features/NatService/NatRule').each do |rule|\n # portforwarding rules information\n ruleId = rule.css('Id').text\n vmRule = rule.css('VmRule')\n\n nat_rules[rule.css('Id').text] = {\n :ExternalIpAddress => vmRule.css('ExternalIpAddress').text,\n :ExternalPort => vmRule.css('ExternalPort').text,\n :VAppScopedVmId => vmRule.css('VAppScopedVmId').text,\n :VmNicId => vmRule.css('VmNicId').text,\n :InternalPort => vmRule.css('InternalPort').text,\n :Protocol => vmRule.css('Protocol').text\n }\n end\n nat_rules\n end", "language": "ruby", "code": "def get_vapp_port_forwarding_rules(vAppId)\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vapp-#{vAppId}/networkConfigSection\"\n }\n\n response, headers = send_request(params)\n\n # FIXME: this will return nil if the vApp uses multiple vApp Networks\n # with Edge devices in natRouted/portForwarding mode.\n config = response.css('NetworkConfigSection/NetworkConfig/Configuration')\n fenceMode = config.css('/FenceMode').text\n natType = config.css('/Features/NatService/NatType').text\n\n raise InvalidStateError, \"Invalid request because FenceMode must be set to natRouted.\" unless fenceMode == \"natRouted\"\n raise InvalidStateError, \"Invalid request because NatType must be set to portForwarding.\" unless natType == \"portForwarding\"\n\n nat_rules = {}\n config.css('/Features/NatService/NatRule').each do |rule|\n # portforwarding rules information\n ruleId = rule.css('Id').text\n vmRule = rule.css('VmRule')\n\n nat_rules[rule.css('Id').text] = {\n :ExternalIpAddress => vmRule.css('ExternalIpAddress').text,\n :ExternalPort => vmRule.css('ExternalPort').text,\n :VAppScopedVmId => vmRule.css('VAppScopedVmId').text,\n :VmNicId => vmRule.css('VmNicId').text,\n :InternalPort => vmRule.css('InternalPort').text,\n :Protocol => vmRule.css('Protocol').text\n }\n end\n nat_rules\n end", "code_tokens": ["def", "get_vapp_port_forwarding_rules", "(", "vAppId", ")", "params", "=", "{", "'method'", "=>", ":get", ",", "'command'", "=>", "\"/vApp/vapp-#{vAppId}/networkConfigSection\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ")", "# FIXME: this will return nil if the vApp uses multiple vApp Networks", "# with Edge devices in natRouted/portForwarding mode.", "config", "=", "response", ".", "css", "(", "'NetworkConfigSection/NetworkConfig/Configuration'", ")", "fenceMode", "=", "config", ".", "css", "(", "'/FenceMode'", ")", ".", "text", "natType", "=", "config", ".", "css", "(", "'/Features/NatService/NatType'", ")", ".", "text", "raise", "InvalidStateError", ",", "\"Invalid request because FenceMode must be set to natRouted.\"", "unless", "fenceMode", "==", "\"natRouted\"", "raise", "InvalidStateError", ",", "\"Invalid request because NatType must be set to portForwarding.\"", "unless", "natType", "==", "\"portForwarding\"", "nat_rules", "=", "{", "}", "config", ".", "css", "(", "'/Features/NatService/NatRule'", ")", ".", "each", "do", "|", "rule", "|", "# portforwarding rules information", "ruleId", "=", "rule", ".", "css", "(", "'Id'", ")", ".", "text", "vmRule", "=", "rule", ".", "css", "(", "'VmRule'", ")", "nat_rules", "[", "rule", ".", "css", "(", "'Id'", ")", ".", "text", "]", "=", "{", ":ExternalIpAddress", "=>", "vmRule", ".", "css", "(", "'ExternalIpAddress'", ")", ".", "text", ",", ":ExternalPort", "=>", "vmRule", ".", "css", "(", "'ExternalPort'", ")", ".", "text", ",", ":VAppScopedVmId", "=>", "vmRule", ".", "css", "(", "'VAppScopedVmId'", ")", ".", "text", ",", ":VmNicId", "=>", "vmRule", ".", "css", "(", "'VmNicId'", ")", ".", "text", ",", ":InternalPort", "=>", "vmRule", ".", "css", "(", "'InternalPort'", ")", ".", "text", ",", ":Protocol", "=>", "vmRule", ".", "css", "(", "'Protocol'", ")", ".", "text", "}", "end", "nat_rules", "end"], "docstring": "Get vApp port forwarding rules\n\n - vappid: id of the vApp", "docstring_tokens": ["Get", "vApp", "port", "forwarding", "rules"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L155-L188", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vapp_networking.rb", "func_name": "VCloudClient.Connection.merge_network_config", "original_string": "def merge_network_config(vapp_networks, new_network, config)\n net_configuration = new_network.css('Configuration').first\n\n fence_mode = new_network.css('FenceMode').first\n fence_mode.content = config[:fence_mode] || 'isolated'\n\n network_features = Nokogiri::XML::Node.new \"Features\", net_configuration\n firewall_service = Nokogiri::XML::Node.new \"FirewallService\", network_features\n firewall_enabled = Nokogiri::XML::Node.new \"IsEnabled\", firewall_service\n firewall_enabled.content = config[:firewall_enabled] || \"false\"\n\n firewall_service.add_child(firewall_enabled)\n network_features.add_child(firewall_service)\n net_configuration.add_child(network_features)\n\n if config[:parent_network]\n # At this stage, set itself as parent network\n parent_network = Nokogiri::XML::Node.new \"ParentNetwork\", net_configuration\n parent_network[\"href\"] = \"#{@api_url}/network/#{config[:parent_network][:id]}\"\n parent_network[\"name\"] = config[:parent_network][:name]\n parent_network[\"type\"] = \"application/vnd.vmware.vcloud.network+xml\"\n new_network.css('IpScopes').first.add_next_sibling(parent_network)\n end\n\n vapp_networks.to_xml.gsub(\"\", new_network.css('Configuration').to_xml)\n end", "language": "ruby", "code": "def merge_network_config(vapp_networks, new_network, config)\n net_configuration = new_network.css('Configuration').first\n\n fence_mode = new_network.css('FenceMode').first\n fence_mode.content = config[:fence_mode] || 'isolated'\n\n network_features = Nokogiri::XML::Node.new \"Features\", net_configuration\n firewall_service = Nokogiri::XML::Node.new \"FirewallService\", network_features\n firewall_enabled = Nokogiri::XML::Node.new \"IsEnabled\", firewall_service\n firewall_enabled.content = config[:firewall_enabled] || \"false\"\n\n firewall_service.add_child(firewall_enabled)\n network_features.add_child(firewall_service)\n net_configuration.add_child(network_features)\n\n if config[:parent_network]\n # At this stage, set itself as parent network\n parent_network = Nokogiri::XML::Node.new \"ParentNetwork\", net_configuration\n parent_network[\"href\"] = \"#{@api_url}/network/#{config[:parent_network][:id]}\"\n parent_network[\"name\"] = config[:parent_network][:name]\n parent_network[\"type\"] = \"application/vnd.vmware.vcloud.network+xml\"\n new_network.css('IpScopes').first.add_next_sibling(parent_network)\n end\n\n vapp_networks.to_xml.gsub(\"\", new_network.css('Configuration').to_xml)\n end", "code_tokens": ["def", "merge_network_config", "(", "vapp_networks", ",", "new_network", ",", "config", ")", "net_configuration", "=", "new_network", ".", "css", "(", "'Configuration'", ")", ".", "first", "fence_mode", "=", "new_network", ".", "css", "(", "'FenceMode'", ")", ".", "first", "fence_mode", ".", "content", "=", "config", "[", ":fence_mode", "]", "||", "'isolated'", "network_features", "=", "Nokogiri", "::", "XML", "::", "Node", ".", "new", "\"Features\"", ",", "net_configuration", "firewall_service", "=", "Nokogiri", "::", "XML", "::", "Node", ".", "new", "\"FirewallService\"", ",", "network_features", "firewall_enabled", "=", "Nokogiri", "::", "XML", "::", "Node", ".", "new", "\"IsEnabled\"", ",", "firewall_service", "firewall_enabled", ".", "content", "=", "config", "[", ":firewall_enabled", "]", "||", "\"false\"", "firewall_service", ".", "add_child", "(", "firewall_enabled", ")", "network_features", ".", "add_child", "(", "firewall_service", ")", "net_configuration", ".", "add_child", "(", "network_features", ")", "if", "config", "[", ":parent_network", "]", "# At this stage, set itself as parent network", "parent_network", "=", "Nokogiri", "::", "XML", "::", "Node", ".", "new", "\"ParentNetwork\"", ",", "net_configuration", "parent_network", "[", "\"href\"", "]", "=", "\"#{@api_url}/network/#{config[:parent_network][:id]}\"", "parent_network", "[", "\"name\"", "]", "=", "config", "[", ":parent_network", "]", "[", ":name", "]", "parent_network", "[", "\"type\"", "]", "=", "\"application/vnd.vmware.vcloud.network+xml\"", "new_network", ".", "css", "(", "'IpScopes'", ")", ".", "first", ".", "add_next_sibling", "(", "parent_network", ")", "end", "vapp_networks", ".", "to_xml", ".", "gsub", "(", "\"\"", ",", "new_network", ".", "css", "(", "'Configuration'", ")", ".", "to_xml", ")", "end"], "docstring": "Merge the Configuration section of a new network and add specific configuration", "docstring_tokens": ["Merge", "the", "Configuration", "section", "of", "a", "new", "network", "and", "add", "specific", "configuration"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L224-L249", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vapp_networking.rb", "func_name": "VCloudClient.Connection.add_network_to_vapp", "original_string": "def add_network_to_vapp(vAppId, network_section)\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vapp-#{vAppId}/networkConfigSection\"\n }\n\n response, headers = send_request(params, network_section, \"application/vnd.vmware.vcloud.networkConfigSection+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "language": "ruby", "code": "def add_network_to_vapp(vAppId, network_section)\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vapp-#{vAppId}/networkConfigSection\"\n }\n\n response, headers = send_request(params, network_section, \"application/vnd.vmware.vcloud.networkConfigSection+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "code_tokens": ["def", "add_network_to_vapp", "(", "vAppId", ",", "network_section", ")", "params", "=", "{", "'method'", "=>", ":put", ",", "'command'", "=>", "\"/vApp/vapp-#{vAppId}/networkConfigSection\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ",", "network_section", ",", "\"application/vnd.vmware.vcloud.networkConfigSection+xml\"", ")", "task_id", "=", "headers", "[", ":location", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "task_id", "end"], "docstring": "Add a new network to a vApp", "docstring_tokens": ["Add", "a", "new", "network", "to", "a", "vApp"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L253-L263", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vapp_networking.rb", "func_name": "VCloudClient.Connection.create_fake_network_node", "original_string": "def create_fake_network_node(vapp_networks, network_name)\n parent_section = vapp_networks.css('NetworkConfigSection').first\n new_network = Nokogiri::XML::Node.new \"NetworkConfig\", parent_section\n new_network['networkName'] = network_name\n placeholder = Nokogiri::XML::Node.new \"PLACEHOLDER\", new_network\n new_network.add_child placeholder\n parent_section.add_child(new_network)\n vapp_networks\n end", "language": "ruby", "code": "def create_fake_network_node(vapp_networks, network_name)\n parent_section = vapp_networks.css('NetworkConfigSection').first\n new_network = Nokogiri::XML::Node.new \"NetworkConfig\", parent_section\n new_network['networkName'] = network_name\n placeholder = Nokogiri::XML::Node.new \"PLACEHOLDER\", new_network\n new_network.add_child placeholder\n parent_section.add_child(new_network)\n vapp_networks\n end", "code_tokens": ["def", "create_fake_network_node", "(", "vapp_networks", ",", "network_name", ")", "parent_section", "=", "vapp_networks", ".", "css", "(", "'NetworkConfigSection'", ")", ".", "first", "new_network", "=", "Nokogiri", "::", "XML", "::", "Node", ".", "new", "\"NetworkConfig\"", ",", "parent_section", "new_network", "[", "'networkName'", "]", "=", "network_name", "placeholder", "=", "Nokogiri", "::", "XML", "::", "Node", ".", "new", "\"PLACEHOLDER\"", ",", "new_network", "new_network", ".", "add_child", "placeholder", "parent_section", ".", "add_child", "(", "new_network", ")", "vapp_networks", "end"], "docstring": "Create a fake NetworkConfig node whose content will be replaced later\n\n Note: this is a hack to avoid wrong merges through Nokogiri\n that would add a default: namespace", "docstring_tokens": ["Create", "a", "fake", "NetworkConfig", "node", "whose", "content", "will", "be", "replaced", "later"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L270-L278", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vapp_networking.rb", "func_name": "VCloudClient.Connection.create_internal_network_node", "original_string": "def create_internal_network_node(network_config)\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.Configuration {\n xml.IpScopes {\n xml.IpScope {\n xml.IsInherited(network_config[:is_inherited] || \"false\")\n xml.Gateway network_config[:gateway]\n xml.Netmask network_config[:netmask]\n xml.Dns1 network_config[:dns1] if network_config[:dns1]\n xml.Dns2 network_config[:dns2] if network_config[:dns2]\n xml.DnsSuffix network_config[:dns_suffix] if network_config[:dns_suffix]\n xml.IsEnabled(network_config[:is_enabled] || true)\n xml.IpRanges {\n xml.IpRange {\n xml.StartAddress network_config[:start_address]\n xml.EndAddress network_config[:end_address]\n }\n }\n }\n }\n xml.FenceMode 'isolated'\n xml.RetainNetInfoAcrossDeployments(network_config[:retain_info] || false)\n }\n end\n builder.doc\n end", "language": "ruby", "code": "def create_internal_network_node(network_config)\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.Configuration {\n xml.IpScopes {\n xml.IpScope {\n xml.IsInherited(network_config[:is_inherited] || \"false\")\n xml.Gateway network_config[:gateway]\n xml.Netmask network_config[:netmask]\n xml.Dns1 network_config[:dns1] if network_config[:dns1]\n xml.Dns2 network_config[:dns2] if network_config[:dns2]\n xml.DnsSuffix network_config[:dns_suffix] if network_config[:dns_suffix]\n xml.IsEnabled(network_config[:is_enabled] || true)\n xml.IpRanges {\n xml.IpRange {\n xml.StartAddress network_config[:start_address]\n xml.EndAddress network_config[:end_address]\n }\n }\n }\n }\n xml.FenceMode 'isolated'\n xml.RetainNetInfoAcrossDeployments(network_config[:retain_info] || false)\n }\n end\n builder.doc\n end", "code_tokens": ["def", "create_internal_network_node", "(", "network_config", ")", "builder", "=", "Nokogiri", "::", "XML", "::", "Builder", ".", "new", "do", "|", "xml", "|", "xml", ".", "Configuration", "{", "xml", ".", "IpScopes", "{", "xml", ".", "IpScope", "{", "xml", ".", "IsInherited", "(", "network_config", "[", ":is_inherited", "]", "||", "\"false\"", ")", "xml", ".", "Gateway", "network_config", "[", ":gateway", "]", "xml", ".", "Netmask", "network_config", "[", ":netmask", "]", "xml", ".", "Dns1", "network_config", "[", ":dns1", "]", "if", "network_config", "[", ":dns1", "]", "xml", ".", "Dns2", "network_config", "[", ":dns2", "]", "if", "network_config", "[", ":dns2", "]", "xml", ".", "DnsSuffix", "network_config", "[", ":dns_suffix", "]", "if", "network_config", "[", ":dns_suffix", "]", "xml", ".", "IsEnabled", "(", "network_config", "[", ":is_enabled", "]", "||", "true", ")", "xml", ".", "IpRanges", "{", "xml", ".", "IpRange", "{", "xml", ".", "StartAddress", "network_config", "[", ":start_address", "]", "xml", ".", "EndAddress", "network_config", "[", ":end_address", "]", "}", "}", "}", "}", "xml", ".", "FenceMode", "'isolated'", "xml", ".", "RetainNetInfoAcrossDeployments", "(", "network_config", "[", ":retain_info", "]", "||", "false", ")", "}", "end", "builder", ".", "doc", "end"], "docstring": "Create a fake Configuration node for internal networking", "docstring_tokens": ["Create", "a", "fake", "Configuration", "node", "for", "internal", "networking"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L282-L307", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vapp_networking.rb", "func_name": "VCloudClient.Connection.generate_network_section", "original_string": "def generate_network_section(vAppId, network, config, type)\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vapp-#{vAppId}/networkConfigSection\"\n }\n\n vapp_networks, headers = send_request(params)\n create_fake_network_node(vapp_networks, network[:name])\n\n if type.to_sym == :internal\n # Create a network configuration based on the config\n new_network = create_internal_network_node(config)\n else\n # Retrieve the requested network and prepare it for customization\n new_network = get_base_network(network[:id])\n end\n\n merge_network_config(vapp_networks, new_network, config)\n end", "language": "ruby", "code": "def generate_network_section(vAppId, network, config, type)\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vapp-#{vAppId}/networkConfigSection\"\n }\n\n vapp_networks, headers = send_request(params)\n create_fake_network_node(vapp_networks, network[:name])\n\n if type.to_sym == :internal\n # Create a network configuration based on the config\n new_network = create_internal_network_node(config)\n else\n # Retrieve the requested network and prepare it for customization\n new_network = get_base_network(network[:id])\n end\n\n merge_network_config(vapp_networks, new_network, config)\n end", "code_tokens": ["def", "generate_network_section", "(", "vAppId", ",", "network", ",", "config", ",", "type", ")", "params", "=", "{", "'method'", "=>", ":get", ",", "'command'", "=>", "\"/vApp/vapp-#{vAppId}/networkConfigSection\"", "}", "vapp_networks", ",", "headers", "=", "send_request", "(", "params", ")", "create_fake_network_node", "(", "vapp_networks", ",", "network", "[", ":name", "]", ")", "if", "type", ".", "to_sym", "==", ":internal", "# Create a network configuration based on the config", "new_network", "=", "create_internal_network_node", "(", "config", ")", "else", "# Retrieve the requested network and prepare it for customization", "new_network", "=", "get_base_network", "(", "network", "[", ":id", "]", ")", "end", "merge_network_config", "(", "vapp_networks", ",", "new_network", ",", "config", ")", "end"], "docstring": "Create a NetworkConfigSection for a new internal or external network", "docstring_tokens": ["Create", "a", "NetworkConfigSection", "for", "a", "new", "internal", "or", "external", "network"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vapp_networking.rb#L311-L329", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/connection.rb", "func_name": "VCloudClient.Connection.login", "original_string": "def login\n params = {\n 'method' => :post,\n 'command' => '/sessions'\n }\n\n response, headers = send_request(params)\n\n if !headers.has_key?(:x_vcloud_authorization)\n raise \"Unable to authenticate: missing x_vcloud_authorization header\"\n end\n\n extensibility_link = response.css(\"Link[rel='down:extensibility']\")\n @extensibility = extensibility_link.first['href'] unless extensibility_link.empty?\n\n @auth_key = headers[:x_vcloud_authorization]\n end", "language": "ruby", "code": "def login\n params = {\n 'method' => :post,\n 'command' => '/sessions'\n }\n\n response, headers = send_request(params)\n\n if !headers.has_key?(:x_vcloud_authorization)\n raise \"Unable to authenticate: missing x_vcloud_authorization header\"\n end\n\n extensibility_link = response.css(\"Link[rel='down:extensibility']\")\n @extensibility = extensibility_link.first['href'] unless extensibility_link.empty?\n\n @auth_key = headers[:x_vcloud_authorization]\n end", "code_tokens": ["def", "login", "params", "=", "{", "'method'", "=>", ":post", ",", "'command'", "=>", "'/sessions'", "}", "response", ",", "headers", "=", "send_request", "(", "params", ")", "if", "!", "headers", ".", "has_key?", "(", ":x_vcloud_authorization", ")", "raise", "\"Unable to authenticate: missing x_vcloud_authorization header\"", "end", "extensibility_link", "=", "response", ".", "css", "(", "\"Link[rel='down:extensibility']\"", ")", "@extensibility", "=", "extensibility_link", ".", "first", "[", "'href'", "]", "unless", "extensibility_link", ".", "empty?", "@auth_key", "=", "headers", "[", ":x_vcloud_authorization", "]", "end"], "docstring": "Authenticate against the specified server", "docstring_tokens": ["Authenticate", "against", "the", "specified", "server"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/connection.rb#L66-L82", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/connection.rb", "func_name": "VCloudClient.Connection.get_task", "original_string": "def get_task(taskid)\n params = {\n 'method' => :get,\n 'command' => \"/task/#{taskid}\"\n }\n\n response, headers = send_request(params)\n\n task = response.css('Task').first\n status = task['status']\n start_time = task['startTime']\n end_time = task['endTime']\n\n { :status => status, :start_time => start_time, :end_time => end_time, :response => response }\n end", "language": "ruby", "code": "def get_task(taskid)\n params = {\n 'method' => :get,\n 'command' => \"/task/#{taskid}\"\n }\n\n response, headers = send_request(params)\n\n task = response.css('Task').first\n status = task['status']\n start_time = task['startTime']\n end_time = task['endTime']\n\n { :status => status, :start_time => start_time, :end_time => end_time, :response => response }\n end", "code_tokens": ["def", "get_task", "(", "taskid", ")", "params", "=", "{", "'method'", "=>", ":get", ",", "'command'", "=>", "\"/task/#{taskid}\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ")", "task", "=", "response", ".", "css", "(", "'Task'", ")", ".", "first", "status", "=", "task", "[", "'status'", "]", "start_time", "=", "task", "[", "'startTime'", "]", "end_time", "=", "task", "[", "'endTime'", "]", "{", ":status", "=>", "status", ",", ":start_time", "=>", "start_time", ",", ":end_time", "=>", "end_time", ",", ":response", "=>", "response", "}", "end"], "docstring": "Fetch information for a given task", "docstring_tokens": ["Fetch", "information", "for", "a", "given", "task"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/connection.rb#L100-L114", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/connection.rb", "func_name": "VCloudClient.Connection.wait_task_completion", "original_string": "def wait_task_completion(taskid)\n errormsg = nil\n task = {}\n\n loop do\n task = get_task(taskid)\n break if task[:status] != 'running'\n sleep 1\n end\n\n if task[:status] == 'error'\n errormsg = task[:response].css(\"Error\").first\n errormsg = \"Error code #{errormsg['majorErrorCode']} - #{errormsg['message']}\"\n end\n\n { :status => task[:status], :errormsg => errormsg,\n :start_time => task[:start_time], :end_time => task[:end_time] }\n end", "language": "ruby", "code": "def wait_task_completion(taskid)\n errormsg = nil\n task = {}\n\n loop do\n task = get_task(taskid)\n break if task[:status] != 'running'\n sleep 1\n end\n\n if task[:status] == 'error'\n errormsg = task[:response].css(\"Error\").first\n errormsg = \"Error code #{errormsg['majorErrorCode']} - #{errormsg['message']}\"\n end\n\n { :status => task[:status], :errormsg => errormsg,\n :start_time => task[:start_time], :end_time => task[:end_time] }\n end", "code_tokens": ["def", "wait_task_completion", "(", "taskid", ")", "errormsg", "=", "nil", "task", "=", "{", "}", "loop", "do", "task", "=", "get_task", "(", "taskid", ")", "break", "if", "task", "[", ":status", "]", "!=", "'running'", "sleep", "1", "end", "if", "task", "[", ":status", "]", "==", "'error'", "errormsg", "=", "task", "[", ":response", "]", ".", "css", "(", "\"Error\"", ")", ".", "first", "errormsg", "=", "\"Error code #{errormsg['majorErrorCode']} - #{errormsg['message']}\"", "end", "{", ":status", "=>", "task", "[", ":status", "]", ",", ":errormsg", "=>", "errormsg", ",", ":start_time", "=>", "task", "[", ":start_time", "]", ",", ":end_time", "=>", "task", "[", ":end_time", "]", "}", "end"], "docstring": "Poll a given task until completion", "docstring_tokens": ["Poll", "a", "given", "task", "until", "completion"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/connection.rb#L118-L135", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/connection.rb", "func_name": "VCloudClient.Connection.send_request", "original_string": "def send_request(params, payload=nil, content_type=nil)\n req_params = setup_request(params, payload, content_type)\n\n handled_request(req_params) do\n request = RestClient::Request.new(req_params)\n\n response = request.execute\n if ![200, 201, 202, 204].include?(response.code)\n @logger.warn \"Warning: unattended code #{response.code}\"\n end\n\n parsed_response = Nokogiri::XML(response)\n @logger.debug \"Send request result: #{parsed_response}\"\n\n [parsed_response, response.headers]\n end\n end", "language": "ruby", "code": "def send_request(params, payload=nil, content_type=nil)\n req_params = setup_request(params, payload, content_type)\n\n handled_request(req_params) do\n request = RestClient::Request.new(req_params)\n\n response = request.execute\n if ![200, 201, 202, 204].include?(response.code)\n @logger.warn \"Warning: unattended code #{response.code}\"\n end\n\n parsed_response = Nokogiri::XML(response)\n @logger.debug \"Send request result: #{parsed_response}\"\n\n [parsed_response, response.headers]\n end\n end", "code_tokens": ["def", "send_request", "(", "params", ",", "payload", "=", "nil", ",", "content_type", "=", "nil", ")", "req_params", "=", "setup_request", "(", "params", ",", "payload", ",", "content_type", ")", "handled_request", "(", "req_params", ")", "do", "request", "=", "RestClient", "::", "Request", ".", "new", "(", "req_params", ")", "response", "=", "request", ".", "execute", "if", "!", "[", "200", ",", "201", ",", "202", ",", "204", "]", ".", "include?", "(", "response", ".", "code", ")", "@logger", ".", "warn", "\"Warning: unattended code #{response.code}\"", "end", "parsed_response", "=", "Nokogiri", "::", "XML", "(", "response", ")", "@logger", ".", "debug", "\"Send request result: #{parsed_response}\"", "[", "parsed_response", ",", "response", ".", "headers", "]", "end", "end"], "docstring": "Sends a synchronous request to the vCloud API and returns the response as parsed XML + headers.", "docstring_tokens": ["Sends", "a", "synchronous", "request", "to", "the", "vCloud", "API", "and", "returns", "the", "response", "as", "parsed", "XML", "+", "headers", "."], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/connection.rb#L140-L156", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/connection.rb", "func_name": "VCloudClient.Connection.upload_file", "original_string": "def upload_file(uploadURL, uploadFile, progressUrl, config={})\n raise ::IOError, \"#{uploadFile} not found.\" unless File.exists?(uploadFile)\n\n # Set chunksize to 10M if not specified otherwise\n chunkSize = (config[:chunksize] || 10485760)\n\n # Set progress bar to default format if not specified otherwise\n progressBarFormat = (config[:progressbar_format] || \"%e <%B> %p%% %t\")\n\n # Set progress bar length to 120 if not specified otherwise\n progressBarLength = (config[:progressbar_length] || 120)\n\n # Open our file for upload\n uploadFileHandle = File.new(uploadFile, \"rb\" )\n fileName = File.basename(uploadFileHandle)\n\n progressBarTitle = \"Uploading: \" + uploadFile.to_s\n\n # Create a progressbar object if progress bar is enabled\n if config[:progressbar_enable] == true && uploadFileHandle.size.to_i > chunkSize\n progressbar = ProgressBar.create(\n :title => progressBarTitle,\n :starting_at => 0,\n :total => uploadFileHandle.size.to_i,\n :length => progressBarLength,\n :format => progressBarFormat\n )\n else\n @logger.info progressBarTitle\n end\n # Create a new HTTP client\n clnt = HTTPClient.new\n\n # Disable SSL cert verification\n clnt.ssl_config.verify_mode=(OpenSSL::SSL::VERIFY_NONE)\n\n # Suppress SSL depth message\n clnt.ssl_config.verify_callback=proc{ |ok, ctx|; true };\n\n # Perform ranged upload until the file reaches its end\n until uploadFileHandle.eof?\n\n # Create ranges for this chunk upload\n rangeStart = uploadFileHandle.pos\n rangeStop = uploadFileHandle.pos.to_i + chunkSize\n\n # Read current chunk\n fileContent = uploadFileHandle.read(chunkSize)\n\n # If statement to handle last chunk transfer if is > than filesize\n if rangeStop.to_i > uploadFileHandle.size.to_i\n contentRange = \"bytes #{rangeStart.to_s}-#{uploadFileHandle.size.to_s}/#{uploadFileHandle.size.to_s}\"\n rangeLen = uploadFileHandle.size.to_i - rangeStart.to_i\n else\n contentRange = \"bytes #{rangeStart.to_s}-#{rangeStop.to_s}/#{uploadFileHandle.size.to_s}\"\n rangeLen = rangeStop.to_i - rangeStart.to_i\n end\n\n # Build headers\n extheader = {\n 'x-vcloud-authorization' => @auth_key,\n 'Content-Range' => contentRange,\n 'Content-Length' => rangeLen.to_s\n }\n\n begin\n uploadRequest = \"#{@host_url}#{uploadURL}\"\n connection = clnt.request('PUT', uploadRequest, nil, fileContent, extheader)\n\n if config[:progressbar_enable] == true && uploadFileHandle.size.to_i > chunkSize\n params = {\n 'method' => :get,\n 'command' => progressUrl\n }\n response, headers = send_request(params)\n\n response.css(\"Files File [name='#{fileName}']\").each do |file|\n progressbar.progress=file[:bytesTransferred].to_i\n end\n end\n rescue\n retryTime = (config[:retry_time] || 5)\n @logger.warn \"Range #{contentRange} failed to upload, retrying the chunk in #{retryTime.to_s} seconds, to stop the action press CTRL+C.\"\n sleep retryTime.to_i\n retry\n end\n end\n uploadFileHandle.close\n end", "language": "ruby", "code": "def upload_file(uploadURL, uploadFile, progressUrl, config={})\n raise ::IOError, \"#{uploadFile} not found.\" unless File.exists?(uploadFile)\n\n # Set chunksize to 10M if not specified otherwise\n chunkSize = (config[:chunksize] || 10485760)\n\n # Set progress bar to default format if not specified otherwise\n progressBarFormat = (config[:progressbar_format] || \"%e <%B> %p%% %t\")\n\n # Set progress bar length to 120 if not specified otherwise\n progressBarLength = (config[:progressbar_length] || 120)\n\n # Open our file for upload\n uploadFileHandle = File.new(uploadFile, \"rb\" )\n fileName = File.basename(uploadFileHandle)\n\n progressBarTitle = \"Uploading: \" + uploadFile.to_s\n\n # Create a progressbar object if progress bar is enabled\n if config[:progressbar_enable] == true && uploadFileHandle.size.to_i > chunkSize\n progressbar = ProgressBar.create(\n :title => progressBarTitle,\n :starting_at => 0,\n :total => uploadFileHandle.size.to_i,\n :length => progressBarLength,\n :format => progressBarFormat\n )\n else\n @logger.info progressBarTitle\n end\n # Create a new HTTP client\n clnt = HTTPClient.new\n\n # Disable SSL cert verification\n clnt.ssl_config.verify_mode=(OpenSSL::SSL::VERIFY_NONE)\n\n # Suppress SSL depth message\n clnt.ssl_config.verify_callback=proc{ |ok, ctx|; true };\n\n # Perform ranged upload until the file reaches its end\n until uploadFileHandle.eof?\n\n # Create ranges for this chunk upload\n rangeStart = uploadFileHandle.pos\n rangeStop = uploadFileHandle.pos.to_i + chunkSize\n\n # Read current chunk\n fileContent = uploadFileHandle.read(chunkSize)\n\n # If statement to handle last chunk transfer if is > than filesize\n if rangeStop.to_i > uploadFileHandle.size.to_i\n contentRange = \"bytes #{rangeStart.to_s}-#{uploadFileHandle.size.to_s}/#{uploadFileHandle.size.to_s}\"\n rangeLen = uploadFileHandle.size.to_i - rangeStart.to_i\n else\n contentRange = \"bytes #{rangeStart.to_s}-#{rangeStop.to_s}/#{uploadFileHandle.size.to_s}\"\n rangeLen = rangeStop.to_i - rangeStart.to_i\n end\n\n # Build headers\n extheader = {\n 'x-vcloud-authorization' => @auth_key,\n 'Content-Range' => contentRange,\n 'Content-Length' => rangeLen.to_s\n }\n\n begin\n uploadRequest = \"#{@host_url}#{uploadURL}\"\n connection = clnt.request('PUT', uploadRequest, nil, fileContent, extheader)\n\n if config[:progressbar_enable] == true && uploadFileHandle.size.to_i > chunkSize\n params = {\n 'method' => :get,\n 'command' => progressUrl\n }\n response, headers = send_request(params)\n\n response.css(\"Files File [name='#{fileName}']\").each do |file|\n progressbar.progress=file[:bytesTransferred].to_i\n end\n end\n rescue\n retryTime = (config[:retry_time] || 5)\n @logger.warn \"Range #{contentRange} failed to upload, retrying the chunk in #{retryTime.to_s} seconds, to stop the action press CTRL+C.\"\n sleep retryTime.to_i\n retry\n end\n end\n uploadFileHandle.close\n end", "code_tokens": ["def", "upload_file", "(", "uploadURL", ",", "uploadFile", ",", "progressUrl", ",", "config", "=", "{", "}", ")", "raise", "::", "IOError", ",", "\"#{uploadFile} not found.\"", "unless", "File", ".", "exists?", "(", "uploadFile", ")", "# Set chunksize to 10M if not specified otherwise", "chunkSize", "=", "(", "config", "[", ":chunksize", "]", "||", "10485760", ")", "# Set progress bar to default format if not specified otherwise", "progressBarFormat", "=", "(", "config", "[", ":progressbar_format", "]", "||", "\"%e <%B> %p%% %t\"", ")", "# Set progress bar length to 120 if not specified otherwise", "progressBarLength", "=", "(", "config", "[", ":progressbar_length", "]", "||", "120", ")", "# Open our file for upload", "uploadFileHandle", "=", "File", ".", "new", "(", "uploadFile", ",", "\"rb\"", ")", "fileName", "=", "File", ".", "basename", "(", "uploadFileHandle", ")", "progressBarTitle", "=", "\"Uploading: \"", "+", "uploadFile", ".", "to_s", "# Create a progressbar object if progress bar is enabled", "if", "config", "[", ":progressbar_enable", "]", "==", "true", "&&", "uploadFileHandle", ".", "size", ".", "to_i", ">", "chunkSize", "progressbar", "=", "ProgressBar", ".", "create", "(", ":title", "=>", "progressBarTitle", ",", ":starting_at", "=>", "0", ",", ":total", "=>", "uploadFileHandle", ".", "size", ".", "to_i", ",", ":length", "=>", "progressBarLength", ",", ":format", "=>", "progressBarFormat", ")", "else", "@logger", ".", "info", "progressBarTitle", "end", "# Create a new HTTP client", "clnt", "=", "HTTPClient", ".", "new", "# Disable SSL cert verification", "clnt", ".", "ssl_config", ".", "verify_mode", "=", "(", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", ")", "# Suppress SSL depth message", "clnt", ".", "ssl_config", ".", "verify_callback", "=", "proc", "{", "|", "ok", ",", "ctx", "|", ";", "true", "}", ";", "# Perform ranged upload until the file reaches its end", "until", "uploadFileHandle", ".", "eof?", "# Create ranges for this chunk upload", "rangeStart", "=", "uploadFileHandle", ".", "pos", "rangeStop", "=", "uploadFileHandle", ".", "pos", ".", "to_i", "+", "chunkSize", "# Read current chunk", "fileContent", "=", "uploadFileHandle", ".", "read", "(", "chunkSize", ")", "# If statement to handle last chunk transfer if is > than filesize", "if", "rangeStop", ".", "to_i", ">", "uploadFileHandle", ".", "size", ".", "to_i", "contentRange", "=", "\"bytes #{rangeStart.to_s}-#{uploadFileHandle.size.to_s}/#{uploadFileHandle.size.to_s}\"", "rangeLen", "=", "uploadFileHandle", ".", "size", ".", "to_i", "-", "rangeStart", ".", "to_i", "else", "contentRange", "=", "\"bytes #{rangeStart.to_s}-#{rangeStop.to_s}/#{uploadFileHandle.size.to_s}\"", "rangeLen", "=", "rangeStop", ".", "to_i", "-", "rangeStart", ".", "to_i", "end", "# Build headers", "extheader", "=", "{", "'x-vcloud-authorization'", "=>", "@auth_key", ",", "'Content-Range'", "=>", "contentRange", ",", "'Content-Length'", "=>", "rangeLen", ".", "to_s", "}", "begin", "uploadRequest", "=", "\"#{@host_url}#{uploadURL}\"", "connection", "=", "clnt", ".", "request", "(", "'PUT'", ",", "uploadRequest", ",", "nil", ",", "fileContent", ",", "extheader", ")", "if", "config", "[", ":progressbar_enable", "]", "==", "true", "&&", "uploadFileHandle", ".", "size", ".", "to_i", ">", "chunkSize", "params", "=", "{", "'method'", "=>", ":get", ",", "'command'", "=>", "progressUrl", "}", "response", ",", "headers", "=", "send_request", "(", "params", ")", "response", ".", "css", "(", "\"Files File [name='#{fileName}']\"", ")", ".", "each", "do", "|", "file", "|", "progressbar", ".", "progress", "=", "file", "[", ":bytesTransferred", "]", ".", "to_i", "end", "end", "rescue", "retryTime", "=", "(", "config", "[", ":retry_time", "]", "||", "5", ")", "@logger", ".", "warn", "\"Range #{contentRange} failed to upload, retrying the chunk in #{retryTime.to_s} seconds, to stop the action press CTRL+C.\"", "sleep", "retryTime", ".", "to_i", "retry", "end", "end", "uploadFileHandle", ".", "close", "end"], "docstring": "Upload a large file in configurable chunks, output an optional progressbar", "docstring_tokens": ["Upload", "a", "large", "file", "in", "configurable", "chunks", "output", "an", "optional", "progressbar"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/connection.rb#L328-L416", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/catalog.rb", "func_name": "VCloudClient.Connection.get_catalog", "original_string": "def get_catalog(catalogId)\n params = {\n 'method' => :get,\n 'command' => \"/catalog/#{catalogId}\"\n }\n\n response, headers = send_request(params)\n description = response.css(\"Description\").first\n description = description.text unless description.nil?\n\n items = {}\n response.css(\"CatalogItem[type='application/vnd.vmware.vcloud.catalogItem+xml']\").each do |item|\n items[item['name']] = item['href'].gsub(/.*\\/catalogItem\\//, \"\")\n end\n { :id => catalogId, :description => description, :items => items }\n end", "language": "ruby", "code": "def get_catalog(catalogId)\n params = {\n 'method' => :get,\n 'command' => \"/catalog/#{catalogId}\"\n }\n\n response, headers = send_request(params)\n description = response.css(\"Description\").first\n description = description.text unless description.nil?\n\n items = {}\n response.css(\"CatalogItem[type='application/vnd.vmware.vcloud.catalogItem+xml']\").each do |item|\n items[item['name']] = item['href'].gsub(/.*\\/catalogItem\\//, \"\")\n end\n { :id => catalogId, :description => description, :items => items }\n end", "code_tokens": ["def", "get_catalog", "(", "catalogId", ")", "params", "=", "{", "'method'", "=>", ":get", ",", "'command'", "=>", "\"/catalog/#{catalogId}\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ")", "description", "=", "response", ".", "css", "(", "\"Description\"", ")", ".", "first", "description", "=", "description", ".", "text", "unless", "description", ".", "nil?", "items", "=", "{", "}", "response", ".", "css", "(", "\"CatalogItem[type='application/vnd.vmware.vcloud.catalogItem+xml']\"", ")", ".", "each", "do", "|", "item", "|", "items", "[", "item", "[", "'name'", "]", "]", "=", "item", "[", "'href'", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "end", "{", ":id", "=>", "catalogId", ",", ":description", "=>", "description", ",", ":items", "=>", "items", "}", "end"], "docstring": "Fetch details about a given catalog", "docstring_tokens": ["Fetch", "details", "about", "a", "given", "catalog"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/catalog.rb#L5-L20", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vm.rb", "func_name": "VCloudClient.Connection.get_vm_disk_info", "original_string": "def get_vm_disk_info(vmid)\n response, headers = __get_disk_info(vmid)\n\n disks = []\n response.css(\"Item\").each do |entry|\n # Pick only entries with node \"HostResource\"\n resource = entry.css(\"rasd|HostResource\").first\n next unless resource\n\n name = entry.css(\"rasd|ElementName\").first\n name = name.text unless name.nil?\n capacity = resource.attribute(\"capacity\").text\n\n disks << {\n :name => name,\n :capacity => \"#{capacity} MB\"\n }\n end\n disks\n end", "language": "ruby", "code": "def get_vm_disk_info(vmid)\n response, headers = __get_disk_info(vmid)\n\n disks = []\n response.css(\"Item\").each do |entry|\n # Pick only entries with node \"HostResource\"\n resource = entry.css(\"rasd|HostResource\").first\n next unless resource\n\n name = entry.css(\"rasd|ElementName\").first\n name = name.text unless name.nil?\n capacity = resource.attribute(\"capacity\").text\n\n disks << {\n :name => name,\n :capacity => \"#{capacity} MB\"\n }\n end\n disks\n end", "code_tokens": ["def", "get_vm_disk_info", "(", "vmid", ")", "response", ",", "headers", "=", "__get_disk_info", "(", "vmid", ")", "disks", "=", "[", "]", "response", ".", "css", "(", "\"Item\"", ")", ".", "each", "do", "|", "entry", "|", "# Pick only entries with node \"HostResource\"", "resource", "=", "entry", ".", "css", "(", "\"rasd|HostResource\"", ")", ".", "first", "next", "unless", "resource", "name", "=", "entry", ".", "css", "(", "\"rasd|ElementName\"", ")", ".", "first", "name", "=", "name", ".", "text", "unless", "name", ".", "nil?", "capacity", "=", "resource", ".", "attribute", "(", "\"capacity\"", ")", ".", "text", "disks", "<<", "{", ":name", "=>", "name", ",", ":capacity", "=>", "\"#{capacity} MB\"", "}", "end", "disks", "end"], "docstring": "Retrieve information about Disks", "docstring_tokens": ["Retrieve", "information", "about", "Disks"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L33-L52", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vm.rb", "func_name": "VCloudClient.Connection.set_vm_disk_info", "original_string": "def set_vm_disk_info(vmid, disk_info={})\n get_response, headers = __get_disk_info(vmid)\n\n if disk_info[:add]\n data = add_disk(get_response, disk_info)\n else\n data = edit_disk(get_response, disk_info)\n end\n\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vm-#{vmid}/virtualHardwareSection/disks\"\n }\n put_response, headers = send_request(params, data, \"application/vnd.vmware.vcloud.rasdItemsList+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "language": "ruby", "code": "def set_vm_disk_info(vmid, disk_info={})\n get_response, headers = __get_disk_info(vmid)\n\n if disk_info[:add]\n data = add_disk(get_response, disk_info)\n else\n data = edit_disk(get_response, disk_info)\n end\n\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vm-#{vmid}/virtualHardwareSection/disks\"\n }\n put_response, headers = send_request(params, data, \"application/vnd.vmware.vcloud.rasdItemsList+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "code_tokens": ["def", "set_vm_disk_info", "(", "vmid", ",", "disk_info", "=", "{", "}", ")", "get_response", ",", "headers", "=", "__get_disk_info", "(", "vmid", ")", "if", "disk_info", "[", ":add", "]", "data", "=", "add_disk", "(", "get_response", ",", "disk_info", ")", "else", "data", "=", "edit_disk", "(", "get_response", ",", "disk_info", ")", "end", "params", "=", "{", "'method'", "=>", ":put", ",", "'command'", "=>", "\"/vApp/vm-#{vmid}/virtualHardwareSection/disks\"", "}", "put_response", ",", "headers", "=", "send_request", "(", "params", ",", "data", ",", "\"application/vnd.vmware.vcloud.rasdItemsList+xml\"", ")", "task_id", "=", "headers", "[", ":location", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "task_id", "end"], "docstring": "Set information about Disks\n\n Disks can be added, deleted or modified", "docstring_tokens": ["Set", "information", "about", "Disks"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L58-L75", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vm.rb", "func_name": "VCloudClient.Connection.set_vm_cpus", "original_string": "def set_vm_cpus(vmid, cpu_number)\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vm-#{vmid}/virtualHardwareSection/cpu\"\n }\n\n get_response, headers = send_request(params)\n\n # Change attributes from the previous invocation\n get_response.css(\"rasd|ElementName\").first.content = \"#{cpu_number} virtual CPU(s)\"\n get_response.css(\"rasd|VirtualQuantity\").first.content = cpu_number\n\n params['method'] = :put\n put_response, headers = send_request(params, get_response.to_xml, \"application/vnd.vmware.vcloud.rasdItem+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "language": "ruby", "code": "def set_vm_cpus(vmid, cpu_number)\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vm-#{vmid}/virtualHardwareSection/cpu\"\n }\n\n get_response, headers = send_request(params)\n\n # Change attributes from the previous invocation\n get_response.css(\"rasd|ElementName\").first.content = \"#{cpu_number} virtual CPU(s)\"\n get_response.css(\"rasd|VirtualQuantity\").first.content = cpu_number\n\n params['method'] = :put\n put_response, headers = send_request(params, get_response.to_xml, \"application/vnd.vmware.vcloud.rasdItem+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "code_tokens": ["def", "set_vm_cpus", "(", "vmid", ",", "cpu_number", ")", "params", "=", "{", "'method'", "=>", ":get", ",", "'command'", "=>", "\"/vApp/vm-#{vmid}/virtualHardwareSection/cpu\"", "}", "get_response", ",", "headers", "=", "send_request", "(", "params", ")", "# Change attributes from the previous invocation", "get_response", ".", "css", "(", "\"rasd|ElementName\"", ")", ".", "first", ".", "content", "=", "\"#{cpu_number} virtual CPU(s)\"", "get_response", ".", "css", "(", "\"rasd|VirtualQuantity\"", ")", ".", "first", ".", "content", "=", "cpu_number", "params", "[", "'method'", "]", "=", ":put", "put_response", ",", "headers", "=", "send_request", "(", "params", ",", "get_response", ".", "to_xml", ",", "\"application/vnd.vmware.vcloud.rasdItem+xml\"", ")", "task_id", "=", "headers", "[", ":location", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "task_id", "end"], "docstring": "Set VM CPUs", "docstring_tokens": ["Set", "VM", "CPUs"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L79-L96", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vm.rb", "func_name": "VCloudClient.Connection.set_vm_ram", "original_string": "def set_vm_ram(vmid, memory_size)\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vm-#{vmid}/virtualHardwareSection/memory\"\n }\n\n get_response, headers = send_request(params)\n\n # Change attributes from the previous invocation\n get_response.css(\"rasd|ElementName\").first.content = \"#{memory_size} MB of memory\"\n get_response.css(\"rasd|VirtualQuantity\").first.content = memory_size\n\n params['method'] = :put\n put_response, headers = send_request(params, get_response.to_xml, \"application/vnd.vmware.vcloud.rasdItem+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "language": "ruby", "code": "def set_vm_ram(vmid, memory_size)\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vm-#{vmid}/virtualHardwareSection/memory\"\n }\n\n get_response, headers = send_request(params)\n\n # Change attributes from the previous invocation\n get_response.css(\"rasd|ElementName\").first.content = \"#{memory_size} MB of memory\"\n get_response.css(\"rasd|VirtualQuantity\").first.content = memory_size\n\n params['method'] = :put\n put_response, headers = send_request(params, get_response.to_xml, \"application/vnd.vmware.vcloud.rasdItem+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "code_tokens": ["def", "set_vm_ram", "(", "vmid", ",", "memory_size", ")", "params", "=", "{", "'method'", "=>", ":get", ",", "'command'", "=>", "\"/vApp/vm-#{vmid}/virtualHardwareSection/memory\"", "}", "get_response", ",", "headers", "=", "send_request", "(", "params", ")", "# Change attributes from the previous invocation", "get_response", ".", "css", "(", "\"rasd|ElementName\"", ")", ".", "first", ".", "content", "=", "\"#{memory_size} MB of memory\"", "get_response", ".", "css", "(", "\"rasd|VirtualQuantity\"", ")", ".", "first", ".", "content", "=", "memory_size", "params", "[", "'method'", "]", "=", ":put", "put_response", ",", "headers", "=", "send_request", "(", "params", ",", "get_response", ".", "to_xml", ",", "\"application/vnd.vmware.vcloud.rasdItem+xml\"", ")", "task_id", "=", "headers", "[", ":location", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "task_id", "end"], "docstring": "Set VM RAM", "docstring_tokens": ["Set", "VM", "RAM"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L100-L117", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vm.rb", "func_name": "VCloudClient.Connection.edit_vm_network", "original_string": "def edit_vm_network(vmId, network, config={})\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vm-#{vmId}/networkConnectionSection\"\n }\n\n netconfig_response, headers = send_request(params)\n\n if config[:primary_index]\n node = netconfig_response.css('PrimaryNetworkConnectionIndex').first\n node.content = config[:primary_index]\n end\n\n picked_network = netconfig_response.css(\"NetworkConnection\").select do |net|\n net.attribute('network').text == network[:name]\n end.first\n\n raise WrongItemIDError, \"Network named #{network[:name]} not found.\" unless picked_network\n\n if config[:ip_allocation_mode]\n node = picked_network.css('IpAddressAllocationMode').first\n node.content = config[:ip_allocation_mode]\n end\n\n if config[:network_index]\n node = picked_network.css('NetworkConnectionIndex').first\n node.content = config[:network_index]\n end\n\n if config[:is_connected]\n node = picked_network.css('IsConnected').first\n node.content = config[:is_connected]\n end\n\n if config[:ip]\n node = picked_network.css('IpAddress').first\n node.content = config[:ip]\n end\n\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vm-#{vmId}/networkConnectionSection\"\n }\n\n response, headers = send_request(params, netconfig_response.to_xml, \"application/vnd.vmware.vcloud.networkConnectionSection+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "language": "ruby", "code": "def edit_vm_network(vmId, network, config={})\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vm-#{vmId}/networkConnectionSection\"\n }\n\n netconfig_response, headers = send_request(params)\n\n if config[:primary_index]\n node = netconfig_response.css('PrimaryNetworkConnectionIndex').first\n node.content = config[:primary_index]\n end\n\n picked_network = netconfig_response.css(\"NetworkConnection\").select do |net|\n net.attribute('network').text == network[:name]\n end.first\n\n raise WrongItemIDError, \"Network named #{network[:name]} not found.\" unless picked_network\n\n if config[:ip_allocation_mode]\n node = picked_network.css('IpAddressAllocationMode').first\n node.content = config[:ip_allocation_mode]\n end\n\n if config[:network_index]\n node = picked_network.css('NetworkConnectionIndex').first\n node.content = config[:network_index]\n end\n\n if config[:is_connected]\n node = picked_network.css('IsConnected').first\n node.content = config[:is_connected]\n end\n\n if config[:ip]\n node = picked_network.css('IpAddress').first\n node.content = config[:ip]\n end\n\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vm-#{vmId}/networkConnectionSection\"\n }\n\n response, headers = send_request(params, netconfig_response.to_xml, \"application/vnd.vmware.vcloud.networkConnectionSection+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "code_tokens": ["def", "edit_vm_network", "(", "vmId", ",", "network", ",", "config", "=", "{", "}", ")", "params", "=", "{", "'method'", "=>", ":get", ",", "'command'", "=>", "\"/vApp/vm-#{vmId}/networkConnectionSection\"", "}", "netconfig_response", ",", "headers", "=", "send_request", "(", "params", ")", "if", "config", "[", ":primary_index", "]", "node", "=", "netconfig_response", ".", "css", "(", "'PrimaryNetworkConnectionIndex'", ")", ".", "first", "node", ".", "content", "=", "config", "[", ":primary_index", "]", "end", "picked_network", "=", "netconfig_response", ".", "css", "(", "\"NetworkConnection\"", ")", ".", "select", "do", "|", "net", "|", "net", ".", "attribute", "(", "'network'", ")", ".", "text", "==", "network", "[", ":name", "]", "end", ".", "first", "raise", "WrongItemIDError", ",", "\"Network named #{network[:name]} not found.\"", "unless", "picked_network", "if", "config", "[", ":ip_allocation_mode", "]", "node", "=", "picked_network", ".", "css", "(", "'IpAddressAllocationMode'", ")", ".", "first", "node", ".", "content", "=", "config", "[", ":ip_allocation_mode", "]", "end", "if", "config", "[", ":network_index", "]", "node", "=", "picked_network", ".", "css", "(", "'NetworkConnectionIndex'", ")", ".", "first", "node", ".", "content", "=", "config", "[", ":network_index", "]", "end", "if", "config", "[", ":is_connected", "]", "node", "=", "picked_network", ".", "css", "(", "'IsConnected'", ")", ".", "first", "node", ".", "content", "=", "config", "[", ":is_connected", "]", "end", "if", "config", "[", ":ip", "]", "node", "=", "picked_network", ".", "css", "(", "'IpAddress'", ")", ".", "first", "node", ".", "content", "=", "config", "[", ":ip", "]", "end", "params", "=", "{", "'method'", "=>", ":put", ",", "'command'", "=>", "\"/vApp/vm-#{vmId}/networkConnectionSection\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ",", "netconfig_response", ".", "to_xml", ",", "\"application/vnd.vmware.vcloud.networkConnectionSection+xml\"", ")", "task_id", "=", "headers", "[", ":location", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "task_id", "end"], "docstring": "Edit VM Network Config\n\n Retrieve the existing network config section and edit it\n to ensure settings are not lost", "docstring_tokens": ["Edit", "VM", "Network", "Config"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L124-L172", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vm.rb", "func_name": "VCloudClient.Connection.add_vm_network", "original_string": "def add_vm_network(vmId, network, config={})\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vm-#{vmId}/networkConnectionSection\"\n }\n\n netconfig_response, headers = send_request(params)\n\n parent_section = netconfig_response.css('NetworkConnectionSection').first\n\n # For some reasons these elements must be removed\n netconfig_response.css(\"Link\").each {|n| n.remove}\n\n # Delete placeholder network if present (since vcloud 5.5 has been removed)\n none_network = netconfig_response.css('NetworkConnection').find{|n| n.attribute('network').text == 'none'}\n none_network.remove if none_network\n\n networks_count = netconfig_response.css('NetworkConnection').count\n\n primary_index_node = netconfig_response.css('PrimaryNetworkConnectionIndex').first\n unless primary_index_node\n primary_index_node = Nokogiri::XML::Node.new \"PrimaryNetworkConnectionIndex\", parent_section\n parent_section.add_child(primary_index_node)\n end\n primary_index_node.content = config[:primary_index] || 0\n\n new_network = Nokogiri::XML::Node.new \"NetworkConnection\", parent_section\n new_network[\"network\"] = network[:name]\n new_network[\"needsCustomization\"] = true\n\n idx_node = Nokogiri::XML::Node.new \"NetworkConnectionIndex\", new_network\n idx_node.content = config[:network_index] || networks_count\n new_network.add_child(idx_node)\n\n if config[:ip]\n ip_node = Nokogiri::XML::Node.new \"IpAddress\", new_network\n ip_node.content = config[:ip]\n new_network.add_child(ip_node)\n end\n\n is_connected_node = Nokogiri::XML::Node.new \"IsConnected\", new_network\n is_connected_node.content = config[:is_connected] || true\n new_network.add_child(is_connected_node)\n\n allocation_node = Nokogiri::XML::Node.new \"IpAddressAllocationMode\", new_network\n allocation_node.content = config[:ip_allocation_mode] || \"POOL\"\n new_network.add_child(allocation_node)\n\n parent_section.add_child(new_network)\n\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vm-#{vmId}/networkConnectionSection\"\n }\n\n put_response, headers = send_request(params, netconfig_response.to_xml, \"application/vnd.vmware.vcloud.networkConnectionSection+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "language": "ruby", "code": "def add_vm_network(vmId, network, config={})\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vm-#{vmId}/networkConnectionSection\"\n }\n\n netconfig_response, headers = send_request(params)\n\n parent_section = netconfig_response.css('NetworkConnectionSection').first\n\n # For some reasons these elements must be removed\n netconfig_response.css(\"Link\").each {|n| n.remove}\n\n # Delete placeholder network if present (since vcloud 5.5 has been removed)\n none_network = netconfig_response.css('NetworkConnection').find{|n| n.attribute('network').text == 'none'}\n none_network.remove if none_network\n\n networks_count = netconfig_response.css('NetworkConnection').count\n\n primary_index_node = netconfig_response.css('PrimaryNetworkConnectionIndex').first\n unless primary_index_node\n primary_index_node = Nokogiri::XML::Node.new \"PrimaryNetworkConnectionIndex\", parent_section\n parent_section.add_child(primary_index_node)\n end\n primary_index_node.content = config[:primary_index] || 0\n\n new_network = Nokogiri::XML::Node.new \"NetworkConnection\", parent_section\n new_network[\"network\"] = network[:name]\n new_network[\"needsCustomization\"] = true\n\n idx_node = Nokogiri::XML::Node.new \"NetworkConnectionIndex\", new_network\n idx_node.content = config[:network_index] || networks_count\n new_network.add_child(idx_node)\n\n if config[:ip]\n ip_node = Nokogiri::XML::Node.new \"IpAddress\", new_network\n ip_node.content = config[:ip]\n new_network.add_child(ip_node)\n end\n\n is_connected_node = Nokogiri::XML::Node.new \"IsConnected\", new_network\n is_connected_node.content = config[:is_connected] || true\n new_network.add_child(is_connected_node)\n\n allocation_node = Nokogiri::XML::Node.new \"IpAddressAllocationMode\", new_network\n allocation_node.content = config[:ip_allocation_mode] || \"POOL\"\n new_network.add_child(allocation_node)\n\n parent_section.add_child(new_network)\n\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vm-#{vmId}/networkConnectionSection\"\n }\n\n put_response, headers = send_request(params, netconfig_response.to_xml, \"application/vnd.vmware.vcloud.networkConnectionSection+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "code_tokens": ["def", "add_vm_network", "(", "vmId", ",", "network", ",", "config", "=", "{", "}", ")", "params", "=", "{", "'method'", "=>", ":get", ",", "'command'", "=>", "\"/vApp/vm-#{vmId}/networkConnectionSection\"", "}", "netconfig_response", ",", "headers", "=", "send_request", "(", "params", ")", "parent_section", "=", "netconfig_response", ".", "css", "(", "'NetworkConnectionSection'", ")", ".", "first", "# For some reasons these elements must be removed", "netconfig_response", ".", "css", "(", "\"Link\"", ")", ".", "each", "{", "|", "n", "|", "n", ".", "remove", "}", "# Delete placeholder network if present (since vcloud 5.5 has been removed)", "none_network", "=", "netconfig_response", ".", "css", "(", "'NetworkConnection'", ")", ".", "find", "{", "|", "n", "|", "n", ".", "attribute", "(", "'network'", ")", ".", "text", "==", "'none'", "}", "none_network", ".", "remove", "if", "none_network", "networks_count", "=", "netconfig_response", ".", "css", "(", "'NetworkConnection'", ")", ".", "count", "primary_index_node", "=", "netconfig_response", ".", "css", "(", "'PrimaryNetworkConnectionIndex'", ")", ".", "first", "unless", "primary_index_node", "primary_index_node", "=", "Nokogiri", "::", "XML", "::", "Node", ".", "new", "\"PrimaryNetworkConnectionIndex\"", ",", "parent_section", "parent_section", ".", "add_child", "(", "primary_index_node", ")", "end", "primary_index_node", ".", "content", "=", "config", "[", ":primary_index", "]", "||", "0", "new_network", "=", "Nokogiri", "::", "XML", "::", "Node", ".", "new", "\"NetworkConnection\"", ",", "parent_section", "new_network", "[", "\"network\"", "]", "=", "network", "[", ":name", "]", "new_network", "[", "\"needsCustomization\"", "]", "=", "true", "idx_node", "=", "Nokogiri", "::", "XML", "::", "Node", ".", "new", "\"NetworkConnectionIndex\"", ",", "new_network", "idx_node", ".", "content", "=", "config", "[", ":network_index", "]", "||", "networks_count", "new_network", ".", "add_child", "(", "idx_node", ")", "if", "config", "[", ":ip", "]", "ip_node", "=", "Nokogiri", "::", "XML", "::", "Node", ".", "new", "\"IpAddress\"", ",", "new_network", "ip_node", ".", "content", "=", "config", "[", ":ip", "]", "new_network", ".", "add_child", "(", "ip_node", ")", "end", "is_connected_node", "=", "Nokogiri", "::", "XML", "::", "Node", ".", "new", "\"IsConnected\"", ",", "new_network", "is_connected_node", ".", "content", "=", "config", "[", ":is_connected", "]", "||", "true", "new_network", ".", "add_child", "(", "is_connected_node", ")", "allocation_node", "=", "Nokogiri", "::", "XML", "::", "Node", ".", "new", "\"IpAddressAllocationMode\"", ",", "new_network", "allocation_node", ".", "content", "=", "config", "[", ":ip_allocation_mode", "]", "||", "\"POOL\"", "new_network", ".", "add_child", "(", "allocation_node", ")", "parent_section", ".", "add_child", "(", "new_network", ")", "params", "=", "{", "'method'", "=>", ":put", ",", "'command'", "=>", "\"/vApp/vm-#{vmId}/networkConnectionSection\"", "}", "put_response", ",", "headers", "=", "send_request", "(", "params", ",", "netconfig_response", ".", "to_xml", ",", "\"application/vnd.vmware.vcloud.networkConnectionSection+xml\"", ")", "task_id", "=", "headers", "[", ":location", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "task_id", "end"], "docstring": "Add a new network to a VM", "docstring_tokens": ["Add", "a", "new", "network", "to", "a", "VM"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L176-L235", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vm.rb", "func_name": "VCloudClient.Connection.delete_vm_network", "original_string": "def delete_vm_network(vmId, network)\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vm-#{vmId}/networkConnectionSection\"\n }\n\n netconfig_response, headers = send_request(params)\n\n picked_network = netconfig_response.css(\"NetworkConnection\").select do |net|\n net.attribute('network').text == network[:name]\n end.first\n\n raise WrongItemIDError, \"Network #{network[:name]} not found on this VM.\" unless picked_network\n\n picked_network.remove\n\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vm-#{vmId}/networkConnectionSection\"\n }\n\n put_response, headers = send_request(params, netconfig_response.to_xml, \"application/vnd.vmware.vcloud.networkConnectionSection+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "language": "ruby", "code": "def delete_vm_network(vmId, network)\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vm-#{vmId}/networkConnectionSection\"\n }\n\n netconfig_response, headers = send_request(params)\n\n picked_network = netconfig_response.css(\"NetworkConnection\").select do |net|\n net.attribute('network').text == network[:name]\n end.first\n\n raise WrongItemIDError, \"Network #{network[:name]} not found on this VM.\" unless picked_network\n\n picked_network.remove\n\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vm-#{vmId}/networkConnectionSection\"\n }\n\n put_response, headers = send_request(params, netconfig_response.to_xml, \"application/vnd.vmware.vcloud.networkConnectionSection+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "code_tokens": ["def", "delete_vm_network", "(", "vmId", ",", "network", ")", "params", "=", "{", "'method'", "=>", ":get", ",", "'command'", "=>", "\"/vApp/vm-#{vmId}/networkConnectionSection\"", "}", "netconfig_response", ",", "headers", "=", "send_request", "(", "params", ")", "picked_network", "=", "netconfig_response", ".", "css", "(", "\"NetworkConnection\"", ")", ".", "select", "do", "|", "net", "|", "net", ".", "attribute", "(", "'network'", ")", ".", "text", "==", "network", "[", ":name", "]", "end", ".", "first", "raise", "WrongItemIDError", ",", "\"Network #{network[:name]} not found on this VM.\"", "unless", "picked_network", "picked_network", ".", "remove", "params", "=", "{", "'method'", "=>", ":put", ",", "'command'", "=>", "\"/vApp/vm-#{vmId}/networkConnectionSection\"", "}", "put_response", ",", "headers", "=", "send_request", "(", "params", ",", "netconfig_response", ".", "to_xml", ",", "\"application/vnd.vmware.vcloud.networkConnectionSection+xml\"", ")", "task_id", "=", "headers", "[", ":location", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "task_id", "end"], "docstring": "Remove an existing network", "docstring_tokens": ["Remove", "an", "existing", "network"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L239-L264", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vm.rb", "func_name": "VCloudClient.Connection.set_vm_guest_customization", "original_string": "def set_vm_guest_customization(vmid, computer_name, config={})\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.GuestCustomizationSection(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\",\n \"xmlns:ovf\" => \"http://schemas.dmtf.org/ovf/envelope/1\") {\n xml['ovf'].Info \"VM Guest Customization configuration\"\n xml.Enabled config[:enabled] if config[:enabled]\n xml.AdminPasswordEnabled config[:admin_passwd_enabled] if config[:admin_passwd_enabled]\n xml.AdminPassword config[:admin_passwd] if config[:admin_passwd]\n xml.CustomizationScript config[:customization_script] if config[:customization_script]\n xml.ComputerName computer_name\n }\n end\n\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vm-#{vmid}/guestCustomizationSection\"\n }\n\n response, headers = send_request(params, builder.to_xml, \"application/vnd.vmware.vcloud.guestCustomizationSection+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "language": "ruby", "code": "def set_vm_guest_customization(vmid, computer_name, config={})\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.GuestCustomizationSection(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\",\n \"xmlns:ovf\" => \"http://schemas.dmtf.org/ovf/envelope/1\") {\n xml['ovf'].Info \"VM Guest Customization configuration\"\n xml.Enabled config[:enabled] if config[:enabled]\n xml.AdminPasswordEnabled config[:admin_passwd_enabled] if config[:admin_passwd_enabled]\n xml.AdminPassword config[:admin_passwd] if config[:admin_passwd]\n xml.CustomizationScript config[:customization_script] if config[:customization_script]\n xml.ComputerName computer_name\n }\n end\n\n params = {\n 'method' => :put,\n 'command' => \"/vApp/vm-#{vmid}/guestCustomizationSection\"\n }\n\n response, headers = send_request(params, builder.to_xml, \"application/vnd.vmware.vcloud.guestCustomizationSection+xml\")\n\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "code_tokens": ["def", "set_vm_guest_customization", "(", "vmid", ",", "computer_name", ",", "config", "=", "{", "}", ")", "builder", "=", "Nokogiri", "::", "XML", "::", "Builder", ".", "new", "do", "|", "xml", "|", "xml", ".", "GuestCustomizationSection", "(", "\"xmlns\"", "=>", "\"http://www.vmware.com/vcloud/v1.5\"", ",", "\"xmlns:ovf\"", "=>", "\"http://schemas.dmtf.org/ovf/envelope/1\"", ")", "{", "xml", "[", "'ovf'", "]", ".", "Info", "\"VM Guest Customization configuration\"", "xml", ".", "Enabled", "config", "[", ":enabled", "]", "if", "config", "[", ":enabled", "]", "xml", ".", "AdminPasswordEnabled", "config", "[", ":admin_passwd_enabled", "]", "if", "config", "[", ":admin_passwd_enabled", "]", "xml", ".", "AdminPassword", "config", "[", ":admin_passwd", "]", "if", "config", "[", ":admin_passwd", "]", "xml", ".", "CustomizationScript", "config", "[", ":customization_script", "]", "if", "config", "[", ":customization_script", "]", "xml", ".", "ComputerName", "computer_name", "}", "end", "params", "=", "{", "'method'", "=>", ":put", ",", "'command'", "=>", "\"/vApp/vm-#{vmid}/guestCustomizationSection\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ",", "builder", ".", "to_xml", ",", "\"application/vnd.vmware.vcloud.guestCustomizationSection+xml\"", ")", "task_id", "=", "headers", "[", ":location", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "task_id", "end"], "docstring": "Set VM Guest Customization Config", "docstring_tokens": ["Set", "VM", "Guest", "Customization", "Config"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L268-L291", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vm.rb", "func_name": "VCloudClient.Connection.get_vm", "original_string": "def get_vm(vmId)\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vm-#{vmId}\"\n }\n\n response, headers = send_request(params)\n\n vm_name = response.css('Vm').attribute(\"name\")\n vm_name = vm_name.text unless vm_name.nil?\n\n status = convert_vapp_status(response.css('Vm').attribute(\"status\").text)\n\n os_desc = response.css('ovf|OperatingSystemSection ovf|Description').first.text\n\n networks = {}\n response.css('NetworkConnection').each do |network|\n ip = network.css('IpAddress').first\n ip = ip.text if ip\n\n external_ip = network.css('ExternalIpAddress').first\n external_ip = external_ip.text if external_ip\n\n # Append NetworkConnectionIndex to network name to generate a unique hash key,\n # otherwise different interfaces on the same network would use the same hash key\n key = \"#{network['network']}_#{network.css('NetworkConnectionIndex').first.text}\"\n\n networks[key] = {\n :index => network.css('NetworkConnectionIndex').first.text,\n :ip => ip,\n :external_ip => external_ip,\n :is_connected => network.css('IsConnected').first.text,\n :mac_address => network.css('MACAddress').first.text,\n :ip_allocation_mode => network.css('IpAddressAllocationMode').first.text\n }\n end\n\n admin_password = response.css('GuestCustomizationSection AdminPassword').first\n admin_password = admin_password.text if admin_password\n\n guest_customizations = {\n :enabled => response.css('GuestCustomizationSection Enabled').first.text,\n :admin_passwd_enabled => response.css('GuestCustomizationSection AdminPasswordEnabled').first.text,\n :admin_passwd_auto => response.css('GuestCustomizationSection AdminPasswordAuto').first.text,\n :admin_passwd => admin_password,\n :reset_passwd_required => response.css('GuestCustomizationSection ResetPasswordRequired').first.text,\n :computer_name => response.css('GuestCustomizationSection ComputerName').first.text\n }\n\n { :id => vmId,\n :vm_name => vm_name, :os_desc => os_desc, :networks => networks,\n :guest_customizations => guest_customizations, :status => status\n }\n end", "language": "ruby", "code": "def get_vm(vmId)\n params = {\n 'method' => :get,\n 'command' => \"/vApp/vm-#{vmId}\"\n }\n\n response, headers = send_request(params)\n\n vm_name = response.css('Vm').attribute(\"name\")\n vm_name = vm_name.text unless vm_name.nil?\n\n status = convert_vapp_status(response.css('Vm').attribute(\"status\").text)\n\n os_desc = response.css('ovf|OperatingSystemSection ovf|Description').first.text\n\n networks = {}\n response.css('NetworkConnection').each do |network|\n ip = network.css('IpAddress').first\n ip = ip.text if ip\n\n external_ip = network.css('ExternalIpAddress').first\n external_ip = external_ip.text if external_ip\n\n # Append NetworkConnectionIndex to network name to generate a unique hash key,\n # otherwise different interfaces on the same network would use the same hash key\n key = \"#{network['network']}_#{network.css('NetworkConnectionIndex').first.text}\"\n\n networks[key] = {\n :index => network.css('NetworkConnectionIndex').first.text,\n :ip => ip,\n :external_ip => external_ip,\n :is_connected => network.css('IsConnected').first.text,\n :mac_address => network.css('MACAddress').first.text,\n :ip_allocation_mode => network.css('IpAddressAllocationMode').first.text\n }\n end\n\n admin_password = response.css('GuestCustomizationSection AdminPassword').first\n admin_password = admin_password.text if admin_password\n\n guest_customizations = {\n :enabled => response.css('GuestCustomizationSection Enabled').first.text,\n :admin_passwd_enabled => response.css('GuestCustomizationSection AdminPasswordEnabled').first.text,\n :admin_passwd_auto => response.css('GuestCustomizationSection AdminPasswordAuto').first.text,\n :admin_passwd => admin_password,\n :reset_passwd_required => response.css('GuestCustomizationSection ResetPasswordRequired').first.text,\n :computer_name => response.css('GuestCustomizationSection ComputerName').first.text\n }\n\n { :id => vmId,\n :vm_name => vm_name, :os_desc => os_desc, :networks => networks,\n :guest_customizations => guest_customizations, :status => status\n }\n end", "code_tokens": ["def", "get_vm", "(", "vmId", ")", "params", "=", "{", "'method'", "=>", ":get", ",", "'command'", "=>", "\"/vApp/vm-#{vmId}\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ")", "vm_name", "=", "response", ".", "css", "(", "'Vm'", ")", ".", "attribute", "(", "\"name\"", ")", "vm_name", "=", "vm_name", ".", "text", "unless", "vm_name", ".", "nil?", "status", "=", "convert_vapp_status", "(", "response", ".", "css", "(", "'Vm'", ")", ".", "attribute", "(", "\"status\"", ")", ".", "text", ")", "os_desc", "=", "response", ".", "css", "(", "'ovf|OperatingSystemSection ovf|Description'", ")", ".", "first", ".", "text", "networks", "=", "{", "}", "response", ".", "css", "(", "'NetworkConnection'", ")", ".", "each", "do", "|", "network", "|", "ip", "=", "network", ".", "css", "(", "'IpAddress'", ")", ".", "first", "ip", "=", "ip", ".", "text", "if", "ip", "external_ip", "=", "network", ".", "css", "(", "'ExternalIpAddress'", ")", ".", "first", "external_ip", "=", "external_ip", ".", "text", "if", "external_ip", "# Append NetworkConnectionIndex to network name to generate a unique hash key,", "# otherwise different interfaces on the same network would use the same hash key", "key", "=", "\"#{network['network']}_#{network.css('NetworkConnectionIndex').first.text}\"", "networks", "[", "key", "]", "=", "{", ":index", "=>", "network", ".", "css", "(", "'NetworkConnectionIndex'", ")", ".", "first", ".", "text", ",", ":ip", "=>", "ip", ",", ":external_ip", "=>", "external_ip", ",", ":is_connected", "=>", "network", ".", "css", "(", "'IsConnected'", ")", ".", "first", ".", "text", ",", ":mac_address", "=>", "network", ".", "css", "(", "'MACAddress'", ")", ".", "first", ".", "text", ",", ":ip_allocation_mode", "=>", "network", ".", "css", "(", "'IpAddressAllocationMode'", ")", ".", "first", ".", "text", "}", "end", "admin_password", "=", "response", ".", "css", "(", "'GuestCustomizationSection AdminPassword'", ")", ".", "first", "admin_password", "=", "admin_password", ".", "text", "if", "admin_password", "guest_customizations", "=", "{", ":enabled", "=>", "response", ".", "css", "(", "'GuestCustomizationSection Enabled'", ")", ".", "first", ".", "text", ",", ":admin_passwd_enabled", "=>", "response", ".", "css", "(", "'GuestCustomizationSection AdminPasswordEnabled'", ")", ".", "first", ".", "text", ",", ":admin_passwd_auto", "=>", "response", ".", "css", "(", "'GuestCustomizationSection AdminPasswordAuto'", ")", ".", "first", ".", "text", ",", ":admin_passwd", "=>", "admin_password", ",", ":reset_passwd_required", "=>", "response", ".", "css", "(", "'GuestCustomizationSection ResetPasswordRequired'", ")", ".", "first", ".", "text", ",", ":computer_name", "=>", "response", ".", "css", "(", "'GuestCustomizationSection ComputerName'", ")", ".", "first", ".", "text", "}", "{", ":id", "=>", "vmId", ",", ":vm_name", "=>", "vm_name", ",", ":os_desc", "=>", "os_desc", ",", ":networks", "=>", "networks", ",", ":guest_customizations", "=>", "guest_customizations", ",", ":status", "=>", "status", "}", "end"], "docstring": "Fetch details about a given VM", "docstring_tokens": ["Fetch", "details", "about", "a", "given", "VM"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L330-L383", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vm.rb", "func_name": "VCloudClient.Connection.get_vm_by_name", "original_string": "def get_vm_by_name(organization, vdcName, vAppName, vmName)\n result = nil\n\n get_vapp_by_name(organization, vdcName, vAppName)[:vms_hash].each do |key, values|\n if key.downcase == vmName.downcase\n result = get_vm(values[:id])\n end\n end\n\n result\n end", "language": "ruby", "code": "def get_vm_by_name(organization, vdcName, vAppName, vmName)\n result = nil\n\n get_vapp_by_name(organization, vdcName, vAppName)[:vms_hash].each do |key, values|\n if key.downcase == vmName.downcase\n result = get_vm(values[:id])\n end\n end\n\n result\n end", "code_tokens": ["def", "get_vm_by_name", "(", "organization", ",", "vdcName", ",", "vAppName", ",", "vmName", ")", "result", "=", "nil", "get_vapp_by_name", "(", "organization", ",", "vdcName", ",", "vAppName", ")", "[", ":vms_hash", "]", ".", "each", "do", "|", "key", ",", "values", "|", "if", "key", ".", "downcase", "==", "vmName", ".", "downcase", "result", "=", "get_vm", "(", "values", "[", ":id", "]", ")", "end", "end", "result", "end"], "docstring": "Friendly helper method to fetch a vApp by name\n - Organization object\n - Organization VDC Name\n - vApp Name\n - VM Name", "docstring_tokens": ["Friendly", "helper", "method", "to", "fetch", "a", "vApp", "by", "name", "-", "Organization", "object", "-", "Organization", "VDC", "Name", "-", "vApp", "Name", "-", "VM", "Name"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L391-L401", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vm.rb", "func_name": "VCloudClient.Connection.poweroff_vm", "original_string": "def poweroff_vm(vmId)\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.UndeployVAppParams(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\") {\n xml.UndeployPowerAction 'powerOff'\n }\n end\n\n params = {\n 'method' => :post,\n 'command' => \"/vApp/vm-#{vmId}/action/undeploy\"\n }\n\n response, headers = send_request(params, builder.to_xml,\n \"application/vnd.vmware.vcloud.undeployVAppParams+xml\")\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "language": "ruby", "code": "def poweroff_vm(vmId)\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.UndeployVAppParams(\n \"xmlns\" => \"http://www.vmware.com/vcloud/v1.5\") {\n xml.UndeployPowerAction 'powerOff'\n }\n end\n\n params = {\n 'method' => :post,\n 'command' => \"/vApp/vm-#{vmId}/action/undeploy\"\n }\n\n response, headers = send_request(params, builder.to_xml,\n \"application/vnd.vmware.vcloud.undeployVAppParams+xml\")\n task_id = headers[:location].gsub(/.*\\/task\\//, \"\")\n task_id\n end", "code_tokens": ["def", "poweroff_vm", "(", "vmId", ")", "builder", "=", "Nokogiri", "::", "XML", "::", "Builder", ".", "new", "do", "|", "xml", "|", "xml", ".", "UndeployVAppParams", "(", "\"xmlns\"", "=>", "\"http://www.vmware.com/vcloud/v1.5\"", ")", "{", "xml", ".", "UndeployPowerAction", "'powerOff'", "}", "end", "params", "=", "{", "'method'", "=>", ":post", ",", "'command'", "=>", "\"/vApp/vm-#{vmId}/action/undeploy\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ",", "builder", ".", "to_xml", ",", "\"application/vnd.vmware.vcloud.undeployVAppParams+xml\"", ")", "task_id", "=", "headers", "[", ":location", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "task_id", "end"], "docstring": "Shutdown a given vm", "docstring_tokens": ["Shutdown", "a", "given", "vm"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L405-L422", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vm.rb", "func_name": "VCloudClient.Connection.acquire_ticket_vm", "original_string": "def acquire_ticket_vm(vmId)\n\n params = {\n 'method' => :post,\n 'command' => \"/vApp/vm-#{vmId}/screen/action/acquireTicket\"\n }\n\n response, headers = send_request(params)\n\n screen_ticket = response.css(\"ScreenTicket\").text\n\n result = {}\n\n if screen_ticket =~ /mks:\\/\\/([^\\/]*)\\/([^\\?]*)\\?ticket=(.*)/\n result = { host: $1, moid: $2, token: $3 }\n result[:token] = URI.unescape result[:token]\n end\n result\n end", "language": "ruby", "code": "def acquire_ticket_vm(vmId)\n\n params = {\n 'method' => :post,\n 'command' => \"/vApp/vm-#{vmId}/screen/action/acquireTicket\"\n }\n\n response, headers = send_request(params)\n\n screen_ticket = response.css(\"ScreenTicket\").text\n\n result = {}\n\n if screen_ticket =~ /mks:\\/\\/([^\\/]*)\\/([^\\?]*)\\?ticket=(.*)/\n result = { host: $1, moid: $2, token: $3 }\n result[:token] = URI.unescape result[:token]\n end\n result\n end", "code_tokens": ["def", "acquire_ticket_vm", "(", "vmId", ")", "params", "=", "{", "'method'", "=>", ":post", ",", "'command'", "=>", "\"/vApp/vm-#{vmId}/screen/action/acquireTicket\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ")", "screen_ticket", "=", "response", ".", "css", "(", "\"ScreenTicket\"", ")", ".", "text", "result", "=", "{", "}", "if", "screen_ticket", "=~", "/", "\\/", "\\/", "\\/", "\\/", "\\?", "\\?", "/", "result", "=", "{", "host", ":", "$1", ",", "moid", ":", "$2", ",", "token", ":", "$3", "}", "result", "[", ":token", "]", "=", "URI", ".", "unescape", "result", "[", ":token", "]", "end", "result", "end"], "docstring": "Retrieve a screen ticket that you can use with the VMRC browser plug-in\n to gain access to the console of a running VM.", "docstring_tokens": ["Retrieve", "a", "screen", "ticket", "that", "you", "can", "use", "with", "the", "VMRC", "browser", "plug", "-", "in", "to", "gain", "access", "to", "the", "console", "of", "a", "running", "VM", "."], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vm.rb#L478-L496", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/network.rb", "func_name": "VCloudClient.Connection.get_network", "original_string": "def get_network(networkId)\n response = get_base_network(networkId)\n\n name = response.css('OrgVdcNetwork').attribute('name').text\n\n description = response.css(\"Description\").first\n description = description.text unless description.nil?\n\n gateway = response.css('Gateway')\n gateway = gateway.text unless gateway.nil?\n\n netmask = response.css('Netmask')\n netmask = netmask.text unless netmask.nil?\n\n fence_mode = response.css('FenceMode')\n fence_mode = fence_mode.text unless fence_mode.nil?\n\n start_address = response.css('StartAddress')\n start_address = start_address.text unless start_address.nil?\n\n end_address = response.css('EndAddress')\n end_address = end_address.text unless end_address.nil?\n\n\n { :id => networkId, :name => name, :description => description,\n :gateway => gateway, :netmask => netmask, :fence_mode => fence_mode,\n :start_address => start_address, :end_address => end_address }\n end", "language": "ruby", "code": "def get_network(networkId)\n response = get_base_network(networkId)\n\n name = response.css('OrgVdcNetwork').attribute('name').text\n\n description = response.css(\"Description\").first\n description = description.text unless description.nil?\n\n gateway = response.css('Gateway')\n gateway = gateway.text unless gateway.nil?\n\n netmask = response.css('Netmask')\n netmask = netmask.text unless netmask.nil?\n\n fence_mode = response.css('FenceMode')\n fence_mode = fence_mode.text unless fence_mode.nil?\n\n start_address = response.css('StartAddress')\n start_address = start_address.text unless start_address.nil?\n\n end_address = response.css('EndAddress')\n end_address = end_address.text unless end_address.nil?\n\n\n { :id => networkId, :name => name, :description => description,\n :gateway => gateway, :netmask => netmask, :fence_mode => fence_mode,\n :start_address => start_address, :end_address => end_address }\n end", "code_tokens": ["def", "get_network", "(", "networkId", ")", "response", "=", "get_base_network", "(", "networkId", ")", "name", "=", "response", ".", "css", "(", "'OrgVdcNetwork'", ")", ".", "attribute", "(", "'name'", ")", ".", "text", "description", "=", "response", ".", "css", "(", "\"Description\"", ")", ".", "first", "description", "=", "description", ".", "text", "unless", "description", ".", "nil?", "gateway", "=", "response", ".", "css", "(", "'Gateway'", ")", "gateway", "=", "gateway", ".", "text", "unless", "gateway", ".", "nil?", "netmask", "=", "response", ".", "css", "(", "'Netmask'", ")", "netmask", "=", "netmask", ".", "text", "unless", "netmask", ".", "nil?", "fence_mode", "=", "response", ".", "css", "(", "'FenceMode'", ")", "fence_mode", "=", "fence_mode", ".", "text", "unless", "fence_mode", ".", "nil?", "start_address", "=", "response", ".", "css", "(", "'StartAddress'", ")", "start_address", "=", "start_address", ".", "text", "unless", "start_address", ".", "nil?", "end_address", "=", "response", ".", "css", "(", "'EndAddress'", ")", "end_address", "=", "end_address", ".", "text", "unless", "end_address", ".", "nil?", "{", ":id", "=>", "networkId", ",", ":name", "=>", "name", ",", ":description", "=>", "description", ",", ":gateway", "=>", "gateway", ",", ":netmask", "=>", "netmask", ",", ":fence_mode", "=>", "fence_mode", ",", ":start_address", "=>", "start_address", ",", ":end_address", "=>", "end_address", "}", "end"], "docstring": "Fetch details about a given Org VDC network", "docstring_tokens": ["Fetch", "details", "about", "a", "given", "Org", "VDC", "network"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/network.rb#L5-L32", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/org.rb", "func_name": "VCloudClient.Connection.get_organizations", "original_string": "def get_organizations\n params = {\n 'method' => :get,\n 'command' => '/org'\n }\n\n response, headers = send_request(params)\n orgs = response.css('OrgList Org')\n\n results = {}\n orgs.each do |org|\n results[org['name']] = org['href'].gsub(/.*\\/org\\//, \"\")\n end\n results\n end", "language": "ruby", "code": "def get_organizations\n params = {\n 'method' => :get,\n 'command' => '/org'\n }\n\n response, headers = send_request(params)\n orgs = response.css('OrgList Org')\n\n results = {}\n orgs.each do |org|\n results[org['name']] = org['href'].gsub(/.*\\/org\\//, \"\")\n end\n results\n end", "code_tokens": ["def", "get_organizations", "params", "=", "{", "'method'", "=>", ":get", ",", "'command'", "=>", "'/org'", "}", "response", ",", "headers", "=", "send_request", "(", "params", ")", "orgs", "=", "response", ".", "css", "(", "'OrgList Org'", ")", "results", "=", "{", "}", "orgs", ".", "each", "do", "|", "org", "|", "results", "[", "org", "[", "'name'", "]", "]", "=", "org", "[", "'href'", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "end", "results", "end"], "docstring": "Fetch existing organizations and their IDs", "docstring_tokens": ["Fetch", "existing", "organizations", "and", "their", "IDs"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/org.rb#L5-L19", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/org.rb", "func_name": "VCloudClient.Connection.get_tasks_list", "original_string": "def get_tasks_list(id)\n params = {\n 'method' => :get,\n 'command' => \"/tasksList/#{id}\"\n }\n\n response, headers = send_request(params)\n\n tasks = []\n\n response.css('Task').each do |task|\n id = task['href'].gsub(/.*\\/task\\//, \"\")\n operation = task['operationName']\n status = task['status']\n error = nil\n error = task.css('Error').first['message'] if task['status'] == 'error'\n start_time = task['startTime']\n end_time = task['endTime']\n user_canceled = task['cancelRequested'] == 'true'\n\n tasks << {\n :id => id,\n :operation => operation,\n :status => status,\n :error => error,\n :start_time => start_time,\n :end_time => end_time,\n :user_canceled => user_canceled\n }\n end\n tasks\n end", "language": "ruby", "code": "def get_tasks_list(id)\n params = {\n 'method' => :get,\n 'command' => \"/tasksList/#{id}\"\n }\n\n response, headers = send_request(params)\n\n tasks = []\n\n response.css('Task').each do |task|\n id = task['href'].gsub(/.*\\/task\\//, \"\")\n operation = task['operationName']\n status = task['status']\n error = nil\n error = task.css('Error').first['message'] if task['status'] == 'error'\n start_time = task['startTime']\n end_time = task['endTime']\n user_canceled = task['cancelRequested'] == 'true'\n\n tasks << {\n :id => id,\n :operation => operation,\n :status => status,\n :error => error,\n :start_time => start_time,\n :end_time => end_time,\n :user_canceled => user_canceled\n }\n end\n tasks\n end", "code_tokens": ["def", "get_tasks_list", "(", "id", ")", "params", "=", "{", "'method'", "=>", ":get", ",", "'command'", "=>", "\"/tasksList/#{id}\"", "}", "response", ",", "headers", "=", "send_request", "(", "params", ")", "tasks", "=", "[", "]", "response", ".", "css", "(", "'Task'", ")", ".", "each", "do", "|", "task", "|", "id", "=", "task", "[", "'href'", "]", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "\"\"", ")", "operation", "=", "task", "[", "'operationName'", "]", "status", "=", "task", "[", "'status'", "]", "error", "=", "nil", "error", "=", "task", ".", "css", "(", "'Error'", ")", ".", "first", "[", "'message'", "]", "if", "task", "[", "'status'", "]", "==", "'error'", "start_time", "=", "task", "[", "'startTime'", "]", "end_time", "=", "task", "[", "'endTime'", "]", "user_canceled", "=", "task", "[", "'cancelRequested'", "]", "==", "'true'", "tasks", "<<", "{", ":id", "=>", "id", ",", ":operation", "=>", "operation", ",", ":status", "=>", "status", ",", ":error", "=>", "error", ",", ":start_time", "=>", "start_time", ",", ":end_time", "=>", "end_time", ",", ":user_canceled", "=>", "user_canceled", "}", "end", "tasks", "end"], "docstring": "Fetch tasks from a given task list\n\n Note: id can be retrieved using get_organization", "docstring_tokens": ["Fetch", "tasks", "from", "a", "given", "task", "list"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/org.rb#L96-L127", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vdc.rb", "func_name": "VCloudClient.Connection.get_vdc_id_by_name", "original_string": "def get_vdc_id_by_name(organization, vdcName)\n result = nil\n\n organization[:vdcs].each do |vdc|\n if vdc[0].downcase == vdcName.downcase\n result = vdc[1]\n end\n end\n\n result\n end", "language": "ruby", "code": "def get_vdc_id_by_name(organization, vdcName)\n result = nil\n\n organization[:vdcs].each do |vdc|\n if vdc[0].downcase == vdcName.downcase\n result = vdc[1]\n end\n end\n\n result\n end", "code_tokens": ["def", "get_vdc_id_by_name", "(", "organization", ",", "vdcName", ")", "result", "=", "nil", "organization", "[", ":vdcs", "]", ".", "each", "do", "|", "vdc", "|", "if", "vdc", "[", "0", "]", ".", "downcase", "==", "vdcName", ".", "downcase", "result", "=", "vdc", "[", "1", "]", "end", "end", "result", "end"], "docstring": "Friendly helper method to fetch a Organization VDC Id by name\n - Organization object\n - Organization VDC Name", "docstring_tokens": ["Friendly", "helper", "method", "to", "fetch", "a", "Organization", "VDC", "Id", "by", "name", "-", "Organization", "object", "-", "Organization", "VDC", "Name"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vdc.rb#L53-L63", "partition": "valid"} {"repo": "vmware/vcloud-rest", "path": "lib/vcloud-rest/vcloud/vdc.rb", "func_name": "VCloudClient.Connection.get_vdc_by_name", "original_string": "def get_vdc_by_name(organization, vdcName)\n result = nil\n\n organization[:vdcs].each do |vdc|\n if vdc[0].downcase == vdcName.downcase\n result = get_vdc(vdc[1])\n end\n end\n\n result\n end", "language": "ruby", "code": "def get_vdc_by_name(organization, vdcName)\n result = nil\n\n organization[:vdcs].each do |vdc|\n if vdc[0].downcase == vdcName.downcase\n result = get_vdc(vdc[1])\n end\n end\n\n result\n end", "code_tokens": ["def", "get_vdc_by_name", "(", "organization", ",", "vdcName", ")", "result", "=", "nil", "organization", "[", ":vdcs", "]", ".", "each", "do", "|", "vdc", "|", "if", "vdc", "[", "0", "]", ".", "downcase", "==", "vdcName", ".", "downcase", "result", "=", "get_vdc", "(", "vdc", "[", "1", "]", ")", "end", "end", "result", "end"], "docstring": "Friendly helper method to fetch a Organization VDC by name\n - Organization object\n - Organization VDC Name", "docstring_tokens": ["Friendly", "helper", "method", "to", "fetch", "a", "Organization", "VDC", "by", "name", "-", "Organization", "object", "-", "Organization", "VDC", "Name"], "sha": "45425d93acf988946cac375b803100ad01206459", "url": "https://github.com/vmware/vcloud-rest/blob/45425d93acf988946cac375b803100ad01206459/lib/vcloud-rest/vcloud/vdc.rb#L69-L79", "partition": "valid"} {"repo": "markkorput/data-provider", "path": "lib/data_provider/container.rb", "func_name": "DataProvider.Container.add!", "original_string": "def add!(container)\n ### add container's providers ###\n # internally providers are added in reverse order (last one first)\n # so at runtime you it's easy and fast to grab the latest provider\n # so when adding now, we have to reverse the providers to get them in the original order\n container.providers.reverse.each do |definition|\n add_provider(*definition)\n end\n\n ### add container's provides (simple providers) ###\n self.provides(container.provides)\n\n ### fallback provider ###\n @fallback_provider = container.fallback_provider.block if container.fallback_provider\n\n ### add container's data ###\n give!(container.data)\n end", "language": "ruby", "code": "def add!(container)\n ### add container's providers ###\n # internally providers are added in reverse order (last one first)\n # so at runtime you it's easy and fast to grab the latest provider\n # so when adding now, we have to reverse the providers to get them in the original order\n container.providers.reverse.each do |definition|\n add_provider(*definition)\n end\n\n ### add container's provides (simple providers) ###\n self.provides(container.provides)\n\n ### fallback provider ###\n @fallback_provider = container.fallback_provider.block if container.fallback_provider\n\n ### add container's data ###\n give!(container.data)\n end", "code_tokens": ["def", "add!", "(", "container", ")", "### add container's providers ###", "# internally providers are added in reverse order (last one first)", "# so at runtime you it's easy and fast to grab the latest provider", "# so when adding now, we have to reverse the providers to get them in the original order", "container", ".", "providers", ".", "reverse", ".", "each", "do", "|", "definition", "|", "add_provider", "(", "definition", ")", "end", "### add container's provides (simple providers) ###", "self", ".", "provides", "(", "container", ".", "provides", ")", "### fallback provider ###", "@fallback_provider", "=", "container", ".", "fallback_provider", ".", "block", "if", "container", ".", "fallback_provider", "### add container's data ###", "give!", "(", "container", ".", "data", ")", "end"], "docstring": "\"adding existing containers\"-related methods\n\n adds all the providers defined in the given module to this class", "docstring_tokens": ["adding", "existing", "containers", "-", "related", "methods"], "sha": "faf2d0e5bb88f31da8517974cd315dddb7ded80d", "url": "https://github.com/markkorput/data-provider/blob/faf2d0e5bb88f31da8517974cd315dddb7ded80d/lib/data_provider/container.rb#L149-L166", "partition": "valid"} {"repo": "markkorput/data-provider", "path": "lib/data_provider/container.rb", "func_name": "DataProvider.Container.get_provider", "original_string": "def get_provider(id, opts = {})\n # get all matching providers\n matching_provider_args = providers.find_all{|args| args.first == id}\n # sort providers on priority, form high to low\n matching_provider_args.sort! do |args_a, args_b|\n # we want to sort from high priority to low, but providers with the same priority level\n # should stay in the same order because among those, the last one added has the highest priority\n # (last added means first in the array, since they are pushed into the beginning of the array)\n (Provider.new(*args_b).priority || self.default_priority) <=> (Provider.new(*args_a).priority || self.default_priority)\n end\n # if no skip option is given, opts[:skip].to_i will result in zero, so it'll grab thefirst from the array\n # if the array is empty, args will always turn out nil\n args = matching_provider_args[opts[:skip].to_i]\n\n return args.nil? ? nil : Provider.new(*args)\n end", "language": "ruby", "code": "def get_provider(id, opts = {})\n # get all matching providers\n matching_provider_args = providers.find_all{|args| args.first == id}\n # sort providers on priority, form high to low\n matching_provider_args.sort! do |args_a, args_b|\n # we want to sort from high priority to low, but providers with the same priority level\n # should stay in the same order because among those, the last one added has the highest priority\n # (last added means first in the array, since they are pushed into the beginning of the array)\n (Provider.new(*args_b).priority || self.default_priority) <=> (Provider.new(*args_a).priority || self.default_priority)\n end\n # if no skip option is given, opts[:skip].to_i will result in zero, so it'll grab thefirst from the array\n # if the array is empty, args will always turn out nil\n args = matching_provider_args[opts[:skip].to_i]\n\n return args.nil? ? nil : Provider.new(*args)\n end", "code_tokens": ["def", "get_provider", "(", "id", ",", "opts", "=", "{", "}", ")", "# get all matching providers", "matching_provider_args", "=", "providers", ".", "find_all", "{", "|", "args", "|", "args", ".", "first", "==", "id", "}", "# sort providers on priority, form high to low", "matching_provider_args", ".", "sort!", "do", "|", "args_a", ",", "args_b", "|", "# we want to sort from high priority to low, but providers with the same priority level", "# should stay in the same order because among those, the last one added has the highest priority", "# (last added means first in the array, since they are pushed into the beginning of the array)", "(", "Provider", ".", "new", "(", "args_b", ")", ".", "priority", "||", "self", ".", "default_priority", ")", "<=>", "(", "Provider", ".", "new", "(", "args_a", ")", ".", "priority", "||", "self", ".", "default_priority", ")", "end", "# if no skip option is given, opts[:skip].to_i will result in zero, so it'll grab thefirst from the array", "# if the array is empty, args will always turn out nil", "args", "=", "matching_provider_args", "[", "opts", "[", ":skip", "]", ".", "to_i", "]", "return", "args", ".", "nil?", "?", "nil", ":", "Provider", ".", "new", "(", "args", ")", "end"], "docstring": "returns the requested provider as a Provider object", "docstring_tokens": ["returns", "the", "requested", "provider", "as", "a", "Provider", "object"], "sha": "faf2d0e5bb88f31da8517974cd315dddb7ded80d", "url": "https://github.com/markkorput/data-provider/blob/faf2d0e5bb88f31da8517974cd315dddb7ded80d/lib/data_provider/container.rb#L296-L311", "partition": "valid"} {"repo": "rbialek/rack-tidy", "path": "lib/rack/tidy/cleaner.rb", "func_name": "Rack::Tidy.Cleaner.call!", "original_string": "def call!(env)\n @env = env.dup\n status, @headers, response = @app.call(@env) \n if should_clean?\n @headers.delete('Content-Length')\n response = Rack::Response.new(\n tidy_markup(response.respond_to?(:body) ? response.body : response),\n status,\n @headers\n )\n response.finish\n response.to_a\n else\n [status, @headers, response]\n end\n end", "language": "ruby", "code": "def call!(env)\n @env = env.dup\n status, @headers, response = @app.call(@env) \n if should_clean?\n @headers.delete('Content-Length')\n response = Rack::Response.new(\n tidy_markup(response.respond_to?(:body) ? response.body : response),\n status,\n @headers\n )\n response.finish\n response.to_a\n else\n [status, @headers, response]\n end\n end", "code_tokens": ["def", "call!", "(", "env", ")", "@env", "=", "env", ".", "dup", "status", ",", "@headers", ",", "response", "=", "@app", ".", "call", "(", "@env", ")", "if", "should_clean?", "@headers", ".", "delete", "(", "'Content-Length'", ")", "response", "=", "Rack", "::", "Response", ".", "new", "(", "tidy_markup", "(", "response", ".", "respond_to?", "(", ":body", ")", "?", "response", ".", "body", ":", "response", ")", ",", "status", ",", "@headers", ")", "response", ".", "finish", "response", ".", "to_a", "else", "[", "status", ",", "@headers", ",", "response", "]", "end", "end"], "docstring": "thread safe version using shallow copy of env", "docstring_tokens": ["thread", "safe", "version", "using", "shallow", "copy", "of", "env"], "sha": "fb563cd33da97a3f852c1a7fa0a5fcb51ccbe2c5", "url": "https://github.com/rbialek/rack-tidy/blob/fb563cd33da97a3f852c1a7fa0a5fcb51ccbe2c5/lib/rack/tidy/cleaner.rb#L34-L49", "partition": "valid"} {"repo": "stefankroes/scribble", "path": "lib/scribble/registry.rb", "func_name": "Scribble.Registry.for", "original_string": "def for *classes, &proc\n classes.each { |receiver_class| ForClassContext.new(self, receiver_class).instance_eval &proc }\n end", "language": "ruby", "code": "def for *classes, &proc\n classes.each { |receiver_class| ForClassContext.new(self, receiver_class).instance_eval &proc }\n end", "code_tokens": ["def", "for", "*", "classes", ",", "&", "proc", "classes", ".", "each", "{", "|", "receiver_class", "|", "ForClassContext", ".", "new", "(", "self", ",", "receiver_class", ")", ".", "instance_eval", "proc", "}", "end"], "docstring": "For class context", "docstring_tokens": ["For", "class", "context"], "sha": "bd889cff108c1785cd28150763abd9b31782b44f", "url": "https://github.com/stefankroes/scribble/blob/bd889cff108c1785cd28150763abd9b31782b44f/lib/scribble/registry.rb#L16-L18", "partition": "valid"} {"repo": "stefankroes/scribble", "path": "lib/scribble/registry.rb", "func_name": "Scribble.Registry.evaluate", "original_string": "def evaluate name, receiver, args, call = nil, context = nil\n matcher = Support::Matcher.new self, name, receiver, args\n matcher.match.new(receiver, call, context).send name, *args\n end", "language": "ruby", "code": "def evaluate name, receiver, args, call = nil, context = nil\n matcher = Support::Matcher.new self, name, receiver, args\n matcher.match.new(receiver, call, context).send name, *args\n end", "code_tokens": ["def", "evaluate", "name", ",", "receiver", ",", "args", ",", "call", "=", "nil", ",", "context", "=", "nil", "matcher", "=", "Support", "::", "Matcher", ".", "new", "self", ",", "name", ",", "receiver", ",", "args", "matcher", ".", "match", ".", "new", "(", "receiver", ",", "call", ",", "context", ")", ".", "send", "name", ",", "args", "end"], "docstring": "Evaluate or cast", "docstring_tokens": ["Evaluate", "or", "cast"], "sha": "bd889cff108c1785cd28150763abd9b31782b44f", "url": "https://github.com/stefankroes/scribble/blob/bd889cff108c1785cd28150763abd9b31782b44f/lib/scribble/registry.rb#L65-L68", "partition": "valid"} {"repo": "mattbrictson/bundleup", "path": "lib/bundleup/console.rb", "func_name": "Bundleup.Console.progress", "original_string": "def progress(message, &block)\n spinner = %w[/ - \\\\ |].cycle\n print \"\\e[90m#{message}... \\e[0m\"\n result = observing_thread(block, 0.5, 0.1) do\n print \"\\r\\e[90m#{message}... #{spinner.next} \\e[0m\"\n end\n puts \"\\r\\e[90m#{message}... OK\\e[0m\"\n result\n rescue StandardError\n puts \"\\r\\e[90m#{message}...\\e[0m \\e[31mFAILED\\e[0m\"\n raise\n end", "language": "ruby", "code": "def progress(message, &block)\n spinner = %w[/ - \\\\ |].cycle\n print \"\\e[90m#{message}... \\e[0m\"\n result = observing_thread(block, 0.5, 0.1) do\n print \"\\r\\e[90m#{message}... #{spinner.next} \\e[0m\"\n end\n puts \"\\r\\e[90m#{message}... OK\\e[0m\"\n result\n rescue StandardError\n puts \"\\r\\e[90m#{message}...\\e[0m \\e[31mFAILED\\e[0m\"\n raise\n end", "code_tokens": ["def", "progress", "(", "message", ",", "&", "block", ")", "spinner", "=", "%w[", "/", " \\\\", "|", "]", ".", "cycle", "print", "\"\\e[90m#{message}... \\e[0m\"", "result", "=", "observing_thread", "(", "block", ",", "0.5", ",", "0.1", ")", "do", "print", "\"\\r\\e[90m#{message}... #{spinner.next} \\e[0m\"", "end", "puts", "\"\\r\\e[90m#{message}... OK\\e[0m\"", "result", "rescue", "StandardError", "puts", "\"\\r\\e[90m#{message}...\\e[0m \\e[31mFAILED\\e[0m\"", "raise", "end"], "docstring": "Runs a block in the background and displays a spinner until it completes.", "docstring_tokens": ["Runs", "a", "block", "in", "the", "background", "and", "displays", "a", "spinner", "until", "it", "completes", "."], "sha": "2d0c63fae76506a41af5827d5c7f6db570dfe473", "url": "https://github.com/mattbrictson/bundleup/blob/2d0c63fae76506a41af5827d5c7f6db570dfe473/lib/bundleup/console.rb#L32-L43", "partition": "valid"} {"repo": "mattbrictson/bundleup", "path": "lib/bundleup/console.rb", "func_name": "Bundleup.Console.tableize", "original_string": "def tableize(rows, &block)\n rows = rows.map(&block) if block\n widths = max_length_of_each_column(rows)\n rows.map do |row|\n row.zip(widths).map { |value, width| value.ljust(width) }.join(\" \")\n end\n end", "language": "ruby", "code": "def tableize(rows, &block)\n rows = rows.map(&block) if block\n widths = max_length_of_each_column(rows)\n rows.map do |row|\n row.zip(widths).map { |value, width| value.ljust(width) }.join(\" \")\n end\n end", "code_tokens": ["def", "tableize", "(", "rows", ",", "&", "block", ")", "rows", "=", "rows", ".", "map", "(", "block", ")", "if", "block", "widths", "=", "max_length_of_each_column", "(", "rows", ")", "rows", ".", "map", "do", "|", "row", "|", "row", ".", "zip", "(", "widths", ")", ".", "map", "{", "|", "value", ",", "width", "|", "value", ".", "ljust", "(", "width", ")", "}", ".", "join", "(", "\" \"", ")", "end", "end"], "docstring": "Given a two-dimensional Array of strings representing a table of data,\n translate each row into a single string by joining the values with\n whitespace such that all the columns are nicely aligned.\n\n If a block is given, map the rows through the block first. These two\n usages are equivalent:\n\n tableize(rows.map(&something))\n tableize(rows, &something)\n\n Returns a one-dimensional Array of strings, each representing a formatted\n row of the resulting table.", "docstring_tokens": ["Given", "a", "two", "-", "dimensional", "Array", "of", "strings", "representing", "a", "table", "of", "data", "translate", "each", "row", "into", "a", "single", "string", "by", "joining", "the", "values", "with", "whitespace", "such", "that", "all", "the", "columns", "are", "nicely", "aligned", "."], "sha": "2d0c63fae76506a41af5827d5c7f6db570dfe473", "url": "https://github.com/mattbrictson/bundleup/blob/2d0c63fae76506a41af5827d5c7f6db570dfe473/lib/bundleup/console.rb#L58-L64", "partition": "valid"} {"repo": "mattbrictson/bundleup", "path": "lib/bundleup/console.rb", "func_name": "Bundleup.Console.observing_thread", "original_string": "def observing_thread(callable, initial_wait, periodic_wait)\n thread = Thread.new(&callable)\n wait_for_exit(thread, initial_wait)\n loop do\n break if wait_for_exit(thread, periodic_wait)\n\n yield\n end\n thread.value\n end", "language": "ruby", "code": "def observing_thread(callable, initial_wait, periodic_wait)\n thread = Thread.new(&callable)\n wait_for_exit(thread, initial_wait)\n loop do\n break if wait_for_exit(thread, periodic_wait)\n\n yield\n end\n thread.value\n end", "code_tokens": ["def", "observing_thread", "(", "callable", ",", "initial_wait", ",", "periodic_wait", ")", "thread", "=", "Thread", ".", "new", "(", "callable", ")", "wait_for_exit", "(", "thread", ",", "initial_wait", ")", "loop", "do", "break", "if", "wait_for_exit", "(", "thread", ",", "periodic_wait", ")", "yield", "end", "thread", ".", "value", "end"], "docstring": "Starts the `callable` in a background thread and waits for it to complete.\n If the callable fails with an exception, it will be raised here. Otherwise\n the main thread is paused for an `initial_wait` time in seconds, and\n subsequently for `periodic_wait` repeatedly until the thread completes.\n After each wait, `yield` is called to allow a block to execute.", "docstring_tokens": ["Starts", "the", "callable", "in", "a", "background", "thread", "and", "waits", "for", "it", "to", "complete", ".", "If", "the", "callable", "fails", "with", "an", "exception", "it", "will", "be", "raised", "here", ".", "Otherwise", "the", "main", "thread", "is", "paused", "for", "an", "initial_wait", "time", "in", "seconds", "and", "subsequently", "for", "periodic_wait", "repeatedly", "until", "the", "thread", "completes", ".", "After", "each", "wait", "yield", "is", "called", "to", "allow", "a", "block", "to", "execute", "."], "sha": "2d0c63fae76506a41af5827d5c7f6db570dfe473", "url": "https://github.com/mattbrictson/bundleup/blob/2d0c63fae76506a41af5827d5c7f6db570dfe473/lib/bundleup/console.rb#L79-L88", "partition": "valid"} {"repo": "leesharma/rescuetime", "path": "lib/rescuetime/collection.rb", "func_name": "Rescuetime.Collection.all", "original_string": "def all\n requester = Rescuetime::Requester\n host = HOST\n parse_response requester.get(host, params)\n end", "language": "ruby", "code": "def all\n requester = Rescuetime::Requester\n host = HOST\n parse_response requester.get(host, params)\n end", "code_tokens": ["def", "all", "requester", "=", "Rescuetime", "::", "Requester", "host", "=", "HOST", "parse_response", "requester", ".", "get", "(", "host", ",", "params", ")", "end"], "docstring": "Performs the rescuetime query and returns an array or csv response.\n\n @return [Array, CSV]\n\n @see Rescuetime::Requester#get", "docstring_tokens": ["Performs", "the", "rescuetime", "query", "and", "returns", "an", "array", "or", "csv", "response", "."], "sha": "c69e6d41f31dbaf5053be51a1e45293605612f1e", "url": "https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/collection.rb#L41-L45", "partition": "valid"} {"repo": "leesharma/rescuetime", "path": "lib/rescuetime/collection.rb", "func_name": "Rescuetime.Collection.format", "original_string": "def format(format)\n # Guard: fail if the passed format isn't on the whitelist\n format = format.to_s\n formatters.all.include?(format) || raise(Errors::InvalidFormatError)\n\n @format = format\n self\n end", "language": "ruby", "code": "def format(format)\n # Guard: fail if the passed format isn't on the whitelist\n format = format.to_s\n formatters.all.include?(format) || raise(Errors::InvalidFormatError)\n\n @format = format\n self\n end", "code_tokens": ["def", "format", "(", "format", ")", "# Guard: fail if the passed format isn't on the whitelist", "format", "=", "format", ".", "to_s", "formatters", ".", "all", ".", "include?", "(", "format", ")", "||", "raise", "(", "Errors", "::", "InvalidFormatError", ")", "@format", "=", "format", "self", "end"], "docstring": "Sets the report format to a valid type\n\n @param [#to_s] format desired report format (one of 'array' or 'csv')\n @return [Rescuetime::Collection]\n\n TODO: make chainable to the client", "docstring_tokens": ["Sets", "the", "report", "format", "to", "a", "valid", "type"], "sha": "c69e6d41f31dbaf5053be51a1e45293605612f1e", "url": "https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/collection.rb#L64-L71", "partition": "valid"} {"repo": "leesharma/rescuetime", "path": "lib/rescuetime/collection.rb", "func_name": "Rescuetime.Collection.parse_response", "original_string": "def parse_response(body)\n report = CSV.new(body,\n headers: true,\n header_converters: :symbol,\n converters: :all)\n\n format = @format.to_s.downcase\n report_formatter = formatters.find(format)\n\n report_formatter.format report\n end", "language": "ruby", "code": "def parse_response(body)\n report = CSV.new(body,\n headers: true,\n header_converters: :symbol,\n converters: :all)\n\n format = @format.to_s.downcase\n report_formatter = formatters.find(format)\n\n report_formatter.format report\n end", "code_tokens": ["def", "parse_response", "(", "body", ")", "report", "=", "CSV", ".", "new", "(", "body", ",", "headers", ":", "true", ",", "header_converters", ":", ":symbol", ",", "converters", ":", ":all", ")", "format", "=", "@format", ".", "to_s", ".", "downcase", "report_formatter", "=", "formatters", ".", "find", "(", "format", ")", "report_formatter", ".", "format", "report", "end"], "docstring": "Parses a response from the string response body to the desired format.\n\n @param [String] body response body\n @return [Array, CSV]", "docstring_tokens": ["Parses", "a", "response", "from", "the", "string", "response", "body", "to", "the", "desired", "format", "."], "sha": "c69e6d41f31dbaf5053be51a1e45293605612f1e", "url": "https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/collection.rb#L93-L103", "partition": "valid"} {"repo": "leesharma/rescuetime", "path": "lib/rescuetime/report_formatters.rb", "func_name": "Rescuetime.ReportFormatters.find", "original_string": "def find(name)\n formatter = formatters.find do |f|\n standardize(f.name) == standardize(name)\n end\n formatter || raise(Rescuetime::Errors::InvalidFormatError)\n end", "language": "ruby", "code": "def find(name)\n formatter = formatters.find do |f|\n standardize(f.name) == standardize(name)\n end\n formatter || raise(Rescuetime::Errors::InvalidFormatError)\n end", "code_tokens": ["def", "find", "(", "name", ")", "formatter", "=", "formatters", ".", "find", "do", "|", "f", "|", "standardize", "(", "f", ".", "name", ")", "==", "standardize", "(", "name", ")", "end", "formatter", "||", "raise", "(", "Rescuetime", "::", "Errors", "::", "InvalidFormatError", ")", "end"], "docstring": "Returns the formatter with the specified name or, if not found, raises\n an exception\n\n @param [String] name the name of the desired formatter\n @return [Class] the specified formatter\n\n @raise [Rescuetime::Errors::InvalidFormatError]", "docstring_tokens": ["Returns", "the", "formatter", "with", "the", "specified", "name", "or", "if", "not", "found", "raises", "an", "exception"], "sha": "c69e6d41f31dbaf5053be51a1e45293605612f1e", "url": "https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/report_formatters.rb#L70-L75", "partition": "valid"} {"repo": "leesharma/rescuetime", "path": "lib/rescuetime/query_buildable.rb", "func_name": "Rescuetime.QueryBuildable.order_by", "original_string": "def order_by(order, interval: nil)\n # set order and intervals as symbols\n order = order.to_s\n interval = interval ? interval.to_s : nil\n\n # guards against invalid order or interval\n unless valid_order? order\n raise Errors::InvalidQueryError, \"#{order} is not a valid order\"\n end\n\n unless valid_interval? interval\n raise Errors::InvalidQueryError, \"#{interval} is not a valid interval\"\n end\n\n add_to_query perspective: (order == 'time' ? 'interval' : order),\n resolution_time: interval\n end", "language": "ruby", "code": "def order_by(order, interval: nil)\n # set order and intervals as symbols\n order = order.to_s\n interval = interval ? interval.to_s : nil\n\n # guards against invalid order or interval\n unless valid_order? order\n raise Errors::InvalidQueryError, \"#{order} is not a valid order\"\n end\n\n unless valid_interval? interval\n raise Errors::InvalidQueryError, \"#{interval} is not a valid interval\"\n end\n\n add_to_query perspective: (order == 'time' ? 'interval' : order),\n resolution_time: interval\n end", "code_tokens": ["def", "order_by", "(", "order", ",", "interval", ":", "nil", ")", "# set order and intervals as symbols", "order", "=", "order", ".", "to_s", "interval", "=", "interval", "?", "interval", ".", "to_s", ":", "nil", "# guards against invalid order or interval", "unless", "valid_order?", "order", "raise", "Errors", "::", "InvalidQueryError", ",", "\"#{order} is not a valid order\"", "end", "unless", "valid_interval?", "interval", "raise", "Errors", "::", "InvalidQueryError", ",", "\"#{interval} is not a valid interval\"", "end", "add_to_query", "perspective", ":", "(", "order", "==", "'time'", "?", "'interval'", ":", "order", ")", ",", "resolution_time", ":", "interval", "end"], "docstring": "Specifies the ordering and the interval of the returned Rescuetime report.\n For example, the results can be ordered by time, activity rank, or member;\n The results can be returned in intervals spanning a month, a week, a day,\n an hour, or 5-minutes.\n\n Efficiency reports default to :time order; everything else defaults to\n :rank order.\n\n @example Basic Use\n client = Rescuetime::Client.new\n client.order_by 'time' # interval is not required\n #=> #\n\n client.order_by 'rank', interval: 'hour'\n #=> #\n\n client.order_by :rank, interval: :hour # Symbols are also valid\n #=> #\n\n @example Invalid Values Raise Errors\n client = Rescuetime::Client.new\n client.order_by 'invalid'\n # => Rescuetime::Errors::InvalidQueryError: invalid is not a valid order\n\n client.order_by 'time', interval: 'invalid'\n # => Rescuetime::Errors::InvalidQueryError: invalid is not a valid interval\n\n @param [#to_s] order an order for the results (ex. 'time')\n @param [#intern, nil] interval a chunking interval for results\n (ex. 'month'). defaults to nil\n\n @return [Rescuetime::Collection] a Rescuetime Collection specifying order\n and interval (if set)\n\n @raise [Rescuetime::Errors::InvalidQueryError] if either order or interval are\n invalid\n\n @see https://www.rescuetime.com/apidoc#paramlist Rescuetime API docs\n (see: perspective,\n resolution_time)\n @see Rescuetime::QueryBuildable::VALID List of valid values", "docstring_tokens": ["Specifies", "the", "ordering", "and", "the", "interval", "of", "the", "returned", "Rescuetime", "report", ".", "For", "example", "the", "results", "can", "be", "ordered", "by", "time", "activity", "rank", "or", "member", ";", "The", "results", "can", "be", "returned", "in", "intervals", "spanning", "a", "month", "a", "week", "a", "day", "an", "hour", "or", "5", "-", "minutes", "."], "sha": "c69e6d41f31dbaf5053be51a1e45293605612f1e", "url": "https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/query_buildable.rb#L191-L207", "partition": "valid"} {"repo": "leesharma/rescuetime", "path": "lib/rescuetime/query_buildable.rb", "func_name": "Rescuetime.QueryBuildable.where", "original_string": "def where(name: nil, document: nil)\n # Stand-in for required keyword arguments\n name || raise(ArgumentError, 'missing keyword: name')\n\n add_to_query restrict_thing: name,\n restrict_thingy: document\n end", "language": "ruby", "code": "def where(name: nil, document: nil)\n # Stand-in for required keyword arguments\n name || raise(ArgumentError, 'missing keyword: name')\n\n add_to_query restrict_thing: name,\n restrict_thingy: document\n end", "code_tokens": ["def", "where", "(", "name", ":", "nil", ",", "document", ":", "nil", ")", "# Stand-in for required keyword arguments", "name", "||", "raise", "(", "ArgumentError", ",", "'missing keyword: name'", ")", "add_to_query", "restrict_thing", ":", "name", ",", "restrict_thingy", ":", "document", "end"], "docstring": "Limits the Rescuetime report to specific activities and documents.\n The name option limits the results to those where name is an exact match;\n this can be used on the overview, activity, and category report. The\n document option limits the specific document title; this is only available\n on the activity report.\n\n If a value is passed for an unsupported report, it will be ignored.\n\n To see the category and document names for your account, please look at\n your rescuetime dashboard or generated rescuetime report.\n\n :name can be used on:\n - Overview report\n - Category report\n - Activity report\n\n :document can be used on:\n - Activity report when :name is set\n\n @example Basic Use\n client = Rescuetime::Client.new\n client.activities.where name: 'github.com',\n document: 'leesharma/rescuetime'\n #=> #\n\n @example Valid reports\n client.overview.where name: 'Utilities'\n client.categories.where name: 'Intelligence'\n client.activities.where name: 'github.com'\n client.activities.where name: 'github.com', document: 'rails/rails'\n\n @example Invalid reports\n client.productivity.where name: 'Intelligence' # Invalid!\n client.efficiency.where name: 'Intelligence' # Invalid!\n client.activities.where document: 'rails/rails' # Invalid!\n\n @param [String] name Rescuetime category name, valid on overview,\n category, and activity reports\n @param [String] document Specific document name, valid on activity\n reports when :name is set\n\n @return [Rescuetime::Collection] a Rescuetime Collection specifying\n category name and (optionally) document\n @raise [ArgumentError] if name is not set\n\n @see #overview\n @see #activities\n @see #categories\n @see https://www.rescuetime.com/apidoc#paramlist Rescuetime API docs\n (see: restrict_thing,\n restrict_thingy)\n @since v0.3.0", "docstring_tokens": ["Limits", "the", "Rescuetime", "report", "to", "specific", "activities", "and", "documents", ".", "The", "name", "option", "limits", "the", "results", "to", "those", "where", "name", "is", "an", "exact", "match", ";", "this", "can", "be", "used", "on", "the", "overview", "activity", "and", "category", "report", ".", "The", "document", "option", "limits", "the", "specific", "document", "title", ";", "this", "is", "only", "available", "on", "the", "activity", "report", "."], "sha": "c69e6d41f31dbaf5053be51a1e45293605612f1e", "url": "https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/query_buildable.rb#L362-L368", "partition": "valid"} {"repo": "leesharma/rescuetime", "path": "lib/rescuetime/query_buildable.rb", "func_name": "Rescuetime.QueryBuildable.add_to_query", "original_string": "def add_to_query(**terms)\n if is_a? Rescuetime::Collection\n self << terms\n self\n else\n Rescuetime::Collection.new(BASE_PARAMS, state, terms)\n end\n end", "language": "ruby", "code": "def add_to_query(**terms)\n if is_a? Rescuetime::Collection\n self << terms\n self\n else\n Rescuetime::Collection.new(BASE_PARAMS, state, terms)\n end\n end", "code_tokens": ["def", "add_to_query", "(", "**", "terms", ")", "if", "is_a?", "Rescuetime", "::", "Collection", "self", "<<", "terms", "self", "else", "Rescuetime", "::", "Collection", ".", "new", "(", "BASE_PARAMS", ",", "state", ",", "terms", ")", "end", "end"], "docstring": "Adds terms to the Rescuetime collection query\n\n @param [Hash] terms a set of terms to add to the query\n @return [Rescuetime::Collection]", "docstring_tokens": ["Adds", "terms", "to", "the", "Rescuetime", "collection", "query"], "sha": "c69e6d41f31dbaf5053be51a1e45293605612f1e", "url": "https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/query_buildable.rb#L376-L383", "partition": "valid"} {"repo": "leesharma/rescuetime", "path": "lib/rescuetime/client.rb", "func_name": "Rescuetime.Client.valid_credentials?", "original_string": "def valid_credentials?\n return false unless api_key?\n !activities.all.nil?\n rescue Rescuetime::Errors::InvalidCredentialsError\n false\n end", "language": "ruby", "code": "def valid_credentials?\n return false unless api_key?\n !activities.all.nil?\n rescue Rescuetime::Errors::InvalidCredentialsError\n false\n end", "code_tokens": ["def", "valid_credentials?", "return", "false", "unless", "api_key?", "!", "activities", ".", "all", ".", "nil?", "rescue", "Rescuetime", "::", "Errors", "::", "InvalidCredentialsError", "false", "end"], "docstring": "Returns true if the provided api key is valid. Performs a request to the\n Rescuetime API.\n\n @example Basic Use\n # Assuming that INVALID_KEY is an invalid Rescuetime API key\n # and VALID_KEY is a valid one\n\n client = Rescuetime::Client\n client.valid_credentials?\n # => false\n\n client.api_key = INVALID_KEY\n client.valid_credentials? # Performs a request to the Rescuetime API\n # => false\n\n client.api_key = VALID_KEY\n client.valid_credentials? # Performs a request to the Rescuetime API\n # => true\n\n @return [Boolean]", "docstring_tokens": ["Returns", "true", "if", "the", "provided", "api", "key", "is", "valid", ".", "Performs", "a", "request", "to", "the", "Rescuetime", "API", "."], "sha": "c69e6d41f31dbaf5053be51a1e45293605612f1e", "url": "https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/client.rb#L91-L96", "partition": "valid"} {"repo": "leesharma/rescuetime", "path": "lib/rescuetime/formatters.rb", "func_name": "Rescuetime.Formatters.load_formatter_files", "original_string": "def load_formatter_files(local_path: LOCAL_FORMATTER_PATH)\n # require all formatters, local and configured\n paths = Rescuetime.configuration.formatter_paths << local_path\n paths.each do |path|\n Dir[File.expand_path(path, __FILE__)].each { |file| require file }\n end\n end", "language": "ruby", "code": "def load_formatter_files(local_path: LOCAL_FORMATTER_PATH)\n # require all formatters, local and configured\n paths = Rescuetime.configuration.formatter_paths << local_path\n paths.each do |path|\n Dir[File.expand_path(path, __FILE__)].each { |file| require file }\n end\n end", "code_tokens": ["def", "load_formatter_files", "(", "local_path", ":", "LOCAL_FORMATTER_PATH", ")", "# require all formatters, local and configured", "paths", "=", "Rescuetime", ".", "configuration", ".", "formatter_paths", "<<", "local_path", "paths", ".", "each", "do", "|", "path", "|", "Dir", "[", "File", ".", "expand_path", "(", "path", ",", "__FILE__", ")", "]", ".", "each", "{", "|", "file", "|", "require", "file", "}", "end", "end"], "docstring": "Requires all formatter files, determined by the local path for formatters\n plus any additional paths set in the Rescuetime configuration.\n\n @param [String] local_path the location of the local in-gem formatters\n\n @see Rescuetime::Configuration.formatter_paths", "docstring_tokens": ["Requires", "all", "formatter", "files", "determined", "by", "the", "local", "path", "for", "formatters", "plus", "any", "additional", "paths", "set", "in", "the", "Rescuetime", "configuration", "."], "sha": "c69e6d41f31dbaf5053be51a1e45293605612f1e", "url": "https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/formatters.rb#L40-L46", "partition": "valid"} {"repo": "mislav/nibbler", "path": "lib/nibbler.rb", "func_name": "NibblerMethods.InstanceMethods.parse", "original_string": "def parse\n self.class.rules.each do |target, (selector, delegate, plural)|\n if plural\n send(target).concat @doc.search(selector).map { |i| parse_result(i, delegate) }\n else\n send(\"#{target}=\", parse_result(@doc.at(selector), delegate))\n end\n end\n self\n end", "language": "ruby", "code": "def parse\n self.class.rules.each do |target, (selector, delegate, plural)|\n if plural\n send(target).concat @doc.search(selector).map { |i| parse_result(i, delegate) }\n else\n send(\"#{target}=\", parse_result(@doc.at(selector), delegate))\n end\n end\n self\n end", "code_tokens": ["def", "parse", "self", ".", "class", ".", "rules", ".", "each", "do", "|", "target", ",", "(", "selector", ",", "delegate", ",", "plural", ")", "|", "if", "plural", "send", "(", "target", ")", ".", "concat", "@doc", ".", "search", "(", "selector", ")", ".", "map", "{", "|", "i", "|", "parse_result", "(", "i", ",", "delegate", ")", "}", "else", "send", "(", "\"#{target}=\"", ",", "parse_result", "(", "@doc", ".", "at", "(", "selector", ")", ",", "delegate", ")", ")", "end", "end", "self", "end"], "docstring": "Initialize the parser with a document\n Parse the document and save values returned by selectors", "docstring_tokens": ["Initialize", "the", "parser", "with", "a", "document", "Parse", "the", "document", "and", "save", "values", "returned", "by", "selectors"], "sha": "32ae685077fdf11731ab26bc7ff3e44026cf380e", "url": "https://github.com/mislav/nibbler/blob/32ae685077fdf11731ab26bc7ff3e44026cf380e/lib/nibbler.rb#L71-L80", "partition": "valid"} {"repo": "mislav/nibbler", "path": "lib/nibbler.rb", "func_name": "NibblerMethods.InstanceMethods.to_hash", "original_string": "def to_hash\n converter = lambda { |obj| obj.respond_to?(:to_hash) ? obj.to_hash : obj }\n self.class.rules.keys.inject({}) do |hash, name|\n value = send(name)\n hash[name.to_sym] = Array === value ? value.map(&converter) : converter[value]\n hash\n end\n end", "language": "ruby", "code": "def to_hash\n converter = lambda { |obj| obj.respond_to?(:to_hash) ? obj.to_hash : obj }\n self.class.rules.keys.inject({}) do |hash, name|\n value = send(name)\n hash[name.to_sym] = Array === value ? value.map(&converter) : converter[value]\n hash\n end\n end", "code_tokens": ["def", "to_hash", "converter", "=", "lambda", "{", "|", "obj", "|", "obj", ".", "respond_to?", "(", ":to_hash", ")", "?", "obj", ".", "to_hash", ":", "obj", "}", "self", ".", "class", ".", "rules", ".", "keys", ".", "inject", "(", "{", "}", ")", "do", "|", "hash", ",", "name", "|", "value", "=", "send", "(", "name", ")", "hash", "[", "name", ".", "to_sym", "]", "=", "Array", "===", "value", "?", "value", ".", "map", "(", "converter", ")", ":", "converter", "[", "value", "]", "hash", "end", "end"], "docstring": "Dump the extracted data into a hash with symbolized keys", "docstring_tokens": ["Dump", "the", "extracted", "data", "into", "a", "hash", "with", "symbolized", "keys"], "sha": "32ae685077fdf11731ab26bc7ff3e44026cf380e", "url": "https://github.com/mislav/nibbler/blob/32ae685077fdf11731ab26bc7ff3e44026cf380e/lib/nibbler.rb#L83-L90", "partition": "valid"} {"repo": "mislav/nibbler", "path": "lib/nibbler.rb", "func_name": "NibblerMethods.InstanceMethods.parse_result", "original_string": "def parse_result(node, delegate)\n if delegate\n method = delegate.is_a?(Proc) ? delegate : delegate.method(delegate.respond_to?(:call) ? :call : :parse)\n method.arity == 1 ? method[node] : method[node, self]\n else\n node\n end unless node.nil?\n end", "language": "ruby", "code": "def parse_result(node, delegate)\n if delegate\n method = delegate.is_a?(Proc) ? delegate : delegate.method(delegate.respond_to?(:call) ? :call : :parse)\n method.arity == 1 ? method[node] : method[node, self]\n else\n node\n end unless node.nil?\n end", "code_tokens": ["def", "parse_result", "(", "node", ",", "delegate", ")", "if", "delegate", "method", "=", "delegate", ".", "is_a?", "(", "Proc", ")", "?", "delegate", ":", "delegate", ".", "method", "(", "delegate", ".", "respond_to?", "(", ":call", ")", "?", ":call", ":", ":parse", ")", "method", ".", "arity", "==", "1", "?", "method", "[", "node", "]", ":", "method", "[", "node", ",", "self", "]", "else", "node", "end", "unless", "node", ".", "nil?", "end"], "docstring": "`delegate` is optional, but should respond to `call` or `parse`", "docstring_tokens": ["delegate", "is", "optional", "but", "should", "respond", "to", "call", "or", "parse"], "sha": "32ae685077fdf11731ab26bc7ff3e44026cf380e", "url": "https://github.com/mislav/nibbler/blob/32ae685077fdf11731ab26bc7ff3e44026cf380e/lib/nibbler.rb#L95-L102", "partition": "valid"} {"repo": "mislav/nibbler", "path": "examples/tweetburner.rb", "func_name": "Tweetburner.Scraper.get_document", "original_string": "def get_document(url)\n URI === url ? Nokogiri::HTML::Document.parse(open(url), url.to_s, 'UTF-8') : url\n rescue OpenURI::HTTPError\n $stderr.puts \"ERROR opening #{url}\"\n Nokogiri('')\n end", "language": "ruby", "code": "def get_document(url)\n URI === url ? Nokogiri::HTML::Document.parse(open(url), url.to_s, 'UTF-8') : url\n rescue OpenURI::HTTPError\n $stderr.puts \"ERROR opening #{url}\"\n Nokogiri('')\n end", "code_tokens": ["def", "get_document", "(", "url", ")", "URI", "===", "url", "?", "Nokogiri", "::", "HTML", "::", "Document", ".", "parse", "(", "open", "(", "url", ")", ",", "url", ".", "to_s", ",", "'UTF-8'", ")", ":", "url", "rescue", "OpenURI", "::", "HTTPError", "$stderr", ".", "puts", "\"ERROR opening #{url}\"", "Nokogiri", "(", "''", ")", "end"], "docstring": "open web pages with UTF-8 encoding", "docstring_tokens": ["open", "web", "pages", "with", "UTF", "-", "8", "encoding"], "sha": "32ae685077fdf11731ab26bc7ff3e44026cf380e", "url": "https://github.com/mislav/nibbler/blob/32ae685077fdf11731ab26bc7ff3e44026cf380e/examples/tweetburner.rb#L27-L32", "partition": "valid"} {"repo": "monde/mms2r", "path": "lib/mms2r/media.rb", "func_name": "MMS2R.MMS2R::Media.subject", "original_string": "def subject\n\n unless @subject\n subject = mail.subject.strip rescue \"\"\n ignores = config['ignore']['text/plain']\n if ignores && ignores.detect{|s| s == subject}\n @subject = \"\"\n else\n @subject = transform_text('text/plain', subject).last\n end\n end\n\n @subject\n end", "language": "ruby", "code": "def subject\n\n unless @subject\n subject = mail.subject.strip rescue \"\"\n ignores = config['ignore']['text/plain']\n if ignores && ignores.detect{|s| s == subject}\n @subject = \"\"\n else\n @subject = transform_text('text/plain', subject).last\n end\n end\n\n @subject\n end", "code_tokens": ["def", "subject", "unless", "@subject", "subject", "=", "mail", ".", "subject", ".", "strip", "rescue", "\"\"", "ignores", "=", "config", "[", "'ignore'", "]", "[", "'text/plain'", "]", "if", "ignores", "&&", "ignores", ".", "detect", "{", "|", "s", "|", "s", "==", "subject", "}", "@subject", "=", "\"\"", "else", "@subject", "=", "transform_text", "(", "'text/plain'", ",", "subject", ")", ".", "last", "end", "end", "@subject", "end"], "docstring": "Return the Subject for this message, returns \"\" for default carrier\n subject such as 'Multimedia message' for ATT&T carrier.", "docstring_tokens": ["Return", "the", "Subject", "for", "this", "message", "returns", "for", "default", "carrier", "subject", "such", "as", "Multimedia", "message", "for", "ATT&T", "carrier", "."], "sha": "4b4419580a1eccb55cc1862795d926852d4554bd", "url": "https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L246-L259", "partition": "valid"} {"repo": "monde/mms2r", "path": "lib/mms2r/media.rb", "func_name": "MMS2R.MMS2R::Media.ignore_media?", "original_string": "def ignore_media?(type, part)\n ignores = config['ignore'][type] || []\n ignore = ignores.detect{ |test| filename?(part) == test}\n ignore ||= ignores.detect{ |test| filename?(part) =~ test if test.is_a?(Regexp) }\n ignore ||= ignores.detect{ |test| part.body.decoded.strip =~ test if test.is_a?(Regexp) }\n ignore ||= (part.body.decoded.strip.size == 0 ? true : nil)\n ignore.nil? ? false : true\n end", "language": "ruby", "code": "def ignore_media?(type, part)\n ignores = config['ignore'][type] || []\n ignore = ignores.detect{ |test| filename?(part) == test}\n ignore ||= ignores.detect{ |test| filename?(part) =~ test if test.is_a?(Regexp) }\n ignore ||= ignores.detect{ |test| part.body.decoded.strip =~ test if test.is_a?(Regexp) }\n ignore ||= (part.body.decoded.strip.size == 0 ? true : nil)\n ignore.nil? ? false : true\n end", "code_tokens": ["def", "ignore_media?", "(", "type", ",", "part", ")", "ignores", "=", "config", "[", "'ignore'", "]", "[", "type", "]", "||", "[", "]", "ignore", "=", "ignores", ".", "detect", "{", "|", "test", "|", "filename?", "(", "part", ")", "==", "test", "}", "ignore", "||=", "ignores", ".", "detect", "{", "|", "test", "|", "filename?", "(", "part", ")", "=~", "test", "if", "test", ".", "is_a?", "(", "Regexp", ")", "}", "ignore", "||=", "ignores", ".", "detect", "{", "|", "test", "|", "part", ".", "body", ".", "decoded", ".", "strip", "=~", "test", "if", "test", ".", "is_a?", "(", "Regexp", ")", "}", "ignore", "||=", "(", "part", ".", "body", ".", "decoded", ".", "strip", ".", "size", "==", "0", "?", "true", ":", "nil", ")", "ignore", ".", "nil?", "?", "false", ":", "true", "end"], "docstring": "Helper for process template method to determine if media contained in a\n part should be ignored. Producers should override this method to return\n true for media such as images that are advertising, carrier logos, etc.\n See the ignore section in the discussion of the built-in configuration.", "docstring_tokens": ["Helper", "for", "process", "template", "method", "to", "determine", "if", "media", "contained", "in", "a", "part", "should", "be", "ignored", ".", "Producers", "should", "override", "this", "method", "to", "return", "true", "for", "media", "such", "as", "images", "that", "are", "advertising", "carrier", "logos", "etc", ".", "See", "the", "ignore", "section", "in", "the", "discussion", "of", "the", "built", "-", "in", "configuration", "."], "sha": "4b4419580a1eccb55cc1862795d926852d4554bd", "url": "https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L380-L387", "partition": "valid"} {"repo": "monde/mms2r", "path": "lib/mms2r/media.rb", "func_name": "MMS2R.MMS2R::Media.process_media", "original_string": "def process_media(part)\n # Mail body auto-magically decodes quoted\n # printable for text/html type.\n file = temp_file(part)\n if part.part_type? =~ /^text\\// ||\n part.part_type? == 'application/smil'\n type, content = transform_text_part(part)\n else\n if part.part_type? == 'application/octet-stream'\n type = type_from_filename(filename?(part))\n else\n type = part.part_type?\n end\n content = part.body.decoded\n end\n return type, nil if content.nil? || content.empty?\n\n log(\"#{self.class} writing file #{file}\", :info)\n File.open(file, 'wb'){ |f| f.write(content) }\n return type, file\n end", "language": "ruby", "code": "def process_media(part)\n # Mail body auto-magically decodes quoted\n # printable for text/html type.\n file = temp_file(part)\n if part.part_type? =~ /^text\\// ||\n part.part_type? == 'application/smil'\n type, content = transform_text_part(part)\n else\n if part.part_type? == 'application/octet-stream'\n type = type_from_filename(filename?(part))\n else\n type = part.part_type?\n end\n content = part.body.decoded\n end\n return type, nil if content.nil? || content.empty?\n\n log(\"#{self.class} writing file #{file}\", :info)\n File.open(file, 'wb'){ |f| f.write(content) }\n return type, file\n end", "code_tokens": ["def", "process_media", "(", "part", ")", "# Mail body auto-magically decodes quoted", "# printable for text/html type.", "file", "=", "temp_file", "(", "part", ")", "if", "part", ".", "part_type?", "=~", "/", "\\/", "/", "||", "part", ".", "part_type?", "==", "'application/smil'", "type", ",", "content", "=", "transform_text_part", "(", "part", ")", "else", "if", "part", ".", "part_type?", "==", "'application/octet-stream'", "type", "=", "type_from_filename", "(", "filename?", "(", "part", ")", ")", "else", "type", "=", "part", ".", "part_type?", "end", "content", "=", "part", ".", "body", ".", "decoded", "end", "return", "type", ",", "nil", "if", "content", ".", "nil?", "||", "content", ".", "empty?", "log", "(", "\"#{self.class} writing file #{file}\"", ",", ":info", ")", "File", ".", "open", "(", "file", ",", "'wb'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "content", ")", "}", "return", "type", ",", "file", "end"], "docstring": "Helper for process template method to decode the part based on its type\n and write its content to a temporary file. Returns path to temporary\n file that holds the content. Parts with a main type of text will have\n their contents transformed with a call to transform_text\n\n Producers should only override this method if the parts of the MMS need\n special treatment besides what is expected for a normal mime part (like\n Sprint).\n\n Returns a tuple of content type, file path", "docstring_tokens": ["Helper", "for", "process", "template", "method", "to", "decode", "the", "part", "based", "on", "its", "type", "and", "write", "its", "content", "to", "a", "temporary", "file", ".", "Returns", "path", "to", "temporary", "file", "that", "holds", "the", "content", ".", "Parts", "with", "a", "main", "type", "of", "text", "will", "have", "their", "contents", "transformed", "with", "a", "call", "to", "transform_text"], "sha": "4b4419580a1eccb55cc1862795d926852d4554bd", "url": "https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L401-L421", "partition": "valid"} {"repo": "monde/mms2r", "path": "lib/mms2r/media.rb", "func_name": "MMS2R.MMS2R::Media.process_part", "original_string": "def process_part(part)\n return if ignore_media?(part.part_type?, part)\n\n type, file = process_media(part)\n add_file(type, file) unless type.nil? || file.nil?\n end", "language": "ruby", "code": "def process_part(part)\n return if ignore_media?(part.part_type?, part)\n\n type, file = process_media(part)\n add_file(type, file) unless type.nil? || file.nil?\n end", "code_tokens": ["def", "process_part", "(", "part", ")", "return", "if", "ignore_media?", "(", "part", ".", "part_type?", ",", "part", ")", "type", ",", "file", "=", "process_media", "(", "part", ")", "add_file", "(", "type", ",", "file", ")", "unless", "type", ".", "nil?", "||", "file", ".", "nil?", "end"], "docstring": "Helper to decide if a part should be kept or ignored", "docstring_tokens": ["Helper", "to", "decide", "if", "a", "part", "should", "be", "kept", "or", "ignored"], "sha": "4b4419580a1eccb55cc1862795d926852d4554bd", "url": "https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L426-L431", "partition": "valid"} {"repo": "monde/mms2r", "path": "lib/mms2r/media.rb", "func_name": "MMS2R.MMS2R::Media.transform_text", "original_string": "def transform_text(type, text)\n return type, text if !config['transform'] || !(transforms = config['transform'][type])\n\n if RUBY_VERSION < \"1.9\"\n require 'iconv'\n ic = Iconv.new('UTF-8', 'ISO-8859-1')\n text = ic.iconv(text)\n text << ic.iconv(nil)\n ic.close\n end\n\n transforms.each do |transform|\n next unless transform.size == 2\n p = transform.first\n r = transform.last\n text = text.gsub(p, r) rescue text\n end\n\n return type, text\n end", "language": "ruby", "code": "def transform_text(type, text)\n return type, text if !config['transform'] || !(transforms = config['transform'][type])\n\n if RUBY_VERSION < \"1.9\"\n require 'iconv'\n ic = Iconv.new('UTF-8', 'ISO-8859-1')\n text = ic.iconv(text)\n text << ic.iconv(nil)\n ic.close\n end\n\n transforms.each do |transform|\n next unless transform.size == 2\n p = transform.first\n r = transform.last\n text = text.gsub(p, r) rescue text\n end\n\n return type, text\n end", "code_tokens": ["def", "transform_text", "(", "type", ",", "text", ")", "return", "type", ",", "text", "if", "!", "config", "[", "'transform'", "]", "||", "!", "(", "transforms", "=", "config", "[", "'transform'", "]", "[", "type", "]", ")", "if", "RUBY_VERSION", "<", "\"1.9\"", "require", "'iconv'", "ic", "=", "Iconv", ".", "new", "(", "'UTF-8'", ",", "'ISO-8859-1'", ")", "text", "=", "ic", ".", "iconv", "(", "text", ")", "text", "<<", "ic", ".", "iconv", "(", "nil", ")", "ic", ".", "close", "end", "transforms", ".", "each", "do", "|", "transform", "|", "next", "unless", "transform", ".", "size", "==", "2", "p", "=", "transform", ".", "first", "r", "=", "transform", ".", "last", "text", "=", "text", ".", "gsub", "(", "p", ",", "r", ")", "rescue", "text", "end", "return", "type", ",", "text", "end"], "docstring": "Helper for process_media template method to transform text.\n See the transform section in the discussion of the built-in\n configuration.", "docstring_tokens": ["Helper", "for", "process_media", "template", "method", "to", "transform", "text", ".", "See", "the", "transform", "section", "in", "the", "discussion", "of", "the", "built", "-", "in", "configuration", "."], "sha": "4b4419580a1eccb55cc1862795d926852d4554bd", "url": "https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L447-L466", "partition": "valid"} {"repo": "monde/mms2r", "path": "lib/mms2r/media.rb", "func_name": "MMS2R.MMS2R::Media.transform_text_part", "original_string": "def transform_text_part(part)\n type = part.part_type?\n text = part.body.decoded.strip\n transform_text(type, text)\n end", "language": "ruby", "code": "def transform_text_part(part)\n type = part.part_type?\n text = part.body.decoded.strip\n transform_text(type, text)\n end", "code_tokens": ["def", "transform_text_part", "(", "part", ")", "type", "=", "part", ".", "part_type?", "text", "=", "part", ".", "body", ".", "decoded", ".", "strip", "transform_text", "(", "type", ",", "text", ")", "end"], "docstring": "Helper for process_media template method to transform text.", "docstring_tokens": ["Helper", "for", "process_media", "template", "method", "to", "transform", "text", "."], "sha": "4b4419580a1eccb55cc1862795d926852d4554bd", "url": "https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L471-L475", "partition": "valid"} {"repo": "monde/mms2r", "path": "lib/mms2r/media.rb", "func_name": "MMS2R.MMS2R::Media.temp_file", "original_string": "def temp_file(part)\n file_name = filename?(part)\n File.expand_path(File.join(msg_tmp_dir(),File.basename(file_name)))\n end", "language": "ruby", "code": "def temp_file(part)\n file_name = filename?(part)\n File.expand_path(File.join(msg_tmp_dir(),File.basename(file_name)))\n end", "code_tokens": ["def", "temp_file", "(", "part", ")", "file_name", "=", "filename?", "(", "part", ")", "File", ".", "expand_path", "(", "File", ".", "join", "(", "msg_tmp_dir", "(", ")", ",", "File", ".", "basename", "(", "file_name", ")", ")", ")", "end"], "docstring": "Helper for process template method to name a temporary filepath based on\n information in the part. This version attempts to honor the name of the\n media as labeled in the part header and creates a unique temporary\n directory for writing the file so filename collision does not occur.\n Consumers of this method expect the directory structure to the file\n exists, if the method is overridden it is mandatory that this behavior is\n retained.", "docstring_tokens": ["Helper", "for", "process", "template", "method", "to", "name", "a", "temporary", "filepath", "based", "on", "information", "in", "the", "part", ".", "This", "version", "attempts", "to", "honor", "the", "name", "of", "the", "media", "as", "labeled", "in", "the", "part", "header", "and", "creates", "a", "unique", "temporary", "directory", "for", "writing", "the", "file", "so", "filename", "collision", "does", "not", "occur", ".", "Consumers", "of", "this", "method", "expect", "the", "directory", "structure", "to", "the", "file", "exists", "if", "the", "method", "is", "overridden", "it", "is", "mandatory", "that", "this", "behavior", "is", "retained", "."], "sha": "4b4419580a1eccb55cc1862795d926852d4554bd", "url": "https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L486-L489", "partition": "valid"} {"repo": "monde/mms2r", "path": "lib/mms2r/media.rb", "func_name": "MMS2R.MMS2R::Media.add_file", "original_string": "def add_file(type, file)\n media[type] = [] unless media[type]\n media[type] << file\n end", "language": "ruby", "code": "def add_file(type, file)\n media[type] = [] unless media[type]\n media[type] << file\n end", "code_tokens": ["def", "add_file", "(", "type", ",", "file", ")", "media", "[", "type", "]", "=", "[", "]", "unless", "media", "[", "type", "]", "media", "[", "type", "]", "<<", "file", "end"], "docstring": "Helper to add a file to the media hash.", "docstring_tokens": ["Helper", "to", "add", "a", "file", "to", "the", "media", "hash", "."], "sha": "4b4419580a1eccb55cc1862795d926852d4554bd", "url": "https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L503-L506", "partition": "valid"} {"repo": "monde/mms2r", "path": "lib/mms2r/media.rb", "func_name": "MMS2R.MMS2R::Media.msg_tmp_dir", "original_string": "def msg_tmp_dir\n @dir_count += 1\n dir = File.expand_path(File.join(@media_dir, \"#{@dir_count}\"))\n FileUtils.mkdir_p(dir)\n dir\n end", "language": "ruby", "code": "def msg_tmp_dir\n @dir_count += 1\n dir = File.expand_path(File.join(@media_dir, \"#{@dir_count}\"))\n FileUtils.mkdir_p(dir)\n dir\n end", "code_tokens": ["def", "msg_tmp_dir", "@dir_count", "+=", "1", "dir", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "@media_dir", ",", "\"#{@dir_count}\"", ")", ")", "FileUtils", ".", "mkdir_p", "(", "dir", ")", "dir", "end"], "docstring": "Helper to temp_file to create a unique temporary directory that is a\n child of tmp_dir This version is based on the message_id of the mail.", "docstring_tokens": ["Helper", "to", "temp_file", "to", "create", "a", "unique", "temporary", "directory", "that", "is", "a", "child", "of", "tmp_dir", "This", "version", "is", "based", "on", "the", "message_id", "of", "the", "mail", "."], "sha": "4b4419580a1eccb55cc1862795d926852d4554bd", "url": "https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L512-L517", "partition": "valid"} {"repo": "monde/mms2r", "path": "lib/mms2r/media.rb", "func_name": "MMS2R.MMS2R::Media.filename?", "original_string": "def filename?(part)\n name = part.filename\n if (name.nil? || name.empty?)\n if part.content_id && (matched = /^<(.+)>$/.match(part.content_id))\n name = matched[1]\n else\n name = \"#{Time.now.to_f}.#{self.default_ext(part.part_type?)}\"\n end\n end\n # FIXME FWIW, janky look for dot extension 1 to 4 chars long\n name = (name =~ /\\..{1,4}$/ ? name : \"#{name}.#{self.default_ext(part.part_type?)}\").strip\n\n # handle excessively large filenames\n if name.size > 255\n ext = File.extname(name)\n base = File.basename(name, ext)\n name = \"#{base[0, 255 - ext.size]}#{ext}\"\n end\n\n name\n end", "language": "ruby", "code": "def filename?(part)\n name = part.filename\n if (name.nil? || name.empty?)\n if part.content_id && (matched = /^<(.+)>$/.match(part.content_id))\n name = matched[1]\n else\n name = \"#{Time.now.to_f}.#{self.default_ext(part.part_type?)}\"\n end\n end\n # FIXME FWIW, janky look for dot extension 1 to 4 chars long\n name = (name =~ /\\..{1,4}$/ ? name : \"#{name}.#{self.default_ext(part.part_type?)}\").strip\n\n # handle excessively large filenames\n if name.size > 255\n ext = File.extname(name)\n base = File.basename(name, ext)\n name = \"#{base[0, 255 - ext.size]}#{ext}\"\n end\n\n name\n end", "code_tokens": ["def", "filename?", "(", "part", ")", "name", "=", "part", ".", "filename", "if", "(", "name", ".", "nil?", "||", "name", ".", "empty?", ")", "if", "part", ".", "content_id", "&&", "(", "matched", "=", "/", "/", ".", "match", "(", "part", ".", "content_id", ")", ")", "name", "=", "matched", "[", "1", "]", "else", "name", "=", "\"#{Time.now.to_f}.#{self.default_ext(part.part_type?)}\"", "end", "end", "# FIXME FWIW, janky look for dot extension 1 to 4 chars long", "name", "=", "(", "name", "=~", "/", "\\.", "/", "?", "name", ":", "\"#{name}.#{self.default_ext(part.part_type?)}\"", ")", ".", "strip", "# handle excessively large filenames", "if", "name", ".", "size", ">", "255", "ext", "=", "File", ".", "extname", "(", "name", ")", "base", "=", "File", ".", "basename", "(", "name", ",", "ext", ")", "name", "=", "\"#{base[0, 255 - ext.size]}#{ext}\"", "end", "name", "end"], "docstring": "returns a filename declared for a part, or a default if its not defined", "docstring_tokens": ["returns", "a", "filename", "declared", "for", "a", "part", "or", "a", "default", "if", "its", "not", "defined"], "sha": "4b4419580a1eccb55cc1862795d926852d4554bd", "url": "https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L522-L542", "partition": "valid"} {"repo": "monde/mms2r", "path": "lib/mms2r/media.rb", "func_name": "MMS2R.MMS2R::Media.type_from_filename", "original_string": "def type_from_filename(filename)\n ext = filename.split('.').last\n ent = MMS2R::EXT.detect{|k,v| v == ext}\n ent.nil? ? nil : ent.first\n end", "language": "ruby", "code": "def type_from_filename(filename)\n ext = filename.split('.').last\n ent = MMS2R::EXT.detect{|k,v| v == ext}\n ent.nil? ? nil : ent.first\n end", "code_tokens": ["def", "type_from_filename", "(", "filename", ")", "ext", "=", "filename", ".", "split", "(", "'.'", ")", ".", "last", "ent", "=", "MMS2R", "::", "EXT", ".", "detect", "{", "|", "k", ",", "v", "|", "v", "==", "ext", "}", "ent", ".", "nil?", "?", "nil", ":", "ent", ".", "first", "end"], "docstring": "guess content type from filename", "docstring_tokens": ["guess", "content", "type", "from", "filename"], "sha": "4b4419580a1eccb55cc1862795d926852d4554bd", "url": "https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L779-L783", "partition": "valid"} {"repo": "pierrickrouxel/activerecord-jdbcas400-adapter", "path": "lib/arjdbc/as400/adapter.rb", "func_name": "ArJdbc.AS400.prefetch_primary_key?", "original_string": "def prefetch_primary_key?(table_name = nil)\n return true if table_name.nil?\n table_name = table_name.to_s\n primary_keys(table_name.to_s).size == 0\n end", "language": "ruby", "code": "def prefetch_primary_key?(table_name = nil)\n return true if table_name.nil?\n table_name = table_name.to_s\n primary_keys(table_name.to_s).size == 0\n end", "code_tokens": ["def", "prefetch_primary_key?", "(", "table_name", "=", "nil", ")", "return", "true", "if", "table_name", ".", "nil?", "table_name", "=", "table_name", ".", "to_s", "primary_keys", "(", "table_name", ".", "to_s", ")", ".", "size", "==", "0", "end"], "docstring": "If true, next_sequence_value is called before each insert statement\n to set the record's primary key.\n By default DB2 for i supports IDENTITY_VAL_LOCAL for tables that have\n one primary key.", "docstring_tokens": ["If", "true", "next_sequence_value", "is", "called", "before", "each", "insert", "statement", "to", "set", "the", "record", "s", "primary", "key", ".", "By", "default", "DB2", "for", "i", "supports", "IDENTITY_VAL_LOCAL", "for", "tables", "that", "have", "one", "primary", "key", "."], "sha": "01505cc6d2da476aaf11133b3d5cfd05b6ef7d8c", "url": "https://github.com/pierrickrouxel/activerecord-jdbcas400-adapter/blob/01505cc6d2da476aaf11133b3d5cfd05b6ef7d8c/lib/arjdbc/as400/adapter.rb#L72-L76", "partition": "valid"} {"repo": "pierrickrouxel/activerecord-jdbcas400-adapter", "path": "lib/arjdbc/as400/adapter.rb", "func_name": "ArJdbc.AS400.execute_and_auto_confirm", "original_string": "def execute_and_auto_confirm(sql, name = nil)\n\n begin\n execute_system_command('CHGJOB INQMSGRPY(*SYSRPYL)')\n execute_system_command(\"ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')\")\n rescue Exception => e\n raise unauthorized_error_message(\"CHGJOB INQMSGRPY(*SYSRPYL) and ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')\", e)\n end\n\n begin\n result = execute(sql, name)\n rescue Exception\n raise\n else\n # Return if all work fine\n result\n ensure\n\n # Ensure default configuration restoration\n begin\n execute_system_command('CHGJOB INQMSGRPY(*DFT)')\n execute_system_command('RMVRPYLE SEQNBR(9876)')\n rescue Exception => e\n raise unauthorized_error_message('CHGJOB INQMSGRPY(*DFT) and RMVRPYLE SEQNBR(9876)', e)\n end\n\n end\n end", "language": "ruby", "code": "def execute_and_auto_confirm(sql, name = nil)\n\n begin\n execute_system_command('CHGJOB INQMSGRPY(*SYSRPYL)')\n execute_system_command(\"ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')\")\n rescue Exception => e\n raise unauthorized_error_message(\"CHGJOB INQMSGRPY(*SYSRPYL) and ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')\", e)\n end\n\n begin\n result = execute(sql, name)\n rescue Exception\n raise\n else\n # Return if all work fine\n result\n ensure\n\n # Ensure default configuration restoration\n begin\n execute_system_command('CHGJOB INQMSGRPY(*DFT)')\n execute_system_command('RMVRPYLE SEQNBR(9876)')\n rescue Exception => e\n raise unauthorized_error_message('CHGJOB INQMSGRPY(*DFT) and RMVRPYLE SEQNBR(9876)', e)\n end\n\n end\n end", "code_tokens": ["def", "execute_and_auto_confirm", "(", "sql", ",", "name", "=", "nil", ")", "begin", "execute_system_command", "(", "'CHGJOB INQMSGRPY(*SYSRPYL)'", ")", "execute_system_command", "(", "\"ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')\"", ")", "rescue", "Exception", "=>", "e", "raise", "unauthorized_error_message", "(", "\"CHGJOB INQMSGRPY(*SYSRPYL) and ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')\"", ",", "e", ")", "end", "begin", "result", "=", "execute", "(", "sql", ",", "name", ")", "rescue", "Exception", "raise", "else", "# Return if all work fine", "result", "ensure", "# Ensure default configuration restoration", "begin", "execute_system_command", "(", "'CHGJOB INQMSGRPY(*DFT)'", ")", "execute_system_command", "(", "'RMVRPYLE SEQNBR(9876)'", ")", "rescue", "Exception", "=>", "e", "raise", "unauthorized_error_message", "(", "'CHGJOB INQMSGRPY(*DFT) and RMVRPYLE SEQNBR(9876)'", ",", "e", ")", "end", "end", "end"], "docstring": "Holy moly batman! all this to tell AS400 \"yes i am sure\"", "docstring_tokens": ["Holy", "moly", "batman!", "all", "this", "to", "tell", "AS400", "yes", "i", "am", "sure"], "sha": "01505cc6d2da476aaf11133b3d5cfd05b6ef7d8c", "url": "https://github.com/pierrickrouxel/activerecord-jdbcas400-adapter/blob/01505cc6d2da476aaf11133b3d5cfd05b6ef7d8c/lib/arjdbc/as400/adapter.rb#L154-L181", "partition": "valid"} {"repo": "jens-na/travis-custom-deploy", "path": "lib/travis-custom-deploy/deployment.rb", "func_name": "TravisCustomDeploy.Deployment.get_transfer", "original_string": "def get_transfer(type)\n type = type[0].upcase + type[1..-1]\n try_require(type)\n Transfer.const_get(type).new(@options, @files) \n end", "language": "ruby", "code": "def get_transfer(type)\n type = type[0].upcase + type[1..-1]\n try_require(type)\n Transfer.const_get(type).new(@options, @files) \n end", "code_tokens": ["def", "get_transfer", "(", "type", ")", "type", "=", "type", "[", "0", "]", ".", "upcase", "+", "type", "[", "1", "..", "-", "1", "]", "try_require", "(", "type", ")", "Transfer", ".", "const_get", "(", "type", ")", ".", "new", "(", "@options", ",", "@files", ")", "end"], "docstring": "Creates an instance for the transfer type and return it\n\n type - the transfer type like sftp, ftp, etc.", "docstring_tokens": ["Creates", "an", "instance", "for", "the", "transfer", "type", "and", "return", "it"], "sha": "5c767322074d69edced7bc2ae22afa3b0b874a79", "url": "https://github.com/jens-na/travis-custom-deploy/blob/5c767322074d69edced7bc2ae22afa3b0b874a79/lib/travis-custom-deploy/deployment.rb#L28-L32", "partition": "valid"} {"repo": "thumblemonks/smurf", "path": "lib/smurf/javascript.rb", "func_name": "Smurf.Javascript.peek", "original_string": "def peek(aheadCount=1)\n history = []\n aheadCount.times { history << @input.getc }\n history.reverse.each { |chr| @input.ungetc(chr) }\n return history.last.chr\n end", "language": "ruby", "code": "def peek(aheadCount=1)\n history = []\n aheadCount.times { history << @input.getc }\n history.reverse.each { |chr| @input.ungetc(chr) }\n return history.last.chr\n end", "code_tokens": ["def", "peek", "(", "aheadCount", "=", "1", ")", "history", "=", "[", "]", "aheadCount", ".", "times", "{", "history", "<<", "@input", ".", "getc", "}", "history", ".", "reverse", ".", "each", "{", "|", "chr", "|", "@input", ".", "ungetc", "(", "chr", ")", "}", "return", "history", ".", "last", ".", "chr", "end"], "docstring": "Get the next character without getting it.", "docstring_tokens": ["Get", "the", "next", "character", "without", "getting", "it", "."], "sha": "09e10d7934786a3c9baf118d503f65b62ba13ae0", "url": "https://github.com/thumblemonks/smurf/blob/09e10d7934786a3c9baf118d503f65b62ba13ae0/lib/smurf/javascript.rb#L80-L85", "partition": "valid"} {"repo": "dblandin/motion-capture", "path": "lib/project/motion-capture.rb", "func_name": "Motion.Capture.captureOutput", "original_string": "def captureOutput(output, didFinishProcessingPhoto: photo, error: error)\n if error\n error_callback.call(error)\n else\n @capture_callback.call(photo.fileDataRepresentation)\n end\n end", "language": "ruby", "code": "def captureOutput(output, didFinishProcessingPhoto: photo, error: error)\n if error\n error_callback.call(error)\n else\n @capture_callback.call(photo.fileDataRepresentation)\n end\n end", "code_tokens": ["def", "captureOutput", "(", "output", ",", "didFinishProcessingPhoto", ":", "photo", ",", "error", ":", "error", ")", "if", "error", "error_callback", ".", "call", "(", "error", ")", "else", "@capture_callback", ".", "call", "(", "photo", ".", "fileDataRepresentation", ")", "end", "end"], "docstring": "iOS 11+ AVCapturePhotoCaptureDelegate method", "docstring_tokens": ["iOS", "11", "+", "AVCapturePhotoCaptureDelegate", "method"], "sha": "5e7bfd5636f75493f322d6e9e416253c940d0d14", "url": "https://github.com/dblandin/motion-capture/blob/5e7bfd5636f75493f322d6e9e416253c940d0d14/lib/project/motion-capture.rb#L107-L113", "partition": "valid"} {"repo": "dblandin/motion-capture", "path": "lib/project/motion-capture.rb", "func_name": "Motion.Capture.captureOutput", "original_string": "def captureOutput(output, didFinishProcessingPhotoSampleBuffer: photo_sample_buffer, previewPhotoSampleBuffer: preview_photo_sample_buffer, resolvedSettings: resolved_settings, bracketSettings: bracket_settings, error: error)\n if error\n error_callback.call(error)\n else\n jpeg_data = AVCapturePhotoOutput.jpegPhotoDataRepresentation(\n forJPEGSampleBuffer: photo_sample_buffer,\n previewPhotoSampleBuffer: preview_photo_sample_buffer\n )\n @capture_callback.call(jpeg_data)\n end\n end", "language": "ruby", "code": "def captureOutput(output, didFinishProcessingPhotoSampleBuffer: photo_sample_buffer, previewPhotoSampleBuffer: preview_photo_sample_buffer, resolvedSettings: resolved_settings, bracketSettings: bracket_settings, error: error)\n if error\n error_callback.call(error)\n else\n jpeg_data = AVCapturePhotoOutput.jpegPhotoDataRepresentation(\n forJPEGSampleBuffer: photo_sample_buffer,\n previewPhotoSampleBuffer: preview_photo_sample_buffer\n )\n @capture_callback.call(jpeg_data)\n end\n end", "code_tokens": ["def", "captureOutput", "(", "output", ",", "didFinishProcessingPhotoSampleBuffer", ":", "photo_sample_buffer", ",", "previewPhotoSampleBuffer", ":", "preview_photo_sample_buffer", ",", "resolvedSettings", ":", "resolved_settings", ",", "bracketSettings", ":", "bracket_settings", ",", "error", ":", "error", ")", "if", "error", "error_callback", ".", "call", "(", "error", ")", "else", "jpeg_data", "=", "AVCapturePhotoOutput", ".", "jpegPhotoDataRepresentation", "(", "forJPEGSampleBuffer", ":", "photo_sample_buffer", ",", "previewPhotoSampleBuffer", ":", "preview_photo_sample_buffer", ")", "@capture_callback", ".", "call", "(", "jpeg_data", ")", "end", "end"], "docstring": "iOS 10 AVCapturePhotoCaptureDelegate method", "docstring_tokens": ["iOS", "10", "AVCapturePhotoCaptureDelegate", "method"], "sha": "5e7bfd5636f75493f322d6e9e416253c940d0d14", "url": "https://github.com/dblandin/motion-capture/blob/5e7bfd5636f75493f322d6e9e416253c940d0d14/lib/project/motion-capture.rb#L116-L126", "partition": "valid"} {"repo": "dblandin/motion-capture", "path": "lib/project/motion-capture.rb", "func_name": "Motion.Capture.save_to_assets_library", "original_string": "def save_to_assets_library(jpeg_data, &block)\n assets_library.writeImageDataToSavedPhotosAlbum(jpeg_data, metadata: nil, completionBlock: -> (asset_url, error) {\n error ? error_callback.call(error) : block.call(asset_url)\n })\n end", "language": "ruby", "code": "def save_to_assets_library(jpeg_data, &block)\n assets_library.writeImageDataToSavedPhotosAlbum(jpeg_data, metadata: nil, completionBlock: -> (asset_url, error) {\n error ? error_callback.call(error) : block.call(asset_url)\n })\n end", "code_tokens": ["def", "save_to_assets_library", "(", "jpeg_data", ",", "&", "block", ")", "assets_library", ".", "writeImageDataToSavedPhotosAlbum", "(", "jpeg_data", ",", "metadata", ":", "nil", ",", "completionBlock", ":", "->", "(", "asset_url", ",", "error", ")", "{", "error", "?", "error_callback", ".", "call", "(", "error", ")", ":", "block", ".", "call", "(", "asset_url", ")", "}", ")", "end"], "docstring": "iOS 4-8", "docstring_tokens": ["iOS", "4", "-", "8"], "sha": "5e7bfd5636f75493f322d6e9e416253c940d0d14", "url": "https://github.com/dblandin/motion-capture/blob/5e7bfd5636f75493f322d6e9e416253c940d0d14/lib/project/motion-capture.rb#L161-L165", "partition": "valid"} {"repo": "dblandin/motion-capture", "path": "lib/project/motion-capture.rb", "func_name": "Motion.Capture.save_to_photo_library", "original_string": "def save_to_photo_library(jpeg_data, &block)\n photo_library.performChanges(-> {\n image = UIImage.imageWithData(jpeg_data)\n PHAssetChangeRequest.creationRequestForAssetFromImage(image)\n }, completionHandler: -> (success, error) {\n if error\n error_callback.call(error)\n else\n block.call(nil) # asset url is not returned in completion block\n end\n })\n end", "language": "ruby", "code": "def save_to_photo_library(jpeg_data, &block)\n photo_library.performChanges(-> {\n image = UIImage.imageWithData(jpeg_data)\n PHAssetChangeRequest.creationRequestForAssetFromImage(image)\n }, completionHandler: -> (success, error) {\n if error\n error_callback.call(error)\n else\n block.call(nil) # asset url is not returned in completion block\n end\n })\n end", "code_tokens": ["def", "save_to_photo_library", "(", "jpeg_data", ",", "&", "block", ")", "photo_library", ".", "performChanges", "(", "->", "{", "image", "=", "UIImage", ".", "imageWithData", "(", "jpeg_data", ")", "PHAssetChangeRequest", ".", "creationRequestForAssetFromImage", "(", "image", ")", "}", ",", "completionHandler", ":", "->", "(", "success", ",", "error", ")", "{", "if", "error", "error_callback", ".", "call", "(", "error", ")", "else", "block", ".", "call", "(", "nil", ")", "# asset url is not returned in completion block", "end", "}", ")", "end"], "docstring": "iOS 8+", "docstring_tokens": ["iOS", "8", "+"], "sha": "5e7bfd5636f75493f322d6e9e416253c940d0d14", "url": "https://github.com/dblandin/motion-capture/blob/5e7bfd5636f75493f322d6e9e416253c940d0d14/lib/project/motion-capture.rb#L168-L179", "partition": "valid"} {"repo": "dblandin/motion-capture", "path": "lib/project/motion-capture.rb", "func_name": "Motion.Capture.update_video_orientation!", "original_string": "def update_video_orientation!\n photo_output.connectionWithMediaType(AVMediaTypeVideo).tap do |connection|\n device_orientation = UIDevice.currentDevice.orientation\n video_orientation = orientation_mapping.fetch(device_orientation, AVCaptureVideoOrientationPortrait)\n\n connection.setVideoOrientation(video_orientation) if connection.videoOrientationSupported?\n end\n end", "language": "ruby", "code": "def update_video_orientation!\n photo_output.connectionWithMediaType(AVMediaTypeVideo).tap do |connection|\n device_orientation = UIDevice.currentDevice.orientation\n video_orientation = orientation_mapping.fetch(device_orientation, AVCaptureVideoOrientationPortrait)\n\n connection.setVideoOrientation(video_orientation) if connection.videoOrientationSupported?\n end\n end", "code_tokens": ["def", "update_video_orientation!", "photo_output", ".", "connectionWithMediaType", "(", "AVMediaTypeVideo", ")", ".", "tap", "do", "|", "connection", "|", "device_orientation", "=", "UIDevice", ".", "currentDevice", ".", "orientation", "video_orientation", "=", "orientation_mapping", ".", "fetch", "(", "device_orientation", ",", "AVCaptureVideoOrientationPortrait", ")", "connection", ".", "setVideoOrientation", "(", "video_orientation", ")", "if", "connection", ".", "videoOrientationSupported?", "end", "end"], "docstring": "iOS 10+", "docstring_tokens": ["iOS", "10", "+"], "sha": "5e7bfd5636f75493f322d6e9e416253c940d0d14", "url": "https://github.com/dblandin/motion-capture/blob/5e7bfd5636f75493f322d6e9e416253c940d0d14/lib/project/motion-capture.rb#L255-L262", "partition": "valid"} {"repo": "Hamdiakoguz/onedclusterer", "path": "lib/onedclusterer/ckmeans.rb", "func_name": "OnedClusterer.Ckmeans.select_levels", "original_string": "def select_levels(data, backtrack, kmin, kmax)\r\n return kmin if kmin == kmax\r\n\r\n method = :normal # \"uniform\" or \"normal\"\r\n\r\n kopt = kmin\r\n\r\n base = 1 # The position of first element in x: 1 or 0.\r\n n = data.size - base\r\n\r\n max_bic = 0.0\r\n\r\n for k in kmin..kmax\r\n cluster_sizes = []\r\n kbacktrack = backtrack[0..k]\r\n backtrack(kbacktrack) do |cluster, left, right|\r\n cluster_sizes[cluster] = right - left + 1\r\n end\r\n\r\n index_left = base\r\n index_right = 0\r\n\r\n likelihood = 0\r\n bin_left, bin_right = 0\r\n for i in 0..(k-1)\r\n points_in_bin = cluster_sizes[i + base]\r\n index_right = index_left + points_in_bin - 1\r\n\r\n if data[index_left] < data[index_right]\r\n bin_left = data[index_left]\r\n bin_right = data[index_right]\r\n elsif data[index_left] == data[index_right]\r\n bin_left = index_left == base ? data[base] : (data[index_left-1] + data[index_left]) / 2\r\n bin_right = index_right < n-1+base ? (data[index_right] + data[index_right+1]) / 2 : data[n-1+base]\r\n else\r\n raise \"ERROR: binLeft > binRight\"\r\n end\r\n\r\n bin_width = bin_right - bin_left\r\n if method == :uniform\r\n likelihood += points_in_bin * Math.log(points_in_bin / bin_width / n)\r\n else\r\n mean = 0.0\r\n variance = 0.0\r\n\r\n for j in index_left..index_right\r\n mean += data[j]\r\n variance += data[j] ** 2\r\n end\r\n mean /= points_in_bin\r\n variance = (variance - points_in_bin * mean ** 2) / (points_in_bin - 1) if points_in_bin > 1\r\n\r\n if variance > 0\r\n for j in index_left..index_right\r\n likelihood += - (data[j] - mean) ** 2 / (2.0 * variance)\r\n end\r\n likelihood += points_in_bin * (Math.log(points_in_bin / Float(n))\r\n - 0.5 * Math.log( 2 * Math::PI * variance))\r\n else\r\n likelihood += points_in_bin * Math.log(1.0 / bin_width / n)\r\n end\r\n end\r\n\r\n index_left = index_right + 1\r\n end\r\n\r\n # Compute the Bayesian information criterion\r\n bic = 2 * likelihood - (3 * k - 1) * Math.log(Float(n))\r\n\r\n if k == kmin\r\n max_bic = bic\r\n kopt = kmin\r\n elsif bic > max_bic\r\n max_bic = bic\r\n kopt = k\r\n end\r\n\r\n end\r\n\r\n kopt\r\n end", "language": "ruby", "code": "def select_levels(data, backtrack, kmin, kmax)\r\n return kmin if kmin == kmax\r\n\r\n method = :normal # \"uniform\" or \"normal\"\r\n\r\n kopt = kmin\r\n\r\n base = 1 # The position of first element in x: 1 or 0.\r\n n = data.size - base\r\n\r\n max_bic = 0.0\r\n\r\n for k in kmin..kmax\r\n cluster_sizes = []\r\n kbacktrack = backtrack[0..k]\r\n backtrack(kbacktrack) do |cluster, left, right|\r\n cluster_sizes[cluster] = right - left + 1\r\n end\r\n\r\n index_left = base\r\n index_right = 0\r\n\r\n likelihood = 0\r\n bin_left, bin_right = 0\r\n for i in 0..(k-1)\r\n points_in_bin = cluster_sizes[i + base]\r\n index_right = index_left + points_in_bin - 1\r\n\r\n if data[index_left] < data[index_right]\r\n bin_left = data[index_left]\r\n bin_right = data[index_right]\r\n elsif data[index_left] == data[index_right]\r\n bin_left = index_left == base ? data[base] : (data[index_left-1] + data[index_left]) / 2\r\n bin_right = index_right < n-1+base ? (data[index_right] + data[index_right+1]) / 2 : data[n-1+base]\r\n else\r\n raise \"ERROR: binLeft > binRight\"\r\n end\r\n\r\n bin_width = bin_right - bin_left\r\n if method == :uniform\r\n likelihood += points_in_bin * Math.log(points_in_bin / bin_width / n)\r\n else\r\n mean = 0.0\r\n variance = 0.0\r\n\r\n for j in index_left..index_right\r\n mean += data[j]\r\n variance += data[j] ** 2\r\n end\r\n mean /= points_in_bin\r\n variance = (variance - points_in_bin * mean ** 2) / (points_in_bin - 1) if points_in_bin > 1\r\n\r\n if variance > 0\r\n for j in index_left..index_right\r\n likelihood += - (data[j] - mean) ** 2 / (2.0 * variance)\r\n end\r\n likelihood += points_in_bin * (Math.log(points_in_bin / Float(n))\r\n - 0.5 * Math.log( 2 * Math::PI * variance))\r\n else\r\n likelihood += points_in_bin * Math.log(1.0 / bin_width / n)\r\n end\r\n end\r\n\r\n index_left = index_right + 1\r\n end\r\n\r\n # Compute the Bayesian information criterion\r\n bic = 2 * likelihood - (3 * k - 1) * Math.log(Float(n))\r\n\r\n if k == kmin\r\n max_bic = bic\r\n kopt = kmin\r\n elsif bic > max_bic\r\n max_bic = bic\r\n kopt = k\r\n end\r\n\r\n end\r\n\r\n kopt\r\n end", "code_tokens": ["def", "select_levels", "(", "data", ",", "backtrack", ",", "kmin", ",", "kmax", ")", "return", "kmin", "if", "kmin", "==", "kmax", "method", "=", ":normal", "# \"uniform\" or \"normal\"\r", "kopt", "=", "kmin", "base", "=", "1", "# The position of first element in x: 1 or 0.\r", "n", "=", "data", ".", "size", "-", "base", "max_bic", "=", "0.0", "for", "k", "in", "kmin", "..", "kmax", "cluster_sizes", "=", "[", "]", "kbacktrack", "=", "backtrack", "[", "0", "..", "k", "]", "backtrack", "(", "kbacktrack", ")", "do", "|", "cluster", ",", "left", ",", "right", "|", "cluster_sizes", "[", "cluster", "]", "=", "right", "-", "left", "+", "1", "end", "index_left", "=", "base", "index_right", "=", "0", "likelihood", "=", "0", "bin_left", ",", "bin_right", "=", "0", "for", "i", "in", "0", "..", "(", "k", "-", "1", ")", "points_in_bin", "=", "cluster_sizes", "[", "i", "+", "base", "]", "index_right", "=", "index_left", "+", "points_in_bin", "-", "1", "if", "data", "[", "index_left", "]", "<", "data", "[", "index_right", "]", "bin_left", "=", "data", "[", "index_left", "]", "bin_right", "=", "data", "[", "index_right", "]", "elsif", "data", "[", "index_left", "]", "==", "data", "[", "index_right", "]", "bin_left", "=", "index_left", "==", "base", "?", "data", "[", "base", "]", ":", "(", "data", "[", "index_left", "-", "1", "]", "+", "data", "[", "index_left", "]", ")", "/", "2", "bin_right", "=", "index_right", "<", "n", "-", "1", "+", "base", "?", "(", "data", "[", "index_right", "]", "+", "data", "[", "index_right", "+", "1", "]", ")", "/", "2", ":", "data", "[", "n", "-", "1", "+", "base", "]", "else", "raise", "\"ERROR: binLeft > binRight\"", "end", "bin_width", "=", "bin_right", "-", "bin_left", "if", "method", "==", ":uniform", "likelihood", "+=", "points_in_bin", "*", "Math", ".", "log", "(", "points_in_bin", "/", "bin_width", "/", "n", ")", "else", "mean", "=", "0.0", "variance", "=", "0.0", "for", "j", "in", "index_left", "..", "index_right", "mean", "+=", "data", "[", "j", "]", "variance", "+=", "data", "[", "j", "]", "**", "2", "end", "mean", "/=", "points_in_bin", "variance", "=", "(", "variance", "-", "points_in_bin", "*", "mean", "**", "2", ")", "/", "(", "points_in_bin", "-", "1", ")", "if", "points_in_bin", ">", "1", "if", "variance", ">", "0", "for", "j", "in", "index_left", "..", "index_right", "likelihood", "+=", "-", "(", "data", "[", "j", "]", "-", "mean", ")", "**", "2", "/", "(", "2.0", "*", "variance", ")", "end", "likelihood", "+=", "points_in_bin", "*", "(", "Math", ".", "log", "(", "points_in_bin", "/", "Float", "(", "n", ")", ")", "-", "0.5", "*", "Math", ".", "log", "(", "2", "*", "Math", "::", "PI", "*", "variance", ")", ")", "else", "likelihood", "+=", "points_in_bin", "*", "Math", ".", "log", "(", "1.0", "/", "bin_width", "/", "n", ")", "end", "end", "index_left", "=", "index_right", "+", "1", "end", "# Compute the Bayesian information criterion\r", "bic", "=", "2", "*", "likelihood", "-", "(", "3", "*", "k", "-", "1", ")", "*", "Math", ".", "log", "(", "Float", "(", "n", ")", ")", "if", "k", "==", "kmin", "max_bic", "=", "bic", "kopt", "=", "kmin", "elsif", "bic", ">", "max_bic", "max_bic", "=", "bic", "kopt", "=", "k", "end", "end", "kopt", "end"], "docstring": "Choose an optimal number of levels between Kmin and Kmax", "docstring_tokens": ["Choose", "an", "optimal", "number", "of", "levels", "between", "Kmin", "and", "Kmax"], "sha": "5d134970cb7e2bc0d29ae108d952c081707e02b6", "url": "https://github.com/Hamdiakoguz/onedclusterer/blob/5d134970cb7e2bc0d29ae108d952c081707e02b6/lib/onedclusterer/ckmeans.rb#L147-L227", "partition": "valid"} {"repo": "raykin/source-route", "path": "lib/source_route/config.rb", "func_name": "SourceRoute.ParamsConfigParser.full_feature", "original_string": "def full_feature(value=true)\n return unless value\n @config.formulize\n @config.event = (@config.event + [:call, :return]).uniq\n @config.import_return_to_call = true\n @config.show_additional_attrs = [:path, :lineno]\n # JSON serialize trigger many problems when handle complicated object(in rails?)\n # a Back Door to open more data. but be care it could trigger weird crash when Jsonify these vars\n if value == 10\n @config.include_instance_var = true\n @config.include_local_var = true\n end\n end", "language": "ruby", "code": "def full_feature(value=true)\n return unless value\n @config.formulize\n @config.event = (@config.event + [:call, :return]).uniq\n @config.import_return_to_call = true\n @config.show_additional_attrs = [:path, :lineno]\n # JSON serialize trigger many problems when handle complicated object(in rails?)\n # a Back Door to open more data. but be care it could trigger weird crash when Jsonify these vars\n if value == 10\n @config.include_instance_var = true\n @config.include_local_var = true\n end\n end", "code_tokens": ["def", "full_feature", "(", "value", "=", "true", ")", "return", "unless", "value", "@config", ".", "formulize", "@config", ".", "event", "=", "(", "@config", ".", "event", "+", "[", ":call", ",", ":return", "]", ")", ".", "uniq", "@config", ".", "import_return_to_call", "=", "true", "@config", ".", "show_additional_attrs", "=", "[", ":path", ",", ":lineno", "]", "# JSON serialize trigger many problems when handle complicated object(in rails?)", "# a Back Door to open more data. but be care it could trigger weird crash when Jsonify these vars", "if", "value", "==", "10", "@config", ".", "include_instance_var", "=", "true", "@config", ".", "include_local_var", "=", "true", "end", "end"], "docstring": "todo. value equal 10 may not be a good params", "docstring_tokens": ["todo", ".", "value", "equal", "10", "may", "not", "be", "a", "good", "params"], "sha": "c45feacd080511ca85691a2e2176bd0125e9ca09", "url": "https://github.com/raykin/source-route/blob/c45feacd080511ca85691a2e2176bd0125e9ca09/lib/source_route/config.rb#L119-L131", "partition": "valid"} {"repo": "hassox/pancake", "path": "lib/pancake/middleware.rb", "func_name": "Pancake.Middleware.stack", "original_string": "def stack(name = nil, opts = {})\n if self::StackMiddleware._mwares[name] && mw = self::StackMiddleware._mwares[name]\n unless mw.stack == self\n mw = self::StackMiddleware._mwares[name] = self::StackMiddleware._mwares[name].dup\n end\n mw\n else\n self::StackMiddleware.new(name, self, opts)\n end\n end", "language": "ruby", "code": "def stack(name = nil, opts = {})\n if self::StackMiddleware._mwares[name] && mw = self::StackMiddleware._mwares[name]\n unless mw.stack == self\n mw = self::StackMiddleware._mwares[name] = self::StackMiddleware._mwares[name].dup\n end\n mw\n else\n self::StackMiddleware.new(name, self, opts)\n end\n end", "code_tokens": ["def", "stack", "(", "name", "=", "nil", ",", "opts", "=", "{", "}", ")", "if", "self", "::", "StackMiddleware", ".", "_mwares", "[", "name", "]", "&&", "mw", "=", "self", "::", "StackMiddleware", ".", "_mwares", "[", "name", "]", "unless", "mw", ".", "stack", "==", "self", "mw", "=", "self", "::", "StackMiddleware", ".", "_mwares", "[", "name", "]", "=", "self", "::", "StackMiddleware", ".", "_mwares", "[", "name", "]", ".", "dup", "end", "mw", "else", "self", "::", "StackMiddleware", ".", "new", "(", "name", ",", "self", ",", "opts", ")", "end", "end"], "docstring": "Useful for adding additional information into your middleware stack definition\n\n @param [Object] name\n The name of a given middleware. Each piece of middleware has a name in the stack.\n By naming middleware we can refer to it later, swap it out for a different class or even just remove it from the stack.\n @param [Hash] opts An options hash\n @option opts [Object] :before\n Sets this middlware to be run after the middleware named. Name is either the name given to the\n middleware stack, or the Middleware class itself.\n @option opts [Object] :after\n Sets this middleware to be run after the middleware name. Name is either the name given to the\n middleware stack or the Middleware class itself.\n\n @example Declaring un-named middleware via the stack\n MyClass.stack.use(MyMiddleware)\n\n This middleware will be named MyMiddleware, and can be specified with (:before | :after) => MyMiddleware\n\n @example Declaring a named middleware via the stack\n MyClass.stack(:foo).use(MyMiddleware)\n\n This middleware will be named :foo and can be specified with (:before | :after) => :foo\n\n @example Declaring a named middleware with a :before key\n MyClass.stack(:foo, :before => :bar).use(MyMiddleware)\n\n This middleware will be named :foo and will be run before the middleware named :bar\n If :bar is not run, :foo will not be run either\n\n @example Declaring a named middlware with an :after key\n MyClass.stack(:foo, :after => :bar).use(MyMiddleware)\n\n This middleware will be named :foo and will be run after the middleware named :bar\n If :bar is not run, :foo will not be run either\n\n @see Pancake::Middleware#use\n @api public\n @since 0.1.0\n @author Daniel Neighman", "docstring_tokens": ["Useful", "for", "adding", "additional", "information", "into", "your", "middleware", "stack", "definition"], "sha": "774b1e878cf8d4f8e7160173ed9a236a290989e6", "url": "https://github.com/hassox/pancake/blob/774b1e878cf8d4f8e7160173ed9a236a290989e6/lib/pancake/middleware.rb#L100-L109", "partition": "valid"} {"repo": "hassox/pancake", "path": "lib/pancake/middleware.rb", "func_name": "Pancake.Middleware.use", "original_string": "def use(middleware, *_args, &block)\n stack(middleware).use(middleware, *_args, &block)\n end", "language": "ruby", "code": "def use(middleware, *_args, &block)\n stack(middleware).use(middleware, *_args, &block)\n end", "code_tokens": ["def", "use", "(", "middleware", ",", "*", "_args", ",", "&", "block", ")", "stack", "(", "middleware", ")", ".", "use", "(", "middleware", ",", "_args", ",", "block", ")", "end"], "docstring": "Adds middleware to the current stack definition\n\n @param [Class] middleware The middleware class to use in the stack\n @param [Hash] opts An options hash that is passed through to the middleware when it is instantiated\n\n @yield The block is provided to the middlewares #new method when it is initialized\n\n @example Bare use call\n MyApp.use(MyMiddleware, :some => :option){ # middleware initialization block here }\n\n @example Use call after a stack call\n MyApp.stack(:foo).use(MyMiddleware, :some => :option){ # middleware initialization block here }\n\n @see Pancake::Middleware#stack\n @api public\n @since 0.1.0\n @author Daniel Neighman", "docstring_tokens": ["Adds", "middleware", "to", "the", "current", "stack", "definition"], "sha": "774b1e878cf8d4f8e7160173ed9a236a290989e6", "url": "https://github.com/hassox/pancake/blob/774b1e878cf8d4f8e7160173ed9a236a290989e6/lib/pancake/middleware.rb#L128-L130", "partition": "valid"} {"repo": "OregonDigital/metadata-ingest-form", "path": "lib/metadata/ingest/translators/form_to_attributes.rb", "func_name": "Metadata::Ingest::Translators.FormToAttributes.attribute_lookup", "original_string": "def attribute_lookup(assoc)\n group_data = @map[assoc.group.to_sym]\n return nil unless group_data\n\n attribute = group_data[assoc.type.to_sym]\n return attribute\n end", "language": "ruby", "code": "def attribute_lookup(assoc)\n group_data = @map[assoc.group.to_sym]\n return nil unless group_data\n\n attribute = group_data[assoc.type.to_sym]\n return attribute\n end", "code_tokens": ["def", "attribute_lookup", "(", "assoc", ")", "group_data", "=", "@map", "[", "assoc", ".", "group", ".", "to_sym", "]", "return", "nil", "unless", "group_data", "attribute", "=", "group_data", "[", "assoc", ".", "type", ".", "to_sym", "]", "return", "attribute", "end"], "docstring": "Extracts the attribute definition for a given association", "docstring_tokens": ["Extracts", "the", "attribute", "definition", "for", "a", "given", "association"], "sha": "1d36b5a1380fe009cda797555883b1d258463682", "url": "https://github.com/OregonDigital/metadata-ingest-form/blob/1d36b5a1380fe009cda797555883b1d258463682/lib/metadata/ingest/translators/form_to_attributes.rb#L60-L66", "partition": "valid"} {"repo": "OregonDigital/metadata-ingest-form", "path": "lib/metadata/ingest/translators/form_to_attributes.rb", "func_name": "Metadata::Ingest::Translators.FormToAttributes.translate_association", "original_string": "def translate_association(assoc)\n attribute = attribute_lookup(assoc)\n return unless attribute\n\n # Make sure we properly handle destroyed values by forcing them to an\n # empty association. We keep their state up to this point because the\n # caller may be using the prior value for something.\n if assoc.marked_for_destruction?\n assoc = @form.create_association\n end\n\n add_association_to_attribute_map(attribute, assoc)\n end", "language": "ruby", "code": "def translate_association(assoc)\n attribute = attribute_lookup(assoc)\n return unless attribute\n\n # Make sure we properly handle destroyed values by forcing them to an\n # empty association. We keep their state up to this point because the\n # caller may be using the prior value for something.\n if assoc.marked_for_destruction?\n assoc = @form.create_association\n end\n\n add_association_to_attribute_map(attribute, assoc)\n end", "code_tokens": ["def", "translate_association", "(", "assoc", ")", "attribute", "=", "attribute_lookup", "(", "assoc", ")", "return", "unless", "attribute", "# Make sure we properly handle destroyed values by forcing them to an", "# empty association. We keep their state up to this point because the", "# caller may be using the prior value for something.", "if", "assoc", ".", "marked_for_destruction?", "assoc", "=", "@form", ".", "create_association", "end", "add_association_to_attribute_map", "(", "attribute", ",", "assoc", ")", "end"], "docstring": "Maps an association to the attribute its data will be tied", "docstring_tokens": ["Maps", "an", "association", "to", "the", "attribute", "its", "data", "will", "be", "tied"], "sha": "1d36b5a1380fe009cda797555883b1d258463682", "url": "https://github.com/OregonDigital/metadata-ingest-form/blob/1d36b5a1380fe009cda797555883b1d258463682/lib/metadata/ingest/translators/form_to_attributes.rb#L69-L81", "partition": "valid"} {"repo": "OregonDigital/metadata-ingest-form", "path": "lib/metadata/ingest/translators/form_to_attributes.rb", "func_name": "Metadata::Ingest::Translators.FormToAttributes.add_association_to_attribute_map", "original_string": "def add_association_to_attribute_map(attribute, assoc)\n current = @attributes[attribute]\n\n # If there's already a value, we can safely ignore the empty association\n return if current && assoc.blank?\n\n case current\n when nil then @attributes[attribute] = [assoc]\n when Array then @attributes[attribute].push(assoc)\n end\n end", "language": "ruby", "code": "def add_association_to_attribute_map(attribute, assoc)\n current = @attributes[attribute]\n\n # If there's already a value, we can safely ignore the empty association\n return if current && assoc.blank?\n\n case current\n when nil then @attributes[attribute] = [assoc]\n when Array then @attributes[attribute].push(assoc)\n end\n end", "code_tokens": ["def", "add_association_to_attribute_map", "(", "attribute", ",", "assoc", ")", "current", "=", "@attributes", "[", "attribute", "]", "# If there's already a value, we can safely ignore the empty association", "return", "if", "current", "&&", "assoc", ".", "blank?", "case", "current", "when", "nil", "then", "@attributes", "[", "attribute", "]", "=", "[", "assoc", "]", "when", "Array", "then", "@attributes", "[", "attribute", "]", ".", "push", "(", "assoc", ")", "end", "end"], "docstring": "Adds the given association to an array of associations for the given\n attribute", "docstring_tokens": ["Adds", "the", "given", "association", "to", "an", "array", "of", "associations", "for", "the", "given", "attribute"], "sha": "1d36b5a1380fe009cda797555883b1d258463682", "url": "https://github.com/OregonDigital/metadata-ingest-form/blob/1d36b5a1380fe009cda797555883b1d258463682/lib/metadata/ingest/translators/form_to_attributes.rb#L85-L95", "partition": "valid"} {"repo": "OregonDigital/metadata-ingest-form", "path": "lib/metadata/ingest/translators/form_to_attributes.rb", "func_name": "Metadata::Ingest::Translators.FormToAttributes.store_associations_on_object", "original_string": "def store_associations_on_object(object, attribute, associations)\n values = associations.collect do |assoc|\n assoc.internal.blank? ? assoc.value : assoc.internal\n end\n\n # Clean up values\n values.compact!\n case values.length\n when 0 then values = nil\n when 1 then values = values.first\n end\n\n object.send(\"#{attribute}=\", values)\n end", "language": "ruby", "code": "def store_associations_on_object(object, attribute, associations)\n values = associations.collect do |assoc|\n assoc.internal.blank? ? assoc.value : assoc.internal\n end\n\n # Clean up values\n values.compact!\n case values.length\n when 0 then values = nil\n when 1 then values = values.first\n end\n\n object.send(\"#{attribute}=\", values)\n end", "code_tokens": ["def", "store_associations_on_object", "(", "object", ",", "attribute", ",", "associations", ")", "values", "=", "associations", ".", "collect", "do", "|", "assoc", "|", "assoc", ".", "internal", ".", "blank?", "?", "assoc", ".", "value", ":", "assoc", ".", "internal", "end", "# Clean up values", "values", ".", "compact!", "case", "values", ".", "length", "when", "0", "then", "values", "=", "nil", "when", "1", "then", "values", "=", "values", ".", "first", "end", "object", ".", "send", "(", "\"#{attribute}=\"", ",", "values", ")", "end"], "docstring": "Stores all association data on the object at the given attribute.\n Associations with internal data use that instead of value. If only one\n association is present, it is extracted from the array and stored as-is.", "docstring_tokens": ["Stores", "all", "association", "data", "on", "the", "object", "at", "the", "given", "attribute", ".", "Associations", "with", "internal", "data", "use", "that", "instead", "of", "value", ".", "If", "only", "one", "association", "is", "present", "it", "is", "extracted", "from", "the", "array", "and", "stored", "as", "-", "is", "."], "sha": "1d36b5a1380fe009cda797555883b1d258463682", "url": "https://github.com/OregonDigital/metadata-ingest-form/blob/1d36b5a1380fe009cda797555883b1d258463682/lib/metadata/ingest/translators/form_to_attributes.rb#L100-L113", "partition": "valid"} {"repo": "OregonDigital/metadata-ingest-form", "path": "lib/metadata/ingest/translators/attributes_to_form.rb", "func_name": "Metadata::Ingest::Translators.AttributesToForm.setup_form", "original_string": "def setup_form(group, type, attr_definition)\n attr_trans = single_attribute_translator.new(\n source: @source,\n form: @form,\n group: group,\n type: type,\n attribute_definition: attr_definition\n )\n\n attr_trans.add_associations_to_form\n end", "language": "ruby", "code": "def setup_form(group, type, attr_definition)\n attr_trans = single_attribute_translator.new(\n source: @source,\n form: @form,\n group: group,\n type: type,\n attribute_definition: attr_definition\n )\n\n attr_trans.add_associations_to_form\n end", "code_tokens": ["def", "setup_form", "(", "group", ",", "type", ",", "attr_definition", ")", "attr_trans", "=", "single_attribute_translator", ".", "new", "(", "source", ":", "@source", ",", "form", ":", "@form", ",", "group", ":", "group", ",", "type", ":", "type", ",", "attribute_definition", ":", "attr_definition", ")", "attr_trans", ".", "add_associations_to_form", "end"], "docstring": "Sets up translation state instance to hold various attributes that need to be passed around,\n and calls helpers to build the necessary associations and attach them to the form.", "docstring_tokens": ["Sets", "up", "translation", "state", "instance", "to", "hold", "various", "attributes", "that", "need", "to", "be", "passed", "around", "and", "calls", "helpers", "to", "build", "the", "necessary", "associations", "and", "attach", "them", "to", "the", "form", "."], "sha": "1d36b5a1380fe009cda797555883b1d258463682", "url": "https://github.com/OregonDigital/metadata-ingest-form/blob/1d36b5a1380fe009cda797555883b1d258463682/lib/metadata/ingest/translators/attributes_to_form.rb#L67-L77", "partition": "valid"} {"repo": "hassox/pancake", "path": "lib/pancake/router.rb", "func_name": "Pancake.Router.mount", "original_string": "def mount(mounted_app, path, options = {})\n mounted_app = MountedApplication.new(mounted_app, path, options)\n self.class.mounted_applications << mounted_app\n mounted_app\n end", "language": "ruby", "code": "def mount(mounted_app, path, options = {})\n mounted_app = MountedApplication.new(mounted_app, path, options)\n self.class.mounted_applications << mounted_app\n mounted_app\n end", "code_tokens": ["def", "mount", "(", "mounted_app", ",", "path", ",", "options", "=", "{", "}", ")", "mounted_app", "=", "MountedApplication", ".", "new", "(", "mounted_app", ",", "path", ",", "options", ")", "self", ".", "class", ".", "mounted_applications", "<<", "mounted_app", "mounted_app", "end"], "docstring": "Mounts an application in the router as a sub application in the\n url space. This will route directly to the sub application and\n skip any middlewares etc defined on a stack", "docstring_tokens": ["Mounts", "an", "application", "in", "the", "router", "as", "a", "sub", "application", "in", "the", "url", "space", ".", "This", "will", "route", "directly", "to", "the", "sub", "application", "and", "skip", "any", "middlewares", "etc", "defined", "on", "a", "stack"], "sha": "774b1e878cf8d4f8e7160173ed9a236a290989e6", "url": "https://github.com/hassox/pancake/blob/774b1e878cf8d4f8e7160173ed9a236a290989e6/lib/pancake/router.rb#L90-L94", "partition": "valid"} {"repo": "raykin/source-route", "path": "lib/source_route/generate_result.rb", "func_name": "SourceRoute.GenerateResult.assign_tp_self_caches", "original_string": "def assign_tp_self_caches(tp_ins)\n unless tp_self_caches.find { |tp_cache| tp_cache.object_id.equal? tp_ins.self.object_id }\n tp_self_caches.push tp_ins.self\n end\n end", "language": "ruby", "code": "def assign_tp_self_caches(tp_ins)\n unless tp_self_caches.find { |tp_cache| tp_cache.object_id.equal? tp_ins.self.object_id }\n tp_self_caches.push tp_ins.self\n end\n end", "code_tokens": ["def", "assign_tp_self_caches", "(", "tp_ins", ")", "unless", "tp_self_caches", ".", "find", "{", "|", "tp_cache", "|", "tp_cache", ".", "object_id", ".", "equal?", "tp_ins", ".", "self", ".", "object_id", "}", "tp_self_caches", ".", "push", "tp_ins", ".", "self", "end", "end"], "docstring": "include? will evaluate @tp.self, if @tp.self is AR::Relation, it could cause problems\n So that's why I use object_id as replace", "docstring_tokens": ["include?", "will", "evaluate"], "sha": "c45feacd080511ca85691a2e2176bd0125e9ca09", "url": "https://github.com/raykin/source-route/blob/c45feacd080511ca85691a2e2176bd0125e9ca09/lib/source_route/generate_result.rb#L84-L88", "partition": "valid"} {"repo": "hassox/pancake", "path": "lib/pancake/logger.rb", "func_name": "Pancake.Logger.set_log", "original_string": "def set_log(stream = Pancake.configuration.log_stream,\n log_level = Pancake.configuration.log_level,\n delimiter = Pancake.configuration.log_delimiter,\n auto_flush = Pancake.configuration.log_auto_flush)\n\n @buffer = []\n @delimiter = delimiter\n @auto_flush = auto_flush\n\n if Levels[log_level]\n @level = Levels[log_level]\n else\n @level = log_level\n end\n\n @log = stream\n @log.sync = true\n @mutex = (@@mutex[@log] ||= Mutex.new)\n end", "language": "ruby", "code": "def set_log(stream = Pancake.configuration.log_stream,\n log_level = Pancake.configuration.log_level,\n delimiter = Pancake.configuration.log_delimiter,\n auto_flush = Pancake.configuration.log_auto_flush)\n\n @buffer = []\n @delimiter = delimiter\n @auto_flush = auto_flush\n\n if Levels[log_level]\n @level = Levels[log_level]\n else\n @level = log_level\n end\n\n @log = stream\n @log.sync = true\n @mutex = (@@mutex[@log] ||= Mutex.new)\n end", "code_tokens": ["def", "set_log", "(", "stream", "=", "Pancake", ".", "configuration", ".", "log_stream", ",", "log_level", "=", "Pancake", ".", "configuration", ".", "log_level", ",", "delimiter", "=", "Pancake", ".", "configuration", ".", "log_delimiter", ",", "auto_flush", "=", "Pancake", ".", "configuration", ".", "log_auto_flush", ")", "@buffer", "=", "[", "]", "@delimiter", "=", "delimiter", "@auto_flush", "=", "auto_flush", "if", "Levels", "[", "log_level", "]", "@level", "=", "Levels", "[", "log_level", "]", "else", "@level", "=", "log_level", "end", "@log", "=", "stream", "@log", ".", "sync", "=", "true", "@mutex", "=", "(", "@@mutex", "[", "@log", "]", "||=", "Mutex", ".", "new", ")", "end"], "docstring": "To initialize the logger you create a new object, proxies to set_log.\n\n ==== Parameters\n *args:: Arguments to create the log from. See set_logs for specifics.\n Replaces an existing logger with a new one.\n\n ==== Parameters\n log:: Either an IO object or a name of a logfile.\n log_level<~to_sym>::\n The log level from, e.g. :fatal or :info. Defaults to :error in the\n production environment and :debug otherwise.\n delimiter::\n Delimiter to use between message sections. Defaults to \" ~ \".\n auto_flush::\n Whether the log should automatically flush after new messages are\n added. Defaults to false.", "docstring_tokens": ["To", "initialize", "the", "logger", "you", "create", "a", "new", "object", "proxies", "to", "set_log", "."], "sha": "774b1e878cf8d4f8e7160173ed9a236a290989e6", "url": "https://github.com/hassox/pancake/blob/774b1e878cf8d4f8e7160173ed9a236a290989e6/lib/pancake/logger.rb#L84-L102", "partition": "valid"} {"repo": "hassox/pancake", "path": "lib/pancake/paths.rb", "func_name": "Pancake.Paths.dirs_for", "original_string": "def dirs_for(name, opts = {})\n if _load_paths[name].blank?\n []\n else\n result = []\n invert = !!opts[:invert]\n load_paths = invert ? _load_paths[name].reverse : _load_paths[name]\n roots.each do |root|\n load_paths.each do |paths, glob|\n paths = paths.reverse if invert\n result << paths.map{|p| File.join(root, p)}\n end\n end\n result.flatten\n end # if\n end", "language": "ruby", "code": "def dirs_for(name, opts = {})\n if _load_paths[name].blank?\n []\n else\n result = []\n invert = !!opts[:invert]\n load_paths = invert ? _load_paths[name].reverse : _load_paths[name]\n roots.each do |root|\n load_paths.each do |paths, glob|\n paths = paths.reverse if invert\n result << paths.map{|p| File.join(root, p)}\n end\n end\n result.flatten\n end # if\n end", "code_tokens": ["def", "dirs_for", "(", "name", ",", "opts", "=", "{", "}", ")", "if", "_load_paths", "[", "name", "]", ".", "blank?", "[", "]", "else", "result", "=", "[", "]", "invert", "=", "!", "!", "opts", "[", ":invert", "]", "load_paths", "=", "invert", "?", "_load_paths", "[", "name", "]", ".", "reverse", ":", "_load_paths", "[", "name", "]", "roots", ".", "each", "do", "|", "root", "|", "load_paths", ".", "each", "do", "|", "paths", ",", "glob", "|", "paths", "=", "paths", ".", "reverse", "if", "invert", "result", "<<", "paths", ".", "map", "{", "|", "p", "|", "File", ".", "join", "(", "root", ",", "p", ")", "}", "end", "end", "result", ".", "flatten", "end", "# if", "end"], "docstring": "Provides the directories or raw paths that are associated with a given name.\n\n @param [Symbol] name The name for the paths group\n @param [Hash] opts An options hash\n @option opts [Boolean] :invert (false) inverts the order of the returned paths\n\n @example Read Directories:\n MyClass.dirs_for(:models)\n\n @example Inverted Read:\n MyClass.dirs_for(:models, :invert => true)\n\n @return [Array] An array of the paths\n Returned in declared order unless the :invert option is set\n @api public\n @since 0.1.1\n @author Daniel Neighman", "docstring_tokens": ["Provides", "the", "directories", "or", "raw", "paths", "that", "are", "associated", "with", "a", "given", "name", "."], "sha": "774b1e878cf8d4f8e7160173ed9a236a290989e6", "url": "https://github.com/hassox/pancake/blob/774b1e878cf8d4f8e7160173ed9a236a290989e6/lib/pancake/paths.rb#L92-L107", "partition": "valid"} {"repo": "hassox/pancake", "path": "lib/pancake/paths.rb", "func_name": "Pancake.Paths.paths_for", "original_string": "def paths_for(name, opts = {})\n result = []\n dirs_and_glob_for(name, opts).each do |path, glob|\n next if glob.nil?\n paths = Dir[File.join(path, glob)]\n paths = paths.reverse if opts[:invert]\n paths.each do |full_path|\n result << [path, full_path.gsub(path, \"\")]\n end\n end\n result\n end", "language": "ruby", "code": "def paths_for(name, opts = {})\n result = []\n dirs_and_glob_for(name, opts).each do |path, glob|\n next if glob.nil?\n paths = Dir[File.join(path, glob)]\n paths = paths.reverse if opts[:invert]\n paths.each do |full_path|\n result << [path, full_path.gsub(path, \"\")]\n end\n end\n result\n end", "code_tokens": ["def", "paths_for", "(", "name", ",", "opts", "=", "{", "}", ")", "result", "=", "[", "]", "dirs_and_glob_for", "(", "name", ",", "opts", ")", ".", "each", "do", "|", "path", ",", "glob", "|", "next", "if", "glob", ".", "nil?", "paths", "=", "Dir", "[", "File", ".", "join", "(", "path", ",", "glob", ")", "]", "paths", "=", "paths", ".", "reverse", "if", "opts", "[", ":invert", "]", "paths", ".", "each", "do", "|", "full_path", "|", "result", "<<", "[", "path", ",", "full_path", ".", "gsub", "(", "path", ",", "\"\"", ")", "]", "end", "end", "result", "end"], "docstring": "Provides an expanded, globbed list of paths and files for a given name.\n\n @param [Symbol] name The name of the paths group\n @param [Hash] opts An options hash\n @option opts [Boolean] :invert (false) Inverts the order of the returned values\n\n @example\n MyClass.paths_for(:model)\n MyClass.paths_for(:model, :invert => true)\n\n @return [Array]\n An array of [path, file] arrays. These may be joined to get the full path.\n All matched files for [paths, glob] will be returned in declared and then found order unless +:invert+ is true.\n Any path that has a +nil+ glob associated with it will be excluded.\n\n @api public\n @since 0.1.1\n @author Daniel Neighman", "docstring_tokens": ["Provides", "an", "expanded", "globbed", "list", "of", "paths", "and", "files", "for", "a", "given", "name", "."], "sha": "774b1e878cf8d4f8e7160173ed9a236a290989e6", "url": "https://github.com/hassox/pancake/blob/774b1e878cf8d4f8e7160173ed9a236a290989e6/lib/pancake/paths.rb#L160-L171", "partition": "valid"} {"repo": "hassox/pancake", "path": "lib/pancake/paths.rb", "func_name": "Pancake.Paths.unique_paths_for", "original_string": "def unique_paths_for(name, opts = {})\n tally = {}\n output = []\n paths_for(name, opts).reverse.each do |ary|\n tally[ary[1]] ||= ary[0]\n output << ary if tally[ary[1]] == ary[0]\n end\n output.reverse\n end", "language": "ruby", "code": "def unique_paths_for(name, opts = {})\n tally = {}\n output = []\n paths_for(name, opts).reverse.each do |ary|\n tally[ary[1]] ||= ary[0]\n output << ary if tally[ary[1]] == ary[0]\n end\n output.reverse\n end", "code_tokens": ["def", "unique_paths_for", "(", "name", ",", "opts", "=", "{", "}", ")", "tally", "=", "{", "}", "output", "=", "[", "]", "paths_for", "(", "name", ",", "opts", ")", ".", "reverse", ".", "each", "do", "|", "ary", "|", "tally", "[", "ary", "[", "1", "]", "]", "||=", "ary", "[", "0", "]", "output", "<<", "ary", "if", "tally", "[", "ary", "[", "1", "]", "]", "==", "ary", "[", "0", "]", "end", "output", ".", "reverse", "end"], "docstring": "Provides an expanded, globbed list of paths and files for a given name.\n The result includes only the last matched file of a given sub path and name.\n\n @param [Symbol] name The name of the paths group\n @param [Hash] opts An options hash\n @option opts [Boolean] :invert (false) Inverts the order of returned paths and files\n\n @example\n #Given the following:\n # /path/one/file1.rb\n # /path/one/file2.rb\n # /path/two/file1.rb\n\n MyClass.push_path(:files, [\"/path/one\", \"/path/two\"], \"**/*.rb\")\n\n MyClass.unique_paths_for(:files)\n MyClass.unique_paths_for(:files, :invert => true)\n\n @return [Array]\n Returns an array of [path, file] arrays\n Results are retuned in declared order. Only unique files are returned (the file part - the path)\n In the above example, the following would be returned for the standard call\n [\n [\"#{root}/path/one\", \"/file2.rb\"],\n [\"#{root}/path/two\", \"/file1.rb\"]\n ]\n For the inverted example the following is returned:\n [\n [\"#{root}/path/one/file2.rb\"],\n [\"#{root}/path/one/file1.rb\"]\n ]\n\n @api public\n @since 0.1.1\n @author Daniel Neighman", "docstring_tokens": ["Provides", "an", "expanded", "globbed", "list", "of", "paths", "and", "files", "for", "a", "given", "name", ".", "The", "result", "includes", "only", "the", "last", "matched", "file", "of", "a", "given", "sub", "path", "and", "name", "."], "sha": "774b1e878cf8d4f8e7160173ed9a236a290989e6", "url": "https://github.com/hassox/pancake/blob/774b1e878cf8d4f8e7160173ed9a236a290989e6/lib/pancake/paths.rb#L208-L216", "partition": "valid"} {"repo": "OregonDigital/metadata-ingest-form", "path": "lib/metadata/ingest/translators/single_attribute_translator.rb", "func_name": "Metadata::Ingest::Translators.SingleAttributeTranslator.build_association", "original_string": "def build_association(value)\n association = @form.create_association(\n group: @group.to_s,\n type: @type.to_s,\n value: value\n )\n\n # Since the associations are fake, we just set persistence to the parent\n # object's value\n association.persisted = @source.persisted?\n\n return association\n end", "language": "ruby", "code": "def build_association(value)\n association = @form.create_association(\n group: @group.to_s,\n type: @type.to_s,\n value: value\n )\n\n # Since the associations are fake, we just set persistence to the parent\n # object's value\n association.persisted = @source.persisted?\n\n return association\n end", "code_tokens": ["def", "build_association", "(", "value", ")", "association", "=", "@form", ".", "create_association", "(", "group", ":", "@group", ".", "to_s", ",", "type", ":", "@type", ".", "to_s", ",", "value", ":", "value", ")", "# Since the associations are fake, we just set persistence to the parent", "# object's value", "association", ".", "persisted", "=", "@source", ".", "persisted?", "return", "association", "end"], "docstring": "Builds a single association with the given data", "docstring_tokens": ["Builds", "a", "single", "association", "with", "the", "given", "data"], "sha": "1d36b5a1380fe009cda797555883b1d258463682", "url": "https://github.com/OregonDigital/metadata-ingest-form/blob/1d36b5a1380fe009cda797555883b1d258463682/lib/metadata/ingest/translators/single_attribute_translator.rb#L49-L61", "partition": "valid"} {"repo": "raykin/source-route", "path": "lib/source_route/trace_filter.rb", "func_name": "SourceRoute.TraceFilter.block_it?", "original_string": "def block_it?(tp)\n if @cond.track_params\n return true if negative_check(tp)\n if positives_check(tp)\n return !tp.binding.eval('local_variables').any? do |v|\n tp.binding.local_variable_get(v).object_id == @cond.track_params\n end\n end\n else\n return true if negative_check(tp)\n return false if positives_check(tp)\n end\n true # default is blocked the tp\n end", "language": "ruby", "code": "def block_it?(tp)\n if @cond.track_params\n return true if negative_check(tp)\n if positives_check(tp)\n return !tp.binding.eval('local_variables').any? do |v|\n tp.binding.local_variable_get(v).object_id == @cond.track_params\n end\n end\n else\n return true if negative_check(tp)\n return false if positives_check(tp)\n end\n true # default is blocked the tp\n end", "code_tokens": ["def", "block_it?", "(", "tp", ")", "if", "@cond", ".", "track_params", "return", "true", "if", "negative_check", "(", "tp", ")", "if", "positives_check", "(", "tp", ")", "return", "!", "tp", ".", "binding", ".", "eval", "(", "'local_variables'", ")", ".", "any?", "do", "|", "v", "|", "tp", ".", "binding", ".", "local_variable_get", "(", "v", ")", ".", "object_id", "==", "@cond", ".", "track_params", "end", "end", "else", "return", "true", "if", "negative_check", "(", "tp", ")", "return", "false", "if", "positives_check", "(", "tp", ")", "end", "true", "# default is blocked the tp", "end"], "docstring": "to improve performance, we didnt assign tp as instance variable", "docstring_tokens": ["to", "improve", "performance", "we", "didnt", "assign", "tp", "as", "instance", "variable"], "sha": "c45feacd080511ca85691a2e2176bd0125e9ca09", "url": "https://github.com/raykin/source-route/blob/c45feacd080511ca85691a2e2176bd0125e9ca09/lib/source_route/trace_filter.rb#L10-L23", "partition": "valid"} {"repo": "Hamdiakoguz/onedclusterer", "path": "lib/onedclusterer/clusterer.rb", "func_name": "OnedClusterer.Clusterer.classify", "original_string": "def classify(value)\r\n raise ArgumentError, \"value: #{value} must be in data array\" unless @data.include?(value)\r\n\r\n bounds[1..-1].index { |bound| value <= bound }\r\n end", "language": "ruby", "code": "def classify(value)\r\n raise ArgumentError, \"value: #{value} must be in data array\" unless @data.include?(value)\r\n\r\n bounds[1..-1].index { |bound| value <= bound }\r\n end", "code_tokens": ["def", "classify", "(", "value", ")", "raise", "ArgumentError", ",", "\"value: #{value} must be in data array\"", "unless", "@data", ".", "include?", "(", "value", ")", "bounds", "[", "1", "..", "-", "1", "]", ".", "index", "{", "|", "bound", "|", "value", "<=", "bound", "}", "end"], "docstring": "Returns zero based index of cluster which a value belongs to\n value must be in data array", "docstring_tokens": ["Returns", "zero", "based", "index", "of", "cluster", "which", "a", "value", "belongs", "to", "value", "must", "be", "in", "data", "array"], "sha": "5d134970cb7e2bc0d29ae108d952c081707e02b6", "url": "https://github.com/Hamdiakoguz/onedclusterer/blob/5d134970cb7e2bc0d29ae108d952c081707e02b6/lib/onedclusterer/clusterer.rb#L8-L12", "partition": "valid"} {"repo": "Hamdiakoguz/onedclusterer", "path": "lib/onedclusterer/clusterer.rb", "func_name": "OnedClusterer.Clusterer.intervals", "original_string": "def intervals\r\n first, *rest = bounds.each_cons(2).to_a\r\n [first, *rest.map {|lower, upper| [data[data.rindex(lower) + 1] , upper] }]\r\n end", "language": "ruby", "code": "def intervals\r\n first, *rest = bounds.each_cons(2).to_a\r\n [first, *rest.map {|lower, upper| [data[data.rindex(lower) + 1] , upper] }]\r\n end", "code_tokens": ["def", "intervals", "first", ",", "*", "rest", "=", "bounds", ".", "each_cons", "(", "2", ")", ".", "to_a", "[", "first", ",", "rest", ".", "map", "{", "|", "lower", ",", "upper", "|", "[", "data", "[", "data", ".", "rindex", "(", "lower", ")", "+", "1", "]", ",", "upper", "]", "}", "]", "end"], "docstring": "Returns inclusive interval limits", "docstring_tokens": ["Returns", "inclusive", "interval", "limits"], "sha": "5d134970cb7e2bc0d29ae108d952c081707e02b6", "url": "https://github.com/Hamdiakoguz/onedclusterer/blob/5d134970cb7e2bc0d29ae108d952c081707e02b6/lib/onedclusterer/clusterer.rb#L15-L18", "partition": "valid"} {"repo": "Hamdiakoguz/onedclusterer", "path": "lib/onedclusterer/jenks.rb", "func_name": "OnedClusterer.Jenks.matrices", "original_string": "def matrices\r\n rows = data.size\r\n cols = n_classes\r\n\r\n # in the original implementation, these matrices are referred to\r\n # as `LC` and `OP`\r\n # * lower_class_limits (LC): optimal lower class limits\r\n # * variance_combinations (OP): optimal variance combinations for all classes\r\n lower_class_limits = *Matrix.zero(rows + 1, cols + 1)\r\n variance_combinations = *Matrix.zero(rows + 1, cols + 1)\r\n\r\n # the variance, as computed at each step in the calculation\r\n variance = 0\r\n\r\n for i in 1..cols\r\n lower_class_limits[1][i] = 1\r\n variance_combinations[1][i] = 0\r\n for j in 2..rows\r\n variance_combinations[j][i] = Float::INFINITY\r\n end\r\n end\r\n\r\n for l in 2..rows\r\n sum = 0 # `SZ` originally. this is the sum of the values seen thus far when calculating variance.\r\n sum_squares = 0 # `ZSQ` originally. the sum of squares of values seen thus far\r\n w = 0 # `WT` originally. This is the number of data points considered so far.\r\n\r\n for m in 1..l\r\n lower_class_limit = l - m + 1 # `III` originally\r\n val = data[lower_class_limit - 1]\r\n\r\n # here we're estimating variance for each potential classing\r\n # of the data, for each potential number of classes. `w`\r\n # is the number of data points considered so far.\r\n w += 1\r\n\r\n # increase the current sum and sum-of-squares\r\n sum += val\r\n sum_squares += (val ** 2)\r\n\r\n # the variance at this point in the sequence is the difference\r\n # between the sum of squares and the total x 2, over the number\r\n # of samples.\r\n variance = sum_squares - (sum ** 2) / w\r\n\r\n i4 = lower_class_limit - 1 # `IV` originally\r\n if i4 != 0\r\n for j in 2..cols\r\n # if adding this element to an existing class\r\n # will increase its variance beyond the limit, break\r\n # the class at this point, setting the lower_class_limit\r\n # at this point.\r\n if variance_combinations[l][j] >= (variance + variance_combinations[i4][j - 1])\r\n lower_class_limits[l][j] = lower_class_limit\r\n variance_combinations[l][j] = variance +\r\n variance_combinations[i4][j - 1]\r\n end\r\n end\r\n end\r\n end\r\n\r\n lower_class_limits[l][1] = 1\r\n variance_combinations[l][1] = variance\r\n end\r\n\r\n [lower_class_limits, variance_combinations]\r\n end", "language": "ruby", "code": "def matrices\r\n rows = data.size\r\n cols = n_classes\r\n\r\n # in the original implementation, these matrices are referred to\r\n # as `LC` and `OP`\r\n # * lower_class_limits (LC): optimal lower class limits\r\n # * variance_combinations (OP): optimal variance combinations for all classes\r\n lower_class_limits = *Matrix.zero(rows + 1, cols + 1)\r\n variance_combinations = *Matrix.zero(rows + 1, cols + 1)\r\n\r\n # the variance, as computed at each step in the calculation\r\n variance = 0\r\n\r\n for i in 1..cols\r\n lower_class_limits[1][i] = 1\r\n variance_combinations[1][i] = 0\r\n for j in 2..rows\r\n variance_combinations[j][i] = Float::INFINITY\r\n end\r\n end\r\n\r\n for l in 2..rows\r\n sum = 0 # `SZ` originally. this is the sum of the values seen thus far when calculating variance.\r\n sum_squares = 0 # `ZSQ` originally. the sum of squares of values seen thus far\r\n w = 0 # `WT` originally. This is the number of data points considered so far.\r\n\r\n for m in 1..l\r\n lower_class_limit = l - m + 1 # `III` originally\r\n val = data[lower_class_limit - 1]\r\n\r\n # here we're estimating variance for each potential classing\r\n # of the data, for each potential number of classes. `w`\r\n # is the number of data points considered so far.\r\n w += 1\r\n\r\n # increase the current sum and sum-of-squares\r\n sum += val\r\n sum_squares += (val ** 2)\r\n\r\n # the variance at this point in the sequence is the difference\r\n # between the sum of squares and the total x 2, over the number\r\n # of samples.\r\n variance = sum_squares - (sum ** 2) / w\r\n\r\n i4 = lower_class_limit - 1 # `IV` originally\r\n if i4 != 0\r\n for j in 2..cols\r\n # if adding this element to an existing class\r\n # will increase its variance beyond the limit, break\r\n # the class at this point, setting the lower_class_limit\r\n # at this point.\r\n if variance_combinations[l][j] >= (variance + variance_combinations[i4][j - 1])\r\n lower_class_limits[l][j] = lower_class_limit\r\n variance_combinations[l][j] = variance +\r\n variance_combinations[i4][j - 1]\r\n end\r\n end\r\n end\r\n end\r\n\r\n lower_class_limits[l][1] = 1\r\n variance_combinations[l][1] = variance\r\n end\r\n\r\n [lower_class_limits, variance_combinations]\r\n end", "code_tokens": ["def", "matrices", "rows", "=", "data", ".", "size", "cols", "=", "n_classes", "# in the original implementation, these matrices are referred to\r", "# as `LC` and `OP`\r", "# * lower_class_limits (LC): optimal lower class limits\r", "# * variance_combinations (OP): optimal variance combinations for all classes\r", "lower_class_limits", "=", "Matrix", ".", "zero", "(", "rows", "+", "1", ",", "cols", "+", "1", ")", "variance_combinations", "=", "Matrix", ".", "zero", "(", "rows", "+", "1", ",", "cols", "+", "1", ")", "# the variance, as computed at each step in the calculation\r", "variance", "=", "0", "for", "i", "in", "1", "..", "cols", "lower_class_limits", "[", "1", "]", "[", "i", "]", "=", "1", "variance_combinations", "[", "1", "]", "[", "i", "]", "=", "0", "for", "j", "in", "2", "..", "rows", "variance_combinations", "[", "j", "]", "[", "i", "]", "=", "Float", "::", "INFINITY", "end", "end", "for", "l", "in", "2", "..", "rows", "sum", "=", "0", "# `SZ` originally. this is the sum of the values seen thus far when calculating variance.\r", "sum_squares", "=", "0", "# `ZSQ` originally. the sum of squares of values seen thus far\r", "w", "=", "0", "# `WT` originally. This is the number of data points considered so far.\r", "for", "m", "in", "1", "..", "l", "lower_class_limit", "=", "l", "-", "m", "+", "1", "# `III` originally\r", "val", "=", "data", "[", "lower_class_limit", "-", "1", "]", "# here we're estimating variance for each potential classing\r", "# of the data, for each potential number of classes. `w`\r", "# is the number of data points considered so far.\r", "w", "+=", "1", "# increase the current sum and sum-of-squares\r", "sum", "+=", "val", "sum_squares", "+=", "(", "val", "**", "2", ")", "# the variance at this point in the sequence is the difference\r", "# between the sum of squares and the total x 2, over the number\r", "# of samples.\r", "variance", "=", "sum_squares", "-", "(", "sum", "**", "2", ")", "/", "w", "i4", "=", "lower_class_limit", "-", "1", "# `IV` originally\r", "if", "i4", "!=", "0", "for", "j", "in", "2", "..", "cols", "# if adding this element to an existing class\r", "# will increase its variance beyond the limit, break\r", "# the class at this point, setting the lower_class_limit\r", "# at this point.\r", "if", "variance_combinations", "[", "l", "]", "[", "j", "]", ">=", "(", "variance", "+", "variance_combinations", "[", "i4", "]", "[", "j", "-", "1", "]", ")", "lower_class_limits", "[", "l", "]", "[", "j", "]", "=", "lower_class_limit", "variance_combinations", "[", "l", "]", "[", "j", "]", "=", "variance", "+", "variance_combinations", "[", "i4", "]", "[", "j", "-", "1", "]", "end", "end", "end", "end", "lower_class_limits", "[", "l", "]", "[", "1", "]", "=", "1", "variance_combinations", "[", "l", "]", "[", "1", "]", "=", "variance", "end", "[", "lower_class_limits", ",", "variance_combinations", "]", "end"], "docstring": "Compute the matrices required for Jenks breaks. These matrices\n can be used for any classing of data with `classes <= n_classes`", "docstring_tokens": ["Compute", "the", "matrices", "required", "for", "Jenks", "breaks", ".", "These", "matrices", "can", "be", "used", "for", "any", "classing", "of", "data", "with", "classes", "<", "=", "n_classes"], "sha": "5d134970cb7e2bc0d29ae108d952c081707e02b6", "url": "https://github.com/Hamdiakoguz/onedclusterer/blob/5d134970cb7e2bc0d29ae108d952c081707e02b6/lib/onedclusterer/jenks.rb#L67-L133", "partition": "valid"} {"repo": "jvanbaarsen/omdb", "path": "lib/omdb/api.rb", "func_name": "Omdb.Api.fetch", "original_string": "def fetch(title, year = \"\", tomatoes = false, plot = \"short\")\n res = network.call({ t: title, y: year, tomatoes: tomatoes, plot: plot })\n\n if res[:data][\"Response\"] == \"False\"\n { status: 404 }\n else\n { status: res[:code], movie: parse_movie(res[:data]) }\n end\n end", "language": "ruby", "code": "def fetch(title, year = \"\", tomatoes = false, plot = \"short\")\n res = network.call({ t: title, y: year, tomatoes: tomatoes, plot: plot })\n\n if res[:data][\"Response\"] == \"False\"\n { status: 404 }\n else\n { status: res[:code], movie: parse_movie(res[:data]) }\n end\n end", "code_tokens": ["def", "fetch", "(", "title", ",", "year", "=", "\"\"", ",", "tomatoes", "=", "false", ",", "plot", "=", "\"short\"", ")", "res", "=", "network", ".", "call", "(", "{", "t", ":", "title", ",", "y", ":", "year", ",", "tomatoes", ":", "tomatoes", ",", "plot", ":", "plot", "}", ")", "if", "res", "[", ":data", "]", "[", "\"Response\"", "]", "==", "\"False\"", "{", "status", ":", "404", "}", "else", "{", "status", ":", "res", "[", ":code", "]", ",", "movie", ":", "parse_movie", "(", "res", "[", ":data", "]", ")", "}", "end", "end"], "docstring": "fetchs a movie with a given title\n set tomatoes to true if you want to get the rotten tomatoes ranking\n set plot to full if you want to have the full, long plot", "docstring_tokens": ["fetchs", "a", "movie", "with", "a", "given", "title", "set", "tomatoes", "to", "true", "if", "you", "want", "to", "get", "the", "rotten", "tomatoes", "ranking", "set", "plot", "to", "full", "if", "you", "want", "to", "have", "the", "full", "long", "plot"], "sha": "b9b08658c2c0e7d62536153f8b7f299cfa630709", "url": "https://github.com/jvanbaarsen/omdb/blob/b9b08658c2c0e7d62536153f8b7f299cfa630709/lib/omdb/api.rb#L17-L25", "partition": "valid"} {"repo": "jvanbaarsen/omdb", "path": "lib/omdb/api.rb", "func_name": "Omdb.Api.find", "original_string": "def find(id, tomatoes = false, plot = \"short\")\n res = network.call({ i: id, tomatoes: tomatoes, plot: plot })\n\n if res[:data][\"Response\"] == \"False\"\n { status: 404 }\n else\n { status: res[:code], movie: parse_movie(res[:data]) }\n end\n end", "language": "ruby", "code": "def find(id, tomatoes = false, plot = \"short\")\n res = network.call({ i: id, tomatoes: tomatoes, plot: plot })\n\n if res[:data][\"Response\"] == \"False\"\n { status: 404 }\n else\n { status: res[:code], movie: parse_movie(res[:data]) }\n end\n end", "code_tokens": ["def", "find", "(", "id", ",", "tomatoes", "=", "false", ",", "plot", "=", "\"short\"", ")", "res", "=", "network", ".", "call", "(", "{", "i", ":", "id", ",", "tomatoes", ":", "tomatoes", ",", "plot", ":", "plot", "}", ")", "if", "res", "[", ":data", "]", "[", "\"Response\"", "]", "==", "\"False\"", "{", "status", ":", "404", "}", "else", "{", "status", ":", "res", "[", ":code", "]", ",", "movie", ":", "parse_movie", "(", "res", "[", ":data", "]", ")", "}", "end", "end"], "docstring": "fetches a movie by IMDB id\n set tomatoes to true if you want to get the rotten tomatoes ranking\n set plot to full if you want to have the full, long plot", "docstring_tokens": ["fetches", "a", "movie", "by", "IMDB", "id", "set", "tomatoes", "to", "true", "if", "you", "want", "to", "get", "the", "rotten", "tomatoes", "ranking", "set", "plot", "to", "full", "if", "you", "want", "to", "have", "the", "full", "long", "plot"], "sha": "b9b08658c2c0e7d62536153f8b7f299cfa630709", "url": "https://github.com/jvanbaarsen/omdb/blob/b9b08658c2c0e7d62536153f8b7f299cfa630709/lib/omdb/api.rb#L30-L38", "partition": "valid"} {"repo": "G5/g5_authentication_client", "path": "lib/g5_authentication_client/configuration.rb", "func_name": "G5AuthenticationClient.Configuration.options", "original_string": "def options\n VALID_CONFIG_OPTIONS.inject({}) do |option, key|\n option.merge!(key => send(key))\n end\n end", "language": "ruby", "code": "def options\n VALID_CONFIG_OPTIONS.inject({}) do |option, key|\n option.merge!(key => send(key))\n end\n end", "code_tokens": ["def", "options", "VALID_CONFIG_OPTIONS", ".", "inject", "(", "{", "}", ")", "do", "|", "option", ",", "key", "|", "option", ".", "merge!", "(", "key", "=>", "send", "(", "key", ")", ")", "end", "end"], "docstring": "Create a hash of configuration options and their\n values.\n\n @return [Hash] the options hash", "docstring_tokens": ["Create", "a", "hash", "of", "configuration", "options", "and", "their", "values", "."], "sha": "c9e470b006706e68682692772b6e3d43ff782f78", "url": "https://github.com/G5/g5_authentication_client/blob/c9e470b006706e68682692772b6e3d43ff782f78/lib/g5_authentication_client/configuration.rb#L123-L127", "partition": "valid"} {"repo": "G5/g5_authentication_client", "path": "lib/g5_authentication_client/client.rb", "func_name": "G5AuthenticationClient.Client.create_user", "original_string": "def create_user(options={})\n user=User.new(options)\n user.validate_for_create!\n body = user_hash(user.to_hash)\n response=oauth_access_token.post('/v1/users', body: body)\n User.new(response.parsed)\n end", "language": "ruby", "code": "def create_user(options={})\n user=User.new(options)\n user.validate_for_create!\n body = user_hash(user.to_hash)\n response=oauth_access_token.post('/v1/users', body: body)\n User.new(response.parsed)\n end", "code_tokens": ["def", "create_user", "(", "options", "=", "{", "}", ")", "user", "=", "User", ".", "new", "(", "options", ")", "user", ".", "validate_for_create!", "body", "=", "user_hash", "(", "user", ".", "to_hash", ")", "response", "=", "oauth_access_token", ".", "post", "(", "'/v1/users'", ",", "body", ":", "body", ")", "User", ".", "new", "(", "response", ".", "parsed", ")", "end"], "docstring": "Create a user from the options\n @param [Hash] options\n @option options [String] :email The new user's email address\n @option options [String] :password The new user's password\n @option options [String] :password_confirmation The new user's password confirmation string\n @return [G5AuthenticationClient::User]", "docstring_tokens": ["Create", "a", "user", "from", "the", "options"], "sha": "c9e470b006706e68682692772b6e3d43ff782f78", "url": "https://github.com/G5/g5_authentication_client/blob/c9e470b006706e68682692772b6e3d43ff782f78/lib/g5_authentication_client/client.rb#L100-L106", "partition": "valid"} {"repo": "G5/g5_authentication_client", "path": "lib/g5_authentication_client/client.rb", "func_name": "G5AuthenticationClient.Client.update_user", "original_string": "def update_user(options={})\n user=User.new(options)\n user.validate!\n response=oauth_access_token.put(\"/v1/users/#{user.id}\", body: user_hash(user.to_hash))\n User.new(response.parsed)\n end", "language": "ruby", "code": "def update_user(options={})\n user=User.new(options)\n user.validate!\n response=oauth_access_token.put(\"/v1/users/#{user.id}\", body: user_hash(user.to_hash))\n User.new(response.parsed)\n end", "code_tokens": ["def", "update_user", "(", "options", "=", "{", "}", ")", "user", "=", "User", ".", "new", "(", "options", ")", "user", ".", "validate!", "response", "=", "oauth_access_token", ".", "put", "(", "\"/v1/users/#{user.id}\"", ",", "body", ":", "user_hash", "(", "user", ".", "to_hash", ")", ")", "User", ".", "new", "(", "response", ".", "parsed", ")", "end"], "docstring": "Update an existing user\n @param [Hash] options\n @option options [String] :email The new user's email address\n @option options [String] :password The new user's password\n @option options [String] :password_confirmation The new user's password confirmation string\n @return [G5AuthenticationClient::User]", "docstring_tokens": ["Update", "an", "existing", "user"], "sha": "c9e470b006706e68682692772b6e3d43ff782f78", "url": "https://github.com/G5/g5_authentication_client/blob/c9e470b006706e68682692772b6e3d43ff782f78/lib/g5_authentication_client/client.rb#L114-L119", "partition": "valid"} {"repo": "G5/g5_authentication_client", "path": "lib/g5_authentication_client/client.rb", "func_name": "G5AuthenticationClient.Client.find_user_by_email", "original_string": "def find_user_by_email(email)\n response = oauth_access_token.get('/v1/users', params: { email: email })\n user = response.parsed.first\n if user\n user=User.new(user)\n end\n user\n end", "language": "ruby", "code": "def find_user_by_email(email)\n response = oauth_access_token.get('/v1/users', params: { email: email })\n user = response.parsed.first\n if user\n user=User.new(user)\n end\n user\n end", "code_tokens": ["def", "find_user_by_email", "(", "email", ")", "response", "=", "oauth_access_token", ".", "get", "(", "'/v1/users'", ",", "params", ":", "{", "email", ":", "email", "}", ")", "user", "=", "response", ".", "parsed", ".", "first", "if", "user", "user", "=", "User", ".", "new", "(", "user", ")", "end", "user", "end"], "docstring": "Find a user by email\n @param [String] email address\n @return [G5AuthenticationClient::User]", "docstring_tokens": ["Find", "a", "user", "by", "email"], "sha": "c9e470b006706e68682692772b6e3d43ff782f78", "url": "https://github.com/G5/g5_authentication_client/blob/c9e470b006706e68682692772b6e3d43ff782f78/lib/g5_authentication_client/client.rb#L124-L131", "partition": "valid"} {"repo": "G5/g5_authentication_client", "path": "lib/g5_authentication_client/client.rb", "func_name": "G5AuthenticationClient.Client.sign_out_url", "original_string": "def sign_out_url(redirect_url=nil)\n auth_server_url = Addressable::URI.parse(endpoint)\n auth_server_url.path = '/users/sign_out'\n auth_server_url.query_values = {redirect_url: redirect_url} if redirect_url\n auth_server_url.to_s\n end", "language": "ruby", "code": "def sign_out_url(redirect_url=nil)\n auth_server_url = Addressable::URI.parse(endpoint)\n auth_server_url.path = '/users/sign_out'\n auth_server_url.query_values = {redirect_url: redirect_url} if redirect_url\n auth_server_url.to_s\n end", "code_tokens": ["def", "sign_out_url", "(", "redirect_url", "=", "nil", ")", "auth_server_url", "=", "Addressable", "::", "URI", ".", "parse", "(", "endpoint", ")", "auth_server_url", ".", "path", "=", "'/users/sign_out'", "auth_server_url", ".", "query_values", "=", "{", "redirect_url", ":", "redirect_url", "}", "if", "redirect_url", "auth_server_url", ".", "to_s", "end"], "docstring": "Return the URL for signing out of the auth server.\n Clients should redirect to this URL to globally sign out.\n\n @param [String] redirect_url the URL that the auth server should redirect back to after sign out\n @return [String] the auth server endpoint for signing out", "docstring_tokens": ["Return", "the", "URL", "for", "signing", "out", "of", "the", "auth", "server", ".", "Clients", "should", "redirect", "to", "this", "URL", "to", "globally", "sign", "out", "."], "sha": "c9e470b006706e68682692772b6e3d43ff782f78", "url": "https://github.com/G5/g5_authentication_client/blob/c9e470b006706e68682692772b6e3d43ff782f78/lib/g5_authentication_client/client.rb#L168-L173", "partition": "valid"} {"repo": "G5/g5_authentication_client", "path": "lib/g5_authentication_client/client.rb", "func_name": "G5AuthenticationClient.Client.list_users", "original_string": "def list_users\n response=oauth_access_token.get(\"/v1/users\")\n response.parsed.collect { |parsed_user| User.new(parsed_user) }\n end", "language": "ruby", "code": "def list_users\n response=oauth_access_token.get(\"/v1/users\")\n response.parsed.collect { |parsed_user| User.new(parsed_user) }\n end", "code_tokens": ["def", "list_users", "response", "=", "oauth_access_token", ".", "get", "(", "\"/v1/users\"", ")", "response", ".", "parsed", ".", "collect", "{", "|", "parsed_user", "|", "User", ".", "new", "(", "parsed_user", ")", "}", "end"], "docstring": "Return all users from the remote service\n @return [Array]", "docstring_tokens": ["Return", "all", "users", "from", "the", "remote", "service"], "sha": "c9e470b006706e68682692772b6e3d43ff782f78", "url": "https://github.com/G5/g5_authentication_client/blob/c9e470b006706e68682692772b6e3d43ff782f78/lib/g5_authentication_client/client.rb#L177-L180", "partition": "valid"} {"repo": "G5/g5_authentication_client", "path": "lib/g5_authentication_client/client.rb", "func_name": "G5AuthenticationClient.Client.list_roles", "original_string": "def list_roles\n response = oauth_access_token.get('/v1/roles')\n response.parsed.collect { |parsed_role| Role.new(parsed_role) }\n end", "language": "ruby", "code": "def list_roles\n response = oauth_access_token.get('/v1/roles')\n response.parsed.collect { |parsed_role| Role.new(parsed_role) }\n end", "code_tokens": ["def", "list_roles", "response", "=", "oauth_access_token", ".", "get", "(", "'/v1/roles'", ")", "response", ".", "parsed", ".", "collect", "{", "|", "parsed_role", "|", "Role", ".", "new", "(", "parsed_role", ")", "}", "end"], "docstring": "Return all user roles from the remote service\n @return [Array]", "docstring_tokens": ["Return", "all", "user", "roles", "from", "the", "remote", "service"], "sha": "c9e470b006706e68682692772b6e3d43ff782f78", "url": "https://github.com/G5/g5_authentication_client/blob/c9e470b006706e68682692772b6e3d43ff782f78/lib/g5_authentication_client/client.rb#L184-L187", "partition": "valid"} {"repo": "aaronrussell/cloudapp_api", "path": "lib/cloudapp/client.rb", "func_name": "CloudApp.Client.bookmark", "original_string": "def bookmark(*args)\n if args[0].is_a? Array\n Drop.create(:bookmarks, args)\n else\n url, name = args[0], (args[1] || \"\")\n Drop.create(:bookmark, {:name => name, :redirect_url => url})\n end\n end", "language": "ruby", "code": "def bookmark(*args)\n if args[0].is_a? Array\n Drop.create(:bookmarks, args)\n else\n url, name = args[0], (args[1] || \"\")\n Drop.create(:bookmark, {:name => name, :redirect_url => url})\n end\n end", "code_tokens": ["def", "bookmark", "(", "*", "args", ")", "if", "args", "[", "0", "]", ".", "is_a?", "Array", "Drop", ".", "create", "(", ":bookmarks", ",", "args", ")", "else", "url", ",", "name", "=", "args", "[", "0", "]", ",", "(", "args", "[", "1", "]", "||", "\"\"", ")", "Drop", ".", "create", "(", ":bookmark", ",", "{", ":name", "=>", "name", ",", ":redirect_url", "=>", "url", "}", ")", "end", "end"], "docstring": "Create one or more new bookmark drops.\n\n Requires authentication.\n\n @overload bookmark(url, name = \"\")\n @param [String] url url to bookmark\n @param [String] name name of bookmark\n @overload bookmark(opts)\n @param [Array] opts array of bookmark option parameters (containing +:name+ and +:redirect_url+)\n @return [CloudApp::Drop]", "docstring_tokens": ["Create", "one", "or", "more", "new", "bookmark", "drops", "."], "sha": "6d28d0541cb0f938a8fc2fed3a2fcaddf5391988", "url": "https://github.com/aaronrussell/cloudapp_api/blob/6d28d0541cb0f938a8fc2fed3a2fcaddf5391988/lib/cloudapp/client.rb#L105-L112", "partition": "valid"} {"repo": "aaronrussell/cloudapp_api", "path": "lib/cloudapp/client.rb", "func_name": "CloudApp.Client.rename", "original_string": "def rename(id, name = \"\")\n drop = Drop.find(id)\n drop.update(:name => name)\n end", "language": "ruby", "code": "def rename(id, name = \"\")\n drop = Drop.find(id)\n drop.update(:name => name)\n end", "code_tokens": ["def", "rename", "(", "id", ",", "name", "=", "\"\"", ")", "drop", "=", "Drop", ".", "find", "(", "id", ")", "drop", ".", "update", "(", ":name", "=>", "name", ")", "end"], "docstring": "Change the name of the drop.\n\n Finds the drop by it's slug id, for example \"2wr4\".\n\n Requires authentication.\n\n @param [String] id drop id\n @param [String] name new drop name\n @return [CloudApp::Drop]", "docstring_tokens": ["Change", "the", "name", "of", "the", "drop", "."], "sha": "6d28d0541cb0f938a8fc2fed3a2fcaddf5391988", "url": "https://github.com/aaronrussell/cloudapp_api/blob/6d28d0541cb0f938a8fc2fed3a2fcaddf5391988/lib/cloudapp/client.rb#L135-L138", "partition": "valid"} {"repo": "aaronrussell/cloudapp_api", "path": "lib/cloudapp/client.rb", "func_name": "CloudApp.Client.privacy", "original_string": "def privacy(id, privacy = false)\n drop = Drop.find(id)\n drop.update(:private => privacy)\n end", "language": "ruby", "code": "def privacy(id, privacy = false)\n drop = Drop.find(id)\n drop.update(:private => privacy)\n end", "code_tokens": ["def", "privacy", "(", "id", ",", "privacy", "=", "false", ")", "drop", "=", "Drop", ".", "find", "(", "id", ")", "drop", ".", "update", "(", ":private", "=>", "privacy", ")", "end"], "docstring": "Modify a drop with a private URL to have a public URL or vice versa.\n\n Finds the drop by it's slug id, for example \"2wr4\".\n\n Requires authentication.\n\n @param [String] id drop id\n @param [Boolean] privacy privacy setting\n @return [CloudApp::Drop]", "docstring_tokens": ["Modify", "a", "drop", "with", "a", "private", "URL", "to", "have", "a", "public", "URL", "or", "vice", "versa", "."], "sha": "6d28d0541cb0f938a8fc2fed3a2fcaddf5391988", "url": "https://github.com/aaronrussell/cloudapp_api/blob/6d28d0541cb0f938a8fc2fed3a2fcaddf5391988/lib/cloudapp/client.rb#L149-L152", "partition": "valid"} {"repo": "aaronrussell/cloudapp_api", "path": "lib/cloudapp/base.rb", "func_name": "CloudApp.Base.load", "original_string": "def load(attributes = {})\n attributes.each do |key, val|\n if key =~ /^.*_at$/ and val\n # if this is a date/time key and it's not nil, try to parse it first\n # as DateTime, then as Date only\n begin\n dt = DateTime.strptime(val, \"%Y-%m-%dT%H:%M:%SZ\")\n newval = Time.utc(dt.year, dt.month, dt.day, dt.hour, dt.min, dt.sec)\n rescue ArgumentError => ex\n newval = DateTime.strptime(val, \"%Y-%m-%d\")\n end\n self.instance_variable_set(\"@#{key}\", newval)\n else\n self.instance_variable_set(\"@#{key}\", val)\n end\n end\n end", "language": "ruby", "code": "def load(attributes = {})\n attributes.each do |key, val|\n if key =~ /^.*_at$/ and val\n # if this is a date/time key and it's not nil, try to parse it first\n # as DateTime, then as Date only\n begin\n dt = DateTime.strptime(val, \"%Y-%m-%dT%H:%M:%SZ\")\n newval = Time.utc(dt.year, dt.month, dt.day, dt.hour, dt.min, dt.sec)\n rescue ArgumentError => ex\n newval = DateTime.strptime(val, \"%Y-%m-%d\")\n end\n self.instance_variable_set(\"@#{key}\", newval)\n else\n self.instance_variable_set(\"@#{key}\", val)\n end\n end\n end", "code_tokens": ["def", "load", "(", "attributes", "=", "{", "}", ")", "attributes", ".", "each", "do", "|", "key", ",", "val", "|", "if", "key", "=~", "/", "/", "and", "val", "# if this is a date/time key and it's not nil, try to parse it first", "# as DateTime, then as Date only", "begin", "dt", "=", "DateTime", ".", "strptime", "(", "val", ",", "\"%Y-%m-%dT%H:%M:%SZ\"", ")", "newval", "=", "Time", ".", "utc", "(", "dt", ".", "year", ",", "dt", ".", "month", ",", "dt", ".", "day", ",", "dt", ".", "hour", ",", "dt", ".", "min", ",", "dt", ".", "sec", ")", "rescue", "ArgumentError", "=>", "ex", "newval", "=", "DateTime", ".", "strptime", "(", "val", ",", "\"%Y-%m-%d\"", ")", "end", "self", ".", "instance_variable_set", "(", "\"@#{key}\"", ",", "newval", ")", "else", "self", ".", "instance_variable_set", "(", "\"@#{key}\"", ",", "val", ")", "end", "end", "end"], "docstring": "Sets the attributes for object.\n\n @param [Hash] attributes", "docstring_tokens": ["Sets", "the", "attributes", "for", "object", "."], "sha": "6d28d0541cb0f938a8fc2fed3a2fcaddf5391988", "url": "https://github.com/aaronrussell/cloudapp_api/blob/6d28d0541cb0f938a8fc2fed3a2fcaddf5391988/lib/cloudapp/base.rb#L60-L76", "partition": "valid"} {"repo": "mattetti/wd-sinatra", "path": "lib/wd_sinatra/app_loader.rb", "func_name": "WDSinatra.AppLoader.load_environment", "original_string": "def load_environment(env=RACK_ENV)\n # Load the default which can be overwritten or extended by specific\n # env config files.\n require File.join(root_path, 'config', 'environments', 'default.rb')\n env_file = File.join(root_path, \"config\", \"environments\", \"#{env}.rb\")\n if File.exist?(env_file)\n require env_file\n else\n debug_msg = \"Environment file: #{env_file} couldn't be found, using only the default environment config instead.\" unless env == 'development'\n end\n # making sure we have a LOGGER constant defined.\n unless Object.const_defined?(:LOGGER)\n Object.const_set(:LOGGER, Logger.new($stdout))\n end\n LOGGER.debug(debug_msg) if debug_msg\n end", "language": "ruby", "code": "def load_environment(env=RACK_ENV)\n # Load the default which can be overwritten or extended by specific\n # env config files.\n require File.join(root_path, 'config', 'environments', 'default.rb')\n env_file = File.join(root_path, \"config\", \"environments\", \"#{env}.rb\")\n if File.exist?(env_file)\n require env_file\n else\n debug_msg = \"Environment file: #{env_file} couldn't be found, using only the default environment config instead.\" unless env == 'development'\n end\n # making sure we have a LOGGER constant defined.\n unless Object.const_defined?(:LOGGER)\n Object.const_set(:LOGGER, Logger.new($stdout))\n end\n LOGGER.debug(debug_msg) if debug_msg\n end", "code_tokens": ["def", "load_environment", "(", "env", "=", "RACK_ENV", ")", "# Load the default which can be overwritten or extended by specific", "# env config files.", "require", "File", ".", "join", "(", "root_path", ",", "'config'", ",", "'environments'", ",", "'default.rb'", ")", "env_file", "=", "File", ".", "join", "(", "root_path", ",", "\"config\"", ",", "\"environments\"", ",", "\"#{env}.rb\"", ")", "if", "File", ".", "exist?", "(", "env_file", ")", "require", "env_file", "else", "debug_msg", "=", "\"Environment file: #{env_file} couldn't be found, using only the default environment config instead.\"", "unless", "env", "==", "'development'", "end", "# making sure we have a LOGGER constant defined.", "unless", "Object", ".", "const_defined?", "(", ":LOGGER", ")", "Object", ".", "const_set", "(", ":LOGGER", ",", "Logger", ".", "new", "(", "$stdout", ")", ")", "end", "LOGGER", ".", "debug", "(", "debug_msg", ")", "if", "debug_msg", "end"], "docstring": "Loads an environment specific config if available, the config file is where the logger should be set\n if it was not, we are using stdout.", "docstring_tokens": ["Loads", "an", "environment", "specific", "config", "if", "available", "the", "config", "file", "is", "where", "the", "logger", "should", "be", "set", "if", "it", "was", "not", "we", "are", "using", "stdout", "."], "sha": "cead82665da00dfefc800132ecfc2ab58010eb46", "url": "https://github.com/mattetti/wd-sinatra/blob/cead82665da00dfefc800132ecfc2ab58010eb46/lib/wd_sinatra/app_loader.rb#L55-L70", "partition": "valid"} {"repo": "mattetti/wd-sinatra", "path": "lib/wd_sinatra/app_loader.rb", "func_name": "WDSinatra.AppLoader.load_apis", "original_string": "def load_apis\n Dir.glob(File.join(root_path, \"api\", \"**\", \"*.rb\")).each do |api|\n require api\n end\n end", "language": "ruby", "code": "def load_apis\n Dir.glob(File.join(root_path, \"api\", \"**\", \"*.rb\")).each do |api|\n require api\n end\n end", "code_tokens": ["def", "load_apis", "Dir", ".", "glob", "(", "File", ".", "join", "(", "root_path", ",", "\"api\"", ",", "\"**\"", ",", "\"*.rb\"", ")", ")", ".", "each", "do", "|", "api", "|", "require", "api", "end", "end"], "docstring": "DSL routes are located in the api folder", "docstring_tokens": ["DSL", "routes", "are", "located", "in", "the", "api", "folder"], "sha": "cead82665da00dfefc800132ecfc2ab58010eb46", "url": "https://github.com/mattetti/wd-sinatra/blob/cead82665da00dfefc800132ecfc2ab58010eb46/lib/wd_sinatra/app_loader.rb#L98-L102", "partition": "valid"} {"repo": "tribune/is_it_working", "path": "lib/is_it_working/filter.rb", "func_name": "IsItWorking.Filter.run", "original_string": "def run\n status = Status.new(name)\n runner = (async ? AsyncRunner : SyncRunner).new do\n t = Time.now\n begin\n @check.call(status)\n rescue Exception => e\n status.fail(\"#{name} error: #{e.inspect}\")\n end\n status.time = Time.now - t\n end\n runner.filter_status = status\n runner\n end", "language": "ruby", "code": "def run\n status = Status.new(name)\n runner = (async ? AsyncRunner : SyncRunner).new do\n t = Time.now\n begin\n @check.call(status)\n rescue Exception => e\n status.fail(\"#{name} error: #{e.inspect}\")\n end\n status.time = Time.now - t\n end\n runner.filter_status = status\n runner\n end", "code_tokens": ["def", "run", "status", "=", "Status", ".", "new", "(", "name", ")", "runner", "=", "(", "async", "?", "AsyncRunner", ":", "SyncRunner", ")", ".", "new", "do", "t", "=", "Time", ".", "now", "begin", "@check", ".", "call", "(", "status", ")", "rescue", "Exception", "=>", "e", "status", ".", "fail", "(", "\"#{name} error: #{e.inspect}\"", ")", "end", "status", ".", "time", "=", "Time", ".", "now", "-", "t", "end", "runner", ".", "filter_status", "=", "status", "runner", "end"], "docstring": "Create a new filter to run a status check. The name is used for display purposes.\n Run a status the status check. This method keeps track of the time it took to run\n the check and will trap any unexpected exceptions and report them as failures.", "docstring_tokens": ["Create", "a", "new", "filter", "to", "run", "a", "status", "check", ".", "The", "name", "is", "used", "for", "display", "purposes", ".", "Run", "a", "status", "the", "status", "check", ".", "This", "method", "keeps", "track", "of", "the", "time", "it", "took", "to", "run", "the", "check", "and", "will", "trap", "any", "unexpected", "exceptions", "and", "report", "them", "as", "failures", "."], "sha": "44645f8f676dd9fd25cff2d93cfdff0876cef36d", "url": "https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/filter.rb#L30-L43", "partition": "valid"} {"repo": "tribune/is_it_working", "path": "lib/is_it_working/handler.rb", "func_name": "IsItWorking.Handler.call", "original_string": "def call(env)\n if @app.nil? || env[PATH_INFO] == @route_path\n statuses = []\n t = Time.now\n statuses = Filter.run_filters(@filters)\n render(statuses, Time.now - t)\n else\n @app.call(env)\n end\n end", "language": "ruby", "code": "def call(env)\n if @app.nil? || env[PATH_INFO] == @route_path\n statuses = []\n t = Time.now\n statuses = Filter.run_filters(@filters)\n render(statuses, Time.now - t)\n else\n @app.call(env)\n end\n end", "code_tokens": ["def", "call", "(", "env", ")", "if", "@app", ".", "nil?", "||", "env", "[", "PATH_INFO", "]", "==", "@route_path", "statuses", "=", "[", "]", "t", "=", "Time", ".", "now", "statuses", "=", "Filter", ".", "run_filters", "(", "@filters", ")", "render", "(", "statuses", ",", "Time", ".", "now", "-", "t", ")", "else", "@app", ".", "call", "(", "env", ")", "end", "end"], "docstring": "Create a new handler. This method can take a block which will yield itself so it can\n be configured.\n\n The handler can be set up in one of two ways. If no arguments are supplied, it will\n return a regular Rack handler that can be used with a rackup +run+ method or in a\n Rails 3+ routes.rb file. Otherwise, an application stack can be supplied in the first\n argument and a routing path in the second (defaults to /is_it_working) so\n it can be used with the rackup +use+ method or in Rails.middleware.", "docstring_tokens": ["Create", "a", "new", "handler", ".", "This", "method", "can", "take", "a", "block", "which", "will", "yield", "itself", "so", "it", "can", "be", "configured", "."], "sha": "44645f8f676dd9fd25cff2d93cfdff0876cef36d", "url": "https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/handler.rb#L41-L50", "partition": "valid"} {"repo": "tribune/is_it_working", "path": "lib/is_it_working/handler.rb", "func_name": "IsItWorking.Handler.check", "original_string": "def check (name, *options_or_check, &block)\n raise ArgumentError(\"Too many arguments to #{self.class.name}#check\") if options_or_check.size > 2\n check = nil\n options = {:async => true}\n \n unless options_or_check.empty?\n if options_or_check[0].is_a?(Hash)\n options = options.merge(options_or_check[0])\n else\n check = options_or_check[0]\n end\n if options_or_check[1].is_a?(Hash)\n options = options.merge(options_or_check[1])\n end\n end\n \n unless check\n if block\n check = block\n else\n check = lookup_check(name, options)\n end\n end\n \n @filters << Filter.new(name, check, options[:async])\n end", "language": "ruby", "code": "def check (name, *options_or_check, &block)\n raise ArgumentError(\"Too many arguments to #{self.class.name}#check\") if options_or_check.size > 2\n check = nil\n options = {:async => true}\n \n unless options_or_check.empty?\n if options_or_check[0].is_a?(Hash)\n options = options.merge(options_or_check[0])\n else\n check = options_or_check[0]\n end\n if options_or_check[1].is_a?(Hash)\n options = options.merge(options_or_check[1])\n end\n end\n \n unless check\n if block\n check = block\n else\n check = lookup_check(name, options)\n end\n end\n \n @filters << Filter.new(name, check, options[:async])\n end", "code_tokens": ["def", "check", "(", "name", ",", "*", "options_or_check", ",", "&", "block", ")", "raise", "ArgumentError", "(", "\"Too many arguments to #{self.class.name}#check\"", ")", "if", "options_or_check", ".", "size", ">", "2", "check", "=", "nil", "options", "=", "{", ":async", "=>", "true", "}", "unless", "options_or_check", ".", "empty?", "if", "options_or_check", "[", "0", "]", ".", "is_a?", "(", "Hash", ")", "options", "=", "options", ".", "merge", "(", "options_or_check", "[", "0", "]", ")", "else", "check", "=", "options_or_check", "[", "0", "]", "end", "if", "options_or_check", "[", "1", "]", ".", "is_a?", "(", "Hash", ")", "options", "=", "options", ".", "merge", "(", "options_or_check", "[", "1", "]", ")", "end", "end", "unless", "check", "if", "block", "check", "=", "block", "else", "check", "=", "lookup_check", "(", "name", ",", "options", ")", "end", "end", "@filters", "<<", "Filter", ".", "new", "(", "name", ",", "check", ",", "options", "[", ":async", "]", ")", "end"], "docstring": "Add a status check to the handler.\n\n If a block is given, it will be used as the status check and will be yielded to\n with a Status object.\n\n If the name matches one of the pre-defined status check classes, a new instance will\n be created using the rest of the arguments as the arguments to the initializer. The\n pre-defined classes are:\n\n * :action_mailer - Check if the send mail configuration used by ActionMailer is available\n * :active_record - Check if the database connection for an ActiveRecord class is up\n * :dalli - DalliCheck checks if all the servers in a MemCache cluster are available using dalli\n * :directory - DirectoryCheck checks for the accessibilty of a file system directory\n * :ping - Check if a host is reachable and accepting connections on a port\n * :url - Check if a getting a URL returns a success response", "docstring_tokens": ["Add", "a", "status", "check", "to", "the", "handler", "."], "sha": "44645f8f676dd9fd25cff2d93cfdff0876cef36d", "url": "https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/handler.rb#L74-L99", "partition": "valid"} {"repo": "tribune/is_it_working", "path": "lib/is_it_working/handler.rb", "func_name": "IsItWorking.Handler.lookup_check", "original_string": "def lookup_check(name, options) #:nodoc:\n check_class_name = \"#{name.to_s.gsub(/(^|_)([a-z])/){|m| m.sub('_', '').upcase}}Check\"\n check = nil\n if IsItWorking.const_defined?(check_class_name)\n check_class = IsItWorking.const_get(check_class_name)\n check = check_class.new(options)\n else\n raise ArgumentError.new(\"Check not defined #{check_class_name}\")\n end\n check\n end", "language": "ruby", "code": "def lookup_check(name, options) #:nodoc:\n check_class_name = \"#{name.to_s.gsub(/(^|_)([a-z])/){|m| m.sub('_', '').upcase}}Check\"\n check = nil\n if IsItWorking.const_defined?(check_class_name)\n check_class = IsItWorking.const_get(check_class_name)\n check = check_class.new(options)\n else\n raise ArgumentError.new(\"Check not defined #{check_class_name}\")\n end\n check\n end", "code_tokens": ["def", "lookup_check", "(", "name", ",", "options", ")", "#:nodoc:", "check_class_name", "=", "\"#{name.to_s.gsub(/(^|_)([a-z])/){|m| m.sub('_', '').upcase}}Check\"", "check", "=", "nil", "if", "IsItWorking", ".", "const_defined?", "(", "check_class_name", ")", "check_class", "=", "IsItWorking", ".", "const_get", "(", "check_class_name", ")", "check", "=", "check_class", ".", "new", "(", "options", ")", "else", "raise", "ArgumentError", ".", "new", "(", "\"Check not defined #{check_class_name}\"", ")", "end", "check", "end"], "docstring": "Lookup a status check filter from the name and arguments", "docstring_tokens": ["Lookup", "a", "status", "check", "filter", "from", "the", "name", "and", "arguments"], "sha": "44645f8f676dd9fd25cff2d93cfdff0876cef36d", "url": "https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/handler.rb#L112-L122", "partition": "valid"} {"repo": "tribune/is_it_working", "path": "lib/is_it_working/handler.rb", "func_name": "IsItWorking.Handler.render", "original_string": "def render(statuses, elapsed_time) #:nodoc:\n fail = statuses.all?{|s| s.success?}\n headers = {\n \"Content-Type\" => \"text/plain; charset=utf8\",\n \"Cache-Control\" => \"no-cache\",\n \"Date\" => Time.now.httpdate,\n }\n \n messages = []\n statuses.each do |status|\n status.messages.each do |m|\n messages << \"#{m.ok? ? 'OK: ' : 'FAIL:'} #{status.name} - #{m.message} (#{status.time ? sprintf('%0.000f', status.time * 1000) : '?'}ms)\"\n end\n end\n \n info = []\n info << \"Host: #{@hostname}\" unless @hostname.size == 0\n info << \"PID: #{$$}\"\n info << \"Timestamp: #{Time.now.iso8601}\"\n info << \"Elapsed Time: #{(elapsed_time * 1000).round}ms\"\n \n code = (fail ? 200 : 500)\n \n [code, headers, [info.join(\"\\n\"), \"\\n\\n\", messages.join(\"\\n\")]]\n end", "language": "ruby", "code": "def render(statuses, elapsed_time) #:nodoc:\n fail = statuses.all?{|s| s.success?}\n headers = {\n \"Content-Type\" => \"text/plain; charset=utf8\",\n \"Cache-Control\" => \"no-cache\",\n \"Date\" => Time.now.httpdate,\n }\n \n messages = []\n statuses.each do |status|\n status.messages.each do |m|\n messages << \"#{m.ok? ? 'OK: ' : 'FAIL:'} #{status.name} - #{m.message} (#{status.time ? sprintf('%0.000f', status.time * 1000) : '?'}ms)\"\n end\n end\n \n info = []\n info << \"Host: #{@hostname}\" unless @hostname.size == 0\n info << \"PID: #{$$}\"\n info << \"Timestamp: #{Time.now.iso8601}\"\n info << \"Elapsed Time: #{(elapsed_time * 1000).round}ms\"\n \n code = (fail ? 200 : 500)\n \n [code, headers, [info.join(\"\\n\"), \"\\n\\n\", messages.join(\"\\n\")]]\n end", "code_tokens": ["def", "render", "(", "statuses", ",", "elapsed_time", ")", "#:nodoc:", "fail", "=", "statuses", ".", "all?", "{", "|", "s", "|", "s", ".", "success?", "}", "headers", "=", "{", "\"Content-Type\"", "=>", "\"text/plain; charset=utf8\"", ",", "\"Cache-Control\"", "=>", "\"no-cache\"", ",", "\"Date\"", "=>", "Time", ".", "now", ".", "httpdate", ",", "}", "messages", "=", "[", "]", "statuses", ".", "each", "do", "|", "status", "|", "status", ".", "messages", ".", "each", "do", "|", "m", "|", "messages", "<<", "\"#{m.ok? ? 'OK: ' : 'FAIL:'} #{status.name} - #{m.message} (#{status.time ? sprintf('%0.000f', status.time * 1000) : '?'}ms)\"", "end", "end", "info", "=", "[", "]", "info", "<<", "\"Host: #{@hostname}\"", "unless", "@hostname", ".", "size", "==", "0", "info", "<<", "\"PID: #{$$}\"", "info", "<<", "\"Timestamp: #{Time.now.iso8601}\"", "info", "<<", "\"Elapsed Time: #{(elapsed_time * 1000).round}ms\"", "code", "=", "(", "fail", "?", "200", ":", "500", ")", "[", "code", ",", "headers", ",", "[", "info", ".", "join", "(", "\"\\n\"", ")", ",", "\"\\n\\n\"", ",", "messages", ".", "join", "(", "\"\\n\"", ")", "]", "]", "end"], "docstring": "Output the plain text response from calling all the filters.", "docstring_tokens": ["Output", "the", "plain", "text", "response", "from", "calling", "all", "the", "filters", "."], "sha": "44645f8f676dd9fd25cff2d93cfdff0876cef36d", "url": "https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/handler.rb#L125-L149", "partition": "valid"} {"repo": "tribune/is_it_working", "path": "lib/is_it_working/checks/ping_check.rb", "func_name": "IsItWorking.PingCheck.call", "original_string": "def call(status)\n begin\n ping(@host, @port)\n status.ok(\"#{@alias} is accepting connections on port #{@port.inspect}\")\n rescue Errno::ECONNREFUSED\n status.fail(\"#{@alias} is not accepting connections on port #{@port.inspect}\")\n rescue SocketError => e\n status.fail(\"connection to #{@alias} on port #{@port.inspect} failed with '#{e.message}'\")\n rescue Timeout::Error\n status.fail(\"#{@alias} did not respond on port #{@port.inspect} within #{@timeout} seconds\")\n end\n end", "language": "ruby", "code": "def call(status)\n begin\n ping(@host, @port)\n status.ok(\"#{@alias} is accepting connections on port #{@port.inspect}\")\n rescue Errno::ECONNREFUSED\n status.fail(\"#{@alias} is not accepting connections on port #{@port.inspect}\")\n rescue SocketError => e\n status.fail(\"connection to #{@alias} on port #{@port.inspect} failed with '#{e.message}'\")\n rescue Timeout::Error\n status.fail(\"#{@alias} did not respond on port #{@port.inspect} within #{@timeout} seconds\")\n end\n end", "code_tokens": ["def", "call", "(", "status", ")", "begin", "ping", "(", "@host", ",", "@port", ")", "status", ".", "ok", "(", "\"#{@alias} is accepting connections on port #{@port.inspect}\"", ")", "rescue", "Errno", "::", "ECONNREFUSED", "status", ".", "fail", "(", "\"#{@alias} is not accepting connections on port #{@port.inspect}\"", ")", "rescue", "SocketError", "=>", "e", "status", ".", "fail", "(", "\"connection to #{@alias} on port #{@port.inspect} failed with '#{e.message}'\"", ")", "rescue", "Timeout", "::", "Error", "status", ".", "fail", "(", "\"#{@alias} did not respond on port #{@port.inspect} within #{@timeout} seconds\"", ")", "end", "end"], "docstring": "Check if a host is reachable and accepting connections on a specified port.\n\n The host and port to ping are specified with the :host and :port options. The port\n can be either a port number or port name for a well known port (i.e. \"smtp\" and 25 are\n equivalent). The default timeout to wait for a response is 2 seconds. This can be\n changed with the :timeout option.\n\n By default, the host name will be included in the output. If this could pose a security\n risk by making the existence of the host known to the world, you can supply the :alias\n option which will be used for output purposes. In general, you should supply this option\n unless the host is on a private network behind a firewall.\n\n === Example\n\n IsItWorking::Handler.new do |h|\n h.check :ping, :host => \"example.com\", :port => \"ftp\", :timeout => 4\n end", "docstring_tokens": ["Check", "if", "a", "host", "is", "reachable", "and", "accepting", "connections", "on", "a", "specified", "port", "."], "sha": "44645f8f676dd9fd25cff2d93cfdff0876cef36d", "url": "https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/checks/ping_check.rb#L32-L43", "partition": "valid"} {"repo": "LynxEyes/bootstrap_admin", "path": "lib/bootstrap_admin/controller_helpers.rb", "func_name": "BootstrapAdmin.ControllerHelpers.respond_to?", "original_string": "def respond_to? method, include_private = false\n true if bootstrap_admin_config.respond_to? method\n super method, include_private\n end", "language": "ruby", "code": "def respond_to? method, include_private = false\n true if bootstrap_admin_config.respond_to? method\n super method, include_private\n end", "code_tokens": ["def", "respond_to?", "method", ",", "include_private", "=", "false", "true", "if", "bootstrap_admin_config", ".", "respond_to?", "method", "super", "method", ",", "include_private", "end"], "docstring": "self responds_to bootstrap_admin_config methods via method_missing!", "docstring_tokens": ["self", "responds_to", "bootstrap_admin_config", "methods", "via", "method_missing!"], "sha": "f0f1b265a4f05bc65724c540b90a1f0425a772d8", "url": "https://github.com/LynxEyes/bootstrap_admin/blob/f0f1b265a4f05bc65724c540b90a1f0425a772d8/lib/bootstrap_admin/controller_helpers.rb#L69-L72", "partition": "valid"} {"repo": "tribune/is_it_working", "path": "lib/is_it_working/checks/url_check.rb", "func_name": "IsItWorking.UrlCheck.instantiate_http", "original_string": "def instantiate_http #:nodoc:\n http_class = nil\n\n if @proxy && @proxy[:host]\n http_class = Net::HTTP::Proxy(@proxy[:host], @proxy[:port], @proxy[:username], @proxy[:password])\n else\n http_class = Net::HTTP\n end\n\n http = http_class.new(@uri.host, @uri.port)\n if @uri.scheme == 'https'\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_PEER\n end\n http.open_timeout = @open_timeout\n http.read_timeout = @read_timeout\n\n return http\n end", "language": "ruby", "code": "def instantiate_http #:nodoc:\n http_class = nil\n\n if @proxy && @proxy[:host]\n http_class = Net::HTTP::Proxy(@proxy[:host], @proxy[:port], @proxy[:username], @proxy[:password])\n else\n http_class = Net::HTTP\n end\n\n http = http_class.new(@uri.host, @uri.port)\n if @uri.scheme == 'https'\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_PEER\n end\n http.open_timeout = @open_timeout\n http.read_timeout = @read_timeout\n\n return http\n end", "code_tokens": ["def", "instantiate_http", "#:nodoc:", "http_class", "=", "nil", "if", "@proxy", "&&", "@proxy", "[", ":host", "]", "http_class", "=", "Net", "::", "HTTP", "::", "Proxy", "(", "@proxy", "[", ":host", "]", ",", "@proxy", "[", ":port", "]", ",", "@proxy", "[", ":username", "]", ",", "@proxy", "[", ":password", "]", ")", "else", "http_class", "=", "Net", "::", "HTTP", "end", "http", "=", "http_class", ".", "new", "(", "@uri", ".", "host", ",", "@uri", ".", "port", ")", "if", "@uri", ".", "scheme", "==", "'https'", "http", ".", "use_ssl", "=", "true", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_PEER", "end", "http", ".", "open_timeout", "=", "@open_timeout", "http", ".", "read_timeout", "=", "@read_timeout", "return", "http", "end"], "docstring": "Create an HTTP object with the options set.", "docstring_tokens": ["Create", "an", "HTTP", "object", "with", "the", "options", "set", "."], "sha": "44645f8f676dd9fd25cff2d93cfdff0876cef36d", "url": "https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/checks/url_check.rb#L51-L69", "partition": "valid"} {"repo": "tribune/is_it_working", "path": "lib/is_it_working/checks/url_check.rb", "func_name": "IsItWorking.UrlCheck.perform_http_request", "original_string": "def perform_http_request #:nodoc:\n request = Net::HTTP::Get.new(@uri.request_uri, @headers)\n request.basic_auth(@username, @password) if @username || @password\n http = instantiate_http\n http.start do\n http.request(request)\n end\n end", "language": "ruby", "code": "def perform_http_request #:nodoc:\n request = Net::HTTP::Get.new(@uri.request_uri, @headers)\n request.basic_auth(@username, @password) if @username || @password\n http = instantiate_http\n http.start do\n http.request(request)\n end\n end", "code_tokens": ["def", "perform_http_request", "#:nodoc:", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "@uri", ".", "request_uri", ",", "@headers", ")", "request", ".", "basic_auth", "(", "@username", ",", "@password", ")", "if", "@username", "||", "@password", "http", "=", "instantiate_http", "http", ".", "start", "do", "http", ".", "request", "(", "request", ")", "end", "end"], "docstring": "Perform an HTTP request and return the response", "docstring_tokens": ["Perform", "an", "HTTP", "request", "and", "return", "the", "response"], "sha": "44645f8f676dd9fd25cff2d93cfdff0876cef36d", "url": "https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/checks/url_check.rb#L72-L79", "partition": "valid"} {"repo": "Undev/libftdi-ruby", "path": "lib/ftdi.rb", "func_name": "Ftdi.Context.usb_open", "original_string": "def usb_open(vendor, product)\n raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum)\n raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum)\n check_result(Ftdi.ftdi_usb_open(ctx, vendor, product))\n end", "language": "ruby", "code": "def usb_open(vendor, product)\n raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum)\n raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum)\n check_result(Ftdi.ftdi_usb_open(ctx, vendor, product))\n end", "code_tokens": ["def", "usb_open", "(", "vendor", ",", "product", ")", "raise", "ArgumentError", ".", "new", "(", "'vendor should be Fixnum'", ")", "unless", "vendor", ".", "kind_of?", "(", "Fixnum", ")", "raise", "ArgumentError", ".", "new", "(", "'product should be Fixnum'", ")", "unless", "product", ".", "kind_of?", "(", "Fixnum", ")", "check_result", "(", "Ftdi", ".", "ftdi_usb_open", "(", "ctx", ",", "vendor", ",", "product", ")", ")", "end"], "docstring": "Opens the first device with a given vendor and product ids.\n @param [Fixnum] vendor Vendor id.\n @param [Fixnum] product Product id.\n @return [NilClass] nil\n @raise [StatusCodeError] libftdi reports error.\n @raise [ArgumentError] Bad arguments.", "docstring_tokens": ["Opens", "the", "first", "device", "with", "a", "given", "vendor", "and", "product", "ids", "."], "sha": "6fe45a1580df6db08324a237f56d2136fe721dcc", "url": "https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L175-L179", "partition": "valid"} {"repo": "Undev/libftdi-ruby", "path": "lib/ftdi.rb", "func_name": "Ftdi.Context.usb_open_desc", "original_string": "def usb_open_desc(vendor, product, description, serial)\n raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum)\n raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum)\n check_result(Ftdi.ftdi_usb_open_desc(ctx, vendor, product, description, serial))\n end", "language": "ruby", "code": "def usb_open_desc(vendor, product, description, serial)\n raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum)\n raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum)\n check_result(Ftdi.ftdi_usb_open_desc(ctx, vendor, product, description, serial))\n end", "code_tokens": ["def", "usb_open_desc", "(", "vendor", ",", "product", ",", "description", ",", "serial", ")", "raise", "ArgumentError", ".", "new", "(", "'vendor should be Fixnum'", ")", "unless", "vendor", ".", "kind_of?", "(", "Fixnum", ")", "raise", "ArgumentError", ".", "new", "(", "'product should be Fixnum'", ")", "unless", "product", ".", "kind_of?", "(", "Fixnum", ")", "check_result", "(", "Ftdi", ".", "ftdi_usb_open_desc", "(", "ctx", ",", "vendor", ",", "product", ",", "description", ",", "serial", ")", ")", "end"], "docstring": "Opens the first device with a given vendor and product ids, description and serial.\n @param [Fixnum] vendor Vendor id.\n @param [Fixnum] product Product id.\n @param [String] description Description to search for. Use nil if not needed.\n @param [String] serial Serial to search for. Use nil if not needed.\n @return [NilClass] nil\n @raise [StatusCodeError] libftdi reports error.\n @raise [ArgumentError] Bad arguments.", "docstring_tokens": ["Opens", "the", "first", "device", "with", "a", "given", "vendor", "and", "product", "ids", "description", "and", "serial", "."], "sha": "6fe45a1580df6db08324a237f56d2136fe721dcc", "url": "https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L189-L193", "partition": "valid"} {"repo": "Undev/libftdi-ruby", "path": "lib/ftdi.rb", "func_name": "Ftdi.Context.usb_open_desc_index", "original_string": "def usb_open_desc_index(vendor, product, description, serial, index)\n raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum)\n raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum)\n raise ArgumentError.new('index should be Fixnum') unless index.kind_of?(Fixnum)\n raise ArgumentError.new('index should be greater than or equal to zero') if index < 0\n check_result(Ftdi.ftdi_usb_open_desc_index(ctx, vendor, product, description, serial, index))\n end", "language": "ruby", "code": "def usb_open_desc_index(vendor, product, description, serial, index)\n raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum)\n raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum)\n raise ArgumentError.new('index should be Fixnum') unless index.kind_of?(Fixnum)\n raise ArgumentError.new('index should be greater than or equal to zero') if index < 0\n check_result(Ftdi.ftdi_usb_open_desc_index(ctx, vendor, product, description, serial, index))\n end", "code_tokens": ["def", "usb_open_desc_index", "(", "vendor", ",", "product", ",", "description", ",", "serial", ",", "index", ")", "raise", "ArgumentError", ".", "new", "(", "'vendor should be Fixnum'", ")", "unless", "vendor", ".", "kind_of?", "(", "Fixnum", ")", "raise", "ArgumentError", ".", "new", "(", "'product should be Fixnum'", ")", "unless", "product", ".", "kind_of?", "(", "Fixnum", ")", "raise", "ArgumentError", ".", "new", "(", "'index should be Fixnum'", ")", "unless", "index", ".", "kind_of?", "(", "Fixnum", ")", "raise", "ArgumentError", ".", "new", "(", "'index should be greater than or equal to zero'", ")", "if", "index", "<", "0", "check_result", "(", "Ftdi", ".", "ftdi_usb_open_desc_index", "(", "ctx", ",", "vendor", ",", "product", ",", "description", ",", "serial", ",", "index", ")", ")", "end"], "docstring": "Opens the index-th device with a given vendor and product ids, description and serial.\n @param [Fixnum] vendor Vendor id.\n @param [Fixnum] product Product id.\n @param [String] description Description to search for. Use nil if not needed.\n @param [String] serial Serial to search for. Use nil if not needed.\n @param [Fixnum] index Number of matching device to open if there are more than one, starts with 0.\n @return [NilClass] nil\n @raise [StatusCodeError] libftdi reports error.\n @raise [ArgumentError] Bad arguments.", "docstring_tokens": ["Opens", "the", "index", "-", "th", "device", "with", "a", "given", "vendor", "and", "product", "ids", "description", "and", "serial", "."], "sha": "6fe45a1580df6db08324a237f56d2136fe721dcc", "url": "https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L204-L210", "partition": "valid"} {"repo": "Undev/libftdi-ruby", "path": "lib/ftdi.rb", "func_name": "Ftdi.Context.baudrate=", "original_string": "def baudrate=(new_baudrate)\n raise ArgumentError.new('baudrate should be Fixnum') unless new_baudrate.kind_of?(Fixnum)\n check_result(Ftdi.ftdi_set_baudrate(ctx, new_baudrate))\n end", "language": "ruby", "code": "def baudrate=(new_baudrate)\n raise ArgumentError.new('baudrate should be Fixnum') unless new_baudrate.kind_of?(Fixnum)\n check_result(Ftdi.ftdi_set_baudrate(ctx, new_baudrate))\n end", "code_tokens": ["def", "baudrate", "=", "(", "new_baudrate", ")", "raise", "ArgumentError", ".", "new", "(", "'baudrate should be Fixnum'", ")", "unless", "new_baudrate", ".", "kind_of?", "(", "Fixnum", ")", "check_result", "(", "Ftdi", ".", "ftdi_set_baudrate", "(", "ctx", ",", "new_baudrate", ")", ")", "end"], "docstring": "Sets the chip baud rate.\n @raise [StatusCodeError] libftdi reports error.\n @raise [ArgumentError] Bad arguments.\n @return [NilClass] nil", "docstring_tokens": ["Sets", "the", "chip", "baud", "rate", "."], "sha": "6fe45a1580df6db08324a237f56d2136fe721dcc", "url": "https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L236-L239", "partition": "valid"} {"repo": "Undev/libftdi-ruby", "path": "lib/ftdi.rb", "func_name": "Ftdi.Context.write_data_chunksize", "original_string": "def write_data_chunksize\n p = FFI::MemoryPointer.new(:uint, 1)\n check_result(Ftdi.ftdi_write_data_get_chunksize(ctx, p))\n p.read_uint\n end", "language": "ruby", "code": "def write_data_chunksize\n p = FFI::MemoryPointer.new(:uint, 1)\n check_result(Ftdi.ftdi_write_data_get_chunksize(ctx, p))\n p.read_uint\n end", "code_tokens": ["def", "write_data_chunksize", "p", "=", "FFI", "::", "MemoryPointer", ".", "new", "(", ":uint", ",", "1", ")", "check_result", "(", "Ftdi", ".", "ftdi_write_data_get_chunksize", "(", "ctx", ",", "p", ")", ")", "p", ".", "read_uint", "end"], "docstring": "Gets write buffer chunk size.\n @return [Fixnum] Write buffer chunk size.\n @raise [StatusCodeError] libftdi reports error.\n @see #write_data_chunksize=", "docstring_tokens": ["Gets", "write", "buffer", "chunk", "size", "."], "sha": "6fe45a1580df6db08324a237f56d2136fe721dcc", "url": "https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L289-L293", "partition": "valid"} {"repo": "Undev/libftdi-ruby", "path": "lib/ftdi.rb", "func_name": "Ftdi.Context.write_data", "original_string": "def write_data(bytes)\n bytes = bytes.pack('c*') if bytes.respond_to?(:pack)\n size = bytes.respond_to?(:bytesize) ? bytes.bytesize : bytes.size\n mem_buf = FFI::MemoryPointer.new(:char, size)\n mem_buf.put_bytes(0, bytes)\n bytes_written = Ftdi.ftdi_write_data(ctx, mem_buf, size)\n check_result(bytes_written)\n bytes_written\n end", "language": "ruby", "code": "def write_data(bytes)\n bytes = bytes.pack('c*') if bytes.respond_to?(:pack)\n size = bytes.respond_to?(:bytesize) ? bytes.bytesize : bytes.size\n mem_buf = FFI::MemoryPointer.new(:char, size)\n mem_buf.put_bytes(0, bytes)\n bytes_written = Ftdi.ftdi_write_data(ctx, mem_buf, size)\n check_result(bytes_written)\n bytes_written\n end", "code_tokens": ["def", "write_data", "(", "bytes", ")", "bytes", "=", "bytes", ".", "pack", "(", "'c*'", ")", "if", "bytes", ".", "respond_to?", "(", ":pack", ")", "size", "=", "bytes", ".", "respond_to?", "(", ":bytesize", ")", "?", "bytes", ".", "bytesize", ":", "bytes", ".", "size", "mem_buf", "=", "FFI", "::", "MemoryPointer", ".", "new", "(", ":char", ",", "size", ")", "mem_buf", ".", "put_bytes", "(", "0", ",", "bytes", ")", "bytes_written", "=", "Ftdi", ".", "ftdi_write_data", "(", "ctx", ",", "mem_buf", ",", "size", ")", "check_result", "(", "bytes_written", ")", "bytes_written", "end"], "docstring": "Writes data.\n @param [String, Array] bytes String or array of integers that will be interpreted as bytes using pack('c*').\n @return [Fixnum] Number of written bytes.\n @raise [StatusCodeError] libftdi reports error.", "docstring_tokens": ["Writes", "data", "."], "sha": "6fe45a1580df6db08324a237f56d2136fe721dcc", "url": "https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L310-L318", "partition": "valid"} {"repo": "Undev/libftdi-ruby", "path": "lib/ftdi.rb", "func_name": "Ftdi.Context.read_data_chunksize", "original_string": "def read_data_chunksize\n p = FFI::MemoryPointer.new(:uint, 1)\n check_result(Ftdi.ftdi_read_data_get_chunksize(ctx, p))\n p.read_uint\n end", "language": "ruby", "code": "def read_data_chunksize\n p = FFI::MemoryPointer.new(:uint, 1)\n check_result(Ftdi.ftdi_read_data_get_chunksize(ctx, p))\n p.read_uint\n end", "code_tokens": ["def", "read_data_chunksize", "p", "=", "FFI", "::", "MemoryPointer", ".", "new", "(", ":uint", ",", "1", ")", "check_result", "(", "Ftdi", ".", "ftdi_read_data_get_chunksize", "(", "ctx", ",", "p", ")", ")", "p", ".", "read_uint", "end"], "docstring": "Gets read buffer chunk size.\n @return [Fixnum] Read buffer chunk size.\n @raise [StatusCodeError] libftdi reports error.\n @see #read_data_chunksize=", "docstring_tokens": ["Gets", "read", "buffer", "chunk", "size", "."], "sha": "6fe45a1580df6db08324a237f56d2136fe721dcc", "url": "https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L324-L328", "partition": "valid"} {"repo": "Undev/libftdi-ruby", "path": "lib/ftdi.rb", "func_name": "Ftdi.Context.read_data", "original_string": "def read_data\n chunksize = read_data_chunksize\n p = FFI::MemoryPointer.new(:char, chunksize)\n bytes_read = Ftdi.ftdi_read_data(ctx, p, chunksize)\n check_result(bytes_read)\n r = p.read_bytes(bytes_read)\n r.force_encoding(\"ASCII-8BIT\") if r.respond_to?(:force_encoding)\n r\n end", "language": "ruby", "code": "def read_data\n chunksize = read_data_chunksize\n p = FFI::MemoryPointer.new(:char, chunksize)\n bytes_read = Ftdi.ftdi_read_data(ctx, p, chunksize)\n check_result(bytes_read)\n r = p.read_bytes(bytes_read)\n r.force_encoding(\"ASCII-8BIT\") if r.respond_to?(:force_encoding)\n r\n end", "code_tokens": ["def", "read_data", "chunksize", "=", "read_data_chunksize", "p", "=", "FFI", "::", "MemoryPointer", ".", "new", "(", ":char", ",", "chunksize", ")", "bytes_read", "=", "Ftdi", ".", "ftdi_read_data", "(", "ctx", ",", "p", ",", "chunksize", ")", "check_result", "(", "bytes_read", ")", "r", "=", "p", ".", "read_bytes", "(", "bytes_read", ")", "r", ".", "force_encoding", "(", "\"ASCII-8BIT\"", ")", "if", "r", ".", "respond_to?", "(", ":force_encoding", ")", "r", "end"], "docstring": "Reads data in chunks from the chip.\n Returns when at least one byte is available or when the latency timer has elapsed.\n Automatically strips the two modem status bytes transfered during every read.\n @return [String] Bytes read; Empty string if no bytes read.\n @see #read_data_chunksize\n @raise [StatusCodeError] libftdi reports error.", "docstring_tokens": ["Reads", "data", "in", "chunks", "from", "the", "chip", ".", "Returns", "when", "at", "least", "one", "byte", "is", "available", "or", "when", "the", "latency", "timer", "has", "elapsed", ".", "Automatically", "strips", "the", "two", "modem", "status", "bytes", "transfered", "during", "every", "read", "."], "sha": "6fe45a1580df6db08324a237f56d2136fe721dcc", "url": "https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L347-L355", "partition": "valid"} {"repo": "Undev/libftdi-ruby", "path": "lib/ftdi.rb", "func_name": "Ftdi.Context.read_pins", "original_string": "def read_pins\n p = FFI::MemoryPointer.new(:uchar, 1)\n check_result(Ftdi.ftdi_read_pins(ctx, p))\n p.read_uchar\n end", "language": "ruby", "code": "def read_pins\n p = FFI::MemoryPointer.new(:uchar, 1)\n check_result(Ftdi.ftdi_read_pins(ctx, p))\n p.read_uchar\n end", "code_tokens": ["def", "read_pins", "p", "=", "FFI", "::", "MemoryPointer", ".", "new", "(", ":uchar", ",", "1", ")", "check_result", "(", "Ftdi", ".", "ftdi_read_pins", "(", "ctx", ",", "p", ")", ")", "p", ".", "read_uchar", "end"], "docstring": "Directly read pin state, circumventing the read buffer. Useful for bitbang mode.\n @return [Fixnum] Pins state\n @raise [StatusCodeError] libftdi reports error.\n @see #set_bitmode", "docstring_tokens": ["Directly", "read", "pin", "state", "circumventing", "the", "read", "buffer", ".", "Useful", "for", "bitbang", "mode", "."], "sha": "6fe45a1580df6db08324a237f56d2136fe721dcc", "url": "https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L361-L365", "partition": "valid"} {"repo": "dark-panda/geos-extensions", "path": "lib/geos/google_maps/api_2.rb", "func_name": "Geos::GoogleMaps::Api2.Geometry.to_g_marker_api2", "original_string": "def to_g_marker_api2(marker_options = {}, options = {})\n klass = if options[:short_class]\n 'GMarker'\n else\n 'google.maps.Marker'\n end\n\n opts = Geos::Helper.camelize_keys(marker_options)\n\n \"new #{klass}(#{self.centroid.to_g_lat_lng(options)}, #{opts.to_json})\"\n end", "language": "ruby", "code": "def to_g_marker_api2(marker_options = {}, options = {})\n klass = if options[:short_class]\n 'GMarker'\n else\n 'google.maps.Marker'\n end\n\n opts = Geos::Helper.camelize_keys(marker_options)\n\n \"new #{klass}(#{self.centroid.to_g_lat_lng(options)}, #{opts.to_json})\"\n end", "code_tokens": ["def", "to_g_marker_api2", "(", "marker_options", "=", "{", "}", ",", "options", "=", "{", "}", ")", "klass", "=", "if", "options", "[", ":short_class", "]", "'GMarker'", "else", "'google.maps.Marker'", "end", "opts", "=", "Geos", "::", "Helper", ".", "camelize_keys", "(", "marker_options", ")", "\"new #{klass}(#{self.centroid.to_g_lat_lng(options)}, #{opts.to_json})\"", "end"], "docstring": "Returns a new GMarker at the centroid of the geometry. The options\n Hash works the same as the Google Maps API GMarkerOptions class does,\n but allows for underscored Ruby-like options which are then converted\n to the appropriate camel-cased Javascript options.", "docstring_tokens": ["Returns", "a", "new", "GMarker", "at", "the", "centroid", "of", "the", "geometry", ".", "The", "options", "Hash", "works", "the", "same", "as", "the", "Google", "Maps", "API", "GMarkerOptions", "class", "does", "but", "allows", "for", "underscored", "Ruby", "-", "like", "options", "which", "are", "then", "converted", "to", "the", "appropriate", "camel", "-", "cased", "Javascript", "options", "."], "sha": "59b4b84bbed0d551b696dbea909f26f8aca50498", "url": "https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/google_maps/api_2.rb#L39-L49", "partition": "valid"} {"repo": "dark-panda/geos-extensions", "path": "lib/geos/google_maps/api_2.rb", "func_name": "Geos::GoogleMaps::Api2.CoordinateSequence.to_g_polyline_api2", "original_string": "def to_g_polyline_api2(polyline_options = {}, options = {})\n klass = if options[:short_class]\n 'GPolyline'\n else\n 'google.maps.Polyline'\n end\n\n poly_opts = if polyline_options[:polyline_options]\n Geos::Helper.camelize_keys(polyline_options[:polyline_options])\n end\n\n args = [\n (polyline_options[:color] ? \"'#{Geos::Helper.escape_javascript(polyline_options[:color])}'\" : 'null'),\n (polyline_options[:weight] || 'null'),\n (polyline_options[:opacity] || 'null'),\n (poly_opts ? poly_opts.to_json : 'null')\n ].join(', ')\n\n \"new #{klass}([#{self.to_g_lat_lng(options).join(', ')}], #{args})\"\n end", "language": "ruby", "code": "def to_g_polyline_api2(polyline_options = {}, options = {})\n klass = if options[:short_class]\n 'GPolyline'\n else\n 'google.maps.Polyline'\n end\n\n poly_opts = if polyline_options[:polyline_options]\n Geos::Helper.camelize_keys(polyline_options[:polyline_options])\n end\n\n args = [\n (polyline_options[:color] ? \"'#{Geos::Helper.escape_javascript(polyline_options[:color])}'\" : 'null'),\n (polyline_options[:weight] || 'null'),\n (polyline_options[:opacity] || 'null'),\n (poly_opts ? poly_opts.to_json : 'null')\n ].join(', ')\n\n \"new #{klass}([#{self.to_g_lat_lng(options).join(', ')}], #{args})\"\n end", "code_tokens": ["def", "to_g_polyline_api2", "(", "polyline_options", "=", "{", "}", ",", "options", "=", "{", "}", ")", "klass", "=", "if", "options", "[", ":short_class", "]", "'GPolyline'", "else", "'google.maps.Polyline'", "end", "poly_opts", "=", "if", "polyline_options", "[", ":polyline_options", "]", "Geos", "::", "Helper", ".", "camelize_keys", "(", "polyline_options", "[", ":polyline_options", "]", ")", "end", "args", "=", "[", "(", "polyline_options", "[", ":color", "]", "?", "\"'#{Geos::Helper.escape_javascript(polyline_options[:color])}'\"", ":", "'null'", ")", ",", "(", "polyline_options", "[", ":weight", "]", "||", "'null'", ")", ",", "(", "polyline_options", "[", ":opacity", "]", "||", "'null'", ")", ",", "(", "poly_opts", "?", "poly_opts", ".", "to_json", ":", "'null'", ")", "]", ".", "join", "(", "', '", ")", "\"new #{klass}([#{self.to_g_lat_lng(options).join(', ')}], #{args})\"", "end"], "docstring": "Returns a new GPolyline. Note that this GPolyline just uses whatever\n coordinates are found in the sequence in order, so it might not\n make much sense at all.\n\n The options Hash follows the Google Maps API arguments to the\n GPolyline constructor and include :color, :weight, :opacity and\n :options. 'null' is used in place of any unset options.", "docstring_tokens": ["Returns", "a", "new", "GPolyline", ".", "Note", "that", "this", "GPolyline", "just", "uses", "whatever", "coordinates", "are", "found", "in", "the", "sequence", "in", "order", "so", "it", "might", "not", "make", "much", "sense", "at", "all", "."], "sha": "59b4b84bbed0d551b696dbea909f26f8aca50498", "url": "https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/google_maps/api_2.rb#L73-L92", "partition": "valid"} {"repo": "dark-panda/geos-extensions", "path": "lib/geos/google_maps/api_2.rb", "func_name": "Geos::GoogleMaps::Api2.CoordinateSequence.to_g_polygon_api2", "original_string": "def to_g_polygon_api2(polygon_options = {}, options = {})\n klass = if options[:short_class]\n 'GPolygon'\n else\n 'google.maps.Polygon'\n end\n\n poly_opts = if polygon_options[:polygon_options]\n Geos::Helper.camelize_keys(polygon_options[:polygon_options])\n end\n\n args = [\n (polygon_options[:stroke_color] ? \"'#{Geos::Helper.escape_javascript(polygon_options[:stroke_color])}'\" : 'null'),\n (polygon_options[:stroke_weight] || 'null'),\n (polygon_options[:stroke_opacity] || 'null'),\n (polygon_options[:fill_color] ? \"'#{Geos::Helper.escape_javascript(polygon_options[:fill_color])}'\" : 'null'),\n (polygon_options[:fill_opacity] || 'null'),\n (poly_opts ? poly_opts.to_json : 'null')\n ].join(', ')\n \"new #{klass}([#{self.to_g_lat_lng_api2(options).join(', ')}], #{args})\"\n end", "language": "ruby", "code": "def to_g_polygon_api2(polygon_options = {}, options = {})\n klass = if options[:short_class]\n 'GPolygon'\n else\n 'google.maps.Polygon'\n end\n\n poly_opts = if polygon_options[:polygon_options]\n Geos::Helper.camelize_keys(polygon_options[:polygon_options])\n end\n\n args = [\n (polygon_options[:stroke_color] ? \"'#{Geos::Helper.escape_javascript(polygon_options[:stroke_color])}'\" : 'null'),\n (polygon_options[:stroke_weight] || 'null'),\n (polygon_options[:stroke_opacity] || 'null'),\n (polygon_options[:fill_color] ? \"'#{Geos::Helper.escape_javascript(polygon_options[:fill_color])}'\" : 'null'),\n (polygon_options[:fill_opacity] || 'null'),\n (poly_opts ? poly_opts.to_json : 'null')\n ].join(', ')\n \"new #{klass}([#{self.to_g_lat_lng_api2(options).join(', ')}], #{args})\"\n end", "code_tokens": ["def", "to_g_polygon_api2", "(", "polygon_options", "=", "{", "}", ",", "options", "=", "{", "}", ")", "klass", "=", "if", "options", "[", ":short_class", "]", "'GPolygon'", "else", "'google.maps.Polygon'", "end", "poly_opts", "=", "if", "polygon_options", "[", ":polygon_options", "]", "Geos", "::", "Helper", ".", "camelize_keys", "(", "polygon_options", "[", ":polygon_options", "]", ")", "end", "args", "=", "[", "(", "polygon_options", "[", ":stroke_color", "]", "?", "\"'#{Geos::Helper.escape_javascript(polygon_options[:stroke_color])}'\"", ":", "'null'", ")", ",", "(", "polygon_options", "[", ":stroke_weight", "]", "||", "'null'", ")", ",", "(", "polygon_options", "[", ":stroke_opacity", "]", "||", "'null'", ")", ",", "(", "polygon_options", "[", ":fill_color", "]", "?", "\"'#{Geos::Helper.escape_javascript(polygon_options[:fill_color])}'\"", ":", "'null'", ")", ",", "(", "polygon_options", "[", ":fill_opacity", "]", "||", "'null'", ")", ",", "(", "poly_opts", "?", "poly_opts", ".", "to_json", ":", "'null'", ")", "]", ".", "join", "(", "', '", ")", "\"new #{klass}([#{self.to_g_lat_lng_api2(options).join(', ')}], #{args})\"", "end"], "docstring": "Returns a new GPolygon. Note that this GPolygon just uses whatever\n coordinates are found in the sequence in order, so it might not\n make much sense at all.\n\n The options Hash follows the Google Maps API arguments to the\n GPolygon constructor and include :stroke_color, :stroke_weight,\n :stroke_opacity, :fill_color, :fill_opacity and :options. 'null' is\n used in place of any unset options.", "docstring_tokens": ["Returns", "a", "new", "GPolygon", ".", "Note", "that", "this", "GPolygon", "just", "uses", "whatever", "coordinates", "are", "found", "in", "the", "sequence", "in", "order", "so", "it", "might", "not", "make", "much", "sense", "at", "all", "."], "sha": "59b4b84bbed0d551b696dbea909f26f8aca50498", "url": "https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/google_maps/api_2.rb#L102-L122", "partition": "valid"} {"repo": "dark-panda/geos-extensions", "path": "lib/geos/geometry.rb", "func_name": "Geos.Geometry.to_bbox", "original_string": "def to_bbox(long_or_short_names = :long)\n case long_or_short_names\n when :long\n {\n :north => self.north,\n :east => self.east,\n :south => self.south,\n :west => self.west\n }\n when :short\n {\n :n => self.north,\n :e => self.east,\n :s => self.south,\n :w => self.west\n }\n else\n raise ArgumentError.new(\"Expected either :long or :short for long_or_short_names argument\")\n end\n end", "language": "ruby", "code": "def to_bbox(long_or_short_names = :long)\n case long_or_short_names\n when :long\n {\n :north => self.north,\n :east => self.east,\n :south => self.south,\n :west => self.west\n }\n when :short\n {\n :n => self.north,\n :e => self.east,\n :s => self.south,\n :w => self.west\n }\n else\n raise ArgumentError.new(\"Expected either :long or :short for long_or_short_names argument\")\n end\n end", "code_tokens": ["def", "to_bbox", "(", "long_or_short_names", "=", ":long", ")", "case", "long_or_short_names", "when", ":long", "{", ":north", "=>", "self", ".", "north", ",", ":east", "=>", "self", ".", "east", ",", ":south", "=>", "self", ".", "south", ",", ":west", "=>", "self", ".", "west", "}", "when", ":short", "{", ":n", "=>", "self", ".", "north", ",", ":e", "=>", "self", ".", "east", ",", ":s", "=>", "self", ".", "south", ",", ":w", "=>", "self", ".", "west", "}", "else", "raise", "ArgumentError", ".", "new", "(", "\"Expected either :long or :short for long_or_short_names argument\"", ")", "end", "end"], "docstring": "Spits out a Hash containing the cardinal points that describe the\n Geometry's bbox.", "docstring_tokens": ["Spits", "out", "a", "Hash", "containing", "the", "cardinal", "points", "that", "describe", "the", "Geometry", "s", "bbox", "."], "sha": "59b4b84bbed0d551b696dbea909f26f8aca50498", "url": "https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/geometry.rb#L226-L245", "partition": "valid"} {"repo": "dark-panda/geos-extensions", "path": "lib/geos/point.rb", "func_name": "Geos.Point.to_georss", "original_string": "def to_georss(*args)\n xml = Geos::Helper.xml_options(*args)[0]\n xml.georss(:where) do\n xml.gml(:Point) do\n xml.gml(:pos, \"#{self.lat} #{self.lng}\")\n end\n end\n end", "language": "ruby", "code": "def to_georss(*args)\n xml = Geos::Helper.xml_options(*args)[0]\n xml.georss(:where) do\n xml.gml(:Point) do\n xml.gml(:pos, \"#{self.lat} #{self.lng}\")\n end\n end\n end", "code_tokens": ["def", "to_georss", "(", "*", "args", ")", "xml", "=", "Geos", "::", "Helper", ".", "xml_options", "(", "args", ")", "[", "0", "]", "xml", ".", "georss", "(", ":where", ")", "do", "xml", ".", "gml", "(", ":Point", ")", "do", "xml", ".", "gml", "(", ":pos", ",", "\"#{self.lat} #{self.lng}\"", ")", "end", "end", "end"], "docstring": "Build some XmlMarkup for GeoRSS. You should include the\n appropriate georss and gml XML namespaces in your document.", "docstring_tokens": ["Build", "some", "XmlMarkup", "for", "GeoRSS", ".", "You", "should", "include", "the", "appropriate", "georss", "and", "gml", "XML", "namespaces", "in", "your", "document", "."], "sha": "59b4b84bbed0d551b696dbea909f26f8aca50498", "url": "https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/point.rb#L93-L100", "partition": "valid"} {"repo": "dark-panda/geos-extensions", "path": "lib/geos/google_maps/api_3.rb", "func_name": "Geos::GoogleMaps.Api3::Geometry.to_g_marker_api3", "original_string": "def to_g_marker_api3(marker_options = {}, options = {})\n options = {\n :escape => [],\n :lat_lng_options => {}\n }.merge(options)\n\n opts = Geos::Helper.camelize_keys(marker_options)\n opts[:position] = self.centroid.to_g_lat_lng(options[:lat_lng_options])\n json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_MARKER_OPTIONS - options[:escape])\n\n \"new google.maps.Marker(#{json})\"\n end", "language": "ruby", "code": "def to_g_marker_api3(marker_options = {}, options = {})\n options = {\n :escape => [],\n :lat_lng_options => {}\n }.merge(options)\n\n opts = Geos::Helper.camelize_keys(marker_options)\n opts[:position] = self.centroid.to_g_lat_lng(options[:lat_lng_options])\n json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_MARKER_OPTIONS - options[:escape])\n\n \"new google.maps.Marker(#{json})\"\n end", "code_tokens": ["def", "to_g_marker_api3", "(", "marker_options", "=", "{", "}", ",", "options", "=", "{", "}", ")", "options", "=", "{", ":escape", "=>", "[", "]", ",", ":lat_lng_options", "=>", "{", "}", "}", ".", "merge", "(", "options", ")", "opts", "=", "Geos", "::", "Helper", ".", "camelize_keys", "(", "marker_options", ")", "opts", "[", ":position", "]", "=", "self", ".", "centroid", ".", "to_g_lat_lng", "(", "options", "[", ":lat_lng_options", "]", ")", "json", "=", "Geos", "::", "Helper", ".", "escape_json", "(", "opts", ",", "Geos", "::", "GoogleMaps", "::", "Api3Constants", "::", "UNESCAPED_MARKER_OPTIONS", "-", "options", "[", ":escape", "]", ")", "\"new google.maps.Marker(#{json})\"", "end"], "docstring": "Returns a new Marker at the centroid of the geometry. The options\n Hash works the same as the Google Maps API MarkerOptions class does,\n but allows for underscored Ruby-like options which are then converted\n to the appropriate camel-cased Javascript options.", "docstring_tokens": ["Returns", "a", "new", "Marker", "at", "the", "centroid", "of", "the", "geometry", ".", "The", "options", "Hash", "works", "the", "same", "as", "the", "Google", "Maps", "API", "MarkerOptions", "class", "does", "but", "allows", "for", "underscored", "Ruby", "-", "like", "options", "which", "are", "then", "converted", "to", "the", "appropriate", "camel", "-", "cased", "Javascript", "options", "."], "sha": "59b4b84bbed0d551b696dbea909f26f8aca50498", "url": "https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/google_maps/api_3.rb#L63-L74", "partition": "valid"} {"repo": "dark-panda/geos-extensions", "path": "lib/geos/google_maps/api_3.rb", "func_name": "Geos::GoogleMaps.Api3::CoordinateSequence.to_g_polyline_api3", "original_string": "def to_g_polyline_api3(polyline_options = {}, options = {})\n options = {\n :escape => [],\n :lat_lng_options => {}\n }.merge(options)\n\n opts = Geos::Helper.camelize_keys(polyline_options)\n opts[:path] = \"[#{self.to_g_lat_lng_api3(options[:lat_lng_options]).join(', ')}]\"\n json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_POLY_OPTIONS - options[:escape])\n\n \"new google.maps.Polyline(#{json})\"\n end", "language": "ruby", "code": "def to_g_polyline_api3(polyline_options = {}, options = {})\n options = {\n :escape => [],\n :lat_lng_options => {}\n }.merge(options)\n\n opts = Geos::Helper.camelize_keys(polyline_options)\n opts[:path] = \"[#{self.to_g_lat_lng_api3(options[:lat_lng_options]).join(', ')}]\"\n json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_POLY_OPTIONS - options[:escape])\n\n \"new google.maps.Polyline(#{json})\"\n end", "code_tokens": ["def", "to_g_polyline_api3", "(", "polyline_options", "=", "{", "}", ",", "options", "=", "{", "}", ")", "options", "=", "{", ":escape", "=>", "[", "]", ",", ":lat_lng_options", "=>", "{", "}", "}", ".", "merge", "(", "options", ")", "opts", "=", "Geos", "::", "Helper", ".", "camelize_keys", "(", "polyline_options", ")", "opts", "[", ":path", "]", "=", "\"[#{self.to_g_lat_lng_api3(options[:lat_lng_options]).join(', ')}]\"", "json", "=", "Geos", "::", "Helper", ".", "escape_json", "(", "opts", ",", "Geos", "::", "GoogleMaps", "::", "Api3Constants", "::", "UNESCAPED_POLY_OPTIONS", "-", "options", "[", ":escape", "]", ")", "\"new google.maps.Polyline(#{json})\"", "end"], "docstring": "Returns a new Polyline. Note that this Polyline just uses whatever\n coordinates are found in the sequence in order, so it might not\n make much sense at all.\n\n The polyline_options Hash follows the Google Maps API arguments to the\n Polyline constructor and include :clickable, :geodesic, :map, etc. See\n the Google Maps API documentation for details.\n\n The options Hash allows you to specify if certain arguments should be\n escaped on output. Usually the options in UNESCAPED_POLY_OPTIONS are\n escaped, but if for some reason you want some other options to be\n escaped, pass them along in options[:escape]. The options Hash also\n passes along options to to_g_lat_lng_api3.", "docstring_tokens": ["Returns", "a", "new", "Polyline", ".", "Note", "that", "this", "Polyline", "just", "uses", "whatever", "coordinates", "are", "found", "in", "the", "sequence", "in", "order", "so", "it", "might", "not", "make", "much", "sense", "at", "all", "."], "sha": "59b4b84bbed0d551b696dbea909f26f8aca50498", "url": "https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/google_maps/api_3.rb#L98-L109", "partition": "valid"} {"repo": "dark-panda/geos-extensions", "path": "lib/geos/coordinate_sequence.rb", "func_name": "Geos.CoordinateSequence.to_georss", "original_string": "def to_georss(*args)\n xml = Geos::Helper.xml_options(*args)[0]\n\n xml.georss(:where) do\n xml.gml(:LineString) do\n xml.gml(:posList) do\n xml << self.to_a.collect do |p|\n \"#{p[1]} #{p[0]}\"\n end.join(' ')\n end\n end\n end\n end", "language": "ruby", "code": "def to_georss(*args)\n xml = Geos::Helper.xml_options(*args)[0]\n\n xml.georss(:where) do\n xml.gml(:LineString) do\n xml.gml(:posList) do\n xml << self.to_a.collect do |p|\n \"#{p[1]} #{p[0]}\"\n end.join(' ')\n end\n end\n end\n end", "code_tokens": ["def", "to_georss", "(", "*", "args", ")", "xml", "=", "Geos", "::", "Helper", ".", "xml_options", "(", "args", ")", "[", "0", "]", "xml", ".", "georss", "(", ":where", ")", "do", "xml", ".", "gml", "(", ":LineString", ")", "do", "xml", ".", "gml", "(", ":posList", ")", "do", "xml", "<<", "self", ".", "to_a", ".", "collect", "do", "|", "p", "|", "\"#{p[1]} #{p[0]}\"", "end", ".", "join", "(", "' '", ")", "end", "end", "end", "end"], "docstring": "Build some XmlMarkup for GeoRSS GML. You should include the\n appropriate georss and gml XML namespaces in your document.", "docstring_tokens": ["Build", "some", "XmlMarkup", "for", "GeoRSS", "GML", ".", "You", "should", "include", "the", "appropriate", "georss", "and", "gml", "XML", "namespaces", "in", "your", "document", "."], "sha": "59b4b84bbed0d551b696dbea909f26f8aca50498", "url": "https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/coordinate_sequence.rb#L27-L39", "partition": "valid"} {"repo": "ngelx/solidus_import_products", "path": "app/services/solidus_import_products/process_row.rb", "func_name": "SolidusImportProducts.ProcessRow.convert_to_price", "original_string": "def convert_to_price(price_str)\n raise SolidusImportProducts::Exception::InvalidPrice unless price_str\n punt = price_str.index('.')\n coma = price_str.index(',')\n if !coma.nil? && !punt.nil?\n price_str.gsub!(punt < coma ? '.' : ',', '')\n end\n price_str.tr(',', '.').to_f\n end", "language": "ruby", "code": "def convert_to_price(price_str)\n raise SolidusImportProducts::Exception::InvalidPrice unless price_str\n punt = price_str.index('.')\n coma = price_str.index(',')\n if !coma.nil? && !punt.nil?\n price_str.gsub!(punt < coma ? '.' : ',', '')\n end\n price_str.tr(',', '.').to_f\n end", "code_tokens": ["def", "convert_to_price", "(", "price_str", ")", "raise", "SolidusImportProducts", "::", "Exception", "::", "InvalidPrice", "unless", "price_str", "punt", "=", "price_str", ".", "index", "(", "'.'", ")", "coma", "=", "price_str", ".", "index", "(", "','", ")", "if", "!", "coma", ".", "nil?", "&&", "!", "punt", ".", "nil?", "price_str", ".", "gsub!", "(", "punt", "<", "coma", "?", "'.'", ":", "','", ",", "''", ")", "end", "price_str", ".", "tr", "(", "','", ",", "'.'", ")", ".", "to_f", "end"], "docstring": "Special process of prices because of locales and different decimal separator characters.\n We want to get a format with dot as decimal separator and without thousand separator", "docstring_tokens": ["Special", "process", "of", "prices", "because", "of", "locales", "and", "different", "decimal", "separator", "characters", ".", "We", "want", "to", "get", "a", "format", "with", "dot", "as", "decimal", "separator", "and", "without", "thousand", "separator"], "sha": "643ce2a38c0c0ee26c8919e630ad7dad0adc568a", "url": "https://github.com/ngelx/solidus_import_products/blob/643ce2a38c0c0ee26c8919e630ad7dad0adc568a/app/services/solidus_import_products/process_row.rb#L83-L91", "partition": "valid"} {"repo": "westernmilling/synchronized_model", "path": "lib/synchronized_model/support.rb", "func_name": "SynchronizedModel.Support.matches", "original_string": "def matches(regexp, word)\n if regexp.respond_to?(:match?)\n regexp.match?(word)\n else\n regexp.match(word)\n end\n end", "language": "ruby", "code": "def matches(regexp, word)\n if regexp.respond_to?(:match?)\n regexp.match?(word)\n else\n regexp.match(word)\n end\n end", "code_tokens": ["def", "matches", "(", "regexp", ",", "word", ")", "if", "regexp", ".", "respond_to?", "(", ":match?", ")", "regexp", ".", "match?", "(", "word", ")", "else", "regexp", ".", "match", "(", "word", ")", "end", "end"], "docstring": "`match?` was added in Ruby 2.4 this allows us to be backwards\n compatible with older Ruby versions", "docstring_tokens": ["match?", "was", "added", "in", "Ruby", "2", ".", "4", "this", "allows", "us", "to", "be", "backwards", "compatible", "with", "older", "Ruby", "versions"], "sha": "f181f3d451ff94d25613232948e762f55292c51b", "url": "https://github.com/westernmilling/synchronized_model/blob/f181f3d451ff94d25613232948e762f55292c51b/lib/synchronized_model/support.rb#L22-L28", "partition": "valid"} {"repo": "dark-panda/geos-extensions", "path": "lib/geos/polygon.rb", "func_name": "Geos.Polygon.dump_points", "original_string": "def dump_points(cur_path = [])\n points = [ self.exterior_ring.dump_points ]\n\n self.interior_rings.each do |ring|\n points.push(ring.dump_points)\n end\n\n cur_path.concat(points)\n end", "language": "ruby", "code": "def dump_points(cur_path = [])\n points = [ self.exterior_ring.dump_points ]\n\n self.interior_rings.each do |ring|\n points.push(ring.dump_points)\n end\n\n cur_path.concat(points)\n end", "code_tokens": ["def", "dump_points", "(", "cur_path", "=", "[", "]", ")", "points", "=", "[", "self", ".", "exterior_ring", ".", "dump_points", "]", "self", ".", "interior_rings", ".", "each", "do", "|", "ring", "|", "points", ".", "push", "(", "ring", ".", "dump_points", ")", "end", "cur_path", ".", "concat", "(", "points", ")", "end"], "docstring": "Dumps points similarly to the PostGIS `ST_DumpPoints` function.", "docstring_tokens": ["Dumps", "points", "similarly", "to", "the", "PostGIS", "ST_DumpPoints", "function", "."], "sha": "59b4b84bbed0d551b696dbea909f26f8aca50498", "url": "https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/polygon.rb#L160-L168", "partition": "valid"} {"repo": "contently/prune_ar", "path": "lib/prune_ar/foreign_key_handler.rb", "func_name": "PruneAr.ForeignKeyHandler.generate_belongs_to_foreign_key_name", "original_string": "def generate_belongs_to_foreign_key_name(assoc)\n source = assoc.source_table[0..7]\n column = assoc.foreign_key_column[0..7]\n destination = assoc.destination_table[0..7]\n \"fk_#{source}_#{column}_#{destination}_#{SecureRandom.hex}\"\n end", "language": "ruby", "code": "def generate_belongs_to_foreign_key_name(assoc)\n source = assoc.source_table[0..7]\n column = assoc.foreign_key_column[0..7]\n destination = assoc.destination_table[0..7]\n \"fk_#{source}_#{column}_#{destination}_#{SecureRandom.hex}\"\n end", "code_tokens": ["def", "generate_belongs_to_foreign_key_name", "(", "assoc", ")", "source", "=", "assoc", ".", "source_table", "[", "0", "..", "7", "]", "column", "=", "assoc", ".", "foreign_key_column", "[", "0", "..", "7", "]", "destination", "=", "assoc", ".", "destination_table", "[", "0", "..", "7", "]", "\"fk_#{source}_#{column}_#{destination}_#{SecureRandom.hex}\"", "end"], "docstring": "Limited to 64 characters", "docstring_tokens": ["Limited", "to", "64", "characters"], "sha": "7e2a7e0680cfd445a2b726b46175f1b35e31b17a", "url": "https://github.com/contently/prune_ar/blob/7e2a7e0680cfd445a2b726b46175f1b35e31b17a/lib/prune_ar/foreign_key_handler.rb#L77-L82", "partition": "valid"} {"repo": "a14m/EGP-Rates", "path": "lib/egp_rates/cib.rb", "func_name": "EGPRates.CIB.raw_exchange_rates", "original_string": "def raw_exchange_rates\n req = Net::HTTP::Post.new(@uri, 'Content-Type' => 'application/json')\n req.body = { lang: :en }.to_json\n response = Net::HTTP.start(@uri.hostname, @uri.port) do |http|\n http.request(req)\n end\n fail ResponseError, response.code unless response.is_a? Net::HTTPSuccess\n response = JSON.parse(response.body)\n\n # CIB provide 6 currencies only\n unless response['d'] && response['d'].size >= 6\n fail ResponseError, \"Unknown JSON #{response}\"\n end\n\n response\n rescue JSON::ParserError\n raise ResponseError, \"Unknown JSON: #{response.body}\"\n end", "language": "ruby", "code": "def raw_exchange_rates\n req = Net::HTTP::Post.new(@uri, 'Content-Type' => 'application/json')\n req.body = { lang: :en }.to_json\n response = Net::HTTP.start(@uri.hostname, @uri.port) do |http|\n http.request(req)\n end\n fail ResponseError, response.code unless response.is_a? Net::HTTPSuccess\n response = JSON.parse(response.body)\n\n # CIB provide 6 currencies only\n unless response['d'] && response['d'].size >= 6\n fail ResponseError, \"Unknown JSON #{response}\"\n end\n\n response\n rescue JSON::ParserError\n raise ResponseError, \"Unknown JSON: #{response.body}\"\n end", "code_tokens": ["def", "raw_exchange_rates", "req", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "@uri", ",", "'Content-Type'", "=>", "'application/json'", ")", "req", ".", "body", "=", "{", "lang", ":", ":en", "}", ".", "to_json", "response", "=", "Net", "::", "HTTP", ".", "start", "(", "@uri", ".", "hostname", ",", "@uri", ".", "port", ")", "do", "|", "http", "|", "http", ".", "request", "(", "req", ")", "end", "fail", "ResponseError", ",", "response", ".", "code", "unless", "response", ".", "is_a?", "Net", "::", "HTTPSuccess", "response", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", "# CIB provide 6 currencies only", "unless", "response", "[", "'d'", "]", "&&", "response", "[", "'d'", "]", ".", "size", ">=", "6", "fail", "ResponseError", ",", "\"Unknown JSON #{response}\"", "end", "response", "rescue", "JSON", "::", "ParserError", "raise", "ResponseError", ",", "\"Unknown JSON: #{response.body}\"", "end"], "docstring": "Send the request to URL and return the JSON response\n @return [Hash] JSON response of the exchange rates\n {\n \"d\"=> [\n {\n \"__type\"=>\"LINKDev.CIB.CurrenciesFunds.CIBFund.CurrencyObject\",\n \"CurrencyID\"=>\"USD\",\n \"BuyRate\"=>15.9,\n \"SellRate\"=>16.05\n }, {\n \"__type\"=>\"LINKDev.CIB.CurrenciesFunds.CIBFund.CurrencyObject\",\n \"CurrencyID\"=>\"EUR\",\n \"BuyRate\"=>17.1904,\n \"SellRate\"=>17.5234\n }, {\n ...\n }\n ]\n }", "docstring_tokens": ["Send", "the", "request", "to", "URL", "and", "return", "the", "JSON", "response"], "sha": "ebb960c8cae62c5823aef50bb4121397276c7af6", "url": "https://github.com/a14m/EGP-Rates/blob/ebb960c8cae62c5823aef50bb4121397276c7af6/lib/egp_rates/cib.rb#L40-L57", "partition": "valid"} {"repo": "nicolasdespres/respect", "path": "lib/respect/format_validator.rb", "func_name": "Respect.FormatValidator.validate_ipv4_addr", "original_string": "def validate_ipv4_addr(value)\n ipaddr = IPAddr.new(value)\n unless ipaddr.ipv4?\n raise ValidationError, \"IP address '#{value}' is not IPv4\"\n end\n ipaddr\n rescue ArgumentError => e\n raise ValidationError, \"invalid IPv4 address '#{value}' - #{e.message}\"\n end", "language": "ruby", "code": "def validate_ipv4_addr(value)\n ipaddr = IPAddr.new(value)\n unless ipaddr.ipv4?\n raise ValidationError, \"IP address '#{value}' is not IPv4\"\n end\n ipaddr\n rescue ArgumentError => e\n raise ValidationError, \"invalid IPv4 address '#{value}' - #{e.message}\"\n end", "code_tokens": ["def", "validate_ipv4_addr", "(", "value", ")", "ipaddr", "=", "IPAddr", ".", "new", "(", "value", ")", "unless", "ipaddr", ".", "ipv4?", "raise", "ValidationError", ",", "\"IP address '#{value}' is not IPv4\"", "end", "ipaddr", "rescue", "ArgumentError", "=>", "e", "raise", "ValidationError", ",", "\"invalid IPv4 address '#{value}' - #{e.message}\"", "end"], "docstring": "Validate IPV4 using the standard \"ipaddr\" ruby module.", "docstring_tokens": ["Validate", "IPV4", "using", "the", "standard", "ipaddr", "ruby", "module", "."], "sha": "916bef1c3a84788507a45cfb75b8f7d0c56b685f", "url": "https://github.com/nicolasdespres/respect/blob/916bef1c3a84788507a45cfb75b8f7d0c56b685f/lib/respect/format_validator.rb#L56-L64", "partition": "valid"} {"repo": "nicolasdespres/respect", "path": "lib/respect/format_validator.rb", "func_name": "Respect.FormatValidator.validate_ipv6_addr", "original_string": "def validate_ipv6_addr(value)\n ipaddr = IPAddr.new(value)\n unless ipaddr.ipv6?\n raise ValidationError, \"IP address '#{value}' is not IPv6\"\n end\n ipaddr\n rescue ArgumentError => e\n raise ValidationError, \"invalid IPv6 address '#{value}' - #{e.message}\"\n end", "language": "ruby", "code": "def validate_ipv6_addr(value)\n ipaddr = IPAddr.new(value)\n unless ipaddr.ipv6?\n raise ValidationError, \"IP address '#{value}' is not IPv6\"\n end\n ipaddr\n rescue ArgumentError => e\n raise ValidationError, \"invalid IPv6 address '#{value}' - #{e.message}\"\n end", "code_tokens": ["def", "validate_ipv6_addr", "(", "value", ")", "ipaddr", "=", "IPAddr", ".", "new", "(", "value", ")", "unless", "ipaddr", ".", "ipv6?", "raise", "ValidationError", ",", "\"IP address '#{value}' is not IPv6\"", "end", "ipaddr", "rescue", "ArgumentError", "=>", "e", "raise", "ValidationError", ",", "\"invalid IPv6 address '#{value}' - #{e.message}\"", "end"], "docstring": "Validate that the given string _value_ describes a well-formed\n IPV6 network address using the standard \"ipaddr\" ruby module.", "docstring_tokens": ["Validate", "that", "the", "given", "string", "_value_", "describes", "a", "well", "-", "formed", "IPV6", "network", "address", "using", "the", "standard", "ipaddr", "ruby", "module", "."], "sha": "916bef1c3a84788507a45cfb75b8f7d0c56b685f", "url": "https://github.com/nicolasdespres/respect/blob/916bef1c3a84788507a45cfb75b8f7d0c56b685f/lib/respect/format_validator.rb#L76-L84", "partition": "valid"} {"repo": "avinashbot/lazy_lazer", "path": "lib/lazy_lazer/internal_model.rb", "func_name": "LazyLazer.InternalModel.to_h", "original_string": "def to_h(strict: false)\n todo = @key_metadata.keys - @cache.keys\n todo.each_with_object({}) do |key, hsh|\n loaded_key = (strict ? load_key_strict(key) : load_key_lenient(key))\n hsh[key] = loaded_key if exists_locally?(key)\n end\n end", "language": "ruby", "code": "def to_h(strict: false)\n todo = @key_metadata.keys - @cache.keys\n todo.each_with_object({}) do |key, hsh|\n loaded_key = (strict ? load_key_strict(key) : load_key_lenient(key))\n hsh[key] = loaded_key if exists_locally?(key)\n end\n end", "code_tokens": ["def", "to_h", "(", "strict", ":", "false", ")", "todo", "=", "@key_metadata", ".", "keys", "-", "@cache", ".", "keys", "todo", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "key", ",", "hsh", "|", "loaded_key", "=", "(", "strict", "?", "load_key_strict", "(", "key", ")", ":", "load_key_lenient", "(", "key", ")", ")", "hsh", "[", "key", "]", "=", "loaded_key", "if", "exists_locally?", "(", "key", ")", "end", "end"], "docstring": "Create an internal model with a reference to a public model.\n @param key_metadata [KeyMetadataStore] a reference to a metadata store\n @param parent [LazyLazer] a reference to a LazyLazer model\n Converts all unconverted keys and packages them as a hash.\n @return [Hash] the converted hash", "docstring_tokens": ["Create", "an", "internal", "model", "with", "a", "reference", "to", "a", "public", "model", "."], "sha": "ed23f152697e76816872301363ab1daff2d2cfc7", "url": "https://github.com/avinashbot/lazy_lazer/blob/ed23f152697e76816872301363ab1daff2d2cfc7/lib/lazy_lazer/internal_model.rb#L22-L28", "partition": "valid"} {"repo": "avinashbot/lazy_lazer", "path": "lib/lazy_lazer/internal_model.rb", "func_name": "LazyLazer.InternalModel.exists_locally?", "original_string": "def exists_locally?(key_name)\n return true if @cache.key?(key_name) || @writethrough.key?(key_name)\n meta = ensure_metadata_exists(key_name)\n @source.key?(meta.source_key)\n end", "language": "ruby", "code": "def exists_locally?(key_name)\n return true if @cache.key?(key_name) || @writethrough.key?(key_name)\n meta = ensure_metadata_exists(key_name)\n @source.key?(meta.source_key)\n end", "code_tokens": ["def", "exists_locally?", "(", "key_name", ")", "return", "true", "if", "@cache", ".", "key?", "(", "key_name", ")", "||", "@writethrough", ".", "key?", "(", "key_name", ")", "meta", "=", "ensure_metadata_exists", "(", "key_name", ")", "@source", ".", "key?", "(", "meta", ".", "source_key", ")", "end"], "docstring": "Whether the key doesn't need to be lazily loaded.\n @param key_name [Symbol] the key to check\n @return [Boolean] whether the key exists locally.", "docstring_tokens": ["Whether", "the", "key", "doesn", "t", "need", "to", "be", "lazily", "loaded", "."], "sha": "ed23f152697e76816872301363ab1daff2d2cfc7", "url": "https://github.com/avinashbot/lazy_lazer/blob/ed23f152697e76816872301363ab1daff2d2cfc7/lib/lazy_lazer/internal_model.rb#L39-L43", "partition": "valid"} {"repo": "avinashbot/lazy_lazer", "path": "lib/lazy_lazer/internal_model.rb", "func_name": "LazyLazer.InternalModel.write_attribute", "original_string": "def write_attribute(key_name, new_value)\n meta = ensure_metadata_exists(key_name)\n @source.delete(meta.source_key)\n @writethrough[key_name] = @cache[key_name] = new_value\n end", "language": "ruby", "code": "def write_attribute(key_name, new_value)\n meta = ensure_metadata_exists(key_name)\n @source.delete(meta.source_key)\n @writethrough[key_name] = @cache[key_name] = new_value\n end", "code_tokens": ["def", "write_attribute", "(", "key_name", ",", "new_value", ")", "meta", "=", "ensure_metadata_exists", "(", "key_name", ")", "@source", ".", "delete", "(", "meta", ".", "source_key", ")", "@writethrough", "[", "key_name", "]", "=", "@cache", "[", "key_name", "]", "=", "new_value", "end"], "docstring": "Update an attribute.\n @param key_name [Symbol] the attribute to update\n @param new_value [Object] the new value\n @return [Object] the written value", "docstring_tokens": ["Update", "an", "attribute", "."], "sha": "ed23f152697e76816872301363ab1daff2d2cfc7", "url": "https://github.com/avinashbot/lazy_lazer/blob/ed23f152697e76816872301363ab1daff2d2cfc7/lib/lazy_lazer/internal_model.rb#L57-L61", "partition": "valid"} {"repo": "avinashbot/lazy_lazer", "path": "lib/lazy_lazer/internal_model.rb", "func_name": "LazyLazer.InternalModel.delete_attribute", "original_string": "def delete_attribute(key_name)\n key_name_sym = key_name.to_sym\n meta = ensure_metadata_exists(key_name_sym)\n @cache.delete(key_name)\n @writethrough.delete(key_name)\n @source.delete(meta.source_key)\n nil\n end", "language": "ruby", "code": "def delete_attribute(key_name)\n key_name_sym = key_name.to_sym\n meta = ensure_metadata_exists(key_name_sym)\n @cache.delete(key_name)\n @writethrough.delete(key_name)\n @source.delete(meta.source_key)\n nil\n end", "code_tokens": ["def", "delete_attribute", "(", "key_name", ")", "key_name_sym", "=", "key_name", ".", "to_sym", "meta", "=", "ensure_metadata_exists", "(", "key_name_sym", ")", "@cache", ".", "delete", "(", "key_name", ")", "@writethrough", ".", "delete", "(", "key_name", ")", "@source", ".", "delete", "(", "meta", ".", "source_key", ")", "nil", "end"], "docstring": "Delete an attribute\n @param key_name [Symbol] the name of the key\n @return [void]", "docstring_tokens": ["Delete", "an", "attribute"], "sha": "ed23f152697e76816872301363ab1daff2d2cfc7", "url": "https://github.com/avinashbot/lazy_lazer/blob/ed23f152697e76816872301363ab1daff2d2cfc7/lib/lazy_lazer/internal_model.rb#L66-L73", "partition": "valid"} {"repo": "avinashbot/lazy_lazer", "path": "lib/lazy_lazer/internal_model.rb", "func_name": "LazyLazer.InternalModel.verify_required!", "original_string": "def verify_required!\n @key_metadata.required_properties.each do |key_name|\n next if @source.key?(@key_metadata.get(key_name).source_key)\n raise RequiredAttribute, \"#{@parent} requires `#{key_name}`\"\n end\n end", "language": "ruby", "code": "def verify_required!\n @key_metadata.required_properties.each do |key_name|\n next if @source.key?(@key_metadata.get(key_name).source_key)\n raise RequiredAttribute, \"#{@parent} requires `#{key_name}`\"\n end\n end", "code_tokens": ["def", "verify_required!", "@key_metadata", ".", "required_properties", ".", "each", "do", "|", "key_name", "|", "next", "if", "@source", ".", "key?", "(", "@key_metadata", ".", "get", "(", "key_name", ")", ".", "source_key", ")", "raise", "RequiredAttribute", ",", "\"#{@parent} requires `#{key_name}`\"", "end", "end"], "docstring": "Verify that all the keys marked as required are present.\n @api private\n @raise RequiredAttribute if a required attribute is missing\n @return [void]", "docstring_tokens": ["Verify", "that", "all", "the", "keys", "marked", "as", "required", "are", "present", "."], "sha": "ed23f152697e76816872301363ab1daff2d2cfc7", "url": "https://github.com/avinashbot/lazy_lazer/blob/ed23f152697e76816872301363ab1daff2d2cfc7/lib/lazy_lazer/internal_model.rb#L96-L101", "partition": "valid"} {"repo": "avinashbot/lazy_lazer", "path": "lib/lazy_lazer/internal_model.rb", "func_name": "LazyLazer.InternalModel.transform_value", "original_string": "def transform_value(value, transform)\n case transform\n when nil\n value\n when Proc\n @parent.instance_exec(value, &transform)\n when Symbol\n value.public_send(transform)\n end\n end", "language": "ruby", "code": "def transform_value(value, transform)\n case transform\n when nil\n value\n when Proc\n @parent.instance_exec(value, &transform)\n when Symbol\n value.public_send(transform)\n end\n end", "code_tokens": ["def", "transform_value", "(", "value", ",", "transform", ")", "case", "transform", "when", "nil", "value", "when", "Proc", "@parent", ".", "instance_exec", "(", "value", ",", "transform", ")", "when", "Symbol", "value", ".", "public_send", "(", "transform", ")", "end", "end"], "docstring": "Apply a transformation to a value.\n @param value [Object] a value\n @param transform [nil, Proc, Symbol] a transform type\n @return [Object] the transformed value", "docstring_tokens": ["Apply", "a", "transformation", "to", "a", "value", "."], "sha": "ed23f152697e76816872301363ab1daff2d2cfc7", "url": "https://github.com/avinashbot/lazy_lazer/blob/ed23f152697e76816872301363ab1daff2d2cfc7/lib/lazy_lazer/internal_model.rb#L168-L177", "partition": "valid"} {"repo": "a14m/EGP-Rates", "path": "lib/egp_rates/bank.rb", "func_name": "EGPRates.Bank.response", "original_string": "def response\n response = Net::HTTP.get_response(@uri)\n if response.is_a? Net::HTTPRedirection\n response = Net::HTTP.get_response(URI.parse(response['location']))\n end\n fail ResponseError, response.code unless response.is_a? Net::HTTPSuccess\n response\n end", "language": "ruby", "code": "def response\n response = Net::HTTP.get_response(@uri)\n if response.is_a? Net::HTTPRedirection\n response = Net::HTTP.get_response(URI.parse(response['location']))\n end\n fail ResponseError, response.code unless response.is_a? Net::HTTPSuccess\n response\n end", "code_tokens": ["def", "response", "response", "=", "Net", "::", "HTTP", ".", "get_response", "(", "@uri", ")", "if", "response", ".", "is_a?", "Net", "::", "HTTPRedirection", "response", "=", "Net", "::", "HTTP", ".", "get_response", "(", "URI", ".", "parse", "(", "response", "[", "'location'", "]", ")", ")", "end", "fail", "ResponseError", ",", "response", ".", "code", "unless", "response", ".", "is_a?", "Net", "::", "HTTPSuccess", "response", "end"], "docstring": "Make a call to the @uri to get the raw_response\n @return [Net::HTTPSuccess] of the raw response\n @raises [ResponseError] if response is not 200 OK", "docstring_tokens": ["Make", "a", "call", "to", "the"], "sha": "ebb960c8cae62c5823aef50bb4121397276c7af6", "url": "https://github.com/a14m/EGP-Rates/blob/ebb960c8cae62c5823aef50bb4121397276c7af6/lib/egp_rates/bank.rb#L20-L27", "partition": "valid"} {"repo": "a14m/EGP-Rates", "path": "lib/egp_rates/adib.rb", "func_name": "EGPRates.ADIB.currencies", "original_string": "def currencies(table_rows)\n table_rows.lazy.map do |e|\n e.css('img').map { |img| img.attribute('src').value }\n end.force.flatten\n end", "language": "ruby", "code": "def currencies(table_rows)\n table_rows.lazy.map do |e|\n e.css('img').map { |img| img.attribute('src').value }\n end.force.flatten\n end", "code_tokens": ["def", "currencies", "(", "table_rows", ")", "table_rows", ".", "lazy", ".", "map", "do", "|", "e", "|", "e", ".", "css", "(", "'img'", ")", ".", "map", "{", "|", "img", "|", "img", ".", "attribute", "(", "'src'", ")", ".", "value", "}", "end", ".", "force", ".", "flatten", "end"], "docstring": "Extract the currencies from the image components src attribute\n @return [Array] containing the URL to image of the currency", "docstring_tokens": ["Extract", "the", "currencies", "from", "the", "image", "components", "src", "attribute"], "sha": "ebb960c8cae62c5823aef50bb4121397276c7af6", "url": "https://github.com/a14m/EGP-Rates/blob/ebb960c8cae62c5823aef50bb4121397276c7af6/lib/egp_rates/adib.rb#L38-L42", "partition": "valid"} {"repo": "avinashbot/lazy_lazer", "path": "lib/lazy_lazer/key_metadata_store.rb", "func_name": "LazyLazer.KeyMetadataStore.add", "original_string": "def add(key, meta)\n @collection[key] = meta\n if meta.required?\n @required_properties << key\n else\n @required_properties.delete(key)\n end\n meta\n end", "language": "ruby", "code": "def add(key, meta)\n @collection[key] = meta\n if meta.required?\n @required_properties << key\n else\n @required_properties.delete(key)\n end\n meta\n end", "code_tokens": ["def", "add", "(", "key", ",", "meta", ")", "@collection", "[", "key", "]", "=", "meta", "if", "meta", ".", "required?", "@required_properties", "<<", "key", "else", "@required_properties", ".", "delete", "(", "key", ")", "end", "meta", "end"], "docstring": "Add a KeyMetadata to the store.\n @param key [Symbol] the key\n @param meta [KeyMetadata] the key metadata\n @return [KeyMetadata] the provided meta", "docstring_tokens": ["Add", "a", "KeyMetadata", "to", "the", "store", "."], "sha": "ed23f152697e76816872301363ab1daff2d2cfc7", "url": "https://github.com/avinashbot/lazy_lazer/blob/ed23f152697e76816872301363ab1daff2d2cfc7/lib/lazy_lazer/key_metadata_store.rb#L25-L33", "partition": "valid"} {"repo": "nicolasdespres/respect", "path": "lib/respect/has_constraints.rb", "func_name": "Respect.HasConstraints.validate_constraints", "original_string": "def validate_constraints(value)\n options.each do |option, arg|\n if validator_class = Respect.validator_for(option)\n validator_class.new(arg).validate(value)\n end\n end\n end", "language": "ruby", "code": "def validate_constraints(value)\n options.each do |option, arg|\n if validator_class = Respect.validator_for(option)\n validator_class.new(arg).validate(value)\n end\n end\n end", "code_tokens": ["def", "validate_constraints", "(", "value", ")", "options", ".", "each", "do", "|", "option", ",", "arg", "|", "if", "validator_class", "=", "Respect", ".", "validator_for", "(", "option", ")", "validator_class", ".", "new", "(", "arg", ")", ".", "validate", "(", "value", ")", "end", "end", "end"], "docstring": "Validate all the constraints listed in +options+ to the\n given +value+.", "docstring_tokens": ["Validate", "all", "the", "constraints", "listed", "in", "+", "options", "+", "to", "the", "given", "+", "value", "+", "."], "sha": "916bef1c3a84788507a45cfb75b8f7d0c56b685f", "url": "https://github.com/nicolasdespres/respect/blob/916bef1c3a84788507a45cfb75b8f7d0c56b685f/lib/respect/has_constraints.rb#L12-L18", "partition": "valid"} {"repo": "nicolasdespres/respect", "path": "lib/respect/has_constraints.rb", "func_name": "Respect.HasConstraints.validate", "original_string": "def validate(object)\n sanitized_object = validate_type(object)\n validate_constraints(sanitized_object) unless sanitized_object.nil? && allow_nil?\n self.sanitized_object = sanitized_object\n true\n rescue ValidationError => e\n # Reset sanitized object.\n self.sanitized_object = nil\n raise e\n end", "language": "ruby", "code": "def validate(object)\n sanitized_object = validate_type(object)\n validate_constraints(sanitized_object) unless sanitized_object.nil? && allow_nil?\n self.sanitized_object = sanitized_object\n true\n rescue ValidationError => e\n # Reset sanitized object.\n self.sanitized_object = nil\n raise e\n end", "code_tokens": ["def", "validate", "(", "object", ")", "sanitized_object", "=", "validate_type", "(", "object", ")", "validate_constraints", "(", "sanitized_object", ")", "unless", "sanitized_object", ".", "nil?", "&&", "allow_nil?", "self", ".", "sanitized_object", "=", "sanitized_object", "true", "rescue", "ValidationError", "=>", "e", "# Reset sanitized object.", "self", ".", "sanitized_object", "=", "nil", "raise", "e", "end"], "docstring": "Call +validate_type+ with the given +object+, apply the constraints\n and assign the sanitized object.", "docstring_tokens": ["Call", "+", "validate_type", "+", "with", "the", "given", "+", "object", "+", "apply", "the", "constraints", "and", "assign", "the", "sanitized", "object", "."], "sha": "916bef1c3a84788507a45cfb75b8f7d0c56b685f", "url": "https://github.com/nicolasdespres/respect/blob/916bef1c3a84788507a45cfb75b8f7d0c56b685f/lib/respect/has_constraints.rb#L22-L31", "partition": "valid"} {"repo": "nicolasdespres/respect", "path": "lib/respect/hash_schema.rb", "func_name": "Respect.HashSchema.[]=", "original_string": "def []=(name, schema)\n case name\n when Symbol, String, Regexp\n if @properties.has_key?(name)\n raise InvalidSchemaError, \"property '#{name}' already defined\"\n end\n @properties[name] = schema\n else\n raise InvalidSchemaError, \"unsupported property name type #{name}:#{name.class}\"\n end\n end", "language": "ruby", "code": "def []=(name, schema)\n case name\n when Symbol, String, Regexp\n if @properties.has_key?(name)\n raise InvalidSchemaError, \"property '#{name}' already defined\"\n end\n @properties[name] = schema\n else\n raise InvalidSchemaError, \"unsupported property name type #{name}:#{name.class}\"\n end\n end", "code_tokens": ["def", "[]=", "(", "name", ",", "schema", ")", "case", "name", "when", "Symbol", ",", "String", ",", "Regexp", "if", "@properties", ".", "has_key?", "(", "name", ")", "raise", "InvalidSchemaError", ",", "\"property '#{name}' already defined\"", "end", "@properties", "[", "name", "]", "=", "schema", "else", "raise", "InvalidSchemaError", ",", "\"unsupported property name type #{name}:#{name.class}\"", "end", "end"], "docstring": "Set the given +schema+ for the given property +name+. A name can be\n a Symbol, a String or a Regexp.", "docstring_tokens": ["Set", "the", "given", "+", "schema", "+", "for", "the", "given", "property", "+", "name", "+", ".", "A", "name", "can", "be", "a", "Symbol", "a", "String", "or", "a", "Regexp", "."], "sha": "916bef1c3a84788507a45cfb75b8f7d0c56b685f", "url": "https://github.com/nicolasdespres/respect/blob/916bef1c3a84788507a45cfb75b8f7d0c56b685f/lib/respect/hash_schema.rb#L61-L71", "partition": "valid"} {"repo": "nicolasdespres/respect", "path": "lib/respect/hash_def.rb", "func_name": "Respect.HashDef.[]=", "original_string": "def []=(key, value)\n case value\n when String\n string(key, equal_to: value.to_s)\n else\n any(key, equal_to: value.to_s)\n end\n end", "language": "ruby", "code": "def []=(key, value)\n case value\n when String\n string(key, equal_to: value.to_s)\n else\n any(key, equal_to: value.to_s)\n end\n end", "code_tokens": ["def", "[]=", "(", "key", ",", "value", ")", "case", "value", "when", "String", "string", "(", "key", ",", "equal_to", ":", "value", ".", "to_s", ")", "else", "any", "(", "key", ",", "equal_to", ":", "value", ".", "to_s", ")", "end", "end"], "docstring": "Shortcut to say a schema +key+ must be equal to a given +value+. When it\n does not recognize the value type it creates a \"any\" schema.\n\n Example:\n HashSchema.define do |s|\n s[\"a_string\"] = \"value\" # equivalent to: s.string(\"a_string\", equal_to: \"value\")\n s[\"a_key\"] = 0..5 # equivalent to: s.any(\"a_key\", equal_to: \"0..5\")\n end", "docstring_tokens": ["Shortcut", "to", "say", "a", "schema", "+", "key", "+", "must", "be", "equal", "to", "a", "given", "+", "value", "+", ".", "When", "it", "does", "not", "recognize", "the", "value", "type", "it", "creates", "a", "any", "schema", "."], "sha": "916bef1c3a84788507a45cfb75b8f7d0c56b685f", "url": "https://github.com/nicolasdespres/respect/blob/916bef1c3a84788507a45cfb75b8f7d0c56b685f/lib/respect/hash_def.rb#L21-L28", "partition": "valid"} {"repo": "sue445/google_holiday_calendar", "path": "lib/google_holiday_calendar/calendar.rb", "func_name": "GoogleHolidayCalendar.Calendar.holiday?", "original_string": "def holiday?(arg)\n date = to_date(arg)\n holidays(start_date: date, end_date: date + 1.day, limit: 1).length > 0\n end", "language": "ruby", "code": "def holiday?(arg)\n date = to_date(arg)\n holidays(start_date: date, end_date: date + 1.day, limit: 1).length > 0\n end", "code_tokens": ["def", "holiday?", "(", "arg", ")", "date", "=", "to_date", "(", "arg", ")", "holidays", "(", "start_date", ":", "date", ",", "end_date", ":", "date", "+", "1", ".", "day", ",", "limit", ":", "1", ")", ".", "length", ">", "0", "end"], "docstring": "whether arg is holiday\n @param arg [#to_date, String] {Date}, {Time}, or date like String (ex. \"YYYY-MM-DD\")", "docstring_tokens": ["whether", "arg", "is", "holiday"], "sha": "167384881ec1c970322aa4d7e5dd0d5d736ba875", "url": "https://github.com/sue445/google_holiday_calendar/blob/167384881ec1c970322aa4d7e5dd0d5d736ba875/lib/google_holiday_calendar/calendar.rb#L53-L56", "partition": "valid"} {"repo": "defunkt/choice", "path": "lib/choice/parser.rb", "func_name": "Choice.Parser.arrayize_arguments", "original_string": "def arrayize_arguments(args)\n # Go through trailing arguments and suck them in if they don't seem\n # to have an owner.\n array = []\n until args.empty? || args.first.match(/^-/)\n array << args.shift\n end\n array\n end", "language": "ruby", "code": "def arrayize_arguments(args)\n # Go through trailing arguments and suck them in if they don't seem\n # to have an owner.\n array = []\n until args.empty? || args.first.match(/^-/)\n array << args.shift\n end\n array\n end", "code_tokens": ["def", "arrayize_arguments", "(", "args", ")", "# Go through trailing arguments and suck them in if they don't seem", "# to have an owner.", "array", "=", "[", "]", "until", "args", ".", "empty?", "||", "args", ".", "first", ".", "match", "(", "/", "/", ")", "array", "<<", "args", ".", "shift", "end", "array", "end"], "docstring": "Turns trailing command line arguments into an array for an arrayed value", "docstring_tokens": ["Turns", "trailing", "command", "line", "arguments", "into", "an", "array", "for", "an", "arrayed", "value"], "sha": "16e9431519463a9aa22138c0a3d07fda11486847", "url": "https://github.com/defunkt/choice/blob/16e9431519463a9aa22138c0a3d07fda11486847/lib/choice/parser.rb#L206-L214", "partition": "valid"} {"repo": "defunkt/choice", "path": "lib/choice/option.rb", "func_name": "Choice.Option.to_a", "original_string": "def to_a\n [\n required,\n short,\n long,\n desc,\n default,\n filter,\n action,\n cast,\n valid,\n validate\n ].compact\n end", "language": "ruby", "code": "def to_a\n [\n required,\n short,\n long,\n desc,\n default,\n filter,\n action,\n cast,\n valid,\n validate\n ].compact\n end", "code_tokens": ["def", "to_a", "[", "required", ",", "short", ",", "long", ",", "desc", ",", "default", ",", "filter", ",", "action", ",", "cast", ",", "valid", ",", "validate", "]", ".", "compact", "end"], "docstring": "Returns Option converted to an array.", "docstring_tokens": ["Returns", "Option", "converted", "to", "an", "array", "."], "sha": "16e9431519463a9aa22138c0a3d07fda11486847", "url": "https://github.com/defunkt/choice/blob/16e9431519463a9aa22138c0a3d07fda11486847/lib/choice/option.rb#L110-L123", "partition": "valid"} {"repo": "defunkt/choice", "path": "lib/choice/option.rb", "func_name": "Choice.Option.to_h", "original_string": "def to_h\n {\n \"required\" => required,\n \"short\" => short,\n \"long\" => long,\n \"desc\" => desc,\n \"default\" => default,\n \"filter\" => filter,\n \"action\" => action,\n \"cast\" => cast,\n \"valid\" => valid,\n \"validate\" => validate\n }.reject {|k, v| v.nil? }\n end", "language": "ruby", "code": "def to_h\n {\n \"required\" => required,\n \"short\" => short,\n \"long\" => long,\n \"desc\" => desc,\n \"default\" => default,\n \"filter\" => filter,\n \"action\" => action,\n \"cast\" => cast,\n \"valid\" => valid,\n \"validate\" => validate\n }.reject {|k, v| v.nil? }\n end", "code_tokens": ["def", "to_h", "{", "\"required\"", "=>", "required", ",", "\"short\"", "=>", "short", ",", "\"long\"", "=>", "long", ",", "\"desc\"", "=>", "desc", ",", "\"default\"", "=>", "default", ",", "\"filter\"", "=>", "filter", ",", "\"action\"", "=>", "action", ",", "\"cast\"", "=>", "cast", ",", "\"valid\"", "=>", "valid", ",", "\"validate\"", "=>", "validate", "}", ".", "reject", "{", "|", "k", ",", "v", "|", "v", ".", "nil?", "}", "end"], "docstring": "Returns Option converted to a hash.", "docstring_tokens": ["Returns", "Option", "converted", "to", "a", "hash", "."], "sha": "16e9431519463a9aa22138c0a3d07fda11486847", "url": "https://github.com/defunkt/choice/blob/16e9431519463a9aa22138c0a3d07fda11486847/lib/choice/option.rb#L126-L139", "partition": "valid"} {"repo": "thomis/eventhub-processor2", "path": "lib/eventhub/configuration.rb", "func_name": "EventHub.Configuration.parse_options", "original_string": "def parse_options(argv = ARGV)\n @config_file = File.join(Dir.getwd, 'config', \"#{@name}.json\")\n\n OptionParser.new do |opts|\n note = 'Define environment'\n opts.on('-e', '--environment ENVIRONMENT', note) do |environment|\n @environment = environment\n end\n\n opts.on('-d', '--detached', 'Run processor detached as a daemon') do\n @detached = true\n end\n\n note = 'Define configuration file'\n opts.on('-c', '--config CONFIG', note) do |config|\n @config_file = config\n end\n end.parse!(argv)\n\n true\n rescue OptionParser::InvalidOption => e\n EventHub.logger.warn(\"Argument Parsing: #{e}\")\n false\n rescue OptionParser::MissingArgument => e\n EventHub.logger.warn(\"Argument Parsing: #{e}\")\n false\n end", "language": "ruby", "code": "def parse_options(argv = ARGV)\n @config_file = File.join(Dir.getwd, 'config', \"#{@name}.json\")\n\n OptionParser.new do |opts|\n note = 'Define environment'\n opts.on('-e', '--environment ENVIRONMENT', note) do |environment|\n @environment = environment\n end\n\n opts.on('-d', '--detached', 'Run processor detached as a daemon') do\n @detached = true\n end\n\n note = 'Define configuration file'\n opts.on('-c', '--config CONFIG', note) do |config|\n @config_file = config\n end\n end.parse!(argv)\n\n true\n rescue OptionParser::InvalidOption => e\n EventHub.logger.warn(\"Argument Parsing: #{e}\")\n false\n rescue OptionParser::MissingArgument => e\n EventHub.logger.warn(\"Argument Parsing: #{e}\")\n false\n end", "code_tokens": ["def", "parse_options", "(", "argv", "=", "ARGV", ")", "@config_file", "=", "File", ".", "join", "(", "Dir", ".", "getwd", ",", "'config'", ",", "\"#{@name}.json\"", ")", "OptionParser", ".", "new", "do", "|", "opts", "|", "note", "=", "'Define environment'", "opts", ".", "on", "(", "'-e'", ",", "'--environment ENVIRONMENT'", ",", "note", ")", "do", "|", "environment", "|", "@environment", "=", "environment", "end", "opts", ".", "on", "(", "'-d'", ",", "'--detached'", ",", "'Run processor detached as a daemon'", ")", "do", "@detached", "=", "true", "end", "note", "=", "'Define configuration file'", "opts", ".", "on", "(", "'-c'", ",", "'--config CONFIG'", ",", "note", ")", "do", "|", "config", "|", "@config_file", "=", "config", "end", "end", ".", "parse!", "(", "argv", ")", "true", "rescue", "OptionParser", "::", "InvalidOption", "=>", "e", "EventHub", ".", "logger", ".", "warn", "(", "\"Argument Parsing: #{e}\"", ")", "false", "rescue", "OptionParser", "::", "MissingArgument", "=>", "e", "EventHub", ".", "logger", ".", "warn", "(", "\"Argument Parsing: #{e}\"", ")", "false", "end"], "docstring": "parse options from argument list", "docstring_tokens": ["parse", "options", "from", "argument", "list"], "sha": "74271f30d0ec35f1f44421b7ae92c2f4ccf51786", "url": "https://github.com/thomis/eventhub-processor2/blob/74271f30d0ec35f1f44421b7ae92c2f4ccf51786/lib/eventhub/configuration.rb#L35-L61", "partition": "valid"} {"repo": "thomis/eventhub-processor2", "path": "lib/eventhub/configuration.rb", "func_name": "EventHub.Configuration.load!", "original_string": "def load!(args = {})\n # for better rspec testing\n @config_file = args[:config_file] if args[:config_file]\n @environment = args[:environment] if args[:environment]\n\n new_data = {}\n begin\n new_data = JSON.parse(File.read(@config_file), symbolize_names: true)\n rescue => e\n EventHub.logger.warn(\"Exception while loading configuration file: #{e}\")\n EventHub.logger.info('Using default configuration values')\n end\n\n deep_merge!(@config_data, default_configuration)\n new_data = new_data[@environment.to_sym]\n deep_merge!(@config_data, new_data)\n end", "language": "ruby", "code": "def load!(args = {})\n # for better rspec testing\n @config_file = args[:config_file] if args[:config_file]\n @environment = args[:environment] if args[:environment]\n\n new_data = {}\n begin\n new_data = JSON.parse(File.read(@config_file), symbolize_names: true)\n rescue => e\n EventHub.logger.warn(\"Exception while loading configuration file: #{e}\")\n EventHub.logger.info('Using default configuration values')\n end\n\n deep_merge!(@config_data, default_configuration)\n new_data = new_data[@environment.to_sym]\n deep_merge!(@config_data, new_data)\n end", "code_tokens": ["def", "load!", "(", "args", "=", "{", "}", ")", "# for better rspec testing", "@config_file", "=", "args", "[", ":config_file", "]", "if", "args", "[", ":config_file", "]", "@environment", "=", "args", "[", ":environment", "]", "if", "args", "[", ":environment", "]", "new_data", "=", "{", "}", "begin", "new_data", "=", "JSON", ".", "parse", "(", "File", ".", "read", "(", "@config_file", ")", ",", "symbolize_names", ":", "true", ")", "rescue", "=>", "e", "EventHub", ".", "logger", ".", "warn", "(", "\"Exception while loading configuration file: #{e}\"", ")", "EventHub", ".", "logger", ".", "info", "(", "'Using default configuration values'", ")", "end", "deep_merge!", "(", "@config_data", ",", "default_configuration", ")", "new_data", "=", "new_data", "[", "@environment", ".", "to_sym", "]", "deep_merge!", "(", "@config_data", ",", "new_data", ")", "end"], "docstring": "load configuration from file", "docstring_tokens": ["load", "configuration", "from", "file"], "sha": "74271f30d0ec35f1f44421b7ae92c2f4ccf51786", "url": "https://github.com/thomis/eventhub-processor2/blob/74271f30d0ec35f1f44421b7ae92c2f4ccf51786/lib/eventhub/configuration.rb#L64-L80", "partition": "valid"} {"repo": "vidibus/vidibus-words", "path": "lib/vidibus/words.rb", "func_name": "Vidibus.Words.keywords", "original_string": "def keywords(limit = 20)\n @keywords ||= {}\n @keywords[limit] ||= begin\n list = []\n count = 0\n _stopwords = Vidibus::Words.stopwords(*locales)\n for word in sort\n clean = word.permalink.gsub('-','')\n unless _stopwords.include?(clean)\n list << word\n count += 1\n break if count >= limit\n end\n end\n list\n end\n end", "language": "ruby", "code": "def keywords(limit = 20)\n @keywords ||= {}\n @keywords[limit] ||= begin\n list = []\n count = 0\n _stopwords = Vidibus::Words.stopwords(*locales)\n for word in sort\n clean = word.permalink.gsub('-','')\n unless _stopwords.include?(clean)\n list << word\n count += 1\n break if count >= limit\n end\n end\n list\n end\n end", "code_tokens": ["def", "keywords", "(", "limit", "=", "20", ")", "@keywords", "||=", "{", "}", "@keywords", "[", "limit", "]", "||=", "begin", "list", "=", "[", "]", "count", "=", "0", "_stopwords", "=", "Vidibus", "::", "Words", ".", "stopwords", "(", "locales", ")", "for", "word", "in", "sort", "clean", "=", "word", ".", "permalink", ".", "gsub", "(", "'-'", ",", "''", ")", "unless", "_stopwords", ".", "include?", "(", "clean", ")", "list", "<<", "word", "count", "+=", "1", "break", "if", "count", ">=", "limit", "end", "end", "list", "end", "end"], "docstring": "Returns top keywords from input string.", "docstring_tokens": ["Returns", "top", "keywords", "from", "input", "string", "."], "sha": "de01b2e84feec75ca175d44db4f4765a5ae41b1f", "url": "https://github.com/vidibus/vidibus-words/blob/de01b2e84feec75ca175d44db4f4765a5ae41b1f/lib/vidibus/words.rb#L39-L55", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/normaliser.rb", "func_name": "ONIX.Normaliser.next_tempfile", "original_string": "def next_tempfile\n p = nil\n Tempfile.open(\"onix\") do |tf|\n p = tf.path\n tf.close!\n end\n p\n end", "language": "ruby", "code": "def next_tempfile\n p = nil\n Tempfile.open(\"onix\") do |tf|\n p = tf.path\n tf.close!\n end\n p\n end", "code_tokens": ["def", "next_tempfile", "p", "=", "nil", "Tempfile", ".", "open", "(", "\"onix\"", ")", "do", "|", "tf", "|", "p", "=", "tf", ".", "path", "tf", ".", "close!", "end", "p", "end"], "docstring": "generate a temp filename", "docstring_tokens": ["generate", "a", "temp", "filename"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/normaliser.rb#L78-L85", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/reader.rb", "func_name": "ONIX.Reader.each", "original_string": "def each(&block)\n @reader.each do |node|\n if @reader.node_type == 1 && @reader.name == \"Product\"\n str = @reader.outer_xml\n if str.nil?\n yield @product_klass.new\n else\n yield @product_klass.from_xml(str)\n end\n end\n end\n end", "language": "ruby", "code": "def each(&block)\n @reader.each do |node|\n if @reader.node_type == 1 && @reader.name == \"Product\"\n str = @reader.outer_xml\n if str.nil?\n yield @product_klass.new\n else\n yield @product_klass.from_xml(str)\n end\n end\n end\n end", "code_tokens": ["def", "each", "(", "&", "block", ")", "@reader", ".", "each", "do", "|", "node", "|", "if", "@reader", ".", "node_type", "==", "1", "&&", "@reader", ".", "name", "==", "\"Product\"", "str", "=", "@reader", ".", "outer_xml", "if", "str", ".", "nil?", "yield", "@product_klass", ".", "new", "else", "yield", "@product_klass", ".", "from_xml", "(", "str", ")", "end", "end", "end", "end"], "docstring": "Iterate over all the products in an ONIX file", "docstring_tokens": ["Iterate", "over", "all", "the", "products", "in", "an", "ONIX", "file"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/reader.rb#L106-L117", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/apa_product.rb", "func_name": "ONIX.APAProduct.title", "original_string": "def title\n composite = product.titles.first\n if composite.nil?\n nil\n else\n composite.title_text || composite.title_without_prefix\n end\n end", "language": "ruby", "code": "def title\n composite = product.titles.first\n if composite.nil?\n nil\n else\n composite.title_text || composite.title_without_prefix\n end\n end", "code_tokens": ["def", "title", "composite", "=", "product", ".", "titles", ".", "first", "if", "composite", ".", "nil?", "nil", "else", "composite", ".", "title_text", "||", "composite", ".", "title_without_prefix", "end", "end"], "docstring": "retrieve the current title", "docstring_tokens": ["retrieve", "the", "current", "title"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L68-L75", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/apa_product.rb", "func_name": "ONIX.APAProduct.title=", "original_string": "def title=(str)\n composite = product.titles.first\n if composite.nil?\n composite = ONIX::Title.new\n composite.title_type = 1\n product.titles << composite\n end\n composite.title_text = str\n end", "language": "ruby", "code": "def title=(str)\n composite = product.titles.first\n if composite.nil?\n composite = ONIX::Title.new\n composite.title_type = 1\n product.titles << composite\n end\n composite.title_text = str\n end", "code_tokens": ["def", "title", "=", "(", "str", ")", "composite", "=", "product", ".", "titles", ".", "first", "if", "composite", ".", "nil?", "composite", "=", "ONIX", "::", "Title", ".", "new", "composite", ".", "title_type", "=", "1", "product", ".", "titles", "<<", "composite", "end", "composite", ".", "title_text", "=", "str", "end"], "docstring": "set a new title", "docstring_tokens": ["set", "a", "new", "title"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L78-L86", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/apa_product.rb", "func_name": "ONIX.APAProduct.subtitle=", "original_string": "def subtitle=(str)\n composite = product.titles.first\n if composite.nil?\n composite = ONIX::Title.new\n composite.title_type = 1\n product.titles << composite\n end\n composite.subtitle = str\n end", "language": "ruby", "code": "def subtitle=(str)\n composite = product.titles.first\n if composite.nil?\n composite = ONIX::Title.new\n composite.title_type = 1\n product.titles << composite\n end\n composite.subtitle = str\n end", "code_tokens": ["def", "subtitle", "=", "(", "str", ")", "composite", "=", "product", ".", "titles", ".", "first", "if", "composite", ".", "nil?", "composite", "=", "ONIX", "::", "Title", ".", "new", "composite", ".", "title_type", "=", "1", "product", ".", "titles", "<<", "composite", "end", "composite", ".", "subtitle", "=", "str", "end"], "docstring": "set a new subtitle", "docstring_tokens": ["set", "a", "new", "subtitle"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L99-L107", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/apa_product.rb", "func_name": "ONIX.APAProduct.bic_subjects", "original_string": "def bic_subjects\n subjects = product.subjects.select { |sub| sub.subject_scheme_id.to_i == 12 }\n subjects.collect { |sub| sub.subject_code}\n end", "language": "ruby", "code": "def bic_subjects\n subjects = product.subjects.select { |sub| sub.subject_scheme_id.to_i == 12 }\n subjects.collect { |sub| sub.subject_code}\n end", "code_tokens": ["def", "bic_subjects", "subjects", "=", "product", ".", "subjects", ".", "select", "{", "|", "sub", "|", "sub", ".", "subject_scheme_id", ".", "to_i", "==", "12", "}", "subjects", ".", "collect", "{", "|", "sub", "|", "sub", ".", "subject_code", "}", "end"], "docstring": "return an array of BIC subjects for this title\n could be version 1 or version 2, most ONIX files don't\n specifiy", "docstring_tokens": ["return", "an", "array", "of", "BIC", "subjects", "for", "this", "title", "could", "be", "version", "1", "or", "version", "2", "most", "ONIX", "files", "don", "t", "specifiy"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L161-L164", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/apa_product.rb", "func_name": "ONIX.APAProduct.imprint=", "original_string": "def imprint=(str)\n composite = product.imprints.first\n if composite.nil?\n composite = ONIX::Imprint.new\n product.imprints << composite\n end\n composite.imprint_name = str\n end", "language": "ruby", "code": "def imprint=(str)\n composite = product.imprints.first\n if composite.nil?\n composite = ONIX::Imprint.new\n product.imprints << composite\n end\n composite.imprint_name = str\n end", "code_tokens": ["def", "imprint", "=", "(", "str", ")", "composite", "=", "product", ".", "imprints", ".", "first", "if", "composite", ".", "nil?", "composite", "=", "ONIX", "::", "Imprint", ".", "new", "product", ".", "imprints", "<<", "composite", "end", "composite", ".", "imprint_name", "=", "str", "end"], "docstring": "set a new imprint", "docstring_tokens": ["set", "a", "new", "imprint"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L255-L262", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/apa_product.rb", "func_name": "ONIX.APAProduct.sales_restriction_type=", "original_string": "def sales_restriction_type=(type)\n composite = product.sales_restrictions.first\n if composite.nil?\n composite = ONIX::SalesRestriction.new\n product.sales_restrictions << composite\n end\n composite.sales_restriction_type = type\n end", "language": "ruby", "code": "def sales_restriction_type=(type)\n composite = product.sales_restrictions.first\n if composite.nil?\n composite = ONIX::SalesRestriction.new\n product.sales_restrictions << composite\n end\n composite.sales_restriction_type = type\n end", "code_tokens": ["def", "sales_restriction_type", "=", "(", "type", ")", "composite", "=", "product", ".", "sales_restrictions", ".", "first", "if", "composite", ".", "nil?", "composite", "=", "ONIX", "::", "SalesRestriction", ".", "new", "product", ".", "sales_restrictions", "<<", "composite", "end", "composite", ".", "sales_restriction_type", "=", "type", "end"], "docstring": "set a new sales restriction type", "docstring_tokens": ["set", "a", "new", "sales", "restriction", "type"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L281-L288", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/apa_product.rb", "func_name": "ONIX.APAProduct.on_order", "original_string": "def on_order\n supply = find_or_create_supply_detail\n composite = supply.stock.first\n if composite.nil?\n composite = ONIX::Stock.new\n supply.stock << composite\n end\n composite.on_order\n end", "language": "ruby", "code": "def on_order\n supply = find_or_create_supply_detail\n composite = supply.stock.first\n if composite.nil?\n composite = ONIX::Stock.new\n supply.stock << composite\n end\n composite.on_order\n end", "code_tokens": ["def", "on_order", "supply", "=", "find_or_create_supply_detail", "composite", "=", "supply", ".", "stock", ".", "first", "if", "composite", ".", "nil?", "composite", "=", "ONIX", "::", "Stock", ".", "new", "supply", ".", "stock", "<<", "composite", "end", "composite", ".", "on_order", "end"], "docstring": "retrieve the number on order", "docstring_tokens": ["retrieve", "the", "number", "on", "order"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L385-L393", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/apa_product.rb", "func_name": "ONIX.APAProduct.proprietry_discount_code_for_rrp", "original_string": "def proprietry_discount_code_for_rrp\n price = price_get(2)\n return nil if price.nil?\n\n discount = price.discounts_coded.find { |disc| disc.discount_code_type == 2 }\n discount.andand.discount_code\n end", "language": "ruby", "code": "def proprietry_discount_code_for_rrp\n price = price_get(2)\n return nil if price.nil?\n\n discount = price.discounts_coded.find { |disc| disc.discount_code_type == 2 }\n discount.andand.discount_code\n end", "code_tokens": ["def", "proprietry_discount_code_for_rrp", "price", "=", "price_get", "(", "2", ")", "return", "nil", "if", "price", ".", "nil?", "discount", "=", "price", ".", "discounts_coded", ".", "find", "{", "|", "disc", "|", "disc", ".", "discount_code_type", "==", "2", "}", "discount", ".", "andand", ".", "discount_code", "end"], "docstring": "retrieve the discount code that describes the rrp in this file", "docstring_tokens": ["retrieve", "the", "discount", "code", "that", "describes", "the", "rrp", "in", "this", "file"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L449-L455", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/apa_product.rb", "func_name": "ONIX.APAProduct.proprietry_discount_code_for_rrp=", "original_string": "def proprietry_discount_code_for_rrp=(code)\n price = price_get(2)\n if price.nil?\n self.rrp_inc_sales_tax = 0\n price = price_get(2)\n end\n\n discount = price.discounts_coded.find { |disc| disc.discount_code_type == 2 }\n\n if discount.nil?\n discount = ONIX::DiscountCoded.new\n discount.discount_code_type = 2\n price.discounts_coded << discount\n end\n discount.discount_code = code\n end", "language": "ruby", "code": "def proprietry_discount_code_for_rrp=(code)\n price = price_get(2)\n if price.nil?\n self.rrp_inc_sales_tax = 0\n price = price_get(2)\n end\n\n discount = price.discounts_coded.find { |disc| disc.discount_code_type == 2 }\n\n if discount.nil?\n discount = ONIX::DiscountCoded.new\n discount.discount_code_type = 2\n price.discounts_coded << discount\n end\n discount.discount_code = code\n end", "code_tokens": ["def", "proprietry_discount_code_for_rrp", "=", "(", "code", ")", "price", "=", "price_get", "(", "2", ")", "if", "price", ".", "nil?", "self", ".", "rrp_inc_sales_tax", "=", "0", "price", "=", "price_get", "(", "2", ")", "end", "discount", "=", "price", ".", "discounts_coded", ".", "find", "{", "|", "disc", "|", "disc", ".", "discount_code_type", "==", "2", "}", "if", "discount", ".", "nil?", "discount", "=", "ONIX", "::", "DiscountCoded", ".", "new", "discount", ".", "discount_code_type", "=", "2", "price", ".", "discounts_coded", "<<", "discount", "end", "discount", ".", "discount_code", "=", "code", "end"], "docstring": "set the discount code that describes the rrp in this file", "docstring_tokens": ["set", "the", "discount", "code", "that", "describes", "the", "rrp", "in", "this", "file"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L458-L473", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/apa_product.rb", "func_name": "ONIX.APAProduct.add_subject", "original_string": "def add_subject(str, type = \"12\")\n subject = ::ONIX::Subject.new\n subject.subject_scheme_id = type.to_i\n subject.subject_code = str\n product.subjects << subject\n end", "language": "ruby", "code": "def add_subject(str, type = \"12\")\n subject = ::ONIX::Subject.new\n subject.subject_scheme_id = type.to_i\n subject.subject_code = str\n product.subjects << subject\n end", "code_tokens": ["def", "add_subject", "(", "str", ",", "type", "=", "\"12\"", ")", "subject", "=", "::", "ONIX", "::", "Subject", ".", "new", "subject", ".", "subject_scheme_id", "=", "type", ".", "to_i", "subject", ".", "subject_code", "=", "str", "product", ".", "subjects", "<<", "subject", "end"], "docstring": "add a new subject to this product\n str should be the subject code\n type should be the code for the subject scheme you're using. See ONIX codelist 27.\n 12 is BIC", "docstring_tokens": ["add", "a", "new", "subject", "to", "this", "product", "str", "should", "be", "the", "subject", "code", "type", "should", "be", "the", "code", "for", "the", "subject", "scheme", "you", "re", "using", ".", "See", "ONIX", "codelist", "27", ".", "12", "is", "BIC"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L624-L629", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/apa_product.rb", "func_name": "ONIX.APAProduct.measurement_set", "original_string": "def measurement_set(type, value, unit)\n measure = measurement(type)\n\n # create a new isbn record if we need to\n if measure.nil?\n measure = ONIX::Measure.new\n measure.measure_type_code = type\n product.measurements << measure\n end\n\n # store the new value\n measure.measurement = value\n measure.measure_unit_code = unit.to_s\n end", "language": "ruby", "code": "def measurement_set(type, value, unit)\n measure = measurement(type)\n\n # create a new isbn record if we need to\n if measure.nil?\n measure = ONIX::Measure.new\n measure.measure_type_code = type\n product.measurements << measure\n end\n\n # store the new value\n measure.measurement = value\n measure.measure_unit_code = unit.to_s\n end", "code_tokens": ["def", "measurement_set", "(", "type", ",", "value", ",", "unit", ")", "measure", "=", "measurement", "(", "type", ")", "# create a new isbn record if we need to", "if", "measure", ".", "nil?", "measure", "=", "ONIX", "::", "Measure", ".", "new", "measure", ".", "measure_type_code", "=", "type", "product", ".", "measurements", "<<", "measure", "end", "# store the new value", "measure", ".", "measurement", "=", "value", "measure", ".", "measure_unit_code", "=", "unit", ".", "to_s", "end"], "docstring": "set the value of a particular measurement", "docstring_tokens": ["set", "the", "value", "of", "a", "particular", "measurement"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L665-L678", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/apa_product.rb", "func_name": "ONIX.APAProduct.price_get", "original_string": "def price_get(type)\n supply = find_or_create_supply_detail\n if type.nil?\n supply.prices.first\n else\n supply.prices.find { |p| p.price_type_code == type }\n end\n end", "language": "ruby", "code": "def price_get(type)\n supply = find_or_create_supply_detail\n if type.nil?\n supply.prices.first\n else\n supply.prices.find { |p| p.price_type_code == type }\n end\n end", "code_tokens": ["def", "price_get", "(", "type", ")", "supply", "=", "find_or_create_supply_detail", "if", "type", ".", "nil?", "supply", ".", "prices", ".", "first", "else", "supply", ".", "prices", ".", "find", "{", "|", "p", "|", "p", ".", "price_type_code", "==", "type", "}", "end", "end"], "docstring": "retrieve the value of a particular price", "docstring_tokens": ["retrieve", "the", "value", "of", "a", "particular", "price"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L702-L709", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/apa_product.rb", "func_name": "ONIX.APAProduct.price_set", "original_string": "def price_set(type, num)\n p = price_get(type)\n\n # create a new isbn record if we need to\n if p.nil?\n supply = find_or_create_supply_detail\n p = ONIX::Price.new\n p.price_type_code = type\n supply.prices << p\n end\n\n # store the new value\n p.price_amount = num\n end", "language": "ruby", "code": "def price_set(type, num)\n p = price_get(type)\n\n # create a new isbn record if we need to\n if p.nil?\n supply = find_or_create_supply_detail\n p = ONIX::Price.new\n p.price_type_code = type\n supply.prices << p\n end\n\n # store the new value\n p.price_amount = num\n end", "code_tokens": ["def", "price_set", "(", "type", ",", "num", ")", "p", "=", "price_get", "(", "type", ")", "# create a new isbn record if we need to", "if", "p", ".", "nil?", "supply", "=", "find_or_create_supply_detail", "p", "=", "ONIX", "::", "Price", ".", "new", "p", ".", "price_type_code", "=", "type", "supply", ".", "prices", "<<", "p", "end", "# store the new value", "p", ".", "price_amount", "=", "num", "end"], "docstring": "set the value of a particular price", "docstring_tokens": ["set", "the", "value", "of", "a", "particular", "price"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L712-L725", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/apa_product.rb", "func_name": "ONIX.APAProduct.other_text_set", "original_string": "def other_text_set(type, value)\n text = other_text(type)\n\n if text.nil?\n text = ONIX::OtherText.new\n text.text_type_code = type\n product.text << text\n end\n\n # store the new value\n text.text = value.to_s\n end", "language": "ruby", "code": "def other_text_set(type, value)\n text = other_text(type)\n\n if text.nil?\n text = ONIX::OtherText.new\n text.text_type_code = type\n product.text << text\n end\n\n # store the new value\n text.text = value.to_s\n end", "code_tokens": ["def", "other_text_set", "(", "type", ",", "value", ")", "text", "=", "other_text", "(", "type", ")", "if", "text", ".", "nil?", "text", "=", "ONIX", "::", "OtherText", ".", "new", "text", ".", "text_type_code", "=", "type", "product", ".", "text", "<<", "text", "end", "# store the new value", "text", ".", "text", "=", "value", ".", "to_s", "end"], "docstring": "set the value of a particular other text value", "docstring_tokens": ["set", "the", "value", "of", "a", "particular", "other", "text", "value"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L753-L764", "partition": "valid"} {"repo": "yob/onix", "path": "lib/onix/apa_product.rb", "func_name": "ONIX.APAProduct.website_set", "original_string": "def website_set(type, value)\n site = website(type)\n\n # create a new website record if we need to\n if site.nil?\n site = ONIX::Website.new\n site.website_role = type\n product.websites << site\n end\n\n site.website_link = value.to_s\n end", "language": "ruby", "code": "def website_set(type, value)\n site = website(type)\n\n # create a new website record if we need to\n if site.nil?\n site = ONIX::Website.new\n site.website_role = type\n product.websites << site\n end\n\n site.website_link = value.to_s\n end", "code_tokens": ["def", "website_set", "(", "type", ",", "value", ")", "site", "=", "website", "(", "type", ")", "# create a new website record if we need to", "if", "site", ".", "nil?", "site", "=", "ONIX", "::", "Website", ".", "new", "site", ".", "website_role", "=", "type", "product", ".", "websites", "<<", "site", "end", "site", ".", "website_link", "=", "value", ".", "to_s", "end"], "docstring": "set the value of a particular website", "docstring_tokens": ["set", "the", "value", "of", "a", "particular", "website"], "sha": "0d4c9a966f47868ea4dd01690e118bea87442ced", "url": "https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L772-L783", "partition": "valid"} {"repo": "thejchap/popular", "path": "lib/popular/popular.rb", "func_name": "Popular.Popular.befriend", "original_string": "def befriend new_friend\n run_callbacks :befriend do\n friendships.create friend_id: new_friend.id, friend_type: new_friend.class.name\n end\n end", "language": "ruby", "code": "def befriend new_friend\n run_callbacks :befriend do\n friendships.create friend_id: new_friend.id, friend_type: new_friend.class.name\n end\n end", "code_tokens": ["def", "befriend", "new_friend", "run_callbacks", ":befriend", "do", "friendships", ".", "create", "friend_id", ":", "new_friend", ".", "id", ",", "friend_type", ":", "new_friend", ".", "class", ".", "name", "end", "end"], "docstring": "Adds a friend to an instance's friend's list\n\n @param [Object] new_friend a popular_model that the instance is not already friends with\n\n @example\n user = User.create name: \"Justin\"\n other_user = User.create name: \"Jenny\"\n user.befriend other_user\n\n user.friends_with? other_user #=> true", "docstring_tokens": ["Adds", "a", "friend", "to", "an", "instance", "s", "friend", "s", "list"], "sha": "9c0b63c9409b3e2bc0bbd356c60eead04de7a4df", "url": "https://github.com/thejchap/popular/blob/9c0b63c9409b3e2bc0bbd356c60eead04de7a4df/lib/popular/popular.rb#L49-L53", "partition": "valid"} {"repo": "thejchap/popular", "path": "lib/popular/popular.rb", "func_name": "Popular.Popular.befriend!", "original_string": "def befriend! new_friend\n run_callbacks :befriend do\n friendships.create! friend_id: new_friend.id, friend_type: new_friend.class.name\n end\n end", "language": "ruby", "code": "def befriend! new_friend\n run_callbacks :befriend do\n friendships.create! friend_id: new_friend.id, friend_type: new_friend.class.name\n end\n end", "code_tokens": ["def", "befriend!", "new_friend", "run_callbacks", ":befriend", "do", "friendships", ".", "create!", "friend_id", ":", "new_friend", ".", "id", ",", "friend_type", ":", "new_friend", ".", "class", ".", "name", "end", "end"], "docstring": "Adds a friend to an instance's friend's list\n Similar to .befriend, but will raise an error if the operation is not successful\n\n @param [Object] new_friend a popular_model that the instance is not already friends with\n\n @example\n user = User.create name: \"Justin\"\n other_user = User.create name: \"Jenny\"\n user.befriend! other_user\n\n user.friends_with? other_user # => true", "docstring_tokens": ["Adds", "a", "friend", "to", "an", "instance", "s", "friend", "s", "list", "Similar", "to", ".", "befriend", "but", "will", "raise", "an", "error", "if", "the", "operation", "is", "not", "successful"], "sha": "9c0b63c9409b3e2bc0bbd356c60eead04de7a4df", "url": "https://github.com/thejchap/popular/blob/9c0b63c9409b3e2bc0bbd356c60eead04de7a4df/lib/popular/popular.rb#L66-L70", "partition": "valid"} {"repo": "thejchap/popular", "path": "lib/popular/popular.rb", "func_name": "Popular.Popular.unfriend", "original_string": "def unfriend friend\n run_callbacks :unfriend do\n friendships\n .where( friend_type: friend.class.name )\n .where( friend_id: friend.id )\n .first.destroy\n end\n end", "language": "ruby", "code": "def unfriend friend\n run_callbacks :unfriend do\n friendships\n .where( friend_type: friend.class.name )\n .where( friend_id: friend.id )\n .first.destroy\n end\n end", "code_tokens": ["def", "unfriend", "friend", "run_callbacks", ":unfriend", "do", "friendships", ".", "where", "(", "friend_type", ":", "friend", ".", "class", ".", "name", ")", ".", "where", "(", "friend_id", ":", "friend", ".", "id", ")", ".", "first", ".", "destroy", "end", "end"], "docstring": "Removes a friend from an instance's friend's list\n\n @param [Object] friend a popular_model in this instance's friends list\n\n @example\n user = User.create name: \"Justin\"\n other_user = User.create name: \"Jenny\"\n user.befriend other_user\n user.unfriend other_user\n\n user.friends_with? other_user # => false", "docstring_tokens": ["Removes", "a", "friend", "from", "an", "instance", "s", "friend", "s", "list"], "sha": "9c0b63c9409b3e2bc0bbd356c60eead04de7a4df", "url": "https://github.com/thejchap/popular/blob/9c0b63c9409b3e2bc0bbd356c60eead04de7a4df/lib/popular/popular.rb#L83-L90", "partition": "valid"} {"repo": "ferndopolis/timecop-console", "path": "lib/timecop_console/controller_methods.rb", "func_name": "TimecopConsole.ControllerMethods.handle_timecop_offset", "original_string": "def handle_timecop_offset\n # Establish now\n if session[TimecopConsole::SESSION_KEY_NAME].present?\n Rails.logger.debug \"[timecop-console] Time traveling to #{session[TimecopConsole::SESSION_KEY_NAME].to_s}\"\n Timecop.travel(session[TimecopConsole::SESSION_KEY_NAME])\n else\n Timecop.return\n end\n\n # Run the intended action\n yield\n\n if session[TimecopConsole::SESSION_KEY_NAME].present?\n # we want to continue to slide time forward, even if it's only 3 seconds at a time.\n # this ensures that subsequent calls during the same \"time travel\" actually pass time\n adjusted_time = Time.now + 3\n Rails.logger.debug \"[timecop-console] Resetting session to: #{adjusted_time}\"\n session[TimecopConsole::SESSION_KEY_NAME] = adjusted_time\n end\n end", "language": "ruby", "code": "def handle_timecop_offset\n # Establish now\n if session[TimecopConsole::SESSION_KEY_NAME].present?\n Rails.logger.debug \"[timecop-console] Time traveling to #{session[TimecopConsole::SESSION_KEY_NAME].to_s}\"\n Timecop.travel(session[TimecopConsole::SESSION_KEY_NAME])\n else\n Timecop.return\n end\n\n # Run the intended action\n yield\n\n if session[TimecopConsole::SESSION_KEY_NAME].present?\n # we want to continue to slide time forward, even if it's only 3 seconds at a time.\n # this ensures that subsequent calls during the same \"time travel\" actually pass time\n adjusted_time = Time.now + 3\n Rails.logger.debug \"[timecop-console] Resetting session to: #{adjusted_time}\"\n session[TimecopConsole::SESSION_KEY_NAME] = adjusted_time\n end\n end", "code_tokens": ["def", "handle_timecop_offset", "# Establish now", "if", "session", "[", "TimecopConsole", "::", "SESSION_KEY_NAME", "]", ".", "present?", "Rails", ".", "logger", ".", "debug", "\"[timecop-console] Time traveling to #{session[TimecopConsole::SESSION_KEY_NAME].to_s}\"", "Timecop", ".", "travel", "(", "session", "[", "TimecopConsole", "::", "SESSION_KEY_NAME", "]", ")", "else", "Timecop", ".", "return", "end", "# Run the intended action", "yield", "if", "session", "[", "TimecopConsole", "::", "SESSION_KEY_NAME", "]", ".", "present?", "# we want to continue to slide time forward, even if it's only 3 seconds at a time.", "# this ensures that subsequent calls during the same \"time travel\" actually pass time", "adjusted_time", "=", "Time", ".", "now", "+", "3", "Rails", ".", "logger", ".", "debug", "\"[timecop-console] Resetting session to: #{adjusted_time}\"", "session", "[", "TimecopConsole", "::", "SESSION_KEY_NAME", "]", "=", "adjusted_time", "end", "end"], "docstring": "to be used as an around_filter", "docstring_tokens": ["to", "be", "used", "as", "an", "around_filter"], "sha": "30491e690e9882701ef0609e2fe87b3573b5efcb", "url": "https://github.com/ferndopolis/timecop-console/blob/30491e690e9882701ef0609e2fe87b3573b5efcb/lib/timecop_console/controller_methods.rb#L11-L30", "partition": "valid"} {"repo": "bf4/code_metrics", "path": "lib/code_metrics/stats_directories.rb", "func_name": "CodeMetrics.StatsDirectories.default_app_directories", "original_string": "def default_app_directories\n StatDirectory.from_list([\n %w(Controllers app/controllers),\n %w(Helpers app/helpers),\n %w(Models app/models),\n %w(Mailers app/mailers),\n %w(Javascripts app/assets/javascripts),\n %w(Libraries lib),\n %w(APIs app/apis)\n ], @root)\n end", "language": "ruby", "code": "def default_app_directories\n StatDirectory.from_list([\n %w(Controllers app/controllers),\n %w(Helpers app/helpers),\n %w(Models app/models),\n %w(Mailers app/mailers),\n %w(Javascripts app/assets/javascripts),\n %w(Libraries lib),\n %w(APIs app/apis)\n ], @root)\n end", "code_tokens": ["def", "default_app_directories", "StatDirectory", ".", "from_list", "(", "[", "%w(", "Controllers", "app/controllers", ")", ",", "%w(", "Helpers", "app/helpers", ")", ",", "%w(", "Models", "app/models", ")", ",", "%w(", "Mailers", "app/mailers", ")", ",", "%w(", "Javascripts", "app/assets/javascripts", ")", ",", "%w(", "Libraries", "lib", ")", ",", "%w(", "APIs", "app/apis", ")", "]", ",", "@root", ")", "end"], "docstring": "What Rails expects", "docstring_tokens": ["What", "Rails", "expects"], "sha": "115cb539ccc494ac151c34a5d61b4e010e45d21b", "url": "https://github.com/bf4/code_metrics/blob/115cb539ccc494ac151c34a5d61b4e010e45d21b/lib/code_metrics/stats_directories.rb#L38-L48", "partition": "valid"} {"repo": "bf4/code_metrics", "path": "lib/code_metrics/stats_directories.rb", "func_name": "CodeMetrics.StatsDirectories.collect_directories", "original_string": "def collect_directories(glob_pattern, file_pattern='')\n Pathname.glob(glob_pattern).select{|f| f.basename.to_s.include?(file_pattern) }.map(&:dirname).uniq.map(&:realpath)\n end", "language": "ruby", "code": "def collect_directories(glob_pattern, file_pattern='')\n Pathname.glob(glob_pattern).select{|f| f.basename.to_s.include?(file_pattern) }.map(&:dirname).uniq.map(&:realpath)\n end", "code_tokens": ["def", "collect_directories", "(", "glob_pattern", ",", "file_pattern", "=", "''", ")", "Pathname", ".", "glob", "(", "glob_pattern", ")", ".", "select", "{", "|", "f", "|", "f", ".", "basename", ".", "to_s", ".", "include?", "(", "file_pattern", ")", "}", ".", "map", "(", ":dirname", ")", ".", "uniq", ".", "map", "(", ":realpath", ")", "end"], "docstring": "collects non empty directories and names the metric by the folder name\n parent? or dirname? or basename?", "docstring_tokens": ["collects", "non", "empty", "directories", "and", "names", "the", "metric", "by", "the", "folder", "name", "parent?", "or", "dirname?", "or", "basename?"], "sha": "115cb539ccc494ac151c34a5d61b4e010e45d21b", "url": "https://github.com/bf4/code_metrics/blob/115cb539ccc494ac151c34a5d61b4e010e45d21b/lib/code_metrics/stats_directories.rb#L107-L109", "partition": "valid"} {"repo": "wejn/ws2812", "path": "lib/ws2812/basic.rb", "func_name": "Ws2812.Basic.[]=", "original_string": "def []=(index, color)\n\t\t\tif index.respond_to?(:to_a)\n\t\t\t\tindex.to_a.each do |i|\n\t\t\t\t\tcheck_index(i)\n\t\t\t\t\tws2811_led_set(@channel, i, color.to_i)\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tcheck_index(index)\n\t\t\t\tws2811_led_set(@channel, index, color.to_i)\n\t\t\tend\n\t\tend", "language": "ruby", "code": "def []=(index, color)\n\t\t\tif index.respond_to?(:to_a)\n\t\t\t\tindex.to_a.each do |i|\n\t\t\t\t\tcheck_index(i)\n\t\t\t\t\tws2811_led_set(@channel, i, color.to_i)\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tcheck_index(index)\n\t\t\t\tws2811_led_set(@channel, index, color.to_i)\n\t\t\tend\n\t\tend", "code_tokens": ["def", "[]=", "(", "index", ",", "color", ")", "if", "index", ".", "respond_to?", "(", ":to_a", ")", "index", ".", "to_a", ".", "each", "do", "|", "i", "|", "check_index", "(", "i", ")", "ws2811_led_set", "(", "@channel", ",", "i", ",", "color", ".", "to_i", ")", "end", "else", "check_index", "(", "index", ")", "ws2811_led_set", "(", "@channel", ",", "index", ",", "color", ".", "to_i", ")", "end", "end"], "docstring": "Set given pixel identified by +index+ to +color+\n\n See +set+ for a method that takes individual +r+, +g+, +b+\n components", "docstring_tokens": ["Set", "given", "pixel", "identified", "by", "+", "index", "+", "to", "+", "color", "+"], "sha": "69195f827052e30f989e8502f0caabb19b343dfd", "url": "https://github.com/wejn/ws2812/blob/69195f827052e30f989e8502f0caabb19b343dfd/lib/ws2812/basic.rb#L116-L126", "partition": "valid"} {"repo": "wejn/ws2812", "path": "lib/ws2812/basic.rb", "func_name": "Ws2812.Basic.set", "original_string": "def set(index, r, g, b)\n\t\t\tcheck_index(index)\n\t\t\tself[index] = Color.new(r, g, b)\n\t\tend", "language": "ruby", "code": "def set(index, r, g, b)\n\t\t\tcheck_index(index)\n\t\t\tself[index] = Color.new(r, g, b)\n\t\tend", "code_tokens": ["def", "set", "(", "index", ",", "r", ",", "g", ",", "b", ")", "check_index", "(", "index", ")", "self", "[", "index", "]", "=", "Color", ".", "new", "(", "r", ",", "g", ",", "b", ")", "end"], "docstring": "Set given pixel identified by +index+ to +r+, +g+, +b+\n\n See []= for a method that takes +Color+ instance instead\n of individual components", "docstring_tokens": ["Set", "given", "pixel", "identified", "by", "+", "index", "+", "to", "+", "r", "+", "+", "g", "+", "+", "b", "+"], "sha": "69195f827052e30f989e8502f0caabb19b343dfd", "url": "https://github.com/wejn/ws2812/blob/69195f827052e30f989e8502f0caabb19b343dfd/lib/ws2812/basic.rb#L133-L136", "partition": "valid"} {"repo": "wejn/ws2812", "path": "lib/ws2812/basic.rb", "func_name": "Ws2812.Basic.[]", "original_string": "def [](index)\n\t\t\tif index.respond_to?(:to_a)\n\t\t\t\tindex.to_a.map do |i|\n\t\t\t\t\tcheck_index(i)\n\t\t\t\t\tColor.from_i(ws2811_led_get(@channel, i))\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tcheck_index(index)\n\t\t\t\tColor.from_i(ws2811_led_get(@channel, index))\n\t\t\tend\n\t\tend", "language": "ruby", "code": "def [](index)\n\t\t\tif index.respond_to?(:to_a)\n\t\t\t\tindex.to_a.map do |i|\n\t\t\t\t\tcheck_index(i)\n\t\t\t\t\tColor.from_i(ws2811_led_get(@channel, i))\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tcheck_index(index)\n\t\t\t\tColor.from_i(ws2811_led_get(@channel, index))\n\t\t\tend\n\t\tend", "code_tokens": ["def", "[]", "(", "index", ")", "if", "index", ".", "respond_to?", "(", ":to_a", ")", "index", ".", "to_a", ".", "map", "do", "|", "i", "|", "check_index", "(", "i", ")", "Color", ".", "from_i", "(", "ws2811_led_get", "(", "@channel", ",", "i", ")", ")", "end", "else", "check_index", "(", "index", ")", "Color", ".", "from_i", "(", "ws2811_led_get", "(", "@channel", ",", "index", ")", ")", "end", "end"], "docstring": "Return +Color+ of led located at given index\n\n Indexed from 0 upto #count - 1", "docstring_tokens": ["Return", "+", "Color", "+", "of", "led", "located", "at", "given", "index"], "sha": "69195f827052e30f989e8502f0caabb19b343dfd", "url": "https://github.com/wejn/ws2812/blob/69195f827052e30f989e8502f0caabb19b343dfd/lib/ws2812/basic.rb#L169-L179", "partition": "valid"} {"repo": "jkeiser/knife-essentials", "path": "lib/chef_fs/config.rb", "func_name": "ChefFS.Config.format_path", "original_string": "def format_path(entry)\n server_path = entry.path\n if base_path && server_path[0,base_path.length] == base_path\n if server_path == base_path\n return \".\"\n elsif server_path[base_path.length,1] == \"/\"\n return server_path[base_path.length + 1, server_path.length - base_path.length - 1]\n elsif base_path == \"/\" && server_path[0,1] == \"/\"\n return server_path[1, server_path.length - 1]\n end\n end\n server_path\n end", "language": "ruby", "code": "def format_path(entry)\n server_path = entry.path\n if base_path && server_path[0,base_path.length] == base_path\n if server_path == base_path\n return \".\"\n elsif server_path[base_path.length,1] == \"/\"\n return server_path[base_path.length + 1, server_path.length - base_path.length - 1]\n elsif base_path == \"/\" && server_path[0,1] == \"/\"\n return server_path[1, server_path.length - 1]\n end\n end\n server_path\n end", "code_tokens": ["def", "format_path", "(", "entry", ")", "server_path", "=", "entry", ".", "path", "if", "base_path", "&&", "server_path", "[", "0", ",", "base_path", ".", "length", "]", "==", "base_path", "if", "server_path", "==", "base_path", "return", "\".\"", "elsif", "server_path", "[", "base_path", ".", "length", ",", "1", "]", "==", "\"/\"", "return", "server_path", "[", "base_path", ".", "length", "+", "1", ",", "server_path", ".", "length", "-", "base_path", ".", "length", "-", "1", "]", "elsif", "base_path", "==", "\"/\"", "&&", "server_path", "[", "0", ",", "1", "]", "==", "\"/\"", "return", "server_path", "[", "1", ",", "server_path", ".", "length", "-", "1", "]", "end", "end", "server_path", "end"], "docstring": "Print the given server path, relative to the current directory", "docstring_tokens": ["Print", "the", "given", "server", "path", "relative", "to", "the", "current", "directory"], "sha": "ae8dcebd4694e9bda618eac52228d07d88813ce8", "url": "https://github.com/jkeiser/knife-essentials/blob/ae8dcebd4694e9bda618eac52228d07d88813ce8/lib/chef_fs/config.rb#L118-L130", "partition": "valid"} {"repo": "jkeiser/knife-essentials", "path": "lib/chef_fs/file_pattern.rb", "func_name": "ChefFS.FilePattern.exact_path", "original_string": "def exact_path\n return nil if has_double_star || exact_parts.any? { |part| part.nil? }\n result = ChefFS::PathUtils::join(*exact_parts)\n is_absolute ? ChefFS::PathUtils::join('', result) : result\n end", "language": "ruby", "code": "def exact_path\n return nil if has_double_star || exact_parts.any? { |part| part.nil? }\n result = ChefFS::PathUtils::join(*exact_parts)\n is_absolute ? ChefFS::PathUtils::join('', result) : result\n end", "code_tokens": ["def", "exact_path", "return", "nil", "if", "has_double_star", "||", "exact_parts", ".", "any?", "{", "|", "part", "|", "part", ".", "nil?", "}", "result", "=", "ChefFS", "::", "PathUtils", "::", "join", "(", "exact_parts", ")", "is_absolute", "?", "ChefFS", "::", "PathUtils", "::", "join", "(", "''", ",", "result", ")", ":", "result", "end"], "docstring": "If this pattern represents an exact path, returns the exact path.\n\n abc/def.exact_path == 'abc/def'\n abc/*def.exact_path == 'abc/def'\n abc/x\\\\yz.exact_path == 'abc/xyz'", "docstring_tokens": ["If", "this", "pattern", "represents", "an", "exact", "path", "returns", "the", "exact", "path", "."], "sha": "ae8dcebd4694e9bda618eac52228d07d88813ce8", "url": "https://github.com/jkeiser/knife-essentials/blob/ae8dcebd4694e9bda618eac52228d07d88813ce8/lib/chef_fs/file_pattern.rb#L124-L128", "partition": "valid"} {"repo": "wejn/ws2812", "path": "lib/ws2812/unicornhat.rb", "func_name": "Ws2812.UnicornHAT.[]=", "original_string": "def []=(x, y, color)\n\t\t\tcheck_coords(x, y)\n\t\t\t@pixels[x][y] = color\n\t\t\t@hat[map_coords(x, y)] = color\n\t\tend", "language": "ruby", "code": "def []=(x, y, color)\n\t\t\tcheck_coords(x, y)\n\t\t\t@pixels[x][y] = color\n\t\t\t@hat[map_coords(x, y)] = color\n\t\tend", "code_tokens": ["def", "[]=", "(", "x", ",", "y", ",", "color", ")", "check_coords", "(", "x", ",", "y", ")", "@pixels", "[", "x", "]", "[", "y", "]", "=", "color", "@hat", "[", "map_coords", "(", "x", ",", "y", ")", "]", "=", "color", "end"], "docstring": "Set given pixel identified by +x+, +y+ to +color+\n\n See +set+ for a method that takes individual +r+, +g+, +b+\n components.\n\n You still have to call +show+ to make the changes visible.", "docstring_tokens": ["Set", "given", "pixel", "identified", "by", "+", "x", "+", "+", "y", "+", "to", "+", "color", "+"], "sha": "69195f827052e30f989e8502f0caabb19b343dfd", "url": "https://github.com/wejn/ws2812/blob/69195f827052e30f989e8502f0caabb19b343dfd/lib/ws2812/unicornhat.rb#L79-L83", "partition": "valid"} {"repo": "wejn/ws2812", "path": "lib/ws2812/unicornhat.rb", "func_name": "Ws2812.UnicornHAT.set", "original_string": "def set(x, y, r, g, b)\n\t\t\tcheck_coords(x, y)\n\t\t\tself[x, y] = Color.new(r, g, b)\n\t\tend", "language": "ruby", "code": "def set(x, y, r, g, b)\n\t\t\tcheck_coords(x, y)\n\t\t\tself[x, y] = Color.new(r, g, b)\n\t\tend", "code_tokens": ["def", "set", "(", "x", ",", "y", ",", "r", ",", "g", ",", "b", ")", "check_coords", "(", "x", ",", "y", ")", "self", "[", "x", ",", "y", "]", "=", "Color", ".", "new", "(", "r", ",", "g", ",", "b", ")", "end"], "docstring": "Set given pixel identified by +x+, +y+ to +r+, +g+, +b+\n\n See []= for a method that takes +Color+ instance instead\n of individual components.\n\n You still have to call +show+ to make the changes visible.", "docstring_tokens": ["Set", "given", "pixel", "identified", "by", "+", "x", "+", "+", "y", "+", "to", "+", "r", "+", "+", "g", "+", "+", "b", "+"], "sha": "69195f827052e30f989e8502f0caabb19b343dfd", "url": "https://github.com/wejn/ws2812/blob/69195f827052e30f989e8502f0caabb19b343dfd/lib/ws2812/unicornhat.rb#L92-L95", "partition": "valid"} {"repo": "wejn/ws2812", "path": "lib/ws2812/unicornhat.rb", "func_name": "Ws2812.UnicornHAT.rotation=", "original_string": "def rotation=(val)\n\t\t\tpermissible = [0, 90, 180, 270]\n\t\t\tfail ArgumentError, \"invalid rotation, permissible: #{permissible.join(', ')}\" unless permissible.include?(val % 360)\n\t\t\t@rotation = val % 360\n\t\t\tpush_all_pixels\n\t\tend", "language": "ruby", "code": "def rotation=(val)\n\t\t\tpermissible = [0, 90, 180, 270]\n\t\t\tfail ArgumentError, \"invalid rotation, permissible: #{permissible.join(', ')}\" unless permissible.include?(val % 360)\n\t\t\t@rotation = val % 360\n\t\t\tpush_all_pixels\n\t\tend", "code_tokens": ["def", "rotation", "=", "(", "val", ")", "permissible", "=", "[", "0", ",", "90", ",", "180", ",", "270", "]", "fail", "ArgumentError", ",", "\"invalid rotation, permissible: #{permissible.join(', ')}\"", "unless", "permissible", ".", "include?", "(", "val", "%", "360", ")", "@rotation", "=", "val", "%", "360", "push_all_pixels", "end"], "docstring": "Set rotation of the Unicorn HAT to +val+\n\n Permissible values for rotation are [0, 90, 180, 270] (mod 360).\n\n You still have to call +show+ to make the changes visible.", "docstring_tokens": ["Set", "rotation", "of", "the", "Unicorn", "HAT", "to", "+", "val", "+"], "sha": "69195f827052e30f989e8502f0caabb19b343dfd", "url": "https://github.com/wejn/ws2812/blob/69195f827052e30f989e8502f0caabb19b343dfd/lib/ws2812/unicornhat.rb#L135-L140", "partition": "valid"} {"repo": "wejn/ws2812", "path": "lib/ws2812/unicornhat.rb", "func_name": "Ws2812.UnicornHAT.check_coords", "original_string": "def check_coords(x, y)\n\t\t\tif 0 <= x && x < 8 && 0 <= y && y < 8\n\t\t\t\ttrue\n\t\t\telse\n\t\t\t\tfail ArgumentError, \"coord (#{x},#{y}) outside of permitted range ((0..7), (0..7))\"\n\t\t\tend\n\t\tend", "language": "ruby", "code": "def check_coords(x, y)\n\t\t\tif 0 <= x && x < 8 && 0 <= y && y < 8\n\t\t\t\ttrue\n\t\t\telse\n\t\t\t\tfail ArgumentError, \"coord (#{x},#{y}) outside of permitted range ((0..7), (0..7))\"\n\t\t\tend\n\t\tend", "code_tokens": ["def", "check_coords", "(", "x", ",", "y", ")", "if", "0", "<=", "x", "&&", "x", "<", "8", "&&", "0", "<=", "y", "&&", "y", "<", "8", "true", "else", "fail", "ArgumentError", ",", "\"coord (#{x},#{y}) outside of permitted range ((0..7), (0..7))\"", "end", "end"], "docstring": "Verify supplied coords +x+ and +y+\n\n Raises ArgumentError if the supplied coords are invalid\n (doesn't address configured pixel)", "docstring_tokens": ["Verify", "supplied", "coords", "+", "x", "+", "and", "+", "y", "+"], "sha": "69195f827052e30f989e8502f0caabb19b343dfd", "url": "https://github.com/wejn/ws2812/blob/69195f827052e30f989e8502f0caabb19b343dfd/lib/ws2812/unicornhat.rb#L200-L206", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/models/model.rb", "func_name": "Pupa.Model.validate!", "original_string": "def validate!\n if self.class.json_schema\n self.class.validator.instance_variable_set('@errors', [])\n self.class.validator.instance_variable_set('@data', stringify_keys(to_h(persist: true)))\n self.class.validator.validate\n true\n end\n end", "language": "ruby", "code": "def validate!\n if self.class.json_schema\n self.class.validator.instance_variable_set('@errors', [])\n self.class.validator.instance_variable_set('@data', stringify_keys(to_h(persist: true)))\n self.class.validator.validate\n true\n end\n end", "code_tokens": ["def", "validate!", "if", "self", ".", "class", ".", "json_schema", "self", ".", "class", ".", "validator", ".", "instance_variable_set", "(", "'@errors'", ",", "[", "]", ")", "self", ".", "class", ".", "validator", ".", "instance_variable_set", "(", "'@data'", ",", "stringify_keys", "(", "to_h", "(", "persist", ":", "true", ")", ")", ")", "self", ".", "class", ".", "validator", ".", "validate", "true", "end", "end"], "docstring": "Validates the object against the schema.\n\n @raises [JSON::Schema::ValidationError] if the object is invalid", "docstring_tokens": ["Validates", "the", "object", "against", "the", "schema", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/models/model.rb#L165-L172", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/models/model.rb", "func_name": "Pupa.Model.to_h", "original_string": "def to_h(persist: false)\n {}.tap do |hash|\n (persist ? properties - foreign_objects : properties).each do |property|\n value = self[property]\n if value == false || value.present?\n hash[property] = value\n end\n end\n end\n end", "language": "ruby", "code": "def to_h(persist: false)\n {}.tap do |hash|\n (persist ? properties - foreign_objects : properties).each do |property|\n value = self[property]\n if value == false || value.present?\n hash[property] = value\n end\n end\n end\n end", "code_tokens": ["def", "to_h", "(", "persist", ":", "false", ")", "{", "}", ".", "tap", "do", "|", "hash", "|", "(", "persist", "?", "properties", "-", "foreign_objects", ":", "properties", ")", ".", "each", "do", "|", "property", "|", "value", "=", "self", "[", "property", "]", "if", "value", "==", "false", "||", "value", ".", "present?", "hash", "[", "property", "]", "=", "value", "end", "end", "end", "end"], "docstring": "Returns the object as a hash.\n\n @param [Boolean] persist whether the object is being persisted, validated,\n or used as a database selector, in which case foreign objects (hints)\n are excluded\n @return [Hash] the object as a hash", "docstring_tokens": ["Returns", "the", "object", "as", "a", "hash", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/models/model.rb#L180-L189", "partition": "valid"} {"repo": "shawn42/tmx", "path": "lib/tmx/map.rb", "func_name": "Tmx.Map.export_to_file", "original_string": "def export_to_file(filename, options={})\n content_string = export_to_string(default_options(filename).merge(:filename => filename))\n File.open(filename, \"w\") { |f| f.write(content_string) }\n nil\n end", "language": "ruby", "code": "def export_to_file(filename, options={})\n content_string = export_to_string(default_options(filename).merge(:filename => filename))\n File.open(filename, \"w\") { |f| f.write(content_string) }\n nil\n end", "code_tokens": ["def", "export_to_file", "(", "filename", ",", "options", "=", "{", "}", ")", "content_string", "=", "export_to_string", "(", "default_options", "(", "filename", ")", ".", "merge", "(", ":filename", "=>", "filename", ")", ")", "File", ".", "open", "(", "filename", ",", "\"w\"", ")", "{", "|", "f", "|", "f", ".", "write", "(", "content_string", ")", "}", "nil", "end"], "docstring": "Export this map to the given filename in the appropriate format.\n\n @param filename [String] The file path to export to\n @param options [Hash] Options for exporting\n @option options [Symbol] format The format to export to, such as :tmx or :json\n @return [void]", "docstring_tokens": ["Export", "this", "map", "to", "the", "given", "filename", "in", "the", "appropriate", "format", "."], "sha": "9c1948e586781610b926b6019db21e0894118d33", "url": "https://github.com/shawn42/tmx/blob/9c1948e586781610b926b6019db21e0894118d33/lib/tmx/map.rb#L19-L23", "partition": "valid"} {"repo": "shawn42/tmx", "path": "lib/tmx/map.rb", "func_name": "Tmx.Map.export_to_string", "original_string": "def export_to_string(options = {})\n hash = self.to_h\n\n # Need to add back all non-tilelayers to hash[\"layers\"]\n image_layers = hash.delete(:image_layers)\n object_groups = hash.delete(:object_groups)\n hash[:layers] += image_layers\n hash[:layers] += object_groups\n hash[:layers].sort_by! { |l| l[:name] }\n hash.delete(:contents)\n\n object_groups.each do |object_layer|\n object_layer[\"objects\"].each do |object|\n # If present, \"shape\" and \"points\" should be removed\n object.delete(\"shape\")\n object.delete(\"points\")\n end\n end\n\n MultiJson.dump(hash)\n end", "language": "ruby", "code": "def export_to_string(options = {})\n hash = self.to_h\n\n # Need to add back all non-tilelayers to hash[\"layers\"]\n image_layers = hash.delete(:image_layers)\n object_groups = hash.delete(:object_groups)\n hash[:layers] += image_layers\n hash[:layers] += object_groups\n hash[:layers].sort_by! { |l| l[:name] }\n hash.delete(:contents)\n\n object_groups.each do |object_layer|\n object_layer[\"objects\"].each do |object|\n # If present, \"shape\" and \"points\" should be removed\n object.delete(\"shape\")\n object.delete(\"points\")\n end\n end\n\n MultiJson.dump(hash)\n end", "code_tokens": ["def", "export_to_string", "(", "options", "=", "{", "}", ")", "hash", "=", "self", ".", "to_h", "# Need to add back all non-tilelayers to hash[\"layers\"]", "image_layers", "=", "hash", ".", "delete", "(", ":image_layers", ")", "object_groups", "=", "hash", ".", "delete", "(", ":object_groups", ")", "hash", "[", ":layers", "]", "+=", "image_layers", "hash", "[", ":layers", "]", "+=", "object_groups", "hash", "[", ":layers", "]", ".", "sort_by!", "{", "|", "l", "|", "l", "[", ":name", "]", "}", "hash", ".", "delete", "(", ":contents", ")", "object_groups", ".", "each", "do", "|", "object_layer", "|", "object_layer", "[", "\"objects\"", "]", ".", "each", "do", "|", "object", "|", "# If present, \"shape\" and \"points\" should be removed", "object", ".", "delete", "(", "\"shape\"", ")", "object", ".", "delete", "(", "\"points\"", ")", "end", "end", "MultiJson", ".", "dump", "(", "hash", ")", "end"], "docstring": "Export this map as a string in the appropriate format.\n\n @param options [Hash] Options for exporting\n @option options [Symbol,String] :format The format to export to, such as :tmx or :json\n @option options [String] :filename The eventual filename, which gives a relative path for linked TSX files\n @return [String] The exported content in the appropriate format", "docstring_tokens": ["Export", "this", "map", "as", "a", "string", "in", "the", "appropriate", "format", "."], "sha": "9c1948e586781610b926b6019db21e0894118d33", "url": "https://github.com/shawn42/tmx/blob/9c1948e586781610b926b6019db21e0894118d33/lib/tmx/map.rb#L33-L53", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/processor.rb", "func_name": "Pupa.Processor.dump_scraped_objects", "original_string": "def dump_scraped_objects(task_name)\n counts = Hash.new(0)\n @store.pipelined do\n send(task_name).each do |object|\n counts[object._type] += 1\n dump_scraped_object(object)\n end\n end\n counts\n end", "language": "ruby", "code": "def dump_scraped_objects(task_name)\n counts = Hash.new(0)\n @store.pipelined do\n send(task_name).each do |object|\n counts[object._type] += 1\n dump_scraped_object(object)\n end\n end\n counts\n end", "code_tokens": ["def", "dump_scraped_objects", "(", "task_name", ")", "counts", "=", "Hash", ".", "new", "(", "0", ")", "@store", ".", "pipelined", "do", "send", "(", "task_name", ")", ".", "each", "do", "|", "object", "|", "counts", "[", "object", ".", "_type", "]", "+=", "1", "dump_scraped_object", "(", "object", ")", "end", "end", "counts", "end"], "docstring": "Dumps scraped objects to disk.\n\n @param [Symbol] task_name the name of the scraping task to perform\n @return [Hash] the number of scraped objects by type\n @raises [Pupa::Errors::DuplicateObjectIdError]", "docstring_tokens": ["Dumps", "scraped", "objects", "to", "disk", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L112-L121", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/processor.rb", "func_name": "Pupa.Processor.import", "original_string": "def import\n @report[:import] = {}\n\n objects = deduplicate(load_scraped_objects)\n\n object_id_to_database_id = {}\n\n if use_dependency_graph?(objects)\n dependency_graph = build_dependency_graph(objects)\n\n # Replace object IDs with database IDs in foreign keys and save objects.\n dependency_graph.tsort.each do |id|\n object = objects[id]\n resolve_foreign_keys(object, object_id_to_database_id)\n # The dependency graph strategy only works if there are no foreign objects.\n\n database_id = import_object(object)\n object_id_to_database_id[id] = database_id\n object_id_to_database_id[database_id] = database_id\n end\n else\n size = objects.size\n\n # Should be O(n\u00b2). If there are foreign objects, we do not know all the\n # edges in the graph, and therefore cannot build a dependency graph or\n # derive any evaluation order.\n #\n # An exception is raised if a foreign object matches multiple documents\n # in the database. However, if a matching object is not yet saved, this\n # exception may not be raised.\n loop do\n progress_made = false\n\n objects.delete_if do |id,object|\n begin\n resolve_foreign_keys(object, object_id_to_database_id)\n resolve_foreign_objects(object, object_id_to_database_id)\n progress_made = true\n\n database_id = import_object(object)\n object_id_to_database_id[id] = database_id\n object_id_to_database_id[database_id] = database_id\n rescue Pupa::Errors::MissingDatabaseIdError\n false\n end\n end\n\n break if objects.empty? || !progress_made\n end\n\n unless objects.empty?\n raise Errors::UnprocessableEntity, \"couldn't resolve #{objects.size}/#{size} objects:\\n #{objects.values.map{|object| JSON.dump(object.foreign_properties)}.join(\"\\n \")}\"\n end\n end\n\n # Ensure that fingerprints uniquely identified objects.\n counts = {}\n object_id_to_database_id.each do |object_id,database_id|\n unless object_id == database_id\n (counts[database_id] ||= []) << object_id\n end\n end\n duplicates = counts.select do |_,object_ids|\n object_ids.size > 1\n end\n unless duplicates.empty?\n raise Errors::DuplicateDocumentError, \"multiple objects written to same document:\\n\" + duplicates.map{|database_id,object_ids| \" #{database_id} <- #{object_ids.join(' ')}\"}.join(\"\\n\")\n end\n end", "language": "ruby", "code": "def import\n @report[:import] = {}\n\n objects = deduplicate(load_scraped_objects)\n\n object_id_to_database_id = {}\n\n if use_dependency_graph?(objects)\n dependency_graph = build_dependency_graph(objects)\n\n # Replace object IDs with database IDs in foreign keys and save objects.\n dependency_graph.tsort.each do |id|\n object = objects[id]\n resolve_foreign_keys(object, object_id_to_database_id)\n # The dependency graph strategy only works if there are no foreign objects.\n\n database_id = import_object(object)\n object_id_to_database_id[id] = database_id\n object_id_to_database_id[database_id] = database_id\n end\n else\n size = objects.size\n\n # Should be O(n\u00b2). If there are foreign objects, we do not know all the\n # edges in the graph, and therefore cannot build a dependency graph or\n # derive any evaluation order.\n #\n # An exception is raised if a foreign object matches multiple documents\n # in the database. However, if a matching object is not yet saved, this\n # exception may not be raised.\n loop do\n progress_made = false\n\n objects.delete_if do |id,object|\n begin\n resolve_foreign_keys(object, object_id_to_database_id)\n resolve_foreign_objects(object, object_id_to_database_id)\n progress_made = true\n\n database_id = import_object(object)\n object_id_to_database_id[id] = database_id\n object_id_to_database_id[database_id] = database_id\n rescue Pupa::Errors::MissingDatabaseIdError\n false\n end\n end\n\n break if objects.empty? || !progress_made\n end\n\n unless objects.empty?\n raise Errors::UnprocessableEntity, \"couldn't resolve #{objects.size}/#{size} objects:\\n #{objects.values.map{|object| JSON.dump(object.foreign_properties)}.join(\"\\n \")}\"\n end\n end\n\n # Ensure that fingerprints uniquely identified objects.\n counts = {}\n object_id_to_database_id.each do |object_id,database_id|\n unless object_id == database_id\n (counts[database_id] ||= []) << object_id\n end\n end\n duplicates = counts.select do |_,object_ids|\n object_ids.size > 1\n end\n unless duplicates.empty?\n raise Errors::DuplicateDocumentError, \"multiple objects written to same document:\\n\" + duplicates.map{|database_id,object_ids| \" #{database_id} <- #{object_ids.join(' ')}\"}.join(\"\\n\")\n end\n end", "code_tokens": ["def", "import", "@report", "[", ":import", "]", "=", "{", "}", "objects", "=", "deduplicate", "(", "load_scraped_objects", ")", "object_id_to_database_id", "=", "{", "}", "if", "use_dependency_graph?", "(", "objects", ")", "dependency_graph", "=", "build_dependency_graph", "(", "objects", ")", "# Replace object IDs with database IDs in foreign keys and save objects.", "dependency_graph", ".", "tsort", ".", "each", "do", "|", "id", "|", "object", "=", "objects", "[", "id", "]", "resolve_foreign_keys", "(", "object", ",", "object_id_to_database_id", ")", "# The dependency graph strategy only works if there are no foreign objects.", "database_id", "=", "import_object", "(", "object", ")", "object_id_to_database_id", "[", "id", "]", "=", "database_id", "object_id_to_database_id", "[", "database_id", "]", "=", "database_id", "end", "else", "size", "=", "objects", ".", "size", "# Should be O(n\u00b2). If there are foreign objects, we do not know all the", "# edges in the graph, and therefore cannot build a dependency graph or", "# derive any evaluation order.", "#", "# An exception is raised if a foreign object matches multiple documents", "# in the database. However, if a matching object is not yet saved, this", "# exception may not be raised.", "loop", "do", "progress_made", "=", "false", "objects", ".", "delete_if", "do", "|", "id", ",", "object", "|", "begin", "resolve_foreign_keys", "(", "object", ",", "object_id_to_database_id", ")", "resolve_foreign_objects", "(", "object", ",", "object_id_to_database_id", ")", "progress_made", "=", "true", "database_id", "=", "import_object", "(", "object", ")", "object_id_to_database_id", "[", "id", "]", "=", "database_id", "object_id_to_database_id", "[", "database_id", "]", "=", "database_id", "rescue", "Pupa", "::", "Errors", "::", "MissingDatabaseIdError", "false", "end", "end", "break", "if", "objects", ".", "empty?", "||", "!", "progress_made", "end", "unless", "objects", ".", "empty?", "raise", "Errors", "::", "UnprocessableEntity", ",", "\"couldn't resolve #{objects.size}/#{size} objects:\\n #{objects.values.map{|object| JSON.dump(object.foreign_properties)}.join(\"\\n \")}\"", "end", "end", "# Ensure that fingerprints uniquely identified objects.", "counts", "=", "{", "}", "object_id_to_database_id", ".", "each", "do", "|", "object_id", ",", "database_id", "|", "unless", "object_id", "==", "database_id", "(", "counts", "[", "database_id", "]", "||=", "[", "]", ")", "<<", "object_id", "end", "end", "duplicates", "=", "counts", ".", "select", "do", "|", "_", ",", "object_ids", "|", "object_ids", ".", "size", ">", "1", "end", "unless", "duplicates", ".", "empty?", "raise", "Errors", "::", "DuplicateDocumentError", ",", "\"multiple objects written to same document:\\n\"", "+", "duplicates", ".", "map", "{", "|", "database_id", ",", "object_ids", "|", "\" #{database_id} <- #{object_ids.join(' ')}\"", "}", ".", "join", "(", "\"\\n\"", ")", "end", "end"], "docstring": "Saves scraped objects to a database.\n\n @raises [TSort::Cyclic] if the dependency graph is cyclic\n @raises [Pupa::Errors::UnprocessableEntity] if an object's foreign keys or\n foreign objects cannot be resolved\n @raises [Pupa::Errors::DuplicateDocumentError] if duplicate objects were\n inadvertently saved to the database", "docstring_tokens": ["Saves", "scraped", "objects", "to", "a", "database", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L130-L198", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/processor.rb", "func_name": "Pupa.Processor.dump_scraped_object", "original_string": "def dump_scraped_object(object)\n type = object.class.to_s.demodulize.underscore\n name = \"#{type}_#{object._id.gsub(File::SEPARATOR, '_')}.json\"\n\n if @store.write_unless_exists(name, object.to_h)\n info {\"save #{type} #{object.to_s} as #{name}\"}\n else\n raise Errors::DuplicateObjectIdError, \"duplicate object ID: #{object._id} (was the same objected yielded twice?)\"\n end\n\n if @validate\n begin\n object.validate!\n rescue JSON::Schema::ValidationError => e\n warn {e.message}\n end\n end\n end", "language": "ruby", "code": "def dump_scraped_object(object)\n type = object.class.to_s.demodulize.underscore\n name = \"#{type}_#{object._id.gsub(File::SEPARATOR, '_')}.json\"\n\n if @store.write_unless_exists(name, object.to_h)\n info {\"save #{type} #{object.to_s} as #{name}\"}\n else\n raise Errors::DuplicateObjectIdError, \"duplicate object ID: #{object._id} (was the same objected yielded twice?)\"\n end\n\n if @validate\n begin\n object.validate!\n rescue JSON::Schema::ValidationError => e\n warn {e.message}\n end\n end\n end", "code_tokens": ["def", "dump_scraped_object", "(", "object", ")", "type", "=", "object", ".", "class", ".", "to_s", ".", "demodulize", ".", "underscore", "name", "=", "\"#{type}_#{object._id.gsub(File::SEPARATOR, '_')}.json\"", "if", "@store", ".", "write_unless_exists", "(", "name", ",", "object", ".", "to_h", ")", "info", "{", "\"save #{type} #{object.to_s} as #{name}\"", "}", "else", "raise", "Errors", "::", "DuplicateObjectIdError", ",", "\"duplicate object ID: #{object._id} (was the same objected yielded twice?)\"", "end", "if", "@validate", "begin", "object", ".", "validate!", "rescue", "JSON", "::", "Schema", "::", "ValidationError", "=>", "e", "warn", "{", "e", ".", "message", "}", "end", "end", "end"], "docstring": "Dumps an scraped object to disk.\n\n @param [Object] object an scraped object\n @raises [Pupa::Errors::DuplicateObjectIdError]", "docstring_tokens": ["Dumps", "an", "scraped", "object", "to", "disk", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L219-L236", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/processor.rb", "func_name": "Pupa.Processor.load_scraped_objects", "original_string": "def load_scraped_objects\n {}.tap do |objects|\n @store.read_multi(@store.entries).each do |properties|\n object = load_scraped_object(properties)\n objects[object._id] = object\n end\n end\n end", "language": "ruby", "code": "def load_scraped_objects\n {}.tap do |objects|\n @store.read_multi(@store.entries).each do |properties|\n object = load_scraped_object(properties)\n objects[object._id] = object\n end\n end\n end", "code_tokens": ["def", "load_scraped_objects", "{", "}", ".", "tap", "do", "|", "objects", "|", "@store", ".", "read_multi", "(", "@store", ".", "entries", ")", ".", "each", "do", "|", "properties", "|", "object", "=", "load_scraped_object", "(", "properties", ")", "objects", "[", "object", ".", "_id", "]", "=", "object", "end", "end", "end"], "docstring": "Loads scraped objects from disk.\n\n @return [Hash] a hash of scraped objects keyed by ID", "docstring_tokens": ["Loads", "scraped", "objects", "from", "disk", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L241-L248", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/processor.rb", "func_name": "Pupa.Processor.load_scraped_object", "original_string": "def load_scraped_object(properties)\n type = properties['_type'] || properties[:_type]\n if type\n type.camelize.constantize.new(properties)\n else\n raise Errors::MissingObjectTypeError, \"missing _type: #{JSON.dump(properties)}\"\n end\n end", "language": "ruby", "code": "def load_scraped_object(properties)\n type = properties['_type'] || properties[:_type]\n if type\n type.camelize.constantize.new(properties)\n else\n raise Errors::MissingObjectTypeError, \"missing _type: #{JSON.dump(properties)}\"\n end\n end", "code_tokens": ["def", "load_scraped_object", "(", "properties", ")", "type", "=", "properties", "[", "'_type'", "]", "||", "properties", "[", ":_type", "]", "if", "type", "type", ".", "camelize", ".", "constantize", ".", "new", "(", "properties", ")", "else", "raise", "Errors", "::", "MissingObjectTypeError", ",", "\"missing _type: #{JSON.dump(properties)}\"", "end", "end"], "docstring": "Loads a scraped object from its properties.\n\n @param [Hash] properties the object's properties\n @return [Object] a scraped object\n @raises [Pupa::Errors::MissingObjectTypeError] if the scraped object is\n missing a `_type` property.", "docstring_tokens": ["Loads", "a", "scraped", "object", "from", "its", "properties", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L256-L263", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/processor.rb", "func_name": "Pupa.Processor.deduplicate", "original_string": "def deduplicate(objects)\n losers_to_winners = build_losers_to_winners_map(objects)\n\n # Remove all losers.\n losers_to_winners.each_key do |key|\n objects.delete(key)\n end\n\n # Swap the IDs of losers for the IDs of winners.\n objects.each do |id,object|\n object.foreign_keys.each do |property|\n value = object[property]\n if value && losers_to_winners.key?(value)\n object[property] = losers_to_winners[value]\n end\n end\n end\n\n objects\n end", "language": "ruby", "code": "def deduplicate(objects)\n losers_to_winners = build_losers_to_winners_map(objects)\n\n # Remove all losers.\n losers_to_winners.each_key do |key|\n objects.delete(key)\n end\n\n # Swap the IDs of losers for the IDs of winners.\n objects.each do |id,object|\n object.foreign_keys.each do |property|\n value = object[property]\n if value && losers_to_winners.key?(value)\n object[property] = losers_to_winners[value]\n end\n end\n end\n\n objects\n end", "code_tokens": ["def", "deduplicate", "(", "objects", ")", "losers_to_winners", "=", "build_losers_to_winners_map", "(", "objects", ")", "# Remove all losers.", "losers_to_winners", ".", "each_key", "do", "|", "key", "|", "objects", ".", "delete", "(", "key", ")", "end", "# Swap the IDs of losers for the IDs of winners.", "objects", ".", "each", "do", "|", "id", ",", "object", "|", "object", ".", "foreign_keys", ".", "each", "do", "|", "property", "|", "value", "=", "object", "[", "property", "]", "if", "value", "&&", "losers_to_winners", ".", "key?", "(", "value", ")", "object", "[", "property", "]", "=", "losers_to_winners", "[", "value", "]", "end", "end", "end", "objects", "end"], "docstring": "Removes all duplicate objects and re-assigns any foreign keys.\n\n @param [Hash] objects a hash of scraped objects keyed by ID\n @return [Hash] the objects without duplicates", "docstring_tokens": ["Removes", "all", "duplicate", "objects", "and", "re", "-", "assigns", "any", "foreign", "keys", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L269-L288", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/processor.rb", "func_name": "Pupa.Processor.build_losers_to_winners_map", "original_string": "def build_losers_to_winners_map(objects)\n inverse = {}\n objects.each do |id,object|\n (inverse[object.to_h.except(:_id)] ||= []) << id\n end\n\n {}.tap do |map|\n inverse.values.each do |ids|\n ids.drop(1).each do |id|\n map[id] = ids[0]\n end\n end\n end\n end", "language": "ruby", "code": "def build_losers_to_winners_map(objects)\n inverse = {}\n objects.each do |id,object|\n (inverse[object.to_h.except(:_id)] ||= []) << id\n end\n\n {}.tap do |map|\n inverse.values.each do |ids|\n ids.drop(1).each do |id|\n map[id] = ids[0]\n end\n end\n end\n end", "code_tokens": ["def", "build_losers_to_winners_map", "(", "objects", ")", "inverse", "=", "{", "}", "objects", ".", "each", "do", "|", "id", ",", "object", "|", "(", "inverse", "[", "object", ".", "to_h", ".", "except", "(", ":_id", ")", "]", "||=", "[", "]", ")", "<<", "id", "end", "{", "}", ".", "tap", "do", "|", "map", "|", "inverse", ".", "values", ".", "each", "do", "|", "ids", "|", "ids", ".", "drop", "(", "1", ")", ".", "each", "do", "|", "id", "|", "map", "[", "id", "]", "=", "ids", "[", "0", "]", "end", "end", "end", "end"], "docstring": "For each object, map its ID to the ID of its duplicate, if any.\n\n @param [Hash] objects a hash of scraped objects keyed by ID\n @return [Hash] a mapping from an object ID to the ID of its duplicate", "docstring_tokens": ["For", "each", "object", "map", "its", "ID", "to", "the", "ID", "of", "its", "duplicate", "if", "any", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L294-L307", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/processor.rb", "func_name": "Pupa.Processor.use_dependency_graph?", "original_string": "def use_dependency_graph?(objects)\n objects.each do |id,object|\n object.foreign_objects.each do |property|\n if object[property].present?\n return false\n end\n end\n end\n true\n end", "language": "ruby", "code": "def use_dependency_graph?(objects)\n objects.each do |id,object|\n object.foreign_objects.each do |property|\n if object[property].present?\n return false\n end\n end\n end\n true\n end", "code_tokens": ["def", "use_dependency_graph?", "(", "objects", ")", "objects", ".", "each", "do", "|", "id", ",", "object", "|", "object", ".", "foreign_objects", ".", "each", "do", "|", "property", "|", "if", "object", "[", "property", "]", ".", "present?", "return", "false", "end", "end", "end", "true", "end"], "docstring": "If any objects have unresolved foreign objects, we cannot derive an\n evaluation order using a dependency graph.\n\n @param [Hash] objects a hash of scraped objects keyed by ID\n @return [Boolean] whether a dependency graph can be used to derive an\n evaluation order", "docstring_tokens": ["If", "any", "objects", "have", "unresolved", "foreign", "objects", "we", "cannot", "derive", "an", "evaluation", "order", "using", "a", "dependency", "graph", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L315-L324", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/processor.rb", "func_name": "Pupa.Processor.build_dependency_graph", "original_string": "def build_dependency_graph(objects)\n DependencyGraph.new.tap do |graph|\n objects.each do |id,object|\n graph[id] = [] # no duplicate IDs\n object.foreign_keys.each do |property|\n value = object[property]\n if value\n graph[id] << value\n end\n end\n end\n end\n end", "language": "ruby", "code": "def build_dependency_graph(objects)\n DependencyGraph.new.tap do |graph|\n objects.each do |id,object|\n graph[id] = [] # no duplicate IDs\n object.foreign_keys.each do |property|\n value = object[property]\n if value\n graph[id] << value\n end\n end\n end\n end\n end", "code_tokens": ["def", "build_dependency_graph", "(", "objects", ")", "DependencyGraph", ".", "new", ".", "tap", "do", "|", "graph", "|", "objects", ".", "each", "do", "|", "id", ",", "object", "|", "graph", "[", "id", "]", "=", "[", "]", "# no duplicate IDs", "object", ".", "foreign_keys", ".", "each", "do", "|", "property", "|", "value", "=", "object", "[", "property", "]", "if", "value", "graph", "[", "id", "]", "<<", "value", "end", "end", "end", "end", "end"], "docstring": "Builds a dependency graph.\n\n @param [Hash] objects a hash of scraped objects keyed by ID\n @return [DependencyGraph] the dependency graph", "docstring_tokens": ["Builds", "a", "dependency", "graph", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L330-L342", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/processor.rb", "func_name": "Pupa.Processor.resolve_foreign_keys", "original_string": "def resolve_foreign_keys(object, map)\n object.foreign_keys.each do |property|\n value = object[property]\n if value\n if map.key?(value)\n object[property] = map[value]\n else\n raise Errors::MissingDatabaseIdError, \"couldn't resolve foreign key: #{property} #{value}\"\n end\n end\n end\n end", "language": "ruby", "code": "def resolve_foreign_keys(object, map)\n object.foreign_keys.each do |property|\n value = object[property]\n if value\n if map.key?(value)\n object[property] = map[value]\n else\n raise Errors::MissingDatabaseIdError, \"couldn't resolve foreign key: #{property} #{value}\"\n end\n end\n end\n end", "code_tokens": ["def", "resolve_foreign_keys", "(", "object", ",", "map", ")", "object", ".", "foreign_keys", ".", "each", "do", "|", "property", "|", "value", "=", "object", "[", "property", "]", "if", "value", "if", "map", ".", "key?", "(", "value", ")", "object", "[", "property", "]", "=", "map", "[", "value", "]", "else", "raise", "Errors", "::", "MissingDatabaseIdError", ",", "\"couldn't resolve foreign key: #{property} #{value}\"", "end", "end", "end", "end"], "docstring": "Resolves an object's foreign keys from object IDs to database IDs.\n\n @param [Object] an object\n @param [Hash] a map from object ID to database ID\n @raises [Pupa::Errors::MissingDatabaseIdError] if a foreign key cannot be\n resolved", "docstring_tokens": ["Resolves", "an", "object", "s", "foreign", "keys", "from", "object", "IDs", "to", "database", "IDs", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L350-L361", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/processor.rb", "func_name": "Pupa.Processor.resolve_foreign_objects", "original_string": "def resolve_foreign_objects(object, map)\n object.foreign_objects.each do |property|\n value = object[property]\n if value.present?\n foreign_object = ForeignObject.new(value)\n resolve_foreign_keys(foreign_object, map)\n document = connection.find(foreign_object.to_h)\n\n if document\n object[\"#{property}_id\"] = document['_id']\n else\n raise Errors::MissingDatabaseIdError, \"couldn't resolve foreign object: #{property} #{value}\"\n end\n end\n end\n end", "language": "ruby", "code": "def resolve_foreign_objects(object, map)\n object.foreign_objects.each do |property|\n value = object[property]\n if value.present?\n foreign_object = ForeignObject.new(value)\n resolve_foreign_keys(foreign_object, map)\n document = connection.find(foreign_object.to_h)\n\n if document\n object[\"#{property}_id\"] = document['_id']\n else\n raise Errors::MissingDatabaseIdError, \"couldn't resolve foreign object: #{property} #{value}\"\n end\n end\n end\n end", "code_tokens": ["def", "resolve_foreign_objects", "(", "object", ",", "map", ")", "object", ".", "foreign_objects", ".", "each", "do", "|", "property", "|", "value", "=", "object", "[", "property", "]", "if", "value", ".", "present?", "foreign_object", "=", "ForeignObject", ".", "new", "(", "value", ")", "resolve_foreign_keys", "(", "foreign_object", ",", "map", ")", "document", "=", "connection", ".", "find", "(", "foreign_object", ".", "to_h", ")", "if", "document", "object", "[", "\"#{property}_id\"", "]", "=", "document", "[", "'_id'", "]", "else", "raise", "Errors", "::", "MissingDatabaseIdError", ",", "\"couldn't resolve foreign object: #{property} #{value}\"", "end", "end", "end", "end"], "docstring": "Resolves an object's foreign objects to database IDs.\n\n @param [Object] object an object\n @param [Hash] a map from object ID to database ID\n @raises [Pupa::Errors::MissingDatabaseIdError] if a foreign object cannot\n be resolved", "docstring_tokens": ["Resolves", "an", "object", "s", "foreign", "objects", "to", "database", "IDs", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L369-L384", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/runner.rb", "func_name": "Pupa.Runner.run", "original_string": "def run(args, overrides = {})\n rest = opts.parse!(args)\n\n @options = OpenStruct.new(options.to_h.merge(overrides))\n\n if options.actions.empty?\n options.actions = %w(scrape import)\n end\n if options.tasks.empty?\n options.tasks = @processor_class.tasks\n end\n\n processor = @processor_class.new(options.output_dir,\n pipelined: options.pipelined,\n cache_dir: options.cache_dir,\n expires_in: options.expires_in,\n value_max_bytes: options.value_max_bytes,\n memcached_username: options.memcached_username,\n memcached_password: options.memcached_password,\n database_url: options.database_url,\n validate: options.validate,\n level: options.level,\n faraday_options: options.faraday_options,\n options: Hash[*rest])\n\n options.actions.each do |action|\n unless action == 'scrape' || processor.respond_to?(action)\n abort %(`#{action}` is not a #{opts.program_name} action. See `#{opts.program_name} --help` for a list of available actions.)\n end\n end\n\n if %w(DEBUG INFO).include?(options.level)\n puts \"processor: #{@processor_class}\"\n puts \"actions: #{options.actions.join(', ')}\"\n puts \"tasks: #{options.tasks.join(', ')}\"\n end\n\n if options.level == 'DEBUG'\n %w(output_dir pipelined cache_dir expires_in value_max_bytes memcached_username memcached_password database_url validate level).each do |option|\n puts \"#{option}: #{options[option]}\"\n end\n unless rest.empty?\n puts \"options: #{rest.join(' ')}\"\n end\n end\n\n exit if options.dry_run\n\n report = {\n plan: {\n processor: @processor_class,\n options: Marshal.load(Marshal.dump(options)).to_h,\n arguments: rest,\n },\n start: Time.now.utc,\n }\n\n if options.actions.delete('scrape')\n processor.store.clear\n report[:scrape] = {}\n options.tasks.each do |task_name|\n report[:scrape][task_name] = processor.dump_scraped_objects(task_name)\n end\n end\n\n options.actions.each do |action|\n processor.send(action)\n if processor.report.key?(action.to_sym)\n report.update(action.to_sym => processor.report[action.to_sym])\n end\n end\n\n if %w(DEBUG INFO).include?(options.level)\n report[:end] = Time.now.utc\n report[:time] = report[:end] - report[:start]\n puts JSON.dump(report)\n end\n end", "language": "ruby", "code": "def run(args, overrides = {})\n rest = opts.parse!(args)\n\n @options = OpenStruct.new(options.to_h.merge(overrides))\n\n if options.actions.empty?\n options.actions = %w(scrape import)\n end\n if options.tasks.empty?\n options.tasks = @processor_class.tasks\n end\n\n processor = @processor_class.new(options.output_dir,\n pipelined: options.pipelined,\n cache_dir: options.cache_dir,\n expires_in: options.expires_in,\n value_max_bytes: options.value_max_bytes,\n memcached_username: options.memcached_username,\n memcached_password: options.memcached_password,\n database_url: options.database_url,\n validate: options.validate,\n level: options.level,\n faraday_options: options.faraday_options,\n options: Hash[*rest])\n\n options.actions.each do |action|\n unless action == 'scrape' || processor.respond_to?(action)\n abort %(`#{action}` is not a #{opts.program_name} action. See `#{opts.program_name} --help` for a list of available actions.)\n end\n end\n\n if %w(DEBUG INFO).include?(options.level)\n puts \"processor: #{@processor_class}\"\n puts \"actions: #{options.actions.join(', ')}\"\n puts \"tasks: #{options.tasks.join(', ')}\"\n end\n\n if options.level == 'DEBUG'\n %w(output_dir pipelined cache_dir expires_in value_max_bytes memcached_username memcached_password database_url validate level).each do |option|\n puts \"#{option}: #{options[option]}\"\n end\n unless rest.empty?\n puts \"options: #{rest.join(' ')}\"\n end\n end\n\n exit if options.dry_run\n\n report = {\n plan: {\n processor: @processor_class,\n options: Marshal.load(Marshal.dump(options)).to_h,\n arguments: rest,\n },\n start: Time.now.utc,\n }\n\n if options.actions.delete('scrape')\n processor.store.clear\n report[:scrape] = {}\n options.tasks.each do |task_name|\n report[:scrape][task_name] = processor.dump_scraped_objects(task_name)\n end\n end\n\n options.actions.each do |action|\n processor.send(action)\n if processor.report.key?(action.to_sym)\n report.update(action.to_sym => processor.report[action.to_sym])\n end\n end\n\n if %w(DEBUG INFO).include?(options.level)\n report[:end] = Time.now.utc\n report[:time] = report[:end] - report[:start]\n puts JSON.dump(report)\n end\n end", "code_tokens": ["def", "run", "(", "args", ",", "overrides", "=", "{", "}", ")", "rest", "=", "opts", ".", "parse!", "(", "args", ")", "@options", "=", "OpenStruct", ".", "new", "(", "options", ".", "to_h", ".", "merge", "(", "overrides", ")", ")", "if", "options", ".", "actions", ".", "empty?", "options", ".", "actions", "=", "%w(", "scrape", "import", ")", "end", "if", "options", ".", "tasks", ".", "empty?", "options", ".", "tasks", "=", "@processor_class", ".", "tasks", "end", "processor", "=", "@processor_class", ".", "new", "(", "options", ".", "output_dir", ",", "pipelined", ":", "options", ".", "pipelined", ",", "cache_dir", ":", "options", ".", "cache_dir", ",", "expires_in", ":", "options", ".", "expires_in", ",", "value_max_bytes", ":", "options", ".", "value_max_bytes", ",", "memcached_username", ":", "options", ".", "memcached_username", ",", "memcached_password", ":", "options", ".", "memcached_password", ",", "database_url", ":", "options", ".", "database_url", ",", "validate", ":", "options", ".", "validate", ",", "level", ":", "options", ".", "level", ",", "faraday_options", ":", "options", ".", "faraday_options", ",", "options", ":", "Hash", "[", "rest", "]", ")", "options", ".", "actions", ".", "each", "do", "|", "action", "|", "unless", "action", "==", "'scrape'", "||", "processor", ".", "respond_to?", "(", "action", ")", "abort", "%(`#{action}` is not a #{opts.program_name} action. See `#{opts.program_name} --help` for a list of available actions.)", "end", "end", "if", "%w(", "DEBUG", "INFO", ")", ".", "include?", "(", "options", ".", "level", ")", "puts", "\"processor: #{@processor_class}\"", "puts", "\"actions: #{options.actions.join(', ')}\"", "puts", "\"tasks: #{options.tasks.join(', ')}\"", "end", "if", "options", ".", "level", "==", "'DEBUG'", "%w(", "output_dir", "pipelined", "cache_dir", "expires_in", "value_max_bytes", "memcached_username", "memcached_password", "database_url", "validate", "level", ")", ".", "each", "do", "|", "option", "|", "puts", "\"#{option}: #{options[option]}\"", "end", "unless", "rest", ".", "empty?", "puts", "\"options: #{rest.join(' ')}\"", "end", "end", "exit", "if", "options", ".", "dry_run", "report", "=", "{", "plan", ":", "{", "processor", ":", "@processor_class", ",", "options", ":", "Marshal", ".", "load", "(", "Marshal", ".", "dump", "(", "options", ")", ")", ".", "to_h", ",", "arguments", ":", "rest", ",", "}", ",", "start", ":", "Time", ".", "now", ".", "utc", ",", "}", "if", "options", ".", "actions", ".", "delete", "(", "'scrape'", ")", "processor", ".", "store", ".", "clear", "report", "[", ":scrape", "]", "=", "{", "}", "options", ".", "tasks", ".", "each", "do", "|", "task_name", "|", "report", "[", ":scrape", "]", "[", "task_name", "]", "=", "processor", ".", "dump_scraped_objects", "(", "task_name", ")", "end", "end", "options", ".", "actions", ".", "each", "do", "|", "action", "|", "processor", ".", "send", "(", "action", ")", "if", "processor", ".", "report", ".", "key?", "(", "action", ".", "to_sym", ")", "report", ".", "update", "(", "action", ".", "to_sym", "=>", "processor", ".", "report", "[", "action", ".", "to_sym", "]", ")", "end", "end", "if", "%w(", "DEBUG", "INFO", ")", ".", "include?", "(", "options", ".", "level", ")", "report", "[", ":end", "]", "=", "Time", ".", "now", ".", "utc", "report", "[", ":time", "]", "=", "report", "[", ":end", "]", "-", "report", "[", ":start", "]", "puts", "JSON", ".", "dump", "(", "report", ")", "end", "end"], "docstring": "Runs the action.\n\n @example Run from a command-line script\n\n runner.run(ARGV)\n\n @example Override the command-line options\n\n runner.run(ARGV, expires_in: 3600) # 1 hour\n\n @param [Array] args command-line arguments\n @param [Hash] overrides any overridden options", "docstring_tokens": ["Runs", "the", "action", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/runner.rb#L145-L222", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/models/vote_event.rb", "func_name": "Pupa.VoteEvent.add_group_result", "original_string": "def add_group_result(result, group: nil)\n data = {result: result}\n if group\n data[:group] = group\n end\n if result.present?\n @group_results << data\n end\n end", "language": "ruby", "code": "def add_group_result(result, group: nil)\n data = {result: result}\n if group\n data[:group] = group\n end\n if result.present?\n @group_results << data\n end\n end", "code_tokens": ["def", "add_group_result", "(", "result", ",", "group", ":", "nil", ")", "data", "=", "{", "result", ":", "result", "}", "if", "group", "data", "[", ":group", "]", "=", "group", "end", "if", "result", ".", "present?", "@group_results", "<<", "data", "end", "end"], "docstring": "Adds a group result.\n\n @param [String] result the result of the vote event within a group of voters\n @param [String] group a group of voters", "docstring_tokens": ["Adds", "a", "group", "result", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/models/vote_event.rb#L47-L55", "partition": "valid"} {"repo": "jpmckinney/pupa-ruby", "path": "lib/pupa/models/vote_event.rb", "func_name": "Pupa.VoteEvent.add_count", "original_string": "def add_count(option, value, group: nil)\n data = {option: option, value: value}\n if group\n data[:group] = group\n end\n if option.present? && value.present?\n @counts << data\n end\n end", "language": "ruby", "code": "def add_count(option, value, group: nil)\n data = {option: option, value: value}\n if group\n data[:group] = group\n end\n if option.present? && value.present?\n @counts << data\n end\n end", "code_tokens": ["def", "add_count", "(", "option", ",", "value", ",", "group", ":", "nil", ")", "data", "=", "{", "option", ":", "option", ",", "value", ":", "value", "}", "if", "group", "data", "[", ":group", "]", "=", "group", "end", "if", "option", ".", "present?", "&&", "value", ".", "present?", "@counts", "<<", "data", "end", "end"], "docstring": "Adds a count.\n\n @param [String] option an option in a vote event\n @param [String] value the number of votes for an option\n @param [String] group a group of voters", "docstring_tokens": ["Adds", "a", "count", "."], "sha": "cb1485a42c1ee1a81cdf113a3199ad2993a45db1", "url": "https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/models/vote_event.rb#L62-L70", "partition": "valid"} {"repo": "thiagofelix/danger-jenkins", "path": "lib/jenkins/plugin.rb", "func_name": "Danger.DangerJenkins.print_artifacts", "original_string": "def print_artifacts\n artifacts = build.artifacts\n return if artifacts.empty?\n\n content = \"### Jenkins artifacts:\\n\\n\"\n content << \"\\n\"\n\n artifacts.each do |artifact|\n content << \"* #{artifact_link(artifact)}\\n\"\n end\n\n markdown content\n end", "language": "ruby", "code": "def print_artifacts\n artifacts = build.artifacts\n return if artifacts.empty?\n\n content = \"### Jenkins artifacts:\\n\\n\"\n content << \"\\n\"\n\n artifacts.each do |artifact|\n content << \"* #{artifact_link(artifact)}\\n\"\n end\n\n markdown content\n end", "code_tokens": ["def", "print_artifacts", "artifacts", "=", "build", ".", "artifacts", "return", "if", "artifacts", ".", "empty?", "content", "=", "\"### Jenkins artifacts:\\n\\n\"", "content", "<<", "\"\\n\"", "artifacts", ".", "each", "do", "|", "artifact", "|", "content", "<<", "\"* #{artifact_link(artifact)}\\n\"", "end", "markdown", "content", "end"], "docstring": "Adds a list of artifacts to the danger comment\n\n @return [void]", "docstring_tokens": ["Adds", "a", "list", "of", "artifacts", "to", "the", "danger", "comment"], "sha": "8c7f4f5517a3edc15dad151d9291c50de9d26cb4", "url": "https://github.com/thiagofelix/danger-jenkins/blob/8c7f4f5517a3edc15dad151d9291c50de9d26cb4/lib/jenkins/plugin.rb#L77-L89", "partition": "valid"} {"repo": "dmacvicar/ruby-rpm-ffi", "path": "lib/rpm/transaction.rb", "func_name": "RPM.Transaction.delete", "original_string": "def delete(pkg)\n iterator = case pkg\n when Package\n pkg[:sigmd5] ? each_match(:sigmd5, pkg[:sigmd5]) : each_match(:label, pkg[:label])\n when String\n each_match(:label, pkg)\n when Dependency\n each_match(:label, pkg.name).set_iterator_version(pkg.version)\n else\n raise TypeError, 'illegal argument type'\n end\n\n iterator.each do |header|\n ret = RPM::C.rpmtsAddEraseElement(@ptr, header.ptr, iterator.offset)\n raise \"Error while adding erase/#{pkg} to transaction\" if ret != 0\n end\n end", "language": "ruby", "code": "def delete(pkg)\n iterator = case pkg\n when Package\n pkg[:sigmd5] ? each_match(:sigmd5, pkg[:sigmd5]) : each_match(:label, pkg[:label])\n when String\n each_match(:label, pkg)\n when Dependency\n each_match(:label, pkg.name).set_iterator_version(pkg.version)\n else\n raise TypeError, 'illegal argument type'\n end\n\n iterator.each do |header|\n ret = RPM::C.rpmtsAddEraseElement(@ptr, header.ptr, iterator.offset)\n raise \"Error while adding erase/#{pkg} to transaction\" if ret != 0\n end\n end", "code_tokens": ["def", "delete", "(", "pkg", ")", "iterator", "=", "case", "pkg", "when", "Package", "pkg", "[", ":sigmd5", "]", "?", "each_match", "(", ":sigmd5", ",", "pkg", "[", ":sigmd5", "]", ")", ":", "each_match", "(", ":label", ",", "pkg", "[", ":label", "]", ")", "when", "String", "each_match", "(", ":label", ",", "pkg", ")", "when", "Dependency", "each_match", "(", ":label", ",", "pkg", ".", "name", ")", ".", "set_iterator_version", "(", "pkg", ".", "version", ")", "else", "raise", "TypeError", ",", "'illegal argument type'", "end", "iterator", ".", "each", "do", "|", "header", "|", "ret", "=", "RPM", "::", "C", ".", "rpmtsAddEraseElement", "(", "@ptr", ",", "header", ".", "ptr", ",", "iterator", ".", "offset", ")", "raise", "\"Error while adding erase/#{pkg} to transaction\"", "if", "ret", "!=", "0", "end", "end"], "docstring": "Add a delete operation to the transaction\n @param [String, Package, Dependency] pkg Package to delete", "docstring_tokens": ["Add", "a", "delete", "operation", "to", "the", "transaction"], "sha": "f5302d3717d3e2d489ebbd522a65447e3ccefa64", "url": "https://github.com/dmacvicar/ruby-rpm-ffi/blob/f5302d3717d3e2d489ebbd522a65447e3ccefa64/lib/rpm/transaction.rb#L85-L101", "partition": "valid"} {"repo": "dmacvicar/ruby-rpm-ffi", "path": "lib/rpm/transaction.rb", "func_name": "RPM.Transaction.commit", "original_string": "def commit\n flags = RPM::C::TransFlags[:none]\n\n callback = proc do |hdr, type, amount, total, key_ptr, data_ignored|\n key_id = key_ptr.address\n key = @keys.include?(key_id) ? @keys[key_id] : nil\n\n if block_given?\n package = hdr.null? ? nil : Package.new(hdr)\n data = CallbackData.new(type, key, package, amount, total)\n yield(data)\n else\n RPM::C.rpmShowProgress(hdr, type, amount, total, key, data_ignored)\n end\n end\n # We create a callback to pass to the C method and we\n # call the user supplied callback from there\n #\n # The C callback expects you to return a file handle,\n # We expect from the user to get a File, which we\n # then convert to a file handle to return.\n callback = proc do |hdr, type, amount, total, key_ptr, data_ignored|\n key_id = key_ptr.address\n key = @keys.include?(key_id) ? @keys[key_id] : nil\n\n if block_given?\n package = hdr.null? ? nil : Package.new(hdr)\n data = CallbackData.new(type, key, package, amount, total)\n ret = yield(data)\n\n # For OPEN_FILE we need to do some type conversion\n # for certain callback types we need to do some\n case type\n when :inst_open_file\n # For :inst_open_file the user callback has to\n # return the open file\n unless ret.is_a?(::File)\n raise TypeError, \"illegal return value type #{ret.class}. Expected File.\"\n end\n fdt = RPM::C.fdDup(ret.to_i)\n if fdt.null? || RPM::C.Ferror(fdt) != 0\n raise \"Can't use opened file #{data.key}: #{RPM::C.Fstrerror(fdt)}\"\n RPM::C.Fclose(fdt) unless fdt.nil?\n else\n fdt = RPM::C.fdLink(fdt)\n @fdt = fdt\n end\n # return the (RPM type) file handle\n fdt\n when :inst_close_file\n fdt = @fdt\n RPM::C.Fclose(fdt)\n @fdt = nil\n else\n ret\n end\n else\n # No custom callback given, use the default to show progress\n RPM::C.rpmShowProgress(hdr, type, amount, total, key, data_ignored)\n end\n end\n\n rc = RPM::C.rpmtsSetNotifyCallback(@ptr, callback, nil)\n raise \"Can't set commit callback\" if rc != 0\n\n rc = RPM::C.rpmtsRun(@ptr, nil, :none)\n\n raise \"#{self}: #{RPM::C.rpmlogMessage}\" if rc < 0\n\n if rc > 0\n ps = RPM::C.rpmtsProblems(@ptr)\n psi = RPM::C.rpmpsInitIterator(ps)\n while RPM::C.rpmpsNextIterator(psi) >= 0\n problem = Problem.from_ptr(RPM::C.rpmpsGetProblem(psi))\n STDERR.puts problem\n end\n RPM::C.rpmpsFree(ps)\n end\n end", "language": "ruby", "code": "def commit\n flags = RPM::C::TransFlags[:none]\n\n callback = proc do |hdr, type, amount, total, key_ptr, data_ignored|\n key_id = key_ptr.address\n key = @keys.include?(key_id) ? @keys[key_id] : nil\n\n if block_given?\n package = hdr.null? ? nil : Package.new(hdr)\n data = CallbackData.new(type, key, package, amount, total)\n yield(data)\n else\n RPM::C.rpmShowProgress(hdr, type, amount, total, key, data_ignored)\n end\n end\n # We create a callback to pass to the C method and we\n # call the user supplied callback from there\n #\n # The C callback expects you to return a file handle,\n # We expect from the user to get a File, which we\n # then convert to a file handle to return.\n callback = proc do |hdr, type, amount, total, key_ptr, data_ignored|\n key_id = key_ptr.address\n key = @keys.include?(key_id) ? @keys[key_id] : nil\n\n if block_given?\n package = hdr.null? ? nil : Package.new(hdr)\n data = CallbackData.new(type, key, package, amount, total)\n ret = yield(data)\n\n # For OPEN_FILE we need to do some type conversion\n # for certain callback types we need to do some\n case type\n when :inst_open_file\n # For :inst_open_file the user callback has to\n # return the open file\n unless ret.is_a?(::File)\n raise TypeError, \"illegal return value type #{ret.class}. Expected File.\"\n end\n fdt = RPM::C.fdDup(ret.to_i)\n if fdt.null? || RPM::C.Ferror(fdt) != 0\n raise \"Can't use opened file #{data.key}: #{RPM::C.Fstrerror(fdt)}\"\n RPM::C.Fclose(fdt) unless fdt.nil?\n else\n fdt = RPM::C.fdLink(fdt)\n @fdt = fdt\n end\n # return the (RPM type) file handle\n fdt\n when :inst_close_file\n fdt = @fdt\n RPM::C.Fclose(fdt)\n @fdt = nil\n else\n ret\n end\n else\n # No custom callback given, use the default to show progress\n RPM::C.rpmShowProgress(hdr, type, amount, total, key, data_ignored)\n end\n end\n\n rc = RPM::C.rpmtsSetNotifyCallback(@ptr, callback, nil)\n raise \"Can't set commit callback\" if rc != 0\n\n rc = RPM::C.rpmtsRun(@ptr, nil, :none)\n\n raise \"#{self}: #{RPM::C.rpmlogMessage}\" if rc < 0\n\n if rc > 0\n ps = RPM::C.rpmtsProblems(@ptr)\n psi = RPM::C.rpmpsInitIterator(ps)\n while RPM::C.rpmpsNextIterator(psi) >= 0\n problem = Problem.from_ptr(RPM::C.rpmpsGetProblem(psi))\n STDERR.puts problem\n end\n RPM::C.rpmpsFree(ps)\n end\n end", "code_tokens": ["def", "commit", "flags", "=", "RPM", "::", "C", "::", "TransFlags", "[", ":none", "]", "callback", "=", "proc", "do", "|", "hdr", ",", "type", ",", "amount", ",", "total", ",", "key_ptr", ",", "data_ignored", "|", "key_id", "=", "key_ptr", ".", "address", "key", "=", "@keys", ".", "include?", "(", "key_id", ")", "?", "@keys", "[", "key_id", "]", ":", "nil", "if", "block_given?", "package", "=", "hdr", ".", "null?", "?", "nil", ":", "Package", ".", "new", "(", "hdr", ")", "data", "=", "CallbackData", ".", "new", "(", "type", ",", "key", ",", "package", ",", "amount", ",", "total", ")", "yield", "(", "data", ")", "else", "RPM", "::", "C", ".", "rpmShowProgress", "(", "hdr", ",", "type", ",", "amount", ",", "total", ",", "key", ",", "data_ignored", ")", "end", "end", "# We create a callback to pass to the C method and we", "# call the user supplied callback from there", "#", "# The C callback expects you to return a file handle,", "# We expect from the user to get a File, which we", "# then convert to a file handle to return.", "callback", "=", "proc", "do", "|", "hdr", ",", "type", ",", "amount", ",", "total", ",", "key_ptr", ",", "data_ignored", "|", "key_id", "=", "key_ptr", ".", "address", "key", "=", "@keys", ".", "include?", "(", "key_id", ")", "?", "@keys", "[", "key_id", "]", ":", "nil", "if", "block_given?", "package", "=", "hdr", ".", "null?", "?", "nil", ":", "Package", ".", "new", "(", "hdr", ")", "data", "=", "CallbackData", ".", "new", "(", "type", ",", "key", ",", "package", ",", "amount", ",", "total", ")", "ret", "=", "yield", "(", "data", ")", "# For OPEN_FILE we need to do some type conversion", "# for certain callback types we need to do some", "case", "type", "when", ":inst_open_file", "# For :inst_open_file the user callback has to", "# return the open file", "unless", "ret", ".", "is_a?", "(", "::", "File", ")", "raise", "TypeError", ",", "\"illegal return value type #{ret.class}. Expected File.\"", "end", "fdt", "=", "RPM", "::", "C", ".", "fdDup", "(", "ret", ".", "to_i", ")", "if", "fdt", ".", "null?", "||", "RPM", "::", "C", ".", "Ferror", "(", "fdt", ")", "!=", "0", "raise", "\"Can't use opened file #{data.key}: #{RPM::C.Fstrerror(fdt)}\"", "RPM", "::", "C", ".", "Fclose", "(", "fdt", ")", "unless", "fdt", ".", "nil?", "else", "fdt", "=", "RPM", "::", "C", ".", "fdLink", "(", "fdt", ")", "@fdt", "=", "fdt", "end", "# return the (RPM type) file handle", "fdt", "when", ":inst_close_file", "fdt", "=", "@fdt", "RPM", "::", "C", ".", "Fclose", "(", "fdt", ")", "@fdt", "=", "nil", "else", "ret", "end", "else", "# No custom callback given, use the default to show progress", "RPM", "::", "C", ".", "rpmShowProgress", "(", "hdr", ",", "type", ",", "amount", ",", "total", ",", "key", ",", "data_ignored", ")", "end", "end", "rc", "=", "RPM", "::", "C", ".", "rpmtsSetNotifyCallback", "(", "@ptr", ",", "callback", ",", "nil", ")", "raise", "\"Can't set commit callback\"", "if", "rc", "!=", "0", "rc", "=", "RPM", "::", "C", ".", "rpmtsRun", "(", "@ptr", ",", "nil", ",", ":none", ")", "raise", "\"#{self}: #{RPM::C.rpmlogMessage}\"", "if", "rc", "<", "0", "if", "rc", ">", "0", "ps", "=", "RPM", "::", "C", ".", "rpmtsProblems", "(", "@ptr", ")", "psi", "=", "RPM", "::", "C", ".", "rpmpsInitIterator", "(", "ps", ")", "while", "RPM", "::", "C", ".", "rpmpsNextIterator", "(", "psi", ")", ">=", "0", "problem", "=", "Problem", ".", "from_ptr", "(", "RPM", "::", "C", ".", "rpmpsGetProblem", "(", "psi", ")", ")", "STDERR", ".", "puts", "problem", "end", "RPM", "::", "C", ".", "rpmpsFree", "(", "ps", ")", "end", "end"], "docstring": "Performs the transaction.\n @param [Number] flag Transaction flags, default +RPM::TRANS_FLAG_NONE+\n @param [Number] filter Transaction filter, default +RPM::PROB_FILTER_NONE+\n @example\n transaction.commit\n You can supply your own callback\n @example\n transaction.commit do |data|\n end\n end\n @yield [CallbackData] sig Transaction progress", "docstring_tokens": ["Performs", "the", "transaction", "."], "sha": "f5302d3717d3e2d489ebbd522a65447e3ccefa64", "url": "https://github.com/dmacvicar/ruby-rpm-ffi/blob/f5302d3717d3e2d489ebbd522a65447e3ccefa64/lib/rpm/transaction.rb#L166-L244", "partition": "valid"} {"repo": "shawn42/tmx", "path": "lib/tmx/objects.rb", "func_name": "Tmx.Objects.find", "original_string": "def find(params)\n params = { type: params } if params.is_a?(String)\n\n found_objects = find_all do |object|\n params.any? {|key,value| object.send(key) == value.to_s }\n end.compact\n\n self.class.new found_objects\n end", "language": "ruby", "code": "def find(params)\n params = { type: params } if params.is_a?(String)\n\n found_objects = find_all do |object|\n params.any? {|key,value| object.send(key) == value.to_s }\n end.compact\n\n self.class.new found_objects\n end", "code_tokens": ["def", "find", "(", "params", ")", "params", "=", "{", "type", ":", "params", "}", "if", "params", ".", "is_a?", "(", "String", ")", "found_objects", "=", "find_all", "do", "|", "object", "|", "params", ".", "any?", "{", "|", "key", ",", "value", "|", "object", ".", "send", "(", "key", ")", "==", "value", ".", "to_s", "}", "end", ".", "compact", "self", ".", "class", ".", "new", "found_objects", "end"], "docstring": "Allows finding by type or a specfied hash of parameters\n\n @example Find all objects that have the type 'ground'\n\n objects.find(:floor)\n objects.find(type: 'floor')\n\n @example Find all objects that have the name 'mushroom'\n\n objects.find(name: \"mushroom\")", "docstring_tokens": ["Allows", "finding", "by", "type", "or", "a", "specfied", "hash", "of", "parameters"], "sha": "9c1948e586781610b926b6019db21e0894118d33", "url": "https://github.com/shawn42/tmx/blob/9c1948e586781610b926b6019db21e0894118d33/lib/tmx/objects.rb#L20-L28", "partition": "valid"} {"repo": "lzap/deacon", "path": "lib/deacon/random_generator.rb", "func_name": "Deacon.RandomGenerator.next_lfsr25", "original_string": "def next_lfsr25(seed)\n i = 1\n i = (seed + 1) & MASK\n raise ArgumentError, \"Seed #{seed} out of bounds\" if seed && i == 0\n i = (seed + 1) & MASK while i == 0\n i = (i >> 1) | ((i[0]^i[1]^i[2]^i[3]) << 0x18)\n i = (i >> 1) | ((i[0]^i[1]^i[2]^i[3]) << 0x18) while i > MASK\n i - 1\n end", "language": "ruby", "code": "def next_lfsr25(seed)\n i = 1\n i = (seed + 1) & MASK\n raise ArgumentError, \"Seed #{seed} out of bounds\" if seed && i == 0\n i = (seed + 1) & MASK while i == 0\n i = (i >> 1) | ((i[0]^i[1]^i[2]^i[3]) << 0x18)\n i = (i >> 1) | ((i[0]^i[1]^i[2]^i[3]) << 0x18) while i > MASK\n i - 1\n end", "code_tokens": ["def", "next_lfsr25", "(", "seed", ")", "i", "=", "1", "i", "=", "(", "seed", "+", "1", ")", "&", "MASK", "raise", "ArgumentError", ",", "\"Seed #{seed} out of bounds\"", "if", "seed", "&&", "i", "==", "0", "i", "=", "(", "seed", "+", "1", ")", "&", "MASK", "while", "i", "==", "0", "i", "=", "(", "i", ">>", "1", ")", "|", "(", "(", "i", "[", "0", "]", "^", "i", "[", "1", "]", "^", "i", "[", "2", "]", "^", "i", "[", "3", "]", ")", "<<", "0x18", ")", "i", "=", "(", "i", ">>", "1", ")", "|", "(", "(", "i", "[", "0", "]", "^", "i", "[", "1", "]", "^", "i", "[", "2", "]", "^", "i", "[", "3", "]", ")", "<<", "0x18", ")", "while", "i", ">", "MASK", "i", "-", "1", "end"], "docstring": "Fibonacci linear feedback shift register with x^25 + x^24 + x^23 + x^22 + 1 poly", "docstring_tokens": ["Fibonacci", "linear", "feedback", "shift", "register", "with", "x^25", "+", "x^24", "+", "x^23", "+", "x^22", "+", "1", "poly"], "sha": "bf52b5e741bcbaacb4e34b0f24b5397ce2051a50", "url": "https://github.com/lzap/deacon/blob/bf52b5e741bcbaacb4e34b0f24b5397ce2051a50/lib/deacon/random_generator.rb#L6-L14", "partition": "valid"} {"repo": "YorickPeterse/shebang", "path": "lib/shebang/command.rb", "func_name": "Shebang.Command.parse", "original_string": "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", "language": "ruby", "code": "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", "code_tokens": ["def", "parse", "(", "argv", "=", "[", "]", ")", "@option_parser", ".", "parse!", "(", "argv", ")", "options", ".", "each", "do", "|", "option", "|", "if", "option", ".", "required?", "and", "!", "option", ".", "has_value?", "Shebang", ".", "error", "(", "\"The -#{option.short} option is required\"", ")", "end", "end", "return", "argv", "end"], "docstring": "Creates a new instance of the command and sets up OptionParser.\n\n @author Yorick Peterse\n @since 0.1\n\n\n Parses the command line arguments using OptionParser.\n\n @author Yorick Peterse\n @since 0.1\n @param [Array] argv Array containing the command line arguments to parse.\n @return [Array] argv Array containing all the command line arguments after\n it has been processed.", "docstring_tokens": ["Creates", "a", "new", "instance", "of", "the", "command", "and", "sets", "up", "OptionParser", "."], "sha": "efea81648ac22016619780bc9859cbdddcc88ea3", "url": "https://github.com/YorickPeterse/shebang/blob/efea81648ac22016619780bc9859cbdddcc88ea3/lib/shebang/command.rb#L186-L196", "partition": "valid"} {"repo": "YorickPeterse/shebang", "path": "lib/shebang/command.rb", "func_name": "Shebang.Command.option", "original_string": "def option(opt)\n opt = opt.to_sym\n\n options.each do |op|\n if op.short === opt or op.long === opt\n return op.value\n end\n end\n end", "language": "ruby", "code": "def option(opt)\n opt = opt.to_sym\n\n options.each do |op|\n if op.short === opt or op.long === opt\n return op.value\n end\n end\n end", "code_tokens": ["def", "option", "(", "opt", ")", "opt", "=", "opt", ".", "to_sym", "options", ".", "each", "do", "|", "op", "|", "if", "op", ".", "short", "===", "opt", "or", "op", ".", "long", "===", "opt", "return", "op", ".", "value", "end", "end", "end"], "docstring": "Returns the value of a given option. The option can be specified using\n either the short or long name.\n\n @example\n puts \"Hello #{option(:name)}\n\n @author Yorick Peterse\n @since 0.1\n @param [#to_sym] opt The name of the option.\n @return [Mixed]", "docstring_tokens": ["Returns", "the", "value", "of", "a", "given", "option", ".", "The", "option", "can", "be", "specified", "using", "either", "the", "short", "or", "long", "name", "."], "sha": "efea81648ac22016619780bc9859cbdddcc88ea3", "url": "https://github.com/YorickPeterse/shebang/blob/efea81648ac22016619780bc9859cbdddcc88ea3/lib/shebang/command.rb#L253-L261", "partition": "valid"} {"repo": "markquezada/fcs", "path": "lib/fcs/client.rb", "func_name": "FCS.Client.method_missing", "original_string": "def method_missing(method, *args, &block)\n klass = class_for_api_command(method)\n\n return klass.new(@socket).send(method, *args, &block) if klass\n super(method, *args, &block)\n end", "language": "ruby", "code": "def method_missing(method, *args, &block)\n klass = class_for_api_command(method)\n\n return klass.new(@socket).send(method, *args, &block) if klass\n super(method, *args, &block)\n end", "code_tokens": ["def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "klass", "=", "class_for_api_command", "(", "method", ")", "return", "klass", ".", "new", "(", "@socket", ")", ".", "send", "(", "method", ",", "args", ",", "block", ")", "if", "klass", "super", "(", "method", ",", "args", ",", "block", ")", "end"], "docstring": "Delgate api call to Request", "docstring_tokens": ["Delgate", "api", "call", "to", "Request"], "sha": "500ff5bf43082d98a89a3bb0843056b76aa9e9c9", "url": "https://github.com/markquezada/fcs/blob/500ff5bf43082d98a89a3bb0843056b76aa9e9c9/lib/fcs/client.rb#L32-L37", "partition": "valid"} {"repo": "seblindberg/ruby-linked", "path": "lib/linked/listable.rb", "func_name": "Linked.Listable.in_chain?", "original_string": "def in_chain?(other)\n return false unless other.is_a? Listable\n chain_head.equal? other.chain_head\n end", "language": "ruby", "code": "def in_chain?(other)\n return false unless other.is_a? Listable\n chain_head.equal? other.chain_head\n end", "code_tokens": ["def", "in_chain?", "(", "other", ")", "return", "false", "unless", "other", ".", "is_a?", "Listable", "chain_head", ".", "equal?", "other", ".", "chain_head", "end"], "docstring": "Check if this object is in a chain.\n\n @param other [Object] the object to check.\n @return [true] if this object is in the same chain as the given one.\n @return [false] otherwise.", "docstring_tokens": ["Check", "if", "this", "object", "is", "in", "a", "chain", "."], "sha": "ea4e7ee23a26db599b48b0e32c0c1ecf46adf682", "url": "https://github.com/seblindberg/ruby-linked/blob/ea4e7ee23a26db599b48b0e32c0c1ecf46adf682/lib/linked/listable.rb#L126-L129", "partition": "valid"} {"repo": "seblindberg/ruby-linked", "path": "lib/linked/listable.rb", "func_name": "Linked.Listable.before", "original_string": "def before\n return to_enum(__callee__) unless block_given?\n return if chain_head?\n\n item = prev\n\n loop do\n yield item\n item = item.prev\n end\n end", "language": "ruby", "code": "def before\n return to_enum(__callee__) unless block_given?\n return if chain_head?\n\n item = prev\n\n loop do\n yield item\n item = item.prev\n end\n end", "code_tokens": ["def", "before", "return", "to_enum", "(", "__callee__", ")", "unless", "block_given?", "return", "if", "chain_head?", "item", "=", "prev", "loop", "do", "yield", "item", "item", "=", "item", ".", "prev", "end", "end"], "docstring": "Iterates over each item before this, in reverse order. If a block is not\n given an enumerator is returned.\n\n Note that raising a StopIteraion inside the block will cause the loop to\n silently stop the iteration early.", "docstring_tokens": ["Iterates", "over", "each", "item", "before", "this", "in", "reverse", "order", ".", "If", "a", "block", "is", "not", "given", "an", "enumerator", "is", "returned", "."], "sha": "ea4e7ee23a26db599b48b0e32c0c1ecf46adf682", "url": "https://github.com/seblindberg/ruby-linked/blob/ea4e7ee23a26db599b48b0e32c0c1ecf46adf682/lib/linked/listable.rb#L173-L183", "partition": "valid"} {"repo": "seblindberg/ruby-linked", "path": "lib/linked/listable.rb", "func_name": "Linked.Listable.after", "original_string": "def after\n return to_enum(__callee__) unless block_given?\n return if chain_tail?\n\n item = self.next\n\n loop do\n yield item\n item = item.next\n end\n end", "language": "ruby", "code": "def after\n return to_enum(__callee__) unless block_given?\n return if chain_tail?\n\n item = self.next\n\n loop do\n yield item\n item = item.next\n end\n end", "code_tokens": ["def", "after", "return", "to_enum", "(", "__callee__", ")", "unless", "block_given?", "return", "if", "chain_tail?", "item", "=", "self", ".", "next", "loop", "do", "yield", "item", "item", "=", "item", ".", "next", "end", "end"], "docstring": "Iterates over each item after this. If a block is not given an enumerator\n is returned.\n\n Note that raising a StopIteraion inside the block will cause the loop to\n silently stop the iteration early.", "docstring_tokens": ["Iterates", "over", "each", "item", "after", "this", ".", "If", "a", "block", "is", "not", "given", "an", "enumerator", "is", "returned", "."], "sha": "ea4e7ee23a26db599b48b0e32c0c1ecf46adf682", "url": "https://github.com/seblindberg/ruby-linked/blob/ea4e7ee23a26db599b48b0e32c0c1ecf46adf682/lib/linked/listable.rb#L190-L200", "partition": "valid"} {"repo": "berkes/bitkassa", "path": "lib/bitkassa/payment_result.rb", "func_name": "Bitkassa.PaymentResult.valid?", "original_string": "def valid?\n return false if raw_payload.nil? || raw_payload.empty?\n return false if raw_authentication.nil? || raw_authentication.empty?\n return false unless json_valid?\n\n Authentication.valid?(raw_authentication, json_payload)\n end", "language": "ruby", "code": "def valid?\n return false if raw_payload.nil? || raw_payload.empty?\n return false if raw_authentication.nil? || raw_authentication.empty?\n return false unless json_valid?\n\n Authentication.valid?(raw_authentication, json_payload)\n end", "code_tokens": ["def", "valid?", "return", "false", "if", "raw_payload", ".", "nil?", "||", "raw_payload", ".", "empty?", "return", "false", "if", "raw_authentication", ".", "nil?", "||", "raw_authentication", ".", "empty?", "return", "false", "unless", "json_valid?", "Authentication", ".", "valid?", "(", "raw_authentication", ",", "json_payload", ")", "end"], "docstring": "Wether or not this payment result can be considered valid.\n Authentication is checked, payload and authentication should be available\n and the decoded JSON should be valid JSON.\n When the result is valid, it is safe to assume no-one tampered with it\n and that it was sent by Bitkassa.", "docstring_tokens": ["Wether", "or", "not", "this", "payment", "result", "can", "be", "considered", "valid", ".", "Authentication", "is", "checked", "payload", "and", "authentication", "should", "be", "available", "and", "the", "decoded", "JSON", "should", "be", "valid", "JSON", ".", "When", "the", "result", "is", "valid", "it", "is", "safe", "to", "assume", "no", "-", "one", "tampered", "with", "it", "and", "that", "it", "was", "sent", "by", "Bitkassa", "."], "sha": "ba51277d2d542840d3411f981e3846fb13c7dd23", "url": "https://github.com/berkes/bitkassa/blob/ba51277d2d542840d3411f981e3846fb13c7dd23/lib/bitkassa/payment_result.rb#L52-L58", "partition": "valid"} {"repo": "lasseebert/incremental_backup", "path": "lib/incremental_backup/task.rb", "func_name": "IncrementalBackup.Task.run", "original_string": "def run\n\n # Validate - this will throw an exception if settings are not valid\n validate_settings\n\n # Run everything inside a lock, ensuring that only one instance of this\n # task is running.\n Lock.create(self) do\n\n # Find the schedule to run\n schedule = find_schedule\n unless schedule\n logger.info \"No backup needed - exiting\"\n return\n end\n\n logger.info \"Starting #{schedule} backup to #{settings.remote_server}\"\n\n # Paths and other options\n timestamp = Time.now.strftime('backup_%Y-%m-%d-T%H-%M-%S')\n current_path = File.join(settings.remote_path, 'current')\n progress_path = File.join(settings.remote_path, 'incomplete')\n complete_path = File.join(schedule_path(schedule), timestamp)\n login = \"#{settings.remote_user}@#{settings.remote_server}\"\n rsync_path = \"#{login}:#{progress_path}\"\n\n # Make schedule folder\n execute_ssh \"mkdir --verbose --parents #{schedule_path schedule}\"\n\n # Rsync\n Rsync.execute(logger, settings.local_path, rsync_path, {\n exclude_file: settings.exclude_file,\n link_dest: current_path,\n max_upload_speed: settings.max_upload_speed,\n max_download_speed: settings.max_download_speed\n })\n\n # shuffle backups around\n logger.info \"Do the backup shuffle\"\n execute_ssh [\n \"mv --verbose #{progress_path} #{complete_path}\",\n \"rm --verbose --force #{current_path}\",\n \"ln --verbose --symbolic #{complete_path} #{current_path}\",\n ]\n\n delete_old_backups schedule\n\n logger.info \"#{schedule} backup done\"\n end\n\n rescue Exception => exception\n logger.error exception.message\n logger.error exception.backtrace\n end", "language": "ruby", "code": "def run\n\n # Validate - this will throw an exception if settings are not valid\n validate_settings\n\n # Run everything inside a lock, ensuring that only one instance of this\n # task is running.\n Lock.create(self) do\n\n # Find the schedule to run\n schedule = find_schedule\n unless schedule\n logger.info \"No backup needed - exiting\"\n return\n end\n\n logger.info \"Starting #{schedule} backup to #{settings.remote_server}\"\n\n # Paths and other options\n timestamp = Time.now.strftime('backup_%Y-%m-%d-T%H-%M-%S')\n current_path = File.join(settings.remote_path, 'current')\n progress_path = File.join(settings.remote_path, 'incomplete')\n complete_path = File.join(schedule_path(schedule), timestamp)\n login = \"#{settings.remote_user}@#{settings.remote_server}\"\n rsync_path = \"#{login}:#{progress_path}\"\n\n # Make schedule folder\n execute_ssh \"mkdir --verbose --parents #{schedule_path schedule}\"\n\n # Rsync\n Rsync.execute(logger, settings.local_path, rsync_path, {\n exclude_file: settings.exclude_file,\n link_dest: current_path,\n max_upload_speed: settings.max_upload_speed,\n max_download_speed: settings.max_download_speed\n })\n\n # shuffle backups around\n logger.info \"Do the backup shuffle\"\n execute_ssh [\n \"mv --verbose #{progress_path} #{complete_path}\",\n \"rm --verbose --force #{current_path}\",\n \"ln --verbose --symbolic #{complete_path} #{current_path}\",\n ]\n\n delete_old_backups schedule\n\n logger.info \"#{schedule} backup done\"\n end\n\n rescue Exception => exception\n logger.error exception.message\n logger.error exception.backtrace\n end", "code_tokens": ["def", "run", "# Validate - this will throw an exception if settings are not valid", "validate_settings", "# Run everything inside a lock, ensuring that only one instance of this", "# task is running.", "Lock", ".", "create", "(", "self", ")", "do", "# Find the schedule to run", "schedule", "=", "find_schedule", "unless", "schedule", "logger", ".", "info", "\"No backup needed - exiting\"", "return", "end", "logger", ".", "info", "\"Starting #{schedule} backup to #{settings.remote_server}\"", "# Paths and other options", "timestamp", "=", "Time", ".", "now", ".", "strftime", "(", "'backup_%Y-%m-%d-T%H-%M-%S'", ")", "current_path", "=", "File", ".", "join", "(", "settings", ".", "remote_path", ",", "'current'", ")", "progress_path", "=", "File", ".", "join", "(", "settings", ".", "remote_path", ",", "'incomplete'", ")", "complete_path", "=", "File", ".", "join", "(", "schedule_path", "(", "schedule", ")", ",", "timestamp", ")", "login", "=", "\"#{settings.remote_user}@#{settings.remote_server}\"", "rsync_path", "=", "\"#{login}:#{progress_path}\"", "# Make schedule folder", "execute_ssh", "\"mkdir --verbose --parents #{schedule_path schedule}\"", "# Rsync", "Rsync", ".", "execute", "(", "logger", ",", "settings", ".", "local_path", ",", "rsync_path", ",", "{", "exclude_file", ":", "settings", ".", "exclude_file", ",", "link_dest", ":", "current_path", ",", "max_upload_speed", ":", "settings", ".", "max_upload_speed", ",", "max_download_speed", ":", "settings", ".", "max_download_speed", "}", ")", "# shuffle backups around", "logger", ".", "info", "\"Do the backup shuffle\"", "execute_ssh", "[", "\"mv --verbose #{progress_path} #{complete_path}\"", ",", "\"rm --verbose --force #{current_path}\"", ",", "\"ln --verbose --symbolic #{complete_path} #{current_path}\"", ",", "]", "delete_old_backups", "schedule", "logger", ".", "info", "\"#{schedule} backup done\"", "end", "rescue", "Exception", "=>", "exception", "logger", ".", "error", "exception", ".", "message", "logger", ".", "error", "exception", ".", "backtrace", "end"], "docstring": "Perform the backup", "docstring_tokens": ["Perform", "the", "backup"], "sha": "afa50dd612e1a34d23fc346b705c77b2eecc0ddb", "url": "https://github.com/lasseebert/incremental_backup/blob/afa50dd612e1a34d23fc346b705c77b2eecc0ddb/lib/incremental_backup/task.rb#L18-L71", "partition": "valid"} {"repo": "lasseebert/incremental_backup", "path": "lib/incremental_backup/task.rb", "func_name": "IncrementalBackup.Task.execute_ssh", "original_string": "def execute_ssh(commands)\n commands = [commands] unless commands.is_a? Array\n result = \"\"\n Net::SSH.start settings.remote_server, settings.remote_user do |ssh|\n commands.each do |command|\n was_error = false\n logger.info \"ssh: #{command}\"\n ssh.exec! command do |channel, stream, data|\n case stream\n when :stdout\n logger.info data\n result += \"#{data}\\n\" unless data.empty?\n when :stderr\n logger.error data\n was_error = true\n end\n end\n throw \"Exception during ssh, look in log file\" if was_error\n end\n end\n result\n end", "language": "ruby", "code": "def execute_ssh(commands)\n commands = [commands] unless commands.is_a? Array\n result = \"\"\n Net::SSH.start settings.remote_server, settings.remote_user do |ssh|\n commands.each do |command|\n was_error = false\n logger.info \"ssh: #{command}\"\n ssh.exec! command do |channel, stream, data|\n case stream\n when :stdout\n logger.info data\n result += \"#{data}\\n\" unless data.empty?\n when :stderr\n logger.error data\n was_error = true\n end\n end\n throw \"Exception during ssh, look in log file\" if was_error\n end\n end\n result\n end", "code_tokens": ["def", "execute_ssh", "(", "commands", ")", "commands", "=", "[", "commands", "]", "unless", "commands", ".", "is_a?", "Array", "result", "=", "\"\"", "Net", "::", "SSH", ".", "start", "settings", ".", "remote_server", ",", "settings", ".", "remote_user", "do", "|", "ssh", "|", "commands", ".", "each", "do", "|", "command", "|", "was_error", "=", "false", "logger", ".", "info", "\"ssh: #{command}\"", "ssh", ".", "exec!", "command", "do", "|", "channel", ",", "stream", ",", "data", "|", "case", "stream", "when", ":stdout", "logger", ".", "info", "data", "result", "+=", "\"#{data}\\n\"", "unless", "data", ".", "empty?", "when", ":stderr", "logger", ".", "error", "data", "was_error", "=", "true", "end", "end", "throw", "\"Exception during ssh, look in log file\"", "if", "was_error", "end", "end", "result", "end"], "docstring": "Runs one ore more commands remotely via ssh", "docstring_tokens": ["Runs", "one", "ore", "more", "commands", "remotely", "via", "ssh"], "sha": "afa50dd612e1a34d23fc346b705c77b2eecc0ddb", "url": "https://github.com/lasseebert/incremental_backup/blob/afa50dd612e1a34d23fc346b705c77b2eecc0ddb/lib/incremental_backup/task.rb#L118-L139", "partition": "valid"} {"repo": "lasseebert/incremental_backup", "path": "lib/incremental_backup/task.rb", "func_name": "IncrementalBackup.Task.find_schedule", "original_string": "def find_schedule\n minutes = {\n # If a cron job is run hourly it can be off by a couple of seconds\n # from the last run. Set hourly to 58 minutes\n hourly: 58, \n daily: 24*60,\n weekly: 7*24*60,\n monthly: 30*24*60,\n yearly: 365*24*60\n }\n\n now = DateTime.now\n [:yearly, :monthly, :weekly, :daily, :hourly].each do |schedule|\n next if backups_to_keep(schedule) <= 0\n list = list_backup_dir schedule\n date = list.map { |path| parse_backup_dir_name path, now.offset }.max\n return schedule if !date || (now - date) * 24 * 60 >= minutes[schedule]\n end\n\n nil\n end", "language": "ruby", "code": "def find_schedule\n minutes = {\n # If a cron job is run hourly it can be off by a couple of seconds\n # from the last run. Set hourly to 58 minutes\n hourly: 58, \n daily: 24*60,\n weekly: 7*24*60,\n monthly: 30*24*60,\n yearly: 365*24*60\n }\n\n now = DateTime.now\n [:yearly, :monthly, :weekly, :daily, :hourly].each do |schedule|\n next if backups_to_keep(schedule) <= 0\n list = list_backup_dir schedule\n date = list.map { |path| parse_backup_dir_name path, now.offset }.max\n return schedule if !date || (now - date) * 24 * 60 >= minutes[schedule]\n end\n\n nil\n end", "code_tokens": ["def", "find_schedule", "minutes", "=", "{", "# If a cron job is run hourly it can be off by a couple of seconds", "# from the last run. Set hourly to 58 minutes", "hourly", ":", "58", ",", "daily", ":", "24", "*", "60", ",", "weekly", ":", "7", "*", "24", "*", "60", ",", "monthly", ":", "30", "*", "24", "*", "60", ",", "yearly", ":", "365", "*", "24", "*", "60", "}", "now", "=", "DateTime", ".", "now", "[", ":yearly", ",", ":monthly", ",", ":weekly", ",", ":daily", ",", ":hourly", "]", ".", "each", "do", "|", "schedule", "|", "next", "if", "backups_to_keep", "(", "schedule", ")", "<=", "0", "list", "=", "list_backup_dir", "schedule", "date", "=", "list", ".", "map", "{", "|", "path", "|", "parse_backup_dir_name", "path", ",", "now", ".", "offset", "}", ".", "max", "return", "schedule", "if", "!", "date", "||", "(", "now", "-", "date", ")", "*", "24", "*", "60", ">=", "minutes", "[", "schedule", "]", "end", "nil", "end"], "docstring": "Find out which schedule to run", "docstring_tokens": ["Find", "out", "which", "schedule", "to", "run"], "sha": "afa50dd612e1a34d23fc346b705c77b2eecc0ddb", "url": "https://github.com/lasseebert/incremental_backup/blob/afa50dd612e1a34d23fc346b705c77b2eecc0ddb/lib/incremental_backup/task.rb#L142-L162", "partition": "valid"} {"repo": "berkes/bitkassa", "path": "lib/bitkassa/config.rb", "func_name": "Bitkassa.Config.debug=", "original_string": "def debug=(mode)\n @debug = mode\n\n if mode\n HTTPI.log = true\n HTTPI.log_level = :debug\n else\n HTTPI.log = false\n end\n end", "language": "ruby", "code": "def debug=(mode)\n @debug = mode\n\n if mode\n HTTPI.log = true\n HTTPI.log_level = :debug\n else\n HTTPI.log = false\n end\n end", "code_tokens": ["def", "debug", "=", "(", "mode", ")", "@debug", "=", "mode", "if", "mode", "HTTPI", ".", "log", "=", "true", "HTTPI", ".", "log_level", "=", ":debug", "else", "HTTPI", ".", "log", "=", "false", "end", "end"], "docstring": "Sets defaults for the configuration.\n Enable or disable debug mode. Boolean.", "docstring_tokens": ["Sets", "defaults", "for", "the", "configuration", ".", "Enable", "or", "disable", "debug", "mode", ".", "Boolean", "."], "sha": "ba51277d2d542840d3411f981e3846fb13c7dd23", "url": "https://github.com/berkes/bitkassa/blob/ba51277d2d542840d3411f981e3846fb13c7dd23/lib/bitkassa/config.rb#L24-L33", "partition": "valid"} {"repo": "YorickPeterse/shebang", "path": "lib/shebang/option.rb", "func_name": "Shebang.Option.option_parser", "original_string": "def option_parser\n params = [\"-#{@short}\", \"--#{@long}\", nil, @options[:type]]\n\n if !@description.nil? and !@description.empty?\n params[2] = @description\n end\n\n # Set the correct format for the long/short option based on the type.\n if ![TrueClass, FalseClass].include?(@options[:type])\n params[1] += \" #{@options[:key]}\"\n end\n\n return params\n end", "language": "ruby", "code": "def option_parser\n params = [\"-#{@short}\", \"--#{@long}\", nil, @options[:type]]\n\n if !@description.nil? and !@description.empty?\n params[2] = @description\n end\n\n # Set the correct format for the long/short option based on the type.\n if ![TrueClass, FalseClass].include?(@options[:type])\n params[1] += \" #{@options[:key]}\"\n end\n\n return params\n end", "code_tokens": ["def", "option_parser", "params", "=", "[", "\"-#{@short}\"", ",", "\"--#{@long}\"", ",", "nil", ",", "@options", "[", ":type", "]", "]", "if", "!", "@description", ".", "nil?", "and", "!", "@description", ".", "empty?", "params", "[", "2", "]", "=", "@description", "end", "# Set the correct format for the long/short option based on the type.", "if", "!", "[", "TrueClass", ",", "FalseClass", "]", ".", "include?", "(", "@options", "[", ":type", "]", ")", "params", "[", "1", "]", "+=", "\" #{@options[:key]}\"", "end", "return", "params", "end"], "docstring": "Creates a new instance of the Option class.\n\n @author Yorick Peterse\n @since 0.1\n @param [#to_sym] short The short option name such as :h.\n @param [#to_sym] long The long option name such as :help.\n @param [String] desc The description of the option.\n @param [Hash] options Hash containing various configuration options for\n the OptionParser option.\n @option options :type The type of value for the option, set to TrueClass\n by default.\n @option options :key The key to use to indicate a value whenever the type\n of an option is something else than TrueClass or FalseClass. This option\n is set to \"VALUE\" by default.\n @option options :method A symbol that refers to a method that should be\n called whenever the option is specified.\n @option options :required Indicates that the option has to be specified.\n @option options :default The default value of the option.\n\n\n Builds an array containing all the required parameters for\n OptionParser#on().\n\n @author Yorick Peterse\n @since 0.1\n @return [Array]", "docstring_tokens": ["Creates", "a", "new", "instance", "of", "the", "Option", "class", "."], "sha": "efea81648ac22016619780bc9859cbdddcc88ea3", "url": "https://github.com/YorickPeterse/shebang/blob/efea81648ac22016619780bc9859cbdddcc88ea3/lib/shebang/option.rb#L54-L67", "partition": "valid"} {"repo": "seblindberg/ruby-linked", "path": "lib/linked/list.rb", "func_name": "Linked.List.shift", "original_string": "def shift\n return nil if empty?\n\n if list_head.last?\n @_chain.tap { @_chain = nil }\n else\n old_head = list_head\n @_chain = list_head.next\n old_head.delete\n end\n end", "language": "ruby", "code": "def shift\n return nil if empty?\n\n if list_head.last?\n @_chain.tap { @_chain = nil }\n else\n old_head = list_head\n @_chain = list_head.next\n old_head.delete\n end\n end", "code_tokens": ["def", "shift", "return", "nil", "if", "empty?", "if", "list_head", ".", "last?", "@_chain", ".", "tap", "{", "@_chain", "=", "nil", "}", "else", "old_head", "=", "list_head", "@_chain", "=", "list_head", ".", "next", "old_head", ".", "delete", "end", "end"], "docstring": "Shift the first item off the list.\n\n @return [Listable, nil] the first item in the list, or nil if the list is\n empty.", "docstring_tokens": ["Shift", "the", "first", "item", "off", "the", "list", "."], "sha": "ea4e7ee23a26db599b48b0e32c0c1ecf46adf682", "url": "https://github.com/seblindberg/ruby-linked/blob/ea4e7ee23a26db599b48b0e32c0c1ecf46adf682/lib/linked/list.rb#L114-L124", "partition": "valid"} {"repo": "PGSSoft/GoldenRose", "path": "lib/golden_rose/results_filterer.rb", "func_name": "GoldenRose.ResultsFilterer.compact_results", "original_string": "def compact_results(items)\n items.map do |subtest|\n subtests = subtest[:subtests]\n if subtests.size > 1\n subtests\n elsif subtests.size == 1\n compact_results(subtests)\n end\n end.flatten.compact\n end", "language": "ruby", "code": "def compact_results(items)\n items.map do |subtest|\n subtests = subtest[:subtests]\n if subtests.size > 1\n subtests\n elsif subtests.size == 1\n compact_results(subtests)\n end\n end.flatten.compact\n end", "code_tokens": ["def", "compact_results", "(", "items", ")", "items", ".", "map", "do", "|", "subtest", "|", "subtests", "=", "subtest", "[", ":subtests", "]", "if", "subtests", ".", "size", ">", "1", "subtests", "elsif", "subtests", ".", "size", "==", "1", "compact_results", "(", "subtests", ")", "end", "end", ".", "flatten", ".", "compact", "end"], "docstring": "This method simplify results structure,\n it sets only one level of nesting\n by leaving parents only with collection as child", "docstring_tokens": ["This", "method", "simplify", "results", "structure", "it", "sets", "only", "one", "level", "of", "nesting", "by", "leaving", "parents", "only", "with", "collection", "as", "child"], "sha": "c5af1e1968b77c89058a76ba30fc5533c34b1763", "url": "https://github.com/PGSSoft/GoldenRose/blob/c5af1e1968b77c89058a76ba30fc5533c34b1763/lib/golden_rose/results_filterer.rb#L42-L51", "partition": "valid"} {"repo": "tconnolly/BnetApi", "path": "lib/bnet_api/wow.rb", "func_name": "BnetApi.WoW.pet_stats", "original_string": "def pet_stats(species_id, options = {})\r\n level = options[:level] || 1\r\n breedId = options[:breedId] || 3\r\n qualityId = options[:qualityId] || 1\r\n\r\n BnetApi.make_request_with_params(\"/wow/pet/stats/#{species_id}\",\r\n { \r\n level: level, \r\n breedId: breedId, \r\n qualityId: qualityId }\r\n )\r\n end", "language": "ruby", "code": "def pet_stats(species_id, options = {})\r\n level = options[:level] || 1\r\n breedId = options[:breedId] || 3\r\n qualityId = options[:qualityId] || 1\r\n\r\n BnetApi.make_request_with_params(\"/wow/pet/stats/#{species_id}\",\r\n { \r\n level: level, \r\n breedId: breedId, \r\n qualityId: qualityId }\r\n )\r\n end", "code_tokens": ["def", "pet_stats", "(", "species_id", ",", "options", "=", "{", "}", ")", "level", "=", "options", "[", ":level", "]", "||", "1", "breedId", "=", "options", "[", ":breedId", "]", "||", "3", "qualityId", "=", "options", "[", ":qualityId", "]", "||", "1", "BnetApi", ".", "make_request_with_params", "(", "\"/wow/pet/stats/#{species_id}\"", ",", "{", "level", ":", "level", ",", "breedId", ":", "breedId", ",", "qualityId", ":", "qualityId", "}", ")", "end"], "docstring": "Retrieves the stats for the pet with the specified ID.\n\n @param species_id [Integer] The ID of the pet species.\n @param options [Hash] Any additional options.\n @option options [Integer] :level The level of the species.\n @option options [Integer] :breedId The ID of the breed.\n @option options [Integer] :qualityId The quality of the pet.\n @return [Hash] A hash containing the pet stats data.", "docstring_tokens": ["Retrieves", "the", "stats", "for", "the", "pet", "with", "the", "specified", "ID", "."], "sha": "0d1c75822e1faafa8f148e0228371ebb04b24bfb", "url": "https://github.com/tconnolly/BnetApi/blob/0d1c75822e1faafa8f148e0228371ebb04b24bfb/lib/bnet_api/wow.rb#L112-L123", "partition": "valid"} {"repo": "tconnolly/BnetApi", "path": "lib/bnet_api/wow.rb", "func_name": "BnetApi.WoW.realm_status", "original_string": "def realm_status(*realms)\r\n if realms.count > 0\r\n BnetApi.make_request_with_params(\"/wow/realm/status\", { realms: realms.join(',') })\r\n else\r\n BnetApi.make_request(\"/wow/realm/status\")\r\n end\r\n end", "language": "ruby", "code": "def realm_status(*realms)\r\n if realms.count > 0\r\n BnetApi.make_request_with_params(\"/wow/realm/status\", { realms: realms.join(',') })\r\n else\r\n BnetApi.make_request(\"/wow/realm/status\")\r\n end\r\n end", "code_tokens": ["def", "realm_status", "(", "*", "realms", ")", "if", "realms", ".", "count", ">", "0", "BnetApi", ".", "make_request_with_params", "(", "\"/wow/realm/status\"", ",", "{", "realms", ":", "realms", ".", "join", "(", "','", ")", "}", ")", "else", "BnetApi", ".", "make_request", "(", "\"/wow/realm/status\"", ")", "end", "end"], "docstring": "Retrieves the realm status for the region. If any realms are specified as parameters,\n only the status of these realms will be returned.\n\n @param *realms [Array] Any realms to restrict the data to.\n @return [Hash] A hash containing the realm status data.", "docstring_tokens": ["Retrieves", "the", "realm", "status", "for", "the", "region", ".", "If", "any", "realms", "are", "specified", "as", "parameters", "only", "the", "status", "of", "these", "realms", "will", "be", "returned", "."], "sha": "0d1c75822e1faafa8f148e0228371ebb04b24bfb", "url": "https://github.com/tconnolly/BnetApi/blob/0d1c75822e1faafa8f148e0228371ebb04b24bfb/lib/bnet_api/wow.rb#L146-L152", "partition": "valid"} {"repo": "klaustopher/cloudmade", "path": "lib/cloudmade/tiles.rb", "func_name": "CloudMade.TilesService.get_tile", "original_string": "def get_tile(lat, lon, zoom, style_id = nil, tile_size = nil)\n get_xy_tile(xtile(lon, zoom), ytile(lat, zoom), zoom, style_id, tile_size)\n end", "language": "ruby", "code": "def get_tile(lat, lon, zoom, style_id = nil, tile_size = nil)\n get_xy_tile(xtile(lon, zoom), ytile(lat, zoom), zoom, style_id, tile_size)\n end", "code_tokens": ["def", "get_tile", "(", "lat", ",", "lon", ",", "zoom", ",", "style_id", "=", "nil", ",", "tile_size", "=", "nil", ")", "get_xy_tile", "(", "xtile", "(", "lon", ",", "zoom", ")", ",", "ytile", "(", "lat", ",", "zoom", ")", ",", "zoom", ",", "style_id", ",", "tile_size", ")", "end"], "docstring": "Get tile with given latitude, longitude and zoom.\n Returns Raw PNG data which could be saved to file\n\n * +lat+ Latitude of requested tile\n * +lon+ Longitude of requested tile\n * +zoom+ Zoom level, on which tile is being requested\n * +style_id+ CloudMade's style id, if not given, default style is used (usually 1)\n * +tile_size+ size of tile, if not given the default 256 is used", "docstring_tokens": ["Get", "tile", "with", "given", "latitude", "longitude", "and", "zoom", ".", "Returns", "Raw", "PNG", "data", "which", "could", "be", "saved", "to", "file"], "sha": "3d3554b6048970eed7d95af40e9055f003cdb1e1", "url": "https://github.com/klaustopher/cloudmade/blob/3d3554b6048970eed7d95af40e9055f003cdb1e1/lib/cloudmade/tiles.rb#L84-L86", "partition": "valid"} {"repo": "klaustopher/cloudmade", "path": "lib/cloudmade/tiles.rb", "func_name": "CloudMade.TilesService.get_xy_tile", "original_string": "def get_xy_tile(xtile, ytile, zoom, style_id = nil, tile_size = nil)\n style_id = self.default_style_id if style_id == nil\n tile_size = self.default_tile_size if tile_size == nil\n connect \"/#{style_id}/#{tile_size}/#{zoom}/#{xtile}/#{ytile}.png\"\n end", "language": "ruby", "code": "def get_xy_tile(xtile, ytile, zoom, style_id = nil, tile_size = nil)\n style_id = self.default_style_id if style_id == nil\n tile_size = self.default_tile_size if tile_size == nil\n connect \"/#{style_id}/#{tile_size}/#{zoom}/#{xtile}/#{ytile}.png\"\n end", "code_tokens": ["def", "get_xy_tile", "(", "xtile", ",", "ytile", ",", "zoom", ",", "style_id", "=", "nil", ",", "tile_size", "=", "nil", ")", "style_id", "=", "self", ".", "default_style_id", "if", "style_id", "==", "nil", "tile_size", "=", "self", ".", "default_tile_size", "if", "tile_size", "==", "nil", "connect", "\"/#{style_id}/#{tile_size}/#{zoom}/#{xtile}/#{ytile}.png\"", "end"], "docstring": "Get tile with given x, y numbers and zoom\n Returns Raw PNG data which could be saved to file\n\n * +xtile+\n * +ytile+\n * +zoom+ Zoom level, on which tile is being requested\n * +style_id+ CloudMade's style id, if not given, default style is used (usually 1)\n * +tile_size+ size of tile, if not given the default 256 is used", "docstring_tokens": ["Get", "tile", "with", "given", "x", "y", "numbers", "and", "zoom", "Returns", "Raw", "PNG", "data", "which", "could", "be", "saved", "to", "file"], "sha": "3d3554b6048970eed7d95af40e9055f003cdb1e1", "url": "https://github.com/klaustopher/cloudmade/blob/3d3554b6048970eed7d95af40e9055f003cdb1e1/lib/cloudmade/tiles.rb#L96-L100", "partition": "valid"} {"repo": "seblindberg/ruby-linked", "path": "lib/linked/list_enumerable.rb", "func_name": "Linked.ListEnumerable.each_item", "original_string": "def each_item\n return to_enum(__method__) { count } unless block_given?\n return if empty?\n\n item = list_head\n loop do\n yield item\n item = item.next\n end\n end", "language": "ruby", "code": "def each_item\n return to_enum(__method__) { count } unless block_given?\n return if empty?\n\n item = list_head\n loop do\n yield item\n item = item.next\n end\n end", "code_tokens": ["def", "each_item", "return", "to_enum", "(", "__method__", ")", "{", "count", "}", "unless", "block_given?", "return", "if", "empty?", "item", "=", "list_head", "loop", "do", "yield", "item", "item", "=", "item", ".", "next", "end", "end"], "docstring": "Iterates over each item in the list If a block is not given an enumerator\n is returned.", "docstring_tokens": ["Iterates", "over", "each", "item", "in", "the", "list", "If", "a", "block", "is", "not", "given", "an", "enumerator", "is", "returned", "."], "sha": "ea4e7ee23a26db599b48b0e32c0c1ecf46adf682", "url": "https://github.com/seblindberg/ruby-linked/blob/ea4e7ee23a26db599b48b0e32c0c1ecf46adf682/lib/linked/list_enumerable.rb#L10-L19", "partition": "valid"} {"repo": "seblindberg/ruby-linked", "path": "lib/linked/list_enumerable.rb", "func_name": "Linked.ListEnumerable.reverse_each_item", "original_string": "def reverse_each_item\n return to_enum(__method__) { count } unless block_given?\n return if empty?\n\n item = list_tail\n loop do\n yield item\n item = item.prev\n end\n end", "language": "ruby", "code": "def reverse_each_item\n return to_enum(__method__) { count } unless block_given?\n return if empty?\n\n item = list_tail\n loop do\n yield item\n item = item.prev\n end\n end", "code_tokens": ["def", "reverse_each_item", "return", "to_enum", "(", "__method__", ")", "{", "count", "}", "unless", "block_given?", "return", "if", "empty?", "item", "=", "list_tail", "loop", "do", "yield", "item", "item", "=", "item", ".", "prev", "end", "end"], "docstring": "Iterates over each item in the list in reverse order. If a block is not\n given an enumerator is returned.\n\n @yield [Listable] each item in the list.\n @return [Enumerable] if no block is given.", "docstring_tokens": ["Iterates", "over", "each", "item", "in", "the", "list", "in", "reverse", "order", ".", "If", "a", "block", "is", "not", "given", "an", "enumerator", "is", "returned", "."], "sha": "ea4e7ee23a26db599b48b0e32c0c1ecf46adf682", "url": "https://github.com/seblindberg/ruby-linked/blob/ea4e7ee23a26db599b48b0e32c0c1ecf46adf682/lib/linked/list_enumerable.rb#L28-L37", "partition": "valid"} {"repo": "ridiculous/duck_puncher", "path": "lib/duck_puncher/registration.rb", "func_name": "DuckPuncher.Registration.register", "original_string": "def register(target, *mods, &block)\n options = mods.last.is_a?(Hash) ? mods.pop : {}\n mods << Module.new(&block) if block\n target = DuckPuncher.lookup_constant target\n Ducks.list[target] = Set.new [] unless Ducks.list.key?(target)\n mods = Array(mods).each do |mod|\n duck = UniqueDuck.new Duck.new(target, mod, options)\n Ducks.list[target] << duck\n end\n [target, *mods]\n end", "language": "ruby", "code": "def register(target, *mods, &block)\n options = mods.last.is_a?(Hash) ? mods.pop : {}\n mods << Module.new(&block) if block\n target = DuckPuncher.lookup_constant target\n Ducks.list[target] = Set.new [] unless Ducks.list.key?(target)\n mods = Array(mods).each do |mod|\n duck = UniqueDuck.new Duck.new(target, mod, options)\n Ducks.list[target] << duck\n end\n [target, *mods]\n end", "code_tokens": ["def", "register", "(", "target", ",", "*", "mods", ",", "&", "block", ")", "options", "=", "mods", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "mods", ".", "pop", ":", "{", "}", "mods", "<<", "Module", ".", "new", "(", "block", ")", "if", "block", "target", "=", "DuckPuncher", ".", "lookup_constant", "target", "Ducks", ".", "list", "[", "target", "]", "=", "Set", ".", "new", "[", "]", "unless", "Ducks", ".", "list", ".", "key?", "(", "target", ")", "mods", "=", "Array", "(", "mods", ")", ".", "each", "do", "|", "mod", "|", "duck", "=", "UniqueDuck", ".", "new", "Duck", ".", "new", "(", "target", ",", "mod", ",", "options", ")", "Ducks", ".", "list", "[", "target", "]", "<<", "duck", "end", "[", "target", ",", "mods", "]", "end"], "docstring": "Register an extension with a target class\n When given a block, the block is used to create an anonymous module\n @param target [Class,Module,Object] constant or instance to extend\n @param mods [Array] modules to extend or mix into the target. The last argument can be a hash of options to customize the extension\n @option :only [Symbol, Array] list of methods to extend onto the target (the module must have these defined)\n @option :method [Symbol,String] the method used to apply the module, e.g. :extend (:include)\n @option :before [Proc] A hook that is called with the target class before #punch\n @option :after [Proc] A hook that is called with the target class after #punch", "docstring_tokens": ["Register", "an", "extension", "with", "a", "target", "class", "When", "given", "a", "block", "the", "block", "is", "used", "to", "create", "an", "anonymous", "module"], "sha": "146753a42832dbcc2b006343c8360aaa302bd1db", "url": "https://github.com/ridiculous/duck_puncher/blob/146753a42832dbcc2b006343c8360aaa302bd1db/lib/duck_puncher/registration.rb#L12-L22", "partition": "valid"} {"repo": "ridiculous/duck_puncher", "path": "lib/duck_puncher/registration.rb", "func_name": "DuckPuncher.Registration.deregister", "original_string": "def deregister(*targets)\n targets.each &Ducks.list.method(:delete)\n targets.each &decorators.method(:delete)\n end", "language": "ruby", "code": "def deregister(*targets)\n targets.each &Ducks.list.method(:delete)\n targets.each &decorators.method(:delete)\n end", "code_tokens": ["def", "deregister", "(", "*", "targets", ")", "targets", ".", "each", "Ducks", ".", "list", ".", "method", "(", ":delete", ")", "targets", ".", "each", "decorators", ".", "method", "(", ":delete", ")", "end"], "docstring": "Remove extensions for a given class or list of classes", "docstring_tokens": ["Remove", "extensions", "for", "a", "given", "class", "or", "list", "of", "classes"], "sha": "146753a42832dbcc2b006343c8360aaa302bd1db", "url": "https://github.com/ridiculous/duck_puncher/blob/146753a42832dbcc2b006343c8360aaa302bd1db/lib/duck_puncher/registration.rb#L32-L35", "partition": "valid"} {"repo": "hetznerZA/logstash_auditor", "path": "lib/logstash_auditor/auditor.rb", "func_name": "LogstashAuditor.LogstashAuditor.audit", "original_string": "def audit(audit_data)\n request = create_request(audit_data)\n http = create_http_transport\n send_request_to_server(http, request)\n end", "language": "ruby", "code": "def audit(audit_data)\n request = create_request(audit_data)\n http = create_http_transport\n send_request_to_server(http, request)\n end", "code_tokens": ["def", "audit", "(", "audit_data", ")", "request", "=", "create_request", "(", "audit_data", ")", "http", "=", "create_http_transport", "send_request_to_server", "(", "http", ",", "request", ")", "end"], "docstring": "inversion of control method required by the AuditorAPI", "docstring_tokens": ["inversion", "of", "control", "method", "required", "by", "the", "AuditorAPI"], "sha": "584899dbaa451afbd45baee842d9aca58f5c4c33", "url": "https://github.com/hetznerZA/logstash_auditor/blob/584899dbaa451afbd45baee842d9aca58f5c4c33/lib/logstash_auditor/auditor.rb#L19-L23", "partition": "valid"} {"repo": "knaveofdiamonds/sequel_migration_builder", "path": "lib/sequel/migration_builder.rb", "func_name": "Sequel.MigrationBuilder.generate_migration", "original_string": "def generate_migration(tables)\n return if tables.empty? && @db_tables.empty?\n result.clear\n\n add_line \"Sequel.migration do\"\n indent do\n generate_migration_body(tables)\n end\n add_line \"end\\n\"\n\n result.join(\"\\n\")\n end", "language": "ruby", "code": "def generate_migration(tables)\n return if tables.empty? && @db_tables.empty?\n result.clear\n\n add_line \"Sequel.migration do\"\n indent do\n generate_migration_body(tables)\n end\n add_line \"end\\n\"\n\n result.join(\"\\n\")\n end", "code_tokens": ["def", "generate_migration", "(", "tables", ")", "return", "if", "tables", ".", "empty?", "&&", "@db_tables", ".", "empty?", "result", ".", "clear", "add_line", "\"Sequel.migration do\"", "indent", "do", "generate_migration_body", "(", "tables", ")", "end", "add_line", "\"end\\n\"", "result", ".", "join", "(", "\"\\n\"", ")", "end"], "docstring": "Creates a migration builder for the given database.\n\n Generates a string of ruby code to define a sequel\n migration, based on the differences between the database schema\n of this MigrationBuilder and the tables passed.", "docstring_tokens": ["Creates", "a", "migration", "builder", "for", "the", "given", "database", "."], "sha": "8e640d1af39ccd83418ae408f62d68519363fa7b", "url": "https://github.com/knaveofdiamonds/sequel_migration_builder/blob/8e640d1af39ccd83418ae408f62d68519363fa7b/lib/sequel/migration_builder.rb#L32-L43", "partition": "valid"} {"repo": "knaveofdiamonds/sequel_migration_builder", "path": "lib/sequel/migration_builder.rb", "func_name": "Sequel.MigrationBuilder.generate_migration_body", "original_string": "def generate_migration_body(tables)\n current_tables, new_tables = table_names(tables).partition do |table_name| \n @db_table_names.include?(table_name)\n end\n\n add_line \"change do\"\n create_new_tables(new_tables, tables)\n alter_tables(current_tables, tables)\n add_line \"end\"\n end", "language": "ruby", "code": "def generate_migration_body(tables)\n current_tables, new_tables = table_names(tables).partition do |table_name| \n @db_table_names.include?(table_name)\n end\n\n add_line \"change do\"\n create_new_tables(new_tables, tables)\n alter_tables(current_tables, tables)\n add_line \"end\"\n end", "code_tokens": ["def", "generate_migration_body", "(", "tables", ")", "current_tables", ",", "new_tables", "=", "table_names", "(", "tables", ")", ".", "partition", "do", "|", "table_name", "|", "@db_table_names", ".", "include?", "(", "table_name", ")", "end", "add_line", "\"change do\"", "create_new_tables", "(", "new_tables", ",", "tables", ")", "alter_tables", "(", "current_tables", ",", "tables", ")", "add_line", "\"end\"", "end"], "docstring": "Generates the 'change' block of the migration.", "docstring_tokens": ["Generates", "the", "change", "block", "of", "the", "migration", "."], "sha": "8e640d1af39ccd83418ae408f62d68519363fa7b", "url": "https://github.com/knaveofdiamonds/sequel_migration_builder/blob/8e640d1af39ccd83418ae408f62d68519363fa7b/lib/sequel/migration_builder.rb#L47-L56", "partition": "valid"} {"repo": "knaveofdiamonds/sequel_migration_builder", "path": "lib/sequel/migration_builder.rb", "func_name": "Sequel.MigrationBuilder.create_new_tables", "original_string": "def create_new_tables(new_table_names, tables)\n each_table(new_table_names, tables) do |table_name, table, last_table|\n create_table_statement table_name, table\n add_blank_line unless last_table\n end\n end", "language": "ruby", "code": "def create_new_tables(new_table_names, tables)\n each_table(new_table_names, tables) do |table_name, table, last_table|\n create_table_statement table_name, table\n add_blank_line unless last_table\n end\n end", "code_tokens": ["def", "create_new_tables", "(", "new_table_names", ",", "tables", ")", "each_table", "(", "new_table_names", ",", "tables", ")", "do", "|", "table_name", ",", "table", ",", "last_table", "|", "create_table_statement", "table_name", ",", "table", "add_blank_line", "unless", "last_table", "end", "end"], "docstring": "Generates any create table statements for new tables.", "docstring_tokens": ["Generates", "any", "create", "table", "statements", "for", "new", "tables", "."], "sha": "8e640d1af39ccd83418ae408f62d68519363fa7b", "url": "https://github.com/knaveofdiamonds/sequel_migration_builder/blob/8e640d1af39ccd83418ae408f62d68519363fa7b/lib/sequel/migration_builder.rb#L60-L65", "partition": "valid"} {"repo": "knaveofdiamonds/sequel_migration_builder", "path": "lib/sequel/migration_builder.rb", "func_name": "Sequel.MigrationBuilder.alter_tables", "original_string": "def alter_tables(current_table_names, tables)\n each_table(current_table_names, tables) do |table_name, table, last_table|\n hsh = table.dup\n hsh[:columns] = hsh[:columns].map {|c| Schema::DbColumn.build_from_hash(c) }\n operations = Schema::AlterTableOperations.\n build(@db_tables[table_name], hsh, :immutable_columns => @immutable_columns)\n unless operations.empty?\n all_operations = if @separate_alter_table_statements\n operations.map {|o| [o] }\n else\n [operations]\n end\n\n all_operations.each_with_index do |o, i|\n alter_table_statement table_name, o\n add_blank_line unless last_table && i + 1 == all_operations.size\n end\n end\n end\n end", "language": "ruby", "code": "def alter_tables(current_table_names, tables)\n each_table(current_table_names, tables) do |table_name, table, last_table|\n hsh = table.dup\n hsh[:columns] = hsh[:columns].map {|c| Schema::DbColumn.build_from_hash(c) }\n operations = Schema::AlterTableOperations.\n build(@db_tables[table_name], hsh, :immutable_columns => @immutable_columns)\n unless operations.empty?\n all_operations = if @separate_alter_table_statements\n operations.map {|o| [o] }\n else\n [operations]\n end\n\n all_operations.each_with_index do |o, i|\n alter_table_statement table_name, o\n add_blank_line unless last_table && i + 1 == all_operations.size\n end\n end\n end\n end", "code_tokens": ["def", "alter_tables", "(", "current_table_names", ",", "tables", ")", "each_table", "(", "current_table_names", ",", "tables", ")", "do", "|", "table_name", ",", "table", ",", "last_table", "|", "hsh", "=", "table", ".", "dup", "hsh", "[", ":columns", "]", "=", "hsh", "[", ":columns", "]", ".", "map", "{", "|", "c", "|", "Schema", "::", "DbColumn", ".", "build_from_hash", "(", "c", ")", "}", "operations", "=", "Schema", "::", "AlterTableOperations", ".", "build", "(", "@db_tables", "[", "table_name", "]", ",", "hsh", ",", ":immutable_columns", "=>", "@immutable_columns", ")", "unless", "operations", ".", "empty?", "all_operations", "=", "if", "@separate_alter_table_statements", "operations", ".", "map", "{", "|", "o", "|", "[", "o", "]", "}", "else", "[", "operations", "]", "end", "all_operations", ".", "each_with_index", "do", "|", "o", ",", "i", "|", "alter_table_statement", "table_name", ",", "o", "add_blank_line", "unless", "last_table", "&&", "i", "+", "1", "==", "all_operations", ".", "size", "end", "end", "end", "end"], "docstring": "Generates any alter table statements for current tables.", "docstring_tokens": ["Generates", "any", "alter", "table", "statements", "for", "current", "tables", "."], "sha": "8e640d1af39ccd83418ae408f62d68519363fa7b", "url": "https://github.com/knaveofdiamonds/sequel_migration_builder/blob/8e640d1af39ccd83418ae408f62d68519363fa7b/lib/sequel/migration_builder.rb#L77-L96", "partition": "valid"} {"repo": "knaveofdiamonds/sequel_migration_builder", "path": "lib/sequel/migration_builder.rb", "func_name": "Sequel.MigrationBuilder.alter_table_statement", "original_string": "def alter_table_statement(table_name, operations)\n add_line \"alter_table #{table_name.inspect} do\"\n indent do\n operations.compact.each {|op| add_line op }\n end\n add_line \"end\"\n end", "language": "ruby", "code": "def alter_table_statement(table_name, operations)\n add_line \"alter_table #{table_name.inspect} do\"\n indent do\n operations.compact.each {|op| add_line op }\n end\n add_line \"end\"\n end", "code_tokens": ["def", "alter_table_statement", "(", "table_name", ",", "operations", ")", "add_line", "\"alter_table #{table_name.inspect} do\"", "indent", "do", "operations", ".", "compact", ".", "each", "{", "|", "op", "|", "add_line", "op", "}", "end", "add_line", "\"end\"", "end"], "docstring": "Generates an individual alter table statement.", "docstring_tokens": ["Generates", "an", "individual", "alter", "table", "statement", "."], "sha": "8e640d1af39ccd83418ae408f62d68519363fa7b", "url": "https://github.com/knaveofdiamonds/sequel_migration_builder/blob/8e640d1af39ccd83418ae408f62d68519363fa7b/lib/sequel/migration_builder.rb#L100-L106", "partition": "valid"} {"repo": "knaveofdiamonds/sequel_migration_builder", "path": "lib/sequel/migration_builder.rb", "func_name": "Sequel.MigrationBuilder.create_table_statement", "original_string": "def create_table_statement(table_name, table)\n normalize_primary_key(table)\n add_line \"create_table #{table_name.inspect}#{pretty_hash(table[:table_options])} do\"\n indent do\n output_columns(table[:columns], table[:primary_key])\n output_indexes(table[:indexes])\n output_primary_key(table)\n end\n add_line \"end\"\n end", "language": "ruby", "code": "def create_table_statement(table_name, table)\n normalize_primary_key(table)\n add_line \"create_table #{table_name.inspect}#{pretty_hash(table[:table_options])} do\"\n indent do\n output_columns(table[:columns], table[:primary_key])\n output_indexes(table[:indexes])\n output_primary_key(table)\n end\n add_line \"end\"\n end", "code_tokens": ["def", "create_table_statement", "(", "table_name", ",", "table", ")", "normalize_primary_key", "(", "table", ")", "add_line", "\"create_table #{table_name.inspect}#{pretty_hash(table[:table_options])} do\"", "indent", "do", "output_columns", "(", "table", "[", ":columns", "]", ",", "table", "[", ":primary_key", "]", ")", "output_indexes", "(", "table", "[", ":indexes", "]", ")", "output_primary_key", "(", "table", ")", "end", "add_line", "\"end\"", "end"], "docstring": "Generates an individual create_table statement.", "docstring_tokens": ["Generates", "an", "individual", "create_table", "statement", "."], "sha": "8e640d1af39ccd83418ae408f62d68519363fa7b", "url": "https://github.com/knaveofdiamonds/sequel_migration_builder/blob/8e640d1af39ccd83418ae408f62d68519363fa7b/lib/sequel/migration_builder.rb#L110-L119", "partition": "valid"} {"repo": "machzqcq/saucelabs", "path": "lib/saucelabs/sauce_browser_factory.rb", "func_name": "SauceLabs.SauceBrowserFactory.watir_browser", "original_string": "def watir_browser(browser,browser_options)\n target,options = browser_caps(browser,browser_options)\n create_watir_browser(target,options)\n end", "language": "ruby", "code": "def watir_browser(browser,browser_options)\n target,options = browser_caps(browser,browser_options)\n create_watir_browser(target,options)\n end", "code_tokens": ["def", "watir_browser", "(", "browser", ",", "browser_options", ")", "target", ",", "options", "=", "browser_caps", "(", "browser", ",", "browser_options", ")", "create_watir_browser", "(", "target", ",", "options", ")", "end"], "docstring": "Creates a watir browser session and returns the browser object\n\n @example\n SauceLabs.watir_browser(browser = :chrome, browser_options = {})\n @param [String] the browser string passed into the method\n @param [Hash] the optional hash to specify browser options\n @return [Object] browser session", "docstring_tokens": ["Creates", "a", "watir", "browser", "session", "and", "returns", "the", "browser", "object"], "sha": "fcdf933c83c6b8bd32773b571a1919c697d8ce53", "url": "https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/sauce_browser_factory.rb#L25-L28", "partition": "valid"} {"repo": "machzqcq/saucelabs", "path": "lib/saucelabs/sauce_browser_factory.rb", "func_name": "SauceLabs.SauceBrowserFactory.selenium_driver", "original_string": "def selenium_driver(browser,browser_options)\n target,options = browser_caps(browser,browser_options)\n create_selenium_driver(target,options)\n end", "language": "ruby", "code": "def selenium_driver(browser,browser_options)\n target,options = browser_caps(browser,browser_options)\n create_selenium_driver(target,options)\n end", "code_tokens": ["def", "selenium_driver", "(", "browser", ",", "browser_options", ")", "target", ",", "options", "=", "browser_caps", "(", "browser", ",", "browser_options", ")", "create_selenium_driver", "(", "target", ",", "options", ")", "end"], "docstring": "Creates a Selenium driver session and returns the driver object\n\n @example\n SauceLabs.selenium_driver(browser = :chrome, browser_options = {})\n @param [String] the browser string passed into the method\n @param [Hash] the optional hash to specify browser options\n @return [Object] browser session", "docstring_tokens": ["Creates", "a", "Selenium", "driver", "session", "and", "returns", "the", "driver", "object"], "sha": "fcdf933c83c6b8bd32773b571a1919c697d8ce53", "url": "https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/sauce_browser_factory.rb#L40-L43", "partition": "valid"} {"repo": "machzqcq/saucelabs", "path": "lib/saucelabs/sauce_browser_factory.rb", "func_name": "SauceLabs.SauceBrowserFactory.browser_caps", "original_string": "def browser_caps(browser,browser_options)\n target = (browser.to_sym if ENV['BROWSER'].nil? or ENV['browser'].empty?) || (ENV['BROWSER'].to_sym)\n browser,version,platform,device = extract_values_from(target)\n options = {}\n options.merge! browser_options\n caps = capabilities(browser,version,platform,device)\n options[:url] = url if url\n if options.include? :url\n browser = :remote\n options[:desired_capabilities] = caps\n end\n options[:http_client] = http_client if persistent_http or options.delete(:persistent_http)\n return browser,options\n end", "language": "ruby", "code": "def browser_caps(browser,browser_options)\n target = (browser.to_sym if ENV['BROWSER'].nil? or ENV['browser'].empty?) || (ENV['BROWSER'].to_sym)\n browser,version,platform,device = extract_values_from(target)\n options = {}\n options.merge! browser_options\n caps = capabilities(browser,version,platform,device)\n options[:url] = url if url\n if options.include? :url\n browser = :remote\n options[:desired_capabilities] = caps\n end\n options[:http_client] = http_client if persistent_http or options.delete(:persistent_http)\n return browser,options\n end", "code_tokens": ["def", "browser_caps", "(", "browser", ",", "browser_options", ")", "target", "=", "(", "browser", ".", "to_sym", "if", "ENV", "[", "'BROWSER'", "]", ".", "nil?", "or", "ENV", "[", "'browser'", "]", ".", "empty?", ")", "||", "(", "ENV", "[", "'BROWSER'", "]", ".", "to_sym", ")", "browser", ",", "version", ",", "platform", ",", "device", "=", "extract_values_from", "(", "target", ")", "options", "=", "{", "}", "options", ".", "merge!", "browser_options", "caps", "=", "capabilities", "(", "browser", ",", "version", ",", "platform", ",", "device", ")", "options", "[", ":url", "]", "=", "url", "if", "url", "if", "options", ".", "include?", ":url", "browser", "=", ":remote", "options", "[", ":desired_capabilities", "]", "=", "caps", "end", "options", "[", ":http_client", "]", "=", "http_client", "if", "persistent_http", "or", "options", ".", "delete", "(", ":persistent_http", ")", "return", "browser", ",", "options", "end"], "docstring": "Returns the target and options including the capabilities\n\n @param [String] the browser string passed into the method\n @param [Hash] the optional hash to specify browser options\n @return [Symbol,Hash] browser as symbol and options as Hash", "docstring_tokens": ["Returns", "the", "target", "and", "options", "including", "the", "capabilities"], "sha": "fcdf933c83c6b8bd32773b571a1919c697d8ce53", "url": "https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/sauce_browser_factory.rb#L81-L94", "partition": "valid"} {"repo": "machzqcq/saucelabs", "path": "lib/saucelabs/parsed_values.rb", "func_name": "SauceLabs.ParsedValues.extract_values_from", "original_string": "def extract_values_from(browser_string)\n browser = extract_browser(browser_string).to_sym\n version = extract_version(browser_string)\n platform = extract_platform(browser_string)\n device = extract_device(browser_string)\n return browser,version,platform,device\n end", "language": "ruby", "code": "def extract_values_from(browser_string)\n browser = extract_browser(browser_string).to_sym\n version = extract_version(browser_string)\n platform = extract_platform(browser_string)\n device = extract_device(browser_string)\n return browser,version,platform,device\n end", "code_tokens": ["def", "extract_values_from", "(", "browser_string", ")", "browser", "=", "extract_browser", "(", "browser_string", ")", ".", "to_sym", "version", "=", "extract_version", "(", "browser_string", ")", "platform", "=", "extract_platform", "(", "browser_string", ")", "device", "=", "extract_device", "(", "browser_string", ")", "return", "browser", ",", "version", ",", "platform", ",", "device", "end"], "docstring": "Extracts browser, version, platform, device from the browser string\n\n @example\n extract_values_from(:'safari5|linux|iphone') will extract\n browser = safari\n version=5\n platform=Linux\n device=iPhone\n\n @param [String] the browser string passed into the method\n @return [String,String,String,String] browser, version, platform and device", "docstring_tokens": ["Extracts", "browser", "version", "platform", "device", "from", "the", "browser", "string"], "sha": "fcdf933c83c6b8bd32773b571a1919c697d8ce53", "url": "https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/parsed_values.rb#L17-L23", "partition": "valid"} {"repo": "machzqcq/saucelabs", "path": "lib/saucelabs/parsed_values.rb", "func_name": "SauceLabs.ParsedValues.extract_browser", "original_string": "def extract_browser(value)\n browser = value.to_s.split(/\\d+/)[0]\n browser = browser.to_s.split('|')[0] if browser.to_s.include? '|'\n browser\n end", "language": "ruby", "code": "def extract_browser(value)\n browser = value.to_s.split(/\\d+/)[0]\n browser = browser.to_s.split('|')[0] if browser.to_s.include? '|'\n browser\n end", "code_tokens": ["def", "extract_browser", "(", "value", ")", "browser", "=", "value", ".", "to_s", ".", "split", "(", "/", "\\d", "/", ")", "[", "0", "]", "browser", "=", "browser", ".", "to_s", ".", "split", "(", "'|'", ")", "[", "0", "]", "if", "browser", ".", "to_s", ".", "include?", "'|'", "browser", "end"], "docstring": "Extracts browser from browser string\n\n @example\n extract_browser(:'safari5|linux|iphone') will extract\n browser = safari\n\n @param [String] the browser string passed into the method\n @return [String] the browser value", "docstring_tokens": ["Extracts", "browser", "from", "browser", "string"], "sha": "fcdf933c83c6b8bd32773b571a1919c697d8ce53", "url": "https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/parsed_values.rb#L37-L41", "partition": "valid"} {"repo": "machzqcq/saucelabs", "path": "lib/saucelabs/parsed_values.rb", "func_name": "SauceLabs.ParsedValues.extract_version", "original_string": "def extract_version(value)\n value = value.to_s.split('|')[0] if value.to_s.include? '|'\n regexp_to_match = /\\d{1,}/\n if (not regexp_to_match.match(value).nil?)\n version = regexp_to_match.match(value)[0]\n else\n version = ''\n end\n version\n end", "language": "ruby", "code": "def extract_version(value)\n value = value.to_s.split('|')[0] if value.to_s.include? '|'\n regexp_to_match = /\\d{1,}/\n if (not regexp_to_match.match(value).nil?)\n version = regexp_to_match.match(value)[0]\n else\n version = ''\n end\n version\n end", "code_tokens": ["def", "extract_version", "(", "value", ")", "value", "=", "value", ".", "to_s", ".", "split", "(", "'|'", ")", "[", "0", "]", "if", "value", ".", "to_s", ".", "include?", "'|'", "regexp_to_match", "=", "/", "\\d", "/", "if", "(", "not", "regexp_to_match", ".", "match", "(", "value", ")", ".", "nil?", ")", "version", "=", "regexp_to_match", ".", "match", "(", "value", ")", "[", "0", "]", "else", "version", "=", "''", "end", "version", "end"], "docstring": "Extracts version from browser string\n\n @example\n extract_version(:'safari5|linux|iphone') will extract\n browser = safari\n\n @param [String] the browser string passed into the method\n @return [String] the version value", "docstring_tokens": ["Extracts", "version", "from", "browser", "string"], "sha": "fcdf933c83c6b8bd32773b571a1919c697d8ce53", "url": "https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/parsed_values.rb#L53-L62", "partition": "valid"} {"repo": "machzqcq/saucelabs", "path": "lib/saucelabs/parsed_values.rb", "func_name": "SauceLabs.ParsedValues.extract_platform", "original_string": "def extract_platform(value)\n platform = value.to_s.split('|')[1] if value.to_s.include? '|'\n sauce_platforms\n @sauce_platforms[platform] if not platform.nil?\n end", "language": "ruby", "code": "def extract_platform(value)\n platform = value.to_s.split('|')[1] if value.to_s.include? '|'\n sauce_platforms\n @sauce_platforms[platform] if not platform.nil?\n end", "code_tokens": ["def", "extract_platform", "(", "value", ")", "platform", "=", "value", ".", "to_s", ".", "split", "(", "'|'", ")", "[", "1", "]", "if", "value", ".", "to_s", ".", "include?", "'|'", "sauce_platforms", "@sauce_platforms", "[", "platform", "]", "if", "not", "platform", ".", "nil?", "end"], "docstring": "Extracts platform from browser string\n\n @example\n extract_platform(:'safari5|linux|iphone') will extract\n browser = safari\n\n @param [String] the browser string passed into the method\n @return [String] the platform value", "docstring_tokens": ["Extracts", "platform", "from", "browser", "string"], "sha": "fcdf933c83c6b8bd32773b571a1919c697d8ce53", "url": "https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/parsed_values.rb#L74-L78", "partition": "valid"} {"repo": "machzqcq/saucelabs", "path": "lib/saucelabs/parsed_values.rb", "func_name": "SauceLabs.ParsedValues.extract_device", "original_string": "def extract_device(value)\n device = value.to_s.split('|')[2] if value.to_s.include? '|'\n sauce_devices\n @sauce_devices[device] if not device.nil?\n end", "language": "ruby", "code": "def extract_device(value)\n device = value.to_s.split('|')[2] if value.to_s.include? '|'\n sauce_devices\n @sauce_devices[device] if not device.nil?\n end", "code_tokens": ["def", "extract_device", "(", "value", ")", "device", "=", "value", ".", "to_s", ".", "split", "(", "'|'", ")", "[", "2", "]", "if", "value", ".", "to_s", ".", "include?", "'|'", "sauce_devices", "@sauce_devices", "[", "device", "]", "if", "not", "device", ".", "nil?", "end"], "docstring": "Extracts device from browser string\n\n @example\n extract_device(:'safari5|linux|iphone') will extract\n browser = safari\n\n @param [String] the browser string passed into the method\n @return [String] the device value", "docstring_tokens": ["Extracts", "device", "from", "browser", "string"], "sha": "fcdf933c83c6b8bd32773b571a1919c697d8ce53", "url": "https://github.com/machzqcq/saucelabs/blob/fcdf933c83c6b8bd32773b571a1919c697d8ce53/lib/saucelabs/parsed_values.rb#L91-L95", "partition": "valid"} {"repo": "billdueber/library_stdnums", "path": "lib/library_stdnums.rb", "func_name": "StdNum.Helpers.extractNumber", "original_string": "def extractNumber str\n match = STDNUMPAT.match str\n return nil unless match\n return (match[1].gsub(/\\-/, '')).upcase\n end", "language": "ruby", "code": "def extractNumber str\n match = STDNUMPAT.match str\n return nil unless match\n return (match[1].gsub(/\\-/, '')).upcase\n end", "code_tokens": ["def", "extractNumber", "str", "match", "=", "STDNUMPAT", ".", "match", "str", "return", "nil", "unless", "match", "return", "(", "match", "[", "1", "]", ".", "gsub", "(", "/", "\\-", "/", ",", "''", ")", ")", ".", "upcase", "end"], "docstring": "Extract the most likely looking number from the string. This will be the first\n string of digits-and-hyphens-and-maybe-a-trailing-X, with the hypens removed\n @param [String] str The string from which to extract an ISBN/ISSN\n @return [String] The extracted identifier", "docstring_tokens": ["Extract", "the", "most", "likely", "looking", "number", "from", "the", "string", ".", "This", "will", "be", "the", "first", "string", "of", "digits", "-", "and", "-", "hyphens", "-", "and", "-", "maybe", "-", "a", "-", "trailing", "-", "X", "with", "the", "hypens", "removed"], "sha": "388cca76f90c241dbcc556a4fe506ab0fc05996f", "url": "https://github.com/billdueber/library_stdnums/blob/388cca76f90c241dbcc556a4fe506ab0fc05996f/lib/library_stdnums.rb#L18-L22", "partition": "valid"} {"repo": "billdueber/library_stdnums", "path": "lib/library_stdnums.rb", "func_name": "StdNum.Helpers.extract_multiple_numbers", "original_string": "def extract_multiple_numbers(str)\n return [] if str == '' || str.nil?\n str.scan(STDNUMPAT_MULTIPLE).flatten.map{ |i| i.gsub(/\\-/, '').upcase }\n end", "language": "ruby", "code": "def extract_multiple_numbers(str)\n return [] if str == '' || str.nil?\n str.scan(STDNUMPAT_MULTIPLE).flatten.map{ |i| i.gsub(/\\-/, '').upcase }\n end", "code_tokens": ["def", "extract_multiple_numbers", "(", "str", ")", "return", "[", "]", "if", "str", "==", "''", "||", "str", ".", "nil?", "str", ".", "scan", "(", "STDNUMPAT_MULTIPLE", ")", ".", "flatten", ".", "map", "{", "|", "i", "|", "i", ".", "gsub", "(", "/", "\\-", "/", ",", "''", ")", ".", "upcase", "}", "end"], "docstring": "Extract the most likely looking numbers from the string. This will be each\n string with digits-and-hyphens-and-maybe-a-trailing-X, with the hypens removed\n @param [String] str The string from which to extract the ISBN/ISSNs\n @return [Array] An array of extracted identifiers", "docstring_tokens": ["Extract", "the", "most", "likely", "looking", "numbers", "from", "the", "string", ".", "This", "will", "be", "each", "string", "with", "digits", "-", "and", "-", "hyphens", "-", "and", "-", "maybe", "-", "a", "-", "trailing", "-", "X", "with", "the", "hypens", "removed"], "sha": "388cca76f90c241dbcc556a4fe506ab0fc05996f", "url": "https://github.com/billdueber/library_stdnums/blob/388cca76f90c241dbcc556a4fe506ab0fc05996f/lib/library_stdnums.rb#L31-L34", "partition": "valid"} {"repo": "thinkwell/mongoid_nested_set", "path": "lib/mongoid_nested_set/update.rb", "func_name": "Mongoid::Acts::NestedSet.Update.set_default_left_and_right", "original_string": "def set_default_left_and_right\n maxright = nested_set_scope.remove_order_by.max(right_field_name) || 0\n self[left_field_name] = maxright + 1\n self[right_field_name] = maxright + 2\n self[:depth] = 0\n end", "language": "ruby", "code": "def set_default_left_and_right\n maxright = nested_set_scope.remove_order_by.max(right_field_name) || 0\n self[left_field_name] = maxright + 1\n self[right_field_name] = maxright + 2\n self[:depth] = 0\n end", "code_tokens": ["def", "set_default_left_and_right", "maxright", "=", "nested_set_scope", ".", "remove_order_by", ".", "max", "(", "right_field_name", ")", "||", "0", "self", "[", "left_field_name", "]", "=", "maxright", "+", "1", "self", "[", "right_field_name", "]", "=", "maxright", "+", "2", "self", "[", ":depth", "]", "=", "0", "end"], "docstring": "on creation, set automatically lft and rgt to the end of the tree", "docstring_tokens": ["on", "creation", "set", "automatically", "lft", "and", "rgt", "to", "the", "end", "of", "the", "tree"], "sha": "d482b2642889d5853079cb13ced049513caa1af3", "url": "https://github.com/thinkwell/mongoid_nested_set/blob/d482b2642889d5853079cb13ced049513caa1af3/lib/mongoid_nested_set/update.rb#L67-L72", "partition": "valid"} {"repo": "thinkwell/mongoid_nested_set", "path": "lib/mongoid_nested_set/update.rb", "func_name": "Mongoid::Acts::NestedSet.Update.update_self_and_descendants_depth", "original_string": "def update_self_and_descendants_depth\n if depth?\n scope_class.each_with_level(self_and_descendants) do |node, level|\n node.with(:safe => true).set(:depth, level) unless node.depth == level\n end\n self.reload\n end\n self\n end", "language": "ruby", "code": "def update_self_and_descendants_depth\n if depth?\n scope_class.each_with_level(self_and_descendants) do |node, level|\n node.with(:safe => true).set(:depth, level) unless node.depth == level\n end\n self.reload\n end\n self\n end", "code_tokens": ["def", "update_self_and_descendants_depth", "if", "depth?", "scope_class", ".", "each_with_level", "(", "self_and_descendants", ")", "do", "|", "node", ",", "level", "|", "node", ".", "with", "(", ":safe", "=>", "true", ")", ".", "set", "(", ":depth", ",", "level", ")", "unless", "node", ".", "depth", "==", "level", "end", "self", ".", "reload", "end", "self", "end"], "docstring": "Update cached level attribute for self and descendants", "docstring_tokens": ["Update", "cached", "level", "attribute", "for", "self", "and", "descendants"], "sha": "d482b2642889d5853079cb13ced049513caa1af3", "url": "https://github.com/thinkwell/mongoid_nested_set/blob/d482b2642889d5853079cb13ced049513caa1af3/lib/mongoid_nested_set/update.rb#L188-L196", "partition": "valid"} {"repo": "thinkwell/mongoid_nested_set", "path": "lib/mongoid_nested_set/update.rb", "func_name": "Mongoid::Acts::NestedSet.Update.destroy_descendants", "original_string": "def destroy_descendants\n return if right.nil? || left.nil? || skip_before_destroy\n\n if acts_as_nested_set_options[:dependent] == :destroy\n descendants.each do |model|\n model.skip_before_destroy = true\n model.destroy\n end\n else\n c = nested_set_scope.where(left_field_name.to_sym.gt => left, right_field_name.to_sym.lt => right)\n scope_class.where(c.selector).delete_all\n end\n\n # update lefts and rights for remaining nodes\n diff = right - left + 1\n\n scope_class.with(:safe => true).where(\n nested_set_scope.where(left_field_name.to_sym.gt => right).selector\n ).inc(left_field_name, -diff)\n\n scope_class.with(:safe => true).where(\n nested_set_scope.where(right_field_name.to_sym.gt => right).selector\n ).inc(right_field_name, -diff)\n\n # Don't allow multiple calls to destroy to corrupt the set\n self.skip_before_destroy = true\n end", "language": "ruby", "code": "def destroy_descendants\n return if right.nil? || left.nil? || skip_before_destroy\n\n if acts_as_nested_set_options[:dependent] == :destroy\n descendants.each do |model|\n model.skip_before_destroy = true\n model.destroy\n end\n else\n c = nested_set_scope.where(left_field_name.to_sym.gt => left, right_field_name.to_sym.lt => right)\n scope_class.where(c.selector).delete_all\n end\n\n # update lefts and rights for remaining nodes\n diff = right - left + 1\n\n scope_class.with(:safe => true).where(\n nested_set_scope.where(left_field_name.to_sym.gt => right).selector\n ).inc(left_field_name, -diff)\n\n scope_class.with(:safe => true).where(\n nested_set_scope.where(right_field_name.to_sym.gt => right).selector\n ).inc(right_field_name, -diff)\n\n # Don't allow multiple calls to destroy to corrupt the set\n self.skip_before_destroy = true\n end", "code_tokens": ["def", "destroy_descendants", "return", "if", "right", ".", "nil?", "||", "left", ".", "nil?", "||", "skip_before_destroy", "if", "acts_as_nested_set_options", "[", ":dependent", "]", "==", ":destroy", "descendants", ".", "each", "do", "|", "model", "|", "model", ".", "skip_before_destroy", "=", "true", "model", ".", "destroy", "end", "else", "c", "=", "nested_set_scope", ".", "where", "(", "left_field_name", ".", "to_sym", ".", "gt", "=>", "left", ",", "right_field_name", ".", "to_sym", ".", "lt", "=>", "right", ")", "scope_class", ".", "where", "(", "c", ".", "selector", ")", ".", "delete_all", "end", "# update lefts and rights for remaining nodes", "diff", "=", "right", "-", "left", "+", "1", "scope_class", ".", "with", "(", ":safe", "=>", "true", ")", ".", "where", "(", "nested_set_scope", ".", "where", "(", "left_field_name", ".", "to_sym", ".", "gt", "=>", "right", ")", ".", "selector", ")", ".", "inc", "(", "left_field_name", ",", "-", "diff", ")", "scope_class", ".", "with", "(", ":safe", "=>", "true", ")", ".", "where", "(", "nested_set_scope", ".", "where", "(", "right_field_name", ".", "to_sym", ".", "gt", "=>", "right", ")", ".", "selector", ")", ".", "inc", "(", "right_field_name", ",", "-", "diff", ")", "# Don't allow multiple calls to destroy to corrupt the set", "self", ".", "skip_before_destroy", "=", "true", "end"], "docstring": "Prunes a branch off of the tree, shifting all of the elements on the right\n back to the left so the counts still work", "docstring_tokens": ["Prunes", "a", "branch", "off", "of", "the", "tree", "shifting", "all", "of", "the", "elements", "on", "the", "right", "back", "to", "the", "left", "so", "the", "counts", "still", "work"], "sha": "d482b2642889d5853079cb13ced049513caa1af3", "url": "https://github.com/thinkwell/mongoid_nested_set/blob/d482b2642889d5853079cb13ced049513caa1af3/lib/mongoid_nested_set/update.rb#L201-L227", "partition": "valid"} {"repo": "knife/nlp", "path": "lib/text_statistics.rb", "func_name": "NLP.TextStatistics.add", "original_string": "def add(word,categories)\n categories.each do |category|\n @cwords[category] = [] if @cwords[category].nil?\n @cwords[category].push word\n @scores[category] += 1\n end\n @words.push word\n @word_count += 1\n end", "language": "ruby", "code": "def add(word,categories)\n categories.each do |category|\n @cwords[category] = [] if @cwords[category].nil?\n @cwords[category].push word\n @scores[category] += 1\n end\n @words.push word\n @word_count += 1\n end", "code_tokens": ["def", "add", "(", "word", ",", "categories", ")", "categories", ".", "each", "do", "|", "category", "|", "@cwords", "[", "category", "]", "=", "[", "]", "if", "@cwords", "[", "category", "]", ".", "nil?", "@cwords", "[", "category", "]", ".", "push", "word", "@scores", "[", "category", "]", "+=", "1", "end", "@words", ".", "push", "word", "@word_count", "+=", "1", "end"], "docstring": "Adds word and its category to stats.", "docstring_tokens": ["Adds", "word", "and", "its", "category", "to", "stats", "."], "sha": "3729a516a177b5b92780dabe913a5e74c3364f6b", "url": "https://github.com/knife/nlp/blob/3729a516a177b5b92780dabe913a5e74c3364f6b/lib/text_statistics.rb#L17-L25", "partition": "valid"} {"repo": "ksylvest/formula", "path": "lib/formula.rb", "func_name": "Formula.FormulaFormBuilder.button", "original_string": "def button(value = nil, options = {})\n options[:button] ||= {}\n\n options[:container] ||= {}\n options[:container][:class] = arrayorize(options[:container][:class]) << ::Formula.block_class\n\n\n @template.content_tag(::Formula.block_tag, options[:container]) do\n submit value, options[:button]\n end\n end", "language": "ruby", "code": "def button(value = nil, options = {})\n options[:button] ||= {}\n\n options[:container] ||= {}\n options[:container][:class] = arrayorize(options[:container][:class]) << ::Formula.block_class\n\n\n @template.content_tag(::Formula.block_tag, options[:container]) do\n submit value, options[:button]\n end\n end", "code_tokens": ["def", "button", "(", "value", "=", "nil", ",", "options", "=", "{", "}", ")", "options", "[", ":button", "]", "||=", "{", "}", "options", "[", ":container", "]", "||=", "{", "}", "options", "[", ":container", "]", "[", ":class", "]", "=", "arrayorize", "(", "options", "[", ":container", "]", "[", ":class", "]", ")", "<<", "::", "Formula", ".", "block_class", "@template", ".", "content_tag", "(", "::", "Formula", ".", "block_tag", ",", "options", "[", ":container", "]", ")", "do", "submit", "value", ",", "options", "[", ":button", "]", "end", "end"], "docstring": "Generate a form button.\n\n Options:\n\n * :container - add custom options to the container\n * :button - add custom options to the button\n\n Usage:\n\n f.button(:name)\n\n Equivalent:\n\n
\n <%= f.submit(\"Save\")\n
", "docstring_tokens": ["Generate", "a", "form", "button", "."], "sha": "3a06528f674a5f9e19472561a61c0cc8edcb6bfd", "url": "https://github.com/ksylvest/formula/blob/3a06528f674a5f9e19472561a61c0cc8edcb6bfd/lib/formula.rb#L98-L108", "partition": "valid"} {"repo": "ksylvest/formula", "path": "lib/formula.rb", "func_name": "Formula.FormulaFormBuilder.block", "original_string": "def block(method = nil, options = {}, &block)\n options[:error] ||= error(method) if method\n\n components = \"\".html_safe\n\n if method\n components << self.label(method, options[:label]) if options[:label] or options[:label].nil? and method\n end\n\n components << @template.capture(&block)\n\n options[:container] ||= {}\n options[:container][:class] = arrayorize(options[:container][:class]) << ::Formula.block_class << method\n options[:container][:class] << ::Formula.block_error_class if ::Formula.block_error_class.present? and error?(method)\n\n components << @template.content_tag(::Formula.hint_tag , options[:hint ], :class => ::Formula.hint_class ) if options[:hint ]\n components << @template.content_tag(::Formula.error_tag, options[:error], :class => ::Formula.error_class) if options[:error]\n\n @template.content_tag(::Formula.block_tag, options[:container]) do\n components\n end\n end", "language": "ruby", "code": "def block(method = nil, options = {}, &block)\n options[:error] ||= error(method) if method\n\n components = \"\".html_safe\n\n if method\n components << self.label(method, options[:label]) if options[:label] or options[:label].nil? and method\n end\n\n components << @template.capture(&block)\n\n options[:container] ||= {}\n options[:container][:class] = arrayorize(options[:container][:class]) << ::Formula.block_class << method\n options[:container][:class] << ::Formula.block_error_class if ::Formula.block_error_class.present? and error?(method)\n\n components << @template.content_tag(::Formula.hint_tag , options[:hint ], :class => ::Formula.hint_class ) if options[:hint ]\n components << @template.content_tag(::Formula.error_tag, options[:error], :class => ::Formula.error_class) if options[:error]\n\n @template.content_tag(::Formula.block_tag, options[:container]) do\n components\n end\n end", "code_tokens": ["def", "block", "(", "method", "=", "nil", ",", "options", "=", "{", "}", ",", "&", "block", ")", "options", "[", ":error", "]", "||=", "error", "(", "method", ")", "if", "method", "components", "=", "\"\"", ".", "html_safe", "if", "method", "components", "<<", "self", ".", "label", "(", "method", ",", "options", "[", ":label", "]", ")", "if", "options", "[", ":label", "]", "or", "options", "[", ":label", "]", ".", "nil?", "and", "method", "end", "components", "<<", "@template", ".", "capture", "(", "block", ")", "options", "[", ":container", "]", "||=", "{", "}", "options", "[", ":container", "]", "[", ":class", "]", "=", "arrayorize", "(", "options", "[", ":container", "]", "[", ":class", "]", ")", "<<", "::", "Formula", ".", "block_class", "<<", "method", "options", "[", ":container", "]", "[", ":class", "]", "<<", "::", "Formula", ".", "block_error_class", "if", "::", "Formula", ".", "block_error_class", ".", "present?", "and", "error?", "(", "method", ")", "components", "<<", "@template", ".", "content_tag", "(", "::", "Formula", ".", "hint_tag", ",", "options", "[", ":hint", "]", ",", ":class", "=>", "::", "Formula", ".", "hint_class", ")", "if", "options", "[", ":hint", "]", "components", "<<", "@template", ".", "content_tag", "(", "::", "Formula", ".", "error_tag", ",", "options", "[", ":error", "]", ",", ":class", "=>", "::", "Formula", ".", "error_class", ")", "if", "options", "[", ":error", "]", "@template", ".", "content_tag", "(", "::", "Formula", ".", "block_tag", ",", "options", "[", ":container", "]", ")", "do", "components", "end", "end"], "docstring": "Basic container generator for use with blocks.\n\n Options:\n\n * :hint - specify a hint to be displayed ('We promise not to spam you.', etc.)\n * :label - override the default label used ('Name:', 'URL:', etc.)\n * :error - override the default error used ('invalid', 'incorrect', etc.)\n\n Usage:\n\n f.block(:name, :label => \"Name:\", :hint => \"Please use your full name.\", :container => { :class => 'fill' }) do\n ...\n end\n\n Equivalent:\n\n
\n <%= f.label(:name, \"Name:\") %>\n ...\n
Please use your full name.
\n
...
\n
", "docstring_tokens": ["Basic", "container", "generator", "for", "use", "with", "blocks", "."], "sha": "3a06528f674a5f9e19472561a61c0cc8edcb6bfd", "url": "https://github.com/ksylvest/formula/blob/3a06528f674a5f9e19472561a61c0cc8edcb6bfd/lib/formula.rb#L134-L155", "partition": "valid"} {"repo": "ksylvest/formula", "path": "lib/formula.rb", "func_name": "Formula.FormulaFormBuilder.input", "original_string": "def input(method, options = {})\n options[:as] ||= as(method)\n options[:input] ||= {}\n\n return hidden_field method, options[:input] if options[:as] == :hidden\n\n klass = [::Formula.input_class, options[:as]]\n klass << ::Formula.input_error_class if ::Formula.input_error_class.present? and error?(method)\n\n self.block(method, options) do\n @template.content_tag(::Formula.input_tag, :class => klass) do\n case options[:as]\n when :text then text_area method, ::Formula.area_options.merge(options[:input] || {})\n when :file then file_field method, ::Formula.file_options.merge(options[:input] || {})\n when :string then text_field method, ::Formula.field_options.merge(options[:input] || {})\n when :password then password_field method, ::Formula.field_options.merge(options[:input] || {})\n when :url then url_field method, ::Formula.field_options.merge(options[:input] || {})\n when :email then email_field method, ::Formula.field_options.merge(options[:input] || {})\n when :phone then phone_field method, ::Formula.field_options.merge(options[:input] || {})\n when :number then number_field method, ::Formula.field_options.merge(options[:input] || {})\n when :boolean then check_box method, ::Formula.box_options.merge(options[:input] || {})\n when :country then country_select method, ::Formula.select_options.merge(options[:input] || {})\n when :date then date_select method, ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}\n when :time then time_select method, ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}\n when :datetime then datetime_select method, ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}\n when :select then select method, options[:choices], ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}\n end\n end\n end\n end", "language": "ruby", "code": "def input(method, options = {})\n options[:as] ||= as(method)\n options[:input] ||= {}\n\n return hidden_field method, options[:input] if options[:as] == :hidden\n\n klass = [::Formula.input_class, options[:as]]\n klass << ::Formula.input_error_class if ::Formula.input_error_class.present? and error?(method)\n\n self.block(method, options) do\n @template.content_tag(::Formula.input_tag, :class => klass) do\n case options[:as]\n when :text then text_area method, ::Formula.area_options.merge(options[:input] || {})\n when :file then file_field method, ::Formula.file_options.merge(options[:input] || {})\n when :string then text_field method, ::Formula.field_options.merge(options[:input] || {})\n when :password then password_field method, ::Formula.field_options.merge(options[:input] || {})\n when :url then url_field method, ::Formula.field_options.merge(options[:input] || {})\n when :email then email_field method, ::Formula.field_options.merge(options[:input] || {})\n when :phone then phone_field method, ::Formula.field_options.merge(options[:input] || {})\n when :number then number_field method, ::Formula.field_options.merge(options[:input] || {})\n when :boolean then check_box method, ::Formula.box_options.merge(options[:input] || {})\n when :country then country_select method, ::Formula.select_options.merge(options[:input] || {})\n when :date then date_select method, ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}\n when :time then time_select method, ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}\n when :datetime then datetime_select method, ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}\n when :select then select method, options[:choices], ::Formula.select_options.merge(options[:input] || {}), options[:input].delete(:html) || {}\n end\n end\n end\n end", "code_tokens": ["def", "input", "(", "method", ",", "options", "=", "{", "}", ")", "options", "[", ":as", "]", "||=", "as", "(", "method", ")", "options", "[", ":input", "]", "||=", "{", "}", "return", "hidden_field", "method", ",", "options", "[", ":input", "]", "if", "options", "[", ":as", "]", "==", ":hidden", "klass", "=", "[", "::", "Formula", ".", "input_class", ",", "options", "[", ":as", "]", "]", "klass", "<<", "::", "Formula", ".", "input_error_class", "if", "::", "Formula", ".", "input_error_class", ".", "present?", "and", "error?", "(", "method", ")", "self", ".", "block", "(", "method", ",", "options", ")", "do", "@template", ".", "content_tag", "(", "::", "Formula", ".", "input_tag", ",", ":class", "=>", "klass", ")", "do", "case", "options", "[", ":as", "]", "when", ":text", "then", "text_area", "method", ",", "::", "Formula", ".", "area_options", ".", "merge", "(", "options", "[", ":input", "]", "||", "{", "}", ")", "when", ":file", "then", "file_field", "method", ",", "::", "Formula", ".", "file_options", ".", "merge", "(", "options", "[", ":input", "]", "||", "{", "}", ")", "when", ":string", "then", "text_field", "method", ",", "::", "Formula", ".", "field_options", ".", "merge", "(", "options", "[", ":input", "]", "||", "{", "}", ")", "when", ":password", "then", "password_field", "method", ",", "::", "Formula", ".", "field_options", ".", "merge", "(", "options", "[", ":input", "]", "||", "{", "}", ")", "when", ":url", "then", "url_field", "method", ",", "::", "Formula", ".", "field_options", ".", "merge", "(", "options", "[", ":input", "]", "||", "{", "}", ")", "when", ":email", "then", "email_field", "method", ",", "::", "Formula", ".", "field_options", ".", "merge", "(", "options", "[", ":input", "]", "||", "{", "}", ")", "when", ":phone", "then", "phone_field", "method", ",", "::", "Formula", ".", "field_options", ".", "merge", "(", "options", "[", ":input", "]", "||", "{", "}", ")", "when", ":number", "then", "number_field", "method", ",", "::", "Formula", ".", "field_options", ".", "merge", "(", "options", "[", ":input", "]", "||", "{", "}", ")", "when", ":boolean", "then", "check_box", "method", ",", "::", "Formula", ".", "box_options", ".", "merge", "(", "options", "[", ":input", "]", "||", "{", "}", ")", "when", ":country", "then", "country_select", "method", ",", "::", "Formula", ".", "select_options", ".", "merge", "(", "options", "[", ":input", "]", "||", "{", "}", ")", "when", ":date", "then", "date_select", "method", ",", "::", "Formula", ".", "select_options", ".", "merge", "(", "options", "[", ":input", "]", "||", "{", "}", ")", ",", "options", "[", ":input", "]", ".", "delete", "(", ":html", ")", "||", "{", "}", "when", ":time", "then", "time_select", "method", ",", "::", "Formula", ".", "select_options", ".", "merge", "(", "options", "[", ":input", "]", "||", "{", "}", ")", ",", "options", "[", ":input", "]", ".", "delete", "(", ":html", ")", "||", "{", "}", "when", ":datetime", "then", "datetime_select", "method", ",", "::", "Formula", ".", "select_options", ".", "merge", "(", "options", "[", ":input", "]", "||", "{", "}", ")", ",", "options", "[", ":input", "]", ".", "delete", "(", ":html", ")", "||", "{", "}", "when", ":select", "then", "select", "method", ",", "options", "[", ":choices", "]", ",", "::", "Formula", ".", "select_options", ".", "merge", "(", "options", "[", ":input", "]", "||", "{", "}", ")", ",", "options", "[", ":input", "]", ".", "delete", "(", ":html", ")", "||", "{", "}", "end", "end", "end", "end"], "docstring": "Generate a suitable form input for a given method by performing introspection on the type.\n\n Options:\n\n * :as - override the default type used (:url, :email, :phone, :password, :number, :text)\n * :label - override the default label used ('Name:', 'URL:', etc.)\n * :error - override the default error used ('invalid', 'incorrect', etc.)\n * :input - add custom options to the input ({ :class => 'goregous' }, etc.)\n * :container - add custom options to the container ({ :class => 'gorgeous' }, etc.)\n\n Usage:\n\n f.input(:name)\n f.input(:email)\n f.input(:password_a, :label => \"Password\", :hint => \"It's a secret!\", :container => { :class => \"half\" })\n f.input(:password_b, :label => \"Password\", :hint => \"It's a secret!\", :container => { :class => \"half\" })\n\n Equivalent:\n\n
\n <%= f.label(:name)\n
<%= f.text_field(:name)
\n
...
\n
\n
\n <%= f.label(:email)\n
<%= f.email_field(:email)
\n
...
\n
\n
\n
\n <%= f.label(:password_a, \"Password\")\n <%= f.password_field(:password_a)\n
It's a secret!
\n
...
\n
\n
\n
\n
\n <%= f.label(:password_b, \"Password\")\n <%= f.password_field(:password_b)\n
It's a secret!
\n
...
\n
\n
", "docstring_tokens": ["Generate", "a", "suitable", "form", "input", "for", "a", "given", "method", "by", "performing", "introspection", "on", "the", "type", "."], "sha": "3a06528f674a5f9e19472561a61c0cc8edcb6bfd", "url": "https://github.com/ksylvest/formula/blob/3a06528f674a5f9e19472561a61c0cc8edcb6bfd/lib/formula.rb#L204-L233", "partition": "valid"} {"repo": "ksylvest/formula", "path": "lib/formula.rb", "func_name": "Formula.FormulaFormBuilder.file?", "original_string": "def file?(method)\n @files ||= {}\n @files[method] ||= begin\n file = @object.send(method) if @object && @object.respond_to?(method)\n file && ::Formula.file.any? { |method| file.respond_to?(method) }\n end\n end", "language": "ruby", "code": "def file?(method)\n @files ||= {}\n @files[method] ||= begin\n file = @object.send(method) if @object && @object.respond_to?(method)\n file && ::Formula.file.any? { |method| file.respond_to?(method) }\n end\n end", "code_tokens": ["def", "file?", "(", "method", ")", "@files", "||=", "{", "}", "@files", "[", "method", "]", "||=", "begin", "file", "=", "@object", ".", "send", "(", "method", ")", "if", "@object", "&&", "@object", ".", "respond_to?", "(", "method", ")", "file", "&&", "::", "Formula", ".", "file", ".", "any?", "{", "|", "method", "|", "file", ".", "respond_to?", "(", "method", ")", "}", "end", "end"], "docstring": "Introspection on an association to determine if a method is a file. This\n is determined by the methods ability to respond to file methods.", "docstring_tokens": ["Introspection", "on", "an", "association", "to", "determine", "if", "a", "method", "is", "a", "file", ".", "This", "is", "determined", "by", "the", "methods", "ability", "to", "respond", "to", "file", "methods", "."], "sha": "3a06528f674a5f9e19472561a61c0cc8edcb6bfd", "url": "https://github.com/ksylvest/formula/blob/3a06528f674a5f9e19472561a61c0cc8edcb6bfd/lib/formula.rb#L330-L336", "partition": "valid"} {"repo": "ksylvest/formula", "path": "lib/formula.rb", "func_name": "Formula.FormulaFormBuilder.arrayorize", "original_string": "def arrayorize(value)\n case value\n when nil then return []\n when String then value.to_s.split\n when Symbol then value.to_s.split\n else value\n end\n end", "language": "ruby", "code": "def arrayorize(value)\n case value\n when nil then return []\n when String then value.to_s.split\n when Symbol then value.to_s.split\n else value\n end\n end", "code_tokens": ["def", "arrayorize", "(", "value", ")", "case", "value", "when", "nil", "then", "return", "[", "]", "when", "String", "then", "value", ".", "to_s", ".", "split", "when", "Symbol", "then", "value", ".", "to_s", ".", "split", "else", "value", "end", "end"], "docstring": "Create an array from a string, a symbol, or an undefined value. The default is to return\n the value and assume it has already is valid.", "docstring_tokens": ["Create", "an", "array", "from", "a", "string", "a", "symbol", "or", "an", "undefined", "value", ".", "The", "default", "is", "to", "return", "the", "value", "and", "assume", "it", "has", "already", "is", "valid", "."], "sha": "3a06528f674a5f9e19472561a61c0cc8edcb6bfd", "url": "https://github.com/ksylvest/formula/blob/3a06528f674a5f9e19472561a61c0cc8edcb6bfd/lib/formula.rb#L403-L410", "partition": "valid"} {"repo": "pd/yard_types", "path": "lib/yard_types/types.rb", "func_name": "YardTypes.KindType.check", "original_string": "def check(obj)\n if name == 'Boolean'\n obj == true || obj == false\n else\n obj.kind_of? constant\n end\n end", "language": "ruby", "code": "def check(obj)\n if name == 'Boolean'\n obj == true || obj == false\n else\n obj.kind_of? constant\n end\n end", "code_tokens": ["def", "check", "(", "obj", ")", "if", "name", "==", "'Boolean'", "obj", "==", "true", "||", "obj", "==", "false", "else", "obj", ".", "kind_of?", "constant", "end", "end"], "docstring": "Type checks a given object. Special consideration is given to\n the pseudo-class `Boolean`, which does not actually exist in Ruby,\n but is commonly used to mean `TrueClass, FalseClass`.\n\n @param (see Type#check)\n @return [Boolean] `true` if `obj.kind_of?(constant)`.", "docstring_tokens": ["Type", "checks", "a", "given", "object", ".", "Special", "consideration", "is", "given", "to", "the", "pseudo", "-", "class", "Boolean", "which", "does", "not", "actually", "exist", "in", "Ruby", "but", "is", "commonly", "used", "to", "mean", "TrueClass", "FalseClass", "."], "sha": "a909254cff3b7e63d483e17169519ee11b7ab15d", "url": "https://github.com/pd/yard_types/blob/a909254cff3b7e63d483e17169519ee11b7ab15d/lib/yard_types/types.rb#L135-L141", "partition": "valid"} {"repo": "tablexi/synaccess", "path": "lib/synaccess_connect/net_booter/http/http_connection.rb", "func_name": "NetBooter.HttpConnection.toggle", "original_string": "def toggle(outlet, status)\n current_status = status(outlet)\n toggle_relay(outlet) if current_status != status\n status\n end", "language": "ruby", "code": "def toggle(outlet, status)\n current_status = status(outlet)\n toggle_relay(outlet) if current_status != status\n status\n end", "code_tokens": ["def", "toggle", "(", "outlet", ",", "status", ")", "current_status", "=", "status", "(", "outlet", ")", "toggle_relay", "(", "outlet", ")", "if", "current_status", "!=", "status", "status", "end"], "docstring": "Toggle the status of an outlet\n\n Example:\n >> netbooter.toggle(1, false)\n => false\n\n Arguments:\n +outlet+ The outlet you want to toggle\n +status+ Boolean. true to turn on, false to turn off\n\n Returns:\n boolean - The new status of the outlet", "docstring_tokens": ["Toggle", "the", "status", "of", "an", "outlet"], "sha": "68df823b226975d22e3b1ce00daf36b31639003b", "url": "https://github.com/tablexi/synaccess/blob/68df823b226975d22e3b1ce00daf36b31639003b/lib/synaccess_connect/net_booter/http/http_connection.rb#L72-L76", "partition": "valid"} {"repo": "tablexi/synaccess", "path": "lib/synaccess_connect/net_booter/http/http_connection.rb", "func_name": "NetBooter.HttpConnection.get_request", "original_string": "def get_request(path)\n resp = nil\n begin\n Timeout::timeout(5) do\n resp = do_http_request(path)\n end\n rescue => e\n raise NetBooter::Error.new(\"Error connecting to relay: #{e.message}\")\n end\n resp\n end", "language": "ruby", "code": "def get_request(path)\n resp = nil\n begin\n Timeout::timeout(5) do\n resp = do_http_request(path)\n end\n rescue => e\n raise NetBooter::Error.new(\"Error connecting to relay: #{e.message}\")\n end\n resp\n end", "code_tokens": ["def", "get_request", "(", "path", ")", "resp", "=", "nil", "begin", "Timeout", "::", "timeout", "(", "5", ")", "do", "resp", "=", "do_http_request", "(", "path", ")", "end", "rescue", "=>", "e", "raise", "NetBooter", "::", "Error", ".", "new", "(", "\"Error connecting to relay: #{e.message}\"", ")", "end", "resp", "end"], "docstring": "Make an http request and return the result.", "docstring_tokens": ["Make", "an", "http", "request", "and", "return", "the", "result", "."], "sha": "68df823b226975d22e3b1ce00daf36b31639003b", "url": "https://github.com/tablexi/synaccess/blob/68df823b226975d22e3b1ce00daf36b31639003b/lib/synaccess_connect/net_booter/http/http_connection.rb#L102-L112", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/adapters/array_model_persistence.rb", "func_name": "MotionModel.ArrayModelAdapter.encodeWithCoder", "original_string": "def encodeWithCoder(coder)\n columns.each do |attr|\n # Serialize attributes except the proxy has_many and belongs_to ones.\n unless [:belongs_to, :has_many, :has_one].include? column(attr).type\n value = self.send(attr)\n unless value.nil?\n coder.encodeObject(value, forKey: attr.to_s)\n end\n end\n end\n end", "language": "ruby", "code": "def encodeWithCoder(coder)\n columns.each do |attr|\n # Serialize attributes except the proxy has_many and belongs_to ones.\n unless [:belongs_to, :has_many, :has_one].include? column(attr).type\n value = self.send(attr)\n unless value.nil?\n coder.encodeObject(value, forKey: attr.to_s)\n end\n end\n end\n end", "code_tokens": ["def", "encodeWithCoder", "(", "coder", ")", "columns", ".", "each", "do", "|", "attr", "|", "# Serialize attributes except the proxy has_many and belongs_to ones.", "unless", "[", ":belongs_to", ",", ":has_many", ",", ":has_one", "]", ".", "include?", "column", "(", "attr", ")", ".", "type", "value", "=", "self", ".", "send", "(", "attr", ")", "unless", "value", ".", "nil?", "coder", ".", "encodeObject", "(", "value", ",", "forKey", ":", "attr", ".", "to_s", ")", "end", "end", "end", "end"], "docstring": "Follow Apple's recommendation not to encode missing\n values.", "docstring_tokens": ["Follow", "Apple", "s", "recommendation", "not", "to", "encode", "missing", "values", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_model_persistence.rb#L146-L156", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/adapters/array_finder_query.rb", "func_name": "MotionModel.ArrayFinderQuery.order", "original_string": "def order(field = nil, &block)\n if block_given?\n @collection = @collection.sort{|o1, o2| yield(o1, o2)}\n else\n raise ArgumentError.new('you must supply a field name to sort unless you supply a block.') if field.nil?\n @collection = @collection.sort{|o1, o2| o1.send(field) <=> o2.send(field)}\n end\n self\n end", "language": "ruby", "code": "def order(field = nil, &block)\n if block_given?\n @collection = @collection.sort{|o1, o2| yield(o1, o2)}\n else\n raise ArgumentError.new('you must supply a field name to sort unless you supply a block.') if field.nil?\n @collection = @collection.sort{|o1, o2| o1.send(field) <=> o2.send(field)}\n end\n self\n end", "code_tokens": ["def", "order", "(", "field", "=", "nil", ",", "&", "block", ")", "if", "block_given?", "@collection", "=", "@collection", ".", "sort", "{", "|", "o1", ",", "o2", "|", "yield", "(", "o1", ",", "o2", ")", "}", "else", "raise", "ArgumentError", ".", "new", "(", "'you must supply a field name to sort unless you supply a block.'", ")", "if", "field", ".", "nil?", "@collection", "=", "@collection", ".", "sort", "{", "|", "o1", ",", "o2", "|", "o1", ".", "send", "(", "field", ")", "<=>", "o2", ".", "send", "(", "field", ")", "}", "end", "self", "end"], "docstring": "Specifies how to sort. only ascending sort is supported in the short\n form. For descending, implement the block form.\n\n Task.where(:name).eq('bob').order(:pay_grade).all => array of bobs ascending by pay grade\n Task.where(:name).eq('bob').order(:pay_grade){|o1, o2| o2 <=> o1} => array of bobs descending by pay grade", "docstring_tokens": ["Specifies", "how", "to", "sort", ".", "only", "ascending", "sort", "is", "supported", "in", "the", "short", "form", ".", "For", "descending", "implement", "the", "block", "form", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L31-L39", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/adapters/array_finder_query.rb", "func_name": "MotionModel.ArrayFinderQuery.contain", "original_string": "def contain(query_string, options = {:case_sensitive => false})\n do_comparison(query_string) do |comparator, item|\n if options[:case_sensitive]\n item =~ Regexp.new(comparator, Regexp::MULTILINE)\n else\n item =~ Regexp.new(comparator, Regexp::IGNORECASE | Regexp::MULTILINE)\n end\n end\n end", "language": "ruby", "code": "def contain(query_string, options = {:case_sensitive => false})\n do_comparison(query_string) do |comparator, item|\n if options[:case_sensitive]\n item =~ Regexp.new(comparator, Regexp::MULTILINE)\n else\n item =~ Regexp.new(comparator, Regexp::IGNORECASE | Regexp::MULTILINE)\n end\n end\n end", "code_tokens": ["def", "contain", "(", "query_string", ",", "options", "=", "{", ":case_sensitive", "=>", "false", "}", ")", "do_comparison", "(", "query_string", ")", "do", "|", "comparator", ",", "item", "|", "if", "options", "[", ":case_sensitive", "]", "item", "=~", "Regexp", ".", "new", "(", "comparator", ",", "Regexp", "::", "MULTILINE", ")", "else", "item", "=~", "Regexp", ".", "new", "(", "comparator", ",", "Regexp", "::", "IGNORECASE", "|", "Regexp", "::", "MULTILINE", ")", "end", "end", "end"], "docstring": "performs a \"like\" query.\n\n Task.find(:work_group).contain('dev') => ['UI dev', 'Core dev', ...]", "docstring_tokens": ["performs", "a", "like", "query", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L59-L67", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/adapters/array_finder_query.rb", "func_name": "MotionModel.ArrayFinderQuery.in", "original_string": "def in(set)\n @collection = @collection.collect do |item|\n item if set.include?(item.send(@field_name.to_sym))\n end.compact\n end", "language": "ruby", "code": "def in(set)\n @collection = @collection.collect do |item|\n item if set.include?(item.send(@field_name.to_sym))\n end.compact\n end", "code_tokens": ["def", "in", "(", "set", ")", "@collection", "=", "@collection", ".", "collect", "do", "|", "item", "|", "item", "if", "set", ".", "include?", "(", "item", ".", "send", "(", "@field_name", ".", "to_sym", ")", ")", "end", ".", "compact", "end"], "docstring": "performs a set-inclusion test.\n\n Task.find(:id).in([3, 5, 9])", "docstring_tokens": ["performs", "a", "set", "-", "inclusion", "test", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L74-L78", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/adapters/array_finder_query.rb", "func_name": "MotionModel.ArrayFinderQuery.eq", "original_string": "def eq(query_string, options = {:case_sensitive => false})\n do_comparison(query_string, options) do |comparator, item|\n comparator == item\n end\n end", "language": "ruby", "code": "def eq(query_string, options = {:case_sensitive => false})\n do_comparison(query_string, options) do |comparator, item|\n comparator == item\n end\n end", "code_tokens": ["def", "eq", "(", "query_string", ",", "options", "=", "{", ":case_sensitive", "=>", "false", "}", ")", "do_comparison", "(", "query_string", ",", "options", ")", "do", "|", "comparator", ",", "item", "|", "comparator", "==", "item", "end", "end"], "docstring": "performs strict equality comparison.\n\n If arguments are strings, they are, by default,\n compared case-insensitive, if case-sensitivity\n is required, use:\n\n eq('something', :case_sensitive => true)", "docstring_tokens": ["performs", "strict", "equality", "comparison", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L87-L91", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/adapters/array_finder_query.rb", "func_name": "MotionModel.ArrayFinderQuery.gt", "original_string": "def gt(query_string, options = {:case_sensitive => false})\n do_comparison(query_string, options) do |comparator, item|\n comparator < item\n end\n end", "language": "ruby", "code": "def gt(query_string, options = {:case_sensitive => false})\n do_comparison(query_string, options) do |comparator, item|\n comparator < item\n end\n end", "code_tokens": ["def", "gt", "(", "query_string", ",", "options", "=", "{", ":case_sensitive", "=>", "false", "}", ")", "do_comparison", "(", "query_string", ",", "options", ")", "do", "|", "comparator", ",", "item", "|", "comparator", "<", "item", "end", "end"], "docstring": "performs greater-than comparison.\n\n see `eq` for notes on case sensitivity.", "docstring_tokens": ["performs", "greater", "-", "than", "comparison", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L98-L102", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/adapters/array_finder_query.rb", "func_name": "MotionModel.ArrayFinderQuery.lt", "original_string": "def lt(query_string, options = {:case_sensitive => false})\n do_comparison(query_string, options) do |comparator, item|\n comparator > item\n end\n end", "language": "ruby", "code": "def lt(query_string, options = {:case_sensitive => false})\n do_comparison(query_string, options) do |comparator, item|\n comparator > item\n end\n end", "code_tokens": ["def", "lt", "(", "query_string", ",", "options", "=", "{", ":case_sensitive", "=>", "false", "}", ")", "do_comparison", "(", "query_string", ",", "options", ")", "do", "|", "comparator", ",", "item", "|", "comparator", ">", "item", "end", "end"], "docstring": "performs less-than comparison.\n\n see `eq` for notes on case sensitivity.", "docstring_tokens": ["performs", "less", "-", "than", "comparison", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L109-L113", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/adapters/array_finder_query.rb", "func_name": "MotionModel.ArrayFinderQuery.gte", "original_string": "def gte(query_string, options = {:case_sensitive => false})\n do_comparison(query_string, options) do |comparator, item|\n comparator <= item\n end\n end", "language": "ruby", "code": "def gte(query_string, options = {:case_sensitive => false})\n do_comparison(query_string, options) do |comparator, item|\n comparator <= item\n end\n end", "code_tokens": ["def", "gte", "(", "query_string", ",", "options", "=", "{", ":case_sensitive", "=>", "false", "}", ")", "do_comparison", "(", "query_string", ",", "options", ")", "do", "|", "comparator", ",", "item", "|", "comparator", "<=", "item", "end", "end"], "docstring": "performs greater-than-or-equal comparison.\n\n see `eq` for notes on case sensitivity.", "docstring_tokens": ["performs", "greater", "-", "than", "-", "or", "-", "equal", "comparison", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L120-L124", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/adapters/array_finder_query.rb", "func_name": "MotionModel.ArrayFinderQuery.lte", "original_string": "def lte(query_string, options = {:case_sensitive => false})\n do_comparison(query_string, options) do |comparator, item|\n comparator >= item\n end\n end", "language": "ruby", "code": "def lte(query_string, options = {:case_sensitive => false})\n do_comparison(query_string, options) do |comparator, item|\n comparator >= item\n end\n end", "code_tokens": ["def", "lte", "(", "query_string", ",", "options", "=", "{", ":case_sensitive", "=>", "false", "}", ")", "do_comparison", "(", "query_string", ",", "options", ")", "do", "|", "comparator", ",", "item", "|", "comparator", ">=", "item", "end", "end"], "docstring": "performs less-than-or-equal comparison.\n\n see `eq` for notes on case sensitivity.", "docstring_tokens": ["performs", "less", "-", "than", "-", "or", "-", "equal", "comparison", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L131-L135", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/adapters/array_finder_query.rb", "func_name": "MotionModel.ArrayFinderQuery.ne", "original_string": "def ne(query_string, options = {:case_sensitive => false})\n do_comparison(query_string, options) do |comparator, item|\n comparator != item\n end\n end", "language": "ruby", "code": "def ne(query_string, options = {:case_sensitive => false})\n do_comparison(query_string, options) do |comparator, item|\n comparator != item\n end\n end", "code_tokens": ["def", "ne", "(", "query_string", ",", "options", "=", "{", ":case_sensitive", "=>", "false", "}", ")", "do_comparison", "(", "query_string", ",", "options", ")", "do", "|", "comparator", ",", "item", "|", "comparator", "!=", "item", "end", "end"], "docstring": "performs inequality comparison.\n\n see `eq` for notes on case sensitivity.", "docstring_tokens": ["performs", "inequality", "comparison", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/adapters/array_finder_query.rb#L142-L146", "partition": "valid"} {"repo": "cheerfulstoic/music", "path": "lib/music/chord.rb", "func_name": "Music.Chord.inversion", "original_string": "def inversion(amount)\n fail ArgumentError, 'Inversion amount must be greater than or equal to 1' if amount < 1\n fail ArgumentError, 'Not enough notes in chord for inversion' if amount >= @notes.size\n\n note_array = @notes.to_a.sort\n notes = (0...amount).collect { note_array.shift.adjust_by_semitones(12) }\n Chord.new(notes + note_array)\n end", "language": "ruby", "code": "def inversion(amount)\n fail ArgumentError, 'Inversion amount must be greater than or equal to 1' if amount < 1\n fail ArgumentError, 'Not enough notes in chord for inversion' if amount >= @notes.size\n\n note_array = @notes.to_a.sort\n notes = (0...amount).collect { note_array.shift.adjust_by_semitones(12) }\n Chord.new(notes + note_array)\n end", "code_tokens": ["def", "inversion", "(", "amount", ")", "fail", "ArgumentError", ",", "'Inversion amount must be greater than or equal to 1'", "if", "amount", "<", "1", "fail", "ArgumentError", ",", "'Not enough notes in chord for inversion'", "if", "amount", ">=", "@notes", ".", "size", "note_array", "=", "@notes", ".", "to_a", ".", "sort", "notes", "=", "(", "0", "...", "amount", ")", ".", "collect", "{", "note_array", ".", "shift", ".", "adjust_by_semitones", "(", "12", ")", "}", "Chord", ".", "new", "(", "notes", "+", "note_array", ")", "end"], "docstring": "Give the Nth inversion of the chord which simply adjusts the lowest N notes up by one octive\n\n @returns [Chord] The specified inversion of chord", "docstring_tokens": ["Give", "the", "Nth", "inversion", "of", "the", "chord", "which", "simply", "adjusts", "the", "lowest", "N", "notes", "up", "by", "one", "octive"], "sha": "fef5354e5d965dad54c92eac851bff9192aa183b", "url": "https://github.com/cheerfulstoic/music/blob/fef5354e5d965dad54c92eac851bff9192aa183b/lib/music/chord.rb#L74-L81", "partition": "valid"} {"repo": "pwnall/stellar", "path": "lib/stellar/courses.rb", "func_name": "Stellar.Courses.mine", "original_string": "def mine\n page = @client.get_nokogiri '/atstellar'\n class_links = page.css('a[href*=\"/S/course/\"]').\n map { |link| Stellar::Course.from_link link, @client }.reject(&:nil?)\n end", "language": "ruby", "code": "def mine\n page = @client.get_nokogiri '/atstellar'\n class_links = page.css('a[href*=\"/S/course/\"]').\n map { |link| Stellar::Course.from_link link, @client }.reject(&:nil?)\n end", "code_tokens": ["def", "mine", "page", "=", "@client", ".", "get_nokogiri", "'/atstellar'", "class_links", "=", "page", ".", "css", "(", "'a[href*=\"/S/course/\"]'", ")", ".", "map", "{", "|", "link", "|", "Stellar", "::", "Course", ".", "from_link", "link", ",", "@client", "}", ".", "reject", "(", ":nil?", ")", "end"], "docstring": "My classes.\n @return [Array] array with one Hash per class; Hashes have :number and\n :url keys", "docstring_tokens": ["My", "classes", "."], "sha": "cd2bfd55a6afe9118a06c0d45d6a168e520ec19f", "url": "https://github.com/pwnall/stellar/blob/cd2bfd55a6afe9118a06c0d45d6a168e520ec19f/lib/stellar/courses.rb#L13-L17", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/validatable.rb", "func_name": "MotionModel.Validatable.error_messages_for", "original_string": "def error_messages_for(field)\n key = field.to_sym\n error_messages.select{|message| message.has_key?(key)}.map{|message| message[key]}\n end", "language": "ruby", "code": "def error_messages_for(field)\n key = field.to_sym\n error_messages.select{|message| message.has_key?(key)}.map{|message| message[key]}\n end", "code_tokens": ["def", "error_messages_for", "(", "field", ")", "key", "=", "field", ".", "to_sym", "error_messages", ".", "select", "{", "|", "message", "|", "message", ".", "has_key?", "(", "key", ")", "}", ".", "map", "{", "|", "message", "|", "message", "[", "key", "]", "}", "end"], "docstring": "Array of messages for a given field. Results are always an array\n because a field can fail multiple validations.", "docstring_tokens": ["Array", "of", "messages", "for", "a", "given", "field", ".", "Results", "are", "always", "an", "array", "because", "a", "field", "can", "fail", "multiple", "validations", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/validatable.rb#L89-L92", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/validatable.rb", "func_name": "MotionModel.Validatable.validate_presence", "original_string": "def validate_presence(field, value, setting)\n if(value.is_a?(Numeric))\n return true\n elsif value.is_a?(String) || value.nil?\n result = value.nil? || ((value.length == 0) == setting)\n additional_message = setting ? \"non-empty\" : \"non-empty\"\n add_message(field, \"incorrect value supplied for #{field.to_s} -- should be #{additional_message}.\") if result\n return !result\n end\n return false\n end", "language": "ruby", "code": "def validate_presence(field, value, setting)\n if(value.is_a?(Numeric))\n return true\n elsif value.is_a?(String) || value.nil?\n result = value.nil? || ((value.length == 0) == setting)\n additional_message = setting ? \"non-empty\" : \"non-empty\"\n add_message(field, \"incorrect value supplied for #{field.to_s} -- should be #{additional_message}.\") if result\n return !result\n end\n return false\n end", "code_tokens": ["def", "validate_presence", "(", "field", ",", "value", ",", "setting", ")", "if", "(", "value", ".", "is_a?", "(", "Numeric", ")", ")", "return", "true", "elsif", "value", ".", "is_a?", "(", "String", ")", "||", "value", ".", "nil?", "result", "=", "value", ".", "nil?", "||", "(", "(", "value", ".", "length", "==", "0", ")", "==", "setting", ")", "additional_message", "=", "setting", "?", "\"non-empty\"", ":", "\"non-empty\"", "add_message", "(", "field", ",", "\"incorrect value supplied for #{field.to_s} -- should be #{additional_message}.\"", ")", "if", "result", "return", "!", "result", "end", "return", "false", "end"], "docstring": "Validates that something has been endntered in a field.\n Should catch Fixnums, Bignums and Floats. Nils and Strings should\n be handled as well, Arrays, Hashes and other datatypes will not.", "docstring_tokens": ["Validates", "that", "something", "has", "been", "endntered", "in", "a", "field", ".", "Should", "catch", "Fixnums", "Bignums", "and", "Floats", ".", "Nils", "and", "Strings", "should", "be", "handled", "as", "well", "Arrays", "Hashes", "and", "other", "datatypes", "will", "not", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/validatable.rb#L149-L159", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/validatable.rb", "func_name": "MotionModel.Validatable.validate_length", "original_string": "def validate_length(field, value, setting)\n if value.is_a?(String) || value.nil?\n result = value.nil? || (value.length < setting.first || value.length > setting.last)\n add_message(field, \"incorrect value supplied for #{field.to_s} -- should be between #{setting.first} and #{setting.last} characters long.\") if result\n return !result\n end\n return false\n end", "language": "ruby", "code": "def validate_length(field, value, setting)\n if value.is_a?(String) || value.nil?\n result = value.nil? || (value.length < setting.first || value.length > setting.last)\n add_message(field, \"incorrect value supplied for #{field.to_s} -- should be between #{setting.first} and #{setting.last} characters long.\") if result\n return !result\n end\n return false\n end", "code_tokens": ["def", "validate_length", "(", "field", ",", "value", ",", "setting", ")", "if", "value", ".", "is_a?", "(", "String", ")", "||", "value", ".", "nil?", "result", "=", "value", ".", "nil?", "||", "(", "value", ".", "length", "<", "setting", ".", "first", "||", "value", ".", "length", ">", "setting", ".", "last", ")", "add_message", "(", "field", ",", "\"incorrect value supplied for #{field.to_s} -- should be between #{setting.first} and #{setting.last} characters long.\"", ")", "if", "result", "return", "!", "result", "end", "return", "false", "end"], "docstring": "Validates that the length is in a given range of characters. E.g.,\n\n validate :name, :length => 5..8", "docstring_tokens": ["Validates", "that", "the", "length", "is", "in", "a", "given", "range", "of", "characters", ".", "E", ".", "g", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/validatable.rb#L164-L171", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/validatable.rb", "func_name": "MotionModel.Validatable.validate_format", "original_string": "def validate_format(field, value, setting)\n result = value.nil? || setting.match(value).nil?\n add_message(field, \"#{field.to_s} does not appear to be in the proper format.\") if result\n return !result\n end", "language": "ruby", "code": "def validate_format(field, value, setting)\n result = value.nil? || setting.match(value).nil?\n add_message(field, \"#{field.to_s} does not appear to be in the proper format.\") if result\n return !result\n end", "code_tokens": ["def", "validate_format", "(", "field", ",", "value", ",", "setting", ")", "result", "=", "value", ".", "nil?", "||", "setting", ".", "match", "(", "value", ")", ".", "nil?", "add_message", "(", "field", ",", "\"#{field.to_s} does not appear to be in the proper format.\"", ")", "if", "result", "return", "!", "result", "end"], "docstring": "Validates contents of field against a given Regexp. This can be tricky because you need\n to anchor both sides in most cases using \\A and \\Z to get a reliable match.", "docstring_tokens": ["Validates", "contents", "of", "field", "against", "a", "given", "Regexp", ".", "This", "can", "be", "tricky", "because", "you", "need", "to", "anchor", "both", "sides", "in", "most", "cases", "using", "\\", "A", "and", "\\", "Z", "to", "get", "a", "reliable", "match", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/validatable.rb#L183-L187", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/model/model.rb", "func_name": "MotionModel.Model.set_auto_date_field", "original_string": "def set_auto_date_field(field_name)\n unless self.class.protect_remote_timestamps?\n method = \"#{field_name}=\"\n self.send(method, Time.now) if self.respond_to?(method)\n end\n end", "language": "ruby", "code": "def set_auto_date_field(field_name)\n unless self.class.protect_remote_timestamps?\n method = \"#{field_name}=\"\n self.send(method, Time.now) if self.respond_to?(method)\n end\n end", "code_tokens": ["def", "set_auto_date_field", "(", "field_name", ")", "unless", "self", ".", "class", ".", "protect_remote_timestamps?", "method", "=", "\"#{field_name}=\"", "self", ".", "send", "(", "method", ",", "Time", ".", "now", ")", "if", "self", ".", "respond_to?", "(", "method", ")", "end", "end"], "docstring": "Set created_at and updated_at fields", "docstring_tokens": ["Set", "created_at", "and", "updated_at", "fields"], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/model/model.rb#L551-L556", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/model/model.rb", "func_name": "MotionModel.Model.set_belongs_to_attr", "original_string": "def set_belongs_to_attr(col, owner, options = {})\n _col = column(col)\n unless belongs_to_synced?(_col, owner)\n _set_attr(_col.name, owner)\n rebuild_relation(_col, owner, set_inverse: options[:set_inverse])\n if _col.polymorphic\n set_polymorphic_attr(_col.name, owner)\n else\n _set_attr(_col.foreign_key, owner ? owner.id : nil)\n end\n end\n\n owner\n end", "language": "ruby", "code": "def set_belongs_to_attr(col, owner, options = {})\n _col = column(col)\n unless belongs_to_synced?(_col, owner)\n _set_attr(_col.name, owner)\n rebuild_relation(_col, owner, set_inverse: options[:set_inverse])\n if _col.polymorphic\n set_polymorphic_attr(_col.name, owner)\n else\n _set_attr(_col.foreign_key, owner ? owner.id : nil)\n end\n end\n\n owner\n end", "code_tokens": ["def", "set_belongs_to_attr", "(", "col", ",", "owner", ",", "options", "=", "{", "}", ")", "_col", "=", "column", "(", "col", ")", "unless", "belongs_to_synced?", "(", "_col", ",", "owner", ")", "_set_attr", "(", "_col", ".", "name", ",", "owner", ")", "rebuild_relation", "(", "_col", ",", "owner", ",", "set_inverse", ":", "options", "[", ":set_inverse", "]", ")", "if", "_col", ".", "polymorphic", "set_polymorphic_attr", "(", "_col", ".", "name", ",", "owner", ")", "else", "_set_attr", "(", "_col", ".", "foreign_key", ",", "owner", "?", "owner", ".", "id", ":", "nil", ")", "end", "end", "owner", "end"], "docstring": "Associate the owner but without rebuilding the inverse assignment", "docstring_tokens": ["Associate", "the", "owner", "but", "without", "rebuilding", "the", "inverse", "assignment"], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/model/model.rb#L707-L720", "partition": "valid"} {"repo": "pwnall/stellar", "path": "lib/stellar/homework.rb", "func_name": "Stellar.Homework.submissions", "original_string": "def submissions\n page = @client.get_nokogiri @url\n @submissions ||= page.css('.gradeTable tbody tr').map { |tr|\n begin\n Stellar::Homework::Submission.new tr, self\n rescue ArgumentError\n nil\n end\n }.reject(&:nil?)\n end", "language": "ruby", "code": "def submissions\n page = @client.get_nokogiri @url\n @submissions ||= page.css('.gradeTable tbody tr').map { |tr|\n begin\n Stellar::Homework::Submission.new tr, self\n rescue ArgumentError\n nil\n end\n }.reject(&:nil?)\n end", "code_tokens": ["def", "submissions", "page", "=", "@client", ".", "get_nokogiri", "@url", "@submissions", "||=", "page", ".", "css", "(", "'.gradeTable tbody tr'", ")", ".", "map", "{", "|", "tr", "|", "begin", "Stellar", "::", "Homework", "::", "Submission", ".", "new", "tr", ",", "self", "rescue", "ArgumentError", "nil", "end", "}", ".", "reject", "(", ":nil?", ")", "end"], "docstring": "Creates a Stellar client scoped to an assignment.\n\n @param [URI, String] page_url URL to the assignment's main Stellar page\n @param [String] assignment name, e.g. \"name\"\n @param [Course] the course that issued the assignment\n List of submissions associated with this problem set.", "docstring_tokens": ["Creates", "a", "Stellar", "client", "scoped", "to", "an", "assignment", "."], "sha": "cd2bfd55a6afe9118a06c0d45d6a168e520ec19f", "url": "https://github.com/pwnall/stellar/blob/cd2bfd55a6afe9118a06c0d45d6a168e520ec19f/lib/stellar/homework.rb#L70-L79", "partition": "valid"} {"repo": "pwnall/stellar", "path": "lib/stellar/client.rb", "func_name": "Stellar.Client.mech", "original_string": "def mech(&block)\n m = Mechanize.new do |m|\n m.cert_store = OpenSSL::X509::Store.new\n m.cert_store.add_file mitca_path\n m.user_agent_alias = 'Linux Firefox'\n yield m if block\n m\n end\n m\n end", "language": "ruby", "code": "def mech(&block)\n m = Mechanize.new do |m|\n m.cert_store = OpenSSL::X509::Store.new\n m.cert_store.add_file mitca_path\n m.user_agent_alias = 'Linux Firefox'\n yield m if block\n m\n end\n m\n end", "code_tokens": ["def", "mech", "(", "&", "block", ")", "m", "=", "Mechanize", ".", "new", "do", "|", "m", "|", "m", ".", "cert_store", "=", "OpenSSL", "::", "X509", "::", "Store", ".", "new", "m", ".", "cert_store", ".", "add_file", "mitca_path", "m", ".", "user_agent_alias", "=", "'Linux Firefox'", "yield", "m", "if", "block", "m", "end", "m", "end"], "docstring": "Client for accessing public information.\n\n Call auth to authenticate as a user and access restricted functionality.\n New Mechanize instance.", "docstring_tokens": ["Client", "for", "accessing", "public", "information", "."], "sha": "cd2bfd55a6afe9118a06c0d45d6a168e520ec19f", "url": "https://github.com/pwnall/stellar/blob/cd2bfd55a6afe9118a06c0d45d6a168e520ec19f/lib/stellar/client.rb#L18-L27", "partition": "valid"} {"repo": "pwnall/stellar", "path": "lib/stellar/client.rb", "func_name": "Stellar.Client.get_nokogiri", "original_string": "def get_nokogiri(path)\n uri = URI.join('https://stellar.mit.edu', path)\n raw_html = @mech.get_file uri\n Nokogiri.HTML raw_html, uri.to_s\n end", "language": "ruby", "code": "def get_nokogiri(path)\n uri = URI.join('https://stellar.mit.edu', path)\n raw_html = @mech.get_file uri\n Nokogiri.HTML raw_html, uri.to_s\n end", "code_tokens": ["def", "get_nokogiri", "(", "path", ")", "uri", "=", "URI", ".", "join", "(", "'https://stellar.mit.edu'", ",", "path", ")", "raw_html", "=", "@mech", ".", "get_file", "uri", "Nokogiri", ".", "HTML", "raw_html", ",", "uri", ".", "to_s", "end"], "docstring": "Fetches a page from the Stellar site.\n\n @param [String] path relative URL of the page to be fetched\n @return [Nokogiri::HTML::Document] the desired page, parsed with Nokogiri", "docstring_tokens": ["Fetches", "a", "page", "from", "the", "Stellar", "site", "."], "sha": "cd2bfd55a6afe9118a06c0d45d6a168e520ec19f", "url": "https://github.com/pwnall/stellar/blob/cd2bfd55a6afe9118a06c0d45d6a168e520ec19f/lib/stellar/client.rb#L42-L46", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/input_helpers.rb", "func_name": "MotionModel.InputHelpers.field_at", "original_string": "def field_at(index)\n data = self.class.instance_variable_get('@binding_data'.to_sym)\n data[index].tag = index + 1\n data[index]\n end", "language": "ruby", "code": "def field_at(index)\n data = self.class.instance_variable_get('@binding_data'.to_sym)\n data[index].tag = index + 1\n data[index]\n end", "code_tokens": ["def", "field_at", "(", "index", ")", "data", "=", "self", ".", "class", ".", "instance_variable_get", "(", "'@binding_data'", ".", "to_sym", ")", "data", "[", "index", "]", ".", "tag", "=", "index", "+", "1", "data", "[", "index", "]", "end"], "docstring": "+field_at+ retrieves the field at a given index.\n\n Usage:\n\n field = field_at(indexPath.row)\n label_view = subview(UILabel, :label_frame, text: field.label)", "docstring_tokens": ["+", "field_at", "+", "retrieves", "the", "field", "at", "a", "given", "index", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/input_helpers.rb#L73-L77", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/input_helpers.rb", "func_name": "MotionModel.InputHelpers.bind", "original_string": "def bind\n raise ModelNotSetError.new(\"You must set the model before binding it.\") unless @model\n\n fields do |field|\n view_obj = self.view.viewWithTag(field.tag)\n @model.send(\"#{field.name}=\".to_sym, view_obj.text) if view_obj.respond_to?(:text)\n end\n end", "language": "ruby", "code": "def bind\n raise ModelNotSetError.new(\"You must set the model before binding it.\") unless @model\n\n fields do |field|\n view_obj = self.view.viewWithTag(field.tag)\n @model.send(\"#{field.name}=\".to_sym, view_obj.text) if view_obj.respond_to?(:text)\n end\n end", "code_tokens": ["def", "bind", "raise", "ModelNotSetError", ".", "new", "(", "\"You must set the model before binding it.\"", ")", "unless", "@model", "fields", "do", "|", "field", "|", "view_obj", "=", "self", ".", "view", ".", "viewWithTag", "(", "field", ".", "tag", ")", "@model", ".", "send", "(", "\"#{field.name}=\"", ".", "to_sym", ",", "view_obj", ".", "text", ")", "if", "view_obj", ".", "respond_to?", "(", ":text", ")", "end", "end"], "docstring": "+bind+ fetches all mapped fields from\n any subview of the current +UIView+\n and transfers the contents to the\n corresponding fields of the model\n specified by the +model+ method.", "docstring_tokens": ["+", "bind", "+", "fetches", "all", "mapped", "fields", "from", "any", "subview", "of", "the", "current", "+", "UIView", "+", "and", "transfers", "the", "contents", "to", "the", "corresponding", "fields", "of", "the", "model", "specified", "by", "the", "+", "model", "+", "method", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/input_helpers.rb#L108-L115", "partition": "valid"} {"repo": "sxross/MotionModel", "path": "motion/input_helpers.rb", "func_name": "MotionModel.InputHelpers.handle_keyboard_will_hide", "original_string": "def handle_keyboard_will_hide(notification)\n return unless @table\n\n if UIEdgeInsetsEqualToEdgeInsets(@table.contentInset, UIEdgeInsetsZero)\n return\n end\n\n animationCurve = notification.userInfo.valueForKey(UIKeyboardAnimationCurveUserInfoKey)\n animationDuration = notification.userInfo.valueForKey(UIKeyboardAnimationDurationUserInfoKey)\n\n UIView.beginAnimations(\"changeTableViewContentInset\", context:nil)\n UIView.setAnimationDuration(animationDuration)\n UIView.setAnimationCurve(animationCurve)\n\n @table.contentInset = UIEdgeInsetsZero;\n\n UIView.commitAnimations\n end", "language": "ruby", "code": "def handle_keyboard_will_hide(notification)\n return unless @table\n\n if UIEdgeInsetsEqualToEdgeInsets(@table.contentInset, UIEdgeInsetsZero)\n return\n end\n\n animationCurve = notification.userInfo.valueForKey(UIKeyboardAnimationCurveUserInfoKey)\n animationDuration = notification.userInfo.valueForKey(UIKeyboardAnimationDurationUserInfoKey)\n\n UIView.beginAnimations(\"changeTableViewContentInset\", context:nil)\n UIView.setAnimationDuration(animationDuration)\n UIView.setAnimationCurve(animationCurve)\n\n @table.contentInset = UIEdgeInsetsZero;\n\n UIView.commitAnimations\n end", "code_tokens": ["def", "handle_keyboard_will_hide", "(", "notification", ")", "return", "unless", "@table", "if", "UIEdgeInsetsEqualToEdgeInsets", "(", "@table", ".", "contentInset", ",", "UIEdgeInsetsZero", ")", "return", "end", "animationCurve", "=", "notification", ".", "userInfo", ".", "valueForKey", "(", "UIKeyboardAnimationCurveUserInfoKey", ")", "animationDuration", "=", "notification", ".", "userInfo", ".", "valueForKey", "(", "UIKeyboardAnimationDurationUserInfoKey", ")", "UIView", ".", "beginAnimations", "(", "\"changeTableViewContentInset\"", ",", "context", ":", "nil", ")", "UIView", ".", "setAnimationDuration", "(", "animationDuration", ")", "UIView", ".", "setAnimationCurve", "(", "animationCurve", ")", "@table", ".", "contentInset", "=", "UIEdgeInsetsZero", ";", "UIView", ".", "commitAnimations", "end"], "docstring": "Undo all the rejiggering when the keyboard slides\n down.\n\n You *must* handle the +UIKeyboardWillHideNotification+ and\n when you receive it, call this method to handle the keyboard\n hiding.", "docstring_tokens": ["Undo", "all", "the", "rejiggering", "when", "the", "keyboard", "slides", "down", "."], "sha": "37bf447b6c9bdc2158f320cef40714f41132c542", "url": "https://github.com/sxross/MotionModel/blob/37bf447b6c9bdc2158f320cef40714f41132c542/motion/input_helpers.rb#L191-L208", "partition": "valid"} {"repo": "mkristian/cuba-api", "path": "lib/cuba_api/utils.rb", "func_name": "CubaApi.Utils.no_body", "original_string": "def no_body( status )\n res.status = ::Rack::Utils.status_code( status )\n res.write ::Rack::Utils::HTTP_STATUS_CODES[ res.status ]\n res['Content-Type' ] = 'text/plain'\n end", "language": "ruby", "code": "def no_body( status )\n res.status = ::Rack::Utils.status_code( status )\n res.write ::Rack::Utils::HTTP_STATUS_CODES[ res.status ]\n res['Content-Type' ] = 'text/plain'\n end", "code_tokens": ["def", "no_body", "(", "status", ")", "res", ".", "status", "=", "::", "Rack", "::", "Utils", ".", "status_code", "(", "status", ")", "res", ".", "write", "::", "Rack", "::", "Utils", "::", "HTTP_STATUS_CODES", "[", "res", ".", "status", "]", "res", "[", "'Content-Type'", "]", "=", "'text/plain'", "end"], "docstring": "convenient method for status only responses", "docstring_tokens": ["convenient", "method", "for", "status", "only", "responses"], "sha": "e3413d7c32bee83280efd001e3d166b0b93c7417", "url": "https://github.com/mkristian/cuba-api/blob/e3413d7c32bee83280efd001e3d166b0b93c7417/lib/cuba_api/utils.rb#L19-L23", "partition": "valid"} {"repo": "smileart/rack-fraction", "path": "lib/rack/fraction.rb", "func_name": "Rack.Fraction.call", "original_string": "def call(env)\n if rand(1..100) <= @percent\n if @modify == :response\n # status, headers, body\n response = @handler.call(*@app.call(env))\n else # :env\n modified_env = @handler.call(env) || env\n response = @app.call(modified_env)\n end\n else\n response = @app.call(env)\n end\n\n response\n end", "language": "ruby", "code": "def call(env)\n if rand(1..100) <= @percent\n if @modify == :response\n # status, headers, body\n response = @handler.call(*@app.call(env))\n else # :env\n modified_env = @handler.call(env) || env\n response = @app.call(modified_env)\n end\n else\n response = @app.call(env)\n end\n\n response\n end", "code_tokens": ["def", "call", "(", "env", ")", "if", "rand", "(", "1", "..", "100", ")", "<=", "@percent", "if", "@modify", "==", ":response", "# status, headers, body", "response", "=", "@handler", ".", "call", "(", "@app", ".", "call", "(", "env", ")", ")", "else", "# :env", "modified_env", "=", "@handler", ".", "call", "(", "env", ")", "||", "env", "response", "=", "@app", ".", "call", "(", "modified_env", ")", "end", "else", "response", "=", "@app", ".", "call", "(", "env", ")", "end", "response", "end"], "docstring": "Initialisation of the middleware\n\n @param [Rack::App] app rack app to stack middleware into (passed automatically)\n @param [Symbol] modify a flag which tells what to modify with this middleware (:response or :env)\n anything other than :response would mean :env (default: nil)\n @param [Integer] percent fraction of the requests that should be affected by this middleware (default: 0)\n @param [Proc] block the block of code with business logic which modifies response/env\n Implementation of the middleware automatically called by Rack\n\n @param [Hash] env rack app env automatically passed to the middleware\n\n @return [Rack::Response] response after either calling original app and modifying response\n or calling the app with modified environment and returning its response", "docstring_tokens": ["Initialisation", "of", "the", "middleware"], "sha": "d030b63a6b0181ceca2768faf5452ca823c15fcf", "url": "https://github.com/smileart/rack-fraction/blob/d030b63a6b0181ceca2768faf5452ca823c15fcf/lib/rack/fraction.rb#L30-L44", "partition": "valid"} {"repo": "claco/muster", "path": "lib/muster/results.rb", "func_name": "Muster.Results.filtered", "original_string": "def filtered\n return self if filters.empty?\n\n filtered_results = filters.each_with_object({}) do |(key, options), results|\n results[key] = filter(key, *options)\n end\n\n self.class.new(filtered_results)\n end", "language": "ruby", "code": "def filtered\n return self if filters.empty?\n\n filtered_results = filters.each_with_object({}) do |(key, options), results|\n results[key] = filter(key, *options)\n end\n\n self.class.new(filtered_results)\n end", "code_tokens": ["def", "filtered", "return", "self", "if", "filters", ".", "empty?", "filtered_results", "=", "filters", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "key", ",", "options", ")", ",", "results", "|", "results", "[", "key", "]", "=", "filter", "(", "key", ",", "options", ")", "end", "self", ".", "class", ".", "new", "(", "filtered_results", ")", "end"], "docstring": "Returns the raw data with all of the filters applied\n\n If no filters were added, this method simply returns self.\n\n @return [Muster::Results]\n\n @example\n\n results.add_filter(:select, :only => [:id, :name])\n results.add_dilter(:page, 1)\n results.filtered #=> { 'select' => [:id, :name], 'page' => 1 }", "docstring_tokens": ["Returns", "the", "raw", "data", "with", "all", "of", "the", "filters", "applied"], "sha": "71e99053ced9da3e98820eb8be653d9b76325a39", "url": "https://github.com/claco/muster/blob/71e99053ced9da3e98820eb8be653d9b76325a39/lib/muster/results.rb#L99-L107", "partition": "valid"} {"repo": "claco/muster", "path": "lib/muster/results.rb", "func_name": "Muster.Results.filter", "original_string": "def filter(key, *options)\n if options.present? && options.first.instance_of?(Hash)\n options = options.first.with_indifferent_access\n\n if options.key?(:only)\n return filter_only_values(key, options[:only])\n elsif options.key?(:except)\n return filter_excluded_values(key, options[:except])\n end\n else\n return fetch(key, *options)\n end\n end", "language": "ruby", "code": "def filter(key, *options)\n if options.present? && options.first.instance_of?(Hash)\n options = options.first.with_indifferent_access\n\n if options.key?(:only)\n return filter_only_values(key, options[:only])\n elsif options.key?(:except)\n return filter_excluded_values(key, options[:except])\n end\n else\n return fetch(key, *options)\n end\n end", "code_tokens": ["def", "filter", "(", "key", ",", "*", "options", ")", "if", "options", ".", "present?", "&&", "options", ".", "first", ".", "instance_of?", "(", "Hash", ")", "options", "=", "options", ".", "first", ".", "with_indifferent_access", "if", "options", ".", "key?", "(", ":only", ")", "return", "filter_only_values", "(", "key", ",", "options", "[", ":only", "]", ")", "elsif", "options", ".", "key?", "(", ":except", ")", "return", "filter_excluded_values", "(", "key", ",", "options", "[", ":except", "]", ")", "end", "else", "return", "fetch", "(", "key", ",", "options", ")", "end", "end"], "docstring": "Filters and returns the raw data values for the specifid key and options\n\n @param key [String,Symbol] the key of the values in {#data} to filter\n @param [optional, Hash] options the options available for this filter\n @option options [optional] :only when specified, only return the matching values\n If you specify a single value, a single value will be returned\n If you specify an Array of values, an Array will be returned, even if only one value matches\n @option options [optional] :except return all values except the ones given here\n If the raw data value is a single value, a single value will be returned\n If the raw data value is an Array, and array will be returned, even if all values are excluded\n If nothing was excluded, the raw value is returned as-is\n\n If you pass a scalar value instead of a Hash into options, it will be treated as the default, just like\n Hash#fetch does.\n\n If you pass nothing into the options argument, it will return all values if the key exists or raise\n a KeyError like Hash#fetch.\n\n @return [void]\n\n @example\n\n data = { :select => [:id, :name, :created_at] }\n results = Muster::Results.new(data)\n results.filter(:select) #=> [:id, :name, :created_at]\n results.filter(:select, :only => :name) #=> :name\n results.filter(:select, :only => [:other, :name]) #=> [:name]\n results.filter(:other, :default) #=> :default\n results.filter(:other) #=> KeyError", "docstring_tokens": ["Filters", "and", "returns", "the", "raw", "data", "values", "for", "the", "specifid", "key", "and", "options"], "sha": "71e99053ced9da3e98820eb8be653d9b76325a39", "url": "https://github.com/claco/muster/blob/71e99053ced9da3e98820eb8be653d9b76325a39/lib/muster/results.rb#L138-L150", "partition": "valid"} {"repo": "mnpopcenter/stats_package_syntax_file_generator", "path": "lib/syntax_file/controller.rb", "func_name": "SyntaxFile.Controller.modify_metadata", "original_string": "def modify_metadata\n # Force all variables to be strings.\n if @all_vars_as_string\n @variables.each do |var|\n var.is_string_var = true\n var.is_double_var = false\n var.implied_decimals = 0\n end\n end\n\n # If the user wants to rectangularize hierarchical data, the\n # select_vars_by_record_type option is required.\n @select_vars_by_record_type = true if @rectangularize\n\n # Remove any variables not belonging to the declared record types.\n if @select_vars_by_record_type\n rt_lookup = rec_type_lookup_hash()\n @variables = @variables.find_all { |var| var.is_common_var or rt_lookup[var.record_type] }\n end\nend", "language": "ruby", "code": "def modify_metadata\n # Force all variables to be strings.\n if @all_vars_as_string\n @variables.each do |var|\n var.is_string_var = true\n var.is_double_var = false\n var.implied_decimals = 0\n end\n end\n\n # If the user wants to rectangularize hierarchical data, the\n # select_vars_by_record_type option is required.\n @select_vars_by_record_type = true if @rectangularize\n\n # Remove any variables not belonging to the declared record types.\n if @select_vars_by_record_type\n rt_lookup = rec_type_lookup_hash()\n @variables = @variables.find_all { |var| var.is_common_var or rt_lookup[var.record_type] }\n end\nend", "code_tokens": ["def", "modify_metadata", "# Force all variables to be strings.", "if", "@all_vars_as_string", "@variables", ".", "each", "do", "|", "var", "|", "var", ".", "is_string_var", "=", "true", "var", ".", "is_double_var", "=", "false", "var", ".", "implied_decimals", "=", "0", "end", "end", "# If the user wants to rectangularize hierarchical data, the", "# select_vars_by_record_type option is required.", "@select_vars_by_record_type", "=", "true", "if", "@rectangularize", "# Remove any variables not belonging to the declared record types.", "if", "@select_vars_by_record_type", "rt_lookup", "=", "rec_type_lookup_hash", "(", ")", "@variables", "=", "@variables", ".", "find_all", "{", "|", "var", "|", "var", ".", "is_common_var", "or", "rt_lookup", "[", "var", ".", "record_type", "]", "}", "end", "end"], "docstring": "Before generating syntax, we need to handle some controller-level\n options that require global modification of the metadata.", "docstring_tokens": ["Before", "generating", "syntax", "we", "need", "to", "handle", "some", "controller", "-", "level", "options", "that", "require", "global", "modification", "of", "the", "metadata", "."], "sha": "014e23a69f9a647f20eaffcf9e95016f98d5c17e", "url": "https://github.com/mnpopcenter/stats_package_syntax_file_generator/blob/014e23a69f9a647f20eaffcf9e95016f98d5c17e/lib/syntax_file/controller.rb#L252-L271", "partition": "valid"} {"repo": "mnpopcenter/stats_package_syntax_file_generator", "path": "lib/syntax_file/controller.rb", "func_name": "SyntaxFile.Controller.validate_metadata", "original_string": "def validate_metadata (check = {})\n bad_metadata('no variables') if @variables.empty?\n\n if @rectangularize\n msg = 'the rectangularize option requires data_structure=hier'\n bad_metadata(msg) unless @data_structure == 'hier'\n end\n\n if @data_structure == 'hier' or @select_vars_by_record_type\n bad_metadata('no record types') if @record_types.empty?\n\n msg = 'record types must be unique'\n bad_metadata(msg) unless rec_type_lookup_hash.keys.size == @record_types.size\n\n msg = 'all variables must have a record type'\n bad_metadata(msg) unless @variables.find { |var| var.record_type.length == 0 }.nil?\n\n msg = 'with no common variables, every record type needs at least one variable ('\n if @variables.find { |var| var.is_common_var }.nil?\n @record_types.each do |rt|\n next if get_vars_by_record_type(rt).size > 0\n bad_metadata(msg + rt + ')')\n end\n end\n end\n\n if @data_structure == 'hier'\n bad_metadata('no record type variable') if record_type_var.nil?\n end\n\n return if check[:minimal]\n\n @variables.each do |v|\n v.start_column = v.start_column.to_i\n v.width = v.width.to_i\n v.implied_decimals = v.implied_decimals.to_i\n bad_metadata(\"#{v.name}, start_column\" ) unless v.start_column > 0\n bad_metadata(\"#{v.name}, width\" ) unless v.width > 0\n bad_metadata(\"#{v.name}, implied_decimals\") unless v.implied_decimals >= 0\n end\nend", "language": "ruby", "code": "def validate_metadata (check = {})\n bad_metadata('no variables') if @variables.empty?\n\n if @rectangularize\n msg = 'the rectangularize option requires data_structure=hier'\n bad_metadata(msg) unless @data_structure == 'hier'\n end\n\n if @data_structure == 'hier' or @select_vars_by_record_type\n bad_metadata('no record types') if @record_types.empty?\n\n msg = 'record types must be unique'\n bad_metadata(msg) unless rec_type_lookup_hash.keys.size == @record_types.size\n\n msg = 'all variables must have a record type'\n bad_metadata(msg) unless @variables.find { |var| var.record_type.length == 0 }.nil?\n\n msg = 'with no common variables, every record type needs at least one variable ('\n if @variables.find { |var| var.is_common_var }.nil?\n @record_types.each do |rt|\n next if get_vars_by_record_type(rt).size > 0\n bad_metadata(msg + rt + ')')\n end\n end\n end\n\n if @data_structure == 'hier'\n bad_metadata('no record type variable') if record_type_var.nil?\n end\n\n return if check[:minimal]\n\n @variables.each do |v|\n v.start_column = v.start_column.to_i\n v.width = v.width.to_i\n v.implied_decimals = v.implied_decimals.to_i\n bad_metadata(\"#{v.name}, start_column\" ) unless v.start_column > 0\n bad_metadata(\"#{v.name}, width\" ) unless v.width > 0\n bad_metadata(\"#{v.name}, implied_decimals\") unless v.implied_decimals >= 0\n end\nend", "code_tokens": ["def", "validate_metadata", "(", "check", "=", "{", "}", ")", "bad_metadata", "(", "'no variables'", ")", "if", "@variables", ".", "empty?", "if", "@rectangularize", "msg", "=", "'the rectangularize option requires data_structure=hier'", "bad_metadata", "(", "msg", ")", "unless", "@data_structure", "==", "'hier'", "end", "if", "@data_structure", "==", "'hier'", "or", "@select_vars_by_record_type", "bad_metadata", "(", "'no record types'", ")", "if", "@record_types", ".", "empty?", "msg", "=", "'record types must be unique'", "bad_metadata", "(", "msg", ")", "unless", "rec_type_lookup_hash", ".", "keys", ".", "size", "==", "@record_types", ".", "size", "msg", "=", "'all variables must have a record type'", "bad_metadata", "(", "msg", ")", "unless", "@variables", ".", "find", "{", "|", "var", "|", "var", ".", "record_type", ".", "length", "==", "0", "}", ".", "nil?", "msg", "=", "'with no common variables, every record type needs at least one variable ('", "if", "@variables", ".", "find", "{", "|", "var", "|", "var", ".", "is_common_var", "}", ".", "nil?", "@record_types", ".", "each", "do", "|", "rt", "|", "next", "if", "get_vars_by_record_type", "(", "rt", ")", ".", "size", ">", "0", "bad_metadata", "(", "msg", "+", "rt", "+", "')'", ")", "end", "end", "end", "if", "@data_structure", "==", "'hier'", "bad_metadata", "(", "'no record type variable'", ")", "if", "record_type_var", ".", "nil?", "end", "return", "if", "check", "[", ":minimal", "]", "@variables", ".", "each", "do", "|", "v", "|", "v", ".", "start_column", "=", "v", ".", "start_column", ".", "to_i", "v", ".", "width", "=", "v", ".", "width", ".", "to_i", "v", ".", "implied_decimals", "=", "v", ".", "implied_decimals", ".", "to_i", "bad_metadata", "(", "\"#{v.name}, start_column\"", ")", "unless", "v", ".", "start_column", ">", "0", "bad_metadata", "(", "\"#{v.name}, width\"", ")", "unless", "v", ".", "width", ">", "0", "bad_metadata", "(", "\"#{v.name}, implied_decimals\"", ")", "unless", "v", ".", "implied_decimals", ">=", "0", "end", "end"], "docstring": "Before generating syntax, run a sanity check on the metadata.", "docstring_tokens": ["Before", "generating", "syntax", "run", "a", "sanity", "check", "on", "the", "metadata", "."], "sha": "014e23a69f9a647f20eaffcf9e95016f98d5c17e", "url": "https://github.com/mnpopcenter/stats_package_syntax_file_generator/blob/014e23a69f9a647f20eaffcf9e95016f98d5c17e/lib/syntax_file/controller.rb#L276-L316", "partition": "valid"} {"repo": "mrcsparker/activerecord-jdbcteradata-adapter", "path": "lib/arjdbc/teradata/adapter.rb", "func_name": "::ArJdbc.Teradata._execute", "original_string": "def _execute(sql, name = nil)\n if self.class.select?(sql)\n result = @connection.execute_query(sql)\n result.map! do |r|\n new_hash = {}\n r.each_pair do |k, v|\n new_hash.merge!({ k.downcase => v })\n end\n new_hash\n end if self.class.lowercase_schema_reflection\n result\n elsif self.class.insert?(sql)\n (@connection.execute_insert(sql) || last_insert_id(_table_name_from_insert(sql))).to_i\n else\n @connection.execute_update(sql)\n end\n end", "language": "ruby", "code": "def _execute(sql, name = nil)\n if self.class.select?(sql)\n result = @connection.execute_query(sql)\n result.map! do |r|\n new_hash = {}\n r.each_pair do |k, v|\n new_hash.merge!({ k.downcase => v })\n end\n new_hash\n end if self.class.lowercase_schema_reflection\n result\n elsif self.class.insert?(sql)\n (@connection.execute_insert(sql) || last_insert_id(_table_name_from_insert(sql))).to_i\n else\n @connection.execute_update(sql)\n end\n end", "code_tokens": ["def", "_execute", "(", "sql", ",", "name", "=", "nil", ")", "if", "self", ".", "class", ".", "select?", "(", "sql", ")", "result", "=", "@connection", ".", "execute_query", "(", "sql", ")", "result", ".", "map!", "do", "|", "r", "|", "new_hash", "=", "{", "}", "r", ".", "each_pair", "do", "|", "k", ",", "v", "|", "new_hash", ".", "merge!", "(", "{", "k", ".", "downcase", "=>", "v", "}", ")", "end", "new_hash", "end", "if", "self", ".", "class", ".", "lowercase_schema_reflection", "result", "elsif", "self", ".", "class", ".", "insert?", "(", "sql", ")", "(", "@connection", ".", "execute_insert", "(", "sql", ")", "||", "last_insert_id", "(", "_table_name_from_insert", "(", "sql", ")", ")", ")", ".", "to_i", "else", "@connection", ".", "execute_update", "(", "sql", ")", "end", "end"], "docstring": "- native_sql_to_type\n- active?\n- reconnect!\n- disconnect!\n- exec_query\n- exec_insert\n- exec_delete\n- exec_update\n+ do_exec\n- execute", "docstring_tokens": ["-", "native_sql_to_type", "-", "active?", "-", "reconnect!", "-", "disconnect!", "-", "exec_query", "-", "exec_insert", "-", "exec_delete", "-", "exec_update", "+", "do_exec", "-", "execute"], "sha": "4cad231a69ae13b82a5fecdecb10f243230690f6", "url": "https://github.com/mrcsparker/activerecord-jdbcteradata-adapter/blob/4cad231a69ae13b82a5fecdecb10f243230690f6/lib/arjdbc/teradata/adapter.rb#L127-L143", "partition": "valid"} {"repo": "mrcsparker/activerecord-jdbcteradata-adapter", "path": "lib/arjdbc/teradata/adapter.rb", "func_name": "::ArJdbc.Teradata.primary_keys", "original_string": "def primary_keys(table)\n if self.class.lowercase_schema_reflection\n @connection.primary_keys(table).map do |key|\n key.downcase\n end\n else\n @connection.primary_keys(table)\n end\n end", "language": "ruby", "code": "def primary_keys(table)\n if self.class.lowercase_schema_reflection\n @connection.primary_keys(table).map do |key|\n key.downcase\n end\n else\n @connection.primary_keys(table)\n end\n end", "code_tokens": ["def", "primary_keys", "(", "table", ")", "if", "self", ".", "class", ".", "lowercase_schema_reflection", "@connection", ".", "primary_keys", "(", "table", ")", ".", "map", "do", "|", "key", "|", "key", ".", "downcase", "end", "else", "@connection", ".", "primary_keys", "(", "table", ")", "end", "end"], "docstring": "- begin_db_transaction\n- commit_db_transaction\n- rollback_db_transaction\n- begin_isolated_db_transaction\n- supports_transaction_isolation?\n- write_large_object\n- pk_and_sequence_for\n- primary_key\n- primary_keys", "docstring_tokens": ["-", "begin_db_transaction", "-", "commit_db_transaction", "-", "rollback_db_transaction", "-", "begin_isolated_db_transaction", "-", "supports_transaction_isolation?", "-", "write_large_object", "-", "pk_and_sequence_for", "-", "primary_key", "-", "primary_keys"], "sha": "4cad231a69ae13b82a5fecdecb10f243230690f6", "url": "https://github.com/mrcsparker/activerecord-jdbcteradata-adapter/blob/4cad231a69ae13b82a5fecdecb10f243230690f6/lib/arjdbc/teradata/adapter.rb#L249-L257", "partition": "valid"} {"repo": "mrcsparker/activerecord-jdbcteradata-adapter", "path": "lib/arjdbc/teradata/adapter.rb", "func_name": "::ArJdbc.Teradata.change_column", "original_string": "def change_column(table_name, column_name, type, options = {}) #:nodoc:\n change_column_sql = \"ALTER TABLE #{quote_table_name(table_name)} \" <<\n \"ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit])}\"\n add_column_options!(change_column_sql, options)\n execute(change_column_sql)\n end", "language": "ruby", "code": "def change_column(table_name, column_name, type, options = {}) #:nodoc:\n change_column_sql = \"ALTER TABLE #{quote_table_name(table_name)} \" <<\n \"ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit])}\"\n add_column_options!(change_column_sql, options)\n execute(change_column_sql)\n end", "code_tokens": ["def", "change_column", "(", "table_name", ",", "column_name", ",", "type", ",", "options", "=", "{", "}", ")", "#:nodoc:", "change_column_sql", "=", "\"ALTER TABLE #{quote_table_name(table_name)} \"", "<<", "\"ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit])}\"", "add_column_options!", "(", "change_column_sql", ",", "options", ")", "execute", "(", "change_column_sql", ")", "end"], "docstring": "+ change_column\n This only works in a VERY limited fashion. For example, VARCHAR columns\n cannot be shortened, one column type cannot be converted to another.", "docstring_tokens": ["+", "change_column", "This", "only", "works", "in", "a", "VERY", "limited", "fashion", ".", "For", "example", "VARCHAR", "columns", "cannot", "be", "shortened", "one", "column", "type", "cannot", "be", "converted", "to", "another", "."], "sha": "4cad231a69ae13b82a5fecdecb10f243230690f6", "url": "https://github.com/mrcsparker/activerecord-jdbcteradata-adapter/blob/4cad231a69ae13b82a5fecdecb10f243230690f6/lib/arjdbc/teradata/adapter.rb#L298-L303", "partition": "valid"} {"repo": "mnpopcenter/stats_package_syntax_file_generator", "path": "lib/syntax_file/maker.rb", "func_name": "SyntaxFile.Maker.labelable_values", "original_string": "def labelable_values (var)\n # For non-string variables, only values that look\n # like integers can be labeled.\n return var.values if var.is_string_var\n var.values.find_all { |val| val.value.to_s =~ /^\\-?\\d+$/ }\nend", "language": "ruby", "code": "def labelable_values (var)\n # For non-string variables, only values that look\n # like integers can be labeled.\n return var.values if var.is_string_var\n var.values.find_all { |val| val.value.to_s =~ /^\\-?\\d+$/ }\nend", "code_tokens": ["def", "labelable_values", "(", "var", ")", "# For non-string variables, only values that look", "# like integers can be labeled.", "return", "var", ".", "values", "if", "var", ".", "is_string_var", "var", ".", "values", ".", "find_all", "{", "|", "val", "|", "val", ".", "value", ".", "to_s", "=~", "/", "\\-", "\\d", "/", "}", "end"], "docstring": "Helper methods for values and their labels.", "docstring_tokens": ["Helper", "methods", "for", "values", "and", "their", "labels", "."], "sha": "014e23a69f9a647f20eaffcf9e95016f98d5c17e", "url": "https://github.com/mnpopcenter/stats_package_syntax_file_generator/blob/014e23a69f9a647f20eaffcf9e95016f98d5c17e/lib/syntax_file/maker.rb#L86-L91", "partition": "valid"} {"repo": "joseairosa/ohm-expire", "path": "lib/ohm/expire.rb", "func_name": "Ohm.Model.update_ttl", "original_string": "def update_ttl new_ttl=nil\n # Load default if no new ttl is specified\n new_ttl = self._default_expire if new_ttl.nil?\n # Make sure we have a valid value\n new_ttl = -1 if !new_ttl.to_i.is_a?(Fixnum) || new_ttl.to_i < 0\n # Update indices\n Ohm.redis.expire(self.key, new_ttl)\n Ohm.redis.expire(\"#{self.key}:_indices\", new_ttl)\n end", "language": "ruby", "code": "def update_ttl new_ttl=nil\n # Load default if no new ttl is specified\n new_ttl = self._default_expire if new_ttl.nil?\n # Make sure we have a valid value\n new_ttl = -1 if !new_ttl.to_i.is_a?(Fixnum) || new_ttl.to_i < 0\n # Update indices\n Ohm.redis.expire(self.key, new_ttl)\n Ohm.redis.expire(\"#{self.key}:_indices\", new_ttl)\n end", "code_tokens": ["def", "update_ttl", "new_ttl", "=", "nil", "# Load default if no new ttl is specified", "new_ttl", "=", "self", ".", "_default_expire", "if", "new_ttl", ".", "nil?", "# Make sure we have a valid value", "new_ttl", "=", "-", "1", "if", "!", "new_ttl", ".", "to_i", ".", "is_a?", "(", "Fixnum", ")", "||", "new_ttl", ".", "to_i", "<", "0", "# Update indices", "Ohm", ".", "redis", ".", "expire", "(", "self", ".", "key", ",", "new_ttl", ")", "Ohm", ".", "redis", ".", "expire", "(", "\"#{self.key}:_indices\"", ",", "new_ttl", ")", "end"], "docstring": "Update the ttl\n\n ==== Attributes\n\n * +new_ttl Fixnum+ - The new expire amount. If nil, value will fallback to default expire\n\n ==== Returns\n\n * nil\n\n ==== Examples\n\n d = Model.create(:hash => \"123\")\n d.update_ttl(30)", "docstring_tokens": ["Update", "the", "ttl"], "sha": "979cc9252baefcf77aa56a5cbf85fba5cf98cf76", "url": "https://github.com/joseairosa/ohm-expire/blob/979cc9252baefcf77aa56a5cbf85fba5cf98cf76/lib/ohm/expire.rb#L107-L115", "partition": "valid"} {"repo": "gregory/sipwizard", "path": "lib/sipwizard/relation.rb", "func_name": "Sipwizard.Relation.hash_to_query", "original_string": "def hash_to_query(h)\n h = Hash[h.map{|k,v| [k, \"\\\"#{v}\\\"\"]}]\n Rack::Utils.unescape Rack::Utils.build_query(h)\n end", "language": "ruby", "code": "def hash_to_query(h)\n h = Hash[h.map{|k,v| [k, \"\\\"#{v}\\\"\"]}]\n Rack::Utils.unescape Rack::Utils.build_query(h)\n end", "code_tokens": ["def", "hash_to_query", "(", "h", ")", "h", "=", "Hash", "[", "h", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ",", "\"\\\"#{v}\\\"\"", "]", "}", "]", "Rack", "::", "Utils", ".", "unescape", "Rack", "::", "Utils", ".", "build_query", "(", "h", ")", "end"], "docstring": "Hack to comply with the api spec ... which sucks", "docstring_tokens": ["Hack", "to", "comply", "with", "the", "api", "spec", "...", "which", "sucks"], "sha": "93751f507ced2ba5aafa28dd25c8c6a3a20ea955", "url": "https://github.com/gregory/sipwizard/blob/93751f507ced2ba5aafa28dd25c8c6a3a20ea955/lib/sipwizard/relation.rb#L22-L25", "partition": "valid"} {"repo": "gouravtiwari/akamai-cloudlet-manager", "path": "lib/akamai_cloudlet_manager/policy_version.rb", "func_name": "AkamaiCloudletManager.PolicyVersion.existing_rules", "original_string": "def existing_rules\n request = Net::HTTP::Get.new URI.join(@base_uri.to_s, \"cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}?omitRules=false&matchRuleFormat=1.0\").to_s\n response = @http_host.request(request)\n response.body\n end", "language": "ruby", "code": "def existing_rules\n request = Net::HTTP::Get.new URI.join(@base_uri.to_s, \"cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}?omitRules=false&matchRuleFormat=1.0\").to_s\n response = @http_host.request(request)\n response.body\n end", "code_tokens": ["def", "existing_rules", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "URI", ".", "join", "(", "@base_uri", ".", "to_s", ",", "\"cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}?omitRules=false&matchRuleFormat=1.0\"", ")", ".", "to_s", "response", "=", "@http_host", ".", "request", "(", "request", ")", "response", ".", "body", "end"], "docstring": "Get Policy version's rules", "docstring_tokens": ["Get", "Policy", "version", "s", "rules"], "sha": "03ef8a19065bdd1998550071be07b872b643715a", "url": "https://github.com/gouravtiwari/akamai-cloudlet-manager/blob/03ef8a19065bdd1998550071be07b872b643715a/lib/akamai_cloudlet_manager/policy_version.rb#L10-L14", "partition": "valid"} {"repo": "gouravtiwari/akamai-cloudlet-manager", "path": "lib/akamai_cloudlet_manager/policy_version.rb", "func_name": "AkamaiCloudletManager.PolicyVersion.create", "original_string": "def create(clone_from_version_id)\n request = Net::HTTP::Post.new(\n URI.join(\n @base_uri.to_s,\n \"cloudlets/api/v2/policies/#{@policy_id}/versions?includeRules=false&matchRuleFormat=1.0&cloneVersion=#{clone_from_version_id}\"\n ).to_s,\n { 'Content-Type' => 'application/json'}\n )\n response = @http_host.request(request)\n response.body\n end", "language": "ruby", "code": "def create(clone_from_version_id)\n request = Net::HTTP::Post.new(\n URI.join(\n @base_uri.to_s,\n \"cloudlets/api/v2/policies/#{@policy_id}/versions?includeRules=false&matchRuleFormat=1.0&cloneVersion=#{clone_from_version_id}\"\n ).to_s,\n { 'Content-Type' => 'application/json'}\n )\n response = @http_host.request(request)\n response.body\n end", "code_tokens": ["def", "create", "(", "clone_from_version_id", ")", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "URI", ".", "join", "(", "@base_uri", ".", "to_s", ",", "\"cloudlets/api/v2/policies/#{@policy_id}/versions?includeRules=false&matchRuleFormat=1.0&cloneVersion=#{clone_from_version_id}\"", ")", ".", "to_s", ",", "{", "'Content-Type'", "=>", "'application/json'", "}", ")", "response", "=", "@http_host", ".", "request", "(", "request", ")", "response", ".", "body", "end"], "docstring": "Create a policy version", "docstring_tokens": ["Create", "a", "policy", "version"], "sha": "03ef8a19065bdd1998550071be07b872b643715a", "url": "https://github.com/gouravtiwari/akamai-cloudlet-manager/blob/03ef8a19065bdd1998550071be07b872b643715a/lib/akamai_cloudlet_manager/policy_version.rb#L28-L38", "partition": "valid"} {"repo": "gouravtiwari/akamai-cloudlet-manager", "path": "lib/akamai_cloudlet_manager/policy_version.rb", "func_name": "AkamaiCloudletManager.PolicyVersion.activate", "original_string": "def activate(network)\n request = Net::HTTP::Post.new(\n URI.join(\n @base_uri.to_s,\n \"/cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}/activations\"\n ).to_s,\n { 'Content-Type' => 'application/json'}\n )\n request.body = {\n \"network\": network\n }.to_json\n response = @http_host.request(request)\n response.body\n end", "language": "ruby", "code": "def activate(network)\n request = Net::HTTP::Post.new(\n URI.join(\n @base_uri.to_s,\n \"/cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}/activations\"\n ).to_s,\n { 'Content-Type' => 'application/json'}\n )\n request.body = {\n \"network\": network\n }.to_json\n response = @http_host.request(request)\n response.body\n end", "code_tokens": ["def", "activate", "(", "network", ")", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "URI", ".", "join", "(", "@base_uri", ".", "to_s", ",", "\"/cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}/activations\"", ")", ".", "to_s", ",", "{", "'Content-Type'", "=>", "'application/json'", "}", ")", "request", ".", "body", "=", "{", "\"network\"", ":", "network", "}", ".", "to_json", "response", "=", "@http_host", ".", "request", "(", "request", ")", "response", ".", "body", "end"], "docstring": "Activate a policy version", "docstring_tokens": ["Activate", "a", "policy", "version"], "sha": "03ef8a19065bdd1998550071be07b872b643715a", "url": "https://github.com/gouravtiwari/akamai-cloudlet-manager/blob/03ef8a19065bdd1998550071be07b872b643715a/lib/akamai_cloudlet_manager/policy_version.rb#L41-L54", "partition": "valid"} {"repo": "gouravtiwari/akamai-cloudlet-manager", "path": "lib/akamai_cloudlet_manager/policy_version.rb", "func_name": "AkamaiCloudletManager.PolicyVersion.update", "original_string": "def update(options = {}, existing_rules = [])\n\n request = Net::HTTP::Put.new(\n URI.join(@base_uri.to_s, \"cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}?omitRules=false&matchRuleFormat=1.0\").to_s,\n { 'Content-Type' => 'application/json'}\n )\n rules = generate_path_rules(options) + generate_cookie_rules(options) + existing_rules\n\n if rules.empty?\n puts \"No rules to apply, please check syntax\"\n return\n end\n\n request.body = {\n matchRules: rules\n }.to_json\n response = @http_host.request(request)\n response.body\n end", "language": "ruby", "code": "def update(options = {}, existing_rules = [])\n\n request = Net::HTTP::Put.new(\n URI.join(@base_uri.to_s, \"cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}?omitRules=false&matchRuleFormat=1.0\").to_s,\n { 'Content-Type' => 'application/json'}\n )\n rules = generate_path_rules(options) + generate_cookie_rules(options) + existing_rules\n\n if rules.empty?\n puts \"No rules to apply, please check syntax\"\n return\n end\n\n request.body = {\n matchRules: rules\n }.to_json\n response = @http_host.request(request)\n response.body\n end", "code_tokens": ["def", "update", "(", "options", "=", "{", "}", ",", "existing_rules", "=", "[", "]", ")", "request", "=", "Net", "::", "HTTP", "::", "Put", ".", "new", "(", "URI", ".", "join", "(", "@base_uri", ".", "to_s", ",", "\"cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}?omitRules=false&matchRuleFormat=1.0\"", ")", ".", "to_s", ",", "{", "'Content-Type'", "=>", "'application/json'", "}", ")", "rules", "=", "generate_path_rules", "(", "options", ")", "+", "generate_cookie_rules", "(", "options", ")", "+", "existing_rules", "if", "rules", ".", "empty?", "puts", "\"No rules to apply, please check syntax\"", "return", "end", "request", ".", "body", "=", "{", "matchRules", ":", "rules", "}", ".", "to_json", "response", "=", "@http_host", ".", "request", "(", "request", ")", "response", ".", "body", "end"], "docstring": "Update policy version, all rules", "docstring_tokens": ["Update", "policy", "version", "all", "rules"], "sha": "03ef8a19065bdd1998550071be07b872b643715a", "url": "https://github.com/gouravtiwari/akamai-cloudlet-manager/blob/03ef8a19065bdd1998550071be07b872b643715a/lib/akamai_cloudlet_manager/policy_version.rb#L66-L84", "partition": "valid"} {"repo": "gouravtiwari/akamai-cloudlet-manager", "path": "lib/akamai_cloudlet_manager/origin.rb", "func_name": "AkamaiCloudletManager.Origin.list", "original_string": "def list(type)\n request = Net::HTTP::Get.new URI.join(@base_uri.to_s, \"cloudlets/api/v2/origins?type=#{type}\").to_s\n response = @http_host.request(request)\n response.body\n end", "language": "ruby", "code": "def list(type)\n request = Net::HTTP::Get.new URI.join(@base_uri.to_s, \"cloudlets/api/v2/origins?type=#{type}\").to_s\n response = @http_host.request(request)\n response.body\n end", "code_tokens": ["def", "list", "(", "type", ")", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "URI", ".", "join", "(", "@base_uri", ".", "to_s", ",", "\"cloudlets/api/v2/origins?type=#{type}\"", ")", ".", "to_s", "response", "=", "@http_host", ".", "request", "(", "request", ")", "response", ".", "body", "end"], "docstring": "List cloudlet Origins\n @type this is origin type, e.g. APPLICATION_LOAD_BALANCER", "docstring_tokens": ["List", "cloudlet", "Origins"], "sha": "03ef8a19065bdd1998550071be07b872b643715a", "url": "https://github.com/gouravtiwari/akamai-cloudlet-manager/blob/03ef8a19065bdd1998550071be07b872b643715a/lib/akamai_cloudlet_manager/origin.rb#L5-L9", "partition": "valid"} {"repo": "LucasAndrad/InoxConverter", "path": "lib/inox_converter/converter.rb", "func_name": "InoxConverter.Converter.convert", "original_string": "def convert(valueToConvert, firstUnit, secondUnit)\n\t\t\t# First Step\n\t\t\tfinalValue = valueToConvert.round(10)\n\n\t\t\t# Second Step\n\t\t\tfirstUnitResultant = getInDictionary(firstUnit)\n\t\t\tif firstUnitResultant.nil? \n\t\t\t\traise NotImplementedError.new(\"#{firstUnit} isn't recognized by InoxConverter\") \n\t\t\tend\n\t\t\tfinalValue *= firstUnitResultant.round(10)\n\n\t\t\t# Third step\n\t\t\tsecondUnitResultant = getInDictionary(secondUnit)\n\t\t\tif secondUnitResultant.nil? \n\t\t\t\traise NotImplementedError.new(\"#{secondUnit} isn't recognized by InoxConverter\") \n\t\t\tend\n\t\t\tfinalValue /= secondUnitResultant.round(10)\n\n\t\t\t# Fourth step\n\t\t\treturn finalValue.round(10)\n\t\tend", "language": "ruby", "code": "def convert(valueToConvert, firstUnit, secondUnit)\n\t\t\t# First Step\n\t\t\tfinalValue = valueToConvert.round(10)\n\n\t\t\t# Second Step\n\t\t\tfirstUnitResultant = getInDictionary(firstUnit)\n\t\t\tif firstUnitResultant.nil? \n\t\t\t\traise NotImplementedError.new(\"#{firstUnit} isn't recognized by InoxConverter\") \n\t\t\tend\n\t\t\tfinalValue *= firstUnitResultant.round(10)\n\n\t\t\t# Third step\n\t\t\tsecondUnitResultant = getInDictionary(secondUnit)\n\t\t\tif secondUnitResultant.nil? \n\t\t\t\traise NotImplementedError.new(\"#{secondUnit} isn't recognized by InoxConverter\") \n\t\t\tend\n\t\t\tfinalValue /= secondUnitResultant.round(10)\n\n\t\t\t# Fourth step\n\t\t\treturn finalValue.round(10)\n\t\tend", "code_tokens": ["def", "convert", "(", "valueToConvert", ",", "firstUnit", ",", "secondUnit", ")", "# First Step", "finalValue", "=", "valueToConvert", ".", "round", "(", "10", ")", "# Second Step", "firstUnitResultant", "=", "getInDictionary", "(", "firstUnit", ")", "if", "firstUnitResultant", ".", "nil?", "raise", "NotImplementedError", ".", "new", "(", "\"#{firstUnit} isn't recognized by InoxConverter\"", ")", "end", "finalValue", "*=", "firstUnitResultant", ".", "round", "(", "10", ")", "# Third step", "secondUnitResultant", "=", "getInDictionary", "(", "secondUnit", ")", "if", "secondUnitResultant", ".", "nil?", "raise", "NotImplementedError", ".", "new", "(", "\"#{secondUnit} isn't recognized by InoxConverter\"", ")", "end", "finalValue", "/=", "secondUnitResultant", ".", "round", "(", "10", ")", "# Fourth step", "return", "finalValue", ".", "round", "(", "10", ")", "end"], "docstring": "Template to convert", "docstring_tokens": ["Template", "to", "convert"], "sha": "c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3", "url": "https://github.com/LucasAndrad/InoxConverter/blob/c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3/lib/inox_converter/converter.rb#L13-L33", "partition": "valid"} {"repo": "mmb/meme_captain", "path": "lib/meme_captain/caption.rb", "func_name": "MemeCaptain.Caption.wrap", "original_string": "def wrap(num_lines)\n cleaned = gsub(/\\s+/, ' ').strip\n\n chars_per_line = cleaned.size / num_lines.to_f\n\n lines = []\n cleaned.split.each do |word|\n if lines.empty?\n lines << word\n else\n if (lines[-1].size + 1 + word.size) <= chars_per_line ||\n lines.size >= num_lines\n lines[-1] << ' ' unless lines[-1].empty?\n lines[-1] << word\n else\n lines << word\n end\n end\n end\n\n Caption.new(lines.join(\"\\n\"))\n end", "language": "ruby", "code": "def wrap(num_lines)\n cleaned = gsub(/\\s+/, ' ').strip\n\n chars_per_line = cleaned.size / num_lines.to_f\n\n lines = []\n cleaned.split.each do |word|\n if lines.empty?\n lines << word\n else\n if (lines[-1].size + 1 + word.size) <= chars_per_line ||\n lines.size >= num_lines\n lines[-1] << ' ' unless lines[-1].empty?\n lines[-1] << word\n else\n lines << word\n end\n end\n end\n\n Caption.new(lines.join(\"\\n\"))\n end", "code_tokens": ["def", "wrap", "(", "num_lines", ")", "cleaned", "=", "gsub", "(", "/", "\\s", "/", ",", "' '", ")", ".", "strip", "chars_per_line", "=", "cleaned", ".", "size", "/", "num_lines", ".", "to_f", "lines", "=", "[", "]", "cleaned", ".", "split", ".", "each", "do", "|", "word", "|", "if", "lines", ".", "empty?", "lines", "<<", "word", "else", "if", "(", "lines", "[", "-", "1", "]", ".", "size", "+", "1", "+", "word", ".", "size", ")", "<=", "chars_per_line", "||", "lines", ".", "size", ">=", "num_lines", "lines", "[", "-", "1", "]", "<<", "' '", "unless", "lines", "[", "-", "1", "]", ".", "empty?", "lines", "[", "-", "1", "]", "<<", "word", "else", "lines", "<<", "word", "end", "end", "end", "Caption", ".", "new", "(", "lines", ".", "join", "(", "\"\\n\"", ")", ")", "end"], "docstring": "Wrap the string of into num_lines lines.", "docstring_tokens": ["Wrap", "the", "string", "of", "into", "num_lines", "lines", "."], "sha": "daa7ac8244916562378d37820dad21ee01b89d71", "url": "https://github.com/mmb/meme_captain/blob/daa7ac8244916562378d37820dad21ee01b89d71/lib/meme_captain/caption.rb#L25-L46", "partition": "valid"} {"repo": "LucasAndrad/InoxConverter", "path": "lib/inox_converter/api/api.rb", "func_name": "Api.Api.consume_api", "original_string": "def consume_api\n\t\t\t@dados = RestClient::Request.execute(method: :get, url: 'https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote')\n\t\t\thash_local = Hash.new\n\t\t\t@hash_local = Hash.from_xml(@dados)\n\t\tend", "language": "ruby", "code": "def consume_api\n\t\t\t@dados = RestClient::Request.execute(method: :get, url: 'https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote')\n\t\t\thash_local = Hash.new\n\t\t\t@hash_local = Hash.from_xml(@dados)\n\t\tend", "code_tokens": ["def", "consume_api", "@dados", "=", "RestClient", "::", "Request", ".", "execute", "(", "method", ":", ":get", ",", "url", ":", "'https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote'", ")", "hash_local", "=", "Hash", ".", "new", "@hash_local", "=", "Hash", ".", "from_xml", "(", "@dados", ")", "end"], "docstring": "Consuming yahoo finances api and transform in hash for ruby", "docstring_tokens": ["Consuming", "yahoo", "finances", "api", "and", "transform", "in", "hash", "for", "ruby"], "sha": "c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3", "url": "https://github.com/LucasAndrad/InoxConverter/blob/c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3/lib/inox_converter/api/api.rb#L10-L14", "partition": "valid"} {"repo": "LucasAndrad/InoxConverter", "path": "lib/inox_converter/api/api.rb", "func_name": "Api.Api.treat_data", "original_string": "def treat_data\n\t\t\t@hash_inter = Hash.new\n\t\t\t@hash = Hash.new\n\t\t\tif validate_api_return\n\t\t\t\t@hash_inter = @hash_local['list']['resources']['resource']\n\t\t\t\t@hash_inter.each do |cout|\n\t\t\t\t\tsimbol_string = cout['field'][0].to_s\n\t\t\t\t\tsimbol = simbol_string.split(\"/\")\n\t\t\t\t \t@hash[simbol[1]] = cout['field'][1].to_f\n\t\t \t\tend\n\t\t \telse\n \t\t\t\t@data = false\n \t\t\tend\t\n\t\tend", "language": "ruby", "code": "def treat_data\n\t\t\t@hash_inter = Hash.new\n\t\t\t@hash = Hash.new\n\t\t\tif validate_api_return\n\t\t\t\t@hash_inter = @hash_local['list']['resources']['resource']\n\t\t\t\t@hash_inter.each do |cout|\n\t\t\t\t\tsimbol_string = cout['field'][0].to_s\n\t\t\t\t\tsimbol = simbol_string.split(\"/\")\n\t\t\t\t \t@hash[simbol[1]] = cout['field'][1].to_f\n\t\t \t\tend\n\t\t \telse\n \t\t\t\t@data = false\n \t\t\tend\t\n\t\tend", "code_tokens": ["def", "treat_data", "@hash_inter", "=", "Hash", ".", "new", "@hash", "=", "Hash", ".", "new", "if", "validate_api_return", "@hash_inter", "=", "@hash_local", "[", "'list'", "]", "[", "'resources'", "]", "[", "'resource'", "]", "@hash_inter", ".", "each", "do", "|", "cout", "|", "simbol_string", "=", "cout", "[", "'field'", "]", "[", "0", "]", ".", "to_s", "simbol", "=", "simbol_string", ".", "split", "(", "\"/\"", ")", "@hash", "[", "simbol", "[", "1", "]", "]", "=", "cout", "[", "'field'", "]", "[", "1", "]", ".", "to_f", "end", "else", "@data", "=", "false", "end", "end"], "docstring": "Treating data in hash", "docstring_tokens": ["Treating", "data", "in", "hash"], "sha": "c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3", "url": "https://github.com/LucasAndrad/InoxConverter/blob/c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3/lib/inox_converter/api/api.rb#L17-L30", "partition": "valid"} {"repo": "LucasAndrad/InoxConverter", "path": "lib/inox_converter/api/api.rb", "func_name": "Api.Api.convert_currency", "original_string": "def convert_currency(valueToConvert, firstUnit, secondUnit)\n\t\t\tdictionary_api\n\t\t\tif validate_usd_unit(firstUnit) && validate_usd_unit(secondUnit)\n\t\t\t\treturn valueToConvert\n\t\t\telsif validate_usd_unit(firstUnit) && validate_usd_unit(secondUnit) == false\n\t\t\t\tif validate_currency_unit(secondUnit)\n\t\t\t\t\tfinalValue = valueToConvert * @hash[secondUnit]\n\t\t\t\t\treturn finalValue\n\t\t\t\telse\n\t\t\t\t\treturn 0\n\t\t\t\tend\n\t\t\telsif validate_usd_unit(firstUnit) == false && validate_usd_unit(secondUnit)\n\t\t\t\tif validate_currency_unit(firstUnit)\n\t\t\t\t\tfinalValue = valueToConvert / @hash[firstUnit]\n\t\t\t\t\treturn finalValue\n\t\t\t\telse\n\t\t\t\t\treturn 0\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tif data_validate_api(firstUnit, secondUnit)\n\t\t\t\t\tfinalValue = (valueToConvert / @hash[firstUnit]) * @hash[secondUnit]\n\t\t\t\t\treturn finalValue\n\t\t\t\telse\t \n\t\t\t\t\treturn 0\n\t\t\t\tend\n\t\t\tend\t\t\n\t\tend", "language": "ruby", "code": "def convert_currency(valueToConvert, firstUnit, secondUnit)\n\t\t\tdictionary_api\n\t\t\tif validate_usd_unit(firstUnit) && validate_usd_unit(secondUnit)\n\t\t\t\treturn valueToConvert\n\t\t\telsif validate_usd_unit(firstUnit) && validate_usd_unit(secondUnit) == false\n\t\t\t\tif validate_currency_unit(secondUnit)\n\t\t\t\t\tfinalValue = valueToConvert * @hash[secondUnit]\n\t\t\t\t\treturn finalValue\n\t\t\t\telse\n\t\t\t\t\treturn 0\n\t\t\t\tend\n\t\t\telsif validate_usd_unit(firstUnit) == false && validate_usd_unit(secondUnit)\n\t\t\t\tif validate_currency_unit(firstUnit)\n\t\t\t\t\tfinalValue = valueToConvert / @hash[firstUnit]\n\t\t\t\t\treturn finalValue\n\t\t\t\telse\n\t\t\t\t\treturn 0\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tif data_validate_api(firstUnit, secondUnit)\n\t\t\t\t\tfinalValue = (valueToConvert / @hash[firstUnit]) * @hash[secondUnit]\n\t\t\t\t\treturn finalValue\n\t\t\t\telse\t \n\t\t\t\t\treturn 0\n\t\t\t\tend\n\t\t\tend\t\t\n\t\tend", "code_tokens": ["def", "convert_currency", "(", "valueToConvert", ",", "firstUnit", ",", "secondUnit", ")", "dictionary_api", "if", "validate_usd_unit", "(", "firstUnit", ")", "&&", "validate_usd_unit", "(", "secondUnit", ")", "return", "valueToConvert", "elsif", "validate_usd_unit", "(", "firstUnit", ")", "&&", "validate_usd_unit", "(", "secondUnit", ")", "==", "false", "if", "validate_currency_unit", "(", "secondUnit", ")", "finalValue", "=", "valueToConvert", "*", "@hash", "[", "secondUnit", "]", "return", "finalValue", "else", "return", "0", "end", "elsif", "validate_usd_unit", "(", "firstUnit", ")", "==", "false", "&&", "validate_usd_unit", "(", "secondUnit", ")", "if", "validate_currency_unit", "(", "firstUnit", ")", "finalValue", "=", "valueToConvert", "/", "@hash", "[", "firstUnit", "]", "return", "finalValue", "else", "return", "0", "end", "else", "if", "data_validate_api", "(", "firstUnit", ",", "secondUnit", ")", "finalValue", "=", "(", "valueToConvert", "/", "@hash", "[", "firstUnit", "]", ")", "*", "@hash", "[", "secondUnit", "]", "return", "finalValue", "else", "return", "0", "end", "end", "end"], "docstring": "new metodo for convert currency", "docstring_tokens": ["new", "metodo", "for", "convert", "currency"], "sha": "c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3", "url": "https://github.com/LucasAndrad/InoxConverter/blob/c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3/lib/inox_converter/api/api.rb#L82-L108", "partition": "valid"} {"repo": "mynyml/holygrail", "path": "lib/holygrail.rb", "func_name": "HolyGrail.XhrProxy.request", "original_string": "def request(info, data=\"\")\n context.instance_eval do\n xhr(info[\"method\"].downcase, info[\"url\"], data)\n @response.body.to_s\n end\n end", "language": "ruby", "code": "def request(info, data=\"\")\n context.instance_eval do\n xhr(info[\"method\"].downcase, info[\"url\"], data)\n @response.body.to_s\n end\n end", "code_tokens": ["def", "request", "(", "info", ",", "data", "=", "\"\"", ")", "context", ".", "instance_eval", "do", "xhr", "(", "info", "[", "\"method\"", "]", ".", "downcase", ",", "info", "[", "\"url\"", "]", ",", "data", ")", "@response", ".", "body", ".", "to_s", "end", "end"], "docstring": "Surrogate ajax request", "docstring_tokens": ["Surrogate", "ajax", "request"], "sha": "0c6ef60f18c3e032c9bee74867b0e5a26028e05d", "url": "https://github.com/mynyml/holygrail/blob/0c6ef60f18c3e032c9bee74867b0e5a26028e05d/lib/holygrail.rb#L15-L20", "partition": "valid"} {"repo": "mynyml/holygrail", "path": "lib/holygrail.rb", "func_name": "HolyGrail.Extensions.js", "original_string": "def js(code)\n XhrProxy.context = self\n @__page ||= Harmony::Page.new(XHR_MOCK_SCRIPT + rewrite_script_paths(@response.body.to_s))\n Harmony::Page::Window::BASE_RUNTIME.wait\n @__page.execute_js(code)\n end", "language": "ruby", "code": "def js(code)\n XhrProxy.context = self\n @__page ||= Harmony::Page.new(XHR_MOCK_SCRIPT + rewrite_script_paths(@response.body.to_s))\n Harmony::Page::Window::BASE_RUNTIME.wait\n @__page.execute_js(code)\n end", "code_tokens": ["def", "js", "(", "code", ")", "XhrProxy", ".", "context", "=", "self", "@__page", "||=", "Harmony", "::", "Page", ".", "new", "(", "XHR_MOCK_SCRIPT", "+", "rewrite_script_paths", "(", "@response", ".", "body", ".", "to_s", ")", ")", "Harmony", "::", "Page", "::", "Window", "::", "BASE_RUNTIME", ".", "wait", "@__page", ".", "execute_js", "(", "code", ")", "end"], "docstring": "Execute javascript within the context of a view.\n\n @example\n\n class PeopleControllerTest < ActionController::TestCase\n get :index\n assert_equal 'People: index', js('document.title')\n end\n\n @param [String]\n code javascript code to evaluate\n\n @return [Object]\n value of last javascript statement, cast to an equivalent ruby object\n\n @raise [Johnson::Error]\n javascript code exception", "docstring_tokens": ["Execute", "javascript", "within", "the", "context", "of", "a", "view", "."], "sha": "0c6ef60f18c3e032c9bee74867b0e5a26028e05d", "url": "https://github.com/mynyml/holygrail/blob/0c6ef60f18c3e032c9bee74867b0e5a26028e05d/lib/holygrail.rb#L77-L82", "partition": "valid"} {"repo": "mmb/meme_captain", "path": "lib/meme_captain/draw.rb", "func_name": "MemeCaptain.Draw.calc_pointsize", "original_string": "def calc_pointsize(width, height, text, min_pointsize)\n current_pointsize = min_pointsize\n\n metrics = nil\n\n loop {\n self.pointsize = current_pointsize\n last_metrics = metrics\n metrics = get_multiline_type_metrics(text)\n\n if metrics.width + stroke_padding > width or\n metrics.height + stroke_padding > height\n if current_pointsize > min_pointsize\n current_pointsize -= 1\n metrics = last_metrics\n end\n break\n else\n current_pointsize += 1\n end\n }\n\n [current_pointsize, metrics]\n end", "language": "ruby", "code": "def calc_pointsize(width, height, text, min_pointsize)\n current_pointsize = min_pointsize\n\n metrics = nil\n\n loop {\n self.pointsize = current_pointsize\n last_metrics = metrics\n metrics = get_multiline_type_metrics(text)\n\n if metrics.width + stroke_padding > width or\n metrics.height + stroke_padding > height\n if current_pointsize > min_pointsize\n current_pointsize -= 1\n metrics = last_metrics\n end\n break\n else\n current_pointsize += 1\n end\n }\n\n [current_pointsize, metrics]\n end", "code_tokens": ["def", "calc_pointsize", "(", "width", ",", "height", ",", "text", ",", "min_pointsize", ")", "current_pointsize", "=", "min_pointsize", "metrics", "=", "nil", "loop", "{", "self", ".", "pointsize", "=", "current_pointsize", "last_metrics", "=", "metrics", "metrics", "=", "get_multiline_type_metrics", "(", "text", ")", "if", "metrics", ".", "width", "+", "stroke_padding", ">", "width", "or", "metrics", ".", "height", "+", "stroke_padding", ">", "height", "if", "current_pointsize", ">", "min_pointsize", "current_pointsize", "-=", "1", "metrics", "=", "last_metrics", "end", "break", "else", "current_pointsize", "+=", "1", "end", "}", "[", "current_pointsize", ",", "metrics", "]", "end"], "docstring": "Calculate the largest pointsize for text that will be in a width x\n height box.\n\n Return [pointsize, metrics] where pointsize is the largest pointsize and\n metrics is the RMagick multiline type metrics of the best fit.", "docstring_tokens": ["Calculate", "the", "largest", "pointsize", "for", "text", "that", "will", "be", "in", "a", "width", "x", "height", "box", "."], "sha": "daa7ac8244916562378d37820dad21ee01b89d71", "url": "https://github.com/mmb/meme_captain/blob/daa7ac8244916562378d37820dad21ee01b89d71/lib/meme_captain/draw.rb#L11-L34", "partition": "valid"} {"repo": "LucasAndrad/InoxConverter", "path": "lib/inox_converter/currency_adapter.rb", "func_name": "InoxConverter.CurrencyAdapter.convert", "original_string": "def convert(valueToConvert, firstUnit, secondUnit)\n \t\t@api = Api::Api.new\n \t\t@api.convert_currency(valueToConvert, firstUnit, secondUnit)\n\t\tend", "language": "ruby", "code": "def convert(valueToConvert, firstUnit, secondUnit)\n \t\t@api = Api::Api.new\n \t\t@api.convert_currency(valueToConvert, firstUnit, secondUnit)\n\t\tend", "code_tokens": ["def", "convert", "(", "valueToConvert", ",", "firstUnit", ",", "secondUnit", ")", "@api", "=", "Api", "::", "Api", ".", "new", "@api", ".", "convert_currency", "(", "valueToConvert", ",", "firstUnit", ",", "secondUnit", ")", "end"], "docstring": "subscrible of metod convert in adapter", "docstring_tokens": ["subscrible", "of", "metod", "convert", "in", "adapter"], "sha": "c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3", "url": "https://github.com/LucasAndrad/InoxConverter/blob/c7dd8ac2c6ee8f9447b6302ec7ba8b3a55d4e6a3/lib/inox_converter/currency_adapter.rb#L9-L12", "partition": "valid"} {"repo": "ordinaryzelig/entrez", "path": "lib/entrez/query_limit.rb", "func_name": "Entrez.QueryLimit.respect_query_limit", "original_string": "def respect_query_limit\n now = Time.now.to_f\n three_requests_ago = request_times[-3]\n request_times << now\n return unless three_requests_ago\n time_for_last_3_requeests = now - three_requests_ago\n enough_time_has_passed = time_for_last_3_requeests >= 1.0\n unless enough_time_has_passed\n sleep_time = 1 - time_for_last_3_requeests\n STDERR.puts \"sleeping #{sleep_time}\"\n sleep(sleep_time)\n end\n end", "language": "ruby", "code": "def respect_query_limit\n now = Time.now.to_f\n three_requests_ago = request_times[-3]\n request_times << now\n return unless three_requests_ago\n time_for_last_3_requeests = now - three_requests_ago\n enough_time_has_passed = time_for_last_3_requeests >= 1.0\n unless enough_time_has_passed\n sleep_time = 1 - time_for_last_3_requeests\n STDERR.puts \"sleeping #{sleep_time}\"\n sleep(sleep_time)\n end\n end", "code_tokens": ["def", "respect_query_limit", "now", "=", "Time", ".", "now", ".", "to_f", "three_requests_ago", "=", "request_times", "[", "-", "3", "]", "request_times", "<<", "now", "return", "unless", "three_requests_ago", "time_for_last_3_requeests", "=", "now", "-", "three_requests_ago", "enough_time_has_passed", "=", "time_for_last_3_requeests", ">=", "1.0", "unless", "enough_time_has_passed", "sleep_time", "=", "1", "-", "time_for_last_3_requeests", "STDERR", ".", "puts", "\"sleeping #{sleep_time}\"", "sleep", "(", "sleep_time", ")", "end", "end"], "docstring": "NCBI does not allow more than 3 requests per second.\n If the last 3 requests happened within the last 1 second,\n sleep for enough time to let a full 1 second pass before the next request.\n Add current time to queue.", "docstring_tokens": ["NCBI", "does", "not", "allow", "more", "than", "3", "requests", "per", "second", ".", "If", "the", "last", "3", "requests", "happened", "within", "the", "last", "1", "second", "sleep", "for", "enough", "time", "to", "let", "a", "full", "1", "second", "pass", "before", "the", "next", "request", ".", "Add", "current", "time", "to", "queue", "."], "sha": "cbed68ae3f432f476f5335910d6f04279acfdb1a", "url": "https://github.com/ordinaryzelig/entrez/blob/cbed68ae3f432f476f5335910d6f04279acfdb1a/lib/entrez/query_limit.rb#L10-L22", "partition": "valid"} {"repo": "govdelivery/jekyll-ramler", "path": "lib/utils.rb", "func_name": "Jekyll.RamlSchemaGenerator.insert_schemas", "original_string": "def insert_schemas(obj)\n if obj.is_a?(Array)\n obj.map!{|method| insert_schemas(method)}\n elsif obj.is_a?(Hash)\n @current_method = obj['method'] if obj.include?('method')\n \n obj.each { |k, v| obj[k] = insert_schemas(v)}\n\n if obj.include?('body')\n if obj['body'].fetch('application/x-www-form-urlencoded', {}).include?('formParameters')\n if insert_json_schema?(obj)\n insert_json_schema(obj, generate_json_schema(obj))\n end\n end\n end\n end\n\n obj\n end", "language": "ruby", "code": "def insert_schemas(obj)\n if obj.is_a?(Array)\n obj.map!{|method| insert_schemas(method)}\n elsif obj.is_a?(Hash)\n @current_method = obj['method'] if obj.include?('method')\n \n obj.each { |k, v| obj[k] = insert_schemas(v)}\n\n if obj.include?('body')\n if obj['body'].fetch('application/x-www-form-urlencoded', {}).include?('formParameters')\n if insert_json_schema?(obj)\n insert_json_schema(obj, generate_json_schema(obj))\n end\n end\n end\n end\n\n obj\n end", "code_tokens": ["def", "insert_schemas", "(", "obj", ")", "if", "obj", ".", "is_a?", "(", "Array", ")", "obj", ".", "map!", "{", "|", "method", "|", "insert_schemas", "(", "method", ")", "}", "elsif", "obj", ".", "is_a?", "(", "Hash", ")", "@current_method", "=", "obj", "[", "'method'", "]", "if", "obj", ".", "include?", "(", "'method'", ")", "obj", ".", "each", "{", "|", "k", ",", "v", "|", "obj", "[", "k", "]", "=", "insert_schemas", "(", "v", ")", "}", "if", "obj", ".", "include?", "(", "'body'", ")", "if", "obj", "[", "'body'", "]", ".", "fetch", "(", "'application/x-www-form-urlencoded'", ",", "{", "}", ")", ".", "include?", "(", "'formParameters'", ")", "if", "insert_json_schema?", "(", "obj", ")", "insert_json_schema", "(", "obj", ",", "generate_json_schema", "(", "obj", ")", ")", "end", "end", "end", "end", "obj", "end"], "docstring": "Creates a schema attribute sibling of any formParameter attribute found,\n based on the found formParameters attribute.\n\n Existing schema siblings of formParameter attributes are not modified.\n\n Modifys obj, and returns the modified obj", "docstring_tokens": ["Creates", "a", "schema", "attribute", "sibling", "of", "any", "formParameter", "attribute", "found", "based", "on", "the", "found", "formParameters", "attribute", "."], "sha": "8415d0d3a5a742fb88c47799326f0f470bc3d6fe", "url": "https://github.com/govdelivery/jekyll-ramler/blob/8415d0d3a5a742fb88c47799326f0f470bc3d6fe/lib/utils.rb#L39-L57", "partition": "valid"} {"repo": "brendanhay/amqp-subscribe-many", "path": "lib/messaging/client.rb", "func_name": "Messaging.Client.declare_exchange", "original_string": "def declare_exchange(channel, name, type, options = {})\n exchange =\n # Check if default options need to be supplied to a non-default delcaration\n if default_exchange?(name)\n channel.default_exchange\n else\n channel.send(type, name, options)\n end\n\n log.debug(\"Exchange #{exchange.name.inspect} declared\")\n\n exchange\n end", "language": "ruby", "code": "def declare_exchange(channel, name, type, options = {})\n exchange =\n # Check if default options need to be supplied to a non-default delcaration\n if default_exchange?(name)\n channel.default_exchange\n else\n channel.send(type, name, options)\n end\n\n log.debug(\"Exchange #{exchange.name.inspect} declared\")\n\n exchange\n end", "code_tokens": ["def", "declare_exchange", "(", "channel", ",", "name", ",", "type", ",", "options", "=", "{", "}", ")", "exchange", "=", "# Check if default options need to be supplied to a non-default delcaration", "if", "default_exchange?", "(", "name", ")", "channel", ".", "default_exchange", "else", "channel", ".", "send", "(", "type", ",", "name", ",", "options", ")", "end", "log", ".", "debug", "(", "\"Exchange #{exchange.name.inspect} declared\"", ")", "exchange", "end"], "docstring": "Declare an exchange on the specified channel.\n\n @param channel [AMQP::Channel]\n @param name [String]\n @param type [String]\n @param options [Hash]\n @return [AMQP::Exchange]\n @api public", "docstring_tokens": ["Declare", "an", "exchange", "on", "the", "specified", "channel", "."], "sha": "6832204579ae46c2bd8703977682750f21bdf74e", "url": "https://github.com/brendanhay/amqp-subscribe-many/blob/6832204579ae46c2bd8703977682750f21bdf74e/lib/messaging/client.rb#L91-L103", "partition": "valid"} {"repo": "brendanhay/amqp-subscribe-many", "path": "lib/messaging/client.rb", "func_name": "Messaging.Client.declare_queue", "original_string": "def declare_queue(channel, exchange, name, key, options = {})\n channel.queue(name, options) do |queue|\n # Check if additional bindings are needed\n unless default_exchange?(exchange.name)\n queue.bind(exchange, { :routing_key => key })\n end\n\n log.debug(\"Queue #{queue.name.inspect} bound to #{exchange.name.inspect}\")\n end\n end", "language": "ruby", "code": "def declare_queue(channel, exchange, name, key, options = {})\n channel.queue(name, options) do |queue|\n # Check if additional bindings are needed\n unless default_exchange?(exchange.name)\n queue.bind(exchange, { :routing_key => key })\n end\n\n log.debug(\"Queue #{queue.name.inspect} bound to #{exchange.name.inspect}\")\n end\n end", "code_tokens": ["def", "declare_queue", "(", "channel", ",", "exchange", ",", "name", ",", "key", ",", "options", "=", "{", "}", ")", "channel", ".", "queue", "(", "name", ",", "options", ")", "do", "|", "queue", "|", "# Check if additional bindings are needed", "unless", "default_exchange?", "(", "exchange", ".", "name", ")", "queue", ".", "bind", "(", "exchange", ",", "{", ":routing_key", "=>", "key", "}", ")", "end", "log", ".", "debug", "(", "\"Queue #{queue.name.inspect} bound to #{exchange.name.inspect}\"", ")", "end", "end"], "docstring": "Declare and bind a queue to the specified exchange via the\n supplied routing key.\n\n @param channel [AMQP::Channel]\n @param exchange [AMQP::Exchange]\n @param name [String]\n @param key [String]\n @param options [Hash]\n @return [AMQP::Queue]\n @api public", "docstring_tokens": ["Declare", "and", "bind", "a", "queue", "to", "the", "specified", "exchange", "via", "the", "supplied", "routing", "key", "."], "sha": "6832204579ae46c2bd8703977682750f21bdf74e", "url": "https://github.com/brendanhay/amqp-subscribe-many/blob/6832204579ae46c2bd8703977682750f21bdf74e/lib/messaging/client.rb#L115-L124", "partition": "valid"} {"repo": "brendanhay/amqp-subscribe-many", "path": "lib/messaging/client.rb", "func_name": "Messaging.Client.disconnect", "original_string": "def disconnect\n channels.each do |chan|\n chan.close\n end\n\n connections.each do |conn|\n conn.disconnect\n end\n end", "language": "ruby", "code": "def disconnect\n channels.each do |chan|\n chan.close\n end\n\n connections.each do |conn|\n conn.disconnect\n end\n end", "code_tokens": ["def", "disconnect", "channels", ".", "each", "do", "|", "chan", "|", "chan", ".", "close", "end", "connections", ".", "each", "do", "|", "conn", "|", "conn", ".", "disconnect", "end", "end"], "docstring": "Close all channels and then disconnect all the connections.\n\n @return []\n @api public", "docstring_tokens": ["Close", "all", "channels", "and", "then", "disconnect", "all", "the", "connections", "."], "sha": "6832204579ae46c2bd8703977682750f21bdf74e", "url": "https://github.com/brendanhay/amqp-subscribe-many/blob/6832204579ae46c2bd8703977682750f21bdf74e/lib/messaging/client.rb#L130-L138", "partition": "valid"} {"repo": "postmodern/env", "path": "lib/env/variables.rb", "func_name": "Env.Variables.home", "original_string": "def home\n # logic adapted from Gem.find_home.\n path = if (env['HOME'] || env['USERPROFILE'])\n env['HOME'] || env['USERPROFILE']\n elsif (env['HOMEDRIVE'] && env['HOMEPATH'])\n \"#{env['HOMEDRIVE']}#{env['HOMEPATH']}\"\n else\n begin\n File.expand_path('~')\n rescue\n if File::ALT_SEPARATOR\n 'C:/'\n else\n '/'\n end\n end\n end\n\n return Pathname.new(path)\n end", "language": "ruby", "code": "def home\n # logic adapted from Gem.find_home.\n path = if (env['HOME'] || env['USERPROFILE'])\n env['HOME'] || env['USERPROFILE']\n elsif (env['HOMEDRIVE'] && env['HOMEPATH'])\n \"#{env['HOMEDRIVE']}#{env['HOMEPATH']}\"\n else\n begin\n File.expand_path('~')\n rescue\n if File::ALT_SEPARATOR\n 'C:/'\n else\n '/'\n end\n end\n end\n\n return Pathname.new(path)\n end", "code_tokens": ["def", "home", "# logic adapted from Gem.find_home.", "path", "=", "if", "(", "env", "[", "'HOME'", "]", "||", "env", "[", "'USERPROFILE'", "]", ")", "env", "[", "'HOME'", "]", "||", "env", "[", "'USERPROFILE'", "]", "elsif", "(", "env", "[", "'HOMEDRIVE'", "]", "&&", "env", "[", "'HOMEPATH'", "]", ")", "\"#{env['HOMEDRIVE']}#{env['HOMEPATH']}\"", "else", "begin", "File", ".", "expand_path", "(", "'~'", ")", "rescue", "if", "File", "::", "ALT_SEPARATOR", "'C:/'", "else", "'/'", "end", "end", "end", "return", "Pathname", ".", "new", "(", "path", ")", "end"], "docstring": "The home directory.\n\n @return [Pathname]\n The path of the home directory.", "docstring_tokens": ["The", "home", "directory", "."], "sha": "f3c76e432320f6134c0e34d3906502290e0aa145", "url": "https://github.com/postmodern/env/blob/f3c76e432320f6134c0e34d3906502290e0aa145/lib/env/variables.rb#L69-L88", "partition": "valid"} {"repo": "postmodern/env", "path": "lib/env/variables.rb", "func_name": "Env.Variables.parse_paths", "original_string": "def parse_paths(paths)\n if paths\n paths.split(File::PATH_SEPARATOR).map do |path|\n Pathname.new(path)\n end\n else\n []\n end\n end", "language": "ruby", "code": "def parse_paths(paths)\n if paths\n paths.split(File::PATH_SEPARATOR).map do |path|\n Pathname.new(path)\n end\n else\n []\n end\n end", "code_tokens": ["def", "parse_paths", "(", "paths", ")", "if", "paths", "paths", ".", "split", "(", "File", "::", "PATH_SEPARATOR", ")", ".", "map", "do", "|", "path", "|", "Pathname", ".", "new", "(", "path", ")", "end", "else", "[", "]", "end", "end"], "docstring": "Parses a String containing multiple paths.\n\n @return [Array]\n The multiple paths.", "docstring_tokens": ["Parses", "a", "String", "containing", "multiple", "paths", "."], "sha": "f3c76e432320f6134c0e34d3906502290e0aa145", "url": "https://github.com/postmodern/env/blob/f3c76e432320f6134c0e34d3906502290e0aa145/lib/env/variables.rb#L206-L214", "partition": "valid"} {"repo": "sealink/timely", "path": "lib/timely/week_days.rb", "func_name": "Timely.WeekDays.weekdays_int", "original_string": "def weekdays_int\n int = 0\n WEEKDAY_KEYS.each.with_index do |day, index|\n int += 2 ** index if @weekdays[day]\n end\n int\n end", "language": "ruby", "code": "def weekdays_int\n int = 0\n WEEKDAY_KEYS.each.with_index do |day, index|\n int += 2 ** index if @weekdays[day]\n end\n int\n end", "code_tokens": ["def", "weekdays_int", "int", "=", "0", "WEEKDAY_KEYS", ".", "each", ".", "with_index", "do", "|", "day", ",", "index", "|", "int", "+=", "2", "**", "index", "if", "@weekdays", "[", "day", "]", "end", "int", "end"], "docstring": "7 bits encoded in decimal number\n 0th bit = Sunday, 6th bit = Saturday\n Value of 127 => all days are on", "docstring_tokens": ["7", "bits", "encoded", "in", "decimal", "number", "0th", "bit", "=", "Sunday", "6th", "bit", "=", "Saturday", "Value", "of", "127", "=", ">", "all", "days", "are", "on"], "sha": "39ad5164242d679a936ea4792c41562ba9f3e670", "url": "https://github.com/sealink/timely/blob/39ad5164242d679a936ea4792c41562ba9f3e670/lib/timely/week_days.rb#L116-L122", "partition": "valid"} {"repo": "sealink/timely", "path": "lib/timely/trackable_date_set.rb", "func_name": "Timely.TrackableDateSet.do_once", "original_string": "def do_once(action_name, opts={})\n return if action_applied?(action_name)\n result = yield\n\n job_done = opts[:job_done_when].blank? || opts[:job_done_when].call(result)\n apply_action(action_name) if job_done\n end", "language": "ruby", "code": "def do_once(action_name, opts={})\n return if action_applied?(action_name)\n result = yield\n\n job_done = opts[:job_done_when].blank? || opts[:job_done_when].call(result)\n apply_action(action_name) if job_done\n end", "code_tokens": ["def", "do_once", "(", "action_name", ",", "opts", "=", "{", "}", ")", "return", "if", "action_applied?", "(", "action_name", ")", "result", "=", "yield", "job_done", "=", "opts", "[", ":job_done_when", "]", ".", "blank?", "||", "opts", "[", ":job_done_when", "]", ".", "call", "(", "result", ")", "apply_action", "(", "action_name", ")", "if", "job_done", "end"], "docstring": "Do something once within this tracked period\n\n Will only consider job done when opts[:job_done] is true\n\n action_name => Name to track\n {:job_done_when} => Block to call, passed result of yield", "docstring_tokens": ["Do", "something", "once", "within", "this", "tracked", "period"], "sha": "39ad5164242d679a936ea4792c41562ba9f3e670", "url": "https://github.com/sealink/timely/blob/39ad5164242d679a936ea4792c41562ba9f3e670/lib/timely/trackable_date_set.rb#L115-L121", "partition": "valid"} {"repo": "govdelivery/jekyll-ramler", "path": "lib/raml-generate.rb", "func_name": "Jekyll.ResourcePage.add_schema_hashes", "original_string": "def add_schema_hashes(obj, key=nil)\n if obj.is_a?(Array)\n obj.map! { |method| add_schema_hashes(method) }\n elsif obj.is_a?(Hash)\n obj.each { |k, v| obj[k] = add_schema_hashes(v, k)}\n\n if obj.include?(\"schema\")\n \n case key\n when 'application/json'\n obj['schema_hash'] = JSON.parse(obj['schema'])\n\n refactor_object = lambda do |lam_obj|\n lam_obj['properties'].each do |name, param|\n param['displayName'] = name\n param['required'] = true if lam_obj.fetch('required', []).include?(name)\n\n if param.include?('example') and ['object', 'array'].include?(param['type'])\n param['example'] = JSON.pretty_generate(JSON.parse(param['example']))\n elsif param.include?('properties')\n param['properties'] = JSON.pretty_generate(param['properties'])\n elsif param.include?('items')\n param['items'] = JSON.pretty_generate(param['items'])\n end\n\n lam_obj['properties'][name] = param\n end\n lam_obj\n end\n\n if obj['schema_hash'].include?('properties')\n obj['schema_hash'] = refactor_object.call(obj['schema_hash'])\n end\n\n if obj['schema_hash'].include?('items') and obj['schema_hash']['items'].include?('properties')\n obj['schema_hash']['items'] = refactor_object.call(obj['schema_hash']['items'])\n end\n end\n end\n end\n\n obj\n end", "language": "ruby", "code": "def add_schema_hashes(obj, key=nil)\n if obj.is_a?(Array)\n obj.map! { |method| add_schema_hashes(method) }\n elsif obj.is_a?(Hash)\n obj.each { |k, v| obj[k] = add_schema_hashes(v, k)}\n\n if obj.include?(\"schema\")\n \n case key\n when 'application/json'\n obj['schema_hash'] = JSON.parse(obj['schema'])\n\n refactor_object = lambda do |lam_obj|\n lam_obj['properties'].each do |name, param|\n param['displayName'] = name\n param['required'] = true if lam_obj.fetch('required', []).include?(name)\n\n if param.include?('example') and ['object', 'array'].include?(param['type'])\n param['example'] = JSON.pretty_generate(JSON.parse(param['example']))\n elsif param.include?('properties')\n param['properties'] = JSON.pretty_generate(param['properties'])\n elsif param.include?('items')\n param['items'] = JSON.pretty_generate(param['items'])\n end\n\n lam_obj['properties'][name] = param\n end\n lam_obj\n end\n\n if obj['schema_hash'].include?('properties')\n obj['schema_hash'] = refactor_object.call(obj['schema_hash'])\n end\n\n if obj['schema_hash'].include?('items') and obj['schema_hash']['items'].include?('properties')\n obj['schema_hash']['items'] = refactor_object.call(obj['schema_hash']['items'])\n end\n end\n end\n end\n\n obj\n end", "code_tokens": ["def", "add_schema_hashes", "(", "obj", ",", "key", "=", "nil", ")", "if", "obj", ".", "is_a?", "(", "Array", ")", "obj", ".", "map!", "{", "|", "method", "|", "add_schema_hashes", "(", "method", ")", "}", "elsif", "obj", ".", "is_a?", "(", "Hash", ")", "obj", ".", "each", "{", "|", "k", ",", "v", "|", "obj", "[", "k", "]", "=", "add_schema_hashes", "(", "v", ",", "k", ")", "}", "if", "obj", ".", "include?", "(", "\"schema\"", ")", "case", "key", "when", "'application/json'", "obj", "[", "'schema_hash'", "]", "=", "JSON", ".", "parse", "(", "obj", "[", "'schema'", "]", ")", "refactor_object", "=", "lambda", "do", "|", "lam_obj", "|", "lam_obj", "[", "'properties'", "]", ".", "each", "do", "|", "name", ",", "param", "|", "param", "[", "'displayName'", "]", "=", "name", "param", "[", "'required'", "]", "=", "true", "if", "lam_obj", ".", "fetch", "(", "'required'", ",", "[", "]", ")", ".", "include?", "(", "name", ")", "if", "param", ".", "include?", "(", "'example'", ")", "and", "[", "'object'", ",", "'array'", "]", ".", "include?", "(", "param", "[", "'type'", "]", ")", "param", "[", "'example'", "]", "=", "JSON", ".", "pretty_generate", "(", "JSON", ".", "parse", "(", "param", "[", "'example'", "]", ")", ")", "elsif", "param", ".", "include?", "(", "'properties'", ")", "param", "[", "'properties'", "]", "=", "JSON", ".", "pretty_generate", "(", "param", "[", "'properties'", "]", ")", "elsif", "param", ".", "include?", "(", "'items'", ")", "param", "[", "'items'", "]", "=", "JSON", ".", "pretty_generate", "(", "param", "[", "'items'", "]", ")", "end", "lam_obj", "[", "'properties'", "]", "[", "name", "]", "=", "param", "end", "lam_obj", "end", "if", "obj", "[", "'schema_hash'", "]", ".", "include?", "(", "'properties'", ")", "obj", "[", "'schema_hash'", "]", "=", "refactor_object", ".", "call", "(", "obj", "[", "'schema_hash'", "]", ")", "end", "if", "obj", "[", "'schema_hash'", "]", ".", "include?", "(", "'items'", ")", "and", "obj", "[", "'schema_hash'", "]", "[", "'items'", "]", ".", "include?", "(", "'properties'", ")", "obj", "[", "'schema_hash'", "]", "[", "'items'", "]", "=", "refactor_object", ".", "call", "(", "obj", "[", "'schema_hash'", "]", "[", "'items'", "]", ")", "end", "end", "end", "end", "obj", "end"], "docstring": "Adds a 'schema_hash' attribute to bodies with 'schema', which allows for the generation of schema table views", "docstring_tokens": ["Adds", "a", "schema_hash", "attribute", "to", "bodies", "with", "schema", "which", "allows", "for", "the", "generation", "of", "schema", "table", "views"], "sha": "8415d0d3a5a742fb88c47799326f0f470bc3d6fe", "url": "https://github.com/govdelivery/jekyll-ramler/blob/8415d0d3a5a742fb88c47799326f0f470bc3d6fe/lib/raml-generate.rb#L154-L196", "partition": "valid"} {"repo": "sealink/timely", "path": "lib/timely/rails/extensions.rb", "func_name": "Timely.Extensions.weekdays_field", "original_string": "def weekdays_field(attribute, options={})\n db_field = options[:db_field] || attribute.to_s + '_bit_array'\n self.composed_of(attribute,\n :class_name => \"::Timely::WeekDays\",\n :mapping => [[db_field, 'weekdays_int']],\n :converter => Proc.new {|field| ::Timely::WeekDays.new(field)}\n )\n end", "language": "ruby", "code": "def weekdays_field(attribute, options={})\n db_field = options[:db_field] || attribute.to_s + '_bit_array'\n self.composed_of(attribute,\n :class_name => \"::Timely::WeekDays\",\n :mapping => [[db_field, 'weekdays_int']],\n :converter => Proc.new {|field| ::Timely::WeekDays.new(field)}\n )\n end", "code_tokens": ["def", "weekdays_field", "(", "attribute", ",", "options", "=", "{", "}", ")", "db_field", "=", "options", "[", ":db_field", "]", "||", "attribute", ".", "to_s", "+", "'_bit_array'", "self", ".", "composed_of", "(", "attribute", ",", ":class_name", "=>", "\"::Timely::WeekDays\"", ",", ":mapping", "=>", "[", "[", "db_field", ",", "'weekdays_int'", "]", "]", ",", ":converter", "=>", "Proc", ".", "new", "{", "|", "field", "|", "::", "Timely", "::", "WeekDays", ".", "new", "(", "field", ")", "}", ")", "end"], "docstring": "Add a WeekDays attribute\n\n By default it will use attribute_bit_array as db field, but this can\n be overridden by specifying :db_field => 'somthing_else'", "docstring_tokens": ["Add", "a", "WeekDays", "attribute"], "sha": "39ad5164242d679a936ea4792c41562ba9f3e670", "url": "https://github.com/sealink/timely/blob/39ad5164242d679a936ea4792c41562ba9f3e670/lib/timely/rails/extensions.rb#L7-L14", "partition": "valid"} {"repo": "MatthewChang/PaperTrailAudit", "path": "lib/paper_trail-audit.rb", "func_name": "PaperTrailAudit.Model.calculate_audit_for", "original_string": "def calculate_audit_for(param)\n #Gets all flattened attribute lists\n #objects are a hash of\n #{attributes: object attributes, whodunnit: paper_trail whodunnit which caused the object to be in this state}\n objects = [{attributes: self.attributes, whodunnit: self.paper_trail.originator},\n self.versions.map {|e| {attributes: YAML.load(e.object), whodunnit: e.paper_trail_originator} if e.object}.compact].flatten\n #rejecting objects with no update time, orders by the updated at times in ascending order\n objects = objects.select {|e| e[:attributes][\"updated_at\"]}.sort_by {|e| e[:attributes][\"updated_at\"]}\n result = []\n #Add the initial state if the first element has a value\n if(objects.count > 0 && !objects.first[:attributes][param.to_s].nil?)\n result << PaperTrailAudit::Change.new({old_value: nil,\n new_value: objects.first[:attributes][param.to_s],\n time: objects.first[:attributes][\"updated_at\"],\n whodunnit: objects.first[:whodunnit]\n })\n end\n objects.each_cons(2) do |a,b|\n if a[:attributes][param.to_s] != b[:attributes][param.to_s]\n result << PaperTrailAudit::Change.new({old_value: a[:attributes][param.to_s],\n new_value: b[:attributes][param.to_s],\n time: b[:attributes][\"updated_at\"],\n whodunnit: b[:whodunnit]\n })\n end\n end\n result\n end", "language": "ruby", "code": "def calculate_audit_for(param)\n #Gets all flattened attribute lists\n #objects are a hash of\n #{attributes: object attributes, whodunnit: paper_trail whodunnit which caused the object to be in this state}\n objects = [{attributes: self.attributes, whodunnit: self.paper_trail.originator},\n self.versions.map {|e| {attributes: YAML.load(e.object), whodunnit: e.paper_trail_originator} if e.object}.compact].flatten\n #rejecting objects with no update time, orders by the updated at times in ascending order\n objects = objects.select {|e| e[:attributes][\"updated_at\"]}.sort_by {|e| e[:attributes][\"updated_at\"]}\n result = []\n #Add the initial state if the first element has a value\n if(objects.count > 0 && !objects.first[:attributes][param.to_s].nil?)\n result << PaperTrailAudit::Change.new({old_value: nil,\n new_value: objects.first[:attributes][param.to_s],\n time: objects.first[:attributes][\"updated_at\"],\n whodunnit: objects.first[:whodunnit]\n })\n end\n objects.each_cons(2) do |a,b|\n if a[:attributes][param.to_s] != b[:attributes][param.to_s]\n result << PaperTrailAudit::Change.new({old_value: a[:attributes][param.to_s],\n new_value: b[:attributes][param.to_s],\n time: b[:attributes][\"updated_at\"],\n whodunnit: b[:whodunnit]\n })\n end\n end\n result\n end", "code_tokens": ["def", "calculate_audit_for", "(", "param", ")", "#Gets all flattened attribute lists", "#objects are a hash of", "#{attributes: object attributes, whodunnit: paper_trail whodunnit which caused the object to be in this state}", "objects", "=", "[", "{", "attributes", ":", "self", ".", "attributes", ",", "whodunnit", ":", "self", ".", "paper_trail", ".", "originator", "}", ",", "self", ".", "versions", ".", "map", "{", "|", "e", "|", "{", "attributes", ":", "YAML", ".", "load", "(", "e", ".", "object", ")", ",", "whodunnit", ":", "e", ".", "paper_trail_originator", "}", "if", "e", ".", "object", "}", ".", "compact", "]", ".", "flatten", "#rejecting objects with no update time, orders by the updated at times in ascending order", "objects", "=", "objects", ".", "select", "{", "|", "e", "|", "e", "[", ":attributes", "]", "[", "\"updated_at\"", "]", "}", ".", "sort_by", "{", "|", "e", "|", "e", "[", ":attributes", "]", "[", "\"updated_at\"", "]", "}", "result", "=", "[", "]", "#Add the initial state if the first element has a value", "if", "(", "objects", ".", "count", ">", "0", "&&", "!", "objects", ".", "first", "[", ":attributes", "]", "[", "param", ".", "to_s", "]", ".", "nil?", ")", "result", "<<", "PaperTrailAudit", "::", "Change", ".", "new", "(", "{", "old_value", ":", "nil", ",", "new_value", ":", "objects", ".", "first", "[", ":attributes", "]", "[", "param", ".", "to_s", "]", ",", "time", ":", "objects", ".", "first", "[", ":attributes", "]", "[", "\"updated_at\"", "]", ",", "whodunnit", ":", "objects", ".", "first", "[", ":whodunnit", "]", "}", ")", "end", "objects", ".", "each_cons", "(", "2", ")", "do", "|", "a", ",", "b", "|", "if", "a", "[", ":attributes", "]", "[", "param", ".", "to_s", "]", "!=", "b", "[", ":attributes", "]", "[", "param", ".", "to_s", "]", "result", "<<", "PaperTrailAudit", "::", "Change", ".", "new", "(", "{", "old_value", ":", "a", "[", ":attributes", "]", "[", "param", ".", "to_s", "]", ",", "new_value", ":", "b", "[", ":attributes", "]", "[", "param", ".", "to_s", "]", ",", "time", ":", "b", "[", ":attributes", "]", "[", "\"updated_at\"", "]", ",", "whodunnit", ":", "b", "[", ":whodunnit", "]", "}", ")", "end", "end", "result", "end"], "docstring": "Returns the audit list for the specified column\n\n @param [symbol] param: symbol to query\n @return [array of Change objects]", "docstring_tokens": ["Returns", "the", "audit", "list", "for", "the", "specified", "column"], "sha": "e8c7de44f2a7f227f8d3880ae657e91df4357c7e", "url": "https://github.com/MatthewChang/PaperTrailAudit/blob/e8c7de44f2a7f227f8d3880ae657e91df4357c7e/lib/paper_trail-audit.rb#L14-L41", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/analyzer.rb", "func_name": "Sycsvpro.Analyzer.result", "original_string": "def result\n rows = File.readlines(file)\n\n result = Result.new\n unless rows.empty?\n row_number = 0\n row_number += 1 while rows[row_number].chomp.empty?\n\n result.cols = rows[row_number].chomp.split(';')\n result.col_count = result.cols.size\n\n row_number += 1\n row_number += 1 while rows[row_number].chomp.empty?\n\n result.row_count = rows.size - 1\n result.sample_row = rows[row_number].chomp\n end\n\n result\n end", "language": "ruby", "code": "def result\n rows = File.readlines(file)\n\n result = Result.new\n unless rows.empty?\n row_number = 0\n row_number += 1 while rows[row_number].chomp.empty?\n\n result.cols = rows[row_number].chomp.split(';')\n result.col_count = result.cols.size\n\n row_number += 1\n row_number += 1 while rows[row_number].chomp.empty?\n\n result.row_count = rows.size - 1\n result.sample_row = rows[row_number].chomp\n end\n\n result\n end", "code_tokens": ["def", "result", "rows", "=", "File", ".", "readlines", "(", "file", ")", "result", "=", "Result", ".", "new", "unless", "rows", ".", "empty?", "row_number", "=", "0", "row_number", "+=", "1", "while", "rows", "[", "row_number", "]", ".", "chomp", ".", "empty?", "result", ".", "cols", "=", "rows", "[", "row_number", "]", ".", "chomp", ".", "split", "(", "';'", ")", "result", ".", "col_count", "=", "result", ".", "cols", ".", "size", "row_number", "+=", "1", "row_number", "+=", "1", "while", "rows", "[", "row_number", "]", ".", "chomp", ".", "empty?", "result", ".", "row_count", "=", "rows", ".", "size", "-", "1", "result", ".", "sample_row", "=", "rows", "[", "row_number", "]", ".", "chomp", "end", "result", "end"], "docstring": "Creates a new analyzer\n Analyzes the file and returns the result", "docstring_tokens": ["Creates", "a", "new", "analyzer", "Analyzes", "the", "file", "and", "returns", "the", "result"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/analyzer.rb#L33-L52", "partition": "valid"} {"repo": "caruby/tissue", "path": "examples/galena/lib/galena/seed.rb", "func_name": "Galena.Seed.populate", "original_string": "def populate\n galena = CaTissue::Institution.new(:name => 'Galena University')\n\n addr = CaTissue::Address.new(\n :city => 'Galena', :state => 'Illinois', :country => 'United States', :zipCode => '37544',\n :street => '411 Basin St', :phoneNumber => '311-555-5555')\n\n dept = CaTissue::Department.new(:name => 'Pathology')\n\n crg = CaTissue::CancerResearchGroup.new(:name => 'Don Thomas Cancer Center')\n\n coord = CaTissue::User.new(\n :email_address => 'corey.nator@galena.edu',\n :last_name => 'Nator', :first_name => 'Corey', :address => addr.copy,\n :institution => galena, :department => dept, :cancer_research_group => crg)\n\n @hospital = CaTissue::Site.new(\n :site_type => CaTissue::Site::SiteType::COLLECTION, :name => 'Galena Hospital', \n :address => addr.copy, :coordinator => coord)\n\n @tissue_bank = CaTissue::Site.new(\n :site_type => CaTissue::Site::SiteType::REPOSITORY, :name => 'Galena Tissue Bank', \n :address => addr.copy, :coordinator => coord)\n\n pi = CaTissue::User.new(\n :email_address => 'vesta.gator@galena.edu',\n :last_name => 'Gator', :first_name => 'Vesta', :address => addr.copy,\n :institution => galena, :department => dept, :cancer_research_group => crg)\n\n @surgeon = CaTissue::User.new(\n :email_address => 'serge.on@galena.edu',\n :first_name => 'Serge', :last_name => 'On', :address => addr.copy,\n :institution => galena, :department => dept, :cancer_research_group => crg)\n\n @protocol = CaTissue::CollectionProtocol.new(:title => 'Galena Migration', \n :principal_investigator => pi, :sites => [@tissue_bank])\n\n # CPE has default 1.0 event point and label\n cpe = CaTissue::CollectionProtocolEvent.new(\n :collection_protocol => @protocol,\n :event_point => 1.0\n )\n \n # The sole specimen requirement. Setting the requirement collection_event attribute to a CPE automatically\n # sets the CPE requirement inverse attribute in caRuby.\n CaTissue::TissueSpecimenRequirement.new(:collection_event => cpe, :specimen_type => 'Fixed Tissue')\n\n # the storage container type hierarchy\n @freezer_type = CaTissue::StorageType.new(\n :name => 'Galena Freezer',\n :columns => 10, :rows => 1,\n :column_label => 'Rack'\n )\n rack_type = CaTissue::StorageType.new(:name => 'Galena Rack', :columns => 10, :rows => 10)\n @box_type = CaTissue::StorageType.new(:name => 'Galena Box', :columns => 10, :rows => 10)\n @freezer_type << rack_type\n rack_type << @box_type\n @box_type << 'Tissue'\n \n # the example tissue box\n @box = @box_type.new_container(:name => 'Galena Box 1')\n end", "language": "ruby", "code": "def populate\n galena = CaTissue::Institution.new(:name => 'Galena University')\n\n addr = CaTissue::Address.new(\n :city => 'Galena', :state => 'Illinois', :country => 'United States', :zipCode => '37544',\n :street => '411 Basin St', :phoneNumber => '311-555-5555')\n\n dept = CaTissue::Department.new(:name => 'Pathology')\n\n crg = CaTissue::CancerResearchGroup.new(:name => 'Don Thomas Cancer Center')\n\n coord = CaTissue::User.new(\n :email_address => 'corey.nator@galena.edu',\n :last_name => 'Nator', :first_name => 'Corey', :address => addr.copy,\n :institution => galena, :department => dept, :cancer_research_group => crg)\n\n @hospital = CaTissue::Site.new(\n :site_type => CaTissue::Site::SiteType::COLLECTION, :name => 'Galena Hospital', \n :address => addr.copy, :coordinator => coord)\n\n @tissue_bank = CaTissue::Site.new(\n :site_type => CaTissue::Site::SiteType::REPOSITORY, :name => 'Galena Tissue Bank', \n :address => addr.copy, :coordinator => coord)\n\n pi = CaTissue::User.new(\n :email_address => 'vesta.gator@galena.edu',\n :last_name => 'Gator', :first_name => 'Vesta', :address => addr.copy,\n :institution => galena, :department => dept, :cancer_research_group => crg)\n\n @surgeon = CaTissue::User.new(\n :email_address => 'serge.on@galena.edu',\n :first_name => 'Serge', :last_name => 'On', :address => addr.copy,\n :institution => galena, :department => dept, :cancer_research_group => crg)\n\n @protocol = CaTissue::CollectionProtocol.new(:title => 'Galena Migration', \n :principal_investigator => pi, :sites => [@tissue_bank])\n\n # CPE has default 1.0 event point and label\n cpe = CaTissue::CollectionProtocolEvent.new(\n :collection_protocol => @protocol,\n :event_point => 1.0\n )\n \n # The sole specimen requirement. Setting the requirement collection_event attribute to a CPE automatically\n # sets the CPE requirement inverse attribute in caRuby.\n CaTissue::TissueSpecimenRequirement.new(:collection_event => cpe, :specimen_type => 'Fixed Tissue')\n\n # the storage container type hierarchy\n @freezer_type = CaTissue::StorageType.new(\n :name => 'Galena Freezer',\n :columns => 10, :rows => 1,\n :column_label => 'Rack'\n )\n rack_type = CaTissue::StorageType.new(:name => 'Galena Rack', :columns => 10, :rows => 10)\n @box_type = CaTissue::StorageType.new(:name => 'Galena Box', :columns => 10, :rows => 10)\n @freezer_type << rack_type\n rack_type << @box_type\n @box_type << 'Tissue'\n \n # the example tissue box\n @box = @box_type.new_container(:name => 'Galena Box 1')\n end", "code_tokens": ["def", "populate", "galena", "=", "CaTissue", "::", "Institution", ".", "new", "(", ":name", "=>", "'Galena University'", ")", "addr", "=", "CaTissue", "::", "Address", ".", "new", "(", ":city", "=>", "'Galena'", ",", ":state", "=>", "'Illinois'", ",", ":country", "=>", "'United States'", ",", ":zipCode", "=>", "'37544'", ",", ":street", "=>", "'411 Basin St'", ",", ":phoneNumber", "=>", "'311-555-5555'", ")", "dept", "=", "CaTissue", "::", "Department", ".", "new", "(", ":name", "=>", "'Pathology'", ")", "crg", "=", "CaTissue", "::", "CancerResearchGroup", ".", "new", "(", ":name", "=>", "'Don Thomas Cancer Center'", ")", "coord", "=", "CaTissue", "::", "User", ".", "new", "(", ":email_address", "=>", "'corey.nator@galena.edu'", ",", ":last_name", "=>", "'Nator'", ",", ":first_name", "=>", "'Corey'", ",", ":address", "=>", "addr", ".", "copy", ",", ":institution", "=>", "galena", ",", ":department", "=>", "dept", ",", ":cancer_research_group", "=>", "crg", ")", "@hospital", "=", "CaTissue", "::", "Site", ".", "new", "(", ":site_type", "=>", "CaTissue", "::", "Site", "::", "SiteType", "::", "COLLECTION", ",", ":name", "=>", "'Galena Hospital'", ",", ":address", "=>", "addr", ".", "copy", ",", ":coordinator", "=>", "coord", ")", "@tissue_bank", "=", "CaTissue", "::", "Site", ".", "new", "(", ":site_type", "=>", "CaTissue", "::", "Site", "::", "SiteType", "::", "REPOSITORY", ",", ":name", "=>", "'Galena Tissue Bank'", ",", ":address", "=>", "addr", ".", "copy", ",", ":coordinator", "=>", "coord", ")", "pi", "=", "CaTissue", "::", "User", ".", "new", "(", ":email_address", "=>", "'vesta.gator@galena.edu'", ",", ":last_name", "=>", "'Gator'", ",", ":first_name", "=>", "'Vesta'", ",", ":address", "=>", "addr", ".", "copy", ",", ":institution", "=>", "galena", ",", ":department", "=>", "dept", ",", ":cancer_research_group", "=>", "crg", ")", "@surgeon", "=", "CaTissue", "::", "User", ".", "new", "(", ":email_address", "=>", "'serge.on@galena.edu'", ",", ":first_name", "=>", "'Serge'", ",", ":last_name", "=>", "'On'", ",", ":address", "=>", "addr", ".", "copy", ",", ":institution", "=>", "galena", ",", ":department", "=>", "dept", ",", ":cancer_research_group", "=>", "crg", ")", "@protocol", "=", "CaTissue", "::", "CollectionProtocol", ".", "new", "(", ":title", "=>", "'Galena Migration'", ",", ":principal_investigator", "=>", "pi", ",", ":sites", "=>", "[", "@tissue_bank", "]", ")", "# CPE has default 1.0 event point and label", "cpe", "=", "CaTissue", "::", "CollectionProtocolEvent", ".", "new", "(", ":collection_protocol", "=>", "@protocol", ",", ":event_point", "=>", "1.0", ")", "# The sole specimen requirement. Setting the requirement collection_event attribute to a CPE automatically", "# sets the CPE requirement inverse attribute in caRuby.", "CaTissue", "::", "TissueSpecimenRequirement", ".", "new", "(", ":collection_event", "=>", "cpe", ",", ":specimen_type", "=>", "'Fixed Tissue'", ")", "# the storage container type hierarchy", "@freezer_type", "=", "CaTissue", "::", "StorageType", ".", "new", "(", ":name", "=>", "'Galena Freezer'", ",", ":columns", "=>", "10", ",", ":rows", "=>", "1", ",", ":column_label", "=>", "'Rack'", ")", "rack_type", "=", "CaTissue", "::", "StorageType", ".", "new", "(", ":name", "=>", "'Galena Rack'", ",", ":columns", "=>", "10", ",", ":rows", "=>", "10", ")", "@box_type", "=", "CaTissue", "::", "StorageType", ".", "new", "(", ":name", "=>", "'Galena Box'", ",", ":columns", "=>", "10", ",", ":rows", "=>", "10", ")", "@freezer_type", "<<", "rack_type", "rack_type", "<<", "@box_type", "@box_type", "<<", "'Tissue'", "# the example tissue box", "@box", "=", "@box_type", ".", "new_container", "(", ":name", "=>", "'Galena Box 1'", ")", "end"], "docstring": "Sets the Galena example Defaults attributes to new objects.", "docstring_tokens": ["Sets", "the", "Galena", "example", "Defaults", "attributes", "to", "new", "objects", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/examples/galena/lib/galena/seed.rb#L60-L121", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/script_list.rb", "func_name": "Sycsvpro.ScriptList.execute", "original_string": "def execute\n scripts = Dir.glob(File.join(@script_dir, @script_file))\n scripts.each do |script|\n list[script] = []\n if show_methods\n list[script] = retrieve_methods(script)\n end\n end\n list\n end", "language": "ruby", "code": "def execute\n scripts = Dir.glob(File.join(@script_dir, @script_file))\n scripts.each do |script|\n list[script] = []\n if show_methods\n list[script] = retrieve_methods(script)\n end\n end\n list\n end", "code_tokens": ["def", "execute", "scripts", "=", "Dir", ".", "glob", "(", "File", ".", "join", "(", "@script_dir", ",", "@script_file", ")", ")", "scripts", ".", "each", "do", "|", "script", "|", "list", "[", "script", "]", "=", "[", "]", "if", "show_methods", "list", "[", "script", "]", "=", "retrieve_methods", "(", "script", ")", "end", "end", "list", "end"], "docstring": "Creates a new ScriptList. Takes params script_dir, script_file and show_methods\n Retrieves the information about scripts and methods from the script directory", "docstring_tokens": ["Creates", "a", "new", "ScriptList", ".", "Takes", "params", "script_dir", "script_file", "and", "show_methods", "Retrieves", "the", "information", "about", "scripts", "and", "methods", "from", "the", "script", "directory"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/script_list.rb#L31-L40", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/script_list.rb", "func_name": "Sycsvpro.ScriptList.retrieve_methods", "original_string": "def retrieve_methods(script)\n code = File.read(script)\n methods = code.scan(/((#.*\\s)*def.*\\s|def.*\\s)/)\n result = []\n methods.each do |method|\n result << method[0]\n end\n result\n end", "language": "ruby", "code": "def retrieve_methods(script)\n code = File.read(script)\n methods = code.scan(/((#.*\\s)*def.*\\s|def.*\\s)/)\n result = []\n methods.each do |method|\n result << method[0]\n end\n result\n end", "code_tokens": ["def", "retrieve_methods", "(", "script", ")", "code", "=", "File", ".", "read", "(", "script", ")", "methods", "=", "code", ".", "scan", "(", "/", "\\s", "\\s", "\\s", "/", ")", "result", "=", "[", "]", "methods", ".", "each", "do", "|", "method", "|", "result", "<<", "method", "[", "0", "]", "end", "result", "end"], "docstring": "Retrieve the methods including comments if available", "docstring_tokens": ["Retrieve", "the", "methods", "including", "comments", "if", "available"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/script_list.rb#L45-L53", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/client.rb", "func_name": "Turntabler.Client.close", "original_string": "def close(allow_reconnect = false)\n if @connection\n # Disable reconnects if specified\n reconnect = @reconnect\n @reconnect = reconnect && allow_reconnect\n\n # Clean up timers / connections\n @keepalive_timer.cancel if @keepalive_timer\n @keepalive_timer = nil\n @connection.close\n\n # Revert change to reconnect config once the final signal is received\n wait do |&resume|\n on(:session_ended, :once => true) { resume.call }\n end\n @reconnect = reconnect\n end\n \n true\n end", "language": "ruby", "code": "def close(allow_reconnect = false)\n if @connection\n # Disable reconnects if specified\n reconnect = @reconnect\n @reconnect = reconnect && allow_reconnect\n\n # Clean up timers / connections\n @keepalive_timer.cancel if @keepalive_timer\n @keepalive_timer = nil\n @connection.close\n\n # Revert change to reconnect config once the final signal is received\n wait do |&resume|\n on(:session_ended, :once => true) { resume.call }\n end\n @reconnect = reconnect\n end\n \n true\n end", "code_tokens": ["def", "close", "(", "allow_reconnect", "=", "false", ")", "if", "@connection", "# Disable reconnects if specified", "reconnect", "=", "@reconnect", "@reconnect", "=", "reconnect", "&&", "allow_reconnect", "# Clean up timers / connections", "@keepalive_timer", ".", "cancel", "if", "@keepalive_timer", "@keepalive_timer", "=", "nil", "@connection", ".", "close", "# Revert change to reconnect config once the final signal is received", "wait", "do", "|", "&", "resume", "|", "on", "(", ":session_ended", ",", ":once", "=>", "true", ")", "{", "resume", ".", "call", "}", "end", "@reconnect", "=", "reconnect", "end", "true", "end"], "docstring": "Closes the current connection to Turntable if one was previously opened.\n\n @return [true]", "docstring_tokens": ["Closes", "the", "current", "connection", "to", "Turntable", "if", "one", "was", "previously", "opened", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L125-L144", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/client.rb", "func_name": "Turntabler.Client.api", "original_string": "def api(command, params = {})\n raise(ConnectionError, 'Connection is not open') unless @connection && @connection.connected?\n \n message_id = @connection.publish(params.merge(:api => command))\n\n # Wait until we get a response for the given message\n data = wait do |&resume|\n on(:response_received, :once => true, :if => {'msgid' => message_id}) {|data| resume.call(data)}\n end\n\n if data['success']\n data\n else\n error = data['error'] || data['err']\n raise APIError, \"Command \\\"#{command}\\\" failed with message: \\\"#{error}\\\"\"\n end\n end", "language": "ruby", "code": "def api(command, params = {})\n raise(ConnectionError, 'Connection is not open') unless @connection && @connection.connected?\n \n message_id = @connection.publish(params.merge(:api => command))\n\n # Wait until we get a response for the given message\n data = wait do |&resume|\n on(:response_received, :once => true, :if => {'msgid' => message_id}) {|data| resume.call(data)}\n end\n\n if data['success']\n data\n else\n error = data['error'] || data['err']\n raise APIError, \"Command \\\"#{command}\\\" failed with message: \\\"#{error}\\\"\"\n end\n end", "code_tokens": ["def", "api", "(", "command", ",", "params", "=", "{", "}", ")", "raise", "(", "ConnectionError", ",", "'Connection is not open'", ")", "unless", "@connection", "&&", "@connection", ".", "connected?", "message_id", "=", "@connection", ".", "publish", "(", "params", ".", "merge", "(", ":api", "=>", "command", ")", ")", "# Wait until we get a response for the given message", "data", "=", "wait", "do", "|", "&", "resume", "|", "on", "(", ":response_received", ",", ":once", "=>", "true", ",", ":if", "=>", "{", "'msgid'", "=>", "message_id", "}", ")", "{", "|", "data", "|", "resume", ".", "call", "(", "data", ")", "}", "end", "if", "data", "[", "'success'", "]", "data", "else", "error", "=", "data", "[", "'error'", "]", "||", "data", "[", "'err'", "]", "raise", "APIError", ",", "\"Command \\\"#{command}\\\" failed with message: \\\"#{error}\\\"\"", "end", "end"], "docstring": "Runs the given API command.\n\n @api private\n @param [String] command The name of the command to execute\n @param [Hash] params The parameters to pass into the command\n @return [Hash] The data returned from the Turntable service\n @raise [Turntabler::Error] if the connection is not open or the command fails to execute", "docstring_tokens": ["Runs", "the", "given", "API", "command", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L161-L177", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/client.rb", "func_name": "Turntabler.Client.on", "original_string": "def on(event, options = {}, &block)\n event = event.to_sym\n @event_handlers[event] ||= []\n @event_handlers[event] << Handler.new(event, options, &block)\n true\n end", "language": "ruby", "code": "def on(event, options = {}, &block)\n event = event.to_sym\n @event_handlers[event] ||= []\n @event_handlers[event] << Handler.new(event, options, &block)\n true\n end", "code_tokens": ["def", "on", "(", "event", ",", "options", "=", "{", "}", ",", "&", "block", ")", "event", "=", "event", ".", "to_sym", "@event_handlers", "[", "event", "]", "||=", "[", "]", "@event_handlers", "[", "event", "]", "<<", "Handler", ".", "new", "(", "event", ",", "options", ",", "block", ")", "true", "end"], "docstring": "Registers a handler to invoke when an event occurs in Turntable.\n\n @param [Symbol] event The event to register a handler for\n @param [Hash] options The configuration options for the handler\n @option options [Hash] :if Specifies a set of key-value pairs that must be matched in the event data in order to run the handler\n @option options [Boolean] :once (false) Whether to only run the handler once\n @return [true]\n\n == Client Events\n\n * +:reconnected+ - The client reconnected (and re-entered any room that the user was previously in)\n\n @example\n client.on :reconnected do\n client.room.dj\n # ...\n end\n\n == Room Events\n\n * +:room_updated+ - Information about the room was updated\n * +:room_description_updated+ - The room's description was updated\n\n @example\n client.on :room_updated do |room| # Room\n puts room.description\n # ...\n end\n\n client.on :room_description_updated do |room| # Room\n puts room.description\n # ...\n end\n\n == User Events\n\n * +:user_entered+ - A user entered the room\n * +:user_left+ - A user left the room\n * +:user_booted+ - A user has been booted from the room\n * +:user_updated+ - A user's profile was updated\n * +:user_name_updated+ - A user's name was updated\n * +:user_avatar_updated+ - A user's avatar was updated\n * +:user_spoke+ - A user spoke in the chat room\n\n @example\n client.on :user_entered do |user| # User\n puts user.id\n # ...\n end\n\n client.on :user_left do |user| # User\n puts user.id\n # ...\n end\n\n client.on :user_booted do |boot| # Boot\n puts boot.user.id\n puts boot.reason\n # ...\n end\n\n client.on :user_updated do |user| # User\n puts user.name\n # ...\n end\n\n client.on :user_name_updated do |user| # User\n puts user.name\n # ...\n end\n\n client.on :user_avatar_updated do |user| # User\n puts user.avatar.id\n # ...\n end\n\n client.on :user_stickers_updated do |user| # User\n puts user.stickers.map {|sticker| sticker.id}\n # ...\n end\n\n client.on :user_spoke do |message| # Message\n puts message.content\n # ...\n end\n\n == DJ Events\n\n * +:fan_added+ - A new fan was added by a user in the room\n * +:fan_removed+ - A fan was removed from a user in the room\n\n @example\n client.on :fan_added do |user, fan_of| # User, User\n puts user.id\n # ...\n end\n\n client.on :fan_removed do |user, count| # User, Fixnum\n puts user.id\n # ...\n end\n\n == DJ Events\n\n * +:dj_added+ - A new DJ was added to the stage\n * +:dj_removed+ - A DJ was removed from the stage\n * +:dj_escorted_off+ - A DJ was escorted off the stage by a moderator\n * +:dj_booed_off+ - A DJ was booed off the stage\n\n @example\n client.on :dj_added do |user| # User\n puts user.id\n # ...\n end\n\n client.on :dj_removed do |user| # User\n puts user.id\n # ...\n end\n\n client.on :dj_escorted_off do |user, moderator| # User, User\n puts user.id\n # ...\n end\n\n client.on :dj_booed_off do |user| # User\n puts user.id\n # ...\n end\n\n == Moderator Events\n\n * +:moderator_added+ - A new moderator was added to the room\n * +:moderator_removed+ - A moderator was removed from the room\n\n @example\n client.on :moderator_added do |user| # User\n puts user.id\n # ...\n end\n\n client.on :moderator_removed do |user| # User\n puts user.id\n # ...\n end\n\n == Song Events\n\n * +:song_unavailable+ - Indicates that there are no more songs to play in the room\n * +:song_started+ - A new song has started playing\n * +:song_ended+ - The current song has ended. This is typically followed by a +:song_started+ or +:song_unavailable+ event.\n * +:song_voted+ - One or more votes were cast for the song\n * +:song_snagged+ - A user in the room has queued the current song onto their playlist\n * +:song_skipped+ - A song was skipped due to either the dj skipping it or too many downvotes\n * +:song_moderated+ - A song was forcefully skipped by a moderator\n * +:song_blocked+ - A song was prevented from playing due to a copyright claim\n\n @example\n client.on :song_unavailable do\n # ...\n end\n\n client.on :song_started do |song| # Song\n puts song.title\n # ...\n end\n\n client.on :song_ended do |song| # Song\n puts song.title\n # ...\n end\n\n client.on :song_voted do |song| # Song\n puts song.up_votes_count\n puts song.down_votes_count\n puts song.votes\n # ...\n end\n\n client.on :song_snagged do |snag| # Snag\n puts snag.user.id\n puts snag.song.id\n # ...\n end\n\n client.on :song_skipped do |song| # Song\n puts song.title\n # ...\n end\n\n client.on :song_moderated do |song, moderator| # Song, User\n puts song.title\n puts moderator.id\n # ...\n end\n\n client.on :song_blocked do |song| # Song\n puts song.id\n # ...\n end\n\n client.on :song_limited do |song| # Song\n puts song.id\n # ...\n end\n\n == Messaging Events\n\n * +:message_received+ - A private message was received from another user in the room\n\n @example\n client.on :message_received do |message| # Message\n puts message.content\n # ...\n end", "docstring_tokens": ["Registers", "a", "handler", "to", "invoke", "when", "an", "event", "occurs", "in", "Turntable", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L394-L399", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/client.rb", "func_name": "Turntabler.Client.user_by_name", "original_string": "def user_by_name(name)\n data = api('user.get_id', :name => name)\n user = self.user(data['userid'])\n user.attributes = {'name' => name}\n user\n end", "language": "ruby", "code": "def user_by_name(name)\n data = api('user.get_id', :name => name)\n user = self.user(data['userid'])\n user.attributes = {'name' => name}\n user\n end", "code_tokens": ["def", "user_by_name", "(", "name", ")", "data", "=", "api", "(", "'user.get_id'", ",", ":name", "=>", "name", ")", "user", "=", "self", ".", "user", "(", "data", "[", "'userid'", "]", ")", "user", ".", "attributes", "=", "{", "'name'", "=>", "name", "}", "user", "end"], "docstring": "Gets the user with the given DJ name. This should only be used if the id\n of the user is unknown.\n\n @param [String] name The user's DJ name\n @return [Turntabler::User]\n @raise [Turntabler::Error] if the command fails\n @example\n client.user_by_name('DJSpinster') # => #", "docstring_tokens": ["Gets", "the", "user", "with", "the", "given", "DJ", "name", ".", "This", "should", "only", "be", "used", "if", "the", "id", "of", "the", "user", "is", "unknown", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L433-L438", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/client.rb", "func_name": "Turntabler.Client.avatars", "original_string": "def avatars\n data = api('user.available_avatars')\n avatars = []\n data['avatars'].each do |avatar_group|\n avatar_group['avatarids'].each do |avatar_id|\n avatars << Avatar.new(self, :_id => avatar_id, :min => avatar_group['min'], :acl => avatar_group['acl'])\n end\n end\n avatars\n end", "language": "ruby", "code": "def avatars\n data = api('user.available_avatars')\n avatars = []\n data['avatars'].each do |avatar_group|\n avatar_group['avatarids'].each do |avatar_id|\n avatars << Avatar.new(self, :_id => avatar_id, :min => avatar_group['min'], :acl => avatar_group['acl'])\n end\n end\n avatars\n end", "code_tokens": ["def", "avatars", "data", "=", "api", "(", "'user.available_avatars'", ")", "avatars", "=", "[", "]", "data", "[", "'avatars'", "]", ".", "each", "do", "|", "avatar_group", "|", "avatar_group", "[", "'avatarids'", "]", ".", "each", "do", "|", "avatar_id", "|", "avatars", "<<", "Avatar", ".", "new", "(", "self", ",", ":_id", "=>", "avatar_id", ",", ":min", "=>", "avatar_group", "[", "'min'", "]", ",", ":acl", "=>", "avatar_group", "[", "'acl'", "]", ")", "end", "end", "avatars", "end"], "docstring": "Get all avatars availble on Turntable.\n\n @return [Array]\n @raise [Turntabler::Error] if the command fails\n @example\n client.avatars # => [#, ...]", "docstring_tokens": ["Get", "all", "avatars", "availble", "on", "Turntable", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L446-L455", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/client.rb", "func_name": "Turntabler.Client.search_song", "original_string": "def search_song(query, options = {})\n assert_valid_keys(options, :artist, :duration, :page)\n options = {:page => 1}.merge(options)\n\n raise(APIError, 'User must be in a room to search for songs') unless room\n\n if artist = options[:artist]\n query = \"title: #{query}\"\n query << \" artist: #{artist}\"\n end\n query << \" duration: #{options[:duration]}\" if options[:duration]\n\n api('file.search', :query => query, :page => options[:page])\n\n conditions = {'query' => query}\n\n # Time out if the response takes too long\n EventMachine.add_timer(@timeout) do\n trigger(:search_failed, conditions)\n end if @timeout\n\n # Wait for the async callback\n songs = wait do |&resume|\n on(:search_completed, :once => true, :if => conditions) {|songs| resume.call(songs)}\n on(:search_failed, :once => true, :if => conditions) { resume.call }\n end\n\n # Clean up any leftover handlers\n @event_handlers[:search_completed].delete_if {|handler| handler.conditions == conditions}\n @event_handlers[:search_failed].delete_if {|handler| handler.conditions == conditions}\n\n songs || raise(APIError, 'Search failed to complete')\n end", "language": "ruby", "code": "def search_song(query, options = {})\n assert_valid_keys(options, :artist, :duration, :page)\n options = {:page => 1}.merge(options)\n\n raise(APIError, 'User must be in a room to search for songs') unless room\n\n if artist = options[:artist]\n query = \"title: #{query}\"\n query << \" artist: #{artist}\"\n end\n query << \" duration: #{options[:duration]}\" if options[:duration]\n\n api('file.search', :query => query, :page => options[:page])\n\n conditions = {'query' => query}\n\n # Time out if the response takes too long\n EventMachine.add_timer(@timeout) do\n trigger(:search_failed, conditions)\n end if @timeout\n\n # Wait for the async callback\n songs = wait do |&resume|\n on(:search_completed, :once => true, :if => conditions) {|songs| resume.call(songs)}\n on(:search_failed, :once => true, :if => conditions) { resume.call }\n end\n\n # Clean up any leftover handlers\n @event_handlers[:search_completed].delete_if {|handler| handler.conditions == conditions}\n @event_handlers[:search_failed].delete_if {|handler| handler.conditions == conditions}\n\n songs || raise(APIError, 'Search failed to complete')\n end", "code_tokens": ["def", "search_song", "(", "query", ",", "options", "=", "{", "}", ")", "assert_valid_keys", "(", "options", ",", ":artist", ",", ":duration", ",", ":page", ")", "options", "=", "{", ":page", "=>", "1", "}", ".", "merge", "(", "options", ")", "raise", "(", "APIError", ",", "'User must be in a room to search for songs'", ")", "unless", "room", "if", "artist", "=", "options", "[", ":artist", "]", "query", "=", "\"title: #{query}\"", "query", "<<", "\" artist: #{artist}\"", "end", "query", "<<", "\" duration: #{options[:duration]}\"", "if", "options", "[", ":duration", "]", "api", "(", "'file.search'", ",", ":query", "=>", "query", ",", ":page", "=>", "options", "[", ":page", "]", ")", "conditions", "=", "{", "'query'", "=>", "query", "}", "# Time out if the response takes too long", "EventMachine", ".", "add_timer", "(", "@timeout", ")", "do", "trigger", "(", ":search_failed", ",", "conditions", ")", "end", "if", "@timeout", "# Wait for the async callback", "songs", "=", "wait", "do", "|", "&", "resume", "|", "on", "(", ":search_completed", ",", ":once", "=>", "true", ",", ":if", "=>", "conditions", ")", "{", "|", "songs", "|", "resume", ".", "call", "(", "songs", ")", "}", "on", "(", ":search_failed", ",", ":once", "=>", "true", ",", ":if", "=>", "conditions", ")", "{", "resume", ".", "call", "}", "end", "# Clean up any leftover handlers", "@event_handlers", "[", ":search_completed", "]", ".", "delete_if", "{", "|", "handler", "|", "handler", ".", "conditions", "==", "conditions", "}", "@event_handlers", "[", ":search_failed", "]", ".", "delete_if", "{", "|", "handler", "|", "handler", ".", "conditions", "==", "conditions", "}", "songs", "||", "raise", "(", "APIError", ",", "'Search failed to complete'", ")", "end"], "docstring": "Finds songs that match the given query.\n\n @note The user must be entered in a room to search for songs\n @param [String] query The query string to search for. This should just be the title of the song if :artist is specified.\n @param [Hash] options The configuration options for the search\n @option options [String] :artist The name of the artist for the song\n @option options [Fixnum] :duration The length, in minutes, of the song\n @option options [Fixnum] :page The page number to get from the results\n @return [Array]\n @raise [ArgumentError] if an invalid option is specified\n @raise [Turntabler::Error] if the user is not in a room or the command fails\n @example\n # Less accurate, general query search\n client.search_song('Like a Rolling Stone by Bob Dylan') # => [#, ...]\n\n # More accurate, explicit title / artist search\n client.search_song('Like a Rolling Stone', :artist => 'Bob Dylan') # => [#, ...]", "docstring_tokens": ["Finds", "songs", "that", "match", "the", "given", "query", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L495-L527", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/client.rb", "func_name": "Turntabler.Client.trigger", "original_string": "def trigger(command, *args)\n command = command.to_sym if command\n\n if Event.command?(command)\n event = Event.new(self, command, args)\n handlers = @event_handlers[event.name] || []\n handlers.each do |handler|\n success = handler.run(event)\n handlers.delete(handler) if success && handler.once\n end\n end\n\n true\n end", "language": "ruby", "code": "def trigger(command, *args)\n command = command.to_sym if command\n\n if Event.command?(command)\n event = Event.new(self, command, args)\n handlers = @event_handlers[event.name] || []\n handlers.each do |handler|\n success = handler.run(event)\n handlers.delete(handler) if success && handler.once\n end\n end\n\n true\n end", "code_tokens": ["def", "trigger", "(", "command", ",", "*", "args", ")", "command", "=", "command", ".", "to_sym", "if", "command", "if", "Event", ".", "command?", "(", "command", ")", "event", "=", "Event", ".", "new", "(", "self", ",", "command", ",", "args", ")", "handlers", "=", "@event_handlers", "[", "event", ".", "name", "]", "||", "[", "]", "handlers", ".", "each", "do", "|", "handler", "|", "success", "=", "handler", ".", "run", "(", "event", ")", "handlers", ".", "delete", "(", "handler", ")", "if", "success", "&&", "handler", ".", "once", "end", "end", "true", "end"], "docstring": "Triggers callback handlers for the given Turntable command. This should\n either be invoked when responses are received for Turntable or when\n triggering custom events.\n\n @note If the command is unknown, it will simply get skipped and not raise an exception\n @param [Symbol] command The name of the command triggered. This is typically the same name as the event.\n @param [Array] args The arguments to be processed by the event\n @return [true]\n\n == Triggering custom events\n\n After defining custom events, `trigger` can be used to invoke any handler\n that's been registered for that event. The argument list passed into\n `trigger` will be passed, exactly as specified, to the registered\n handlers.\n\n @example\n # Define names of events\n Turntabler.events(:no_args, :one_arg, :multiple_args)\n\n # ...\n\n # Register handlers\n client.on(:no_args) { }\n client.on(:one_arg) {|arg| }\n client.on(:multiple_args) {|arg1, arg2| }\n\n # Trigger handlers registered for events\n client.trigger(:no_args) # => true\n client.trigger(:one_arg, 1) # => true\n client.trigger(:multiple_args, 1, 2) # => true", "docstring_tokens": ["Triggers", "callback", "handlers", "for", "the", "given", "Turntable", "command", ".", "This", "should", "either", "be", "invoked", "when", "responses", "are", "received", "for", "Turntable", "or", "when", "triggering", "custom", "events", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L560-L573", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/client.rb", "func_name": "Turntabler.Client.reset_keepalive", "original_string": "def reset_keepalive(interval = 10)\n if !@keepalive_timer || @keepalive_interval != interval\n @keepalive_interval = interval\n\n # Periodically update the user's status to remain available\n @keepalive_timer.cancel if @keepalive_timer\n @keepalive_timer = EM::Synchrony.add_periodic_timer(interval) do\n Turntabler.run { user.update(:status => user.status) }\n end\n end\n end", "language": "ruby", "code": "def reset_keepalive(interval = 10)\n if !@keepalive_timer || @keepalive_interval != interval\n @keepalive_interval = interval\n\n # Periodically update the user's status to remain available\n @keepalive_timer.cancel if @keepalive_timer\n @keepalive_timer = EM::Synchrony.add_periodic_timer(interval) do\n Turntabler.run { user.update(:status => user.status) }\n end\n end\n end", "code_tokens": ["def", "reset_keepalive", "(", "interval", "=", "10", ")", "if", "!", "@keepalive_timer", "||", "@keepalive_interval", "!=", "interval", "@keepalive_interval", "=", "interval", "# Periodically update the user's status to remain available", "@keepalive_timer", ".", "cancel", "if", "@keepalive_timer", "@keepalive_timer", "=", "EM", "::", "Synchrony", ".", "add_periodic_timer", "(", "interval", ")", "do", "Turntabler", ".", "run", "{", "user", ".", "update", "(", ":status", "=>", "user", ".", "status", ")", "}", "end", "end", "end"], "docstring": "Resets the keepalive timer to run at the given interval.\n\n @param [Fixnum] interval The frequency with which keepalives get sent (in seconds)\n @api private", "docstring_tokens": ["Resets", "the", "keepalive", "timer", "to", "run", "at", "the", "given", "interval", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L579-L589", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/client.rb", "func_name": "Turntabler.Client.on_session_missing", "original_string": "def on_session_missing\n user.authenticate\n user.fan_of\n user.update(:status => user.status)\n reset_keepalive\n end", "language": "ruby", "code": "def on_session_missing\n user.authenticate\n user.fan_of\n user.update(:status => user.status)\n reset_keepalive\n end", "code_tokens": ["def", "on_session_missing", "user", ".", "authenticate", "user", ".", "fan_of", "user", ".", "update", "(", ":status", "=>", "user", ".", "status", ")", "reset_keepalive", "end"], "docstring": "Callback when session authentication is missing from the connection. This\n will automatically authenticate with configured user as well as set up a\n heartbeat.", "docstring_tokens": ["Callback", "when", "session", "authentication", "is", "missing", "from", "the", "connection", ".", "This", "will", "automatically", "authenticate", "with", "configured", "user", "as", "well", "as", "set", "up", "a", "heartbeat", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L601-L606", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/client.rb", "func_name": "Turntabler.Client.on_session_ended", "original_string": "def on_session_ended\n url = @connection.url\n room = @room\n @connection = nil\n @room = nil\n\n # Automatically reconnect to the room / server if allowed\n if @reconnect\n reconnect_from(Exception) do\n room ? room.enter : connect(url)\n trigger(:reconnected)\n end\n end\n end", "language": "ruby", "code": "def on_session_ended\n url = @connection.url\n room = @room\n @connection = nil\n @room = nil\n\n # Automatically reconnect to the room / server if allowed\n if @reconnect\n reconnect_from(Exception) do\n room ? room.enter : connect(url)\n trigger(:reconnected)\n end\n end\n end", "code_tokens": ["def", "on_session_ended", "url", "=", "@connection", ".", "url", "room", "=", "@room", "@connection", "=", "nil", "@room", "=", "nil", "# Automatically reconnect to the room / server if allowed", "if", "@reconnect", "reconnect_from", "(", "Exception", ")", "do", "room", "?", "room", ".", "enter", ":", "connect", "(", "url", ")", "trigger", "(", ":reconnected", ")", "end", "end", "end"], "docstring": "Callback when the session has ended. This will automatically reconnect if\n allowed to do so.", "docstring_tokens": ["Callback", "when", "the", "session", "has", "ended", ".", "This", "will", "automatically", "reconnect", "if", "allowed", "to", "do", "so", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L610-L623", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/client.rb", "func_name": "Turntabler.Client.reconnect_from", "original_string": "def reconnect_from(*exceptions)\n begin\n yield\n rescue *exceptions => ex\n if @reconnect\n logger.debug \"Connection failed: #{ex.message}\"\n EM::Synchrony.sleep(@reconnect_wait)\n logger.debug 'Attempting to reconnect'\n retry\n else\n raise\n end\n end\n end", "language": "ruby", "code": "def reconnect_from(*exceptions)\n begin\n yield\n rescue *exceptions => ex\n if @reconnect\n logger.debug \"Connection failed: #{ex.message}\"\n EM::Synchrony.sleep(@reconnect_wait)\n logger.debug 'Attempting to reconnect'\n retry\n else\n raise\n end\n end\n end", "code_tokens": ["def", "reconnect_from", "(", "*", "exceptions", ")", "begin", "yield", "rescue", "exceptions", "=>", "ex", "if", "@reconnect", "logger", ".", "debug", "\"Connection failed: #{ex.message}\"", "EM", "::", "Synchrony", ".", "sleep", "(", "@reconnect_wait", ")", "logger", ".", "debug", "'Attempting to reconnect'", "retry", "else", "raise", "end", "end", "end"], "docstring": "Runs a given block and retries that block after a certain period of time\n if any of the specified exceptions are raised. Note that there is no\n limit on the number of attempts to retry.", "docstring_tokens": ["Runs", "a", "given", "block", "and", "retries", "that", "block", "after", "a", "certain", "period", "of", "time", "if", "any", "of", "the", "specified", "exceptions", "are", "raised", ".", "Note", "that", "there", "is", "no", "limit", "on", "the", "number", "of", "attempts", "to", "retry", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L628-L641", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/client.rb", "func_name": "Turntabler.Client.wait", "original_string": "def wait(&block)\n fiber = Fiber.current\n\n # Resume the fiber when a response is received\n allow_resume = true\n block.call do |*args|\n fiber.resume(*args) if allow_resume\n end\n\n # Attempt to pause the fiber until a response is received\n begin\n Fiber.yield\n rescue FiberError => ex\n allow_resume = false\n raise Error, 'Turntabler APIs cannot be called from root fiber; use Turntabler.run { ... } instead'\n end\n end", "language": "ruby", "code": "def wait(&block)\n fiber = Fiber.current\n\n # Resume the fiber when a response is received\n allow_resume = true\n block.call do |*args|\n fiber.resume(*args) if allow_resume\n end\n\n # Attempt to pause the fiber until a response is received\n begin\n Fiber.yield\n rescue FiberError => ex\n allow_resume = false\n raise Error, 'Turntabler APIs cannot be called from root fiber; use Turntabler.run { ... } instead'\n end\n end", "code_tokens": ["def", "wait", "(", "&", "block", ")", "fiber", "=", "Fiber", ".", "current", "# Resume the fiber when a response is received", "allow_resume", "=", "true", "block", ".", "call", "do", "|", "*", "args", "|", "fiber", ".", "resume", "(", "args", ")", "if", "allow_resume", "end", "# Attempt to pause the fiber until a response is received", "begin", "Fiber", ".", "yield", "rescue", "FiberError", "=>", "ex", "allow_resume", "=", "false", "raise", "Error", ",", "'Turntabler APIs cannot be called from root fiber; use Turntabler.run { ... } instead'", "end", "end"], "docstring": "Pauses the current fiber until it is resumed with response data. This\n can only get resumed explicitly by the provided block.", "docstring_tokens": ["Pauses", "the", "current", "fiber", "until", "it", "is", "resumed", "with", "response", "data", ".", "This", "can", "only", "get", "resumed", "explicitly", "by", "the", "provided", "block", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/client.rb#L645-L661", "partition": "valid"} {"repo": "o2web/rails_admin_cms", "path": "app/presenters/viewable/page_presenter.rb", "func_name": "Viewable.PagePresenter.tree", "original_string": "def tree(root_depth: 1, sitemap: false, nav_class: 'tree')\n return if m.parent_at_depth(root_depth).nil?\n @sitemap = sitemap\n h.content_tag :nav, class: nav_class do\n h.concat render_tree_master_ul(m.parent_at_depth(root_depth))\n end\n end", "language": "ruby", "code": "def tree(root_depth: 1, sitemap: false, nav_class: 'tree')\n return if m.parent_at_depth(root_depth).nil?\n @sitemap = sitemap\n h.content_tag :nav, class: nav_class do\n h.concat render_tree_master_ul(m.parent_at_depth(root_depth))\n end\n end", "code_tokens": ["def", "tree", "(", "root_depth", ":", "1", ",", "sitemap", ":", "false", ",", "nav_class", ":", "'tree'", ")", "return", "if", "m", ".", "parent_at_depth", "(", "root_depth", ")", ".", "nil?", "@sitemap", "=", "sitemap", "h", ".", "content_tag", ":nav", ",", "class", ":", "nav_class", "do", "h", ".", "concat", "render_tree_master_ul", "(", "m", ".", "parent_at_depth", "(", "root_depth", ")", ")", "end", "end"], "docstring": "build page tree from specified root_depth, default second level root with sitemap property to render a sitemap from top root of current page", "docstring_tokens": ["build", "page", "tree", "from", "specified", "root_depth", "default", "second", "level", "root", "with", "sitemap", "property", "to", "render", "a", "sitemap", "from", "top", "root", "of", "current", "page"], "sha": "764197753a2beb80780a44c7f559ba2bc1bb429e", "url": "https://github.com/o2web/rails_admin_cms/blob/764197753a2beb80780a44c7f559ba2bc1bb429e/app/presenters/viewable/page_presenter.rb#L5-L11", "partition": "valid"} {"repo": "o2web/rails_admin_cms", "path": "app/presenters/viewable/page_presenter.rb", "func_name": "Viewable.PagePresenter.breadcrumbs", "original_string": "def breadcrumbs(root_depth: 0, last_page_title: nil, nav_class: 'breadcrumbs', div_class: 'scrollable')\n return if m.parent_at_depth(root_depth).nil?\n h.content_tag :nav, class: nav_class do\n h.concat h.content_tag(:div, breadcrumbs_ul(breadcrumbs_list(root_depth, last_page_title)), class: div_class)\n end\n end", "language": "ruby", "code": "def breadcrumbs(root_depth: 0, last_page_title: nil, nav_class: 'breadcrumbs', div_class: 'scrollable')\n return if m.parent_at_depth(root_depth).nil?\n h.content_tag :nav, class: nav_class do\n h.concat h.content_tag(:div, breadcrumbs_ul(breadcrumbs_list(root_depth, last_page_title)), class: div_class)\n end\n end", "code_tokens": ["def", "breadcrumbs", "(", "root_depth", ":", "0", ",", "last_page_title", ":", "nil", ",", "nav_class", ":", "'breadcrumbs'", ",", "div_class", ":", "'scrollable'", ")", "return", "if", "m", ".", "parent_at_depth", "(", "root_depth", ")", ".", "nil?", "h", ".", "content_tag", ":nav", ",", "class", ":", "nav_class", "do", "h", ".", "concat", "h", ".", "content_tag", "(", ":div", ",", "breadcrumbs_ul", "(", "breadcrumbs_list", "(", "root_depth", ",", "last_page_title", ")", ")", ",", "class", ":", "div_class", ")", "end", "end"], "docstring": "build page breadcrumbs from specified root_depth, default root", "docstring_tokens": ["build", "page", "breadcrumbs", "from", "specified", "root_depth", "default", "root"], "sha": "764197753a2beb80780a44c7f559ba2bc1bb429e", "url": "https://github.com/o2web/rails_admin_cms/blob/764197753a2beb80780a44c7f559ba2bc1bb429e/app/presenters/viewable/page_presenter.rb#L14-L19", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/resource.rb", "func_name": "CaTissue.Resource.tolerant_match?", "original_string": "def tolerant_match?(other, attributes)\n attributes.all? { |pa| Resource.tolerant_value_match?(send(pa), other.send(pa)) }\n end", "language": "ruby", "code": "def tolerant_match?(other, attributes)\n attributes.all? { |pa| Resource.tolerant_value_match?(send(pa), other.send(pa)) }\n end", "code_tokens": ["def", "tolerant_match?", "(", "other", ",", "attributes", ")", "attributes", ".", "all?", "{", "|", "pa", "|", "Resource", ".", "tolerant_value_match?", "(", "send", "(", "pa", ")", ",", "other", ".", "send", "(", "pa", ")", ")", "}", "end"], "docstring": "Returns whether each of the given attribute values either equals the\n respective other attribute value or one of the values is nil or 'Not Specified'.\n\n @param [Resource] other the domain object to compare\n @param [] attributes the attributes to compare\n @return [Boolean} whether this domain object is a tolerant match with the other\n domain object on the given attributes", "docstring_tokens": ["Returns", "whether", "each", "of", "the", "given", "attribute", "values", "either", "equals", "the", "respective", "other", "attribute", "value", "or", "one", "of", "the", "values", "is", "nil", "or", "Not", "Specified", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/resource.rb#L17-L19", "partition": "valid"} {"repo": "jonathanpike/mako", "path": "lib/mako/feed_constructor.rb", "func_name": "Mako.FeedConstructor.parse_and_create", "original_string": "def parse_and_create\n parsed_feed = parse_feed\n return false unless parsed_feed\n\n feed = create_feed(parsed_feed)\n create_articles(feed, parsed_feed)\n feed\n end", "language": "ruby", "code": "def parse_and_create\n parsed_feed = parse_feed\n return false unless parsed_feed\n\n feed = create_feed(parsed_feed)\n create_articles(feed, parsed_feed)\n feed\n end", "code_tokens": ["def", "parse_and_create", "parsed_feed", "=", "parse_feed", "return", "false", "unless", "parsed_feed", "feed", "=", "create_feed", "(", "parsed_feed", ")", "create_articles", "(", "feed", ",", "parsed_feed", ")", "feed", "end"], "docstring": "Parses raw XML feed and creates Feed and Article objects to\n be rendered. Returns false if feed cannot be parsed.\n\n @return [Feed]", "docstring_tokens": ["Parses", "raw", "XML", "feed", "and", "creates", "Feed", "and", "Article", "objects", "to", "be", "rendered", ".", "Returns", "false", "if", "feed", "cannot", "be", "parsed", "."], "sha": "2aa3665ebf23f09727e59d667b34155755493bdf", "url": "https://github.com/jonathanpike/mako/blob/2aa3665ebf23f09727e59d667b34155755493bdf/lib/mako/feed_constructor.rb#L16-L23", "partition": "valid"} {"repo": "jonathanpike/mako", "path": "lib/mako/feed_constructor.rb", "func_name": "Mako.FeedConstructor.entry_summary", "original_string": "def entry_summary(entry)\n !entry.content || entry.content.empty? ? entry.summary : entry.content\n end", "language": "ruby", "code": "def entry_summary(entry)\n !entry.content || entry.content.empty? ? entry.summary : entry.content\n end", "code_tokens": ["def", "entry_summary", "(", "entry", ")", "!", "entry", ".", "content", "||", "entry", ".", "content", ".", "empty?", "?", "entry", ".", "summary", ":", "entry", ".", "content", "end"], "docstring": "Some feeds use summary for the full article body, other feeds use content.\n This prefers content, but falls back to summary.\n\n @param [Feedjira::Feed]\n @return [String] an HTML string of the source article body", "docstring_tokens": ["Some", "feeds", "use", "summary", "for", "the", "full", "article", "body", "other", "feeds", "use", "content", ".", "This", "prefers", "content", "but", "falls", "back", "to", "summary", "."], "sha": "2aa3665ebf23f09727e59d667b34155755493bdf", "url": "https://github.com/jonathanpike/mako/blob/2aa3665ebf23f09727e59d667b34155755493bdf/lib/mako/feed_constructor.rb#L67-L69", "partition": "valid"} {"repo": "thefrontiergroup/scoped_attr_accessible", "path": "lib/scoped_attr_accessible/sanitizer.rb", "func_name": "ScopedAttrAccessible.Sanitizer.normalize_scope", "original_string": "def normalize_scope(object, context)\n return object if object.is_a?(Symbol)\n # 1. Process recognizers, looking for a match.\n @scope_recognizers.each_pair do |name, recognizers|\n return name if recognizers.any? { |r| lambda(&r).call(context, object) }\n end\n # 2. Process converters, finding a result.\n @scope_converters.each do |converter|\n scope = lambda(&converter).call(context, object)\n return normalize_scope(scope, converter) unless scope.nil?\n end\n # 3. Fall back to default\n return :default\n end", "language": "ruby", "code": "def normalize_scope(object, context)\n return object if object.is_a?(Symbol)\n # 1. Process recognizers, looking for a match.\n @scope_recognizers.each_pair do |name, recognizers|\n return name if recognizers.any? { |r| lambda(&r).call(context, object) }\n end\n # 2. Process converters, finding a result.\n @scope_converters.each do |converter|\n scope = lambda(&converter).call(context, object)\n return normalize_scope(scope, converter) unless scope.nil?\n end\n # 3. Fall back to default\n return :default\n end", "code_tokens": ["def", "normalize_scope", "(", "object", ",", "context", ")", "return", "object", "if", "object", ".", "is_a?", "(", "Symbol", ")", "# 1. Process recognizers, looking for a match.", "@scope_recognizers", ".", "each_pair", "do", "|", "name", ",", "recognizers", "|", "return", "name", "if", "recognizers", ".", "any?", "{", "|", "r", "|", "lambda", "(", "r", ")", ".", "call", "(", "context", ",", "object", ")", "}", "end", "# 2. Process converters, finding a result.", "@scope_converters", ".", "each", "do", "|", "converter", "|", "scope", "=", "lambda", "(", "converter", ")", ".", "call", "(", "context", ",", "object", ")", "return", "normalize_scope", "(", "scope", ",", "converter", ")", "unless", "scope", ".", "nil?", "end", "# 3. Fall back to default", "return", ":default", "end"], "docstring": "Looks up a scope name from the registered recognizers and then from the converters.", "docstring_tokens": ["Looks", "up", "a", "scope", "name", "from", "the", "registered", "recognizers", "and", "then", "from", "the", "converters", "."], "sha": "7f70825f8eb76be95f499045a0d27028d74f8321", "url": "https://github.com/thefrontiergroup/scoped_attr_accessible/blob/7f70825f8eb76be95f499045a0d27028d74f8321/lib/scoped_attr_accessible/sanitizer.rb#L16-L29", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/playlist_directory.rb", "func_name": "Turntabler.PlaylistDirectory.build", "original_string": "def build(attrs)\n playlist = Playlist.new(client, attrs)\n\n # Update existing in cache or cache a new playlist\n if existing = @playlists[playlist.id]\n playlist = existing\n playlist.attributes = attrs\n else\n @playlists[playlist.id] = playlist\n end\n\n playlist\n end", "language": "ruby", "code": "def build(attrs)\n playlist = Playlist.new(client, attrs)\n\n # Update existing in cache or cache a new playlist\n if existing = @playlists[playlist.id]\n playlist = existing\n playlist.attributes = attrs\n else\n @playlists[playlist.id] = playlist\n end\n\n playlist\n end", "code_tokens": ["def", "build", "(", "attrs", ")", "playlist", "=", "Playlist", ".", "new", "(", "client", ",", "attrs", ")", "# Update existing in cache or cache a new playlist", "if", "existing", "=", "@playlists", "[", "playlist", ".", "id", "]", "playlist", "=", "existing", "playlist", ".", "attributes", "=", "attrs", "else", "@playlists", "[", "playlist", ".", "id", "]", "=", "playlist", "end", "playlist", "end"], "docstring": "Gets the playlist represented by the given attributes.\n\n If the playlist hasn't been previously accessed, then a new Playlist\n instance will get created.\n\n @api private\n @param [Hash] attrs The attributes representing the playlist\n @return [Turntabler::Playlist]", "docstring_tokens": ["Gets", "the", "playlist", "represented", "by", "the", "given", "attributes", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/playlist_directory.rb#L47-L59", "partition": "valid"} {"repo": "weibel/MapKitWrapper", "path": "lib/map-kit-wrapper/zoom_level.rb", "func_name": "MapKit.ZoomLevel.set_center_coordinates", "original_string": "def set_center_coordinates(center_coordinate, zoom_level, animated = false)\n # clamp large numbers to 18\n zoom_level = [zoom_level, 18].min\n\n # use the zoom level to compute the region\n span = self.class.coordinate_span_with_map_view(self, center_coordinate, zoom_level)\n region = CoordinateRegion.new(center_coordinate, span)\n\n # set the region like normal\n self.setRegion(region.api, animated: animated)\n end", "language": "ruby", "code": "def set_center_coordinates(center_coordinate, zoom_level, animated = false)\n # clamp large numbers to 18\n zoom_level = [zoom_level, 18].min\n\n # use the zoom level to compute the region\n span = self.class.coordinate_span_with_map_view(self, center_coordinate, zoom_level)\n region = CoordinateRegion.new(center_coordinate, span)\n\n # set the region like normal\n self.setRegion(region.api, animated: animated)\n end", "code_tokens": ["def", "set_center_coordinates", "(", "center_coordinate", ",", "zoom_level", ",", "animated", "=", "false", ")", "# clamp large numbers to 18", "zoom_level", "=", "[", "zoom_level", ",", "18", "]", ".", "min", "# use the zoom level to compute the region", "span", "=", "self", ".", "class", ".", "coordinate_span_with_map_view", "(", "self", ",", "center_coordinate", ",", "zoom_level", ")", "region", "=", "CoordinateRegion", ".", "new", "(", "center_coordinate", ",", "span", ")", "# set the region like normal", "self", ".", "setRegion", "(", "region", ".", "api", ",", "animated", ":", "animated", ")", "end"], "docstring": "Set the views center coordinates with a given zoom level\n\n * *Args* :\n - +center_coordinate+ -> A MKMapPoint\n - +zoom_level+ -> Zoom level as Int\n - +animated+ -> bool", "docstring_tokens": ["Set", "the", "views", "center", "coordinates", "with", "a", "given", "zoom", "level"], "sha": "6ad3579b77e4d9be1c23ebab6a624a7dbc4ed2e6", "url": "https://github.com/weibel/MapKitWrapper/blob/6ad3579b77e4d9be1c23ebab6a624a7dbc4ed2e6/lib/map-kit-wrapper/zoom_level.rb#L121-L131", "partition": "valid"} {"repo": "weibel/MapKitWrapper", "path": "lib/map-kit-wrapper/zoom_level.rb", "func_name": "MapKit.ZoomLevel.set_map_lat_lon", "original_string": "def set_map_lat_lon(latitude, longitude, zoom_level, animated = false)\n coordinate = LocationCoordinate.new(latitude, longitude)\n set_center_coordinates(coordinate, zoom_level, animated)\n end", "language": "ruby", "code": "def set_map_lat_lon(latitude, longitude, zoom_level, animated = false)\n coordinate = LocationCoordinate.new(latitude, longitude)\n set_center_coordinates(coordinate, zoom_level, animated)\n end", "code_tokens": ["def", "set_map_lat_lon", "(", "latitude", ",", "longitude", ",", "zoom_level", ",", "animated", "=", "false", ")", "coordinate", "=", "LocationCoordinate", ".", "new", "(", "latitude", ",", "longitude", ")", "set_center_coordinates", "(", "coordinate", ",", "zoom_level", ",", "animated", ")", "end"], "docstring": "Set the views latitude and longitude with a given zoom level\n\n * *Args* :\n - +latitude+ -> Float\n - +longitude+ -> Float\n - +zoom_level+ -> Zoom level as Int\n - +animated+ -> bool", "docstring_tokens": ["Set", "the", "views", "latitude", "and", "longitude", "with", "a", "given", "zoom", "level"], "sha": "6ad3579b77e4d9be1c23ebab6a624a7dbc4ed2e6", "url": "https://github.com/weibel/MapKitWrapper/blob/6ad3579b77e4d9be1c23ebab6a624a7dbc4ed2e6/lib/map-kit-wrapper/zoom_level.rb#L142-L145", "partition": "valid"} {"repo": "weibel/MapKitWrapper", "path": "lib/map-kit-wrapper/zoom_level.rb", "func_name": "MapKit.ZoomLevel.zoom_level", "original_string": "def zoom_level\n region = self.region\n center_pixel = region.center.to_pixel_space\n top_left_pixel = (region.center - (region.span / 2)).to_pixel_space\n\n scaled_map_width = (center_pixel.x - top_left_pixel.x) * 2\n map_size_in_pixels = MapSize.new(self.bounds.size)\n\n zoom_scale = scaled_map_width / map_size_in_pixels.width\n zoom_exponent = log(zoom_scale) / log(2)\n 20 - zoom_exponent\n end", "language": "ruby", "code": "def zoom_level\n region = self.region\n center_pixel = region.center.to_pixel_space\n top_left_pixel = (region.center - (region.span / 2)).to_pixel_space\n\n scaled_map_width = (center_pixel.x - top_left_pixel.x) * 2\n map_size_in_pixels = MapSize.new(self.bounds.size)\n\n zoom_scale = scaled_map_width / map_size_in_pixels.width\n zoom_exponent = log(zoom_scale) / log(2)\n 20 - zoom_exponent\n end", "code_tokens": ["def", "zoom_level", "region", "=", "self", ".", "region", "center_pixel", "=", "region", ".", "center", ".", "to_pixel_space", "top_left_pixel", "=", "(", "region", ".", "center", "-", "(", "region", ".", "span", "/", "2", ")", ")", ".", "to_pixel_space", "scaled_map_width", "=", "(", "center_pixel", ".", "x", "-", "top_left_pixel", ".", "x", ")", "*", "2", "map_size_in_pixels", "=", "MapSize", ".", "new", "(", "self", ".", "bounds", ".", "size", ")", "zoom_scale", "=", "scaled_map_width", "/", "map_size_in_pixels", ".", "width", "zoom_exponent", "=", "log", "(", "zoom_scale", ")", "/", "log", "(", "2", ")", "20", "-", "zoom_exponent", "end"], "docstring": "Get the current zoom level\n\n * *Returns* :\n - Zoom level as a Float", "docstring_tokens": ["Get", "the", "current", "zoom", "level"], "sha": "6ad3579b77e4d9be1c23ebab6a624a7dbc4ed2e6", "url": "https://github.com/weibel/MapKitWrapper/blob/6ad3579b77e4d9be1c23ebab6a624a7dbc4ed2e6/lib/map-kit-wrapper/zoom_level.rb#L153-L164", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/transfer_event_parameters.rb", "func_name": "CaTissue.TransferEventParameters.from=", "original_string": "def from=(location)\n if location then\n self.from_container = location.container\n self.from_row = location.row\n self.from_column = location.column\n end\n location\n end", "language": "ruby", "code": "def from=(location)\n if location then\n self.from_container = location.container\n self.from_row = location.row\n self.from_column = location.column\n end\n location\n end", "code_tokens": ["def", "from", "=", "(", "location", ")", "if", "location", "then", "self", ".", "from_container", "=", "location", ".", "container", "self", ".", "from_row", "=", "location", ".", "row", "self", ".", "from_column", "=", "location", ".", "column", "end", "location", "end"], "docstring": "Sets the from Location.", "docstring_tokens": ["Sets", "the", "from", "Location", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/transfer_event_parameters.rb#L22-L29", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/transfer_event_parameters.rb", "func_name": "CaTissue.TransferEventParameters.to=", "original_string": "def to=(location)\n if location.nil? then raise ArgumentError.new(\"Specimen cannot be moved to an empty location\") end\n self.to_container = location.container\n self.to_row = location.row\n self.to_column = location.column\n end", "language": "ruby", "code": "def to=(location)\n if location.nil? then raise ArgumentError.new(\"Specimen cannot be moved to an empty location\") end\n self.to_container = location.container\n self.to_row = location.row\n self.to_column = location.column\n end", "code_tokens": ["def", "to", "=", "(", "location", ")", "if", "location", ".", "nil?", "then", "raise", "ArgumentError", ".", "new", "(", "\"Specimen cannot be moved to an empty location\"", ")", "end", "self", ".", "to_container", "=", "location", ".", "container", "self", ".", "to_row", "=", "location", ".", "row", "self", ".", "to_column", "=", "location", ".", "column", "end"], "docstring": "Sets the to Location.", "docstring_tokens": ["Sets", "the", "to", "Location", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/transfer_event_parameters.rb#L39-L44", "partition": "valid"} {"repo": "fastpeek/steamd", "path": "lib/steamd/cli_options.rb", "func_name": "Steamd.CliOptions.input", "original_string": "def input\n o = if @input.nil?\n Steamd.language_dir\n else\n @input\n end\n\n raise 'input must be a directory' unless File.directory?(o)\n File.expand_path(o)\n end", "language": "ruby", "code": "def input\n o = if @input.nil?\n Steamd.language_dir\n else\n @input\n end\n\n raise 'input must be a directory' unless File.directory?(o)\n File.expand_path(o)\n end", "code_tokens": ["def", "input", "o", "=", "if", "@input", ".", "nil?", "Steamd", ".", "language_dir", "else", "@input", "end", "raise", "'input must be a directory'", "unless", "File", ".", "directory?", "(", "o", ")", "File", ".", "expand_path", "(", "o", ")", "end"], "docstring": "Create a CliOptions object\n\n @example Using CliOptions\n opts = CliOptions.new(ouput: './')\n\n @param opts [Hash] options hash\n @option opts [String] :output the output directory\n @option opts [String] :input the output directory\n Returns the absolute path of the input directory specified by the\n cli.\n\n Throws an exception if the input is not a directory\n\n @example Getting the input path\n opts = CliOptions.new(input: '/some/dir')\n opts.input # => '/some/dir'", "docstring_tokens": ["Create", "a", "CliOptions", "object"], "sha": "8e66e78369ec735223995ea31a125b73541dfa3e", "url": "https://github.com/fastpeek/steamd/blob/8e66e78369ec735223995ea31a125b73541dfa3e/lib/steamd/cli_options.rb#L28-L37", "partition": "valid"} {"repo": "fastpeek/steamd", "path": "lib/steamd/cli_options.rb", "func_name": "Steamd.CliOptions.output", "original_string": "def output\n o = if @output.nil?\n './lib/steamd'\n else\n @output\n end\n\n raise 'output must be a directory' unless File.directory?(o)\n File.expand_path(o)\n end", "language": "ruby", "code": "def output\n o = if @output.nil?\n './lib/steamd'\n else\n @output\n end\n\n raise 'output must be a directory' unless File.directory?(o)\n File.expand_path(o)\n end", "code_tokens": ["def", "output", "o", "=", "if", "@output", ".", "nil?", "'./lib/steamd'", "else", "@output", "end", "raise", "'output must be a directory'", "unless", "File", ".", "directory?", "(", "o", ")", "File", ".", "expand_path", "(", "o", ")", "end"], "docstring": "Returns the absolute path of the output directory specified by the\n cli.\n\n Throws an exception if the output is not a directory\n\n @example Getting the output path\n opts = CliOptions.new(output: '/some/dir')\n opts.output # => '/some/dir'", "docstring_tokens": ["Returns", "the", "absolute", "path", "of", "the", "output", "directory", "specified", "by", "the", "cli", "."], "sha": "8e66e78369ec735223995ea31a125b73541dfa3e", "url": "https://github.com/fastpeek/steamd/blob/8e66e78369ec735223995ea31a125b73541dfa3e/lib/steamd/cli_options.rb#L47-L56", "partition": "valid"} {"repo": "danijoo/Sightstone", "path": "lib/sightstone/modules/game_module.rb", "func_name": "Sightstone.GameModule.recent", "original_string": "def recent(summoner, optional={})\n region = optional[:region] || @sightstone.region\n id = if summoner.is_a? Summoner\n summoner.id\n else\n summoner\n end\n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v1.3/game/by-summoner/#{id}/recent\"\n \n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n history = MatchHistory.new(data)\n if block_given?\n yield history\n else\n return history\n end\n }\n end", "language": "ruby", "code": "def recent(summoner, optional={})\n region = optional[:region] || @sightstone.region\n id = if summoner.is_a? Summoner\n summoner.id\n else\n summoner\n end\n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v1.3/game/by-summoner/#{id}/recent\"\n \n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n history = MatchHistory.new(data)\n if block_given?\n yield history\n else\n return history\n end\n }\n end", "code_tokens": ["def", "recent", "(", "summoner", ",", "optional", "=", "{", "}", ")", "region", "=", "optional", "[", ":region", "]", "||", "@sightstone", ".", "region", "id", "=", "if", "summoner", ".", "is_a?", "Summoner", "summoner", ".", "id", "else", "summoner", "end", "uri", "=", "\"https://prod.api.pvp.net/api/lol/#{region}/v1.3/game/by-summoner/#{id}/recent\"", "response", "=", "_get_api_response", "(", "uri", ")", "_parse_response", "(", "response", ")", "{", "|", "resp", "|", "data", "=", "JSON", ".", "parse", "(", "resp", ")", "history", "=", "MatchHistory", ".", "new", "(", "data", ")", "if", "block_given?", "yield", "history", "else", "return", "history", "end", "}", "end"], "docstring": "returns the match history of a summoner\n @param [Summoner, Fixnum] summoner summoner object or id of a summoner\n @param optional [Hash] optional arguments: :region => replaces default region\n @return [MatchHistory] match history of the summoner", "docstring_tokens": ["returns", "the", "match", "history", "of", "a", "summoner"], "sha": "4c6709916ce7552f622de1a120c021e067601b4d", "url": "https://github.com/danijoo/Sightstone/blob/4c6709916ce7552f622de1a120c021e067601b4d/lib/sightstone/modules/game_module.rb#L16-L35", "partition": "valid"} {"repo": "knuedge/cratus", "path": "lib/cratus/user.rb", "func_name": "Cratus.User.disable", "original_string": "def disable\n if enabled?\n Cratus::LDAP.replace_attribute(\n dn,\n Cratus.config.user_account_control_attribute,\n ['514']\n )\n refresh\n else\n true\n end\n end", "language": "ruby", "code": "def disable\n if enabled?\n Cratus::LDAP.replace_attribute(\n dn,\n Cratus.config.user_account_control_attribute,\n ['514']\n )\n refresh\n else\n true\n end\n end", "code_tokens": ["def", "disable", "if", "enabled?", "Cratus", "::", "LDAP", ".", "replace_attribute", "(", "dn", ",", "Cratus", ".", "config", ".", "user_account_control_attribute", ",", "[", "'514'", "]", ")", "refresh", "else", "true", "end", "end"], "docstring": "Disables an enabled user", "docstring_tokens": ["Disables", "an", "enabled", "user"], "sha": "a58465314a957db258f2c6bbda115c4be8ad0d83", "url": "https://github.com/knuedge/cratus/blob/a58465314a957db258f2c6bbda115c4be8ad0d83/lib/cratus/user.rb#L32-L43", "partition": "valid"} {"repo": "knuedge/cratus", "path": "lib/cratus/user.rb", "func_name": "Cratus.User.enable", "original_string": "def enable\n if disabled?\n Cratus::LDAP.replace_attribute(\n dn,\n Cratus.config.user_account_control_attribute,\n ['512']\n )\n refresh\n else\n true\n end\n end", "language": "ruby", "code": "def enable\n if disabled?\n Cratus::LDAP.replace_attribute(\n dn,\n Cratus.config.user_account_control_attribute,\n ['512']\n )\n refresh\n else\n true\n end\n end", "code_tokens": ["def", "enable", "if", "disabled?", "Cratus", "::", "LDAP", ".", "replace_attribute", "(", "dn", ",", "Cratus", ".", "config", ".", "user_account_control_attribute", ",", "[", "'512'", "]", ")", "refresh", "else", "true", "end", "end"], "docstring": "Enables a disabled user", "docstring_tokens": ["Enables", "a", "disabled", "user"], "sha": "a58465314a957db258f2c6bbda115c4be8ad0d83", "url": "https://github.com/knuedge/cratus/blob/a58465314a957db258f2c6bbda115c4be8ad0d83/lib/cratus/user.rb#L59-L70", "partition": "valid"} {"repo": "knuedge/cratus", "path": "lib/cratus/user.rb", "func_name": "Cratus.User.unlock", "original_string": "def unlock\n if locked? && enabled?\n Cratus::LDAP.replace_attribute(\n dn,\n Cratus.config.user_lockout_attribute,\n ['0']\n )\n refresh\n elsif disabled?\n false\n else\n true\n end\n end", "language": "ruby", "code": "def unlock\n if locked? && enabled?\n Cratus::LDAP.replace_attribute(\n dn,\n Cratus.config.user_lockout_attribute,\n ['0']\n )\n refresh\n elsif disabled?\n false\n else\n true\n end\n end", "code_tokens": ["def", "unlock", "if", "locked?", "&&", "enabled?", "Cratus", "::", "LDAP", ".", "replace_attribute", "(", "dn", ",", "Cratus", ".", "config", ".", "user_lockout_attribute", ",", "[", "'0'", "]", ")", "refresh", "elsif", "disabled?", "false", "else", "true", "end", "end"], "docstring": "Unlocks a user\n @return `true` on success (or if user is already unlocked)\n @return `false` when the account is disabled (unlocking not permitted)", "docstring_tokens": ["Unlocks", "a", "user"], "sha": "a58465314a957db258f2c6bbda115c4be8ad0d83", "url": "https://github.com/knuedge/cratus/blob/a58465314a957db258f2c6bbda115c4be8ad0d83/lib/cratus/user.rb#L138-L151", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/specimen_position.rb", "func_name": "CaTissue.SpecimenPosition.saver_proxy", "original_string": "def saver_proxy\n # Look for a transfer event that matches the position.\n xfr = specimen.event_parameters.detect do |sep|\n CaTissue::TransferEventParameters === sep and sep.to == location\n end\n # Create a new transfer event, if necessary.\n xfr ||= CaTissue::TransferEventParameters.new(:specimen => specimen, :to => location)\n # If this position changed, then copy the original position to the transfer event from attributes.\n if snapshot and changed? then\n xfr.from_storage_container = snapshot[:storage_container]\n xfr.from_position_dimension_one = snapshot[:position_dimension_one]\n xfr.from_position_dimension_two = snapshot[:position_dimension_two]\n end\n xfr\n end", "language": "ruby", "code": "def saver_proxy\n # Look for a transfer event that matches the position.\n xfr = specimen.event_parameters.detect do |sep|\n CaTissue::TransferEventParameters === sep and sep.to == location\n end\n # Create a new transfer event, if necessary.\n xfr ||= CaTissue::TransferEventParameters.new(:specimen => specimen, :to => location)\n # If this position changed, then copy the original position to the transfer event from attributes.\n if snapshot and changed? then\n xfr.from_storage_container = snapshot[:storage_container]\n xfr.from_position_dimension_one = snapshot[:position_dimension_one]\n xfr.from_position_dimension_two = snapshot[:position_dimension_two]\n end\n xfr\n end", "code_tokens": ["def", "saver_proxy", "# Look for a transfer event that matches the position.", "xfr", "=", "specimen", ".", "event_parameters", ".", "detect", "do", "|", "sep", "|", "CaTissue", "::", "TransferEventParameters", "===", "sep", "and", "sep", ".", "to", "==", "location", "end", "# Create a new transfer event, if necessary.", "xfr", "||=", "CaTissue", "::", "TransferEventParameters", ".", "new", "(", ":specimen", "=>", "specimen", ",", ":to", "=>", "location", ")", "# If this position changed, then copy the original position to the transfer event from attributes.", "if", "snapshot", "and", "changed?", "then", "xfr", ".", "from_storage_container", "=", "snapshot", "[", ":storage_container", "]", "xfr", ".", "from_position_dimension_one", "=", "snapshot", "[", ":position_dimension_one", "]", "xfr", ".", "from_position_dimension_two", "=", "snapshot", "[", ":position_dimension_two", "]", "end", "xfr", "end"], "docstring": "Returns a TransferEventParameters which serves as a proxy for saving this SpecimenPosition.\n\n @quirk caTissue caTissue does not allow saving a SpecimenPosition directly in the database.\n Creating a TransferEventParameters sets the SpecimenPosition as a side-effect. Therefore,\n SpecimenPosition save is accomplished by creating a proxy TransferEventParameters instead.", "docstring_tokens": ["Returns", "a", "TransferEventParameters", "which", "serves", "as", "a", "proxy", "for", "saving", "this", "SpecimenPosition", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/specimen_position.rb#L22-L36", "partition": "valid"} {"repo": "fastpeek/steamd", "path": "lib/steamd/code_generator.rb", "func_name": "Steamd.CodeGenerator.generate", "original_string": "def generate\n make_output_directory\n\n files.each do |file|\n File.write(\"#{@output}/#{File.basename(file, '.*')}.rb\",\n Steamd::Generator::Ruby.new(file).run)\n end\n end", "language": "ruby", "code": "def generate\n make_output_directory\n\n files.each do |file|\n File.write(\"#{@output}/#{File.basename(file, '.*')}.rb\",\n Steamd::Generator::Ruby.new(file).run)\n end\n end", "code_tokens": ["def", "generate", "make_output_directory", "files", ".", "each", "do", "|", "file", "|", "File", ".", "write", "(", "\"#{@output}/#{File.basename(file, '.*')}.rb\"", ",", "Steamd", "::", "Generator", "::", "Ruby", ".", "new", "(", "file", ")", ".", "run", ")", "end", "end"], "docstring": "Generates ruby code from the input, places the Ruby files\n in the output", "docstring_tokens": ["Generates", "ruby", "code", "from", "the", "input", "places", "the", "Ruby", "files", "in", "the", "output"], "sha": "8e66e78369ec735223995ea31a125b73541dfa3e", "url": "https://github.com/fastpeek/steamd/blob/8e66e78369ec735223995ea31a125b73541dfa3e/lib/steamd/code_generator.rb#L18-L25", "partition": "valid"} {"repo": "PRX/yahoo_content_analysis", "path": "lib/yahoo_content_analysis/configuration.rb", "func_name": "YahooContentAnalysis.Configuration.reset!", "original_string": "def reset!\n self.api_key = DEFAULT_API_KEY\n self.api_secret = DEFAULT_API_SECRET\n self.adapter = DEFAULT_ADAPTER\n self.endpoint = DEFAULT_ENDPOINT\n self.user_agent = DEFAULT_USER_AGENT\n self.format = DEFAULT_FORMAT\n self.max = DEFAULT_MAX\n self.related_entities = DEFAULT_RELATED_ENTITIES\n self.show_metadata = DEFAULT_SHOW_METADATA\n self.enable_categorizer = DEFAULT_ENABLE_CATEGORIZER\n self.unique = DEFAULT_UNIQUE\n self\n end", "language": "ruby", "code": "def reset!\n self.api_key = DEFAULT_API_KEY\n self.api_secret = DEFAULT_API_SECRET\n self.adapter = DEFAULT_ADAPTER\n self.endpoint = DEFAULT_ENDPOINT\n self.user_agent = DEFAULT_USER_AGENT\n self.format = DEFAULT_FORMAT\n self.max = DEFAULT_MAX\n self.related_entities = DEFAULT_RELATED_ENTITIES\n self.show_metadata = DEFAULT_SHOW_METADATA\n self.enable_categorizer = DEFAULT_ENABLE_CATEGORIZER\n self.unique = DEFAULT_UNIQUE\n self\n end", "code_tokens": ["def", "reset!", "self", ".", "api_key", "=", "DEFAULT_API_KEY", "self", ".", "api_secret", "=", "DEFAULT_API_SECRET", "self", ".", "adapter", "=", "DEFAULT_ADAPTER", "self", ".", "endpoint", "=", "DEFAULT_ENDPOINT", "self", ".", "user_agent", "=", "DEFAULT_USER_AGENT", "self", ".", "format", "=", "DEFAULT_FORMAT", "self", ".", "max", "=", "DEFAULT_MAX", "self", ".", "related_entities", "=", "DEFAULT_RELATED_ENTITIES", "self", ".", "show_metadata", "=", "DEFAULT_SHOW_METADATA", "self", ".", "enable_categorizer", "=", "DEFAULT_ENABLE_CATEGORIZER", "self", ".", "unique", "=", "DEFAULT_UNIQUE", "self", "end"], "docstring": "Reset configuration options to their defaults", "docstring_tokens": ["Reset", "configuration", "options", "to", "their", "defaults"], "sha": "542caeecd693f6529f2bddb7abe980b4f7b476cf", "url": "https://github.com/PRX/yahoo_content_analysis/blob/542caeecd693f6529f2bddb7abe980b4f7b476cf/lib/yahoo_content_analysis/configuration.rb#L87-L100", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/merger.rb", "func_name": "Sycsvpro.Merger.execute", "original_string": "def execute\n File.open(outfile, 'w') do |out|\n out.puts \"#{';' unless @key.empty?}#{header_cols.join(';')}\"\n files.each do |file|\n @current_key = create_current_key\n @current_source_header = @source_header.shift\n processed_header = false\n File.open(file).each_with_index do |line, index|\n next if line.chomp.empty?\n\n unless processed_header\n create_file_header unstring(line).split(';')\n processed_header = true\n next\n end\n\n out.puts create_line unstring(line).split(';')\n end\n end\n end\n end", "language": "ruby", "code": "def execute\n File.open(outfile, 'w') do |out|\n out.puts \"#{';' unless @key.empty?}#{header_cols.join(';')}\"\n files.each do |file|\n @current_key = create_current_key\n @current_source_header = @source_header.shift\n processed_header = false\n File.open(file).each_with_index do |line, index|\n next if line.chomp.empty?\n\n unless processed_header\n create_file_header unstring(line).split(';')\n processed_header = true\n next\n end\n\n out.puts create_line unstring(line).split(';')\n end\n end\n end\n end", "code_tokens": ["def", "execute", "File", ".", "open", "(", "outfile", ",", "'w'", ")", "do", "|", "out", "|", "out", ".", "puts", "\"#{';' unless @key.empty?}#{header_cols.join(';')}\"", "files", ".", "each", "do", "|", "file", "|", "@current_key", "=", "create_current_key", "@current_source_header", "=", "@source_header", ".", "shift", "processed_header", "=", "false", "File", ".", "open", "(", "file", ")", ".", "each_with_index", "do", "|", "line", ",", "index", "|", "next", "if", "line", ".", "chomp", ".", "empty?", "unless", "processed_header", "create_file_header", "unstring", "(", "line", ")", ".", "split", "(", "';'", ")", "processed_header", "=", "true", "next", "end", "out", ".", "puts", "create_line", "unstring", "(", "line", ")", ".", "split", "(", "';'", ")", "end", "end", "end", "end"], "docstring": "Merge files based on common header columns\n\n :call-seq:\n Sycsvpro::Merger.new(outfile: \"out.csv\",\n files: \"file1.csv,file2.csv,filen.csv\",\n header: \"2010,2011,2012,2013,2014\",\n source_header: \"(\\\\d{4}/),(/\\\\d{4}/)\",\n key: \"0,0\").execute\n\n Semantics\n =========\n Merges the files file1.csv, file2.csv ... based on the header columns\n 2010, 2011, 2012, 2013 and 2014 where columns are identified by the\n regex /(\\d{4})/. The first column in a row is column 0 of the file1.csv\n and so on.\n\n outfile:: result is written to the outfile\n files:: list of files that get merged. In the result file the files are\n inserted in the sequence they are provided\n header:: header of the result file and key for assigning column values\n from source files to result file\n source_header:: pattern for each header of the source file to determine\n the column. The pattern is a regex without the enclosing slashes '/'\n key:: first column value from the source file that is used as first\n column in the target file. The key is optional.\n Merges the files based on the provided parameters", "docstring_tokens": ["Merge", "files", "based", "on", "common", "header", "columns"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/merger.rb#L86-L106", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/merger.rb", "func_name": "Sycsvpro.Merger.create_file_header", "original_string": "def create_file_header(columns)\n columns.each_with_index do |c,i|\n next if i == @current_key\n columns[i] = c.scan(Regexp.new(@current_source_header)).flatten[0]\n end\n\n @file_header = @current_key ? [@current_key.to_i] : []\n\n header_cols.each do |h|\n @file_header << columns.index(h) \n end \n\n @file_header.compact!\n end", "language": "ruby", "code": "def create_file_header(columns)\n columns.each_with_index do |c,i|\n next if i == @current_key\n columns[i] = c.scan(Regexp.new(@current_source_header)).flatten[0]\n end\n\n @file_header = @current_key ? [@current_key.to_i] : []\n\n header_cols.each do |h|\n @file_header << columns.index(h) \n end \n\n @file_header.compact!\n end", "code_tokens": ["def", "create_file_header", "(", "columns", ")", "columns", ".", "each_with_index", "do", "|", "c", ",", "i", "|", "next", "if", "i", "==", "@current_key", "columns", "[", "i", "]", "=", "c", ".", "scan", "(", "Regexp", ".", "new", "(", "@current_source_header", ")", ")", ".", "flatten", "[", "0", "]", "end", "@file_header", "=", "@current_key", "?", "[", "@current_key", ".", "to_i", "]", ":", "[", "]", "header_cols", ".", "each", "do", "|", "h", "|", "@file_header", "<<", "columns", ".", "index", "(", "h", ")", "end", "@file_header", ".", "compact!", "end"], "docstring": "create a filter for the columns that match the header filter", "docstring_tokens": ["create", "a", "filter", "for", "the", "columns", "that", "match", "the", "header", "filter"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/merger.rb#L111-L124", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/consent_tier_status.rb", "func_name": "CaTissue.ConsentTierStatus.statement_match?", "original_string": "def statement_match?(other)\n ct = consent_tier\n oct = other.consent_tier\n ct.nil? or oct.nil? or ct.identifier == oct.identifier or ct.statement == oct.statement\n end", "language": "ruby", "code": "def statement_match?(other)\n ct = consent_tier\n oct = other.consent_tier\n ct.nil? or oct.nil? or ct.identifier == oct.identifier or ct.statement == oct.statement\n end", "code_tokens": ["def", "statement_match?", "(", "other", ")", "ct", "=", "consent_tier", "oct", "=", "other", ".", "consent_tier", "ct", ".", "nil?", "or", "oct", ".", "nil?", "or", "ct", ".", "identifier", "==", "oct", ".", "identifier", "or", "ct", ".", "statement", "==", "oct", ".", "statement", "end"], "docstring": "Returns true if this ConsentTierStatus ConsentTier is nil, the other ConsentTierStatus ConsentTier is nil,\n both ConsentTier identifiers are equal, or both ConsentTier statements are equal.", "docstring_tokens": ["Returns", "true", "if", "this", "ConsentTierStatus", "ConsentTier", "is", "nil", "the", "other", "ConsentTierStatus", "ConsentTier", "is", "nil", "both", "ConsentTier", "identifiers", "are", "equal", "or", "both", "ConsentTier", "statements", "are", "equal", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/consent_tier_status.rb#L20-L24", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/column_filter.rb", "func_name": "Sycsvpro.ColumnFilter.process", "original_string": "def process(object, options={})\n return nil if object.nil? or object.empty?\n object = object.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')\n object += \" \" if object =~ /;$/\n return object if filter.empty? and pivot.empty?\n filtered = object.split(';').values_at(*filter.flatten.uniq)\n pivot_each_column(object.split(';')) do |column, match|\n filtered << column if match\n end\n if !filtered.last.nil? and filtered.last.empty?\n filtered.compact.join(';') + \" \" \n else\n filtered.compact.join(';')\n end\n end", "language": "ruby", "code": "def process(object, options={})\n return nil if object.nil? or object.empty?\n object = object.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')\n object += \" \" if object =~ /;$/\n return object if filter.empty? and pivot.empty?\n filtered = object.split(';').values_at(*filter.flatten.uniq)\n pivot_each_column(object.split(';')) do |column, match|\n filtered << column if match\n end\n if !filtered.last.nil? and filtered.last.empty?\n filtered.compact.join(';') + \" \" \n else\n filtered.compact.join(';')\n end\n end", "code_tokens": ["def", "process", "(", "object", ",", "options", "=", "{", "}", ")", "return", "nil", "if", "object", ".", "nil?", "or", "object", ".", "empty?", "object", "=", "object", ".", "encode", "(", "'UTF-8'", ",", "'binary'", ",", "invalid", ":", ":replace", ",", "undef", ":", ":replace", ",", "replace", ":", "''", ")", "object", "+=", "\" \"", "if", "object", "=~", "/", "/", "return", "object", "if", "filter", ".", "empty?", "and", "pivot", ".", "empty?", "filtered", "=", "object", ".", "split", "(", "';'", ")", ".", "values_at", "(", "filter", ".", "flatten", ".", "uniq", ")", "pivot_each_column", "(", "object", ".", "split", "(", "';'", ")", ")", "do", "|", "column", ",", "match", "|", "filtered", "<<", "column", "if", "match", "end", "if", "!", "filtered", ".", "last", ".", "nil?", "and", "filtered", ".", "last", ".", "empty?", "filtered", ".", "compact", ".", "join", "(", "';'", ")", "+", "\" \"", "else", "filtered", ".", "compact", ".", "join", "(", "';'", ")", "end", "end"], "docstring": "Processes the filter and returns the values that respect the filter", "docstring_tokens": ["Processes", "the", "filter", "and", "returns", "the", "values", "that", "respect", "the", "filter"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/column_filter.rb#L10-L24", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/storage_container.rb", "func_name": "CaTissue.StorageContainer.add", "original_string": "def add(storable, *coordinate)\n return add_local(storable, *coordinate) unless coordinate.empty?\n add_to_existing_container(storable) or add_to_new_subcontainer(storable) or out_of_bounds(storable)\n self\n end", "language": "ruby", "code": "def add(storable, *coordinate)\n return add_local(storable, *coordinate) unless coordinate.empty?\n add_to_existing_container(storable) or add_to_new_subcontainer(storable) or out_of_bounds(storable)\n self\n end", "code_tokens": ["def", "add", "(", "storable", ",", "*", "coordinate", ")", "return", "add_local", "(", "storable", ",", "coordinate", ")", "unless", "coordinate", ".", "empty?", "add_to_existing_container", "(", "storable", ")", "or", "add_to_new_subcontainer", "(", "storable", ")", "or", "out_of_bounds", "(", "storable", ")", "self", "end"], "docstring": "Adds the given storable to this container. If the storable has a current position, then\n the storable is moved from that position to this container. The new position is given\n by the given coordinate, if given to this method.\n\n The default coordinate is the first available slot within this Container.\n If this container cannot hold the storable type, then the storable is added to a\n subcontainer which can hold the storable type.\n\n @example\n rack << box #=> places the tissue box on the rack\n freezer << box #=> places the tissue box on a rack in the freezer\n freezer << specimen #=> places the specimen in the first available box in the freezer\n\n @param [Storable] the item to add\n @param [Coordinate, ] the storage location (default is first available location)\n @return [StorageContainer] self\n @raise [IndexError] if this Container is full\n @raise [IndexError] if the row and column are given but exceed the Container bounds", "docstring_tokens": ["Adds", "the", "given", "storable", "to", "this", "container", ".", "If", "the", "storable", "has", "a", "current", "position", "then", "the", "storable", "is", "moved", "from", "that", "position", "to", "this", "container", ".", "The", "new", "position", "is", "given", "by", "the", "given", "coordinate", "if", "given", "to", "this", "method", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/storage_container.rb#L83-L87", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/storage_container.rb", "func_name": "CaTissue.StorageContainer.find_subcontainer", "original_string": "def find_subcontainer(name, type)\n logger.debug { \"Finding box with name #{name}...\" }\n ctr = CaTissue::StorageContainer.new(:name => name)\n if ctr.find then\n logger.debug { \"Container found: #{ctr}.\" }\n else\n logger.debug { \"Container not found: #{name}.\" }\n create_subcontainer(name, type)\n end\n box\n end", "language": "ruby", "code": "def find_subcontainer(name, type)\n logger.debug { \"Finding box with name #{name}...\" }\n ctr = CaTissue::StorageContainer.new(:name => name)\n if ctr.find then\n logger.debug { \"Container found: #{ctr}.\" }\n else\n logger.debug { \"Container not found: #{name}.\" }\n create_subcontainer(name, type)\n end\n box\n end", "code_tokens": ["def", "find_subcontainer", "(", "name", ",", "type", ")", "logger", ".", "debug", "{", "\"Finding box with name #{name}...\"", "}", "ctr", "=", "CaTissue", "::", "StorageContainer", ".", "new", "(", ":name", "=>", "name", ")", "if", "ctr", ".", "find", "then", "logger", ".", "debug", "{", "\"Container found: #{ctr}.\"", "}", "else", "logger", ".", "debug", "{", "\"Container not found: #{name}.\"", "}", "create_subcontainer", "(", "name", ",", "type", ")", "end", "box", "end"], "docstring": "Finds the container with the given name, or creates a new container\n of the given type if necessary.\n\n @param [String] the container search name\n @param [CaTissue::StorageContainer] the container type\n @return a container with the given name", "docstring_tokens": ["Finds", "the", "container", "with", "the", "given", "name", "or", "creates", "a", "new", "container", "of", "the", "given", "type", "if", "necessary", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/storage_container.rb#L97-L107", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/storage_container.rb", "func_name": "CaTissue.StorageContainer.add_to_existing_container", "original_string": "def add_to_existing_container(storable)\n if storage_type.nil? then\n raise Jinx::ValidationError.new(\"Cannot add #{storable.qp} to #{qp} with missing storage type\")\n end\n # the subcontainers in column, row sort order\n scs = subcontainers.sort { |sc1, sc2| sc1.position.coordinate <=> sc2.position.coordinate }\n logger.debug { \"Looking for a #{self} subcontainer from among #{scs.pp_s} to place #{storable.qp}...\" } unless scs.empty?\n # The first subcontainer that can hold the storable is preferred.\n sc = scs.detect do |sc|\n # Check for circular reference. This occurred as a result of the caTissue bug described\n # in CaTissue::Database#query_object. The work-around circumvents the bug for now, but\n # it doesn't hurt to check again.\n if identifier and sc.identifier == identifier then\n raise Jinx::ValidationError.new(\"#{self} has a circular containment reference to subcontainer #{sc}\")\n end\n # No circular reference; add to subcontainer if possible.\n sc.add_to_existing_container(storable) if StorageContainer === sc\n end\n if sc then\n logger.debug { \"#{self} subcontainer #{sc} stored #{storable.qp}.\" }\n self\n elsif can_hold_child?(storable) then\n logger.debug { \"#{self} can hold #{storable.qp}.\" }\n add_local(storable)\n else\n logger.debug { \"Neither #{self} of type #{storage_type.name} nor its subcontainers can hold #{storable.qp}.\" }\n nil\n end\n end", "language": "ruby", "code": "def add_to_existing_container(storable)\n if storage_type.nil? then\n raise Jinx::ValidationError.new(\"Cannot add #{storable.qp} to #{qp} with missing storage type\")\n end\n # the subcontainers in column, row sort order\n scs = subcontainers.sort { |sc1, sc2| sc1.position.coordinate <=> sc2.position.coordinate }\n logger.debug { \"Looking for a #{self} subcontainer from among #{scs.pp_s} to place #{storable.qp}...\" } unless scs.empty?\n # The first subcontainer that can hold the storable is preferred.\n sc = scs.detect do |sc|\n # Check for circular reference. This occurred as a result of the caTissue bug described\n # in CaTissue::Database#query_object. The work-around circumvents the bug for now, but\n # it doesn't hurt to check again.\n if identifier and sc.identifier == identifier then\n raise Jinx::ValidationError.new(\"#{self} has a circular containment reference to subcontainer #{sc}\")\n end\n # No circular reference; add to subcontainer if possible.\n sc.add_to_existing_container(storable) if StorageContainer === sc\n end\n if sc then\n logger.debug { \"#{self} subcontainer #{sc} stored #{storable.qp}.\" }\n self\n elsif can_hold_child?(storable) then\n logger.debug { \"#{self} can hold #{storable.qp}.\" }\n add_local(storable)\n else\n logger.debug { \"Neither #{self} of type #{storage_type.name} nor its subcontainers can hold #{storable.qp}.\" }\n nil\n end\n end", "code_tokens": ["def", "add_to_existing_container", "(", "storable", ")", "if", "storage_type", ".", "nil?", "then", "raise", "Jinx", "::", "ValidationError", ".", "new", "(", "\"Cannot add #{storable.qp} to #{qp} with missing storage type\"", ")", "end", "# the subcontainers in column, row sort order", "scs", "=", "subcontainers", ".", "sort", "{", "|", "sc1", ",", "sc2", "|", "sc1", ".", "position", ".", "coordinate", "<=>", "sc2", ".", "position", ".", "coordinate", "}", "logger", ".", "debug", "{", "\"Looking for a #{self} subcontainer from among #{scs.pp_s} to place #{storable.qp}...\"", "}", "unless", "scs", ".", "empty?", "# The first subcontainer that can hold the storable is preferred.", "sc", "=", "scs", ".", "detect", "do", "|", "sc", "|", "# Check for circular reference. This occurred as a result of the caTissue bug described", "# in CaTissue::Database#query_object. The work-around circumvents the bug for now, but", "# it doesn't hurt to check again.", "if", "identifier", "and", "sc", ".", "identifier", "==", "identifier", "then", "raise", "Jinx", "::", "ValidationError", ".", "new", "(", "\"#{self} has a circular containment reference to subcontainer #{sc}\"", ")", "end", "# No circular reference; add to subcontainer if possible.", "sc", ".", "add_to_existing_container", "(", "storable", ")", "if", "StorageContainer", "===", "sc", "end", "if", "sc", "then", "logger", ".", "debug", "{", "\"#{self} subcontainer #{sc} stored #{storable.qp}.\"", "}", "self", "elsif", "can_hold_child?", "(", "storable", ")", "then", "logger", ".", "debug", "{", "\"#{self} can hold #{storable.qp}.\"", "}", "add_local", "(", "storable", ")", "else", "logger", ".", "debug", "{", "\"Neither #{self} of type #{storage_type.name} nor its subcontainers can hold #{storable.qp}.\"", "}", "nil", "end", "end"], "docstring": "Adds the given storable to a container within this StorageContainer's hierarchy.\n\n @param @storable (see #add)\n @return [StorageContainer, nil] self if added, nil otherwise\n @raise [Jinx::ValidationError] if this container does not have a storage type, or if a circular\n containment reference is detected", "docstring_tokens": ["Adds", "the", "given", "storable", "to", "a", "container", "within", "this", "StorageContainer", "s", "hierarchy", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/storage_container.rb#L144-L172", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/storage_container.rb", "func_name": "CaTissue.StorageContainer.add_to_new_subcontainer", "original_string": "def add_to_new_subcontainer(storable)\n # the subcontainers in column, row sort order\n scs = subcontainers.sort { |sc1, sc2| sc1.position.coordinate <=> sc2.position.coordinate }\n logger.debug { \"Looking for a #{self} subcontainer #{scs} to place a new #{storable.qp} container...\" } unless scs.empty?\n # The first subcontainer that can hold the new subcontainer is preferred.\n sc = scs.detect { |sc| sc.add_to_new_subcontainer(storable) if StorageContainer === sc }\n if sc then\n logger.debug { \"#{self} subcontainer #{sc} stored #{storable.qp}.\" }\n self\n elsif not full? then\n logger.debug { \"Creating a subcontainer in #{self} of type #{storage_type} to hold #{storable.qp}...\" }\n create_subcontainer_for(storable)\n end\n end", "language": "ruby", "code": "def add_to_new_subcontainer(storable)\n # the subcontainers in column, row sort order\n scs = subcontainers.sort { |sc1, sc2| sc1.position.coordinate <=> sc2.position.coordinate }\n logger.debug { \"Looking for a #{self} subcontainer #{scs} to place a new #{storable.qp} container...\" } unless scs.empty?\n # The first subcontainer that can hold the new subcontainer is preferred.\n sc = scs.detect { |sc| sc.add_to_new_subcontainer(storable) if StorageContainer === sc }\n if sc then\n logger.debug { \"#{self} subcontainer #{sc} stored #{storable.qp}.\" }\n self\n elsif not full? then\n logger.debug { \"Creating a subcontainer in #{self} of type #{storage_type} to hold #{storable.qp}...\" }\n create_subcontainer_for(storable)\n end\n end", "code_tokens": ["def", "add_to_new_subcontainer", "(", "storable", ")", "# the subcontainers in column, row sort order", "scs", "=", "subcontainers", ".", "sort", "{", "|", "sc1", ",", "sc2", "|", "sc1", ".", "position", ".", "coordinate", "<=>", "sc2", ".", "position", ".", "coordinate", "}", "logger", ".", "debug", "{", "\"Looking for a #{self} subcontainer #{scs} to place a new #{storable.qp} container...\"", "}", "unless", "scs", ".", "empty?", "# The first subcontainer that can hold the new subcontainer is preferred.", "sc", "=", "scs", ".", "detect", "{", "|", "sc", "|", "sc", ".", "add_to_new_subcontainer", "(", "storable", ")", "if", "StorageContainer", "===", "sc", "}", "if", "sc", "then", "logger", ".", "debug", "{", "\"#{self} subcontainer #{sc} stored #{storable.qp}.\"", "}", "self", "elsif", "not", "full?", "then", "logger", ".", "debug", "{", "\"Creating a subcontainer in #{self} of type #{storage_type} to hold #{storable.qp}...\"", "}", "create_subcontainer_for", "(", "storable", ")", "end", "end"], "docstring": "Creates a subcontainer which holds the given storable. Creates nested subcontainers as necessary.\n\n @param @storable (see #add)\n @return [StorageContainer, nil] self if a subcontainer was created, nil otherwise", "docstring_tokens": ["Creates", "a", "subcontainer", "which", "holds", "the", "given", "storable", ".", "Creates", "nested", "subcontainers", "as", "necessary", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/storage_container.rb#L178-L191", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/storage_container.rb", "func_name": "CaTissue.StorageContainer.type_path_to", "original_string": "def type_path_to(storable)\n shortest = nil\n holds_storage_types.each do |st|\n stp = st.path_to(storable) || next\n shortest = stp if shortest.nil? or stp.size < shortest.size\n end\n shortest\n end", "language": "ruby", "code": "def type_path_to(storable)\n shortest = nil\n holds_storage_types.each do |st|\n stp = st.path_to(storable) || next\n shortest = stp if shortest.nil? or stp.size < shortest.size\n end\n shortest\n end", "code_tokens": ["def", "type_path_to", "(", "storable", ")", "shortest", "=", "nil", "holds_storage_types", ".", "each", "do", "|", "st", "|", "stp", "=", "st", ".", "path_to", "(", "storable", ")", "||", "next", "shortest", "=", "stp", "if", "shortest", ".", "nil?", "or", "stp", ".", "size", "<", "shortest", ".", "size", "end", "shortest", "end"], "docstring": "Returns a StorageType array of descendant StorageTypes which can hold the given storable,\n or nil if no such path exists.\n\n @param [Storable] the domain object to store in this container\n @return [] the {StorageType}s leading from this container to the storable holder", "docstring_tokens": ["Returns", "a", "StorageType", "array", "of", "descendant", "StorageTypes", "which", "can", "hold", "the", "given", "storable", "or", "nil", "if", "no", "such", "path", "exists", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/storage_container.rb#L237-L244", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/resource.rb", "func_name": "Turntabler.Resource.attributes=", "original_string": "def attributes=(attributes)\n if attributes\n attributes.each do |attribute, value|\n attribute = attribute.to_s\n if attribute == 'metadata'\n self.attributes = value\n else\n __send__(\"#{attribute}=\", value) if respond_to?(\"#{attribute}=\", true)\n end\n end\n end\n end", "language": "ruby", "code": "def attributes=(attributes)\n if attributes\n attributes.each do |attribute, value|\n attribute = attribute.to_s\n if attribute == 'metadata'\n self.attributes = value\n else\n __send__(\"#{attribute}=\", value) if respond_to?(\"#{attribute}=\", true)\n end\n end\n end\n end", "code_tokens": ["def", "attributes", "=", "(", "attributes", ")", "if", "attributes", "attributes", ".", "each", "do", "|", "attribute", ",", "value", "|", "attribute", "=", "attribute", ".", "to_s", "if", "attribute", "==", "'metadata'", "self", ".", "attributes", "=", "value", "else", "__send__", "(", "\"#{attribute}=\"", ",", "value", ")", "if", "respond_to?", "(", "\"#{attribute}=\"", ",", "true", ")", "end", "end", "end", "end"], "docstring": "Attempts to set attributes on the object only if they've been explicitly\n defined by the class. Note that this will also attempt to interpret any\n \"metadata\" properties as additional attributes.\n\n @api private\n @param [Hash] attributes The updated attributes for the resource", "docstring_tokens": ["Attempts", "to", "set", "attributes", "on", "the", "object", "only", "if", "they", "ve", "been", "explicitly", "defined", "by", "the", "class", ".", "Note", "that", "this", "will", "also", "attempt", "to", "interpret", "any", "metadata", "properties", "as", "additional", "attributes", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/resource.rb#L126-L137", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/avatar.rb", "func_name": "Turntabler.Avatar.available?", "original_string": "def available?\n client.user.points >= minimum_points && (!acl || client.user.acl >= acl)\n end", "language": "ruby", "code": "def available?\n client.user.points >= minimum_points && (!acl || client.user.acl >= acl)\n end", "code_tokens": ["def", "available?", "client", ".", "user", ".", "points", ">=", "minimum_points", "&&", "(", "!", "acl", "||", "client", ".", "user", ".", "acl", ">=", "acl", ")", "end"], "docstring": "Determines whether this avatar is available to the current user.\n\n @return [Boolean] +true+ if the avatar is available, otherwise +false+", "docstring_tokens": ["Determines", "whether", "this", "avatar", "is", "available", "to", "the", "current", "user", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/avatar.rb#L17-L19", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/avatar.rb", "func_name": "Turntabler.Avatar.set", "original_string": "def set\n api('user.set_avatar', :avatarid => id)\n client.user.attributes = {'avatarid' => id}\n client.user.avatar.attributes = {'min' => minimum_points, 'acl' => acl}\n true\n end", "language": "ruby", "code": "def set\n api('user.set_avatar', :avatarid => id)\n client.user.attributes = {'avatarid' => id}\n client.user.avatar.attributes = {'min' => minimum_points, 'acl' => acl}\n true\n end", "code_tokens": ["def", "set", "api", "(", "'user.set_avatar'", ",", ":avatarid", "=>", "id", ")", "client", ".", "user", ".", "attributes", "=", "{", "'avatarid'", "=>", "id", "}", "client", ".", "user", ".", "avatar", ".", "attributes", "=", "{", "'min'", "=>", "minimum_points", ",", "'acl'", "=>", "acl", "}", "true", "end"], "docstring": "Updates the current user's avatar to this one.\n\n @return [true]\n @raise [Turntabler::Error] if the command fails\n @example\n avatar.set # => true", "docstring_tokens": ["Updates", "the", "current", "user", "s", "avatar", "to", "this", "one", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/avatar.rb#L27-L32", "partition": "valid"} {"repo": "danijoo/Sightstone", "path": "lib/sightstone/modules/champion_module.rb", "func_name": "Sightstone.ChampionModule.champions", "original_string": "def champions(optional={})\n region = optional[:region] || @sightstone.region\n free_to_play = optional[:free_to_play] || false\n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v1.1/champion\"\n response = _get_api_response(uri, {'freeToPlay' => free_to_play})\n\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n champions = []\n data['champions'].each do |champ|\n champions << Champion.new(champ)\n end\n if block_given?\n yield champions\n else\n return champions\n end\n }\n end", "language": "ruby", "code": "def champions(optional={})\n region = optional[:region] || @sightstone.region\n free_to_play = optional[:free_to_play] || false\n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v1.1/champion\"\n response = _get_api_response(uri, {'freeToPlay' => free_to_play})\n\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n champions = []\n data['champions'].each do |champ|\n champions << Champion.new(champ)\n end\n if block_given?\n yield champions\n else\n return champions\n end\n }\n end", "code_tokens": ["def", "champions", "(", "optional", "=", "{", "}", ")", "region", "=", "optional", "[", ":region", "]", "||", "@sightstone", ".", "region", "free_to_play", "=", "optional", "[", ":free_to_play", "]", "||", "false", "uri", "=", "\"https://prod.api.pvp.net/api/lol/#{region}/v1.1/champion\"", "response", "=", "_get_api_response", "(", "uri", ",", "{", "'freeToPlay'", "=>", "free_to_play", "}", ")", "_parse_response", "(", "response", ")", "{", "|", "resp", "|", "data", "=", "JSON", ".", "parse", "(", "resp", ")", "champions", "=", "[", "]", "data", "[", "'champions'", "]", ".", "each", "do", "|", "champ", "|", "champions", "<<", "Champion", ".", "new", "(", "champ", ")", "end", "if", "block_given?", "yield", "champions", "else", "return", "champions", "end", "}", "end"], "docstring": "call to get champions\n @param optional [Hash] optional arguments: :region => replaces default region, :free_to_play => boolean (only free to play champs if true)\n @return [Array] array of champs", "docstring_tokens": ["call", "to", "get", "champions"], "sha": "4c6709916ce7552f622de1a120c021e067601b4d", "url": "https://github.com/danijoo/Sightstone/blob/4c6709916ce7552f622de1a120c021e067601b4d/lib/sightstone/modules/champion_module.rb#L14-L32", "partition": "valid"} {"repo": "superp/meta_manager", "path": "lib/meta_manager/taggable.rb", "func_name": "MetaManager.Taggable.meta_tag", "original_string": "def meta_tag(attr_name, options={})\n key = normalize_meta_tag_name(attr_name)\n\n cached_meta_tags[key] ||= self.meta_tags.detect {|t| t.name == key}\n cached_meta_tags[key] ||= self.meta_tags.build(:name => key) if options[:build]\n cached_meta_tags[key]\n end", "language": "ruby", "code": "def meta_tag(attr_name, options={})\n key = normalize_meta_tag_name(attr_name)\n\n cached_meta_tags[key] ||= self.meta_tags.detect {|t| t.name == key}\n cached_meta_tags[key] ||= self.meta_tags.build(:name => key) if options[:build]\n cached_meta_tags[key]\n end", "code_tokens": ["def", "meta_tag", "(", "attr_name", ",", "options", "=", "{", "}", ")", "key", "=", "normalize_meta_tag_name", "(", "attr_name", ")", "cached_meta_tags", "[", "key", "]", "||=", "self", ".", "meta_tags", ".", "detect", "{", "|", "t", "|", "t", ".", "name", "==", "key", "}", "cached_meta_tags", "[", "key", "]", "||=", "self", ".", "meta_tags", ".", "build", "(", ":name", "=>", "key", ")", "if", "options", "[", ":build", "]", "cached_meta_tags", "[", "key", "]", "end"], "docstring": "Save meta tags records into one hash", "docstring_tokens": ["Save", "meta", "tags", "records", "into", "one", "hash"], "sha": "bb3d131a1e07afd970db6491d5abb99fbc46e484", "url": "https://github.com/superp/meta_manager/blob/bb3d131a1e07afd970db6491d5abb99fbc46e484/lib/meta_manager/taggable.rb#L15-L21", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/mapper.rb", "func_name": "Sycsvpro.Mapper.init_col_filter", "original_string": "def init_col_filter(columns, source)\n if columns.nil?\n File.open(source, 'r').each do |line| \n line = unstring(line)\n next if line.empty?\n line += ' ' if line =~ /;$/\n size = line.split(';').size\n columns = \"0-#{size-1}\"\n break\n end\n end\n ColumnFilter.new(columns).filter.flatten\n end", "language": "ruby", "code": "def init_col_filter(columns, source)\n if columns.nil?\n File.open(source, 'r').each do |line| \n line = unstring(line)\n next if line.empty?\n line += ' ' if line =~ /;$/\n size = line.split(';').size\n columns = \"0-#{size-1}\"\n break\n end\n end\n ColumnFilter.new(columns).filter.flatten\n end", "code_tokens": ["def", "init_col_filter", "(", "columns", ",", "source", ")", "if", "columns", ".", "nil?", "File", ".", "open", "(", "source", ",", "'r'", ")", ".", "each", "do", "|", "line", "|", "line", "=", "unstring", "(", "line", ")", "next", "if", "line", ".", "empty?", "line", "+=", "' '", "if", "line", "=~", "/", "/", "size", "=", "line", ".", "split", "(", "';'", ")", ".", "size", "columns", "=", "\"0-#{size-1}\"", "break", "end", "end", "ColumnFilter", ".", "new", "(", "columns", ")", ".", "filter", ".", "flatten", "end"], "docstring": "Initialize the col_filter that contains columns to be considered for\n mapping. If no columns are provided, that is being empty, a filter with\n all columns is returned", "docstring_tokens": ["Initialize", "the", "col_filter", "that", "contains", "columns", "to", "be", "considered", "for", "mapping", ".", "If", "no", "columns", "are", "provided", "that", "is", "being", "empty", "a", "filter", "with", "all", "columns", "is", "returned"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/mapper.rb#L100-L112", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/metadata.rb", "func_name": "CaTissue.Metadata.add_annotation", "original_string": "def add_annotation(name, opts={})\n # the module symbol\n mod_sym = name.camelize.to_sym\n # the module spec defaults\n pkg = opts[:package] ||= name.underscore\n svc = opts[:service] ||= name.underscore\n grp = opts[:group] ||= pkg\n pxy_nm = opts[:proxy_name] || \"#{self.name.demodulize}RecordEntry\"\n self.annotation_proxy_class_name = pxy_nm\n # add the annotation entry\n @ann_spec_hash ||= {}\n @ann_spec_hash[mod_sym] = opts\n logger.info(\"Added #{qp} annotation #{name} with module #{mod_sym}, package #{pkg}, service #{svc} and group #{grp}.\")\n end", "language": "ruby", "code": "def add_annotation(name, opts={})\n # the module symbol\n mod_sym = name.camelize.to_sym\n # the module spec defaults\n pkg = opts[:package] ||= name.underscore\n svc = opts[:service] ||= name.underscore\n grp = opts[:group] ||= pkg\n pxy_nm = opts[:proxy_name] || \"#{self.name.demodulize}RecordEntry\"\n self.annotation_proxy_class_name = pxy_nm\n # add the annotation entry\n @ann_spec_hash ||= {}\n @ann_spec_hash[mod_sym] = opts\n logger.info(\"Added #{qp} annotation #{name} with module #{mod_sym}, package #{pkg}, service #{svc} and group #{grp}.\")\n end", "code_tokens": ["def", "add_annotation", "(", "name", ",", "opts", "=", "{", "}", ")", "# the module symbol", "mod_sym", "=", "name", ".", "camelize", ".", "to_sym", "# the module spec defaults", "pkg", "=", "opts", "[", ":package", "]", "||=", "name", ".", "underscore", "svc", "=", "opts", "[", ":service", "]", "||=", "name", ".", "underscore", "grp", "=", "opts", "[", ":group", "]", "||=", "pkg", "pxy_nm", "=", "opts", "[", ":proxy_name", "]", "||", "\"#{self.name.demodulize}RecordEntry\"", "self", ".", "annotation_proxy_class_name", "=", "pxy_nm", "# add the annotation entry", "@ann_spec_hash", "||=", "{", "}", "@ann_spec_hash", "[", "mod_sym", "]", "=", "opts", "logger", ".", "info", "(", "\"Added #{qp} annotation #{name} with module #{mod_sym}, package #{pkg}, service #{svc} and group #{grp}.\"", ")", "end"], "docstring": "Declares an annotation scoped by this class.\n\n @param [String] name the name of the annotation module\n @param [{Symbol => Object}] opts the annotation options\n @option opts [String] :package the package name (default is the lower-case underscore name)\n @option opts [String] :service the service name (default is the lower-case underscore name)\n @option opts [String] :group the DE group short name (default is the package)\n @option opts [String] :proxy_name the DE proxy class name (default is the class name followed by +RecordEntry+)", "docstring_tokens": ["Declares", "an", "annotation", "scoped", "by", "this", "class", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/metadata.rb#L177-L190", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/metadata.rb", "func_name": "CaTissue.Metadata.load_local_annotations", "original_string": "def load_local_annotations\n return Array::EMPTY_ARRAY if @ann_spec_hash.nil?\n # an annotated class has a hook entity id\n initialize_annotation_holder\n # build the annotations\n @ann_spec_hash.map { |name, opts| import_annotation(name, opts) }\n end", "language": "ruby", "code": "def load_local_annotations\n return Array::EMPTY_ARRAY if @ann_spec_hash.nil?\n # an annotated class has a hook entity id\n initialize_annotation_holder\n # build the annotations\n @ann_spec_hash.map { |name, opts| import_annotation(name, opts) }\n end", "code_tokens": ["def", "load_local_annotations", "return", "Array", "::", "EMPTY_ARRAY", "if", "@ann_spec_hash", ".", "nil?", "# an annotated class has a hook entity id", "initialize_annotation_holder", "# build the annotations", "@ann_spec_hash", ".", "map", "{", "|", "name", ",", "opts", "|", "import_annotation", "(", "name", ",", "opts", ")", "}", "end"], "docstring": "Loads this class's annotations.\n\n @return [] the loaded annotation modules", "docstring_tokens": ["Loads", "this", "class", "s", "annotations", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/metadata.rb#L200-L206", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/metadata.rb", "func_name": "CaTissue.Metadata.import_annotation", "original_string": "def import_annotation(name, opts)\n logger.debug { \"Importing #{qp} annotation #{name}...\" }\n # Make the annotation module class scoped by this Annotatable class.\n class_eval(\"module #{name}; end\")\n mod = const_get(name)\n # Append the AnnotationModule methods.\n mod.extend(Annotation::Importer)\n # Build the annnotation module.\n mod.initialize_annotation(self, opts) { |pxy| create_proxy_attribute(mod, pxy) }\n mod\n end", "language": "ruby", "code": "def import_annotation(name, opts)\n logger.debug { \"Importing #{qp} annotation #{name}...\" }\n # Make the annotation module class scoped by this Annotatable class.\n class_eval(\"module #{name}; end\")\n mod = const_get(name)\n # Append the AnnotationModule methods.\n mod.extend(Annotation::Importer)\n # Build the annnotation module.\n mod.initialize_annotation(self, opts) { |pxy| create_proxy_attribute(mod, pxy) }\n mod\n end", "code_tokens": ["def", "import_annotation", "(", "name", ",", "opts", ")", "logger", ".", "debug", "{", "\"Importing #{qp} annotation #{name}...\"", "}", "# Make the annotation module class scoped by this Annotatable class.", "class_eval", "(", "\"module #{name}; end\"", ")", "mod", "=", "const_get", "(", "name", ")", "# Append the AnnotationModule methods.", "mod", ".", "extend", "(", "Annotation", "::", "Importer", ")", "# Build the annnotation module.", "mod", ".", "initialize_annotation", "(", "self", ",", "opts", ")", "{", "|", "pxy", "|", "create_proxy_attribute", "(", "mod", ",", "pxy", ")", "}", "mod", "end"], "docstring": "Builds a new annotation module for the given module name and options.\n\n @param [String] name the attribute module name\n @param opts (see #add_annotation)\n @return [Module] the annotation module\n @raise [AnnotationError] if there is no annotation proxy class", "docstring_tokens": ["Builds", "a", "new", "annotation", "module", "for", "the", "given", "module", "name", "and", "options", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/metadata.rb#L225-L235", "partition": "valid"} {"repo": "o2web/rails_admin_cms", "path": "app/controllers/cms/viewables_controller.rb", "func_name": "CMS.ViewablesController.create", "original_string": "def create\n current_count = UniqueKey.where(list_key_params).count\n\n if params[:max] == 'Infinity' || current_count < params[:max].to_i\n unique_key = list_key_params.merge(position: current_count + 1)\n\n viewable = UniqueKey.create_localized_viewable!(unique_key)\n\n if unique_key[:viewable_type] != 'Viewable::Block'\n path = rails_admin.edit_path(model_name: unique_key[:viewable_type].to_s.underscore.gsub('/', '~'), id: viewable.id)\n\n redirect_to path\n else\n redirect_to :back\n end\n else\n redirect_to :back\n end\n end", "language": "ruby", "code": "def create\n current_count = UniqueKey.where(list_key_params).count\n\n if params[:max] == 'Infinity' || current_count < params[:max].to_i\n unique_key = list_key_params.merge(position: current_count + 1)\n\n viewable = UniqueKey.create_localized_viewable!(unique_key)\n\n if unique_key[:viewable_type] != 'Viewable::Block'\n path = rails_admin.edit_path(model_name: unique_key[:viewable_type].to_s.underscore.gsub('/', '~'), id: viewable.id)\n\n redirect_to path\n else\n redirect_to :back\n end\n else\n redirect_to :back\n end\n end", "code_tokens": ["def", "create", "current_count", "=", "UniqueKey", ".", "where", "(", "list_key_params", ")", ".", "count", "if", "params", "[", ":max", "]", "==", "'Infinity'", "||", "current_count", "<", "params", "[", ":max", "]", ".", "to_i", "unique_key", "=", "list_key_params", ".", "merge", "(", "position", ":", "current_count", "+", "1", ")", "viewable", "=", "UniqueKey", ".", "create_localized_viewable!", "(", "unique_key", ")", "if", "unique_key", "[", ":viewable_type", "]", "!=", "'Viewable::Block'", "path", "=", "rails_admin", ".", "edit_path", "(", "model_name", ":", "unique_key", "[", ":viewable_type", "]", ".", "to_s", ".", "underscore", ".", "gsub", "(", "'/'", ",", "'~'", ")", ",", "id", ":", "viewable", ".", "id", ")", "redirect_to", "path", "else", "redirect_to", ":back", "end", "else", "redirect_to", ":back", "end", "end"], "docstring": "used by the add viewable link", "docstring_tokens": ["used", "by", "the", "add", "viewable", "link"], "sha": "764197753a2beb80780a44c7f559ba2bc1bb429e", "url": "https://github.com/o2web/rails_admin_cms/blob/764197753a2beb80780a44c7f559ba2bc1bb429e/app/controllers/cms/viewables_controller.rb#L6-L24", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/header.rb", "func_name": "Sycsvpro.Header.process", "original_string": "def process(line, values = true)\n return \"\" if @header_cols.empty? && @insert_cols.empty?\n header_patterns = {}\n @row_cols = unstring(line).split(';')\n if @header_cols[0] == '*'\n @header_cols[0] = @row_cols\n else\n @header_cols.each_with_index do |h,i|\n if h =~ /^\\(?c\\d+(?:[=~]{,2}).*$/ \n if col = eval(h)\n last_eval = $1\n unless @header_cols.index(last_eval) || @header_cols.index(col)\n if values\n @header_cols[i] = (h =~ /^\\(?c\\d+=~/) ? last_eval : col\n header_patterns[i+1] = h if h =~ /^\\(?c\\d+[=~+-.]{1,2}/\n else\n @header_cols[i] = col if h =~ /^\\(?c\\d+$/\n end\n end\n end\n else\n @header_cols[i] = h\n end\n end\n end\n insert_header_cols\n header_patterns.each { |i,h| @header_cols.insert(i,h) }\n to_s\n end", "language": "ruby", "code": "def process(line, values = true)\n return \"\" if @header_cols.empty? && @insert_cols.empty?\n header_patterns = {}\n @row_cols = unstring(line).split(';')\n if @header_cols[0] == '*'\n @header_cols[0] = @row_cols\n else\n @header_cols.each_with_index do |h,i|\n if h =~ /^\\(?c\\d+(?:[=~]{,2}).*$/ \n if col = eval(h)\n last_eval = $1\n unless @header_cols.index(last_eval) || @header_cols.index(col)\n if values\n @header_cols[i] = (h =~ /^\\(?c\\d+=~/) ? last_eval : col\n header_patterns[i+1] = h if h =~ /^\\(?c\\d+[=~+-.]{1,2}/\n else\n @header_cols[i] = col if h =~ /^\\(?c\\d+$/\n end\n end\n end\n else\n @header_cols[i] = h\n end\n end\n end\n insert_header_cols\n header_patterns.each { |i,h| @header_cols.insert(i,h) }\n to_s\n end", "code_tokens": ["def", "process", "(", "line", ",", "values", "=", "true", ")", "return", "\"\"", "if", "@header_cols", ".", "empty?", "&&", "@insert_cols", ".", "empty?", "header_patterns", "=", "{", "}", "@row_cols", "=", "unstring", "(", "line", ")", ".", "split", "(", "';'", ")", "if", "@header_cols", "[", "0", "]", "==", "'*'", "@header_cols", "[", "0", "]", "=", "@row_cols", "else", "@header_cols", ".", "each_with_index", "do", "|", "h", ",", "i", "|", "if", "h", "=~", "/", "\\(", "\\d", "/", "if", "col", "=", "eval", "(", "h", ")", "last_eval", "=", "$1", "unless", "@header_cols", ".", "index", "(", "last_eval", ")", "||", "@header_cols", ".", "index", "(", "col", ")", "if", "values", "@header_cols", "[", "i", "]", "=", "(", "h", "=~", "/", "\\(", "\\d", "/", ")", "?", "last_eval", ":", "col", "header_patterns", "[", "i", "+", "1", "]", "=", "h", "if", "h", "=~", "/", "\\(", "\\d", "/", "else", "@header_cols", "[", "i", "]", "=", "col", "if", "h", "=~", "/", "\\(", "\\d", "/", "end", "end", "end", "else", "@header_cols", "[", "i", "]", "=", "h", "end", "end", "end", "insert_header_cols", "header_patterns", ".", "each", "{", "|", "i", ",", "h", "|", "@header_cols", ".", "insert", "(", "i", ",", "h", ")", "}", "to_s", "end"], "docstring": "Returns the header", "docstring_tokens": ["Returns", "the", "header"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/header.rb#L35-L63", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/room.rb", "func_name": "Turntabler.Room.load", "original_string": "def load(options = {})\n assert_valid_keys(options, :song_log)\n options = {:song_log => false}.merge(options)\n\n # Use a client that is connected on the same url this room is hosted on\n client = @client.url == url ? @client : Turntabler::Client.new(@client.user.id, @client.user.auth, :url => url, :timeout => @client.timeout)\n\n begin\n data = api('room.info', :extended => options[:song_log])\n self.attributes = data['room'].merge('users' => data['users'])\n super()\n ensure\n # Close the client if it was only opened for use in this API call\n client.close if client != @client\n end\n end", "language": "ruby", "code": "def load(options = {})\n assert_valid_keys(options, :song_log)\n options = {:song_log => false}.merge(options)\n\n # Use a client that is connected on the same url this room is hosted on\n client = @client.url == url ? @client : Turntabler::Client.new(@client.user.id, @client.user.auth, :url => url, :timeout => @client.timeout)\n\n begin\n data = api('room.info', :extended => options[:song_log])\n self.attributes = data['room'].merge('users' => data['users'])\n super()\n ensure\n # Close the client if it was only opened for use in this API call\n client.close if client != @client\n end\n end", "code_tokens": ["def", "load", "(", "options", "=", "{", "}", ")", "assert_valid_keys", "(", "options", ",", ":song_log", ")", "options", "=", "{", ":song_log", "=>", "false", "}", ".", "merge", "(", "options", ")", "# Use a client that is connected on the same url this room is hosted on", "client", "=", "@client", ".", "url", "==", "url", "?", "@client", ":", "Turntabler", "::", "Client", ".", "new", "(", "@client", ".", "user", ".", "id", ",", "@client", ".", "user", ".", "auth", ",", ":url", "=>", "url", ",", ":timeout", "=>", "@client", ".", "timeout", ")", "begin", "data", "=", "api", "(", "'room.info'", ",", ":extended", "=>", "options", "[", ":song_log", "]", ")", "self", ".", "attributes", "=", "data", "[", "'room'", "]", ".", "merge", "(", "'users'", "=>", "data", "[", "'users'", "]", ")", "super", "(", ")", "ensure", "# Close the client if it was only opened for use in this API call", "client", ".", "close", "if", "client", "!=", "@client", "end", "end"], "docstring": "Loads the attributes for this room. Attributes will automatically load\n when accessed, but this allows data to be forcefully loaded upfront.\n\n @note This will open a connection to the chat server the room is hosted on if the client is not already connected to it\n @param [Hash] options The configuration options\n @option options [Boolean] :song_log (false) Whether to include the song log\n @return [true]\n @raise [ArgumentError] if an invalid option is specified\n @raise [Turntabler::Error] if the command fails\n @example\n room.load # => true\n room.load(:song_log => true) # => true", "docstring_tokens": ["Loads", "the", "attributes", "for", "this", "room", ".", "Attributes", "will", "automatically", "load", "when", "accessed", "but", "this", "allows", "data", "to", "be", "forcefully", "loaded", "upfront", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/room.rb#L158-L173", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/room.rb", "func_name": "Turntabler.Room.attributes=", "original_string": "def attributes=(attrs)\n if attrs\n super('users' => attrs.delete('users')) if attrs['users']\n super\n \n # Set room-level attributes that are specific to the song\n song_attributes = attrs['metadata'] && attrs['metadata'].select {|key, value| %w(upvotes downvotes votelog).include?(key)}\n current_song.attributes = song_attributes if @current_song\n end\n end", "language": "ruby", "code": "def attributes=(attrs)\n if attrs\n super('users' => attrs.delete('users')) if attrs['users']\n super\n \n # Set room-level attributes that are specific to the song\n song_attributes = attrs['metadata'] && attrs['metadata'].select {|key, value| %w(upvotes downvotes votelog).include?(key)}\n current_song.attributes = song_attributes if @current_song\n end\n end", "code_tokens": ["def", "attributes", "=", "(", "attrs", ")", "if", "attrs", "super", "(", "'users'", "=>", "attrs", ".", "delete", "(", "'users'", ")", ")", "if", "attrs", "[", "'users'", "]", "super", "# Set room-level attributes that are specific to the song", "song_attributes", "=", "attrs", "[", "'metadata'", "]", "&&", "attrs", "[", "'metadata'", "]", ".", "select", "{", "|", "key", ",", "value", "|", "%w(", "upvotes", "downvotes", "votelog", ")", ".", "include?", "(", "key", ")", "}", "current_song", ".", "attributes", "=", "song_attributes", "if", "@current_song", "end", "end"], "docstring": "Sets the current attributes for this room, ensuring that the full list of\n listeners gets set first so that we can use those built users to then fill\n out the collection of djs, moderators, etc.\n\n @api private\n @param [Hash] attrs The attributes to set", "docstring_tokens": ["Sets", "the", "current", "attributes", "for", "this", "room", "ensuring", "that", "the", "full", "list", "of", "listeners", "gets", "set", "first", "so", "that", "we", "can", "use", "those", "built", "users", "to", "then", "fill", "out", "the", "collection", "of", "djs", "moderators", "etc", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/room.rb#L181-L190", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/room.rb", "func_name": "Turntabler.Room.enter", "original_string": "def enter\n if client.room != self\n # Leave the old room\n client.room.leave if client.room\n\n # Connect and register with this room\n client.connect(url)\n begin\n client.room = self\n data = api('room.register', :section => nil)\n self.attributes = {'section' => data['section']}\n rescue Exception\n client.room = nil\n raise\n end\n end\n\n true\n end", "language": "ruby", "code": "def enter\n if client.room != self\n # Leave the old room\n client.room.leave if client.room\n\n # Connect and register with this room\n client.connect(url)\n begin\n client.room = self\n data = api('room.register', :section => nil)\n self.attributes = {'section' => data['section']}\n rescue Exception\n client.room = nil\n raise\n end\n end\n\n true\n end", "code_tokens": ["def", "enter", "if", "client", ".", "room", "!=", "self", "# Leave the old room", "client", ".", "room", ".", "leave", "if", "client", ".", "room", "# Connect and register with this room", "client", ".", "connect", "(", "url", ")", "begin", "client", ".", "room", "=", "self", "data", "=", "api", "(", "'room.register'", ",", ":section", "=>", "nil", ")", "self", ".", "attributes", "=", "{", "'section'", "=>", "data", "[", "'section'", "]", "}", "rescue", "Exception", "client", ".", "room", "=", "nil", "raise", "end", "end", "true", "end"], "docstring": "Enters the current room.\n\n @note This will leave any room the user is already currently in (unless the same room is being entered)\n @return [true]\n @raise [Turntabler::Error] if the command fails\n @example\n room.enter # => true", "docstring_tokens": ["Enters", "the", "current", "room", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/room.rb#L216-L234", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/room.rb", "func_name": "Turntabler.Room.sticker_placements=", "original_string": "def sticker_placements=(user_placements)\n user_placements.each do |user_id, placements|\n listener(user_id).attributes = {'placements' => placements}\n end\n end", "language": "ruby", "code": "def sticker_placements=(user_placements)\n user_placements.each do |user_id, placements|\n listener(user_id).attributes = {'placements' => placements}\n end\n end", "code_tokens": ["def", "sticker_placements", "=", "(", "user_placements", ")", "user_placements", ".", "each", "do", "|", "user_id", ",", "placements", "|", "listener", "(", "user_id", ")", ".", "attributes", "=", "{", "'placements'", "=>", "placements", "}", "end", "end"], "docstring": "Sets the sticker placements for each dj", "docstring_tokens": ["Sets", "the", "sticker", "placements", "for", "each", "dj"], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/room.rb#L387-L391", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/song.rb", "func_name": "Turntabler.Song.skip", "original_string": "def skip\n assert_current_song\n api('room.stop_song', :songid => id, :djid => played_by.id, :roomid => room.id, :section => room.section)\n true\n end", "language": "ruby", "code": "def skip\n assert_current_song\n api('room.stop_song', :songid => id, :djid => played_by.id, :roomid => room.id, :section => room.section)\n true\n end", "code_tokens": ["def", "skip", "assert_current_song", "api", "(", "'room.stop_song'", ",", ":songid", "=>", "id", ",", ":djid", "=>", "played_by", ".", "id", ",", ":roomid", "=>", "room", ".", "id", ",", ":section", "=>", "room", ".", "section", ")", "true", "end"], "docstring": "Skips the song.\n\n @return [true]\n @raise [Turntabler::Error] if the command fails\n @raise [Turntabler::Error] if the song is not playing in the current song\n @example\n song.skip # => true", "docstring_tokens": ["Skips", "the", "song", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/song.rb#L152-L156", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/song.rb", "func_name": "Turntabler.Song.vote", "original_string": "def vote(direction = :up)\n assert_current_song\n api('room.vote',\n :roomid => room.id,\n :section => room.section,\n :val => direction,\n :songid => id,\n :vh => digest(\"#{room.id}#{direction}#{id}\"),\n :th => digest(rand),\n :ph => digest(rand)\n )\n true\n end", "language": "ruby", "code": "def vote(direction = :up)\n assert_current_song\n api('room.vote',\n :roomid => room.id,\n :section => room.section,\n :val => direction,\n :songid => id,\n :vh => digest(\"#{room.id}#{direction}#{id}\"),\n :th => digest(rand),\n :ph => digest(rand)\n )\n true\n end", "code_tokens": ["def", "vote", "(", "direction", "=", ":up", ")", "assert_current_song", "api", "(", "'room.vote'", ",", ":roomid", "=>", "room", ".", "id", ",", ":section", "=>", "room", ".", "section", ",", ":val", "=>", "direction", ",", ":songid", "=>", "id", ",", ":vh", "=>", "digest", "(", "\"#{room.id}#{direction}#{id}\"", ")", ",", ":th", "=>", "digest", "(", "rand", ")", ",", ":ph", "=>", "digest", "(", "rand", ")", ")", "true", "end"], "docstring": "Vote for the song.\n\n @param [Symbol] direction The direction to vote the song (:up or :down)\n @return [true]\n @raise [Turntabler::Error] if the command fails\n @raise [Turntabler::Error] if the song is not playing in the current song\n @example\n song.vote # => true\n song.vote(:down) # => true", "docstring_tokens": ["Vote", "for", "the", "song", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/song.rb#L167-L179", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/song.rb", "func_name": "Turntabler.Song.snag", "original_string": "def snag\n assert_current_song\n sh = digest(rand)\n api('snag.add',\n :djid => room.current_dj.id,\n :songid => id,\n :roomid => room.id,\n :section => room.section,\n :site => 'queue',\n :location => 'board',\n :in_queue => 'false',\n :blocked => 'false',\n :vh => digest([client.user.id, room.current_dj.id, id, room.id, 'queue', 'board', 'false', 'false', sh] * '/'),\n :sh => sh,\n :fh => digest(rand)\n )\n true\n end", "language": "ruby", "code": "def snag\n assert_current_song\n sh = digest(rand)\n api('snag.add',\n :djid => room.current_dj.id,\n :songid => id,\n :roomid => room.id,\n :section => room.section,\n :site => 'queue',\n :location => 'board',\n :in_queue => 'false',\n :blocked => 'false',\n :vh => digest([client.user.id, room.current_dj.id, id, room.id, 'queue', 'board', 'false', 'false', sh] * '/'),\n :sh => sh,\n :fh => digest(rand)\n )\n true\n end", "code_tokens": ["def", "snag", "assert_current_song", "sh", "=", "digest", "(", "rand", ")", "api", "(", "'snag.add'", ",", ":djid", "=>", "room", ".", "current_dj", ".", "id", ",", ":songid", "=>", "id", ",", ":roomid", "=>", "room", ".", "id", ",", ":section", "=>", "room", ".", "section", ",", ":site", "=>", "'queue'", ",", ":location", "=>", "'board'", ",", ":in_queue", "=>", "'false'", ",", ":blocked", "=>", "'false'", ",", ":vh", "=>", "digest", "(", "[", "client", ".", "user", ".", "id", ",", "room", ".", "current_dj", ".", "id", ",", "id", ",", "room", ".", "id", ",", "'queue'", ",", "'board'", ",", "'false'", ",", "'false'", ",", "sh", "]", "*", "'/'", ")", ",", ":sh", "=>", "sh", ",", ":fh", "=>", "digest", "(", "rand", ")", ")", "true", "end"], "docstring": "Triggers the heart animation for the song.\n\n @note This will not add the song to the user's playlist\n @return [true]\n @raise [Turntabler::Error] if the command fails\n @raise [Turntabler::Error] if the song is not playing in the current song\n @example\n song.snag # => true", "docstring_tokens": ["Triggers", "the", "heart", "animation", "for", "the", "song", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/song.rb#L189-L206", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/song.rb", "func_name": "Turntabler.Song.add", "original_string": "def add(options = {})\n assert_valid_keys(options, :playlist, :index)\n options = {:playlist => playlist.id, :index => 0}.merge(options)\n\n # Create a copy of the song so that the playlist can get set properly\n song = dup\n song.attributes = {:playlist => options[:playlist]}\n playlist, index = song.playlist, options[:index]\n\n api('playlist.add', :playlist_name => playlist.id, :song_dict => {:fileid => id}, :index => index)\n playlist.songs.insert(index, song) if playlist.loaded?\n true\n end", "language": "ruby", "code": "def add(options = {})\n assert_valid_keys(options, :playlist, :index)\n options = {:playlist => playlist.id, :index => 0}.merge(options)\n\n # Create a copy of the song so that the playlist can get set properly\n song = dup\n song.attributes = {:playlist => options[:playlist]}\n playlist, index = song.playlist, options[:index]\n\n api('playlist.add', :playlist_name => playlist.id, :song_dict => {:fileid => id}, :index => index)\n playlist.songs.insert(index, song) if playlist.loaded?\n true\n end", "code_tokens": ["def", "add", "(", "options", "=", "{", "}", ")", "assert_valid_keys", "(", "options", ",", ":playlist", ",", ":index", ")", "options", "=", "{", ":playlist", "=>", "playlist", ".", "id", ",", ":index", "=>", "0", "}", ".", "merge", "(", "options", ")", "# Create a copy of the song so that the playlist can get set properly", "song", "=", "dup", "song", ".", "attributes", "=", "{", ":playlist", "=>", "options", "[", ":playlist", "]", "}", "playlist", ",", "index", "=", "song", ".", "playlist", ",", "options", "[", ":index", "]", "api", "(", "'playlist.add'", ",", ":playlist_name", "=>", "playlist", ".", "id", ",", ":song_dict", "=>", "{", ":fileid", "=>", "id", "}", ",", ":index", "=>", "index", ")", "playlist", ".", "songs", ".", "insert", "(", "index", ",", "song", ")", "if", "playlist", ".", "loaded?", "true", "end"], "docstring": "Adds the song to one of the user's playlists.\n\n @param [Hash] options The options for where to add the song\n @option options [String] :playlist (\"default\") The playlist to add the song in\n @option options [Fixnum] :index (0) The location in the playlist to insert the song\n @return [true]\n @raise [ArgumentError] if an invalid option is specified\n @raise [Turntabler::Error] if the command fails\n @example\n song.add(:index => 1) # => true", "docstring_tokens": ["Adds", "the", "song", "to", "one", "of", "the", "user", "s", "playlists", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/song.rb#L218-L230", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/song.rb", "func_name": "Turntabler.Song.move", "original_string": "def move(to_index)\n api('playlist.reorder', :playlist_name => playlist.id, :index_from => index, :index_to => to_index)\n playlist.songs.insert(to_index, playlist.songs.delete(self))\n true\n end", "language": "ruby", "code": "def move(to_index)\n api('playlist.reorder', :playlist_name => playlist.id, :index_from => index, :index_to => to_index)\n playlist.songs.insert(to_index, playlist.songs.delete(self))\n true\n end", "code_tokens": ["def", "move", "(", "to_index", ")", "api", "(", "'playlist.reorder'", ",", ":playlist_name", "=>", "playlist", ".", "id", ",", ":index_from", "=>", "index", ",", ":index_to", "=>", "to_index", ")", "playlist", ".", "songs", ".", "insert", "(", "to_index", ",", "playlist", ".", "songs", ".", "delete", "(", "self", ")", ")", "true", "end"], "docstring": "Move a song from one location in the playlist to another.\n\n @param [Fixnum] to_index The index to move the song to\n @return [true]\n @raise [ArgumentError] if an invalid option is specified\n @raise [Turntabler::Error] if the command fails\n song.move(5) # => true", "docstring_tokens": ["Move", "a", "song", "from", "one", "location", "in", "the", "playlist", "to", "another", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/song.rb#L252-L256", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/helpers/storage_type_holder.rb", "func_name": "CaTissue.StorageTypeHolder.add_child_type", "original_string": "def add_child_type(type)\n case type\n when CaTissue::StorageType then add_storage_type(type)\n when CaTissue::SpecimenArrayType then add_specimen_array_type(type)\n when String then add_specimen_class(type)\n else raise ArgumentError.new(\"Storage type child not supported - #{type}\")\n end\n self\n end", "language": "ruby", "code": "def add_child_type(type)\n case type\n when CaTissue::StorageType then add_storage_type(type)\n when CaTissue::SpecimenArrayType then add_specimen_array_type(type)\n when String then add_specimen_class(type)\n else raise ArgumentError.new(\"Storage type child not supported - #{type}\")\n end\n self\n end", "code_tokens": ["def", "add_child_type", "(", "type", ")", "case", "type", "when", "CaTissue", "::", "StorageType", "then", "add_storage_type", "(", "type", ")", "when", "CaTissue", "::", "SpecimenArrayType", "then", "add_specimen_array_type", "(", "type", ")", "when", "String", "then", "add_specimen_class", "(", "type", ")", "else", "raise", "ArgumentError", ".", "new", "(", "\"Storage type child not supported - #{type}\"", ")", "end", "self", "end"], "docstring": "Adds the given subtype to the list of subtypes which this StorageType can hold.\n\n @param [CaTissue::StorageType, CaTissue::SpecimenArrayType, String] the subcontainer type or\n {CaTissue::AbstractSpecimen#specimen_class} which this StorageType can hold\n @return [StorageTypeHolder] self\n @raise [ArgumentError] if the type to add is not a supported parameter", "docstring_tokens": ["Adds", "the", "given", "subtype", "to", "the", "list", "of", "subtypes", "which", "this", "StorageType", "can", "hold", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/helpers/storage_type_holder.rb#L41-L49", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/helpers/storage_type_holder.rb", "func_name": "CaTissue.StorageTypeHolder.copy_child_types", "original_string": "def copy_child_types(other)\n child_storage_types.merge!(other.child_storage_types)\n child_specimen_array_types.merge!(other.child_specimen_array_types)\n child_specimen_classes.merge!(other.child_specimen_classes)\n end", "language": "ruby", "code": "def copy_child_types(other)\n child_storage_types.merge!(other.child_storage_types)\n child_specimen_array_types.merge!(other.child_specimen_array_types)\n child_specimen_classes.merge!(other.child_specimen_classes)\n end", "code_tokens": ["def", "copy_child_types", "(", "other", ")", "child_storage_types", ".", "merge!", "(", "other", ".", "child_storage_types", ")", "child_specimen_array_types", ".", "merge!", "(", "other", ".", "child_specimen_array_types", ")", "child_specimen_classes", ".", "merge!", "(", "other", ".", "child_specimen_classes", ")", "end"], "docstring": "Copies the other child types into this container's child types.\n\n @param [StorageTypeHolder] other the source child type holder", "docstring_tokens": ["Copies", "the", "other", "child", "types", "into", "this", "container", "s", "child", "types", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/helpers/storage_type_holder.rb#L56-L60", "partition": "valid"} {"repo": "fastpeek/steamd", "path": "lib/steamd/cli.rb", "func_name": "Steamd.Cli.generate", "original_string": "def generate\n opts = CliOptions.new(options) # options is built by Thor\n gen = CodeGenerator.new(opts.input, opts.output)\n gen.generate\n end", "language": "ruby", "code": "def generate\n opts = CliOptions.new(options) # options is built by Thor\n gen = CodeGenerator.new(opts.input, opts.output)\n gen.generate\n end", "code_tokens": ["def", "generate", "opts", "=", "CliOptions", ".", "new", "(", "options", ")", "# options is built by Thor", "gen", "=", "CodeGenerator", ".", "new", "(", "opts", ".", "input", ",", "opts", ".", "output", ")", "gen", ".", "generate", "end"], "docstring": "Generate Ruby code for Steam Language", "docstring_tokens": ["Generate", "Ruby", "code", "for", "Steam", "Language"], "sha": "8e66e78369ec735223995ea31a125b73541dfa3e", "url": "https://github.com/fastpeek/steamd/blob/8e66e78369ec735223995ea31a125b73541dfa3e/lib/steamd/cli.rb#L16-L20", "partition": "valid"} {"repo": "fastpeek/steamd", "path": "lib/steamd/parser.rb", "func_name": "Steamd.Parser.load!", "original_string": "def load!\n return if loaded?\n\n Treetop.load(\"#{Steamd.grammar_dir}/shared.treetop\")\n\n Dir.glob(\"#{Steamd.grammar_dir}/*.treetop\") do |file|\n Treetop.load(file)\n end\n\n @parser = SteamdParser.new\n true\n end", "language": "ruby", "code": "def load!\n return if loaded?\n\n Treetop.load(\"#{Steamd.grammar_dir}/shared.treetop\")\n\n Dir.glob(\"#{Steamd.grammar_dir}/*.treetop\") do |file|\n Treetop.load(file)\n end\n\n @parser = SteamdParser.new\n true\n end", "code_tokens": ["def", "load!", "return", "if", "loaded?", "Treetop", ".", "load", "(", "\"#{Steamd.grammar_dir}/shared.treetop\"", ")", "Dir", ".", "glob", "(", "\"#{Steamd.grammar_dir}/*.treetop\"", ")", "do", "|", "file", "|", "Treetop", ".", "load", "(", "file", ")", "end", "@parser", "=", "SteamdParser", ".", "new", "true", "end"], "docstring": "Load the grammars\n\n @return [Bool] returns true unless an exception is thrown", "docstring_tokens": ["Load", "the", "grammars"], "sha": "8e66e78369ec735223995ea31a125b73541dfa3e", "url": "https://github.com/fastpeek/steamd/blob/8e66e78369ec735223995ea31a125b73541dfa3e/lib/steamd/parser.rb#L30-L41", "partition": "valid"} {"repo": "fastpeek/steamd", "path": "lib/steamd/parser.rb", "func_name": "Steamd.Parser.parse", "original_string": "def parse(io)\n io.rewind\n raise NotLoadedError, 'load before parsing (#load!)' if @parser.nil?\n\n data = strip_comments_and_obsolete_tags!(io)\n\n @tree = @parser.parse(data)\n raise_parser_error! if @tree.nil?\n\n true\n end", "language": "ruby", "code": "def parse(io)\n io.rewind\n raise NotLoadedError, 'load before parsing (#load!)' if @parser.nil?\n\n data = strip_comments_and_obsolete_tags!(io)\n\n @tree = @parser.parse(data)\n raise_parser_error! if @tree.nil?\n\n true\n end", "code_tokens": ["def", "parse", "(", "io", ")", "io", ".", "rewind", "raise", "NotLoadedError", ",", "'load before parsing (#load!)'", "if", "@parser", ".", "nil?", "data", "=", "strip_comments_and_obsolete_tags!", "(", "io", ")", "@tree", "=", "@parser", ".", "parse", "(", "data", ")", "raise_parser_error!", "if", "@tree", ".", "nil?", "true", "end"], "docstring": "Parses an IO stream.\n\n @param io [#read, #rewind] An IO stream containing the Steam Language\n data.\n @return [Bool] returns true unless an error is thrown", "docstring_tokens": ["Parses", "an", "IO", "stream", "."], "sha": "8e66e78369ec735223995ea31a125b73541dfa3e", "url": "https://github.com/fastpeek/steamd/blob/8e66e78369ec735223995ea31a125b73541dfa3e/lib/steamd/parser.rb#L48-L58", "partition": "valid"} {"repo": "fastpeek/steamd", "path": "lib/steamd/parser.rb", "func_name": "Steamd.Parser.imports", "original_string": "def imports\n raise StreamNotParsed, 'you must parse first' if @tree.nil?\n\n imports = statements.select do |node|\n node.is_a?(ImportStatement)\n end\n\n imports.map(&:to_hash)\n end", "language": "ruby", "code": "def imports\n raise StreamNotParsed, 'you must parse first' if @tree.nil?\n\n imports = statements.select do |node|\n node.is_a?(ImportStatement)\n end\n\n imports.map(&:to_hash)\n end", "code_tokens": ["def", "imports", "raise", "StreamNotParsed", ",", "'you must parse first'", "if", "@tree", ".", "nil?", "imports", "=", "statements", ".", "select", "do", "|", "node", "|", "node", ".", "is_a?", "(", "ImportStatement", ")", "end", "imports", ".", "map", "(", ":to_hash", ")", "end"], "docstring": "An array of hashes containing the imports found in the parsed\n Steam Language file.\n\n The hash is the hash version of ImportStatement\n\n @example Accessing imports\n parser.imports # => [{filename: 'test'}]\n\n @return [Array] an array of hashes representing the imports found\n @see ImportStatement", "docstring_tokens": ["An", "array", "of", "hashes", "containing", "the", "imports", "found", "in", "the", "parsed", "Steam", "Language", "file", "."], "sha": "8e66e78369ec735223995ea31a125b73541dfa3e", "url": "https://github.com/fastpeek/steamd/blob/8e66e78369ec735223995ea31a125b73541dfa3e/lib/steamd/parser.rb#L70-L78", "partition": "valid"} {"repo": "fastpeek/steamd", "path": "lib/steamd/parser.rb", "func_name": "Steamd.Parser.classes", "original_string": "def classes\n raise StreamNotParsed, 'you must parse first' if @tree.nil?\n\n classes = statements.select do |node|\n node.is_a?(ClassStatement)\n end\n\n classes.map(&:to_hash)\n end", "language": "ruby", "code": "def classes\n raise StreamNotParsed, 'you must parse first' if @tree.nil?\n\n classes = statements.select do |node|\n node.is_a?(ClassStatement)\n end\n\n classes.map(&:to_hash)\n end", "code_tokens": ["def", "classes", "raise", "StreamNotParsed", ",", "'you must parse first'", "if", "@tree", ".", "nil?", "classes", "=", "statements", ".", "select", "do", "|", "node", "|", "node", ".", "is_a?", "(", "ClassStatement", ")", "end", "classes", ".", "map", "(", ":to_hash", ")", "end"], "docstring": "Returns an array of classes parsed from the IO stream. The array\n contains hashes with class information and variables.\n\n The hash is the hash form of ClassStatement\n\n @example Accessing the classes\n parser.classes # => [{ name: 'test', variables: [], ...]\n\n @return [Array] an array of hashes representing the class\n @see ClassStatement", "docstring_tokens": ["Returns", "an", "array", "of", "classes", "parsed", "from", "the", "IO", "stream", ".", "The", "array", "contains", "hashes", "with", "class", "information", "and", "variables", "."], "sha": "8e66e78369ec735223995ea31a125b73541dfa3e", "url": "https://github.com/fastpeek/steamd/blob/8e66e78369ec735223995ea31a125b73541dfa3e/lib/steamd/parser.rb#L90-L98", "partition": "valid"} {"repo": "fastpeek/steamd", "path": "lib/steamd/parser.rb", "func_name": "Steamd.Parser.enums", "original_string": "def enums\n raise StreamNotParsed, 'you must parse first' if @tree.nil?\n\n enums = statements.select do |node|\n node.is_a?(EnumStatement)\n end\n\n enums.map(&:to_hash)\n end", "language": "ruby", "code": "def enums\n raise StreamNotParsed, 'you must parse first' if @tree.nil?\n\n enums = statements.select do |node|\n node.is_a?(EnumStatement)\n end\n\n enums.map(&:to_hash)\n end", "code_tokens": ["def", "enums", "raise", "StreamNotParsed", ",", "'you must parse first'", "if", "@tree", ".", "nil?", "enums", "=", "statements", ".", "select", "do", "|", "node", "|", "node", ".", "is_a?", "(", "EnumStatement", ")", "end", "enums", ".", "map", "(", ":to_hash", ")", "end"], "docstring": "Returns an array of eneums parsed from the IO stream. The array\n contains hashes with enum information and variables.\n\n The hash is the hash form of EnumStatement\n\n @example Accessing the enums\n parser.enums # => [{ name: 'test', variables: [], ...]\n\n @return [Array] an array of hashes representing the class\n @see EnumStatement", "docstring_tokens": ["Returns", "an", "array", "of", "eneums", "parsed", "from", "the", "IO", "stream", ".", "The", "array", "contains", "hashes", "with", "enum", "information", "and", "variables", "."], "sha": "8e66e78369ec735223995ea31a125b73541dfa3e", "url": "https://github.com/fastpeek/steamd/blob/8e66e78369ec735223995ea31a125b73541dfa3e/lib/steamd/parser.rb#L110-L118", "partition": "valid"} {"repo": "pmahoney/mini_aether", "path": "lib/mini_aether/xml_parser.rb", "func_name": "MiniAether.XmlParser.pull_to_start", "original_string": "def pull_to_start(name)\n loop do\n res = pull\n raise NotFoundError if res.event_type == :end_document\n next if res.start_element? && res[0] == name.to_s\n end\n end", "language": "ruby", "code": "def pull_to_start(name)\n loop do\n res = pull\n raise NotFoundError if res.event_type == :end_document\n next if res.start_element? && res[0] == name.to_s\n end\n end", "code_tokens": ["def", "pull_to_start", "(", "name", ")", "loop", "do", "res", "=", "pull", "raise", "NotFoundError", "if", "res", ".", "event_type", "==", ":end_document", "next", "if", "res", ".", "start_element?", "&&", "res", "[", "0", "]", "==", "name", ".", "to_s", "end", "end"], "docstring": "Pull events until the start of an element of tag name +name+ is\n reached.", "docstring_tokens": ["Pull", "events", "until", "the", "start", "of", "an", "element", "of", "tag", "name", "+", "name", "+", "is", "reached", "."], "sha": "0359967c2fa5fd9ba8bd05b12567e307b44ea7a4", "url": "https://github.com/pmahoney/mini_aether/blob/0359967c2fa5fd9ba8bd05b12567e307b44ea7a4/lib/mini_aether/xml_parser.rb#L13-L19", "partition": "valid"} {"repo": "pmahoney/mini_aether", "path": "lib/mini_aether/xml_parser.rb", "func_name": "MiniAether.XmlParser.pull_text_until_end", "original_string": "def pull_text_until_end\n texts = []\n loop do\n res = pull\n break unless res.text?\n texts << res[0]\n end\n texts.join\n end", "language": "ruby", "code": "def pull_text_until_end\n texts = []\n loop do\n res = pull\n break unless res.text?\n texts << res[0]\n end\n texts.join\n end", "code_tokens": ["def", "pull_text_until_end", "texts", "=", "[", "]", "loop", "do", "res", "=", "pull", "break", "unless", "res", ".", "text?", "texts", "<<", "res", "[", "0", "]", "end", "texts", ".", "join", "end"], "docstring": "Pull all text nodes until the next +end_element+ event. Return\n the concatenation of text nodes.", "docstring_tokens": ["Pull", "all", "text", "nodes", "until", "the", "next", "+", "end_element", "+", "event", ".", "Return", "the", "concatenation", "of", "text", "nodes", "."], "sha": "0359967c2fa5fd9ba8bd05b12567e307b44ea7a4", "url": "https://github.com/pmahoney/mini_aether/blob/0359967c2fa5fd9ba8bd05b12567e307b44ea7a4/lib/mini_aether/xml_parser.rb#L29-L37", "partition": "valid"} {"repo": "jparker/comparison", "path": "lib/comparison/presenter.rb", "func_name": "Comparison.Presenter.dom_classes", "original_string": "def dom_classes\n if positive?\n t 'comparison.dom_classes.positive',\n default: %i[comparison.classes.positive]\n elsif negative?\n t 'comparison.dom_classes.negative',\n default: %i[comparison.classes.negative]\n else\n t 'comparison.dom_classes.nochange',\n default: %i[comparison.classes.nochange]\n end\n end", "language": "ruby", "code": "def dom_classes\n if positive?\n t 'comparison.dom_classes.positive',\n default: %i[comparison.classes.positive]\n elsif negative?\n t 'comparison.dom_classes.negative',\n default: %i[comparison.classes.negative]\n else\n t 'comparison.dom_classes.nochange',\n default: %i[comparison.classes.nochange]\n end\n end", "code_tokens": ["def", "dom_classes", "if", "positive?", "t", "'comparison.dom_classes.positive'", ",", "default", ":", "%i[", "comparison.classes.positive", "]", "elsif", "negative?", "t", "'comparison.dom_classes.negative'", ",", "default", ":", "%i[", "comparison.classes.negative", "]", "else", "t", "'comparison.dom_classes.nochange'", ",", "default", ":", "%i[", "comparison.classes.nochange", "]", "end", "end"], "docstring": "Returns the I18n translation for `comparison.dom_classes`.\n\n Use these translations to specify CSS classes for tags that contain\n comparison data. For example:\n\n en:\n comparison:\n dom_classes:\n positive: 'comparison positive'\n negative: 'comparison negative'\n nochange: 'comparison nochange'\n\n .comparison.positive {\n color: #3c763d;\n background-color: #dff0d8;\n }\n .comparison.negative {\n color: #a94442;\n background-color: #f2dede;\n }\n .comparison.nochange {\n color: #777777;\n }\n\n content_tag :span, cmp.difference, class: cmp.dom_classes\n # => \"+10%\"\n\n If you need to work with inline styles instead of CSS classes, see the\n `#style` method.", "docstring_tokens": ["Returns", "the", "I18n", "translation", "for", "comparison", ".", "dom_classes", "."], "sha": "b268d30b01eed422c10f2c7b5b2987f05fb1a00c", "url": "https://github.com/jparker/comparison/blob/b268d30b01eed422c10f2c7b5b2987f05fb1a00c/lib/comparison/presenter.rb#L146-L157", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/column_type_filter.rb", "func_name": "Sycsvpro.ColumnTypeFilter.process", "original_string": "def process(object, options={})\n filtered = super(object, options)\n\n return nil if filtered.nil?\n\n values = filtered.split(';')\n\n values.each_with_index do |value, index|\n if types[index] == 'n'\n if value =~ /\\./\n number_value = value.to_f\n else\n number_value = value.to_i\n end\n values[index] = number_value\n elsif types[index] == 'd'\n if value.strip.empty?\n date = Date.strptime('9999-9-9', '%Y-%m-%d')\n else\n begin\n date = Date.strptime(value, date_format)\n rescue\n puts \"Error #{value}, #{index}\"\n end\n end\n values[index] = date\n end\n end \n\n values\n end", "language": "ruby", "code": "def process(object, options={})\n filtered = super(object, options)\n\n return nil if filtered.nil?\n\n values = filtered.split(';')\n\n values.each_with_index do |value, index|\n if types[index] == 'n'\n if value =~ /\\./\n number_value = value.to_f\n else\n number_value = value.to_i\n end\n values[index] = number_value\n elsif types[index] == 'd'\n if value.strip.empty?\n date = Date.strptime('9999-9-9', '%Y-%m-%d')\n else\n begin\n date = Date.strptime(value, date_format)\n rescue\n puts \"Error #{value}, #{index}\"\n end\n end\n values[index] = date\n end\n end \n\n values\n end", "code_tokens": ["def", "process", "(", "object", ",", "options", "=", "{", "}", ")", "filtered", "=", "super", "(", "object", ",", "options", ")", "return", "nil", "if", "filtered", ".", "nil?", "values", "=", "filtered", ".", "split", "(", "';'", ")", "values", ".", "each_with_index", "do", "|", "value", ",", "index", "|", "if", "types", "[", "index", "]", "==", "'n'", "if", "value", "=~", "/", "\\.", "/", "number_value", "=", "value", ".", "to_f", "else", "number_value", "=", "value", ".", "to_i", "end", "values", "[", "index", "]", "=", "number_value", "elsif", "types", "[", "index", "]", "==", "'d'", "if", "value", ".", "strip", ".", "empty?", "date", "=", "Date", ".", "strptime", "(", "'9999-9-9'", ",", "'%Y-%m-%d'", ")", "else", "begin", "date", "=", "Date", ".", "strptime", "(", "value", ",", "date_format", ")", "rescue", "puts", "\"Error #{value}, #{index}\"", "end", "end", "values", "[", "index", "]", "=", "date", "end", "end", "values", "end"], "docstring": "Processes the filter and returns the filtered columns", "docstring_tokens": ["Processes", "the", "filter", "and", "returns", "the", "filtered", "columns"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/column_type_filter.rb#L8-L38", "partition": "valid"} {"repo": "nbaum/blower", "path": "lib/blower/logger.rb", "func_name": "Blower.Logger.log", "original_string": "def log (level, message, quiet: false, &block)\n if !quiet && (LEVELS.index(level) >= LEVELS.index(Logger.level))\n synchronize do\n message = message.to_s.colorize(COLORS[level]) if level\n message.split(\"\\n\").each do |line|\n STDERR.puts \" \" * Logger.indent + @prefix + line\n end\n end\n with_indent(&block) if block\n elsif block\n block.()\n end\n end", "language": "ruby", "code": "def log (level, message, quiet: false, &block)\n if !quiet && (LEVELS.index(level) >= LEVELS.index(Logger.level))\n synchronize do\n message = message.to_s.colorize(COLORS[level]) if level\n message.split(\"\\n\").each do |line|\n STDERR.puts \" \" * Logger.indent + @prefix + line\n end\n end\n with_indent(&block) if block\n elsif block\n block.()\n end\n end", "code_tokens": ["def", "log", "(", "level", ",", "message", ",", "quiet", ":", "false", ",", "&", "block", ")", "if", "!", "quiet", "&&", "(", "LEVELS", ".", "index", "(", "level", ")", ">=", "LEVELS", ".", "index", "(", "Logger", ".", "level", ")", ")", "synchronize", "do", "message", "=", "message", ".", "to_s", ".", "colorize", "(", "COLORS", "[", "level", "]", ")", "if", "level", "message", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "line", "|", "STDERR", ".", "puts", "\" \"", "*", "Logger", ".", "indent", "+", "@prefix", "+", "line", "end", "end", "with_indent", "(", "block", ")", "if", "block", "elsif", "block", "block", ".", "(", ")", "end", "end"], "docstring": "Display a log message. The block, if specified, is executed in an indented region after the log message is shown.\n @api private\n @param [Symbol] level the severity level\n @param [#to_s] message the message to display\n @param block a block to execute with an indent after the message is displayed\n @return the value of block, or nil", "docstring_tokens": ["Display", "a", "log", "message", ".", "The", "block", "if", "specified", "is", "executed", "in", "an", "indented", "region", "after", "the", "log", "message", "is", "shown", "."], "sha": "9e09a56f9d4bf547bf1aa1843d894be625a27628", "url": "https://github.com/nbaum/blower/blob/9e09a56f9d4bf547bf1aa1843d894be625a27628/lib/blower/logger.rb#L64-L76", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/user.rb", "func_name": "CaTissue.User.role_id=", "original_string": "def role_id=(value)\n # value as an integer (nil is zero)\n value_i = value.to_i\n # set the Bug #66 work-around i.v.\n @role_id = value_i.zero? ? nil : value_i\n # value as a String (if non-nil)\n value_s = @role_id.to_s if @role_id\n # call Java with a String\n setRoleId(value_s)\n end", "language": "ruby", "code": "def role_id=(value)\n # value as an integer (nil is zero)\n value_i = value.to_i\n # set the Bug #66 work-around i.v.\n @role_id = value_i.zero? ? nil : value_i\n # value as a String (if non-nil)\n value_s = @role_id.to_s if @role_id\n # call Java with a String\n setRoleId(value_s)\n end", "code_tokens": ["def", "role_id", "=", "(", "value", ")", "# value as an integer (nil is zero)", "value_i", "=", "value", ".", "to_i", "# set the Bug #66 work-around i.v.", "@role_id", "=", "value_i", ".", "zero?", "?", "nil", ":", "value_i", "# value as a String (if non-nil)", "value_s", "=", "@role_id", ".", "to_s", "if", "@role_id", "# call Java with a String", "setRoleId", "(", "value_s", ")", "end"], "docstring": "Sets the role id to the given value, which can be either a String or an Integer.\n An empty or zero value is converted to nil.\n\n @quirk caTissue caTissue API roleId is a String although the intended value domain is the\n integer csm_role.identifier.", "docstring_tokens": ["Sets", "the", "role", "id", "to", "the", "given", "value", "which", "can", "be", "either", "a", "String", "or", "an", "Integer", ".", "An", "empty", "or", "zero", "value", "is", "converted", "to", "nil", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/user.rb#L32-L41", "partition": "valid"} {"repo": "Smartibuy/SecondHandler", "path": "lib/second_handler.rb", "func_name": "SecondHandler.FbGroupPost.get_content", "original_string": "def get_content (&func)\n data = Array.new\n @feed.to_a.each do |single_post|\n begin\n if func.nil?\n data << clean_post_content(single_post, &@message_parser)\n else\n data << clean_post_content(single_post, &func)\n end\n rescue\n end\n end\n data\n end", "language": "ruby", "code": "def get_content (&func)\n data = Array.new\n @feed.to_a.each do |single_post|\n begin\n if func.nil?\n data << clean_post_content(single_post, &@message_parser)\n else\n data << clean_post_content(single_post, &func)\n end\n rescue\n end\n end\n data\n end", "code_tokens": ["def", "get_content", "(", "&", "func", ")", "data", "=", "Array", ".", "new", "@feed", ".", "to_a", ".", "each", "do", "|", "single_post", "|", "begin", "if", "func", ".", "nil?", "data", "<<", "clean_post_content", "(", "single_post", ",", "@message_parser", ")", "else", "data", "<<", "clean_post_content", "(", "single_post", ",", "func", ")", "end", "rescue", "end", "end", "data", "end"], "docstring": "return feed of current page infomation , including image", "docstring_tokens": ["return", "feed", "of", "current", "page", "infomation", "including", "image"], "sha": "b44b5d65b8735a3372376c4b701d3d46e0d7e09c", "url": "https://github.com/Smartibuy/SecondHandler/blob/b44b5d65b8735a3372376c4b701d3d46e0d7e09c/lib/second_handler.rb#L146-L159", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/database/controlled_value_finder.rb", "func_name": "CaTissue.ControlledValueFinder.controlled_value", "original_string": "def controlled_value(value)\n return if value.blank?\n ControlledValues.instance.find(@attribute, value) or\n raise ControlledValueError.new(\"#{@attribute} value '#{value}' is not a recognized controlled value.\")\n end", "language": "ruby", "code": "def controlled_value(value)\n return if value.blank?\n ControlledValues.instance.find(@attribute, value) or\n raise ControlledValueError.new(\"#{@attribute} value '#{value}' is not a recognized controlled value.\")\n end", "code_tokens": ["def", "controlled_value", "(", "value", ")", "return", "if", "value", ".", "blank?", "ControlledValues", ".", "instance", ".", "find", "(", "@attribute", ",", "value", ")", "or", "raise", "ControlledValueError", ".", "new", "(", "\"#{@attribute} value '#{value}' is not a recognized controlled value.\"", ")", "end"], "docstring": "Creates a new ControlledValueFinder for the given attribute.\n The optional YAML properties file name maps input values to controlled values.\n\n @param [Symbol] attribute the CV attribute\n Returns the CV value for the given source value. A case-insensitive lookup\n is performed on the CV.\n\n @param [String, nil] value the CV string value to find\n @raise [ControlledValueError] if the CV was not found\n @see ControlledValues#find", "docstring_tokens": ["Creates", "a", "new", "ControlledValueFinder", "for", "the", "given", "attribute", ".", "The", "optional", "YAML", "properties", "file", "name", "maps", "input", "values", "to", "controlled", "values", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/database/controlled_value_finder.rb#L22-L26", "partition": "valid"} {"repo": "knuedge/cratus", "path": "lib/cratus/config.rb", "func_name": "Cratus.Config.defaults", "original_string": "def defaults\n {\n group_dn_attribute: :cn,\n group_member_attribute: :member,\n group_description_attribute: :description,\n group_objectclass: :group,\n group_basedn: 'ou=groups,dc=example,dc=com',\n group_memberof_attribute: :memberOf,\n user_dn_attribute: :samaccountname,\n user_objectclass: :user,\n user_basedn: 'ou=users,dc=example,dc=com',\n user_account_control_attribute: :userAccountControl,\n user_department_attribute: :department,\n user_lockout_attribute: :lockouttime,\n user_mail_attribute: :mail,\n user_displayname_attribute: :displayName,\n user_memberof_attribute: :memberOf,\n host: 'ldap.example.com', port: 389,\n basedn: 'dc=example,dc=com',\n username: 'username',\n password: 'p@assedWard!',\n include_distribution_groups: true\n }\n end", "language": "ruby", "code": "def defaults\n {\n group_dn_attribute: :cn,\n group_member_attribute: :member,\n group_description_attribute: :description,\n group_objectclass: :group,\n group_basedn: 'ou=groups,dc=example,dc=com',\n group_memberof_attribute: :memberOf,\n user_dn_attribute: :samaccountname,\n user_objectclass: :user,\n user_basedn: 'ou=users,dc=example,dc=com',\n user_account_control_attribute: :userAccountControl,\n user_department_attribute: :department,\n user_lockout_attribute: :lockouttime,\n user_mail_attribute: :mail,\n user_displayname_attribute: :displayName,\n user_memberof_attribute: :memberOf,\n host: 'ldap.example.com', port: 389,\n basedn: 'dc=example,dc=com',\n username: 'username',\n password: 'p@assedWard!',\n include_distribution_groups: true\n }\n end", "code_tokens": ["def", "defaults", "{", "group_dn_attribute", ":", ":cn", ",", "group_member_attribute", ":", ":member", ",", "group_description_attribute", ":", ":description", ",", "group_objectclass", ":", ":group", ",", "group_basedn", ":", "'ou=groups,dc=example,dc=com'", ",", "group_memberof_attribute", ":", ":memberOf", ",", "user_dn_attribute", ":", ":samaccountname", ",", "user_objectclass", ":", ":user", ",", "user_basedn", ":", "'ou=users,dc=example,dc=com'", ",", "user_account_control_attribute", ":", ":userAccountControl", ",", "user_department_attribute", ":", ":department", ",", "user_lockout_attribute", ":", ":lockouttime", ",", "user_mail_attribute", ":", ":mail", ",", "user_displayname_attribute", ":", ":displayName", ",", "user_memberof_attribute", ":", ":memberOf", ",", "host", ":", "'ldap.example.com'", ",", "port", ":", "389", ",", "basedn", ":", "'dc=example,dc=com'", ",", "username", ":", "'username'", ",", "password", ":", "'p@assedWard!'", ",", "include_distribution_groups", ":", "true", "}", "end"], "docstring": "A Hash of the default configuration options", "docstring_tokens": ["A", "Hash", "of", "the", "default", "configuration", "options"], "sha": "a58465314a957db258f2c6bbda115c4be8ad0d83", "url": "https://github.com/knuedge/cratus/blob/a58465314a957db258f2c6bbda115c4be8ad0d83/lib/cratus/config.rb#L6-L29", "partition": "valid"} {"repo": "jonathanpike/mako", "path": "lib/mako/subscription_list_writer.rb", "func_name": "Mako.SubscriptionListWriter.append_and_write", "original_string": "def append_and_write\n contents = append_and_render\n File.open(destination, 'w+', encoding: 'utf-8') do |f|\n f.write(contents)\n end\n end", "language": "ruby", "code": "def append_and_write\n contents = append_and_render\n File.open(destination, 'w+', encoding: 'utf-8') do |f|\n f.write(contents)\n end\n end", "code_tokens": ["def", "append_and_write", "contents", "=", "append_and_render", "File", ".", "open", "(", "destination", ",", "'w+'", ",", "encoding", ":", "'utf-8'", ")", "do", "|", "f", "|", "f", ".", "write", "(", "contents", ")", "end", "end"], "docstring": "Appends the new subscriptions to the subscription list and\n writes the results out to the file.", "docstring_tokens": ["Appends", "the", "new", "subscriptions", "to", "the", "subscription", "list", "and", "writes", "the", "results", "out", "to", "the", "file", "."], "sha": "2aa3665ebf23f09727e59d667b34155755493bdf", "url": "https://github.com/jonathanpike/mako/blob/2aa3665ebf23f09727e59d667b34155755493bdf/lib/mako/subscription_list_writer.rb#L16-L21", "partition": "valid"} {"repo": "jonathanpike/mako", "path": "lib/mako/subscription_list_writer.rb", "func_name": "Mako.SubscriptionListWriter.render_opml", "original_string": "def render_opml(list)\n document = Nokogiri::XML(list.load_list)\n feeds.each do |feed_url|\n node = \"\\n\"\n document.xpath(\"//outline[@text='Subscriptions']\").last.add_child node\n end\n formatted_no_decl = Nokogiri::XML::Node::SaveOptions::FORMAT +\n Nokogiri::XML::Node::SaveOptions::NO_DECLARATION\n document.to_xml(encoding: 'utf-8', save_with: formatted_no_decl)\n end", "language": "ruby", "code": "def render_opml(list)\n document = Nokogiri::XML(list.load_list)\n feeds.each do |feed_url|\n node = \"\\n\"\n document.xpath(\"//outline[@text='Subscriptions']\").last.add_child node\n end\n formatted_no_decl = Nokogiri::XML::Node::SaveOptions::FORMAT +\n Nokogiri::XML::Node::SaveOptions::NO_DECLARATION\n document.to_xml(encoding: 'utf-8', save_with: formatted_no_decl)\n end", "code_tokens": ["def", "render_opml", "(", "list", ")", "document", "=", "Nokogiri", "::", "XML", "(", "list", ".", "load_list", ")", "feeds", ".", "each", "do", "|", "feed_url", "|", "node", "=", "\"\\n\"", "document", ".", "xpath", "(", "\"//outline[@text='Subscriptions']\"", ")", ".", "last", ".", "add_child", "node", "end", "formatted_no_decl", "=", "Nokogiri", "::", "XML", "::", "Node", "::", "SaveOptions", "::", "FORMAT", "+", "Nokogiri", "::", "XML", "::", "Node", "::", "SaveOptions", "::", "NO_DECLARATION", "document", ".", "to_xml", "(", "encoding", ":", "'utf-8'", ",", "save_with", ":", "formatted_no_decl", ")", "end"], "docstring": "Append feeds to current subscription list and return XML document\n\n @return [String]", "docstring_tokens": ["Append", "feeds", "to", "current", "subscription", "list", "and", "return", "XML", "document"], "sha": "2aa3665ebf23f09727e59d667b34155755493bdf", "url": "https://github.com/jonathanpike/mako/blob/2aa3665ebf23f09727e59d667b34155755493bdf/lib/mako/subscription_list_writer.rb#L58-L67", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/calculator.rb", "func_name": "Sycsvpro.Calculator.execute", "original_string": "def execute\n processed_header = false\n\n File.open(outfile, 'w') do |out|\n File.open(infile).each_with_index do |line, index|\n next if line.chomp.empty? || unstring(line).chomp.split(';').empty?\n\n unless processed_header\n header_row = header.process(line.chomp)\n header_row = @write_filter.process(header_row) unless @final_header\n out.puts header_row unless header_row.nil? or header_row.empty?\n processed_header = true\n next\n end\n\n next if row_filter.process(line, row: index).nil?\n\n @columns = unstring(line).chomp.split(';')\n formulae.each do |col, formula|\n @columns[col.to_i] = eval(formula)\n end\n out.puts @write_filter.process(@columns.join(';'))\n\n @columns.each_with_index do |column, index|\n column = 0 unless column.to_s =~ /^[\\d\\.,]*$/\n\n if @sum_row[index]\n @sum_row[index] += to_number column\n else\n @sum_row[index] = to_number column\n end\n end if add_sum_row\n\n end\n\n out.puts @write_filter.process(@sum_row.join(';')) if add_sum_row\n\n end\n end", "language": "ruby", "code": "def execute\n processed_header = false\n\n File.open(outfile, 'w') do |out|\n File.open(infile).each_with_index do |line, index|\n next if line.chomp.empty? || unstring(line).chomp.split(';').empty?\n\n unless processed_header\n header_row = header.process(line.chomp)\n header_row = @write_filter.process(header_row) unless @final_header\n out.puts header_row unless header_row.nil? or header_row.empty?\n processed_header = true\n next\n end\n\n next if row_filter.process(line, row: index).nil?\n\n @columns = unstring(line).chomp.split(';')\n formulae.each do |col, formula|\n @columns[col.to_i] = eval(formula)\n end\n out.puts @write_filter.process(@columns.join(';'))\n\n @columns.each_with_index do |column, index|\n column = 0 unless column.to_s =~ /^[\\d\\.,]*$/\n\n if @sum_row[index]\n @sum_row[index] += to_number column\n else\n @sum_row[index] = to_number column\n end\n end if add_sum_row\n\n end\n\n out.puts @write_filter.process(@sum_row.join(';')) if add_sum_row\n\n end\n end", "code_tokens": ["def", "execute", "processed_header", "=", "false", "File", ".", "open", "(", "outfile", ",", "'w'", ")", "do", "|", "out", "|", "File", ".", "open", "(", "infile", ")", ".", "each_with_index", "do", "|", "line", ",", "index", "|", "next", "if", "line", ".", "chomp", ".", "empty?", "||", "unstring", "(", "line", ")", ".", "chomp", ".", "split", "(", "';'", ")", ".", "empty?", "unless", "processed_header", "header_row", "=", "header", ".", "process", "(", "line", ".", "chomp", ")", "header_row", "=", "@write_filter", ".", "process", "(", "header_row", ")", "unless", "@final_header", "out", ".", "puts", "header_row", "unless", "header_row", ".", "nil?", "or", "header_row", ".", "empty?", "processed_header", "=", "true", "next", "end", "next", "if", "row_filter", ".", "process", "(", "line", ",", "row", ":", "index", ")", ".", "nil?", "@columns", "=", "unstring", "(", "line", ")", ".", "chomp", ".", "split", "(", "';'", ")", "formulae", ".", "each", "do", "|", "col", ",", "formula", "|", "@columns", "[", "col", ".", "to_i", "]", "=", "eval", "(", "formula", ")", "end", "out", ".", "puts", "@write_filter", ".", "process", "(", "@columns", ".", "join", "(", "';'", ")", ")", "@columns", ".", "each_with_index", "do", "|", "column", ",", "index", "|", "column", "=", "0", "unless", "column", ".", "to_s", "=~", "/", "\\d", "\\.", "/", "if", "@sum_row", "[", "index", "]", "@sum_row", "[", "index", "]", "+=", "to_number", "column", "else", "@sum_row", "[", "index", "]", "=", "to_number", "column", "end", "end", "if", "add_sum_row", "end", "out", ".", "puts", "@write_filter", ".", "process", "(", "@sum_row", ".", "join", "(", "';'", ")", ")", "if", "add_sum_row", "end", "end"], "docstring": "Executes the calculator and writes the result to the _outfile_", "docstring_tokens": ["Executes", "the", "calculator", "and", "writes", "the", "result", "to", "the", "_outfile_"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/calculator.rb#L118-L156", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/calculator.rb", "func_name": "Sycsvpro.Calculator.to_date", "original_string": "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", "language": "ruby", "code": "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", "code_tokens": ["def", "to_date", "(", "value", ")", "if", "value", ".", "nil?", "or", "value", ".", "strip", ".", "empty?", "nil", "else", "Date", ".", "strptime", "(", "value", ",", "date_format", ")", "end", "end"], "docstring": "Casts a string to a date", "docstring_tokens": ["Casts", "a", "string", "to", "a", "date"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/calculator.rb#L184-L190", "partition": "valid"} {"repo": "knuedge/cratus", "path": "lib/cratus/group.rb", "func_name": "Cratus.Group.add_user", "original_string": "def add_user(user)\n raise 'InvalidUser' unless user.respond_to?(:dn)\n direct_members = @raw_ldap_data[Cratus.config.group_member_attribute]\n return true if direct_members.include?(user.dn)\n\n direct_members << user.dn\n Cratus::LDAP.replace_attribute(\n dn,\n Cratus.config.group_member_attribute,\n direct_members.uniq\n )\n end", "language": "ruby", "code": "def add_user(user)\n raise 'InvalidUser' unless user.respond_to?(:dn)\n direct_members = @raw_ldap_data[Cratus.config.group_member_attribute]\n return true if direct_members.include?(user.dn)\n\n direct_members << user.dn\n Cratus::LDAP.replace_attribute(\n dn,\n Cratus.config.group_member_attribute,\n direct_members.uniq\n )\n end", "code_tokens": ["def", "add_user", "(", "user", ")", "raise", "'InvalidUser'", "unless", "user", ".", "respond_to?", "(", ":dn", ")", "direct_members", "=", "@raw_ldap_data", "[", "Cratus", ".", "config", ".", "group_member_attribute", "]", "return", "true", "if", "direct_members", ".", "include?", "(", "user", ".", "dn", ")", "direct_members", "<<", "user", ".", "dn", "Cratus", "::", "LDAP", ".", "replace_attribute", "(", "dn", ",", "Cratus", ".", "config", ".", "group_member_attribute", ",", "direct_members", ".", "uniq", ")", "end"], "docstring": "Add a User to the group", "docstring_tokens": ["Add", "a", "User", "to", "the", "group"], "sha": "a58465314a957db258f2c6bbda115c4be8ad0d83", "url": "https://github.com/knuedge/cratus/blob/a58465314a957db258f2c6bbda115c4be8ad0d83/lib/cratus/group.rb#L63-L74", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/database/annotation/annotator.rb", "func_name": "CaTissue.Annotator.create_annotation_service", "original_string": "def create_annotation_service(mod, name)\n @integrator = Annotation::Integrator.new(mod)\n Annotation::AnnotationService.new(@database, name, @integrator)\n end", "language": "ruby", "code": "def create_annotation_service(mod, name)\n @integrator = Annotation::Integrator.new(mod)\n Annotation::AnnotationService.new(@database, name, @integrator)\n end", "code_tokens": ["def", "create_annotation_service", "(", "mod", ",", "name", ")", "@integrator", "=", "Annotation", "::", "Integrator", ".", "new", "(", "mod", ")", "Annotation", "::", "AnnotationService", ".", "new", "(", "@database", ",", "name", ",", "@integrator", ")", "end"], "docstring": "Initializes a new Annotator for the given database.\n\n @param [CaTissue::Database] the database\n @param [Module] the annotation module\n @param [String] name the service name\n @return [Annotation::AnnotationService] the annotation service", "docstring_tokens": ["Initializes", "a", "new", "Annotator", "for", "the", "given", "database", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/database/annotation/annotator.rb#L20-L23", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/helpers/person.rb", "func_name": "CaTissue.Person.name", "original_string": "def name\n middle = middle_name if respond_to?(:middle_name)\n Name.new(last_name, first_name, middle) if last_name\n end", "language": "ruby", "code": "def name\n middle = middle_name if respond_to?(:middle_name)\n Name.new(last_name, first_name, middle) if last_name\n end", "code_tokens": ["def", "name", "middle", "=", "middle_name", "if", "respond_to?", "(", ":middle_name", ")", "Name", ".", "new", "(", "last_name", ",", "first_name", ",", "middle", ")", "if", "last_name", "end"], "docstring": "Returns this Person's name as a Name structure, or nil if there is no last name.", "docstring_tokens": ["Returns", "this", "Person", "s", "name", "as", "a", "Name", "structure", "or", "nil", "if", "there", "is", "no", "last", "name", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/helpers/person.rb#L11-L14", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/helpers/person.rb", "func_name": "CaTissue.Person.name=", "original_string": "def name=(value)\n value = Name.parse(value) if String === value\n # a missing name is equivalent to an empty name for our purposes here\n value = Name.new(nil, nil) if value.nil?\n unless Name === value then\n raise ArgumentError.new(\"Name argument type invalid; expected <#{Name}>, found <#{value.class}>\")\n end\n self.first_name = value.first\n self.last_name = value.last\n self.middle_name = value.middle if respond_to?(:middle_name)\n end", "language": "ruby", "code": "def name=(value)\n value = Name.parse(value) if String === value\n # a missing name is equivalent to an empty name for our purposes here\n value = Name.new(nil, nil) if value.nil?\n unless Name === value then\n raise ArgumentError.new(\"Name argument type invalid; expected <#{Name}>, found <#{value.class}>\")\n end\n self.first_name = value.first\n self.last_name = value.last\n self.middle_name = value.middle if respond_to?(:middle_name)\n end", "code_tokens": ["def", "name", "=", "(", "value", ")", "value", "=", "Name", ".", "parse", "(", "value", ")", "if", "String", "===", "value", "# a missing name is equivalent to an empty name for our purposes here", "value", "=", "Name", ".", "new", "(", "nil", ",", "nil", ")", "if", "value", ".", "nil?", "unless", "Name", "===", "value", "then", "raise", "ArgumentError", ".", "new", "(", "\"Name argument type invalid; expected <#{Name}>, found <#{value.class}>\"", ")", "end", "self", ".", "first_name", "=", "value", ".", "first", "self", ".", "last_name", "=", "value", ".", "last", "self", ".", "middle_name", "=", "value", ".", "middle", "if", "respond_to?", "(", ":middle_name", ")", "end"], "docstring": "Sets this Person's name to the name string or Name object.\n A string name argument is parsed using Name.parse.\n\n @quirk caTissue CaTissue person names are inconsistent: Participant has a middle name, User doesn't.", "docstring_tokens": ["Sets", "this", "Person", "s", "name", "to", "the", "name", "string", "or", "Name", "object", ".", "A", "string", "name", "argument", "is", "parsed", "using", "Name", ".", "parse", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/helpers/person.rb#L20-L30", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/database/controlled_values.rb", "func_name": "CaTissue.ControlledValues.find", "original_string": "def find(public_id_or_alias, value, recursive=false)\n pid = ControlledValue.standard_public_id(public_id_or_alias)\n value_cv_hash = @pid_value_cv_hash[pid]\n cv = value_cv_hash[value]\n if recursive then\n fetch_descendants(cv, value_cv_hash)\n end\n cv\n end", "language": "ruby", "code": "def find(public_id_or_alias, value, recursive=false)\n pid = ControlledValue.standard_public_id(public_id_or_alias)\n value_cv_hash = @pid_value_cv_hash[pid]\n cv = value_cv_hash[value]\n if recursive then\n fetch_descendants(cv, value_cv_hash)\n end\n cv\n end", "code_tokens": ["def", "find", "(", "public_id_or_alias", ",", "value", ",", "recursive", "=", "false", ")", "pid", "=", "ControlledValue", ".", "standard_public_id", "(", "public_id_or_alias", ")", "value_cv_hash", "=", "@pid_value_cv_hash", "[", "pid", "]", "cv", "=", "value_cv_hash", "[", "value", "]", "if", "recursive", "then", "fetch_descendants", "(", "cv", ",", "value_cv_hash", ")", "end", "cv", "end"], "docstring": "Returns the CV with the given public_id_or_alias and value. Loads the CV if necessary\n from the database. The loaded CV does not have a parent or children.\n\n @param [String, Symbol] public_id_or_alias the caTissue public id or alias\n @param [String] value the CV value\n @param [Boolean] recursive whether to load the CV children as well.\n @return [CaRuby::ControlledValue, nil] the matching CV, or nil if no match", "docstring_tokens": ["Returns", "the", "CV", "with", "the", "given", "public_id_or_alias", "and", "value", ".", "Loads", "the", "CV", "if", "necessary", "from", "the", "database", ".", "The", "loaded", "CV", "does", "not", "have", "a", "parent", "or", "children", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/database/controlled_values.rb#L48-L56", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/database/controlled_values.rb", "func_name": "CaTissue.ControlledValues.create", "original_string": "def create(cv)\n if cv.public_id.nil? then\n raise ArgumentError.new(\"Controlled value create is missing a public id\")\n end\n if cv.value.nil? then\n raise ArgumentError.new(\"Controlled value create is missing a value\")\n end\n cv.identifier ||= next_id\n logger.debug { \"Creating controlled value #{cv} in the database...\" }\n @executor.transact(INSERT_STMT, cv.identifier, cv.parent_identifier, cv.public_id, cv.value)\n logger.debug { \"Controlled value #{cv.public_id} #{cv.value} created with identifier #{cv.identifier}\" }\n @pid_value_cv_hash[cv.public_id][cv.value] = cv\n end", "language": "ruby", "code": "def create(cv)\n if cv.public_id.nil? then\n raise ArgumentError.new(\"Controlled value create is missing a public id\")\n end\n if cv.value.nil? then\n raise ArgumentError.new(\"Controlled value create is missing a value\")\n end\n cv.identifier ||= next_id\n logger.debug { \"Creating controlled value #{cv} in the database...\" }\n @executor.transact(INSERT_STMT, cv.identifier, cv.parent_identifier, cv.public_id, cv.value)\n logger.debug { \"Controlled value #{cv.public_id} #{cv.value} created with identifier #{cv.identifier}\" }\n @pid_value_cv_hash[cv.public_id][cv.value] = cv\n end", "code_tokens": ["def", "create", "(", "cv", ")", "if", "cv", ".", "public_id", ".", "nil?", "then", "raise", "ArgumentError", ".", "new", "(", "\"Controlled value create is missing a public id\"", ")", "end", "if", "cv", ".", "value", ".", "nil?", "then", "raise", "ArgumentError", ".", "new", "(", "\"Controlled value create is missing a value\"", ")", "end", "cv", ".", "identifier", "||=", "next_id", "logger", ".", "debug", "{", "\"Creating controlled value #{cv} in the database...\"", "}", "@executor", ".", "transact", "(", "INSERT_STMT", ",", "cv", ".", "identifier", ",", "cv", ".", "parent_identifier", ",", "cv", ".", "public_id", ",", "cv", ".", "value", ")", "logger", ".", "debug", "{", "\"Controlled value #{cv.public_id} #{cv.value} created with identifier #{cv.identifier}\"", "}", "@pid_value_cv_hash", "[", "cv", ".", "public_id", "]", "[", "cv", ".", "value", "]", "=", "cv", "end"], "docstring": "Creates a new controlled value record in the database from the given ControlledValue cv.\n The default identifier is the next identifier in the permissible values table.\n\n @param [ControlledValue] cv the controlled value to create\n @return [ControlledValue] the created CV", "docstring_tokens": ["Creates", "a", "new", "controlled", "value", "record", "in", "the", "database", "from", "the", "given", "ControlledValue", "cv", ".", "The", "default", "identifier", "is", "the", "next", "identifier", "in", "the", "permissible", "values", "table", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/database/controlled_values.rb#L63-L75", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/database/controlled_values.rb", "func_name": "CaTissue.ControlledValues.delete", "original_string": "def delete(cv)\n @executor.transact do |dbh|\n sth = dbh.prepare(DELETE_STMT)\n delete_recursive(cv, sth)\n sth.finish\n end\n end", "language": "ruby", "code": "def delete(cv)\n @executor.transact do |dbh|\n sth = dbh.prepare(DELETE_STMT)\n delete_recursive(cv, sth)\n sth.finish\n end\n end", "code_tokens": ["def", "delete", "(", "cv", ")", "@executor", ".", "transact", "do", "|", "dbh", "|", "sth", "=", "dbh", ".", "prepare", "(", "DELETE_STMT", ")", "delete_recursive", "(", "cv", ",", "sth", ")", "sth", ".", "finish", "end", "end"], "docstring": "Deletes the given ControlledValue record in the database. Recursively deletes the\n transitive closure of children as well.\n\n @param [ControlledValue] cv the controlled value to delete", "docstring_tokens": ["Deletes", "the", "given", "ControlledValue", "record", "in", "the", "database", ".", "Recursively", "deletes", "the", "transitive", "closure", "of", "children", "as", "well", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/database/controlled_values.rb#L81-L87", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/database/controlled_values.rb", "func_name": "CaTissue.ControlledValues.make_controlled_value", "original_string": "def make_controlled_value(value_hash)\n cv = ControlledValue.new(value_hash[:value], value_hash[:parent])\n cv.identifier = value_hash[:identifier]\n cv.public_id = value_hash[:public_id]\n cv\n end", "language": "ruby", "code": "def make_controlled_value(value_hash)\n cv = ControlledValue.new(value_hash[:value], value_hash[:parent])\n cv.identifier = value_hash[:identifier]\n cv.public_id = value_hash[:public_id]\n cv\n end", "code_tokens": ["def", "make_controlled_value", "(", "value_hash", ")", "cv", "=", "ControlledValue", ".", "new", "(", "value_hash", "[", ":value", "]", ",", "value_hash", "[", ":parent", "]", ")", "cv", ".", "identifier", "=", "value_hash", "[", ":identifier", "]", "cv", ".", "public_id", "=", "value_hash", "[", ":public_id", "]", "cv", "end"], "docstring": "Returns a new ControlledValue with attributes set by the given attribute => value hash.", "docstring_tokens": ["Returns", "a", "new", "ControlledValue", "with", "attributes", "set", "by", "the", "given", "attribute", "=", ">", "value", "hash", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/database/controlled_values.rb#L174-L179", "partition": "valid"} {"repo": "nbaum/blower", "path": "lib/blower/context.rb", "func_name": "Blower.Context.with", "original_string": "def with (hash, quiet: false)\n old_values = data.values_at(hash.keys)\n log.debug \"with #{hash}\", quiet: quiet do\n set hash\n yield\n end\n ensure\n hash.keys.each.with_index do |key, i|\n @data[key] = old_values[i]\n end\n end", "language": "ruby", "code": "def with (hash, quiet: false)\n old_values = data.values_at(hash.keys)\n log.debug \"with #{hash}\", quiet: quiet do\n set hash\n yield\n end\n ensure\n hash.keys.each.with_index do |key, i|\n @data[key] = old_values[i]\n end\n end", "code_tokens": ["def", "with", "(", "hash", ",", "quiet", ":", "false", ")", "old_values", "=", "data", ".", "values_at", "(", "hash", ".", "keys", ")", "log", ".", "debug", "\"with #{hash}\"", ",", "quiet", ":", "quiet", "do", "set", "hash", "yield", "end", "ensure", "hash", ".", "keys", ".", "each", ".", "with_index", "do", "|", "key", ",", "i", "|", "@data", "[", "key", "]", "=", "old_values", "[", "i", "]", "end", "end"], "docstring": "Yield with the hash temporary merged into the context variables.\n Only variables specifically named in +hash+ will be reset when the yield returns.\n @param [Hash] hash The values to merge into the context variables.\n @return Whatever the yielded-to block returns.\n @macro quietable", "docstring_tokens": ["Yield", "with", "the", "hash", "temporary", "merged", "into", "the", "context", "variables", ".", "Only", "variables", "specifically", "named", "in", "+", "hash", "+", "will", "be", "reset", "when", "the", "yield", "returns", "."], "sha": "9e09a56f9d4bf547bf1aa1843d894be625a27628", "url": "https://github.com/nbaum/blower/blob/9e09a56f9d4bf547bf1aa1843d894be625a27628/lib/blower/context.rb#L75-L85", "partition": "valid"} {"repo": "nbaum/blower", "path": "lib/blower/context.rb", "func_name": "Blower.Context.on", "original_string": "def on (*hosts, quiet: false)\n let :@hosts => hosts.flatten do\n log.info \"on #{@hosts.map(&:name).join(\", \")}\", quiet: quiet do\n yield\n end\n end\n end", "language": "ruby", "code": "def on (*hosts, quiet: false)\n let :@hosts => hosts.flatten do\n log.info \"on #{@hosts.map(&:name).join(\", \")}\", quiet: quiet do\n yield\n end\n end\n end", "code_tokens": ["def", "on", "(", "*", "hosts", ",", "quiet", ":", "false", ")", "let", ":@hosts", "=>", "hosts", ".", "flatten", "do", "log", ".", "info", "\"on #{@hosts.map(&:name).join(\", \")}\"", ",", "quiet", ":", "quiet", "do", "yield", "end", "end", "end"], "docstring": "Yield with a temporary host list\n @macro quietable", "docstring_tokens": ["Yield", "with", "a", "temporary", "host", "list"], "sha": "9e09a56f9d4bf547bf1aa1843d894be625a27628", "url": "https://github.com/nbaum/blower/blob/9e09a56f9d4bf547bf1aa1843d894be625a27628/lib/blower/context.rb#L89-L95", "partition": "valid"} {"repo": "nbaum/blower", "path": "lib/blower/context.rb", "func_name": "Blower.Context.as", "original_string": "def as (user, quiet: false)\n let :@user => user do\n log.info \"as #{user}\", quiet: quiet do\n yield\n end\n end\n end", "language": "ruby", "code": "def as (user, quiet: false)\n let :@user => user do\n log.info \"as #{user}\", quiet: quiet do\n yield\n end\n end\n end", "code_tokens": ["def", "as", "(", "user", ",", "quiet", ":", "false", ")", "let", ":@user", "=>", "user", "do", "log", ".", "info", "\"as #{user}\"", ",", "quiet", ":", "quiet", "do", "yield", "end", "end", "end"], "docstring": "Yield with a temporary username override\n @macro quietable", "docstring_tokens": ["Yield", "with", "a", "temporary", "username", "override"], "sha": "9e09a56f9d4bf547bf1aa1843d894be625a27628", "url": "https://github.com/nbaum/blower/blob/9e09a56f9d4bf547bf1aa1843d894be625a27628/lib/blower/context.rb#L99-L105", "partition": "valid"} {"repo": "nbaum/blower", "path": "lib/blower/context.rb", "func_name": "Blower.Context.sh", "original_string": "def sh (command, as: user, on: hosts, quiet: false, once: nil)\n self.once once, quiet: quiet do\n log.info \"sh #{command}\", quiet: quiet do\n hash_map(hosts) do |host|\n host.sh command, as: as, quiet: quiet\n end\n end\n end\n end", "language": "ruby", "code": "def sh (command, as: user, on: hosts, quiet: false, once: nil)\n self.once once, quiet: quiet do\n log.info \"sh #{command}\", quiet: quiet do\n hash_map(hosts) do |host|\n host.sh command, as: as, quiet: quiet\n end\n end\n end\n end", "code_tokens": ["def", "sh", "(", "command", ",", "as", ":", "user", ",", "on", ":", "hosts", ",", "quiet", ":", "false", ",", "once", ":", "nil", ")", "self", ".", "once", "once", ",", "quiet", ":", "quiet", "do", "log", ".", "info", "\"sh #{command}\"", ",", "quiet", ":", "quiet", "do", "hash_map", "(", "hosts", ")", "do", "|", "host", "|", "host", ".", "sh", "command", ",", "as", ":", "as", ",", "quiet", ":", "quiet", "end", "end", "end", "end"], "docstring": "Execute a shell command on each host\n @macro onable\n @macro asable\n @macro quietable\n @macro onceable", "docstring_tokens": ["Execute", "a", "shell", "command", "on", "each", "host"], "sha": "9e09a56f9d4bf547bf1aa1843d894be625a27628", "url": "https://github.com/nbaum/blower/blob/9e09a56f9d4bf547bf1aa1843d894be625a27628/lib/blower/context.rb#L136-L144", "partition": "valid"} {"repo": "nbaum/blower", "path": "lib/blower/context.rb", "func_name": "Blower.Context.cp", "original_string": "def cp (from, to, as: user, on: hosts, quiet: false, once: nil)\n self.once once, quiet: quiet do\n log.info \"cp: #{from} -> #{to}\", quiet: quiet do\n Dir.chdir File.dirname(file) do\n hash_map(hosts) do |host|\n host.cp from, to, as: as, quiet: quiet\n end\n end\n end\n end\n end", "language": "ruby", "code": "def cp (from, to, as: user, on: hosts, quiet: false, once: nil)\n self.once once, quiet: quiet do\n log.info \"cp: #{from} -> #{to}\", quiet: quiet do\n Dir.chdir File.dirname(file) do\n hash_map(hosts) do |host|\n host.cp from, to, as: as, quiet: quiet\n end\n end\n end\n end\n end", "code_tokens": ["def", "cp", "(", "from", ",", "to", ",", "as", ":", "user", ",", "on", ":", "hosts", ",", "quiet", ":", "false", ",", "once", ":", "nil", ")", "self", ".", "once", "once", ",", "quiet", ":", "quiet", "do", "log", ".", "info", "\"cp: #{from} -> #{to}\"", ",", "quiet", ":", "quiet", "do", "Dir", ".", "chdir", "File", ".", "dirname", "(", "file", ")", "do", "hash_map", "(", "hosts", ")", "do", "|", "host", "|", "host", ".", "cp", "from", ",", "to", ",", "as", ":", "as", ",", "quiet", ":", "quiet", "end", "end", "end", "end", "end"], "docstring": "Copy a file or readable to the host filesystems.\n @overload cp(readable, to, as: user, on: hosts, quiet: false)\n @param [#read] from An object from which to read the contents of the new file.\n @param [String] to The file name to write the string to.\n @macro onable\n @macro asable\n @macro quietable\n @macro onceable\n @overload cp(filename, to, as: user, on: hosts, quiet: false)\n @param [String] from The name of the local file to copy.\n @param [String] to The file name to write the string to.\n @macro onable\n @macro asable\n @macro quietable\n @macro onceable", "docstring_tokens": ["Copy", "a", "file", "or", "readable", "to", "the", "host", "filesystems", "."], "sha": "9e09a56f9d4bf547bf1aa1843d894be625a27628", "url": "https://github.com/nbaum/blower/blob/9e09a56f9d4bf547bf1aa1843d894be625a27628/lib/blower/context.rb#L161-L171", "partition": "valid"} {"repo": "nbaum/blower", "path": "lib/blower/context.rb", "func_name": "Blower.Context.read", "original_string": "def read (filename, as: user, on: hosts, quiet: false)\n log.info \"read: #{filename}\", quiet: quiet do\n hash_map(hosts) do |host|\n host.read filename, as: as\n end\n end\n end", "language": "ruby", "code": "def read (filename, as: user, on: hosts, quiet: false)\n log.info \"read: #{filename}\", quiet: quiet do\n hash_map(hosts) do |host|\n host.read filename, as: as\n end\n end\n end", "code_tokens": ["def", "read", "(", "filename", ",", "as", ":", "user", ",", "on", ":", "hosts", ",", "quiet", ":", "false", ")", "log", ".", "info", "\"read: #{filename}\"", ",", "quiet", ":", "quiet", "do", "hash_map", "(", "hosts", ")", "do", "|", "host", "|", "host", ".", "read", "filename", ",", "as", ":", "as", "end", "end", "end"], "docstring": "Reads a remote file from each host.\n @param [String] filename The file to read.\n @return [Hash] A hash of +Host+ objects to +Strings+ of the file contents.\n @macro onable\n @macro asable\n @macro quietable", "docstring_tokens": ["Reads", "a", "remote", "file", "from", "each", "host", "."], "sha": "9e09a56f9d4bf547bf1aa1843d894be625a27628", "url": "https://github.com/nbaum/blower/blob/9e09a56f9d4bf547bf1aa1843d894be625a27628/lib/blower/context.rb#L179-L185", "partition": "valid"} {"repo": "nbaum/blower", "path": "lib/blower/context.rb", "func_name": "Blower.Context.write", "original_string": "def write (string, to, as: user, on: hosts, quiet: false, once: nil)\n self.once once, quiet: quiet do\n log.info \"write: #{string.bytesize} bytes -> #{to}\", quiet: quiet do\n hash_map(hosts) do |host|\n host.write string, to, as: as, quiet: quiet\n end\n end\n end\n end", "language": "ruby", "code": "def write (string, to, as: user, on: hosts, quiet: false, once: nil)\n self.once once, quiet: quiet do\n log.info \"write: #{string.bytesize} bytes -> #{to}\", quiet: quiet do\n hash_map(hosts) do |host|\n host.write string, to, as: as, quiet: quiet\n end\n end\n end\n end", "code_tokens": ["def", "write", "(", "string", ",", "to", ",", "as", ":", "user", ",", "on", ":", "hosts", ",", "quiet", ":", "false", ",", "once", ":", "nil", ")", "self", ".", "once", "once", ",", "quiet", ":", "quiet", "do", "log", ".", "info", "\"write: #{string.bytesize} bytes -> #{to}\"", ",", "quiet", ":", "quiet", "do", "hash_map", "(", "hosts", ")", "do", "|", "host", "|", "host", ".", "write", "string", ",", "to", ",", "as", ":", "as", ",", "quiet", ":", "quiet", "end", "end", "end", "end"], "docstring": "Writes a string to a file on the host filesystems.\n @param [String] string The string to write.\n @param [String] to The file name to write the string to.\n @macro onable\n @macro asable\n @macro quietable\n @macro onceable", "docstring_tokens": ["Writes", "a", "string", "to", "a", "file", "on", "the", "host", "filesystems", "."], "sha": "9e09a56f9d4bf547bf1aa1843d894be625a27628", "url": "https://github.com/nbaum/blower/blob/9e09a56f9d4bf547bf1aa1843d894be625a27628/lib/blower/context.rb#L194-L202", "partition": "valid"} {"repo": "nbaum/blower", "path": "lib/blower/context.rb", "func_name": "Blower.Context.ping", "original_string": "def ping (on: hosts, quiet: false)\n log.info \"ping\", quiet: quiet do\n hash_map(hosts) do |host|\n host.ping\n end\n end\n end", "language": "ruby", "code": "def ping (on: hosts, quiet: false)\n log.info \"ping\", quiet: quiet do\n hash_map(hosts) do |host|\n host.ping\n end\n end\n end", "code_tokens": ["def", "ping", "(", "on", ":", "hosts", ",", "quiet", ":", "false", ")", "log", ".", "info", "\"ping\"", ",", "quiet", ":", "quiet", "do", "hash_map", "(", "hosts", ")", "do", "|", "host", "|", "host", ".", "ping", "end", "end", "end"], "docstring": "Ping each host by trying to connect to port 22\n @macro onable\n @macro quietable", "docstring_tokens": ["Ping", "each", "host", "by", "trying", "to", "connect", "to", "port", "22"], "sha": "9e09a56f9d4bf547bf1aa1843d894be625a27628", "url": "https://github.com/nbaum/blower/blob/9e09a56f9d4bf547bf1aa1843d894be625a27628/lib/blower/context.rb#L231-L237", "partition": "valid"} {"repo": "nbaum/blower", "path": "lib/blower/context.rb", "func_name": "Blower.Context.once", "original_string": "def once (key, store: \"/var/cache/blower.json\", quiet: false)\n return yield unless key\n log.info \"once: #{key}\", quiet: quiet do\n hash_map(hosts) do |host|\n done = begin\n JSON.parse(host.read(store, quiet: true))\n rescue => e\n {}\n end\n unless done[key]\n on [host] do\n yield\n end\n done[key] = true\n host.write(done.to_json, store, quiet: true)\n end\n end\n end\n end", "language": "ruby", "code": "def once (key, store: \"/var/cache/blower.json\", quiet: false)\n return yield unless key\n log.info \"once: #{key}\", quiet: quiet do\n hash_map(hosts) do |host|\n done = begin\n JSON.parse(host.read(store, quiet: true))\n rescue => e\n {}\n end\n unless done[key]\n on [host] do\n yield\n end\n done[key] = true\n host.write(done.to_json, store, quiet: true)\n end\n end\n end\n end", "code_tokens": ["def", "once", "(", "key", ",", "store", ":", "\"/var/cache/blower.json\"", ",", "quiet", ":", "false", ")", "return", "yield", "unless", "key", "log", ".", "info", "\"once: #{key}\"", ",", "quiet", ":", "quiet", "do", "hash_map", "(", "hosts", ")", "do", "|", "host", "|", "done", "=", "begin", "JSON", ".", "parse", "(", "host", ".", "read", "(", "store", ",", "quiet", ":", "true", ")", ")", "rescue", "=>", "e", "{", "}", "end", "unless", "done", "[", "key", "]", "on", "[", "host", "]", "do", "yield", "end", "done", "[", "key", "]", "=", "true", "host", ".", "write", "(", "done", ".", "to_json", ",", "store", ",", "quiet", ":", "true", ")", "end", "end", "end", "end"], "docstring": "Execute a block only once per host.\n It is usually preferable to make tasks idempotent, but when that isn't\n possible, +once+ will only execute the block on hosts where a block\n with the same key hasn't previously been successfully executed.\n @param [String] key Uniquely identifies the block.\n @param [String] store File to store +once+'s state in.\n @macro quietable", "docstring_tokens": ["Execute", "a", "block", "only", "once", "per", "host", ".", "It", "is", "usually", "preferable", "to", "make", "tasks", "idempotent", "but", "when", "that", "isn", "t", "possible", "+", "once", "+", "will", "only", "execute", "the", "block", "on", "hosts", "where", "a", "block", "with", "the", "same", "key", "hasn", "t", "previously", "been", "successfully", "executed", "."], "sha": "9e09a56f9d4bf547bf1aa1843d894be625a27628", "url": "https://github.com/nbaum/blower/blob/9e09a56f9d4bf547bf1aa1843d894be625a27628/lib/blower/context.rb#L246-L264", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/authorized_user.rb", "func_name": "Turntabler.AuthorizedUser.update", "original_string": "def update(attributes = {})\n assert_valid_keys(attributes, :name, :status, :laptop_name, :twitter_id, :facebook_url, :website, :about, :top_artists, :hangout)\n\n # Update status\n status = attributes.delete(:status)\n update_status(status) if status\n\n # Update laptop\n laptop_name = attributes.delete(:laptop_name)\n update_laptop(laptop_name) if laptop_name\n\n # Update profile with remaining data\n update_profile(attributes) if attributes.any?\n\n true\n end", "language": "ruby", "code": "def update(attributes = {})\n assert_valid_keys(attributes, :name, :status, :laptop_name, :twitter_id, :facebook_url, :website, :about, :top_artists, :hangout)\n\n # Update status\n status = attributes.delete(:status)\n update_status(status) if status\n\n # Update laptop\n laptop_name = attributes.delete(:laptop_name)\n update_laptop(laptop_name) if laptop_name\n\n # Update profile with remaining data\n update_profile(attributes) if attributes.any?\n\n true\n end", "code_tokens": ["def", "update", "(", "attributes", "=", "{", "}", ")", "assert_valid_keys", "(", "attributes", ",", ":name", ",", ":status", ",", ":laptop_name", ",", ":twitter_id", ",", ":facebook_url", ",", ":website", ",", ":about", ",", ":top_artists", ",", ":hangout", ")", "# Update status", "status", "=", "attributes", ".", "delete", "(", ":status", ")", "update_status", "(", "status", ")", "if", "status", "# Update laptop", "laptop_name", "=", "attributes", ".", "delete", "(", ":laptop_name", ")", "update_laptop", "(", "laptop_name", ")", "if", "laptop_name", "# Update profile with remaining data", "update_profile", "(", "attributes", ")", "if", "attributes", ".", "any?", "true", "end"], "docstring": "Updates this user's profile information.\n\n @param [Hash] attributes The attributes to update\n @option attributes [String] :name\n @option attributes [String] :status Valid values include \"available\", \"unavailable\", and \"away\"\n @option attributes [String] :laptop_name Valid values include \"mac\", \"pc\", \"linux\", \"chrome\", \"iphone\", \"cake\", \"intel\", and \"android\"\n @option attributes [String] :twitter_id\n @option attributes [String] :facebook_url\n @option attributes [String] :website\n @option attributes [String] :about\n @option attributes [String] :top_artists\n @option attributes [String] :hangout\n @return [true]\n @raise [ArgumentError] if an invalid attribute or value is specified\n @raise [Turntabler::Error] if the command fails\n @example\n user.update(:status => \"away\") # => true\n user.update(:laptop_name => \"mac\") # => true\n user.update(:name => \"...\") # => true", "docstring_tokens": ["Updates", "this", "user", "s", "profile", "information", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/authorized_user.rb#L130-L145", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/authorized_user.rb", "func_name": "Turntabler.AuthorizedUser.buddies", "original_string": "def buddies\n data = api('user.get_buddies')\n data['buddies'].map {|id| User.new(client, :_id => id)}\n end", "language": "ruby", "code": "def buddies\n data = api('user.get_buddies')\n data['buddies'].map {|id| User.new(client, :_id => id)}\n end", "code_tokens": ["def", "buddies", "data", "=", "api", "(", "'user.get_buddies'", ")", "data", "[", "'buddies'", "]", ".", "map", "{", "|", "id", "|", "User", ".", "new", "(", "client", ",", ":_id", "=>", "id", ")", "}", "end"], "docstring": "Loads the list of users that are connected to the current user through a\n social network like Facebook or Twitter.\n\n @return [Array]\n @raise [Turntabler::Error] if the command fails\n @example\n user.buddies # => [#, ...]", "docstring_tokens": ["Loads", "the", "list", "of", "users", "that", "are", "connected", "to", "the", "current", "user", "through", "a", "social", "network", "like", "Facebook", "or", "Twitter", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/authorized_user.rb#L154-L157", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/authorized_user.rb", "func_name": "Turntabler.AuthorizedUser.fan_of", "original_string": "def fan_of\n data = api('user.get_fan_of')\n data['fanof'].map {|id| User.new(client, :_id => id)}\n end", "language": "ruby", "code": "def fan_of\n data = api('user.get_fan_of')\n data['fanof'].map {|id| User.new(client, :_id => id)}\n end", "code_tokens": ["def", "fan_of", "data", "=", "api", "(", "'user.get_fan_of'", ")", "data", "[", "'fanof'", "]", ".", "map", "{", "|", "id", "|", "User", ".", "new", "(", "client", ",", ":_id", "=>", "id", ")", "}", "end"], "docstring": "Loads the list of users that the current user is a fan of.\n\n @return [Array]\n @raise [Turntabler::Error] if the command fails\n @example\n user.fan_of # => [#, ...]", "docstring_tokens": ["Loads", "the", "list", "of", "users", "that", "the", "current", "user", "is", "a", "fan", "of", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/authorized_user.rb#L165-L168", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/authorized_user.rb", "func_name": "Turntabler.AuthorizedUser.fans", "original_string": "def fans\n data = api('user.get_fans')\n data['fans'].map {|id| User.new(client, :_id => id)}\n end", "language": "ruby", "code": "def fans\n data = api('user.get_fans')\n data['fans'].map {|id| User.new(client, :_id => id)}\n end", "code_tokens": ["def", "fans", "data", "=", "api", "(", "'user.get_fans'", ")", "data", "[", "'fans'", "]", ".", "map", "{", "|", "id", "|", "User", ".", "new", "(", "client", ",", ":_id", "=>", "id", ")", "}", "end"], "docstring": "Loads the list of users that are a fan of the current user.\n\n @return [Array]\n @raise [Turntabler::Error] if the command fails\n @example\n user.fans # => [#, ...]", "docstring_tokens": ["Loads", "the", "list", "of", "users", "that", "are", "a", "fan", "of", "the", "current", "user", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/authorized_user.rb#L176-L179", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/authorized_user.rb", "func_name": "Turntabler.AuthorizedUser.stickers_purchased", "original_string": "def stickers_purchased\n data = api('sticker.get_purchased_stickers')\n data['stickers'].map {|sticker_id| Sticker.new(client, :_id => sticker_id)}\n end", "language": "ruby", "code": "def stickers_purchased\n data = api('sticker.get_purchased_stickers')\n data['stickers'].map {|sticker_id| Sticker.new(client, :_id => sticker_id)}\n end", "code_tokens": ["def", "stickers_purchased", "data", "=", "api", "(", "'sticker.get_purchased_stickers'", ")", "data", "[", "'stickers'", "]", ".", "map", "{", "|", "sticker_id", "|", "Sticker", ".", "new", "(", "client", ",", ":_id", "=>", "sticker_id", ")", "}", "end"], "docstring": "Gets the stickers that have been purchased by this user.\n\n @return [Array]\n @raise [Turntabler::Error] if the command fails\n @example\n user.stickers_purchased # => [#, ...]", "docstring_tokens": ["Gets", "the", "stickers", "that", "have", "been", "purchased", "by", "this", "user", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/authorized_user.rb#L209-L212", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/authorized_user.rb", "func_name": "Turntabler.AuthorizedUser.blocks", "original_string": "def blocks\n data = api('block.list_all')\n data['blocks'].map {|attrs| User.new(client, attrs['block']['blocked'])}\n end", "language": "ruby", "code": "def blocks\n data = api('block.list_all')\n data['blocks'].map {|attrs| User.new(client, attrs['block']['blocked'])}\n end", "code_tokens": ["def", "blocks", "data", "=", "api", "(", "'block.list_all'", ")", "data", "[", "'blocks'", "]", ".", "map", "{", "|", "attrs", "|", "User", ".", "new", "(", "client", ",", "attrs", "[", "'block'", "]", "[", "'blocked'", "]", ")", "}", "end"], "docstring": "Gets the users that have been blocked by this user.\n\n @return [Array]\n @raise [Turntabler::Error] if the command fails\n @example\n user.blocks # => [#, ...]", "docstring_tokens": ["Gets", "the", "users", "that", "have", "been", "blocked", "by", "this", "user", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/authorized_user.rb#L220-L223", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/authorized_user.rb", "func_name": "Turntabler.AuthorizedUser.update_profile", "original_string": "def update_profile(attributes = {})\n assert_valid_keys(attributes, :name, :twitter_id, :facebook_url, :website, :about, :top_artists, :hangout)\n\n # Convert attribute names over to their Turntable equivalent\n {:twitter_id => :twitter, :facebook_url => :facebook, :top_artists => :topartists}.each do |from, to|\n attributes[to] = attributes.delete(from) if attributes[from]\n end\n\n api('user.modify_profile', attributes)\n self.attributes = attributes\n true\n end", "language": "ruby", "code": "def update_profile(attributes = {})\n assert_valid_keys(attributes, :name, :twitter_id, :facebook_url, :website, :about, :top_artists, :hangout)\n\n # Convert attribute names over to their Turntable equivalent\n {:twitter_id => :twitter, :facebook_url => :facebook, :top_artists => :topartists}.each do |from, to|\n attributes[to] = attributes.delete(from) if attributes[from]\n end\n\n api('user.modify_profile', attributes)\n self.attributes = attributes\n true\n end", "code_tokens": ["def", "update_profile", "(", "attributes", "=", "{", "}", ")", "assert_valid_keys", "(", "attributes", ",", ":name", ",", ":twitter_id", ",", ":facebook_url", ",", ":website", ",", ":about", ",", ":top_artists", ",", ":hangout", ")", "# Convert attribute names over to their Turntable equivalent", "{", ":twitter_id", "=>", ":twitter", ",", ":facebook_url", "=>", ":facebook", ",", ":top_artists", "=>", ":topartists", "}", ".", "each", "do", "|", "from", ",", "to", "|", "attributes", "[", "to", "]", "=", "attributes", ".", "delete", "(", "from", ")", "if", "attributes", "[", "from", "]", "end", "api", "(", "'user.modify_profile'", ",", "attributes", ")", "self", ".", "attributes", "=", "attributes", "true", "end"], "docstring": "Updates the user's profile information", "docstring_tokens": ["Updates", "the", "user", "s", "profile", "information"], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/authorized_user.rb#L227-L238", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/authorized_user.rb", "func_name": "Turntabler.AuthorizedUser.update_laptop", "original_string": "def update_laptop(name)\n assert_valid_values(name, *%w(mac pc linux chrome iphone cake intel android))\n\n api('user.modify', :laptop => name)\n self.attributes = {'laptop' => name}\n true\n end", "language": "ruby", "code": "def update_laptop(name)\n assert_valid_values(name, *%w(mac pc linux chrome iphone cake intel android))\n\n api('user.modify', :laptop => name)\n self.attributes = {'laptop' => name}\n true\n end", "code_tokens": ["def", "update_laptop", "(", "name", ")", "assert_valid_values", "(", "name", ",", "%w(", "mac", "pc", "linux", "chrome", "iphone", "cake", "intel", "android", ")", ")", "api", "(", "'user.modify'", ",", ":laptop", "=>", "name", ")", "self", ".", "attributes", "=", "{", "'laptop'", "=>", "name", "}", "true", "end"], "docstring": "Updates the laptop currently being used", "docstring_tokens": ["Updates", "the", "laptop", "currently", "being", "used"], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/authorized_user.rb#L241-L247", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/authorized_user.rb", "func_name": "Turntabler.AuthorizedUser.update_status", "original_string": "def update_status(status = self.status)\n assert_valid_values(status, *%w(available unavailable away))\n\n now = Time.now.to_i\n result = api('presence.update', :status => status)\n\n client.reset_keepalive(result['interval'])\n client.clock_delta = ((now + Time.now.to_i) / 2 - result['now']).round\n self.attributes = {'status' => status}\n\n true\n end", "language": "ruby", "code": "def update_status(status = self.status)\n assert_valid_values(status, *%w(available unavailable away))\n\n now = Time.now.to_i\n result = api('presence.update', :status => status)\n\n client.reset_keepalive(result['interval'])\n client.clock_delta = ((now + Time.now.to_i) / 2 - result['now']).round\n self.attributes = {'status' => status}\n\n true\n end", "code_tokens": ["def", "update_status", "(", "status", "=", "self", ".", "status", ")", "assert_valid_values", "(", "status", ",", "%w(", "available", "unavailable", "away", ")", ")", "now", "=", "Time", ".", "now", ".", "to_i", "result", "=", "api", "(", "'presence.update'", ",", ":status", "=>", "status", ")", "client", ".", "reset_keepalive", "(", "result", "[", "'interval'", "]", ")", "client", ".", "clock_delta", "=", "(", "(", "now", "+", "Time", ".", "now", ".", "to_i", ")", "/", "2", "-", "result", "[", "'now'", "]", ")", ".", "round", "self", ".", "attributes", "=", "{", "'status'", "=>", "status", "}", "true", "end"], "docstring": "Sets the user's current status", "docstring_tokens": ["Sets", "the", "user", "s", "current", "status"], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/authorized_user.rb#L250-L261", "partition": "valid"} {"repo": "ozgg/plasper", "path": "lib/Plasper/plasper.rb", "func_name": "Plasper.Plasper.<<", "original_string": "def <<(input)\n if input.index(/\\s+/).nil?\n word = normalize_word input\n self.word = word unless word == ''\n elsif input.scan(SENTENCE_DELIMITER).length < 2\n self.sentence = input.gsub(SENTENCE_DELIMITER, '')\n else\n self.passage = input\n end\n end", "language": "ruby", "code": "def <<(input)\n if input.index(/\\s+/).nil?\n word = normalize_word input\n self.word = word unless word == ''\n elsif input.scan(SENTENCE_DELIMITER).length < 2\n self.sentence = input.gsub(SENTENCE_DELIMITER, '')\n else\n self.passage = input\n end\n end", "code_tokens": ["def", "<<", "(", "input", ")", "if", "input", ".", "index", "(", "/", "\\s", "/", ")", ".", "nil?", "word", "=", "normalize_word", "input", "self", ".", "word", "=", "word", "unless", "word", "==", "''", "elsif", "input", ".", "scan", "(", "SENTENCE_DELIMITER", ")", ".", "length", "<", "2", "self", ".", "sentence", "=", "input", ".", "gsub", "(", "SENTENCE_DELIMITER", ",", "''", ")", "else", "self", ".", "passage", "=", "input", "end", "end"], "docstring": "Prepares selectors and weights storage\n Analyze input and add appropriate part\n\n Determines if input is word, sentence or passage and adds it\n\n @param [String] input", "docstring_tokens": ["Prepares", "selectors", "and", "weights", "storage", "Analyze", "input", "and", "add", "appropriate", "part"], "sha": "6dbca5fd7113522ecbfaced2a5ec4f0645486893", "url": "https://github.com/ozgg/plasper/blob/6dbca5fd7113522ecbfaced2a5ec4f0645486893/lib/Plasper/plasper.rb#L20-L29", "partition": "valid"} {"repo": "ozgg/plasper", "path": "lib/Plasper/plasper.rb", "func_name": "Plasper.Plasper.weighted", "original_string": "def weighted(type, group)\n if @weights[type].has_key?(group)\n selector = WeightedSelect::Selector.new @weights[type][group]\n selector.select\n end\n end", "language": "ruby", "code": "def weighted(type, group)\n if @weights[type].has_key?(group)\n selector = WeightedSelect::Selector.new @weights[type][group]\n selector.select\n end\n end", "code_tokens": ["def", "weighted", "(", "type", ",", "group", ")", "if", "@weights", "[", "type", "]", ".", "has_key?", "(", "group", ")", "selector", "=", "WeightedSelect", "::", "Selector", ".", "new", "@weights", "[", "type", "]", "[", "group", "]", "selector", ".", "select", "end", "end"], "docstring": "Generate weighted-random value\n\n Type is :count, :first, :next or :last\n Group is symbol (for member count or first letter) or string representing letter\n\n @param [Symbol] type\n @param [Symbol|String] group", "docstring_tokens": ["Generate", "weighted", "-", "random", "value"], "sha": "6dbca5fd7113522ecbfaced2a5ec4f0645486893", "url": "https://github.com/ozgg/plasper/blob/6dbca5fd7113522ecbfaced2a5ec4f0645486893/lib/Plasper/plasper.rb#L129-L134", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/handler.rb", "func_name": "Turntabler.Handler.run", "original_string": "def run(event)\n if conditions_match?(event.data)\n # Run the block for each individual result\n event.results.each do |args|\n begin\n @block.call(*args)\n rescue StandardError => ex\n logger.error(([ex.message] + ex.backtrace) * \"\\n\")\n end\n end\n\n true\n else\n false\n end\n end", "language": "ruby", "code": "def run(event)\n if conditions_match?(event.data)\n # Run the block for each individual result\n event.results.each do |args|\n begin\n @block.call(*args)\n rescue StandardError => ex\n logger.error(([ex.message] + ex.backtrace) * \"\\n\")\n end\n end\n\n true\n else\n false\n end\n end", "code_tokens": ["def", "run", "(", "event", ")", "if", "conditions_match?", "(", "event", ".", "data", ")", "# Run the block for each individual result", "event", ".", "results", ".", "each", "do", "|", "args", "|", "begin", "@block", ".", "call", "(", "args", ")", "rescue", "StandardError", "=>", "ex", "logger", ".", "error", "(", "(", "[", "ex", ".", "message", "]", "+", "ex", ".", "backtrace", ")", "*", "\"\\n\"", ")", "end", "end", "true", "else", "false", "end", "end"], "docstring": "Builds a new handler bound to the given event.\n\n @param [String] event The name of the event to bind to\n @param [Hash] options The configuration options\n @option options [Boolean] :once (false) Whether to only call the handler once\n @option options [Hash] :if (nil) Data that must be matched to run\n @raise [ArgumentError] if an invalid option is specified\n Runs this handler for each result from the given event.\n\n @param [Turntabler::Event] event The event being triggered\n @return [Boolean] +true+ if conditions were matched to run the handler, otherwise +false+", "docstring_tokens": ["Builds", "a", "new", "handler", "bound", "to", "the", "given", "event", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/handler.rb#L46-L61", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/handler.rb", "func_name": "Turntabler.Handler.conditions_match?", "original_string": "def conditions_match?(data)\n if conditions\n conditions.all? {|(key, value)| data[key] == value}\n else\n true\n end\n end", "language": "ruby", "code": "def conditions_match?(data)\n if conditions\n conditions.all? {|(key, value)| data[key] == value}\n else\n true\n end\n end", "code_tokens": ["def", "conditions_match?", "(", "data", ")", "if", "conditions", "conditions", ".", "all?", "{", "|", "(", "key", ",", "value", ")", "|", "data", "[", "key", "]", "==", "value", "}", "else", "true", "end", "end"], "docstring": "Determines whether the conditions configured for this handler match the\n event data", "docstring_tokens": ["Determines", "whether", "the", "conditions", "configured", "for", "this", "handler", "match", "the", "event", "data"], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/handler.rb#L66-L72", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/container.rb", "func_name": "CaTissue.Container.add", "original_string": "def add(storable, *coordinate)\n validate_type(storable)\n loc = create_location(coordinate)\n pos = storable.position || storable.position_class.new\n pos.location = loc\n pos.occupant = storable\n pos.holder = self\n logger.debug { \"Added #{storable.qp} to #{qp} at #{loc.coordinate}.\" }\n update_full_flag\n self\n end", "language": "ruby", "code": "def add(storable, *coordinate)\n validate_type(storable)\n loc = create_location(coordinate)\n pos = storable.position || storable.position_class.new\n pos.location = loc\n pos.occupant = storable\n pos.holder = self\n logger.debug { \"Added #{storable.qp} to #{qp} at #{loc.coordinate}.\" }\n update_full_flag\n self\n end", "code_tokens": ["def", "add", "(", "storable", ",", "*", "coordinate", ")", "validate_type", "(", "storable", ")", "loc", "=", "create_location", "(", "coordinate", ")", "pos", "=", "storable", ".", "position", "||", "storable", ".", "position_class", ".", "new", "pos", ".", "location", "=", "loc", "pos", ".", "occupant", "=", "storable", "pos", ".", "holder", "=", "self", "logger", ".", "debug", "{", "\"Added #{storable.qp} to #{qp} at #{loc.coordinate}.\"", "}", "update_full_flag", "self", "end"], "docstring": "Moves the given Storable from its current Position, if any, to this Container at the optional\n coordinate. The default coordinate is the first available slot within this Container.\n The storable Storable position is updated to reflect the new location. Returns self.\n\n @param [Storable] storable the item to add\n @param [CaRuby::Coordinate, ] coordinate the x-y coordinate to place the item\n @raise [IndexError] if this Container is full\n @raise [IndexError] if the row and column are given but exceed the Container bounds", "docstring_tokens": ["Moves", "the", "given", "Storable", "from", "its", "current", "Position", "if", "any", "to", "this", "Container", "at", "the", "optional", "coordinate", ".", "The", "default", "coordinate", "is", "the", "first", "available", "slot", "within", "this", "Container", ".", "The", "storable", "Storable", "position", "is", "updated", "to", "reflect", "the", "new", "location", ".", "Returns", "self", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/container.rb#L148-L158", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/container.rb", "func_name": "CaTissue.Container.copy_container_type_capacity", "original_string": "def copy_container_type_capacity\n return unless container_type and container_type.capacity\n self.capacity = cpc = container_type.capacity.copy(:rows, :columns)\n logger.debug { \"Initialized #{qp} capacity from #{container_type.qp} capacity #{cpc}.\" }\n update_full_flag\n cpc\n end", "language": "ruby", "code": "def copy_container_type_capacity\n return unless container_type and container_type.capacity\n self.capacity = cpc = container_type.capacity.copy(:rows, :columns)\n logger.debug { \"Initialized #{qp} capacity from #{container_type.qp} capacity #{cpc}.\" }\n update_full_flag\n cpc\n end", "code_tokens": ["def", "copy_container_type_capacity", "return", "unless", "container_type", "and", "container_type", ".", "capacity", "self", ".", "capacity", "=", "cpc", "=", "container_type", ".", "capacity", ".", "copy", "(", ":rows", ",", ":columns", ")", "logger", ".", "debug", "{", "\"Initialized #{qp} capacity from #{container_type.qp} capacity #{cpc}.\"", "}", "update_full_flag", "cpc", "end"], "docstring": "Copies this Container's ContainerType capacity, if it exists, to the Container capacity.\n\n @quirk caTissue this method must be called by subclass initializers. The caTissue API\n does not make the reasonable assumption that the default Container capacity is the\n ContainerType capacity.\n\n @return [Capacity, nil] the initialized capacity, if any", "docstring_tokens": ["Copies", "this", "Container", "s", "ContainerType", "capacity", "if", "it", "exists", "to", "the", "Container", "capacity", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/container.rb#L223-L229", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/preferences.rb", "func_name": "Turntabler.Preferences.load", "original_string": "def load\n data = api('user.get_prefs')\n self.attributes = data['result'].inject({}) do |result, (preference, value, *)|\n result[preference] = value\n result\n end\n super\n end", "language": "ruby", "code": "def load\n data = api('user.get_prefs')\n self.attributes = data['result'].inject({}) do |result, (preference, value, *)|\n result[preference] = value\n result\n end\n super\n end", "code_tokens": ["def", "load", "data", "=", "api", "(", "'user.get_prefs'", ")", "self", ".", "attributes", "=", "data", "[", "'result'", "]", ".", "inject", "(", "{", "}", ")", "do", "|", "result", ",", "(", "preference", ",", "value", ",", "*", ")", "|", "result", "[", "preference", "]", "=", "value", "result", "end", "super", "end"], "docstring": "Loads the user's current Turntable preferences.\n\n @return [true]\n @raise [Turntabler::Error] if the command fails\n @example\n preferences.load # => true\n preferences.notify_dj # => false", "docstring_tokens": ["Loads", "the", "user", "s", "current", "Turntable", "preferences", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/preferences.rb#L41-L48", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/extractor.rb", "func_name": "Sycsvpro.Extractor.execute", "original_string": "def execute\n File.open(out_file, 'w') do |o|\n File.new(in_file, 'r').each_with_index do |line, index|\n extraction = col_filter.process(row_filter.process(line.chomp, row: index))\n o.puts extraction unless extraction.nil?\n end\n end\n end", "language": "ruby", "code": "def execute\n File.open(out_file, 'w') do |o|\n File.new(in_file, 'r').each_with_index do |line, index|\n extraction = col_filter.process(row_filter.process(line.chomp, row: index))\n o.puts extraction unless extraction.nil?\n end\n end\n end", "code_tokens": ["def", "execute", "File", ".", "open", "(", "out_file", ",", "'w'", ")", "do", "|", "o", "|", "File", ".", "new", "(", "in_file", ",", "'r'", ")", ".", "each_with_index", "do", "|", "line", ",", "index", "|", "extraction", "=", "col_filter", ".", "process", "(", "row_filter", ".", "process", "(", "line", ".", "chomp", ",", "row", ":", "index", ")", ")", "o", ".", "puts", "extraction", "unless", "extraction", ".", "nil?", "end", "end", "end"], "docstring": "Creates a new extractor\n Executes the extractor", "docstring_tokens": ["Creates", "a", "new", "extractor", "Executes", "the", "extractor"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/extractor.rb#L28-L35", "partition": "valid"} {"repo": "danijoo/Sightstone", "path": "lib/sightstone/modules/team_module.rb", "func_name": "Sightstone.TeamModule.teams", "original_string": "def teams(summoner, optional={})\n region = optional[:region] || @sightstone.region\n id = if summoner.is_a? Summoner\n summoner.id\n else\n summoner\n end\n \n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v2.2/team/by-summoner/#{id}\"\n\n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n teams = []\n data.each do |team|\n teams << Team.new(team)\n end\n if block_given?\n yield teams\n else\n return teams\n end\n }\n end", "language": "ruby", "code": "def teams(summoner, optional={})\n region = optional[:region] || @sightstone.region\n id = if summoner.is_a? Summoner\n summoner.id\n else\n summoner\n end\n \n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v2.2/team/by-summoner/#{id}\"\n\n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n teams = []\n data.each do |team|\n teams << Team.new(team)\n end\n if block_given?\n yield teams\n else\n return teams\n end\n }\n end", "code_tokens": ["def", "teams", "(", "summoner", ",", "optional", "=", "{", "}", ")", "region", "=", "optional", "[", ":region", "]", "||", "@sightstone", ".", "region", "id", "=", "if", "summoner", ".", "is_a?", "Summoner", "summoner", ".", "id", "else", "summoner", "end", "uri", "=", "\"https://prod.api.pvp.net/api/lol/#{region}/v2.2/team/by-summoner/#{id}\"", "response", "=", "_get_api_response", "(", "uri", ")", "_parse_response", "(", "response", ")", "{", "|", "resp", "|", "data", "=", "JSON", ".", "parse", "(", "resp", ")", "teams", "=", "[", "]", "data", ".", "each", "do", "|", "team", "|", "teams", "<<", "Team", ".", "new", "(", "team", ")", "end", "if", "block_given?", "yield", "teams", "else", "return", "teams", "end", "}", "end"], "docstring": "call to receive all teams for a summoner\n @param [Summoner, Fixnum] summoner summoner object or id of a summoner\n @param optional [Hash] optional arguments: :region => replaces default region\n @ return [Array] An array containing all teams of the given summoner", "docstring_tokens": ["call", "to", "receive", "all", "teams", "for", "a", "summoner"], "sha": "4c6709916ce7552f622de1a120c021e067601b4d", "url": "https://github.com/danijoo/Sightstone/blob/4c6709916ce7552f622de1a120c021e067601b4d/lib/sightstone/modules/team_module.rb#L16-L39", "partition": "valid"} {"repo": "code-lever/plans-gem", "path": "lib/plans/publish.rb", "func_name": "Plans.Publish.get_doctype", "original_string": "def get_doctype(path)\n doc_type = nil\n begin\n metadata = YAML.load_file(path + 'template.yml')\n doc_type = metadata['type']\n if doc_type.nil?\n say 'Type value not found. Check template.yml in the document directory', :red\n say 'Make sure there is an entry `type: DOC_TYPE` in the file.'\n say \" #{path}\"\n raise_error('DOC_TYPE not found in template.yml')\n end\n rescue Errno::ENOENT # File not found\n say 'No template.yml found in the document directory. Did you forget to add it?', :red\n say 'Did you run the command in the directory where the document is located?'\n say \" #{path}\"\n raise_error('template.yml not found')\n end\n return doc_type\n end", "language": "ruby", "code": "def get_doctype(path)\n doc_type = nil\n begin\n metadata = YAML.load_file(path + 'template.yml')\n doc_type = metadata['type']\n if doc_type.nil?\n say 'Type value not found. Check template.yml in the document directory', :red\n say 'Make sure there is an entry `type: DOC_TYPE` in the file.'\n say \" #{path}\"\n raise_error('DOC_TYPE not found in template.yml')\n end\n rescue Errno::ENOENT # File not found\n say 'No template.yml found in the document directory. Did you forget to add it?', :red\n say 'Did you run the command in the directory where the document is located?'\n say \" #{path}\"\n raise_error('template.yml not found')\n end\n return doc_type\n end", "code_tokens": ["def", "get_doctype", "(", "path", ")", "doc_type", "=", "nil", "begin", "metadata", "=", "YAML", ".", "load_file", "(", "path", "+", "'template.yml'", ")", "doc_type", "=", "metadata", "[", "'type'", "]", "if", "doc_type", ".", "nil?", "say", "'Type value not found. Check template.yml in the document directory'", ",", ":red", "say", "'Make sure there is an entry `type: DOC_TYPE` in the file.'", "say", "\" #{path}\"", "raise_error", "(", "'DOC_TYPE not found in template.yml'", ")", "end", "rescue", "Errno", "::", "ENOENT", "# File not found", "say", "'No template.yml found in the document directory. Did you forget to add it?'", ",", ":red", "say", "'Did you run the command in the directory where the document is located?'", "say", "\" #{path}\"", "raise_error", "(", "'template.yml not found'", ")", "end", "return", "doc_type", "end"], "docstring": "Get the document type from the YAML file next to the document.\n\n @param [Pathname] The path to the location of the template.yml file.\n @return [String] the type of the document found in the YAML file.", "docstring_tokens": ["Get", "the", "document", "type", "from", "the", "YAML", "file", "next", "to", "the", "document", "."], "sha": "b7463e7cb991f43e7448f5527560ca5d77a608a4", "url": "https://github.com/code-lever/plans-gem/blob/b7463e7cb991f43e7448f5527560ca5d77a608a4/lib/plans/publish.rb#L78-L96", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/allocator.rb", "func_name": "Sycsvpro.Allocator.execute", "original_string": "def execute\n allocation = {}\n File.open(infile).each_with_index do |line, index|\n row = row_filter.process(line, row: index)\n next if row.nil? or row.empty?\n key = key_filter.process(row)\n allocation[key] = [] if allocation[key].nil?\n allocation[key] << col_filter.process(row).split(';') \n end\n\n File.open(outfile, 'w') do |out|\n allocation.each do |key, values|\n out.puts \"#{key};#{values.flatten.uniq.sort.join(';')}\"\n end\n end\n end", "language": "ruby", "code": "def execute\n allocation = {}\n File.open(infile).each_with_index do |line, index|\n row = row_filter.process(line, row: index)\n next if row.nil? or row.empty?\n key = key_filter.process(row)\n allocation[key] = [] if allocation[key].nil?\n allocation[key] << col_filter.process(row).split(';') \n end\n\n File.open(outfile, 'w') do |out|\n allocation.each do |key, values|\n out.puts \"#{key};#{values.flatten.uniq.sort.join(';')}\"\n end\n end\n end", "code_tokens": ["def", "execute", "allocation", "=", "{", "}", "File", ".", "open", "(", "infile", ")", ".", "each_with_index", "do", "|", "line", ",", "index", "|", "row", "=", "row_filter", ".", "process", "(", "line", ",", "row", ":", "index", ")", "next", "if", "row", ".", "nil?", "or", "row", ".", "empty?", "key", "=", "key_filter", ".", "process", "(", "row", ")", "allocation", "[", "key", "]", "=", "[", "]", "if", "allocation", "[", "key", "]", ".", "nil?", "allocation", "[", "key", "]", "<<", "col_filter", ".", "process", "(", "row", ")", ".", "split", "(", "';'", ")", "end", "File", ".", "open", "(", "outfile", ",", "'w'", ")", "do", "|", "out", "|", "allocation", ".", "each", "do", "|", "key", ",", "values", "|", "out", ".", "puts", "\"#{key};#{values.flatten.uniq.sort.join(';')}\"", "end", "end", "end"], "docstring": "Creates a new allocator. Options are infile, outfile, key, rows and columns to allocate to key\n Executes the allocator and assigns column values to the key", "docstring_tokens": ["Creates", "a", "new", "allocator", ".", "Options", "are", "infile", "outfile", "key", "rows", "and", "columns", "to", "allocate", "to", "key", "Executes", "the", "allocator", "and", "assigns", "column", "values", "to", "the", "key"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/allocator.rb#L40-L55", "partition": "valid"} {"repo": "weibel/MapKitWrapper", "path": "lib/map-kit-wrapper/base_data_types.rb", "func_name": "BaseDataTypes.Vector.span_to", "original_string": "def span_to(spanner)\n Vector.new((@x - spanner.x).abs, (@y - spanner.y).abs)\n end", "language": "ruby", "code": "def span_to(spanner)\n Vector.new((@x - spanner.x).abs, (@y - spanner.y).abs)\n end", "code_tokens": ["def", "span_to", "(", "spanner", ")", "Vector", ".", "new", "(", "(", "@x", "-", "spanner", ".", "x", ")", ".", "abs", ",", "(", "@y", "-", "spanner", ".", "y", ")", ".", "abs", ")", "end"], "docstring": "Find the span between two Vectors\n\n * *Args* :\n - +spanner+ -> Vector\n\n * *Returns* :\n - Vector", "docstring_tokens": ["Find", "the", "span", "between", "two", "Vectors"], "sha": "6ad3579b77e4d9be1c23ebab6a624a7dbc4ed2e6", "url": "https://github.com/weibel/MapKitWrapper/blob/6ad3579b77e4d9be1c23ebab6a624a7dbc4ed2e6/lib/map-kit-wrapper/base_data_types.rb#L104-L106", "partition": "valid"} {"repo": "jonathanpike/mako", "path": "lib/mako/core.rb", "func_name": "Mako.Core.build", "original_string": "def build\n log_configuration_information\n\n if subscription_list.empty?\n Mako.logger.warn 'No feeds were found in your subscriptions file. Please add feeds and try again.'\n return\n end\n\n log_time do\n request_and_build_feeds\n renderers.each do |renderer|\n renderer_instance = renderer.new(bound: self)\n writer.new(renderer: renderer_instance,\n destination: File.expand_path(renderer_instance.file_path, Mako.config.destination)).write\n end\n end\n end", "language": "ruby", "code": "def build\n log_configuration_information\n\n if subscription_list.empty?\n Mako.logger.warn 'No feeds were found in your subscriptions file. Please add feeds and try again.'\n return\n end\n\n log_time do\n request_and_build_feeds\n renderers.each do |renderer|\n renderer_instance = renderer.new(bound: self)\n writer.new(renderer: renderer_instance,\n destination: File.expand_path(renderer_instance.file_path, Mako.config.destination)).write\n end\n end\n end", "code_tokens": ["def", "build", "log_configuration_information", "if", "subscription_list", ".", "empty?", "Mako", ".", "logger", ".", "warn", "'No feeds were found in your subscriptions file. Please add feeds and try again.'", "return", "end", "log_time", "do", "request_and_build_feeds", "renderers", ".", "each", "do", "|", "renderer", "|", "renderer_instance", "=", "renderer", ".", "new", "(", "bound", ":", "self", ")", "writer", ".", "new", "(", "renderer", ":", "renderer_instance", ",", "destination", ":", "File", ".", "expand_path", "(", "renderer_instance", ".", "file_path", ",", "Mako", ".", "config", ".", "destination", ")", ")", ".", "write", "end", "end", "end"], "docstring": "Gets list of feed_urls, requests each of them and uses the constructor to\n make Feed and Article objects, then calls to the renderers to render\n the page and stylesheets.", "docstring_tokens": ["Gets", "list", "of", "feed_urls", "requests", "each", "of", "them", "and", "uses", "the", "constructor", "to", "make", "Feed", "and", "Article", "objects", "then", "calls", "to", "the", "renderers", "to", "render", "the", "page", "and", "stylesheets", "."], "sha": "2aa3665ebf23f09727e59d667b34155755493bdf", "url": "https://github.com/jonathanpike/mako/blob/2aa3665ebf23f09727e59d667b34155755493bdf/lib/mako/core.rb#L23-L39", "partition": "valid"} {"repo": "jonathanpike/mako", "path": "lib/mako/core.rb", "func_name": "Mako.Core.log_configuration_information", "original_string": "def log_configuration_information\n Mako.logger.info \"Configuration File: #{Mako.config.config_file}\"\n Mako.logger.info \"Theme: #{Mako.config.theme}\"\n Mako.logger.info \"Destination: #{Mako.config.destination}\"\n end", "language": "ruby", "code": "def log_configuration_information\n Mako.logger.info \"Configuration File: #{Mako.config.config_file}\"\n Mako.logger.info \"Theme: #{Mako.config.theme}\"\n Mako.logger.info \"Destination: #{Mako.config.destination}\"\n end", "code_tokens": ["def", "log_configuration_information", "Mako", ".", "logger", ".", "info", "\"Configuration File: #{Mako.config.config_file}\"", "Mako", ".", "logger", ".", "info", "\"Theme: #{Mako.config.theme}\"", "Mako", ".", "logger", ".", "info", "\"Destination: #{Mako.config.destination}\"", "end"], "docstring": "Prints configuration file, source, and destination directory to STDOUT.", "docstring_tokens": ["Prints", "configuration", "file", "source", "and", "destination", "directory", "to", "STDOUT", "."], "sha": "2aa3665ebf23f09727e59d667b34155755493bdf", "url": "https://github.com/jonathanpike/mako/blob/2aa3665ebf23f09727e59d667b34155755493bdf/lib/mako/core.rb#L53-L57", "partition": "valid"} {"repo": "jonathanpike/mako", "path": "lib/mako/core.rb", "func_name": "Mako.Core.log_time", "original_string": "def log_time\n Mako.logger.info 'Generating...'\n start_time = Time.now.to_f\n yield\n generation_time = Time.now.to_f - start_time\n Mako.logger.info \"done in #{generation_time} seconds\"\n end", "language": "ruby", "code": "def log_time\n Mako.logger.info 'Generating...'\n start_time = Time.now.to_f\n yield\n generation_time = Time.now.to_f - start_time\n Mako.logger.info \"done in #{generation_time} seconds\"\n end", "code_tokens": ["def", "log_time", "Mako", ".", "logger", ".", "info", "'Generating...'", "start_time", "=", "Time", ".", "now", ".", "to_f", "yield", "generation_time", "=", "Time", ".", "now", ".", "to_f", "-", "start_time", "Mako", ".", "logger", ".", "info", "\"done in #{generation_time} seconds\"", "end"], "docstring": "Provides build time logging information and writes it to STDOUT.", "docstring_tokens": ["Provides", "build", "time", "logging", "information", "and", "writes", "it", "to", "STDOUT", "."], "sha": "2aa3665ebf23f09727e59d667b34155755493bdf", "url": "https://github.com/jonathanpike/mako/blob/2aa3665ebf23f09727e59d667b34155755493bdf/lib/mako/core.rb#L60-L66", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/spread_sheet_builder.rb", "func_name": "Sycsvpro.SpreadSheetBuilder.execute", "original_string": "def execute\n result = eval(operation) \n if outfile\n if result.is_a?(SpreadSheet)\n result.write(outfile)\n else\n puts\n puts \"Warning: Result is no spread sheet and not written to file!\"\n puts \" To view the result use -p flag\" unless print\n end\n end\n\n if print\n puts\n puts \"Operation\"\n puts \"---------\"\n operation.split(';').each { |o| puts o }\n puts\n puts \"Result\"\n puts \"------\"\n if result.nil? || result.empty?\n puts result.inspect\n else\n puts result\n end\n puts\n end\n end", "language": "ruby", "code": "def execute\n result = eval(operation) \n if outfile\n if result.is_a?(SpreadSheet)\n result.write(outfile)\n else\n puts\n puts \"Warning: Result is no spread sheet and not written to file!\"\n puts \" To view the result use -p flag\" unless print\n end\n end\n\n if print\n puts\n puts \"Operation\"\n puts \"---------\"\n operation.split(';').each { |o| puts o }\n puts\n puts \"Result\"\n puts \"------\"\n if result.nil? || result.empty?\n puts result.inspect\n else\n puts result\n end\n puts\n end\n end", "code_tokens": ["def", "execute", "result", "=", "eval", "(", "operation", ")", "if", "outfile", "if", "result", ".", "is_a?", "(", "SpreadSheet", ")", "result", ".", "write", "(", "outfile", ")", "else", "puts", "puts", "\"Warning: Result is no spread sheet and not written to file!\"", "puts", "\" To view the result use -p flag\"", "unless", "print", "end", "end", "if", "print", "puts", "puts", "\"Operation\"", "puts", "\"---------\"", "operation", ".", "split", "(", "';'", ")", ".", "each", "{", "|", "o", "|", "puts", "o", "}", "puts", "puts", "\"Result\"", "puts", "\"------\"", "if", "result", ".", "nil?", "||", "result", ".", "empty?", "puts", "result", ".", "inspect", "else", "puts", "result", "end", "puts", "end", "end"], "docstring": "Executes the operation and writes the result to the outfile", "docstring_tokens": ["Executes", "the", "operation", "and", "writes", "the", "result", "to", "the", "outfile"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet_builder.rb#L61-L88", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/spread_sheet_builder.rb", "func_name": "Sycsvpro.SpreadSheetBuilder.create_operands", "original_string": "def create_operands(opts)\n files = opts[:files].split(',')\n rlabels = opts[:rlabels].split(',').collect { |l| l.upcase == \"TRUE\" }\n clabels = opts[:clabels].split(',').collect { |l| l.upcase == \"TRUE\" }\n\n operands = {}\n opts[:aliases].split(',').each_with_index do |a,i|\n operands[a] = SpreadSheet.new(file: files[i], ds: opts[:ds], \n equalize: opts[:equalize],\n r: rlabels[i], c: clabels[i])\n end\n\n operands\n end", "language": "ruby", "code": "def create_operands(opts)\n files = opts[:files].split(',')\n rlabels = opts[:rlabels].split(',').collect { |l| l.upcase == \"TRUE\" }\n clabels = opts[:clabels].split(',').collect { |l| l.upcase == \"TRUE\" }\n\n operands = {}\n opts[:aliases].split(',').each_with_index do |a,i|\n operands[a] = SpreadSheet.new(file: files[i], ds: opts[:ds], \n equalize: opts[:equalize],\n r: rlabels[i], c: clabels[i])\n end\n\n operands\n end", "code_tokens": ["def", "create_operands", "(", "opts", ")", "files", "=", "opts", "[", ":files", "]", ".", "split", "(", "','", ")", "rlabels", "=", "opts", "[", ":rlabels", "]", ".", "split", "(", "','", ")", ".", "collect", "{", "|", "l", "|", "l", ".", "upcase", "==", "\"TRUE\"", "}", "clabels", "=", "opts", "[", ":clabels", "]", ".", "split", "(", "','", ")", ".", "collect", "{", "|", "l", "|", "l", ".", "upcase", "==", "\"TRUE\"", "}", "operands", "=", "{", "}", "opts", "[", ":aliases", "]", ".", "split", "(", "','", ")", ".", "each_with_index", "do", "|", "a", ",", "i", "|", "operands", "[", "a", "]", "=", "SpreadSheet", ".", "new", "(", "file", ":", "files", "[", "i", "]", ",", "ds", ":", "opts", "[", ":ds", "]", ",", "equalize", ":", "opts", "[", ":equalize", "]", ",", "r", ":", "rlabels", "[", "i", "]", ",", "c", ":", "clabels", "[", "i", "]", ")", "end", "operands", "end"], "docstring": "Creates the spread sheet operands for the arithmetic operation", "docstring_tokens": ["Creates", "the", "spread", "sheet", "operands", "for", "the", "arithmetic", "operation"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet_builder.rb#L93-L106", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/connection.rb", "func_name": "Turntabler.Connection.publish", "original_string": "def publish(params)\n params[:msgid] = message_id = next_message_id\n params = @default_params.merge(params)\n\n logger.debug \"Message sent: #{params.inspect}\"\n\n if HTTP_APIS.include?(params[:api])\n publish_to_http(params)\n else\n publish_to_socket(params)\n end\n\n # Add timeout handler\n EventMachine.add_timer(@timeout) do\n dispatch('msgid' => message_id, 'command' => 'response_received', 'error' => 'timed out')\n end if @timeout\n\n message_id\n end", "language": "ruby", "code": "def publish(params)\n params[:msgid] = message_id = next_message_id\n params = @default_params.merge(params)\n\n logger.debug \"Message sent: #{params.inspect}\"\n\n if HTTP_APIS.include?(params[:api])\n publish_to_http(params)\n else\n publish_to_socket(params)\n end\n\n # Add timeout handler\n EventMachine.add_timer(@timeout) do\n dispatch('msgid' => message_id, 'command' => 'response_received', 'error' => 'timed out')\n end if @timeout\n\n message_id\n end", "code_tokens": ["def", "publish", "(", "params", ")", "params", "[", ":msgid", "]", "=", "message_id", "=", "next_message_id", "params", "=", "@default_params", ".", "merge", "(", "params", ")", "logger", ".", "debug", "\"Message sent: #{params.inspect}\"", "if", "HTTP_APIS", ".", "include?", "(", "params", "[", ":api", "]", ")", "publish_to_http", "(", "params", ")", "else", "publish_to_socket", "(", "params", ")", "end", "# Add timeout handler", "EventMachine", ".", "add_timer", "(", "@timeout", ")", "do", "dispatch", "(", "'msgid'", "=>", "message_id", ",", "'command'", "=>", "'response_received'", ",", "'error'", "=>", "'timed out'", ")", "end", "if", "@timeout", "message_id", "end"], "docstring": "Publishes the given params to the underlying web socket. The defaults\n initially configured as part of the connection will also be included in\n the message.\n\n @param [Hash] params The parameters to include in the message sent\n @return [Fixnum] The id of the message delivered", "docstring_tokens": ["Publishes", "the", "given", "params", "to", "the", "underlying", "web", "socket", ".", "The", "defaults", "initially", "configured", "as", "part", "of", "the", "connection", "will", "also", "be", "included", "in", "the", "message", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/connection.rb#L78-L96", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/connection.rb", "func_name": "Turntabler.Connection.publish_to_socket", "original_string": "def publish_to_socket(params)\n message = params.is_a?(String) ? params : params.to_json\n data = \"~m~#{message.length}~m~#{message}\"\n @socket.send(data)\n end", "language": "ruby", "code": "def publish_to_socket(params)\n message = params.is_a?(String) ? params : params.to_json\n data = \"~m~#{message.length}~m~#{message}\"\n @socket.send(data)\n end", "code_tokens": ["def", "publish_to_socket", "(", "params", ")", "message", "=", "params", ".", "is_a?", "(", "String", ")", "?", "params", ":", "params", ".", "to_json", "data", "=", "\"~m~#{message.length}~m~#{message}\"", "@socket", ".", "send", "(", "data", ")", "end"], "docstring": "Publishes the given params to the web socket", "docstring_tokens": ["Publishes", "the", "given", "params", "to", "the", "web", "socket"], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/connection.rb#L100-L104", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/connection.rb", "func_name": "Turntabler.Connection.publish_to_http", "original_string": "def publish_to_http(params)\n api = params.delete(:api)\n message_id = params[:msgid]\n\n http = EventMachine::HttpRequest.new(\"http://turntable.fm/api/#{api}\").get(:query => params)\n if http.response_header.status == 200\n # Command executed properly: parse the results\n success, data = JSON.parse(http.response)\n data = {'result' => data} unless data.is_a?(Hash)\n message = data.merge('success' => success)\n else\n # Command failed to run\n message = {'success' => false, 'error' => http.error}\n end\n message.merge!('msgid' => message_id)\n\n # Run the message handler\n event = Faye::WebSocket::API::Event.new('message', :data => \"~m~#{Time.now.to_i}~m~#{JSON.generate(message)}\")\n on_message(event)\n end", "language": "ruby", "code": "def publish_to_http(params)\n api = params.delete(:api)\n message_id = params[:msgid]\n\n http = EventMachine::HttpRequest.new(\"http://turntable.fm/api/#{api}\").get(:query => params)\n if http.response_header.status == 200\n # Command executed properly: parse the results\n success, data = JSON.parse(http.response)\n data = {'result' => data} unless data.is_a?(Hash)\n message = data.merge('success' => success)\n else\n # Command failed to run\n message = {'success' => false, 'error' => http.error}\n end\n message.merge!('msgid' => message_id)\n\n # Run the message handler\n event = Faye::WebSocket::API::Event.new('message', :data => \"~m~#{Time.now.to_i}~m~#{JSON.generate(message)}\")\n on_message(event)\n end", "code_tokens": ["def", "publish_to_http", "(", "params", ")", "api", "=", "params", ".", "delete", "(", ":api", ")", "message_id", "=", "params", "[", ":msgid", "]", "http", "=", "EventMachine", "::", "HttpRequest", ".", "new", "(", "\"http://turntable.fm/api/#{api}\"", ")", ".", "get", "(", ":query", "=>", "params", ")", "if", "http", ".", "response_header", ".", "status", "==", "200", "# Command executed properly: parse the results", "success", ",", "data", "=", "JSON", ".", "parse", "(", "http", ".", "response", ")", "data", "=", "{", "'result'", "=>", "data", "}", "unless", "data", ".", "is_a?", "(", "Hash", ")", "message", "=", "data", ".", "merge", "(", "'success'", "=>", "success", ")", "else", "# Command failed to run", "message", "=", "{", "'success'", "=>", "false", ",", "'error'", "=>", "http", ".", "error", "}", "end", "message", ".", "merge!", "(", "'msgid'", "=>", "message_id", ")", "# Run the message handler", "event", "=", "Faye", "::", "WebSocket", "::", "API", "::", "Event", ".", "new", "(", "'message'", ",", ":data", "=>", "\"~m~#{Time.now.to_i}~m~#{JSON.generate(message)}\"", ")", "on_message", "(", "event", ")", "end"], "docstring": "Publishes the given params to the HTTP API", "docstring_tokens": ["Publishes", "the", "given", "params", "to", "the", "HTTP", "API"], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/connection.rb#L107-L126", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/connection.rb", "func_name": "Turntabler.Connection.on_message", "original_string": "def on_message(event)\n data = event.data\n\n response = data.match(/~m~\\d*~m~(.*)/)[1]\n message =\n case response\n when /no_session/\n {'command' => 'no_session'}\n when /(~h~[0-9]+)/\n # Send the heartbeat command back to the server\n publish_to_socket($1)\n {'command' => 'heartbeat'}\n else\n JSON.parse(response)\n end\n message['command'] = 'response_received' if message['msgid']\n\n logger.debug \"Message received: #{message.inspect}\"\n dispatch(message)\n end", "language": "ruby", "code": "def on_message(event)\n data = event.data\n\n response = data.match(/~m~\\d*~m~(.*)/)[1]\n message =\n case response\n when /no_session/\n {'command' => 'no_session'}\n when /(~h~[0-9]+)/\n # Send the heartbeat command back to the server\n publish_to_socket($1)\n {'command' => 'heartbeat'}\n else\n JSON.parse(response)\n end\n message['command'] = 'response_received' if message['msgid']\n\n logger.debug \"Message received: #{message.inspect}\"\n dispatch(message)\n end", "code_tokens": ["def", "on_message", "(", "event", ")", "data", "=", "event", ".", "data", "response", "=", "data", ".", "match", "(", "/", "\\d", "/", ")", "[", "1", "]", "message", "=", "case", "response", "when", "/", "/", "{", "'command'", "=>", "'no_session'", "}", "when", "/", "/", "# Send the heartbeat command back to the server", "publish_to_socket", "(", "$1", ")", "{", "'command'", "=>", "'heartbeat'", "}", "else", "JSON", ".", "parse", "(", "response", ")", "end", "message", "[", "'command'", "]", "=", "'response_received'", "if", "message", "[", "'msgid'", "]", "logger", ".", "debug", "\"Message received: #{message.inspect}\"", "dispatch", "(", "message", ")", "end"], "docstring": "Callback when a message has been received from the remote server on the\n open socket.", "docstring_tokens": ["Callback", "when", "a", "message", "has", "been", "received", "from", "the", "remote", "server", "on", "the", "open", "socket", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/connection.rb#L150-L169", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/container_type.rb", "func_name": "CaTissue.ContainerType.add_defaults_local", "original_string": "def add_defaults_local\n super\n self.capacity ||= Capacity.new.add_defaults\n self.row_label ||= capacity.rows && capacity.rows > 0 ? 'Row' : 'Unused'\n self.column_label ||= capacity.columns && capacity.columns > 0 ? 'Column' : 'Unused'\n end", "language": "ruby", "code": "def add_defaults_local\n super\n self.capacity ||= Capacity.new.add_defaults\n self.row_label ||= capacity.rows && capacity.rows > 0 ? 'Row' : 'Unused'\n self.column_label ||= capacity.columns && capacity.columns > 0 ? 'Column' : 'Unused'\n end", "code_tokens": ["def", "add_defaults_local", "super", "self", ".", "capacity", "||=", "Capacity", ".", "new", ".", "add_defaults", "self", ".", "row_label", "||=", "capacity", ".", "rows", "&&", "capacity", ".", "rows", ">", "0", "?", "'Row'", ":", "'Unused'", "self", ".", "column_label", "||=", "capacity", ".", "columns", "&&", "capacity", ".", "columns", ">", "0", "?", "'Column'", ":", "'Unused'", "end"], "docstring": "Adds an empty capacity and default dimension labels, if necessary.\n The default +one_dimension_label+ is 'Column' if there is a non-zero dimension capacity, 'Unused' otherwise.\n The default +two_dimension_label+ is 'Row' if there is a non-zero dimension capacity, 'Unused' otherwise.\n\n @quirk JRuby See {#merge_container_type_attributes}. Work-around is that each ContainerType\n subclass must alias +add_defaults_local+ to this method.", "docstring_tokens": ["Adds", "an", "empty", "capacity", "and", "default", "dimension", "labels", "if", "necessary", ".", "The", "default", "+", "one_dimension_label", "+", "is", "Column", "if", "there", "is", "a", "non", "-", "zero", "dimension", "capacity", "Unused", "otherwise", ".", "The", "default", "+", "two_dimension_label", "+", "is", "Row", "if", "there", "is", "a", "non", "-", "zero", "dimension", "capacity", "Unused", "otherwise", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/container_type.rb#L136-L141", "partition": "valid"} {"repo": "nbaum/blower", "path": "lib/blower/host.rb", "func_name": "Blower.Host.ping", "original_string": "def ping ()\n log.debug \"Pinging\"\n Timeout.timeout(1) do\n TCPSocket.new(address, 22).close\n end\n true\n rescue Timeout::Error, Errno::ECONNREFUSED\n fail \"Failed to ping #{self}\"\n end", "language": "ruby", "code": "def ping ()\n log.debug \"Pinging\"\n Timeout.timeout(1) do\n TCPSocket.new(address, 22).close\n end\n true\n rescue Timeout::Error, Errno::ECONNREFUSED\n fail \"Failed to ping #{self}\"\n end", "code_tokens": ["def", "ping", "(", ")", "log", ".", "debug", "\"Pinging\"", "Timeout", ".", "timeout", "(", "1", ")", "do", "TCPSocket", ".", "new", "(", "address", ",", "22", ")", ".", "close", "end", "true", "rescue", "Timeout", "::", "Error", ",", "Errno", "::", "ECONNREFUSED", "fail", "\"Failed to ping #{self}\"", "end"], "docstring": "Attempt to connect to port 22 on the host.\n @return +true+\n @raise If it doesn't connect within 1 second.\n @api private", "docstring_tokens": ["Attempt", "to", "connect", "to", "port", "22", "on", "the", "host", "."], "sha": "9e09a56f9d4bf547bf1aa1843d894be625a27628", "url": "https://github.com/nbaum/blower/blob/9e09a56f9d4bf547bf1aa1843d894be625a27628/lib/blower/host.rb#L46-L54", "partition": "valid"} {"repo": "nbaum/blower", "path": "lib/blower/host.rb", "func_name": "Blower.Host.cp", "original_string": "def cp (froms, to, as: nil, quiet: false)\n as ||= @user\n output = \"\"\n synchronize do\n [froms].flatten.each do |from|\n if from.is_a?(String)\n to += \"/\" if to[-1] != \"/\" && from.is_a?(Array)\n command = [\"rsync\", \"-e\", ssh_command, \"-r\"]\n command += [*from, \"#{as}@#{@address}:#{to}\"]\n log.trace command.shelljoin, quiet: quiet\n IO.popen(command, in: :close, err: %i(child out)) do |io|\n until io.eof?\n begin\n output << io.read_nonblock(100)\n rescue IO::WaitReadable\n IO.select([io])\n retry\n end\n end\n io.close\n if !$?.success?\n log.fatal \"exit status #{$?.exitstatus}: #{command}\", quiet: quiet\n log.fatal output, quiet: quiet\n fail \"failed to copy files\"\n end\n end\n elsif from.respond_to?(:read)\n cmd = \"echo #{Base64.strict_encode64(from.read).shellescape} | base64 -d > #{to.shellescape}\"\n sh cmd, quiet: quiet\n else\n fail \"Don't know how to copy a #{from.class}: #{from}\"\n end\n end\n end\n true\n end", "language": "ruby", "code": "def cp (froms, to, as: nil, quiet: false)\n as ||= @user\n output = \"\"\n synchronize do\n [froms].flatten.each do |from|\n if from.is_a?(String)\n to += \"/\" if to[-1] != \"/\" && from.is_a?(Array)\n command = [\"rsync\", \"-e\", ssh_command, \"-r\"]\n command += [*from, \"#{as}@#{@address}:#{to}\"]\n log.trace command.shelljoin, quiet: quiet\n IO.popen(command, in: :close, err: %i(child out)) do |io|\n until io.eof?\n begin\n output << io.read_nonblock(100)\n rescue IO::WaitReadable\n IO.select([io])\n retry\n end\n end\n io.close\n if !$?.success?\n log.fatal \"exit status #{$?.exitstatus}: #{command}\", quiet: quiet\n log.fatal output, quiet: quiet\n fail \"failed to copy files\"\n end\n end\n elsif from.respond_to?(:read)\n cmd = \"echo #{Base64.strict_encode64(from.read).shellescape} | base64 -d > #{to.shellescape}\"\n sh cmd, quiet: quiet\n else\n fail \"Don't know how to copy a #{from.class}: #{from}\"\n end\n end\n end\n true\n end", "code_tokens": ["def", "cp", "(", "froms", ",", "to", ",", "as", ":", "nil", ",", "quiet", ":", "false", ")", "as", "||=", "@user", "output", "=", "\"\"", "synchronize", "do", "[", "froms", "]", ".", "flatten", ".", "each", "do", "|", "from", "|", "if", "from", ".", "is_a?", "(", "String", ")", "to", "+=", "\"/\"", "if", "to", "[", "-", "1", "]", "!=", "\"/\"", "&&", "from", ".", "is_a?", "(", "Array", ")", "command", "=", "[", "\"rsync\"", ",", "\"-e\"", ",", "ssh_command", ",", "\"-r\"", "]", "command", "+=", "[", "from", ",", "\"#{as}@#{@address}:#{to}\"", "]", "log", ".", "trace", "command", ".", "shelljoin", ",", "quiet", ":", "quiet", "IO", ".", "popen", "(", "command", ",", "in", ":", ":close", ",", "err", ":", "%i(", "child", "out", ")", ")", "do", "|", "io", "|", "until", "io", ".", "eof?", "begin", "output", "<<", "io", ".", "read_nonblock", "(", "100", ")", "rescue", "IO", "::", "WaitReadable", "IO", ".", "select", "(", "[", "io", "]", ")", "retry", "end", "end", "io", ".", "close", "if", "!", "$?", ".", "success?", "log", ".", "fatal", "\"exit status #{$?.exitstatus}: #{command}\"", ",", "quiet", ":", "quiet", "log", ".", "fatal", "output", ",", "quiet", ":", "quiet", "fail", "\"failed to copy files\"", "end", "end", "elsif", "from", ".", "respond_to?", "(", ":read", ")", "cmd", "=", "\"echo #{Base64.strict_encode64(from.read).shellescape} | base64 -d > #{to.shellescape}\"", "sh", "cmd", ",", "quiet", ":", "quiet", "else", "fail", "\"Don't know how to copy a #{from.class}: #{from}\"", "end", "end", "end", "true", "end"], "docstring": "Copy files or directories to the host.\n @api private", "docstring_tokens": ["Copy", "files", "or", "directories", "to", "the", "host", "."], "sha": "9e09a56f9d4bf547bf1aa1843d894be625a27628", "url": "https://github.com/nbaum/blower/blob/9e09a56f9d4bf547bf1aa1843d894be625a27628/lib/blower/host.rb#L58-L93", "partition": "valid"} {"repo": "nbaum/blower", "path": "lib/blower/host.rb", "func_name": "Blower.Host.write", "original_string": "def write (string, to, as: nil, quiet: false)\n cp StringIO.new(string), to, as: as, quiet: quiet\n end", "language": "ruby", "code": "def write (string, to, as: nil, quiet: false)\n cp StringIO.new(string), to, as: as, quiet: quiet\n end", "code_tokens": ["def", "write", "(", "string", ",", "to", ",", "as", ":", "nil", ",", "quiet", ":", "false", ")", "cp", "StringIO", ".", "new", "(", "string", ")", ",", "to", ",", "as", ":", "as", ",", "quiet", ":", "quiet", "end"], "docstring": "Write a string to a host file.\n @api private", "docstring_tokens": ["Write", "a", "string", "to", "a", "host", "file", "."], "sha": "9e09a56f9d4bf547bf1aa1843d894be625a27628", "url": "https://github.com/nbaum/blower/blob/9e09a56f9d4bf547bf1aa1843d894be625a27628/lib/blower/host.rb#L97-L99", "partition": "valid"} {"repo": "nbaum/blower", "path": "lib/blower/host.rb", "func_name": "Blower.Host.read", "original_string": "def read (filename, as: nil, quiet: false)\n Base64.decode64 sh(\"cat #{filename.shellescape} | base64\", as: as, quiet: quiet)\n end", "language": "ruby", "code": "def read (filename, as: nil, quiet: false)\n Base64.decode64 sh(\"cat #{filename.shellescape} | base64\", as: as, quiet: quiet)\n end", "code_tokens": ["def", "read", "(", "filename", ",", "as", ":", "nil", ",", "quiet", ":", "false", ")", "Base64", ".", "decode64", "sh", "(", "\"cat #{filename.shellescape} | base64\"", ",", "as", ":", "as", ",", "quiet", ":", "quiet", ")", "end"], "docstring": "Read a host file.\n @api private", "docstring_tokens": ["Read", "a", "host", "file", "."], "sha": "9e09a56f9d4bf547bf1aa1843d894be625a27628", "url": "https://github.com/nbaum/blower/blob/9e09a56f9d4bf547bf1aa1843d894be625a27628/lib/blower/host.rb#L103-L105", "partition": "valid"} {"repo": "nbaum/blower", "path": "lib/blower/host.rb", "func_name": "Blower.Host.sh", "original_string": "def sh (command, as: nil, quiet: false)\n as ||= @user\n output = \"\"\n synchronize do\n log.debug \"sh #{command}\", quiet: quiet\n result = nil\n ch = ssh(as).open_channel do |ch|\n ch.request_pty do |ch, success|\n \"failed to acquire pty\" unless success\n ch.exec(command) do |_, success|\n fail \"failed to execute command\" unless success\n ch.on_data do |_, data|\n log.trace \"received #{data.bytesize} bytes stdout\", quiet: quiet\n output << data\n end\n ch.on_extended_data do |_, _, data|\n log.trace \"received #{data.bytesize} bytes stderr\", quiet: quiet\n output << data.colorize(:red)\n end\n ch.on_request(\"exit-status\") do |_, data|\n result = data.read_long\n log.trace \"received exit-status #{result}\", quiet: quiet\n end\n end\n end\n end\n ch.wait\n fail FailedCommand, output if result != 0\n output\n end\n end", "language": "ruby", "code": "def sh (command, as: nil, quiet: false)\n as ||= @user\n output = \"\"\n synchronize do\n log.debug \"sh #{command}\", quiet: quiet\n result = nil\n ch = ssh(as).open_channel do |ch|\n ch.request_pty do |ch, success|\n \"failed to acquire pty\" unless success\n ch.exec(command) do |_, success|\n fail \"failed to execute command\" unless success\n ch.on_data do |_, data|\n log.trace \"received #{data.bytesize} bytes stdout\", quiet: quiet\n output << data\n end\n ch.on_extended_data do |_, _, data|\n log.trace \"received #{data.bytesize} bytes stderr\", quiet: quiet\n output << data.colorize(:red)\n end\n ch.on_request(\"exit-status\") do |_, data|\n result = data.read_long\n log.trace \"received exit-status #{result}\", quiet: quiet\n end\n end\n end\n end\n ch.wait\n fail FailedCommand, output if result != 0\n output\n end\n end", "code_tokens": ["def", "sh", "(", "command", ",", "as", ":", "nil", ",", "quiet", ":", "false", ")", "as", "||=", "@user", "output", "=", "\"\"", "synchronize", "do", "log", ".", "debug", "\"sh #{command}\"", ",", "quiet", ":", "quiet", "result", "=", "nil", "ch", "=", "ssh", "(", "as", ")", ".", "open_channel", "do", "|", "ch", "|", "ch", ".", "request_pty", "do", "|", "ch", ",", "success", "|", "\"failed to acquire pty\"", "unless", "success", "ch", ".", "exec", "(", "command", ")", "do", "|", "_", ",", "success", "|", "fail", "\"failed to execute command\"", "unless", "success", "ch", ".", "on_data", "do", "|", "_", ",", "data", "|", "log", ".", "trace", "\"received #{data.bytesize} bytes stdout\"", ",", "quiet", ":", "quiet", "output", "<<", "data", "end", "ch", ".", "on_extended_data", "do", "|", "_", ",", "_", ",", "data", "|", "log", ".", "trace", "\"received #{data.bytesize} bytes stderr\"", ",", "quiet", ":", "quiet", "output", "<<", "data", ".", "colorize", "(", ":red", ")", "end", "ch", ".", "on_request", "(", "\"exit-status\"", ")", "do", "|", "_", ",", "data", "|", "result", "=", "data", ".", "read_long", "log", ".", "trace", "\"received exit-status #{result}\"", ",", "quiet", ":", "quiet", "end", "end", "end", "end", "ch", ".", "wait", "fail", "FailedCommand", ",", "output", "if", "result", "!=", "0", "output", "end", "end"], "docstring": "Execute a command on the host and return its output.\n @api private", "docstring_tokens": ["Execute", "a", "command", "on", "the", "host", "and", "return", "its", "output", "."], "sha": "9e09a56f9d4bf547bf1aa1843d894be625a27628", "url": "https://github.com/nbaum/blower/blob/9e09a56f9d4bf547bf1aa1843d894be625a27628/lib/blower/host.rb#L109-L139", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/specimen_array_type.rb", "func_name": "CaTissue.SpecimenArrayType.can_hold_child?", "original_string": "def can_hold_child?(storable)\n Specimen === storable and storable.specimen_class == specimen_class and specimen_types.include?(storable.specimen_type)\n end", "language": "ruby", "code": "def can_hold_child?(storable)\n Specimen === storable and storable.specimen_class == specimen_class and specimen_types.include?(storable.specimen_type)\n end", "code_tokens": ["def", "can_hold_child?", "(", "storable", ")", "Specimen", "===", "storable", "and", "storable", ".", "specimen_class", "==", "specimen_class", "and", "specimen_types", ".", "include?", "(", "storable", ".", "specimen_type", ")", "end"], "docstring": "Returns true if Storable is a Specimen and supported by this SpecimenArrayType.", "docstring_tokens": ["Returns", "true", "if", "Storable", "is", "a", "Specimen", "and", "supported", "by", "this", "SpecimenArrayType", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/specimen_array_type.rb#L11-L13", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/aggregator.rb", "func_name": "Sycsvpro.Aggregator.process_aggregation", "original_string": "def process_aggregation\n File.new(infile).each_with_index do |line, index|\n result = col_filter.process(row_filter.process(line.chomp, row: index))\n unless result.nil? or result.empty?\n if heading.empty? and not headerless\n heading << result.split(';')\n next\n else\n @sum_col = [result.split(';').size, sum_col].max \n end\n key_values[result] += 1\n sums[sum_col_title] += 1\n end\n end\n heading.flatten!\n heading[sum_col] = sum_col_title\n end", "language": "ruby", "code": "def process_aggregation\n File.new(infile).each_with_index do |line, index|\n result = col_filter.process(row_filter.process(line.chomp, row: index))\n unless result.nil? or result.empty?\n if heading.empty? and not headerless\n heading << result.split(';')\n next\n else\n @sum_col = [result.split(';').size, sum_col].max \n end\n key_values[result] += 1\n sums[sum_col_title] += 1\n end\n end\n heading.flatten!\n heading[sum_col] = sum_col_title\n end", "code_tokens": ["def", "process_aggregation", "File", ".", "new", "(", "infile", ")", ".", "each_with_index", "do", "|", "line", ",", "index", "|", "result", "=", "col_filter", ".", "process", "(", "row_filter", ".", "process", "(", "line", ".", "chomp", ",", "row", ":", "index", ")", ")", "unless", "result", ".", "nil?", "or", "result", ".", "empty?", "if", "heading", ".", "empty?", "and", "not", "headerless", "heading", "<<", "result", ".", "split", "(", "';'", ")", "next", "else", "@sum_col", "=", "[", "result", ".", "split", "(", "';'", ")", ".", "size", ",", "sum_col", "]", ".", "max", "end", "key_values", "[", "result", "]", "+=", "1", "sums", "[", "sum_col_title", "]", "+=", "1", "end", "end", "heading", ".", "flatten!", "heading", "[", "sum_col", "]", "=", "sum_col_title", "end"], "docstring": "Process the aggregation of the key values. The result will be written to\n _outfile_", "docstring_tokens": ["Process", "the", "aggregation", "of", "the", "key", "values", ".", "The", "result", "will", "be", "written", "to", "_outfile_"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/aggregator.rb#L82-L98", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/aggregator.rb", "func_name": "Sycsvpro.Aggregator.write_result", "original_string": "def write_result\n sum_line = [sum_row_title]\n (heading.size - 2).times { sum_line << \"\" }\n sum_line << sums[sum_col_title]\n row = 0;\n File.open(outfile, 'w') do |out|\n out.puts sum_line.join(';') if row == sum_row ; row += 1\n out.puts heading.join(';')\n key_values.each do |k, v|\n out.puts sum_line.join(';') if row == sum_row ; row += 1\n out.puts [k, v].join(';')\n end\n end\n end", "language": "ruby", "code": "def write_result\n sum_line = [sum_row_title]\n (heading.size - 2).times { sum_line << \"\" }\n sum_line << sums[sum_col_title]\n row = 0;\n File.open(outfile, 'w') do |out|\n out.puts sum_line.join(';') if row == sum_row ; row += 1\n out.puts heading.join(';')\n key_values.each do |k, v|\n out.puts sum_line.join(';') if row == sum_row ; row += 1\n out.puts [k, v].join(';')\n end\n end\n end", "code_tokens": ["def", "write_result", "sum_line", "=", "[", "sum_row_title", "]", "(", "heading", ".", "size", "-", "2", ")", ".", "times", "{", "sum_line", "<<", "\"\"", "}", "sum_line", "<<", "sums", "[", "sum_col_title", "]", "row", "=", "0", ";", "File", ".", "open", "(", "outfile", ",", "'w'", ")", "do", "|", "out", "|", "out", ".", "puts", "sum_line", ".", "join", "(", "';'", ")", "if", "row", "==", "sum_row", ";", "row", "+=", "1", "out", ".", "puts", "heading", ".", "join", "(", "';'", ")", "key_values", ".", "each", "do", "|", "k", ",", "v", "|", "out", ".", "puts", "sum_line", ".", "join", "(", "';'", ")", "if", "row", "==", "sum_row", ";", "row", "+=", "1", "out", ".", "puts", "[", "k", ",", "v", "]", ".", "join", "(", "';'", ")", "end", "end", "end"], "docstring": "Writes the aggration results", "docstring_tokens": ["Writes", "the", "aggration", "results"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/aggregator.rb#L101-L114", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/aggregator.rb", "func_name": "Sycsvpro.Aggregator.init_sum_scheme", "original_string": "def init_sum_scheme(sum_scheme)\n row_scheme, col_scheme = sum_scheme.split(',') unless sum_scheme.nil?\n\n unless row_scheme.nil?\n @sum_row_title, @sum_row = row_scheme.split(':') unless row_scheme.empty?\n end\n \n @sum_row.nil? ? @sum_row = 0 : @sum_row = @sum_row.to_i\n @sum_row_title = 'Total' if @sum_row_title.nil? \n\n col_scheme.nil? ? @sum_col_title = 'Total' : @sum_col_title = col_scheme\n @sum_col = 0\n end", "language": "ruby", "code": "def init_sum_scheme(sum_scheme)\n row_scheme, col_scheme = sum_scheme.split(',') unless sum_scheme.nil?\n\n unless row_scheme.nil?\n @sum_row_title, @sum_row = row_scheme.split(':') unless row_scheme.empty?\n end\n \n @sum_row.nil? ? @sum_row = 0 : @sum_row = @sum_row.to_i\n @sum_row_title = 'Total' if @sum_row_title.nil? \n\n col_scheme.nil? ? @sum_col_title = 'Total' : @sum_col_title = col_scheme\n @sum_col = 0\n end", "code_tokens": ["def", "init_sum_scheme", "(", "sum_scheme", ")", "row_scheme", ",", "col_scheme", "=", "sum_scheme", ".", "split", "(", "','", ")", "unless", "sum_scheme", ".", "nil?", "unless", "row_scheme", ".", "nil?", "@sum_row_title", ",", "@sum_row", "=", "row_scheme", ".", "split", "(", "':'", ")", "unless", "row_scheme", ".", "empty?", "end", "@sum_row", ".", "nil?", "?", "@sum_row", "=", "0", ":", "@sum_row", "=", "@sum_row", ".", "to_i", "@sum_row_title", "=", "'Total'", "if", "@sum_row_title", ".", "nil?", "col_scheme", ".", "nil?", "?", "@sum_col_title", "=", "'Total'", ":", "@sum_col_title", "=", "col_scheme", "@sum_col", "=", "0", "end"], "docstring": "Initializes the sum row title an positions as well as the sum column\n title and position", "docstring_tokens": ["Initializes", "the", "sum", "row", "title", "an", "positions", "as", "well", "as", "the", "sum", "column", "title", "and", "position"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/aggregator.rb#L120-L132", "partition": "valid"} {"repo": "droidlabs/morf", "path": "lib/morf/caster.rb", "func_name": "Morf::Caster.ClassMethods.attributes", "original_string": "def attributes(&block)\n raise ArgumentError, \"You should provide block\" unless block_given?\n\n attributes = Morf::AttributesParser.parse(&block)\n self.class_variable_set(:@@attributes, attributes)\n end", "language": "ruby", "code": "def attributes(&block)\n raise ArgumentError, \"You should provide block\" unless block_given?\n\n attributes = Morf::AttributesParser.parse(&block)\n self.class_variable_set(:@@attributes, attributes)\n end", "code_tokens": ["def", "attributes", "(", "&", "block", ")", "raise", "ArgumentError", ",", "\"You should provide block\"", "unless", "block_given?", "attributes", "=", "Morf", "::", "AttributesParser", ".", "parse", "(", "block", ")", "self", ".", "class_variable_set", "(", ":@@attributes", ",", "attributes", ")", "end"], "docstring": "Defines casting rules\n @example\n attributes do\n string :first_name\n string :last_name\n integer :age, optional: true\n end", "docstring_tokens": ["Defines", "casting", "rules"], "sha": "acf02e0ed9277c7d494e8c9c60d054ca6c33e2da", "url": "https://github.com/droidlabs/morf/blob/acf02e0ed9277c7d494e8c9c60d054ca6c33e2da/lib/morf/caster.rb#L91-L96", "partition": "valid"} {"repo": "pmahoney/mini_aether", "path": "lib/mini_aether/resolver_impl.rb", "func_name": "MiniAether.ResolverImpl.resolve", "original_string": "def resolve(dep_hashes, repos)\n logger.info 'resolving dependencies'\n \n session = MavenRepositorySystemSession.new\n local_repo = LocalRepository.new(local_repository_path)\n local_manager = @system.newLocalRepositoryManager(local_repo)\n session.setLocalRepositoryManager(local_manager)\n\n collect_req = CollectRequest.new\n\n dep_hashes.each do |hash|\n dep = Dependency.new new_artifact(hash), 'compile'\n collect_req.addDependency dep\n logger.debug 'requested {}', dep\n end\n\n repos.each do |uri|\n repo = RemoteRepository.new(uri.object_id.to_s, 'default', uri)\n collect_req.addRepository repo\n logger.info 'added repository {}', repo.getUrl\n enabled = []\n enabled << 'releases' if repo.getPolicy(false).isEnabled\n enabled << 'snapshots' if repo.getPolicy(true).isEnabled\n logger.debug '{}', enabled.join('+')\n end\n\n node = @system.collectDependencies(session, collect_req).getRoot\n \n dependency_req = DependencyRequest.new(node, nil)\n @system.resolveDependencies(session, dependency_req)\n \n nlg = PreorderNodeListGenerator.new\n node.accept nlg\n\n if logger.isDebugEnabled\n total_size = 0\n nlg.getArtifacts(false).each do |artifact|\n file = artifact.file\n size = File.stat(artifact.file.absolute_path).size\n total_size += size\n \n logger.debug(\"Using %0.2f %s\" % [size/MiB_PER_BYTE, artifact])\n end\n logger.debug(' -----')\n logger.debug(\" %0.2f MiB total\" % [total_size/MiB_PER_BYTE])\n else\n nlg.getArtifacts(false).each do |artifact|\n logger.info 'Using {}', artifact\n end\n end\n\n nlg.getFiles.map{|e| e.to_s }\n end", "language": "ruby", "code": "def resolve(dep_hashes, repos)\n logger.info 'resolving dependencies'\n \n session = MavenRepositorySystemSession.new\n local_repo = LocalRepository.new(local_repository_path)\n local_manager = @system.newLocalRepositoryManager(local_repo)\n session.setLocalRepositoryManager(local_manager)\n\n collect_req = CollectRequest.new\n\n dep_hashes.each do |hash|\n dep = Dependency.new new_artifact(hash), 'compile'\n collect_req.addDependency dep\n logger.debug 'requested {}', dep\n end\n\n repos.each do |uri|\n repo = RemoteRepository.new(uri.object_id.to_s, 'default', uri)\n collect_req.addRepository repo\n logger.info 'added repository {}', repo.getUrl\n enabled = []\n enabled << 'releases' if repo.getPolicy(false).isEnabled\n enabled << 'snapshots' if repo.getPolicy(true).isEnabled\n logger.debug '{}', enabled.join('+')\n end\n\n node = @system.collectDependencies(session, collect_req).getRoot\n \n dependency_req = DependencyRequest.new(node, nil)\n @system.resolveDependencies(session, dependency_req)\n \n nlg = PreorderNodeListGenerator.new\n node.accept nlg\n\n if logger.isDebugEnabled\n total_size = 0\n nlg.getArtifacts(false).each do |artifact|\n file = artifact.file\n size = File.stat(artifact.file.absolute_path).size\n total_size += size\n \n logger.debug(\"Using %0.2f %s\" % [size/MiB_PER_BYTE, artifact])\n end\n logger.debug(' -----')\n logger.debug(\" %0.2f MiB total\" % [total_size/MiB_PER_BYTE])\n else\n nlg.getArtifacts(false).each do |artifact|\n logger.info 'Using {}', artifact\n end\n end\n\n nlg.getFiles.map{|e| e.to_s }\n end", "code_tokens": ["def", "resolve", "(", "dep_hashes", ",", "repos", ")", "logger", ".", "info", "'resolving dependencies'", "session", "=", "MavenRepositorySystemSession", ".", "new", "local_repo", "=", "LocalRepository", ".", "new", "(", "local_repository_path", ")", "local_manager", "=", "@system", ".", "newLocalRepositoryManager", "(", "local_repo", ")", "session", ".", "setLocalRepositoryManager", "(", "local_manager", ")", "collect_req", "=", "CollectRequest", ".", "new", "dep_hashes", ".", "each", "do", "|", "hash", "|", "dep", "=", "Dependency", ".", "new", "new_artifact", "(", "hash", ")", ",", "'compile'", "collect_req", ".", "addDependency", "dep", "logger", ".", "debug", "'requested {}'", ",", "dep", "end", "repos", ".", "each", "do", "|", "uri", "|", "repo", "=", "RemoteRepository", ".", "new", "(", "uri", ".", "object_id", ".", "to_s", ",", "'default'", ",", "uri", ")", "collect_req", ".", "addRepository", "repo", "logger", ".", "info", "'added repository {}'", ",", "repo", ".", "getUrl", "enabled", "=", "[", "]", "enabled", "<<", "'releases'", "if", "repo", ".", "getPolicy", "(", "false", ")", ".", "isEnabled", "enabled", "<<", "'snapshots'", "if", "repo", ".", "getPolicy", "(", "true", ")", ".", "isEnabled", "logger", ".", "debug", "'{}'", ",", "enabled", ".", "join", "(", "'+'", ")", "end", "node", "=", "@system", ".", "collectDependencies", "(", "session", ",", "collect_req", ")", ".", "getRoot", "dependency_req", "=", "DependencyRequest", ".", "new", "(", "node", ",", "nil", ")", "@system", ".", "resolveDependencies", "(", "session", ",", "dependency_req", ")", "nlg", "=", "PreorderNodeListGenerator", ".", "new", "node", ".", "accept", "nlg", "if", "logger", ".", "isDebugEnabled", "total_size", "=", "0", "nlg", ".", "getArtifacts", "(", "false", ")", ".", "each", "do", "|", "artifact", "|", "file", "=", "artifact", ".", "file", "size", "=", "File", ".", "stat", "(", "artifact", ".", "file", ".", "absolute_path", ")", ".", "size", "total_size", "+=", "size", "logger", ".", "debug", "(", "\"Using %0.2f %s\"", "%", "[", "size", "/", "MiB_PER_BYTE", ",", "artifact", "]", ")", "end", "logger", ".", "debug", "(", "' -----'", ")", "logger", ".", "debug", "(", "\" %0.2f MiB total\"", "%", "[", "total_size", "/", "MiB_PER_BYTE", "]", ")", "else", "nlg", ".", "getArtifacts", "(", "false", ")", ".", "each", "do", "|", "artifact", "|", "logger", ".", "info", "'Using {}'", ",", "artifact", "end", "end", "nlg", ".", "getFiles", ".", "map", "{", "|", "e", "|", "e", ".", "to_s", "}", "end"], "docstring": "Resolve a set of dependencies +dep_hashes+ from repositories\n +repos+.\n\n @param [Array] dep_hashes\n\n @option dep_hash [String] :group_id the groupId of the artifact\n @option dep_hash [String] :artifact_id the artifactId of the artifact\n @option dep_hash [String] :version the version (or range of versions) of the artifact\n @option dep_hash [String] :extension default to 'jar'\n\n @param [Array] repos urls to maven2 repositories\n\n @return [Array] list of files", "docstring_tokens": ["Resolve", "a", "set", "of", "dependencies", "+", "dep_hashes", "+", "from", "repositories", "+", "repos", "+", "."], "sha": "0359967c2fa5fd9ba8bd05b12567e307b44ea7a4", "url": "https://github.com/pmahoney/mini_aether/blob/0359967c2fa5fd9ba8bd05b12567e307b44ea7a4/lib/mini_aether/resolver_impl.rb#L67-L119", "partition": "valid"} {"repo": "jphager2/ruby-go", "path": "lib/ruby-go/board.rb", "func_name": "RubyGo.Board.place", "original_string": "def place(stone)\n x, y = stone.to_coord\n\n internal_board[y][x] = stone\n end", "language": "ruby", "code": "def place(stone)\n x, y = stone.to_coord\n\n internal_board[y][x] = stone\n end", "code_tokens": ["def", "place", "(", "stone", ")", "x", ",", "y", "=", "stone", ".", "to_coord", "internal_board", "[", "y", "]", "[", "x", "]", "=", "stone", "end"], "docstring": "Board shouldn't care about game rules", "docstring_tokens": ["Board", "shouldn", "t", "care", "about", "game", "rules"], "sha": "672e93f92bc8464aa14bed5f7a5bbd9c7a18aca5", "url": "https://github.com/jphager2/ruby-go/blob/672e93f92bc8464aa14bed5f7a5bbd9c7a18aca5/lib/ruby-go/board.rb#L41-L45", "partition": "valid"} {"repo": "ozgg/plasper", "path": "lib/Plasper/options.rb", "func_name": "Plasper.Options.parse", "original_string": "def parse(argv)\n OptionParser.new do |options|\n usage_and_help options\n assign_text_file options\n assign_weights_file options\n assign_output_file options\n\n begin\n options.parse argv\n rescue OptionParser::ParseError => error\n STDERR.puts error.message, \"\\n\", options\n exit(-1)\n end\n end\n end", "language": "ruby", "code": "def parse(argv)\n OptionParser.new do |options|\n usage_and_help options\n assign_text_file options\n assign_weights_file options\n assign_output_file options\n\n begin\n options.parse argv\n rescue OptionParser::ParseError => error\n STDERR.puts error.message, \"\\n\", options\n exit(-1)\n end\n end\n end", "code_tokens": ["def", "parse", "(", "argv", ")", "OptionParser", ".", "new", "do", "|", "options", "|", "usage_and_help", "options", "assign_text_file", "options", "assign_weights_file", "options", "assign_output_file", "options", "begin", "options", ".", "parse", "argv", "rescue", "OptionParser", "::", "ParseError", "=>", "error", "STDERR", ".", "puts", "error", ".", "message", ",", "\"\\n\"", ",", "options", "exit", "(", "-", "1", ")", "end", "end", "end"], "docstring": "Parse given arguments\n\n @param [Array] argv", "docstring_tokens": ["Parse", "given", "arguments"], "sha": "6dbca5fd7113522ecbfaced2a5ec4f0645486893", "url": "https://github.com/ozgg/plasper/blob/6dbca5fd7113522ecbfaced2a5ec4f0645486893/lib/Plasper/options.rb#L24-L38", "partition": "valid"} {"repo": "ManageIQ/active_bugzilla", "path": "lib/active_bugzilla/service.rb", "func_name": "ActiveBugzilla.Service.execute", "original_string": "def execute(command, params)\n params[:Bugzilla_login] ||= username\n params[:Bugzilla_password] ||= password\n\n self.last_command = command_string(command, params)\n xmlrpc_client.call(command, params)\n end", "language": "ruby", "code": "def execute(command, params)\n params[:Bugzilla_login] ||= username\n params[:Bugzilla_password] ||= password\n\n self.last_command = command_string(command, params)\n xmlrpc_client.call(command, params)\n end", "code_tokens": ["def", "execute", "(", "command", ",", "params", ")", "params", "[", ":Bugzilla_login", "]", "||=", "username", "params", "[", ":Bugzilla_password", "]", "||=", "password", "self", ".", "last_command", "=", "command_string", "(", "command", ",", "params", ")", "xmlrpc_client", ".", "call", "(", "command", ",", "params", ")", "end"], "docstring": "Clone of an existing bug\n\n Example:\n # Perform a clone of an existing bug, and return the new bug ID.\n bz.clone(948970)\n\n @param bug_id [String, Fixnum] A single bug id to process.\n @param overrides [Hash] The properties to change from the source bug. Some properties include\n * :target_release - The target release for the new cloned bug.\n * :assigned_to - The person to assign the new cloned bug to.\n @return [Fixnum] The bug id to the new, cloned, bug.", "docstring_tokens": ["Clone", "of", "an", "existing", "bug"], "sha": "3672da87bc25ce057978cf8fed9688670c09a50a", "url": "https://github.com/ManageIQ/active_bugzilla/blob/3672da87bc25ce057978cf8fed9688670c09a50a/lib/active_bugzilla/service.rb#L179-L185", "partition": "valid"} {"repo": "danijoo/Sightstone", "path": "lib/sightstone/modules/league_module.rb", "func_name": "Sightstone.LeagueModule.leagues", "original_string": "def leagues(summoner, optional={})\n region = optional[:region] || @sightstone.region\n id = if summoner.is_a? Summoner\n summoner.id\n else\n summoner\n end\n \n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v2.3/league/by-summoner/#{id}\"\n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n leagues = []\n data.each do |league|\n leagues << League.new(league)\n end\n if block_given?\n yield leagues\n else\n return leagues\n end\n }\n end", "language": "ruby", "code": "def leagues(summoner, optional={})\n region = optional[:region] || @sightstone.region\n id = if summoner.is_a? Summoner\n summoner.id\n else\n summoner\n end\n \n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v2.3/league/by-summoner/#{id}\"\n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n leagues = []\n data.each do |league|\n leagues << League.new(league)\n end\n if block_given?\n yield leagues\n else\n return leagues\n end\n }\n end", "code_tokens": ["def", "leagues", "(", "summoner", ",", "optional", "=", "{", "}", ")", "region", "=", "optional", "[", ":region", "]", "||", "@sightstone", ".", "region", "id", "=", "if", "summoner", ".", "is_a?", "Summoner", "summoner", ".", "id", "else", "summoner", "end", "uri", "=", "\"https://prod.api.pvp.net/api/lol/#{region}/v2.3/league/by-summoner/#{id}\"", "response", "=", "_get_api_response", "(", "uri", ")", "_parse_response", "(", "response", ")", "{", "|", "resp", "|", "data", "=", "JSON", ".", "parse", "(", "resp", ")", "leagues", "=", "[", "]", "data", ".", "each", "do", "|", "league", "|", "leagues", "<<", "League", ".", "new", "(", "league", ")", "end", "if", "block_given?", "yield", "leagues", "else", "return", "leagues", "end", "}", "end"], "docstring": "Provides league information of a summoner\n @param [Summoner, Integer] summoner\n @param optional [Hash] optional arguments: :region => replaces default region\n @return [Array] an array of all leagues the summoner and his teams are in", "docstring_tokens": ["Provides", "league", "information", "of", "a", "summoner"], "sha": "4c6709916ce7552f622de1a120c021e067601b4d", "url": "https://github.com/danijoo/Sightstone/blob/4c6709916ce7552f622de1a120c021e067601b4d/lib/sightstone/modules/league_module.rb#L16-L38", "partition": "valid"} {"repo": "danijoo/Sightstone", "path": "lib/sightstone/modules/league_module.rb", "func_name": "Sightstone.LeagueModule.league_entries", "original_string": "def league_entries(summoner, optional={})\n region = optional[:region] || @sightstone.region\n id = if summoner.is_a? Summoner\n summoner.id\n else\n summoner\n end\n \n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v2.3/league/by-summoner/#{id}/entry\"\n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n entries = []\n data.each do |entry|\n entries << LeagueItem.new(entry)\n end\n if block_given?\n yield entries\n else\n return entries\n end\n }\n end", "language": "ruby", "code": "def league_entries(summoner, optional={})\n region = optional[:region] || @sightstone.region\n id = if summoner.is_a? Summoner\n summoner.id\n else\n summoner\n end\n \n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v2.3/league/by-summoner/#{id}/entry\"\n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n entries = []\n data.each do |entry|\n entries << LeagueItem.new(entry)\n end\n if block_given?\n yield entries\n else\n return entries\n end\n }\n end", "code_tokens": ["def", "league_entries", "(", "summoner", ",", "optional", "=", "{", "}", ")", "region", "=", "optional", "[", ":region", "]", "||", "@sightstone", ".", "region", "id", "=", "if", "summoner", ".", "is_a?", "Summoner", "summoner", ".", "id", "else", "summoner", "end", "uri", "=", "\"https://prod.api.pvp.net/api/lol/#{region}/v2.3/league/by-summoner/#{id}/entry\"", "response", "=", "_get_api_response", "(", "uri", ")", "_parse_response", "(", "response", ")", "{", "|", "resp", "|", "data", "=", "JSON", ".", "parse", "(", "resp", ")", "entries", "=", "[", "]", "data", ".", "each", "do", "|", "entry", "|", "entries", "<<", "LeagueItem", ".", "new", "(", "entry", ")", "end", "if", "block_given?", "yield", "entries", "else", "return", "entries", "end", "}", "end"], "docstring": "Get all entries for the given summoner\n @param [Summoner, Integer] summoner or summoner id\n @param optional [Hash] optional arguments: :region => replaces default region\n @return [Array] an array of all entries for that given summoner", "docstring_tokens": ["Get", "all", "entries", "for", "the", "given", "summoner"], "sha": "4c6709916ce7552f622de1a120c021e067601b4d", "url": "https://github.com/danijoo/Sightstone/blob/4c6709916ce7552f622de1a120c021e067601b4d/lib/sightstone/modules/league_module.rb#L44-L66", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/sticker.rb", "func_name": "Turntabler.Sticker.place", "original_string": "def place(top, left, angle)\n api('sticker.place', :placement => [:sticker_id => id, :top => top, :left => left, :angle => angle], :is_dj => client.user.dj?, :roomid => room.id, :section => room.section)\n true\n end", "language": "ruby", "code": "def place(top, left, angle)\n api('sticker.place', :placement => [:sticker_id => id, :top => top, :left => left, :angle => angle], :is_dj => client.user.dj?, :roomid => room.id, :section => room.section)\n true\n end", "code_tokens": ["def", "place", "(", "top", ",", "left", ",", "angle", ")", "api", "(", "'sticker.place'", ",", ":placement", "=>", "[", ":sticker_id", "=>", "id", ",", ":top", "=>", "top", ",", ":left", "=>", "left", ",", ":angle", "=>", "angle", "]", ",", ":is_dj", "=>", "client", ".", "user", ".", "dj?", ",", ":roomid", "=>", "room", ".", "id", ",", ":section", "=>", "room", ".", "section", ")", "true", "end"], "docstring": "Sets the current user's stickers.\n\n @param [Fixnum] top The y-coordinate of the sticker\n @param [Fixnum] left The x-coordinate of the sticker\n @param [Float] angle The degree at which the sticker is angled\n @return [true]\n @raise [Turntabler::Error] if the command fails\n @example\n sticker.place(126, 78, -23) # => true", "docstring_tokens": ["Sets", "the", "current", "user", "s", "stickers", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/sticker.rb#L43-L46", "partition": "valid"} {"repo": "jonathanpike/mako", "path": "lib/mako/feed_finder.rb", "func_name": "Mako.FeedFinder.find", "original_string": "def find\n request_uris.map do |request|\n if request[:body].nil?\n request[:uri]\n else\n html = Nokogiri::HTML(request[:body])\n potential_feed_uris = html.xpath(XPATHS.detect { |path| !html.xpath(path).empty? })\n if potential_feed_uris.empty?\n Mako.errors.add_error \"Could not find feed for #{request[:uri]}\"\n next\n end\n uri_string = potential_feed_uris.first.value\n feed_uri = URI.parse(uri_string)\n feed_uri.absolutize!(request[:uri])\n end\n end.compact\n end", "language": "ruby", "code": "def find\n request_uris.map do |request|\n if request[:body].nil?\n request[:uri]\n else\n html = Nokogiri::HTML(request[:body])\n potential_feed_uris = html.xpath(XPATHS.detect { |path| !html.xpath(path).empty? })\n if potential_feed_uris.empty?\n Mako.errors.add_error \"Could not find feed for #{request[:uri]}\"\n next\n end\n uri_string = potential_feed_uris.first.value\n feed_uri = URI.parse(uri_string)\n feed_uri.absolutize!(request[:uri])\n end\n end.compact\n end", "code_tokens": ["def", "find", "request_uris", ".", "map", "do", "|", "request", "|", "if", "request", "[", ":body", "]", ".", "nil?", "request", "[", ":uri", "]", "else", "html", "=", "Nokogiri", "::", "HTML", "(", "request", "[", ":body", "]", ")", "potential_feed_uris", "=", "html", ".", "xpath", "(", "XPATHS", ".", "detect", "{", "|", "path", "|", "!", "html", ".", "xpath", "(", "path", ")", ".", "empty?", "}", ")", "if", "potential_feed_uris", ".", "empty?", "Mako", ".", "errors", ".", "add_error", "\"Could not find feed for #{request[:uri]}\"", "next", "end", "uri_string", "=", "potential_feed_uris", ".", "first", ".", "value", "feed_uri", "=", "URI", ".", "parse", "(", "uri_string", ")", "feed_uri", ".", "absolutize!", "(", "request", "[", ":uri", "]", ")", "end", "end", ".", "compact", "end"], "docstring": "From an array of supplied URIs, will request each one and attempt to\n find a feed URI on the page. If one is found, it will be added to\n an array and returned.\n\n @return [Array]", "docstring_tokens": ["From", "an", "array", "of", "supplied", "URIs", "will", "request", "each", "one", "and", "attempt", "to", "find", "a", "feed", "URI", "on", "the", "page", ".", "If", "one", "is", "found", "it", "will", "be", "added", "to", "an", "array", "and", "returned", "."], "sha": "2aa3665ebf23f09727e59d667b34155755493bdf", "url": "https://github.com/jonathanpike/mako/blob/2aa3665ebf23f09727e59d667b34155755493bdf/lib/mako/feed_finder.rb#L26-L42", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/specimen_collection_group.rb", "func_name": "CaTissue.SpecimenCollectionGroup.collection_status=", "original_string": "def collection_status=(value)\n if value == 'Complete' then\n specimens.each { |spc| spc.collection_status = 'Collected' if spc.pending? }\n end\n setCollectionStatus(value)\n end", "language": "ruby", "code": "def collection_status=(value)\n if value == 'Complete' then\n specimens.each { |spc| spc.collection_status = 'Collected' if spc.pending? }\n end\n setCollectionStatus(value)\n end", "code_tokens": ["def", "collection_status", "=", "(", "value", ")", "if", "value", "==", "'Complete'", "then", "specimens", ".", "each", "{", "|", "spc", "|", "spc", ".", "collection_status", "=", "'Collected'", "if", "spc", ".", "pending?", "}", "end", "setCollectionStatus", "(", "value", ")", "end"], "docstring": "Sets the collection status for this SCG.\n If the SCG status is set to +Complete+, then the status of each of the SCG Specimens with\n status +Pending+ is reset to +Collected+.\n\n @param [String] value a permissible SCG status", "docstring_tokens": ["Sets", "the", "collection", "status", "for", "this", "SCG", ".", "If", "the", "SCG", "status", "is", "set", "to", "+", "Complete", "+", "then", "the", "status", "of", "each", "of", "the", "SCG", "Specimens", "with", "status", "+", "Pending", "+", "is", "reset", "to", "+", "Collected", "+", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/specimen_collection_group.rb#L27-L32", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/specimen_collection_group.rb", "func_name": "CaTissue.SpecimenCollectionGroup.make_default_consent_tier_statuses", "original_string": "def make_default_consent_tier_statuses\n return if registration.nil? or registration.consent_tier_responses.empty?\n \n # the consent tiers\n ctses = consent_tier_statuses.map { |cts| cts.consent_tier }\n # ensure that there is a CT status for each consent tier\n registration.consent_tier_responses.each do |ctr|\n ct = ctr.consent_tier\n # skip if there is a status for the response tier\n next if ctses.include?(ct)\n # make a new status\n cts = CaTissue::ConsentTierStatus.new(:consent_tier => ct)\n cts.add_defaults\n consent_tier_statuses << cts\n logger.debug { \"Made default #{qp} #{cts.qp} for consent tier #{ct.qp}.\" }\n end\n end", "language": "ruby", "code": "def make_default_consent_tier_statuses\n return if registration.nil? or registration.consent_tier_responses.empty?\n \n # the consent tiers\n ctses = consent_tier_statuses.map { |cts| cts.consent_tier }\n # ensure that there is a CT status for each consent tier\n registration.consent_tier_responses.each do |ctr|\n ct = ctr.consent_tier\n # skip if there is a status for the response tier\n next if ctses.include?(ct)\n # make a new status\n cts = CaTissue::ConsentTierStatus.new(:consent_tier => ct)\n cts.add_defaults\n consent_tier_statuses << cts\n logger.debug { \"Made default #{qp} #{cts.qp} for consent tier #{ct.qp}.\" }\n end\n end", "code_tokens": ["def", "make_default_consent_tier_statuses", "return", "if", "registration", ".", "nil?", "or", "registration", ".", "consent_tier_responses", ".", "empty?", "# the consent tiers", "ctses", "=", "consent_tier_statuses", ".", "map", "{", "|", "cts", "|", "cts", ".", "consent_tier", "}", "# ensure that there is a CT status for each consent tier", "registration", ".", "consent_tier_responses", ".", "each", "do", "|", "ctr", "|", "ct", "=", "ctr", ".", "consent_tier", "# skip if there is a status for the response tier", "next", "if", "ctses", ".", "include?", "(", "ct", ")", "# make a new status", "cts", "=", "CaTissue", "::", "ConsentTierStatus", ".", "new", "(", ":consent_tier", "=>", "ct", ")", "cts", ".", "add_defaults", "consent_tier_statuses", "<<", "cts", "logger", ".", "debug", "{", "\"Made default #{qp} #{cts.qp} for consent tier #{ct.qp}.\"", "}", "end", "end"], "docstring": "Makes a consent status for each registration consent.\n\n @quirk caTissue Bug #156: SCG without consent status displays error.\n A SCG consent tier status is required for each consent tier in the SCG registration.", "docstring_tokens": ["Makes", "a", "consent", "status", "for", "each", "registration", "consent", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/specimen_collection_group.rb#L271-L287", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/specimen_collection_group.rb", "func_name": "CaTissue.SpecimenCollectionGroup.default_collection_event", "original_string": "def default_collection_event\n return if registration.nil?\n pcl = registration.protocol || return\n # if no protocol event, then add the default event\n pcl.add_defaults if pcl.events.empty?\n ev = pcl.sorted_events.first || return\n logger.debug { \"Default #{qp} collection event is the registration protocol #{pcl.qp} first event #{ev.qp}.\" }\n ev\n end", "language": "ruby", "code": "def default_collection_event\n return if registration.nil?\n pcl = registration.protocol || return\n # if no protocol event, then add the default event\n pcl.add_defaults if pcl.events.empty?\n ev = pcl.sorted_events.first || return\n logger.debug { \"Default #{qp} collection event is the registration protocol #{pcl.qp} first event #{ev.qp}.\" }\n ev\n end", "code_tokens": ["def", "default_collection_event", "return", "if", "registration", ".", "nil?", "pcl", "=", "registration", ".", "protocol", "||", "return", "# if no protocol event, then add the default event", "pcl", ".", "add_defaults", "if", "pcl", ".", "events", ".", "empty?", "ev", "=", "pcl", ".", "sorted_events", ".", "first", "||", "return", "logger", ".", "debug", "{", "\"Default #{qp} collection event is the registration protocol #{pcl.qp} first event #{ev.qp}.\"", "}", "ev", "end"], "docstring": "Returns the first event in the protocol registered with this SCG.", "docstring_tokens": ["Returns", "the", "first", "event", "in", "the", "protocol", "registered", "with", "this", "SCG", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/specimen_collection_group.rb#L298-L306", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/specimen_collection_group.rb", "func_name": "CaTissue.SpecimenCollectionGroup.default_receiver", "original_string": "def default_receiver\n cep = collection_event_parameters\n cltr = cep.user if cep\n return cltr if cltr\n cp = collection_protocol || return\n rcv = cp.coordinators.first\n return rcv if rcv or cp.fetched?\n # Try to fetch the CP coordinator \n return cp.coordinators.first if cp.find\n # CP does not exist; add the CP defaults and retry\n cp.add_defaults\n cp.coordinators.first\n end", "language": "ruby", "code": "def default_receiver\n cep = collection_event_parameters\n cltr = cep.user if cep\n return cltr if cltr\n cp = collection_protocol || return\n rcv = cp.coordinators.first\n return rcv if rcv or cp.fetched?\n # Try to fetch the CP coordinator \n return cp.coordinators.first if cp.find\n # CP does not exist; add the CP defaults and retry\n cp.add_defaults\n cp.coordinators.first\n end", "code_tokens": ["def", "default_receiver", "cep", "=", "collection_event_parameters", "cltr", "=", "cep", ".", "user", "if", "cep", "return", "cltr", "if", "cltr", "cp", "=", "collection_protocol", "||", "return", "rcv", "=", "cp", ".", "coordinators", ".", "first", "return", "rcv", "if", "rcv", "or", "cp", ".", "fetched?", "# Try to fetch the CP coordinator ", "return", "cp", ".", "coordinators", ".", "first", "if", "cp", ".", "find", "# CP does not exist; add the CP defaults and retry", "cp", ".", "add_defaults", "cp", ".", "coordinators", ".", "first", "end"], "docstring": "Returns the collection protocol coordinator. Fetches the CP if necessary and possible.\n Adds defaults to the CP if necessary, which sets a default coordinator if possible.\n\n @return [CaTissue::User] the default receiver", "docstring_tokens": ["Returns", "the", "collection", "protocol", "coordinator", ".", "Fetches", "the", "CP", "if", "necessary", "and", "possible", ".", "Adds", "defaults", "to", "the", "CP", "if", "necessary", "which", "sets", "a", "default", "coordinator", "if", "possible", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/specimen_collection_group.rb#L324-L336", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/specimen.rb", "func_name": "CaTissue.Specimen.decrement_derived_quantity", "original_string": "def decrement_derived_quantity(child)\n return unless specimen_type == child.specimen_type and child.initial_quantity\n if available_quantity.nil? then\n raise Jinx::ValidationError.new(\"Derived specimen has an initial quantity #{child.initial_quantity} but the parent is missing an available quantity\")\n elsif (available_quantity - child.initial_quantity).abs < 0.00000001 then\n # rounding error\n self.available_quantity = 0.0\n elsif child.initial_quantity <= available_quantity then\n self.available_quantity -= child.initial_quantity\n else\n raise Jinx::ValidationError.new(\"Derived specimen initial quantity #{child.initial_quantity} exceeds parent available quantity #{available_quantity}\")\n end\n end", "language": "ruby", "code": "def decrement_derived_quantity(child)\n return unless specimen_type == child.specimen_type and child.initial_quantity\n if available_quantity.nil? then\n raise Jinx::ValidationError.new(\"Derived specimen has an initial quantity #{child.initial_quantity} but the parent is missing an available quantity\")\n elsif (available_quantity - child.initial_quantity).abs < 0.00000001 then\n # rounding error\n self.available_quantity = 0.0\n elsif child.initial_quantity <= available_quantity then\n self.available_quantity -= child.initial_quantity\n else\n raise Jinx::ValidationError.new(\"Derived specimen initial quantity #{child.initial_quantity} exceeds parent available quantity #{available_quantity}\")\n end\n end", "code_tokens": ["def", "decrement_derived_quantity", "(", "child", ")", "return", "unless", "specimen_type", "==", "child", ".", "specimen_type", "and", "child", ".", "initial_quantity", "if", "available_quantity", ".", "nil?", "then", "raise", "Jinx", "::", "ValidationError", ".", "new", "(", "\"Derived specimen has an initial quantity #{child.initial_quantity} but the parent is missing an available quantity\"", ")", "elsif", "(", "available_quantity", "-", "child", ".", "initial_quantity", ")", ".", "abs", "<", "0.00000001", "then", "# rounding error", "self", ".", "available_quantity", "=", "0.0", "elsif", "child", ".", "initial_quantity", "<=", "available_quantity", "then", "self", ".", "available_quantity", "-=", "child", ".", "initial_quantity", "else", "raise", "Jinx", "::", "ValidationError", ".", "new", "(", "\"Derived specimen initial quantity #{child.initial_quantity} exceeds parent available quantity #{available_quantity}\"", ")", "end", "end"], "docstring": "Decrements this parent's available quantity by the given child's initial quantity, if the specimen types are the same and there\n are the relevant quantities.", "docstring_tokens": ["Decrements", "this", "parent", "s", "available", "quantity", "by", "the", "given", "child", "s", "initial", "quantity", "if", "the", "specimen", "types", "are", "the", "same", "and", "there", "are", "the", "relevant", "quantities", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/specimen.rb#L580-L592", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/database.rb", "func_name": "CaTissue.Database.update_changed_dependent", "original_string": "def update_changed_dependent(owner, property, dependent, autogenerated)\n # Save the changed collectible event parameters directly rather than via a cascade.\n if CollectibleEventParameters === dependent then\n logger.debug { \"Work around a caTissue bug by resaving the collected #{owner} #{dependent} directly rather than via a cascade...\" }\n update_from_template(dependent)\n elsif CaTissue::User === owner and property.attribute == :address then\n update_user_address(owner, dependent)\n elsif CaTissue::Specimen === owner and CaTissue::Specimen === dependent then\n logger.debug { \"Work around caTissue bug to update #{dependent} separately after the parent #{owner} update...\" }\n prepare_specimen_for_update(dependent)\n update_from_template(dependent)\n logger.debug { \"Updated the #{owner} child #{dependent}.\" }\n elsif CaTissue::ConsentTierStatus === dependent then\n update_from_template(owner)\n else\n super\n end\n end", "language": "ruby", "code": "def update_changed_dependent(owner, property, dependent, autogenerated)\n # Save the changed collectible event parameters directly rather than via a cascade.\n if CollectibleEventParameters === dependent then\n logger.debug { \"Work around a caTissue bug by resaving the collected #{owner} #{dependent} directly rather than via a cascade...\" }\n update_from_template(dependent)\n elsif CaTissue::User === owner and property.attribute == :address then\n update_user_address(owner, dependent)\n elsif CaTissue::Specimen === owner and CaTissue::Specimen === dependent then\n logger.debug { \"Work around caTissue bug to update #{dependent} separately after the parent #{owner} update...\" }\n prepare_specimen_for_update(dependent)\n update_from_template(dependent)\n logger.debug { \"Updated the #{owner} child #{dependent}.\" }\n elsif CaTissue::ConsentTierStatus === dependent then\n update_from_template(owner)\n else\n super\n end\n end", "code_tokens": ["def", "update_changed_dependent", "(", "owner", ",", "property", ",", "dependent", ",", "autogenerated", ")", "# Save the changed collectible event parameters directly rather than via a cascade.", "if", "CollectibleEventParameters", "===", "dependent", "then", "logger", ".", "debug", "{", "\"Work around a caTissue bug by resaving the collected #{owner} #{dependent} directly rather than via a cascade...\"", "}", "update_from_template", "(", "dependent", ")", "elsif", "CaTissue", "::", "User", "===", "owner", "and", "property", ".", "attribute", "==", ":address", "then", "update_user_address", "(", "owner", ",", "dependent", ")", "elsif", "CaTissue", "::", "Specimen", "===", "owner", "and", "CaTissue", "::", "Specimen", "===", "dependent", "then", "logger", ".", "debug", "{", "\"Work around caTissue bug to update #{dependent} separately after the parent #{owner} update...\"", "}", "prepare_specimen_for_update", "(", "dependent", ")", "update_from_template", "(", "dependent", ")", "logger", ".", "debug", "{", "\"Updated the #{owner} child #{dependent}.\"", "}", "elsif", "CaTissue", "::", "ConsentTierStatus", "===", "dependent", "then", "update_from_template", "(", "owner", ")", "else", "super", "end", "end"], "docstring": "Updates the given dependent.\n\n @quirk caTissue 1.2 user address update results in authorization error. Work-around is to\n create a new address record.\n\n @quirk caTissue Specimen update cascades to child update according to Hibernate, but\n caTissue somehow circumvents the child update. The child database content is not changed\n to reflect the update argument. Work-around is to update the child independently after\n the parent update.\n\n @quirk caTissue The aforementioned {#save_with_template} caTissue collectible event parameters\n dependent bug implies that the dependent must be saved directly rather than via a cascade\n from the Specimen or SCG owner to the referenced event parameters. The direct save avoids\n a tangled nest of obscure caTissue bugs described in the {#save_with_template} rubydoc.\n\n @quirk caTissue A SCG or Specimen consent tier status is not necessarily cascaded.\n @param (see CaRuby::Writer#update_changed_dependent)", "docstring_tokens": ["Updates", "the", "given", "dependent", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/database.rb#L272-L289", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/database.rb", "func_name": "CaTissue.Database.update_user_address", "original_string": "def update_user_address(user, address)\n logger.debug { \"Work around caTissue prohibition of #{user} address #{address} update by creating a new address record for a dummy user...\" }\n address.identifier = nil\n perform(:create, address) { create_object(address) }\n logger.debug { \"Worked around caTissue address update bug by swizzling the #{user} address #{address} identifier.\" }\n perform(:update, user) { update_object(user) }\n user\n end", "language": "ruby", "code": "def update_user_address(user, address)\n logger.debug { \"Work around caTissue prohibition of #{user} address #{address} update by creating a new address record for a dummy user...\" }\n address.identifier = nil\n perform(:create, address) { create_object(address) }\n logger.debug { \"Worked around caTissue address update bug by swizzling the #{user} address #{address} identifier.\" }\n perform(:update, user) { update_object(user) }\n user\n end", "code_tokens": ["def", "update_user_address", "(", "user", ",", "address", ")", "logger", ".", "debug", "{", "\"Work around caTissue prohibition of #{user} address #{address} update by creating a new address record for a dummy user...\"", "}", "address", ".", "identifier", "=", "nil", "perform", "(", ":create", ",", "address", ")", "{", "create_object", "(", "address", ")", "}", "logger", ".", "debug", "{", "\"Worked around caTissue address update bug by swizzling the #{user} address #{address} identifier.\"", "}", "perform", "(", ":update", ",", "user", ")", "{", "update_object", "(", "user", ")", "}", "user", "end"], "docstring": "Updates the given user address.\n\n @param [CaTissue::User] the user owner\n @param [CaTissue::Address] the address to update\n @return [CaTissue::User] the updated user", "docstring_tokens": ["Updates", "the", "given", "user", "address", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/database.rb#L347-L354", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/database.rb", "func_name": "CaTissue.Database.add_position_to_specimen_template", "original_string": "def add_position_to_specimen_template(specimen, template)\n pos = specimen.position\n # the non-domain position attributes\n pas = pos.class.nondomain_attributes\n # the template position reflects the old values, if available\n ss = pos.snapshot\n # the attribute => value hash\n vh = ss ? pas.to_compact_hash { |pas| ss[pas] } : pos.value_hash(pas)\n vh[:specimen] = template\n vh[:storage_container] = pos.storage_container.copy\n # the template position reflects the old values\n template.position = pos.class.new(vh)\n logger.debug { \"Work around #{specimen} update anomaly by copying position #{template.position.qp} to update template #{template.qp} as #{template.position.qp} with values #{vh.qp}...\" }\n end", "language": "ruby", "code": "def add_position_to_specimen_template(specimen, template)\n pos = specimen.position\n # the non-domain position attributes\n pas = pos.class.nondomain_attributes\n # the template position reflects the old values, if available\n ss = pos.snapshot\n # the attribute => value hash\n vh = ss ? pas.to_compact_hash { |pas| ss[pas] } : pos.value_hash(pas)\n vh[:specimen] = template\n vh[:storage_container] = pos.storage_container.copy\n # the template position reflects the old values\n template.position = pos.class.new(vh)\n logger.debug { \"Work around #{specimen} update anomaly by copying position #{template.position.qp} to update template #{template.qp} as #{template.position.qp} with values #{vh.qp}...\" }\n end", "code_tokens": ["def", "add_position_to_specimen_template", "(", "specimen", ",", "template", ")", "pos", "=", "specimen", ".", "position", "# the non-domain position attributes", "pas", "=", "pos", ".", "class", ".", "nondomain_attributes", "# the template position reflects the old values, if available", "ss", "=", "pos", ".", "snapshot", "# the attribute => value hash", "vh", "=", "ss", "?", "pas", ".", "to_compact_hash", "{", "|", "pas", "|", "ss", "[", "pas", "]", "}", ":", "pos", ".", "value_hash", "(", "pas", ")", "vh", "[", ":specimen", "]", "=", "template", "vh", "[", ":storage_container", "]", "=", "pos", ".", "storage_container", ".", "copy", "# the template position reflects the old values", "template", ".", "position", "=", "pos", ".", "class", ".", "new", "(", "vh", ")", "logger", ".", "debug", "{", "\"Work around #{specimen} update anomaly by copying position #{template.position.qp} to update template #{template.qp} as #{template.position.qp} with values #{vh.qp}...\"", "}", "end"], "docstring": "Adds the specimen position to its save template.\n\n @param [CaTissue::Specimen] specimen the existing specimen with an existing position\n @param template (see #save_with_template)\n @see {#save_with_template}", "docstring_tokens": ["Adds", "the", "specimen", "position", "to", "its", "save", "template", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/database.rb#L385-L398", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/database.rb", "func_name": "CaTissue.Database.ensure_primary_annotation_has_hook", "original_string": "def ensure_primary_annotation_has_hook(annotation)\n hook = annotation.hook\n if hook.nil? then\n raise CaRuby::DatabaseError.new(\"Cannot save annotation #{annotation} since it does not reference a hook entity\")\n end\n if hook.identifier.nil? then\n logger.debug { \"Ensuring that the annotation #{annotation.qp} hook entity #{hook.qp} exists in the database...\" }\n ensure_exists(hook)\n end\n end", "language": "ruby", "code": "def ensure_primary_annotation_has_hook(annotation)\n hook = annotation.hook\n if hook.nil? then\n raise CaRuby::DatabaseError.new(\"Cannot save annotation #{annotation} since it does not reference a hook entity\")\n end\n if hook.identifier.nil? then\n logger.debug { \"Ensuring that the annotation #{annotation.qp} hook entity #{hook.qp} exists in the database...\" }\n ensure_exists(hook)\n end\n end", "code_tokens": ["def", "ensure_primary_annotation_has_hook", "(", "annotation", ")", "hook", "=", "annotation", ".", "hook", "if", "hook", ".", "nil?", "then", "raise", "CaRuby", "::", "DatabaseError", ".", "new", "(", "\"Cannot save annotation #{annotation} since it does not reference a hook entity\"", ")", "end", "if", "hook", ".", "identifier", ".", "nil?", "then", "logger", ".", "debug", "{", "\"Ensuring that the annotation #{annotation.qp} hook entity #{hook.qp} exists in the database...\"", "}", "ensure_exists", "(", "hook", ")", "end", "end"], "docstring": "Ensures that a primary annotation hook exists.\n\n @param (see #prepare_annotation_for_save)\n @raise [CaRuby::DatabaseError] if the annotation does not reference a hook entity", "docstring_tokens": ["Ensures", "that", "a", "primary", "annotation", "hook", "exists", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/database.rb#L503-L512", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/database.rb", "func_name": "CaTissue.Database.copy_annotation_proxy_owner_to_template", "original_string": "def copy_annotation_proxy_owner_to_template(obj, template)\n prop = obj.class.proxy_property\n # Ignore the proxy attribute if it is defined by caRuby rather than caTissue.\n return unless prop and prop.java_property?\n rdr, wtr = prop.java_accessors\n pxy = obj.send(rdr)\n logger.debug { \"Setting #{obj.qp} template #{template.qp} proxy owner to #{pxy}...\" }\n template.send(wtr, pxy)\n end", "language": "ruby", "code": "def copy_annotation_proxy_owner_to_template(obj, template)\n prop = obj.class.proxy_property\n # Ignore the proxy attribute if it is defined by caRuby rather than caTissue.\n return unless prop and prop.java_property?\n rdr, wtr = prop.java_accessors\n pxy = obj.send(rdr)\n logger.debug { \"Setting #{obj.qp} template #{template.qp} proxy owner to #{pxy}...\" }\n template.send(wtr, pxy)\n end", "code_tokens": ["def", "copy_annotation_proxy_owner_to_template", "(", "obj", ",", "template", ")", "prop", "=", "obj", ".", "class", ".", "proxy_property", "# Ignore the proxy attribute if it is defined by caRuby rather than caTissue.", "return", "unless", "prop", "and", "prop", ".", "java_property?", "rdr", ",", "wtr", "=", "prop", ".", "java_accessors", "pxy", "=", "obj", ".", "send", "(", "rdr", ")", "logger", ".", "debug", "{", "\"Setting #{obj.qp} template #{template.qp} proxy owner to #{pxy}...\"", "}", "template", ".", "send", "(", "wtr", ",", "pxy", ")", "end"], "docstring": "The annotation proxy is not copied because the attribute redirects to the hook rather\n than the proxy. Set the template copy source proxy to the target object proxy using\n the low-level Java property methods instead.\n\n @param [Annotation] obj the copy source\n @param [Annotation] template the copy target", "docstring_tokens": ["The", "annotation", "proxy", "is", "not", "copied", "because", "the", "attribute", "redirects", "to", "the", "hook", "rather", "than", "the", "proxy", ".", "Set", "the", "template", "copy", "source", "proxy", "to", "the", "target", "object", "proxy", "using", "the", "low", "-", "level", "Java", "property", "methods", "instead", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/database.rb#L788-L796", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/table.rb", "func_name": "Sycsvpro.Table.create_table_data", "original_string": "def create_table_data\n processed_header = false\n\n File.open(infile).each_with_index do |line, index|\n line = line.chomp\n\n next if line.empty?\n \n line = unstring(line).chomp\n\n header.process line, processed_header\n\n unless processed_header\n processed_header = true\n next\n end\n\n next if row_filter.process(line, row: index).nil?\n \n @columns = line.split(';')\n\n create_row(create_key, line)\n end\n\n end", "language": "ruby", "code": "def create_table_data\n processed_header = false\n\n File.open(infile).each_with_index do |line, index|\n line = line.chomp\n\n next if line.empty?\n \n line = unstring(line).chomp\n\n header.process line, processed_header\n\n unless processed_header\n processed_header = true\n next\n end\n\n next if row_filter.process(line, row: index).nil?\n \n @columns = line.split(';')\n\n create_row(create_key, line)\n end\n\n end", "code_tokens": ["def", "create_table_data", "processed_header", "=", "false", "File", ".", "open", "(", "infile", ")", ".", "each_with_index", "do", "|", "line", ",", "index", "|", "line", "=", "line", ".", "chomp", "next", "if", "line", ".", "empty?", "line", "=", "unstring", "(", "line", ")", ".", "chomp", "header", ".", "process", "line", ",", "processed_header", "unless", "processed_header", "processed_header", "=", "true", "next", "end", "next", "if", "row_filter", ".", "process", "(", "line", ",", "row", ":", "index", ")", ".", "nil?", "@columns", "=", "line", ".", "split", "(", "';'", ")", "create_row", "(", "create_key", ",", "line", ")", "end", "end"], "docstring": "Create the table", "docstring_tokens": ["Create", "the", "table"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/table.rb#L103-L127", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/table.rb", "func_name": "Sycsvpro.Table.write_to_file", "original_string": "def write_to_file\n File.open(outfile, 'w') do |out|\n out.puts header.to_s\n out.puts create_sum_row if @sum_row_pos == 'TOP'\n rows.each do |key, row|\n line = [] << row[:key]\n header.clear_header_cols.each_with_index do |col, index|\n next if index < row[:key].size\n line << row[:cols][col]\n end\n out.puts line.flatten.join(';')\n end\n out.puts create_sum_row if @sum_row_pos == 'EOF'\n end\n end", "language": "ruby", "code": "def write_to_file\n File.open(outfile, 'w') do |out|\n out.puts header.to_s\n out.puts create_sum_row if @sum_row_pos == 'TOP'\n rows.each do |key, row|\n line = [] << row[:key]\n header.clear_header_cols.each_with_index do |col, index|\n next if index < row[:key].size\n line << row[:cols][col]\n end\n out.puts line.flatten.join(';')\n end\n out.puts create_sum_row if @sum_row_pos == 'EOF'\n end\n end", "code_tokens": ["def", "write_to_file", "File", ".", "open", "(", "outfile", ",", "'w'", ")", "do", "|", "out", "|", "out", ".", "puts", "header", ".", "to_s", "out", ".", "puts", "create_sum_row", "if", "@sum_row_pos", "==", "'TOP'", "rows", ".", "each", "do", "|", "key", ",", "row", "|", "line", "=", "[", "]", "<<", "row", "[", ":key", "]", "header", ".", "clear_header_cols", ".", "each_with_index", "do", "|", "col", ",", "index", "|", "next", "if", "index", "<", "row", "[", ":key", "]", ".", "size", "line", "<<", "row", "[", ":cols", "]", "[", "col", "]", "end", "out", ".", "puts", "line", ".", "flatten", ".", "join", "(", "';'", ")", "end", "out", ".", "puts", "create_sum_row", "if", "@sum_row_pos", "==", "'EOF'", "end", "end"], "docstring": "Write table to _outfile_", "docstring_tokens": ["Write", "table", "to", "_outfile_"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/table.rb#L130-L144", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/table.rb", "func_name": "Sycsvpro.Table.to_number", "original_string": "def to_number(value)\n value = convert_to_en(value)\n return value.to_i unless value =~ /\\./\n return value.to_f if value =~ /\\./ \n end", "language": "ruby", "code": "def to_number(value)\n value = convert_to_en(value)\n return value.to_i unless value =~ /\\./\n return value.to_f if value =~ /\\./ \n end", "code_tokens": ["def", "to_number", "(", "value", ")", "value", "=", "convert_to_en", "(", "value", ")", "return", "value", ".", "to_i", "unless", "value", "=~", "/", "\\.", "/", "return", "value", ".", "to_f", "if", "value", "=~", "/", "\\.", "/", "end"], "docstring": "Casts a string to an integer or float depending whether the value has a\n decimal point", "docstring_tokens": ["Casts", "a", "string", "to", "an", "integer", "or", "float", "depending", "whether", "the", "value", "has", "a", "decimal", "point"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/table.rb#L176-L180", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/table.rb", "func_name": "Sycsvpro.Table.prepare_sum_row", "original_string": "def prepare_sum_row(pattern)\n return if pattern.nil? || pattern.empty?\n @sum_row_pos, sum_row_pattern = pattern.split(/(?<=^top|^eof):/i)\n @sum_row_pos.upcase!\n @sum_row = Hash.new\n @sum_row_patterns = split_by_comma_regex(sum_row_pattern)\n end", "language": "ruby", "code": "def prepare_sum_row(pattern)\n return if pattern.nil? || pattern.empty?\n @sum_row_pos, sum_row_pattern = pattern.split(/(?<=^top|^eof):/i)\n @sum_row_pos.upcase!\n @sum_row = Hash.new\n @sum_row_patterns = split_by_comma_regex(sum_row_pattern)\n end", "code_tokens": ["def", "prepare_sum_row", "(", "pattern", ")", "return", "if", "pattern", ".", "nil?", "||", "pattern", ".", "empty?", "@sum_row_pos", ",", "sum_row_pattern", "=", "pattern", ".", "split", "(", "/", "/i", ")", "@sum_row_pos", ".", "upcase!", "@sum_row", "=", "Hash", ".", "new", "@sum_row_patterns", "=", "split_by_comma_regex", "(", "sum_row_pattern", ")", "end"], "docstring": "Initializes sum_row_pos, sum_row and sum_row_patterns based on the\n provided sum option", "docstring_tokens": ["Initializes", "sum_row_pos", "sum_row", "and", "sum_row_patterns", "based", "on", "the", "provided", "sum", "option"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/table.rb#L216-L222", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/table.rb", "func_name": "Sycsvpro.Table.add_to_sum_row", "original_string": "def add_to_sum_row(value, column)\n return unless @sum_row_patterns\n @sum_row_patterns.each do |pattern|\n if pattern =~ /^\\(?c\\d+[=~+.]/\n header_column = evaluate(pattern, \"\")\n else\n header_column = pattern\n end\n\n if header_column == column\n @sum_row[header_column] ||= 0\n @sum_row[header_column] += value\n end\n end\n end", "language": "ruby", "code": "def add_to_sum_row(value, column)\n return unless @sum_row_patterns\n @sum_row_patterns.each do |pattern|\n if pattern =~ /^\\(?c\\d+[=~+.]/\n header_column = evaluate(pattern, \"\")\n else\n header_column = pattern\n end\n\n if header_column == column\n @sum_row[header_column] ||= 0\n @sum_row[header_column] += value\n end\n end\n end", "code_tokens": ["def", "add_to_sum_row", "(", "value", ",", "column", ")", "return", "unless", "@sum_row_patterns", "@sum_row_patterns", ".", "each", "do", "|", "pattern", "|", "if", "pattern", "=~", "/", "\\(", "\\d", "/", "header_column", "=", "evaluate", "(", "pattern", ",", "\"\"", ")", "else", "header_column", "=", "pattern", "end", "if", "header_column", "==", "column", "@sum_row", "[", "header_column", "]", "||=", "0", "@sum_row", "[", "header_column", "]", "+=", "value", "end", "end", "end"], "docstring": "Adds a value in the specified column to the sum_row", "docstring_tokens": ["Adds", "a", "value", "in", "the", "specified", "column", "to", "the", "sum_row"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/table.rb#L225-L239", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/table.rb", "func_name": "Sycsvpro.Table.create_sum_row", "original_string": "def create_sum_row\n line = []\n header.clear_header_cols.each do |col|\n line << @sum_row[col] || \"\"\n end\n line.flatten.join(';')\n end", "language": "ruby", "code": "def create_sum_row\n line = []\n header.clear_header_cols.each do |col|\n line << @sum_row[col] || \"\"\n end\n line.flatten.join(';')\n end", "code_tokens": ["def", "create_sum_row", "line", "=", "[", "]", "header", ".", "clear_header_cols", ".", "each", "do", "|", "col", "|", "line", "<<", "@sum_row", "[", "col", "]", "||", "\"\"", "end", "line", ".", "flatten", ".", "join", "(", "';'", ")", "end"], "docstring": "Creates the sum_row when the file has been completely processed", "docstring_tokens": ["Creates", "the", "sum_row", "when", "the", "file", "has", "been", "completely", "processed"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/table.rb#L242-L248", "partition": "valid"} {"repo": "rsanders/translated_collection", "path": "lib/translated_collection/wrapper.rb", "func_name": "TranslatedCollection.Wrapper._rewrap_array", "original_string": "def _rewrap_array(result)\n if @wrap_results\n newcoll = @collection.class.new(result)\n self.class.new(newcoll, @wrapfunc_in, @wrapfunc_out)\n else\n @collection.class.new(result.map(&@wrapfunc_out))\n end\n end", "language": "ruby", "code": "def _rewrap_array(result)\n if @wrap_results\n newcoll = @collection.class.new(result)\n self.class.new(newcoll, @wrapfunc_in, @wrapfunc_out)\n else\n @collection.class.new(result.map(&@wrapfunc_out))\n end\n end", "code_tokens": ["def", "_rewrap_array", "(", "result", ")", "if", "@wrap_results", "newcoll", "=", "@collection", ".", "class", ".", "new", "(", "result", ")", "self", ".", "class", ".", "new", "(", "newcoll", ",", "@wrapfunc_in", ",", "@wrapfunc_out", ")", "else", "@collection", ".", "class", ".", "new", "(", "result", ".", "map", "(", "@wrapfunc_out", ")", ")", "end", "end"], "docstring": "Used to wrap results from various Enumerable methods that are defined\n to return an array", "docstring_tokens": ["Used", "to", "wrap", "results", "from", "various", "Enumerable", "methods", "that", "are", "defined", "to", "return", "an", "array"], "sha": "048353e9cb71f40679693a0e76f07698fa3d28ff", "url": "https://github.com/rsanders/translated_collection/blob/048353e9cb71f40679693a0e76f07698fa3d28ff/lib/translated_collection/wrapper.rb#L152-L159", "partition": "valid"} {"repo": "stationkeeping/deep_end", "path": "lib/deep_end.rb", "func_name": "DeepEnd.Graph.add_dependency", "original_string": "def add_dependency(key, dependencies = [])\n\n raise SelfDependencyError, \"An object's dependencies cannot contain itself\" if dependencies.include? key\n\n node = node_for_key_or_new key\n dependencies.each do |dependency|\n node.addEdge(node_for_key_or_new(dependency))\n end\n resolve_dependencies\n end", "language": "ruby", "code": "def add_dependency(key, dependencies = [])\n\n raise SelfDependencyError, \"An object's dependencies cannot contain itself\" if dependencies.include? key\n\n node = node_for_key_or_new key\n dependencies.each do |dependency|\n node.addEdge(node_for_key_or_new(dependency))\n end\n resolve_dependencies\n end", "code_tokens": ["def", "add_dependency", "(", "key", ",", "dependencies", "=", "[", "]", ")", "raise", "SelfDependencyError", ",", "\"An object's dependencies cannot contain itself\"", "if", "dependencies", ".", "include?", "key", "node", "=", "node_for_key_or_new", "key", "dependencies", ".", "each", "do", "|", "dependency", "|", "node", ".", "addEdge", "(", "node_for_key_or_new", "(", "dependency", ")", ")", "end", "resolve_dependencies", "end"], "docstring": "Add a new node, causing dependencies to be re-evaluated", "docstring_tokens": ["Add", "a", "new", "node", "causing", "dependencies", "to", "be", "re", "-", "evaluated"], "sha": "1556c3ec4a0486bb15dc134777ba5fe17db1b253", "url": "https://github.com/stationkeeping/deep_end/blob/1556c3ec4a0486bb15dc134777ba5fe17db1b253/lib/deep_end.rb#L40-L49", "partition": "valid"} {"repo": "stationkeeping/deep_end", "path": "lib/deep_end.rb", "func_name": "DeepEnd.Graph.resolve_dependency", "original_string": "def resolve_dependency(node)\n node.seen = true\n @seen_this_pass << node\n\n node.edges.each do |edge|\n unless @resolved.include? edge\n unless @seen_this_pass.include? edge\n unless edge.seen?\n resolve_dependency edge\n end\n else\n raise CircularDependencyError, \"Circular reference detected: #{node.key.to_s} - #{edge.key.to_s}\"\n end\n end\n end\n @resolved << node\n end", "language": "ruby", "code": "def resolve_dependency(node)\n node.seen = true\n @seen_this_pass << node\n\n node.edges.each do |edge|\n unless @resolved.include? edge\n unless @seen_this_pass.include? edge\n unless edge.seen?\n resolve_dependency edge\n end\n else\n raise CircularDependencyError, \"Circular reference detected: #{node.key.to_s} - #{edge.key.to_s}\"\n end\n end\n end\n @resolved << node\n end", "code_tokens": ["def", "resolve_dependency", "(", "node", ")", "node", ".", "seen", "=", "true", "@seen_this_pass", "<<", "node", "node", ".", "edges", ".", "each", "do", "|", "edge", "|", "unless", "@resolved", ".", "include?", "edge", "unless", "@seen_this_pass", ".", "include?", "edge", "unless", "edge", ".", "seen?", "resolve_dependency", "edge", "end", "else", "raise", "CircularDependencyError", ",", "\"Circular reference detected: #{node.key.to_s} - #{edge.key.to_s}\"", "end", "end", "end", "@resolved", "<<", "node", "end"], "docstring": "Recurse through node edges", "docstring_tokens": ["Recurse", "through", "node", "edges"], "sha": "1556c3ec4a0486bb15dc134777ba5fe17db1b253", "url": "https://github.com/stationkeeping/deep_end/blob/1556c3ec4a0486bb15dc134777ba5fe17db1b253/lib/deep_end.rb#L71-L87", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/room_directory.rb", "func_name": "Turntabler.RoomDirectory.with_friends", "original_string": "def with_friends\n data = api('room.directory_graph')\n data['rooms'].map do |(attrs, friends)|\n Room.new(client, attrs.merge(:friends => friends))\n end\n end", "language": "ruby", "code": "def with_friends\n data = api('room.directory_graph')\n data['rooms'].map do |(attrs, friends)|\n Room.new(client, attrs.merge(:friends => friends))\n end\n end", "code_tokens": ["def", "with_friends", "data", "=", "api", "(", "'room.directory_graph'", ")", "data", "[", "'rooms'", "]", ".", "map", "do", "|", "(", "attrs", ",", "friends", ")", "|", "Room", ".", "new", "(", "client", ",", "attrs", ".", "merge", "(", ":friends", "=>", "friends", ")", ")", "end", "end"], "docstring": "Gets the rooms where the current user's friends are currently listening.\n\n @return [Array]\n @raise [Turntabler::Error] if the command fails\n @example\n rooms.with_friends # => [#, ...]", "docstring_tokens": ["Gets", "the", "rooms", "where", "the", "current", "user", "s", "friends", "are", "currently", "listening", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/room_directory.rb#L99-L104", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/room_directory.rb", "func_name": "Turntabler.RoomDirectory.find", "original_string": "def find(query, options = {})\n assert_valid_keys(options, :limit, :skip)\n options = {:limit => 20, :skip => 0}.merge(options)\n\n data = api('room.search', :query => query, :skip => options[:skip])\n data['rooms'].map {|(attrs, *)| Room.new(client, attrs)}\n end", "language": "ruby", "code": "def find(query, options = {})\n assert_valid_keys(options, :limit, :skip)\n options = {:limit => 20, :skip => 0}.merge(options)\n\n data = api('room.search', :query => query, :skip => options[:skip])\n data['rooms'].map {|(attrs, *)| Room.new(client, attrs)}\n end", "code_tokens": ["def", "find", "(", "query", ",", "options", "=", "{", "}", ")", "assert_valid_keys", "(", "options", ",", ":limit", ",", ":skip", ")", "options", "=", "{", ":limit", "=>", "20", ",", ":skip", "=>", "0", "}", ".", "merge", "(", "options", ")", "data", "=", "api", "(", "'room.search'", ",", ":query", "=>", "query", ",", ":skip", "=>", "options", "[", ":skip", "]", ")", "data", "[", "'rooms'", "]", ".", "map", "{", "|", "(", "attrs", ",", "*", ")", "|", "Room", ".", "new", "(", "client", ",", "attrs", ")", "}", "end"], "docstring": "Finds rooms that match the given query string.\n\n @param [String] query The query string to search with\n @param [Hash] options The search options\n @option options [Fixnum] :limit (20) The maximum number of rooms to query for\n @option options [Fixnum] :skip (0) The number of rooms to skip when loading the results\n @return [Array]\n @raise [ArgumentError] if an invalid option is specified\n @raise [Turntabler::Error] if the command fails\n rooms.find('indie') # => [#, ...]", "docstring_tokens": ["Finds", "rooms", "that", "match", "the", "given", "query", "string", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/room_directory.rb#L116-L122", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/playlist.rb", "func_name": "Turntabler.Playlist.load", "original_string": "def load(options = {})\n assert_valid_keys(options, :minimal)\n options = {:minimal => false}.merge(options)\n\n data = api('playlist.all', options)\n self.attributes = data\n super()\n end", "language": "ruby", "code": "def load(options = {})\n assert_valid_keys(options, :minimal)\n options = {:minimal => false}.merge(options)\n\n data = api('playlist.all', options)\n self.attributes = data\n super()\n end", "code_tokens": ["def", "load", "(", "options", "=", "{", "}", ")", "assert_valid_keys", "(", "options", ",", ":minimal", ")", "options", "=", "{", ":minimal", "=>", "false", "}", ".", "merge", "(", "options", ")", "data", "=", "api", "(", "'playlist.all'", ",", "options", ")", "self", ".", "attributes", "=", "data", "super", "(", ")", "end"], "docstring": "Loads the attributes for this playlist. Attributes will automatically load\n when accessed, but this allows data to be forcefully loaded upfront.\n\n @param [Hash] options The configuration options\n @option options [Boolean] minimal (false) Whether to only include the identifiers for songs and not the entire metadata\n @return [true]\n @raise [Turntabler::Error] if the command fails\n @example\n playlist.load # => true\n playlist.songs # => [#, ...]", "docstring_tokens": ["Loads", "the", "attributes", "for", "this", "playlist", ".", "Attributes", "will", "automatically", "load", "when", "accessed", "but", "this", "allows", "data", "to", "be", "forcefully", "loaded", "upfront", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/playlist.rb#L35-L42", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/playlist.rb", "func_name": "Turntabler.Playlist.update", "original_string": "def update(attributes = {})\n assert_valid_keys(attributes, :id)\n\n # Update id\n id = attributes.delete(:id)\n update_id(id) if id\n\n true\n end", "language": "ruby", "code": "def update(attributes = {})\n assert_valid_keys(attributes, :id)\n\n # Update id\n id = attributes.delete(:id)\n update_id(id) if id\n\n true\n end", "code_tokens": ["def", "update", "(", "attributes", "=", "{", "}", ")", "assert_valid_keys", "(", "attributes", ",", ":id", ")", "# Update id", "id", "=", "attributes", ".", "delete", "(", ":id", ")", "update_id", "(", "id", ")", "if", "id", "true", "end"], "docstring": "Updates this playlist's information.\n\n @param [Hash] attributes The attributes to update\n @option attributes [String] :id\n @return [true]\n @raise [ArgumentError] if an invalid attribute or value is specified\n @raise [Turntabler::Error] if the command fails\n @example\n playlist.update(:id => \"rock\") # => true", "docstring_tokens": ["Updates", "this", "playlist", "s", "information", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/playlist.rb#L53-L61", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/playlist.rb", "func_name": "Turntabler.Playlist.active", "original_string": "def active\n @active = client.user.playlists.all.any? {|playlist| playlist == self && playlist.active?} if @active.nil?\n @active\n end", "language": "ruby", "code": "def active\n @active = client.user.playlists.all.any? {|playlist| playlist == self && playlist.active?} if @active.nil?\n @active\n end", "code_tokens": ["def", "active", "@active", "=", "client", ".", "user", ".", "playlists", ".", "all", ".", "any?", "{", "|", "playlist", "|", "playlist", "==", "self", "&&", "playlist", ".", "active?", "}", "if", "@active", ".", "nil?", "@active", "end"], "docstring": "Whether this is the currently active playlist\n\n @return [Boolean]\n @raise [Turntabler::Error] if the command fails\n @example\n playlist.active # => true", "docstring_tokens": ["Whether", "this", "is", "the", "currently", "active", "playlist"], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/playlist.rb#L69-L72", "partition": "valid"} {"repo": "nepalez/attributes_dsl", "path": "lib/attributes_dsl/attributes.rb", "func_name": "AttributesDSL.Attributes.add", "original_string": "def add(name, options = {}, &coercer)\n name = name.to_sym\n value = Attribute.new(name, options, &coercer)\n clone_with do\n @attributes = attributes.merge(name => value)\n @transformer = nil\n end\n end", "language": "ruby", "code": "def add(name, options = {}, &coercer)\n name = name.to_sym\n value = Attribute.new(name, options, &coercer)\n clone_with do\n @attributes = attributes.merge(name => value)\n @transformer = nil\n end\n end", "code_tokens": ["def", "add", "(", "name", ",", "options", "=", "{", "}", ",", "&", "coercer", ")", "name", "=", "name", ".", "to_sym", "value", "=", "Attribute", ".", "new", "(", "name", ",", "options", ",", "coercer", ")", "clone_with", "do", "@attributes", "=", "attributes", ".", "merge", "(", "name", "=>", "value", ")", "@transformer", "=", "nil", "end", "end"], "docstring": "Initializes the attribute from given arguments\n and returns new immutable collection with the attribute\n\n @param (see Attribute#initialize)\n\n @return [AttributesDSL::Attributes]", "docstring_tokens": ["Initializes", "the", "attribute", "from", "given", "arguments", "and", "returns", "new", "immutable", "collection", "with", "the", "attribute"], "sha": "f9032561629240c251cd86bf61c9a86618a8fef5", "url": "https://github.com/nepalez/attributes_dsl/blob/f9032561629240c251cd86bf61c9a86618a8fef5/lib/attributes_dsl/attributes.rb#L30-L37", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/collection_protocol.rb", "func_name": "CaTissue.CollectionProtocol.add_specimens", "original_string": "def add_specimens(*args)\n hash = args.pop\n spcs = args\n # validate arguments\n unless Hash === hash then\n raise ArgumentError.new(\"Collection parameters are missing when adding specimens to protocol #{self}\")\n end\n # Make the default registration, if necessary.\n unless hash.has_key?(:registration) || hash.has_key?(:collection_protocol_registration) then\n # the participant\n pnt = hash.delete(:participant)\n unless pnt then\n raise ArgumentError.new(\"Registration or participant missing from collection parameters: #{hash.qp}\")\n end\n hash[:registration] = registration(pnt) || make_cpr(pnt)\n end\n # the new SCG\n scg = SpecimenCollectionGroup.new(hash)\n # set each Specimen SCG\n spcs.each { |spc| spc.specimen_collection_group = scg }\n scg\n end", "language": "ruby", "code": "def add_specimens(*args)\n hash = args.pop\n spcs = args\n # validate arguments\n unless Hash === hash then\n raise ArgumentError.new(\"Collection parameters are missing when adding specimens to protocol #{self}\")\n end\n # Make the default registration, if necessary.\n unless hash.has_key?(:registration) || hash.has_key?(:collection_protocol_registration) then\n # the participant\n pnt = hash.delete(:participant)\n unless pnt then\n raise ArgumentError.new(\"Registration or participant missing from collection parameters: #{hash.qp}\")\n end\n hash[:registration] = registration(pnt) || make_cpr(pnt)\n end\n # the new SCG\n scg = SpecimenCollectionGroup.new(hash)\n # set each Specimen SCG\n spcs.each { |spc| spc.specimen_collection_group = scg }\n scg\n end", "code_tokens": ["def", "add_specimens", "(", "*", "args", ")", "hash", "=", "args", ".", "pop", "spcs", "=", "args", "# validate arguments", "unless", "Hash", "===", "hash", "then", "raise", "ArgumentError", ".", "new", "(", "\"Collection parameters are missing when adding specimens to protocol #{self}\"", ")", "end", "# Make the default registration, if necessary.", "unless", "hash", ".", "has_key?", "(", ":registration", ")", "||", "hash", ".", "has_key?", "(", ":collection_protocol_registration", ")", "then", "# the participant", "pnt", "=", "hash", ".", "delete", "(", ":participant", ")", "unless", "pnt", "then", "raise", "ArgumentError", ".", "new", "(", "\"Registration or participant missing from collection parameters: #{hash.qp}\"", ")", "end", "hash", "[", ":registration", "]", "=", "registration", "(", "pnt", ")", "||", "make_cpr", "(", "pnt", ")", "end", "# the new SCG", "scg", "=", "SpecimenCollectionGroup", ".", "new", "(", "hash", ")", "# set each Specimen SCG", "spcs", ".", "each", "{", "|", "spc", "|", "spc", ".", "specimen_collection_group", "=", "scg", "}", "scg", "end"], "docstring": "Adds specimens to this protocol. The argumentes includes the\n specimens to add followed by a Hash with parameters and options.\n If the SCG registration parameter is not set, then a default registration\n is created which registers the given participant to this protocol.\n\n @example\n protocol.add_specimens(tumor, normal, :participant => pnt, :collector => srg)\n #=> a new SCG for the given participant with a matched pair of samples\n #=> collected by the given surgeon.\n\n @param [(, {Symbol => Object})] args the specimens to add followed\n by the parameters and options hash\n @option args [CaTissue::Participant] :participant the person from whom the\n specimen is collected\n @return [CaTissue::SpecimenCollectionGroup] the new SCG\n @raise [ArgumentError] if the options do not include either a participant or a registration", "docstring_tokens": ["Adds", "specimens", "to", "this", "protocol", ".", "The", "argumentes", "includes", "the", "specimens", "to", "add", "followed", "by", "a", "Hash", "with", "parameters", "and", "options", ".", "If", "the", "SCG", "registration", "parameter", "is", "not", "set", "then", "a", "default", "registration", "is", "created", "which", "registers", "the", "given", "participant", "to", "this", "protocol", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/collection_protocol.rb#L84-L105", "partition": "valid"} {"repo": "danijoo/Sightstone", "path": "lib/sightstone/modules/summoner_module.rb", "func_name": "Sightstone.SummonerModule.summoner", "original_string": "def summoner(name_or_id, optional={})\n region = optional[:region] || @sightstone.region\n uri = if name_or_id.is_a? Integer\n \"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{name_or_id}\"\n else\n \"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/by-name/#{URI::encode(name_or_id)}\"\n end\n \n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n s = Summoner.new(data.values[0])\n if block_given?\n yield s\n else\n return s\n end\n }\n end", "language": "ruby", "code": "def summoner(name_or_id, optional={})\n region = optional[:region] || @sightstone.region\n uri = if name_or_id.is_a? Integer\n \"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{name_or_id}\"\n else\n \"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/by-name/#{URI::encode(name_or_id)}\"\n end\n \n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n s = Summoner.new(data.values[0])\n if block_given?\n yield s\n else\n return s\n end\n }\n end", "code_tokens": ["def", "summoner", "(", "name_or_id", ",", "optional", "=", "{", "}", ")", "region", "=", "optional", "[", ":region", "]", "||", "@sightstone", ".", "region", "uri", "=", "if", "name_or_id", ".", "is_a?", "Integer", "\"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{name_or_id}\"", "else", "\"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/by-name/#{URI::encode(name_or_id)}\"", "end", "response", "=", "_get_api_response", "(", "uri", ")", "_parse_response", "(", "response", ")", "{", "|", "resp", "|", "data", "=", "JSON", ".", "parse", "(", "resp", ")", "s", "=", "Summoner", ".", "new", "(", "data", ".", "values", "[", "0", "]", ")", "if", "block_given?", "yield", "s", "else", "return", "s", "end", "}", "end"], "docstring": "returns a summoner object\n @param name_or_id [Integer, String] name or id of the summoner\n @param optional [Hash] optional arguments: :region => replaces default region\n @ return [Summoner] summoner", "docstring_tokens": ["returns", "a", "summoner", "object"], "sha": "4c6709916ce7552f622de1a120c021e067601b4d", "url": "https://github.com/danijoo/Sightstone/blob/4c6709916ce7552f622de1a120c021e067601b4d/lib/sightstone/modules/summoner_module.rb#L19-L37", "partition": "valid"} {"repo": "danijoo/Sightstone", "path": "lib/sightstone/modules/summoner_module.rb", "func_name": "Sightstone.SummonerModule.names", "original_string": "def names(ids, optional={})\n region = optional[:region] || @sightstone.region\n ids = ids.join(',')\n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{ids}/name\"\n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n\n names_hash = Hash.new\n data.each do |id, name|\n names_hash[id.to_i] = name\n end\n if block_given?\n yield names_hash\n else\n return names_hash\n end\n }\n end", "language": "ruby", "code": "def names(ids, optional={})\n region = optional[:region] || @sightstone.region\n ids = ids.join(',')\n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{ids}/name\"\n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n\n names_hash = Hash.new\n data.each do |id, name|\n names_hash[id.to_i] = name\n end\n if block_given?\n yield names_hash\n else\n return names_hash\n end\n }\n end", "code_tokens": ["def", "names", "(", "ids", ",", "optional", "=", "{", "}", ")", "region", "=", "optional", "[", ":region", "]", "||", "@sightstone", ".", "region", "ids", "=", "ids", ".", "join", "(", "','", ")", "uri", "=", "\"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{ids}/name\"", "response", "=", "_get_api_response", "(", "uri", ")", "_parse_response", "(", "response", ")", "{", "|", "resp", "|", "data", "=", "JSON", ".", "parse", "(", "resp", ")", "names_hash", "=", "Hash", ".", "new", "data", ".", "each", "do", "|", "id", ",", "name", "|", "names_hash", "[", "id", ".", "to_i", "]", "=", "name", "end", "if", "block_given?", "yield", "names_hash", "else", "return", "names_hash", "end", "}", "end"], "docstring": "returns the names for the ids\n @param ids [Array] ids\n @param optional [Hash] optional arguments: :region => replaces default region\n @return [Hash] a hash matching each id to the summoners name", "docstring_tokens": ["returns", "the", "names", "for", "the", "ids"], "sha": "4c6709916ce7552f622de1a120c021e067601b4d", "url": "https://github.com/danijoo/Sightstone/blob/4c6709916ce7552f622de1a120c021e067601b4d/lib/sightstone/modules/summoner_module.rb#L75-L93", "partition": "valid"} {"repo": "danijoo/Sightstone", "path": "lib/sightstone/modules/summoner_module.rb", "func_name": "Sightstone.SummonerModule.runebook", "original_string": "def runebook(summoner, optional={})\n region = optional[:region] || @sightstone.region\n id = if summoner.is_a? Summoner\n summoner.id\n else\n summoner\n end\n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{id}/runes\"\n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n book = RuneBook.new(data.values[0])\n if block_given?\n yield book\n else\n return book\n end\n }\n end", "language": "ruby", "code": "def runebook(summoner, optional={})\n region = optional[:region] || @sightstone.region\n id = if summoner.is_a? Summoner\n summoner.id\n else\n summoner\n end\n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{id}/runes\"\n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n book = RuneBook.new(data.values[0])\n if block_given?\n yield book\n else\n return book\n end\n }\n end", "code_tokens": ["def", "runebook", "(", "summoner", ",", "optional", "=", "{", "}", ")", "region", "=", "optional", "[", ":region", "]", "||", "@sightstone", ".", "region", "id", "=", "if", "summoner", ".", "is_a?", "Summoner", "summoner", ".", "id", "else", "summoner", "end", "uri", "=", "\"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{id}/runes\"", "response", "=", "_get_api_response", "(", "uri", ")", "_parse_response", "(", "response", ")", "{", "|", "resp", "|", "data", "=", "JSON", ".", "parse", "(", "resp", ")", "book", "=", "RuneBook", ".", "new", "(", "data", ".", "values", "[", "0", "]", ")", "if", "block_given?", "yield", "book", "else", "return", "book", "end", "}", "end"], "docstring": "returns the runebook of a summoner\n @param summoner [Summoner, id] summoner object or id of a summoner\n @param optional [Hash] optional arguments: :region => replaces default region\n @return [Runebook] runebook of the summoner", "docstring_tokens": ["returns", "the", "runebook", "of", "a", "summoner"], "sha": "4c6709916ce7552f622de1a120c021e067601b4d", "url": "https://github.com/danijoo/Sightstone/blob/4c6709916ce7552f622de1a120c021e067601b4d/lib/sightstone/modules/summoner_module.rb#L99-L117", "partition": "valid"} {"repo": "danijoo/Sightstone", "path": "lib/sightstone/modules/summoner_module.rb", "func_name": "Sightstone.SummonerModule.runebooks", "original_string": "def runebooks(summoners, optional={})\n return {} if summoners.empty?\n\n region = optional[:region] || @sightstone.region\n ids = summoners.collect { |summoner|\n if summoner.is_a? Summoner\n summoner.id\n else\n summoner\n end\n }\n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{ids.join(',')}/runes\"\n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n books = {}\n data.each do |key, raw_book|\n books[key] = RuneBook.new(raw_book)\n end\n if block_given?\n yield books\n else\n return books\n end\n }\n end", "language": "ruby", "code": "def runebooks(summoners, optional={})\n return {} if summoners.empty?\n\n region = optional[:region] || @sightstone.region\n ids = summoners.collect { |summoner|\n if summoner.is_a? Summoner\n summoner.id\n else\n summoner\n end\n }\n uri = \"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{ids.join(',')}/runes\"\n response = _get_api_response(uri)\n _parse_response(response) { |resp|\n data = JSON.parse(resp)\n books = {}\n data.each do |key, raw_book|\n books[key] = RuneBook.new(raw_book)\n end\n if block_given?\n yield books\n else\n return books\n end\n }\n end", "code_tokens": ["def", "runebooks", "(", "summoners", ",", "optional", "=", "{", "}", ")", "return", "{", "}", "if", "summoners", ".", "empty?", "region", "=", "optional", "[", ":region", "]", "||", "@sightstone", ".", "region", "ids", "=", "summoners", ".", "collect", "{", "|", "summoner", "|", "if", "summoner", ".", "is_a?", "Summoner", "summoner", ".", "id", "else", "summoner", "end", "}", "uri", "=", "\"https://prod.api.pvp.net/api/lol/#{region}/v1.3/summoner/#{ids.join(',')}/runes\"", "response", "=", "_get_api_response", "(", "uri", ")", "_parse_response", "(", "response", ")", "{", "|", "resp", "|", "data", "=", "JSON", ".", "parse", "(", "resp", ")", "books", "=", "{", "}", "data", ".", "each", "do", "|", "key", ",", "raw_book", "|", "books", "[", "key", "]", "=", "RuneBook", ".", "new", "(", "raw_book", ")", "end", "if", "block_given?", "yield", "books", "else", "return", "books", "end", "}", "end"], "docstring": "returns the runebook for multiple summoners\n @param summoners [Array<(Summoner, Integer)>] list of summoner objects or ids of summoners\n @param optional [Hash] optional arguments: :region => replaces default region\n @return [Hash] A hash mapping runebooks to the ids of summoners", "docstring_tokens": ["returns", "the", "runebook", "for", "multiple", "summoners"], "sha": "4c6709916ce7552f622de1a120c021e067601b4d", "url": "https://github.com/danijoo/Sightstone/blob/4c6709916ce7552f622de1a120c021e067601b4d/lib/sightstone/modules/summoner_module.rb#L123-L148", "partition": "valid"} {"repo": "Le0Michine/ruby-zipper", "path": "lib/zipper.rb", "func_name": "Zipper.ZipFileGenerator.write", "original_string": "def write\n buffer = create_zip(@entries, @ignore_entries)\n\n puts \"\\nwrite file #{@output_file}\"\n File.open(@output_file, \"wb\") {|f| f.write buffer.string }\n end", "language": "ruby", "code": "def write\n buffer = create_zip(@entries, @ignore_entries)\n\n puts \"\\nwrite file #{@output_file}\"\n File.open(@output_file, \"wb\") {|f| f.write buffer.string }\n end", "code_tokens": ["def", "write", "buffer", "=", "create_zip", "(", "@entries", ",", "@ignore_entries", ")", "puts", "\"\\nwrite file #{@output_file}\"", "File", ".", "open", "(", "@output_file", ",", "\"wb\"", ")", "{", "|", "f", "|", "f", ".", "write", "buffer", ".", "string", "}", "end"], "docstring": "Initialize with the json config.\n Zip the input entries.", "docstring_tokens": ["Initialize", "with", "the", "json", "config", ".", "Zip", "the", "input", "entries", "."], "sha": "97439228056905adb84cfff9d3bfb6835891c988", "url": "https://github.com/Le0Michine/ruby-zipper/blob/97439228056905adb84cfff9d3bfb6835891c988/lib/zipper.rb#L19-L24", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/helpers/collectible.rb", "func_name": "CaTissue.Collectible.collect", "original_string": "def collect(opts)\n raise Jinx::ValidationError.new(\"#{self} is already collected\") if received?\n specimen_event_parameters.merge!(extract_event_parameters(opts))\n end", "language": "ruby", "code": "def collect(opts)\n raise Jinx::ValidationError.new(\"#{self} is already collected\") if received?\n specimen_event_parameters.merge!(extract_event_parameters(opts))\n end", "code_tokens": ["def", "collect", "(", "opts", ")", "raise", "Jinx", "::", "ValidationError", ".", "new", "(", "\"#{self} is already collected\"", ")", "if", "received?", "specimen_event_parameters", ".", "merge!", "(", "extract_event_parameters", "(", "opts", ")", ")", "end"], "docstring": "Collects and receives this Collectible with the given options.\n\n @param (see #extract_event_parameters)\n @option opts (see #extract_event_parameters)\n @raise [Jinx::ValidationError] if this Collectible has already been received", "docstring_tokens": ["Collects", "and", "receives", "this", "Collectible", "with", "the", "given", "options", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/helpers/collectible.rb#L36-L39", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/filter.rb", "func_name": "Sycsvpro.Filter.method_missing", "original_string": "def method_missing(id, *args, &block)\n boolean_row_regex = %r{\n BEGIN(\\(*[nsd]\\d+[]{1,2}\n (?:[A-Z][A-Za-z]*\\.new\\(.*?\\)|\\d+|['\"].*?['\"])\n (?:\\)*(?:&&|\\|\\||$)\n \\(*[nsd]\\d+[]{1,2}\n (?:[A-Z][A-Za-z]*\\.new\\(.*?\\)|\\d+|['\"].*?['\"])\\)*)*)END\n }xi\n\n return boolean_row($1, args, block) if id =~ boolean_row_regex\n return equal($1, args, block) if id =~ /^(\\d+)$/\n return equal_type($1, $2, args, block) if id =~ /^(s|n|d):(\\d+)$/\n return range($1, $2, args, block) if id =~ /^(\\d+)-(\\d+)$/\n return range_type($1, $2, $3, args, block) if id =~ /^(s|n|d):(\\d+)-(\\d+)$/\n return regex($1, args, block) if id =~ /^\\/(.*)\\/$/\n return col_regex($1, $2, args, block) if id =~ /^(\\d+):\\/(.*)\\/$/\n return date($1, $2, $3, args, block) if id =~ /^(\\d+):(<|=|>)(\\d+.\\d+.\\d+)$/\n return date_range($1, $2, $3, args, block) if id =~ /^(\\d+):(\\d+.\\d+.\\d+.)-(\\d+.\\d+.\\d+)$/\n return number($1, $2, $3, args, block) if id =~ /^(\\d+):(<|=|>)(\\d+)$/\n return number_range($1, $2, $3, args, block) if id =~ /^(\\d):(\\d+)-(\\d+)$/\n\n super\n end", "language": "ruby", "code": "def method_missing(id, *args, &block)\n boolean_row_regex = %r{\n BEGIN(\\(*[nsd]\\d+[]{1,2}\n (?:[A-Z][A-Za-z]*\\.new\\(.*?\\)|\\d+|['\"].*?['\"])\n (?:\\)*(?:&&|\\|\\||$)\n \\(*[nsd]\\d+[]{1,2}\n (?:[A-Z][A-Za-z]*\\.new\\(.*?\\)|\\d+|['\"].*?['\"])\\)*)*)END\n }xi\n\n return boolean_row($1, args, block) if id =~ boolean_row_regex\n return equal($1, args, block) if id =~ /^(\\d+)$/\n return equal_type($1, $2, args, block) if id =~ /^(s|n|d):(\\d+)$/\n return range($1, $2, args, block) if id =~ /^(\\d+)-(\\d+)$/\n return range_type($1, $2, $3, args, block) if id =~ /^(s|n|d):(\\d+)-(\\d+)$/\n return regex($1, args, block) if id =~ /^\\/(.*)\\/$/\n return col_regex($1, $2, args, block) if id =~ /^(\\d+):\\/(.*)\\/$/\n return date($1, $2, $3, args, block) if id =~ /^(\\d+):(<|=|>)(\\d+.\\d+.\\d+)$/\n return date_range($1, $2, $3, args, block) if id =~ /^(\\d+):(\\d+.\\d+.\\d+.)-(\\d+.\\d+.\\d+)$/\n return number($1, $2, $3, args, block) if id =~ /^(\\d+):(<|=|>)(\\d+)$/\n return number_range($1, $2, $3, args, block) if id =~ /^(\\d):(\\d+)-(\\d+)$/\n\n super\n end", "code_tokens": ["def", "method_missing", "(", "id", ",", "*", "args", ",", "&", "block", ")", "boolean_row_regex", "=", "%r{", "\\(", "\\d", "\\.", "\\(", "\\)", "\\d", "\\)", "\\|", "\\|", "\\(", "\\d", "\\.", "\\(", "\\)", "\\d", "\\)", "}xi", "return", "boolean_row", "(", "$1", ",", "args", ",", "block", ")", "if", "id", "=~", "boolean_row_regex", "return", "equal", "(", "$1", ",", "args", ",", "block", ")", "if", "id", "=~", "/", "\\d", "/", "return", "equal_type", "(", "$1", ",", "$2", ",", "args", ",", "block", ")", "if", "id", "=~", "/", "\\d", "/", "return", "range", "(", "$1", ",", "$2", ",", "args", ",", "block", ")", "if", "id", "=~", "/", "\\d", "\\d", "/", "return", "range_type", "(", "$1", ",", "$2", ",", "$3", ",", "args", ",", "block", ")", "if", "id", "=~", "/", "\\d", "\\d", "/", "return", "regex", "(", "$1", ",", "args", ",", "block", ")", "if", "id", "=~", "/", "\\/", "\\/", "/", "return", "col_regex", "(", "$1", ",", "$2", ",", "args", ",", "block", ")", "if", "id", "=~", "/", "\\d", "\\/", "\\/", "/", "return", "date", "(", "$1", ",", "$2", ",", "$3", ",", "args", ",", "block", ")", "if", "id", "=~", "/", "\\d", "\\d", "\\d", "\\d", "/", "return", "date_range", "(", "$1", ",", "$2", ",", "$3", ",", "args", ",", "block", ")", "if", "id", "=~", "/", "\\d", "\\d", "\\d", "\\d", "\\d", "\\d", "\\d", "/", "return", "number", "(", "$1", ",", "$2", ",", "$3", ",", "args", ",", "block", ")", "if", "id", "=~", "/", "\\d", "\\d", "/", "return", "number_range", "(", "$1", ",", "$2", ",", "$3", ",", "args", ",", "block", ")", "if", "id", "=~", "/", "\\d", "\\d", "\\d", "/", "super", "end"], "docstring": "Creates a new filter\n Creates the filters based on the given patterns", "docstring_tokens": ["Creates", "a", "new", "filter", "Creates", "the", "filters", "based", "on", "the", "given", "patterns"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/filter.rb#L35-L57", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/filter.rb", "func_name": "Sycsvpro.Filter.match_boolean_filter?", "original_string": "def match_boolean_filter?(values=[])\n return false if boolean_filter.empty? or values.empty?\n expression = boolean_filter\n columns = expression.scan(/(([nsd])(\\d+))([]{1,2})(.*?)(?:[\\|&]{2}|$)/)\n columns.each do |c|\n value = case c[1]\n when 'n'\n values[c[2].to_i].empty? ? '0' : values[c[2].to_i]\n when 's'\n \"\\\"#{values[c[2].to_i]}\\\"\"\n when 'd'\n begin\n Date.strptime(values[c[2].to_i], date_format)\n rescue Exception => e\n case c[3]\n when '<', '<=', '=='\n \"#{c[4]}+1\"\n when '>', '>='\n '0'\n when '!='\n c[4]\n end\n else\n \"Date.strptime('#{values[c[2].to_i]}', '#{date_format}')\"\n end \n end\n expression = expression.gsub(c[0], value)\n end\n eval(expression)\n end", "language": "ruby", "code": "def match_boolean_filter?(values=[])\n return false if boolean_filter.empty? or values.empty?\n expression = boolean_filter\n columns = expression.scan(/(([nsd])(\\d+))([]{1,2})(.*?)(?:[\\|&]{2}|$)/)\n columns.each do |c|\n value = case c[1]\n when 'n'\n values[c[2].to_i].empty? ? '0' : values[c[2].to_i]\n when 's'\n \"\\\"#{values[c[2].to_i]}\\\"\"\n when 'd'\n begin\n Date.strptime(values[c[2].to_i], date_format)\n rescue Exception => e\n case c[3]\n when '<', '<=', '=='\n \"#{c[4]}+1\"\n when '>', '>='\n '0'\n when '!='\n c[4]\n end\n else\n \"Date.strptime('#{values[c[2].to_i]}', '#{date_format}')\"\n end \n end\n expression = expression.gsub(c[0], value)\n end\n eval(expression)\n end", "code_tokens": ["def", "match_boolean_filter?", "(", "values", "=", "[", "]", ")", "return", "false", "if", "boolean_filter", ".", "empty?", "or", "values", ".", "empty?", "expression", "=", "boolean_filter", "columns", "=", "expression", ".", "scan", "(", "/", "\\d", "\\|", "/", ")", "columns", ".", "each", "do", "|", "c", "|", "value", "=", "case", "c", "[", "1", "]", "when", "'n'", "values", "[", "c", "[", "2", "]", ".", "to_i", "]", ".", "empty?", "?", "'0'", ":", "values", "[", "c", "[", "2", "]", ".", "to_i", "]", "when", "'s'", "\"\\\"#{values[c[2].to_i]}\\\"\"", "when", "'d'", "begin", "Date", ".", "strptime", "(", "values", "[", "c", "[", "2", "]", ".", "to_i", "]", ",", "date_format", ")", "rescue", "Exception", "=>", "e", "case", "c", "[", "3", "]", "when", "'<'", ",", "'<='", ",", "'=='", "\"#{c[4]}+1\"", "when", "'>'", ",", "'>='", "'0'", "when", "'!='", "c", "[", "4", "]", "end", "else", "\"Date.strptime('#{values[c[2].to_i]}', '#{date_format}')\"", "end", "end", "expression", "=", "expression", ".", "gsub", "(", "c", "[", "0", "]", ",", "value", ")", "end", "eval", "(", "expression", ")", "end"], "docstring": "Checks whether the values match the boolean filter", "docstring_tokens": ["Checks", "whether", "the", "values", "match", "the", "boolean", "filter"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/filter.rb#L65-L94", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/filter.rb", "func_name": "Sycsvpro.Filter.pivot_each_column", "original_string": "def pivot_each_column(values=[])\n pivot.each do |column, parameters|\n value = values[parameters[:col].to_i]\n value = value.strip.gsub(/^\"|\"$/, \"\") unless value.nil?\n match = false\n begin\n match = eval(parameters[:operation].gsub('[value]', value))\n rescue Exception => e\n\n end\n yield column, match\n end\n end", "language": "ruby", "code": "def pivot_each_column(values=[])\n pivot.each do |column, parameters|\n value = values[parameters[:col].to_i]\n value = value.strip.gsub(/^\"|\"$/, \"\") unless value.nil?\n match = false\n begin\n match = eval(parameters[:operation].gsub('[value]', value))\n rescue Exception => e\n\n end\n yield column, match\n end\n end", "code_tokens": ["def", "pivot_each_column", "(", "values", "=", "[", "]", ")", "pivot", ".", "each", "do", "|", "column", ",", "parameters", "|", "value", "=", "values", "[", "parameters", "[", ":col", "]", ".", "to_i", "]", "value", "=", "value", ".", "strip", ".", "gsub", "(", "/", "/", ",", "\"\"", ")", "unless", "value", ".", "nil?", "match", "=", "false", "begin", "match", "=", "eval", "(", "parameters", "[", ":operation", "]", ".", "gsub", "(", "'[value]'", ",", "value", ")", ")", "rescue", "Exception", "=>", "e", "end", "yield", "column", ",", "match", "end", "end"], "docstring": "Yields the column value and whether the filter matches the column", "docstring_tokens": ["Yields", "the", "column", "value", "and", "whether", "the", "filter", "matches", "the", "column"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/filter.rb#L97-L109", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/filter.rb", "func_name": "Sycsvpro.Filter.create_filter", "original_string": "def create_filter(values)\n values.scan(/(?<=,|^)(BEGIN.*?END|\\/.*?\\/|.*?)(?=,|$)/i).flatten.each do |value|\n send(value)\n end unless values.nil?\n end", "language": "ruby", "code": "def create_filter(values)\n values.scan(/(?<=,|^)(BEGIN.*?END|\\/.*?\\/|.*?)(?=,|$)/i).flatten.each do |value|\n send(value)\n end unless values.nil?\n end", "code_tokens": ["def", "create_filter", "(", "values", ")", "values", ".", "scan", "(", "/", "\\/", "\\/", "/i", ")", ".", "flatten", ".", "each", "do", "|", "value", "|", "send", "(", "value", ")", "end", "unless", "values", ".", "nil?", "end"], "docstring": "Creates a filter based on the provided rows and columns select criteria", "docstring_tokens": ["Creates", "a", "filter", "based", "on", "the", "provided", "rows", "and", "columns", "select", "criteria"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/filter.rb#L119-L123", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/filter.rb", "func_name": "Sycsvpro.Filter.equal", "original_string": "def equal(value, args, block)\n filter << value.to_i unless filter.index(value.to_i) \n end", "language": "ruby", "code": "def equal(value, args, block)\n filter << value.to_i unless filter.index(value.to_i) \n end", "code_tokens": ["def", "equal", "(", "value", ",", "args", ",", "block", ")", "filter", "<<", "value", ".", "to_i", "unless", "filter", ".", "index", "(", "value", ".", "to_i", ")", "end"], "docstring": "Adds a single value to the filter", "docstring_tokens": ["Adds", "a", "single", "value", "to", "the", "filter"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/filter.rb#L126-L128", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/filter.rb", "func_name": "Sycsvpro.Filter.equal_type", "original_string": "def equal_type(type, value, args, block)\n filter_size_before = filter.size\n equal(value, args, block)\n types << type if filter_size_before < filter.size\n end", "language": "ruby", "code": "def equal_type(type, value, args, block)\n filter_size_before = filter.size\n equal(value, args, block)\n types << type if filter_size_before < filter.size\n end", "code_tokens": ["def", "equal_type", "(", "type", ",", "value", ",", "args", ",", "block", ")", "filter_size_before", "=", "filter", ".", "size", "equal", "(", "value", ",", "args", ",", "block", ")", "types", "<<", "type", "if", "filter_size_before", "<", "filter", ".", "size", "end"], "docstring": "Adds a single value and an associated type to the filter", "docstring_tokens": ["Adds", "a", "single", "value", "and", "an", "associated", "type", "to", "the", "filter"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/filter.rb#L131-L135", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/filter.rb", "func_name": "Sycsvpro.Filter.range", "original_string": "def range(start_value, end_value, args, block)\n filter << (start_value.to_i..end_value.to_i).to_a\n end", "language": "ruby", "code": "def range(start_value, end_value, args, block)\n filter << (start_value.to_i..end_value.to_i).to_a\n end", "code_tokens": ["def", "range", "(", "start_value", ",", "end_value", ",", "args", ",", "block", ")", "filter", "<<", "(", "start_value", ".", "to_i", "..", "end_value", ".", "to_i", ")", ".", "to_a", "end"], "docstring": "Adds a range to the filter", "docstring_tokens": ["Adds", "a", "range", "to", "the", "filter"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/filter.rb#L138-L140", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/filter.rb", "func_name": "Sycsvpro.Filter.range_type", "original_string": "def range_type(type, start_value, end_value, args, block)\n filter_size_before = filter.size\n range(start_value, end_value, args, block)\n (filter.size - filter_size_before).times { types << type }\n end", "language": "ruby", "code": "def range_type(type, start_value, end_value, args, block)\n filter_size_before = filter.size\n range(start_value, end_value, args, block)\n (filter.size - filter_size_before).times { types << type }\n end", "code_tokens": ["def", "range_type", "(", "type", ",", "start_value", ",", "end_value", ",", "args", ",", "block", ")", "filter_size_before", "=", "filter", ".", "size", "range", "(", "start_value", ",", "end_value", ",", "args", ",", "block", ")", "(", "filter", ".", "size", "-", "filter_size_before", ")", ".", "times", "{", "types", "<<", "type", "}", "end"], "docstring": "Adds a range and the associated types to the filter", "docstring_tokens": ["Adds", "a", "range", "and", "the", "associated", "types", "to", "the", "filter"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/filter.rb#L143-L147", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/filter.rb", "func_name": "Sycsvpro.Filter.col_regex", "original_string": "def col_regex(col, r, args, block)\n operation = \"'[value]' =~ Regexp.new('#{r}')\"\n pivot[r] = { col: col, operation: operation } \n end", "language": "ruby", "code": "def col_regex(col, r, args, block)\n operation = \"'[value]' =~ Regexp.new('#{r}')\"\n pivot[r] = { col: col, operation: operation } \n end", "code_tokens": ["def", "col_regex", "(", "col", ",", "r", ",", "args", ",", "block", ")", "operation", "=", "\"'[value]' =~ Regexp.new('#{r}')\"", "pivot", "[", "r", "]", "=", "{", "col", ":", "col", ",", "operation", ":", "operation", "}", "end"], "docstring": "Adds a comparisson filter", "docstring_tokens": ["Adds", "a", "comparisson", "filter"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/filter.rb#L155-L158", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/filter.rb", "func_name": "Sycsvpro.Filter.date", "original_string": "def date(col, comparator, date, args, block)\n comparator = '==' if comparator == '='\n operation = \"Date.strptime(\\\"[value]\\\", \\\"#{date_format}\\\") #{comparator} \" +\n \"Date.strptime(\\\"#{date}\\\", \\\"#{date_format}\\\")\"\n pivot[\"#{comparator}#{date}\"] = { col: col, operation: operation }\n end", "language": "ruby", "code": "def date(col, comparator, date, args, block)\n comparator = '==' if comparator == '='\n operation = \"Date.strptime(\\\"[value]\\\", \\\"#{date_format}\\\") #{comparator} \" +\n \"Date.strptime(\\\"#{date}\\\", \\\"#{date_format}\\\")\"\n pivot[\"#{comparator}#{date}\"] = { col: col, operation: operation }\n end", "code_tokens": ["def", "date", "(", "col", ",", "comparator", ",", "date", ",", "args", ",", "block", ")", "comparator", "=", "'=='", "if", "comparator", "==", "'='", "operation", "=", "\"Date.strptime(\\\"[value]\\\", \\\"#{date_format}\\\") #{comparator} \"", "+", "\"Date.strptime(\\\"#{date}\\\", \\\"#{date_format}\\\")\"", "pivot", "[", "\"#{comparator}#{date}\"", "]", "=", "{", "col", ":", "col", ",", "operation", ":", "operation", "}", "end"], "docstring": "Adds a date filter", "docstring_tokens": ["Adds", "a", "date", "filter"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/filter.rb#L166-L171", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/filter.rb", "func_name": "Sycsvpro.Filter.date_range", "original_string": "def date_range(col, start_date, end_date, args, block)\n operation = \" Date.strptime(\\\"#{start_date}\\\", \\\"#{date_format}\\\") \" +\n \"<= Date.strptime(\\\"[value]\\\", \\\"#{date_format}\\\") && \" +\n \" Date.strptime(\\\"[value]\\\", \\\"#{date_format}\\\") \" +\n \"<= Date.strptime(\\\"#{end_date}\\\", \\\"#{date_format}\\\")\"\n pivot[\"#{start_date}-#{end_date}\"] = { col: col, operation: operation }\n end", "language": "ruby", "code": "def date_range(col, start_date, end_date, args, block)\n operation = \" Date.strptime(\\\"#{start_date}\\\", \\\"#{date_format}\\\") \" +\n \"<= Date.strptime(\\\"[value]\\\", \\\"#{date_format}\\\") && \" +\n \" Date.strptime(\\\"[value]\\\", \\\"#{date_format}\\\") \" +\n \"<= Date.strptime(\\\"#{end_date}\\\", \\\"#{date_format}\\\")\"\n pivot[\"#{start_date}-#{end_date}\"] = { col: col, operation: operation }\n end", "code_tokens": ["def", "date_range", "(", "col", ",", "start_date", ",", "end_date", ",", "args", ",", "block", ")", "operation", "=", "\" Date.strptime(\\\"#{start_date}\\\", \\\"#{date_format}\\\") \"", "+", "\"<= Date.strptime(\\\"[value]\\\", \\\"#{date_format}\\\") && \"", "+", "\" Date.strptime(\\\"[value]\\\", \\\"#{date_format}\\\") \"", "+", "\"<= Date.strptime(\\\"#{end_date}\\\", \\\"#{date_format}\\\")\"", "pivot", "[", "\"#{start_date}-#{end_date}\"", "]", "=", "{", "col", ":", "col", ",", "operation", ":", "operation", "}", "end"], "docstring": "Adds a date range filter", "docstring_tokens": ["Adds", "a", "date", "range", "filter"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/filter.rb#L174-L180", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/filter.rb", "func_name": "Sycsvpro.Filter.number", "original_string": "def number(col, comparator, number, args, block)\n comparator = '==' if comparator == '='\n operation = \"[value] #{comparator} #{number}\"\n pivot[\"#{comparator}#{number}\"] = { col: col, operation: operation }\n end", "language": "ruby", "code": "def number(col, comparator, number, args, block)\n comparator = '==' if comparator == '='\n operation = \"[value] #{comparator} #{number}\"\n pivot[\"#{comparator}#{number}\"] = { col: col, operation: operation }\n end", "code_tokens": ["def", "number", "(", "col", ",", "comparator", ",", "number", ",", "args", ",", "block", ")", "comparator", "=", "'=='", "if", "comparator", "==", "'='", "operation", "=", "\"[value] #{comparator} #{number}\"", "pivot", "[", "\"#{comparator}#{number}\"", "]", "=", "{", "col", ":", "col", ",", "operation", ":", "operation", "}", "end"], "docstring": "Adds a number filter", "docstring_tokens": ["Adds", "a", "number", "filter"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/filter.rb#L183-L187", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/filter.rb", "func_name": "Sycsvpro.Filter.number_range", "original_string": "def number_range(col, start_number, end_number, arg, block)\n operation = \" #{start_number} <= [value] && [value] <= #{end_number}\"\n pivot[\"#{start_number}-#{end_number}\"] = { col: col, operation: operation }\n end", "language": "ruby", "code": "def number_range(col, start_number, end_number, arg, block)\n operation = \" #{start_number} <= [value] && [value] <= #{end_number}\"\n pivot[\"#{start_number}-#{end_number}\"] = { col: col, operation: operation }\n end", "code_tokens": ["def", "number_range", "(", "col", ",", "start_number", ",", "end_number", ",", "arg", ",", "block", ")", "operation", "=", "\" #{start_number} <= [value] && [value] <= #{end_number}\"", "pivot", "[", "\"#{start_number}-#{end_number}\"", "]", "=", "{", "col", ":", "col", ",", "operation", ":", "operation", "}", "end"], "docstring": "Adds a number range filter", "docstring_tokens": ["Adds", "a", "number", "range", "filter"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/filter.rb#L190-L193", "partition": "valid"} {"repo": "caruby/tissue", "path": "embed/ruby/catissue/embed/jbridge.rb", "func_name": "CaTissue.JBridge.create_annotation", "original_string": "def create_annotation(hook, annotation)\n # validate the arguments\n if hook.nil? then raise ArgumentError.new(\"Annotated caTissue object is missing\") end\n if annotation.nil? then raise ArgumentError.new(\"Annotation caTissue object is missing\") end\n # the annotated object must exist in the database\n unless hook.identifier then\n raise AnnotationError.new(\"Annotation writer does not support annotation of a caTissue object without an identifier: #{hook}\")\n end\n # load the caRuby annotations if necessary\n hook.class.ensure_annotations_loaded\n # set the annotation hook reference\n annotation.hook = hook\n # create the annotation in the database\n annotation.create\n end", "language": "ruby", "code": "def create_annotation(hook, annotation)\n # validate the arguments\n if hook.nil? then raise ArgumentError.new(\"Annotated caTissue object is missing\") end\n if annotation.nil? then raise ArgumentError.new(\"Annotation caTissue object is missing\") end\n # the annotated object must exist in the database\n unless hook.identifier then\n raise AnnotationError.new(\"Annotation writer does not support annotation of a caTissue object without an identifier: #{hook}\")\n end\n # load the caRuby annotations if necessary\n hook.class.ensure_annotations_loaded\n # set the annotation hook reference\n annotation.hook = hook\n # create the annotation in the database\n annotation.create\n end", "code_tokens": ["def", "create_annotation", "(", "hook", ",", "annotation", ")", "# validate the arguments", "if", "hook", ".", "nil?", "then", "raise", "ArgumentError", ".", "new", "(", "\"Annotated caTissue object is missing\"", ")", "end", "if", "annotation", ".", "nil?", "then", "raise", "ArgumentError", ".", "new", "(", "\"Annotation caTissue object is missing\"", ")", "end", "# the annotated object must exist in the database", "unless", "hook", ".", "identifier", "then", "raise", "AnnotationError", ".", "new", "(", "\"Annotation writer does not support annotation of a caTissue object without an identifier: #{hook}\"", ")", "end", "# load the caRuby annotations if necessary", "hook", ".", "class", ".", "ensure_annotations_loaded", "# set the annotation hook reference", "annotation", ".", "hook", "=", "hook", "# create the annotation in the database", "annotation", ".", "create", "end"], "docstring": "Creates a new annotation object in the caTissue database.\n\n @param [CaTissue::Resource] hook the existing static hook object to annotate\n @param [CaTissue::Annotation] annotation the annotation object to create\n @raise [AnnotationError] if the hook object does not have a database identifier", "docstring_tokens": ["Creates", "a", "new", "annotation", "object", "in", "the", "caTissue", "database", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/embed/ruby/catissue/embed/jbridge.rb#L18-L32", "partition": "valid"} {"repo": "cerebris/series_joiner", "path": "lib/series_joiner/array_additions.rb", "func_name": "SeriesJoiner.ArrayAdditions.join_as_series", "original_string": "def join_as_series(options = {})\n if defined?(I18n)\n default_delimiter = I18n.translate(:'series_joiner.default_delimiter', :locale => options[:locale])\n default_final_delimiter = I18n.translate(:'series_joiner.default_final_delimiter', :locale => options[:locale])\n default_conjunction = I18n.translate(:'series_joiner.default_conjunction', :locale => options[:locale])\n else\n default_delimiter = ', '\n default_final_delimiter = ''\n default_conjunction = ' and '\n end\n\n delimiter = options[:delimiter] || default_delimiter\n final_delimiter = options[:final_delimiter] || default_final_delimiter\n conjunction = options[:conjunction] || default_conjunction\n\n sz = self.size\n if sz > 0\n r = self[0]\n if sz > 1\n if sz > 2\n for i in 1..(sz - 2)\n r += delimiter + self[i]\n end\n r += final_delimiter\n end\n r += conjunction + self[sz - 1]\n end\n end\n return r\n end", "language": "ruby", "code": "def join_as_series(options = {})\n if defined?(I18n)\n default_delimiter = I18n.translate(:'series_joiner.default_delimiter', :locale => options[:locale])\n default_final_delimiter = I18n.translate(:'series_joiner.default_final_delimiter', :locale => options[:locale])\n default_conjunction = I18n.translate(:'series_joiner.default_conjunction', :locale => options[:locale])\n else\n default_delimiter = ', '\n default_final_delimiter = ''\n default_conjunction = ' and '\n end\n\n delimiter = options[:delimiter] || default_delimiter\n final_delimiter = options[:final_delimiter] || default_final_delimiter\n conjunction = options[:conjunction] || default_conjunction\n\n sz = self.size\n if sz > 0\n r = self[0]\n if sz > 1\n if sz > 2\n for i in 1..(sz - 2)\n r += delimiter + self[i]\n end\n r += final_delimiter\n end\n r += conjunction + self[sz - 1]\n end\n end\n return r\n end", "code_tokens": ["def", "join_as_series", "(", "options", "=", "{", "}", ")", "if", "defined?", "(", "I18n", ")", "default_delimiter", "=", "I18n", ".", "translate", "(", ":'", "'", ",", ":locale", "=>", "options", "[", ":locale", "]", ")", "default_final_delimiter", "=", "I18n", ".", "translate", "(", ":'", "'", ",", ":locale", "=>", "options", "[", ":locale", "]", ")", "default_conjunction", "=", "I18n", ".", "translate", "(", ":'", "'", ",", ":locale", "=>", "options", "[", ":locale", "]", ")", "else", "default_delimiter", "=", "', '", "default_final_delimiter", "=", "''", "default_conjunction", "=", "' and '", "end", "delimiter", "=", "options", "[", ":delimiter", "]", "||", "default_delimiter", "final_delimiter", "=", "options", "[", ":final_delimiter", "]", "||", "default_final_delimiter", "conjunction", "=", "options", "[", ":conjunction", "]", "||", "default_conjunction", "sz", "=", "self", ".", "size", "if", "sz", ">", "0", "r", "=", "self", "[", "0", "]", "if", "sz", ">", "1", "if", "sz", ">", "2", "for", "i", "in", "1", "..", "(", "sz", "-", "2", ")", "r", "+=", "delimiter", "+", "self", "[", "i", "]", "end", "r", "+=", "final_delimiter", "end", "r", "+=", "conjunction", "+", "self", "[", "sz", "-", "1", "]", "end", "end", "return", "r", "end"], "docstring": "Joins items in an array together in a grammatically correct manner.\n\n Options:\n * `delimiter` - inserted between items, except for the final two (default: ', ')\n * `final_delimiter` - inserted between the final two items (if > 2), but before the conjunction (default: '')\n * `conjunction` - inserted between the final two items (default: ' and ')", "docstring_tokens": ["Joins", "items", "in", "an", "array", "together", "in", "a", "grammatically", "correct", "manner", "."], "sha": "c0b609eb2bcad10648a5a8b03f80e2262757f3a3", "url": "https://github.com/cerebris/series_joiner/blob/c0b609eb2bcad10648a5a8b03f80e2262757f3a3/lib/series_joiner/array_additions.rb#L9-L38", "partition": "valid"} {"repo": "nomoon/ragabash", "path": "lib/ragabash/awesome_string_formatter.rb", "func_name": "Ragabash.AwesomeStringFormatter.awesome_string", "original_string": "def awesome_string(string)\n lexers = ::Rouge::Guessers::Source.new(string).filter(R_LEXERS)\n if !lexers.empty?\n format_syntax_string(string, lexers.first)\n elsif string =~ /(?:\\r?\\n)(?!\\z)/\n format_multiline_string(string)\n else\n format_plain_string(string)\n end\n end", "language": "ruby", "code": "def awesome_string(string)\n lexers = ::Rouge::Guessers::Source.new(string).filter(R_LEXERS)\n if !lexers.empty?\n format_syntax_string(string, lexers.first)\n elsif string =~ /(?:\\r?\\n)(?!\\z)/\n format_multiline_string(string)\n else\n format_plain_string(string)\n end\n end", "code_tokens": ["def", "awesome_string", "(", "string", ")", "lexers", "=", "::", "Rouge", "::", "Guessers", "::", "Source", ".", "new", "(", "string", ")", ".", "filter", "(", "R_LEXERS", ")", "if", "!", "lexers", ".", "empty?", "format_syntax_string", "(", "string", ",", "lexers", ".", "first", ")", "elsif", "string", "=~", "/", "\\r", "\\n", "\\z", "/", "format_multiline_string", "(", "string", ")", "else", "format_plain_string", "(", "string", ")", "end", "end"], "docstring": "Format a String for awesome_print display.\n\n @param string [String] the String to format\n @return [String] the formatted String", "docstring_tokens": ["Format", "a", "String", "for", "awesome_print", "display", "."], "sha": "bee40e15a66a452db1dedff2c994c386da845af5", "url": "https://github.com/nomoon/ragabash/blob/bee40e15a66a452db1dedff2c994c386da845af5/lib/ragabash/awesome_string_formatter.rb#L43-L52", "partition": "valid"} {"repo": "lemmycaution/papercat", "path": "app/models/papercat/page.rb", "func_name": "Papercat.Page.meta=", "original_string": "def meta=val\n val = JSON.parse(val) if val.is_a?(String)\n write_store_attribute(:data, :meta, val)\n end", "language": "ruby", "code": "def meta=val\n val = JSON.parse(val) if val.is_a?(String)\n write_store_attribute(:data, :meta, val)\n end", "code_tokens": ["def", "meta", "=", "val", "val", "=", "JSON", ".", "parse", "(", "val", ")", "if", "val", ".", "is_a?", "(", "String", ")", "write_store_attribute", "(", ":data", ",", ":meta", ",", "val", ")", "end"], "docstring": "ensure meta always will be saved as json instead of json string", "docstring_tokens": ["ensure", "meta", "always", "will", "be", "saved", "as", "json", "instead", "of", "json", "string"], "sha": "7b8ce4609dced14fae16548ebc73eb11e46cadc5", "url": "https://github.com/lemmycaution/papercat/blob/7b8ce4609dced14fae16548ebc73eb11e46cadc5/app/models/papercat/page.rb#L8-L11", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/collector.rb", "func_name": "Sycsvpro.Collector.execute", "original_string": "def execute\n File.new(infile).each_with_index do |line, index|\n row = row_filter.process(line, row: index)\n next if row.nil? or row.chomp.empty?\n collection.each do |category, elements|\n values = elements[:filter].process(row) \n values.chomp.split(';').each do |value|\n elements[:entries] << value.chomp if elements[:entries].index(value.chomp).nil?\n end\n end\n end\n\n File.open(outfile, 'w') do |out|\n collection.each do |category, elements|\n out.puts \"[#{category}]\"\n elements[:entries].sort.each { |c| out.puts c }\n end\n end\n end", "language": "ruby", "code": "def execute\n File.new(infile).each_with_index do |line, index|\n row = row_filter.process(line, row: index)\n next if row.nil? or row.chomp.empty?\n collection.each do |category, elements|\n values = elements[:filter].process(row) \n values.chomp.split(';').each do |value|\n elements[:entries] << value.chomp if elements[:entries].index(value.chomp).nil?\n end\n end\n end\n\n File.open(outfile, 'w') do |out|\n collection.each do |category, elements|\n out.puts \"[#{category}]\"\n elements[:entries].sort.each { |c| out.puts c }\n end\n end\n end", "code_tokens": ["def", "execute", "File", ".", "new", "(", "infile", ")", ".", "each_with_index", "do", "|", "line", ",", "index", "|", "row", "=", "row_filter", ".", "process", "(", "line", ",", "row", ":", "index", ")", "next", "if", "row", ".", "nil?", "or", "row", ".", "chomp", ".", "empty?", "collection", ".", "each", "do", "|", "category", ",", "elements", "|", "values", "=", "elements", "[", ":filter", "]", ".", "process", "(", "row", ")", "values", ".", "chomp", ".", "split", "(", "';'", ")", ".", "each", "do", "|", "value", "|", "elements", "[", ":entries", "]", "<<", "value", ".", "chomp", "if", "elements", "[", ":entries", "]", ".", "index", "(", "value", ".", "chomp", ")", ".", "nil?", "end", "end", "end", "File", ".", "open", "(", "outfile", ",", "'w'", ")", "do", "|", "out", "|", "collection", ".", "each", "do", "|", "category", ",", "elements", "|", "out", ".", "puts", "\"[#{category}]\"", "elements", "[", ":entries", "]", ".", "sort", ".", "each", "{", "|", "c", "|", "out", ".", "puts", "c", "}", "end", "end", "end"], "docstring": "Creates a new Collector\n Execute the collector", "docstring_tokens": ["Creates", "a", "new", "Collector", "Execute", "the", "collector"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/collector.rb#L29-L47", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/collector.rb", "func_name": "Sycsvpro.Collector.init_collection", "original_string": "def init_collection(column_filter)\n column_filter.split('+').each do |f|\n category, filter = f.split(':')\n collection[category] = { entries: [], filter: ColumnFilter.new(filter) }\n end \n end", "language": "ruby", "code": "def init_collection(column_filter)\n column_filter.split('+').each do |f|\n category, filter = f.split(':')\n collection[category] = { entries: [], filter: ColumnFilter.new(filter) }\n end \n end", "code_tokens": ["def", "init_collection", "(", "column_filter", ")", "column_filter", ".", "split", "(", "'+'", ")", ".", "each", "do", "|", "f", "|", "category", ",", "filter", "=", "f", ".", "split", "(", "':'", ")", "collection", "[", "category", "]", "=", "{", "entries", ":", "[", "]", ",", "filter", ":", "ColumnFilter", ".", "new", "(", "filter", ")", "}", "end", "end"], "docstring": "Initializes the collection", "docstring_tokens": ["Initializes", "the", "collection"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/collector.rb#L52-L57", "partition": "valid"} {"repo": "PiXeL16/Spark", "path": "lib/Spark/fire.rb", "func_name": "Spark.Fire.log", "original_string": "def log\n out.sync = true\n @log ||= Logger.new(out)\n\n @log.formatter = proc do |severity, datetime, progname, msg|\n if verbose\n string = \"#{severity} [#{datetime.strftime('%Y-%m-%d %H:%M:%S.%2N')}]: \"\n else\n string = \"[#{datetime.strftime('%H:%M:%S')}]: \"\n end\n\n string += \"#{msg}\\n\"\n\n string\n end\n @log\n end", "language": "ruby", "code": "def log\n out.sync = true\n @log ||= Logger.new(out)\n\n @log.formatter = proc do |severity, datetime, progname, msg|\n if verbose\n string = \"#{severity} [#{datetime.strftime('%Y-%m-%d %H:%M:%S.%2N')}]: \"\n else\n string = \"[#{datetime.strftime('%H:%M:%S')}]: \"\n end\n\n string += \"#{msg}\\n\"\n\n string\n end\n @log\n end", "code_tokens": ["def", "log", "out", ".", "sync", "=", "true", "@log", "||=", "Logger", ".", "new", "(", "out", ")", "@log", ".", "formatter", "=", "proc", "do", "|", "severity", ",", "datetime", ",", "progname", ",", "msg", "|", "if", "verbose", "string", "=", "\"#{severity} [#{datetime.strftime('%Y-%m-%d %H:%M:%S.%2N')}]: \"", "else", "string", "=", "\"[#{datetime.strftime('%H:%M:%S')}]: \"", "end", "string", "+=", "\"#{msg}\\n\"", "string", "end", "@log", "end"], "docstring": "Initialize with default stdout output and verbose false\n Gets the logging object", "docstring_tokens": ["Initialize", "with", "default", "stdout", "output", "and", "verbose", "false", "Gets", "the", "logging", "object"], "sha": "20dac7084eda0405c1ea99b112a54d57c6086bd1", "url": "https://github.com/PiXeL16/Spark/blob/20dac7084eda0405c1ea99b112a54d57c6086bd1/lib/Spark/fire.rb#L17-L33", "partition": "valid"} {"repo": "pmahoney/mini_aether", "path": "lib/mini_aether/require.rb", "func_name": "MiniAether.Require.require_aether", "original_string": "def require_aether *deps\n @mini_aether_require_spec ||= MiniAether::Spec.new\n @mini_aether_require_resolver ||= MiniAether::Resolver.new\n\n spec = @mini_aether_require_spec\n resolver = @mini_aether_require_resolver\n\n if deps.last.kind_of?(Hash)\n hash = deps.pop\n [hash[:source], hash[:sources]].flatten.compact.each do |source|\n spec.source(source)\n end\n end\n\n deps.each {|coords| spec.jar(coords) }\n resolver.require(spec.dependencies, spec.sources)\n nil\n end", "language": "ruby", "code": "def require_aether *deps\n @mini_aether_require_spec ||= MiniAether::Spec.new\n @mini_aether_require_resolver ||= MiniAether::Resolver.new\n\n spec = @mini_aether_require_spec\n resolver = @mini_aether_require_resolver\n\n if deps.last.kind_of?(Hash)\n hash = deps.pop\n [hash[:source], hash[:sources]].flatten.compact.each do |source|\n spec.source(source)\n end\n end\n\n deps.each {|coords| spec.jar(coords) }\n resolver.require(spec.dependencies, spec.sources)\n nil\n end", "code_tokens": ["def", "require_aether", "*", "deps", "@mini_aether_require_spec", "||=", "MiniAether", "::", "Spec", ".", "new", "@mini_aether_require_resolver", "||=", "MiniAether", "::", "Resolver", ".", "new", "spec", "=", "@mini_aether_require_spec", "resolver", "=", "@mini_aether_require_resolver", "if", "deps", ".", "last", ".", "kind_of?", "(", "Hash", ")", "hash", "=", "deps", ".", "pop", "[", "hash", "[", ":source", "]", ",", "hash", "[", ":sources", "]", "]", ".", "flatten", ".", "compact", ".", "each", "do", "|", "source", "|", "spec", ".", "source", "(", "source", ")", "end", "end", "deps", ".", "each", "{", "|", "coords", "|", "spec", ".", "jar", "(", "coords", ")", "}", "resolver", ".", "require", "(", "spec", ".", "dependencies", ",", "spec", ".", "sources", ")", "nil", "end"], "docstring": "Experimental 'require_aether' method for use in irb or just for\n convenience. Not threadsafe.\n\n @overload require_aether(*coords)\n @param [Array] coords one or more colon-separated maven coordinate strings\n\n @overload require_aether(*coords, sources)\n @param [Array] coords one or more colon-separated maven coordinate strings\n @param [Hash] sources a hash with a key +:source+ or +:sources+\n and a value of a single string or an array of sources that will be\n permanently added to the list of sources", "docstring_tokens": ["Experimental", "require_aether", "method", "for", "use", "in", "irb", "or", "just", "for", "convenience", ".", "Not", "threadsafe", "."], "sha": "0359967c2fa5fd9ba8bd05b12567e307b44ea7a4", "url": "https://github.com/pmahoney/mini_aether/blob/0359967c2fa5fd9ba8bd05b12567e307b44ea7a4/lib/mini_aether/require.rb#L17-L34", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/join.rb", "func_name": "Sycsvpro.Join.create_lookup_table", "original_string": "def create_lookup_table\n File.open(source).each_with_index do |line|\n next if line.chomp.empty?\n\n values = unstring(line).chomp.split(';')\n\n next if values.empty?\n\n @joiners.each do |joiner|\n key = values[joiner.join[0]]\n joiner.lookup[:rows][key] = []\n\n joiner.cols.each do |i|\n joiner.lookup[:rows][key] << values[i]\n end\n end\n\n end\n end", "language": "ruby", "code": "def create_lookup_table\n File.open(source).each_with_index do |line|\n next if line.chomp.empty?\n\n values = unstring(line).chomp.split(';')\n\n next if values.empty?\n\n @joiners.each do |joiner|\n key = values[joiner.join[0]]\n joiner.lookup[:rows][key] = []\n\n joiner.cols.each do |i|\n joiner.lookup[:rows][key] << values[i]\n end\n end\n\n end\n end", "code_tokens": ["def", "create_lookup_table", "File", ".", "open", "(", "source", ")", ".", "each_with_index", "do", "|", "line", "|", "next", "if", "line", ".", "chomp", ".", "empty?", "values", "=", "unstring", "(", "line", ")", ".", "chomp", ".", "split", "(", "';'", ")", "next", "if", "values", ".", "empty?", "@joiners", ".", "each", "do", "|", "joiner", "|", "key", "=", "values", "[", "joiner", ".", "join", "[", "0", "]", "]", "joiner", ".", "lookup", "[", ":rows", "]", "[", "key", "]", "=", "[", "]", "joiner", ".", "cols", ".", "each", "do", "|", "i", "|", "joiner", ".", "lookup", "[", ":rows", "]", "[", "key", "]", "<<", "values", "[", "i", "]", "end", "end", "end", "end"], "docstring": "Creates a lookup table from the source file values. The join column of\n the source file is the key", "docstring_tokens": ["Creates", "a", "lookup", "table", "from", "the", "source", "file", "values", ".", "The", "join", "column", "of", "the", "source", "file", "is", "the", "key"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/join.rb#L136-L154", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/join.rb", "func_name": "Sycsvpro.Join.col_positions", "original_string": "def col_positions(pos, cols)\n if pos.nil? || pos.empty?\n pos = []\n cols.each { |c| pos << Array.new(c.size) { |c| c } }\n pos\n else\n pos.split(';').collect { |p| p.split(',').collect { |p| p.to_i } }\n end\n end", "language": "ruby", "code": "def col_positions(pos, cols)\n if pos.nil? || pos.empty?\n pos = []\n cols.each { |c| pos << Array.new(c.size) { |c| c } }\n pos\n else\n pos.split(';').collect { |p| p.split(',').collect { |p| p.to_i } }\n end\n end", "code_tokens": ["def", "col_positions", "(", "pos", ",", "cols", ")", "if", "pos", ".", "nil?", "||", "pos", ".", "empty?", "pos", "=", "[", "]", "cols", ".", "each", "{", "|", "c", "|", "pos", "<<", "Array", ".", "new", "(", "c", ".", "size", ")", "{", "|", "c", "|", "c", "}", "}", "pos", "else", "pos", ".", "split", "(", "';'", ")", ".", "collect", "{", "|", "p", "|", "p", ".", "split", "(", "','", ")", ".", "collect", "{", "|", "p", "|", "p", ".", "to_i", "}", "}", "end", "end"], "docstring": "Initializes the column positions where the source file columns have to\n be inserted. If no column positions are provided the inserted columns\n are put at the beginning of the row", "docstring_tokens": ["Initializes", "the", "column", "positions", "where", "the", "source", "file", "columns", "have", "to", "be", "inserted", ".", "If", "no", "column", "positions", "are", "provided", "the", "inserted", "columns", "are", "put", "at", "the", "beginning", "of", "the", "row"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/join.rb#L159-L167", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/join.rb", "func_name": "Sycsvpro.Join.create_joiners", "original_string": "def create_joiners(j, c, p)\n js = j.split(';').collect { |j| j.split('=').collect { |j| j.to_i } }\n cs = c.split(';').collect { |c| c.split(',').collect { |c| c.to_i } }\n ps = col_positions(p, cs)\n\n @joiners = []\n (0...js.size).each do |i| \n @joiners << Joiner.new(js[i], ps[i], cs[i], { rows: { } }) \n end \n\n ps.flatten\n end", "language": "ruby", "code": "def create_joiners(j, c, p)\n js = j.split(';').collect { |j| j.split('=').collect { |j| j.to_i } }\n cs = c.split(';').collect { |c| c.split(',').collect { |c| c.to_i } }\n ps = col_positions(p, cs)\n\n @joiners = []\n (0...js.size).each do |i| \n @joiners << Joiner.new(js[i], ps[i], cs[i], { rows: { } }) \n end \n\n ps.flatten\n end", "code_tokens": ["def", "create_joiners", "(", "j", ",", "c", ",", "p", ")", "js", "=", "j", ".", "split", "(", "';'", ")", ".", "collect", "{", "|", "j", "|", "j", ".", "split", "(", "'='", ")", ".", "collect", "{", "|", "j", "|", "j", ".", "to_i", "}", "}", "cs", "=", "c", ".", "split", "(", "';'", ")", ".", "collect", "{", "|", "c", "|", "c", ".", "split", "(", "','", ")", ".", "collect", "{", "|", "c", "|", "c", ".", "to_i", "}", "}", "ps", "=", "col_positions", "(", "p", ",", "cs", ")", "@joiners", "=", "[", "]", "(", "0", "...", "js", ".", "size", ")", ".", "each", "do", "|", "i", "|", "@joiners", "<<", "Joiner", ".", "new", "(", "js", "[", "i", "]", ",", "ps", "[", "i", "]", ",", "cs", "[", "i", "]", ",", "{", "rows", ":", "{", "}", "}", ")", "end", "ps", ".", "flatten", "end"], "docstring": "Initializes joiners based on joins, positions and columns\n\n Possible input forms are:\n joins:: \"4=0;4=1\" or \"4=1\"\n positions:: \"1,2;4,5\" or \"1,2\"\n columns:: \"1,2;3,4\"\n\n This has the semantic of 'insert columns 1 and 2 at positions 1 and 2\n for key 0 and columns 3 and 4 at positions 4 and 5 for key 1. Key 4 is\n the corresponding value in the source file\n\n Return value:: positions where to insert values from source file", "docstring_tokens": ["Initializes", "joiners", "based", "on", "joins", "positions", "and", "columns"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/join.rb#L181-L192", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/specimen_protocol.rb", "func_name": "CaTissue.SpecimenProtocol.add_defaults_local", "original_string": "def add_defaults_local\n super\n self.title ||= short_title\n self.short_title ||= title\n self.start_date ||= Java::JavaUtil::Date.new\n end", "language": "ruby", "code": "def add_defaults_local\n super\n self.title ||= short_title\n self.short_title ||= title\n self.start_date ||= Java::JavaUtil::Date.new\n end", "code_tokens": ["def", "add_defaults_local", "super", "self", ".", "title", "||=", "short_title", "self", ".", "short_title", "||=", "title", "self", ".", "start_date", "||=", "Java", "::", "JavaUtil", "::", "Date", ".", "new", "end"], "docstring": "Sets the defaults if necessary. The start date is set to now. The title is\n set to the short title.", "docstring_tokens": ["Sets", "the", "defaults", "if", "necessary", ".", "The", "start", "date", "is", "set", "to", "now", ".", "The", "title", "is", "set", "to", "the", "short", "title", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/specimen_protocol.rb#L22-L27", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/spread_sheet.rb", "func_name": "Sycsvpro.SpreadSheet.[]", "original_string": "def [](*range)\n r, c = range\n r ||= 0..(nrows-1)\n c ||= 0..(ncols-1)\n \n row_selection = rows.values_at(*r)\n col_selection = []\n\n if rows_are_arrays?(row_selection)\n row_selection.each do |row|\n values = row.values_at(*c)\n col_selection << (values.respond_to?(:to_ary) ? values : [values])\n end \n else\n col_selection << row_selection[*c]\n end\n\n SpreadSheet.new(*col_selection, \n row_labels: row_labels.values_at(*r),\n col_labels: col_labels.values_at(*c))\n end", "language": "ruby", "code": "def [](*range)\n r, c = range\n r ||= 0..(nrows-1)\n c ||= 0..(ncols-1)\n \n row_selection = rows.values_at(*r)\n col_selection = []\n\n if rows_are_arrays?(row_selection)\n row_selection.each do |row|\n values = row.values_at(*c)\n col_selection << (values.respond_to?(:to_ary) ? values : [values])\n end \n else\n col_selection << row_selection[*c]\n end\n\n SpreadSheet.new(*col_selection, \n row_labels: row_labels.values_at(*r),\n col_labels: col_labels.values_at(*c))\n end", "code_tokens": ["def", "[]", "(", "*", "range", ")", "r", ",", "c", "=", "range", "r", "||=", "0", "..", "(", "nrows", "-", "1", ")", "c", "||=", "0", "..", "(", "ncols", "-", "1", ")", "row_selection", "=", "rows", ".", "values_at", "(", "r", ")", "col_selection", "=", "[", "]", "if", "rows_are_arrays?", "(", "row_selection", ")", "row_selection", ".", "each", "do", "|", "row", "|", "values", "=", "row", ".", "values_at", "(", "c", ")", "col_selection", "<<", "(", "values", ".", "respond_to?", "(", ":to_ary", ")", "?", "values", ":", "[", "values", "]", ")", "end", "else", "col_selection", "<<", "row_selection", "[", "c", "]", "end", "SpreadSheet", ".", "new", "(", "col_selection", ",", "row_labels", ":", "row_labels", ".", "values_at", "(", "r", ")", ",", "col_labels", ":", "col_labels", ".", "values_at", "(", "c", ")", ")", "end"], "docstring": "Returns a subset of the spread sheet and returns a new spread sheet with\n the result and the corresponding row and column labels", "docstring_tokens": ["Returns", "a", "subset", "of", "the", "spread", "sheet", "and", "returns", "a", "new", "spread", "sheet", "with", "the", "result", "and", "the", "corresponding", "row", "and", "column", "labels"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet.rb#L129-L149", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/spread_sheet.rb", "func_name": "Sycsvpro.SpreadSheet.column_collect", "original_string": "def column_collect(&block)\n result = []\n 0.upto(ncols-1) { |i| result << block.call(self[nil,i]) }\n result\n end", "language": "ruby", "code": "def column_collect(&block)\n result = []\n 0.upto(ncols-1) { |i| result << block.call(self[nil,i]) }\n result\n end", "code_tokens": ["def", "column_collect", "(", "&", "block", ")", "result", "=", "[", "]", "0", ".", "upto", "(", "ncols", "-", "1", ")", "{", "|", "i", "|", "result", "<<", "block", ".", "call", "(", "self", "[", "nil", ",", "i", "]", ")", "}", "result", "end"], "docstring": "Collects the operation on each column and returns the result in an array", "docstring_tokens": ["Collects", "the", "operation", "on", "each", "column", "and", "returns", "the", "result", "in", "an", "array"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet.rb#L300-L304", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/spread_sheet.rb", "func_name": "Sycsvpro.SpreadSheet.rename", "original_string": "def rename(opts = {})\n if opts[:rows]\n opts[:rows] = opts[:rows][0,nrows]\n opts[:rows] += row_labels[opts[:rows].size, nrows]\n end\n\n if opts[:cols]\n opts[:cols] = opts[:cols][0,ncols]\n opts[:cols] += col_labels[opts[:cols].size, ncols]\n end\n\n @row_labels = opts[:rows] if opts[:rows]\n @col_labels = opts[:cols] if opts[:cols]\n end", "language": "ruby", "code": "def rename(opts = {})\n if opts[:rows]\n opts[:rows] = opts[:rows][0,nrows]\n opts[:rows] += row_labels[opts[:rows].size, nrows]\n end\n\n if opts[:cols]\n opts[:cols] = opts[:cols][0,ncols]\n opts[:cols] += col_labels[opts[:cols].size, ncols]\n end\n\n @row_labels = opts[:rows] if opts[:rows]\n @col_labels = opts[:cols] if opts[:cols]\n end", "code_tokens": ["def", "rename", "(", "opts", "=", "{", "}", ")", "if", "opts", "[", ":rows", "]", "opts", "[", ":rows", "]", "=", "opts", "[", ":rows", "]", "[", "0", ",", "nrows", "]", "opts", "[", ":rows", "]", "+=", "row_labels", "[", "opts", "[", ":rows", "]", ".", "size", ",", "nrows", "]", "end", "if", "opts", "[", ":cols", "]", "opts", "[", ":cols", "]", "=", "opts", "[", ":cols", "]", "[", "0", ",", "ncols", "]", "opts", "[", ":cols", "]", "+=", "col_labels", "[", "opts", "[", ":cols", "]", ".", "size", ",", "ncols", "]", "end", "@row_labels", "=", "opts", "[", ":rows", "]", "if", "opts", "[", ":rows", "]", "@col_labels", "=", "opts", "[", ":cols", "]", "if", "opts", "[", ":cols", "]", "end"], "docstring": "Renames the row and column labels\n\n sheet.rename(rows: ['Row 1', 'Row 2'], cols: ['Col 1', 'Col 2'])\n\n If the provided rows and columns are larger than the spread sheet's rows\n and columns then only the respective row and column values are used. If\n the row and column labels are fewer than the respective row and column\n sizes the old labels are left untouched for the missing new labels", "docstring_tokens": ["Renames", "the", "row", "and", "column", "labels"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet.rb#L314-L327", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/spread_sheet.rb", "func_name": "Sycsvpro.SpreadSheet.to_s", "original_string": "def to_s\n col_label_sizes = col_labels.collect { |c| c.to_s.size + 2 }\n row_label_size = row_labels.collect { |r| r.to_s.size + 2 }.max\n\n row_col_sizes = rows.transpose.collect { |r| r.collect { |c| c.to_s.size } } \n\n i = -1\n col_sizes = col_label_sizes.collect do |s| \n i += 1\n [row_col_sizes[i],s].flatten.max + 1\n end\n\n s = (sprintf(\"%#{row_label_size}s\", \" \"))\n col_labels.each_with_index { |l,i| s << (sprintf(\"%#{col_sizes[i]}s\", \n \"[#{l}]\")) } \n s << \"\\n\"\n\n rows.each_with_index do |row, i|\n s << (sprintf(\"%#{row_label_size}s\", \"[#{row_labels[i]}]\"))\n row.each_with_index { |c,j| s << (sprintf(\"%#{col_sizes[j]}s\", c)) }\n s << \"\\n\"\n end\n\n s\n end", "language": "ruby", "code": "def to_s\n col_label_sizes = col_labels.collect { |c| c.to_s.size + 2 }\n row_label_size = row_labels.collect { |r| r.to_s.size + 2 }.max\n\n row_col_sizes = rows.transpose.collect { |r| r.collect { |c| c.to_s.size } } \n\n i = -1\n col_sizes = col_label_sizes.collect do |s| \n i += 1\n [row_col_sizes[i],s].flatten.max + 1\n end\n\n s = (sprintf(\"%#{row_label_size}s\", \" \"))\n col_labels.each_with_index { |l,i| s << (sprintf(\"%#{col_sizes[i]}s\", \n \"[#{l}]\")) } \n s << \"\\n\"\n\n rows.each_with_index do |row, i|\n s << (sprintf(\"%#{row_label_size}s\", \"[#{row_labels[i]}]\"))\n row.each_with_index { |c,j| s << (sprintf(\"%#{col_sizes[j]}s\", c)) }\n s << \"\\n\"\n end\n\n s\n end", "code_tokens": ["def", "to_s", "col_label_sizes", "=", "col_labels", ".", "collect", "{", "|", "c", "|", "c", ".", "to_s", ".", "size", "+", "2", "}", "row_label_size", "=", "row_labels", ".", "collect", "{", "|", "r", "|", "r", ".", "to_s", ".", "size", "+", "2", "}", ".", "max", "row_col_sizes", "=", "rows", ".", "transpose", ".", "collect", "{", "|", "r", "|", "r", ".", "collect", "{", "|", "c", "|", "c", ".", "to_s", ".", "size", "}", "}", "i", "=", "-", "1", "col_sizes", "=", "col_label_sizes", ".", "collect", "do", "|", "s", "|", "i", "+=", "1", "[", "row_col_sizes", "[", "i", "]", ",", "s", "]", ".", "flatten", ".", "max", "+", "1", "end", "s", "=", "(", "sprintf", "(", "\"%#{row_label_size}s\"", ",", "\" \"", ")", ")", "col_labels", ".", "each_with_index", "{", "|", "l", ",", "i", "|", "s", "<<", "(", "sprintf", "(", "\"%#{col_sizes[i]}s\"", ",", "\"[#{l}]\"", ")", ")", "}", "s", "<<", "\"\\n\"", "rows", ".", "each_with_index", "do", "|", "row", ",", "i", "|", "s", "<<", "(", "sprintf", "(", "\"%#{row_label_size}s\"", ",", "\"[#{row_labels[i]}]\"", ")", ")", "row", ".", "each_with_index", "{", "|", "c", ",", "j", "|", "s", "<<", "(", "sprintf", "(", "\"%#{col_sizes[j]}s\"", ",", "c", ")", ")", "}", "s", "<<", "\"\\n\"", "end", "s", "end"], "docstring": "Prints the spread sheet in a matrix with column labels and row labels. If\n no labels are available the column number and row number is printed", "docstring_tokens": ["Prints", "the", "spread", "sheet", "in", "a", "matrix", "with", "column", "labels", "and", "row", "labels", ".", "If", "no", "labels", "are", "available", "the", "column", "number", "and", "row", "number", "is", "printed"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet.rb#L370-L394", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/spread_sheet.rb", "func_name": "Sycsvpro.SpreadSheet.rows_from_params", "original_string": "def rows_from_params(opts)\n col_count = opts[:cols] \n row_count = opts[:rows]\n \n size = row_count * col_count if row_count && col_count\n\n rows = []\n\n if values = opts[:values] \n if size\n values += [NotAvailable] * (size - values.size)\n elsif col_count\n values += [NotAvailable] * ((col_count - values.size) % col_count)\n elsif row_count\n values += [NotAvailable] * ((row_count - values.size) % row_count)\n col_count = values.size / row_count\n else\n col_count = Math.sqrt(values.size).ceil\n values += [NotAvailable] * ((col_count - values.size) % col_count)\n end\n values.each_slice(col_count) { |row| rows << row }\n elsif opts[:file]\n File.foreach(opts[:file]) do |line| \n next if line.chomp.empty?\n values = line.split(SEMICOLON) rescue str2utf8(line).split(SEMICOLON)\n rows << values.collect { |v| \n v.strip.empty? ? NotAvailable : str2num(v.chomp, opts[:ds])\n }\n end\n end\n\n rows\n end", "language": "ruby", "code": "def rows_from_params(opts)\n col_count = opts[:cols] \n row_count = opts[:rows]\n \n size = row_count * col_count if row_count && col_count\n\n rows = []\n\n if values = opts[:values] \n if size\n values += [NotAvailable] * (size - values.size)\n elsif col_count\n values += [NotAvailable] * ((col_count - values.size) % col_count)\n elsif row_count\n values += [NotAvailable] * ((row_count - values.size) % row_count)\n col_count = values.size / row_count\n else\n col_count = Math.sqrt(values.size).ceil\n values += [NotAvailable] * ((col_count - values.size) % col_count)\n end\n values.each_slice(col_count) { |row| rows << row }\n elsif opts[:file]\n File.foreach(opts[:file]) do |line| \n next if line.chomp.empty?\n values = line.split(SEMICOLON) rescue str2utf8(line).split(SEMICOLON)\n rows << values.collect { |v| \n v.strip.empty? ? NotAvailable : str2num(v.chomp, opts[:ds])\n }\n end\n end\n\n rows\n end", "code_tokens": ["def", "rows_from_params", "(", "opts", ")", "col_count", "=", "opts", "[", ":cols", "]", "row_count", "=", "opts", "[", ":rows", "]", "size", "=", "row_count", "*", "col_count", "if", "row_count", "&&", "col_count", "rows", "=", "[", "]", "if", "values", "=", "opts", "[", ":values", "]", "if", "size", "values", "+=", "[", "NotAvailable", "]", "*", "(", "size", "-", "values", ".", "size", ")", "elsif", "col_count", "values", "+=", "[", "NotAvailable", "]", "*", "(", "(", "col_count", "-", "values", ".", "size", ")", "%", "col_count", ")", "elsif", "row_count", "values", "+=", "[", "NotAvailable", "]", "*", "(", "(", "row_count", "-", "values", ".", "size", ")", "%", "row_count", ")", "col_count", "=", "values", ".", "size", "/", "row_count", "else", "col_count", "=", "Math", ".", "sqrt", "(", "values", ".", "size", ")", ".", "ceil", "values", "+=", "[", "NotAvailable", "]", "*", "(", "(", "col_count", "-", "values", ".", "size", ")", "%", "col_count", ")", "end", "values", ".", "each_slice", "(", "col_count", ")", "{", "|", "row", "|", "rows", "<<", "row", "}", "elsif", "opts", "[", ":file", "]", "File", ".", "foreach", "(", "opts", "[", ":file", "]", ")", "do", "|", "line", "|", "next", "if", "line", ".", "chomp", ".", "empty?", "values", "=", "line", ".", "split", "(", "SEMICOLON", ")", "rescue", "str2utf8", "(", "line", ")", ".", "split", "(", "SEMICOLON", ")", "rows", "<<", "values", ".", "collect", "{", "|", "v", "|", "v", ".", "strip", ".", "empty?", "?", "NotAvailable", ":", "str2num", "(", "v", ".", "chomp", ",", "opts", "[", ":ds", "]", ")", "}", "end", "end", "rows", "end"], "docstring": "Creates rows from provided array or file. If array doesn't provide\n equal column sizes the array is extended with NotAvailable values", "docstring_tokens": ["Creates", "rows", "from", "provided", "array", "or", "file", ".", "If", "array", "doesn", "t", "provide", "equal", "column", "sizes", "the", "array", "is", "extended", "with", "NotAvailable", "values"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet.rb#L400-L432", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/spread_sheet.rb", "func_name": "Sycsvpro.SpreadSheet.equalize_rows", "original_string": "def equalize_rows(rows)\n column_sizes = rows.collect { |r| r.size }\n\n return rows if column_sizes.uniq.size == 1\n\n max_size = column_sizes.max\n small_rows = []\n column_sizes.each_with_index { |c,i| small_rows << i if c < max_size }\n\n small_rows.each do |i| \n rows[i] += [NotAvailable] * (max_size - rows[i].size)\n end\n\n rows\n end", "language": "ruby", "code": "def equalize_rows(rows)\n column_sizes = rows.collect { |r| r.size }\n\n return rows if column_sizes.uniq.size == 1\n\n max_size = column_sizes.max\n small_rows = []\n column_sizes.each_with_index { |c,i| small_rows << i if c < max_size }\n\n small_rows.each do |i| \n rows[i] += [NotAvailable] * (max_size - rows[i].size)\n end\n\n rows\n end", "code_tokens": ["def", "equalize_rows", "(", "rows", ")", "column_sizes", "=", "rows", ".", "collect", "{", "|", "r", "|", "r", ".", "size", "}", "return", "rows", "if", "column_sizes", ".", "uniq", ".", "size", "==", "1", "max_size", "=", "column_sizes", ".", "max", "small_rows", "=", "[", "]", "column_sizes", ".", "each_with_index", "{", "|", "c", ",", "i", "|", "small_rows", "<<", "i", "if", "c", "<", "max_size", "}", "small_rows", ".", "each", "do", "|", "i", "|", "rows", "[", "i", "]", "+=", "[", "NotAvailable", "]", "*", "(", "max_size", "-", "rows", "[", "i", "]", ".", "size", ")", "end", "rows", "end"], "docstring": "If rows are of different column size the rows are equalized in column\n size by filling missing columns with NA", "docstring_tokens": ["If", "rows", "are", "of", "different", "column", "size", "the", "rows", "are", "equalized", "in", "column", "size", "by", "filling", "missing", "columns", "with", "NA"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet.rb#L436-L450", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/spread_sheet.rb", "func_name": "Sycsvpro.SpreadSheet.same_column_size?", "original_string": "def same_column_size?(rows)\n offset = opts[:c] ? 1 : 0\n return true if rows.size == 1 + offset\n (0 + offset).upto(rows.size - 2) do |i| \n return false unless rows[i].size == rows[i+1].size\n end\n true\n end", "language": "ruby", "code": "def same_column_size?(rows)\n offset = opts[:c] ? 1 : 0\n return true if rows.size == 1 + offset\n (0 + offset).upto(rows.size - 2) do |i| \n return false unless rows[i].size == rows[i+1].size\n end\n true\n end", "code_tokens": ["def", "same_column_size?", "(", "rows", ")", "offset", "=", "opts", "[", ":c", "]", "?", "1", ":", "0", "return", "true", "if", "rows", ".", "size", "==", "1", "+", "offset", "(", "0", "+", "offset", ")", ".", "upto", "(", "rows", ".", "size", "-", "2", ")", "do", "|", "i", "|", "return", "false", "unless", "rows", "[", "i", "]", ".", "size", "==", "rows", "[", "i", "+", "1", "]", ".", "size", "end", "true", "end"], "docstring": "Checks whether all rows have the same column size. Returns true if\n all columns have the same column size", "docstring_tokens": ["Checks", "whether", "all", "rows", "have", "the", "same", "column", "size", ".", "Returns", "true", "if", "all", "columns", "have", "the", "same", "column", "size"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet.rb#L465-L472", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/spread_sheet.rb", "func_name": "Sycsvpro.SpreadSheet.coerce", "original_string": "def coerce(value)\n return SpreadSheet.new([value]) if value.is_a?(Numeric)\n return SpreadSheet.new(value) if value.is_a?(Array)\n end", "language": "ruby", "code": "def coerce(value)\n return SpreadSheet.new([value]) if value.is_a?(Numeric)\n return SpreadSheet.new(value) if value.is_a?(Array)\n end", "code_tokens": ["def", "coerce", "(", "value", ")", "return", "SpreadSheet", ".", "new", "(", "[", "value", "]", ")", "if", "value", ".", "is_a?", "(", "Numeric", ")", "return", "SpreadSheet", ".", "new", "(", "value", ")", "if", "value", ".", "is_a?", "(", "Array", ")", "end"], "docstring": "Coerces a number or an array to a spread sheet", "docstring_tokens": ["Coerces", "a", "number", "or", "an", "array", "to", "a", "spread", "sheet"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet.rb#L534-L537", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/spread_sheet.rb", "func_name": "Sycsvpro.SpreadSheet.process", "original_string": "def process(operator, s)\n s = coerce(s) || s\n raise \"operand needs to be a SpreadSheet, \"+\n \"Numeric or Array\" unless s.is_a?(SpreadSheet)\n result = []\n rlabel = []\n clabel = []\n s1_row_count, s1_col_count = dim\n s2_row_count, s2_col_count = s.dim\n row_count = [s1_row_count, s2_row_count].max\n col_count = [s1_col_count, s2_col_count].max\n 0.upto(row_count - 1) do |r|\n r1 = r % s1_row_count\n r2 = r % s2_row_count\n rlabel << \"#{row_labels[r1]}#{operator}#{s.row_labels[r2]}\"\n element = []\n 0.upto(col_count - 1) do |c|\n c1 = c % s1_col_count\n c2 = c % s2_col_count\n clabel << \"#{col_labels[c1]}#{operator}#{s.col_labels[c2]}\"\n element << rows[r1][c1].send(operator, s.rows[r2][c2])\n end\n result << element\n end\n SpreadSheet.new(*result, row_labels: rlabel, col_labels: clabel)\n end", "language": "ruby", "code": "def process(operator, s)\n s = coerce(s) || s\n raise \"operand needs to be a SpreadSheet, \"+\n \"Numeric or Array\" unless s.is_a?(SpreadSheet)\n result = []\n rlabel = []\n clabel = []\n s1_row_count, s1_col_count = dim\n s2_row_count, s2_col_count = s.dim\n row_count = [s1_row_count, s2_row_count].max\n col_count = [s1_col_count, s2_col_count].max\n 0.upto(row_count - 1) do |r|\n r1 = r % s1_row_count\n r2 = r % s2_row_count\n rlabel << \"#{row_labels[r1]}#{operator}#{s.row_labels[r2]}\"\n element = []\n 0.upto(col_count - 1) do |c|\n c1 = c % s1_col_count\n c2 = c % s2_col_count\n clabel << \"#{col_labels[c1]}#{operator}#{s.col_labels[c2]}\"\n element << rows[r1][c1].send(operator, s.rows[r2][c2])\n end\n result << element\n end\n SpreadSheet.new(*result, row_labels: rlabel, col_labels: clabel)\n end", "code_tokens": ["def", "process", "(", "operator", ",", "s", ")", "s", "=", "coerce", "(", "s", ")", "||", "s", "raise", "\"operand needs to be a SpreadSheet, \"", "+", "\"Numeric or Array\"", "unless", "s", ".", "is_a?", "(", "SpreadSheet", ")", "result", "=", "[", "]", "rlabel", "=", "[", "]", "clabel", "=", "[", "]", "s1_row_count", ",", "s1_col_count", "=", "dim", "s2_row_count", ",", "s2_col_count", "=", "s", ".", "dim", "row_count", "=", "[", "s1_row_count", ",", "s2_row_count", "]", ".", "max", "col_count", "=", "[", "s1_col_count", ",", "s2_col_count", "]", ".", "max", "0", ".", "upto", "(", "row_count", "-", "1", ")", "do", "|", "r", "|", "r1", "=", "r", "%", "s1_row_count", "r2", "=", "r", "%", "s2_row_count", "rlabel", "<<", "\"#{row_labels[r1]}#{operator}#{s.row_labels[r2]}\"", "element", "=", "[", "]", "0", ".", "upto", "(", "col_count", "-", "1", ")", "do", "|", "c", "|", "c1", "=", "c", "%", "s1_col_count", "c2", "=", "c", "%", "s2_col_count", "clabel", "<<", "\"#{col_labels[c1]}#{operator}#{s.col_labels[c2]}\"", "element", "<<", "rows", "[", "r1", "]", "[", "c1", "]", ".", "send", "(", "operator", ",", "s", ".", "rows", "[", "r2", "]", "[", "c2", "]", ")", "end", "result", "<<", "element", "end", "SpreadSheet", ".", "new", "(", "result", ",", "row_labels", ":", "rlabel", ",", "col_labels", ":", "clabel", ")", "end"], "docstring": "Conducts the calculation of this spread sheet with the provided value\n based on the operator. It s is a number or an array it is coerced into\n a spread sheet", "docstring_tokens": ["Conducts", "the", "calculation", "of", "this", "spread", "sheet", "with", "the", "provided", "value", "based", "on", "the", "operator", ".", "It", "s", "is", "a", "number", "or", "an", "array", "it", "is", "coerced", "into", "a", "spread", "sheet"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet.rb#L542-L567", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/counter.rb", "func_name": "Sycsvpro.Counter.process_count", "original_string": "def process_count\n File.new(infile).each_with_index do |line, index|\n result = col_filter.process(row_filter.process(line.chomp, row: index))\n unless result.nil? or result.empty?\n key = unstring(line).split(';').values_at(*key_columns)\n key_value = key_values[key] || key_values[key] = { name: key, \n elements: Hash.new(0), \n sum: 0 }\n result.chomp.split(';').each do |column|\n heading << column if heading.index(column).nil?\n key_value[:elements][column] += 1\n key_value[:sum] += 1\n sums[column] += 1\n end\n end\n end\n end", "language": "ruby", "code": "def process_count\n File.new(infile).each_with_index do |line, index|\n result = col_filter.process(row_filter.process(line.chomp, row: index))\n unless result.nil? or result.empty?\n key = unstring(line).split(';').values_at(*key_columns)\n key_value = key_values[key] || key_values[key] = { name: key, \n elements: Hash.new(0), \n sum: 0 }\n result.chomp.split(';').each do |column|\n heading << column if heading.index(column).nil?\n key_value[:elements][column] += 1\n key_value[:sum] += 1\n sums[column] += 1\n end\n end\n end\n end", "code_tokens": ["def", "process_count", "File", ".", "new", "(", "infile", ")", ".", "each_with_index", "do", "|", "line", ",", "index", "|", "result", "=", "col_filter", ".", "process", "(", "row_filter", ".", "process", "(", "line", ".", "chomp", ",", "row", ":", "index", ")", ")", "unless", "result", ".", "nil?", "or", "result", ".", "empty?", "key", "=", "unstring", "(", "line", ")", ".", "split", "(", "';'", ")", ".", "values_at", "(", "key_columns", ")", "key_value", "=", "key_values", "[", "key", "]", "||", "key_values", "[", "key", "]", "=", "{", "name", ":", "key", ",", "elements", ":", "Hash", ".", "new", "(", "0", ")", ",", "sum", ":", "0", "}", "result", ".", "chomp", ".", "split", "(", "';'", ")", ".", "each", "do", "|", "column", "|", "heading", "<<", "column", "if", "heading", ".", "index", "(", "column", ")", ".", "nil?", "key_value", "[", ":elements", "]", "[", "column", "]", "+=", "1", "key_value", "[", ":sum", "]", "+=", "1", "sums", "[", "column", "]", "+=", "1", "end", "end", "end", "end"], "docstring": "Processes the counting on the in file", "docstring_tokens": ["Processes", "the", "counting", "on", "the", "in", "file"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/counter.rb#L63-L79", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/counter.rb", "func_name": "Sycsvpro.Counter.write_result", "original_string": "def write_result\n sum_line = [sum_row_title] + [''] * (key_titles.size - 1)\n headline = heading_sort ? heading.sort : original_pivot_sequence_heading\n headline << add_sum_col unless sum_col_title.nil?\n headline.each do |h|\n sum_line << sums[h]\n end\n row = 0;\n File.open(outfile, 'w') do |out|\n out.puts sum_line.join(';') if row == sum_row ; row += 1\n out.puts (key_titles + headline).join(';')\n key_values.each do |k,v|\n out.puts sum_line.join(';') if row == sum_row ; row += 1\n line = [k]\n headline.each do |h|\n line << v[:elements][h] unless h == sum_col_title\n end\n line << v[:sum] unless sum_col_title.nil?\n out.puts line.join(';')\n end\n end\n end", "language": "ruby", "code": "def write_result\n sum_line = [sum_row_title] + [''] * (key_titles.size - 1)\n headline = heading_sort ? heading.sort : original_pivot_sequence_heading\n headline << add_sum_col unless sum_col_title.nil?\n headline.each do |h|\n sum_line << sums[h]\n end\n row = 0;\n File.open(outfile, 'w') do |out|\n out.puts sum_line.join(';') if row == sum_row ; row += 1\n out.puts (key_titles + headline).join(';')\n key_values.each do |k,v|\n out.puts sum_line.join(';') if row == sum_row ; row += 1\n line = [k]\n headline.each do |h|\n line << v[:elements][h] unless h == sum_col_title\n end\n line << v[:sum] unless sum_col_title.nil?\n out.puts line.join(';')\n end\n end\n end", "code_tokens": ["def", "write_result", "sum_line", "=", "[", "sum_row_title", "]", "+", "[", "''", "]", "*", "(", "key_titles", ".", "size", "-", "1", ")", "headline", "=", "heading_sort", "?", "heading", ".", "sort", ":", "original_pivot_sequence_heading", "headline", "<<", "add_sum_col", "unless", "sum_col_title", ".", "nil?", "headline", ".", "each", "do", "|", "h", "|", "sum_line", "<<", "sums", "[", "h", "]", "end", "row", "=", "0", ";", "File", ".", "open", "(", "outfile", ",", "'w'", ")", "do", "|", "out", "|", "out", ".", "puts", "sum_line", ".", "join", "(", "';'", ")", "if", "row", "==", "sum_row", ";", "row", "+=", "1", "out", ".", "puts", "(", "key_titles", "+", "headline", ")", ".", "join", "(", "';'", ")", "key_values", ".", "each", "do", "|", "k", ",", "v", "|", "out", ".", "puts", "sum_line", ".", "join", "(", "';'", ")", "if", "row", "==", "sum_row", ";", "row", "+=", "1", "line", "=", "[", "k", "]", "headline", ".", "each", "do", "|", "h", "|", "line", "<<", "v", "[", ":elements", "]", "[", "h", "]", "unless", "h", "==", "sum_col_title", "end", "line", "<<", "v", "[", ":sum", "]", "unless", "sum_col_title", ".", "nil?", "out", ".", "puts", "line", ".", "join", "(", "';'", ")", "end", "end", "end"], "docstring": "Writes the count results", "docstring_tokens": ["Writes", "the", "count", "results"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/counter.rb#L82-L103", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/counter.rb", "func_name": "Sycsvpro.Counter.init_sum_scheme", "original_string": "def init_sum_scheme(sum_scheme)\n\n return if sum_scheme.nil?\n\n re = /(\\w+):(\\d+)|(\\w+)/\n\n sum_scheme.scan(re).each do |part|\n if part.compact.size == 2\n @sum_row_title = part[0]\n @sum_row = part[1].to_i\n else\n @sum_col_title = part[2]\n end\n end\n\n end", "language": "ruby", "code": "def init_sum_scheme(sum_scheme)\n\n return if sum_scheme.nil?\n\n re = /(\\w+):(\\d+)|(\\w+)/\n\n sum_scheme.scan(re).each do |part|\n if part.compact.size == 2\n @sum_row_title = part[0]\n @sum_row = part[1].to_i\n else\n @sum_col_title = part[2]\n end\n end\n\n end", "code_tokens": ["def", "init_sum_scheme", "(", "sum_scheme", ")", "return", "if", "sum_scheme", ".", "nil?", "re", "=", "/", "\\w", "\\d", "\\w", "/", "sum_scheme", ".", "scan", "(", "re", ")", ".", "each", "do", "|", "part", "|", "if", "part", ".", "compact", ".", "size", "==", "2", "@sum_row_title", "=", "part", "[", "0", "]", "@sum_row", "=", "part", "[", "1", "]", ".", "to_i", "else", "@sum_col_title", "=", "part", "[", "2", "]", "end", "end", "end"], "docstring": "Initializes the sum row title an positions as well as the sum column\n title", "docstring_tokens": ["Initializes", "the", "sum", "row", "title", "an", "positions", "as", "well", "as", "the", "sum", "column", "title"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/counter.rb#L109-L124", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/counter.rb", "func_name": "Sycsvpro.Counter.init_key_columns", "original_string": "def init_key_columns(key_scheme)\n\n @key_titles = []\n @key_columns = []\n\n keys = key_scheme.scan(/(\\d+):(\\w+)/)\n\n keys.each do |key|\n @key_titles << key[1]\n @key_columns << key[0].to_i\n end\n\n end", "language": "ruby", "code": "def init_key_columns(key_scheme)\n\n @key_titles = []\n @key_columns = []\n\n keys = key_scheme.scan(/(\\d+):(\\w+)/)\n\n keys.each do |key|\n @key_titles << key[1]\n @key_columns << key[0].to_i\n end\n\n end", "code_tokens": ["def", "init_key_columns", "(", "key_scheme", ")", "@key_titles", "=", "[", "]", "@key_columns", "=", "[", "]", "keys", "=", "key_scheme", ".", "scan", "(", "/", "\\d", "\\w", "/", ")", "keys", ".", "each", "do", "|", "key", "|", "@key_titles", "<<", "key", "[", "1", "]", "@key_columns", "<<", "key", "[", "0", "]", ".", "to_i", "end", "end"], "docstring": "Initialize the key columns and headers", "docstring_tokens": ["Initialize", "the", "key", "columns", "and", "headers"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/counter.rb#L127-L139", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/counter.rb", "func_name": "Sycsvpro.Counter.original_pivot_sequence_heading", "original_string": "def original_pivot_sequence_heading\n (heading.sort - col_filter.pivot.keys << col_filter.pivot.keys).flatten\n end", "language": "ruby", "code": "def original_pivot_sequence_heading\n (heading.sort - col_filter.pivot.keys << col_filter.pivot.keys).flatten\n end", "code_tokens": ["def", "original_pivot_sequence_heading", "(", "heading", ".", "sort", "-", "col_filter", ".", "pivot", ".", "keys", "<<", "col_filter", ".", "pivot", ".", "keys", ")", ".", "flatten", "end"], "docstring": "Arrange heading in the original sequence regarding conditional column\n filters", "docstring_tokens": ["Arrange", "heading", "in", "the", "original", "sequence", "regarding", "conditional", "column", "filters"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/counter.rb#L143-L145", "partition": "valid"} {"repo": "sugaryourcoffee/syc-svpro", "path": "lib/sycsvpro/row_filter.rb", "func_name": "Sycsvpro.RowFilter.process", "original_string": "def process(object, options={})\n object = unstring(object)\n return object unless has_filter?\n filtered = !filter.flatten.uniq.index(options[:row]).nil?\n pattern.each do |p|\n filtered = (filtered or !(object =~ Regexp.new(p)).nil?)\n end\n filtered = (filtered or match_boolean_filter?(object.split(';')))\n filtered ? object : nil\n end", "language": "ruby", "code": "def process(object, options={})\n object = unstring(object)\n return object unless has_filter?\n filtered = !filter.flatten.uniq.index(options[:row]).nil?\n pattern.each do |p|\n filtered = (filtered or !(object =~ Regexp.new(p)).nil?)\n end\n filtered = (filtered or match_boolean_filter?(object.split(';')))\n filtered ? object : nil\n end", "code_tokens": ["def", "process", "(", "object", ",", "options", "=", "{", "}", ")", "object", "=", "unstring", "(", "object", ")", "return", "object", "unless", "has_filter?", "filtered", "=", "!", "filter", ".", "flatten", ".", "uniq", ".", "index", "(", "options", "[", ":row", "]", ")", ".", "nil?", "pattern", ".", "each", "do", "|", "p", "|", "filtered", "=", "(", "filtered", "or", "!", "(", "object", "=~", "Regexp", ".", "new", "(", "p", ")", ")", ".", "nil?", ")", "end", "filtered", "=", "(", "filtered", "or", "match_boolean_filter?", "(", "object", ".", "split", "(", "';'", ")", ")", ")", "filtered", "?", "object", ":", "nil", "end"], "docstring": "Processes the filter on the given row", "docstring_tokens": ["Processes", "the", "filter", "on", "the", "given", "row"], "sha": "a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3", "url": "https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/row_filter.rb#L13-L22", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/user.rb", "func_name": "Turntabler.User.messages", "original_string": "def messages\n data = api('pm.history', :receiverid => id)\n data['history'].map {|attrs| Message.new(client, attrs)}\n end", "language": "ruby", "code": "def messages\n data = api('pm.history', :receiverid => id)\n data['history'].map {|attrs| Message.new(client, attrs)}\n end", "code_tokens": ["def", "messages", "data", "=", "api", "(", "'pm.history'", ",", ":receiverid", "=>", "id", ")", "data", "[", "'history'", "]", ".", "map", "{", "|", "attrs", "|", "Message", ".", "new", "(", "client", ",", "attrs", ")", "}", "end"], "docstring": "Gets the private conversation history with this user.\n\n @return [Array]\n @raise [Turntabler::Error] if the command fails\n @example\n user.messages # => [#, ...]", "docstring_tokens": ["Gets", "the", "private", "conversation", "history", "with", "this", "user", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/user.rb#L153-L156", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/user.rb", "func_name": "Turntabler.User.stalk", "original_string": "def stalk\n become_fan unless client.user.fan_of.include?(self)\n client.rooms.with_friends.detect do |room|\n room.listener(id)\n end\n end", "language": "ruby", "code": "def stalk\n become_fan unless client.user.fan_of.include?(self)\n client.rooms.with_friends.detect do |room|\n room.listener(id)\n end\n end", "code_tokens": ["def", "stalk", "become_fan", "unless", "client", ".", "user", ".", "fan_of", ".", "include?", "(", "self", ")", "client", ".", "rooms", ".", "with_friends", ".", "detect", "do", "|", "room", "|", "room", ".", "listener", "(", "id", ")", "end", "end"], "docstring": "Gets the location of the user.\n\n @note This will make the current user a fan of this user\n @return [Turntabler::Room]\n @raise [Turntabler::Error] if the command fails\n @example\n user.stalk # => #", "docstring_tokens": ["Gets", "the", "location", "of", "the", "user", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/user.rb#L222-L227", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/user.rb", "func_name": "Turntabler.User.boot", "original_string": "def boot(reason = '')\n api('room.boot_user', :roomid => room.id, :section => room.section, :target_userid => id, :reason => reason)\n true\n end", "language": "ruby", "code": "def boot(reason = '')\n api('room.boot_user', :roomid => room.id, :section => room.section, :target_userid => id, :reason => reason)\n true\n end", "code_tokens": ["def", "boot", "(", "reason", "=", "''", ")", "api", "(", "'room.boot_user'", ",", ":roomid", "=>", "room", ".", "id", ",", ":section", "=>", "room", ".", "section", ",", ":target_userid", "=>", "id", ",", ":reason", "=>", "reason", ")", "true", "end"], "docstring": "Boots the user for the specified reason.\n\n @param [String] reason The reason why the user is being booted\n @return [true]\n @raise [Turntabler::Error] if the command fails\n @example\n user.boot('Broke rules') # => true", "docstring_tokens": ["Boots", "the", "user", "for", "the", "specified", "reason", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/user.rb#L258-L261", "partition": "valid"} {"repo": "obrie/turntabler", "path": "lib/turntabler/user.rb", "func_name": "Turntabler.User.report", "original_string": "def report(reason = '')\n api('room.report_user', :roomid => room.id, :section => room.section, :reported => id, :reason => reason)\n true\n end", "language": "ruby", "code": "def report(reason = '')\n api('room.report_user', :roomid => room.id, :section => room.section, :reported => id, :reason => reason)\n true\n end", "code_tokens": ["def", "report", "(", "reason", "=", "''", ")", "api", "(", "'room.report_user'", ",", ":roomid", "=>", "room", ".", "id", ",", ":section", "=>", "room", ".", "section", ",", ":reported", "=>", "id", ",", ":reason", "=>", "reason", ")", "true", "end"], "docstring": "Reports abuse by a user.\n\n @param [String] reason The reason the user is being reported\n @return [true]\n @raise [Turntabler::Error] if the command fails\n @example\n user.report('Verbal abuse ...') # => true", "docstring_tokens": ["Reports", "abuse", "by", "a", "user", "."], "sha": "e2240f1a5d210a33c05c5b2261d291089cdcf1c6", "url": "https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/user.rb#L270-L273", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/abstract_specimen.rb", "func_name": "CaTissue.AbstractSpecimen.default_derived_characteristics", "original_string": "def default_derived_characteristics\n chrs = specimen_characteristics || return\n pas = chrs.class.nondomain_attributes.reject { |pa| pa == :identifier }\n chrs.copy(pas)\n end", "language": "ruby", "code": "def default_derived_characteristics\n chrs = specimen_characteristics || return\n pas = chrs.class.nondomain_attributes.reject { |pa| pa == :identifier }\n chrs.copy(pas)\n end", "code_tokens": ["def", "default_derived_characteristics", "chrs", "=", "specimen_characteristics", "||", "return", "pas", "=", "chrs", ".", "class", ".", "nondomain_attributes", ".", "reject", "{", "|", "pa", "|", "pa", "==", ":identifier", "}", "chrs", ".", "copy", "(", "pas", ")", "end"], "docstring": "Returns characteristics to use for a derived specimen. The new characteristics is copied from this\n parent specimen's characteristics, without the identifier.\n\n @return [CaTissue::SpecimenCharacteristics, nil] a copy of this Specimen's specimen_characteristics, or nil if none", "docstring_tokens": ["Returns", "characteristics", "to", "use", "for", "a", "derived", "specimen", ".", "The", "new", "characteristics", "is", "copied", "from", "this", "parent", "specimen", "s", "characteristics", "without", "the", "identifier", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/abstract_specimen.rb#L289-L293", "partition": "valid"} {"repo": "weibel/MapKitWrapper", "path": "lib/map-kit-wrapper/map_view.rb", "func_name": "MapKit.MapView.region=", "original_string": "def region=(args)\n case args\n when Hash\n self.setRegion(CoordinateRegion.new(args[:region]).api, animated: args[:animated])\n else\n self.setRegion(CoordinateRegion.new(args).api, animated: false)\n end\n end", "language": "ruby", "code": "def region=(args)\n case args\n when Hash\n self.setRegion(CoordinateRegion.new(args[:region]).api, animated: args[:animated])\n else\n self.setRegion(CoordinateRegion.new(args).api, animated: false)\n end\n end", "code_tokens": ["def", "region", "=", "(", "args", ")", "case", "args", "when", "Hash", "self", ".", "setRegion", "(", "CoordinateRegion", ".", "new", "(", "args", "[", ":region", "]", ")", ".", "api", ",", "animated", ":", "args", "[", ":animated", "]", ")", "else", "self", ".", "setRegion", "(", "CoordinateRegion", ".", "new", "(", "args", ")", ".", "api", ",", "animated", ":", "false", ")", "end", "end"], "docstring": "Set the maps region\n\n * *Args* :\n region = CoordinateRegion.new([56, 10.6], [3.1, 3.1])\n region = {:region => CoordinateRegion.new([56, 10.6], [3.1, 3.1]), :animated => false}", "docstring_tokens": ["Set", "the", "maps", "region"], "sha": "6ad3579b77e4d9be1c23ebab6a624a7dbc4ed2e6", "url": "https://github.com/weibel/MapKitWrapper/blob/6ad3579b77e4d9be1c23ebab6a624a7dbc4ed2e6/lib/map-kit-wrapper/map_view.rb#L110-L117", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/participant.rb", "func_name": "CaTissue.Participant.collection_site", "original_string": "def collection_site\n return unless medical_identifiers.size == 1\n site = medical_identifiers.first.site\n return if site.nil?\n site.site_type == Site::SiteType::COLLECTION ? site : nil\n end", "language": "ruby", "code": "def collection_site\n return unless medical_identifiers.size == 1\n site = medical_identifiers.first.site\n return if site.nil?\n site.site_type == Site::SiteType::COLLECTION ? site : nil\n end", "code_tokens": ["def", "collection_site", "return", "unless", "medical_identifiers", ".", "size", "==", "1", "site", "=", "medical_identifiers", ".", "first", ".", "site", "return", "if", "site", ".", "nil?", "site", ".", "site_type", "==", "Site", "::", "SiteType", "::", "COLLECTION", "?", "site", ":", "nil", "end"], "docstring": "Returns the collection site for which this participant has a MRN. If there is not exactly one\n such site, then this method returns nil. This method is a convenience for the common situation\n where a participant is enrolled at one site.\n\n @return [CaTissue::Site] the collection site", "docstring_tokens": ["Returns", "the", "collection", "site", "for", "which", "this", "participant", "has", "a", "MRN", ".", "If", "there", "is", "not", "exactly", "one", "such", "site", "then", "this", "method", "returns", "nil", ".", "This", "method", "is", "a", "convenience", "for", "the", "common", "situation", "where", "a", "participant", "is", "enrolled", "at", "one", "site", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/participant.rb#L110-L115", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/specimen_requirement.rb", "func_name": "CaTissue.SpecimenRequirement.match_characteristics", "original_string": "def match_characteristics(other)\n chr = characteristics\n ochr = other.characteristics\n chr and ochr and chr.tissue_side == ochr.tissue_side and chr.tissue_site == ochr.tissue_site\n end", "language": "ruby", "code": "def match_characteristics(other)\n chr = characteristics\n ochr = other.characteristics\n chr and ochr and chr.tissue_side == ochr.tissue_side and chr.tissue_site == ochr.tissue_site\n end", "code_tokens": ["def", "match_characteristics", "(", "other", ")", "chr", "=", "characteristics", "ochr", "=", "other", ".", "characteristics", "chr", "and", "ochr", "and", "chr", ".", "tissue_side", "==", "ochr", ".", "tissue_side", "and", "chr", ".", "tissue_site", "==", "ochr", ".", "tissue_site", "end"], "docstring": "Returns whether this SpecimenRequirement characteristics matches the other SpecimenRequirement characteristics\n on the tissue site and tissue side.", "docstring_tokens": ["Returns", "whether", "this", "SpecimenRequirement", "characteristics", "matches", "the", "other", "SpecimenRequirement", "characteristics", "on", "the", "tissue", "site", "and", "tissue", "side", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/specimen_requirement.rb#L60-L64", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/domain/received_event_parameters.rb", "func_name": "CaTissue.ReceivedEventParameters.default_user", "original_string": "def default_user\n scg = specimen_collection_group || (specimen.specimen_collection_group if specimen) || return\n cp = scg.collection_protocol || return\n cp.coordinators.first || (cp.sites.first.coordinator if cp.sites.size === 1)\n end", "language": "ruby", "code": "def default_user\n scg = specimen_collection_group || (specimen.specimen_collection_group if specimen) || return\n cp = scg.collection_protocol || return\n cp.coordinators.first || (cp.sites.first.coordinator if cp.sites.size === 1)\n end", "code_tokens": ["def", "default_user", "scg", "=", "specimen_collection_group", "||", "(", "specimen", ".", "specimen_collection_group", "if", "specimen", ")", "||", "return", "cp", "=", "scg", ".", "collection_protocol", "||", "return", "cp", ".", "coordinators", ".", "first", "||", "(", "cp", ".", "sites", ".", "first", ".", "coordinator", "if", "cp", ".", "sites", ".", "size", "===", "1", ")", "end"], "docstring": "Returns the first SCG CP coordinator, if any.", "docstring_tokens": ["Returns", "the", "first", "SCG", "CP", "coordinator", "if", "any", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/received_event_parameters.rb#L19-L23", "partition": "valid"} {"repo": "FromUte/dune-dashboard", "path": "lib/dune/dashboard/i18n.rb", "func_name": "Dune::Dashboard.I18n.export!", "original_string": "def export!\n puts \"Exporting translations:\\n\"\n if config[:split]\n translations.keys.each do |locale|\n if translations[:en].nil?\n puts 'Missing english translation'\n exit\n end\n puts \"\\nLocale: #{locale}\"\n fallback_english_hash = flat_hash(translations[:en])\n translations_hash = flat_hash(translations[locale])\n if locale != :en\n translations_hash.each do |key, value|\n english_fallback = fallback_english_hash[key]\n if value == nil || value == \"\"\n puts \" #{key} missing!\"\n puts \" taking english default: '#{english_fallback}'\"\n translations_hash[key] = english_fallback\n end\n end\n end\n save(translations_hash, File.join(export_dir, \"translations_#{locale}.js\"))\n end\n else\n save(flat_hash(translations), File.join(export_dir, 'translations.js'))\n end\n end", "language": "ruby", "code": "def export!\n puts \"Exporting translations:\\n\"\n if config[:split]\n translations.keys.each do |locale|\n if translations[:en].nil?\n puts 'Missing english translation'\n exit\n end\n puts \"\\nLocale: #{locale}\"\n fallback_english_hash = flat_hash(translations[:en])\n translations_hash = flat_hash(translations[locale])\n if locale != :en\n translations_hash.each do |key, value|\n english_fallback = fallback_english_hash[key]\n if value == nil || value == \"\"\n puts \" #{key} missing!\"\n puts \" taking english default: '#{english_fallback}'\"\n translations_hash[key] = english_fallback\n end\n end\n end\n save(translations_hash, File.join(export_dir, \"translations_#{locale}.js\"))\n end\n else\n save(flat_hash(translations), File.join(export_dir, 'translations.js'))\n end\n end", "code_tokens": ["def", "export!", "puts", "\"Exporting translations:\\n\"", "if", "config", "[", ":split", "]", "translations", ".", "keys", ".", "each", "do", "|", "locale", "|", "if", "translations", "[", ":en", "]", ".", "nil?", "puts", "'Missing english translation'", "exit", "end", "puts", "\"\\nLocale: #{locale}\"", "fallback_english_hash", "=", "flat_hash", "(", "translations", "[", ":en", "]", ")", "translations_hash", "=", "flat_hash", "(", "translations", "[", "locale", "]", ")", "if", "locale", "!=", ":en", "translations_hash", ".", "each", "do", "|", "key", ",", "value", "|", "english_fallback", "=", "fallback_english_hash", "[", "key", "]", "if", "value", "==", "nil", "||", "value", "==", "\"\"", "puts", "\" #{key} missing!\"", "puts", "\" taking english default: '#{english_fallback}'\"", "translations_hash", "[", "key", "]", "=", "english_fallback", "end", "end", "end", "save", "(", "translations_hash", ",", "File", ".", "join", "(", "export_dir", ",", "\"translations_#{locale}.js\"", ")", ")", "end", "else", "save", "(", "flat_hash", "(", "translations", ")", ",", "File", ".", "join", "(", "export_dir", ",", "'translations.js'", ")", ")", "end", "end"], "docstring": "Export translations to JavaScript, considering settings\n from configuration file", "docstring_tokens": ["Export", "translations", "to", "JavaScript", "considering", "settings", "from", "configuration", "file"], "sha": "4438fb6d9f83867fb22469ebde000a589cdde3f1", "url": "https://github.com/FromUte/dune-dashboard/blob/4438fb6d9f83867fb22469ebde000a589cdde3f1/lib/dune/dashboard/i18n.rb#L23-L49", "partition": "valid"} {"repo": "FromUte/dune-dashboard", "path": "lib/dune/dashboard/i18n.rb", "func_name": "Dune::Dashboard.I18n.save", "original_string": "def save(translations, file)\n file = ::Rails.root.join(file)\n FileUtils.mkdir_p File.dirname(file)\n\n variable_to_assign = config.fetch(:variable, 'Ember.I18n.translations')\n\n File.open(file, 'w+') do |f|\n f << variable_to_assign\n f << ' = '\n f << JSON.pretty_generate(translations).html_safe\n f << ';'\n end\n end", "language": "ruby", "code": "def save(translations, file)\n file = ::Rails.root.join(file)\n FileUtils.mkdir_p File.dirname(file)\n\n variable_to_assign = config.fetch(:variable, 'Ember.I18n.translations')\n\n File.open(file, 'w+') do |f|\n f << variable_to_assign\n f << ' = '\n f << JSON.pretty_generate(translations).html_safe\n f << ';'\n end\n end", "code_tokens": ["def", "save", "(", "translations", ",", "file", ")", "file", "=", "::", "Rails", ".", "root", ".", "join", "(", "file", ")", "FileUtils", ".", "mkdir_p", "File", ".", "dirname", "(", "file", ")", "variable_to_assign", "=", "config", ".", "fetch", "(", ":variable", ",", "'Ember.I18n.translations'", ")", "File", ".", "open", "(", "file", ",", "'w+'", ")", "do", "|", "f", "|", "f", "<<", "variable_to_assign", "f", "<<", "' = '", "f", "<<", "JSON", ".", "pretty_generate", "(", "translations", ")", ".", "html_safe", "f", "<<", "';'", "end", "end"], "docstring": "Convert translations to JSON string and save file.", "docstring_tokens": ["Convert", "translations", "to", "JSON", "string", "and", "save", "file", "."], "sha": "4438fb6d9f83867fb22469ebde000a589cdde3f1", "url": "https://github.com/FromUte/dune-dashboard/blob/4438fb6d9f83867fb22469ebde000a589cdde3f1/lib/dune/dashboard/i18n.rb#L81-L93", "partition": "valid"} {"repo": "FromUte/dune-dashboard", "path": "lib/dune/dashboard/i18n.rb", "func_name": "Dune::Dashboard.I18n.translations", "original_string": "def translations\n ::I18n.load_path = default_locales_path\n ::I18n.backend.instance_eval do\n init_translations unless initialized?\n translations\n end\n end", "language": "ruby", "code": "def translations\n ::I18n.load_path = default_locales_path\n ::I18n.backend.instance_eval do\n init_translations unless initialized?\n translations\n end\n end", "code_tokens": ["def", "translations", "::", "I18n", ".", "load_path", "=", "default_locales_path", "::", "I18n", ".", "backend", ".", "instance_eval", "do", "init_translations", "unless", "initialized?", "translations", "end", "end"], "docstring": "Initialize and return translations", "docstring_tokens": ["Initialize", "and", "return", "translations"], "sha": "4438fb6d9f83867fb22469ebde000a589cdde3f1", "url": "https://github.com/FromUte/dune-dashboard/blob/4438fb6d9f83867fb22469ebde000a589cdde3f1/lib/dune/dashboard/i18n.rb#L96-L102", "partition": "valid"} {"repo": "caruby/tissue", "path": "lib/catissue/helpers/properties_loader.rb", "func_name": "CaTissue.PropertiesLoader.load_properties", "original_string": "def load_properties\n # the properties file\n file = default_properties_file\n # the access properties\n props = file && File.exists?(file) ? load_properties_file(file) : {}\n # Load the Java application jar path.\n path = props[:classpath] || props[:path] || infer_classpath\n Java.expand_to_class_path(path) if path\n # Get the application login properties from the remoteService.xml, if necessary.\n unless props.has_key?(:host) or props.has_key?(:port) then\n url = remote_service_url\n if url then\n host, port = url.split(':')\n props[:host] = host\n props[:port] = port\n end\n end\n unless props.has_key?(:database) then\n props.merge(infer_database_properties)\n end\n props\n end", "language": "ruby", "code": "def load_properties\n # the properties file\n file = default_properties_file\n # the access properties\n props = file && File.exists?(file) ? load_properties_file(file) : {}\n # Load the Java application jar path.\n path = props[:classpath] || props[:path] || infer_classpath\n Java.expand_to_class_path(path) if path\n # Get the application login properties from the remoteService.xml, if necessary.\n unless props.has_key?(:host) or props.has_key?(:port) then\n url = remote_service_url\n if url then\n host, port = url.split(':')\n props[:host] = host\n props[:port] = port\n end\n end\n unless props.has_key?(:database) then\n props.merge(infer_database_properties)\n end\n props\n end", "code_tokens": ["def", "load_properties", "# the properties file", "file", "=", "default_properties_file", "# the access properties", "props", "=", "file", "&&", "File", ".", "exists?", "(", "file", ")", "?", "load_properties_file", "(", "file", ")", ":", "{", "}", "# Load the Java application jar path.", "path", "=", "props", "[", ":classpath", "]", "||", "props", "[", ":path", "]", "||", "infer_classpath", "Java", ".", "expand_to_class_path", "(", "path", ")", "if", "path", "# Get the application login properties from the remoteService.xml, if necessary.", "unless", "props", ".", "has_key?", "(", ":host", ")", "or", "props", ".", "has_key?", "(", ":port", ")", "then", "url", "=", "remote_service_url", "if", "url", "then", "host", ",", "port", "=", "url", ".", "split", "(", "':'", ")", "props", "[", ":host", "]", "=", "host", "props", "[", ":port", "]", "=", "port", "end", "end", "unless", "props", ".", "has_key?", "(", ":database", ")", "then", "props", ".", "merge", "(", "infer_database_properties", ")", "end", "props", "end"], "docstring": "Loads the caTissue classpath and connection properties.", "docstring_tokens": ["Loads", "the", "caTissue", "classpath", "and", "connection", "properties", "."], "sha": "08d99aabf4801c89842ce6dee138ccb1e4f5f56b", "url": "https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/helpers/properties_loader.rb#L44-L65", "partition": "valid"} {"repo": "tdawe/vatsim", "path": "lib/vatsim/data.rb", "func_name": "Vatsim.Data.parse", "original_string": "def parse\n download_files\n\n parsing_clients = false\n parsing_prefile = false\n parsing_general = false\n parsing_servers = false\n parsing_voice_servers = false\n\n File.open(DATA_FILE_PATH, 'r:ascii-8bit').each { |line|\n\n if line.start_with? \";\"\n parsing_clients = false\n parsing_prefile = false\n parsing_general = false\n parsing_servers = false\n parsing_voice_servers = false\n elsif parsing_clients\n clienttype = line.split(\":\")[3]\n if clienttype.eql? \"PILOT\"\n @pilots << Pilot.new(line)\n elsif clienttype.eql? \"ATC\"\n @atc << ATC.new(line)\n end\n elsif parsing_prefile\n @prefiles << Prefile.new(line)\n elsif parsing_general\n line_split = line.split(\"=\")\n @general[line_split[0].strip.downcase.gsub(\" \", \"_\")] = line_split[1].strip\n elsif parsing_servers\n @servers << Server.new(line)\n elsif parsing_voice_servers\n @voice_servers << VoiceServer.new(line) if line.length > 2 # ignore last, empty line for voice server that contains 2 characters\n end\n\n parsing_clients = true if line.start_with? \"!CLIENTS:\"\n parsing_prefile = true if line.start_with? \"!PREFILE:\"\n parsing_general = true if line.start_with? \"!GENERAL:\"\n parsing_servers = true if line.start_with? \"!SERVERS:\"\n parsing_voice_servers = true if line.start_with? \"!VOICE SERVERS:\"\n }\n end", "language": "ruby", "code": "def parse\n download_files\n\n parsing_clients = false\n parsing_prefile = false\n parsing_general = false\n parsing_servers = false\n parsing_voice_servers = false\n\n File.open(DATA_FILE_PATH, 'r:ascii-8bit').each { |line|\n\n if line.start_with? \";\"\n parsing_clients = false\n parsing_prefile = false\n parsing_general = false\n parsing_servers = false\n parsing_voice_servers = false\n elsif parsing_clients\n clienttype = line.split(\":\")[3]\n if clienttype.eql? \"PILOT\"\n @pilots << Pilot.new(line)\n elsif clienttype.eql? \"ATC\"\n @atc << ATC.new(line)\n end\n elsif parsing_prefile\n @prefiles << Prefile.new(line)\n elsif parsing_general\n line_split = line.split(\"=\")\n @general[line_split[0].strip.downcase.gsub(\" \", \"_\")] = line_split[1].strip\n elsif parsing_servers\n @servers << Server.new(line)\n elsif parsing_voice_servers\n @voice_servers << VoiceServer.new(line) if line.length > 2 # ignore last, empty line for voice server that contains 2 characters\n end\n\n parsing_clients = true if line.start_with? \"!CLIENTS:\"\n parsing_prefile = true if line.start_with? \"!PREFILE:\"\n parsing_general = true if line.start_with? \"!GENERAL:\"\n parsing_servers = true if line.start_with? \"!SERVERS:\"\n parsing_voice_servers = true if line.start_with? \"!VOICE SERVERS:\"\n }\n end", "code_tokens": ["def", "parse", "download_files", "parsing_clients", "=", "false", "parsing_prefile", "=", "false", "parsing_general", "=", "false", "parsing_servers", "=", "false", "parsing_voice_servers", "=", "false", "File", ".", "open", "(", "DATA_FILE_PATH", ",", "'r:ascii-8bit'", ")", ".", "each", "{", "|", "line", "|", "if", "line", ".", "start_with?", "\";\"", "parsing_clients", "=", "false", "parsing_prefile", "=", "false", "parsing_general", "=", "false", "parsing_servers", "=", "false", "parsing_voice_servers", "=", "false", "elsif", "parsing_clients", "clienttype", "=", "line", ".", "split", "(", "\":\"", ")", "[", "3", "]", "if", "clienttype", ".", "eql?", "\"PILOT\"", "@pilots", "<<", "Pilot", ".", "new", "(", "line", ")", "elsif", "clienttype", ".", "eql?", "\"ATC\"", "@atc", "<<", "ATC", ".", "new", "(", "line", ")", "end", "elsif", "parsing_prefile", "@prefiles", "<<", "Prefile", ".", "new", "(", "line", ")", "elsif", "parsing_general", "line_split", "=", "line", ".", "split", "(", "\"=\"", ")", "@general", "[", "line_split", "[", "0", "]", ".", "strip", ".", "downcase", ".", "gsub", "(", "\" \"", ",", "\"_\"", ")", "]", "=", "line_split", "[", "1", "]", ".", "strip", "elsif", "parsing_servers", "@servers", "<<", "Server", ".", "new", "(", "line", ")", "elsif", "parsing_voice_servers", "@voice_servers", "<<", "VoiceServer", ".", "new", "(", "line", ")", "if", "line", ".", "length", ">", "2", "# ignore last, empty line for voice server that contains 2 characters", "end", "parsing_clients", "=", "true", "if", "line", ".", "start_with?", "\"!CLIENTS:\"", "parsing_prefile", "=", "true", "if", "line", ".", "start_with?", "\"!PREFILE:\"", "parsing_general", "=", "true", "if", "line", ".", "start_with?", "\"!GENERAL:\"", "parsing_servers", "=", "true", "if", "line", ".", "start_with?", "\"!SERVERS:\"", "parsing_voice_servers", "=", "true", "if", "line", ".", "start_with?", "\"!VOICE SERVERS:\"", "}", "end"], "docstring": "Parse the vatsim data file and store output as necessary", "docstring_tokens": ["Parse", "the", "vatsim", "data", "file", "and", "store", "output", "as", "necessary"], "sha": "79be6099ec808f983ed8f377b7b50feb450d77c9", "url": "https://github.com/tdawe/vatsim/blob/79be6099ec808f983ed8f377b7b50feb450d77c9/lib/vatsim/data.rb#L31-L72", "partition": "valid"} {"repo": "tdawe/vatsim", "path": "lib/vatsim/data.rb", "func_name": "Vatsim.Data.download_files", "original_string": "def download_files\n if !File.exists?(STATUS_FILE_PATH) or File.mtime(STATUS_FILE_PATH) < Time.now - STATUS_DOWNLOAD_INTERVAL\n download_to_file STATUS_URL, STATUS_FILE_PATH\n end\n\n if !File.exists?(DATA_FILE_PATH) or File.mtime(DATA_FILE_PATH) < Time.now - DATA_DOWNLOAD_INTERVAL\n download_to_file random_data_url, DATA_FILE_PATH\n end\n end", "language": "ruby", "code": "def download_files\n if !File.exists?(STATUS_FILE_PATH) or File.mtime(STATUS_FILE_PATH) < Time.now - STATUS_DOWNLOAD_INTERVAL\n download_to_file STATUS_URL, STATUS_FILE_PATH\n end\n\n if !File.exists?(DATA_FILE_PATH) or File.mtime(DATA_FILE_PATH) < Time.now - DATA_DOWNLOAD_INTERVAL\n download_to_file random_data_url, DATA_FILE_PATH\n end\n end", "code_tokens": ["def", "download_files", "if", "!", "File", ".", "exists?", "(", "STATUS_FILE_PATH", ")", "or", "File", ".", "mtime", "(", "STATUS_FILE_PATH", ")", "<", "Time", ".", "now", "-", "STATUS_DOWNLOAD_INTERVAL", "download_to_file", "STATUS_URL", ",", "STATUS_FILE_PATH", "end", "if", "!", "File", ".", "exists?", "(", "DATA_FILE_PATH", ")", "or", "File", ".", "mtime", "(", "DATA_FILE_PATH", ")", "<", "Time", ".", "now", "-", "DATA_DOWNLOAD_INTERVAL", "download_to_file", "random_data_url", ",", "DATA_FILE_PATH", "end", "end"], "docstring": "Initialize the system by downloading status and vatsim data files", "docstring_tokens": ["Initialize", "the", "system", "by", "downloading", "status", "and", "vatsim", "data", "files"], "sha": "79be6099ec808f983ed8f377b7b50feb450d77c9", "url": "https://github.com/tdawe/vatsim/blob/79be6099ec808f983ed8f377b7b50feb450d77c9/lib/vatsim/data.rb#L75-L83", "partition": "valid"} {"repo": "tdawe/vatsim", "path": "lib/vatsim/data.rb", "func_name": "Vatsim.Data.download_to_file", "original_string": "def download_to_file url, file\n url = URI.parse(URI.encode(url.strip))\n\n File.new(file, File::CREAT)\n\n Net::HTTP.start(url.host) { |http|\n resp = http.get(url.path)\n open(file, \"wb\") { |file|\n file.write(resp.body)\n }\n }\n end", "language": "ruby", "code": "def download_to_file url, file\n url = URI.parse(URI.encode(url.strip))\n\n File.new(file, File::CREAT)\n\n Net::HTTP.start(url.host) { |http|\n resp = http.get(url.path)\n open(file, \"wb\") { |file|\n file.write(resp.body)\n }\n }\n end", "code_tokens": ["def", "download_to_file", "url", ",", "file", "url", "=", "URI", ".", "parse", "(", "URI", ".", "encode", "(", "url", ".", "strip", ")", ")", "File", ".", "new", "(", "file", ",", "File", "::", "CREAT", ")", "Net", "::", "HTTP", ".", "start", "(", "url", ".", "host", ")", "{", "|", "http", "|", "resp", "=", "http", ".", "get", "(", "url", ".", "path", ")", "open", "(", "file", ",", "\"wb\"", ")", "{", "|", "file", "|", "file", ".", "write", "(", "resp", ".", "body", ")", "}", "}", "end"], "docstring": "Download a url to a file path", "docstring_tokens": ["Download", "a", "url", "to", "a", "file", "path"], "sha": "79be6099ec808f983ed8f377b7b50feb450d77c9", "url": "https://github.com/tdawe/vatsim/blob/79be6099ec808f983ed8f377b7b50feb450d77c9/lib/vatsim/data.rb#L86-L97", "partition": "valid"} {"repo": "tdawe/vatsim", "path": "lib/vatsim/data.rb", "func_name": "Vatsim.Data.random_data_url", "original_string": "def random_data_url\n url0s = Array.new\n file = File.open(STATUS_FILE_PATH)\n file.each {|line|\n if line.start_with? \"url0\"\n url0s << line.split(\"=\").last\n end\n }\n return url0s[rand(url0s.length)]\n end", "language": "ruby", "code": "def random_data_url\n url0s = Array.new\n file = File.open(STATUS_FILE_PATH)\n file.each {|line|\n if line.start_with? \"url0\"\n url0s << line.split(\"=\").last\n end\n }\n return url0s[rand(url0s.length)]\n end", "code_tokens": ["def", "random_data_url", "url0s", "=", "Array", ".", "new", "file", "=", "File", ".", "open", "(", "STATUS_FILE_PATH", ")", "file", ".", "each", "{", "|", "line", "|", "if", "line", ".", "start_with?", "\"url0\"", "url0s", "<<", "line", ".", "split", "(", "\"=\"", ")", ".", "last", "end", "}", "return", "url0s", "[", "rand", "(", "url0s", ".", "length", ")", "]", "end"], "docstring": "Return random vatsim data url from status file", "docstring_tokens": ["Return", "random", "vatsim", "data", "url", "from", "status", "file"], "sha": "79be6099ec808f983ed8f377b7b50feb450d77c9", "url": "https://github.com/tdawe/vatsim/blob/79be6099ec808f983ed8f377b7b50feb450d77c9/lib/vatsim/data.rb#L100-L109", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/util.rb", "func_name": "NewRelicManagement.Util.cachier!", "original_string": "def cachier!(var = nil)\n if var && instance_variable_get(\"@#{var}\")\n # => Clear the Single Variable\n remove_instance_variable(\"@#{var}\")\n else\n # => Clear the Whole Damned Cache\n instance_variables.each { |x| remove_instance_variable(x) }\n end\n end", "language": "ruby", "code": "def cachier!(var = nil)\n if var && instance_variable_get(\"@#{var}\")\n # => Clear the Single Variable\n remove_instance_variable(\"@#{var}\")\n else\n # => Clear the Whole Damned Cache\n instance_variables.each { |x| remove_instance_variable(x) }\n end\n end", "code_tokens": ["def", "cachier!", "(", "var", "=", "nil", ")", "if", "var", "&&", "instance_variable_get", "(", "\"@#{var}\"", ")", "# => Clear the Single Variable", "remove_instance_variable", "(", "\"@#{var}\"", ")", "else", "# => Clear the Whole Damned Cache", "instance_variables", ".", "each", "{", "|", "x", "|", "remove_instance_variable", "(", "x", ")", "}", "end", "end"], "docstring": "=> Clear Cache", "docstring_tokens": ["=", ">", "Clear", "Cache"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/util.rb#L35-L43", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/util.rb", "func_name": "NewRelicManagement.Util.write_json", "original_string": "def write_json(file, object)\n return unless file && object\n begin\n File.open(file, 'w') { |f| f.write(JSON.pretty_generate(object)) }\n end\n end", "language": "ruby", "code": "def write_json(file, object)\n return unless file && object\n begin\n File.open(file, 'w') { |f| f.write(JSON.pretty_generate(object)) }\n end\n end", "code_tokens": ["def", "write_json", "(", "file", ",", "object", ")", "return", "unless", "file", "&&", "object", "begin", "File", ".", "open", "(", "file", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "JSON", ".", "pretty_generate", "(", "object", ")", ")", "}", "end", "end"], "docstring": "=> Define JSON Writer", "docstring_tokens": ["=", ">", "Define", "JSON", "Writer"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/util.rb#L60-L65", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/util.rb", "func_name": "NewRelicManagement.Util.filestring", "original_string": "def filestring(file, size = 8192)\n return unless file\n return file unless file.is_a?(String) && File.file?(file) && File.size(file) <= size\n File.read(file)\n end", "language": "ruby", "code": "def filestring(file, size = 8192)\n return unless file\n return file unless file.is_a?(String) && File.file?(file) && File.size(file) <= size\n File.read(file)\n end", "code_tokens": ["def", "filestring", "(", "file", ",", "size", "=", "8192", ")", "return", "unless", "file", "return", "file", "unless", "file", ".", "is_a?", "(", "String", ")", "&&", "File", ".", "file?", "(", "file", ")", "&&", "File", ".", "size", "(", "file", ")", "<=", "size", "File", ".", "read", "(", "file", ")", "end"], "docstring": "=> Check if a string is an existing file, and return it's content", "docstring_tokens": ["=", ">", "Check", "if", "a", "string", "is", "an", "existing", "file", "and", "return", "it", "s", "content"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/util.rb#L68-L72", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/util.rb", "func_name": "NewRelicManagement.Util.common_array", "original_string": "def common_array(ary) # rubocop: disable AbcSize\n return ary unless ary.is_a? Array\n count = ary.count\n return ary if count.zero?\n return ary.flatten.uniq if count == 1\n common = ary[0] & ary[1]\n return common if count == 2\n (count - 2).times { |x| common &= ary[x + 2] } if count > 2\n common\n end", "language": "ruby", "code": "def common_array(ary) # rubocop: disable AbcSize\n return ary unless ary.is_a? Array\n count = ary.count\n return ary if count.zero?\n return ary.flatten.uniq if count == 1\n common = ary[0] & ary[1]\n return common if count == 2\n (count - 2).times { |x| common &= ary[x + 2] } if count > 2\n common\n end", "code_tokens": ["def", "common_array", "(", "ary", ")", "# rubocop: disable AbcSize", "return", "ary", "unless", "ary", ".", "is_a?", "Array", "count", "=", "ary", ".", "count", "return", "ary", "if", "count", ".", "zero?", "return", "ary", ".", "flatten", ".", "uniq", "if", "count", "==", "1", "common", "=", "ary", "[", "0", "]", "&", "ary", "[", "1", "]", "return", "common", "if", "count", "==", "2", "(", "count", "-", "2", ")", ".", "times", "{", "|", "x", "|", "common", "&=", "ary", "[", "x", "+", "2", "]", "}", "if", "count", ">", "2", "common", "end"], "docstring": "=> Return Common Elements of an Array", "docstring_tokens": ["=", ">", "Return", "Common", "Elements", "of", "an", "Array"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/util.rb#L90-L99", "partition": "valid"} {"repo": "KeasInc/isimud", "path": "lib/isimud/event_listener.rb", "func_name": "Isimud.EventListener.run", "original_string": "def run\n bind_queues and return if test_env?\n start_shutdown_thread\n start_error_counter_thread\n client.on_exception do |e|\n count_error(e)\n end\n client.connect\n start_event_thread\n\n puts 'EventListener started. Hit Ctrl-C to exit'\n Thread.stop\n puts 'Main thread wakeup - exiting.'\n client.close\n end", "language": "ruby", "code": "def run\n bind_queues and return if test_env?\n start_shutdown_thread\n start_error_counter_thread\n client.on_exception do |e|\n count_error(e)\n end\n client.connect\n start_event_thread\n\n puts 'EventListener started. Hit Ctrl-C to exit'\n Thread.stop\n puts 'Main thread wakeup - exiting.'\n client.close\n end", "code_tokens": ["def", "run", "bind_queues", "and", "return", "if", "test_env?", "start_shutdown_thread", "start_error_counter_thread", "client", ".", "on_exception", "do", "|", "e", "|", "count_error", "(", "e", ")", "end", "client", ".", "connect", "start_event_thread", "puts", "'EventListener started. Hit Ctrl-C to exit'", "Thread", ".", "stop", "puts", "'Main thread wakeup - exiting.'", "client", ".", "close", "end"], "docstring": "Initialize a new EventListener daemon instance\n @param [Hash] options daemon options\n @option options [Integer] :error_limit (10) maximum number of errors that are allowed to occur within error_interval\n before the process terminates\n @option options [Integer] :error_interval (3600) time interval, in seconds, before the error counter is cleared\n @option options [String] :events_exchange ('events') name of AMQP exchange used for listening to event messages\n @option options [String] :models_exchange ('models') name of AMQP exchange used for listening to EventObserver\n instance create, update, and destroy messages\n @option options [String] :name (\"#{Rails.application.class.parent_name.downcase}-listener\") daemon instance name.\n Run the daemon process. This creates the event, error counter, and shutdown threads", "docstring_tokens": ["Initialize", "a", "new", "EventListener", "daemon", "instance"], "sha": "20b66d4d981e39d2c69cb04385551436cda32c67", "url": "https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/event_listener.rb#L93-L107", "partition": "valid"} {"repo": "KeasInc/isimud", "path": "lib/isimud/event_listener.rb", "func_name": "Isimud.EventListener.register_observer_class", "original_string": "def register_observer_class(observer_class)\n @observer_mutex.synchronize do\n return if @observed_models.include?(observer_class)\n @observed_models << observer_class\n log \"EventListener: registering observer class #{observer_class}\"\n observer_queue.bind(models_exchange, routing_key: \"#{Isimud.model_watcher_schema}.#{observer_class.base_class.name}.*\")\n end\n end", "language": "ruby", "code": "def register_observer_class(observer_class)\n @observer_mutex.synchronize do\n return if @observed_models.include?(observer_class)\n @observed_models << observer_class\n log \"EventListener: registering observer class #{observer_class}\"\n observer_queue.bind(models_exchange, routing_key: \"#{Isimud.model_watcher_schema}.#{observer_class.base_class.name}.*\")\n end\n end", "code_tokens": ["def", "register_observer_class", "(", "observer_class", ")", "@observer_mutex", ".", "synchronize", "do", "return", "if", "@observed_models", ".", "include?", "(", "observer_class", ")", "@observed_models", "<<", "observer_class", "log", "\"EventListener: registering observer class #{observer_class}\"", "observer_queue", ".", "bind", "(", "models_exchange", ",", "routing_key", ":", "\"#{Isimud.model_watcher_schema}.#{observer_class.base_class.name}.*\"", ")", "end", "end"], "docstring": "Register the observer class watcher", "docstring_tokens": ["Register", "the", "observer", "class", "watcher"], "sha": "20b66d4d981e39d2c69cb04385551436cda32c67", "url": "https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/event_listener.rb#L236-L243", "partition": "valid"} {"repo": "KeasInc/isimud", "path": "lib/isimud/event_listener.rb", "func_name": "Isimud.EventListener.register_observer", "original_string": "def register_observer(observer)\n @observer_mutex.synchronize do\n log \"EventListener: registering observer #{observer.class} #{observer.id}\"\n @observers[observer_key_for(observer.class, observer.id)] = observer.observe_events(client)\n end\n end", "language": "ruby", "code": "def register_observer(observer)\n @observer_mutex.synchronize do\n log \"EventListener: registering observer #{observer.class} #{observer.id}\"\n @observers[observer_key_for(observer.class, observer.id)] = observer.observe_events(client)\n end\n end", "code_tokens": ["def", "register_observer", "(", "observer", ")", "@observer_mutex", ".", "synchronize", "do", "log", "\"EventListener: registering observer #{observer.class} #{observer.id}\"", "@observers", "[", "observer_key_for", "(", "observer", ".", "class", ",", "observer", ".", "id", ")", "]", "=", "observer", ".", "observe_events", "(", "client", ")", "end", "end"], "docstring": "Register an observer instance, and start listening for events on its associated queue.\n Also ensure that we are listening for observer class update events", "docstring_tokens": ["Register", "an", "observer", "instance", "and", "start", "listening", "for", "events", "on", "its", "associated", "queue", ".", "Also", "ensure", "that", "we", "are", "listening", "for", "observer", "class", "update", "events"], "sha": "20b66d4d981e39d2c69cb04385551436cda32c67", "url": "https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/event_listener.rb#L247-L252", "partition": "valid"} {"repo": "KeasInc/isimud", "path": "lib/isimud/event_listener.rb", "func_name": "Isimud.EventListener.unregister_observer", "original_string": "def unregister_observer(observer_class, observer_id)\n @observer_mutex.synchronize do\n log \"EventListener: un-registering observer #{observer_class} #{observer_id}\"\n if (consumer = @observers.delete(observer_key_for(observer_class, observer_id)))\n consumer.cancel\n end\n end\n end", "language": "ruby", "code": "def unregister_observer(observer_class, observer_id)\n @observer_mutex.synchronize do\n log \"EventListener: un-registering observer #{observer_class} #{observer_id}\"\n if (consumer = @observers.delete(observer_key_for(observer_class, observer_id)))\n consumer.cancel\n end\n end\n end", "code_tokens": ["def", "unregister_observer", "(", "observer_class", ",", "observer_id", ")", "@observer_mutex", ".", "synchronize", "do", "log", "\"EventListener: un-registering observer #{observer_class} #{observer_id}\"", "if", "(", "consumer", "=", "@observers", ".", "delete", "(", "observer_key_for", "(", "observer_class", ",", "observer_id", ")", ")", ")", "consumer", ".", "cancel", "end", "end", "end"], "docstring": "Unregister an observer instance, and cancel consumption of messages. Any pre-fetched messages will be returned to the queue.", "docstring_tokens": ["Unregister", "an", "observer", "instance", "and", "cancel", "consumption", "of", "messages", ".", "Any", "pre", "-", "fetched", "messages", "will", "be", "returned", "to", "the", "queue", "."], "sha": "20b66d4d981e39d2c69cb04385551436cda32c67", "url": "https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/event_listener.rb#L255-L262", "partition": "valid"} {"repo": "KeasInc/isimud", "path": "lib/isimud/event_listener.rb", "func_name": "Isimud.EventListener.observer_queue", "original_string": "def observer_queue\n @observer_queue ||= client.create_queue([name, 'listener', Socket.gethostname, Process.pid].join('.'),\n models_exchange,\n queue_options: {exclusive: true},\n subscribe_options: {manual_ack: true})\n end", "language": "ruby", "code": "def observer_queue\n @observer_queue ||= client.create_queue([name, 'listener', Socket.gethostname, Process.pid].join('.'),\n models_exchange,\n queue_options: {exclusive: true},\n subscribe_options: {manual_ack: true})\n end", "code_tokens": ["def", "observer_queue", "@observer_queue", "||=", "client", ".", "create_queue", "(", "[", "name", ",", "'listener'", ",", "Socket", ".", "gethostname", ",", "Process", ".", "pid", "]", ".", "join", "(", "'.'", ")", ",", "models_exchange", ",", "queue_options", ":", "{", "exclusive", ":", "true", "}", ",", "subscribe_options", ":", "{", "manual_ack", ":", "true", "}", ")", "end"], "docstring": "Create or return the observer queue which listens for ModelWatcher events", "docstring_tokens": ["Create", "or", "return", "the", "observer", "queue", "which", "listens", "for", "ModelWatcher", "events"], "sha": "20b66d4d981e39d2c69cb04385551436cda32c67", "url": "https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/event_listener.rb#L265-L270", "partition": "valid"} {"repo": "KeasInc/isimud", "path": "lib/isimud/event.rb", "func_name": "Isimud.Event.as_json", "original_string": "def as_json(options = {})\n session_id = parameters.delete(:session_id) || Thread.current[:keas_session_id]\n\n data = {type: type,\n action: action,\n user_id: user_id,\n occurred_at: occurred_at,\n eventful_type: eventful_type,\n eventful_id: eventful_id,\n session_id: session_id}\n unless options[:omit_parameters]\n data[:parameters] = parameters\n data[:attributes] = attributes\n end\n data\n end", "language": "ruby", "code": "def as_json(options = {})\n session_id = parameters.delete(:session_id) || Thread.current[:keas_session_id]\n\n data = {type: type,\n action: action,\n user_id: user_id,\n occurred_at: occurred_at,\n eventful_type: eventful_type,\n eventful_id: eventful_id,\n session_id: session_id}\n unless options[:omit_parameters]\n data[:parameters] = parameters\n data[:attributes] = attributes\n end\n data\n end", "code_tokens": ["def", "as_json", "(", "options", "=", "{", "}", ")", "session_id", "=", "parameters", ".", "delete", "(", ":session_id", ")", "||", "Thread", ".", "current", "[", ":keas_session_id", "]", "data", "=", "{", "type", ":", "type", ",", "action", ":", "action", ",", "user_id", ":", "user_id", ",", "occurred_at", ":", "occurred_at", ",", "eventful_type", ":", "eventful_type", ",", "eventful_id", ":", "eventful_id", ",", "session_id", ":", "session_id", "}", "unless", "options", "[", ":omit_parameters", "]", "data", "[", ":parameters", "]", "=", "parameters", "data", "[", ":attributes", "]", "=", "attributes", "end", "data", "end"], "docstring": "Return hash of data to be serialized to JSON\n @option options [Boolean] :omit_parameters when set, do not include attributes or parameters in data\n @return [Hash] data to serialize", "docstring_tokens": ["Return", "hash", "of", "data", "to", "be", "serialized", "to", "JSON"], "sha": "20b66d4d981e39d2c69cb04385551436cda32c67", "url": "https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/event.rb#L87-L102", "partition": "valid"} {"repo": "mmcclimon/mr_poole", "path": "lib/mr_poole/cli.rb", "func_name": "MrPoole.CLI.do_create", "original_string": "def do_create(action)\n options = do_creation_options\n options.title ||= @params.first\n\n @helper.send(\"#{action}_usage\") unless options.title\n fn = @commands.send(action, options)\n puts \"#{@src_dir}/#{fn}\"\n end", "language": "ruby", "code": "def do_create(action)\n options = do_creation_options\n options.title ||= @params.first\n\n @helper.send(\"#{action}_usage\") unless options.title\n fn = @commands.send(action, options)\n puts \"#{@src_dir}/#{fn}\"\n end", "code_tokens": ["def", "do_create", "(", "action", ")", "options", "=", "do_creation_options", "options", ".", "title", "||=", "@params", ".", "first", "@helper", ".", "send", "(", "\"#{action}_usage\"", ")", "unless", "options", ".", "title", "fn", "=", "@commands", ".", "send", "(", "action", ",", "options", ")", "puts", "\"#{@src_dir}/#{fn}\"", "end"], "docstring": "action is a string, either 'post' or 'draft'", "docstring_tokens": ["action", "is", "a", "string", "either", "post", "or", "draft"], "sha": "442404c64dd931185ddf2e2345ce2e76994c910f", "url": "https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/cli.rb#L51-L58", "partition": "valid"} {"repo": "mmcclimon/mr_poole", "path": "lib/mr_poole/cli.rb", "func_name": "MrPoole.CLI.do_move", "original_string": "def do_move(action)\n options = do_move_options(action)\n path = @params.first\n\n @helper.send(\"#{action}_usage\") unless path\n fn = @commands.send(action, path, options)\n puts \"#{@src_dir}/#{fn}\"\n end", "language": "ruby", "code": "def do_move(action)\n options = do_move_options(action)\n path = @params.first\n\n @helper.send(\"#{action}_usage\") unless path\n fn = @commands.send(action, path, options)\n puts \"#{@src_dir}/#{fn}\"\n end", "code_tokens": ["def", "do_move", "(", "action", ")", "options", "=", "do_move_options", "(", "action", ")", "path", "=", "@params", ".", "first", "@helper", ".", "send", "(", "\"#{action}_usage\"", ")", "unless", "path", "fn", "=", "@commands", ".", "send", "(", "action", ",", "path", ",", "options", ")", "puts", "\"#{@src_dir}/#{fn}\"", "end"], "docstring": "action is a string, either 'publish' or 'unpublish'", "docstring_tokens": ["action", "is", "a", "string", "either", "publish", "or", "unpublish"], "sha": "442404c64dd931185ddf2e2345ce2e76994c910f", "url": "https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/cli.rb#L61-L68", "partition": "valid"} {"repo": "mmcclimon/mr_poole", "path": "lib/mr_poole/cli.rb", "func_name": "MrPoole.CLI.do_move_options", "original_string": "def do_move_options(type)\n options = OpenStruct.new\n opt_parser = OptionParser.new do |opts|\n if type == 'publish'\n opts.on('-d', '--keep-draft', \"Keep draft post\") do |d|\n options.keep_draft = d\n end\n else\n opts.on('-p', '--keep-post', \"Do not delete post\") do |p|\n options.keep_post = p\n end\n end\n\n opts.on('-t', '--keep-timestamp', \"Keep existing timestamp\") do |t|\n options.keep_timestamp = t\n end\n end\n\n opt_parser.parse! @params\n options\n end", "language": "ruby", "code": "def do_move_options(type)\n options = OpenStruct.new\n opt_parser = OptionParser.new do |opts|\n if type == 'publish'\n opts.on('-d', '--keep-draft', \"Keep draft post\") do |d|\n options.keep_draft = d\n end\n else\n opts.on('-p', '--keep-post', \"Do not delete post\") do |p|\n options.keep_post = p\n end\n end\n\n opts.on('-t', '--keep-timestamp', \"Keep existing timestamp\") do |t|\n options.keep_timestamp = t\n end\n end\n\n opt_parser.parse! @params\n options\n end", "code_tokens": ["def", "do_move_options", "(", "type", ")", "options", "=", "OpenStruct", ".", "new", "opt_parser", "=", "OptionParser", ".", "new", "do", "|", "opts", "|", "if", "type", "==", "'publish'", "opts", ".", "on", "(", "'-d'", ",", "'--keep-draft'", ",", "\"Keep draft post\"", ")", "do", "|", "d", "|", "options", ".", "keep_draft", "=", "d", "end", "else", "opts", ".", "on", "(", "'-p'", ",", "'--keep-post'", ",", "\"Do not delete post\"", ")", "do", "|", "p", "|", "options", ".", "keep_post", "=", "p", "end", "end", "opts", ".", "on", "(", "'-t'", ",", "'--keep-timestamp'", ",", "\"Keep existing timestamp\"", ")", "do", "|", "t", "|", "options", ".", "keep_timestamp", "=", "t", "end", "end", "opt_parser", ".", "parse!", "@params", "options", "end"], "docstring": "pass a string, either publish or unpublish", "docstring_tokens": ["pass", "a", "string", "either", "publish", "or", "unpublish"], "sha": "442404c64dd931185ddf2e2345ce2e76994c910f", "url": "https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/cli.rb#L97-L117", "partition": "valid"} {"repo": "haines/yard-relative_markdown_links", "path": "lib/yard/relative_markdown_links.rb", "func_name": "YARD.RelativeMarkdownLinks.resolve_links", "original_string": "def resolve_links(text)\n html = Nokogiri::HTML.fragment(text)\n html.css(\"a[href]\").each do |link|\n href = URI(link[\"href\"])\n next unless href.relative? && markup_for_file(nil, href.path) == :markdown\n link.replace \"{file:#{href} #{link.inner_html}}\"\n end\n super(html.to_s)\n end", "language": "ruby", "code": "def resolve_links(text)\n html = Nokogiri::HTML.fragment(text)\n html.css(\"a[href]\").each do |link|\n href = URI(link[\"href\"])\n next unless href.relative? && markup_for_file(nil, href.path) == :markdown\n link.replace \"{file:#{href} #{link.inner_html}}\"\n end\n super(html.to_s)\n end", "code_tokens": ["def", "resolve_links", "(", "text", ")", "html", "=", "Nokogiri", "::", "HTML", ".", "fragment", "(", "text", ")", "html", ".", "css", "(", "\"a[href]\"", ")", ".", "each", "do", "|", "link", "|", "href", "=", "URI", "(", "link", "[", "\"href\"", "]", ")", "next", "unless", "href", ".", "relative?", "&&", "markup_for_file", "(", "nil", ",", "href", ".", "path", ")", "==", ":markdown", "link", ".", "replace", "\"{file:#{href} #{link.inner_html}}\"", "end", "super", "(", "html", ".", "to_s", ")", "end"], "docstring": "Resolves relative links to Markdown files.\n @param [String] text the HTML fragment in which to resolve links.\n @return [String] HTML with relative links to Markdown files converted to `{file:}` links.", "docstring_tokens": ["Resolves", "relative", "links", "to", "Markdown", "files", "."], "sha": "b8952b8f60d47cbfc8879081c61ddd9b844c7edf", "url": "https://github.com/haines/yard-relative_markdown_links/blob/b8952b8f60d47cbfc8879081c61ddd9b844c7edf/lib/yard/relative_markdown_links.rb#L19-L27", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/client.rb", "func_name": "NewRelicManagement.Client.nr_api", "original_string": "def nr_api\n # => Build the Faraday Connection\n @conn ||= Faraday::Connection.new('https://api.newrelic.com', conn_opts) do |client|\n client.use Faraday::Response::RaiseError\n client.use FaradayMiddleware::EncodeJson\n client.use FaradayMiddleware::ParseJson, content_type: /\\bjson$/\n client.response :logger if Config.environment.to_s.casecmp('development').zero? # => Log Requests to STDOUT\n client.adapter Faraday.default_adapter #:net_http_persistent\n end\n end", "language": "ruby", "code": "def nr_api\n # => Build the Faraday Connection\n @conn ||= Faraday::Connection.new('https://api.newrelic.com', conn_opts) do |client|\n client.use Faraday::Response::RaiseError\n client.use FaradayMiddleware::EncodeJson\n client.use FaradayMiddleware::ParseJson, content_type: /\\bjson$/\n client.response :logger if Config.environment.to_s.casecmp('development').zero? # => Log Requests to STDOUT\n client.adapter Faraday.default_adapter #:net_http_persistent\n end\n end", "code_tokens": ["def", "nr_api", "# => Build the Faraday Connection", "@conn", "||=", "Faraday", "::", "Connection", ".", "new", "(", "'https://api.newrelic.com'", ",", "conn_opts", ")", "do", "|", "client", "|", "client", ".", "use", "Faraday", "::", "Response", "::", "RaiseError", "client", ".", "use", "FaradayMiddleware", "::", "EncodeJson", "client", ".", "use", "FaradayMiddleware", "::", "ParseJson", ",", "content_type", ":", "/", "\\b", "/", "client", ".", "response", ":logger", "if", "Config", ".", "environment", ".", "to_s", ".", "casecmp", "(", "'development'", ")", ".", "zero?", "# => Log Requests to STDOUT", "client", ".", "adapter", "Faraday", ".", "default_adapter", "#:net_http_persistent", "end", "end"], "docstring": "=> Build the HTTP Connection", "docstring_tokens": ["=", ">", "Build", "the", "HTTP", "Connection"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/client.rb#L23-L32", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/client.rb", "func_name": "NewRelicManagement.Client.alert_add_entity", "original_string": "def alert_add_entity(entity_id, condition_id, entity_type = 'Server')\n nr_api.put do |req|\n req.url url('alerts_entity_conditions', entity_id)\n req.params['entity_type'] = entity_type\n req.params['condition_id'] = condition_id\n end\n end", "language": "ruby", "code": "def alert_add_entity(entity_id, condition_id, entity_type = 'Server')\n nr_api.put do |req|\n req.url url('alerts_entity_conditions', entity_id)\n req.params['entity_type'] = entity_type\n req.params['condition_id'] = condition_id\n end\n end", "code_tokens": ["def", "alert_add_entity", "(", "entity_id", ",", "condition_id", ",", "entity_type", "=", "'Server'", ")", "nr_api", ".", "put", "do", "|", "req", "|", "req", ".", "url", "url", "(", "'alerts_entity_conditions'", ",", "entity_id", ")", "req", ".", "params", "[", "'entity_type'", "]", "=", "entity_type", "req", ".", "params", "[", "'condition_id'", "]", "=", "condition_id", "end", "end"], "docstring": "=> Add an Entitity to an Existing Alert Policy", "docstring_tokens": ["=", ">", "Add", "an", "Entitity", "to", "an", "Existing", "Alert", "Policy"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/client.rb#L62-L68", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/client.rb", "func_name": "NewRelicManagement.Client.alert_delete_entity", "original_string": "def alert_delete_entity(entity_id, condition_id, entity_type = 'Server')\n nr_api.delete do |req|\n req.url url('alerts_entity_conditions', entity_id)\n req.params['entity_type'] = entity_type\n req.params['condition_id'] = condition_id\n end\n end", "language": "ruby", "code": "def alert_delete_entity(entity_id, condition_id, entity_type = 'Server')\n nr_api.delete do |req|\n req.url url('alerts_entity_conditions', entity_id)\n req.params['entity_type'] = entity_type\n req.params['condition_id'] = condition_id\n end\n end", "code_tokens": ["def", "alert_delete_entity", "(", "entity_id", ",", "condition_id", ",", "entity_type", "=", "'Server'", ")", "nr_api", ".", "delete", "do", "|", "req", "|", "req", ".", "url", "url", "(", "'alerts_entity_conditions'", ",", "entity_id", ")", "req", ".", "params", "[", "'entity_type'", "]", "=", "entity_type", "req", ".", "params", "[", "'condition_id'", "]", "=", "condition_id", "end", "end"], "docstring": "=> Delete an Entitity from an Existing Alert Policy", "docstring_tokens": ["=", ">", "Delete", "an", "Entitity", "from", "an", "Existing", "Alert", "Policy"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/client.rb#L71-L77", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/client.rb", "func_name": "NewRelicManagement.Client.get_server_id", "original_string": "def get_server_id(server_id)\n return nil unless server_id =~ /^[0-9]+$/\n ret = nr_api.get(url('servers', server_id)).body\n ret['server']\n rescue Faraday::ResourceNotFound, NoMethodError\n nil\n end", "language": "ruby", "code": "def get_server_id(server_id)\n return nil unless server_id =~ /^[0-9]+$/\n ret = nr_api.get(url('servers', server_id)).body\n ret['server']\n rescue Faraday::ResourceNotFound, NoMethodError\n nil\n end", "code_tokens": ["def", "get_server_id", "(", "server_id", ")", "return", "nil", "unless", "server_id", "=~", "/", "/", "ret", "=", "nr_api", ".", "get", "(", "url", "(", "'servers'", ",", "server_id", ")", ")", ".", "body", "ret", "[", "'server'", "]", "rescue", "Faraday", "::", "ResourceNotFound", ",", "NoMethodError", "nil", "end"], "docstring": "=> Get a Server based on ID", "docstring_tokens": ["=", ">", "Get", "a", "Server", "based", "on", "ID"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/client.rb#L104-L110", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/client.rb", "func_name": "NewRelicManagement.Client.get_server_name", "original_string": "def get_server_name(server, exact = true)\n ret = nr_api.get(url('servers'), 'filter[name]' => server).body\n return ret['servers'] unless exact\n ret['servers'].find { |x| x['name'].casecmp(server).zero? }\n rescue NoMethodError\n nil\n end", "language": "ruby", "code": "def get_server_name(server, exact = true)\n ret = nr_api.get(url('servers'), 'filter[name]' => server).body\n return ret['servers'] unless exact\n ret['servers'].find { |x| x['name'].casecmp(server).zero? }\n rescue NoMethodError\n nil\n end", "code_tokens": ["def", "get_server_name", "(", "server", ",", "exact", "=", "true", ")", "ret", "=", "nr_api", ".", "get", "(", "url", "(", "'servers'", ")", ",", "'filter[name]'", "=>", "server", ")", ".", "body", "return", "ret", "[", "'servers'", "]", "unless", "exact", "ret", "[", "'servers'", "]", ".", "find", "{", "|", "x", "|", "x", "[", "'name'", "]", ".", "casecmp", "(", "server", ")", ".", "zero?", "}", "rescue", "NoMethodError", "nil", "end"], "docstring": "=> Get a Server based on Name", "docstring_tokens": ["=", ">", "Get", "a", "Server", "based", "on", "Name"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/client.rb#L113-L119", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/client.rb", "func_name": "NewRelicManagement.Client.get_servers_labeled", "original_string": "def get_servers_labeled(labels)\n label_query = Array(labels).reject { |x| !x.include?(':') }.join(';')\n return [] unless label_query\n nr_api.get(url('servers'), 'filter[labels]' => label_query).body\n end", "language": "ruby", "code": "def get_servers_labeled(labels)\n label_query = Array(labels).reject { |x| !x.include?(':') }.join(';')\n return [] unless label_query\n nr_api.get(url('servers'), 'filter[labels]' => label_query).body\n end", "code_tokens": ["def", "get_servers_labeled", "(", "labels", ")", "label_query", "=", "Array", "(", "labels", ")", ".", "reject", "{", "|", "x", "|", "!", "x", ".", "include?", "(", "':'", ")", "}", ".", "join", "(", "';'", ")", "return", "[", "]", "unless", "label_query", "nr_api", ".", "get", "(", "url", "(", "'servers'", ")", ",", "'filter[labels]'", "=>", "label_query", ")", ".", "body", "end"], "docstring": "=> List the Servers with a Label", "docstring_tokens": ["=", ">", "List", "the", "Servers", "with", "a", "Label"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/client.rb#L122-L126", "partition": "valid"} {"repo": "KeasInc/isimud", "path": "lib/isimud/event_observer.rb", "func_name": "Isimud.EventObserver.observe_events", "original_string": "def observe_events(client)\n return unless enable_listener?\n queue = create_queue(client)\n client.subscribe(queue) do |message|\n event = Event.parse(message)\n handle_event(event)\n end\n end", "language": "ruby", "code": "def observe_events(client)\n return unless enable_listener?\n queue = create_queue(client)\n client.subscribe(queue) do |message|\n event = Event.parse(message)\n handle_event(event)\n end\n end", "code_tokens": ["def", "observe_events", "(", "client", ")", "return", "unless", "enable_listener?", "queue", "=", "create_queue", "(", "client", ")", "client", ".", "subscribe", "(", "queue", ")", "do", "|", "message", "|", "event", "=", "Event", ".", "parse", "(", "message", ")", "handle_event", "(", "event", ")", "end", "end"], "docstring": "Create or attach to a queue on the specified exchange. When an event message that matches the observer's routing keys\n is received, parse the event and call handle_event on same.\n @param [Isimud::Client] client client instance\n @return queue or consumer object\n @see BunnyClient#subscribe\n @see TestClient#subscribe", "docstring_tokens": ["Create", "or", "attach", "to", "a", "queue", "on", "the", "specified", "exchange", ".", "When", "an", "event", "message", "that", "matches", "the", "observer", "s", "routing", "keys", "is", "received", "parse", "the", "event", "and", "call", "handle_event", "on", "same", "."], "sha": "20b66d4d981e39d2c69cb04385551436cda32c67", "url": "https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/event_observer.rb#L59-L66", "partition": "valid"} {"repo": "KeasInc/isimud", "path": "lib/isimud/bunny_client.rb", "func_name": "Isimud.BunnyClient.bind", "original_string": "def bind(queue_name, exchange_name, *routing_keys, &block)\n queue = create_queue(queue_name, exchange_name,\n queue_options: {durable: true},\n routing_keys: routing_keys)\n subscribe(queue, &block) if block_given?\n end", "language": "ruby", "code": "def bind(queue_name, exchange_name, *routing_keys, &block)\n queue = create_queue(queue_name, exchange_name,\n queue_options: {durable: true},\n routing_keys: routing_keys)\n subscribe(queue, &block) if block_given?\n end", "code_tokens": ["def", "bind", "(", "queue_name", ",", "exchange_name", ",", "*", "routing_keys", ",", "&", "block", ")", "queue", "=", "create_queue", "(", "queue_name", ",", "exchange_name", ",", "queue_options", ":", "{", "durable", ":", "true", "}", ",", "routing_keys", ":", "routing_keys", ")", "subscribe", "(", "queue", ",", "block", ")", "if", "block_given?", "end"], "docstring": "Initialize a new BunnyClient instance. Note that a connection is not established until any other method is called\n\n @param [String, Hash] _url Server URL or options hash\n @param [Hash] _bunny_options optional Bunny connection options\n @see Bunny.new for connection options\n Convenience method that finds or creates a named queue, binds to an exchange, and subscribes to messages.\n If a block is provided, it will be called by the consumer each time a message is received.\n\n @param [String] queue_name name of the queue\n @param [String] exchange_name name of the AMQP exchange. Note that existing exchanges must be declared as Topic\n exchanges; otherwise, an error will occur\n @param [Array] routing_keys list of routing keys to be bound to the queue for the specified exchange.\n @yieldparam [String] payload message text\n @return [Bunny::Consumer] Bunny consumer interface", "docstring_tokens": ["Initialize", "a", "new", "BunnyClient", "instance", ".", "Note", "that", "a", "connection", "is", "not", "established", "until", "any", "other", "method", "is", "called"], "sha": "20b66d4d981e39d2c69cb04385551436cda32c67", "url": "https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/bunny_client.rb#L35-L40", "partition": "valid"} {"repo": "KeasInc/isimud", "path": "lib/isimud/bunny_client.rb", "func_name": "Isimud.BunnyClient.create_queue", "original_string": "def create_queue(queue_name, exchange_name, options = {})\n queue_options = options[:queue_options] || {durable: true}\n routing_keys = options[:routing_keys] || []\n log \"Isimud::BunnyClient: create_queue #{queue_name}: queue_options=#{queue_options.inspect}\"\n queue = find_queue(queue_name, queue_options)\n bind_routing_keys(queue, exchange_name, routing_keys) if routing_keys.any?\n queue\n end", "language": "ruby", "code": "def create_queue(queue_name, exchange_name, options = {})\n queue_options = options[:queue_options] || {durable: true}\n routing_keys = options[:routing_keys] || []\n log \"Isimud::BunnyClient: create_queue #{queue_name}: queue_options=#{queue_options.inspect}\"\n queue = find_queue(queue_name, queue_options)\n bind_routing_keys(queue, exchange_name, routing_keys) if routing_keys.any?\n queue\n end", "code_tokens": ["def", "create_queue", "(", "queue_name", ",", "exchange_name", ",", "options", "=", "{", "}", ")", "queue_options", "=", "options", "[", ":queue_options", "]", "||", "{", "durable", ":", "true", "}", "routing_keys", "=", "options", "[", ":routing_keys", "]", "||", "[", "]", "log", "\"Isimud::BunnyClient: create_queue #{queue_name}: queue_options=#{queue_options.inspect}\"", "queue", "=", "find_queue", "(", "queue_name", ",", "queue_options", ")", "bind_routing_keys", "(", "queue", ",", "exchange_name", ",", "routing_keys", ")", "if", "routing_keys", ".", "any?", "queue", "end"], "docstring": "Find or create a named queue and bind it to the specified exchange\n\n @param [String] queue_name name of the queue\n @param [String] exchange_name name of the AMQP exchange. Note that pre-existing exchanges must be declared as Topic\n exchanges; otherwise, an error will occur\n @param [Hash] options queue declaration options\n @option options [Boolean] :queue_options ({durable: true}) queue declaration options -- @see Bunny::Channel#queue\n @option options [Array] :routing_keys ([]) routing keys to be bound to the queue. Use \"*\" to match any 1 word\n in a route segment. Use \"#\" to match 0 or more words in a segment.\n @return [Bunny::Queue] Bunny queue", "docstring_tokens": ["Find", "or", "create", "a", "named", "queue", "and", "bind", "it", "to", "the", "specified", "exchange"], "sha": "20b66d4d981e39d2c69cb04385551436cda32c67", "url": "https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/bunny_client.rb#L52-L59", "partition": "valid"} {"repo": "KeasInc/isimud", "path": "lib/isimud/bunny_client.rb", "func_name": "Isimud.BunnyClient.subscribe", "original_string": "def subscribe(queue, options = {}, &block)\n queue.subscribe(options.merge(manual_ack: true)) do |delivery_info, properties, payload|\n current_channel = delivery_info.channel\n begin\n log \"Isimud: queue #{queue.name} received #{properties[:message_id]} routing_key: #{delivery_info.routing_key}\", :debug\n Thread.current['isimud_queue_name'] = queue.name\n Thread.current['isimud_delivery_info'] = delivery_info\n Thread.current['isimud_properties'] = properties\n block.call(payload)\n if current_channel.open?\n log \"Isimud: queue #{queue.name} finished with #{properties[:message_id]}, acknowledging\", :debug\n current_channel.ack(delivery_info.delivery_tag)\n else\n log \"Isimud: queue #{queue.name} unable to acknowledge #{properties[:message_id]}\", :warn\n end\n rescue => e\n log(\"Isimud: queue #{queue.name} error processing #{properties[:message_id]} payload #{payload.inspect}: #{e.class.name} #{e.message}\\n #{e.backtrace.join(\"\\n \")}\", :warn)\n retry_status = run_exception_handlers(e)\n log \"Isimud: rejecting #{properties[:message_id]} requeue=#{retry_status}\", :warn\n current_channel.open? && current_channel.reject(delivery_info.delivery_tag, retry_status)\n end\n end\n end", "language": "ruby", "code": "def subscribe(queue, options = {}, &block)\n queue.subscribe(options.merge(manual_ack: true)) do |delivery_info, properties, payload|\n current_channel = delivery_info.channel\n begin\n log \"Isimud: queue #{queue.name} received #{properties[:message_id]} routing_key: #{delivery_info.routing_key}\", :debug\n Thread.current['isimud_queue_name'] = queue.name\n Thread.current['isimud_delivery_info'] = delivery_info\n Thread.current['isimud_properties'] = properties\n block.call(payload)\n if current_channel.open?\n log \"Isimud: queue #{queue.name} finished with #{properties[:message_id]}, acknowledging\", :debug\n current_channel.ack(delivery_info.delivery_tag)\n else\n log \"Isimud: queue #{queue.name} unable to acknowledge #{properties[:message_id]}\", :warn\n end\n rescue => e\n log(\"Isimud: queue #{queue.name} error processing #{properties[:message_id]} payload #{payload.inspect}: #{e.class.name} #{e.message}\\n #{e.backtrace.join(\"\\n \")}\", :warn)\n retry_status = run_exception_handlers(e)\n log \"Isimud: rejecting #{properties[:message_id]} requeue=#{retry_status}\", :warn\n current_channel.open? && current_channel.reject(delivery_info.delivery_tag, retry_status)\n end\n end\n end", "code_tokens": ["def", "subscribe", "(", "queue", ",", "options", "=", "{", "}", ",", "&", "block", ")", "queue", ".", "subscribe", "(", "options", ".", "merge", "(", "manual_ack", ":", "true", ")", ")", "do", "|", "delivery_info", ",", "properties", ",", "payload", "|", "current_channel", "=", "delivery_info", ".", "channel", "begin", "log", "\"Isimud: queue #{queue.name} received #{properties[:message_id]} routing_key: #{delivery_info.routing_key}\"", ",", ":debug", "Thread", ".", "current", "[", "'isimud_queue_name'", "]", "=", "queue", ".", "name", "Thread", ".", "current", "[", "'isimud_delivery_info'", "]", "=", "delivery_info", "Thread", ".", "current", "[", "'isimud_properties'", "]", "=", "properties", "block", ".", "call", "(", "payload", ")", "if", "current_channel", ".", "open?", "log", "\"Isimud: queue #{queue.name} finished with #{properties[:message_id]}, acknowledging\"", ",", ":debug", "current_channel", ".", "ack", "(", "delivery_info", ".", "delivery_tag", ")", "else", "log", "\"Isimud: queue #{queue.name} unable to acknowledge #{properties[:message_id]}\"", ",", ":warn", "end", "rescue", "=>", "e", "log", "(", "\"Isimud: queue #{queue.name} error processing #{properties[:message_id]} payload #{payload.inspect}: #{e.class.name} #{e.message}\\n #{e.backtrace.join(\"\\n \")}\"", ",", ":warn", ")", "retry_status", "=", "run_exception_handlers", "(", "e", ")", "log", "\"Isimud: rejecting #{properties[:message_id]} requeue=#{retry_status}\"", ",", ":warn", "current_channel", ".", "open?", "&&", "current_channel", ".", "reject", "(", "delivery_info", ".", "delivery_tag", ",", "retry_status", ")", "end", "end", "end"], "docstring": "Subscribe to messages on the Bunny queue. The provided block will be called each time a message is received.\n The message will be acknowledged and deleted from the queue unless an exception is raised from the block.\n In the case that an uncaught exception is raised, the message is rejected, and any declared exception handlers\n will be called.\n\n @param [Bunny::Queue] queue Bunny queue\n @param [Hash] options {} subscription options -- @see Bunny::Queue#subscribe\n @yieldparam [String] payload message text", "docstring_tokens": ["Subscribe", "to", "messages", "on", "the", "Bunny", "queue", ".", "The", "provided", "block", "will", "be", "called", "each", "time", "a", "message", "is", "received", ".", "The", "message", "will", "be", "acknowledged", "and", "deleted", "from", "the", "queue", "unless", "an", "exception", "is", "raised", "from", "the", "block", ".", "In", "the", "case", "that", "an", "uncaught", "exception", "is", "raised", "the", "message", "is", "rejected", "and", "any", "declared", "exception", "handlers", "will", "be", "called", "."], "sha": "20b66d4d981e39d2c69cb04385551436cda32c67", "url": "https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/bunny_client.rb#L69-L91", "partition": "valid"} {"repo": "KeasInc/isimud", "path": "lib/isimud/bunny_client.rb", "func_name": "Isimud.BunnyClient.channel", "original_string": "def channel\n if (channel = Thread.current[CHANNEL_KEY]).try(:open?)\n channel\n else\n new_channel = connection.channel\n new_channel.confirm_select\n new_channel.prefetch(Isimud.prefetch_count) if Isimud.prefetch_count\n Thread.current[CHANNEL_KEY] = new_channel\n end\n end", "language": "ruby", "code": "def channel\n if (channel = Thread.current[CHANNEL_KEY]).try(:open?)\n channel\n else\n new_channel = connection.channel\n new_channel.confirm_select\n new_channel.prefetch(Isimud.prefetch_count) if Isimud.prefetch_count\n Thread.current[CHANNEL_KEY] = new_channel\n end\n end", "code_tokens": ["def", "channel", "if", "(", "channel", "=", "Thread", ".", "current", "[", "CHANNEL_KEY", "]", ")", ".", "try", "(", ":open?", ")", "channel", "else", "new_channel", "=", "connection", ".", "channel", "new_channel", ".", "confirm_select", "new_channel", ".", "prefetch", "(", "Isimud", ".", "prefetch_count", ")", "if", "Isimud", ".", "prefetch_count", "Thread", ".", "current", "[", "CHANNEL_KEY", "]", "=", "new_channel", "end", "end"], "docstring": "Open a new, thread-specific AMQP connection channel, or return the current channel for this thread if it exists\n and is currently open. New channels are created with publisher confirms enabled. Messages will be prefetched\n according to Isimud.prefetch_count when declared.\n @return [Bunny::Channel] channel instance.", "docstring_tokens": ["Open", "a", "new", "thread", "-", "specific", "AMQP", "connection", "channel", "or", "return", "the", "current", "channel", "for", "this", "thread", "if", "it", "exists", "and", "is", "currently", "open", ".", "New", "channels", "are", "created", "with", "publisher", "confirms", "enabled", ".", "Messages", "will", "be", "prefetched", "according", "to", "Isimud", ".", "prefetch_count", "when", "declared", "."], "sha": "20b66d4d981e39d2c69cb04385551436cda32c67", "url": "https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/bunny_client.rb#L114-L123", "partition": "valid"} {"repo": "KeasInc/isimud", "path": "lib/isimud/bunny_client.rb", "func_name": "Isimud.BunnyClient.publish", "original_string": "def publish(exchange, routing_key, payload, options = {})\n log \"Isimud::BunnyClient#publish: exchange=#{exchange} routing_key=#{routing_key}\", :debug\n channel.topic(exchange, durable: true).publish(payload, options.merge(routing_key: routing_key, persistent: true))\n end", "language": "ruby", "code": "def publish(exchange, routing_key, payload, options = {})\n log \"Isimud::BunnyClient#publish: exchange=#{exchange} routing_key=#{routing_key}\", :debug\n channel.topic(exchange, durable: true).publish(payload, options.merge(routing_key: routing_key, persistent: true))\n end", "code_tokens": ["def", "publish", "(", "exchange", ",", "routing_key", ",", "payload", ",", "options", "=", "{", "}", ")", "log", "\"Isimud::BunnyClient#publish: exchange=#{exchange} routing_key=#{routing_key}\"", ",", ":debug", "channel", ".", "topic", "(", "exchange", ",", "durable", ":", "true", ")", ".", "publish", "(", "payload", ",", "options", ".", "merge", "(", "routing_key", ":", "routing_key", ",", "persistent", ":", "true", ")", ")", "end"], "docstring": "Publish a message to the specified exchange, which is declared as a durable, topic exchange. Note that message\n is always persisted.\n @param [String] exchange AMQP exchange name\n @param [String] routing_key message routing key. This should always be in the form of words separated by dots\n e.g. \"user.goal.complete\"\n @param [String] payload message payload\n @param [Hash] options additional message options\n @see Bunny::Exchange#publish\n @see http://rubybunny.info/articles/exchanges.html", "docstring_tokens": ["Publish", "a", "message", "to", "the", "specified", "exchange", "which", "is", "declared", "as", "a", "durable", "topic", "exchange", ".", "Note", "that", "message", "is", "always", "persisted", "."], "sha": "20b66d4d981e39d2c69cb04385551436cda32c67", "url": "https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/bunny_client.rb#L154-L157", "partition": "valid"} {"repo": "mmcclimon/mr_poole", "path": "lib/mr_poole/commands.rb", "func_name": "MrPoole.Commands.post", "original_string": "def post(opts)\n opts = @helper.ensure_open_struct(opts)\n date = @helper.get_date_stamp\n\n # still want to escape any garbage in the slug\n slug = if opts.slug.nil? || opts.slug.empty?\n opts.title\n else\n opts.slug\n end\n slug = @helper.get_slug_for(slug)\n\n # put the metadata into the layout header\n head, ext = @helper.get_layout(opts.layout)\n head.sub!(/^title:\\s*$/, \"title: #{opts.title}\")\n head.sub!(/^date:\\s*$/, \"date: #{date}\")\n ext ||= @ext\n\n path = File.join(POSTS_FOLDER, \"#{date}-#{slug}.#{ext}\")\n f = File.open(path, \"w\")\n f.write(head)\n f.close\n @helper.open_in_editor(path) # open file if config key set\n path # return the path, in case we want to do anything useful\n end", "language": "ruby", "code": "def post(opts)\n opts = @helper.ensure_open_struct(opts)\n date = @helper.get_date_stamp\n\n # still want to escape any garbage in the slug\n slug = if opts.slug.nil? || opts.slug.empty?\n opts.title\n else\n opts.slug\n end\n slug = @helper.get_slug_for(slug)\n\n # put the metadata into the layout header\n head, ext = @helper.get_layout(opts.layout)\n head.sub!(/^title:\\s*$/, \"title: #{opts.title}\")\n head.sub!(/^date:\\s*$/, \"date: #{date}\")\n ext ||= @ext\n\n path = File.join(POSTS_FOLDER, \"#{date}-#{slug}.#{ext}\")\n f = File.open(path, \"w\")\n f.write(head)\n f.close\n @helper.open_in_editor(path) # open file if config key set\n path # return the path, in case we want to do anything useful\n end", "code_tokens": ["def", "post", "(", "opts", ")", "opts", "=", "@helper", ".", "ensure_open_struct", "(", "opts", ")", "date", "=", "@helper", ".", "get_date_stamp", "# still want to escape any garbage in the slug", "slug", "=", "if", "opts", ".", "slug", ".", "nil?", "||", "opts", ".", "slug", ".", "empty?", "opts", ".", "title", "else", "opts", ".", "slug", "end", "slug", "=", "@helper", ".", "get_slug_for", "(", "slug", ")", "# put the metadata into the layout header", "head", ",", "ext", "=", "@helper", ".", "get_layout", "(", "opts", ".", "layout", ")", "head", ".", "sub!", "(", "/", "\\s", "/", ",", "\"title: #{opts.title}\"", ")", "head", ".", "sub!", "(", "/", "\\s", "/", ",", "\"date: #{date}\"", ")", "ext", "||=", "@ext", "path", "=", "File", ".", "join", "(", "POSTS_FOLDER", ",", "\"#{date}-#{slug}.#{ext}\"", ")", "f", "=", "File", ".", "open", "(", "path", ",", "\"w\"", ")", "f", ".", "write", "(", "head", ")", "f", ".", "close", "@helper", ".", "open_in_editor", "(", "path", ")", "# open file if config key set", "path", "# return the path, in case we want to do anything useful", "end"], "docstring": "Generate a timestamped post", "docstring_tokens": ["Generate", "a", "timestamped", "post"], "sha": "442404c64dd931185ddf2e2345ce2e76994c910f", "url": "https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/commands.rb#L15-L39", "partition": "valid"} {"repo": "mmcclimon/mr_poole", "path": "lib/mr_poole/commands.rb", "func_name": "MrPoole.Commands.draft", "original_string": "def draft(opts)\n opts = @helper.ensure_open_struct(opts)\n\n # the drafts folder might not exist yet...create it just in case\n FileUtils.mkdir_p(DRAFTS_FOLDER)\n\n slug = if opts.slug.nil? || opts.slug.empty?\n opts.title\n else\n opts.slug\n end\n slug = @helper.get_slug_for(slug)\n\n # put the metadata into the layout header\n head, ext = @helper.get_layout(opts.layout)\n head.sub!(/^title:\\s*$/, \"title: #{opts.title}\")\n head.sub!(/^date:\\s*$/, \"date: #{@helper.get_date_stamp}\")\n ext ||= @ext\n\n path = File.join(DRAFTS_FOLDER, \"#{slug}.#{ext}\")\n f = File.open(path, \"w\")\n f.write(head)\n f.close\n @helper.open_in_editor(path) # open file if config key set\n path # return the path, in case we want to do anything useful\n end", "language": "ruby", "code": "def draft(opts)\n opts = @helper.ensure_open_struct(opts)\n\n # the drafts folder might not exist yet...create it just in case\n FileUtils.mkdir_p(DRAFTS_FOLDER)\n\n slug = if opts.slug.nil? || opts.slug.empty?\n opts.title\n else\n opts.slug\n end\n slug = @helper.get_slug_for(slug)\n\n # put the metadata into the layout header\n head, ext = @helper.get_layout(opts.layout)\n head.sub!(/^title:\\s*$/, \"title: #{opts.title}\")\n head.sub!(/^date:\\s*$/, \"date: #{@helper.get_date_stamp}\")\n ext ||= @ext\n\n path = File.join(DRAFTS_FOLDER, \"#{slug}.#{ext}\")\n f = File.open(path, \"w\")\n f.write(head)\n f.close\n @helper.open_in_editor(path) # open file if config key set\n path # return the path, in case we want to do anything useful\n end", "code_tokens": ["def", "draft", "(", "opts", ")", "opts", "=", "@helper", ".", "ensure_open_struct", "(", "opts", ")", "# the drafts folder might not exist yet...create it just in case", "FileUtils", ".", "mkdir_p", "(", "DRAFTS_FOLDER", ")", "slug", "=", "if", "opts", ".", "slug", ".", "nil?", "||", "opts", ".", "slug", ".", "empty?", "opts", ".", "title", "else", "opts", ".", "slug", "end", "slug", "=", "@helper", ".", "get_slug_for", "(", "slug", ")", "# put the metadata into the layout header", "head", ",", "ext", "=", "@helper", ".", "get_layout", "(", "opts", ".", "layout", ")", "head", ".", "sub!", "(", "/", "\\s", "/", ",", "\"title: #{opts.title}\"", ")", "head", ".", "sub!", "(", "/", "\\s", "/", ",", "\"date: #{@helper.get_date_stamp}\"", ")", "ext", "||=", "@ext", "path", "=", "File", ".", "join", "(", "DRAFTS_FOLDER", ",", "\"#{slug}.#{ext}\"", ")", "f", "=", "File", ".", "open", "(", "path", ",", "\"w\"", ")", "f", ".", "write", "(", "head", ")", "f", ".", "close", "@helper", ".", "open_in_editor", "(", "path", ")", "# open file if config key set", "path", "# return the path, in case we want to do anything useful", "end"], "docstring": "Generate a non-timestamped draft", "docstring_tokens": ["Generate", "a", "non", "-", "timestamped", "draft"], "sha": "442404c64dd931185ddf2e2345ce2e76994c910f", "url": "https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/commands.rb#L42-L67", "partition": "valid"} {"repo": "mmcclimon/mr_poole", "path": "lib/mr_poole/commands.rb", "func_name": "MrPoole.Commands.publish", "original_string": "def publish(draftpath, opts={})\n opts = @helper.ensure_open_struct(opts)\n tail = File.basename(draftpath)\n\n begin\n infile = File.open(draftpath, \"r\")\n rescue Errno::ENOENT\n @helper.bad_path(draftpath)\n end\n\n date = @helper.get_date_stamp\n time = @helper.get_time_stamp\n\n outpath = File.join(POSTS_FOLDER, \"#{date}-#{tail}\")\n outfile = File.open(outpath, \"w\")\n\n infile.each_line do |line|\n line.sub!(/^date:.*$/, \"date: #{date} #{time}\\n\") unless opts.keep_timestamp\n outfile.write(line)\n end\n\n infile.close\n outfile.close\n FileUtils.rm(draftpath) unless opts.keep_draft\n\n outpath\n end", "language": "ruby", "code": "def publish(draftpath, opts={})\n opts = @helper.ensure_open_struct(opts)\n tail = File.basename(draftpath)\n\n begin\n infile = File.open(draftpath, \"r\")\n rescue Errno::ENOENT\n @helper.bad_path(draftpath)\n end\n\n date = @helper.get_date_stamp\n time = @helper.get_time_stamp\n\n outpath = File.join(POSTS_FOLDER, \"#{date}-#{tail}\")\n outfile = File.open(outpath, \"w\")\n\n infile.each_line do |line|\n line.sub!(/^date:.*$/, \"date: #{date} #{time}\\n\") unless opts.keep_timestamp\n outfile.write(line)\n end\n\n infile.close\n outfile.close\n FileUtils.rm(draftpath) unless opts.keep_draft\n\n outpath\n end", "code_tokens": ["def", "publish", "(", "draftpath", ",", "opts", "=", "{", "}", ")", "opts", "=", "@helper", ".", "ensure_open_struct", "(", "opts", ")", "tail", "=", "File", ".", "basename", "(", "draftpath", ")", "begin", "infile", "=", "File", ".", "open", "(", "draftpath", ",", "\"r\"", ")", "rescue", "Errno", "::", "ENOENT", "@helper", ".", "bad_path", "(", "draftpath", ")", "end", "date", "=", "@helper", ".", "get_date_stamp", "time", "=", "@helper", ".", "get_time_stamp", "outpath", "=", "File", ".", "join", "(", "POSTS_FOLDER", ",", "\"#{date}-#{tail}\"", ")", "outfile", "=", "File", ".", "open", "(", "outpath", ",", "\"w\"", ")", "infile", ".", "each_line", "do", "|", "line", "|", "line", ".", "sub!", "(", "/", "/", ",", "\"date: #{date} #{time}\\n\"", ")", "unless", "opts", ".", "keep_timestamp", "outfile", ".", "write", "(", "line", ")", "end", "infile", ".", "close", "outfile", ".", "close", "FileUtils", ".", "rm", "(", "draftpath", ")", "unless", "opts", ".", "keep_draft", "outpath", "end"], "docstring": "Todo make this take a path instead?\n\n @param draftpath [String] path to the draft, relative to source directory\n @option options :keep_draft [Boolean] if true, keep the draft file\n @option options :keep_timestamp [Boolean] if true, don't change the timestamp", "docstring_tokens": ["Todo", "make", "this", "take", "a", "path", "instead?"], "sha": "442404c64dd931185ddf2e2345ce2e76994c910f", "url": "https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/commands.rb#L74-L100", "partition": "valid"} {"repo": "danopia/luck", "path": "lib/luck/ansi.rb", "func_name": "Luck.ANSIDriver.terminal_size", "original_string": "def terminal_size\n rows, cols = 25, 80\n buf = [0, 0, 0, 0].pack(\"SSSS\")\n if $stdout.ioctl(TIOCGWINSZ, buf) >= 0 then\n rows, cols, row_pixels, col_pixels = buf.unpack(\"SSSS\")\n end\n return [rows, cols]\n end", "language": "ruby", "code": "def terminal_size\n rows, cols = 25, 80\n buf = [0, 0, 0, 0].pack(\"SSSS\")\n if $stdout.ioctl(TIOCGWINSZ, buf) >= 0 then\n rows, cols, row_pixels, col_pixels = buf.unpack(\"SSSS\")\n end\n return [rows, cols]\n end", "code_tokens": ["def", "terminal_size", "rows", ",", "cols", "=", "25", ",", "80", "buf", "=", "[", "0", ",", "0", ",", "0", ",", "0", "]", ".", "pack", "(", "\"SSSS\"", ")", "if", "$stdout", ".", "ioctl", "(", "TIOCGWINSZ", ",", "buf", ")", ">=", "0", "then", "rows", ",", "cols", ",", "row_pixels", ",", "col_pixels", "=", "buf", ".", "unpack", "(", "\"SSSS\"", ")", "end", "return", "[", "rows", ",", "cols", "]", "end"], "docstring": "0000002\n thanks google for all of this", "docstring_tokens": ["0000002", "thanks", "google", "for", "all", "of", "this"], "sha": "70ffc07cfffc3c2cc81a4586198295ba13983212", "url": "https://github.com/danopia/luck/blob/70ffc07cfffc3c2cc81a4586198295ba13983212/lib/luck/ansi.rb#L185-L192", "partition": "valid"} {"repo": "danopia/luck", "path": "lib/luck/ansi.rb", "func_name": "Luck.ANSIDriver.prepare_modes", "original_string": "def prepare_modes\n buf = [0, 0, 0, 0, 0, 0, ''].pack(\"IIIICCA*\")\n $stdout.ioctl(TCGETS, buf)\n @old_modes = buf.unpack(\"IIIICCA*\")\n new_modes = @old_modes.clone\n new_modes[3] &= ~ECHO # echo off\n new_modes[3] &= ~ICANON # one char @ a time\n $stdout.ioctl(TCSETS, new_modes.pack(\"IIIICCA*\"))\n print \"\\e[2J\" # clear screen\n print \"\\e[H\" # go home\n print \"\\e[?47h\" # kick xterm into the alt screen\n print \"\\e[?1000h\" # kindly ask for mouse positions to make up for it\n self.cursor = false\n flush\n end", "language": "ruby", "code": "def prepare_modes\n buf = [0, 0, 0, 0, 0, 0, ''].pack(\"IIIICCA*\")\n $stdout.ioctl(TCGETS, buf)\n @old_modes = buf.unpack(\"IIIICCA*\")\n new_modes = @old_modes.clone\n new_modes[3] &= ~ECHO # echo off\n new_modes[3] &= ~ICANON # one char @ a time\n $stdout.ioctl(TCSETS, new_modes.pack(\"IIIICCA*\"))\n print \"\\e[2J\" # clear screen\n print \"\\e[H\" # go home\n print \"\\e[?47h\" # kick xterm into the alt screen\n print \"\\e[?1000h\" # kindly ask for mouse positions to make up for it\n self.cursor = false\n flush\n end", "code_tokens": ["def", "prepare_modes", "buf", "=", "[", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "''", "]", ".", "pack", "(", "\"IIIICCA*\"", ")", "$stdout", ".", "ioctl", "(", "TCGETS", ",", "buf", ")", "@old_modes", "=", "buf", ".", "unpack", "(", "\"IIIICCA*\"", ")", "new_modes", "=", "@old_modes", ".", "clone", "new_modes", "[", "3", "]", "&=", "~", "ECHO", "# echo off", "new_modes", "[", "3", "]", "&=", "~", "ICANON", "# one char @ a time", "$stdout", ".", "ioctl", "(", "TCSETS", ",", "new_modes", ".", "pack", "(", "\"IIIICCA*\"", ")", ")", "print", "\"\\e[2J\"", "# clear screen", "print", "\"\\e[H\"", "# go home", "print", "\"\\e[?47h\"", "# kick xterm into the alt screen", "print", "\"\\e[?1000h\"", "# kindly ask for mouse positions to make up for it", "self", ".", "cursor", "=", "false", "flush", "end"], "docstring": "had to convert these from C... fun", "docstring_tokens": ["had", "to", "convert", "these", "from", "C", "...", "fun"], "sha": "70ffc07cfffc3c2cc81a4586198295ba13983212", "url": "https://github.com/danopia/luck/blob/70ffc07cfffc3c2cc81a4586198295ba13983212/lib/luck/ansi.rb#L195-L209", "partition": "valid"} {"repo": "chall8908/cancancan_masquerade", "path": "lib/cancancan/masquerade.rb", "func_name": "CanCanCan.Masquerade.extract_subjects", "original_string": "def extract_subjects(subject)\n return extract_subjects(subject.to_permission_instance) if subject.respond_to? :to_permission_instance\n\n return subject[:any] if subject.is_a? Hash and subject.key? :any\n\n [subject]\n end", "language": "ruby", "code": "def extract_subjects(subject)\n return extract_subjects(subject.to_permission_instance) if subject.respond_to? :to_permission_instance\n\n return subject[:any] if subject.is_a? Hash and subject.key? :any\n\n [subject]\n end", "code_tokens": ["def", "extract_subjects", "(", "subject", ")", "return", "extract_subjects", "(", "subject", ".", "to_permission_instance", ")", "if", "subject", ".", "respond_to?", ":to_permission_instance", "return", "subject", "[", ":any", "]", "if", "subject", ".", "is_a?", "Hash", "and", "subject", ".", "key?", ":any", "[", "subject", "]", "end"], "docstring": "Override functionality from CanCan to allow objects to masquerade as other objects", "docstring_tokens": ["Override", "functionality", "from", "CanCan", "to", "allow", "objects", "to", "masquerade", "as", "other", "objects"], "sha": "60640f241e142639f90d88224cac84b3ea381a31", "url": "https://github.com/chall8908/cancancan_masquerade/blob/60640f241e142639f90d88224cac84b3ea381a31/lib/cancancan/masquerade.rb#L4-L10", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/controller.rb", "func_name": "NewRelicManagement.Controller.daemon", "original_string": "def daemon # rubocop: disable AbcSize, MethodLength\n # => Windows Workaround (https://github.com/bdwyertech/newrelic-management/issues/1)\n ENV['TZ'] = 'UTC' if OS.windows? && !ENV['TZ']\n\n scheduler = Rufus::Scheduler.new\n Notifier.msg('Daemonizing Process')\n\n # => Alerts Management\n alerts_interval = Config.alert_management_interval\n scheduler.every alerts_interval, overlap: false do\n Manager.manage_alerts\n end\n\n # => Cleanup Stale Servers\n if Config.cleanup\n cleanup_interval = Config.cleanup_interval\n cleanup_age = Config.cleanup_age\n\n scheduler.every cleanup_interval, overlap: false do\n Manager.remove_nonreporting_servers(cleanup_age)\n end\n end\n\n # => Join the Current Thread to the Scheduler Thread\n scheduler.join\n end", "language": "ruby", "code": "def daemon # rubocop: disable AbcSize, MethodLength\n # => Windows Workaround (https://github.com/bdwyertech/newrelic-management/issues/1)\n ENV['TZ'] = 'UTC' if OS.windows? && !ENV['TZ']\n\n scheduler = Rufus::Scheduler.new\n Notifier.msg('Daemonizing Process')\n\n # => Alerts Management\n alerts_interval = Config.alert_management_interval\n scheduler.every alerts_interval, overlap: false do\n Manager.manage_alerts\n end\n\n # => Cleanup Stale Servers\n if Config.cleanup\n cleanup_interval = Config.cleanup_interval\n cleanup_age = Config.cleanup_age\n\n scheduler.every cleanup_interval, overlap: false do\n Manager.remove_nonreporting_servers(cleanup_age)\n end\n end\n\n # => Join the Current Thread to the Scheduler Thread\n scheduler.join\n end", "code_tokens": ["def", "daemon", "# rubocop: disable AbcSize, MethodLength", "# => Windows Workaround (https://github.com/bdwyertech/newrelic-management/issues/1)", "ENV", "[", "'TZ'", "]", "=", "'UTC'", "if", "OS", ".", "windows?", "&&", "!", "ENV", "[", "'TZ'", "]", "scheduler", "=", "Rufus", "::", "Scheduler", ".", "new", "Notifier", ".", "msg", "(", "'Daemonizing Process'", ")", "# => Alerts Management", "alerts_interval", "=", "Config", ".", "alert_management_interval", "scheduler", ".", "every", "alerts_interval", ",", "overlap", ":", "false", "do", "Manager", ".", "manage_alerts", "end", "# => Cleanup Stale Servers", "if", "Config", ".", "cleanup", "cleanup_interval", "=", "Config", ".", "cleanup_interval", "cleanup_age", "=", "Config", ".", "cleanup_age", "scheduler", ".", "every", "cleanup_interval", ",", "overlap", ":", "false", "do", "Manager", ".", "remove_nonreporting_servers", "(", "cleanup_age", ")", "end", "end", "# => Join the Current Thread to the Scheduler Thread", "scheduler", ".", "join", "end"], "docstring": "=> Daemonization for Periodic Management", "docstring_tokens": ["=", ">", "Daemonization", "for", "Periodic", "Management"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/controller.rb#L23-L48", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/controller.rb", "func_name": "NewRelicManagement.Controller.run", "original_string": "def run\n daemon if Config.daemonize\n\n # => Manage Alerts\n Manager.manage_alerts\n\n # => Manage\n Manager.remove_nonreporting_servers(Config.cleanup_age) if Config.cleanup\n end", "language": "ruby", "code": "def run\n daemon if Config.daemonize\n\n # => Manage Alerts\n Manager.manage_alerts\n\n # => Manage\n Manager.remove_nonreporting_servers(Config.cleanup_age) if Config.cleanup\n end", "code_tokens": ["def", "run", "daemon", "if", "Config", ".", "daemonize", "# => Manage Alerts", "Manager", ".", "manage_alerts", "# => Manage", "Manager", ".", "remove_nonreporting_servers", "(", "Config", ".", "cleanup_age", ")", "if", "Config", ".", "cleanup", "end"], "docstring": "=> Run the Application", "docstring_tokens": ["=", ">", "Run", "the", "Application"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/controller.rb#L51-L59", "partition": "valid"} {"repo": "mmcclimon/mr_poole", "path": "lib/mr_poole/helper.rb", "func_name": "MrPoole.Helper.ensure_jekyll_dir", "original_string": "def ensure_jekyll_dir\n @orig_dir = Dir.pwd\n start_path = Pathname.new(@orig_dir)\n\n ok = File.exists?('./_posts')\n new_path = nil\n\n # if it doesn't exist, check for a custom source dir in _config.yml\n if !ok\n check_custom_src_dir!\n ok = File.exists?('./_posts')\n new_path = Pathname.new(Dir.pwd)\n end\n\n if ok\n return (new_path ? new_path.relative_path_from(start_path) : '.')\n else\n puts 'ERROR: Cannot locate _posts directory. Double check to make sure'\n puts ' that you are in a jekyll directory.'\n exit\n end\n end", "language": "ruby", "code": "def ensure_jekyll_dir\n @orig_dir = Dir.pwd\n start_path = Pathname.new(@orig_dir)\n\n ok = File.exists?('./_posts')\n new_path = nil\n\n # if it doesn't exist, check for a custom source dir in _config.yml\n if !ok\n check_custom_src_dir!\n ok = File.exists?('./_posts')\n new_path = Pathname.new(Dir.pwd)\n end\n\n if ok\n return (new_path ? new_path.relative_path_from(start_path) : '.')\n else\n puts 'ERROR: Cannot locate _posts directory. Double check to make sure'\n puts ' that you are in a jekyll directory.'\n exit\n end\n end", "code_tokens": ["def", "ensure_jekyll_dir", "@orig_dir", "=", "Dir", ".", "pwd", "start_path", "=", "Pathname", ".", "new", "(", "@orig_dir", ")", "ok", "=", "File", ".", "exists?", "(", "'./_posts'", ")", "new_path", "=", "nil", "# if it doesn't exist, check for a custom source dir in _config.yml", "if", "!", "ok", "check_custom_src_dir!", "ok", "=", "File", ".", "exists?", "(", "'./_posts'", ")", "new_path", "=", "Pathname", ".", "new", "(", "Dir", ".", "pwd", ")", "end", "if", "ok", "return", "(", "new_path", "?", "new_path", ".", "relative_path_from", "(", "start_path", ")", ":", "'.'", ")", "else", "puts", "'ERROR: Cannot locate _posts directory. Double check to make sure'", "puts", "' that you are in a jekyll directory.'", "exit", "end", "end"], "docstring": "Check for a _posts directory in current directory. If there's not one,\n check for a _config.yml and look for a custom src directory. If we\n don't find one, puke an error message and die. If we do, return the name\n of the directory", "docstring_tokens": ["Check", "for", "a", "_posts", "directory", "in", "current", "directory", ".", "If", "there", "s", "not", "one", "check", "for", "a", "_config", ".", "yml", "and", "look", "for", "a", "custom", "src", "directory", ".", "If", "we", "don", "t", "find", "one", "puke", "an", "error", "message", "and", "die", ".", "If", "we", "do", "return", "the", "name", "of", "the", "directory"], "sha": "442404c64dd931185ddf2e2345ce2e76994c910f", "url": "https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/helper.rb#L17-L38", "partition": "valid"} {"repo": "mmcclimon/mr_poole", "path": "lib/mr_poole/helper.rb", "func_name": "MrPoole.Helper.get_layout", "original_string": "def get_layout(layout_path)\n\n if layout_path.nil?\n contents = \"---\\n\"\n contents << \"title:\\n\"\n contents << \"layout: post\\n\"\n contents << \"date:\\n\"\n contents << \"---\\n\"\n ext = nil\n else\n begin\n contents = File.open(layout_path, \"r\").read()\n ext = layout_path.match(/\\.(.*?)$/)[1]\n rescue Errno::ENOENT\n bad_path(layout_path)\n end\n end\n\n return contents, ext\n end", "language": "ruby", "code": "def get_layout(layout_path)\n\n if layout_path.nil?\n contents = \"---\\n\"\n contents << \"title:\\n\"\n contents << \"layout: post\\n\"\n contents << \"date:\\n\"\n contents << \"---\\n\"\n ext = nil\n else\n begin\n contents = File.open(layout_path, \"r\").read()\n ext = layout_path.match(/\\.(.*?)$/)[1]\n rescue Errno::ENOENT\n bad_path(layout_path)\n end\n end\n\n return contents, ext\n end", "code_tokens": ["def", "get_layout", "(", "layout_path", ")", "if", "layout_path", ".", "nil?", "contents", "=", "\"---\\n\"", "contents", "<<", "\"title:\\n\"", "contents", "<<", "\"layout: post\\n\"", "contents", "<<", "\"date:\\n\"", "contents", "<<", "\"---\\n\"", "ext", "=", "nil", "else", "begin", "contents", "=", "File", ".", "open", "(", "layout_path", ",", "\"r\"", ")", ".", "read", "(", ")", "ext", "=", "layout_path", ".", "match", "(", "/", "\\.", "/", ")", "[", "1", "]", "rescue", "Errno", "::", "ENOENT", "bad_path", "(", "layout_path", ")", "end", "end", "return", "contents", ",", "ext", "end"], "docstring": "Get a layout as a string. If layout_path is non-nil, will open that\n file and read it, otherwise will return a default one, and a file\n extension to use", "docstring_tokens": ["Get", "a", "layout", "as", "a", "string", ".", "If", "layout_path", "is", "non", "-", "nil", "will", "open", "that", "file", "and", "read", "it", "otherwise", "will", "return", "a", "default", "one", "and", "a", "file", "extension", "to", "use"], "sha": "442404c64dd931185ddf2e2345ce2e76994c910f", "url": "https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/helper.rb#L51-L70", "partition": "valid"} {"repo": "mmcclimon/mr_poole", "path": "lib/mr_poole/helper.rb", "func_name": "MrPoole.Helper.gen_usage", "original_string": "def gen_usage\n puts 'Usage:'\n puts ' poole [ACTION] [ARG]'\n puts ''\n puts 'Actions:'\n puts ' draft Create a new draft in _drafts with title SLUG'\n puts ' post Create a new timestamped post in _posts with title SLUG'\n puts ' publish Publish the draft with SLUG, timestamping appropriately'\n puts ' unpublish Move a post to _drafts, untimestamping appropriately'\n exit\n end", "language": "ruby", "code": "def gen_usage\n puts 'Usage:'\n puts ' poole [ACTION] [ARG]'\n puts ''\n puts 'Actions:'\n puts ' draft Create a new draft in _drafts with title SLUG'\n puts ' post Create a new timestamped post in _posts with title SLUG'\n puts ' publish Publish the draft with SLUG, timestamping appropriately'\n puts ' unpublish Move a post to _drafts, untimestamping appropriately'\n exit\n end", "code_tokens": ["def", "gen_usage", "puts", "'Usage:'", "puts", "' poole [ACTION] [ARG]'", "puts", "''", "puts", "'Actions:'", "puts", "' draft Create a new draft in _drafts with title SLUG'", "puts", "' post Create a new timestamped post in _posts with title SLUG'", "puts", "' publish Publish the draft with SLUG, timestamping appropriately'", "puts", "' unpublish Move a post to _drafts, untimestamping appropriately'", "exit", "end"], "docstring": "Print a usage message and exit", "docstring_tokens": ["Print", "a", "usage", "message", "and", "exit"], "sha": "442404c64dd931185ddf2e2345ce2e76994c910f", "url": "https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/helper.rb#L120-L130", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/notifier.rb", "func_name": "NewRelicManagement.Notifier.msg", "original_string": "def msg(message, subtitle = message, title = 'NewRelic Management')\n # => Stdout Messages\n terminal_notification(message, subtitle)\n\n return if Config.silent\n\n # => Pretty GUI Messages\n osx_notification(message, subtitle, title) if OS.x?\n end", "language": "ruby", "code": "def msg(message, subtitle = message, title = 'NewRelic Management')\n # => Stdout Messages\n terminal_notification(message, subtitle)\n\n return if Config.silent\n\n # => Pretty GUI Messages\n osx_notification(message, subtitle, title) if OS.x?\n end", "code_tokens": ["def", "msg", "(", "message", ",", "subtitle", "=", "message", ",", "title", "=", "'NewRelic Management'", ")", "# => Stdout Messages", "terminal_notification", "(", "message", ",", "subtitle", ")", "return", "if", "Config", ".", "silent", "# => Pretty GUI Messages", "osx_notification", "(", "message", ",", "subtitle", ",", "title", ")", "if", "OS", ".", "x?", "end"], "docstring": "=> Primary Notification Message Controller", "docstring_tokens": ["=", ">", "Primary", "Notification", "Message", "Controller"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/notifier.rb#L23-L31", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/notifier.rb", "func_name": "NewRelicManagement.Notifier.osx_notification", "original_string": "def osx_notification(message, subtitle, title)\n TerminalNotifier.notify(message, title: title, subtitle: subtitle)\n end", "language": "ruby", "code": "def osx_notification(message, subtitle, title)\n TerminalNotifier.notify(message, title: title, subtitle: subtitle)\n end", "code_tokens": ["def", "osx_notification", "(", "message", ",", "subtitle", ",", "title", ")", "TerminalNotifier", ".", "notify", "(", "message", ",", "title", ":", "title", ",", "subtitle", ":", "subtitle", ")", "end"], "docstring": "=> OS X Cocoa Messages", "docstring_tokens": ["=", ">", "OS", "X", "Cocoa", "Messages"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/notifier.rb#L40-L42", "partition": "valid"} {"repo": "mlj/ruby-sfst", "path": "lib/sfst.rb", "func_name": "SFST.RegularTransducer.analyze", "original_string": "def analyze(string, options = {})\n x = []\n @fst._analyze(string) do |a| \n if options[:symbol_sequence]\n x << a.map { |s| s.match(/^<(.*)>$/) ? $1.to_sym : s }\n else\n x << a.join\n end\n end\n x\n end", "language": "ruby", "code": "def analyze(string, options = {})\n x = []\n @fst._analyze(string) do |a| \n if options[:symbol_sequence]\n x << a.map { |s| s.match(/^<(.*)>$/) ? $1.to_sym : s }\n else\n x << a.join\n end\n end\n x\n end", "code_tokens": ["def", "analyze", "(", "string", ",", "options", "=", "{", "}", ")", "x", "=", "[", "]", "@fst", ".", "_analyze", "(", "string", ")", "do", "|", "a", "|", "if", "options", "[", ":symbol_sequence", "]", "x", "<<", "a", ".", "map", "{", "|", "s", "|", "s", ".", "match", "(", "/", "/", ")", "?", "$1", ".", "to_sym", ":", "s", "}", "else", "x", "<<", "a", ".", "join", "end", "end", "x", "end"], "docstring": "Analyses a string +string+. Returns an array of analysed\n strings if the string is accepted, or an empty array if not.\n\n ==== Options\n * +symbol_sequence+ - Return each analysis as a sequence of symbols.\n Multicharacter symbols will be strings on the form ++.", "docstring_tokens": ["Analyses", "a", "string", "+", "string", "+", ".", "Returns", "an", "array", "of", "analysed", "strings", "if", "the", "string", "is", "accepted", "or", "an", "empty", "array", "if", "not", "."], "sha": "f3e1bc83d702f91d3d4792d622538938188af997", "url": "https://github.com/mlj/ruby-sfst/blob/f3e1bc83d702f91d3d4792d622538938188af997/lib/sfst.rb#L35-L45", "partition": "valid"} {"repo": "mlj/ruby-sfst", "path": "lib/sfst.rb", "func_name": "SFST.RegularTransducer.generate", "original_string": "def generate(string)\n x = []\n @fst._generate(string) { |a| x << a.join }\n x\n end", "language": "ruby", "code": "def generate(string)\n x = []\n @fst._generate(string) { |a| x << a.join }\n x\n end", "code_tokens": ["def", "generate", "(", "string", ")", "x", "=", "[", "]", "@fst", ".", "_generate", "(", "string", ")", "{", "|", "a", "|", "x", "<<", "a", ".", "join", "}", "x", "end"], "docstring": "Generates a string +string+. Returns an array of generated\n strings if the string is accepted or an empty array if not.", "docstring_tokens": ["Generates", "a", "string", "+", "string", "+", ".", "Returns", "an", "array", "of", "generated", "strings", "if", "the", "string", "is", "accepted", "or", "an", "empty", "array", "if", "not", "."], "sha": "f3e1bc83d702f91d3d4792d622538938188af997", "url": "https://github.com/mlj/ruby-sfst/blob/f3e1bc83d702f91d3d4792d622538938188af997/lib/sfst.rb#L54-L58", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/cli.rb", "func_name": "NewRelicManagement.CLI.configure", "original_string": "def configure(argv = ARGV)\n # => Parse CLI Configuration\n cli = Options.new\n cli.parse_options(argv)\n\n # => Parse JSON Config File (If Specified and Exists)\n json_config = Util.parse_json(cli.config[:config_file] || Config.config_file)\n\n # => Merge Configuration (CLI Wins)\n config = [json_config, cli.config].compact.reduce(:merge)\n\n # => Apply Configuration\n config.each { |k, v| Config.send(\"#{k}=\", v) }\n end", "language": "ruby", "code": "def configure(argv = ARGV)\n # => Parse CLI Configuration\n cli = Options.new\n cli.parse_options(argv)\n\n # => Parse JSON Config File (If Specified and Exists)\n json_config = Util.parse_json(cli.config[:config_file] || Config.config_file)\n\n # => Merge Configuration (CLI Wins)\n config = [json_config, cli.config].compact.reduce(:merge)\n\n # => Apply Configuration\n config.each { |k, v| Config.send(\"#{k}=\", v) }\n end", "code_tokens": ["def", "configure", "(", "argv", "=", "ARGV", ")", "# => Parse CLI Configuration", "cli", "=", "Options", ".", "new", "cli", ".", "parse_options", "(", "argv", ")", "# => Parse JSON Config File (If Specified and Exists)", "json_config", "=", "Util", ".", "parse_json", "(", "cli", ".", "config", "[", ":config_file", "]", "||", "Config", ".", "config_file", ")", "# => Merge Configuration (CLI Wins)", "config", "=", "[", "json_config", ",", "cli", ".", "config", "]", ".", "compact", ".", "reduce", "(", ":merge", ")", "# => Apply Configuration", "config", ".", "each", "{", "|", "k", ",", "v", "|", "Config", ".", "send", "(", "\"#{k}=\"", ",", "v", ")", "}", "end"], "docstring": "=> Configure the CLI", "docstring_tokens": ["=", ">", "Configure", "the", "CLI"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/cli.rb#L67-L80", "partition": "valid"} {"repo": "robertodecurnex/spectro", "path": "lib/spectro/compiler.rb", "func_name": "Spectro.Compiler.missing_specs_from_file", "original_string": "def missing_specs_from_file(path)\n Spectro::Spec::Parser.parse(path).select do |spec|\n index_spec = Spectro::Database.index[path] && Spectro::Database.index[path][spec.signature.name]\n index_spec.nil? || index_spec['spec_md5'] != spec.md5\n end\n end", "language": "ruby", "code": "def missing_specs_from_file(path)\n Spectro::Spec::Parser.parse(path).select do |spec|\n index_spec = Spectro::Database.index[path] && Spectro::Database.index[path][spec.signature.name]\n index_spec.nil? || index_spec['spec_md5'] != spec.md5\n end\n end", "code_tokens": ["def", "missing_specs_from_file", "(", "path", ")", "Spectro", "::", "Spec", "::", "Parser", ".", "parse", "(", "path", ")", ".", "select", "do", "|", "spec", "|", "index_spec", "=", "Spectro", "::", "Database", ".", "index", "[", "path", "]", "&&", "Spectro", "::", "Database", ".", "index", "[", "path", "]", "[", "spec", ".", "signature", ".", "name", "]", "index_spec", ".", "nil?", "||", "index_spec", "[", "'spec_md5'", "]", "!=", "spec", ".", "md5", "end", "end"], "docstring": "Parse the specs on the given file path and return those\n that have not been fulfilled or need to be updated.\n\n @param [String] path target file path\n @return [] collection of specs not fulfilled or out of date", "docstring_tokens": ["Parse", "the", "specs", "on", "the", "given", "file", "path", "and", "return", "those", "that", "have", "not", "been", "fulfilled", "or", "need", "to", "be", "updated", "."], "sha": "0c9945659e6eb00c7ff026a5065cdbd9a74f119f", "url": "https://github.com/robertodecurnex/spectro/blob/0c9945659e6eb00c7ff026a5065cdbd9a74f119f/lib/spectro/compiler.rb#L87-L92", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/manager.rb", "func_name": "NewRelicManagement.Manager.remove_nonreporting_servers", "original_string": "def remove_nonreporting_servers(keeptime = nil)\n list_nonreporting_servers.each do |server|\n next if keeptime && Time.parse(server[:last_reported_at]) >= Time.now - ChronicDuration.parse(keeptime)\n Notifier.msg(server[:name], 'Removing Stale, Non-Reporting Server')\n Client.delete_server(server[:id])\n end\n end", "language": "ruby", "code": "def remove_nonreporting_servers(keeptime = nil)\n list_nonreporting_servers.each do |server|\n next if keeptime && Time.parse(server[:last_reported_at]) >= Time.now - ChronicDuration.parse(keeptime)\n Notifier.msg(server[:name], 'Removing Stale, Non-Reporting Server')\n Client.delete_server(server[:id])\n end\n end", "code_tokens": ["def", "remove_nonreporting_servers", "(", "keeptime", "=", "nil", ")", "list_nonreporting_servers", ".", "each", "do", "|", "server", "|", "next", "if", "keeptime", "&&", "Time", ".", "parse", "(", "server", "[", ":last_reported_at", "]", ")", ">=", "Time", ".", "now", "-", "ChronicDuration", ".", "parse", "(", "keeptime", ")", "Notifier", ".", "msg", "(", "server", "[", ":name", "]", ",", "'Removing Stale, Non-Reporting Server'", ")", "Client", ".", "delete_server", "(", "server", "[", ":id", "]", ")", "end", "end"], "docstring": "=> Remove Non-Reporting Servers", "docstring_tokens": ["=", ">", "Remove", "Non", "-", "Reporting", "Servers"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/manager.rb#L119-L125", "partition": "valid"} {"repo": "bdwyertech/newrelic-management", "path": "lib/newrelic-management/manager.rb", "func_name": "NewRelicManagement.Manager.find_excluded", "original_string": "def find_excluded(excluded)\n result = []\n Array(excluded).each do |exclude|\n if exclude.include?(':')\n find_labeled(exclude).each { |x| result << x }\n next\n end\n res = Client.get_server(exclude)\n result << res['id'] if res\n end\n result\n end", "language": "ruby", "code": "def find_excluded(excluded)\n result = []\n Array(excluded).each do |exclude|\n if exclude.include?(':')\n find_labeled(exclude).each { |x| result << x }\n next\n end\n res = Client.get_server(exclude)\n result << res['id'] if res\n end\n result\n end", "code_tokens": ["def", "find_excluded", "(", "excluded", ")", "result", "=", "[", "]", "Array", "(", "excluded", ")", ".", "each", "do", "|", "exclude", "|", "if", "exclude", ".", "include?", "(", "':'", ")", "find_labeled", "(", "exclude", ")", ".", "each", "{", "|", "x", "|", "result", "<<", "x", "}", "next", "end", "res", "=", "Client", ".", "get_server", "(", "exclude", ")", "result", "<<", "res", "[", "'id'", "]", "if", "res", "end", "result", "end"], "docstring": "=> Find Servers which should be excluded from Management", "docstring_tokens": ["=", ">", "Find", "Servers", "which", "should", "be", "excluded", "from", "Management"], "sha": "265f0024b52d1fed476f35448b6b518453b4b1a6", "url": "https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/manager.rb#L128-L139", "partition": "valid"} {"repo": "JackDanger/twilio_contactable", "path": "lib/contactable.rb", "func_name": "TwilioContactable.Contactable.send_sms_confirmation!", "original_string": "def send_sms_confirmation!\n return false if _TC_sms_blocked\n return true if sms_confirmed?\n return false if _TC_phone_number.blank?\n\n format_phone_number\n confirmation_code = TwilioContactable.confirmation_code(self, :sms)\n\n # Use this class' confirmation_message method if it\n # exists, otherwise use the generic message\n message = (self.class.respond_to?(:confirmation_message) ?\n self.class :\n TwilioContactable).confirmation_message(confirmation_code)\n\n if message.to_s.size > 160\n raise ArgumentError, \"SMS Confirmation Message is too long. Limit it to 160 characters of unescaped text.\"\n end\n\n response = TwilioContactable::Gateway.deliver_sms(message, _TC_formatted_phone_number)\n\n if response.success?\n update_twilio_contactable_sms_confirmation confirmation_code\n end\n\n response\n end", "language": "ruby", "code": "def send_sms_confirmation!\n return false if _TC_sms_blocked\n return true if sms_confirmed?\n return false if _TC_phone_number.blank?\n\n format_phone_number\n confirmation_code = TwilioContactable.confirmation_code(self, :sms)\n\n # Use this class' confirmation_message method if it\n # exists, otherwise use the generic message\n message = (self.class.respond_to?(:confirmation_message) ?\n self.class :\n TwilioContactable).confirmation_message(confirmation_code)\n\n if message.to_s.size > 160\n raise ArgumentError, \"SMS Confirmation Message is too long. Limit it to 160 characters of unescaped text.\"\n end\n\n response = TwilioContactable::Gateway.deliver_sms(message, _TC_formatted_phone_number)\n\n if response.success?\n update_twilio_contactable_sms_confirmation confirmation_code\n end\n\n response\n end", "code_tokens": ["def", "send_sms_confirmation!", "return", "false", "if", "_TC_sms_blocked", "return", "true", "if", "sms_confirmed?", "return", "false", "if", "_TC_phone_number", ".", "blank?", "format_phone_number", "confirmation_code", "=", "TwilioContactable", ".", "confirmation_code", "(", "self", ",", ":sms", ")", "# Use this class' confirmation_message method if it", "# exists, otherwise use the generic message", "message", "=", "(", "self", ".", "class", ".", "respond_to?", "(", ":confirmation_message", ")", "?", "self", ".", "class", ":", "TwilioContactable", ")", ".", "confirmation_message", "(", "confirmation_code", ")", "if", "message", ".", "to_s", ".", "size", ">", "160", "raise", "ArgumentError", ",", "\"SMS Confirmation Message is too long. Limit it to 160 characters of unescaped text.\"", "end", "response", "=", "TwilioContactable", "::", "Gateway", ".", "deliver_sms", "(", "message", ",", "_TC_formatted_phone_number", ")", "if", "response", ".", "success?", "update_twilio_contactable_sms_confirmation", "confirmation_code", "end", "response", "end"], "docstring": "Sends an SMS validation request through the gateway", "docstring_tokens": ["Sends", "an", "SMS", "validation", "request", "through", "the", "gateway"], "sha": "a3ec81c6d9c34dec767642d1dfb76a65ce0929db", "url": "https://github.com/JackDanger/twilio_contactable/blob/a3ec81c6d9c34dec767642d1dfb76a65ce0929db/lib/contactable.rb#L86-L111", "partition": "valid"} {"repo": "JackDanger/twilio_contactable", "path": "lib/contactable.rb", "func_name": "TwilioContactable.Contactable.send_voice_confirmation!", "original_string": "def send_voice_confirmation!\n return false if _TC_voice_blocked\n return true if voice_confirmed?\n return false if _TC_phone_number.blank?\n\n format_phone_number\n confirmation_code = TwilioContactable.confirmation_code(self, :voice)\n\n response = TwilioContactable::Gateway.initiate_voice_call(self, _TC_formatted_phone_number)\n\n if response.success?\n update_twilio_contactable_voice_confirmation confirmation_code\n end\n\n response\n end", "language": "ruby", "code": "def send_voice_confirmation!\n return false if _TC_voice_blocked\n return true if voice_confirmed?\n return false if _TC_phone_number.blank?\n\n format_phone_number\n confirmation_code = TwilioContactable.confirmation_code(self, :voice)\n\n response = TwilioContactable::Gateway.initiate_voice_call(self, _TC_formatted_phone_number)\n\n if response.success?\n update_twilio_contactable_voice_confirmation confirmation_code\n end\n\n response\n end", "code_tokens": ["def", "send_voice_confirmation!", "return", "false", "if", "_TC_voice_blocked", "return", "true", "if", "voice_confirmed?", "return", "false", "if", "_TC_phone_number", ".", "blank?", "format_phone_number", "confirmation_code", "=", "TwilioContactable", ".", "confirmation_code", "(", "self", ",", ":voice", ")", "response", "=", "TwilioContactable", "::", "Gateway", ".", "initiate_voice_call", "(", "self", ",", "_TC_formatted_phone_number", ")", "if", "response", ".", "success?", "update_twilio_contactable_voice_confirmation", "confirmation_code", "end", "response", "end"], "docstring": "Begins a phone call to the user where they'll need to type\n their confirmation code", "docstring_tokens": ["Begins", "a", "phone", "call", "to", "the", "user", "where", "they", "ll", "need", "to", "type", "their", "confirmation", "code"], "sha": "a3ec81c6d9c34dec767642d1dfb76a65ce0929db", "url": "https://github.com/JackDanger/twilio_contactable/blob/a3ec81c6d9c34dec767642d1dfb76a65ce0929db/lib/contactable.rb#L115-L130", "partition": "valid"} {"repo": "sosedoff/terminal_helpers", "path": "lib/terminal_helpers/validations.rb", "func_name": "TerminalHelpers.Validations.validate", "original_string": "def validate(value, format, raise_error=false)\n unless FORMATS.key?(format)\n raise FormatError, \"Invalid data format: #{format}\"\n end\n result = value =~ FORMATS[format] ? true : false\n if raise_error && !result\n raise ValidationError, \"Invalid value \\\"#{value}\\\" for #{format}\"\n end\n result\n end", "language": "ruby", "code": "def validate(value, format, raise_error=false)\n unless FORMATS.key?(format)\n raise FormatError, \"Invalid data format: #{format}\"\n end\n result = value =~ FORMATS[format] ? true : false\n if raise_error && !result\n raise ValidationError, \"Invalid value \\\"#{value}\\\" for #{format}\"\n end\n result\n end", "code_tokens": ["def", "validate", "(", "value", ",", "format", ",", "raise_error", "=", "false", ")", "unless", "FORMATS", ".", "key?", "(", "format", ")", "raise", "FormatError", ",", "\"Invalid data format: #{format}\"", "end", "result", "=", "value", "=~", "FORMATS", "[", "format", "]", "?", "true", ":", "false", "if", "raise_error", "&&", "!", "result", "raise", "ValidationError", ",", "\"Invalid value \\\"#{value}\\\" for #{format}\"", "end", "result", "end"], "docstring": "Validate data against provided format", "docstring_tokens": ["Validate", "data", "against", "provided", "format"], "sha": "7822b28b4f97b31786a149599514a0bc5c8f3cce", "url": "https://github.com/sosedoff/terminal_helpers/blob/7822b28b4f97b31786a149599514a0bc5c8f3cce/lib/terminal_helpers/validations.rb#L14-L23", "partition": "valid"} {"repo": "vyorkin-personal/xftp", "path": "lib/xftp/client.rb", "func_name": "XFTP.Client.call", "original_string": "def call(url, settings, &block)\n uri = URI.parse(url)\n klass = adapter_class(uri.scheme)\n session = klass.new(uri, settings.deep_dup)\n session.start(&block)\n end", "language": "ruby", "code": "def call(url, settings, &block)\n uri = URI.parse(url)\n klass = adapter_class(uri.scheme)\n session = klass.new(uri, settings.deep_dup)\n session.start(&block)\n end", "code_tokens": ["def", "call", "(", "url", ",", "settings", ",", "&", "block", ")", "uri", "=", "URI", ".", "parse", "(", "url", ")", "klass", "=", "adapter_class", "(", "uri", ".", "scheme", ")", "session", "=", "klass", ".", "new", "(", "uri", ",", "settings", ".", "deep_dup", ")", "session", ".", "start", "(", "block", ")", "end"], "docstring": "Initiates a new session\n @see XFTP::Validator::Settings", "docstring_tokens": ["Initiates", "a", "new", "session"], "sha": "91a3185f60b02d5db951d5c3c0ae18c86a131a79", "url": "https://github.com/vyorkin-personal/xftp/blob/91a3185f60b02d5db951d5c3c0ae18c86a131a79/lib/xftp/client.rb#L23-L28", "partition": "valid"} {"repo": "bkerley/miami_dade_geo", "path": "lib/miami_dade_geo/geo_attribute_client.rb", "func_name": "MiamiDadeGeo.GeoAttributeClient.all_fields", "original_string": "def all_fields(table, field_name, value)\n body = savon.\n call(:get_all_fields_records_given_a_field_name_and_value,\n message: {\n 'strFeatureClassOrTableName' => table,\n 'strFieldNameToSearchOn' => field_name,\n 'strValueOfFieldToSearchOn' => value\n }).\n body\n\n resp = body[:get_all_fields_records_given_a_field_name_and_value_response]\n rslt = resp[:get_all_fields_records_given_a_field_name_and_value_result]\n polys = rslt[:diffgram][:document_element][:municipality_poly]\n\n poly = if polys.is_a? Array\n polys.first\n elsif polys.is_a? Hash\n polys\n else\n fail \"Unexpected polys #{polys.class.name}, wanted Array or Hash\"\n end\n end", "language": "ruby", "code": "def all_fields(table, field_name, value)\n body = savon.\n call(:get_all_fields_records_given_a_field_name_and_value,\n message: {\n 'strFeatureClassOrTableName' => table,\n 'strFieldNameToSearchOn' => field_name,\n 'strValueOfFieldToSearchOn' => value\n }).\n body\n\n resp = body[:get_all_fields_records_given_a_field_name_and_value_response]\n rslt = resp[:get_all_fields_records_given_a_field_name_and_value_result]\n polys = rslt[:diffgram][:document_element][:municipality_poly]\n\n poly = if polys.is_a? Array\n polys.first\n elsif polys.is_a? Hash\n polys\n else\n fail \"Unexpected polys #{polys.class.name}, wanted Array or Hash\"\n end\n end", "code_tokens": ["def", "all_fields", "(", "table", ",", "field_name", ",", "value", ")", "body", "=", "savon", ".", "call", "(", ":get_all_fields_records_given_a_field_name_and_value", ",", "message", ":", "{", "'strFeatureClassOrTableName'", "=>", "table", ",", "'strFieldNameToSearchOn'", "=>", "field_name", ",", "'strValueOfFieldToSearchOn'", "=>", "value", "}", ")", ".", "body", "resp", "=", "body", "[", ":get_all_fields_records_given_a_field_name_and_value_response", "]", "rslt", "=", "resp", "[", ":get_all_fields_records_given_a_field_name_and_value_result", "]", "polys", "=", "rslt", "[", ":diffgram", "]", "[", ":document_element", "]", "[", ":municipality_poly", "]", "poly", "=", "if", "polys", ".", "is_a?", "Array", "polys", ".", "first", "elsif", "polys", ".", "is_a?", "Hash", "polys", "else", "fail", "\"Unexpected polys #{polys.class.name}, wanted Array or Hash\"", "end", "end"], "docstring": "Performs a search for geo-attributes.\n\n @param [String] table the table to search\n @param [String] field_name the field/column to search in the given table\n @param [String] value string value to search in the given field and table\n @return [Hash] search results", "docstring_tokens": ["Performs", "a", "search", "for", "geo", "-", "attributes", "."], "sha": "024478a898dca2c6f07c312cfc531112e88daa0b", "url": "https://github.com/bkerley/miami_dade_geo/blob/024478a898dca2c6f07c312cfc531112e88daa0b/lib/miami_dade_geo/geo_attribute_client.rb#L22-L43", "partition": "valid"} {"repo": "kachick/validation", "path": "lib/validation/adjustment.rb", "func_name": "Validation.Adjustment.WHEN", "original_string": "def WHEN(condition, adjuster)\n unless Validation.conditionable? condition\n raise TypeError, 'wrong object for condition'\n end\n\n unless Validation.adjustable? adjuster\n raise TypeError, 'wrong object for adjuster'\n end\n\n ->v{_valid?(condition, v) ? adjuster.call(v) : v}\n end", "language": "ruby", "code": "def WHEN(condition, adjuster)\n unless Validation.conditionable? condition\n raise TypeError, 'wrong object for condition'\n end\n\n unless Validation.adjustable? adjuster\n raise TypeError, 'wrong object for adjuster'\n end\n\n ->v{_valid?(condition, v) ? adjuster.call(v) : v}\n end", "code_tokens": ["def", "WHEN", "(", "condition", ",", "adjuster", ")", "unless", "Validation", ".", "conditionable?", "condition", "raise", "TypeError", ",", "'wrong object for condition'", "end", "unless", "Validation", ".", "adjustable?", "adjuster", "raise", "TypeError", ",", "'wrong object for adjuster'", "end", "->", "v", "{", "_valid?", "(", "condition", ",", "v", ")", "?", "adjuster", ".", "call", "(", "v", ")", ":", "v", "}", "end"], "docstring": "Adjuster Builders\n Apply adjuster when passed condition.\n @param condition [Proc, Method, #===]\n @param adjuster [Proc, #to_proc]\n @return [lambda]", "docstring_tokens": ["Adjuster", "Builders", "Apply", "adjuster", "when", "passed", "condition", "."], "sha": "43390cb6d9adc45c2f040d59f22ee514629309e6", "url": "https://github.com/kachick/validation/blob/43390cb6d9adc45c2f040d59f22ee514629309e6/lib/validation/adjustment.rb#L29-L39", "partition": "valid"} {"repo": "kachick/validation", "path": "lib/validation/adjustment.rb", "func_name": "Validation.Adjustment.INJECT", "original_string": "def INJECT(adjuster1, adjuster2, *adjusters)\n adjusters = [adjuster1, adjuster2, *adjusters]\n\n unless adjusters.all?{|f|adjustable? f}\n raise TypeError, 'wrong object for adjuster'\n end\n\n ->v{\n adjusters.reduce(v){|ret, adjuster|adjuster.call ret}\n }\n end", "language": "ruby", "code": "def INJECT(adjuster1, adjuster2, *adjusters)\n adjusters = [adjuster1, adjuster2, *adjusters]\n\n unless adjusters.all?{|f|adjustable? f}\n raise TypeError, 'wrong object for adjuster'\n end\n\n ->v{\n adjusters.reduce(v){|ret, adjuster|adjuster.call ret}\n }\n end", "code_tokens": ["def", "INJECT", "(", "adjuster1", ",", "adjuster2", ",", "*", "adjusters", ")", "adjusters", "=", "[", "adjuster1", ",", "adjuster2", ",", "adjusters", "]", "unless", "adjusters", ".", "all?", "{", "|", "f", "|", "adjustable?", "f", "}", "raise", "TypeError", ",", "'wrong object for adjuster'", "end", "->", "v", "{", "adjusters", ".", "reduce", "(", "v", ")", "{", "|", "ret", ",", "adjuster", "|", "adjuster", ".", "call", "ret", "}", "}", "end"], "docstring": "Sequencial apply all adjusters.\n @param adjuster1 [Proc, #to_proc]\n @param adjuster2 [Proc, #to_proc]\n @param adjusters [Proc, #to_proc]\n @return [lambda]", "docstring_tokens": ["Sequencial", "apply", "all", "adjusters", "."], "sha": "43390cb6d9adc45c2f040d59f22ee514629309e6", "url": "https://github.com/kachick/validation/blob/43390cb6d9adc45c2f040d59f22ee514629309e6/lib/validation/adjustment.rb#L46-L56", "partition": "valid"} {"repo": "kachick/validation", "path": "lib/validation/adjustment.rb", "func_name": "Validation.Adjustment.PARSE", "original_string": "def PARSE(parser)\n if !::Integer.equal?(parser) and !parser.respond_to?(:parse)\n raise TypeError, 'wrong object for parser'\n end\n\n ->v{\n if ::Integer.equal? parser\n ::Kernel.Integer v\n else\n parser.parse(\n case v\n when String\n v\n when ->_{v.respond_to? :to_str}\n v.to_str\n when ->_{v.respond_to? :read}\n v.read\n else\n raise TypeError, 'wrong object for parsing source'\n end\n )\n end\n }\n end", "language": "ruby", "code": "def PARSE(parser)\n if !::Integer.equal?(parser) and !parser.respond_to?(:parse)\n raise TypeError, 'wrong object for parser'\n end\n\n ->v{\n if ::Integer.equal? parser\n ::Kernel.Integer v\n else\n parser.parse(\n case v\n when String\n v\n when ->_{v.respond_to? :to_str}\n v.to_str\n when ->_{v.respond_to? :read}\n v.read\n else\n raise TypeError, 'wrong object for parsing source'\n end\n )\n end\n }\n end", "code_tokens": ["def", "PARSE", "(", "parser", ")", "if", "!", "::", "Integer", ".", "equal?", "(", "parser", ")", "and", "!", "parser", ".", "respond_to?", "(", ":parse", ")", "raise", "TypeError", ",", "'wrong object for parser'", "end", "->", "v", "{", "if", "::", "Integer", ".", "equal?", "parser", "::", "Kernel", ".", "Integer", "v", "else", "parser", ".", "parse", "(", "case", "v", "when", "String", "v", "when", "->", "_", "{", "v", ".", "respond_to?", ":to_str", "}", "v", ".", "to_str", "when", "->", "_", "{", "v", ".", "respond_to?", ":read", "}", "v", ".", "read", "else", "raise", "TypeError", ",", "'wrong object for parsing source'", "end", ")", "end", "}", "end"], "docstring": "Accept any parser when that resopond to parse method.\n @param parser [#parse]\n @return [lambda]", "docstring_tokens": ["Accept", "any", "parser", "when", "that", "resopond", "to", "parse", "method", "."], "sha": "43390cb6d9adc45c2f040d59f22ee514629309e6", "url": "https://github.com/kachick/validation/blob/43390cb6d9adc45c2f040d59f22ee514629309e6/lib/validation/adjustment.rb#L61-L84", "partition": "valid"} {"repo": "zhimin/rformspec", "path": "lib/rformspec/window.rb", "func_name": "RFormSpec.Window.get_class", "original_string": "def get_class(name)\n @class_list = get_class_list\n @class_list.select {|x| x.include?(name)}.collect{|y| y.strip}\n end", "language": "ruby", "code": "def get_class(name)\n @class_list = get_class_list\n @class_list.select {|x| x.include?(name)}.collect{|y| y.strip}\n end", "code_tokens": ["def", "get_class", "(", "name", ")", "@class_list", "=", "get_class_list", "@class_list", ".", "select", "{", "|", "x", "|", "x", ".", "include?", "(", "name", ")", "}", ".", "collect", "{", "|", "y", "|", "y", ".", "strip", "}", "end"], "docstring": "return the class match by name", "docstring_tokens": ["return", "the", "class", "match", "by", "name"], "sha": "756e89cb730b2ec25564c6243fdcd3e81bd93649", "url": "https://github.com/zhimin/rformspec/blob/756e89cb730b2ec25564c6243fdcd3e81bd93649/lib/rformspec/window.rb#L121-L124", "partition": "valid"} {"repo": "megamsys/megam_scmmanager.rb", "path": "lib/megam/scmmanager.rb", "func_name": "Megam.Scmmanager.connection", "original_string": "def connection\n @options[:path] =API_REST + @options[:path]\n @options[:headers] = HEADERS.merge({\n 'X-Megam-Date' => Time.now.strftime(\"%Y-%m-%d %H:%M\")\n }).merge(@options[:headers])\n\n text.info(\"HTTP Request Data:\")\n text.msg(\"> HTTP #{@options[:scheme]}://#{@options[:host]}\")\n @options.each do |key, value|\n text.msg(\"> #{key}: #{value}\")\n end\n text.info(\"End HTTP Request Data.\")\n http = Net::HTTP.new(@options[:host], @options[:port])\n http\n end", "language": "ruby", "code": "def connection\n @options[:path] =API_REST + @options[:path]\n @options[:headers] = HEADERS.merge({\n 'X-Megam-Date' => Time.now.strftime(\"%Y-%m-%d %H:%M\")\n }).merge(@options[:headers])\n\n text.info(\"HTTP Request Data:\")\n text.msg(\"> HTTP #{@options[:scheme]}://#{@options[:host]}\")\n @options.each do |key, value|\n text.msg(\"> #{key}: #{value}\")\n end\n text.info(\"End HTTP Request Data.\")\n http = Net::HTTP.new(@options[:host], @options[:port])\n http\n end", "code_tokens": ["def", "connection", "@options", "[", ":path", "]", "=", "API_REST", "+", "@options", "[", ":path", "]", "@options", "[", ":headers", "]", "=", "HEADERS", ".", "merge", "(", "{", "'X-Megam-Date'", "=>", "Time", ".", "now", ".", "strftime", "(", "\"%Y-%m-%d %H:%M\"", ")", "}", ")", ".", "merge", "(", "@options", "[", ":headers", "]", ")", "text", ".", "info", "(", "\"HTTP Request Data:\"", ")", "text", ".", "msg", "(", "\"> HTTP #{@options[:scheme]}://#{@options[:host]}\"", ")", "@options", ".", "each", "do", "|", "key", ",", "value", "|", "text", ".", "msg", "(", "\"> #{key}: #{value}\"", ")", "end", "text", ".", "info", "(", "\"End HTTP Request Data.\"", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "@options", "[", ":host", "]", ",", "@options", "[", ":port", "]", ")", "http", "end"], "docstring": "Make a lazy connection.", "docstring_tokens": ["Make", "a", "lazy", "connection", "."], "sha": "fae0fe0f9519dabd3625e5fdc0b24006de5746fb", "url": "https://github.com/megamsys/megam_scmmanager.rb/blob/fae0fe0f9519dabd3625e5fdc0b24006de5746fb/lib/megam/scmmanager.rb#L78-L92", "partition": "valid"} {"repo": "robfors/quack_concurrency", "path": "lib/quack_concurrency/safe_sleeper.rb", "func_name": "QuackConcurrency.SafeSleeper.wake_deadline", "original_string": "def wake_deadline(start_time, timeout)\n timeout = process_timeout(timeout)\n deadline = start_time + timeout if timeout\n end", "language": "ruby", "code": "def wake_deadline(start_time, timeout)\n timeout = process_timeout(timeout)\n deadline = start_time + timeout if timeout\n end", "code_tokens": ["def", "wake_deadline", "(", "start_time", ",", "timeout", ")", "timeout", "=", "process_timeout", "(", "timeout", ")", "deadline", "=", "start_time", "+", "timeout", "if", "timeout", "end"], "docstring": "Calculate the desired time to wake up.\n @api private\n @param start_time [nil,Time] time when the thread is put to sleep\n @param timeout [Numeric] desired time to sleep in seconds, +nil+ for forever\n @raise [TypeError] if +start_time+ is not +nil+ or a +Numeric+\n @raise [ArgumentError] if +start_time+ is negative\n @return [Time]", "docstring_tokens": ["Calculate", "the", "desired", "time", "to", "wake", "up", "."], "sha": "fb42bbd48b4e4994297431e926bbbcc777a3cd08", "url": "https://github.com/robfors/quack_concurrency/blob/fb42bbd48b4e4994297431e926bbbcc777a3cd08/lib/quack_concurrency/safe_sleeper.rb#L74-L77", "partition": "valid"} {"repo": "CoralineAda/mir_extensions", "path": "lib/mir_extensions.rb", "func_name": "MirExtensions.HelperExtensions.crud_links", "original_string": "def crud_links(model, instance_name, actions, args={})\n _html = \"\"\n _options = args.keys.empty? ? '' : \", #{args.map{|k,v| \":#{k} => #{v}\"}}\"\n \n if use_crud_icons\n if actions.include?(:show)\n _html << eval(\"link_to image_tag('/images/icons/view.png', :class => 'crud_icon'), model, :title => 'View'#{_options}\")\n end\n if actions.include?(:edit)\n _html << eval(\"link_to image_tag('/images/icons/edit.png', :class => 'crud_icon'), edit_#{instance_name}_path(model), :title => 'Edit'#{_options}\")\n end\n if actions.include?(:delete)\n _html << eval(\"link_to image_tag('/images/icons/delete.png', :class => 'crud_icon'), model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete'#{_options}\")\n end\n else\n if actions.include?(:show)\n _html << eval(\"link_to 'View', model, :title => 'View', :class => 'crud_link'#{_options}\")\n end\n if actions.include?(:edit)\n _html << eval(\"link_to 'Edit', edit_#{instance_name}_path(model), :title => 'Edit', :class => 'crud_link'#{_options}\")\n end\n if actions.include?(:delete)\n _html << eval(\"link_to 'Delete', model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete', :class => 'crud_link'#{_options}\")\n end\n end\n _html\n end", "language": "ruby", "code": "def crud_links(model, instance_name, actions, args={})\n _html = \"\"\n _options = args.keys.empty? ? '' : \", #{args.map{|k,v| \":#{k} => #{v}\"}}\"\n \n if use_crud_icons\n if actions.include?(:show)\n _html << eval(\"link_to image_tag('/images/icons/view.png', :class => 'crud_icon'), model, :title => 'View'#{_options}\")\n end\n if actions.include?(:edit)\n _html << eval(\"link_to image_tag('/images/icons/edit.png', :class => 'crud_icon'), edit_#{instance_name}_path(model), :title => 'Edit'#{_options}\")\n end\n if actions.include?(:delete)\n _html << eval(\"link_to image_tag('/images/icons/delete.png', :class => 'crud_icon'), model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete'#{_options}\")\n end\n else\n if actions.include?(:show)\n _html << eval(\"link_to 'View', model, :title => 'View', :class => 'crud_link'#{_options}\")\n end\n if actions.include?(:edit)\n _html << eval(\"link_to 'Edit', edit_#{instance_name}_path(model), :title => 'Edit', :class => 'crud_link'#{_options}\")\n end\n if actions.include?(:delete)\n _html << eval(\"link_to 'Delete', model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete', :class => 'crud_link'#{_options}\")\n end\n end\n _html\n end", "code_tokens": ["def", "crud_links", "(", "model", ",", "instance_name", ",", "actions", ",", "args", "=", "{", "}", ")", "_html", "=", "\"\"", "_options", "=", "args", ".", "keys", ".", "empty?", "?", "''", ":", "\", #{args.map{|k,v| \":#{k} => #{v}\"}}\"", "if", "use_crud_icons", "if", "actions", ".", "include?", "(", ":show", ")", "_html", "<<", "eval", "(", "\"link_to image_tag('/images/icons/view.png', :class => 'crud_icon'), model, :title => 'View'#{_options}\"", ")", "end", "if", "actions", ".", "include?", "(", ":edit", ")", "_html", "<<", "eval", "(", "\"link_to image_tag('/images/icons/edit.png', :class => 'crud_icon'), edit_#{instance_name}_path(model), :title => 'Edit'#{_options}\"", ")", "end", "if", "actions", ".", "include?", "(", ":delete", ")", "_html", "<<", "eval", "(", "\"link_to image_tag('/images/icons/delete.png', :class => 'crud_icon'), model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete'#{_options}\"", ")", "end", "else", "if", "actions", ".", "include?", "(", ":show", ")", "_html", "<<", "eval", "(", "\"link_to 'View', model, :title => 'View', :class => 'crud_link'#{_options}\"", ")", "end", "if", "actions", ".", "include?", "(", ":edit", ")", "_html", "<<", "eval", "(", "\"link_to 'Edit', edit_#{instance_name}_path(model), :title => 'Edit', :class => 'crud_link'#{_options}\"", ")", "end", "if", "actions", ".", "include?", "(", ":delete", ")", "_html", "<<", "eval", "(", "\"link_to 'Delete', model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete', :class => 'crud_link'#{_options}\"", ")", "end", "end", "_html", "end"], "docstring": "Display CRUD icons or links, according to setting in use_crud_icons method.\n\n In application_helper.rb:\n\n def use_crud_icons\n true\n end\n\n Then use in index views like this:\n\n <%= crud_links(my_model, 'my_model', [:show, :edit, :delete]) -%>", "docstring_tokens": ["Display", "CRUD", "icons", "or", "links", "according", "to", "setting", "in", "use_crud_icons", "method", "."], "sha": "640c0807afe2015b7912ab3dd90fcd1aa7ad07a3", "url": "https://github.com/CoralineAda/mir_extensions/blob/640c0807afe2015b7912ab3dd90fcd1aa7ad07a3/lib/mir_extensions.rb#L68-L94", "partition": "valid"} {"repo": "CoralineAda/mir_extensions", "path": "lib/mir_extensions.rb", "func_name": "MirExtensions.HelperExtensions.obfuscated_link_to", "original_string": "def obfuscated_link_to(path, image, label, args={})\n _html = %{
}\n _html << %{
}\n args.each{ |k,v| _html << %{
} }\n _html << %{
}\n _html\n end", "language": "ruby", "code": "def obfuscated_link_to(path, image, label, args={})\n _html = %{
}\n _html << %{
}\n args.each{ |k,v| _html << %{
} }\n _html << %{
}\n _html\n end", "code_tokens": ["def", "obfuscated_link_to", "(", "path", ",", "image", ",", "label", ",", "args", "=", "{", "}", ")", "_html", "=", "%{
}", "_html", "<<", "%{
}", "args", ".", "each", "{", "|", "k", ",", "v", "|", "_html", "<<", "%{
}", "}", "_html", "<<", "%{
}", "_html", "end"], "docstring": "Create a link that is opaque to search engine spiders.", "docstring_tokens": ["Create", "a", "link", "that", "is", "opaque", "to", "search", "engine", "spiders", "."], "sha": "640c0807afe2015b7912ab3dd90fcd1aa7ad07a3", "url": "https://github.com/CoralineAda/mir_extensions/blob/640c0807afe2015b7912ab3dd90fcd1aa7ad07a3/lib/mir_extensions.rb#L161-L167", "partition": "valid"} {"repo": "CoralineAda/mir_extensions", "path": "lib/mir_extensions.rb", "func_name": "MirExtensions.HelperExtensions.required_field_helper", "original_string": "def required_field_helper( model, element, html )\n if model && ! model.errors.empty? && element.is_required\n return content_tag( :div, html, :class => 'fieldWithErrors' )\n else\n return html\n end\n end", "language": "ruby", "code": "def required_field_helper( model, element, html )\n if model && ! model.errors.empty? && element.is_required\n return content_tag( :div, html, :class => 'fieldWithErrors' )\n else\n return html\n end\n end", "code_tokens": ["def", "required_field_helper", "(", "model", ",", "element", ",", "html", ")", "if", "model", "&&", "!", "model", ".", "errors", ".", "empty?", "&&", "element", ".", "is_required", "return", "content_tag", "(", ":div", ",", "html", ",", ":class", "=>", "'fieldWithErrors'", ")", "else", "return", "html", "end", "end"], "docstring": "Wraps the given HTML in Rails' default style to highlight validation errors, if any.", "docstring_tokens": ["Wraps", "the", "given", "HTML", "in", "Rails", "default", "style", "to", "highlight", "validation", "errors", "if", "any", "."], "sha": "640c0807afe2015b7912ab3dd90fcd1aa7ad07a3", "url": "https://github.com/CoralineAda/mir_extensions/blob/640c0807afe2015b7912ab3dd90fcd1aa7ad07a3/lib/mir_extensions.rb#L170-L176", "partition": "valid"} {"repo": "CoralineAda/mir_extensions", "path": "lib/mir_extensions.rb", "func_name": "MirExtensions.HelperExtensions.select_tag_for_filter", "original_string": "def select_tag_for_filter(model, nvpairs, params)\n return unless model && nvpairs && ! nvpairs.empty?\n options = { :query => params[:query] }\n _url = url_for(eval(\"#{model}_url(options)\"))\n _html = %{
}\n _html << %{