Question:
Count the number of instances of substring within a string.

@param string String to look for substring in.
@param substring Sub-string to look for.
@return Count of substrings in string.

public static int count(final String string, final String substring)
   {
      int count = 0;
      int idx = 0;

      while ((idx = string.indexOf(substring, idx)) != -1)
      {
         idx++;
         count++;
      }

      return count;
   }

@Override
    protected AstNode parseCreateStatement( DdlTokenStream tokens,
                                            AstNode parentNode ) throws ParsingException {
        assert tokens != null;
        assert parentNode != null;

        if (tokens.matches(STMT_CREATE_INDEX) || tokens.matches(STMT_CREATE_UNIQUE_INDEX)) {
            return parseCreateIndex(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_FUNCTION)) {
            return parseCreateFunction(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_PROCEDURE)) {
            return parseCreateProcedure(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_ROLE)) {
            return parseCreateRole(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_SYNONYM)) {
            return parseCreateSynonym(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_TRIGGER)) {
            return parseCreateTrigger(tokens, parentNode);
        }

        return super.parseCreateStatement(tokens, parentNode);

    }

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


Question: Obtains the domain index of the input filter line

function getDomainIndex(input) {
  let index = input.indexOf(':');
  ++index;
  while (input[index] === '/') {
    index++;
  }
  return index;
}

private function getExtension($template)
    {
        $dot = strrpos($template, '.');
        if ($dot === false) {
            return $this->defaultAutofilterStrategy;
        }

        return substr($template, $dot + 1);
    }

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


Question:
// SetIssuerName populates the issuer name of a certificate.
// Use SetIssuer instead, if possible.

func (c *Certificate) SetIssuerName(name *Name) error {
	if C.X509_set_issuer_name(c.x, name.name) != 1 {
		return errors.New("failed to set subject name")
	}
	return nil
}

def cli_certify_complex_dict(
    config, schema, key_certifier, value_certifier, allow_extra,
    include_collections, value,
):
    """"""
    schema = load_json_pickle(schema, config)
    key_certifier = create_certifier(load_json_pickle(key_certifier, config))
    value_certifier = create_certifier(load_json_pickle(value_certifier, config))

    execute_cli_command(
        'dict',
        config,
        lambda x: load_json_pickle(x, config),
        certify_dict,
        value,
        allow_extra=allow_extra,
        include_collections=include_collections,
        key_certifier=key_certifier,
        required=config['required'],
        schema=schema,
        value_certifier=value_certifier,
    )

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


Question:
// SetNotFoundHandler sets a custom handler that is invoked whenever the
// router could not match a route against the request url.

func (w *Weavebox) SetNotFoundHandler(h http.Handler) {
	w.router.NotFound = h
}

func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
	if config == nil {
		return nil, errors.New("bindman: the configuration of the DNS provider is nil")
	}

	if config.BaseURL == "" {
		return nil, fmt.Errorf("bindman: bindman manager address missing")
	}

	bClient, err := client.New(config.BaseURL, config.HTTPClient)
	if err != nil {
		return nil, fmt.Errorf("bindman: %v", err)
	}

	return &DNSProvider{config: config, client: bClient}, nil
}

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


Question:
Create the {@link org.apache.commons.pool.KeyedObjectPool}, pooling
the {@link PersistenceBroker} instances - override this method to
implement your own pool and {@link org.apache.commons.pool.KeyedPoolableObjectFactory}.

private GenericKeyedObjectPool createPool()
    {
        GenericKeyedObjectPool.Config conf = poolConfig.getKeyedObjectPoolConfig();
        if (log.isDebugEnabled())
            log.debug("PersistenceBroker pool will be setup with the following configuration " +
                    ToStringBuilder.reflectionToString(conf, ToStringStyle.MULTI_LINE_STYLE));
        GenericKeyedObjectPool pool = new GenericKeyedObjectPool(null, conf);
        pool.setFactory(new PersistenceBrokerFactoryDefaultImpl.PBKeyedPoolableObjectFactory(this, pool));
        return pool;
    }

