baban/code_summarization_ruby_valid
09
1[2 {3 "instruction": "Summarize the following code:",4 "input": "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",5 "output": "can t use flatten as it will flatten hashes"6 },7 {8 "instruction": "Summarize the following code:",9 "input": "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",10 "output": "The default formatting is nearly unreadable so make it useful ."11 },12 {13 "instruction": "Summarize the following code:",14 "input": "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",15 "output": "Extract the query parameters and append them to the url"16 },17 {18 "instruction": "Summarize the following code:",19 "input": "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",20 "output": "Return a hash of headers whose keys are capitalized strings"21 },22 {23 "instruction": "Summarize the following code:",24 "input": "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",25 "output": "Given a MIME type or file extension return either a MIME type or if none is found the input unchanged ."26 },27 {28 "instruction": "Summarize the following code:",29 "input": "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",30 "output": "Construct a subresource preserving authentication ."31 },32 {33 "instruction": "Summarize the following code:",34 "input": "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",35 "output": "Hash of cookies extracted from response headers ."36 },37 {38 "instruction": "Summarize the following code:",39 "input": "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",40 "output": "Cookie jar extracted from response headers ."41 },42 {43 "instruction": "Summarize the following code:",44 "input": "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",45 "output": "Follow a redirection response but change the HTTP method to GET and drop the payload from the original request ."46 },47 {48 "instruction": "Summarize the following code:",49 "input": "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",50 "output": "Follow a redirection"51 },52 {53 "instruction": "Summarize the following code:",54 "input": "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",55 "output": "The logic for dispatching any additional actions that need to be taken . For instance calling the request phase if the request path is recognized ."56 },57 {58 "instruction": "Summarize the following code:",59 "input": "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",60 "output": "Responds to an OPTIONS request ."61 },62 {63 "instruction": "Summarize the following code:",64 "input": "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",65 "output": "Performs the steps necessary to run the callback phase of a strategy ."66 },67 {68 "instruction": "Summarize the following code:",69 "input": "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",70 "output": "This is called in lieu of the normal request process in the event that OmniAuth has been configured to be in test mode ."71 },72 {73 "instruction": "Summarize the following code:",74 "input": "def instance_action_module\n @instance_action_module ||= Module.new do\n\n # Returns the <tt>GoogleAdsSavon::Client</tt> from the class instance.\n def client(&block)\n self.class.client(&block)\n end\n\n end.tap { |mod| include(mod) }\n end",75 "output": "Instance methods ."76 },77 {78 "instruction": "Summarize the following code:",79 "input": "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",80 "output": "Retrieve correct soap_header_handler ."81 },82 {83 "instruction": "Summarize the following code:",84 "input": "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",85 "output": "Returns an instance of ReportUtils object with all utilities relevant to the reporting ."86 },87 {88 "instruction": "Summarize the following code:",89 "input": "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",90 "output": "Returns an instance of BatchJobUtils object with all utilities relevant to running batch jobs ."91 },92 {93 "instruction": "Summarize the following code:",94 "input": "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",95 "output": "Executes block with a temporary flag set to a given value . Returns block result ."96 },97 {98 "instruction": "Summarize the following code:",99 "input": "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",100 "output": "Validates given arguments based on provided fields list ."101 },102 {103 "instruction": "Summarize the following code:",104 "input": "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",105 "output": "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 ."106 },107 {108 "instruction": "Summarize the following code:",109 "input": "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",110 "output": "Checks if no extra fields provided outside of known ones ."111 },112 {113 "instruction": "Summarize the following code:",114 "input": "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",115 "output": "Checks the provided data structure matches wsdl definition ."116 },117 {118 "instruction": "Summarize the following code:",119 "input": "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",120 "output": "Overrides non - standard name conversion ."121 },122 {123 "instruction": "Summarize the following code:",124 "input": "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",125 "output": "Overrides non - default namespace if requested ."126 },127 {128 "instruction": "Summarize the following code:",129 "input": "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",130 "output": "Validates single argument ."131 },132 {133 "instruction": "Summarize the following code:",134 "input": "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",135 "output": "Validates Array argument ."136 },137 {138 "instruction": "Summarize the following code:",139 "input": "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",140 "output": "Validates Hash argument ."141 },142 {143 "instruction": "Summarize the following code:",144 "input": "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",145 "output": "Validates Time argument ."146 },147 {148 "instruction": "Summarize the following code:",149 "input": "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",150 "output": "Adds Savon attribute for given node key name and value ."151 },152 {153 "instruction": "Summarize the following code:",154 "input": "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",155 "output": "Prefixes a key with a given namespace index or default namespace ."156 },157 {158 "instruction": "Summarize the following code:",159 "input": "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",160 "output": "Returns type signature with all inherited fields ."161 },162 {163 "instruction": "Summarize the following code:",164 "input": "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",165 "output": "Returns all inherited fields of superclasses for given type ."166 },167 {168 "instruction": "Summarize the following code:",169 "input": "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",170 "output": "Converts Time to a hash for XML marshalling ."171 },172 {173 "instruction": "Summarize the following code:",174 "input": "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",175 "output": "Reads a configuration file into instance variable as a Ruby structure with the complete set of keys and values ."176 },177 {178 "instruction": "Summarize the following code:",179 "input": "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",180 "output": "Auxiliary method to recurse through a hash and convert all the keys to symbols ."181 },182 {183 "instruction": "Summarize the following code:",184 "input": "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",185 "output": "Finds a value for string of format level1 . level2 . name in a given hash ."186 },187 {188 "instruction": "Summarize the following code:",189 "input": "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",190 "output": "Initializes an upload URL to get the actual URL to which to upload operations ."191 },192 {193 "instruction": "Summarize the following code:",194 "input": "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",195 "output": "Puts the provided operations to the provided URL allowing for incremental followup puts ."196 },197 {198 "instruction": "Summarize the following code:",199 "input": "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",200 "output": "Downloads the results of a batch job from the specified URL ."201 },202 {203 "instruction": "Summarize the following code:",204 "input": "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",205 "output": "Given a full SOAP xml string extract just the operations element from the SOAP body as a string ."206 },207 {208 "instruction": "Summarize the following code:",209 "input": "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",210 "output": "Removes extraneous XML information from return hash ."211 },212 {213 "instruction": "Summarize the following code:",214 "input": "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",215 "output": "Determining whether another page exists when dealing with bid landscapes is different from other types of queries . Use this method for those cases ."216 },217 {218 "instruction": "Summarize the following code:",219 "input": "def version_has_service(version, service)\n return service_config.include?(version) &&\n service_config[version].include?(service)\n end",220 "output": "Does the given version exist and contain the given service?"221 },222 {223 "instruction": "Summarize the following code:",224 "input": "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",225 "output": "Get the endpoint for a service on a given API version ."226 },227 {228 "instruction": "Summarize the following code:",229 "input": "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",230 "output": "Perform the loading of the necessary source files for a version ."231 },232 {233 "instruction": "Summarize the following code:",234 "input": "def module_name(version, service)\n return [api_name, version.to_s.upcase, service.to_s].join('::')\n end",235 "output": "Returns the full module name for a given service ."236 },237 {238 "instruction": "Summarize the following code:",239 "input": "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",240 "output": "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 ."241 },242 {243 "instruction": "Summarize the following code:",244 "input": "def process(offset = 0, instance = self, &block)\n block.arity > 0 ? yield_objects(offset, instance, &block) : evaluate(instance, &block)\n end",245 "output": "Processes a given + block + . Yields objects if the block expects any arguments . Otherwise evaluates the block in the context of + instance + ."246 },247 {248 "instruction": "Summarize the following code:",249 "input": "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",250 "output": "Yields a number of objects to a given + block + depending on how many arguments the block is expecting ."251 },252 {253 "instruction": "Summarize the following code:",254 "input": "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",255 "output": "Evaluates a given + block + inside + instance + . Stores the original block binding ."256 },257 {258 "instruction": "Summarize the following code:",259 "input": "def remove_blank_values(hash)\n hash.delete_if { |_, value| value.respond_to?(:empty?) ? value.empty? : !value }\n end",260 "output": "Removes all blank values from a given + hash + ."261 },262 {263 "instruction": "Summarize the following code:",264 "input": "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",265 "output": "Get values as an array the format the Ad Manager API expects ."266 },267 {268 "instruction": "Summarize the following code:",269 "input": "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",270 "output": "Create an individual value object by inferring the xsi_type . If the value type isn t recognized return the original value parameter ."271 },272 {273 "instruction": "Summarize the following code:",274 "input": "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",275 "output": "Return a list of validation errors ."276 },277 {278 "instruction": "Summarize the following code:",279 "input": "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",280 "output": "Create a statement object that can be sent in a Ad Manager API request ."281 },282 {283 "instruction": "Summarize the following code:",284 "input": "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",285 "output": "When an unrecognized method is applied to AdManagerDate pass it through to the internal ruby Date ."286 },287 {288 "instruction": "Summarize the following code:",289 "input": "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",290 "output": "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 ."291 },292 {293 "instruction": "Summarize the following code:",294 "input": "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",295 "output": "When an unrecognized method is applied to AdManagerDateTime pass it through to the internal ruby Time ."296 },297 {298 "instruction": "Summarize the following code:",299 "input": "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",300 "output": "Creates and sets up Savon client ."301 },302 {303 "instruction": "Summarize the following code:",304 "input": "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",305 "output": "Generates and returns SOAP XML for the specified action and args ."306 },307 {308 "instruction": "Summarize the following code:",309 "input": "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",310 "output": "Executes SOAP action specified as a string with given arguments ."311 },312 {313 "instruction": "Summarize the following code:",314 "input": "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",315 "output": "Executes the SOAP request with original SOAP name ."316 },317 {318 "instruction": "Summarize the following code:",319 "input": "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",320 "output": "Checks for errors in response and raises appropriate exception ."321 },322 {323 "instruction": "Summarize the following code:",324 "input": "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",325 "output": "Finds an exception object for a given response ."326 },327 {328 "instruction": "Summarize the following code:",329 "input": "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",330 "output": "Yields to user - specified block with additional information such as headers ."331 },332 {333 "instruction": "Summarize the following code:",334 "input": "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",335 "output": "Log the request response and summary lines ."336 },337 {338 "instruction": "Summarize the following code:",339 "input": "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",340 "output": "Format headers redacting sensitive information ."341 },342 {343 "instruction": "Summarize the following code:",344 "input": "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",345 "output": "Format the fault message by capping length and removing newlines ."346 },347 {348 "instruction": "Summarize the following code:",349 "input": "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",350 "output": "Check whether or not to log request summaries based on log level ."351 },352 {353 "instruction": "Summarize the following code:",354 "input": "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",355 "output": "Check whether or not to log payloads based on log level ."356 },357 {358 "instruction": "Summarize the following code:",359 "input": "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",360 "output": "Downloads a report and saves it to a file ."361 },362 {363 "instruction": "Summarize the following code:",364 "input": "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",365 "output": "Downloads a report with AWQL and saves it to a file ."366 },367 {368 "instruction": "Summarize the following code:",369 "input": "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",370 "output": "Streams a report with AWQL as a string to the given block . This method will not do error checking on returned values ."371 },372 {373 "instruction": "Summarize the following code:",374 "input": "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",375 "output": "Returns a helper object that can manage breaking the streamed report results into individual lines ."376 },377 {378 "instruction": "Summarize the following code:",379 "input": "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",380 "output": "Send POST request for a report and returns Response object ."381 },382 {383 "instruction": "Summarize the following code:",384 "input": "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",385 "output": "Send POST request for a report with AWQL and returns Response object ."386 },387 {388 "instruction": "Summarize the following code:",389 "input": "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",390 "output": "Makes request and AdHoc service and returns response ."391 },392 {393 "instruction": "Summarize the following code:",394 "input": "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",395 "output": "Prepares headers for report request ."396 },397 {398 "instruction": "Summarize the following code:",399 "input": "def save_to_file(data, path)\n open(path, 'wb') { |file| file.write(data) } if path\n end",400 "output": "Saves raw data to a file ."401 },402 {403 "instruction": "Summarize the following code:",404 "input": "def log_headers(headers)\n @api.logger.debug('HTTP headers: [%s]' %\n (headers.map { |k, v| [k, v].join(': ') }.join(', ')))\n end",405 "output": "Logs HTTP headers on debug level ."406 },407 {408 "instruction": "Summarize the following code:",409 "input": "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",410 "output": "Checks downloaded data for error signature . Raises ReportError if it detects an error ."411 },412 {413 "instruction": "Summarize the following code:",414 "input": "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",415 "output": "Checks for an XML error in the response body and raises an exception if it was found ."416 },417 {418 "instruction": "Summarize the following code:",419 "input": "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",420 "output": "Renders a report definition hash into XML text ."421 },422 {423 "instruction": "Summarize the following code:",424 "input": "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",425 "output": "Checks if the report definition looks correct ."426 },427 {428 "instruction": "Summarize the following code:",429 "input": "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",430 "output": "Adds fields order hint to generator based on specification ."431 },432 {433 "instruction": "Summarize the following code:",434 "input": "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",435 "output": "Initializes a header handler ."436 },437 {438 "instruction": "Summarize the following code:",439 "input": "def credentials(credentials_override = nil)\n credentials = @credentials.dup()\n credentials.merge!(credentials_override) unless credentials_override.nil?\n return credentials\n end",440 "output": "Initializes CredentialHandler . Returns credentials set for the next call ."441 },442 {443 "instruction": "Summarize the following code:",444 "input": "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",445 "output": "Set the credentials hash to a new one . Calculate difference and call the AuthHandler callback appropriately ."446 },447 {448 "instruction": "Summarize the following code:",449 "input": "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",450 "output": "Generates string for UserAgent to put into headers ."451 },452 {453 "instruction": "Summarize the following code:",454 "input": "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",455 "output": "Generates an array of extra user agents to include in the user agent string ."456 },457 {458 "instruction": "Summarize the following code:",459 "input": "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",460 "output": "Extracts misc data from response header ."461 },462 {463 "instruction": "Summarize the following code:",464 "input": "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",465 "output": "Extracts misc data from SOAP fault ."466 },467 {468 "instruction": "Summarize the following code:",469 "input": "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",470 "output": "Normalizes all fields for the given data based on the fields list provided ."471 },472 {473 "instruction": "Summarize the following code:",474 "input": "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",475 "output": "Normalizes one field of a given data recursively ."476 },477 {478 "instruction": "Summarize the following code:",479 "input": "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",480 "output": "Normalizes every item of an Array ."481 },482 {483 "instruction": "Summarize the following code:",484 "input": "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",485 "output": "Normalizes every item of a Hash ."486 },487 {488 "instruction": "Summarize the following code:",489 "input": "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",490 "output": "Determines a choice type override for for the field . Returns nil if no override found ."491 },492 {493 "instruction": "Summarize the following code:",494 "input": "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",495 "output": "Finds the choice option matching data provided ."496 },497 {498 "instruction": "Summarize the following code:",499 "input": "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",500 "output": "Converts one leaf item to a built - in type ."501 },502 {503 "instruction": "Summarize the following code:",504 "input": "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",505 "output": "Checks if the field signature allows an array and forces array structure even for a signle item ."506 },507 {508 "instruction": "Summarize the following code:",509 "input": "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",510 "output": "Handles attributes received from Savon ."511 },512 {513 "instruction": "Summarize the following code:",514 "input": "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",515 "output": "Obtain an API service given a version and its name ."516 },517 {518 "instruction": "Summarize the following code:",519 "input": "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",520 "output": "Authorize with specified authentication method ."521 },522 {523 "instruction": "Summarize the following code:",524 "input": "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",525 "output": "Updates default configuration file to include OAuth2 token information ."526 },527 {528 "instruction": "Summarize the following code:",529 "input": "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",530 "output": "Auxiliary method to test parameters correctness for the service request ."531 },532 {533 "instruction": "Summarize the following code:",534 "input": "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",535 "output": "Auxiliary method to create an authentication handler ."536 },537 {538 "instruction": "Summarize the following code:",539 "input": "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",540 "output": "Handle loading of a single service . Creates the wrapper sets up handlers and creates an instance of it ."541 },542 {543 "instruction": "Summarize the following code:",544 "input": "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",545 "output": "Auxiliary method to create a default Logger ."546 },547 {548 "instruction": "Summarize the following code:",549 "input": "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",550 "output": "Helper method to load the default configuration file or a given config ."551 },552 {553 "instruction": "Summarize the following code:",554 "input": "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",555 "output": "Initializes config with default values and converts existing if required ."556 },557 {558 "instruction": "Summarize the following code:",559 "input": "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",560 "output": "Converts value of a config key to uppercase symbol ."561 },562 {563 "instruction": "Summarize the following code:",564 "input": "def class_for_path(path)\n path.split('::').inject(Kernel) do |scope, const_name|\n scope.const_get(const_name)\n end\n end",565 "output": "Converts complete class path into class object ."566 },567 {568 "instruction": "Summarize the following code:",569 "input": "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",570 "output": "Renders the Farm into JSON to show for the end - user in front . rb ."571 },572 {573 "instruction": "Summarize the following code:",574 "input": "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",575 "output": "Returns TRUE if a file for this wallet is already in the queue ."576 },577 {578 "instruction": "Summarize the following code:",579 "input": "def exists?(details)\n !@wallet.txns.find { |t| t.details.start_with?(\"#{PREFIX} \") && t.details == details }.nil?\n end",580 "output": "Check whether this tax payment already exists in the wallet ."581 },582 {583 "instruction": "Summarize the following code:",584 "input": "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",585 "output": "This method is thread - safe"586 },587 {588 "instruction": "Summarize the following code:",589 "input": "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",590 "output": "Creates an empty wallet with the specified ID and public key ."591 },592 {593 "instruction": "Summarize the following code:",594 "input": "def balance\n txns.inject(Amount::ZERO) { |sum, t| sum + t.amount }\n end",595 "output": "Returns current wallet balance ."596 },597 {598 "instruction": "Summarize the following code:",599 "input": "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",600 "output": "Add a payment transaction to the wallet ."601 },602 {603 "instruction": "Summarize the following code:",604 "input": "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",605 "output": "Add a transaction to the wallet ."606 },607 {608 "instruction": "Summarize the following code:",609 "input": "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",610 "output": "Returns TRUE if the wallet contains a payment sent with the specified ID which was sent to the specified beneficiary ."611 },612 {613 "instruction": "Summarize the following code:",614 "input": "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",615 "output": "Returns TRUE if the wallet contains a payment received with the specified ID which was sent by the specified beneficiary ."616 },617 {618 "instruction": "Summarize the following code:",619 "input": "def age\n list = txns\n list.empty? ? 0 : (Time.now - list.min_by(&:date).date) / (60 * 60)\n end",620 "output": "Age of wallet in hours ."621 },622 {623 "instruction": "Summarize the following code:",624 "input": "def max\n negative = txns.select { |t| t.amount.negative? }\n negative.empty? ? 0 : negative.max_by(&:id).id\n end",625 "output": "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 ."626 },627 {628 "instruction": "Summarize the following code:",629 "input": "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",630 "output": "Returns list of Wallet IDs which were affected"631 },632 {633 "instruction": "Summarize the following code:",634 "input": "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",635 "output": "Returns exit code"636 },637 {638 "instruction": "Summarize the following code:",639 "input": "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",640 "output": "Add a new thread"641 },642 {643 "instruction": "Summarize the following code:",644 "input": "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",645 "output": "Kill them all immediately and close the pool"646 },647 {648 "instruction": "Summarize the following code:",649 "input": "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",650 "output": "As a hash map"651 },652 {653 "instruction": "Summarize the following code:",654 "input": "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",655 "output": "As a text"656 },657 {658 "instruction": "Summarize the following code:",659 "input": "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",660 "output": "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 ."661 },662 {663 "instruction": "Summarize the following code:",664 "input": "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",665 "output": "Returns TRUE if the file was actually modified"666 },667 {668 "instruction": "Summarize the following code:",669 "input": "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",670 "output": "Delete all copies that are older than the max age provided in seconds ."671 },672 {673 "instruction": "Summarize the following code:",674 "input": "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",675 "output": "Returns the name of the copy"676 },677 {678 "instruction": "Summarize the following code:",679 "input": "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",680 "output": "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 ."681 },682 {683 "instruction": "Summarize the following code:",684 "input": "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",685 "output": "Marks all the posts from the given one as unread for the given user"686 },687 {688 "instruction": "Summarize the following code:",689 "input": "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",690 "output": "Find a record by ID or return the passed record ."691 },692 {693 "instruction": "Summarize the following code:",694 "input": "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",695 "output": "Whether this is visible to the given user based on the moderation state ."696 },697 {698 "instruction": "Summarize the following code:",699 "input": "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",700 "output": "Set worklist protection"701 },702 {703 "instruction": "Summarize the following code:",704 "input": "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",705 "output": "Sets the default Format of the column at _idx_ ."706 },707 {708 "instruction": "Summarize the following code:",709 "input": "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",710 "output": "Updates the Row at _idx_ with the following arguments ."711 },712 {713 "instruction": "Summarize the following code:",714 "input": "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",715 "output": "Merges multiple cells into one ."716 },717 {718 "instruction": "Summarize the following code:",719 "input": "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",720 "output": "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 ."721 },722 {723 "instruction": "Summarize the following code:",724 "input": "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",725 "output": "Change the RGB components of the elements in the colour palette ."726 },727 {728 "instruction": "Summarize the following code:",729 "input": "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",730 "output": "The Format at _idx_ or - if _idx_ is a String - the Format with name == _idx_"731 },732 {733 "instruction": "Summarize the following code:",734 "input": "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",735 "output": "The Worksheet at _idx_ or - if _idx_ is a String - the Worksheet with name == _idx_"736 },737 {738 "instruction": "Summarize the following code:",739 "input": "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",740 "output": "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 ."741 },742 {743 "instruction": "Summarize the following code:",744 "input": "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",745 "output": "Traverses the resource looking for associations then descends into those associations and checks for applicable resources to side load"746 },747 {748 "instruction": "Summarize the following code:",749 "input": "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",750 "output": "Adds an item to this collection"751 },752 {753 "instruction": "Summarize the following code:",754 "input": "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",755 "output": "Executes actual GET from API and loads resources into proper class ."756 },757 {758 "instruction": "Summarize the following code:",759 "input": "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",760 "output": "Sends methods to underlying array of resources ."761 },762 {763 "instruction": "Summarize the following code:",764 "input": "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",765 "output": "Tries to place side loads onto given resources ."766 },767 {768 "instruction": "Summarize the following code:",769 "input": "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",770 "output": "Saves returning false if it fails and attaching the errors"771 },772 {773 "instruction": "Summarize the following code:",774 "input": "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",775 "output": "Saves associations Takes into account inlining collections and id setting on the parent resource ."776 },777 {778 "instruction": "Summarize the following code:",779 "input": "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",780 "output": "Reloads a resource ."781 },782 {783 "instruction": "Summarize the following code:",784 "input": "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",785 "output": "Creates multiple resources using the create_many endpoint ."786 },787 {788 "instruction": "Summarize the following code:",789 "input": "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",790 "output": "Creates or updates resource using the create_or_update endpoint ."791 },792 {793 "instruction": "Summarize the following code:",794 "input": "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",795 "output": "Creates or updates multiple resources using the create_or_update_many endpoint ."796 },797 {798 "instruction": "Summarize the following code:",799 "input": "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",800 "output": "If this resource hasn t already been deleted then do so ."801 },802 {803 "instruction": "Summarize the following code:",804 "input": "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",805 "output": "Destroys multiple resources using the destroy_many endpoint ."806 },807 {808 "instruction": "Summarize the following code:",809 "input": "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",810 "output": "Updates multiple resources using the update_many endpoint ."811 },812 {813 "instruction": "Summarize the following code:",814 "input": "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",815 "output": "Returns the update to a ticket that happens when a macro will be applied ."816 },817 {818 "instruction": "Summarize the following code:",819 "input": "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",820 "output": "Handles resources such as tickets . Any options are passed to the underlying collection except reload which disregards memoization and creates a new Collection instance ."821 },822 {823 "instruction": "Summarize the following code:",824 "input": "def version(*versions, &block)\n condition = lambda { |env|\n versions.include?(env[\"HTTP_X_API_VERSION\"])\n }\n with_conditions(condition, &block)\n end",825 "output": "yield to a builder block in which all defined apps will only respond for the given version"826 },827 {828 "instruction": "Summarize the following code:",829 "input": "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",830 "output": "Parses arguments to track! method and return array with timestamp identity and array of values ."831 },832 {833 "instruction": "Summarize the following code:",834 "input": "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",835 "output": "Render the named template . Used for reporting and the dashboard ."836 },837 {838 "instruction": "Summarize the following code:",839 "input": "def method_missing(method, *args, &block)\n %w(url_for flash).include?(method.to_s) ? ProxyEmpty.new : super\n end",840 "output": "prevent certain url helper methods from failing so we can run erb templates outside of rails for reports ."841 },842 {843 "instruction": "Summarize the following code:",844 "input": "def vanity_simple_format(text, options={})\n open = \"<p #{options.map { |k,v| \"#{k}=\\\"#{CGI.escapeHTML v}\\\"\" }.join(\" \")}>\"\n text = open + text.gsub(/\\r\\n?/, \"\\n\"). # \\r\\n and \\r -> \\n\n gsub(/\\n\\n+/, \"</p>\\n\\n#{open}\"). # 2+ newline -> paragraph\n gsub(/([^\\n]\\n)(?=[^\\n])/, '\\1<br />') + # 1 newline -> br\n \"</p>\"\n end",845 "output": "Dumbed down from Rails simple_format ."846 },847 {848 "instruction": "Summarize the following code:",849 "input": "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",850 "output": "Returns the experiment . You may not have guessed but this method raises an exception if it cannot load the experiment s definition ."851 },852 {853 "instruction": "Summarize the following code:",854 "input": "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",855 "output": "Check to make sure we set a custome path it exists and there are non - dotfiles in the directory ."856 },857 {858 "instruction": "Summarize the following code:",859 "input": "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",860 "output": "Build jobs and run . This is NOT interface for users ."861 },862 {863 "instruction": "Summarize the following code:",864 "input": "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",865 "output": "The GetUserConfiguration operation gets a user configuration object from a folder ."866 },867 {868 "instruction": "Summarize the following code:",869 "input": "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",870 "output": "Build the FolderShape element"871 },872 {873 "instruction": "Summarize the following code:",874 "input": "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",875 "output": "Build the ItemShape element"876 },877 {878 "instruction": "Summarize the following code:",879 "input": "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",880 "output": "Build the IndexedPageItemView element"881 },882 {883 "instruction": "Summarize the following code:",884 "input": "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",885 "output": "Build the FolderIds element"886 },887 {888 "instruction": "Summarize the following code:",889 "input": "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",890 "output": "Build the DistinguishedFolderId element"891 },892 {893 "instruction": "Summarize the following code:",894 "input": "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",895 "output": "Build the FolderId element"896 },897 {898 "instruction": "Summarize the following code:",899 "input": "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",900 "output": "Build the AdditionalProperties element"901 },902 {903 "instruction": "Summarize the following code:",904 "input": "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",905 "output": "Build the Mailbox element . This element is commonly used for delegation . Typically passing an email_address is sufficient"906 },907 {908 "instruction": "Summarize the following code:",909 "input": "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",910 "output": "Request all known time_zones from server"911 },912 {913 "instruction": "Summarize the following code:",914 "input": "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",915 "output": "Specifies an optional time zone for the start time"916 },917 {918 "instruction": "Summarize the following code:",919 "input": "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",920 "output": "Specifies an optional time zone for the end time"921 },922 {923 "instruction": "Summarize the following code:",924 "input": "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",925 "output": "Specify a time zone"926 },927 {928 "instruction": "Summarize the following code:",929 "input": "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",930 "output": "Build the Restriction element"931 },932 {933 "instruction": "Summarize the following code:",934 "input": "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",935 "output": "Build the CalendarView element"936 },937 {938 "instruction": "Summarize the following code:",939 "input": "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",940 "output": "Build the ContactsView element"941 },942 {943 "instruction": "Summarize the following code:",944 "input": "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",945 "output": "Build the AttachmentIds element"946 },947 {948 "instruction": "Summarize the following code:",949 "input": "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",950 "output": "A helper method to dispatch to an ItemId OccurrenceItemId or a RecurringMasterItemId"951 },952 {953 "instruction": "Summarize the following code:",954 "input": "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",955 "output": "A helper method to dispatch to a AppendToItemField SetItemField or DeleteItemField"956 },957 {958 "instruction": "Summarize the following code:",959 "input": "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",960 "output": "A helper to dispatch to a FieldURI IndexedFieldURI or an ExtendedFieldURI"961 },962 {963 "instruction": "Summarize the following code:",964 "input": "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",965 "output": "Insert item enforce xmlns attribute if prefix is present"966 },967 {968 "instruction": "Summarize the following code:",969 "input": "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",970 "output": "Updates the specified item attributes"971 },972 {973 "instruction": "Summarize the following code:",974 "input": "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",975 "output": "Defines a request to synchronize a folder hierarchy on a client"976 },977 {978 "instruction": "Summarize the following code:",979 "input": "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",980 "output": "Synchronizes items between the Exchange server and the client"981 },982 {983 "instruction": "Summarize the following code:",984 "input": "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",985 "output": "Get information about when the user with the given email address is available ."986 },987 {988 "instruction": "Summarize the following code:",989 "input": "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",990 "output": "Move this item to a new folder"991 },992 {993 "instruction": "Summarize the following code:",994 "input": "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",995 "output": "Copy this item to a new folder"996 },997 {998 "instruction": "Summarize the following code:",999 "input": "def get_item(opts = {})\n args = get_item_args(opts)\n resp = ews.get_item(args)\n get_item_parser(resp)\n end",1000 "output": "Get a specific item by its ID ."1001 },1002 {1003 "instruction": "Summarize the following code:",1004 "input": "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",1005 "output": "Handles the CreateItem call for Forward ReplyTo and ReplyAllTo It will handle the neccessary actions for adding attachments ."1006 },1007 {1008 "instruction": "Summarize the following code:",1009 "input": "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",1010 "output": "validate the CreateItem response ."1011 },1012 {1013 "instruction": "Summarize the following code:",1014 "input": "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",1015 "output": "Fetch items since a give DateTime"1016 },1017 {1018 "instruction": "Summarize the following code:",1019 "input": "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",1020 "output": "Fetch items between a given time period"1021 },1022 {1023 "instruction": "Summarize the following code:",1024 "input": "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",1025 "output": "Search on the item subject"1026 },1027 {1028 "instruction": "Summarize the following code:",1029 "input": "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",1030 "output": "Syncronize Items in this folder . If this method is issued multiple times it will continue where the last sync completed ."1031 },1032 {1033 "instruction": "Summarize the following code:",1034 "input": "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",1035 "output": "Subscribe this folder to events . This method initiates an Exchange pull type subscription ."1036 },1037 {1038 "instruction": "Summarize the following code:",1039 "input": "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",1040 "output": "Unsubscribe this folder from further Exchange events ."1041 },1042 {1043 "instruction": "Summarize the following code:",1044 "input": "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",1045 "output": "Checks a subscribed folder for events"1046 },1047 {1048 "instruction": "Summarize the following code:",1049 "input": "def get_folder(opts = {})\n args = get_folder_args(opts)\n resp = ews.get_folder(args)\n get_folder_parser(resp)\n end",1050 "output": "Get a specific folder by its ID ."1051 },1052 {1053 "instruction": "Summarize the following code:",1054 "input": "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",1055 "output": "Request list of server known time zones"1056 },1057 {1058 "instruction": "Summarize the following code:",1059 "input": "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",1060 "output": "Defines a request to copy folders in the Exchange store"1061 },1062 {1063 "instruction": "Summarize the following code:",1064 "input": "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",1065 "output": "Defines a request to move folders in the Exchange store"1066 },1067 {1068 "instruction": "Summarize the following code:",1069 "input": "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",1070 "output": "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 ."1071 },1072 {1073 "instruction": "Summarize the following code:",1074 "input": "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",1075 "output": "Empties folders in a mailbox ."1076 },1077 {1078 "instruction": "Summarize the following code:",1079 "input": "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",1080 "output": "Creates either an item or file attachment and attaches it to the specified item ."1081 },1082 {1083 "instruction": "Summarize the following code:",1084 "input": "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",1085 "output": "Resolve ambiguous e - mail addresses and display names"1086 },1087 {1088 "instruction": "Summarize the following code:",1089 "input": "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",1090 "output": "Converts item and folder identifiers between formats ."1091 },1092 {1093 "instruction": "Summarize the following code:",1094 "input": "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",1095 "output": "Creates a new appointment"1096 },1097 {1098 "instruction": "Summarize the following code:",1099 "input": "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",1100 "output": "Provides detailed information about the availability of a set of users rooms and resources within a specified time window ."1101 },1102 {1103 "instruction": "Summarize the following code:",1104 "input": "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",1105 "output": "Gets the rooms that are in the specified room distribution list"1106 },1107 {1108 "instruction": "Summarize the following code:",1109 "input": "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",1110 "output": "Gets the room lists that are available within the Exchange organization ."1111 },1112 {1113 "instruction": "Summarize the following code:",1114 "input": "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",1115 "output": "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"1116 },1117 {1118 "instruction": "Summarize the following code:",1119 "input": "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",1120 "output": "Build the common elements in the SOAP message and yield to any custom elements ."1121 },1122 {1123 "instruction": "Summarize the following code:",1124 "input": "def camel_case(input)\n input.to_s.split(/_/).map { |i|\n i.sub(/^./) { |s| s.upcase }\n }.join\n end",1125 "output": "Change a ruby_cased string to CamelCased"1126 },1127 {1128 "instruction": "Summarize the following code:",1129 "input": "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",1130 "output": "Convert an ISO8601 Duration format to seconds"1131 },1132 {1133 "instruction": "Summarize the following code:",1134 "input": "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",1135 "output": "Used to subscribe client applications to either push pull or stream notifications ."1136 },1137 {1138 "instruction": "Summarize the following code:",1139 "input": "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",1140 "output": "Create a push subscription to a single folder"1141 },1142 {1143 "instruction": "Summarize the following code:",1144 "input": "def coerce(*)\n return nil if value.nil?\n return value if value.is_a?(Date)\n\n DateTime.parse(value)\n end",1145 "output": "Coerces value to DateTime"1146 },1147 {1148 "instruction": "Summarize the following code:",1149 "input": "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",1150 "output": "Gets a collection of entries which links to current entry"1151 },1152 {1153 "instruction": "Summarize the following code:",1154 "input": "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",1155 "output": "Gets a specific entry"1156 },1157 {1158 "instruction": "Summarize the following code:",1159 "input": "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",1160 "output": "Returns the X - Contentful - User - Agent os data"1161 },1162 {1163 "instruction": "Summarize the following code:",1164 "input": "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",1165 "output": "Returns the X - Contentful - User - Agent"1166 },1167 {1168 "instruction": "Summarize the following code:",1169 "input": "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",1170 "output": "Returns the headers used for the HTTP requests"1171 },1172 {1173 "instruction": "Summarize the following code:",1174 "input": "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",1175 "output": "Runs request and parses Response"1176 },1177 {1178 "instruction": "Summarize the following code:",1179 "input": "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",1180 "output": "Runs Resource Builder"1181 },1182 {1183 "instruction": "Summarize the following code:",1184 "input": "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",1185 "output": "Queries contentful for the Resource the Link is refering to Takes an optional query hash"1186 },1187 {1188 "instruction": "Summarize the following code:",1189 "input": "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",1190 "output": "Returns all fields of the asset with locales nested by field"1191 },1192 {1193 "instruction": "Summarize the following code:",1194 "input": "def reload(client = nil)\n return client.send(Support.snakify(self.class.name.split('::').last), id) unless client.nil?\n\n false\n end",1195 "output": "Issues the request that was made to fetch this response again . Only works for Entry Asset ContentType and Space"1196 },1197 {1198 "instruction": "Summarize the following code:",1199 "input": "def field_for(field_id)\n fields.detect { |f| Support.snakify(f.id) == Support.snakify(field_id) }\n end",1200 "output": "Field definition for field"