Question:
Verifies this JoinConfig is valid. At most a single joiner should be active.

@throws IllegalStateException when the join config is not valid

@SuppressWarnings("checkstyle:npathcomplexity")
    public void verify() {
        int countEnabled = 0;
        if (getTcpIpConfig().isEnabled()) {
            countEnabled++;
        }
        if (getMulticastConfig().isEnabled()) {
            countEnabled++;
        }
        if (getAwsConfig().isEnabled()) {
            countEnabled++;
        }
        if (getGcpConfig().isEnabled()) {
            countEnabled++;
        }
        if (getAzureConfig().isEnabled()) {
            countEnabled++;
        }
        if (getKubernetesConfig().isEnabled()) {
            countEnabled++;
        }
        if (getEurekaConfig().isEnabled()) {
            countEnabled++;
        }

        if (countEnabled > 1) {
            throw new InvalidConfigurationException("Multiple join configuration cannot be enabled at the same time. Enable only "
                    + "one of: TCP/IP, Multicast, AWS, GCP, Azure, Kubernetes, or Eureka");
        }

        verifyDiscoveryProviderConfig();
    }

def __do_parse(self, pattern_str):

        in_ = antlr4.InputStream(pattern_str)
        lexer = STIXPatternLexer(in_)
        lexer.removeErrorListeners()  # remove the default "console" listener
        token_stream = antlr4.CommonTokenStream(lexer)

        parser = STIXPatternParser(token_stream)
        parser.removeErrorListeners()  # remove the default "console" listener
        error_listener = ParserErrorListener()
        parser.addErrorListener(error_listener)

        # I found no public API for this...
        # The default error handler tries to keep parsing, and I don't
        # think that's appropriate here.  (These error handlers are only for
        # handling the built-in RecognitionException errors.)
        parser._errHandler = antlr4.BailErrorStrategy()

        # To improve error messages, replace "<INVALID>" in the literal
        # names with symbolic names.  This is a hack, but seemed like
        # the simplest workaround.
        for i, lit_name in enumerate(parser.literalNames):
            if lit_name == u"<INVALID>":
                parser.literalNames[i] = parser.symbolicNames[i]

        # parser.setTrace(True)

        try:
            tree = parser.pattern()
            # print(tree.toStringTree(recog=parser))

            return tree
        except antlr4.error.Errors.ParseCancellationException as e:
            # The cancellation exception wraps the real RecognitionException
            # which caused the parser to bail.
            real_exc = e.args[0]

            # I want to bail when the first error is hit.  But I also want
            # a decent error message.  When an error is encountered in
            # Parser.match(), the BailErrorStrategy produces the
            # ParseCancellationException.  It is not a subclass of
            # RecognitionException, so none of the 'except' clauses which would
            # normally report an error are invoked.
            #
            # Error message creation is buried in the ErrorStrategy, and I can
            # (ab)use the API to get a message: register an error listener with
            # the parser, force an error report, then get the message out of the
            # listener.  Error listener registration is above; now we force its
            # invocation.  Wish this could be cleaner...
            parser._errHandler.reportError(parser, real_exc)

            # should probably chain exceptions if we can...
            # Should I report the cancellation or recognition exception as the
            # cause...?
            six.raise_from(ParseException(error_listener.error_message),
                           real_exc)

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


Question:
Format date from timestamp or Carbon instance.

@param $val
@param array $args

public function crudFormatValueDate($val, $args = [])
    {
        if (is_int($val)) {
            return date($args['format'] ?? 'd.m.Y', $val);
        } elseif ($val instanceof \Carbon\Carbon) {
            return $val->format($args['format'] ?? 'd.m.Y');
        }
    }

public function setValue($value, RequestAbstract $request)
    {
        if (!$request->hasParam($this->getHtmlName() . '_change')) {
            $this->value = false;
        } else if ($request->hasParam($this->getHtmlName() . '_change')) {
            $this->value = true;
        }
    }

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


Question: Get a logging instance we can use.

def get_logger(name):
    """"""
    import logging
    import sys
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    shandler = logging.StreamHandler(sys.stdout)
    fmt = ""
    fmt += '\033[1;32m%(levelname)-5s %(module)s:%(funcName)s():'
    fmt += '%(lineno)d %(asctime)s\033[0m| %(message)s'
    fmtr = logging.Formatter(fmt)
    shandler.setFormatter(fmtr)
    logger.addHandler(shandler)
    return logger

func ErrorLoggerT(typ gin.ErrorType) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next()

		if !c.Writer.Written() {
			json := c.Errors.ByType(typ).JSON()
			if json != nil {
				c.JSON(-1, json)
			}
		}
	}
}

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


Question:
Returns text of the current section as well as all its subsections.

        :param level: indentation level
        :return: text of the current section as well as all its subsections

def full_text(self, level: int = 1) -> str:

        res = ""
        if self.wiki.extract_format == ExtractFormat.WIKI:
            res += self.title
        elif self.wiki.extract_format == ExtractFormat.HTML:
            res += "<h{}>{}</h{}>".format(level, self.title, level)
        else:
            raise NotImplementedError("Unknown ExtractFormat type")

        res += "\n"
        res += self._text
        if len(self._text) > 0:
            res += "\n\n"
        for sec in self.sections:
            res += sec.full_text(level + 1)
        return res

protected function seekTernaryElse(\Twig_TokenStream $tokens)
    {
        $i = 1;
        $depth = 0;
        $found = false;
        $token = null;

        while ($depth || !$found) {
            $token = $tokens->look($i);

            if (in_array($token->getType(), [\Twig_Token::BLOCK_END_TYPE, \Twig_Token::VAR_END_TYPE, \Twig_Token::INTERPOLATION_END_TYPE])) {
                return;
            }

            // End of hash value means end of short ternary (eg. "foo ? bar" syntax)
            if ($token->getType() === \Twig_Token::PUNCTUATION_TYPE && $token->getValue() === ',') {
                return;
            }

            if ($token->getType() === \Twig_Token::PUNCTUATION_TYPE && in_array($token->getValue(), ['(', '[', '{'])) {
                $depth++;
            }

            if ($depth && $token->getType() === \Twig_Token::PUNCTUATION_TYPE && in_array($token->getValue(), [')', ']', '}'])) {
                $depth--;
            }

            $found = $token->getType() === \Twig_Token::PUNCTUATION_TYPE && $token->getValue() === ':';
            $i++;
        }

        return $token;
    }

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


Question:
Sorts / orders items of an array.

@param array  $array
@param string $on
@param string $onSecondary

@throws \InvalidArgumentException

@return array

public function order($array, $on, $onSecondary = null)
    {
        // We only want to work with real arrays, anything else is ignored
        if (!is_array($array)) {
            return $array;
        }
        // If we don't get a string, we can't determine a sort order.
        if (!is_string($on)) {
            throw new \InvalidArgumentException(sprintf('Second parameter passed to %s must be a string, %s given', __METHOD__, gettype($on)));
        }
        if (!(is_string($onSecondary) || $onSecondary === null)) {
            throw new \InvalidArgumentException(sprintf('Third parameter passed to %s must be a string, %s given', __METHOD__, gettype($onSecondary)));
        }
        // Set the 'orderOn' and 'orderAscending', taking into account things like '-datepublish'.
        list($this->orderOn, $this->orderAscending) = $this->getSortOrder($on);

        // Set the secondary order, if any.
        if ($onSecondary) {
            list($this->orderOnSecondary, $this->orderAscendingSecondary) = $this->getSortOrder($onSecondary);
        } else {
            $this->orderOnSecondary = false;
            $this->orderAscendingSecondary = false;
        }

        uasort($array, [$this, 'orderHelper']);

        return $array;
    }

public function uaSort($cmp_function)
    {
        if (!is_callable($cmp_function)) {
            throw new \InvalidArgumentException(
                'Callback is not callable.',
                E_USER_ERROR
            );
        }

        return uasort($this->storedData, $cmp_function);
    }

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


Question:
Returns the SEPA file version as a string.
@param int $version Use the SEPA_PAIN_* constants.
@return string|false SEPA file version as a string or false if the version is invalid.

public static function version2string($version)
    {
        switch($version)
        {   // fall-through's are on purpose
            case self::SEPA_PAIN_001_001_03_GBIC:
            case self::SEPA_PAIN_001_001_03: return 'pain.001.001.03';
            case self::SEPA_PAIN_001_002_03: return 'pain.001.002.03';
            case self::SEPA_PAIN_001_003_03: return 'pain.001.003.03';
            case self::SEPA_PAIN_008_001_02_GBIC:
            case self::SEPA_PAIN_008_001_02_AUSTRIAN_003:
            case self::SEPA_PAIN_008_001_02: return 'pain.008.001.02';
            case self::SEPA_PAIN_008_002_02: return 'pain.008.002.02';
            case self::SEPA_PAIN_008_003_02: return 'pain.008.003.02';
            default: return false;
        }
    }

