Question:
Set the time until the cache should expire.
@param DateInterval $interval In what time the cache should expire.
@return CachePolicy Provides fluent interface

public function setExpiresIn(DateInterval $interval)
    {
        $now = new DateTimeImmutable();
        $expire = $now->add($interval);
        $this->setExpiresInSeconds($expire->getTimestamp() - $now->getTimestamp());
        return $this;
    }

protected function parseExpress()
    {
        $options = $this->options;

        // 获取数据表
        if (empty($options['table'])) {
            $options['table'] = $this->getTable();
        }

        foreach (['where', 'data'] as $name) {
            if (!isset($options[$name])) {
                $options[$name] = [];
            }
        }

        $modifiers = empty($options['modifiers']) ? [] : $options['modifiers'];
        if (isset($options['comment'])) {
            $modifiers['$comment'] = $options['comment'];
        }

        if (isset($options['maxTimeMS'])) {
            $modifiers['$maxTimeMS'] = $options['maxTimeMS'];
        }

        if (!empty($modifiers)) {
            $options['modifiers'] = $modifiers;
        }

        if (!isset($options['projection']) || '*' == $options['projection']) {
            $options['projection'] = [];
        }

        if (!isset($options['typeMap'])) {
            $options['typeMap'] = $this->getConfig('type_map');
        }

        if (!isset($options['limit'])) {
            $options['limit'] = 0;
        }

        foreach (['master', 'fetch_cursor'] as $name) {
            if (!isset($options[$name])) {
                $options[$name] = false;
            }
        }

        if (isset($options['page'])) {
            // 根据页数计算limit
            list($page, $listRows) = $options['page'];
            $page                  = $page > 0 ? $page : 1;
            $listRows              = $listRows > 0 ? $listRows : (is_numeric($options['limit']) ? $options['limit'] : 20);
            $offset                = $listRows * ($page - 1);
            $options['skip']       = intval($offset);
            $options['limit']      = intval($listRows);
        }

        $this->options = [];
        return $options;
    }

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


Question: // CurrentToken returns the matched token for the current request, if any.

func CurrentToken(r *http.Request) *session.Session {
	if rv := context.Get(r, tokenKey); rv != nil {
		return rv.(*session.Session)
	}

	return nil
}

public function handleRequest($parent, $upstream)
    {
        $req = $this->beginRequest($parent, $upstream);
        return $req ?: $parent;
    }

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


Question:
// Head registers a route prefix and will invoke the Handler when the route
// matches the prefix and the request METHOD is HEAD

func (w *Weavebox) Head(route string, h Handler) {
	w.add("HEAD", route, h)
}

private static function invalidRequestHandler(ContainerInterface $container): InvalidRequestHandlerInterface
    {
        if (!$container->has(InvalidRequestHandlerInterface::class)) {
            return new InvalidRequestHandler();
        }

        return $container->get(InvalidRequestHandlerInterface::class);
    }

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


Question:
Checks if token is an error and processes it.

@param Token $token
@return $this
@throws SyntaxException
@throws UnknownSyntaxException

protected function assertErrorToken(Token $token)
    {
        if (!$token->isError()) {
            return $this;
        }
        switch ($token->getType()) {
            case Token::TYPE_ERROR_INVALID_ESCAPE:
                throw new SyntaxException(
                    "Invalid escape sequence at position #{$this->getNextPosition()}",
                    $this->getNextPosition()
                );

            default:
                throw new UnknownSyntaxException(
                    "Unknown type of error token: {$token->getType()} at position #{$this->getNextPosition()}",
                    $this->getNextPosition()
                );
        }
    }

public function getToken(IHttpHeaders $headers) {
        $header = $this->getHeader($headers);

        return $this->parseHeader($header);
    }

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


Question: Helper function for opt_soft

def _fill_matrix(rot_crop_matrix, eigvectors):

    (x, y) = rot_crop_matrix.shape

    row_sums = np.sum(rot_crop_matrix, axis=1)
    row_sums = np.reshape(row_sums, (x, 1))

    # add -row_sums as leftmost column to rot_crop_matrix
    rot_crop_matrix = np.concatenate((-row_sums, rot_crop_matrix), axis=1)

    tmp = -np.dot(eigvectors[:, 1:], rot_crop_matrix)

    tmp_col_max = np.max(tmp, axis=0)
    tmp_col_max = np.reshape(tmp_col_max, (1, y + 1))

    tmp_col_max_sum = np.sum(tmp_col_max)

    # add col_max as top row to rot_crop_matrix and normalize
    rot_matrix = np.concatenate((tmp_col_max, rot_crop_matrix), axis=0)
    rot_matrix /= tmp_col_max_sum

    return rot_matrix

public function run()
    {
        $tag = ArrayHelper::remove($this->options, 'tag', 'div');
        $html = Html::beginTag($tag, $this->options);

        $html .= $this->renderSwitch();

        $html .= Html::endTag($tag);

        return $html;
    }

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


Question: // Validate inspects the fields of the type to determine if they are valid.

