Question:
Adds the commerce address restriction to the database. Also notifies the appropriate model listeners.

@param commerceAddressRestriction the commerce address restriction
@return the commerce address restriction that was added

@Indexable(type = IndexableType.REINDEX)
	@Override
	public CommerceAddressRestriction addCommerceAddressRestriction(
		CommerceAddressRestriction commerceAddressRestriction) {
		commerceAddressRestriction.setNew(true);

		return commerceAddressRestrictionPersistence.update(commerceAddressRestriction);
	}

public function authorize($payment, $amount)
        {
            $error = false;

            // check for payment
            if($amount > 0) {

                $payment->setAmount($amount);

                // Map magento keys to moneris way
                $transaction = $this->_build($payment, self::TRANSACTION_PREAUTH);
                $response = $this->_send($transaction);

                $payment->setCcApproval($response->getReceiptId())
                    ->setLastTransId($response->getReceiptId())
                    ->setCcTransId($response->getTxnNumber())
                    ->setCcAvsStatus($response->getAuthCode())
                    ->setCcCidStatus($response->getResponseCode());

                if($response->getResponseCode() > 0 && $response->getResponseCode() <= self::ERROR_CODE_LIMIT) {
                    $payment->setStatus(self::STATUS_APPROVED);
                } else if($response->getResponseCode() > self::ERROR_CODE_LIMIT && $response->getResponseCode() < self::ERROR_CODE_UPPER_LIMIT) {
                    $error = $this->_errors[$response->getResponseCode()];
                } else {
                    $error = 'Incomplete transaction.';
                }
            } else {
                $error = 'Invalid amount for authorization.';
            }

            // we've got something bad here.
            if ($error !== false) {
                $this->_log($error);
            }
            return $this;
        }

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


Question: // CreateProxyARPFilter creates a new child ProxyARPFilter under the Subnet

func (o *Subnet) CreateProxyARPFilter(child *ProxyARPFilter) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}

func (s *Server) verifyNICsWithConfigFile(nics map[string]device, reader func(string) ([]byte, error)) error {
	netName, err := checkBridgeConfigFile(reader)
	if err != nil {
		return errors.Trace(err)
	}

	checked := make([]string, 0, len(nics))
	for name, nic := range nics {
		checked = append(checked, name)

		if nic["parent"] != netName {
			continue
		}
		if !isValidNICType(nic) {
			continue
		}

		logger.Tracef("found usable network device %q with parent %q", name, netName)
		s.localBridgeName = netName
		return nil
	}

	return errors.Errorf("no network device found with nictype %q or %q that uses the configured bridge in %s"+
		"\n\tthe following devices were checked: %v", nicTypeBridged, nicTypeMACVLAN, BridgeConfigFile, checked)
}

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


Question:
Sets User Agent.
@access		public
@param		string		$string		User Agent to set
@return		void

public function setUserAgent( $string )
	{
		if( empty( $string ) )
			throw new InvaligArgumentException( 'Must be set' );
		$this->curl->setOption( CURLOPT_USERAGENT, $string );
	}

def options(self, *args, **kwargs):
        '''

        '''
        # Allow X-Auth-Token in requests
        request_headers = self.request.headers.get('Access-Control-Request-Headers')
        allowed_headers = request_headers.split(',')

        # Filter allowed header here if needed.

        # Allow request headers
        self.set_header('Access-Control-Allow-Headers', ','.join(allowed_headers))

        # Allow X-Auth-Token in responses
        self.set_header('Access-Control-Expose-Headers', 'X-Auth-Token')

        # Allow all methods
        self.set_header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST')

        self.set_status(204)
        self.finish()

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


Question: Load a dictionary with data from the given table, mapping to record objects.

def recordlookup(table, key, dictionary=None):

    if dictionary is None:
        dictionary = dict()

    it = iter(table)
    hdr = next(it)
    flds = list(map(text_type, hdr))
    keyindices = asindices(hdr, key)
    assert len(keyindices) > 0, 'no key selected'
    getkey = operator.itemgetter(*keyindices)
    for row in it:
        k = getkey(row)
        rec = Record(row, flds)
        if k in dictionary:
            # work properly with shelve
            l = dictionary[k]
            l.append(rec)
            dictionary[k] = l
        else:
            dictionary[k] = [rec]
    return dictionary

def populate_event_que(self, que_obj):

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

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


Question: // SetBlockType sets the BlockType field's value.

func (s *Block) SetBlockType(v string) *Block {
	s.BlockType = &v
	return s
}

public static MBlockPos fromLong(long serialized)
	{
		int j = (int) (serialized << 64 - X_SHIFT - NUM_X_BITS >> 64 - NUM_X_BITS);
		int k = (int) (serialized << 64 - Y_SHIFT - NUM_Y_BITS >> 64 - NUM_Y_BITS);
		int l = (int) (serialized << 64 - NUM_Z_BITS >> 64 - NUM_Z_BITS);
		return new MBlockPos(j, k, l);
	}

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


Question: function to correctly order the arguments this is done because arguments in an incorrect order will cause the soap method to fail

function sortArgs(method, args) {

		// get the method definition
		var def = _.get(_client.types, method.replace(/\_Task$/i, '') + 'RequestType');

		// if found create the definition by calling its function
		if (def) {
			return getFields(def(), args);
		}
		return args;
	}

def prepare_sorting_fields(self):

        if self.sorting_parameter_name in self.request.query_params:
            # Extract sorting parameter from query string
            self._sorting_fields = [
                _.strip() for _ in self.request.query_params.get(self.sorting_parameter_name).split(',')
            ]

        if self._sorting_fields:
            # Create a list of sorting parameters. Each parameter is a tuple: (field:str, descending:bool)
            self._sorting_fields = [
                (self.sorting_fields_map.get(field.lstrip('-'), field.lstrip('-')), field[0] == '-')
                for field in self._sorting_fields
            ]

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


Question:
Emit Python code for the phone number metadata to the given file, and
        to a data/ subdirectory in the same directory as that file.

def emit_metadata_py(self, datadir, module_prefix):
        """"""

        if not os.path.isdir(datadir):
            os.mkdir(datadir)
        modulefilename = os.path.join(datadir, '__init__.py')

        # First, generate all of the individual per-region files in that directory
        for country_id in sorted(self.territory.keys()):
            filename = os.path.join(datadir, "region_%s.py" % country_id)
            self.emit_metadata_for_region_py(country_id, filename, module_prefix)

        # Same for any per-country-code alternate format files
        if self.alt_territory is not None:
            for country_code in sorted(self.alt_territory.keys()):
                filename = os.path.join(datadir, "alt_format_%s.py" % country_code)
                self.emit_alt_formats_for_cc_py(country_code, filename, module_prefix)

        # Now build a module file that includes them all
        with open(modulefilename, "w") as outfile:
            prnt(METADATA_FILE_PROLOG, file=outfile)
            prnt(COPYRIGHT_NOTICE, file=outfile)
            prnt(METADATA_FILE_IMPORT % {'module': module_prefix}, file=outfile)
            nongeo_codes = []
            country_codes = []
            for country_id in sorted(self.territory.keys()):
                terrobj = self.territory[country_id]
                if terrobj.o.id == REGION_CODE_FOR_NON_GEO_ENTITY:
                    nongeo_codes.append(country_id)  # int
                else:
                    country_codes.append("'%s'" % country_id)  # quoted string
            prnt("_AVAILABLE_REGION_CODES = [%s]" % ",".join(country_codes), file=outfile)
            if len(nongeo_codes) > 0:
                prnt("_AVAILABLE_NONGEO_COUNTRY_CODES = [%s]" % ", ".join(nongeo_codes), file=outfile)
            register_prefix = "short_" if self.short_data else ""
            prnt(METADATA_FILE_LOOP % {'prefix': register_prefix}, file=outfile)
            if len(nongeo_codes) > 0:
                prnt(METADATA_NONGEO_FILE_LOOP, file=outfile)

            if self.alt_territory is not None:
                for country_code in sorted(self.alt_territory.keys()):
                    prnt("from .alt_format_%s import PHONE_ALT_FORMAT_%s" % (country_code, country_code), file=outfile)
                prnt("_ALT_NUMBER_FORMATS = {%s}" %
                     ", ".join(["%s: PHONE_ALT_FORMAT_%s" % (cc, cc) for cc in sorted(self.alt_territory.keys())]),
                     file=outfile)

            # Build up a map from country code (int) to list of region codes (ISO 3166-1 alpha 2)
            country_code_to_region_code = {}
            for country_id in sorted(self.territory.keys()):
                terrobj = self.territory[country_id]
                if terrobj.o.country_code is not None:
                    country_code = int(terrobj.o.country_code)
                    if country_code not in country_code_to_region_code:
                        country_code_to_region_code[country_code] = []
                    if terrobj.o.main_country_for_code:
                        country_code_to_region_code[country_code].insert(0, terrobj.o.id)
                    else:
                        country_code_to_region_code[country_code].append(terrobj.o.id)

            # Emit the mapping from country code to region code if nonempty.
            if len(country_code_to_region_code.keys()) > 0:
                prnt(_COUNTRY_CODE_TO_REGION_CODE_PROLOG, file=outfile)
                prnt("_COUNTRY_CODE_TO_REGION_CODE = {", file=outfile)
                for country_code in sorted(country_code_to_region_code.keys()):
                    country_ids = country_code_to_region_code[country_code]
                    prnt('    %d: ("%s",),' % (country_code, '", "'.join(country_ids)), file=outfile)
                prnt("}", file=outfile)

def header_match(cls, header):
        '''

        '''
        mo = cls.header_re.match(header)
        if mo is None:
            msg = f'Expected {cls.header_re.pattern!r}, got {header!r}'
            raise ValueError(msg)
        return {
            'name': mo['name'].decode().strip(),
            'label': mo['label'].decode().strip(),
            'type': mo['type'].decode().strip(),
            'created': strptime(mo['created']),
            'modified': strptime(mo['modified']),
            'sas_version': float(mo['version']),
            'os_version': mo['os'].decode().strip(),
            'namestr_size': mo['descriptor_size'],
        }

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


Question:
Convenience function to stop this servlet.

@throws ServerLifecycleException If the servlet could not be stopped for any unexpected reason.

public void stop() throws ServerLifecycleException {
		try {
			contextHandler.stop();
			contextHandlerCollection.removeHandler(contextHandler);
			contextHandlerCollection.mapContexts();
			LOG.info("WebDavServlet stopped: " + contextPath);
		} catch (Exception e) {
			throw new ServerLifecycleException("Servlet couldn't be stopped", e);
		}
	}

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;
    }

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


Question:
Create and start server.