def _PrintSessionsDetails(self, storage_reader):

    for session_number, session in enumerate(storage_reader.GetSessions()):
      session_identifier = uuid.UUID(hex=session.identifier)
      session_identifier = '{0!s}'.format(session_identifier)

      start_time = 'N/A'
      if session.start_time is not None:
        start_time = timelib.Timestamp.CopyToIsoFormat(session.start_time)

      completion_time = 'N/A'
      if session.completion_time is not None:
        completion_time = timelib.Timestamp.CopyToIsoFormat(
            session.completion_time)

      enabled_parser_names = 'N/A'
      if session.enabled_parser_names:
        enabled_parser_names = ', '.join(sorted(session.enabled_parser_names))

      command_line_arguments = session.command_line_arguments or 'N/A'
      parser_filter_expression = session.parser_filter_expression or 'N/A'
      preferred_encoding = session.preferred_encoding or 'N/A'
      # Workaround for some older Plaso releases writing preferred encoding as
      # bytes.
      if isinstance(preferred_encoding, py2to3.BYTES_TYPE):
        preferred_encoding = preferred_encoding.decode('utf-8')
      if session.artifact_filters:
        artifact_filters_string = ', '.join(session.artifact_filters)
      else:
        artifact_filters_string = 'N/A'
      filter_file = session.filter_file or 'N/A'

      title = 'Session: {0:s}'.format(session_identifier)
      table_view = views.ViewsFactory.GetTableView(
          self._views_format_type, title=title)

      table_view.AddRow(['Start time', start_time])
      table_view.AddRow(['Completion time', completion_time])
      table_view.AddRow(['Product name', session.product_name])
      table_view.AddRow(['Product version', session.product_version])
      table_view.AddRow(['Command line arguments', command_line_arguments])
      table_view.AddRow(['Parser filter expression', parser_filter_expression])
      table_view.AddRow(['Enabled parser and plugins', enabled_parser_names])
      table_view.AddRow(['Preferred encoding', preferred_encoding])
      table_view.AddRow(['Debug mode', session.debug_mode])
      table_view.AddRow(['Artifact filters', artifact_filters_string])
      table_view.AddRow(['Filter file', filter_file])

      table_view.Write(self._output_writer)

      if self._verbose:
        self._PrintPreprocessingInformation(storage_reader, session_number + 1)

        self._PrintParsersCounter(
            session.parsers_counter, session_identifier=session_identifier)

        self._PrintAnalysisReportCounter(
            session.analysis_reports_counter,
            session_identifier=session_identifier)

        self._PrintEventLabelsCounter(
            session.event_labels_counter,
            session_identifier=session_identifier)

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


Question:
Update profile from public form and return the public profile view.

@param \Illuminate\Http\Request $request

@return \Illuminate\Http\Response

public function publicUpdateProfile(Request $request)
    {
        $notValid = $this->mainUpdateProfile($request);
        //  If $notValid it's true, something fail and then it should be corrected by user
        //  If $notValid is false, profile is updated ok

        if ($notValid) {
            // Validation or update fails
            return redirect()->route('laralum_public::profile.edit')->with('error', $notValid);
        }

        return redirect()->route('laralum_public::profile.index')->with('success', __('laralum_profile::general.profile_updated'));
    }

func (s *Session) UserUpdate(email, password, username, avatar, newPassword string) (st *User, err error) {

	// NOTE: Avatar must be either the hash/id of existing Avatar or
	// data:image/png;base64,BASE64_STRING_OF_NEW_AVATAR_PNG
	// to set a new avatar.
	// If left blank, avatar will be set to null/blank

	data := struct {
		Email       string `json:"email,omitempty"`
		Password    string `json:"password,omitempty"`
		Username    string `json:"username,omitempty"`
		Avatar      string `json:"avatar,omitempty"`
		NewPassword string `json:"new_password,omitempty"`
	}{email, password, username, avatar, newPassword}

	body, err := s.RequestWithBucketID("PATCH", EndpointUser("@me"), data, EndpointUsers)
	if err != nil {
		return
	}

	err = unmarshal(body, &st)
	return
}

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


Question:
To get default values for the object.
        @param self: The object pointer.
        @param fields: List of fields for which we want default values
        @return: A dictionary which of fields with values.

def default_get(self, fields):

        if self._context is None:
            self._context = {}
        res = super(QuickRoomReservation, self).default_get(fields)
        if self._context:
            keys = self._context.keys()
            if 'date' in keys:
                res.update({'check_in': self._context['date']})
            if 'room_id' in keys:
                roomid = self._context['room_id']
                res.update({'room_id': int(roomid)})
        return res

def dumpable_obj(obj):
    ''' '''

    if isinstance(obj, list):
        _return_list = []
        for item in obj:
            if isinstance(item, list):
                _return_list.append(dumpable_obj(item))
            elif isinstance(item, set):
                _return_list.append(list(item))
            elif isinstance(item, dict):
                _return_list.append(dumpable_obj(item))
            else:
                try:
                    json.dumps(item)
                    _return_list.append(item)
                except:
                    _return_list.append(str(type(item)))
        return _return_list
    elif isinstance(obj, set):
        return list(obj)
    elif isinstance(obj, dict):
        _return_obj = {}
        for key, item in obj.items():
            if isinstance(item, list):
                _return_obj[key] = dumpable_obj(item)
            elif isinstance(item, set):
                _return_obj[key] = list(item)
            elif isinstance(item, dict):
                _return_obj[key] = dumpable_obj(item)
            else:
                try:
                    json.dumps(item)
                    _return_obj[key] = item
                except:
                    _return_obj[key] = str(type(item))
        return _return_obj
    else:
        try:
            json.dumps(obj)
            return obj
        except:
            return str(type(obj))

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


Question:
Get the transaction result once Webpay has resolved the financial authorization

@param string|null $token Webpay token
@return WebpayStandard\transactionResultOutput
@throws Exceptions\InvalidCertificateException
@throws \SoapFault

public function getTransactionResult($token = null)
    {
        if (!$token) {
            $token = $_POST['token_ws'];
        }

        return $this->service->getTransactionResult($token)->return;
    }

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:
Parses the YAML file.

@param  string $file
@return void

protected function parse($file)
    {
        $search = '%%CURRENT_DIRECTORY%%';

        $yaml = file_get_contents($file);

        $yaml = str_replace($search, $this->root, $yaml);

        $result = Yaml::parse($yaml);

        $this->commands = $result['paths']['commands'];

        $this->namespace = $result['namespaces']['commands'];

        $this->templates = $result['paths']['templates'];
    }

def check_eyaml_data(name, val)
      error = nil
      if val.is_a? String
        err = check_eyaml_blob(val)
        error = "Key #{name} #{err}" if err
      elsif val.is_a? Array
        val.each_with_index do |v, idx|
          error = check_eyaml_data("#{name}[#{idx}]", v)
          break if error
        end
      elsif val.is_a? Hash
        val.each do |k,v|
          error = check_eyaml_data("#{name}['#{k}']", v)
          break if error
        end
      end
      error
    end

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


Question:
// ShortHumanDuration returns a succint representation of the provided duration
// with limited precision for consumption by humans.

func ShortHumanDuration(d time.Duration) string {
	// Allow deviation no more than 2 seconds(excluded) to tolerate machine time
	// inconsistence, it can be considered as almost now.
	if seconds := int(d.Seconds()); seconds < -1 {
		return fmt.Sprintf("<invalid>")
	} else if seconds < 0 {
		return fmt.Sprintf("0s")
	} else if seconds < 60 {
		return fmt.Sprintf("%ds", seconds)
	} else if minutes := int(d.Minutes()); minutes < 60 {
		return fmt.Sprintf("%dm", minutes)
	} else if hours := int(d.Hours()); hours < 24 {
		return fmt.Sprintf("%dh", hours)
	} else if hours < 24*365 {
		return fmt.Sprintf("%dd", hours/24)
	}
	return fmt.Sprintf("%dy", int(d.Hours()/24/365))
}

func (ue UnpackingError) Error() string {
	var dv string
	var dt string
	k := ue.Destination.Kind()
	switch k {
	case reflect.Ptr:
		dt = fmt.Sprintf("%s", ue.Destination.Type().Elem())
		if !ue.Destination.IsNil() {
			dv = fmt.Sprintf("%v", ue.Destination.Elem().Interface())
		} else {
			dv = "nil"

		}
	case reflect.Invalid:
		dv = "invalid"
		dt = dv
	default:
		dv = fmt.Sprintf("%v", ue.Destination.Interface())
		dt = fmt.Sprintf("%s", ue.Destination.Type())
	}

	return fmt.Sprintf("Error unpacking %v(%T) into %s(%s):%v",
		ue.Source,
		ue.Source,
		dv,
		dt,
		ue.Err)
}

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


Question: // PrettyTime returns the string representation of the duration. It rounds the time duration to a second and returns a "---" when duration is 0

func PrettyTime(t time.Duration) string {
	if t == 0 {
		return "---"
	}
	return (t - (t % time.Second)).String()
}

def performance_log_message(self):
        """"""
        message = m.Message()
        table = m.Table(style_class='table table-condensed table-striped')
        row = m.Row()
        row.add(m.Cell(tr('Function'), header=True))
        row.add(m.Cell(tr('Time'), header=True))
        if setting(key='memory_profile', expected_type=bool):
            row.add(m.Cell(tr('Memory'), header=True))
        table.add(row)

        if self.performance_log is None:
            message.add(table)
            return message

        indent = -1

        def display_tree(tree, space):
            space += 1
            new_row = m.Row()

            # This is a kind of hack to display the tree with indentation
            text = '|'
            text += '*' * space

            if tree.children:
                text += '\ '
            else:
                text += '| '
            text += tree.__str__()

            busy = tr('Busy')
            new_row.add(m.Cell(text))
            time = tree.elapsed_time
            if time is None:
                time = busy
            new_row.add(m.Cell(time))
            if setting(key='memory_profile', expected_type=bool):
                memory_used = tree.memory_used
                if memory_used is None:
                    memory_used = busy
                new_row.add(m.Cell(memory_used))
            table.add(new_row)
            if tree.children:
                for child in tree.children:
                    display_tree(child, space)
            space -= 1

        # noinspection PyTypeChecker
        display_tree(self.performance_log, indent)
        message.add(table)

        return message

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