func (s *SuggestionQuery) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "SuggestionQuery"}
	if s.PropertyNameQuery != nil {
		if err := s.PropertyNameQuery.Validate(); err != nil {
			invalidParams.AddNested("PropertyNameQuery", err.(request.ErrInvalidParams))
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

func (s *messageStoreImpl) CheckValid(message interface{}) bool {
	s.lock.RLock()
	defer s.lock.RUnlock()

	for _, m := range s.messages {
		if s.pol(message, m.data) == common.MessageInvalidated {
			return false
		}
	}
	return true
}

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


Question:
when shows edit notification form

@param Model $eloquent

public function onSystem()
    {
        Breadcrumbs::register('error-log', function($breadcrumbs) {
            $breadcrumbs->push('Error Log', handles('antares::logger/system/index'));
        });
        $view = !is_null(from_route('date')) ? view('antares/logger::admin.partials._breadcrumb')->render() : Breadcrumbs::render('error-log');
        view()->share('breadcrumbs', $view);
    }

public function instancesByDate($selfedit = "false") {
        $this->selfedit = $selfedit;

        if ($selfedit == "true") {
            $this->moufManager = MoufManager::getMoufManager();
        } else {
            $this->moufManager = MoufManager::getMoufManagerHiddenInstance();
        }

        $this->contentBlock->addFile(dirname(__FILE__)."/../views/listComponents.php", $this);
        $this->template->toHtml();
    }

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


Question:
Encodes a string in the preferred encoding.

    Returns:
      bytes: encoded string.

def _EncodeString(self, string):

    try:
      # Note that encode() will first convert string into a Unicode string
      # if necessary.
      encoded_string = string.encode(
          self.preferred_encoding, errors=self._encode_errors)
    except UnicodeEncodeError:
      if self._encode_errors == 'strict':
        logger.error(
            'Unable to properly write output due to encoding error. '
            'Switching to error tolerant encoding which can result in '
            'non Basic Latin (C0) characters to be replaced with "?" or '
            '"\\ufffd".')
        self._encode_errors = 'replace'

      encoded_string = string.encode(
          self.preferred_encoding, errors=self._encode_errors)

    return encoded_string

function secretKey(length, options = {}) {
  if (!length || length < 1) {
    return '';
  }

  if (!options.crypto || typeof options.crypto.randomBytes !== 'function') {
    throw new Error('Expecting options.crypto to have a randomBytes function');
  }

  return options.crypto
    .randomBytes(length)
    .toString('base64') // convert format
    .slice(0, length); // return required number of characters
}

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


Question:
Lookup a ClassNode by its name from the source unit

@param type the name of the class whose ClassNode we want to lookup
@return a ClassNode representing the class

public ClassNode lookupClassNodeFor(String type) {
        for (ClassNode cn : typeCheckingVisitor.getSourceUnit().getAST().getClasses()) {
            if (cn.getName().equals(type))
                return cn;
        }

        return null;
    }

public void setIdentifierResolver(final Object identifierResolver) {
        if (identifierResolver instanceof IdentifierResolver) {
            this.identifierResolver = (IdentifierResolver) identifierResolver;
        } else if (identifierResolver instanceof String) {
            this.identifierResolver = new IdentifierResolver() {
                public String getIdentifierFor(String nodeName) {
                    return (String) identifierResolver;
                }
            };
        } else if (identifierResolver instanceof Closure) {
            final ObjectGraphBuilder self = this;
            this.identifierResolver = new IdentifierResolver() {
                public String getIdentifierFor(String nodeName) {
                    Closure cls = (Closure) identifierResolver;
                    cls.setDelegate(self);
                    return (String) cls.call(new Object[]{nodeName});
                }
            };
        } else {
            this.identifierResolver = new DefaultIdentifierResolver();
        }
    }

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


Question: Re-implemented from :meth:`AbstractComponentWidget<sparkle.gui.stim.abstract_component_editor.AbstractComponentWidget.saveToObject>`

def saveToObject(self):
        """"""
        details = self._component.auto_details()
        for field, widget in self.inputWidgets.items():
            self._component.set(field, widget.value())
        self.attributesSaved.emit(self._component.__class__.__name__, self._component.stateDict())

public function edit($id)
    {
        $this->request->allowMethod(['get', 'put']);

        $menu = $this->Menus->get($id);

        if ($this->request->is('put')) {
            $menu = $this->Menus->patchEntity($menu, $this->request->data);
            if ($this->Menus->save($menu)) {
                $this->Flash->success(__d('wasabi_core', 'The menu <strong>{0}</strong> has been saved.', $this->request->data['name']));
                $this->redirect(['action' => 'index']);
                return;
            } else {
                $this->Flash->error($this->formErrorMessage);
            }
        }
        $this->set([
            'menu' => $menu,
            'menuItems' => $this->MenuItems->find('threaded', ['order' => ['lft' => 'ASC']])->where(['MenuItems.menu_id' => $id])->hydrate(false)
        ]);
        $this->render('add');
    }

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


Question: // List runs the list action.

func (c *LabelController) List(ctx *app.ListLabelContext) error {
	err := application.Transactional(c.db, func(appl application.Application) error {
		labels, err := appl.Labels().List(ctx, ctx.SpaceID)
		if err != nil {
			return err
		}
		res := &app.LabelList{}
		res.Data = ConvertLabels(appl, ctx.Request, labels)
		return ctx.OK(res)
	})
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	return nil
}

func (t *TabletTracker) TabletsInUse() string {
	t.mu.Lock()
	defer t.mu.Unlock()

	var aliases []string
	for alias := range t.usedTablets {
		aliases = append(aliases, alias)
	}
	sort.Strings(aliases)
	return strings.Join(aliases, " ")
}

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


Question:
// == Access to file
// Load loads the history from the file.

func (h *history) Load() {
	in := bufio.NewReader(h.file)

	for {
		line, err := in.ReadString('\n')
		if err == io.EOF {
			break
		}

		h.li.PushBack(strings.TrimRight(line, "\n"))
	}

	h.mark = h.li.Back() // Point to an element.
}

def parser(self, lines):
        """"""
        while len(lines) > 0:
            if lines[0].startswith('##') and lines[1].startswith('# '):
                # A two-line keyword/value line starts here.
                self._header_append(lines.pop(0), lines.pop(0))
            elif lines[0].startswith('# '):
                # Lines with single comments are exposure numbers unless preceeded by double comment line
                self._append_file_id(lines.pop(0))
            elif lines[0].startswith('##'):
                # Double comment lines without a single comment following are column headers for dataset.
                self._set_column_names(lines.pop(0)[2:])
            else:
                # Last line of the header reached.
                return self
        raise IOError("Failed trying to read header")

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


Question: // SetConfigurationArn sets the ConfigurationArn field's value.

func (s *BrokerSoftwareInfo) SetConfigurationArn(v string) *BrokerSoftwareInfo {
	s.ConfigurationArn = &v
	return s
}

public function getOption($name) {
		$this->validateName($name);
		if (array_key_exists($name, $this->config))
			return $this->config[$name];

		return null;
	}

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


Question:
GET SYNSET STRING //
Obtain a string representation of a WordNet object including its hypernyms / hyponyms.

@param {Object} input - wordNet object
@param {number} depth - current indentation depth
@returns {string} string representation

function getSynsetString( input, depth ){
	var current_depth = depth + 1;
	var words;
	if ( isArray(input.words) ) {
		words = input.words.map( function( item ) {
			return item.lemma;
		});
	} else {
		words = new Array( input.lemma );
	}
	var str = "S: (" + input.pos + ") ";
	str += words.join( ", " );
	str += " (" + input.definition + ")";

	if ( input.hypernym ) {
		if ( isArray( input.hypernym ) ){
			input.hypernym.forEach( function( elem ) {
				var times = current_depth * 4;
				var spaces = String( " " ).repeat( times );
				str += "\n" + spaces + getSynsetString( elem, current_depth );
			});
		} else{
			str += "  " + getSynsetString( input.hypernym, current_depth );
		}
	}
	if ( input.hyponym ) {
		if ( isArray(input.hyponym) ) {
			input.hyponym.forEach( function( elem ) {
				var times = current_depth * 4;
				var spaces = String(" ").repeat( times );
				str += "\n" + spaces + getSynsetString( elem, current_depth );
			});
		} else {
			str += "  " + getSynsetString( input.hyponym, current_depth );
		}
	}
	return str;
}

def abbreviation_definitions(self):
        """"""
        abbreviations = []
        if self.abbreviation_detector:
            # log.debug('Detecting abbreviations')
            ners = self.unprocessed_ner_tags
            for abbr_span, long_span in self.abbreviation_detector.detect_spans(self.raw_tokens):
                abbr = self.raw_tokens[abbr_span[0]:abbr_span[1]]
                long = self.raw_tokens[long_span[0]:long_span[1]]
                # Check if long is entirely tagged as one named entity type
                long_tags = ners[long_span[0]:long_span[1]]
                unique_tags = set([tag[2:] for tag in long_tags if tag is not None])
                tag = long_tags[0][2:] if None not in long_tags and len(unique_tags) == 1 else None
                abbreviations.append((abbr, long, tag))
        return abbreviations

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


Question:
Add labels.

@param Search $entity

@return Builder

public function addLabels(Search $entity)
    {
        if ($entity->getLabels()->count()) {
            $this->add(function (QueryBuilder $query) use ($entity) {
                $ids = [];
                foreach ($entity->getLabels() as $label) {
                    $ids[] = (int) $label->getId();
                }
                $query
                    ->innerJoin('i.labels', 'l')
                    ->andWhere('l.id IN ('.implode(',', $ids).')');
            });
            $this->select->andHaving('COUNT(i.id) = '.$entity->getLabels()->count());
        }

        return $this;
    }

public String getParameterValue(String name) throws RepositoryConfigurationException
   {
      String value = getParameterValue(name, null);
      if (value == null)
         throw new RepositoryConfigurationException("Parameter " + name + " not found ");
      return value;
   }

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


Question:
Make sure the request URI fits how we want it to

@param string $requestURI

private function validateRequestURI(&$requestURI)
    {
        if ($requestURI != '/' && substr($requestURI, -1) == '/') {
            $url = rtrim($requestURI, '/');

            if (php_sapi_name() === 'cli') {
                exit("Please ensure the URL you typed in does not have a trailing backslash.\n");
            }

            header("Location: " . $url);
            exit();
        }
    }

public function parseRoute($routeSpec)
    {
        $path           = isset($routeSpec['path']) ? $routeSpec['path'] : null;
        $methods        = isset($routeSpec['methods']) ? $routeSpec['methods'] : array();
        $controller     = isset($routeSpec['controller']) ? $routeSpec['controller'] : null;
        $calls          = isset($routeSpec['calls']) ? $routeSpec['calls'] : null;
        $requirements   = isset($routeSpec['requirements']) ? $routeSpec['requirements'] : array();
        $regex          = isset($routeSpec['path']) ? $routeSpec['path'] : null;

        $route = new Route($path, $methods, $controller, $calls, $requirements, $regex);

        return $route;
    }

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


Question:
// load iterates over the prefix space in the database and populates the in
// memory maps.

func (i *smallIndex) load() {
	it := i.db.NewIterator(util.BytesPrefix(i.prefix), nil)
	defer it.Release()
	for it.Next() {
		val := string(it.Value())
		id := binary.BigEndian.Uint32(it.Key()[len(i.prefix):])
		if val != "" {
			// Empty value means the entry has been deleted.
			i.id2val[id] = val
			i.val2id[val] = id
		}
		if id >= i.nextID {
			i.nextID = id + 1
		}
	}
}

def sitemap_meta_description
      return controller.sitemap_meta_data[:description].blank? ? nil : tag(:meta, {name: :description, content: controller.sitemap_meta_data[:description]}, false, false)
    end

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


Question:
Overloads the keyPressEvent method to support backtab operations.

        :param      event | <QKeyPressEvent>

def keyPressEvent( self, event ):

        if ( event.key() == Qt.Key_Backtab ):
            self.unindentSelection()
        else:
            super(XScintillaEdit, self).keyPressEvent(event)

def register_actions(self, shortcut_manager):

        shortcut_manager.add_callback_for_action("delete", self.remove_action_callback)
        shortcut_manager.add_callback_for_action("add", self.add_action_callback)
        shortcut_manager.add_callback_for_action("copy", self.copy_action_callback)
        shortcut_manager.add_callback_for_action("cut", self.cut_action_callback)
        shortcut_manager.add_callback_for_action("paste", self.paste_action_callback)

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


Question: format orchestrator errors

function formatError(e) {
  if (!e.err) return e.message;
  if (e.err.message) return e.err.message;
  return JSON.stringify(e.err);
}

func (self Otto) MakeRangeError(message string) Value {
	return self.runtime.toValue(self.runtime.newRangeError(self.runtime.toValue(message)))
}

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


Question: Test if a table exists.

def tableexists(tablename):
    """"""
    result = True
    try:
        t = table(tablename, ack=False)
    except:
        result = False
    return result

public function getIdColumnName(bool $withTableName = false): string
    {
        return ($withTableName) ? $this->addTableName($this->idColumnName) : $this->idColumnName;
    }

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


Question: // SetOfferingDescription sets the OfferingDescription field's value.

func (s *DescribeReservationOutput) SetOfferingDescription(v string) *DescribeReservationOutput {
	s.OfferingDescription = &v
	return s
}

def describeSObject(self, sObjectsType):
    '''

    '''
    self._setHeaders('describeSObject')
    return self._sforce.service.describeSObject(sObjectsType)

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


Question: // WithField returns a new log entry with the supplied field.

func WithField(key string, value interface{}) Entry {
	ne := newEntryWithFields(logFields)
	ne.Fields = append(ne.Fields, Field{Key: key, Value: value})
	return ne
}

public void trace(Object message) {
        doLog(Level.TRACE, FQCN, message, null, null);
    }

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


Question: // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConversionReview.

func (in *ConversionReview) DeepCopy() *ConversionReview {
	if in == nil {
		return nil
	}
	out := new(ConversionReview)
	in.DeepCopyInto(out)
	return out
}

func (bs *blobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
	path, err := pathFor(blobDataPathSpec{
		digest: dgst,
	})

	if err != nil {
		return distribution.Descriptor{}, err
	}

	fi, err := bs.driver.Stat(ctx, path)
	if err != nil {
		switch err := err.(type) {
		case driver.PathNotFoundError:
			return distribution.Descriptor{}, distribution.ErrBlobUnknown
		default:
			return distribution.Descriptor{}, err
		}
	}

	if fi.IsDir() {
		// NOTE(stevvooe): This represents a corruption situation. Somehow, we
		// calculated a blob path and then detected a directory. We log the
		// error and then error on the side of not knowing about the blob.
		dcontext.GetLogger(ctx).Warnf("blob path should not be a directory: %q", path)
		return distribution.Descriptor{}, distribution.ErrBlobUnknown
	}

	// TODO(stevvooe): Add method to resolve the mediatype. We can store and
	// cache a "global" media type for the blob, even if a specific repo has a
	// mediatype that overrides the main one.

	return distribution.Descriptor{
		Size: fi.Size(),

		// NOTE(stevvooe): The central blob store firewalls media types from
		// other users. The caller should look this up and override the value
		// for the specific repository.
		MediaType: "application/octet-stream",
		Digest:    dgst,
	}, nil
}

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


Question:
Stops the Echo Service, taking it offline and out-of-service.

@return a boolean value indicating whether the Echo Service has been shutdown successfully.
@see #getEchoService()

protected boolean stopEchoService() {
    return Optional.ofNullable(getEchoService()).map(localEchoService -> {

      localEchoService.shutdown();

      try {
        if (!localEchoService.awaitTermination(30, TimeUnit.SECONDS)) {
          localEchoService.shutdownNow();

          if (!localEchoService.awaitTermination(30, TimeUnit.SECONDS)) {
            getLogger().warning("Failed to shutdown EchoService");
          }
        }
      }
      catch (InterruptedException ignore) {
        Thread.currentThread().interrupt();
      }

      return localEchoService.isShutdown();

    }).orElse(false);
  }

private SSLEngineResult writeAppRecord(EngineArgs ea) throws IOException {

        Status status = null;
        HandshakeStatus hsStatus = null;

        /*
         * See if the handshaker needs to report back some SSLException.
         */
        checkTaskThrown();

        /*
         * short circuit if we're closed/closing.
         */
        if (writer.isOutboundDone()) {
            return new SSLEngineResult(Status.CLOSED, getHSStatus(null), 0, 0);
        }

        /*
         * If we're still in cs_HANDSHAKE, make sure it's been
         * started.
         */
        synchronized (this) {
            if ((connectionState == cs_HANDSHAKE) ||
                    (connectionState == cs_START)) {
                kickstartHandshake();

                /*
                 * If there's no HS data available to write, we can return
                 * without trying to wrap anything.
                 */
                hsStatus = getHSStatus(null);

                if (hsStatus == HandshakeStatus.NEED_UNWRAP) {
                    return new SSLEngineResult(Status.OK, hsStatus, 0, 0);
                }
            }
        }

        /*
         * Grab a copy of this if it doesn't already exist,
         * and we can use it several places before anything major
         * happens on this side.  Races aren't critical
         * here.
         */
        if (hsStatus == null) {
            hsStatus = getHSStatus(null);
        }

        /*
         * If we have a task outstanding, this *MUST* be done before
         * doing any more wrapping, because we could be in the middle
         * of receiving a handshake message, for example, a finished
         * message which would change the ciphers.
         */
        if (hsStatus == HandshakeStatus.NEED_TASK) {
            return new SSLEngineResult(
                Status.OK, hsStatus, 0, 0);
        }

        /*
         * This will obtain any waiting outbound data, or will
         * process the outbound appData.
         */
        try {
            synchronized (writeLock) {
                hsStatus = writeRecord(outputRecord, ea);
            }
        } catch (SSLException e) {
            throw e;
        } catch (IOException e) {
            SSLException ex = new SSLException("Write problems");
            ex.initCause(e);
            throw ex;
        }

        /*
         * writeRecord might have reported some status.
         * Now check for the remaining cases.
         *
         * status above should cover:  NEED_WRAP/FINISHED
         */
        status = (isOutboundDone() ? Status.CLOSED : Status.OK);
        hsStatus = getHSStatus(hsStatus);

        return new SSLEngineResult(status, hsStatus,
            ea.deltaApp(), ea.deltaNet());
    }

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


Question: Check the data in the file or stream

def check_data(yaml_data, errors_array)
      valid = check_not_empty?(yaml_data, errors_array)
      valid &&= check_syntax_valid?(yaml_data, errors_array)
      valid &&= check_overlapping_keys?(yaml_data, errors_array)

      valid
    end

public BufferedReader newBufferedReader(Path path, Charset cs)
    {
        try {
            return Files.newBufferedReader(path, cs);
        } catch (IOException e) {
            return null;
        }
    }

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


Question: Hide magnifying glass in search bar

function() {
		let search_box = document.getElementById("search-input")
		search_box.onclick = function() {
			document.getElementById("search-image").style.display = "none";
			search_box.style.outline = "none";
			search_box.placeholder = "Search";
			search_box.style.paddingLeft = "2px";
		}
	}

def staff_toolbar(context):

    request = context['request']
    if not request.user.is_staff:
        return u''

    toolbar_html = toolbar_root(request, context)
    return format_html(u'<nav id="django-staff-toolbar">{0}</nav>', toolbar_html)

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


Question: // lockPath locks a directory or symlink, return handle, exec "syscall.CloseHandle(handle)" to unlock the path

func lockPath(path string) (uintptr, error) {
	if len(path) == 0 {
		return uintptr(syscall.InvalidHandle), syscall.ERROR_FILE_NOT_FOUND
	}
	pathp, err := syscall.UTF16PtrFromString(path)
	if err != nil {
		return uintptr(syscall.InvalidHandle), err
	}
	access := uint32(syscall.GENERIC_READ)
	sharemode := uint32(syscall.FILE_SHARE_READ)
	createmode := uint32(syscall.OPEN_EXISTING)
	flags := uint32(syscall.FILE_FLAG_BACKUP_SEMANTICS | syscall.FILE_FLAG_OPEN_REPARSE_POINT)
	fd, err := syscall.CreateFile(pathp, access, sharemode, nil, createmode, flags, 0)
	return uintptr(fd), err
}

func (_m *API) BuildContent(ctx context.Context, scm source.Source, opts *types.BuildOptions) (io.ReadCloser, error) {
	ret := _m.Called(ctx, scm, opts)

	var r0 io.ReadCloser
	if rf, ok := ret.Get(0).(func(context.Context, source.Source, *types.BuildOptions) io.ReadCloser); ok {
		r0 = rf(ctx, scm, opts)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(io.ReadCloser)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, source.Source, *types.BuildOptions) error); ok {
		r1 = rf(ctx, scm, opts)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

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


Question: Filter a list of hooks, keeping only applicable ones.

def _filter_hooks(self, *hook_kinds):
        """"""
        hooks = sum((self.hooks.get(kind, []) for kind in hook_kinds), [])
        return sorted(hook for hook in hooks
                      if hook.applies_to(self.transition, self.current_state))

def trigger(self, name, *args, **kwargs):

        mark_remove = []
        for callback, once in self.event_listeners.get(name, []):
            callback(event_origin=self, *args, **kwargs)
            if once:
                mark_remove.append( (callback, once) )

        for callback, once in mark_remove:
            self.off(name, callback, once=once)

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


Question:
Provides a way to modify the following attributes of a load balancer:
            - name
            - algorithm
            - protocol
            - halfClosed
            - port
            - timeout
            - httpsRedirect

def update(self, lb, name=None, algorithm=None, protocol=None,
            halfClosed=None, port=None, timeout=None, httpsRedirect=None):

        body = {}
        if name is not None:
            body["name"] = name
        if algorithm is not None:
            body["algorithm"] = algorithm
        if protocol is not None:
            body["protocol"] = protocol
        if halfClosed is not None:
            body["halfClosed"] = halfClosed
        if port is not None:
            body["port"] = port
        if timeout is not None:
            body["timeout"] = timeout
        if httpsRedirect is not None:
            body["httpsRedirect"] = httpsRedirect
        if not body:
            # Nothing passed
            return
        body = {"loadBalancer": body}
        uri = "/loadbalancers/%s" % utils.get_id(lb)
        try:
            resp, resp_body = self.api.method_put(uri, body=body)
        except exc.ClientException as e:
            message = e.message
            details = e.details
            if message and details:
                errmsg = "%s - %s" % (message, details)
            else:
                errmsg = message
            raise exc.InvalidLoadBalancerParameters(errmsg)
        return resp, resp_body

def init_app(self, app):
        """"""
        app.config.setdefault('SSLIFY_AGE', self.defaults['age'])
        app.config.setdefault('SSLIFY_SUBDOMAINS', self.defaults['subdomains'])
        app.config.setdefault('SSLIFY_PERMANENT', self.defaults['permanent'])
        app.config.setdefault('SSLIFY_SKIPS', self.defaults['skips'])

        app.before_request(self.redirect_to_ssl)
        app.after_request(self.set_hsts_header)

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


Question:
// ParseCIDR takes a string like "10.2.3.1/24" and
// return IPNet with "10.2.3.1" and /24 mask

func ParseCIDR(s string) (*net.IPNet, error) {
	ip, ipn, err := net.ParseCIDR(s)
	if err != nil {
		return nil, err
	}

	ipn.IP = ip
	return ipn, nil
}

def _netstat_route_sunos():
    '''

    '''
    ret = []
    cmd = 'netstat -f inet -rn | tail +5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': '',
            'flags': comps[2],
            'interface': comps[5] if len(comps) >= 6 else ''})
    cmd = 'netstat -f inet6 -rn | tail +5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet6',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': '',
            'flags': comps[2],
            'interface': comps[5] if len(comps) >= 6 else ''})
    return ret

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