@throws Exception
when server cannot be started.

public static void start() throws Exception {
        MetricRegistry registry = new MetricRegistry();

        QueuedThreadPool threadPool = new InstrumentedQueuedThreadPool(registry);
        threadPool.setName("esigate");
        threadPool.setMaxThreads(maxThreads);
        threadPool.setMinThreads(minThreads);

        srv = new Server(threadPool);
        srv.setStopAtShutdown(true);
        srv.setStopTimeout(5000);

        // HTTP Configuration
        HttpConfiguration httpConfig = new HttpConfiguration();
        httpConfig.setOutputBufferSize(outputBufferSize);
        httpConfig.setSendServerVersion(false);
        Timer processTime = registry.timer("processTime");

        try (ServerConnector connector =
                new InstrumentedServerConnector("main", EsigateServer.port, srv, registry,
                        new InstrumentedConnectionFactory(new HttpConnectionFactory(httpConfig), processTime));
                ServerConnector controlConnector = new ServerConnector(srv)) {

            // Main connector
            connector.setIdleTimeout(EsigateServer.idleTimeout);
            connector.setSoLingerTime(-1);
            connector.setName("main");
            connector.setAcceptQueueSize(200);

            // Control connector
            controlConnector.setHost("127.0.0.1");
            controlConnector.setPort(EsigateServer.controlPort);
            controlConnector.setName("control");

            srv.setConnectors(new Connector[] {connector, controlConnector});
            // War
            ProtectionDomain protectionDomain = EsigateServer.class.getProtectionDomain();
            String warFile = protectionDomain.getCodeSource().getLocation().toExternalForm();
            String currentDir = new File(protectionDomain.getCodeSource().getLocation().getPath()).getParent();

            File workDir = resetTempDirectory(currentDir);

            WebAppContext context = new WebAppContext(warFile, EsigateServer.contextPath);
            context.setServer(srv);
            context.setTempDirectory(workDir);
            if (StringUtils.isNoneEmpty(sessionCookieName)) {
                context.getSessionHandler().getSessionManager().getSessionCookieConfig().setName(sessionCookieName);
            }
            // Add extra classpath (allows to add extensions).
            if (EsigateServer.extraClasspath != null) {
                context.setExtraClasspath(EsigateServer.extraClasspath);
            }

            // Add the handlers
            HandlerCollection handlers = new HandlerList();
            // control handler must be the first one.
            // Work in progress, currently disabled.
            handlers.addHandler(new ControlHandler(registry));
            InstrumentedHandler ih = new InstrumentedHandler(registry);
            ih.setName("main");
            ih.setHandler(context);
            handlers.addHandler(ih);

            srv.setHandler(handlers);
            srv.start();
            srv.join();

        }

    }

public static function onStart($serv) {
		self::setProcessName(Yesf::app()->getConfig('name', Yesf::CONF_PROJECT) . ' master');
		$pidPath = rtrim(Yesf::app()->getConfig('pid', Yesf::CONF_SERVER), '/') . '/';
		try {
			file_put_contents($pidPath . Yesf::app()->getConfig('name', Yesf::CONF_PROJECT) . '_master.pid', $serv->master_pid);
			file_put_contents($pidPath . Yesf::app()->getConfig('name', Yesf::CONF_PROJECT) . '_manager.pid', $serv->manager_pid);
		} catch (\Exception $e) {
			//忽略写入错误
		}
	}

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


Question: GET /links/:slug

def link_detail(slug)
      slug = slug.slug if slug.instance_of? Instamojo::Link
      get("links/#{slug}")
      @response.success? ? Instamojo::Link.new(@response.body[:link], self) : @response
    end

def system_shorten_url(input_params={}, always_retry=True, **kwargs):

    return DXHTTPRequest('/system/shortenURL', input_params, always_retry=always_retry, **kwargs)

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


public Response get(String uri) throws IntegrationException {
        Request request = RequestFactory.createCommonGetRequest(uri);
        return execute(request);
    }

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


Question: Ensure that a valid value for page size is chosen.

def validate_page_size(ctx, param, value):
    """"""
    # pylint: disable=unused-argument
    if value == 0:
        raise click.BadParameter("Page size must be non-zero or unset.", param=param)
    return value

public void setDocumentSize(int v) {
    if (SourceDocumentInformation_Type.featOkTst && ((SourceDocumentInformation_Type)jcasType).casFeat_documentSize == null)
      jcasType.jcas.throwFeatMissing("documentSize", "org.apache.uima.examples.SourceDocumentInformation");
    jcasType.ll_cas.ll_setIntValue(addr, ((SourceDocumentInformation_Type)jcasType).casFeatCode_documentSize, v);}

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


Question:
Create an update query from old and new values of a document

@param   array   $old        Old values of document
@param   array   $new        New values of document
@param   string  $prefix
@return  void

public function createUpdateQuery($old, $new, $prefix = "")
    {
        $update = [];

        foreach ($new as $key => $value) {
            if (is_array($old) && array_key_exists($key, $old)) {
                if (is_array($value) && strstr(key($value), '$') !== false) {
                    $update[key($value)][$prefix . $key] = $value[key($value)];
                } elseif (is_array($value) && is_array($old[$key])) {
                    if (!empty($old[$key])) {
                        $embeddedUpdate = array_merge_recursive($update, $this->createUpdateQuery($old[$key], $value, $prefix . $key . "."));
                        if (isset($embeddedUpdate['$unset']) && array_values($old[$key]) === $old[$key] && $value !== null && count(array_filter(array_keys($value), 'is_string')) == 0) {
                            $update['$set'][$prefix . $key] = array_values($value);
                        } else {
                            foreach ($embeddedUpdate as $updateOperator => $value) {
                                if (!isset($update[$updateOperator])) {
                                    $update[$updateOperator] = [];
                                }
                                $update[$updateOperator] += $value;
                            }
                        }
                    } elseif (!empty($value)) {
                        $update['$set'][$prefix . $key] = $value;
                    }
                } else {
                    if ($value !== null && $value !== $old[$key]) {
                        if ($value instanceof \MongoDB\BSON\UTCDateTime && $old[$key] instanceof \MongoDB\BSON\UTCDateTime) {
                            if (serialize($value) != serialize($old[$key])) {
                                $update['$set'][$prefix . $key] = $value;
                            }
                        } else {
                            $update['$set'][$prefix . $key] = $value;
                        }
                    } elseif ($value === null && $old[$key] !== null) {
                        $update['$unset'][$prefix . $key] = 1;
                    }
                }
            } else {
                if (is_array($value) && strstr(key($value), '$') === false) {
                    $embeddedQuery = $this->createUpdateQuery([], $value, $prefix . $key . ".");
                    if (count($embeddedQuery) == 1 && key($embeddedQuery) == '$set') {
                        $update['$set'][$prefix . $key] = $value;
                    } else {
                        $update = array_merge_recursive($update, $embeddedQuery);
                    }
                } elseif (is_array($value) && strstr(key($value), '$') !== false) {
                    $update[key($value)][$prefix . $key] = $value[key($value)];
                } else {
                    $update['$set'][$prefix . $key] = $value;
                }
            }

            unset($new[$key]);
            unset($old[$key]);
        }
        if (is_array($old)) {
            foreach (array_keys($old) as $key) {
                $update['$unset'][$prefix . $key] = 1;
            }
        }

        if (isset($update['$set']['_id'])) {
            unset($update['$set']['_id']);
        }

        foreach ($update as $modifier => $value) {
            if (empty($value)) {
                unset($update[$modifier]);
            }
        }

        return $update;
    }