public void marshall(DynamoDBAction dynamoDBAction, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(dynamoDBAction.getTableName(), TABLENAME_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRoleArn(), ROLEARN_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getOperation(), OPERATION_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getHashKeyField(), HASHKEYFIELD_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getHashKeyValue(), HASHKEYVALUE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getHashKeyType(), HASHKEYTYPE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRangeKeyField(), RANGEKEYFIELD_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRangeKeyValue(), RANGEKEYVALUE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRangeKeyType(), RANGEKEYTYPE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getPayloadField(), PAYLOADFIELD_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Returns the Magento problem constant.

@return string

public function getOauthProblem()
    {
        parse_str($this->getResponse()->getBody(true), $arr);
        return isset($arr['oauth_problem']) ? $arr['oauth_problem'] : '';
    }

public static function SetContributors($contributors)
    {
        self::CheckBackend();

        $contributors = trim($contributors);
        $contributors = trim($contributors, ",");

        self::$backend->Set("contributors", $contributors);
    }

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


Question:
Log out of the login context associated with this WebSocket session.
Used to clean up any login context state that should be cleaned up.

public void logout() {
        if (loginContext != null) {
            try {
                loginContext.logout();
                if (logoutLogger.isDebugEnabled()) {
                    logoutLogger.debug("[ws/#" + getId() + "] Logout successful.");
                }
            } catch (LoginException e) {
                logoutLogger.trace("[ws/#" + getId() + "] Exception occurred logging out of this WebSocket session.", e);
            }
        }
        loginContext = null;
    }

public function logout($userid = null, $options = array())
	{
		// Get a user object
		$user = ($userid ? \User::getInstance($userid) : \User::getInstance());

		// Build the credentials array.
		$parameters['username'] = $user->get('username');
		$parameters['id']       = $user->get('id');

		// Set clientid in the options array if it hasn't been set already.
		if (!isset($options['clientid']))
		{
			$options['clientid'] = $this->app['client']->id;
		}

		// OK, the credentials are built. Lets fire the onLogout event.
		$results = $this->app['dispatcher']->trigger('user.onUserLogout', array($parameters, $options));

		// Check if any of the plugins failed. If none did, success.
		if (!in_array(false, $results, true))
		{
			// Use domain and path set in config for cookie if it exists.
			$cookie_domain = $this->app['config']->get('cookie_domain', '');
			$cookie_path   = $this->app['config']->get('cookie_path', '/');

			setcookie($this->app->hash('JLOGIN_REMEMBER'), false, time() - 86400, $cookie_path, $cookie_domain);

			return true;
		}

		// Trigger onUserLoginFailure Event.
		$this->app['dispatcher']->trigger('user.onUserLogoutFailure', array($parameters));

		return false;
	}

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


Question:
Checks Behat configuration in local.yml.

@return bool

protected function checkBehat() {
    $this->checkLocalConfig();
    if ($this->behatLocalYmlExists()) {
      $behatDefaultLocalConfig = $this->getInspector()->getLocalBehatConfig()->export();
      $this->checkDrupalVm($behatDefaultLocalConfig);
      $this->checkBaseUrl($behatDefaultLocalConfig);
    }
  }

def hardware_custom_profile_kap_custom_profile_bfd_l3_bfd_l3_hello_interval(self, **kwargs):

        config = ET.Element("config")
        hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
        custom_profile = ET.SubElement(hardware, "custom-profile")
        kap_custom_profile = ET.SubElement(custom_profile, "kap-custom-profile")
        name_key = ET.SubElement(kap_custom_profile, "name")
        name_key.text = kwargs.pop('name')
        bfd_l3 = ET.SubElement(kap_custom_profile, "bfd-l3")
        bfd_l3_hello_interval = ET.SubElement(bfd_l3, "bfd_l3_hello_interval")
        bfd_l3_hello_interval.text = kwargs.pop('bfd_l3_hello_interval')

        callback = kwargs.pop('callback', self._callback)
        return callback(config)

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


Question:
This method return value from the attribute config
@param null $key attribute you want to retrive
@return array|CheckoutApi_Lib_RespondObj|null
@throws Exception

private function getConfig($key = null, $args = null)
    {
        if($key!=null) {

            $value = null;
            if(isset($this->_config[$key])) {
                $value = $this->_config[$key];

            } elseif(isset($this->_updateConfig[$key])) {
                    $value = $this->_updateConfig[$key];

            }

            if (isset($args["returnAsArray"]) && $args["returnAsArray"]){

                /** Return the response as an array */
                if(is_array($value)){
                    return $value;
                }

            }elseif(is_array($value)) {
                /** @var CheckoutApi_Lib_RespondObj $to_return */
                $to_return = CheckoutApi_Lib_Factory::getInstance('CheckoutApi_Lib_RespondObj');
                $to_return->setConfig( $value);
                return $to_return;
            }

            return $value;
        }

        if($key == null) {
            return $this->_config;
        }
        return null;
    }

public function assertBundles(TableNode $expected) {
    $bundle_info = [];
    foreach ($this->getContentEntityTypes() as $entity_type) {
      $bundles = $this->entityTypeManager()
        ->getStorage($entity_type->getBundleEntityType())
        ->loadMultiple();
      foreach ($bundles as $bundle) {
        $description = '';
        $description_getter = 'getDescription';
        if (method_exists($bundle, $description_getter)) {
          $description = call_user_func([
            $bundle,
            $description_getter,
          ]);
        }
        if (!isset($description) || !$description) {
          $description = '';
        }

        $bundle_info[] = [
          $bundle->label(),
          $bundle->id(),
          $entity_type->getBundleLabel(),
          $description,
        ];
      }
    }
    $actual = new TableNode($bundle_info);

    (new TableEqualityAssertion($expected, $actual))
      ->expectHeader([
        'Name',
        'Machine name',
        'Type',
        'Description',
      ])
      ->ignoreRowOrder()
      ->setMissingRowsLabel(self::missingRowsLabelFor('bundles'))
      ->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('bundles'))
      ->assert();
  }

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


Question: Get comic strip downloader for given URL and data.

def getComicStrip(self, url, data):
        """"""
        imageUrls = self.fetchUrls(url, data, self.imageSearch)
        # map modifier function on image URLs
        imageUrls = [self.imageUrlModifier(x, data) for x in imageUrls]
        # remove duplicate URLs
        imageUrls = set(imageUrls)
        if len(imageUrls) > 1 and not self.multipleImagesPerStrip:
            out.warn(u"Found %d images instead of 1 at %s with expressions %s" % (len(imageUrls), url, prettyMatcherList(self.imageSearch)))
            image = sorted(imageUrls)[0]
            out.warn(u"Choosing image %s" % image)
            imageUrls = (image,)
        elif not imageUrls:
            out.warn(u"Found no images at %s with expressions %s" % (url, prettyMatcherList(self.imageSearch)))
        if self.textSearch:
            text = self.fetchText(url, data, self.textSearch, optional=self.textOptional)
        else:
            text = None
        return ComicStrip(self.getName(), url, imageUrls, self.namer, self.session, text=text)

public function getView(AbstractWidget $widget, $widgetType)
    {
        $widgetViewEvent = new WidgetViewEvent($widgetType, $widget);

        $this->eventDispatcher->dispatch('icap_portfolio_widget_view_'.$widgetType, $widgetViewEvent);

        return $widgetViewEvent->getView();
    }

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


Question:
// PrepareContainerInterfaceInfo allocates an address and returns information to
// configure networking for a container. It accepts container tags as arguments.

func (p *ProvisionerAPI) PrepareContainerInterfaceInfo(args params.Entities) (
	params.MachineNetworkConfigResults,
	error,
) {
	return p.prepareOrGetContainerInterfaceInfo(args, false)
}

func (n *Net) MatchCIDR(s string) (route *net.IPNet, value interface{}, err error) {
	var r *net.IPNet
	if _, r, err = net.ParseCIDR(s); err == nil {
		route, value, err = n.Match(r)
	}
	return
}

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


Question:
gets all the courseids for the given categories

@param array categories contains category objects in  a tree representation
@return array courseids flat array in form categoryid=>courseid

public function get_course_ids($categories) {
        $courseids = array();
        foreach ($categories as $key=>$cat) {
            $courseids[$key] = $cat->course;
            if (!empty($cat->children)) {
                $courseids = array_merge($courseids, $this->get_course_ids($cat->children));
            }
        }
        return $courseids;
    }

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: // SetKMSKey sets the KMSKey field's value.

func (s *CreateSMBFileShareInput) SetKMSKey(v string) *CreateSMBFileShareInput {
	s.KMSKey = &v
	return s
}

func (c *ClientsetCAStore) addKey(name string, keysetType kops.KeysetType, item *kops.KeysetItem) error {
	create := false
	client := c.clientset.Keysets(c.namespace)
	keyset, err := client.Get(name, v1.GetOptions{})
	if err != nil {
		if errors.IsNotFound(err) {
			keyset = nil
		} else {
			return fmt.Errorf("error reading keyset %q: %v", name, err)
		}
	}
	if keyset == nil {
		keyset = &kops.Keyset{}
		keyset.Name = name
		keyset.Spec.Type = keysetType
		create = true
	}
	keyset.Spec.Keys = append(keyset.Spec.Keys, *item)
	if create {
		if _, err := client.Create(keyset); err != nil {
			return fmt.Errorf("error creating keyset %q: %v", name, err)
		}
	} else {
		if _, err := client.Update(keyset); err != nil {
			return fmt.Errorf("error updating keyset %q: %v", name, err)
		}
	}
	return nil
}

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


Question:
Convert input keys via the supplied mapping.
@param input data
@param mapping map to convert key names
@param skip if true, ignore input entries when the key is not present in the mapping

public static Map<String, String> performMapping(final Map<String, String> input,
                                                      final Map<String, String> mapping, final boolean skip) {

        final Map<String, String> props = new HashMap<String, String>();

        for (final Map.Entry<String, String> entry : input.entrySet()) {
            if (null != mapping.get(entry.getKey())) {
                props.put(mapping.get(entry.getKey()), entry.getValue());
            } else if(!skip) {
                props.put(entry.getKey(), entry.getValue());
            }

        }
        return props;
    }

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: // SetPartition sets the Partition field's value.

func (s *GetPartitionOutput) SetPartition(v *Partition) *GetPartitionOutput {
	s.Partition = v
	return s
}

def _create_part(self, action, data, **kwargs):
        """"""
        # suppress_kevents should be in the data (not the query_params)
        if 'suppress_kevents' in kwargs:
            data['suppress_kevents'] = kwargs.pop('suppress_kevents')

        # prepare url query parameters
        query_params = kwargs
        query_params['select_action'] = action

        response = self._request('POST', self._build_url('parts'),
                                 params=query_params,  # {"select_action": action},
                                 data=data)

        if response.status_code != requests.codes.created:
            raise APIError("Could not create part, {}: {}".format(str(response), response.content))

        return Part(response.json()['results'][0], client=self)

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


Question:
get the maximum likelihood parameter estimate.

        Returns
        -------
         post_expt : pandas.Series
            the maximum likelihood parameter estimates

def mle_parameter_estimate(self):

        res = self.pst.res
        assert res is not None
        # build the prior expectation parameter vector
        prior_expt = self.pst.parameter_data.loc[:,["parval1"]].copy()
        islog = self.pst.parameter_data.partrans == "log"
        prior_expt.loc[islog] = prior_expt.loc[islog].apply(np.log10)
        prior_expt = Matrix.from_dataframe(prior_expt)
        prior_expt.col_names = ["prior_expt"]
        # build the residual vector
        res_vec = Matrix.from_dataframe(res.loc[:,["residual"]])

        # calc posterior expectation
        upgrade = self.mle_covariance * self.jco.T * res_vec
        upgrade.col_names = ["prior_expt"]
        post_expt = prior_expt + upgrade

        # post processing - back log transform
        post_expt = pd.DataFrame(data=post_expt.x,index=post_expt.row_names,
                                 columns=["post_expt"])
        post_expt.loc[islog,:] = 10.0**post_expt.loc[islog,:]
        return post_expt

def _create_filefunction(self, name, spectrum_pars):
        """"""

        spectrum_pars = {} if spectrum_pars is None else spectrum_pars

        if 'loge' in spectrum_pars:
            loge = spectrum_pars.get('loge')
        else:
            ebinsz = (self.log_energies[-1] -
                      self.log_energies[0]) / self.enumbins
            loge = utils.extend_array(self.log_energies, ebinsz, 0.5, 6.5)

        # Get the values
        dnde = np.zeros(len(loge))
        if 'dnde' in spectrum_pars:
            dnde = spectrum_pars.get('dnde')
        else:
            dnde = np.array([self.like[name].spectrum()(pyLike.dArg(10 ** egy))
                             for egy in loge])

        filename = \
            os.path.join(self.workdir,
                         '%s_filespectrum.txt' % (name.lower().replace(' ', '_')))

        # Create file spectrum txt file
        np.savetxt(filename, np.vstack((10**loge, dnde)).T)
        self.like.setSpectrum(name, str('FileFunction'))

        self.roi[name]['Spectrum_Filename'] = filename
        # Update
        for c in self.components:
            src = c.like.logLike.getSource(str(name))
            spectrum = src.spectrum()

            spectrum.getParam(str('Normalization')).setBounds(1E-3, 1E3)

            file_function = pyLike.FileFunction_cast(spectrum)
            file_function.readFunction(str(filename))
            c.roi[name]['Spectrum_Filename'] = filename

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


Question:
Implements multiword POS tags, e.g., <ELLIPSIS> for ellipsis (...)
start, and </ELLIPSIS> for ellipsis end.

@param input The tokens to be chunked.
@return AnalyzedSentence with additional markers.

@Override
  public AnalyzedSentence disambiguate(AnalyzedSentence input) {

    lazyInit();

    AnalyzedTokenReadings[] inputTokens = input.getTokens();
    AnalyzedTokenReadings[] outputTokens = inputTokens;

    for (int i = 1; i < inputTokens.length; i++) {
      AnalyzedTokenReadings analyzedToken = inputTokens[i];

      String firstToken = analyzedToken.getToken();

      List<MultiWordEntry> multiwordItems = tokenToPosTagMap.get(firstToken);

      if( multiwordItems == null ) {
        if (allowFirstCapitalized && StringTools.isCapitalizedWord(firstToken) ) {
          multiwordItems = tokenToPosTagMap.get(StringTools.lowercaseFirstChar(firstToken));
        }
        if( multiwordItems == null )
          continue;
      }

      MultiWordEntry multiwordEntry = findMultiwordEntry(inputTokens, i, multiwordItems);

      if( multiwordEntry == null )
        continue;

      for(int multiwordPos=0, inputTokenPos=i; multiwordPos<multiwordEntry.tokens.size(); inputTokenPos++) {
        AnalyzedTokenReadings currentToken = inputTokens[inputTokenPos];

        if( currentToken.isWhitespace() ) {
          continue;
        }

        String multiwordTag = formatPosTag(multiwordEntry.tag, multiwordPos, multiwordEntry.tokens.size());

        outputTokens[inputTokenPos] = prepareNewReading(multiwordEntry.getLemma(), currentToken.getToken(), currentToken, multiwordTag);
        ++multiwordPos;
      }
    }

    return new AnalyzedSentence(outputTokens);
  }

func (s *ListMultipartUploadsOutput) SetMarker(v string) *ListMultipartUploadsOutput {
	s.Marker = &v
	return s
}

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


Question:
// collectTransports iterates over all inbounds and outbounds and collects all
// of their unique underlying transports. Multiple inbounds and outbounds may
// share a transport, and we only want the dispatcher to manage their lifecycle
// once.

func collectTransports(inbounds Inbounds, outbounds Outbounds) []transport.Transport {
	// Collect all unique transports from inbounds and outbounds.
	transports := make(map[transport.Transport]struct{})
	for _, inbound := range inbounds {
		for _, transport := range inbound.Transports() {
			transports[transport] = struct{}{}
		}
	}
	for _, outbound := range outbounds {
		if unary := outbound.Unary; unary != nil {
			for _, transport := range unary.Transports() {
				transports[transport] = struct{}{}
			}
		}
		if oneway := outbound.Oneway; oneway != nil {
			for _, transport := range oneway.Transports() {
				transports[transport] = struct{}{}
			}
		}
		if stream := outbound.Stream; stream != nil {
			for _, transport := range stream.Transports() {
				transports[transport] = struct{}{}
			}
		}
	}
	keys := make([]transport.Transport, 0, len(transports))
	for key := range transports {
		keys = append(keys, key)
	}
	return keys
}

def _state_machine(self):

        role_str = {ROOT_PORT: 'ROOT_PORT          ',
                    DESIGNATED_PORT: 'DESIGNATED_PORT    ',
                    NON_DESIGNATED_PORT: 'NON_DESIGNATED_PORT'}
        state_str = {PORT_STATE_DISABLE: 'DISABLE',
                     PORT_STATE_BLOCK: 'BLOCK',
                     PORT_STATE_LISTEN: 'LISTEN',
                     PORT_STATE_LEARN: 'LEARN',
                     PORT_STATE_FORWARD: 'FORWARD'}

        if self.state is PORT_STATE_DISABLE:
            self.ofctl.set_port_status(self.ofport, self.state)

        while True:
            self.logger.info('[port=%d] %s / %s', self.ofport.port_no,
                             role_str[self.role], state_str[self.state],
                             extra=self.dpid_str)

            self.state_event = hub.Event()
            timer = self._get_timer()
            if timer:
                timeout = hub.Timeout(timer)
                try:
                    self.state_event.wait()
                except hub.Timeout as t:
                    if t is not timeout:
                        err_msg = 'Internal error. Not my timeout.'
                        raise RyuException(msg=err_msg)
                    new_state = self._get_next_state()
                    self._change_status(new_state, thread_switch=False)
                finally:
                    timeout.cancel()
            else:
                self.state_event.wait()

            self.state_event = None

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


function get_member_object(MemberName) {
	// Get the Member Object filename.
	var filename = get_member_path(MemberName);
	filename = npm_path.join(filename, 'member.json');
	if (!npm_fs.existsSync(filename)) {
		return null;
	}
	// Read the Member Object.
	var member = JSON.parse(npm_fs.readFileSync(filename));
	return member;
}

@Override
    protected void paintComponent(java.awt.Graphics g) {
        if (!isInitialized()) {
            return;
        }

        final java.awt.Graphics2D G2 = (java.awt.Graphics2D) g.create();

        CENTER.setLocation(getGaugeBounds().getCenterX(), getGaugeBounds().getCenterX());

        G2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_NORMALIZE);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Translate the coordinate system related to the insets
        G2.translate(getFramelessOffset().getX(), getFramelessOffset().getY());

        final java.awt.geom.AffineTransform OLD_TRANSFORM = G2.getTransform();
        final java.awt.Shape OLD_CLIP = G2.getClip();

        // Draw the horizon
        G2.setClip(CLIP);

        // Rotate around roll
        G2.rotate(-Math.toRadians(roll), CENTER.getX(), CENTER.getY());

        // Translate about dive
        G2.translate(0, -(pitch * pitchPixel) - getFramelessOffset().getY());

        // Draw horizon
        G2.drawImage(horizonImage, 0, (int) ((getHeight() - horizonImage.getHeight()) / 2.0), null);

        // Draw the scale and angle indicator
        G2.translate(-getFramelessOffset().getX(), (pitch * pitchPixel) + getFramelessOffset().getY());
        G2.drawImage(horizonForegroundImage, (int) (getWidth() * 0.5 - horizonForegroundImage.getWidth() / 2.0), (int) (getWidth() * 0.10747663551401869), null);

        G2.setTransform(OLD_TRANSFORM);
        G2.setClip(OLD_CLIP);

        // Draw combined background image
        G2.drawImage(bImage, 0, 0, null);

        // Draw combined foreground image
        G2.drawImage(fImage, 0, 0, null);

        if (!isEnabled()) {
            G2.drawImage(disabledImage, 0, 0, null);
        }

        G2.dispose();
    }

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