Question:
{@inheritdoc}

@return bool|ContactSourceEvent

@throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException

protected function dispatchEvent($action, &$entity, $isNew = false, Event $event = null)
    {
        if (!$entity instanceof ContactSource) {
            throw new MethodNotAllowedHttpException(['ContactSource']);
        }

        switch ($action) {
            case 'pre_save':
                $name = ContactSourceEvents::PRE_SAVE;
                break;
            case 'post_save':
                $name = ContactSourceEvents::POST_SAVE;
                break;
            case 'pre_delete':
                $name = ContactSourceEvents::PRE_DELETE;
                break;
            case 'post_delete':
                $name = ContactSourceEvents::POST_DELETE;
                break;
            default:
                return null;
        }

        if ($this->dispatcher->hasListeners($name)) {
            if (empty($event)) {
                $event = new ContactSourceEvent($entity, $isNew);
                $event->setEntityManager($this->em);
            }

            $this->dispatcher->dispatch($name, $event);

            return $event;
        } else {
            return null;
        }
    }

public function commit(string  $objectType, $objectsIds, string  $action, string  $userName = 'Unknown User', string  $comment = '')
    {
        //==============================================================================
        //      Create Event Object
        $event = new ObjectsCommitEvent(
            $this->getWebserviceId(),
            $objectType,
            $objectsIds,
            $action,
            $userName,
            $comment
        );
        //==============================================================================
        //      Dispatch Event
        $this->getEventDispatcher()->dispatch(ObjectsCommitEvent::NAME, $event);
    }

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


Question:
Add all elements in the iterator to the collection.

@param target
@param iterator
@return true if the target was modified, false otherwise

public static <T> boolean addAll(Collection<T> target, Iterator<? extends T> iterator) {
        Preconditions.checkArgumentNotNull(target, "target");
        boolean modified = false;
        while (iterator.hasNext()) {
            modified |= target.add(iterator.next());
        }
        return modified;
    }