def format(args):

    from jcvi.formats.obo import load_GODag, validate_term

    valid_multiparent_ops = ["split", "merge"]

    p = OptionParser(format.__doc__)

    g1 = OptionGroup(p, "Parameter(s) used to modify GFF attributes (9th column)")
    g1.add_option("--name", help="Add Name attribute from two-column file [default: %default]")
    g1.add_option("--note", help="Add Note attribute from two-column file [default: %default]")
    g1.add_option("--add_attribute", dest="attrib_files", help="Add new attribute(s) " + \
                "from two-column file(s); attribute name comes from filename; " + \
                "accepts comma-separated list of files [default: %default]")
    g1.add_option("--add_dbxref", dest="dbxref_files", help="Add new Dbxref value(s) (DBTAG:ID) " + \
                "from two-column file(s). DBTAG comes from filename, ID comes from 2nd column; " + \
                "accepts comma-separated list of files [default: %default]")
    g1.add_option("--nostrict", default=False, action="store_true",
                 help="Disable strict parsing of GFF file and/or mapping file [default: %default]")
    g1.add_option("--remove_attr", dest="remove_attrs", help="Specify attributes to remove; " + \
                "accepts comma-separated list of attribute names [default: %default]")
    g1.add_option("--copy_id_attr_to_name", default=False, action="store_true",
                 help="Copy `ID` attribute value to `Name`, when `Name` is not defined")
    g1.add_option("--invent_name_attr", default=False, action="store_true",
                 help="Invent `Name` attribute for 2nd level child features; " + \
                "Formatted like PARENT:FEAT_TYPE:FEAT_INDEX")
    g1.add_option("--no_keep_attr_order", default=False, action="store_true",
                 help="Do not maintain attribute order [default: %default]")
    p.add_option_group(g1)

    g2 = OptionGroup(p, "Parameter(s) used to modify content within columns 1-8")
    g2.add_option("--seqid", help="Switch seqid from two-column file. If not" + \
                " a file, value will globally replace GFF seqid [default: %default]")
    g2.add_option("--source", help="Switch GFF source from two-column file. If not" + \
                " a file, value will globally replace GFF source [default: %default]")
    g2.add_option("--type", help="Switch GFF feature type from two-column file. If not" + \
                " a file, value will globally replace GFF type [default: %default]")
    g2.add_option("--fixphase", default=False, action="store_true",
                 help="Change phase 1<->2, 2<->1 [default: %default]")
    p.add_option_group(g2)

    g3 = OptionGroup(p, "Other parameter(s) to perform manipulations to the GFF " + \
                 "file content")
    g3.add_option("--unique", default=False, action="store_true",
                 help="Make IDs unique [default: %default]")
    g3.add_option("--chaindup", default=None, dest="duptype",
                 help="Chain duplicate features of a particular GFF3 `type`," + \
                      " sharing the same ID attribute [default: %default]")
    g3.add_option("--multiparents", default=None, choices=valid_multiparent_ops,
                 help="Split/merge identical features (same `seqid`, `source`, `type` " + \
                 "`coord-range`, `strand`, `phase`) mapping to multiple parents " + \
                 "[default: %default]")
    g3.add_option("--remove_feats", help="Comma separated list of features to remove by type" + \
                " [default: %default]")
    g3.add_option("--remove_feats_by_ID", help="List of features to remove by ID;" + \
                " accepts comma-separated list or list file [default: %default]")
    g3.add_option("--gsac", default=False, action="store_true",
                 help="Fix GSAC GFF3 file attributes [default: %default]")
    g3.add_option("--invent_protein_feat", default=False, action="store_true",
                 help="Invent a protein feature span (chain CDS feats)")
    g3.add_option("--process_ftype", default=None, type="str",
                 help="Specify feature types to process; "
                 "accepts comma-separated list of feature types [default: %default]")
    g3.add_option("--gff3", default=False, action="store_true",
                 help="Print output in GFF3 format [default: %default]")
    g3.add_option("--make_gff_store", default=False, action="store_true",
                 help="Store entire GFF file in memory during first iteration [default: %default]")
    p.add_option_group(g3)

    p.set_outfile()
    p.set_SO_opts()

    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    gffile, = args
    mapfile = opts.seqid
    names = opts.name
    note = opts.note
    source = opts.source
    ftype = opts.type
    attrib_files = opts.attrib_files.split(",") if opts.attrib_files else None
    dbxref_files = opts.dbxref_files.split(",") if opts.dbxref_files else None
    remove_attrs = opts.remove_attrs.split(",") if opts.remove_attrs else None
    process_ftype = opts.process_ftype.split(",") if opts.process_ftype else None
    gsac = opts.gsac
    assert not (opts.unique and opts.duptype), \
        "Cannot use `--unique` and `--chaindup` together"
    assert not(opts.type and opts.duptype), \
        "Cannot use `--type` and `--chaindup` together"
    unique = opts.unique
    duptype = opts.duptype
    fixphase = opts.fixphase
    phaseT = {"1":"2", "2":"1"}
    remove_feats = opts.remove_feats.split(",") if opts.remove_feats else None
    remove_feats_by_ID = None
    if opts.remove_feats_by_ID:
        remove_feats_by_ID = LineFile(opts.remove_feats_by_ID, load=True).lines \
                if op.isfile(opts.remove_feats_by_ID) else \
                opts.remove_feats_by_ID.split(",")
    strict = False if opts.nostrict else True
    make_gff_store = True if gffile in ("-", "stdin") else opts.make_gff_store
    assert not (opts.copy_id_attr_to_name and opts.invent_name_attr), \
        "Cannot use `--copy_id_attr_to_name` and `--invent_name_attr` together"
    copy_id_attr_to_name = opts.copy_id_attr_to_name
    invent_name_attr = opts.invent_name_attr
    invent_protein_feat = opts.invent_protein_feat
    compute_signature = False

    outfile = opts.outfile

    mapping = None
    mod_attrs = set()
    if mapfile and op.isfile(mapfile):
        mapping = DictFile(mapfile, delimiter="\t", strict=strict)
        mod_attrs.add("ID")
    if note:
        note = DictFile(note, delimiter="\t", strict=strict)
        mod_attrs.add("Note")
    if source and op.isfile(source):
        source = DictFile(source, delimiter="\t", strict=strict)
    if ftype and op.isfile(ftype):
        ftype = DictFile(ftype, delimiter="\t", strict=strict)
    if names:
        names = DictFile(names, delimiter="\t", strict=strict)
        mod_attrs.add("Name")

    if attrib_files:
        attr_values = {}
        for fn in attrib_files:
            attr_name = op.basename(fn).rsplit(".", 1)[0]
            if attr_name not in reserved_gff_attributes:
                attr_name = attr_name.lower()
            attr_values[attr_name] = DictFile(fn, delimiter="\t", strict=strict)
            mod_attrs.add(attr_name)
    if dbxref_files:
        dbxref_values = {}
        for fn in dbxref_files:
            dbtag = op.basename(fn).rsplit(".", 1)[0]
            dbxref_values[dbtag] = DictFile(fn, delimiter="\t", strict=strict)
        mod_attrs.add("Dbxref")

    if remove_attrs:
        mod_remove_attrs = []
        for remove_attr in remove_attrs:
            if remove_attr in mod_attrs:
                mod_remove_attrs.append(remove_attr)

        if mod_remove_attrs:
            logging.error("Attributes `{0}` cannot be removed and modified".format( \
                    ",".join(mod_remove_attrs)))
            sys.exit()

    if gsac:  # setting gsac will force IDs to be unique
        unique = True
        notes = {}

    remove = set()
    if unique or duptype or remove_feats or remove_feats_by_ID \
            or opts.multiparents == "merge" or invent_name_attr or make_gff_store \
            or invent_protein_feat:
        if unique:
            dupcounts = defaultdict(int)
            seen = defaultdict(int)
            newparentid = {}
        elif duptype:
            dupranges = AutoVivification()
            skip = defaultdict(int)
        if opts.multiparents == "merge":
            merge_feats = AutoVivification()
        if invent_name_attr:
            ft = GffFeatureTracker()
        elif copy_id_attr_to_name:
            pass
        if invent_protein_feat:
            cds_track = {}
        if opts.multiparents == "merge" or invent_name_attr:
            make_gff_store = compute_signature = True
        gff = Gff(gffile, keep_attr_order=(not opts.no_keep_attr_order), \
                make_gff_store=make_gff_store, compute_signature=compute_signature, \
                strict=strict)
        for g in gff:
            if process_ftype and g.type not in process_ftype:
                continue
            id = g.accn
            if remove_feats and g.type in remove_feats:
                remove.add(id)
            if remove_feats_by_ID and id in remove_feats_by_ID:
                remove.add(id)
            if unique:
                dupcounts[id] += 1
            elif duptype and g.type == duptype:
                dupranges[g.seqid][id][g.idx] = (g.start, g.end)
            if opts.multiparents == "merge" and g.type != "CDS": #don't merge CDS
                pp = g.get_attr("Parent", first=False)
                if pp and len(pp) > 0:
                    for parent in pp:
                        if parent not in remove:
                            sig = g.sign
                            if sig not in merge_feats:
                                merge_feats[sig]['parents'] = []
                            if parent not in merge_feats[sig]['parents']:
                                merge_feats[sig]['parents'].append(parent)
            if invent_name_attr:
                parent, iso = atg_name(g.get_attr("Parent"), retval="locus,iso")
                if not parent:
                    parent = g.get_attr("Parent")
                ft.track(parent, g)
            if invent_protein_feat:
                if g.type == 'CDS':
                    cds_parent = g.get_attr("Parent")
                    if cds_parent not in cds_track:
                        cds_track[cds_parent] = []
                    cds_track[cds_parent].append((g.start, g.end))

    if opts.verifySO:
        so = load_GODag()
        valid_soterm = {}

    fw = must_open(outfile, "w")
    if not make_gff_store:
        gff = Gff(gffile, keep_attr_order=(not opts.no_keep_attr_order), \
                strict=strict)
    for g in gff:
        if process_ftype and g.type not in process_ftype:
            print(g, file=fw)
            continue

        id = g.accn

        if opts.multiparents == "merge" and g.type != "CDS": #don't merge CDS
            sig = g.sign
            if len(merge_feats[sig]['parents']) > 1:
                if 'candidate' not in merge_feats[sig]:
                    merge_feats[sig]['candidate'] = id
                    g.set_attr("Parent", merge_feats[sig]['parents'])
                else:
                    continue

        if remove_feats or remove_feats_by_ID:
            if id in remove:
                continue
            else:
                if "Parent" in g.attributes:
                    keep, parent = [], g.get_attr("Parent", first=False)
                    for i, pid in enumerate(parent):
                        if pid not in remove:
                            keep.append(parent[i])
                        else:
                            remove.add(id)
                    if len(keep) == 0:
                        continue
                    parent = g.set_attr("Parent", keep)

        if remove_attrs:
            for remove_attr in remove_attrs:
                if remove_attr in g.attributes:
                    g.set_attr(remove_attr, None)

        if opts.verifySO:
            if g.type not in valid_soterm:
                valid_soterm[g.type] = validate_term(g.type, so=so, method=opts.verifySO)
            ntype = valid_soterm[g.type]
            if ntype and g.type != ntype:
                g.type = ntype

        origid = g.seqid
        if fixphase:
            phase = g.phase
            g.phase = phaseT.get(phase, phase)

        if mapfile:
            if isinstance(mapping, dict):
                if origid in mapping:
                    g.seqid = mapping[origid]
                else:
                    logging.error("{0} not found in `{1}`. ID unchanged.".\
                            format(origid, mapfile))
            else:
                g.seqid = mapfile

        if source:
            if isinstance(source, dict) and g.source in source:
                g.source = source[g.source]
            else:
                g.source = source

        if names:
            if id in names:
                g.set_attr("Name", names[id])

        if note:
            name = g.get_attr("Name")
            tag = None
            if id in note:
                tag = note[id]
            elif name and name in note:
                tag = note[name]

            if tag:
                g.set_attr("Note", tag, update=False)

        if attrib_files:
            for attr_name in attr_values:
                name = g.get_attr("Name")
                if id in attr_values[attr_name]:
                    g.set_attr(attr_name, attr_values[attr_name][id])
                elif name and name in attr_values[attr_name]:
                    g.set_attr(attr_name, attr_values[attr_name][name])

        if dbxref_files:
            for dbtag in dbxref_values:
                if id in dbxref_values[dbtag]:
                    g.set_attr("Dbxref", dbxref_values[dbtag][id], dbtag=dbtag, append=True)

        if unique:
            if dupcounts[id] > 1:
                seen[id] += 1
                old_id = id
                id = "{0}-{1}".format(old_id, seen[old_id])
                newparentid[old_id] = id
                g.set_attr("ID", id)

            if "Parent" in g.attributes:
                parent = g.attributes["Parent"][0]
                if dupcounts[parent] > 1:
                    g.set_attr("Parent", newparentid[parent])

        if duptype:
            if duptype == g.type and len(dupranges[g.seqid][id]) > 1:
                p = sorted(dupranges[g.seqid][id])
                s, e = dupranges[g.seqid][id][p[0]][0:2]  # get coords of first encountered feature
                if g.start == s and g.end == e and p[0] == g.idx:
                    r = [dupranges[g.seqid][id][x] for x in dupranges[g.seqid][id]]
                    g.start, g.end = range_minmax(r)
                else:
                    skip[(g.seqid, g.idx, id, g.start, g.end)] = 1

        if gsac and g.type == "gene":
            notes[id] = g.attributes["Name"]

        if ftype:
            if isinstance(ftype, dict) and g.type in ftype:
                g.type = ftype[g.type]
            else:
                g.type = ftype

        if invent_name_attr:
            ft.store_symbol(g)
            if re.search(ft.ftype, g.type):
                parent, iso = atg_name(g.get_attr("Parent"), retval="locus,iso")
                if not parent:
                    parent = g.get_attr("Parent")
                if parent in ft.tracker:
                    fidx = ft.feat_index(parent, g.type, g.strand, (g.start, g.end, g.sign))
                    symbol = ft.get_symbol(parent)
                    attr = "ID" if symbol == parent else "Name"
                    g.set_attr(attr, "{0}:{1}:{2}".format(symbol, g.type, fidx + 1))
                    if opts.multiparents == "merge" and attr == "Name":
                        g.set_attr("ID", "{0}:{1}:{2}".format(parent, g.type, fidx + 1))
        elif copy_id_attr_to_name:
            if "Name" not in g.attributes.keys():
                g.set_attr("Name", g.get_attr("ID"))

        protein_feat = None
        if invent_protein_feat:
            if g.type == 'mRNA':
                if id in cds_track:
                    pstart, pstop = range_minmax(cds_track[id])
                    protein_feat = GffLine("\t".join(str(x) for x in [g.seqid, g.source, "protein", pstart, pstop, \
                            ".", g.strand, ".", "ID={0}-Protein;Name={0};Derives_from={0}".format(id)]))
            elif g.type == 'CDS':
                parent = g.get_attr("Parent")
                if parent in cds_track:
                    _parent = [parent, "{0}-Protein".format(parent)]
                    g.set_attr("Parent", _parent)

        pp = g.get_attr("Parent", first=False)
        if opts.multiparents == "split" and (pp and len(pp) > 1) and g.type != "CDS":  # separate features with multiple parents
            id = g.get_attr("ID")
            for i, parent in enumerate(pp):
                if id: g.set_attr("ID", "{0}-{1}".format(id, i + 1))
                g.set_attr("Parent", parent, update=True, urlquote=True)
                if gsac:
                    fix_gsac(g, notes)
                print(g, file=fw)
        else:
            if g.gff3 and not opts.gff3:
                opts.gff3 = True
            g.update_attributes(gff3=opts.gff3)
            if gsac:
                fix_gsac(g, notes)
            if duptype == g.type and skip[(g.seqid, g.idx, id, g.start, g.end)] == 1:
                continue
            print(g, file=fw)
            if g.type == 'mRNA' and invent_protein_feat:
                print(protein_feat, file=fw)

    fw.close()

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