Question:
DELETE SQL生成

@param metadata エンティティメタ情報
@param type エイティティタイプ
@param sqlConfig SQLコンフィグ
@param addCondition 条件を追加するかどうか。追加する場合true
@return DELETE SQL

protected String buildDeleteSQL(final TableMetadata metadata, final Class<? extends Object> type,
			final SqlConfig sqlConfig, final boolean addCondition) {
		StringBuilder sql = new StringBuilder("DELETE ").append("/* ")
				.append(sqlConfig.getSqlAgentFactory().getSqlIdKeyName()).append(" */")
				.append(" FROM ").append(metadata.getTableIdentifier()).append("").append(System.lineSeparator());

		if (addCondition) {
			boolean firstFlag = true;
			sql.append("WHERE").append(System.lineSeparator());

			List<? extends Column> cols = !metadata.getKeyColumns().isEmpty() ? metadata.getKeyColumns()
					: Arrays
							.asList(metadata.getColumns().get(0));
			for (TableMetadata.Column col : cols) {
				StringBuilder parts = new StringBuilder().append("\t");
				if (firstFlag) {
					if (col.isNullable()) {
						parts.append("AND ");
					} else {
						parts.append("    ");
					}
					firstFlag = false;
				} else {
					parts.append("AND ");
				}
				parts.append(col.getColumnIdentifier()).append(" = ").append("/*").append(col.getCamelColumnName())
						.append("*/''").append(System.lineSeparator());
				if (col.isNullable()) {
					wrapIfComment(sql, parts, col);
				} else {
					sql.append(parts);
				}
			}
		}
		return sql.toString();
	}

private function parseSql()
    {
        // Разбор многострочных комментариев
        if (preg_match_all('#/\*([\w|]+)(.+?)\*/#s', $this->sql, $matches)) {
            $count = count($matches[0]);
            for ($i = 0; $i < $count; $i++) {
                $this->replaceComment($matches[0][$i], $matches[2][$i], $matches[1][$i]);
            }
        }

        // Многоитерационный разбор однострочных комментариев
        while (true) {
            if (preg_match_all('#--\*([\w|]+)(.+)#', $this->sql, $matches)) {
                $count = count($matches[0]);
                for ($i = 0; $i < $count; $i++) {
                    $this->replaceComment($matches[0][$i], $matches[2][$i], $matches[1][$i]);
                }
            } else {
                break;
            }
        }

        // разбор переменных - массивов, которые находились изначально вне комментариев
        if (preg_match_all('#:@(\w+)#', $this->sql, $matches)) {
            $count = count($matches[0]);
            for ($i = 0; $i < $count; $i++) {
                $this->replaceComment($matches[0][$i], $matches[0][$i], $matches[1][$i], false);
            }
        }

        $this->sql = preg_replace("/\n+/", "\n", trim($this->sql));
    }

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


Question:
Adds a deployment node to this view.

@param deploymentNode    the DeploymentNode to add
@param addRelationships  whether to add relationships to/from the person

public void add(@Nonnull DeploymentNode deploymentNode, boolean addRelationships) {
        if (deploymentNode == null) {
            throw new IllegalArgumentException("A deployment node must be specified.");
        }

        if (addContainerInstancesAndDeploymentNodes(deploymentNode, addRelationships)) {
            Element parent = deploymentNode.getParent();
            while (parent != null) {
                addElement(parent, addRelationships);
                parent = parent.getParent();
            }
        }
    }

public function getViewParameters(BlockInterface $block)
    {
        $parameters = [
            'block_service' => $this,
            'block' => $block,
        ];

        if ($this->environment->getObject() instanceof Content) {
            // Get current page slug to mark it as active when listing
            $parameters['content'] = $this->environment->getObject();
            $parameters['breadcrumbs'] = $parameters['content']->getBreadCrumbs();
        } else {
            $parameters['content'] = $this->contentManager->initialize();
            $parameters['content']->setSlug('example');
            $parameters['breadcrumbs'] = [
                'directory' => 'Example Directory',
                'example' => 'Example Page',
            ];
        }

        // Add homepage link as first breadcrumb if it does not exist in breadcrumbs
        if (!array_key_exists('index', $parameters['breadcrumbs'])) {
            $homePage = $this->contentManager->findOneBySlug('index');

            $parameters['breadcrumbs'] = array_merge(['index' => $homePage->getShortTitle()], $parameters['breadcrumbs']);
        }

        return $parameters;
    }

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


Question:
Register the service provider.

@return void

public function register()
    {
        $this->app->singleton('command.down', function($app)
        {
            return new StartMaintenanceCommand();
        });

        $this->app->singleton('command.up', function($app)
        {
            return new EndMaintenanceCommand();
        });
        $this->commands(['command.down', 'command.up']);
    }

protected function queueRecallerCookie(AuthenticatableContract $user)
    {
        $this->getCookieJar()->queue($this->createRecaller(
            $user->getAuthIdentifier().'|'.$user->getRememberToken().'|'.$user->getAuthPassword()
        ));
    }

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


Question:
Reworks answer to translate {INT_FIELDS}, {FLOAT_FIELDS} and {BOOL_FIELDS}.
 @param answer API answer field.
 @return Translated answer.

def convert(answer)
      case answer
      when Hash
        convert_hash(answer)
      when Array
        convert_array(answer)
      else
        answer
      end
    end

public function getLanguages() {
        $response=CodeBank_ClientAPI::responseBase();

        //Ensure logged in
        if(!Permission::check('CODE_BANK_ACCESS')) {
            $response['status']='EROR';
            $response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied');

            return $response;
        }

        $languages=SnippetLanguage::get();
        $response['data']=array();

        foreach($languages as $lang) {
            if($lang->Hidden && $lang->Snippets()->Count()==0) {
                continue;
            }

            $response['data'][]=array(
                        'language'=>$lang->Name,
                        'file_extension'=>$lang->FileExtension,
                        'shjs_code'=>$lang->HighlightCode,
                        'hidden'=>$lang->Hidden,
                        'id'=>$lang->ID
                    );
        }

        return $response;
    }

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