public function parse($annotation, \ReflectionClass $refClass, Endpoint $endpoint)
    {
        $query = new QueryDefinition();

        if ($annotation->name) {
            $query->setName($annotation->name);
        } else {
            $query->setName(lcfirst(ClassUtils::getDefaultName($refClass->getName())));
        }

        $endpoint->addQuery($query);

        if ($annotation->type) {
            $type = TypeUtil::normalize($annotation->type);
            if (class_exists($annotation->type)) {
                $type = $endpoint->getTypeForClass($annotation->type);
            }
            if ($endpoint->hasType($type)) {
                $query->setNode($type);
            }
            $query->setType($type);
        }

        $query->setList(TypeUtil::isTypeList($annotation->type));
        $query->setNonNull(TypeUtil::isTypeNonNull($annotation->type));
        $query->setNonNullList(TypeUtil::isTypeNonNullList($annotation->type));

        if (!$query->getType()) {
            $nodeType = ClassUtils::getNodeFromClass($refClass->getName());
            $objectDefinition = null;
            if ($nodeType && $endpoint->hasType($nodeType)) {
                $objectDefinition = $endpoint->getType($nodeType);
            }
            if ($objectDefinition) {
                $query->setType($objectDefinition->getName());
                $query->setNode($objectDefinition->getName());
            } else {
                //avoid throw Exception when the schema is empty
                //when the schema is empty the NodeInterface has not been loaded
                //then the node(id) and nodes(ids) queries fails
                if ('Node' === $nodeType) {
                    $endpoint->removeQuery($query->getName());

                    return;
                }

                $error = sprintf('Does not exist any valid type for class "%s"', $refClass->getName());
                throw new \RuntimeException($error);
            }
        }

        if ($annotation->arguments) {
            foreach ($annotation->arguments as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        } else {
            $argAnnotations = $this->reader->getClassAnnotations($refClass);
            foreach ($argAnnotations as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        }

        $query->setResolver($annotation->resolver ?? $refClass->getName());
        $query->setDeprecationReason($annotation->deprecationReason);
        $query->setDescription($annotation->description);

        foreach ($annotation->options as $option => $value) {
            $query->setMeta($option, $value);
        }
    }

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


Question:
@param string $keywords

@return array

public function findByKeywords($keywords)
    {
        $qb = $this->createQueryBuilder();
        $qb->setQueryArray($this->transformConditionToMongoCondition($keywords));

        return $qb->getQuery()->execute();
    }

def hash_to_rets_query_string(hash)
      [].tap do |str|
        hash.each_pair do |k,v|
          val = value_map(v)
          str << "(#{k.to_s.camelize}=#{val})"
        end
      end.join(',')
    end

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


Question:
Refresh self.access_token by querying the metadata server.

        If self.store is initialized, store acquired credentials there.

def _do_refresh_request(self, unused_http_request):

        relative_url = 'instance/service-accounts/{0}/token'.format(
            self.__service_account_name)
        try:
            response = _GceMetadataRequest(relative_url)
        except exceptions.CommunicationError:
            self.invalid = True
            if self.store:
                self.store.locked_put(self)
            raise
        content = response.read()
        try:
            credential_info = json.loads(content)
        except ValueError:
            raise exceptions.CredentialsError(
                'Could not parse response as JSON: %s' % content)

        self.access_token = credential_info['access_token']
        if 'expires_in' in credential_info:
            expires_in = int(credential_info['expires_in'])
            self.token_expiry = (
                datetime.timedelta(seconds=expires_in) +
                datetime.datetime.utcnow())
        else:
            self.token_expiry = None
        self.invalid = False
        if self.store:
            self.store.locked_put(self)

func CreateTenant(obj *Tenant) error {
	// Validate parameters
	err := ValidateTenant(obj)
	if err != nil {
		log.Errorf("ValidateTenant retruned error for: %+v. Err: %v", obj, err)
		return err
	}

	// Check if we handle this object
	if objCallbackHandler.TenantCb == nil {
		log.Errorf("No callback registered for tenant object")
		return errors.New("Invalid object type")
	}

	saveObj := obj

	collections.tenantMutex.Lock()
	key := collections.tenants[obj.Key]
	collections.tenantMutex.Unlock()

	// Check if object already exists
	if key != nil {
		// Perform Update callback
		err = objCallbackHandler.TenantCb.TenantUpdate(collections.tenants[obj.Key], obj)
		if err != nil {
			log.Errorf("TenantUpdate retruned error for: %+v. Err: %v", obj, err)
			return err
		}

		// save the original object after update
		collections.tenantMutex.Lock()
		saveObj = collections.tenants[obj.Key]
		collections.tenantMutex.Unlock()
	} else {
		// save it in cache
		collections.tenantMutex.Lock()
		collections.tenants[obj.Key] = obj
		collections.tenantMutex.Unlock()

		// Perform Create callback
		err = objCallbackHandler.TenantCb.TenantCreate(obj)
		if err != nil {
			log.Errorf("TenantCreate retruned error for: %+v. Err: %v", obj, err)
			collections.tenantMutex.Lock()
			delete(collections.tenants, obj.Key)
			collections.tenantMutex.Unlock()
			return err
		}
	}

	// Write it to modeldb
	collections.tenantMutex.Lock()
	err = saveObj.Write()
	collections.tenantMutex.Unlock()
	if err != nil {
		log.Errorf("Error saving tenant %s to db. Err: %v", saveObj.Key, err)
		return err
	}

	return nil
}

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


Question:
Evict url(s) from the cache.

        :param urls: An iterable containing normalized urls.
        :returns: The number of items removed from the cache.

def evict(self, urls):

        if isinstance(urls, six.string_types):
            urls = (urls,)
        return self.handler.evict(urls)

def deprecated(context):
    """"""
    tar = context.get('tar', None)

    # at least 1 of tarExtract or tarArchive must exist in context
    tar_extract, tar_archive = context.keys_of_type_exist(
        ('tarExtract', list),
        ('tarArchive', list))

    found_at_least_one = (tar_extract.key_in_context
                          or tar_archive.key_in_context)

    if tar and not found_at_least_one:
        return
    elif found_at_least_one:
        tar = context['tar'] = {}

    if tar_extract.key_in_context and tar_extract.is_expected_type:
        tar['extract'] = context[tar_extract.key]

    if tar_archive.key_in_context and tar_archive.is_expected_type:
        tar['archive'] = context[tar_archive.key]

    if 'tarFormat' in context:
        tar['format'] = context['tarFormat']

    logger.warning("tarExtract and tarArchive are deprecated. They will "
                   "stop working upon the next major release. "
                   "Use the new context key env instead. It's a lot "
                   "better, promise! For the moment pypyr is creating the "
                   "new env key for you under the hood.")

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


Question:
@param \Spryker\Zed\DataImport\Business\Model\DataSet\DataSetInterface $dataSet

@throws \Spryker\Zed\DataImport\Business\Exception\EntityNotFoundException

@return void

public function execute(DataSetInterface $dataSet)
    {
        $concreteSku = $dataSet[ProductDiscontinuedDataSetInterface::KEY_CONCRETE_SKU];
        if (!isset($this->idProductCache[$concreteSku])) {
            /** @var \Orm\Zed\Product\Persistence\SpyProductQuery $productQuery */
            $productQuery = SpyProductQuery::create()
                ->select(SpyProductTableMap::COL_ID_PRODUCT);
            /** @var string|int|null $idProduct */
            $idProduct = $productQuery
                ->findOneBySku($concreteSku);

            if (!$idProduct) {
                throw new EntityNotFoundException(sprintf('Could not find product by sku %s', $concreteSku));
            }

            $this->idProductCache[$concreteSku] = (int)$idProduct;
        }

        $dataSet[ProductDiscontinuedDataSetInterface::ID_PRODUCT] = $this->idProductCache[$concreteSku];
    }

function namedParameterList()
    {
        return array( $this->AttributeName => array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 2 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ),
                      $this->DumpName =>      array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "show" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 1 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ) );
    }

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


Question: Shared base method for defining new sequence types.

function defineSequenceType(base, name, overrides) {
    /** @constructor */
    var ctor = function ctor() {};

    // Make this type inherit from the specified base.
    ctor.prototype = new base();

    // Attach overrides to the new sequence type's prototype.
    for (var override in overrides) {
      ctor.prototype[override] = overrides[override];
    }

    // Define a factory method that sets the new sequence's parent to the caller
    // and (optionally) applies any additional initialization logic.
    // Expose this as a chainable method so that we can do:
    // Lazy(...).map(...).filter(...).blah(...);
    var factory = function factory() {
      var sequence = new ctor();

      // Every sequence needs a reference to its parent in order to work.
      sequence.parent = this;

      // If a custom init function was supplied, call it now.
      if (sequence.init) {
        sequence.init.apply(sequence, arguments);
      }

      return sequence;
    };

    var methodNames = typeof name === 'string' ? [name] : name;
    for (var i = 0; i < methodNames.length; ++i) {
      base.prototype[methodNames[i]] = factory;
    }

    return ctor;
  }

func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypes(SchemeGroupVersion,
		&Workflow{},
		&WorkflowList{},
	)
	metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
	return nil
}

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


Question: // SetFileShareARN sets the FileShareARN field's value.

func (s *DeleteFileShareOutput) SetFileShareARN(v string) *DeleteFileShareOutput {
	s.FileShareARN = &v
	return s
}

func (q *Query) GetPayload() string {
	j, err := json.Marshal(struct {
		Encoding string `json:"encoding"`
		Method   string `json:"method"`
		NS       string `json:"key"`
	}{
		Encoding: q.encoding,
		Method:   q.method,
		NS:       q.ns,
	})
	sharedutils.CheckError(err)
	return string(j) + "\n"
}

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


Question: "command=FINALIZE&media_id=601413451156586496"

private UploadedMedia uploadMediaChunkedFinalize(long mediaId) throws TwitterException {
		int tries = 0;
		int maxTries = 20;
		int lastProgressPercent = 0;
		int currentProgressPercent = 0;
		UploadedMedia uploadedMedia = uploadMediaChunkedFinalize0(mediaId);
		while (tries < maxTries) {
			if(lastProgressPercent == currentProgressPercent) {
				tries++;
			}
			lastProgressPercent = currentProgressPercent;
			String state = uploadedMedia.getProcessingState();
			if (state.equals("failed")) {
				throw new TwitterException("Failed to finalize the chuncked upload.");
			}
			if (state.equals("pending") || state.equals("in_progress")) {
				currentProgressPercent = uploadedMedia.getProgressPercent();
				int waitSec = Math.max(uploadedMedia.getProcessingCheckAfterSecs(), 1);
				logger.debug("Chunked finalize, wait for:" + waitSec + " sec");
				try {
					Thread.sleep(waitSec * 1000);
				} catch (InterruptedException e) {
					throw new TwitterException("Failed to finalize the chuncked upload.", e);
				}
			}
			if (state.equals("succeeded")) {
				return uploadedMedia;
			}
			uploadedMedia = uploadMediaChunkedStatus(mediaId);
		}
		throw new TwitterException("Failed to finalize the chuncked upload, progress has stopped, tried " + tries+1 + " times.");
	}

