Question:
transposes uri to http

@param   int  $port  optional  new port to use, defaults to 80
@return  \stubbles\peer\http\HttpUri
@since   2.0.0

public function toHttp(int $port = null): self
    {
        if ($this->isHttp()) {
            if (null !== $port && !$this->parsedUri->portEquals($port)) {
                return new ConstructedHttpUri($this->parsedUri->transpose(['port' => $port]));
            }

            return $this;
        }

        $changes = ['scheme' => Http::SCHEME];
        if ($this->parsedUri->hasPort()) {
            $changes['port'] = $port;
        }

        return new ConstructedHttpUri($this->parsedUri->transpose($changes));
    }

func GetRequestToken(client *FlickrClient) (*RequestToken, error) {
	client.EndpointUrl = REQUEST_TOKEN_URL
	client.SetOAuthDefaults()
	client.Args.Set("oauth_consumer_key", client.ApiKey)
	client.Args.Set("oauth_callback", "oob")

	// we don't have token secret at this stage, pass an empty string
	client.Sign("")

	res, err := client.HTTPClient.Get(client.GetUrl())
	if err != nil {
		return nil, err
	}

	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}

	return ParseRequestToken(string(body))
}

Instruction: Given a code description, retrieve the corresponding code.


Question: Microsoft Visual C++ & Microsoft Foundation Class Includes

def VCIncludes(self):

        return [os.path.join(self.si.VCInstallDir, 'Include'),
                os.path.join(self.si.VCInstallDir, r'ATLMFC\Include')]