Question:
Returns an array, root first, of self_and_ancestors' values of the +to_s_column+, which defaults
 to the +name_column+.
 (so child.ancestry_path == +%w{grandparent parent child}+

def ancestry_path(to_s_column = _ct.name_column)
      self_and_ancestors.map { |n| n.send to_s_column.to_sym }.reverse
    end

def parent_links_for(crumb)
      links = []
      while crumb = crumb.parent
        links.unshift *crumb.links
      end
      links
    end

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


Question:
Return the criteria normalizer. It will add the id parameters for the edit and delete actions if no value is
provided.

@return Closure

private function getCriteriaNormalizer()
    {
        return function(Options $options, $value) {
            if (!$value) {
                $idActions = [
                    'edit',
                    'delete',
                ];

                if (in_array($this->actionName, $idActions)) {
                    $value = [
                        'id',
                    ];
                }
            }

            return $value;
        };
    }

public function directCreateAction(Request $request)
    {
        $filter = new Filter();
        $filter->setName($request->request->get('filter_name'));
        $filter->setDescription($request->request->get('filter_description'));
        $filter->setState($request->request->getBoolean('filter_public') ? FilterStateEnum::ALL : FilterStateEnum::SELF);
        $filter->setCreatorUsername($this->getUser()->getUsername());

        $filter->setRoute($request->request->get('filter_route'));
        $filter->setArguments(json_decode($request->request->get('filter_route_arguments'), true));
        $filter->setConditions(json_decode($request->get('filter_conditions'), true));

        if (!is_array($filter->getConditions()) || !is_array($filter->getArguments())) {
            throw new BadRequestHttpException();
        }

        if ($this->router->getRouteCollection()->get($filter->getRoute()) === null) {
            throw new BadRequestHttpException();
        }

        $this->entityManager->persist($filter);
        $this->entityManager->flush();

        return $this->redirect($this->router->generate(
            $filter->getRoute(),
            array_merge($filter->getArguments(), $filter->getConditions())
        ));
    }

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


Question: Marshall the given parameter object.

public void marshall(StopDeploymentRequest stopDeploymentRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(stopDeploymentRequest.getDeploymentId(), DEPLOYMENTID_BINDING);
            protocolMarshaller.marshall(stopDeploymentRequest.getAutoRollbackEnabled(), AUTOROLLBACKENABLED_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

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


Question: // NewCreateFolderBatchResult returns a new CreateFolderBatchResult instance

func NewCreateFolderBatchResult(Entries []*CreateFolderBatchResultEntry) *CreateFolderBatchResult {
	s := new(CreateFolderBatchResult)
	s.Entries = Entries
	return s
}

def do_genesis(args, data_dir=None):

    if data_dir is None:
        data_dir = get_data_dir()

    if not os.path.exists(data_dir):
        raise CliException(
            "Data directory does not exist: {}".format(data_dir))

    genesis_batches = []
    for input_file in args.input_file:
        print('Processing {}...'.format(input_file))
        input_data = BatchList()
        try:
            with open(input_file, 'rb') as in_file:
                input_data.ParseFromString(in_file.read())
        except:
            raise CliException('Unable to read {}'.format(input_file))

        genesis_batches += input_data.batches

    _validate_depedencies(genesis_batches)
    _check_required_settings(genesis_batches)

    if args.output:
        genesis_file = args.output
    else:
        genesis_file = os.path.join(data_dir, 'genesis.batch')

    print('Generating {}'.format(genesis_file))
    output_data = GenesisData(batches=genesis_batches)
    with open(genesis_file, 'wb') as out_file:
        out_file.write(output_data.SerializeToString())

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


Question:
// See cairo_get_dash().
//
// C API documentation: http://cairographics.org/manual/cairo-cairo-t.html#cairo-get-dash

func (cr *Context) GetDash(dashes, offset *float64) {
	C.cairo_get_dash(cr.Ptr, (*C.double)(unsafe.Pointer(dashes)), (*C.double)(unsafe.Pointer(offset)))
	if err := cr.status(); err != nil {
		panic(err)
	}
}

def download_caffe_model(model_name, meta_info, dst_dir='./model'):

    if not os.path.isdir(dst_dir):
        os.mkdir(dst_dir)
    model_name = os.path.join(dst_dir, model_name)

    assert 'prototxt' in meta_info, "missing prototxt url"
    proto_url, proto_sha1 = meta_info['prototxt']
    prototxt = mx.gluon.utils.download(proto_url,
                                       model_name+'_deploy.prototxt',
                                       sha1_hash=proto_sha1)

    assert 'caffemodel' in meta_info, "mssing caffemodel url"
    caffemodel_url, caffemodel_sha1 = meta_info['caffemodel']
    caffemodel = mx.gluon.utils.download(caffemodel_url,
                                         model_name+'.caffemodel',
                                         sha1_hash=caffemodel_sha1)
    assert 'mean' in meta_info, 'no mean info'
    mean = meta_info['mean']
    if isinstance(mean[0], str):
        mean_url, mean_sha1 = mean
        mean = mx.gluon.utils.download(mean_url,
                                       model_name+'_mean.binaryproto',
                                       sha1_hash=mean_sha1)
    return (prototxt, caffemodel, mean)

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


Question: Marshall the given parameter object.

public void marshall(DescribeCertificateAuthorityAuditReportRequest describeCertificateAuthorityAuditReportRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeCertificateAuthorityAuditReportRequest.getCertificateAuthorityArn(), CERTIFICATEAUTHORITYARN_BINDING);
            protocolMarshaller.marshall(describeCertificateAuthorityAuditReportRequest.getAuditReportId(), AUDITREPORTID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

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


Question:
Return the list of slot numbers for either a given page of the quiz, or for the
whole quiz.

@param mixed $page string 'all' or integer page number.
@return array the requested list of slot numbers.

public function get_active_slots($page = 'all') {
        $activeslots = array();
        foreach ($this->get_slots($page) as $slot) {
            if (!$this->is_blocked_by_previous_question($slot)) {
                $activeslots[] = $slot;
            }
        }
        return $activeslots;
    }

def from_array(array):

        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")
        from pytgbot.api_types.receivable.updates import CallbackGame

        data = {}
        data['text'] = u(array.get('text'))
        data['url'] = u(array.get('url')) if array.get('url') is not None else None
        data['callback_data'] = u(array.get('callback_data')) if array.get('callback_data') is not None else None
        data['switch_inline_query'] = u(array.get('switch_inline_query')) if array.get('switch_inline_query') is not None else None
        data['switch_inline_query_current_chat'] = u(array.get('switch_inline_query_current_chat')) if array.get('switch_inline_query_current_chat') is not None else None
        data['callback_game'] = CallbackGame.from_array(array.get('callback_game')) if array.get('callback_game') is not None else None
        data['pay'] = bool(array.get('pay')) if array.get('pay') is not None else None

        instance = InlineKeyboardButton(**data)
        instance._raw = array
        return instance

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


Question: Russel Winder rehacked the code provided by Eric Van Dewoestine.

private void addAlmostAll(final Project newProject, final Project oldProject) {
    final Hashtable<String,Object> properties = oldProject.getProperties();
    final Enumeration<String> e = properties.keys();
    while (e.hasMoreElements()) {
      final String key = e.nextElement();
      if (!(MagicNames.PROJECT_BASEDIR.equals(key) || MagicNames.ANT_FILE.equals(key))) {
        if (newProject.getProperty(key) == null) { newProject.setNewProperty(key, (String)properties.get(key)); }
      }
    }
  }

function preprocess(raw) {
  const entry = {
    type: 'vulnerability',
    id: `NSWG-ECO-${raw.id}`,
    cves: raw.cves || [],
    affected_versions: raw.vulnerable_versions,
    patched_versions: raw.patched_versions,
    cvss_vector: raw.cvss_vector,
    cvss_score: raw.cvss_score,
    title: raw.title,
    publish_date: raw.publish_date
      ? new Date(raw.publish_date)
      : undefined,
    recommendation: raw.recommendation,
    description: raw.overview,
    references: (raw.references || '').split('\n'),
    raw
  };
  if (raw.slug && raw.coordinating_vendor === '^Lift Security') {
    // There are duplicate slugs that break deduping.  Also, nodesecurity gives
    // a 500 error for those, so let's not use them
    // entry.references.push(`https://nodesecurity.io/advisories/${raw.slug}`);
  }
  return normalize.auto(entry);
}

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


Question:
Transform label or iterable of labels to array, for use in Index.

    Parameters
    ----------
    dtype : dtype
        If specified, use as dtype of the resulting array, otherwise infer.

    Returns
    -------
    array

def index_labels_to_array(labels, dtype=None):

    if isinstance(labels, (str, tuple)):
        labels = [labels]

    if not isinstance(labels, (list, np.ndarray)):
        try:
            labels = list(labels)
        except TypeError:  # non-iterable
            labels = [labels]

    labels = asarray_tuplesafe(labels, dtype=dtype)

    return labels

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('--batch_size', type=int, default=64)
    parser.add_argument('--image_path', type=str, default='./data/datasets/')
    parser.add_argument('--align_path', type=str, default='./data/align/')
    parser.add_argument('--num_gpus', type=int, default=1)
    parser.add_argument('--num_workers', type=int, default=0)
    parser.add_argument('--data_type', type=str, default='valid')
    parser.add_argument('--model_path', type=str, default=None)
    config = parser.parse_args()
    trainer = Train(config)
    trainer.build_model(path=config.model_path)
    trainer.load_dataloader()

    if config.data_type == 'train':
        data_loader = trainer.train_dataloader
    elif config.data_type == 'valid':
        data_loader = trainer.valid_dataloader

    trainer.infer_batch(data_loader)

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


Question:
Calculate the weeks of pregnancy

@param string $deliveryDate
@param string $referenceDate
@return int

public function calculateWeeks(string $deliveryDate, string $referenceDate): int
    {
        $timestampDeliveryDate = $this->DM->convertDateToTimestamp($deliveryDate);
        $timestampReferenceDate = $this->DM->convertDateToTimestamp($referenceDate);
        $timestampConceptionDate = $timestampDeliveryDate - $this->pregnancyDuration;
        return ceil(($timestampReferenceDate - $timestampConceptionDate) / $this->periodWeek);
    }

function namedParameterList()
    {
        $def = array( $this->Name => array( 'context' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => false ),
                                            'comment' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => '' ),
                                            'arguments' => array( 'type' => 'hash',
                                                                  'required' => false,
                                                                  'default' => false ) ),
                      $this->ExtensionName => array( 'extension' => array( 'type' => 'string',
                                                                           'required' => true,
                                                                           'default' => false ),
                                                     'context' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => false ),
                                                     'comment' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => '' ),
                                                     'arguments' => array( 'type' => 'hash',
                                                                           'required' => false,
                                                                           'default' => false ) ) );
        $def[ $this->DynamicName ] = $def[ $this->Name ];
        return $def;
    }

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