protected function applyBulk( $model, $column, $action, $target, $config = [] ) {

		switch( $column ) {

			case 'status': {

				switch( $action ) {

					case 'confirmed': {

						$this->confirm( $model );

						break;
					}
					case 'approved': {

						$this->approve( $model );

						break;
					}
					case 'rejected': {

						$this->reject( $model );

						break;
					}
					case 'active': {

						$this->activate( $model );

						break;
					}
					case 'frozen': {

						$this->freeze( $model );

						break;
					}
					case 'blocked': {

						$this->block( $model );

						break;
					}
					case 'terminated': {

						$this->terminate( $model );

						break;
					}
				}

				break;
			}
			case 'model': {

				switch( $action ) {

					case 'pinned': {

						$model->pinned = true;

						$model->update();

						break;
					}
					case 'featured': {

						$model->featured = true;

						$model->update();

						break;
					}
					case 'delete': {

						$this->delete( $model );

						break;
					}
				}

				break;
			}
		}
	}

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


Question:
Parse JSON text into java object from the input source.

@see JSONParser

@return Instance of the following: JSONObject, JSONArray, String,
java.lang.Number, java.lang.Boolean, null

public static Object parseWithException(String s) throws ParseException {
		return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(s, defaultReader.DEFAULT);
	}

private Class<?> convertType(Class<?> old)
   {
      if (Boolean.class.equals(old))
      {
         return boolean.class;
      }
      else if (boolean.class.equals(old))
      {
         return Boolean.class;
      }
      else if (Byte.class.equals(old))
      {
         return byte.class;
      }
      else if (byte.class.equals(old))
      {
         return Byte.class;
      }
      else if (Short.class.equals(old))
      {
         return short.class;
      }
      else if (short.class.equals(old))
      {
         return Short.class;
      }
      else if (Integer.class.equals(old))
      {
         return int.class;
      }
      else if (int.class.equals(old))
      {
         return Integer.class;
      }
      else if (Long.class.equals(old))
      {
         return long.class;
      }
      else if (long.class.equals(old))
      {
         return Long.class;
      }
      else if (Float.class.equals(old))
      {
         return float.class;
      }
      else if (float.class.equals(old))
      {
         return Float.class;
      }
      else if (Double.class.equals(old))
      {
         return double.class;
      }
      else if (double.class.equals(old))
      {
         return Double.class;
      }
      else if (Character.class.equals(old))
      {
         return char.class;
      }
      else if (char.class.equals(old))
      {
         return Character.class;
      }

      return null;
   }

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


Question:
Validate form

@return boolean

private function validate()
    {
        if (!$this->cfg['validate']) {
            return true;
        }
        $formIsValid = true;
        foreach ($this->currentFields as $field) {
            $isValid = $field->validate();
            $formIsValid = $formIsValid && $isValid;
        }
        return $formIsValid;
    }

public function isValid($value)
    {
        $this->_setValue($value);
        if ($this->_max <= $value) {
            $this->_error(self::NOT_LESS);
            return false;
        }
        return true;
    }

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


Question:
Gets an array of all isotopes matching the searched exact mass within
a certain difference.

@param  exactMass  search mass
@param  difference mass the isotope is allowed to differ from the search mass
@return            An array of all isotopes

public IIsotope[] getIsotopes(double exactMass, double difference) {
        List<IIsotope> list = new ArrayList<>();
        for (List<IIsotope> isotopes : this.isotopes) {
            if (isotopes == null) continue;
            for (IIsotope isotope : isotopes) {
                if (Math.abs(isotope.getExactMass() - exactMass) <= difference) {
                    list.add(clone(isotope));
                }
            }
        }
        return list.toArray(new IIsotope[list.size()]);
    }

public void marshall(DescribeMLModelsRequest describeMLModelsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeMLModelsRequest.getFilterVariable(), FILTERVARIABLE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getEQ(), EQ_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGT(), GT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLT(), LT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGE(), GE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLE(), LE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNE(), NE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getPrefix(), PREFIX_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getSortOrder(), SORTORDER_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLimit(), LIMIT_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:
Call static routes to controller.
@param $uri
@return object

public function callStaticRoute($uri)
    {
        $params = array_slice($this->getUrlSegments(), 2);

        return $this->callController([$uri, $params]);
    }

public function get($pattern, $handler, array $requirements = [], array $defaults = [])
    {
        $this->addRoute('GET', $pattern, $handler, $requirements, $defaults);
    }

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


Question: // NextInterval returns next retriable time

func (r *retrier) NextInterval(retry int) time.Duration {
	return r.backoff.Next(retry)
}

func NewStats() *Stats {
	bps := &Stats{}
	bps.Timings = stats.NewTimings("", "", "")
	bps.Rates = stats.NewRates("", bps.Timings, 15, 60e9)
	bps.History = history.New(3)
	bps.SecondsBehindMaster.Set(math.MaxInt64)
	return bps
}

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


Question: // Resource-level

func (r *Namespace) Reload() (*Namespace, error) {
	return r.collection.Get(r.Metadata.Name)
}

protected RestPath getRealPath(String path,String method){
		return getRealPath(gt.getResourceLoader(),path,method);
	}

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


Question: Update service data in the tran log files

protected void updateTranLogServiceData() throws Exception {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "updateTranLogServiceData");

        try {
            //
            // Check we have a recoverableUnit and three sections to add the data.
            // On recovery we check that all service data sections were recovered.
            //
            if (_tranlogServiceData == null) {
                _tranlogServiceData = _tranLog.createRecoverableUnit();
                _tranlogServerSection = _tranlogServiceData.createSection(TransactionImpl.SERVER_DATA_SECTION, true);
                _tranlogApplIdSection = _tranlogServiceData.createSection(TransactionImpl.APPLID_DATA_SECTION, true);
                _tranlogEpochSection = _tranlogServiceData.createSection(TransactionImpl.EPOCH_DATA_SECTION, true);
                // Log this server name
                _tranlogServerSection.addData(Utils.byteArray(_failureScopeController.serverName()));
                // Log our ApplId
                _tranlogApplIdSection.addData(_ourApplId);
            }

            // Always update this server's current epoch
            _tranlogEpochSection.addData(Util.intToBytes(_ourEpoch));
            _tranlogServiceData.forceSections();
        } catch (Exception e) {
            FFDCFilter.processException(e, "com.ibm.tx.jta.impl.RecoveryManager.updateTranLogSeviceData", "1130", this);
            if (tc.isEntryEnabled())
                Tr.exit(tc, "updateTranLogServiceData", e);
            throw e;
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "updateTranLogServiceData");
    }

func NewClient(config *Config) (*Client, error) {
	c, err := tlsutil.NewConfigurator(config.ToTLSUtilConfig(), nil)
	if err != nil {
		return nil, err
	}
	return NewClientLogger(config, nil, c)
}

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


Question: // Latency returns latency

func (v *Stats) Latency() uint64 {
	ops := v.Writes + v.Reads
	if ops == 0 {
		return 0
	}
	return (uint64)((v.IoMs * 1000) / ops)
}

func (tm *transactionManager) ping(no *node) {
	tm.sendQuery(no, pingType, map[string]interface{}{
		"id": tm.dht.id(no.id.RawString()),
	})
}

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


Question: // IsValid will return true if all rules are true

func (r inclusiveRules) IsValid(value string) bool {
	for _, rule := range r {
		if !rule.IsValid(value) {
			return false
		}
	}
	return true
}

def check_data(yaml_data, errors_array)
      valid = check_not_empty?(yaml_data, errors_array)
      valid &&= check_syntax_valid?(yaml_data, errors_array)
      valid &&= check_overlapping_keys?(yaml_data, errors_array)

      valid
    end

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


Question:
Add a validator the form element

@param  mixed $validator
@throws Exception
@return AbstractElement

public function addValidator($validator)
    {
        if (!($validator instanceof \Pop\Validator\AbstractValidator) && !is_callable($validator)) {
            throw new Exception('Error: The validator must be an instance of Pop\Validator\AbstractValidator or a callable object.');
        }
        $this->validators[] = $validator;
        return $this;
    }

public function composeValidationData(&$container, $constraints, $getters)
    {
        if (null == $container) {
            $container = array();
        }
        if ($getters) {
            if (!isset($container['getters'])) {
                $container['getters'] = array();
            }
            $container['getters'] = array_merge($container['getters'], $this->parseGetters($getters));
        }
        if ($constraints) {
            if (!isset($container['constraints'])) {
                $container['constraints'] = array();
            }
            $container['constraints'] = array_merge($container['constraints'], $this->parseConstraints($constraints));
        }
    }

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


Question:
Parses the the rule FunctionCall according to the following production
rule:
<p>
[47] FunctionCall ::= < QName "(" > (ExprSingle ("," ExprSingle)*)? ")" .
</p>

@throws TTXPathException

private void parseFunctionCall() throws TTXPathException {

        final String funcName = parseQName();

        consume(TokenType.OPEN_BR, true);

        int num = 0;
        if (!(mToken.getType() == TokenType.CLOSE_BR)) {

            do {

                parseExprSingle();
                num++;

            } while (is(TokenType.COMMA, true));
        }

        consume(TokenType.CLOSE_BR, true);
        mPipeBuilder.addFunction(getTransaction(), funcName, num);

    }

func (tx *Tx) ExecOneContext(c context.Context, query interface{}, params ...interface{}) (Result, error) {
	return tx.execOne(c, query, params...)
}

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


Question: JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON

def _create_json(self):

        data_json = {
            "rclass": "local",
            "key": self.name,
            "description": self.description,
            "packageType": self.packageType,
            "notes": "",
            "includesPattern": "**/*",
            "excludesPattern": "",
            "repoLayoutRef": self.repoLayoutRef,
            "dockerApiVersion": self.dockerApiVersion,
            "checksumPolicyType": "client-checksums",
            "handleReleases": True,
            "handleSnapshots": True,
            "maxUniqueSnapshots": 0,
            "snapshotVersionBehavior": "unique",
            "suppressPomConsistencyChecks": True,
            "blackedOut": False,
            "propertySets": [],
            "archiveBrowsingEnabled": self.archiveBrowsingEnabled,
            "yumRootDepth": 0,
        }
        return data_json