Question: Setup logging environment.

protected void setupLogging(@Nullable final Level level) {
    // install JUL adapter
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();

    // conifgure gossip bootstrap loggers with target factory
    Log.configure(LoggerFactory.getILoggerFactory());
    log.debug("Logging setup; level: {}", level);
  }

func (confSrc *MemoryConfigurationSource) DynamicConfigHandler(callback core.DynamicConfigCallback) error {
	confSrc.callback = callback
	openlogging.Info("mem source callback prepared")
	confSrc.CallbackCheck <- true
	return nil
}

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


Question: // Install registers the API group and adds types to a scheme

func Install(scheme *runtime.Scheme) {
	utilruntime.Must(authentication.AddToScheme(scheme))
	utilruntime.Must(v1beta1.AddToScheme(scheme))
	utilruntime.Must(v1.AddToScheme(scheme))
	utilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion))
}

def _isInstalled(fullFname):

    if not fullFname: return False
    if not os.path.exists(fullFname): return False
    instAreas = []
    try:
        import site
        instAreas = site.getsitepackages()
    except:
        pass # python 2.6 and lower don't have site.getsitepackages()
    if len(instAreas) < 1:
        instAreas = [ os.path.dirname(os.__file__) ]
    for ia in instAreas:
        if fullFname.find(ia) >= 0:
            return True
    return False

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


Question:
Allows the caller to refresh the checkEJBApplicationConfiguration
setting from the system property, in case it has changed. <p>

public static void refreshCheckEJBAppConfigSetting()
    {
        svCheckEJBAppConfig = Boolean.getBoolean(svCheckEJBAppConfigName);

        if (TraceComponent.isAnyTracingEnabled() && ejbTc.isDebugEnabled())
            Tr.debug(ejbTc, "refreshValidationMode : " + svCheckEJBAppConfig);
    }

def init_config(self, app):
        """"""
        # Set up API endpoints for records.
        for k in dir(config):
            if k.startswith('RECORDS_REST_'):
                app.config.setdefault(k, getattr(config, k))

        # Resolve the Elasticsearch error handlers
        handlers = app.config['RECORDS_REST_ELASTICSEARCH_ERROR_HANDLERS']
        for k, v in handlers.items():
            handlers[k] = obj_or_import_string(v)

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


Question:
Download the resource at getURL() to the local resource directory, and return the local copy as a File

@return File of the local resource

protected File getResourceFile(){

        URL url = getURL();
        String urlString = url.toString();
        String filename = urlString.substring(urlString.lastIndexOf('/')+1);
        File resourceDir = DL4JResources.getDirectory(ResourceType.RESOURCE, resourceName());
        File localFile = new File(resourceDir, filename);

        String expMD5 = resourceMD5();
        if(localFile.exists()){
            try{
                if(Downloader.checkMD5OfFile(expMD5, localFile)){
                    return localFile;
                }
            } catch (IOException e){
                //Ignore
            }
            //MD5 failed
            localFile.delete();
        }

        //Download
        try {
            Downloader.download(resourceName(), url, localFile, expMD5, 3);
        } catch (IOException e){
            throw new RuntimeException("Error downloading labels",e);
        }

        return localFile;
    }

private static InputStream inputStreamFromAssets(GraphicFactory graphicFactory, String relativePathPrefix, String src) throws IOException {
        InputStream inputStream = null;
        try {
            inputStream = graphicFactory.platformSpecificSources(relativePathPrefix, src);
        } catch (IOException e) {
        }
        if (inputStream != null) {
            return inputStream;
        }
        return null;
    }

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


Question:
Setup terminal and initialize curses. Most of this copied from
    curses.wrapper in order to convert the wrapper into a context manager.

def curses_session():

    try:
        # Curses must wait for some time after the Escape key is pressed to
        # check if it is the beginning of an escape sequence indicating a
        # special key. The default wait time is 1 second, which means that
        # http://stackoverflow.com/questions/27372068
        os.environ['ESCDELAY'] = '25'

        # Initialize curses
        stdscr = curses.initscr()

        # Turn off echoing of keys, and enter cbreak mode, where no buffering
        # is performed on keyboard input
        curses.noecho()
        curses.cbreak()

        # In keypad mode, escape sequences for special keys (like the cursor
        # keys) will be interpreted and a special value like curses.KEY_LEFT
        # will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have color; user
        # can test with has_color() later on.  The try/catch works around a
        # minor bit of over-conscientiousness in the curses module -- the error
        # return from C start_color() is ignorable.
        try:
            curses.start_color()
            curses.use_default_colors()
        except:
            _logger.warning('Curses failed to initialize color support')

        # Hide the blinking cursor
        try:
            curses.curs_set(0)
        except:
            _logger.warning('Curses failed to initialize the cursor mode')

        yield stdscr

    finally:
        if 'stdscr' in locals():
            stdscr.keypad(0)
            curses.echo()
            curses.nocbreak()
            curses.endwin()

public static function run($version, $deployFile)
    {
        // Init Deployer
        $console = new Application('Deployer', $version);
        $input = new ArgvInput();
        $output = new ConsoleOutput();
        $deployer = new self($console);

        // Pretty-print uncaught exceptions in symfony-console
        set_exception_handler(function ($e) use ($input, $output, $deployer) {
            $io = new SymfonyStyle($input, $output);
            $io->block($e->getMessage(), get_class($e), 'fg=white;bg=red', ' ', true);
            $io->block($e->getTraceAsString());

            $deployer->logger->log('['. get_class($e) .'] '. $e->getMessage());
            $deployer->logger->log($e->getTraceAsString());
            exit(1);
        });

        // Require deploy.php file
        if (is_readable($deployFile)) {
            // Prevent variable leak into deploy.php file
            call_user_func(function () use ($deployFile) {
                require $deployFile;
            });
        }

        // Run Deployer
        $deployer->init();
        $console->run($input, $output);
    }

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


Question:
Check if asynchronous backup and restore mode is
enabled at system level.

@return bool $async True if async mode enabled false otherwise.

static public function is_async_enabled() {
        global $CFG;

        $async = false;
        if (!empty($CFG->enableasyncbackup)) {
            $async = true;
        }

        return $async;
    }

def create_replica(self, clone_member):

        self.set_state('creating replica')
        self._sysid = None

        is_remote_master = isinstance(clone_member, RemoteMember)
        create_replica_methods = is_remote_master and clone_member.create_replica_methods

        # get list of replica methods either from clone member or from
        # the config. If there is no configuration key, or no value is
        # specified, use basebackup
        replica_methods = (
            create_replica_methods
            or self._create_replica_methods
            or ['basebackup']
        )

        if clone_member and clone_member.conn_url:
            r = clone_member.conn_kwargs(self._replication)
            connstring = 'postgres://{user}@{host}:{port}/{database}'.format(**r)
            # add the credentials to connect to the replica origin to pgpass.
            env = self.write_pgpass(r)
        else:
            connstring = ''
            env = os.environ.copy()
            # if we don't have any source, leave only replica methods that work without it
            replica_methods = \
                [r for r in replica_methods if self.replica_method_can_work_without_replication_connection(r)]

        # go through them in priority order
        ret = 1
        for replica_method in replica_methods:
            with self._cancellable_lock:
                if self._is_cancelled:
                    break
            # if the method is basebackup, then use the built-in
            if replica_method == "basebackup":
                ret = self.basebackup(connstring, env, self.config.get(replica_method, {}))
                if ret == 0:
                    logger.info("replica has been created using basebackup")
                    # if basebackup succeeds, exit with success
                    break
            else:
                if not self.data_directory_empty():
                    if self.config.get(replica_method, {}).get('keep_data', False):
                        logger.info('Leaving data directory uncleaned')
                    else:
                        self.remove_data_directory()

                cmd = replica_method
                method_config = {}
                # user-defined method; check for configuration
                # not required, actually
                if self.config.get(replica_method, {}):
                    method_config = self.config[replica_method].copy()
                    # look to see if the user has supplied a full command path
                    # if not, use the method name as the command
                    cmd = method_config.pop('command', cmd)

                # add the default parameters
                if not method_config.get('no_params', False):
                    method_config.update({"scope": self.scope,
                                          "role": "replica",
                                          "datadir": self._data_dir,
                                          "connstring": connstring})
                else:
                    for param in ('no_params', 'no_master', 'keep_data'):
                        method_config.pop(param, None)
                params = ["--{0}={1}".format(arg, val) for arg, val in method_config.items()]
                try:
                    # call script with the full set of parameters
                    ret = self.cancellable_subprocess_call(shlex.split(cmd) + params, env=env)
                    # if we succeeded, stop
                    if ret == 0:
                        logger.info('replica has been created using %s', replica_method)
                        break
                    else:
                        logger.error('Error creating replica using method %s: %s exited with code=%s',
                                     replica_method, cmd, ret)
                except Exception:
                    logger.exception('Error creating replica using method %s', replica_method)
                    ret = 1

        self.set_state('stopped')
        return ret

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