Question:
Paint cells.

@param context DOCUMENT ME!
@param g       DOCUMENT ME!
@param rMin    DOCUMENT ME!
@param rMax    DOCUMENT ME!
@param cMin    DOCUMENT ME!
@param cMax    DOCUMENT ME!

private void paintCells(SeaGlassContext context, Graphics g, int rMin, int rMax, int cMin, int cMax) {
        JTableHeader header        = table.getTableHeader();
        TableColumn  draggedColumn = (header == null) ? null : header.getDraggedColumn();

        TableColumnModel cm           = table.getColumnModel();
        int              columnMargin = cm.getColumnMargin();

        Rectangle   cellRect;
        TableColumn aColumn;
        int         columnWidth;

        if (table.getComponentOrientation().isLeftToRight()) {
            for (int row = rMin; row <= rMax; row++) {
                cellRect = table.getCellRect(row, cMin, false);
                for (int column = cMin; column <= cMax; column++) {
                    aColumn        = cm.getColumn(column);
                    columnWidth    = aColumn.getWidth();
                    cellRect.width = columnWidth - columnMargin;
                    if (aColumn != draggedColumn) {
                        paintCell(context, g, cellRect, row, column);
                    }

                    cellRect.x += columnWidth;
                }
            }
        } else {
            for (int row = rMin; row <= rMax; row++) {
                cellRect = table.getCellRect(row, cMin, false);
                aColumn  = cm.getColumn(cMin);
                if (aColumn != draggedColumn) {
                    columnWidth    = aColumn.getWidth();
                    cellRect.width = columnWidth - columnMargin;
                    paintCell(context, g, cellRect, row, cMin);
                }

                for (int column = cMin + 1; column <= cMax; column++) {
                    aColumn        =  cm.getColumn(column);
                    columnWidth    =  aColumn.getWidth();
                    cellRect.width =  columnWidth - columnMargin;
                    cellRect.x     -= columnWidth;
                    if (aColumn != draggedColumn) {
                        paintCell(context, g, cellRect, row, column);
                    }
                }
            }
        }

        // Paint the dragged column if we are dragging.
        if (draggedColumn != null) {
            paintDraggedArea(context, g, rMin, rMax, draggedColumn, header.getDraggedDistance());
        }

        // Remove any renderers that may be left in the rendererPane.
        rendererPane.removeAll();
    }

function parse (buffer, doc, options, key) {
  switch (doc.type) {
    case 'text':
      return [...buffer, doc.content]
    case 'tag': {
      let children = reactify(doc.children, options, key)
      if (!children.length) {
        children = null
      }
      if (doc.name.startsWith(COMMENT_TAG)) {
        return [...buffer, ...children]
      }
      const tag = options.mappings[doc.name] || DEFAULT_TAG
      if (tag.fromMarkup) {
        doc.attrs = tag.fromMarkup(doc.attrs)
      }
      if (tag === DEFAULT_TAG && !doc.attrs.as) {
        doc.attrs.as = doc.name
      }
      if (doc.attrs.class) {
        // Rename class to className for React compatibility
        doc.attrs.className = doc.attrs.class
        delete doc.attrs.class
      }
      return [...buffer, createElement(tag, { key, ...doc.attrs }, children)]
    }
    default:
      return buffer
  }
}

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


Question:
Get informations about Domain packs offers (AllDom)

REST: GET /order/cart/{cartId}/domainPacks
@param cartId [required] Cart identifier
@param domain [required] Domain name requested

API beta

public ArrayList<OvhDomainPacksProductInformation> cart_cartId_domainPacks_GET(String cartId, String domain) throws IOException {
		String qPath = "/order/cart/{cartId}/domainPacks";
		StringBuilder sb = path(qPath, cartId);
		query(sb, "domain", domain);
		String resp = execN(qPath, "GET", sb.toString(), null);
		return convertTo(resp, t8);
	}

public function deleteCORSRequest()
    {
        $operation = array(
            'API' => 'DeleteBucketCORS',
            'Method' => 'DELETE',
            'Uri' => '/<bucket-name>?cors',
            'Headers' => array(
                'Host' => $this->properties['zone'] . '.' . $this->config->host,
            ),
            'Params' => array(
            ),
            'Elements' => array(
            ),
            'Properties' => $this->properties,
            'Body' => null
        );
        $this->deleteCORSValidate($operation);
        $req = new Request($this->config, $operation);
        return $req;
    }

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


Question: // AreSame returns true if both the heights are either nil or equal

func AreSame(h1 *Height, h2 *Height) bool {
	if h1 == nil {
		return h2 == nil
	}
	if h2 == nil {
		return false
	}
	return h1.Compare(h2) == 0
}

public function resizeXorY($x, $y)
    {
        if ($x > $y) {
            $this->resizeX($x);
        } else {
            $this->resizeY($y);
        }
    }

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


Question:
Concrete5_Controller_Login::authenticate
Authenticate the user using a specific authentication type.

@param $type    AuthenticationType handle

public function authenticate($type = '')
    {
        $valt = $this->app->make('token');
        if (!$valt->validate('login_' . $type)) {
            $this->error->add($valt->getErrorMessage());
        } else {
            try {
                $at = AuthenticationType::getByHandle($type);
                $user = $at->controller->authenticate();
                if ($user && $user->isRegistered()) {
                    return $this->finishAuthentication($at, $user);
                }
            } catch (Exception $e) {
                $this->error->add($e->getMessage());
            }
        }

        if (isset($at)) {
            $this->set('lastAuthType', $at);
        }

        $this->view();
    }

public static AuthInfo getUserAuthInfo(Config config, Context context) {
    AuthInfo authInfo = null;
    if (config != null && context != null) {
      String user = context.getUser();
      if (user != null) {
        List<NamedAuthInfo> users = config.getUsers();
        if (users != null) {
          for (NamedAuthInfo namedAuthInfo : users) {
            if (user.equals(namedAuthInfo.getName())) {
              authInfo = namedAuthInfo.getUser();
            }
          }
        }
      }
    }
    return authInfo;
  }

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


Question:
Calls a private or protected method of an object.

@psalm-suppress InvalidScope

@param mixed $objectOrClass
@param string $methodName
@param mixed ...$args

@return mixed

public static function callMethod($objectOrClass, string $methodName, ...$args)
    {
        $objectOrClass = self::getObject($objectOrClass);
        $closure =
            /**
             * @param string $methodName
             * @param array $args
             * @return mixed
             */
            function (string $methodName, ...$args) {
                if (\method_exists($this, $methodName)) {
                    return $this->$methodName(...$args);
                }
                throw new \RuntimeException(
                    Picklock::errorMessage($this, $methodName, true)
                );
            };
        return
            $closure->call($objectOrClass, $methodName, ...$args);
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

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


Question:
Add categories assigned to this message

        :rtype: list(Category)

def category(self, categories):

        if isinstance(categories, list):
            for c in categories:
                self.add_category(c)
        else:
            self.add_category(categories)

def method_rules
      [
        Rule.new(:error, 40..41, "Description", "You should include a description for your method.", proc do |json|
          json[:body_md] && json[:body_md].empty?
        end),
        Rule.new(:warning, 43..45, "Params", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
          json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?(nil)
        end),
        Rule.new(:warning, 43..45, "Unknown Param", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
          json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?("Unknown")
        end),
        Rule.new(:warning, 46, "Return Type", "If the function has no useful return value, use ` @return  [void]` - this will be ignored by documentation generators.", proc do |json|
          return_hash = json[:tags].find { |tag| tag[:name] == "return" }
          !(return_hash && return_hash[:types] && !return_hash[:types].first.empty?)
        end)
      ]
    end

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


Question:
Get collection of subscribers by channel.

@param  string  $topic
@return \Illuminate\Support\Collection<\Nuwave\Lighthouse\Subscriptions\Subscriber>

public function subscribersByTopic(string $topic)
    {
        $key = self::TOPIC_KEY.".{$topic}";

        if (! $this->cache->has($key)) {
            return new Collection;
        }

        $channels = json_decode($this->cache->get($key), true);

        return (new Collection($channels))
            ->map(function (string $channel): ?Subscriber {
                return $this->subscriberByChannel($channel);
            })
            ->filter()
            ->values();
    }

function(node, atoms, call_back) {
        if (!Array.isArray(atoms))
            atoms = [atoms];

        var i, atom, entries = [];
        for (i = 0; i < atoms.length; i++) {
            atom = atoms[i];

            atom.updated = atom.updated || (new Date()).toISOString();
            if (atom.published && atom.published.toISOString)
                atom.published = atom.published.toISOString();

            entries.push({
                data: $build("entry", { xmlns:Strophe.NS.ATOM })
                        .children(atom).tree(),
                attrs:(atom.id ? { id:atom.id } : {}),
            });
        }
        return this.publish(node, entries, call_back);
    }

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


Question:
Add commands configuration

@param ArrayNodeDefinition $node

protected function addCommands(ArrayNodeDefinition $node)
    {
        $node
            ->fixXmlConfig('command')
            ->children()
                ->arrayNode('commands')
                ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('rabbitmq_consumer')->defaultValue('rabbitmq:consumer')->end()
                        ->scalarNode('rabbitmq_multiple_consumer')->defaultValue('rabbitmq:multiple-consumer')->end()
                        ->scalarNode('rabbitmq_batch_consumer')->defaultValue('rabbitmq:batch:consumer')->end()
                        ->scalarNode('rabbitmq_rpc_server')->defaultValue('rabbitmq:rpc-server')->end()
                    ->end()
                ->end()
            ->end()
        ;
    }

function(xmlElement) {
    this.arguments_ = [];
    for (var i = 0, childNode; childNode = xmlElement.childNodes[i]; i++) {
      if (childNode.nodeName.toLowerCase() == 'arg') {
        this.arguments_.push(childNode.getAttribute('name'));
      }
    }
    this.updateParams_();
    Blockly.Procedures.mutateCallers(this);

    // Show or hide the statement input.
    this.setStatements_(xmlElement.getAttribute('statements') !== 'false');
  }

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


Question:
/*
(non-Javadoc)

@see org.restcomm.ss7.management.console.CommandHandler#handles(java.lang .String)

@Override
    public boolean handles(String command) {
        if (command.startsWith(this.tree.getTopNode().getData())) {
            return true;
        }
        return false;
    }

public void run(String[] args) {
        String context = args.length > 0 ? args[0] : "";
        String action = args.length > 1 ? args[1] : "";
        String option = args.length > 2 ? args[2] : "";

        switch (context) {
            case "server":
                server(action, option);
                break;
            case "version":
                version();
                break;
            default:
                help();
        }
    }

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


Question:
Gets node index and its peer count

@return ClientsResult object with info

public ClientsResult calculateAllNodesResult() {
		final List<String> childNodePaths = getChildren(electionRootPath, false);
		_logger.info("Total peers = {} ", childNodePaths.size());
		Collections.sort(childNodePaths);

		int index = childNodePaths.indexOf(clientNodePath.substring(clientNodePath.lastIndexOf('/') + 1));
		return new ClientsResult(index, childNodePaths.size());
	}

func (pb *prober) runProbeWithRetries(probeType probeType, p *v1.Probe, pod *v1.Pod, status v1.PodStatus, container v1.Container, containerID kubecontainer.ContainerID, retries int) (probe.Result, string, error) {
	var err error
	var result probe.Result
	var output string
	for i := 0; i < retries; i++ {
		result, output, err = pb.runProbe(probeType, p, pod, status, container, containerID)
		if err == nil {
			return result, output, nil
		}
	}
	return result, output, err
}

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


Question:
Load script file

@param $file
@return $this

public function load($file, array $data = array())
    {
        $this->queries = array();
        $this->data = $data;

        include $file;

        return $this;
    }

func (h Helper) RunScriptCommand() (*command.Model, error) {
	tmpDir, err := h.ensureTmpDir()
	if err != nil {
		return nil, err
	}

	rubyScriptPth := path.Join(tmpDir, "script.rb")
	if err := fileutil.WriteStringToFile(rubyScriptPth, h.scriptContent); err != nil {
		return nil, err
	}

	var cmd *command.Model
	if h.gemfilePth != "" {
		cmd = command.New("bundle", "exec", "ruby", rubyScriptPth)
		cmd.AppendEnvs("BUNDLE_GEMFILE=" + h.gemfilePth)
	} else {
		cmd = command.New("ruby", rubyScriptPth)
	}

	return cmd, nil
}

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


Question:
Speed up data access

        More efficient because data is accessed and cached locally

def get_tile_images_by_rect(self, rect):

        def rev(seq, start, stop):
            if start < 0:
                start = 0
            return enumerate(seq[start:stop + 1], start)

        x1, y1, x2, y2 = rect_to_bb(rect)
        images = self.tmx.images
        layers = self.tmx.layers
        at = self._animated_tile
        tracked_gids = self._tracked_gids
        anim_map = self._animation_map
        track = bool(self._animation_queue)

        for l in self.tmx.visible_tile_layers:
            for y, row in rev(layers[l].data, y1, y2):
                for x, gid in [i for i in rev(row, x1, x2) if i[1]]:
                    # since the tile has been queried, assume it wants to be checked
                    # for animations sometime in the future
                    if track and gid in tracked_gids:
                        anim_map[gid].positions.add((x, y, l))

                    try:
                        # animated, so return the correct frame
                        yield x, y, l, at[(x, y, l)]

                    except KeyError:

                        # not animated, so return surface from data, if any
                        yield x, y, l, images[gid]

public function prepareCacheData(AbstractModel $model)
    {
        /**
         * @todo change MySQLTableData to a usecase based one
         */
        $tableData  = clone $this->tableData;
        $reflection = new \ReflectionClass($model);
        $tableData->setTableName($this->parseTableName($reflection));

        return [
            'tableData'    => $tableData,
            'reflection'   => new \ReflectionClass($model),
            'relationList' => $this->extractRelations($reflection),
        ];
    }

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