Question:
研发校验更新和删除条件入参：每一个where条件都不允许忽略

@deprecated 废弃严格检查方式，对业务限制太严重

private static UnitResponse doStrictCheck(WhereAction action, Map map) {
        LOG.debug("db执行安全检查..." + map);
        for (String whereFragment : action.searchConditions()) {
            if (action.ignoreWhereFragment(whereFragment, map)) {
                LOG.info(String.format("WARN-安全检查不通过...检查where语句%s发现它是一个全表操作!参数=%s", whereFragment, map));
                return UnitResponse.createError(DaoGroup.CODE_LACK_OF_PARAMETER, JdbcPatternUtil.getCamelKeys(whereFragment), "缺少参数");
            }
        }
        return UnitResponse.createSuccess();
    }

function renderSimpleRuby( $ruby ) {
  var frag = $.create( '!' )
  var clazz = $ruby.classList
  var $rb, $ru

  frag.appendChild( $.clone( $ruby ))

  $
  .tag( 'rt', frag.firstChild )
  .forEach(function( $rt ) {
    var $rb = $.create( '!' )
    var airb = []
    var irb

    // Consider the previous nodes the implied
    // ruby base
    do {
      irb = ( irb || $rt ).previousSibling
      if ( !irb || irb.nodeName.match( /((?:h\-)?r[ubt])/i ))  break

      $rb.insertBefore( $.clone( irb ), $rb.firstChild )
      airb.push( irb )
    } while ( !irb.nodeName.match( /((?:h\-)?r[ubt])/i ))

    // Create a real `<h-ru>` to append.
    $ru = clazz.contains( 'zhuyin' ) ? createZhuyinRu( $rb, $rt ) : createNormalRu( $rb, $rt )

    // Replace the ruby text with the new `<h-ru>`,
    // and remove the original implied ruby base(s)
    try {
      $rt.parentNode.replaceChild( $ru, $rt )
      airb.map( $.remove )
    } catch ( e ) {}
  })
  return createCustomRuby( frag )
}

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


Question:
Helper method to sample from the top and bottom edges of a cylinder.

    If top is set to True, samples only from top edge. If top is set to False,
    samples only from bottom edge. If not set (defaults to None), samples from
    both edges.

def _sampleLocationOnEdge(self, top=None):

    if top is None:
      z = random.choice([-1, 1]) * self.height / 2.
    else:
      z = self.height / 2. if top else - self.height / 2.
    sampledAngle = 2 * random.random() * pi
    x, y = self.radius * cos(sampledAngle), self.radius * sin(sampledAngle)
    return [x, y, z]

def split(self, N, force=False):

        mode = self.mode
        assert mode in ("batch", "cycle", "optimal")
        logging.debug("set split mode=%s" % mode)

        self.names = self.__class__.get_names(self.filename, N)
        if self.outputdir:
            self.names = [op.join(self.outputdir, x) for x in self.names]

        if not need_update(self.filename, self.names) and not force:
            logging.error("file %s already existed, skip file splitting" % \
                    self.names[0])
            return

        filehandles = [open(x, "w") for x in self.names]

        if mode == "batch":
            for batch, fw in zip(self._batch_iterator(N), filehandles):
                count = self.write(fw, batch)
                logging.debug("write %d records to %s" % (count, fw.name))

        elif mode == "cycle":
            handle = self._open(self.filename)
            for record, fw in zip(handle, cycle(filehandles)):
                count = self.write(fw, [record])

        elif mode == "optimal":
            """
            This mode is based on Longest Processing Time (LPT) algorithm:

            A simple, often-used algorithm is the LPT algorithm (Longest
            Processing Time) which sorts the jobs by its processing time and
            then assigns them to the machine with the earliest end time so far.
            This algorithm achieves an upper bound of 4/3 - 1/(3m) OPT.

            Citation: <http://en.wikipedia.org/wiki/Multiprocessor_scheduling>
            """
            endtime = [0] * N
            handle = self._open(self.filename)
            for record in handle:
                mt, mi = min((x, i) for (i, x) in enumerate(endtime))
                fw = filehandles[mi]
                count = self.write(fw, [record])
                endtime[mi] += len(record)

        for fw in filehandles:
            fw.close()

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


Question:
Add a new leaf to this tree

@param child
@return Tree node of the newly added leaf

public Tree<T> addLeaf( T child )
    {
        Tree<T> leaf = new Tree<T>( child );
        leaf.parent = this;
        children.add( leaf );
        return leaf;
    }

func tagAppendParser(doc *p2.Parser, start *p2.Token, arguments *p2.Parser) (p2.INodeTag, *p2.Error) {
	var name string
	var isPublic bool
	// Parse variable name
	typeToken := arguments.MatchType(p2.TokenIdentifier)
	if typeToken != nil {
		name = typeToken.Val
	} else if sToken := arguments.MatchType(p2.TokenString); nil != sToken {
		name = sToken.Val
	} else {
		return nil, arguments.Error("Expected an identifier or string.", nil)
	}

	evals := []p2.IEvaluator{}
	for arguments.Remaining() > 0 {
		expr, err := arguments.ParseExpression()
		if err != nil {
			return nil, err
		}
		evals = append(evals, expr)
	}

	return &INodeImplied{Exec: func(ctx *p2.ExecutionContext, w p2.TemplateWriter) *p2.Error {

		node := &tagAppendNode{isPublic, name, evals}
		return node.Execute(ctx, w)
	}}, nil

}

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


Question:
for each schema version present in the cluster, returns a list of nodes at that version.
    hosts that do not respond will be under the key DatabaseDescriptor.INITIAL_VERSION.
    the cluster is all on the same version if the size of the map is 1.

def describe_schema_versions(self, ):

    self._seqid += 1
    d = self._reqs[self._seqid] = defer.Deferred()
    self.send_describe_schema_versions()
    return d

def map_statements(self):
        """"""
        for stmt in self.statements:
            for agent in stmt.agent_list():
                if agent is None:
                    continue
                all_mappings = []
                for db_name, db_id in agent.db_refs.items():
                    if isinstance(db_id, list):
                        db_id = db_id[0][0]
                    mappings = self._map_id(db_name, db_id)
                    all_mappings += mappings
                for map_db_name, map_db_id, score, orig_db_name in all_mappings:
                    if map_db_name in agent.db_refs:
                        continue
                    if self.scored:
                        # If the original one is a scored grounding,
                        # we take that score and multiply it with the mapping
                        # score. Otherwise we assume the original score is 1.
                        try:
                            orig_score = agent.db_refs[orig_db_name][0][1]
                        except Exception:
                            orig_score = 1.0
                        agent.db_refs[map_db_name] = \
                            [(map_db_id, score * orig_score)]
                    else:
                        if map_db_name in ('UN', 'HUME'):
                            agent.db_refs[map_db_name] = [(map_db_id, 1.0)]
                        else:
                            agent.db_refs[map_db_name] = map_db_id

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


Question:
FUNCTIONS //
FUNCTION: setMetricQuery( query )
Configures a metric query.

@param {Query} Query instance

function setMetricQuery( query ) {
		query.metric( metric )
			.aggregator( aggregator )
			.downsample( downsample )
			.rate( rate )
			.rateOptions({
				'counter': counter,
				'counterMax': counterMax,
				'resetValue': resetValue
			})
			.tags( 'nid', tags.nid );
	}

protected function getFacetParameters() {
        $facetParameters = [];
        $facetParameters['facet'] = 'true';
        $facetParameters['facet.mincount'] = $this->getMinCount();
        $facetParameters['facet.limit'] = $this->getLimit();
        $facetParameters['facet.field'] = $this->getFields();

        foreach ($this->getAdditionalParameters() as $additionalParameterKey => $additionalParameterValue) {
            $facetParameters[$additionalParameterKey] = $additionalParameterValue;
        }

        if ($facetParameters['json.facet']) {
            $facetParameters['json.facet'] = json_encode($facetParameters['json.facet']);
        }

        $facetParameters = $this->applySorting($facetParameters);
        return $facetParameters;
    }

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


Question: copy-pasted from swagger-js

function(inlineStr) {
    if(/^Inline Model \d+$/.test(inlineStr) && this.inlineModels) {
      var id = parseInt(inlineStr.substr('Inline Model'.length).trim(),10); //
      var model = this.inlineModels[id];
      return model;
    }
    // I'm returning null here, should I rather throw an error?
    return null;
  }

public void setImport(StylesheetComposed v)
  {

    if (null == m_imports)
      m_imports = new Vector();

    // I'm going to insert the elements in backwards order,
    // so I can walk them 0 to n.
    m_imports.addElement(v);
  }

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


Question:
Add appropriate form elements to the criteria form

@param stdClass $data details of overall criterion