Question:
// GetString returns the default string value for an auto configured field.
// When not set, "" is returned.

func (tag PluginStructTag) GetString() string {
	tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault)
	if !tagSet {
		return ""
	}
	return tstrings.Unescape(tagValue)
}

protected function _setup($config) {
        if (empty($config['createdField'])) {
            $config['createdField'] = 'created';
        }
        if (empty($config['modifiedField'])) {
            $config['modifiedField'] = 'modified';
        }
        $this->_fields = $config;
    }

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


Question:
Set cover / Weighted Maximum Cover exact algorithm

    https://en.wikipedia.org/wiki/Maximum_coverage_problem

def setcover_ilp(candidate_sets_dict, items=None, set_weights=None, item_values=None, max_weight=None, verbose=False):

    import utool as ut
    import pulp
    if items is None:
        items = ut.flatten(candidate_sets_dict.values())
    if set_weights is None:
        set_weights = {i: 1 for i in candidate_sets_dict.keys()}
    if item_values is None:
        item_values = {e: 1 for e in items}

    if max_weight is None:
        max_weight = sum(ut.take(set_weights, candidate_sets_dict.keys()))

    if False:
        # This is true set coer
        # Formulate integer program
        prob = pulp.LpProblem("Set Cover", pulp.LpMinimize)
        # Solution variable indicates if set it chosen or not
        set_indices = candidate_sets_dict.keys()
        x = pulp.LpVariable.dicts(name='x', indexs=set_indices,
                                  lowBound=0, upBound=1, cat=pulp.LpInteger)
        # minimize the number of sets
        prob.objective = sum(x[i] for i in set_indices)
        # subject to
        for e in items:
            # each element is covered
            containing_sets = [i for i in set_indices if e in candidate_sets_dict[i]]
            prob.add(sum(x[i] for i in containing_sets) >= 1)
        # Solve using with solver like CPLEX, GLPK, or SCIP.
        #pulp.CPLEX().solve(prob)
        pulp.PULP_CBC_CMD().solve(prob)
        # Read solution
        solution_keys = [i for i in set_indices if x[i].varValue]
        solution_cover = {i: candidate_sets_dict[i] for i in solution_keys}
        # Print summary
        if verbose:
            print(prob)
            print('OPT:')
            print('\n'.join(['    %s = %s' % (x[i].name, x[i].varValue) for i in set_indices]))
            print('solution_cover = %r' % (solution_cover,))
    else:
        prob = pulp.LpProblem("Maximum Cover", pulp.LpMaximize)
        # Solution variable indicates if set it chosen or not
        item_indicies = items
        set_indices = candidate_sets_dict.keys()
        x = pulp.LpVariable.dicts(name='x', indexs=set_indices,
                                  lowBound=0, upBound=1, cat=pulp.LpInteger)
        y = pulp.LpVariable.dicts(name='y', indexs=item_indicies,
                                  lowBound=0, upBound=1, cat=pulp.LpInteger)
        r = pulp.LpVariable.dicts(name='r', indexs=item_indicies)
        # maximize the value of the covered items
        primary_objective = sum(item_values[e] * y[e] for e in item_indicies)
        # minimize the number of sets used (make sure it does not influence the chosen primary objective)
        # This is only possible when values are non-negative
        # TODO: minimize redundency
        min_influence = min(item_values.values())
        secondary_weight = min_influence / (1.1 * len(set_indices))
        secondary_objective = (sum(-x[i] for i in set_indices)) * secondary_weight
        #
        prob.objective = primary_objective + secondary_objective
        # subject to
        # no more than the maximum weight
        prob.add(sum(x[i] * set_weights[i] for i in set_indices) <= max_weight)
        # If an item is chosen than at least one set containing it is chosen
        for e in item_indicies:
            containing_sets = [i for i in set_indices if e in candidate_sets_dict[i]]
            if len(containing_sets) > 0:
                prob.add(sum(x[i] for i in containing_sets) >= y[e])
                # record number of times each item is covered
                prob.add(sum(x[i] for i in containing_sets) == r[e])
        # Solve using with solver like CPLEX, GLPK, or SCIP.
        #pulp.CPLEX().solve(prob)
        pulp.PULP_CBC_CMD().solve(prob)
        # Read solution
        solution_keys = [i for i in set_indices if x[i].varValue]
        solution_cover = {i: candidate_sets_dict[i] for i in solution_keys}
        # Print summary
        if verbose:
            print(prob)
            print('OPT:')
            print('\n'.join(['    %s = %s' % (x[i].name, x[i].varValue) for i in set_indices]))
            print('\n'.join(['    %s = %s' % (y[i].name, y[i].varValue) for i in item_indicies]))
            print('solution_cover = %r' % (solution_cover,))
    return solution_cover

protected function collectFileCoverage(\SimpleXMLElement $file, $root)
    {
        $absolutePath = realpath((string) ($file['path'] ?: $file['name']));

        if (strpos($absolutePath, $root) === false) {
            return;
        }

        $filename = $absolutePath;

        if ($root !== DIRECTORY_SEPARATOR) {
            $filename = str_replace($root, '', $absolutePath);
        }

        return $this->collectCoverage($file, $absolutePath, $filename);
    }

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


Question:
Adds an event listener for all events matching the specified pattern.

This method will lazily register the listener when a matching event is
dispatched.

@param ListenerPattern $pattern

protected function addListenerPattern(ListenerPattern $pattern)
    {
        $this->patterns[$pattern->getEventPattern()][] = $pattern;

        foreach ($this->syncedEvents as $eventName => $_) {
            if ($pattern->test($eventName)) {
                unset($this->syncedEvents[$eventName]);
            }
        }
    }