Question:
Routing.

@param string $menuName
The system name of the menu, such as 'menu-business'.
@param string $op
The operation to perform on the menu. Possible values are 'add' or
'edit'.

@return string
The correct relative path to the page.

@throws \Exception

public static function route($menuName = '', $op = '')
    {
        switch ($op) {
            case '':
                return static::URL;
            case 'add':
                return static::URL . '/manage/' . $menuName . '/add';
            case 'edit':
                return static::URL . '/manage/' . $menuName . '/edit';
        }

        throw new \Exception('Invalid route parameter passed to ' . __CLASS__ . ' PageObject.');
    }

public function getViewParameters(BlockInterface $block)
    {
        $parameters = [
            'block_service' => $this,
            'block' => $block,
        ];

        if ($this->environment->getObject() instanceof Content) {
            // Get current page slug to mark it as active when listing
            $parameters['content'] = $this->environment->getObject();
            $parameters['breadcrumbs'] = $parameters['content']->getBreadCrumbs();
        } else {
            $parameters['content'] = $this->contentManager->initialize();
            $parameters['content']->setSlug('example');
            $parameters['breadcrumbs'] = [
                'directory' => 'Example Directory',
                'example' => 'Example Page',
            ];
        }

        // Add homepage link as first breadcrumb if it does not exist in breadcrumbs
        if (!array_key_exists('index', $parameters['breadcrumbs'])) {
            $homePage = $this->contentManager->findOneBySlug('index');

            $parameters['breadcrumbs'] = array_merge(['index' => $homePage->getShortTitle()], $parameters['breadcrumbs']);
        }

        return $parameters;
    }

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


Question: // RemoveAll removes remote files

func (c *Client) RemoveAll(path string) error {
	rs, err := c.req("DELETE", path, nil, nil)
	if err != nil {
		return newPathError("Remove", path, 400)
	}
	err = rs.Body.Close()
	if err != nil {
		return err
	}

	if rs.StatusCode == 200 || rs.StatusCode == 204 || rs.StatusCode == 404 {
		return nil
	}

	return newPathError("Remove", path, rs.StatusCode)
}

public function flush() {
		$pattern = $this->getCachePath() . DIRECTORY_SEPARATOR . $this->prefix . '_*';

		if (self::isExecAvailable()) {
			exec('rm ' . $pattern);
			return true;
		}

		$list = glob($pattern);

		if ($list === false) {
			return false;
		}

		if (empty($list)) {
			return true;
		}

		$result = true;

		foreach ($list as $path) {
			if (! unlink($path)) {
				$result = false;
			}
		}

		return $result;
	}

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


Question: Implementation of `address_target_pairs_from_address_families()` which does no filtering.

def all_address_target_pairs(cls, address_families):
    """"""
    addr_tgt_pairs = []
    for af in address_families:
      addr_tgt_pairs.extend(af.addressables.items())
    return addr_tgt_pairs

func (collector *serverInterceptorBuilder) Build() []grpc.ServerOption {
	log.Infof("Building interceptors with %d unary interceptors and %d stream interceptors", len(collector.unaryInterceptors), len(collector.streamInterceptors))
	switch len(collector.unaryInterceptors) + len(collector.streamInterceptors) {
	case 0:
		return []grpc.ServerOption{}
	default:
		return []grpc.ServerOption{
			grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(collector.unaryInterceptors...)),
			grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(collector.streamInterceptors...)),
		}
	}
}

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


Question: convenience constructor function

function createPiGlow(callback) {
    var myPiGlow = new PiGlowBackend();
    var myInterface = piGlowInterface(myPiGlow);

    myPiGlow
        .on('initialize', function() {
            callback(null, myInterface);
        })
        .on('error', function(error) {
            callback(error, null);
        });
}

public static <T> Codec<T> create(Class<T> cls, Compiler compiler, ICodeGenerator codeGenerator) {
        return create(cls, isDebugEnabled(), null, compiler, getCodeGenerator(cls));
    }

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


Question:
Get the collection of contacts for the calling user.

@return The Collection of Contact objects

public Collection<Contact> getList() throws FlickrException {
    	 ContactList<Contact> contacts = new ContactList<Contact>();

        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("method", METHOD_GET_LIST);

        Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);
        if (response.isError()) {
            throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
        }

        Element contactsElement = response.getPayload();
        contacts.setPage(contactsElement.getAttribute("page"));
        contacts.setPages(contactsElement.getAttribute("pages"));
        contacts.setPerPage(contactsElement.getAttribute("perpage"));
        contacts.setTotal(contactsElement.getAttribute("total"));
        NodeList contactNodes = contactsElement.getElementsByTagName("contact");
        for (int i = 0; i < contactNodes.getLength(); i++) {
            Element contactElement = (Element) contactNodes.item(i);
            Contact contact = new Contact();
            contact.setId(contactElement.getAttribute("nsid"));
            contact.setUsername(contactElement.getAttribute("username"));
            contact.setRealName(contactElement.getAttribute("realname"));
            contact.setFriend("1".equals(contactElement.getAttribute("friend")));
            contact.setFamily("1".equals(contactElement.getAttribute("family")));
            contact.setIgnored("1".equals(contactElement.getAttribute("ignored")));
            String lPathAlias = contactElement.getAttribute("path_alias");
            contact.setPathAlias(lPathAlias == null || "".equals(lPathAlias) ? null : lPathAlias);
            contact.setOnline(OnlineStatus.fromType(contactElement.getAttribute("online")));
            contact.setIconFarm(contactElement.getAttribute("iconfarm"));
            contact.setIconServer(contactElement.getAttribute("iconserver"));
            if (contact.getOnline() == OnlineStatus.AWAY) {
                contactElement.normalize();
                contact.setAwayMessage(XMLUtilities.getValue(contactElement));
            }
            contacts.add(contact);
        }
        return contacts;
    }

public void add(Collection<NrqlAlertCondition> conditions)
    {
        for(NrqlAlertCondition condition : conditions)
            this.conditions.put(condition.getId(), condition);
    }

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


Question:
calculates the mean molecular polarizability as described in paper of Kang and Jhorn.

@param  atomContainer  AtomContainer
@return     polarizabilitiy

public double calculateKJMeanMolecularPolarizability(IAtomContainer atomContainer) {
        double polarizabilitiy = 0;
        IAtomContainer acH = atomContainer.getBuilder().newInstance(IAtomContainer.class, atomContainer);
        addExplicitHydrogens(acH);
        for (int i = 0; i < acH.getAtomCount(); i++) {
            polarizabilitiy += getKJPolarizabilityFactor(acH, acH.getAtom(i));
        }
        return polarizabilitiy;
    }