func (c *Client) GetPlugins(details bool) *GetPluginsResult {
	r := &GetPluginsResult{}

	var path string
	if details {
		path = "/plugins?details"
	} else {
		path = "/plugins"
	}

	resp, err := c.do("GET", path, ContentTypeJSON)
	if err != nil {
		r.Err = err
		return r
	}

	switch resp.Meta.Type {
	// TODO change this to concrete const type when Joel adds it
	case rbody.PluginListType:
		// Success
		b := resp.Body.(*rbody.PluginList)
		r.LoadedPlugins = convertLoadedPlugins(b.LoadedPlugins)
		r.AvailablePlugins = convertAvailablePlugins(b.AvailablePlugins)
		return r
	case rbody.ErrorType:
		r.Err = resp.Body.(*rbody.Error)
	default:
		r.Err = ErrAPIResponseMetaType
	}
	return r
}

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


Question:
Check if the concrete target methods return the correct type of data
        :return: True if the concrete target is compliant

def check_concrete_target_methods(concrete_target):

        entry_point = concrete_target.read_register("pc")
        if not type(entry_point) is int:
            l.error("read_register result type is %s, should be <type 'int'>", (type(entry_point)))
            return False

        mem_read = concrete_target.read_memory(entry_point, 0x4)

        if not type(mem_read) is bytes:
            l.error("read_memory result type is %s, should be <type 'bytes'>", (type(mem_read)))
            return False

        try:
            concrete_target.read_register("not_existent_reg")
            l.error("read_register should raise a SimConcreteRegisterError when accessing non existent registers")
            return False

        except SimConcreteRegisterError:
            l.debug("read_register raise a SimConcreteRegisterError, ok!")

        try:
            concrete_target.read_memory(0x0, 0x4)
            l.error("read_memory should raise a SimConcreteMemoryError when accessing non mapped memory")
            return False

        except SimConcreteMemoryError:
            l.debug("read_register raise a SimConcreteMemoryError, ok!")

        return True

def parse_files(*files)
      require 'ox'
      @tests = []
      failed_tests = []

      Array(files).flatten.each do |file|
        raise "No JUnit file was found at #{file}" unless File.exist? file

        xml_string = File.read(file)
        doc = Ox.parse(xml_string)

        suite_root = doc.nodes.first.value == 'testsuites' ? doc.nodes.first : doc
        @tests += suite_root.nodes.map(&:nodes).flatten.select { |node| node.kind_of?(Ox::Element) && node.value == 'testcase' }

        failed_suites = suite_root.nodes.select { |suite| suite[:failures].to_i > 0 || suite[:errors].to_i > 0 }
        failed_tests += failed_suites.map(&:nodes).flatten.select { |node| node.kind_of?(Ox::Element) && node.value == 'testcase' }
      end

      @failures = failed_tests.select do |test|
        test.nodes.count > 0
      end.select do |test|
        node = test.nodes.first
        node.kind_of?(Ox::Element) && node.value == 'failure'
      end

      @errors = failed_tests.select do |test|
        test.nodes.count > 0
      end.select do |test|
        node = test.nodes.first
        node.kind_of?(Ox::Element) && node.value == 'error'
      end

      @skipped = tests.select do |test|
        test.nodes.count > 0
      end.select do |test|
        node = test.nodes.first
        node.kind_of?(Ox::Element) && node.value == 'skipped'
      end

      @passes = tests - @failures - @errors - @skipped
    end

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


Question:
Returns an array of the entity data.

@return array The entity data.

public function asArray(): array
    {
        $data = [
            'name' => $this->project->getName(),
            'path' => $this->project->getPath(),
        ];
        if (($foregroundColor = $this->project->getForegroundColor())) {
            $data['foreground_color'] = $foregroundColor;
        }
        if (($backgroundColor = $this->project->getBackgroundColor())) {
            $data['background_color'] = $backgroundColor;
        }

        return $data;
    }

public function execute(TransactionData $transactionData, $argument = null)
    {
        foreach ($this->expectationBackup->listExpectations() as $expectation) {
            $this->expectationStorage->addExpectation($expectation);
        }
        $this->logger->debug('Pre-defined expectations are restored, scenarios and requests history are cleared.');

        $transactionData->setResponse(
            $transactionData->getResponse()->withStatus(200)
        );
    }

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


Question: // WithTLSCert sets the TLS certificate to use by the gRPC server and OpenAPI gRPC client. Required.

func WithTLSCert(cert *tls.Certificate) Option {
	return func(o *options) {
		o.cert = cert
	}
}

async def from_payload(cls, payload, endpoint, idgen, debug, force_protocol=None):
        """"""
        service_name = payload["service"]

        if "protocols" not in payload:
            raise SongpalException(
                "Unable to find protocols from payload: %s" % payload
            )

        protocols = payload["protocols"]
        _LOGGER.debug("Available protocols for %s: %s", service_name, protocols)
        if force_protocol and force_protocol.value in protocols:
            protocol = force_protocol
        elif "websocket:jsonizer" in protocols:
            protocol = ProtocolType.WebSocket
        elif "xhrpost:jsonizer" in protocols:
            protocol = ProtocolType.XHRPost
        else:
            raise SongpalException(
                "No known protocols for %s, got: %s" % (service_name, protocols)
            )
        _LOGGER.debug("Using protocol: %s" % protocol)

        service_endpoint = "%s/%s" % (endpoint, service_name)

        # creation here we want to pass the created service class to methods.
        service = cls(service_name, service_endpoint, protocol, idgen, debug)

        sigs = await cls.fetch_signatures(
            service_endpoint, protocol, idgen
        )

        if debug > 1:
            _LOGGER.debug("Signatures: %s", sigs)
        if "error" in sigs:
            _LOGGER.error("Got error when fetching sigs: %s", sigs["error"])
            return None

        methods = {}

        for sig in sigs["results"]:
            name = sig[0]
            parsed_sig = MethodSignature.from_payload(*sig)
            if name in methods:
                _LOGGER.debug("Got duplicate signature for %s, existing was %s. Keeping the existing one",
                              parsed_sig, methods[name])
            else:
                methods[name] = Method(service, parsed_sig, debug)

        service.methods = methods

        if "notifications" in payload and "switchNotifications" in methods:
            notifications = [
                Notification(
                    service_endpoint, methods["switchNotifications"], notification
                )
                for notification in payload["notifications"]
            ]
            service.notifications = notifications
            _LOGGER.debug("Got notifications: %s" % notifications)

        return service

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


Question: // Validate checks that the identity string is well-formed.

func (id Identity) Validate() error {
	chunks := strings.SplitN(string(id), ":", 2)
	if len(chunks) != 2 {
		return fmt.Errorf("auth: bad identity string %q", id)
	}
	re := knownKinds[Kind(chunks[0])]
	if re == nil {
		return fmt.Errorf("auth: bad identity kind %q", chunks[0])
	}
	if !re.MatchString(chunks[1]) {
		return fmt.Errorf("auth: bad value %q for identity kind %q", chunks[1], chunks[0])
	}
	return nil
}

public function set($name, array $data = [])
    {
        $this->setName($name);
        $this->setData($data);

        return $this->isValid();
    }

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


Question:
Set the original source.

@param mixed       $original
@param null|string $adapter

@throws \InvalidArgumentException On error

@return Uploader A new cloned copy with the source and adapter configured

public function with($original, $adapter = null)
    {
        $new = clone $this;
        $new->original = $original;
        $new->adapter = $adapter;

        if ($new->adapter === null) {
            foreach ($new->adapters as $each) {
                if ($each::check($original)) {
                    $new->adapter = $each;
                    break;
                }
            }
        }

        if ($new->adapter === null || !class_exists($new->adapter)) {
            throw new \InvalidArgumentException('No valid adapter found');
        }

        return $new;
    }

func (l *ossObjects) CopyObjectPart(ctx context.Context, srcBucket, srcObject, destBucket, destObject, uploadID string,
	partID int, startOffset, length int64, srcInfo minio.ObjectInfo, srcOpts, dstOpts minio.ObjectOptions) (p minio.PartInfo, err error) {

	bkt, err := l.Client.Bucket(destBucket)
	if err != nil {
		logger.LogIf(ctx, err)
		return p, ossToObjectError(err, destBucket)
	}

	// Build OSS metadata
	opts, err := appendS3MetaToOSSOptions(ctx, nil, srcInfo.UserDefined)
	if err != nil {
		return p, ossToObjectError(err, srcBucket, srcObject)
	}

	completePart, err := bkt.UploadPartCopy(oss.InitiateMultipartUploadResult{
		Key:      destObject,
		UploadID: uploadID,
	}, srcBucket, srcObject, startOffset, length, partID, opts...)

	if err != nil {
		logger.LogIf(ctx, err)
		return p, ossToObjectError(err, srcBucket, srcObject)
	}

	p.PartNumber = completePart.PartNumber
	p.ETag = minio.ToS3ETag(completePart.ETag)
	return p, nil
}

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


Question:
// Callback for notifications from blockchain.  It notifies clients that are
// long polling for changes or subscribed to websockets notifications.

func (s *rpcServer) handleBlockchainNotification(notification *blockchain.Notification) {
	switch notification.Type {
	case blockchain.NTBlockAccepted:
		block, ok := notification.Data.(*btcutil.Block)
		if !ok {
			rpcsLog.Warnf("Chain accepted notification is not a block.")
			break
		}

		// Allow any clients performing long polling via the
		// getblocktemplate RPC to be notified when the new block causes
		// their old block template to become stale.
		s.gbtWorkState.NotifyBlockConnected(block.Hash())

	case blockchain.NTBlockConnected:
		block, ok := notification.Data.(*btcutil.Block)
		if !ok {
			rpcsLog.Warnf("Chain connected notification is not a block.")
			break
		}

		// Notify registered websocket clients of incoming block.
		s.ntfnMgr.NotifyBlockConnected(block)

	case blockchain.NTBlockDisconnected:
		block, ok := notification.Data.(*btcutil.Block)
		if !ok {
			rpcsLog.Warnf("Chain disconnected notification is not a block.")
			break
		}

		// Notify registered websocket clients.
		s.ntfnMgr.NotifyBlockDisconnected(block)
	}
}