public function config_form_criteria($data) {
        global $OUTPUT;
        $prefix = 'criteria-' . $this->id;
        if (count($data->criteria) > 2) {
            echo $OUTPUT->box_start();
            if (!empty($this->description)) {
                $badge = new badge($this->badgeid);
                echo $OUTPUT->box(
                    format_text($this->description, $this->descriptionformat, array('context' => $badge->get_context())),
                    'criteria-description');
            }
            echo $OUTPUT->heading($this->get_title(), 2);

            $agg = $data->get_aggregation_methods();
            if (!$data->is_locked() && !$data->is_active()) {
                $editurl = new moodle_url('/badges/criteria_settings.php',
                               array('badgeid' => $this->badgeid,
                                   'edit' => true,
                                   'type' => $this->criteriatype,
                                   'crit' => $this->id
                               )
                        );
                $editaction = $OUTPUT->action_icon($editurl, new pix_icon('t/edit', get_string('edit')), null,
                              array('class' => 'criteria-action'));
                echo $OUTPUT->box($editaction, array('criteria-header'));

                $url = new moodle_url('criteria.php', array('id' => $data->id, 'sesskey' => sesskey()));
                echo $OUTPUT->single_select($url, 'update', $agg, $data->get_aggregation_method($this->criteriatype),
                    null, null, array('aria-describedby' => 'overall'));
                echo html_writer::span(get_string('overallcrit', 'badges'), '', array('id' => 'overall'));
            } else {
                echo $OUTPUT->box(get_string('criteria_descr_' . $this->criteriatype, 'badges',
                        core_text::strtoupper($agg[$data->get_aggregation_method()])), 'clearfix');
            }
            echo $OUTPUT->box_end();
        }
    }

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: See {@link #unsortedSegmentSum(String, SDVariable, SDVariable, int)}

public SDVariable unsortedSegmentSum(@NonNull SDVariable data, @NonNull SDVariable segmentIds, int numSegments) {
        return unsortedSegmentSum(null, data, segmentIds, numSegments);
    }

def stats(self):

        ret = '{name}:\n' \
            '  sample_num={sample_num}, batch_num={batch_num}\n' \
            '  key={bucket_keys}\n' \
            '  cnt={bucket_counts}\n' \
            '  batch_size={bucket_batch_sizes}'\
            .format(name=self.__class__.__name__,
                    sample_num=len(self._lengths),
                    batch_num=len(self._batch_infos),
                    bucket_keys=self._bucket_keys,
                    bucket_counts=[len(sample_ids) for sample_ids in self._bucket_sample_ids],
                    bucket_batch_sizes=self._bucket_batch_sizes)
        return ret

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


Question:
Prepare the attributes of the entity that has to be persisted.

@return array The prepared attributes

protected function prepareAttributes()
    {

        // prepare the date format for the created at/updated at dates
        $createdAt = $this->getValue(ColumnKeys::CREATED_AT, date('Y-m-d H:i:s'), array($this, 'formatDate'));
        $updatedAt = $this->getValue(ColumnKeys::UPDATED_AT, date('Y-m-d H:i:s'), array($this, 'formatDate'));

        // load the product's attribute set ID
        $attributeSet = $this->getAttributeSetByAttributeSetName($this->getValue(ColumnKeys::ATTRIBUTE_SET_CODE));
        $attributeSetId = $attributeSet[MemberNames::ATTRIBUTE_SET_ID];
        $this->setAttributeSet($attributeSet);

        // initialize parent ID (the parent array entry)
        $parentId = $this->categoryIds[sizeof($this->categoryIds) - 1];

        // initialize the level
        $level = sizeof($this->categoryIds);

        // load the position, if available
        $position = $this->getValue(ColumnKeys::POSITION, 0);

        // return the prepared product
        return $this->initializeEntity(
            array(
                MemberNames::CREATED_AT       => $createdAt,
                MemberNames::UPDATED_AT       => $updatedAt,
                MemberNames::ATTRIBUTE_SET_ID => $attributeSetId,
                MemberNames::PATH             => '',
                MemberNames::PARENT_ID        => $parentId,
                MemberNames::POSITION         => $position,
                MemberNames::LEVEL            => $level,
                MemberNames::CHILDREN_COUNT   => 0
            )
        );
    }

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:
Get the time zone for a specific exchange suffix

@param suffix suffix for the exchange in YahooFinance
@return time zone of the exchange

public static TimeZone get(String suffix) {
        if(SUFFIX_TIMEZONES.containsKey(suffix)) {
            return SUFFIX_TIMEZONES.get(suffix);
        }
        log.warn("Cannot find time zone for exchange suffix: '{}'. Using default: America/New_York", suffix);
        return SUFFIX_TIMEZONES.get("");
    }

public static boolean isDomainSuffix(String domain, String domainSuffix) {
        if (domain.length() < domainSuffix.length()) {
            return false;
        }
        if (domain.length() == domainSuffix.length()) {
            return domain.equals(domainSuffix);
        }

        return domain.endsWith(domainSuffix) && domain.charAt(domain.length() - domainSuffix.length() - 1) == '.';
    }

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


Question: Not every marker is followed by associated segment

private static boolean doesMarkerStartSegment(int markerSecondByte) {
    if (markerSecondByte == JfifUtil.MARKER_TEM) {
      return false;
    }

    if (markerSecondByte >= JfifUtil.MARKER_RST0 && markerSecondByte <= JfifUtil.MARKER_RST7) {
      return false;
    }

    return markerSecondByte != JfifUtil.MARKER_EOI && markerSecondByte != JfifUtil.MARKER_SOI;
  }

public void handleQueryMessage(final long senderHSId, long requestId, long gapStart) {
            m_es.execute(new Runnable() {
                @Override
                public void run() {
                    long lastSeq = Long.MIN_VALUE;
                    Pair<Long, Long> range = m_gapTracker.getRangeContaining(gapStart);
                    if (range != null) {
                        lastSeq = range.getSecond();
                    }
                    sendQueryResponse(senderHSId, requestId, lastSeq);
                }
            });
    }

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


Question:
Based on the {@link #whitelistTag}, find all URI which imports the tag. Then filter out

1. disabled dataset URI
2. None leaf dataset URI

Then created {@link ConfigBasedDataset} based on the {@link Config} of the URIs

@Override
  public List<Dataset> findDatasets() throws IOException {
    Set<URI> leafDatasets = getValidDatasetURIs(this.commonRoot);
    if (leafDatasets.isEmpty()) {
      return ImmutableList.of();
    }

    // Parallel execution for copyDataset for performance consideration.
    final List<Dataset> result = new CopyOnWriteArrayList<>();
    Iterator<Callable<Void>> callableIterator =
        Iterators.transform(leafDatasets.iterator(), new Function<URI, Callable<Void>>() {
          @Override
          public Callable<Void> apply(final URI datasetURI) {
            return findDatasetsCallable(configClient, datasetURI, props, blacklistPatterns, result);
          }
        });

    this.executeItertorExecutor(callableIterator);
    log.info("found {} datasets in ConfigBasedDatasetsFinder", result.size());
    return result;
  }

func ConvertWorkItemLinkTypeFromModel(request *http.Request, modelLinkType link.WorkItemLinkType) app.WorkItemLinkTypeSingle {
	spaceTemplateRelatedURL := rest.AbsoluteURL(request, app.SpaceTemplateHref(modelLinkType.SpaceTemplateID.String()))
	spaceRelatedURL := rest.AbsoluteURL(request, app.SpaceHref(space.SystemSpace.String()))

	topologyStr := modelLinkType.Topology.String()
	var converted = app.WorkItemLinkTypeSingle{
		Data: &app.WorkItemLinkTypeData{
			Type: link.EndpointWorkItemLinkTypes,
			ID:   &modelLinkType.ID,
			Attributes: &app.WorkItemLinkTypeAttributes{
				Name:               &modelLinkType.Name,
				Description:        modelLinkType.Description,
				Version:            &modelLinkType.Version,
				CreatedAt:          &modelLinkType.CreatedAt,
				UpdatedAt:          &modelLinkType.UpdatedAt,
				ForwardName:        &modelLinkType.ForwardName,
				ForwardDescription: modelLinkType.ForwardDescription,
				ReverseName:        &modelLinkType.ReverseName,
				ReverseDescription: modelLinkType.ReverseDescription,
				Topology:           &topologyStr,
			},
			Relationships: &app.WorkItemLinkTypeRelationships{
				Space:         app.NewSpaceRelation(space.SystemSpace, spaceRelatedURL),
				SpaceTemplate: app.NewSpaceTemplateRelation(modelLinkType.SpaceTemplateID, spaceTemplateRelatedURL),
			},
		},
	}
	return converted
}

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


Question:
Check if a column exist in table.

@param table the table to check
@param name the name of the column
@return

public static boolean columnExist(CSTable table, String name) {
        for (int i = 1; i <= table.getColumnCount(); i++) {
            if (table.getColumnName(i).startsWith(name)) {
                return true;
            }
        }
        return false;
    }

private function getColumns($data)
        {
            $cols = [];

            foreach ($data[0] as $key => $value) {
                if (is_numeric($key)){
                    if (is_string($data[1][$key])) {
                        $cols[] = ['id' => '', 'label' => $value, 'type' => 'string'];
                    } else {
                        $cols[] = ['id' => '', 'label' => $value, 'type' => 'number'];
                    }

                    $this->_skipFirstRow = true;
                } else {
                    if (is_string($value)) {
                        $cols[] = ['id' => '', 'label' => $key, 'type' => 'string'];
                    } else {
                        $cols[] = ['id' => '', 'label' => $key, 'type' => 'number'];
                    }
                }
            }

            return $cols;
        }

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


Question: Get mounted file systems

public function getMounts()
    {

        // Time?
        if (!empty($this->settings['timer'])) {
            $t = new Timer('Mounted file systems');
        }

        // Get result of mount command
        try {
            $res = $this->exec->exec('mount');
        } catch (Exception $e) {
            Errors::add('Linfo Core', 'Error running `mount` command');

            return [];
        }

        // Parse it
        if (preg_match_all('/^(\S+) on (\S+) \((\w+)(?:, (.+))?\)/m', $res, $m, PREG_SET_ORDER) == 0) {
            return [];
        }

        // Store them here
        $mounts = [];

        // Deal with each entry
        foreach ($m as $mount) {

            // Should we not show this?
            if (in_array($mount[1], $this->settings['hide']['storage_devices']) || in_array($mount[3], $this->settings['hide']['filesystems'])) {
                continue;
            }

            // Get these
            $size = @disk_total_space($mount[2]);
            $free = @disk_free_space($mount[2]);
            $used = $size - $free;

            // Optionally get mount options
            if (
                $this->settings['show']['mounts_options'] &&
                !in_array($mount[3], (array) $this->settings['hide']['fs_mount_options']) &&
                isset($mount[4])
            ) {
                $mount_options = explode(', ', $mount[4]);
            } else {
                $mount_options = [];
            }

            // Might be good, go for it
            $mounts[] = array(
                'device' => $mount[1],
                'mount' => $mount[2],
                'type' => $mount[3],
                'size' => $size ,
                'used' => $used,
                'free' => $free,
                'free_percent' => ((bool) $free != false && (bool) $size != false ? round($free / $size, 2) * 100 : false),
                'used_percent' => ((bool) $used != false && (bool) $size != false ? round($used / $size, 2) * 100 : false),
                'options' => $mount_options,
            );
        }

        // Give it
        return $mounts;
    }

def changed(self):

        if not self.parents:
            return []
        return ChangedFileNodesGenerator([n for n in
                                self._get_paths_for_status('modified')], self)

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


Question:
Removes wildcards based on an ID list
@param array $idList array of numerical ID
@return void

public static function removeByIDs( $idList )
    {
        if ( !is_array( $idList ) )
            return;

        while ( count( $idList ) > 0 )
        {
            // remove by portion of 100 rows.
            $ids = array_splice( $idList, 0, 100 );

            $conditions = array( 'id' => array( $ids ) );

            eZPersistentObject::removeObject( self::definition(),
                                              $conditions );
        }
    }

public function package()
    {
        $package = [];
        $package['id'] = $this->id;
        $package['instructions'] = $this->instructions;
        $package['filterQuery'] = $this->filterQuery;
        $package['type'] = $this->type;
        $package['typeOptions'] = $this->typeOptions;
        $package['total'] = $this->total;
        $package['bundle'] = false;
        $package['bundle'] = ['offset' => $this->offset, 'size' => count($this->_items), 'items' => []];
        foreach ($this->_items as $item) {
            $package['bundle']['items'][$item->id] = $item->package();
        }

        return $package;
    }

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


Question: // SetRevert sets the Revert field's value.

func (s *UpdateHITReviewStatusInput) SetRevert(v bool) *UpdateHITReviewStatusInput {
	s.Revert = &v
	return s
}

def get_final(self):
        """"""
        if self.prec is None:
            return self.x
        else:
            return self.prec.undo(self.x)

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


Question: If callback is non-null, it will be used for error and load events.

function(method, data, callback) {
      xhr.open(method, url, true, user, password);
      if (mimeType != null && !headers.has("accept")) headers.set("accept", mimeType + ",*/*");
      if (xhr.setRequestHeader) headers.each(function(value, name) { xhr.setRequestHeader(name, value); });
      if (mimeType != null && xhr.overrideMimeType) xhr.overrideMimeType(mimeType);
      if (responseType != null) xhr.responseType = responseType;
      if (timeout > 0) xhr.timeout = timeout;
      if (callback == null && typeof data === "function") callback = data, data = null;
      if (callback != null && callback.length === 1) callback = fixCallback(callback);
      if (callback != null) request.on("error", callback).on("load", function(xhr) { callback(null, xhr); });
      event.call("beforesend", request, xhr);
      xhr.send(data == null ? null : data);
      return request;
    }

func (c *Collector) OnHTML(goquerySelector string, f HTMLCallback) {
	c.lock.Lock()
	if c.htmlCallbacks == nil {
		c.htmlCallbacks = make([]*htmlCallbackContainer, 0, 4)
	}
	c.htmlCallbacks = append(c.htmlCallbacks, &htmlCallbackContainer{
		Selector: goquerySelector,
		Function: f,
	})
	c.lock.Unlock()
}

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


Question:
once animation is setup, start the animation record the beginning and
ending time for the animation

public void startAnimation()
  {
    Date time = new Date();
    this.beginAnimation = time.getTime();
    this.endAnimation = beginAnimation + (long) (animationTime * 1000);
    this.animate = true;
  }

function () {
            var chart = this,
              axes = chart.axes,
              renderer = chart.renderer,
              options = chart.options;

            // Title
            chart.setTitle();

            // Legend
            chart.legend = new Legend(chart, options.legend);

            chart.getStacks(); // render stacks

            // Get margins by pre-rendering axes
            // set axes scales
            each(axes, function (axis) {
                axis.setScale();
            });

            chart.getMargins();

            chart.maxTicks = null; // reset for second pass
            each(axes, function (axis) {
                axis.setTickPositions(true); // update to reflect the new margins
                axis.setMaxTicks();
            });
            chart.adjustTickAmounts();
            chart.getMargins(); // second pass to check for new labels

            // Draw the borders and backgrounds
            chart.drawChartBox();

            // Axes
            if (chart.hasCartesianSeries) {
                each(axes, function (axis) {
                    axis.render();
                });
            }

            // The series
            if (!chart.seriesGroup) {
                chart.seriesGroup = renderer.g('series-group')
                  .attr({ zIndex: 3 })
                  .add();
            }
            chart.renderSeries();

            // Labels
            chart.renderLabels();

            // Credits
            chart.showCredits(options.credits);

            // Set flag
            chart.hasRendered = true;

        }

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


Question:
@param int $size

@return \chillerlan\Traits\ArrayHelpers\ByteArray
@throws \chillerlan\Traits\TraitException

public function fromIntSize(int $size):ByteArray{

		if(!$this->isAllowedInt($size)){
			throw new TraitException('invalid size');
		}

		return new $this->byteArrayClass($size);
	}

def Deserialize(self, reader):

        usage = reader.ReadByte()
        self.Usage = usage

        if usage == TransactionAttributeUsage.ContractHash or usage == TransactionAttributeUsage.Vote or \
                (usage >= TransactionAttributeUsage.Hash1 and usage <= TransactionAttributeUsage.Hash15):
            self.Data = reader.ReadBytes(32)

        elif usage == TransactionAttributeUsage.ECDH02 or usage == TransactionAttributeUsage.ECDH03:
            self.Data = bytearray(usage) + bytearray(reader.ReadBytes(32))

        elif usage == TransactionAttributeUsage.Script:
            self.Data = reader.ReadBytes(20)

        elif usage == TransactionAttributeUsage.DescriptionUrl:

            self.Data = reader.ReadBytes(reader.ReadByte())

        elif usage == TransactionAttributeUsage.Description or usage >= TransactionAttributeUsage.Remark:
            self.Data = reader.ReadVarBytes(max=self.MAX_ATTR_DATA_SIZE)
        else:
            logger.error("format error!!!")

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


Question: // SetIdentifier sets the Identifier field's value.

func (s *DeleteResourceServerInput) SetIdentifier(v string) *DeleteResourceServerInput {
	s.Identifier = &v
	return s
}

public <T> T getField(String locale, String key) {
    return localize(locale).getField(key);
  }

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


Question:
Returns list of files matches specified regex in specified directories

@param regex       to match file names
@param directories to find
@return list of files matches specified regex in specified directories

public static List<File> listFilesByRegex(String regex, File... directories) {
        return listFiles(directories,
                new RegexFileFilter(regex),
                CanReadFileFilter.CAN_READ);
    }

def _render_filenames(filenames, zip_file, saltenv, template):
    '''

    '''
    if not template:
        return (filenames, zip_file)

    # render the path as a template using path_template_engine as the engine
    if template not in salt.utils.templates.TEMPLATE_REGISTRY:
        raise CommandExecutionError(
            'Attempted to render file paths with unavailable engine '
            '{0}'.format(template)
        )

    kwargs = {}
    kwargs['salt'] = __salt__
    kwargs['pillar'] = __pillar__
    kwargs['grains'] = __grains__
    kwargs['opts'] = __opts__
    kwargs['saltenv'] = saltenv

    def _render(contents):
        '''
        Render :param:`contents` into a literal pathname by writing it to a
        temp file, rendering that file, and returning the result.
        '''
        # write out path to temp file
        tmp_path_fn = salt.utils.files.mkstemp()
        with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_:
            fp_.write(salt.utils.stringutils.to_str(contents))
        data = salt.utils.templates.TEMPLATE_REGISTRY[template](
            tmp_path_fn,
            to_str=True,
            **kwargs
        )
        salt.utils.files.safe_rm(tmp_path_fn)
        if not data['result']:
            # Failed to render the template
            raise CommandExecutionError(
                'Failed to render file path with error: {0}'.format(
                    data['data']
                )
            )
        else:
            return data['data']

    filenames = _render(filenames)
    zip_file = _render(zip_file)
    return (filenames, zip_file)

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


Question:
Whether string is a space or null

@param s
@return

public static final boolean isBlank(String s) {
		if (s == null || s.trim().length() == 0) {
			return true;
		}
		return false;
	}

def update_nsval(
        self, *, nsval: str = None, ns: str = None, val: str = None
    ) -> None:

        if not (ns and val) and nsval:
            (ns, val) = nsval.split(":", 1)
        elif not (ns and val) and not nsval:
            log.error("Did not update NSArg - no ns:val or nsval provided")

        self.namespace = ns
        self.value = val

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


Question:
Load the RTree Spatial Index Values

@param tableName
table name
@param geometryColumnName
geometry column name
@param idColumnName
id column name

public void loadRTreeIndex(String tableName, String geometryColumnName,
			String idColumnName) {

		String sqlName = GeoPackageProperties.getProperty(SQL_PROPERTY,
				LOAD_PROPERTY);
		executeSQL(sqlName, tableName, geometryColumnName, idColumnName);
	}

public void addField(String fieldName) throws QueryException {
		EReference feature = null;
		for (TypeDef typeDef : types) {
			if (typeDef.geteClass().getEStructuralFeature(fieldName) == null) {
				throw new QueryException("Class \"" + typeDef.geteClass().getName() + "\" does not have the field \"" + fieldName + "\"");
			}
			if (feature == null) {
				if (!(typeDef.geteClass().getEStructuralFeature(fieldName) instanceof EReference)) {
					throw new QueryException(fieldName + " is not a reference");
				}
				feature = (EReference) typeDef.geteClass().getEStructuralFeature(fieldName);
			} else {
				if (feature != typeDef.geteClass().getEStructuralFeature(fieldName)) {
					throw new QueryException("Classes \"" + typeDef.geteClass().getName() + "\" and \"" + feature.getEContainingClass().getName() + "\" have fields with the same name, but they are not logically the same");
				}
			}
		}
		if (fields == null) {
			fields = new ArrayList<>();
		}
		fields.add(feature);
	}

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


Question: // SetEbsOptimized sets the EbsOptimized field's value.

func (s *UpdateInstanceInput) SetEbsOptimized(v bool) *UpdateInstanceInput {
	s.EbsOptimized = &v
	return s
}

func (mcs *ConsenterSupport) WriteBlock(block *cb.Block, encodedMetadataValue []byte) {
	if encodedMetadataValue != nil {
		block.Metadata.Metadata[cb.BlockMetadataIndex_ORDERER] = utils.MarshalOrPanic(&cb.Metadata{Value: encodedMetadataValue})
	}
	mcs.Append(block)
}

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


Question: // Remove all items in one or more cache instances

func (tc *TransCache) Clear(chIDs []string) {
	tc.cacheMux.Lock()
	if chIDs == nil {
		chIDs = make([]string, len(tc.cache))
		i := 0
		for chID := range tc.cache {
			chIDs[i] = chID
			i += 1
		}
	}
	for _, chID := range chIDs {
		tc.cacheInstance(chID).Clear()
	}
	tc.cacheMux.Unlock()
}

@Override
	public void clearCache() {
		entityCache.clearCache(CommerceAccountUserRelImpl.class);

		finderCache.clearCache(FINDER_CLASS_NAME_ENTITY);
		finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
		finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
	}

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


Question:
Returns the xhtml for this module as a fully parsed and rendered string.

@return string

public function FetchView() {
      $ViewPath = $this->FetchViewLocation();
      $String = '';
      ob_start();
      if(is_object($this->_Sender) && isset($this->_Sender->Data)) {
         $Data = $this->_Sender->Data;
      } else {
         $Data = array();
      }
      include ($ViewPath);
      $String = ob_get_contents();
      @ob_end_clean();
      return $String;
   }

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

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


Question: Handles all `<a>` clicks in the app not handled by another view. This lets us determine if this is a click that should be handled internally by the app.

function (e) {
    // This module determines whether a click event is
    // a local click (making sure the for modifier keys, etc)
    // and dealing with browser quirks to determine if this
    // event was from clicking an internal link. That we should
    // treat like local navigation.
    var localPath = localLinks.pathname(e);

    // fixes navigation problem on Windows platform
    if (navigator.platform === 'Win32') {
      localPath = localPath.replace('/C:', '');
    }

    if (localPath) {
      e.preventDefault();
      app.navigate(localPath);
    }
  }

func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
	if !value.IsValid() {
		if typ == nil || canBeNil(typ) {
			// An untyped nil interface{}. Accept as a proper nil value.
			return reflect.Zero(typ)
		}
		s.errorf("invalid value; expected %s", typ)
	}
	if typ != nil && !value.Type().AssignableTo(typ) {
		if value.Kind() == reflect.Interface && !value.IsNil() {
			value = value.Elem()
			if value.Type().AssignableTo(typ) {
				return value
			}
			// fallthrough
		}
		// Does one dereference or indirection work? We could do more, as we
		// do with method receivers, but that gets messy and method receivers
		// are much more constrained, so it makes more sense there than here.
		// Besides, one is almost always all you need.
		switch {
		case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
			value = value.Elem()
			if !value.IsValid() {
				s.errorf("dereference of nil pointer of type %s", typ)
			}
		case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
			value = value.Addr()
		default:
			s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
		}
	}
	return value
}

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


Question:
Checks if current position is valid.

@return bool Returns true on success, false otherwise

public function valid()
    {
        if (is_null($this->current)) {
            return ! empty($this->branch);
        }
        if ($this->current instanceof RecursiveLeafInterface) {
            return $this->current->valid();
        }

        return false;
    }

public function setByPosition($pos, $value)
    {
        switch ($pos) {
            case 0:
                $this->setId($value);
                break;
            case 1:
                $this->setFirstName($value);
                break;
            case 2:
                $this->setLastName($value);
                break;
            case 3:
                $this->setCreatedAt($value);
                break;
            case 4:
                $this->setUpdatedAt($value);
                break;
        } // switch()
    }

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


Question: Retrieves the DCNM network info for a tenant.

def retrieve_dcnm_net_info(self, tenant_id, direc):

        serv_obj = self.get_service_obj(tenant_id)
        net_dict = serv_obj.get_dcnm_net_dict(direc)
        return net_dict

func (dl *DaemonLocal) Identify(
	ctx context.Context, assertion, _ string,
	offline keybase1.OfflineAvailability) (
	kbname.NormalizedUsername, keybase1.UserOrTeamID, error) {
	// The local daemon doesn't need to distinguish resolves from
	// identifies.
	return dl.Resolve(ctx, assertion, offline)
}

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


Question: // SetStatus sets the status for the application.

func (a *Application) SetStatus(statusInfo status.StatusInfo) error {
	if !status.ValidWorkloadStatus(statusInfo.Status) {
		return errors.Errorf("cannot set invalid status %q", statusInfo.Status)
	}

	var newHistory *statusDoc
	m, err := a.st.Model()
	if err != nil {
		return errors.Trace(err)
	}
	if m.Type() == ModelTypeCAAS {
		// Application status for a caas model needs to consider status
		// info coming from the operator pod as well; It may need to
		// override what is set here.
		operatorStatus, err := getStatus(a.st.db(), applicationGlobalOperatorKey(a.Name()), "operator")
		expectWorkload, err := expectWorkload(a.st, a.Name())
		if err != nil {
			return errors.Trace(err)
		}
		if err == nil {
			newHistory, err = caasHistoryRewriteDoc(statusInfo, operatorStatus, expectWorkload, caasApplicationDisplayStatus, a.st.clock())
			if err != nil {
				return errors.Trace(err)
			}
		} else if !errors.IsNotFound(err) {
			return errors.Trace(err)
		}
	}

	return setStatus(a.st.db(), setStatusParams{
		badge:            "application",
		globalKey:        a.globalKey(),
		status:           statusInfo.Status,
		message:          statusInfo.Message,
		rawData:          statusInfo.Data,
		updated:          timeOrNow(statusInfo.Since, a.st.clock()),
		historyOverwrite: newHistory,
	})
}

func (s *ListApplicationsOutput) SetHasMoreApplications(v bool) *ListApplicationsOutput {
	s.HasMoreApplications = &v
	return s
}

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


Question: // MountAccountController "mounts" a Account resource controller on the given service.

func MountAccountController(service *goa.Service, ctrl AccountController) {
	initService(service)
	var h goa.Handler
	service.Mux.Handle("OPTIONS", "/cellar/accounts", ctrl.MuxHandler("preflight", handleAccountOrigin(cors.HandlePreflight()), nil))
	service.Mux.Handle("OPTIONS", "/cellar/accounts/:accountID", ctrl.MuxHandler("preflight", handleAccountOrigin(cors.HandlePreflight()), nil))

	h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
		// Check if there was an error loading the request
		if err := goa.ContextError(ctx); err != nil {
			return err
		}
		// Build the context
		rctx, err := NewCreateAccountContext(ctx, req, service)
		if err != nil {
			return err
		}
		// Build the payload
		if rawPayload := goa.ContextRequest(ctx).Payload; rawPayload != nil {
			rctx.Payload = rawPayload.(*CreateAccountPayload)
		} else {
			return goa.MissingPayloadError()
		}
		return ctrl.Create(rctx)
	}
	h = handleAccountOrigin(h)
	service.Mux.Handle("POST", "/cellar/accounts", ctrl.MuxHandler("create", h, unmarshalCreateAccountPayload))
	service.LogInfo("mount", "ctrl", "Account", "action", "Create", "route", "POST /cellar/accounts")

	h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
		// Check if there was an error loading the request
		if err := goa.ContextError(ctx); err != nil {
			return err
		}
		// Build the context
		rctx, err := NewDeleteAccountContext(ctx, req, service)
		if err != nil {
			return err
		}
		return ctrl.Delete(rctx)
	}
	h = handleAccountOrigin(h)
	service.Mux.Handle("DELETE", "/cellar/accounts/:accountID", ctrl.MuxHandler("delete", h, nil))
	service.LogInfo("mount", "ctrl", "Account", "action", "Delete", "route", "DELETE /cellar/accounts/:accountID")

	h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
		// Check if there was an error loading the request
		if err := goa.ContextError(ctx); err != nil {
			return err
		}
		// Build the context
		rctx, err := NewListAccountContext(ctx, req, service)
		if err != nil {
			return err
		}
		return ctrl.List(rctx)
	}
	h = handleAccountOrigin(h)
	service.Mux.Handle("GET", "/cellar/accounts", ctrl.MuxHandler("list", h, nil))
	service.LogInfo("mount", "ctrl", "Account", "action", "List", "route", "GET /cellar/accounts")

	h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
		// Check if there was an error loading the request
		if err := goa.ContextError(ctx); err != nil {
			return err
		}
		// Build the context
		rctx, err := NewShowAccountContext(ctx, req, service)
		if err != nil {
			return err
		}
		return ctrl.Show(rctx)
	}
	h = handleAccountOrigin(h)
	service.Mux.Handle("GET", "/cellar/accounts/:accountID", ctrl.MuxHandler("show", h, nil))
	service.LogInfo("mount", "ctrl", "Account", "action", "Show", "route", "GET /cellar/accounts/:accountID")

	h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
		// Check if there was an error loading the request
		if err := goa.ContextError(ctx); err != nil {
			return err
		}
		// Build the context
		rctx, err := NewUpdateAccountContext(ctx, req, service)
		if err != nil {
			return err
		}
		// Build the payload
		if rawPayload := goa.ContextRequest(ctx).Payload; rawPayload != nil {
			rctx.Payload = rawPayload.(*UpdateAccountPayload)
		} else {
			return goa.MissingPayloadError()
		}
		return ctrl.Update(rctx)
	}
	h = handleAccountOrigin(h)
	service.Mux.Handle("PUT", "/cellar/accounts/:accountID", ctrl.MuxHandler("update", h, unmarshalUpdateAccountPayload))
	service.LogInfo("mount", "ctrl", "Account", "action", "Update", "route", "PUT /cellar/accounts/:accountID")
}