public function init()
    {
        parent::init();
        self::$plugin = $this;

        // Add in our console commands
        if (Craft::$app instanceof ConsoleApplication) {
            $this->controllerNamespace = 'venveo\\maintenancemode\\console\\controllers';
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetContents sets the Contents field's value.

func (s *CreateProjectInput) SetContents(v []byte) *CreateProjectInput {
	s.Contents = v
	return s
}

public function getCode() : ?string
    {
        if ( ! $this->hasCode()) {
            $this->setCode($this->getDefaultCode());
        }
        return $this->code;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns a long array of size 2, which is a 128-bit hash of the input.

@param key The input long[] array. Must be non-null and non-empty.
@param seed A long valued seed.
@return the hash.

public static long[] hash(final long[] key, final long seed) {
    final HashState hashState = new HashState(seed, seed);
    final int longs = key.length; //in longs

    // Number of full 128-bit blocks of 2 longs (the body).
    // Possible exclusion of a remainder of 1 long.
    final int nblocks = longs >>> 1; //longs / 2

    // Process the 128-bit blocks (the body) into the hash
    for (int i = 0; i < nblocks; i++ ) {
      final long k1 = key[i << 1]; //0, 2, 4, ...
      final long k2 = key[(i << 1) + 1]; //1, 3, 5, ...
      hashState.blockMix128(k1, k2);
    }

    // Get the tail index, remainder length
    final int tail = nblocks << 1; // 2 longs / block
    final int rem = longs - tail; // remainder longs: 0,1

    // Get the tail
    final long k1 = (rem == 0) ? 0 : key[tail]; //k2 -> 0
    // Mix the tail into the hash and return
    return hashState.finalMix128(k1, 0, longs << 3); //convert to bytes
  }

protected function ensureHashedPassword() {
    // the password is expected to be stored in the 'password' value
    $password = $this->getValue('password');
    if (strlen($password) > 0 && !PasswordService::isHashed($password)) {
      $this->setValue('password', PasswordService::hash($password));
    }
  }

Instruction: Given a code description, retrieve the corresponding code.


Question: Ensure the required items are in the dictionary

def required(self, method, _dict, require):

        for key in require:
            if key not in _dict:
                raise LunrError("'%s' is required argument for method '%s'"
                                % (key, method))

def content(self, value):

        self._validator.validate_message_dict(value)
        self._content = value

Instruction: Given a code description, retrieve the corresponding code.


Question:
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated

public String convertIfcStructuralCurveMemberTypeEnumToString(EDataType eDataType, Object instanceValue) {
		return instanceValue == null ? null : instanceValue.toString();
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Logger objects are used to create log events. The constructor for Logger objects is
private (not accessible outside this module). Instead, they are created through the
LoggerManager.prototype.createLogger method.

function Logger(manager, source) {
        Object.defineProperties(this, {
            "manager" : {
                value : manager,
                writable : false,
                enumerable : true
            },
            "source" : {
                value : source,
                writable : false,
                enumerable : true
            },
            "_timerData" : {
                value : {},
                writable : false,
                enumerable : false
            }
        });
    }

public function loadListeners($manager = null, $scope = null) {
		if (!($manager instanceof CakeEventManager)) {
			$scope = $manager;
			$_this = $this;
		} else {
			$_this = $manager;
		}

		empty($_this->loadedListeners['Common'])
		&& $_this->loadedListeners['Common'] = new CommonEventListener();

		(empty($_this->loadedScopes['Common']) || !in_array($scope, (array) $_this->loadedScopes['Common']))
		&& $_this->loadedScopes['Common'][] = $scope
		&& $_this->attachByScope($_this->loadedListeners['Common'], $_this, $scope);

		$_this->implementedEvents['Common'] = array_keys($_this->loadedListeners['Common']->implementedEvents());

		foreach ($_this->listPlugins() as $plugin) {
			if (isset($_this->loadedListeners[$plugin])) {
				if (
					$_this->loadedListeners[$plugin]
					&& !empty($scope)
					&& !in_array($scope, (array) $_this->loadedScopes[$plugin])
				) {
					$_this->loadedScopes[$plugin][] = $scope;
					$_this->attachByScope($_this->loadedListeners[$plugin], $_this, $scope);
				}
				continue;
			}

			$class = $plugin . 'EventListener';

			if (ClassRegistry::isKeySet($class)) {
				$_this->loadedListeners[$plugin] = ClassRegistry::getObject($class);
			} else if (file_exists(CakePlugin::path($plugin) . 'Event' . DS . $class . '.php')) {
				App::uses($class, $plugin . '.Event');
				$_this->loadedListeners[$plugin] = new $class();
			} else {
				$_this->loadedListeners[$plugin] = false;
				continue;
			}

			$_this->loadedScopes[$plugin] = array();
			$_this->implementedEvents[$plugin] = array_keys($_this->loadedListeners[$plugin]->implementedEvents());

			if (empty($scope)) {
				$_this->attach($_this->loadedListeners[$plugin]);
			} else if (!in_array($scope, $_this->loadedScopes[$plugin])) {
				$_this->loadedScopes[$plugin][] = $scope;
				$_this->attachByScope($_this->loadedListeners[$plugin], $_this, $scope);
			}
		}

		if ((!Reveal::is('Page.test') || empty($_GET['plugin'])) && !isset($_this->loadedListeners['App'])) {
			if (file_exists(APP . 'Event' . DS . 'AppEventListener.php')) {
				App::uses('AppEventListener', 'Event');
				$_this->loadedListeners['App'] = new AppEventListener();
				$_this->loadedScopes['App'] = array();
				$_this->implementedEvents['App'] = array_keys($_this->loadedListeners['App']->implementedEvents());
				if (empty($scope)) {
					$_this->attach($_this->loadedListeners['App']);
				} else if (!in_array($scope, $_this->loadedScopes['App'])) {
					$_this->loadedScopes['App'][] = $scope;
					$_this->attachByScope($_this->loadedListeners['App'], $_this, $scope);
				}
			}
		} else if (
			isset($_this->loadedListeners['App'])
			&& $_this->loadedListeners['App']
			&& !empty($scope)
			&& !in_array($scope, $_this->loadedScopes['App'])
		) {
			$_this->loadedScopes['App'][] = $scope;
			$_this->attachByScope($_this->loadedListeners['App'], $_this, $scope);
		}

		return $_this;
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
This method returns an array because
 multiple plugins could have the same type

def plugins_info_by_type(type, opts={})
      array = all_plugins.select {|pe|
        (pe.config['@type'] == type) rescue nil
      }
      array.map {|pe|
        get_monitor_info(pe, opts)
      }
    end

private function initFieldsTypes()
    {
        $this->fieldTypes = [];

        $fieldTypes = $this->loadFieldTypes();

        foreach ($fieldTypes as $fieldType) {
            if (!$fieldType instanceof FieldTypeInterface) {
                throw new DataSourceException(sprintf('Expected instance of FieldTypeInterface, "%s" given.', get_class($fieldType)));
            }

            if (isset($this->fieldTypes[$fieldType->getType()])) {
                throw new DataSourceException(sprintf('Error during field types loading. Name "%s" already in use.', $fieldType->getType()));
            }

            $this->fieldTypes[$fieldType->getType()] = $fieldType;
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Parser for a file with syntax somewhat similar to Drake.

def parse_input_file(text, variables=None):

    text = find_includes(text)
    lines = text.splitlines()
    tasks, linenumbers = find_tasks(lines)
    preamble = [line for line in lines[:linenumbers[0]]]
    logging.debug("Preamble:\n{}".format("\n".join(preamble)))
    if variables is not None:
        preamble += "\n" + "\n".join(variables)
    environment = create_environment(preamble)
    code_sections = []
    for n in range(len(linenumbers) - 1):
        code_sections.append((linenumbers[n], linenumbers[n+1]))
    for n, task in zip(code_sections, tasks):
        task["code"] = lines[n[0]: n[1]]
        task["environment"] = environment
    clean_tasks = []
    for task in tasks:
        clean_tasks.append(Task(**task))
    return clean_tasks

private function MethodCall()
	{
		$values = [];

		if ( !$this->lexer->isNextToken( DocLexer::T_OPEN_PARENTHESIS ) )
			return $values;

		$this->match( DocLexer::T_OPEN_PARENTHESIS );

		if ( !$this->lexer->isNextToken( DocLexer::T_CLOSE_PARENTHESIS ) )
			$values = $this->Values();

		$this->match( DocLexer::T_CLOSE_PARENTHESIS );

		return $values;
	}

Instruction: Given a code description, retrieve the corresponding code.


Question: // Delete a user from the UsersStore

func (s *UsersStore) Delete(ctx context.Context, u *chronograf.User) error {
	_, err := s.get(ctx, u.ID)
	if err != nil {
		return err
	}
	return s.client.db.Update(func(tx *bolt.Tx) error {
		return tx.Bucket(UsersBucket).Delete(u64tob(u.ID))
	})
}

public function getDeleteRequest($ids)
    {
        return new StorageDataRequest(
            [$this->sourceDataAdapter, $this->cacheDataAdapter, $ids],
            function (DataAdapterInterface $sourceData, DataAdapterInterface $cacheData, $ids) {
                $request = $sourceData->getDeleteRequest($ids);
                $request->send();
                $result = $request->fetch();
                $cacheData->getDeleteRequest($ids)->send();

                return $result;
            }
        );
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// init will initialize this skiplist.  The parameter is expected
// to be of some uint type which will set this skiplist's maximum
// level.

func (sl *SkipList) init(ifc interface{}) {
	switch ifc.(type) {
	case uint8:
		sl.maxLevel = 8
	case uint16:
		sl.maxLevel = 16
	case uint32:
		sl.maxLevel = 32
	case uint64, uint:
		sl.maxLevel = 64
	}
	sl.cache = make(nodes, sl.maxLevel)
	sl.posCache = make(widths, sl.maxLevel)
	sl.head = newNode(nil, sl.maxLevel)
}

func GetParameter(s string, params interface{}) (interface{}, bool) {
	if params == nil {
		return nil, false
	}

	if paramsValue := reflect.ValueOf(params); paramsValue.Kind() == reflect.Slice {
		if paramsValueSliceLength := paramsValue.Len(); paramsValueSliceLength > 0 {

			if p := strings.SplitN(s, ".", 2); len(p) > 1 {
				index, err := strconv.ParseUint(p[0], 10, 64)

				if err != nil || paramsValueSliceLength <= int(index) {
					return nil, false
				}

				return GetParameter(p[1], params.([]interface{})[index])
			}

			index, err := strconv.ParseUint(s, 10, 64)

			if err != nil || paramsValueSliceLength <= int(index) {
				return nil, false
			}

			return params.([]interface{})[index], true
		}

		return nil, false
	}

	if p := strings.SplitN(s, ".", 2); len(p) > 1 {
		if paramsValue := reflect.ValueOf(params); paramsValue.Kind() == reflect.Map {
			if pValue, ok := params.(map[string]interface{})[p[0]]; ok {
				return GetParameter(p[1], pValue)
			}
		} else {
			return nil, false
		}
	} else {
		if pValue, ok := params.(map[string]interface{})[p[0]]; ok {
			return pValue, true
		}
	}

	return nil, false
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Function to view table row
@param \samson\activerecord\material $material Tale material represented as row
@param Pager $pager Pager for multi page table
@return string

public function row(& $material, Pager & $pager = null, $module = NULL)
    {
        /** @var string $tdHTML Table cell HTML code */
        $tdHTML = '';
        $input = null;

        /** @var \samson\cms\CMSField $field Field of current table structure (Table column) */
        foreach ($this->fields as $field) {
            /** @var \samson\activerecord\materialfield $materialField Materialfield object (Table cell) */
            foreach ($material->onetomany['_materialfield'] as $materialField) {

                // If materialfield relates to field (column)
                $isRightField = $materialField->FieldID == $field->FieldID;

                // If field has same locale as passed
                $isRightLocale = $materialField->locale == $this->locale;

                // If field not localized then output it
                $isNotLocalizedField = $materialField->locale == '';

                if ($isRightField && (($isRightLocale) || ($isNotLocalizedField))) {

                    $this->headerFields[$field->id] = $field;
                    if ($field->Type < 9 || $field->Type > 10) {
                        $input = m('samsoncms_input_application')
                            ->createFieldByType($this->dbQuery, $field->Type, $materialField);
                    }
                    // If current field has select type then go to build his value
                    if ($field->Type == 4) {
                        /** @var \samsoncms\input\select\Select $input Select input type */
                        $input->build($field->Value);
                    }

                    // When render the input of table then call all subscribers
                    \samsonphp\event\Event::fire('samson.cms.input.table.render', array($input));

                    // Set HTML row code
                    $tdHTML .= $this->renderModule->view('table/tdView')->set($input, 'input')->output();
                    break;
                }
            }
        }

        // Render field row
        return $this->renderModule
            ->view($this->row_tmpl)
            ->set(m('samsoncms_input_text_application')->createField($this->dbQuery, $material, 'Url'), 'materialName')
            ->set($material->id, 'materialID')
            ->set($material->priority, 'priority')
            ->set($material->parent_id, 'parentID')
            ->set($this->structure->StructureID, 'structureId')
            ->set($tdHTML, 'td_view')
            ->set($pager, 'pager')
            ->output();
    }

def render
      rendered_items = ''
      swiper_classes = 'swiper-container list-generated-swiper'
      list_items = list.list_items.to_a

      list_items.each do |list_item|
        rendered_items += render_item(list_item)
      end

      if opts[:html_classes].present?
        opts[:html_classes] += " #{swiper_classes}"
      else
        opts[:html_classes] = swiper_classes
      end

      rendered_items = [
        "
#{rendered_items}
",
        "

",
        "

",
        "

"
      ].join

      content_tag :div, rendered_items, html_options, false
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
Initialises the cache.

Once this has been done the cache is all set to be used.

@param cache_definition $definition

public function initialise(cache_definition $definition) {
        $this->definition = $definition;
        $hash = preg_replace('#[^a-zA-Z0-9]+#', '_', $this->definition->get_id());
        $this->path = $this->filestorepath.'/'.$hash;
        make_writable_directory($this->path, false);
        if ($this->prescan && $definition->get_mode() !== self::MODE_REQUEST) {
            $this->prescan = false;
        }
        if ($this->prescan) {
            $this->prescan_keys();
        }
    }

def exists?(key, parameters = {})
      begin
        @memcached.get(normalize(key, parameters)) && true
      rescue  Memcached::Stored
        true
      rescue Memcached::NotFound
        nil
      end
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
:param ul: microliters as a float
        :param func: must be one of 'aspirate' or 'dispense'
        :return: microliters/mm as a float

def _ul_per_mm(self, ul: float, func: str) -> float:

        sequence = self.ul_per_mm[func]
        return pipette_config.piecewise_volume_conversion(ul, sequence)

public function toString(\Closure $linkFormatterCallback = null)
    {

        $format = $this->getFormat();

        $linkFormatter = (null !== $linkFormatterCallback) ? $linkFormatterCallback : self::getDefaultLinkFormatter();
        $placeholderFormatter = self::getPlaceholderFormatter();

        foreach ($this->getArgs() as $arg) {
            switch ($arg->getType()) {
                case ArgTypes::ARG_TYPE_HYPERLINK:
                    $format = $linkFormatter($arg, $format);
                    break;
                case ArgTypes::ARG_TYPE_BYTES:
                case ArgTypes::ARG_TYPE_DISTANCE:
                case ArgTypes::ARG_TYPE_DURATION:
                case ArgTypes::ARG_TYPE_INT_LITERAL:
                case ArgTypes::ARG_TYPE_PERCENTAGE:
                case ArgTypes::ARG_TYPE_SNAPSHOT_RECT:
                case ArgTypes::ARG_TYPE_STRING_LITERAL:
                case ArgTypes::ARG_TYPE_URL:
                case ArgTypes::ARG_TYPE_VERBATIM_STRING:
                    $format = $placeholderFormatter($arg, $format);
                    break;
                default:
                    throw new ArgException(sprintf('Unknown argument type: "%s"!', $arg->getType()));
            }
        }

        return $format;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
retrieves the config variable named ``path`` from the config file.
        Path elements that start with a $ are replaced with values from the
        dict passed as ``env``

def get_config_var(self, path, env=None):
        '''

        '''
        if env is None:
            env = {}
        result = self.conf
        for e in path.split('.'):
            if e[0] == '$':
                try:
                    result = result[env[e[1:]]]
                except KeyError as ex:
                    try:
                        result = result['.default']
                    except KeyError:
                        raise ex
            else:
                result = result[e]
        return result

def process(self, pipeline):
        """"""
        output = []
        for entry in pipeline:
            key = list(entry.keys())[0]
            # an environment block can be repeated
            if key == "env":
                self.data.env_list[0].update(entry[key])
                self.logger.debug("Updating environment at level 0 with %s",
                                  self.data.env_list[0])
                continue

            # after validation it can't be anything else but a stage
            # and the title is inside the round brackets:
            stage = Stage(self, re.match(r"stage\((?P<title>.*)\)", key).group("title"))
            result = stage.process(entry[key])
            output += result['output']
            if not result['success']:
                return {'success': False, 'output': output}

        # logging the output of the cleanup shell when registered
        for line in self.cleanup():
            output.append(line)
            self.logger.info(" | %s", line)

        self.event.succeeded()
        return {'success': True, 'output': output}

Instruction: Given a code description, retrieve the corresponding code.


Question: Create an instance of {@link JAXBElement }{@code <}{@link JournalEntry }{@code >}}

@XmlElementDecl(namespace = "http://schema.intuit.com/finance/v3", name = "JournalEntry", substitutionHeadNamespace = "http://schema.intuit.com/finance/v3", substitutionHeadName = "IntuitObject")
    public JAXBElement<JournalEntry> createJournalEntry(JournalEntry value) {
        return new JAXBElement<JournalEntry>(_JournalEntry_QNAME, JournalEntry.class, null, value);
    }

protected String parseJspLinkMacros(String content, CmsFlexController controller) {

        CmsJspLinkMacroResolver macroResolver = new CmsJspLinkMacroResolver(controller.getCmsObject(), null, true);
        return macroResolver.resolveMacros(content);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
/* (non-Javadoc)
@see com.popbill.api.StatementService#update(java.lang.String, java.number.Integer, java.lang.String, com.popbill.api.statement.Statement, java.lang.String)

@Override
	public Response update(String CorpNum, int ItemCode, String MgtKey,
			Statement statement, String UserID) throws PopbillException {
		if (MgtKey == null || MgtKey.isEmpty())
			throw new PopbillException(-99999999, "관리번호가 입력되지 않았습니다.");

		String PostData = toJsonString(statement);

		return httppost("/Statement/" + ItemCode + "/" + MgtKey, CorpNum,
				PostData, UserID, "PATCH", Response.class);
	}

protected void setValue(int newPosition, T1[] values, int number,
      boolean currentExisting) {
    if (number > 0) {
      T1 valueSum = null;
      T2 valueSumOfLogs = null;
      T1 valueSumOfSquares = null;
      T1 valueMin = null;
      T1 valueMax = null;
      for (int i = 0; i < number; i++) {
        valueSum = (i == 0) ? values[i] : operations.add11(valueSum, values[i]);
        valueSumOfLogs = (i == 0) ? operations.log1(values[i])
            : operations.add22(valueSumOfLogs, operations.log1(values[i]));
        valueSumOfSquares = (i == 0)
            ? operations.product11(values[i], values[i])
            : operations.add11(valueSumOfSquares,
                operations.product11(values[i], values[i]));
        valueMin = (i == 0) ? values[i] : operations.min11(valueMin, values[i]);
        valueMax = (i == 0) ? values[i] : operations.max11(valueMax, values[i]);
      }
      setValue(newPosition, valueSum, valueSumOfLogs, valueSumOfSquares,
          valueMin, valueMax, number, currentExisting);
    }
  }

Instruction: Given a code description, retrieve the corresponding code.


Question: Gets metadata linked from the given object.

def get_linked_metadata(obj, name=None, context=None, site=None, language=None):

    # XXX Check that 'modelinstance' and 'model' metadata are installed in backends
    # I believe that get_model() would return None if not
    Metadata = _get_metadata_model(name)
    InstanceMetadata = Metadata._meta.get_model('modelinstance')
    ModelMetadata = Metadata._meta.get_model('model')
    content_type = ContentType.objects.get_for_model(obj)
    instances = []
    if InstanceMetadata is not None:
        try:
            instance_md = InstanceMetadata.objects.get(_content_type=content_type, _object_id=obj.pk)
        except InstanceMetadata.DoesNotExist:
            instance_md = InstanceMetadata(_content_object=obj)
        instances.append(instance_md)
    if ModelMetadata is not None:
        try:
            model_md = ModelMetadata.objects.get(_content_type=content_type)
        except ModelMetadata.DoesNotExist:
            model_md = ModelMetadata(_content_type=content_type)
        instances.append(model_md)
    return FormattedMetadata(Metadata, instances, '', site, language)

public function fill_meta($meta_data) {
	foreach ($meta_data as $key => $single_meta_data) {
		$this->add_meta($key, $single_meta_data);
	}
}

Instruction: Given a code description, retrieve the corresponding code.


Question: // StripChecksum implements BinlogEvent.StripChecksum().

func (ev mariadbBinlogEvent) StripChecksum(f BinlogFormat) (BinlogEvent, []byte, error) {
	switch f.ChecksumAlgorithm {
	case BinlogChecksumAlgOff, BinlogChecksumAlgUndef:
		// There is no checksum.
		return ev, nil, nil
	default:
		// Checksum is the last 4 bytes of the event buffer.
		data := ev.Bytes()
		length := len(data)
		checksum := data[length-4:]
		data = data[:length-4]
		return mariadbBinlogEvent{binlogEvent: binlogEvent(data)}, checksum, nil
	}
}

def process(event, watch_type = nil)
      @zk.raw_event_handler(event)

      logger.debug { "EventHandler#process dispatching event for #{watch_type.inspect}: #{event.inspect}" }# unless event.type == -1
      event.zk = @zk

      cb_keys =
        if event.node_event?
          [event.path, ALL_NODE_EVENTS_KEY]
        elsif event.session_event?
          [state_key(event.state), ALL_STATE_EVENTS_KEY]
        else
          raise ZKError, "don't know how to process event: #{event.inspect}"
        end

      cb_ary = synchronize do
        clear_watch_restrictions(event, watch_type)

        @callbacks.values_at(*cb_keys)
      end

      cb_ary.flatten! # takes care of not modifying original arrays
      cb_ary.compact!

      # we only filter for node events
      if event.node_event?
        interest_key = event.interest_key
        cb_ary.select! { |sub| sub.interests.include?(interest_key) }
      end

      safe_call(cb_ary, event)
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
<strong>[icu]</strong> Returns the names for each of the characters in a string
@param s string to format
@param separator string to go between names
@return string of names

public static String getName(String s, String separator) {
        if (s.length() == 1) { // handle common case
            return getName(s.charAt(0));
        }
        int cp;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i += Character.charCount(cp)) {
            cp = s.codePointAt(i);
            if (i != 0) sb.append(separator);
            sb.append(UCharacter.getName(cp));
        }
        return sb.toString();
    }

def parse_rmd_options(line):

    parsing_context = ParsingContext(line)

    result = []
    prev_char = ''

    name = ''
    value = ''

    for char in ',' + line + ',':
        if parsing_context.in_global_expression():
            if char == ',':
                if name != '' or value != '':
                    if result and name == '':
                        raise RMarkdownOptionParsingError(
                            'Option line "{}" has no name for '
                            'option value {}'.format(line, value))
                    result.append((name.strip(), value.strip()))
                    name = ''
                    value = ''
            elif char == '=':
                if name == '':
                    name = value
                    value = ''
                else:
                    value += char
            else:
                parsing_context.count_special_chars(char, prev_char)
                value += char
        else:
            parsing_context.count_special_chars(char, prev_char)
            value += char
        prev_char = char

    if not parsing_context.in_global_expression():
        raise RMarkdownOptionParsingError(
            'Option line "{}" is not properly terminated'.format(line))

    return result

Instruction: Given a code description, retrieve the corresponding code.


Question: This function is used in post.php files to remove 4-byte UTF-8 characters (MySQL only accepts upto 3-bytes), pack multiple space values, trim and get only $length characters!

static function varchar($str, $length = 65535, $empty = '', $compact = true)
	{
		//return mb_substr(str_squash(preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $str)), 0, $length);
		//return mb_substr(trim(mb_ereg_replace('\s+', ' ', preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $str))), 0, $length);
		$str = trim(mb_substr(trim(mb_ereg_replace($compact ? '\s+' : ' +', ' ', self::utf8($str))), 0, $length)); // 2x trim() because after shortening it, we could have a space at the end of our shortened (substr) string
		return empty($str) ? $empty : $str;
	}

func RightTrim(str, chars string) string {
	if chars == "" {
		return strings.TrimRightFunc(str, unicode.IsSpace)
	}
	r, _ := regexp.Compile("[" + chars + "]+$")
	return r.ReplaceAllString(str, "")
}

Instruction: Given a code description, retrieve the corresponding code.


Question: Derive encryption keys from shared secret.

def hkdf_expand(salt, info, shared_secret):
    """"""
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.kdf.hkdf import HKDF
    from cryptography.hazmat.backends import default_backend
    hkdf = HKDF(
        algorithm=hashes.SHA512(),
        length=32,
        salt=salt.encode(),
        info=info.encode(),
        backend=default_backend()
    )
    return hkdf.derive(shared_secret)

public static ECKey fromPrivate(BigInteger privKey) {
        return new ECKey(privKey, CURVE.getG().multiply(privKey));
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // GetAllAWSCodeDeployDeploymentConfigResources retrieves all AWSCodeDeployDeploymentConfig items from an AWS CloudFormation template

func (t *Template) GetAllAWSCodeDeployDeploymentConfigResources() map[string]*resources.AWSCodeDeployDeploymentConfig {
	results := map[string]*resources.AWSCodeDeployDeploymentConfig{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSCodeDeployDeploymentConfig:
			results[name] = resource
		}
	}
	return results
}

def build_role(self, name, policies=False):

        # Build role template
        if policies:
            role = self.__template.add_resource(
                Role(
                    self.name_strip(name),
                    AssumeRolePolicyDocument=Policy(
                        Version=self.VERSION_IAM,
                        Statement=[
                            Statement(
                                Effect=Allow,
                                Principal=Principal(
                                    "Service", self.__role_principals
                                ),
                                Action=[AssumeRole],
                            )
                        ]
                    ),
                    Path=self.__role_path,
                    ManagedPolicyArns=policies,
                ))
            # Add role to list for default policy
            self.__roles_list.append(troposphere.Ref(role))
        else:
            role = self.__template.add_resource(
                Role(
                    self.name_strip(name),
                    AssumeRolePolicyDocument=Policy(
                        Version=self.VERSION_IAM,
                        Statement=[
                            Statement(
                                Effect=Allow,
                                Principal=Principal(
                                    "Service", self.__role_principals
                                ),
                                Action=[AssumeRole],
                            )
                        ]
                    ),
                    Path=self.__role_path,
                ))
            # Add role to list for default policy
            self.__roles_list.append(troposphere.Ref(role))

        return role

Instruction: Given a code description, retrieve the corresponding code.


Question:
go to parent of node with name, and set as cur_node.  Useful
        for creating new paragraphs

def parent_of(self, name):

        if not self._in_tag(name):
            return

        node = self.cur_node
        while node.tag != name:
            node = node.getparent()
        self.cur_node = node.getparent()

protected function documentFragmentCreate($source, $charset = null)
    {
        $fake              = new DOMDocumentWrapper();
        $fake->contentType = $this->contentType;
        $fake->isXML       = $this->isXML;
        $fake->isHTML      = $this->isHTML;
        $fake->isXHTML     = $this->isXHTML;
        $fake->root        = $fake->document;
        if (!$charset) {
            $charset = $this->charset;
        }
        //	$fake->documentCreate($this->charset);
        if ($source instanceof DOMNODE && !($source instanceof DOMNODELIST)) {
            $source = array($source);
        }
        if (is_array($source) || $source instanceof DOMNODELIST) {
            // dom nodes
            // load fake document
            if (!$this->documentFragmentLoadMarkup($fake, $charset)) {
                return false;
            }
            $nodes = $fake->import($source);
            foreach ($nodes as $node)
                $fake->root->appendChild($node);
        } else {
            // string markup
            $this->documentFragmentLoadMarkup($fake, $charset, $source);
        }

        return $fake;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
@param array $permissionNames

@return Permission[]
@throws PermissionNotFound

protected function getPermissionsByNames(array $permissionNames)
    {
        $permissions = [];

        foreach ($permissionNames as $permissionName) {
            if (isset($permissions[$permissionName])) {
                continue;
            }

            $permission = $this->permissionStorage->getPermission($permissionName);

            if ($permission === null) {
                throw new PermissionNotFound($permissionName);
            }

            $permissions[$permissionName] = $permission;
        }

        return $permissions;
    }

func parseVariablePermissions(v interface{}, errors, warnings *[]error) (*SubjectPermission, error) {
	switch vv := v.(type) {
	case map[string]interface{}:
		// New style with allow and/or deny properties.
		return parseSubjectPermission(vv, errors, warnings)
	default:
		// Old style
		return parseOldPermissionStyle(v, errors, warnings)
	}
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Generates PBM checksum

@since 1.0.0
@param obj $linkObj
@return string

private function generateChecksum($linkObj)
    {
        $arr = (array)$linkObj;
        $arr[] = $this->getSecretCode();

        return sha1(implode("|", $arr));
    }

protected function printPendingVersion(Version $version, $style)
    {
        /** @var Version $version */
        $id = $version->getId();
        $reflectionClass = new \ReflectionClass($version->getMigration());
        $absolutePath = $reflectionClass->getFileName();
        $fileName = $absolutePath ? $this->getRelativePath(getcwd(), $absolutePath) : '';
        $this->output->writeln("\t<$style>[$id] $fileName</$style>");
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
for each {@link Selector} in the current list, call {@link #toBaseStylerParam(org.w3c.css.sac.Selector, java.lang.String, org.w3c.css.sac.LexicalUnit)
}

@param string
@param lu
@param bln
@throws CSSException

@Override
   public void property(String string, LexicalUnit lu, boolean bln) throws CSSException {
      for (int i = 0; i < current.getLength(); i++) {
         toBaseStylerParam(current.item(i), string, lu);
      }
   }

def highlight(self, **kwargs):

        self.debug_log("Highlighting element")

        style = kwargs.get('style')
        highlight_time = kwargs.get('highlight_time', .3)

        driver = self._element._parent

        try:
            original_style = self._element.get_attribute('style')

            driver.execute_script(
                "arguments[0].setAttribute('style', arguments[1]);",
                self._element,
                style
            )
        except Exception as e:
            self.error_log("highlight exception: %s" % str(e))

        sleep(highlight_time)

        try:
            driver.execute_script(
                "arguments[0].setAttribute('style', arguments[1]);",
                self._element,
                original_style
            )
        except Exception as e:
            self.error_log("highlight exception: %s" % str(e))

        return True

Instruction: Given a code description, retrieve the corresponding code.


Question: // End the request.

func (w *ResponseWriter) End() events.APIGatewayProxyResponse {
	w.out.IsBase64Encoded = isBinary(w.header)

	if w.out.IsBase64Encoded {
		w.out.Body = base64.StdEncoding.EncodeToString(w.buf.Bytes())
	} else {
		w.out.Body = w.buf.String()
	}

	// notify end
	w.closeNotifyCh <- true

	return w.out
}

func (ctx *Context) Body() ([]byte, error) {
	if ctx.req.Body == nil {
		return []byte{}, nil
	}

	body, err := ioutil.ReadAll(ctx.req.Body)
	if err != nil {
		return nil, err
	}

	ctx.req.Body.Close()
	ctx.req.Body = ioutil.NopCloser(bytes.NewBuffer(body))

	return body, nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
// Split splits the string v using delimiter rune. Rune can be escaped
// if prefixed with the escape rune.

func Split(delim, escape rune, v string) []string {
	if delim == 0 || escape == 0 {
		return []string{v}
	}
	scanner := bufio.NewScanner(strings.NewReader(v))
	s := &splitter{delim: delim, escape: escape}
	scanner.Split(s.scan)

	out := []string{}
	for scanner.Scan() {
		out = append(out, scanner.Text())
	}
	return out
}

protected function commentOut($search, $from)
    {
        $bounds = $this->getConfigItemBounds($from);
        $file = $this->getFileContents();
        $cutted = substr($file, 0, $bounds[1]);

        preg_match_all(
            '/[\'"]' . preg_quote($search) . '[\'"]/',
            $cutted,
            $matchFacade,
            PREG_OFFSET_CAPTURE | PREG_SET_ORDER
        );
        foreach ($matchFacade as $match) {
            if (!$this->isCharInComment($cutted, $match[0][1])) {
                $commentFrom = $match[0][1];
                $comma = strpos($cutted, ',', $commentFrom);
                while ($this->isCharInComment($cutted, $comma)) {
                    $comma = strpos($cutted, ',', $comma);
                }
                $commentTill = $comma + 1;
                $this->write('*/', ['position' => $commentTill, 'symbol' => '']);
                $this->write('/*', ['position' => $commentFrom, 'symbol' => '']);
            }
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// candidates returns a superset of the edges of the given shape that intersect
// the edge AB.

func (c *CrossingEdgeQuery) candidates(a, b Point, shape Shape) []int {
	var edges []int

	// For small loops it is faster to use brute force. The threshold below was
	// determined using benchmarks.
	const maxBruteForceEdges = 27
	maxEdges := shape.NumEdges()
	if maxEdges <= maxBruteForceEdges {
		edges = make([]int, maxEdges)
		for i := 0; i < maxEdges; i++ {
			edges[i] = i
		}
		return edges
	}

	// Compute the set of index cells intersected by the query edge.
	c.getCellsForEdge(a, b)
	if len(c.cells) == 0 {
		return nil
	}

	// Gather all the edges that intersect those cells and sort them.
	// TODO(roberts): Shapes don't track their ID, so we need to range over
	// the index to find the ID manually.
	var shapeID int32
	for k, v := range c.index.shapes {
		if v == shape {
			shapeID = k
		}
	}

	for _, cell := range c.cells {
		if cell == nil {
		}
		clipped := cell.findByShapeID(shapeID)
		if clipped == nil {
			continue
		}
		for _, j := range clipped.edges {
			edges = append(edges, j)
		}
	}

	if len(c.cells) > 1 {
		edges = uniqueInts(edges)
	}

	return edges
}

def chk_genes(self, study, pop, assoc=None):
        """"""
        if len(pop) < len(study):
            exit("\nERROR: The study file contains more elements than the population file. "
                 "Please check that the study file is a subset of the population file.\n")
        # check the fraction of genomic ids that overlap between study and population
        overlap = self.get_overlap(study, pop)
        if overlap < 0.95:
            sys.stderr.write("\nWARNING: only {} fraction of genes/proteins in study are found in "
                             "the population  background.\n\n".format(overlap))
        if overlap <= self.args.min_overlap:
            exit("\nERROR: only {} of genes/proteins in the study are found in the "
                 "background population. Please check.\n".format(overlap))
        # Population and associations
        if assoc is not None and pop.isdisjoint(assoc.keys()):
            if self.objanno.name == 'gene2go':
                err = ('**FATAL: NO POPULATION ITEMS SEEN IN THE NCBI gene2go ANNOTATIONS '
                       'FOR taxid({T}). TRY: --taxid=<taxid number>')
                exit(err.format(T=next(iter(self.objanno.taxid2asscs.keys()))))
            else:
                exit('**FATAL: NO POPULATION ITEMS SEEN IN THE ANNOTATIONS')

Instruction: Given a code description, retrieve the corresponding code.


Question:
@param PersistenceContext $context
@param ParentChildMap     $map

@return void

protected function insertRelated(PersistenceContext $context, ParentChildMap $map)
    {
        /** @var Row[] $parents */
        $parents = [];
        /** @var array $children */
        $children = [];

        foreach ($map->getItems() as $key => $item) {
            $parents[$key]  = $item->getParent();
            $children[$key] = $item->getChild();
        }

        $primaryKey = $this->mapper->getPrimaryTable()->getPrimaryKeyColumnName();
        $rows       = $this->reference->syncRelated($context, [], $children);

        foreach ($rows as $key => $row) {
            $parent = $parents[$key];

            if ($row->hasColumn($primaryKey)) {
                $this->setForeignKey([$parent], $this->foreignKeyToRelated, $row->getColumn($primaryKey));
            } else {
                $row->onInsertPrimaryKey(function ($id) use ($parent) {
                    $this->setForeignKey([$parent], $this->foreignKeyToRelated, $id);
                });
            }
        }
    }

def _update_requires_resolution_inputs(self):

        input_paths = [quad[1] for quad in self.requires_resolution]
        results = resolve_multiple_existing_paths(input_paths)
        for input_name, input_value, input_class, input_index in self.requires_resolution:
            project = results[input_value]['project']
            folderpath = results[input_value]['folder']
            entity_result = results[input_value]['name']
            if input_class is None:
                if entity_result is not None:
                    if isinstance(entity_result, basestring):
                        # Case: -ifoo=job-012301230123012301230123
                        # Case: -ifoo=analysis-012301230123012301230123
                        assert(is_job_id(entity_result) or
                               (is_analysis_id(entity_result)))
                        input_value = entity_result
                    elif is_hashid(input_value):
                        input_value = {'$dnanexus_link': entity_result['id']}
                    elif 'describe' in entity_result:
                        # Then findDataObjects was called (returned describe hash)
                        input_value = {"$dnanexus_link": {"project": entity_result['describe']['project'],
                                                          "id": entity_result['id']}}
                    else:
                        # Then resolveDataObjects was called in a batch (no describe hash)
                        input_value = {"$dnanexus_link": {"project": entity_result['project'],
                                                          "id": entity_result['id']}}
                if input_index >= 0:
                    if self.inputs[input_name][input_index] is not None:
                        raise AssertionError("Expected 'self.inputs' to have saved a spot for 'input_value'.")
                    self.inputs[input_name][input_index] = input_value
                else:
                    if self.inputs[input_name] is not None:
                        raise AssertionError("Expected 'self.inputs' to have saved a spot for 'input_value'.")
                    self.inputs[input_name] = input_value
            else:
                msg = 'Value provided for input field "' + input_name + '" could not be parsed as ' + \
                      input_class + ': '
                if input_value == '':
                    raise DXCLIError(msg + 'empty string cannot be resolved')
                if entity_result is None:
                    raise DXCLIError(msg + 'could not resolve \"' + input_value + '\" to a name or ID')
                try:
                    dxpy.bindings.verify_string_dxid(entity_result['id'], input_class)
                except DXError as details:
                    raise DXCLIError(msg + str(details))
                if is_hashid(input_value):
                    input_value = {'$dnanexus_link': entity_result['id']}
                elif 'describe' in entity_result:
                    # Then findDataObjects was called (returned describe hash)
                    input_value = {'$dnanexus_link': {"project": entity_result['describe']['project'],
                                                      "id": entity_result['id']}}
                else:
                    # Then resolveDataObjects was called in a batch (no describe hash)
                    input_value = {"$dnanexus_link": {"project": entity_result['project'],
                                                      "id": entity_result['id']}}
                if input_index != -1:
                    # The class is an array, so append the resolved value
                    self.inputs[input_name].append(input_value)
                else:
                    self.inputs[input_name] = input_value

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns a Jmol script that draws symmetry or inertia axes for a structure.
Use showAxes() and hideAxes() to toggle visibility.
@return Jmol script

@Override
	public String drawAxes() {
		StringBuilder s = new StringBuilder();
//		Point3d centroid = helixAxisAligner.getCentroid();
//		System.out.println("Centroid: " + helixAxisAligner.getCentroid());
//		Point3d centroid = helixAxisAligner.getGeometricCenter();
		Point3d centroid = helixAxisAligner.calcCenterOfRotation();
//		System.out.println("Geometric center: " + centroid);
		AxisAngle4d axisAngle = helixAxisAligner.getHelixLayers().getByLowestAngle().getAxisAngle();
		Vector3d axis = new Vector3d(axisAngle.x, axisAngle.y, axisAngle.z);

		s.append("draw axesHelical");
		s.append(name);
		s.append(0);
		s.append(" ");
		s.append("line");
		Point3d v1 = new Point3d(axis);
		v1.scale(AXIS_SCALE_FACTOR*(helixAxisAligner.getDimension().y + SIDE_CHAIN_EXTENSION));
		Point3d v2 = new Point3d(v1);
		v2.negate();
		v1.add(centroid);
		v2.add(centroid);
		s.append(getJmolPoint(v1));
		s.append(getJmolPoint(v2));
		s.append("width 1.0 ");
		s.append(" color red");
		s.append(" off;");
		return s.toString();
	}

def add_quality_score_vs_no_of_observations_section(self):

        sample_data = []
        data_labels = []
        for rt_type_name, rt_type in recal_table_type._asdict().items():
            sample_tables = self.gatk_base_recalibrator[rt_type]['quality_quantization_map']
            if len(sample_tables) == 0:
                continue

            sample_data.append({
                sample: {int(x): int(y) for x, y in zip(table['QualityScore'], table['Count'])}
                for sample, table in sample_tables.items()
            })

            sample_y_sums = {
                sample: sum(int(y) for y in table['Count'])
                for sample, table
                in sample_tables.items()
            }

            sample_data.append({
                sample: {
                    int(x): float(y) / sample_y_sums[sample]
                    for x, y in zip(table['QualityScore'], table['Count'])
                }
                for sample, table in sample_tables.items()
            })

            flat_proportions = [float(y) / sample_y_sums[sample]
                                for sample, table in sample_tables.items()
                                for y in table['Count']]
            prop_ymax = max(flat_proportions)
            data_labels.append({'name': "{} Count".format(rt_type_name.capitalize().replace('_', '-')),
                                'ylab': 'Count'})
            data_labels.append({'ymax': prop_ymax,
                                'name': "{} Percent".format(rt_type_name.capitalize().replace('_', '-')),
                                'ylab': 'Percent'})

        plot = linegraph.plot(
            sample_data,
            pconfig={
                'title': "Observed Quality Score Counts",
                'id': 'gatk-base-recalibrator-quality-score-vs-number-of-observations',
                'xlab': 'Observed Quality Score',
                'ylab': 'Count',
                'xDecimals': False,
                'data_labels': data_labels,
            })

        # Reported vs empirical quality scores
        self.add_section(
            name='Observed Quality Scores',
            description=(
                'This plot shows the distribution of base quality scores in each sample before and '
                'after base quality score recalibration (BQSR). Applying BQSR should broaden the '
                'distribution of base quality scores.'
            ),
            helptext=(
                'For more information see '
                '[the Broad\'s description of BQSR]'
                '(https://gatkforums.broadinstitute.org/gatk/discussion/44/base-quality-score-recalibration-bqsr)'
                '.'
            ),
            plot=plot,
        )

Instruction: Given a code description, retrieve the corresponding code.


Question: Read requirements.txt.

def get_requires():
    """"""
    requirements = open("requirements.txt", "r").read()
    return list(filter(lambda x: x != "", requirements.split()))

public function text(string $text, string $source = 'auto', string $target = 'auto')
    {
        if (!('auto' === $source && 'auto' === $target)) {
            $this->checkTextTarget($source, $target);
        }

        return Request::exec(self::TEXT, compact('text', 'source', 'target'));
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
The text displayed on the block.

        String containing ``"%s"`` in place of inserts.

        eg. ``'say %s for %s secs'``

def text(self):

        parts = [("%s" if isinstance(p, Insert) else p) for p in self.parts]
        parts = [("%%" if p == "%" else p) for p in parts] # escape percent
        return "".join(parts)

def _prompt_placement(D, tt):

    _model_name = ""
    # There wasn't a table name match, so we need prompts to fix it
    _placement_options = _get_available_placements(D, tt)
    print("Please choose where you'd like to place this model:")
    for _idx, _opt in enumerate(_placement_options):
        print("({}) {}".format(_idx, _opt))
    _choice = input("> ")
    try:
        if int(_choice) <= len(_placement_options) and _choice:
            # Get the option the user chose
            _model_name = _placement_options[int(_choice)]
        else:
            # They user chose an option out of the placement list range
            print("Invalid choice input")
            return
    except Exception as e:
        # Choice was not a number or empty
        print("Invalid choice")

    return _model_name

Instruction: Given a code description, retrieve the corresponding code.


Question: CLI for maildirs content analysis and deletion.

def cli(ctx):

    level = logger.level
    try:
        level_to_name = logging._levelToName
    # Fallback to pre-Python 3.4 internals.
    except AttributeError:
        level_to_name = logging._levelNames
    level_name = level_to_name.get(level, level)
    logger.debug('Verbosity set to {}.'.format(level_name))

    # Print help screen and exit if no sub-commands provided.
    if ctx.invoked_subcommand is None:
        click.echo(ctx.get_help())
        ctx.exit()

    # Load up global options to the context.
    ctx.obj = {}

func (m *ContainerDelete) Field(fieldpath []string) (string, bool) {
	if len(fieldpath) == 0 {
		return "", false
	}

	switch fieldpath[0] {
	case "id":
		return string(m.ID), len(m.ID) > 0
	}
	return "", false
}

Instruction: Given a code description, retrieve the corresponding code.


Question: // ReadConfig reads configuration data from the given location.

func ReadConfig(configFilePath string) (ConfigSetterWriter, error) {
	var (
		format formatter
		config *configInternal
	)
	configData, err := ioutil.ReadFile(configFilePath)
	if err != nil {
		return nil, errors.Annotatef(err, "cannot read agent config %q", configFilePath)
	}
	format, config, err = parseConfigData(configData)
	if err != nil {
		return nil, err
	}
	logger.Debugf("read agent config, format %q", format.version())
	config.configFilePath = configFilePath
	return config, nil
}

func (ini *INI) SetComments(section, key string, comments ...string) {
	sec := ini.getSection(section)

	if key == "" {
		if sec == nil {
			sec = ini.addSection(section)
		}
		sec.Comments = comments
		return
	}

	if item := sec.getItem(key, ini.isCaseSensitive); item != nil {
		item.Comments = comments
	}
}

Instruction: Given a code description, retrieve the corresponding code.


Question: // NewSchema creates an object of type Schema if possible, returning an error if not.

func NewSchema(in interface{}, context *compiler.Context) (*Schema, error) {
	errors := make([]error, 0)
	x := &Schema{}
	m, ok := compiler.UnpackMap(in)
	if !ok {
		message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
		errors = append(errors, compiler.NewError(context, message))
	} else {
		allowedKeys := []string{"additionalProperties", "allOf", "anyOf", "default", "deprecated", "description", "discriminator", "enum", "example", "exclusiveMaximum", "exclusiveMinimum", "externalDocs", "format", "items", "maxItems", "maxLength", "maxProperties", "maximum", "minItems", "minLength", "minProperties", "minimum", "multipleOf", "not", "nullable", "oneOf", "pattern", "properties", "readOnly", "required", "title", "type", "uniqueItems", "writeOnly", "xml"}
		allowedPatterns := []*regexp.Regexp{pattern1}
		invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)
		if len(invalidKeys) > 0 {
			message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", "))
			errors = append(errors, compiler.NewError(context, message))
		}
		// bool nullable = 1;
		v1 := compiler.MapValueForKey(m, "nullable")
		if v1 != nil {
			x.Nullable, ok = v1.(bool)
			if !ok {
				message := fmt.Sprintf("has unexpected value for nullable: %+v (%T)", v1, v1)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// Discriminator discriminator = 2;
		v2 := compiler.MapValueForKey(m, "discriminator")
		if v2 != nil {
			var err error
			x.Discriminator, err = NewDiscriminator(v2, compiler.NewContext("discriminator", context))
			if err != nil {
				errors = append(errors, err)
			}
		}
		// bool read_only = 3;
		v3 := compiler.MapValueForKey(m, "readOnly")
		if v3 != nil {
			x.ReadOnly, ok = v3.(bool)
			if !ok {
				message := fmt.Sprintf("has unexpected value for readOnly: %+v (%T)", v3, v3)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// bool write_only = 4;
		v4 := compiler.MapValueForKey(m, "writeOnly")
		if v4 != nil {
			x.WriteOnly, ok = v4.(bool)
			if !ok {
				message := fmt.Sprintf("has unexpected value for writeOnly: %+v (%T)", v4, v4)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// Xml xml = 5;
		v5 := compiler.MapValueForKey(m, "xml")
		if v5 != nil {
			var err error
			x.Xml, err = NewXml(v5, compiler.NewContext("xml", context))
			if err != nil {
				errors = append(errors, err)
			}
		}
		// ExternalDocs external_docs = 6;
		v6 := compiler.MapValueForKey(m, "externalDocs")
		if v6 != nil {
			var err error
			x.ExternalDocs, err = NewExternalDocs(v6, compiler.NewContext("externalDocs", context))
			if err != nil {
				errors = append(errors, err)
			}
		}
		// Any example = 7;
		v7 := compiler.MapValueForKey(m, "example")
		if v7 != nil {
			var err error
			x.Example, err = NewAny(v7, compiler.NewContext("example", context))
			if err != nil {
				errors = append(errors, err)
			}
		}
		// bool deprecated = 8;
		v8 := compiler.MapValueForKey(m, "deprecated")
		if v8 != nil {
			x.Deprecated, ok = v8.(bool)
			if !ok {
				message := fmt.Sprintf("has unexpected value for deprecated: %+v (%T)", v8, v8)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// string title = 9;
		v9 := compiler.MapValueForKey(m, "title")
		if v9 != nil {
			x.Title, ok = v9.(string)
			if !ok {
				message := fmt.Sprintf("has unexpected value for title: %+v (%T)", v9, v9)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// float multiple_of = 10;
		v10 := compiler.MapValueForKey(m, "multipleOf")
		if v10 != nil {
			switch v10 := v10.(type) {
			case float64:
				x.MultipleOf = v10
			case float32:
				x.MultipleOf = float64(v10)
			case uint64:
				x.MultipleOf = float64(v10)
			case uint32:
				x.MultipleOf = float64(v10)
			case int64:
				x.MultipleOf = float64(v10)
			case int32:
				x.MultipleOf = float64(v10)
			case int:
				x.MultipleOf = float64(v10)
			default:
				message := fmt.Sprintf("has unexpected value for multipleOf: %+v (%T)", v10, v10)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// float maximum = 11;
		v11 := compiler.MapValueForKey(m, "maximum")
		if v11 != nil {
			switch v11 := v11.(type) {
			case float64:
				x.Maximum = v11
			case float32:
				x.Maximum = float64(v11)
			case uint64:
				x.Maximum = float64(v11)
			case uint32:
				x.Maximum = float64(v11)
			case int64:
				x.Maximum = float64(v11)
			case int32:
				x.Maximum = float64(v11)
			case int:
				x.Maximum = float64(v11)
			default:
				message := fmt.Sprintf("has unexpected value for maximum: %+v (%T)", v11, v11)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// bool exclusive_maximum = 12;
		v12 := compiler.MapValueForKey(m, "exclusiveMaximum")
		if v12 != nil {
			x.ExclusiveMaximum, ok = v12.(bool)
			if !ok {
				message := fmt.Sprintf("has unexpected value for exclusiveMaximum: %+v (%T)", v12, v12)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// float minimum = 13;
		v13 := compiler.MapValueForKey(m, "minimum")
		if v13 != nil {
			switch v13 := v13.(type) {
			case float64:
				x.Minimum = v13
			case float32:
				x.Minimum = float64(v13)
			case uint64:
				x.Minimum = float64(v13)
			case uint32:
				x.Minimum = float64(v13)
			case int64:
				x.Minimum = float64(v13)
			case int32:
				x.Minimum = float64(v13)
			case int:
				x.Minimum = float64(v13)
			default:
				message := fmt.Sprintf("has unexpected value for minimum: %+v (%T)", v13, v13)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// bool exclusive_minimum = 14;
		v14 := compiler.MapValueForKey(m, "exclusiveMinimum")
		if v14 != nil {
			x.ExclusiveMinimum, ok = v14.(bool)
			if !ok {
				message := fmt.Sprintf("has unexpected value for exclusiveMinimum: %+v (%T)", v14, v14)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// int64 max_length = 15;
		v15 := compiler.MapValueForKey(m, "maxLength")
		if v15 != nil {
			t, ok := v15.(int)
			if ok {
				x.MaxLength = int64(t)
			} else {
				message := fmt.Sprintf("has unexpected value for maxLength: %+v (%T)", v15, v15)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// int64 min_length = 16;
		v16 := compiler.MapValueForKey(m, "minLength")
		if v16 != nil {
			t, ok := v16.(int)
			if ok {
				x.MinLength = int64(t)
			} else {
				message := fmt.Sprintf("has unexpected value for minLength: %+v (%T)", v16, v16)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// string pattern = 17;
		v17 := compiler.MapValueForKey(m, "pattern")
		if v17 != nil {
			x.Pattern, ok = v17.(string)
			if !ok {
				message := fmt.Sprintf("has unexpected value for pattern: %+v (%T)", v17, v17)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// int64 max_items = 18;
		v18 := compiler.MapValueForKey(m, "maxItems")
		if v18 != nil {
			t, ok := v18.(int)
			if ok {
				x.MaxItems = int64(t)
			} else {
				message := fmt.Sprintf("has unexpected value for maxItems: %+v (%T)", v18, v18)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// int64 min_items = 19;
		v19 := compiler.MapValueForKey(m, "minItems")
		if v19 != nil {
			t, ok := v19.(int)
			if ok {
				x.MinItems = int64(t)
			} else {
				message := fmt.Sprintf("has unexpected value for minItems: %+v (%T)", v19, v19)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// bool unique_items = 20;
		v20 := compiler.MapValueForKey(m, "uniqueItems")
		if v20 != nil {
			x.UniqueItems, ok = v20.(bool)
			if !ok {
				message := fmt.Sprintf("has unexpected value for uniqueItems: %+v (%T)", v20, v20)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// int64 max_properties = 21;
		v21 := compiler.MapValueForKey(m, "maxProperties")
		if v21 != nil {
			t, ok := v21.(int)
			if ok {
				x.MaxProperties = int64(t)
			} else {
				message := fmt.Sprintf("has unexpected value for maxProperties: %+v (%T)", v21, v21)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// int64 min_properties = 22;
		v22 := compiler.MapValueForKey(m, "minProperties")
		if v22 != nil {
			t, ok := v22.(int)
			if ok {
				x.MinProperties = int64(t)
			} else {
				message := fmt.Sprintf("has unexpected value for minProperties: %+v (%T)", v22, v22)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// repeated string required = 23;
		v23 := compiler.MapValueForKey(m, "required")
		if v23 != nil {
			v, ok := v23.([]interface{})
			if ok {
				x.Required = compiler.ConvertInterfaceArrayToStringArray(v)
			} else {
				message := fmt.Sprintf("has unexpected value for required: %+v (%T)", v23, v23)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// repeated Any enum = 24;
		v24 := compiler.MapValueForKey(m, "enum")
		if v24 != nil {
			// repeated Any
			x.Enum = make([]*Any, 0)
			a, ok := v24.([]interface{})
			if ok {
				for _, item := range a {
					y, err := NewAny(item, compiler.NewContext("enum", context))
					if err != nil {
						errors = append(errors, err)
					}
					x.Enum = append(x.Enum, y)
				}
			}
		}
		// string type = 25;
		v25 := compiler.MapValueForKey(m, "type")
		if v25 != nil {
			x.Type, ok = v25.(string)
			if !ok {
				message := fmt.Sprintf("has unexpected value for type: %+v (%T)", v25, v25)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// repeated SchemaOrReference all_of = 26;
		v26 := compiler.MapValueForKey(m, "allOf")
		if v26 != nil {
			// repeated SchemaOrReference
			x.AllOf = make([]*SchemaOrReference, 0)
			a, ok := v26.([]interface{})
			if ok {
				for _, item := range a {
					y, err := NewSchemaOrReference(item, compiler.NewContext("allOf", context))
					if err != nil {
						errors = append(errors, err)
					}
					x.AllOf = append(x.AllOf, y)
				}
			}
		}
		// repeated SchemaOrReference one_of = 27;
		v27 := compiler.MapValueForKey(m, "oneOf")
		if v27 != nil {
			// repeated SchemaOrReference
			x.OneOf = make([]*SchemaOrReference, 0)
			a, ok := v27.([]interface{})
			if ok {
				for _, item := range a {
					y, err := NewSchemaOrReference(item, compiler.NewContext("oneOf", context))
					if err != nil {
						errors = append(errors, err)
					}
					x.OneOf = append(x.OneOf, y)
				}
			}
		}
		// repeated SchemaOrReference any_of = 28;
		v28 := compiler.MapValueForKey(m, "anyOf")
		if v28 != nil {
			// repeated SchemaOrReference
			x.AnyOf = make([]*SchemaOrReference, 0)
			a, ok := v28.([]interface{})
			if ok {
				for _, item := range a {
					y, err := NewSchemaOrReference(item, compiler.NewContext("anyOf", context))
					if err != nil {
						errors = append(errors, err)
					}
					x.AnyOf = append(x.AnyOf, y)
				}
			}
		}
		// Schema not = 29;
		v29 := compiler.MapValueForKey(m, "not")
		if v29 != nil {
			var err error
			x.Not, err = NewSchema(v29, compiler.NewContext("not", context))
			if err != nil {
				errors = append(errors, err)
			}
		}
		// ItemsItem items = 30;
		v30 := compiler.MapValueForKey(m, "items")
		if v30 != nil {
			var err error
			x.Items, err = NewItemsItem(v30, compiler.NewContext("items", context))
			if err != nil {
				errors = append(errors, err)
			}
		}
		// Properties properties = 31;
		v31 := compiler.MapValueForKey(m, "properties")
		if v31 != nil {
			var err error
			x.Properties, err = NewProperties(v31, compiler.NewContext("properties", context))
			if err != nil {
				errors = append(errors, err)
			}
		}
		// AdditionalPropertiesItem additional_properties = 32;
		v32 := compiler.MapValueForKey(m, "additionalProperties")
		if v32 != nil {
			var err error
			x.AdditionalProperties, err = NewAdditionalPropertiesItem(v32, compiler.NewContext("additionalProperties", context))
			if err != nil {
				errors = append(errors, err)
			}
		}
		// DefaultType default = 33;
		v33 := compiler.MapValueForKey(m, "default")
		if v33 != nil {
			var err error
			x.Default, err = NewDefaultType(v33, compiler.NewContext("default", context))
			if err != nil {
				errors = append(errors, err)
			}
		}
		// string description = 34;
		v34 := compiler.MapValueForKey(m, "description")
		if v34 != nil {
			x.Description, ok = v34.(string)
			if !ok {
				message := fmt.Sprintf("has unexpected value for description: %+v (%T)", v34, v34)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// string format = 35;
		v35 := compiler.MapValueForKey(m, "format")
		if v35 != nil {
			x.Format, ok = v35.(string)
			if !ok {
				message := fmt.Sprintf("has unexpected value for format: %+v (%T)", v35, v35)
				errors = append(errors, compiler.NewError(context, message))
			}
		}
		// repeated NamedAny specification_extension = 36;
		// MAP: Any ^x-
		x.SpecificationExtension = make([]*NamedAny, 0)
		for _, item := range m {
			k, ok := compiler.StringValue(item.Key)
			if ok {
				v := item.Value
				if strings.HasPrefix(k, "x-") {
					pair := &NamedAny{}
					pair.Name = k
					result := &Any{}
					handled, resultFromExt, err := compiler.HandleExtension(context, v, k)
					if handled {
						if err != nil {
							errors = append(errors, err)
						} else {
							bytes, _ := yaml.Marshal(v)
							result.Yaml = string(bytes)
							result.Value = resultFromExt
							pair.Value = result
						}
					} else {
						pair.Value, err = NewAny(v, compiler.NewContext(k, context))
						if err != nil {
							errors = append(errors, err)
						}
					}
					x.SpecificationExtension = append(x.SpecificationExtension, pair)
				}
			}
		}
	}
	return x, compiler.NewErrorGroupOrNil(errors)
}

func (self *Scheme) fromScope(s conversion.Scope) (inVersion, outVersion string, scheme *Scheme) {
	scheme = self
	inVersion = s.Meta().SrcVersion
	outVersion = s.Meta().DestVersion
	return inVersion, outVersion, scheme
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Sets JDBC |url|.

@param url JDBC URL
@see #getUrl

public void setUrl(final String url) {
        final String old = this.url;

        this.url = url;
        this.connectionConfig = System.currentTimeMillis();
        this.connectionValidated = false;

        this.pcs.firePropertyChange("url", old, this.url);
    }

def db_exists(name, **connection_args):
    '''

    '''
    dbc = _connect(**connection_args)
    if dbc is None:
        return False
    cur = dbc.cursor()
    # Warn: here db identifier is not backtyped but should be
    #  escaped as a string value. Note also that LIKE special characters
    # '_' and '%' should also be escaped.
    args = {"dbname": name}
    qry = "SHOW DATABASES LIKE %(dbname)s;"
    try:
        _execute(cur, qry, args)
    except MySQLdb.OperationalError as exc:
        err = 'MySQL Error {0}: {1}'.format(*exc.args)
        __context__['mysql.error'] = err
        log.error(err)
        return False
    cur.fetchall()
    return cur.rowcount == 1

Instruction: Given a code description, retrieve the corresponding code.


Question:
Sets up the actual job.

@param conf The current configuration.
@param args The command line parameters.
@return The newly created job.
@throws java.io.IOException When setting up the job fails.

public static Job createSubmittableJob(Configuration conf, String[] args)
  throws IOException {
    conf.setIfUnset("hbase.client.connection.impl",
      BigtableConfiguration.getConnectionClass().getName());
    conf.setIfUnset(BigtableOptionsFactory.BIGTABLE_RPC_TIMEOUT_MS_KEY, "60000");

    TableName tableName = TableName.valueOf(args[0]);
    conf.set(TABLE_NAME, tableName.getNameAsString());
    Path inputDir = new Path(args[1]);
    Job job = Job.getInstance(conf, conf.get(JOB_NAME_CONF_KEY, NAME + "_" + tableName));
    job.setJarByClass(Importer.class);
    FileInputFormat.setInputPaths(job, inputDir);
    // Randomize the splits to avoid hot spotting a single tablet server
    job.setInputFormatClass(ShuffledSequenceFileInputFormat.class);
    // Give the mappers enough work to do otherwise each split will be dominated by spinup time
    ShuffledSequenceFileInputFormat.setMinInputSplitSize(job, 1L*1024*1024*1024);
    String hfileOutPath = conf.get(BULK_OUTPUT_CONF_KEY);

    // make sure we get the filter in the jars
    try {
      Class<? extends Filter> filter = conf.getClass(FILTER_CLASS_CONF_KEY, null, Filter.class);
      if (filter != null) {
        TableMapReduceUtil.addDependencyJars(conf, filter);
      }
    } catch (Exception e) {
      throw new IOException(e);
    }

    if (hfileOutPath != null) {
      job.setMapperClass(KeyValueImporter.class);
      try (Connection conn = ConnectionFactory.createConnection(conf);
          Table table = conn.getTable(tableName);
          RegionLocator regionLocator = conn.getRegionLocator(tableName)){
        job.setReducerClass(KeyValueSortReducer.class);
        Path outputDir = new Path(hfileOutPath);
        FileOutputFormat.setOutputPath(job, outputDir);
        job.setMapOutputKeyClass(ImmutableBytesWritable.class);
        job.setMapOutputValueClass(KeyValue.class);
        HFileOutputFormat2.configureIncrementalLoad(job, table, regionLocator);
        TableMapReduceUtil.addDependencyJars(job.getConfiguration(),
            com.google.common.base.Preconditions.class);
      }
    } else {
      // No reducers.  Just write straight to table.  Call initTableReducerJob
      // because it sets up the TableOutputFormat.
      job.setMapperClass(Importer.class);
      //TableMapReduceUtil.initTableReducerJob(tableName.getNameAsString(), null, job);
      TableMapReduceUtil.initTableReducerJob(tableName.getNameAsString(), null, job, null, null, null, null, false);
      job.setNumReduceTasks(0);
    }
    return job;
  }

public void marshall(Output output, ProtocolMarshaller protocolMarshaller) {

        if (output == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(output.getName(), NAME_BINDING);
            protocolMarshaller.marshall(output.getKinesisStreamsOutput(), KINESISSTREAMSOUTPUT_BINDING);
            protocolMarshaller.marshall(output.getKinesisFirehoseOutput(), KINESISFIREHOSEOUTPUT_BINDING);
            protocolMarshaller.marshall(output.getLambdaOutput(), LAMBDAOUTPUT_BINDING);
            protocolMarshaller.marshall(output.getDestinationSchema(), DESTINATIONSCHEMA_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns all instances of objects with scope session

@return array

public function getSessionInstances()
    {
        $sessionObjects = [];
        foreach ($this->objects as $information) {
            if (isset($information['i']) && $information['s'] === ObjectConfiguration::SCOPE_SESSION) {
                $sessionObjects[] = $information['i'];
            }
        }
        return $sessionObjects;
    }

public function checkConnection()
    {
        $success = false;
        $message = '';
        $config  = $this->getPostConfiguration();

        try{
            $this->makeConnection($config);

            /**
             * Just trying to show tables with current connection
             */
            switch ($config['driver']) {
                case 'mysql':
                    $tables = Capsule::select('show tables');
                    break;

                case 'sqlite':
                    $tables = Capsule::select("SELECT * FROM sqlite_master WHERE type='table'");
                    break;

                case 'sqlsrv':
                    $tables = Capsule::select("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'");
                    break;

                case 'pgsql':
                    $tables = Capsule::select("SELECT * FROM pg_catalog.pg_tables");
                    break;
            }

            $success = true;
            $message = 'Successfully connected!';

        }catch(Exception $e){
            $success = false;
            $message = $e->getMessage();
        }

        Response::headers()->set('Content-Type', 'application/json');
        Response::setBody(json_encode(
            array(
                'success' => $success,
                'message' => $message,
                'config'  => $config
            )
        ));
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // Delete handles a request to delete an instance asynchronously.

func (*Instances) Delete(c context.Context, req *instances.DeleteRequest) (*empty.Empty, error) {
	if req.GetId() == "" {
		return nil, status.Errorf(codes.InvalidArgument, "ID is required")
	}
	vm := &model.VM{
		ID: req.Id,
	}
	if err := datastore.RunInTransaction(c, func(c context.Context) error {
		switch err := datastore.Get(c, vm); {
		case err == datastore.ErrNoSuchEntity:
			return nil
		case err != nil:
			return errors.Annotate(err, "failed to fetch VM").Err()
		case vm.Drained:
			return nil
		}
		vm.Drained = true
		if err := datastore.Put(c, vm); err != nil {
			return errors.Annotate(err, "failed to store VM").Err()
		}
		return nil
	}, nil); err != nil {
		return nil, err
	}
	return &empty.Empty{}, nil
}

func (d *Deployment) Reap(args *structs.DeploymentDeleteRequest,
	reply *structs.GenericResponse) error {
	if done, err := d.srv.forward("Deployment.Reap", args, args, reply); done {
		return err
	}
	defer metrics.MeasureSince([]string{"nomad", "deployment", "reap"}, time.Now())

	// Update via Raft
	_, index, err := d.srv.raftApply(structs.DeploymentDeleteRequestType, args)
	if err != nil {
		return err
	}

	// Update the index
	reply.Index = index
	return nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Add one or more maps
A map is simply a class namepsace

@param string|array 	$name
@param path 			$path
@return void

public static function map( $name, $path = null )
	{
		if ( is_array( $name ) )
		{
			static::$namespaces = array_merge( static::$namespaces, $name ); return;
		}
		static::$namespaces[$name] = $path;
	}

@Deprecated
	public static <K, V> HashMap<K, V> newHashMap() {
		return new HashMap<K, V>();
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Return currency amount formatted for display

@return StringType

public function display()
    {
        $formatter = new \NumberFormatter($this->locale->get(), \NumberFormatter::CURRENCY);
        $formatter->setSymbol(\NumberFormatter::CURRENCY_SYMBOL, $this->symbol->get());
        $formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $this->precision->get());

        return new StringType(sprintf($this->displayFormat, $formatter->format($this->getAsFloat())));
    }

public ResultResponseUtil status(IReturnCode iReturnCode) {
        this.setCode(iReturnCode.getCode());
        this.setMsg(iReturnCode.getMsg());
        return this;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Run the migrations.

@return void

public function up()
    {
        Schema::table('component_groups', function (Blueprint $table) {
            $table->dropcolumn('collapsed');
        });

        Schema::table('component_groups', function (Blueprint $table) {
            $table->integer('collapsed')->unsigned()->default(1)->after('order');
        });
    }

func (md *RootMetadataV2) ClearForV4Migration() {
	md.WKeys = nil
	md.RKeys = nil
	md.Extra.UnresolvedWriters = nil
	md.UnresolvedReaders = nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question: // Activate actives the given unit in the given wantPath.

func (uw *UnitWriter) Activate(unit, wantPath string) {
	if uw.err != nil {
		return
	}

	if err := os.Symlink(path.Join("..", unit), wantPath); err != nil && !os.IsExist(err) {
		uw.err = errwrap.Wrap(errors.New("failed to link service want"), err)
	}
}

public function publishNodeAction(NodeInterface $node, Workspace $selectedWorkspace)
    {
        $this->publishingService->publishNode($node);
        $this->addFlashMessage($this->translator->translateById('workspaces.selectedChangeHasBeenPublished', [], null, null, 'Modules', 'Neos.Neos'));
        $this->redirect('show', null, null, ['workspace' => $selectedWorkspace]);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Initializes the dialog content with the replace information.<p>

@param replaceInfo the replace information

protected void initContent(CmsReplaceInfo replaceInfo) {

        m_replaceInfo = replaceInfo;
        CmsListItemWidget fileInfoItem = new CmsListItemWidget(m_replaceInfo.getFileInfo());
        m_mainPanel.setReplaceInfo(fileInfoItem);
        if (!m_replaceInfo.isLockable()) {
            m_mainPanel.displayDialogInfo(Messages.get().key(Messages.GUI_REPLACE_LOCKED_RESOURCE_0), true);
        } else {
            m_mainPanel.displayDialogInfo(Messages.get().key(Messages.GUI_REPLACE_INFO_0), false);
            checkFileType();
            createButtons();
        }
    }

private function loadParameters(ContainerBuilder $container)
    {
        $container->setParameter('gherkin.paths.lib', $this->getLibPath());
        $container->setParameter('gherkin.paths.i18n', '%gherkin.paths.lib%/i18n.php');
        $container->setParameter(
            'suite.generic.default_settings',
            array(
                'paths'    => array('%paths.base%/features'),
                'contexts' => array('FeatureContext')
            )
        );
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: parseUri 1.2.2 (c) Steven Levithan <stevenlevithan.com> MIT License

function(str) {
            var o   = parseUri.options,
            m   = o.parser.exec(str),
            uri = {},
            i   = 14;

            while (i--) if (m[i]) uri[o.key[i]] = m[i];

            if (uri[o.key[12]]) {
                uri[o.q.name] = {};
                uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
                    if ($1) uri[o.q.name][$1] = $2;
                });
            }
            // member functions
            uri.toString = toString;
            uri.validate = validate;
            uri.normalize = normalize;
            uri.contains = contains;
            uri.originOnly = originOnly;
            return uri;
        }

def _format_url(instrument_type,
                instrument_ids,
                start_date,
                end_date,
                earliest_allowed_date):

    return (
        "http://www.bankofcanada.ca/stats/results/csv"
        "?lP=lookup_{instrument_type}_yields.php"
        "&sR={restrict}"
        "&se={instrument_ids}"
        "&dF={start}"
        "&dT={end}".format(
            instrument_type=instrument_type,
            instrument_ids='-'.join(map(prepend("L_"), instrument_ids)),
            restrict=earliest_allowed_date.strftime("%Y-%m-%d"),
            start=start_date.strftime("%Y-%m-%d"),
            end=end_date.strftime("%Y-%m-%d"),
        )
    )

Instruction: Given a code description, retrieve the corresponding code.


Question: Builds an index for an n-cell.  This is more general than dual, but less efficient

function incidence(from_cells, to_cells) {
  var index = new Array(from_cells.length)
  for(var i=0, il=index.length; i<il; ++i) {
    index[i] = []
  }
  var b = []
  for(var i=0, n=to_cells.length; i<n; ++i) {
    var c = to_cells[i]
    var cl = c.length
    for(var k=1, kn=(1<<cl); k<kn; ++k) {
      b.length = bits.popCount(k)
      var l = 0
      for(var j=0; j<cl; ++j) {
        if(k & (1<<j)) {
          b[l++] = c[j]
        }
      }
      var idx=findCell(from_cells, b)
      if(idx < 0) {
        continue
      }
      while(true) {
        index[idx++].push(i)
        if(idx >= from_cells.length || compareCells(from_cells[idx], b) !== 0) {
          break
        }
      }
    }
  }
  return index
}

func NewBloomIndexer(db ethdb.Database, size, confirms uint64) *core.ChainIndexer {
	backend := &BloomIndexer{
		db:   db,
		size: size,
	}
	table := rawdb.NewTable(db, string(rawdb.BloomBitsIndexPrefix))

	return core.NewChainIndexer(db, table, backend, size, confirms, bloomThrottling, "bloombits")
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
<p>
One or more Elastic IP addresses.
</p>

@param publicIps
One or more Elastic IP addresses.

public void setPublicIps(java.util.Collection<String> publicIps) {
        if (publicIps == null) {
            this.publicIps = null;
            return;
        }

        this.publicIps = new com.amazonaws.internal.SdkInternalList<String>(publicIps);
    }

def role_create(role, principal, endpoint_id):

    principal_type, principal_val = principal

    client = get_client()

    if principal_type == "identity":
        principal_val = maybe_lookup_identity_id(principal_val)
        if not principal_val:
            raise click.UsageError(
                "Identity does not exist. "
                "Use --provision-identity to auto-provision an identity."
            )
    elif principal_type == "provision-identity":
        principal_val = maybe_lookup_identity_id(principal_val, provision=True)
        principal_type = "identity"

    role_doc = assemble_generic_doc(
        "role", principal_type=principal_type, principal=principal_val, role=role
    )

    res = client.add_endpoint_role(endpoint_id, role_doc)
    formatted_print(res, simple_text="ID: {}".format(res["id"]))

Instruction: Given a code description, retrieve the corresponding code.


Question:
Recursively clears the specified directory.

@param string $path the directory path

protected function clearDirectory($path)
    {
        $iterator = new \DirectoryIterator($path);

        /** @var \DirectoryIterator $fileinfo */
        foreach ($iterator as $fileinfo) {
            if ($fileinfo->isDot()) {
                continue;
            }

            if ($fileinfo->isFile() || $fileinfo->isLink()) {
                @unlink($fileinfo->getPathname());
            } elseif ($fileinfo->isDir()) {
                $this->clearDirectory($fileinfo->getPathname());
            }
        }
    }

protected function archive($args) {
		$type    = $args['type'];
		$targets = isset($args['targets']) && is_array($args['targets']) ? $args['targets'] : array();

		if (($volume = $this->volume($targets[0])) == false) {
			return $this->error(self::ERROR_ARCHIVE, self::ERROR_TRGDIR_NOT_FOUND);
		}

		return ($file = $volume->archive($targets, $args['type']))
			? array('added' => array($file))
			: array('error' => $this->error(self::ERROR_ARCHIVE, $volume->error()));
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
/*!
Coerce an object for specific action: `get`, `set`, `remove`, `exists`

function coerce (type, obj, path, value) {
  if (isNil(path)) return;

  // Turn positive integer into string
  if (isPositiveInteger(path)) path = String(path);

  // Parse string path into an array
  if (isString(path)) {
    path = compact(path.trim().split(SEPERATOR));
  }

  // Return if path is invalid
  if (!path || !isArray(path) || path.length === 0) return;

  // Copy array for future use
  path = path.slice();

  // Shift the first path value
  var key = path.shift();

  // Return `undefined` if obj is `NaN` or `null` or `undefined`
  if (isNil(obj)) return;

  switch (type) {
    case 'get':
      if (path.length === 0) {
        return obj[key];
      }
      break;
    case 'set':
      if (path.length) {
        if (typeof obj[key] === 'undefined') {
          obj[key] = {};
        }

        if (isNil(obj[key])) return false;
      } else {
        obj[key] = value;
        return true;
      }
      break;
    case 'remove':
      if (path.length === 0) {

        if (isArray(obj) && isPositiveInteger(key)) {
          key = Number(key);

          if (obj.length - 1 < key) return false;

          obj.splice(key, 1);
        } else {
          if (!Object.hasOwnProperty.call(obj, key)) return false;

          delete obj[key];
        }

        return true;
      }
      break;
    case 'exists':
      if (path.length === 0) {
        if (isArray(obj) && isPositiveInteger(key)) {
          key = Number(key);
          return obj.length - 1 >= key;
        } else {
          return Object.hasOwnProperty.call(obj, key);
        }
      }
      break;
    default:
      return;
  }

  return coerce(type, obj[key], path, value);
}

def enable_compression(self,
                           force: Optional[Union[bool, ContentCoding]]=None
                           ) -> None:
        """"""
        # Backwards compatibility for when force was a bool <0.17.
        if type(force) == bool:
            force = ContentCoding.deflate if force else ContentCoding.identity
            warnings.warn("Using boolean for force is deprecated #3318",
                          DeprecationWarning)
        elif force is not None:
            assert isinstance(force, ContentCoding), ("force should one of "
                                                      "None, bool or "
                                                      "ContentEncoding")

        self._compression = True
        self._compression_force = force

Instruction: Given a code description, retrieve the corresponding code.


Question: create the `mousedown` handler for the i-th handle

function (i) {
      return function (e) {
        if (this.props.disabled) return;
        var position = this._getMousePosition(e);
        this._start(i, position[0]);
        this._addHandlers(this._getMouseEventMap());
        pauseEvent(e);
      }.bind(this);
    }

public function dispatchCommentUpdateEvent(Post $post, Comment $comment, $changeSet)
    {
        $event = new LogCommentUpdateEvent($post, $comment, $changeSet, $this->translator);

        return $this->dispatch($event);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Execute an HTTP request to get details on a queue, and
        return it.

def info(self):

        url = "queues/%s" % (self.name,)
        result = self.client.get(url)

        return result['body']['queue']

def populate_event_que(self, que_obj):

        for ip in self.obj_dict:
            drvr_obj = self.obj_dict.get(ip).get('drvr_obj')
            drvr_obj.populate_event_que(que_obj)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns a dict representation of this instance suitable for
        conversion to YAML.

def to_dict(self):

        return {
            'model_type': 'segmented_discretechoice',
            'name': self.name,
            'segmentation_col': self.segmentation_col,
            'sample_size': self.sample_size,
            'probability_mode': self.probability_mode,
            'choice_mode': self.choice_mode,
            'choosers_fit_filters': self.choosers_fit_filters,
            'choosers_predict_filters': self.choosers_predict_filters,
            'alts_fit_filters': self.alts_fit_filters,
            'alts_predict_filters': self.alts_predict_filters,
            'interaction_predict_filters': self.interaction_predict_filters,
            'estimation_sample_size': self.estimation_sample_size,
            'prediction_sample_size': self.prediction_sample_size,
            'choice_column': self.choice_column,
            'default_config': {
                'model_expression': self.default_model_expr,
            },
            'remove_alts': self.remove_alts,
            'fitted': self.fitted,
            'models': {
                yamlio.to_scalar_safe(name):
                    self._process_model_dict(m.to_dict())
                for name, m in self._group.models.items()
            }
        }

def _items(self, type_filter=None, name=None):

        if name:
            if type_filter and self._key_attr == 'type':
                if name in type_filter and name in self:
                    yield name, self[name]
            elif name in self:
                yield name, self[name]

        elif type_filter and self._key_attr == 'type':
            for key, val in self.items():
                if key in type_filter:
                    yield key, val
        else:
            for key, val in self.items():
                yield key, val

Instruction: Given a code description, retrieve the corresponding code.


Question:
Populate JSON object for a top level exception or error.

@param errorInfo additional information to append to exceptions and causes
@param error     the top level exception or error.
@return JSON object representing the Throwable.

@SuppressWarnings("unchecked")
    @Trivial
    private JSONObject toJSONObjectForThrowable(Map<String, ?> errorInfo, Throwable error) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(this, tc, "toJSONObjectForThrowable", errorInfo, error);

        LinkedHashMap<String, List<?>> addedInfo = new LinkedHashMap<String, List<?>>();
        for (Map.Entry<String, ?> entry : errorInfo.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof List)
                addedInfo.put(entry.getKey(), (List<?>) value);
        }

        JSONObject json = new OrderedJSONObject();

        int index = 0;
        JSONObject current = json;
        Set<Throwable> causes = new HashSet<Throwable>(); // avoid cycles in exception chain
        for (Throwable cause = error; cause != null && causes.add(cause); index++) {
            // custom attributes for position in exception chain (for example, sqlState and errorCode for dataSource)
            for (Map.Entry<String, List<?>> entry : addedInfo.entrySet()) {
                List<?> values = entry.getValue();
                if (values.size() > index) {
                    Object value = values.get(index);
                    if (value != null)
                        current.put(entry.getKey(), value);
                }
            }

            current.put("class", cause.getClass().getName());
            current.put("message", cause.getMessage());

            JSONArray stack = new JSONArray();
            for (StackTraceElement element : cause.getStackTrace())
                stack.add(element.toString());
            current.put("stack", stack);

            if ((cause = cause.getCause()) != null) {
                Map<String, Object> parent = current;
                parent.put("cause", current = new OrderedJSONObject());
            }
        }

        return json;
    }

public void detail(MethodNode methodNode, MethodAttributes attrs, StringBuilder output) {
        Validate.notNull(methodNode);
        Validate.notNull(attrs);
        Validate.notNull(output);

        int methodId = attrs.getSignature().getMethodId();

        output.append("Class Name: ").append(attrs.getSignature().getClassName().replace('/', '.')).append('\n');
        output.append("Method Name: ").append(attrs.getSignature().getMethodName()).append('\n');
        output.append("Method Params: ").append(attrs.getSignature().getMethodDescriptor()).append('\n');
        output.append("Method Return: ").append(attrs.getSignature().getReturnType()).append('\n');
        output.append("Method ID: ").append(methodId).append('\n');
        output.append("------------------------------------\n");

        UnmodifiableList<ContinuationPoint> cps = attrs.getContinuationPoints();
        for (int i = 0; i < cps.size(); i++) {
            ContinuationPoint cp = cps.get(i);

            int line = cp.getLineNumber() == null ? -1 : cp.getLineNumber();
            String header = String.format("Continuation Point ID: %-4d Line: %-4d Type: %s",
                    i,
                    line,
                    cp.getClass().getSimpleName());
            output.append(header).append('\n');

            // Check out PackStateGenerators class for how things are organized. Brief overview follows...
            // container[0] has local variables that are bytes/shorts/ints
            // container[1] has local variables that are floats
            // container[2] has local variables that are longs
            // container[3] has local variables that are doubles
            // container[4] has local variables that are Objects
            // container[5] has operands that are bytes/shorts/ints
            // container[6] has operands that are floats
            // container[7] has operands that are longs
            // container[8] has operands that are doubles
            // container[9] has operands that are Objects
            detailLocals(cp, methodNode, output);
            detailOperands(cp, output);

            output.append('\n');
        }

        output.append('\n');
    }

Instruction: Given a code description, retrieve the corresponding code.


public void init(final DeviceData deviceData, final ORB orb) throws DevFailed {
        deviceData.setAny(orb.create_any());
    }

def text message
      @suggested_w = @width || (FFI::NCurses.COLS * 0.80).floor
      @suggested_h = @height || (FFI::NCurses.LINES * 0.80).floor

      message_col = 3
      r = 2
      display_length = @suggested_w-4
      display_length -= message_col
      clr = @color || :white
      bgclr = @bgcolor || :black

      if message.is_a? Array
        l = longest_in_list message
        if l > @suggested_w
          if l < FFI::NCurses.COLS
            #@suggested_w = l
            @suggested_w = FFI::NCurses.COLS-2
          else
            @suggested_w = FFI::NCurses.COLS-2
          end
          display_length = @suggested_w-6
        end
        # reduce width and height if you can based on array contents
      else
        message = wrap_text(message, display_length).split("\n")
      end
      # now that we have moved to textpad that +8 was causing black lines to remain after the text
      message_height = message.size #+ 8
      # reduce if possible if its not required.
      #
      r1 = (FFI::NCurses.LINES-@suggested_h)/2
      r1 = r1.floor
      w = @suggested_w
      c1 = (FFI::NCurses.COLS-w)/2
      c1 = c1.floor
      @suggested_row = r1
      @suggested_col = c1
      brow = @button_row || @suggested_h-4
      available_ht = brow - r + 1
      message_height = [message_height, available_ht].min
      # replaced 2014-04-14 - 23:51
      message_label = Canis::TextPad.new @form, {:name=>"message_label", :text => message,
        :row => r, :col => message_col, :width => display_length, :suppress_borders => true,
        :height => message_height, :bgcolor => bgclr , :color => clr}
      #message_label.set_content message
      yield message_label if block_given?

    end

Instruction: Given a code description, retrieve the corresponding code.