def _monitor_pbc_status(self):
        """"""
        LOG.info('Starting to Monitor PBC status.')
        inspect = celery.current_app.control.inspect()
        workers = inspect.ping()
        start_time = time.time()
        while workers is None:
            time.sleep(0.1)
            elapsed = time.time() - start_time
            if elapsed > 20.0:
                LOG.warning('PBC not found!')
                break
        if workers is not None:
            for worker in workers:
                _tasks = inspect.registered_tasks()[worker]
                LOG.info('Worker: %s tasks:', worker)
                for task_index, task_name in enumerate(_tasks):
                    LOG.info('  %02d : %s', task_index, task_name)

        while True:
            LOG.info('Checking PBC status (%d/%d)', self._num_pbcs,
                     self._max_pbcs)
            celery_app = celery.current_app
            inspect = celery_app.control.inspect()
            workers = inspect.ping()
            if workers is None:
                LOG.warning('PBC service not found!')
            else:
                LOG.info('PBC state:  %s', celery_app.events.State())
                _active = inspect.active()
                _scheduled = inspect.scheduled()
                for worker in workers:
                    LOG.info('  Worker %s: scheduled: %s, active: %s',
                             worker, _active[worker], _scheduled[worker])
            time.sleep(self._report_interval)

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


Question: Delete some very common suffixes.

def delete_suffixes(self, word):

        length = len(word)
        suffixes = ['al', 'ance', 'ence', 'er', 'ic', 'able', 'ible',
                    'ant', 'ement', 'ment', 'ent', 'ism', 'ate',
                    'iti', 'ous', 'ive', 'ize']

        for suffix in suffixes:
            if word.endswith(suffix) and self.r2 <= (length - len(suffix)):
                word = word[:-len(suffix)]
                return word

        if word.endswith('ion') and self.r2 <= (length - 3):
            if word[length - 4] in 'st':
                word = word[:-3]

        return word

protected function internalRemoveItem(&$normalizedKey)
    {
        $filespec = $this->getFileSpec($normalizedKey);
        if (!file_exists($filespec . '.dat')) {
            return false;
        } else {
            $this->unlink($filespec . '.dat');
        }

        return true;
    }

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


Question:
Parse an encaps list.
@param InterpolatedStringNode|HeredocNode|BacktickNode $node Interpolated string.
@param int|string $terminator Token type that terminates the encaps list
@param bool $encaps_whitespace_allowed

private function encapsList($node, $terminator, $encaps_whitespace_allowed = FALSE) {
    if (!$encaps_whitespace_allowed) {
      if ($this->tryMatch(T_ENCAPSED_AND_WHITESPACE, $node)) {
        $node->addChild($this->encapsVar());
      }
    }
    while ($this->currentType !== NULL && $this->currentType !== $terminator) {
      $this->tryMatch(T_ENCAPSED_AND_WHITESPACE, $node) ||
        $node->addChild($this->encapsVar());
    }
  }

def node(node, indent)
      # Pretty print
      if @settings[:pretty]
        indentation = ' ' * indent
        inline = Settings::INLINE_NODE.include? node[@value]

        indentate = proc do
          if @in_definition
            buffer "' ' * (indent + #{indent})"
          else
            buffer_freeze indentation
          end
        end

        if inline
          inline_last_sibling = @sibling_stack[-1][-1] ? Settings::INLINE_NODE.include?(@sibling_stack[-1][-1][1]) : true

          if @sibling_stack[-1][-1] && @sibling_stack[-1][-1][0] == :plain
            buffer_remove_trailing_newline
          end

          if @in_definition || @sibling_stack[-1].length == 1 || !inline_last_sibling
            indentate[]
          end
        else
          indentate[]
        end

        @sibling_stack[-1] << [node[@type], node[@value]]
        @sibling_stack << [[node[@type], node[@value]]]
      end

      # Add the tag opening, with leading whitespace to the code buffer
      buffer_freeze ' ' if node[@options][:leading_whitespace]
      buffer_freeze "<#{node[@value]}"

      # Evaluate node extension in the current context
      if node[@options][:extension]
        extension_name = buffer_set_variable :extension,
                                             node[@options][:extension][@value]

        extension = {
          name: extension_name,
          escaped: node[@options][:extension][@options][:escaped]
        }
      end

      # Evaluate and generate node attributes, then process each one to
      # by generating the required attribute code
      buffer_attributes node[@options][:attributes],
                        extension

      # Check if the current node is self enclosing. Self enclosing nodes
      # do not have any child elements
      if node[@options][:self_enclosing]
        # If the tag is self enclosing, it cannot have any child elements.
        buffer_freeze '>'

        # Pretty print
        buffer_freeze "\n" if @settings[:pretty]

        # If we mistakenly add children to self enclosing nodes,
        # process each child element as if it was correctly indented
        # node[@children].each do |child|
        #   root child, indent + @settings[:indent]
        # end
      else
        # Set tag ending code
        buffer_freeze '>'

        # Pretty print
        if @settings[:pretty]
          if node[@children].length > 0
            buffer_freeze "\n" unless inline
          end
          # @sibling_stack << [[node[@type], node[@value]]]
        end

        # Process each child element recursively, increasing indentation
        node[@children].each do |child|
          root child, indent + @settings[:indent]
        end

        inline_last_child = @sibling_stack[-1][-2] &&
                            (@sibling_stack[-1][-2][0] == :plain ||
                              Settings::INLINE_NODE.include?(@sibling_stack[-1][-2][1]))

        # Pretty print
        if @settings[:pretty]
          if node[@children].length > 1 && inline_last_child
            buffer_freeze "\n"
          end

          if node[@children].size > 0 && !inline
            indentate[]
          end
        end

        # Set tag closing code
        buffer_freeze "</#{node[@value]}>"
        buffer_freeze ' ' if node[@options][:trailing_whitespace]

        # Pretty print
        if @settings[:pretty]
          buffer_freeze "\n" if !inline || @in_definition
        end
      end

      if @settings[:pretty]
        @sibling_stack.pop
      end
    end

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


Question:
Get HTML tag, if any, with which to surround tooltip

@return string

public function getTag()
    {
        if (null === $this->_tag) {
            $tag = $this->getOption('tag');
            if (null !== $tag) {
                $this->removeOption('tag');
            } else {
                $tag = 'span';
            }

            $this->setTag($tag);
            return $tag;
        }

        return $this->_tag;
    }

def prepare_gold(ctx, annotations, gout):
    """"""
    click.echo('chemdataextractor.chemdner.prepare_gold')
    for line in annotations:
        pmid, ta, start, end, text, category = line.strip().split('\t')
        gout.write('%s\t%s:%s:%s\n' % (pmid, ta, start, end))

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


Question: TENG' algorithm (Krotkov86)

def tenengrad(img, ksize=3):
    '''''''
    Gx = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=ksize)
    Gy = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=ksize)
    FM = Gx*Gx + Gy*Gy
    mn = cv2.mean(FM)[0]
    if np.isnan(mn):
        return np.nanmean(FM)
    return mn

func (tm *transactionManager) ping(no *node) {
	tm.sendQuery(no, pingType, map[string]interface{}{
		"id": tm.dht.id(no.id.RawString()),
	})
}

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


Question:
Returns number of syllables in a word
@param   boolean|string  $strText      Text to be measured
@return  int

public function syllableCount($strText = false)
    {
        $strText = $this->setText($strText);

        return Syllables::syllableCount($strText, $this->strEncoding);
    }

def parse_block_scalar_empty_line(indent_token_class, content_token_class):
        """"""
        def callback(lexer, match, context):
            text = match.group()
            if (context.block_scalar_indent is None or
                    len(text) <= context.block_scalar_indent):
                if text:
                    yield match.start(), indent_token_class, text
            else:
                indentation = text[:context.block_scalar_indent]
                content = text[context.block_scalar_indent:]
                yield match.start(), indent_token_class, indentation
                yield (match.start()+context.block_scalar_indent,
                       content_token_class, content)
            context.pos = match.end()
        return callback

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


Question:
Load the connection adapter

@return Zend_Http_Client_Adapter_Interface $adapter

public function getAdapter()
    {
        if (null === $this->adapter) {
            $this->setAdapter($this->config['adapter']);
        }

        return $this->adapter;
    }

protected function getSoap()
    {
        if ($this->SOAPClient === null) {
            $this->SOAPClient = new \SoapClient($this->url,
                [
                    'trace' => 1,
                    'cache_wsdl' => WSDL_CACHE_NONE
                ]);
            if ($this->location) {
                $this->SOAPClient->__setLocation($this->location);
            }
        }
        return $this->SOAPClient;
    }

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


Question: Verify the given signature with the RSA key.

def key_verify(rsakey, signature, message, digest):
    """"""
    padding = _asymmetric.padding.PKCS1v15()
    if isinstance(rsakey, _asymmetric.rsa.RSAPrivateKey):
        rsakey = rsakey.public_key()

    try:
        rsakey.verify(signature, message, padding, digest)
    except Exception as e:
        return False
    else:
        return True

protected function resolveRequestSignature($request)
    {
        return sha1(
            $request->method() .
            '|' . $request->server('SERVER_NAME') .
            '|' . $request->path() .
            '|' . $request->ip()
        );
    }

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


Question:
Gets the host name or IP address.

@return the host name or IP address.

public String getHost() {
		String host = getAsNullableString("host");
		host = host != null ? host : getAsNullableString("ip");
		return host;
	}

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

        this.ipAddresses = new java.util.ArrayList<String>(ipAddresses);
    }

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