public void marshall(Sunglasses sunglasses, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(sunglasses.getValue(), VALUE_BINDING);
            protocolMarshaller.marshall(sunglasses.getConfidence(), CONFIDENCE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
{@link Writer}を開きます。

@param context コンテキスト
@return {@link Writer}

protected Writer openWriter(GenerationContext context) {
    Charset charset = Charset.forName(context.getEncoding());
    return new BufferedWriter(
        new OutputStreamWriter(createFileOutputStream(context.getFile()), charset));
  }

public static void main(String[] args) {
    System.out.println("Hello Stats World");
    System.out.println("Default Tags: " + tagger.empty());
    System.out.println("Current Tags: " + tagger.getCurrentTagContext());
    TagContext tags1 = tagger.emptyBuilder().put(K1, V1).put(K2, V2).build();
    try (Scope scopedTagCtx1 = tagger.withTagContext(tags1)) {
      System.out.println("  Current Tags: " + tagger.getCurrentTagContext());
      System.out.println(
          "  Current == Default + tags1: " + tagger.getCurrentTagContext().equals(tags1));
      TagContext tags2 = tagger.toBuilder(tags1).put(K3, V3).put(K4, V4).build();
      try (Scope scopedTagCtx2 = tagger.withTagContext(tags2)) {
        System.out.println("    Current Tags: " + tagger.getCurrentTagContext());
        System.out.println(
            "    Current == Default + tags1 + tags2: "
                + tagger.getCurrentTagContext().equals(tags2));
        statsRecorder.newMeasureMap().put(M1, 0.2).put(M2, 0.4).record();
      }
    }
    System.out.println(
        "Current == Default: " + tagger.getCurrentTagContext().equals(tagger.empty()));
  }

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


Question: Returns true if enough bytes are available to read an int with {@link #readVarInt(boolean)}.

public boolean canReadVarInt () throws KryoException {
		if (limit - position >= 5) return true;
		if (optional(5) <= 0) return false;
		int p = position, limit = this.limit;
		byte[] buffer = this.buffer;
		if ((buffer[p++] & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((buffer[p++] & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((buffer[p++] & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((buffer[p++] & 0x80) == 0) return true;
		if (p == limit) return false;
		return true;
	}

private void discardReadBytesIfNecessary(ByteBuf buffer) {

        float usedRatio = (float) buffer.readerIndex() / buffer.capacity();

        if (usedRatio >= discardReadBytesRatio && buffer.refCnt() != 0) {
            buffer.discardReadBytes();
        }
    }

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


Question: Clone a DAG, optionally skipping the commit.

def clone(self, substitutions, commit=True, **kwargs):

        return self.store.clone(substitutions, **kwargs)

def name(self):
        '''

        '''
        clonify_ids = [p.heavy['clonify']['id'] for p in self.heavies if 'clonify' in p.heavy]
        if len(clonify_ids) > 0:
            return clonify_ids[0]
        return None

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


Question:
/*
Mode and System Configuration

@author Li Ding (oldratlee AT gmail DOT com)

@SuppressWarnings({"unchecked", "rawtypes"})
    private static Properties initProperties(String configPath, Properties configProperties) {
        Map<String, String> systemProperties = ConfigUtils.filterWithPrefix(HTTL_KEY_PREFIX, (Map) System.getProperties(), false);
        Map<String, String> systemEnv = ConfigUtils.filterWithPrefix(HTTL_KEY_PREFIX, System.getenv(), true);
        Properties properties = ConfigUtils.mergeProperties(HTTL_DEFAULT_PROPERTIES, configPath, configProperties, systemProperties, systemEnv);
        String[] modes = StringUtils.splitByComma(properties.getProperty(MODES_KEY));
        if (CollectionUtils.isNotEmpty(modes)) {
            Object[] configs = new Object[modes.length + 5];
            configs[0] = HTTL_DEFAULT_PROPERTIES;
            for (int i = 0; i < modes.length; i++) {
                configs[i + 1] = HTTL_PREFIX + modes[i] + PROPERTIES_SUFFIX;
            }
            configs[modes.length + 1] = configPath;
            configs[modes.length + 2] = configProperties;
            configs[modes.length + 3] = systemProperties;
            configs[modes.length + 4] = systemEnv;
            properties = ConfigUtils.mergeProperties(configs);
        }
        properties.setProperty(ENGINE_NAME, configPath);
        return properties;
    }

func (o Output) ConfigSets() []ConfigSet {
	names := make([]string, 0, len(o.Roots))
	for name := range o.Roots {
		names = append(names, name)
	}
	sort.Strings(names) // order is important for logs

	cs := make([]ConfigSet, len(names))
	for i, nm := range names {
		root := o.Roots[nm]

		// Normalize in preparation for prefix matching.
		root = path.Clean(root)
		if root == "." {
			root = "" // match EVERYTHING
		} else {
			root = root + "/" // match only what's under 'root/...'
		}

		files := map[string][]byte{}
		for f, body := range o.Data {
			f = path.Clean(f)
			if strings.HasPrefix(f, root) {
				files[f[len(root):]] = body
			}
		}

		cs[i] = ConfigSet{Name: nm, Data: files}
	}

	return cs
}

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


Question:
Enable TLS 1.2 on the OkHttpClient on API 16-21, which is supported but not enabled by default.

@link https://github.com/square/okhttp/issues/2372
@see TLS12SocketFactory

private void enforceTls12(OkHttpClient client) {
        // No need to modify client as TLS 1.2 is enabled by default on API21+
        // Lollipop is included because some Samsung devices face the same problem on API 21.
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN
                || Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            return;
        }
        try {
            SSLContext sc = SSLContext.getInstance("TLSv1.2");
            sc.init(null, null, null);
            client.setSslSocketFactory(new TLS12SocketFactory(sc.getSocketFactory()));

            ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                    .tlsVersions(TlsVersion.TLS_1_2)
                    .build();

            List<ConnectionSpec> specs = new ArrayList<>();
            specs.add(cs);
            specs.add(ConnectionSpec.COMPATIBLE_TLS);
            specs.add(ConnectionSpec.CLEARTEXT);

            client.setConnectionSpecs(specs);
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            Log.e(TAG, "Error while setting TLS 1.2", e);
        }
    }

def tcp_client(tcp_addr):
  """"""
  family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET
  sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP)
  for i in range(300):
    logging.info("Connecting to: %s, attempt %d", tcp_addr, i)
    try:
      sock.connect(tcp_addr)
      break
    except socket.error:
      time.sleep(1)
  else:
    sock.connect(tcp_addr)  # One last try, but don't catch this error.
  logging.info("Connected.")

  map_data = read_tcp(sock)
  settings_str = read_tcp(sock)
  if not settings_str:
    raise socket.error("Failed to read")
  settings = json.loads(settings_str.decode())
  logging.info("Got settings. map_name: %s.", settings["map_name"])
  logging.debug("settings: %s", settings)
  settings["map_data"] = map_data
  return sock, settings

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


Question:
Header callback

@param resource $handle
@param string $header
@return void

public function header($handle, $header)
    {
      if(!is_resource($handle))
        throw new Exception(__METHOD__ . '; cURL handle is not valid');

      $length = strlen($header);

      $this->headers .= $header;

      /*// Trim header (newline)
      $header = rtrim($header);

      if(strlen($header) > 0)
        $this->headers[] = $header;*/

      return $length;
    }

def _run__http(self, action, replace):
        """"""

        query = action['query']
#        self._debug = True
        url = '{type}://{host}{path}'.format(path=query['path'], **action)
        content = None
        method = query.get('method', "get").lower()
        self.debug("{} {} url={}\n", action['type'], method, url)
        if method == "post":
            content = query['content']
        headers = query.get('headers', {})

        if replace and action.get('template'):
            self.rfxcfg.macro_expand(url, replace)
            if content:
                if isinstance(content, dict):
                    for key, value in content.items():
                        content[key] = self.rfxcfg.macro_expand(value, replace)
                else:
                    content = self.rfxcfg.macro_expand(content, replace)

            newhdrs = dict()
            for key, value in headers.items():
                newhdrs[key.lower()] = self.rfxcfg.macro_expand(value, replace)
            headers = newhdrs

        self.debug("{} headers={}\n", action['type'], headers)
        self.debug("{} content={}\n", action['type'], content)

        if content and isinstance(content, dict):
            content = json.dumps(content)

        self.logf("Action {name} {type}\n", **action)
        result = getattr(requests, method)(url, headers=headers, data=content, timeout=action.get('timeout', 5))
        expect = action.get('expect', {})
        expected_codes = expect.get("response-codes", (200, 201, 202, 204))
        self.debug("{} expect codes={}\n", action['type'], expected_codes)
        self.debug("{} status={} content={}\n", action['type'], result.status_code, result.text)
        if result.status_code not in expected_codes:
            self.die("Unable to make {} call, unexpected result ({})",
                     action['type'], result.status_code)

        if 'content' in expect:
            self.debug("{} expect content={}\n", action['type'], expect['content'])
            if expect['content'] not in result.text:
                self.die("{} call to {} failed\nExpected: {}\nReceived:\n{}",
                         action['type'], url, expect['content'], result.text)

        if 'regex' in expect:
            self.debug("{} expect regex={}\n", action['type'], expect['regex'])
            if not re.search(expect['regex'], result.text):
                self.die("{} call to {} failed\nRegex: {}\nDid not match:\n{}",
                         action['type'], url, expect['regex'], result.text)

        self.log(result.text, level=common.log_msg)

        self.logf("Success, status={}\n", result.status_code, level=common.log_good)
        return True

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


Question:
// This function wraps application with daemonization.
// Returns isDaemon value to distinguish parent and daemonized processes.

func Daemonize() (isDaemon bool, err error) {
	const errLoc = "daemonigo.Daemonize()"
	isDaemon = os.Getenv(EnvVarName) == EnvVarValue
	if WorkDir != "" {
		if err = os.Chdir(WorkDir); err != nil {
			err = fmt.Errorf(
				"%s: changing working directory failed, reason -> %s",
				errLoc, err.Error(),
			)
			return
		}
	}
	if isDaemon {
		syscall.Umask(int(Umask))
		if _, err = syscall.Setsid(); err != nil {
			err = fmt.Errorf(
				"%s: setsid failed, reason -> %s", errLoc, err.Error(),
			)
			return
		}
		if pidFile, err = lockPidFile(); err != nil {
			err = fmt.Errorf(
				"%s: locking PID file failed, reason -> %s",
				errLoc, err.Error(),
			)
		}
	} else {
		flag.Usage = func() {
			arr := make([]string, 0, len(actions))
			for k, _ := range actions {
				arr = append(arr, k)
			}
			fmt.Fprintf(os.Stderr, "Usage: %s {%s}\n",
				os.Args[0], strings.Join(arr, "|"),
			)
			flag.PrintDefaults()
		}
		if !flag.Parsed() {
			flag.Parse()
		}
		action, exist := actions[flag.Arg(0)]
		if exist {
			action()
		} else {
			flag.Usage()
		}
	}
	return
}

def parse_data_to_internal(self, data=None):

        if data is None:
            f = open(self.location_dat, "rb")
            data = {
                "PMCA SPECTRUM": {},
                "DATA": [],
                "DP5 CONFIGURATION": {},
                "DPP STATUS": {}
            }
            delimiter = {
                "PMCA SPECTRUM": " - ",
                "DP5 CONFIGURATION": "=",
                "DPP STATUS": ":"
            }
            comments = {
                "PMCA SPECTRUM": None,
                "DP5 CONFIGURATION": ";",
                "DPP STATUS": None
            }
            for e in f:
                if "<<" in e:
                    if "<<END>>" in e:
                        current = None
                    elif "<<PMCA SPECTRUM>>" in e:
                        current = "PMCA SPECTRUM"
                    elif "<<DATA>>" in e:
                        current = "DATA"
                    elif "<<DP5 CONFIGURATION>>" in e:
                        current = "DP5 CONFIGURATION"
                    elif "<<DPP STATUS>>" in e:
                        current = "DPP STATUS"
                    elif "<<ROI>>" in e:
                        current = "ROI"
                else:
                    if current == "DATA":
                        data["DATA"].append(float(e))
                    elif current == "ROI":
                        continue
                    elif current is not None:
                        e = e.split("\r\n")[0]
                        if comments[current] is not None:
                            e = e.split(comments[current], 1)[0]
                        e_list = e.split(delimiter[current], 1)
                        data[current][e_list[0]] = e_list[1]
            f.close()
        self.save_to_internal(data)

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


Question:
Pay an order.

@author yansongda <me@yansongda.cn>

@param string $endpoint
@param array  $payload

@throws GatewayException
@throws InvalidArgumentException
@throws InvalidSignException

@return RedirectResponse

public function pay($endpoint, array $payload): RedirectResponse
    {
        $payload['trade_type'] = $this->getTradeType();

        Events::dispatch(Events::PAY_STARTED, new Events\PayStarted('Wechat', 'Wap', $endpoint, $payload));

        $mweb_url = $this->preOrder($payload)->get('mweb_url');

        $url = is_null(Support::getInstance()->return_url) ? $mweb_url : $mweb_url.
                        '&redirect_url='.urlencode(Support::getInstance()->return_url);

        return RedirectResponse::create($url);
    }

public function encodeParameter($type, $param)
    {
        if (!is_string($type)) {
            throw new InvalidArgumentException('The type to encodeParameter must be string.');
        }
        return $this->encodeParameters([$type], [$param]);
    }

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


Question: Convert SubRipTime instance into a pure datetime.time object

def to_time(self):

        return time(self.hours, self.minutes, self.seconds,
                    self.milliseconds * 1000)

def normalize_type(type_, level=0):

    if not typing or not isinstance(type_, typing.TypingMeta) or type_ is AnyType:
        return type_
    if isinstance(type_, typing.TypeVar):
        if type_.__constraints__ or type_.__bound__:
            return type_
        else:
            return AnyType
    if issubclass(type_, typing.Union):
        if not type_.__union_params__:
            raise OverloadingError("typing.Union must be parameterized")
        return typing.Union[tuple(normalize_type(t, level) for t in type_.__union_params__)]
    if issubclass(type_, typing.Tuple):
        params = type_.__tuple_params__
        if level > 0 or params is None:
            return typing.Tuple
        elif type_.__tuple_use_ellipsis__:
            return typing.Tuple[normalize_type(params[0], level + 1), ...]
        else:
            return typing.Tuple[tuple(normalize_type(t, level + 1) for t in params)]
    if issubclass(type_, typing.Callable):
        return typing.Callable
    if isinstance(type_, typing.GenericMeta):
        base = find_base_generic(type_)
        if base is typing.Generic:
            return type_
        else:
            return GenericWrapper(type_, base, level > 0)
    raise OverloadingError("%r not supported yet" % type_)

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


Question:
Remove the last *count* ser elements from *plotArea*. Any xChart
        elements having no ser child elements after trimming are also
        removed.

def _trim_ser_count_by(self, plotArea, count):

        extra_sers = plotArea.sers[-count:]
        for ser in extra_sers:
            parent = ser.getparent()
            parent.remove(ser)
        extra_xCharts = [
            xChart for xChart in plotArea.iter_xCharts()
            if len(xChart.sers) == 0
        ]
        for xChart in extra_xCharts:
            parent = xChart.getparent()
            parent.remove(xChart)

function (vis, redraw) {
		var series = this,
			chart = series.chart,
			legendItem = series.legendItem,
			seriesGroup = series.group,
			seriesTracker = series.tracker,
			dataLabelsGroup = series.dataLabelsGroup,
			showOrHide,
			i,
			data = series.data,
			point,
			ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
			oldVisibility = series.visible;

		// if called without an argument, toggle visibility
		series.visible = vis = vis === UNDEFINED ? !oldVisibility : vis;
		showOrHide = vis ? 'show' : 'hide';

		// show or hide series
		if (seriesGroup) { // pies don't have one
			seriesGroup[showOrHide]();
		}

		// show or hide trackers
		if (seriesTracker) {
			seriesTracker[showOrHide]();
		} else {
			i = data.length;
			while (i--) {
				point = data[i];
				if (point.tracker) {
					point.tracker[showOrHide]();
				}
			}
		}

		if (dataLabelsGroup) {
			dataLabelsGroup[showOrHide]();
		}

		if (legendItem) {
			chart.legend.colorizeItem(series, vis);
		}

		// rescale or adapt to resized chart
		series.isDirty = true;
		// in a stack, all other series are affected
		if (series.options.stacking) {
			each(chart.series, function (otherSeries) {
				if (otherSeries.options.stacking && otherSeries.visible) {
					otherSeries.isDirty = true;
				}
			});
		}

		if (ignoreHiddenSeries) {
			chart.isDirtyBox = true;
		}
		if (redraw !== false) {
			chart.redraw();
		}

		fireEvent(series, showOrHide);
	}

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


Question:
Recursively scans Django settings for values that appear to be
    imported modules.

def scan_django_settings(values, imports):
    '''
    '''
    if isinstance(values, (str, bytes)):
        if utils.is_import_str(values):
            imports.add(values)
    elif isinstance(values, dict):
        for k, v in values.items():
            scan_django_settings(k, imports)
            scan_django_settings(v, imports)
    elif hasattr(values, '__file__') and getattr(values, '__file__'):
        imp, _ = utils.import_path_from_file(getattr(values, '__file__'))
        imports.add(imp)
    elif hasattr(values, '__iter__'):
        for item in values:
            scan_django_settings(item, imports)

def kitchen_config(backend, kitchen, add, get, unset, listall):

    err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
    if use_kitchen is None:
        raise click.ClickException(err_str)
    check_and_print(DKCloudCommandRunner.config_kitchen(backend.dki, use_kitchen, add, get, unset, listall))

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


Question:
@param Content      $content Content model
@param QueryBuilder $builder Query builder

@return Collection|LengthAwarePaginator

public function getManyPublishedChildren(Content $content, QueryBuilder $builder)
    {
        return $this->getManyPublishedFrom($content->children()->newQuery()->with('type')->getQuery(), $builder);
    }

private void addQueryParams(final Request request) {
        if (endDate != null) {
            request.addQueryParam("EndDate", endDate.toString());
        }

        if (friendlyName != null) {
            request.addQueryParam("FriendlyName", friendlyName);
        }

        if (minutes != null) {
            request.addQueryParam("Minutes", minutes.toString());
        }

        if (startDate != null) {
            request.addQueryParam("StartDate", startDate.toString());
        }

        if (taskChannel != null) {
            request.addQueryParam("TaskChannel", taskChannel);
        }

        if (splitByWaitTime != null) {
            request.addQueryParam("SplitByWaitTime", splitByWaitTime);
        }

        if (getPageSize() != null) {
            request.addQueryParam("PageSize", Integer.toString(getPageSize()));
        }
    }

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


Question:
returns the same type as the input, except when:
- null, it returns the default ::TYPE_CONTINUOUS
- not one of the allowed types, it throws an exception

@param  string $type one of the ::TYPE_* consts
@return string|exception

private static function check_type($type=null) {
	if (is_null($type)) {
		return self::TYPE_CONTINUOUS;
	}

	if (isset(self::$type_durations[$type]) == false) {
		$exception = bootstrap::get_library('exception');
		throw new $exception('unknown session type');
	}

	return $type;
}

public function assertBundles(TableNode $expected) {
    $bundle_info = [];
    foreach ($this->getContentEntityTypes() as $entity_type) {
      $bundles = $this->entityTypeManager()
        ->getStorage($entity_type->getBundleEntityType())
        ->loadMultiple();
      foreach ($bundles as $bundle) {
        $description = '';
        $description_getter = 'getDescription';
        if (method_exists($bundle, $description_getter)) {
          $description = call_user_func([
            $bundle,
            $description_getter,
          ]);
        }
        if (!isset($description) || !$description) {
          $description = '';
        }

        $bundle_info[] = [
          $bundle->label(),
          $bundle->id(),
          $entity_type->getBundleLabel(),
          $description,
        ];
      }
    }
    $actual = new TableNode($bundle_info);

    (new TableEqualityAssertion($expected, $actual))
      ->expectHeader([
        'Name',
        'Machine name',
        'Type',
        'Description',
      ])
      ->ignoreRowOrder()
      ->setMissingRowsLabel(self::missingRowsLabelFor('bundles'))
      ->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('bundles'))
      ->assert();
  }

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