protected function getView(Medools\Model $model)
    {
        $assignment = $model->assignment;

        $view_class = __NAMESPACE__ . "\\Views\\Cnab$assignment->cnab\\"
            . BankInterchange\Utils::toPascalCase($assignment->bank->name);

        return new $view_class($model);
    }

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


Question:
Generated and write xml-entity class to disk for the given ClassMetadataInfo instance

@param ClassMetadataInfo $metadata
@param string $outputDirectory
@return void

public function writeXmlEntityClass(ClassMetadataInfo $metadata, $outputDirectory)
    {
        $path = $outputDirectory . '/' . str_replace('\\', DIRECTORY_SEPARATOR, $metadata->name) . $this->extension;
        $dir = dirname($path);

        if ( ! is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

        $this->isNew = !file_exists($path) || (file_exists($path) && $this->regenerateXmlEntityIfExists);

        if ( ! $this->isNew) {
            $this->parseTokensInXmlEntityFile($path);
        }

        if ($this->backupExisting && file_exists($path)) {
            $backupPath = dirname($path) . DIRECTORY_SEPARATOR .  "~" . basename($path);
            if (!copy($path, $backupPath)) {
                throw new \RuntimeException("Attempt to backup overwritten xml-entity file but copy operation failed.");
            }
        }
        // If xml-entity doesn't exist or we're re-generating the xml-entities entirely
        if ($this->isNew) {
            file_put_contents($path, $this->generateXmlEntityClass($metadata));
        // If xml-entity exists and we're allowed to update the xml-entity class
        } else if ( ! $this->isNew && $this->updateXmlEntityIfExists) {
            file_put_contents($path, $this->generateUpdatedXmlEntityClass($metadata, $path));
        }
    }

void writeConfigPropsXml(List<ConfigPropType> props, Writer out, int indent) throws IOException
   {
      if (props == null || props.size() == 0)
         return;
      for (ConfigPropType prop : props)
      {
         writeIndent(out, indent);
         out.write("<config-property>");
         writeEol(out);

         writeIndent(out, indent + 1);
         out.write("<config-property-name>" + prop.getName() + "</config-property-name>");
         writeEol(out);
         writeIndent(out, indent + 1);
         out.write("<config-property-type>java.lang." + prop.getType() + "</config-property-type>");
         writeEol(out);
         writeIndent(out, indent + 1);
         out.write("<config-property-value>" + prop.getValue() + "</config-property-value>");
         writeEol(out);

         writeIndent(out, indent);
         out.write("</config-property>");
         writeEol(out);
         writeEol(out);
      }
   }

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


Question:
Add a role into the hierarchy

@param string $role
Role to add
@param array|null $parents
Parents for this role. Leave to null if none

@throws UndefinedRoleException
When a parent role cannot be resolved

public function addRole(string $role, ?array $parents = null): void
    {
        $this->roles[] = $role;

        if(null !== $parents) {
            $map = [];
            foreach ($parents as $parent) {
                $map[] = $parent;
                $map = \array_merge($map, $this->getRoles($parent));
            }
            unset($map[0]);

            $this->map[$role] = \array_values(\array_unique($map));
        }
    }

function onUncaughtException(\Throwable $exception): void
    {
        try {
            // handle the exception
            try {
                $this->emit(ErrorHandlerEvents::EXCEPTION, $exception, $this->debug);
            } catch (\Throwable $e) {
                $exception = new ChainedException(
                    'Additional exception was thrown from an [exception] event listener. See previous exceptions.',
                    0,
                    Exception::joinChains($exception, $e)
                );
            }

            $this->invokeErrorScreen($exception);

            return;
        } catch (\Throwable $e) {
            $exception = new ChainedException(
                sprintf('Additional exception was thrown while trying to invoke %s. See previous exceptions.', get_class($this->errorScreen)),
                0,
                Exception::joinChains($exception, $e)
            );

            $this->emit(ErrorHandlerEvents::FAILURE, $exception, $this->debug);
        }

        // unhandled exception
        if ($this->debug && $this->printUnhandledExceptionInDebug) {
            echo Exception::render($exception, true, true);
        }
    }

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


Question:
Returns a DataTable with analytics information for every unique entry page title
for the given site, time period & segment.

public function getEntryPageTitles($idSite, $period, $date, $segment = false, $expanded = false,
                                       $idSubtable = false, $flat = false)
    {
        Piwik::checkUserHasViewAccess($idSite);

        $dataTable = $this->getPageTitles($idSite, $period, $date, $segment, $expanded, $idSubtable, $flat);
        $this->filterNonEntryActions($dataTable);
        return $dataTable;
    }

public function getAuthorizeResponse($params, $user_id = null)
    {
        // build the URL to redirect to
        $result = array('query' => array());

        $params += array('scope' => null, 'state' => null);

        /*
         * a refresh token MUST NOT be included in the fragment
         *
         * @see http://tools.ietf.org/html/rfc6749#section-4.2.2
         */
        $includeRefreshToken = false;
        $result["fragment"] = $this->createAccessToken($params['client_id'], $user_id, $params['scope'], $includeRefreshToken);

        if (isset($params['state'])) {
            $result["fragment"]["state"] = $params['state'];
        }

        return array($params['redirect_uri'], $result);
    }

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


Question:
Set body of the message
        Args:
            body (str): The body of the message

def body(self, body: str):

        if body is not None and not isinstance(body, str):
            raise TypeError("'body' MUST be a string")
        self._body = body

func writeBindExecuteMsg(buf *pool.WriteBuffer, name string, params ...interface{}) error {
	buf.StartMessage(bindMsg)
	buf.WriteString("")
	buf.WriteString(name)
	buf.WriteInt16(0)
	buf.WriteInt16(int16(len(params)))
	for _, param := range params {
		buf.StartParam()
		bytes := types.Append(buf.Bytes, param, 0)
		if bytes != nil {
			buf.Bytes = bytes
			buf.FinishParam()
		} else {
			buf.FinishNullParam()
		}
	}
	buf.WriteInt16(0)
	buf.FinishMessage()

	buf.StartMessage(executeMsg)
	buf.WriteString("")
	buf.WriteInt32(0)
	buf.FinishMessage()

	writeSyncMsg(buf)

	return nil
}

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


Question: // PrintOutputConfig prints the config usage of a single output.

func PrintOutputConfig(name string) error {
	if creator, ok := outputs.Outputs[name]; ok {
		printConfig(name, creator(), "outputs", false)
	} else {
		return errors.New(fmt.Sprintf("Output %s not found", name))
	}
	return nil
}

public static ServerSetup[] verbose(ServerSetup[] serverSetups) {
        ServerSetup[] copies = new ServerSetup[serverSetups.length];
        for (int i = 0; i < serverSetups.length; i++) {
            copies[i] = serverSetups[i].createCopy().setVerbose(true);
        }
        return copies;
    }

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


Question:
Wraps a user callback to parse TimeInfo
    from a WebSocket data message

def _wrap_callback_parse_time_info(subscription, on_data, message):

    if message.type == message.REPLY:
        time_response = web_pb2.TimeSubscriptionResponse()
        time_response.ParseFromString(message.reply.data)
        time = parse_isostring(time_response.timeInfo.currentTimeUTC)
        #pylint: disable=protected-access
        subscription._process(time)
        if on_data:
            on_data(time)
    elif message.type == message.DATA:
        if message.data.type == yamcs_pb2.TIME_INFO:
            time_message = getattr(message.data, 'timeInfo')
            time = parse_isostring(time_message.currentTimeUTC)
            #pylint: disable=protected-access
            subscription._process(time)
            if on_data:
                on_data(time)

async def Track(self, payloads):
        '''

        '''
        # map input types to rpc msg
        _params = dict()
        msg = dict(type='PayloadsHookContext',
                   request='Track',
                   version=1,
                   params=_params)
        _params['payloads'] = payloads
        reply = await self.rpc(msg)
        return reply

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


Question:
Generator for streaming request body data.

        :param data: A response object to be streamed.
        :param callback: Custom callback for monitoring progress.

def stream_download(self, data, callback):
        # type: (Union[requests.Response, ClientResponse], Callable) -> Iterator[bytes]

        block = self.config.connection.data_block_size
        try:
            # Assume this is ClientResponse, which it should be if backward compat was not important
            return cast(ClientResponse, data).stream_download(block, callback)
        except AttributeError:
            try:
                # Assume this is the patched requests.Response from "send"
                return data._universal_http_response.stream_download(block, callback)  # type: ignore
            except AttributeError:
                # Assume this is a raw requests.Response
                from .universal_http.requests import RequestsClientResponse
                response = RequestsClientResponse(None, data)
                return response.stream_download(block, callback)

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:
take a word pattern and return a Python regexp. A word pattern is a word
    with unknown letters replaced by a '?', e.g. 'di?ti??nar?'.

def compile_pattern(word):

    return re.compile(r'^%s$' % re.sub(r'\?', '[a-z]',
                                       dicts.sanitize_word(word)))

def __write_filter_dic(wk_sheet, column):
    '''

    '''
    row1_val = wk_sheet['{0}1'.format(column)].value
    row2_val = wk_sheet['{0}2'.format(column)].value
    row3_val = wk_sheet['{0}3'.format(column)].value
    row4_val = wk_sheet['{0}4'.format(column)].value

    if row1_val and row1_val.strip() != '':
        row2_val = row2_val.strip()

        slug_name = row1_val.strip()
        c_name = row2_val.strip()

        tags1 = [x.strip() for x in row3_val.split(',')]
        tags_dic = {}

        #  if only one tag,
        if len(tags1) == 1:
            xx_1 = row2_val.split(':')  # 'text'  # HTML text input control.

            if xx_1[0].lower() in INPUT_ARR:
                xx_1[0] = xx_1[0].lower()
            else:
                xx_1[0] = 'text'

            if len(xx_1) == 2:
                ctr_type, unit = xx_1
            else:
                ctr_type = xx_1[0]
                unit = ''
            tags_dic[1] = unit

        else:
            ctr_type = 'select'  # HTML selectiom control.
            for index, tag_val in enumerate(tags1):
                # the index of tags_dic starts from 1.
                tags_dic[index + 1] = tag_val.strip()

        outkey = 'html_{0}'.format(slug_name)
        outval = {
            'en': slug_name,
            'zh': c_name,
            'dic': tags_dic,
            'type': ctr_type,
            'display': row4_val,
        }
        return (outkey, outval)
    else:
        return (None, None)

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


Question:
Sets an exact length.

@param int $length

@return LengthValidator

public function setLength(int $length) : self
    {
        $this->minLength = $length;
        $this->maxLength = $length;

        return $this;
    }

protected function validate(array $input, array &$messages)
    {
        if (!call_user_func_array($this->validationCallback, [$input, &$messages])) {
            if ($this->messageId) {
                $messages[] = new Message($this->messageId, $this->messageParameters);
            }
        }
    }

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


Question:
/*
Link specific warning message
(510343)

protected void issueDepthIntervalMessage(long depth)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "issueDepthIntervalMessage", new Long(depth));

    // {0} messages queued for transmission from messaging engine {1} to foreign bus {2} on link {3}.
    SibTr.info(tc, "REMOTE_LINK_DESTINATION_DEPTH_INTERVAL_REACHED_CWSIP0789",
        new Object[] {new Long(depth),
                      destinationHandler.getMessageProcessor().getMessagingEngineName(),
                      ((LinkHandler)destinationHandler).getBusName(),
                      destinationHandler.getName()});

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "issueDepthIntervalMessage");
  }

protected function err($msg, $url = null)
    {
        $this->saveDataInSession();
        return $this->msg($msg, self::MSG_BAD, $url);
    }

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


Question:
Sets attributes

@param array $attr = []

@return self

public function attr(Array $attr = [])
    {
        if( isset($this->settings['attr']) && is_array($this->settings['attr']) )
        {
            $settings = $this->settings['attr'];
        }
        else
        {
            $settings = [];
        }

        $this->settings['attr'] = array_merge($settings, $attr);

        return $this;
    }

public function getConfirmation()
    {
        $cAttribute = $this->confirmationAttribute;
        return (is_string($cAttribute) && !empty($cAttribute)) ? $this->$cAttribute : null;
    }

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


Question:
Sort an array of question types according to the order the admin set up,
and then alphabetically for the rest.
@param array qtype->name() => qtype->local_name().
@return array sorted array.

public static function sort_qtype_array($qtypes, $config = null) {
        if (is_null($config)) {
            $config = self::get_config();
        }

        $sortorder = array();
        $otherqtypes = array();
        foreach ($qtypes as $name => $localname) {
            $sortvar = $name . '_sortorder';
            if (isset($config->$sortvar)) {
                $sortorder[$config->$sortvar] = $name;
            } else {
                $otherqtypes[$name] = $localname;
            }
        }

        ksort($sortorder);
        core_collator::asort($otherqtypes);

        $sortedqtypes = array();
        foreach ($sortorder as $name) {
            $sortedqtypes[$name] = $qtypes[$name];
        }
        foreach ($otherqtypes as $name => $notused) {
            $sortedqtypes[$name] = $qtypes[$name];
        }
        return $sortedqtypes;
    }

public function changeSort(int $id, ?int $prevId, ?int $nextId)
	{
		$this->mapper->changeSort('position', $id, $prevId, $nextId);
	}

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


Question:
<p>
The Amazon Resource Names (ARNs) of the security groups that are configured for the Amazon EC2 resource.
</p>

@param securityGroupArns
The Amazon Resource Names (ARNs) of the security groups that are configured for the Amazon EC2 resource.

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

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

function executeCommand(parameters) {
    if (parameters.environment === undefined) { parameters.environment = plugin.myrmex.getConfig('environment'); }

    return plugin.loadTemplates()
    .then(templates => {
      // If the parameter "all" is set, we deploy all templates
      if (!parameters.all) {
        templates = _.filter(templates, template => { return parameters.templateIdentifiers.indexOf(template.getIdentifier()) !== -1; });
      }

      icli.print();
      icli.print('Deploying ' + icli.format.info(templates.length) + ' template(s):');
      icli.print('  AWS region: ' + icli.format.info(parameters.region));
      icli.print('  Environement: ' + icli.format.info(parameters.environment || 'no environment specified'));
      icli.print();
      icli.print('This operation may last a little');

      return Promise.map(templates, template => {
        const context = {
          environment: parameters.environment
        };
        return template.deploy(parameters.region, context);
      });
    })
    .then(reports => {
      console.log(reports);
    })
    .catch(e => {
      if (e.code === 'AccessDeniedException' && e.cause && e.cause.message) {
        icli.print('\n    ' + icli.format.error('Insufficient permissions to perform the action\n'));
        icli.print('The IAM user/role you are using to perform this action does not have sufficient permissions.\n');
        icli.print(e.cause.message + '\n');
        icli.print('Please update the policies of the user/role before trying again.\n');
        process.exit(1);
      }
      throw e;
    });
  }

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


Question:
Return the fields which contain personal data.

@param   collection $collection The initialised collection to add items to.
@return  collection A listing of user data stored through this system.

public static function get_metadata(collection $collection) : collection {
        $collection->add_database_table('scorm_scoes_track', [
                'userid' => 'privacy:metadata:userid',
                'attempt' => 'privacy:metadata:attempt',
                'element' => 'privacy:metadata:scoes_track:element',
                'value' => 'privacy:metadata:scoes_track:value',
                'timemodified' => 'privacy:metadata:timemodified'
            ], 'privacy:metadata:scorm_scoes_track');

        $collection->add_database_table('scorm_aicc_session', [
                'userid' => 'privacy:metadata:userid',
                'scormmode' => 'privacy:metadata:aicc_session:scormmode',
                'scormstatus' => 'privacy:metadata:aicc_session:scormstatus',
                'attempt' => 'privacy:metadata:attempt',
                'lessonstatus' => 'privacy:metadata:aicc_session:lessonstatus',
                'sessiontime' => 'privacy:metadata:aicc_session:sessiontime',
                'timecreated' => 'privacy:metadata:aicc_session:timecreated',
                'timemodified' => 'privacy:metadata:timemodified',
            ], 'privacy:metadata:scorm_aicc_session');

        $collection->add_external_location_link('aicc', [
                'data' => 'privacy:metadata:aicc:data'
            ], 'privacy:metadata:aicc:externalpurpose');

        return $collection;
    }

public function parseResults(LoopResult $loopResult)
    {
        foreach ($loopResult->getResultDataCollection() as $filter) {
            $loopResultRow = new LoopResultRow($filter);

            $loopResultRow->set("ID", $filter->getId())
                ->set("IS_TRANSLATED", $filter->getVirtualColumn('IS_TRANSLATED'))
                ->set("LOCALE", $filter->locale)
                ->set("TITLE", $filter->getVirtualColumn('i18n_TITLE'))
                ->set("CODE", $filter->getCode())
                ->set("DESCRIPTION", $filter->getVirtualColumn('i18n_DESCRIPTION'))
                ->set("ACTIVATE", $filter->getActive())
                ->set("TYPE", $filter->getFiltertype());

            $loopResult->addRow($loopResultRow);
        }

        return $loopResult;
    }

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