Question:
/*
Check that there are enough entries in the arrays paras_limit and paras_level

private void checkParaCount() {
        int[] saveLimits;
        byte[] saveLevels;
        int count = paraCount;
        if (count <= paras_level.length)
            return;
        int oldLength = paras_level.length;
        saveLimits = paras_limit;
        saveLevels = paras_level;
        try {
            paras_limit = new int[count * 2];
            paras_level = new byte[count * 2];
        } catch (Exception e) {
            throw new OutOfMemoryError("Failed to allocate memory for paras");
        }
        System.arraycopy(saveLimits, 0, paras_limit, 0, oldLength);
        System.arraycopy(saveLevels, 0, paras_level, 0, oldLength);
    }

function verify(node) {
	switch (node.type) {
		case esprima.Syntax.FunctionDeclaration:
			if (node.leadingComments && node.leadingComments.length === 1) {
				analyzeFunction(node);
			}
			break;
		default:
			break;
	}
}

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


Question:
// reachableAddressGetter dials all addresses of the given entity, returning the
// first one that succeeds. Only used with SSHClient API facade v2 or later is
// available. It does not try to dial if only one address is available.

func (c *SSHCommon) reachableAddressGetter(entity string) (string, error) {
	addresses, err := c.apiClient.AllAddresses(entity)
	if err != nil {
		return "", errors.Trace(err)
	} else if len(addresses) == 0 {
		return "", network.NoAddressError("available")
	} else if len(addresses) == 1 {
		logger.Debugf("Only one SSH address provided (%s), using it without probing", addresses[0])
		return addresses[0], nil
	}
	publicKeys := []string{}
	if !c.noHostKeyChecks {
		publicKeys, err = c.apiClient.PublicKeys(entity)
		if err != nil {
			return "", errors.Annotatef(err, "retrieving SSH host keys for %q", entity)
		}
	}

	hostPorts := network.NewHostPorts(SSHPort, addresses...)
	usableHPs := network.FilterUnusableHostPorts(hostPorts)
	bestHP, err := c.hostChecker.FindHost(usableHPs, publicKeys)
	if err != nil {
		return "", errors.Trace(err)
	}

	return bestHP.Address.Value, nil
}

func addBgp(ctx *cli.Context) {
	if len(ctx.Args()) < 1 {
		errExit(ctx, exitHelp, "Host name required", true)
	}

	hostname := ctx.Args()[0]
	routerip := ctx.String("router-ip")
	asid := ctx.String("as")
	neighboras := ctx.String("neighbor-as")
	neighbor := ctx.String("neighbor")

	//Error checks
	_, _, err := net.ParseCIDR(routerip)
	if err != nil {
		errExit(ctx, exitHelp, "Wrong CIDR format. Enter in x.x.x.x/len format", true)
	}

	ip := net.ParseIP(neighbor)
	if ip == nil {
		errExit(ctx, exitHelp, "Wrong IP format. Enter in x.x.x.x format", true)
	}

	if routerip == "" || asid == "" || neighbor == "" || neighboras == "" {
		errExit(ctx, exitHelp, "Missing attributes", true)
	}

	errCheck(ctx, getClient(ctx).BgpPost(&contivClient.Bgp{
		As:         asid,
		Hostname:   hostname,
		Neighbor:   neighbor,
		NeighborAs: neighboras,
		Routerip:   routerip,
	}))

}

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


Question: /* cleans/recreates the file input

function(){
        if (this._input.parentNode){
            qq.remove(this._input);
        }

        qq.removeClass(this._element, this._options.focusClass);
        this._input = this._createInput();
    }

public List<SuggestedFix> drive(Scanner scanner, Pattern includeFilePattern) {
    JsFlumeCallback callback = new JsFlumeCallback(scanner, includeFilePattern);
    NodeTraversal.traverse(compiler, rootNode, callback);
    List<SuggestedFix> fixes = callback.getFixes();
    fixes.addAll(scanner.processAllMatches(callback.getMatches()));
    return fixes;
  }

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


Question: // Next returns the next tag key in the slice.

func (itr *tagKeySliceIterator) Next() ([]byte, error) {
	if len(itr.keys) == 0 {
		return nil, nil
	}
	key := itr.keys[0]
	itr.keys = itr.keys[1:]
	return key, nil
}

private void addNameSpaceStorage(int nsID, NameSpaceSliceStorage nsStorage)
      throws IOException {
    if (!this.nsStorageMap.containsKey(nsID)) {
      this.nsStorageMap.put(nsID, nsStorage);
    }
  }

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


Question:
// Error can be either of the following types:
//
//   - InvalidObjectFault
//   - RuntimeFault

func (service *VboxPortType) IMousePointerShapeChangedEventgetYhot(request *IMousePointerShapeChangedEventgetYhot) (*IMousePointerShapeChangedEventgetYhotResponse, error) {
	response := new(IMousePointerShapeChangedEventgetYhotResponse)
	err := service.client.Call("", request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

public function get($tag)
    {
        if (!isset($this->styles[$tag])) {
            throw new OutOfBoundsException(sprintf(
                'The style tag "%s" does not exist.',
                $tag
            ));
        }

        return $this->styles[$tag];
    }

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


Question:
Get the form address for monitor messages

@param string $name Optional section name
@return string

public function getMonitorFrom($name = null)
    {
        if ($name) {
            if (isset($this['monitor'], $this['monitor'][$name], $this['monitor'][$name]['from']) &&
                    trim($this['monitor'][$name]['from'])) {
                return $this['monitor'][$name]['from'];
            }
        }
        if (isset($this['monitor'], $this['monitor']['default'], $this['monitor']['default']['from']) &&
                trim($this['monitor']['default']['from'])) {
            return $this['monitor']['default']['from'];
        }

        $email = $this->getSiteEmail();
        if ($email) {
            return $email;
        }

        return 'noreply@gemstracker.org';
    }

def notes(element_key)
      parameter = { basic_auth: @auth }

      response = self.class.get("/elements/#{element_key}/notes", parameter)
      if response.success?
        search_response_header = SearchResponseHeader.new(response)
        search_response_header.elementList
      end
    end

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


Question: Validate rate limits settings

function (routeConfig, methodValue) {
        var rateLimits = [];
        var environment = Shared.config("environment");
        var globalRateLimit = environment.rateLimit;
        if (globalRateLimit) {
            if (globalRateLimit.interval && _.isNumber(globalRateLimit.interval) && parseInt(globalRateLimit.interval) > 0 && globalRateLimit.maxRequests && _.isNumber(globalRateLimit.maxRequests) && parseInt(globalRateLimit.maxRequests) > 0) {
                rateLimits.push(globalRateLimit);
            }
            else {
                throw new Error('Global rate limit config invalid' + ". Provide parameters 'interval' and 'maxRequests' with Int value");
            }
        }
        if (routeConfig && routeConfig.rateLimit) {
            if (routeConfig.rateLimit.interval && _.isNumber(routeConfig.rateLimit.interval) && parseInt(routeConfig.rateLimit.interval) > 0 && routeConfig.rateLimit.maxRequests && _.isNumber(routeConfig.rateLimit.maxRequests) && parseInt(routeConfig.rateLimit.maxRequests) > 0) {
                rateLimits.push(routeConfig.rateLimit);
            }
            else {
                throw new Error('Rate limit config invalid for route file ' + routeConfig.prefix + ". Provide parameters 'interval' and 'maxRequests' with Int value");
            }
        }
        if (methodValue && methodValue.rateLimit) {
            if (methodValue.rateLimit.interval && _.isNumber(methodValue.rateLimit.interval) && parseInt(methodValue.rateLimit.interval) > 0 && methodValue.rateLimit.maxRequests && _.isNumber(methodValue.rateLimit.maxRequests) && parseInt(methodValue.rateLimit.maxRequests) > 0) {
                rateLimits.push(methodValue.rateLimit);
            }
            else {
                throw new Error('Rate limit config invalid for route ' + methodValue.identity + ' in route file ' + routeConfig.prefix + ". Provide parameters 'interval' and 'maxRequests' with Int value");
            }
        }

        if (!_.isEmpty(rateLimits) && !Shared.memcached()) {
            throw new Error("Rate limits set but memcached not configured. Provide settings for memcached in environment config file");
        }

        return rateLimits;
    }

public static autoscalepolicy_binding get(nitro_service service, String name) throws Exception{
		autoscalepolicy_binding obj = new autoscalepolicy_binding();
		obj.set_name(name);
		autoscalepolicy_binding response = (autoscalepolicy_binding) obj.get_resource(service);
		return response;
	}

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


Question: // Indent creates a new Formatter that will indent the code by that much more.

func (f Formatter) Indent(indent int) *Formatter {
	f.IndentLevel = f.IndentLevel + indent
	return &f
}

def help_for_command(command):
    """"""
    help_text = pydoc.text.document(command)
    # remove backspaces
    return re.subn('.\\x08', '', help_text)[0]

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


Question:
Calls compose function of respective data type of object.

@param dataTypeClazz
the data type clazz
@param dataValue
the data value
@param isCql3Enabled
the is cql3 enabled
@return the byte[]

public static byte[] compose(Class<?> dataTypeClazz, Object dataValue, boolean isCql3Enabled)
    {

        if (isCql3Enabled || (!isCql3Enabled && dataValue != null))
        {

            switch (getCassandraDataTypeClass(dataTypeClazz))
            {
            case INT:
                return IntegerTypeBuilder.compose(dataValue, dataTypeClazz);
            case DATE:
                return DateTypeBuilder.compose(dataValue, dataTypeClazz);
            case FLOAT:
                return FloatTypeBuilder.compose(dataValue, dataTypeClazz);
            case LONG:
                return LongTypeBuilder.compose(dataValue, dataTypeClazz);
            case DOUBLE:
                return DoubleTypeBuilder.compose(dataValue, dataTypeClazz);
            case STRING:
                return StringTypeBuilder.compose(dataValue, dataTypeClazz);
            case ASCII:
                return AsciiTypeBuilder.compose(dataValue, dataTypeClazz);
            case UUID:
                return UUIDTypeBuilder.compose(dataValue, dataTypeClazz);
            case BYTES:
                return BytesTypeBuilder.compose(dataValue, dataTypeClazz);
            case BOOLEAN:
                return BooleanTypeBuilder.compose(dataValue, dataTypeClazz);
            case INT32:
                return IntegerTypeBuilder.compose(dataValue, dataTypeClazz);
            case DECIMAL:
                return DecimalTypeBuilder.compose(dataValue, dataTypeClazz);
            case COUNTER:
                return CounterTypeBuilder.compose(dataValue, dataTypeClazz);
            case ENUM:
                return EnumTypeBuilder.compose(dataValue, dataTypeClazz);
            case CHARACTER:
                return CharacterTypeBuilder.compose(dataValue, dataTypeClazz);
            case SHORT:
                return ShortTypeBuilder.compose(dataValue, dataTypeClazz);
            case BIGINT:
                return BigIntegerTypeBuilder.compose(dataValue, dataTypeClazz);
            case TIMESTAMP:
                return TimeStampTypeBuilder.compose(dataValue, dataTypeClazz);
            case SQL_DATE:
                return SQLDateTypeBuilder.compose(dataValue, dataTypeClazz);
            case SQL_TIME:
                return SQLTimeTypeBuilder.compose(dataValue, dataTypeClazz);
            case SQL_TIMESTAMP:
                return SQLTimeStampTypeBuilder.compose(dataValue, dataTypeClazz);
            case CALENDAR:
                return CalendarTypeBuilder.compose(dataValue, dataTypeClazz);
            }
        }
        return null;
    }

public void marshall(DimensionValuesWithAttributes dimensionValuesWithAttributes, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(dimensionValuesWithAttributes.getValue(), VALUE_BINDING);
            protocolMarshaller.marshall(dimensionValuesWithAttributes.getAttributes(), ATTRIBUTES_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.