public void marshall(FilterLogEventsRequest filterLogEventsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(filterLogEventsRequest.getLogGroupName(), LOGGROUPNAME_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getLogStreamNames(), LOGSTREAMNAMES_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getLogStreamNamePrefix(), LOGSTREAMNAMEPREFIX_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getStartTime(), STARTTIME_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getEndTime(), ENDTIME_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getFilterPattern(), FILTERPATTERN_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getLimit(), LIMIT_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getInterleaved(), INTERLEAVED_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:
Establishes connection
@throws \Grace\DBAL\Exception\ConnectionException

private function connect($selectDb = true)
    {
        if (!$this->isPhpEnvironmentSupported()) {
            throw new ConnectionException("Function pg_connect doesn't exist");
        }

        //Can throw warning, if have incorrect connection params
        //So we need '@'
        $this
            ->getLogger()
            ->startConnection('Pgsql connection');
        $connectString  = $this->generateConnectionString($selectDb);
        $this->resource = @\pg_connect($connectString);
        $this
            ->getLogger()
            ->stopConnection();

        if (!$this->resource) {
            $error = \error_get_last();
            throw new ConnectionException('Error ' . $error['message']);
        }
    }

public function createFailedAuthTable($installer, $tableName)
    {
        $emailAuthEdc = $installer->getConnection()->newTable($installer->getTable($tableName));
        $emailAuthEdc = $this->addColumnForFailedAuthTable($emailAuthEdc);
        $emailAuthEdc = $this->addIndexToFailedAuthTable($installer, $emailAuthEdc);
        $emailAuthEdc->setComment('Email Failed Auth Table.');
        $installer->getConnection()->createTable($emailAuthEdc);
    }

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


Question:
Answer the SQL-Clause for a FieldCriteria

@param c FieldCriteria
@param cld ClassDescriptor

private String toSQLClause(FieldCriteria c, ClassDescriptor cld)
    {
        String colName = toSqlClause(c.getAttribute(), cld);
        return colName + c.getClause() + c.getValue();
    }

public function search()
    {
        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('path', $this->path, true);
        $criteria->compare('extension', $this->extension, true);
        $criteria->compare('filename', $this->filename, true);
        $criteria->compare('mimeType', $this->mimeType, true);
        $criteria->compare('byteSize', $this->byteSize, true);
        $criteria->compare('hash', $this->hash, true);
        $criteria->compare('createdAt', $this->createdAt, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

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


Question:
Given an attribute, set what parameters it requires.

@param string $attribute
@param array $value

protected function setRequirementsForAttribute($attribute, array $value)
    {
        $parameters = [];

        foreach ($value as $attrValue) {
            $parameters = array_filter(array_merge(
                $parameters,
                self::getParametersInValue($attrValue)
            ));
        }

        if (!empty($parameters)) {
            $this->requirements[$attribute] = $parameters;
        }
    }

def provide_attr(attr)
      list_item_attr_value = list_item.public_send(attr)

      # Provide user supplied attr
      return list_item_attr_value if list_item_attr_value.present?

      # Provide object supplied attr
      return object_data[attr] if object_available?

      # Provide error - Object is linked but has been deleted
      return 'Object Unavailable' if list_item.object? && !object_available?

      # Provide empty string - no attr supplied and no object linked
      ''
    end

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


Question:
Private: Returns if this request comes from the informed device

 devive - device symbol. It must be previously registered as a device.

def request_device?(device)
      (request.user_agent.to_s.downcase =~ (Mobylette.devices.device(device) || %r{not_to_be_matched_please}) ? true : false)
    end

def visit_Name(self, node, store_as_param=False, **kwargs):
        """"""
        if store_as_param or node.ctx == 'param':
            self.symbols.declare_parameter(node.name)
        elif node.ctx == 'store':
            self.symbols.store(node.name)
        elif node.ctx == 'load':
            self.symbols.load(node.name)

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


Question:
Add delta to total blocking timeout
@param delta The value

public void deltaTotalBlockingTime(long delta)
   {
      if (enabled.get() && delta > 0)
      {
         totalBlockingTime.addAndGet(delta);
         totalBlockingTimeInvocations.incrementAndGet();

         if (delta > maxWaitTime.get())
            maxWaitTime.set(delta);
      }
   }

private ThroughputStatDO throughputStatModelToDo(ThroughputStat throughputStat) {
        ThroughputStatDO throughputStatDO = new ThroughputStatDO();
        throughputStatDO.setId(throughputStat.getId());
        throughputStatDO.setPipelineId(throughputStat.getPipelineId());
        throughputStatDO.setStartTime(throughputStat.getStartTime());
        throughputStatDO.setEndTime(throughputStat.getEndTime());
        throughputStatDO.setType(throughputStat.getType());
        throughputStatDO.setNumber(throughputStat.getNumber());
        throughputStatDO.setSize(throughputStat.getSize());
        throughputStatDO.setGmtCreate(throughputStat.getGmtCreate());
        throughputStatDO.setGmtModified(throughputStat.getGmtModified());
        return throughputStatDO;
    }

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


Question:
Fetches information about a single volume member
        :param username: Member name
        :param api: Api instance
        :return: Member object

def get_member(self, username, api=None):

        api = api if api else self._API

        response = api.get(
            url=self._URL['member'].format(id=self.id, username=username),
        )
        data = response.json()
        return Member(api=api, **data)

public function initialize(DAV\Server $server)
    {
        if ($this->allowUnauthenticatedAccess) {
            $authPlugin = $server->getPlugin('auth');
            if (!$authPlugin) {
                throw new \Exception('The Auth plugin must be loaded before the ACL plugin if you want to allow unauthenticated access.');
            }
            $authPlugin->autoRequireLogin = false;
        }

        $this->server = $server;
        $server->on('propFind', [$this, 'propFind'], 20);
        $server->on('beforeMethod:*', [$this, 'beforeMethod'], 20);
        $server->on('beforeBind', [$this, 'beforeBind'], 20);
        $server->on('beforeUnbind', [$this, 'beforeUnbind'], 20);
        $server->on('propPatch', [$this, 'propPatch']);
        $server->on('beforeUnlock', [$this, 'beforeUnlock'], 20);
        $server->on('report', [$this, 'report']);
        $server->on('method:ACL', [$this, 'httpAcl']);
        $server->on('onHTMLActionsPanel', [$this, 'htmlActionsPanel']);
        $server->on('getPrincipalByUri', function ($principal, &$uri) {
            $uri = $this->getPrincipalByUri($principal);

            // Break event chain
            if ($uri) {
                return false;
            }
        });

        array_push($server->protectedProperties,
            '{DAV:}alternate-URI-set',
            '{DAV:}principal-URL',
            '{DAV:}group-membership',
            '{DAV:}principal-collection-set',
            '{DAV:}current-user-principal',
            '{DAV:}supported-privilege-set',
            '{DAV:}current-user-privilege-set',
            '{DAV:}acl',
            '{DAV:}acl-restrictions',
            '{DAV:}inherited-acl-set',
            '{DAV:}owner',
            '{DAV:}group'
        );

        // Automatically mapping nodes implementing IPrincipal to the
        // {DAV:}principal resourcetype.
        $server->resourceTypeMapping['Sabre\\DAVACL\\IPrincipal'] = '{DAV:}principal';

        // Mapping the group-member-set property to the HrefList property
        // class.
        $server->xml->elementMap['{DAV:}group-member-set'] = 'Sabre\\DAV\\Xml\\Property\\Href';
        $server->xml->elementMap['{DAV:}acl'] = 'Sabre\\DAVACL\\Xml\\Property\\Acl';
        $server->xml->elementMap['{DAV:}acl-principal-prop-set'] = 'Sabre\\DAVACL\\Xml\\Request\\AclPrincipalPropSetReport';
        $server->xml->elementMap['{DAV:}expand-property'] = 'Sabre\\DAVACL\\Xml\\Request\\ExpandPropertyReport';
        $server->xml->elementMap['{DAV:}principal-property-search'] = 'Sabre\\DAVACL\\Xml\\Request\\PrincipalPropertySearchReport';
        $server->xml->elementMap['{DAV:}principal-search-property-set'] = 'Sabre\\DAVACL\\Xml\\Request\\PrincipalSearchPropertySetReport';
        $server->xml->elementMap['{DAV:}principal-match'] = 'Sabre\\DAVACL\\Xml\\Request\\PrincipalMatchReport';
    }

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


Question: // WriteBigFloat to the writer

func (w *Writer) WriteBigFloat(bf *big.Float) {
	w.writeByte(TagDouble)
	var buf [64]byte
	w.write(bf.Append(buf[:0], 'g', -1))
	w.writeByte(TagSemicolon)
}

public static BigFloat cosh(BigFloat x) {
		if (x.isNaN())
			return NaN;
		if (x.isInfinity())
			return POSITIVE_INFINITY;
		if (x.isZero())
			return x.context.ONE;
		return x.context.valueOf(BigDecimalMath.cosh(x.value, x.context.mathContext));
	}

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


Question:
Execute the command.

@return void

public function handle()
    {
        parent::handle();

        if ($this->commandData->getOption('fromTable')) {
            $this->error('fromTable option is now allowed to use with migration generator');

            return;
        }

        $migrationGenerator = new MigrationGenerator($this->commandData);
        $migrationGenerator->generate();

        $this->performPostActionsWithMigration();
    }

protected function registerCommands()
    {
        $this->application->addCommands([
            new BuildCommand($this->viewFactory, $this->filesystem),
            new PostCommand($this->viewFactory, $this->filesystem)
        ]);
    }

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


Question:
Set the warning level.
@param value The warning level by string name. (default, quiet, verbose).

public void setWarning(String value) {
    if ("default".equalsIgnoreCase(value)) {
      this.warningLevel = WarningLevel.DEFAULT;
    } else if ("quiet".equalsIgnoreCase(value)) {
      this.warningLevel = WarningLevel.QUIET;
    } else if ("verbose".equalsIgnoreCase(value)) {
      this.warningLevel = WarningLevel.VERBOSE;
    } else {
      throw new BuildException(
          "Unrecognized 'warning' option value (" + value + ")");
    }
  }

private function configureFormatter(OutputFormatter $formatter)
    {
        $style = new OutputFormatterStyle('yellow', null, ['bold']);
        $formatter->setStyle('pathbold', $style);

        $style = new OutputFormatterStyle('green');
        $formatter->setStyle('localname', $style);

        $style = new OutputFormatterStyle(null, null, ['bold']);
        $formatter->setStyle('node', $style);

        $style = new OutputFormatterStyle('blue', null, ['bold']);
        $formatter->setStyle('templatenode', $style);

        $style = new OutputFormatterStyle('blue', null, []);
        $formatter->setStyle('templateproperty', $style);

        $style = new OutputFormatterStyle(null, null, []);
        $formatter->setStyle('property', $style);

        $style = new OutputFormatterStyle('magenta', null, ['bold']);
        $formatter->setStyle('node-type', $style);

        $style = new OutputFormatterStyle('magenta', null, []);
        $formatter->setStyle('property-type', $style);

        $style = new OutputFormatterStyle(null, null, []);
        $formatter->setStyle('property-value', $style);

        $style = new OutputFormatterStyle(null, 'red', []);
        $formatter->setStyle('exception', $style);
    }

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


Question:
Get A record

    CLI Examples:

    .. code-block:: bash

        salt-call infoblox.get_a name=abc.example.com
        salt-call infoblox.get_a ipv4addr=192.168.3.5

def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts):
    '''

    '''
    data = {}
    if name:
        data['name'] = name
    if ipv4addr:
        data['ipv4addr'] = ipv4addr
    r = get_object('record:a', data=data, **api_opts)
    if r and len(r) > 1 and not allow_array:
        raise Exception('More than one result, use allow_array to return the data')
    return r

public function getServiceAccount(array $options = [])
    {
        $resp = $this->connection->getServiceAccount($options + ['projectId' => $this->projectId]);
        return $resp['email'];
    }

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


Question: Get section level and reset curent xml node according to input header.

function sectionLevel( &$sectionLevel, $headerLevel, &$TagStack, &$currentNode, &$domDocument )
    {
        if ( $sectionLevel < $headerLevel )
        {
            if ( $this->IsStrictHeader )
            {
                $sectionLevel += 1;
            }
            else
            {
                if ( ( $sectionLevel + 1 ) == $headerLevel )
                {
                    $sectionLevel += 1;
                }
                else
                {
                    for ( $i = 1; $i <= ( $headerLevel - $sectionLevel - 1 ); $i++ )
                    {
                        // Add section tag
                        unset( $subNode );
                        $subNode = new DOMElemenetNode( 'section' );
                        $currentNode->appendChild( $subNode );
                        $childTag = $this->SectionArray;
                        $TagStack[] = array( 'TagName' => 'section',
                                             'ParentNodeObject' => &$currentNode,
                                             'ChildTag' => $childTag );
                        $currentNode = $subNode;
                    }
                    $sectionLevel = $headerLevel;
                }
            }
        }
        elseif ( $sectionLevel == $headerLevel )
        {
            $lastNodeArray = array_pop( $TagStack );
            $lastNode = $lastNodeArray['ParentNodeObject'];
            $currentNode = $lastNode;
            $sectionLevel = $headerLevel;
        }
        else
        {
            for ( $i = 1; $i <= ( $sectionLevel - $headerLevel + 1 ); $i++ )
            {
                $lastNodeArray = array_pop( $TagStack );
                $lastTag = $lastNodeArray['TagName'];
                $lastNode = $lastNodeArray['ParentNodeObject'];
                $lastChildTag = $lastNodeArray['ChildTag'];
                $currentNode = $lastNode;
            }
            $sectionLevel = $headerLevel;
        }
        return $currentNode;
    }

private static void anchorToId(Element heading, Element anchor) {

		if ("a".equals(anchor.tagName()) && heading.id().isEmpty()) {
			String aName = anchor.attr("name");
			if (!aName.isEmpty()) {
				// set the anchor name as heading ID
				heading.attr("id", aName);

				// remove the anchor
				anchor.remove();
			}
		}
	}

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


Question:
加密fxml文件

@param url {@link URL}

@return {@link Scene}

@throws IOException 异常

public static Scene loadFxml(URL url) throws IOException {
        logger.info("load fxml from url: " + url);
        BorderPane root = FXMLLoader.load(url);
        return new Scene(root);
    }

public function to(
        $path = null,
        ?array $query = [],
        ?string $fragment = null,
        bool $trailingSlash = false
    ): string {
        return $this->create(null, $this->appUrl, $path, $query, $fragment, $trailingSlash);
    }

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


Question: checks if floating point number are equal to a threshold

def almost_eq(arr1, arr2, thresh=1E-11, ret_error=False):

    error = np.abs(arr1 - arr2)
    passed = error < thresh
    if ret_error:
        return passed, error
    return passed

func getSplitCount(numFeedbacks, remainBuckets int) int {
	// Split more if have more buckets available.
	splitCount := mathutil.Max(remainBuckets, defaultSplitCount)
	return mathutil.Min(splitCount, numFeedbacks/splitPerFeedback)
}

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


Question:
Change the attributes of the tuple.

@param segment the segment.
@param curviline the curviline coordinate.
@param shift the shift distance.

public void set(Segment1D<?, ?> segment, double curviline, double shift) {
		assert segment != null : AssertMessages.notNullParameter(0);
		segmentProperty().set(new WeakReference<>(segment));
		xProperty().set(curviline);
		yProperty().set(shift);
	}

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: // GetName returns the Name field if it's non-nil, zero value otherwise.

func (b *Branch) GetName() string {
	if b == nil || b.Name == nil {
		return ""
	}
	return *b.Name
}

func (m *Meta) Values(i interface{}, cols ...string) []interface{} {
	ptr := reflects.Ptr(i)
	values := make([]interface{}, len(cols))
	for i, f := range cols {
		values[i] = m.fieldMap[f].Get(ptr)
	}
	return values
}

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


Question: // UnmarshalBinary decodes data according to the Intervals.MarshalBinary format.

func (i *Intervals) UnmarshalBinary(data []byte) (err error) {
	d := bytes.Split(data, []byte(";"))
	l := len(d)
	if l == 0 {
		return nil
	}
	if l >= 1 {
		i.start, err = strconv.ParseUint(string(d[0]), 36, 64)
		if err != nil {
			return err
		}
	}
	if l == 1 {
		return nil
	}

	i.ranges = make([][2]uint64, 0, l-1)
	for j := 1; j < l; j++ {
		r := bytes.SplitN(d[j], []byte(","), 2)
		if len(r) < 2 {
			return fmt.Errorf("range %d has less then 2 elements", j)
		}
		start, err := strconv.ParseUint(string(r[0]), 36, 64)
		if err != nil {
			return fmt.Errorf("parsing the first element in range %d: %v", j, err)
		}
		end, err := strconv.ParseUint(string(r[1]), 36, 64)
		if err != nil {
			return fmt.Errorf("parsing the second element in range %d: %v", j, err)
		}
		i.ranges = append(i.ranges, [2]uint64{start, end})
	}

	return nil
}

@Override
    protected int writeBytesWireFormat ( byte[] dst, int dstIndex ) {
        int start = dstIndex;
        if ( this.unlocks != null ) {
            for ( LockingAndXRange lockingAndXRange : this.unlocks ) {
                dstIndex += lockingAndXRange.encode(dst, dstIndex);
            }
        }
        if ( this.locks != null ) {
            for ( LockingAndXRange lockingAndXRange : this.locks ) {
                dstIndex += lockingAndXRange.encode(dst, dstIndex);
            }
        }
        return start - dstIndex;
    }

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


Question:
Reserved for internal framework use. Retrieves a framework attribute.

@param name the attribute name.
@return the framework attribute with the given name.

@Override
	public Object getFwkAttribute(final String name) {
		if (attribMap == null) {
			return null;
		}
		return attribMap.get(name);
	}

private function generateProxyMethod(\ReflectionMethod $method): string
    {
        if ($method->isConstructor()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy method for constructor in class "%s".',
                $method->getDeclaringClass()->getName()
            ));
        }

        if ($method->isStatic()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy method for static method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        if ($method->isPrivate()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy for private method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        $proxyMethodParameters = [];
        $methodParameters = [];

        foreach ($method->getParameters() as $methodParameter) {
            $methodParameters[] = '$'.$methodParameter->getName();

            if ($methodParameter->getClass()) {
                $proxyMethodParameter = sprintf(
                    '\\%s %s',
                    $methodParameter->getClass()->getName(),
                    '$'.$methodParameter->getName()
                );
            } else if ($methodParameter->getType()) {
                $proxyMethodParameter = \sprintf(
                    '%s%s $%s',
                    $methodParameter->getType()->allowsNull() ? '?' : '',
                    $methodParameter->getType()->getName(),
                    $methodParameter->getName()
                );
            } else {
                $proxyMethodParameter = '$'.$methodParameter->getName();
            }

            if ($methodParameter->isOptional()) {
                $proxyMethodParameter .= ' = '.\var_export($methodParameter->getDefaultValue(), true);
            }

            $proxyMethodParameters[] = $proxyMethodParameter;
        }

        if ($method->isPublic()) {
            $availability = 'public';
        } else if ($method->isProtected()) {
            $availability = 'protected';
        } else {
            throw new \RuntimeException(sprintf(
                'Not support availability for method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        $docComment = "/**\n * {@inheritdoc}\n */";
        $returnTypeHint = '';
        $returnResult = "\n\n    return \$result;";

        if ($method->getReturnType()) {
            $returnTypeHint = sprintf(
                ': %s%s%s',
                \class_exists($method->getReturnType()->getName()) ? '\\' : '',
                $method->getReturnType()->allowsNull() ? '?' : '',
                $method->getReturnType()->getName()
            );
        }

        if ($method->getReturnType() && 'void' === $method->getReturnType()->getName()) {
            $returnResult = '';
        }

        $templateVariables = [
            'docComment'            => $docComment,
            'availability'          => $availability,
            'name'                  => $method->getName(),
            'proxyMethodParameters' => \implode(', ', $proxyMethodParameters),
            'parameters'            => \implode(', ', $methodParameters),
            'beginArguments'        => null,
            'rollbackArguments'     => null,
            'commitArguments'       => null,
            'return_type_hint'      => $returnTypeHint,
            'return_result'         => $returnResult,
        ];

        $methodTemplate = $this->getTemplateForProxyMethod();
        $methodCode = $this->replaceVariables($methodTemplate, $templateVariables);
        $methodCode = $this->appendTabulationCharacter($methodCode, 1);

        return $methodCode;
    }

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


Question:
Private method create_basic_request

creates by using private method header_add an general request header.
@param string method
@access private

private function create_basic_request($method) {
        $this->header_add(sprintf('%s %s %s', $method, $this->_path, $this->_protocol));
        $this->header_add(sprintf('Host: %s:%s', $this->_server, $this->_port));
        //$request .= sprintf('Connection: Keep-Alive');
        $this->header_add(sprintf('User-Agent: %s', $this->_user_agent));
        $this->header_add('Connection: TE');
        $this->header_add('TE: Trailers');
        if ($this->_auth == 'basic') {
            $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
        } else if ($this->_auth == 'digest') {
            if ($signature = $this->digest_signature($method)){
                $this->header_add($signature);
            }
        } else if ($this->_auth == 'bearer') {
            $this->header_add(sprintf('Authorization: Bearer %s', $this->oauthtoken));
        }
    }

protected function buildAuthorizationHeaderForTokenRequest(array $extraParameters = [])
    {
        $parameters = $this->getBasicAuthorizationHeaderInfo();
        $parameters = array_merge($parameters, $extraParameters);
        $parameters[ 'oauth_signature' ] = $this->signature->getSignature(
            $this->getRequestTokenEndpoint(),
            $parameters,
            'POST'
        );

        $authorizationHeader = 'OAuth ';
        $delimiter = '';
        foreach ($parameters as $key => $value) {
            $authorizationHeader .= $delimiter . rawurlencode($key) . '="' . rawurlencode($value) . '"';

            $delimiter = ', ';
        }

        return $authorizationHeader;
    }

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


Question:
Creates a link Element to load an external stylesheet

@method stylesheet
@param  {String} arg   URL to stylesheet
@param  {String} media [Optional] Medias the stylesheet applies to
@return {Objecct}      Stylesheet

function ( arg, media ) {
		return element.create( "link", {rel: "stylesheet", type: "text/css", href: arg, media: media || "print, screen"}, utility.$( "head" )[0] );
	}

public function getFormatter($format)
    {
        static $defaultFormatters = [
            self::FORMAT_JSON => 'yii\httpclient\JsonFormatter',
            self::FORMAT_URLENCODED => [
                'class' => 'yii\httpclient\UrlEncodedFormatter',
                'encodingType' => PHP_QUERY_RFC1738
            ],
            self::FORMAT_RAW_URLENCODED => [
                'class' => 'yii\httpclient\UrlEncodedFormatter',
                'encodingType' => PHP_QUERY_RFC3986
            ],
            self::FORMAT_XML => 'yii\httpclient\XmlFormatter',
            self::FORMAT_CURL => 'yii\httpclient\CurlFormatter',
        ];

        if (!isset($this->formatters[$format])) {
            if (!isset($defaultFormatters[$format])) {
                throw new InvalidParamException("Unrecognized format '{$format}'");
            }
            $this->formatters[$format] = $defaultFormatters[$format];
        }

        if (!is_object($this->formatters[$format])) {
            $this->formatters[$format] = Yii::createObject($this->formatters[$format]);
        }

        return $this->formatters[$format];
    }

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


Question: // Called by higher layers to create the plugin SDN node instance

func New(c *OsdnNodeConfig) (*OsdnNode, error) {
	var policy osdnPolicy
	var pluginId int
	var minOvsVersion string
	var useConnTrack bool
	switch strings.ToLower(c.PluginName) {
	case network.SingleTenantPluginName:
		policy = NewSingleTenantPlugin()
		pluginId = 0
	case network.MultiTenantPluginName:
		policy = NewMultiTenantPlugin()
		pluginId = 1
	case network.NetworkPolicyPluginName:
		policy = NewNetworkPolicyPlugin()
		pluginId = 2
		minOvsVersion = "2.6.0"
		useConnTrack = true
	default:
		// Not an OpenShift plugin
		return nil, nil
	}
	klog.Infof("Initializing SDN node of type %q with configured hostname %q (IP %q), iptables sync period %q", c.PluginName, c.Hostname, c.SelfIP, c.IPTablesSyncPeriod.String())

	if useConnTrack && c.ProxyMode != kubeproxyconfig.ProxyModeIPTables {
		return nil, fmt.Errorf("%q plugin is not compatible with proxy-mode %q", c.PluginName, c.ProxyMode)
	}

	// If our CNI config file exists, remove it so that kubelet doesn't think
	// we're ready yet
	os.Remove(filepath.Join(c.CNIConfDir, openshiftCNIFile))

	if err := c.setNodeIP(); err != nil {
		return nil, err
	}

	ovsif, err := ovs.New(kexec.New(), Br0, minOvsVersion)
	if err != nil {
		return nil, err
	}
	oc := NewOVSController(ovsif, pluginId, useConnTrack, c.SelfIP)

	plugin := &OsdnNode{
		policy:             policy,
		kClient:            c.KClient,
		networkClient:      c.NetworkClient,
		recorder:           c.Recorder,
		oc:                 oc,
		podManager:         newPodManager(c.KClient, policy, c.MTU, c.CNIBinDir, oc, c.EnableHostports),
		localIP:            c.SelfIP,
		hostName:           c.Hostname,
		useConnTrack:       useConnTrack,
		iptablesSyncPeriod: c.IPTablesSyncPeriod,
		mtu:                c.MTU,
		egressPolicies:     make(map[uint32][]networkapi.EgressNetworkPolicy),
		egressDNS:          common.NewEgressDNS(),
		kubeInformers:      c.KubeInformers,
		networkInformers:   c.NetworkInformers,
		egressIP:           newEgressIPWatcher(oc, c.SelfIP, c.MasqueradeBit),
		cniDirPath:         c.CNIConfDir,

		runtimeEndpoint: c.RuntimeEndpoint,
		// 2 minutes is the current default value used in kubelet
		runtimeRequestTimeout: 2 * time.Minute,
		// populated on demand
		runtimeService: nil,
	}

	RegisterMetrics()

	return plugin, nil
}

protected function getServer(string $serverType): string
    {
        if (in_array($serverType, array_keys(config('swoole.servers')), true)) {
            return config("swoole.servers.{$serverType}.driver");
        }

        throw new DomainException("The server type: [{$serverType}] not found");
    }

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


Question:
Return the entityset repository.

@return AnDomainAbstractRepository

public function getRepository()
    {
        if (!$this->_repository instanceof AnDomainRepositoryAbstract) {
            if (!$this->_repository instanceof AnServiceIdentifier) {
                $this->setRepository($this->_repository);
            }

            $this->_repository = $this->getService($this->_repository);
        }

        return $this->_repository;
    }

def get_domain_class_collection_attribute_iterator(ent):

    for attr in itervalues_(ent.__everest_attributes__):
        if attr.kind == RESOURCE_ATTRIBUTE_KINDS.COLLECTION:
            yield attr

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


Question:
Return list of Robot Framework -compatible cli-variables parsed
    from ROBOT_-prefixed environment variable

def get_robot_variables():

    prefix = 'ROBOT_'
    variables = []

    def safe_str(s):
        if isinstance(s, six.text_type):
            return s
        else:
            return six.text_type(s, 'utf-8', 'ignore')
    for key in os.environ:
        if key.startswith(prefix) and len(key) > len(prefix):
            variables.append(safe_str(
                '%s:%s' % (key[len(prefix):], os.environ[key]),
            ))
    return variables

def create_arg_file(target, source, env):

    output_name = str(target[0])

    with open(output_name, "w") as outfile:
        for define in env.get('CPPDEFINES', []):
            outfile.write(define + '\n')

        include_folders = target[0].RDirs(tuple(env.get('CPPPATH', [])))
        include_folders.append('.')

        for include_folder in include_folders:
            include_folder = str(include_folder)

            if not include_folder.startswith('build'):
                include_folder = os.path.join('firmware', 'src', include_folder)

            outfile.write('"-I{}"\n'.format(include_folder.replace('\\', '\\\\')))

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


Question: Preprocess the entire Notebook.

def preprocess(
        self, nb: "NotebookNode", resources: dict
    ) -> Tuple["NotebookNode", dict]:
        """"""

        exam_num = resources["exam_num"]
        time = resources["time"]
        date = resources["date"]

        nb.cells.insert(0, new_markdown_cell(source="---"))
        nb.cells.insert(0, new_markdown_cell(source=""))
        nb.cells.insert(0, exam_instructions_cell)
        first_cell_source = (
            "# ME 2233: Thermodynamic Principles\n\n"
            f"# Exam {exam_num} - {time}\n\n# {date}"
        )
        nb.cells.insert(0, new_markdown_cell(source=first_cell_source))

        return nb, resources

def start(self, plugin_name=None, kwargs=None):
        """"""
        self.output = [] # Start basically resets the output data
        super(WorkbenchRenderer, self).start(plugin_name=plugin_name)
        return self

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


Question:
Returns a new instance from an array.

@param array $arr

@return self

public static function fromArray(array $arr): self
    {
        $prop = $arr + (new self($arr['fallback'] ?? ''))->toArray();

        return self::__set_state($prop);
    }

protected function describeProcedures($names, $refresh = false)
    {
        $names = static::validateAsArray(
            $names,
            ',',
            true,
            'The request contains no valid procedure names or properties.'
        );

        $out = [];
        foreach ($names as $name) {
            $out[] = $this->describeProcedure($name, $refresh);
        }

        return $out;
    }

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


Question:
Inserts a call signature at the beginning of the docstring on `dispatcher`.
    The signature is taken from `func` if provided; otherwise `(...)` is used.

def update_docstring(dispatcher, func=None):

    doc = dispatcher.__doc__ or ''
    if inspect.cleandoc(doc).startswith('%s(' % dispatcher.__name__):
        return
    sig = '(...)'
    if func and func.__code__.co_argcount:
        argspec = inspect.getfullargspec(func) # pylint: disable=deprecated-method
        if argspec.args and argspec.args[0] in {'self', 'cls'}:
            argspec.args.pop(0)
        if any(argspec):
            sig = inspect.formatargspec(*argspec) # pylint: disable=deprecated-method
            sig = re.sub(r' at 0x[0-9a-f]{8,16}(?=>)', '', sig)
    sep = '\n' if doc.startswith('\n') else '\n\n'
    dispatcher.__doc__ = dispatcher.__name__ + sig + sep + doc

def drain_events(self, timeout=None):
        """"""
        chanmap = self.channels
        chanid, method_sig, args, content = self._wait_multiple(
            chanmap, None, timeout=timeout,
        )

        channel = chanmap[chanid]

        if (content and
                channel.auto_encode_decode and
                hasattr(content, 'content_encoding')):
            try:
                content.body = content.body.decode(content.content_encoding)
            except Exception:
                pass

        amqp_method = (self._method_override.get(method_sig) or
                       channel._METHOD_MAP.get(method_sig, None))

        if amqp_method is None:
            raise AMQPNotImplementedError(
                'Unknown AMQP method {0!r}'.format(method_sig))

        if content is None:
            return amqp_method(channel, args)
        else:
            return amqp_method(channel, args, content)

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


Question:
Wrap the fetched content in a SimpleHtmlDom object.
This is just an adaptation of SHD::fileGetHtml() method.
@param  string $url
@return SimpleHtmlDom|false

protected function getSHDWrapper($url)
    {
        $content = $this->fetchSerpContent($url);
        // sanity check
        if (GenericValidator::invalidContent($content, self::DEFAULT_MAX_FILE_SIZE))
            return false;
        // create the wrapper
        $dom = new SimpleHtmlDom(null, self::SHD_USE_INCLUDE_PATH,
                                 self::SHD_FORCE_TAGS_CLOSED,
                                 $this->getCharset(), self::SHD_STRIP_RN,
                                 self::SHD_DEFAULT_BR_TEXT,
                                 self::SHD_DEFAULT_SPAN_TEXT);
        // load the fetched content in the wrapper
        $dom->load($content, self::SHD_LOWERCASE, self::SHD_STRIP_RN);
        return $dom;
    }

protected function build($template)
    {
        $this->body['flash'] = array();
        if(isset($_SESSION['flash']['message'])) {
            $this->body['flash']['message'] = $_SESSION['flash']['message'];
            $this->body['flash']['type'] = $_SESSION['flash']['type'];
            unset($_SESSION['flash']);
        }

        $body = $this->parse($template, $this->body);

        $page = array(
            'flash' => $this->body['flash'],
            'meta' => $this->meta,
            'links' => $this->links,
            'styles' => $this->styles,
            'scripts' => $this->scripts,
            'title' => $this->title,
            'class' => $this->id,
            'head' => $this->head,
            'body' => $body,
            'foot' => $this->foot);

        $page = $this->parse($this->layout, $page);

        $this->response
            ->set('headers', 'Content-Type', 'text/html; charset=utf-8')
            ->set('body', $page);

        return $page;
    }

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


Question: Given the value of a pixel, compute which bin in the histogram it belongs in

protected int computeHistogramBin( float value[] ) {
		int indexHistogram = 0;
		int binStride = 1;
		for( int bandIndex = 0; bandIndex < value.length; bandIndex++ ) {
			int bin = (int)(numBins*value[bandIndex]/maxPixelValue);

			indexHistogram += bin*binStride;
			binStride *= numBins;
		}
		return indexHistogram;
	}

public static double quantile(double val, double shape, double location, double scale) {
    return val < 0 || val > 1 ? Double.NaN : scale * FastMath.pow(val / (1. - val), 1. / shape) + location;
  }

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


Question: // SetIdentities sets the Identities field's value.

func (s *GetIdentityDkimAttributesInput) SetIdentities(v []*string) *GetIdentityDkimAttributesInput {
	s.Identities = v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

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


Question:
Execute a text

@param string $text
@param int    $offsetX
@param int    $offsetY
@param float  $opacity
@param int    $color
@param int    $size
@param string $font_file

@return static

public function do_text(
        $text,
        $offsetX = 0,
        $offsetY = 0,
        $opacity = 1.0,
        $color = 0x000000,
        $size = 12,
        $font_file = null
    ) {
        $draw = new \ImagickDraw();
        $textColor = sprintf('rgb(%u,%u,%u)', ($color >> 16) & 0xFF, ($color >> 8) & 0xFF, $color & 0xFF);
        $draw->setFillColor(new \ImagickPixel($textColor));
        if ($font_file) {
            $draw->setFont($this->alias->resolve($font_file));
        }
        $draw->setFontSize($size);
        $draw->setFillOpacity($opacity);
        $draw->setGravity(\Imagick::GRAVITY_NORTHWEST);
        $this->_image->annotateImage($draw, $offsetX, $offsetY, 0, $text);
        $draw->destroy();

        return $this;
    }

function(oValues) {
				var sHighColor = "",
					sMediumColor = "",
					sLowColor = "";

				if (oValues.highCount > 0) {
					sHighColor = "color: " + constants.SUPPORT_ASSISTANT_SEVERITY_HIGH_COLOR + ";";
				}

				if (oValues.mediumCount > 0) {
					sMediumColor = "color: " + constants.SUPPORT_ASSISTANT_SEVERITY_MEDIUM_COLOR + ";";
				}

				if (oValues.lowCount > 0) {
					sLowColor = "color: " + constants.SUPPORT_ASSISTANT_SEVERITY_LOW_COLOR + ";";
				}

				return oValues.name +
					" ( " + oValues.highCount + " " + oValues.highName + ",  " +
					" " + oValues.mediumCount + " " + oValues.mediumName + ",  " +
					" " + oValues.lowCount + " " + oValues.lowName + " )";
			}

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