Question:
Create a record
        :param zone_name: Name of the zone
        :param params: {'fieldType': 'A', 'ttl': 60, 'subDomain': 'www',
        'target': '1.2.3.4'

def create_record(self, zone_name, params):

        self.log.debug('Create record: zone: %s, id %s', zone_name,
                       params)
        return self._client.post('/domain/zone/{}/record'.format(zone_name),
                                 **params)

public function make($identifier, $expireTime = 3600)
    {
        $json = [
            'TLS.account_type' => $this->accountType,
            'TLS.identifier' => (string)$identifier,
            'TLS.appid_at_3rd' => (string)$this->appId,
            'TLS.sdk_appid' => (string)$this->appId,
            'TLS.expire_after' => (string)$expireTime,
            'TLS.version' => '201512300000',
            'TLS.time' => (string)time()
        ];

        $content = $this->genSignatureContent($json);
        $signature = $this->makeSignature($content);
        $json['TLS.sig'] = base64_encode($signature);
        if ($json['TLS.sig'] === false) {
            throw new SignatureException('base64_encode error.');
        }
        $json_text = json_encode($json);
        if ($json_text === false) {
            throw new SignatureException('json_encode error.');
        }
        $compressed = gzcompress($json_text);
        if ($compressed === false) {
            throw new SignatureException('gzcompress error.');
        }
        return $this->base64Encode($compressed);

    }

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


Question:
Log in to the server and store these credentials in `authset`.

        Can raise ConnectionFailure or OperationFailure.

        :Parameters:
          - `credentials`: A MongoCredential.

def authenticate(self, credentials):

        auth.authenticate(credentials, self)
        self.authset.add(credentials)

private static Audit doBasicAuditCheck(JSONArray jsonArray, JSONArray global, AuditType auditType) {
        Audit audit = new Audit();
        audit.setType(auditType);
        if (!isConfigured(auditType, global)) {
            audit.setDataStatus(DataStatus.NOT_CONFIGURED);
            audit.setAuditStatus(AuditStatus.NA);
            return audit;
        }
        if (jsonArray == null || CollectionUtils.isEmpty(jsonArray)) {
            audit.setAuditStatus(AuditStatus.NA);
            audit.setDataStatus(DataStatus.NO_DATA);
            return audit;
        }
        if (isCollectorError(jsonArray)) {
            audit.setAuditStatus(AuditStatus.NA);
            audit.setDataStatus(DataStatus.ERROR);
            return audit;
        }
        return null;
    }

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


Question:
Given an existing active OAuth 1 access token, make a Dropbox API call to get a new OAuth 2
access token that represents the same user and app.

public String createOAuth2AccessToken(DbxOAuth1AccessToken token)
        throws DbxException
    {
        if (token == null) throw new IllegalArgumentException("'token' can't be null");
        return DbxRequestUtil.doPostNoAuth(
            requestConfig,
            DbxClientV1.USER_AGENT_ID,
            appInfo.getHost().getApi(),
            "1/oauth2/token_from_oauth1",
            null,
            getHeaders(token),
            new DbxRequestUtil.ResponseHandler<String>() {
                @Override
                public String handle(HttpRequestor.Response response) throws DbxException {
                    if (response.getStatusCode() != 200) throw DbxRequestUtil.unexpectedStatus(response);
                    return DbxRequestUtil.readJsonFromResponse(ResponseReader, response);
                }
            }
        );
    }

func (s *Storage) LoadAuthorize(code string) (*osin.AuthorizeData, error) {

	// Load Authorize from DB
	var authorize service.Authorize
	if err := dbconn.DB.Where("code = ?", code).Find(&authorize).Error; err != nil {
		return nil, err
	}

	// Copy Authorize in OSIN AuthorizeData
	var data osin.AuthorizeData
	copier.Copy(&data, &authorize)

	c, err := s.GetClient(authorize.Client)
	if err != nil {
		return nil, err
	}

	if data.ExpireAt().Before(time.Now()) {
		return nil, errors.Errorf("Token expired at %s.", data.ExpireAt().String())
	}

	data.Client = c
	return &data, nil
}

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


Question: // SetEstimatedNumberOfUsers sets the EstimatedNumberOfUsers field's value.

func (s *UserPoolType) SetEstimatedNumberOfUsers(v int64) *UserPoolType {
	s.EstimatedNumberOfUsers = &v
	return s
}

def click_signal(target_usage, target_vendor_id):
    """"""
    # usually you'll find and open the target device, here we'll browse for the
    # current connected devices
    all_devices = hid.HidDeviceFilter(vendor_id = target_vendor_id).get_devices()

    if not all_devices:
        print("Can't find target device (vendor_id = 0x%04x)!" % target_vendor_id)
    else:
        # search for our target usage
        # target pageId, usageId

        for device in all_devices:
            try:
                device.open()
                # browse output reports, we could search over feature reports also,
                # changing find_output_reports() to find_feature_reports()
                for report in device.find_output_reports():
                    if target_usage in report:
                        # found out target!
                        report[target_usage] = 1 # yes, changing values is that easy
                        # at this point you could change different usages at a time...
                        # and finally send the prepared output report
                        report.send()
                        # now toggle back the signal
                        report[target_usage] = 0
                        report.send()
                        print("\nUsage clicked!\n")
                        return
            finally:
                device.close()
        print("The target device was found, but the requested usage does not exist!\n")

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


Question: // ConfigCreate applies the given config entry update.

func (s *HTTPServer) ConfigApply(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	args := structs.ConfigEntryRequest{
		Op: structs.ConfigEntryUpsert,
	}
	s.parseDC(req, &args.Datacenter)
	s.parseToken(req, &args.Token)

	var raw map[string]interface{}
	if err := decodeBody(req, &raw, nil); err != nil {
		return nil, BadRequestError{Reason: fmt.Sprintf("Request decoding failed: %v", err)}
	}

	if entry, err := structs.DecodeConfigEntry(raw); err == nil {
		args.Entry = entry
	} else {
		return nil, BadRequestError{Reason: fmt.Sprintf("Request decoding failed: %v", err)}
	}

	// Check for cas value
	if casStr := req.URL.Query().Get("cas"); casStr != "" {
		casVal, err := strconv.ParseUint(casStr, 10, 64)
		if err != nil {
			return nil, err
		}
		args.Op = structs.ConfigEntryUpsertCAS
		args.Entry.GetRaftIndex().ModifyIndex = casVal
	}

	var reply bool
	if err := s.agent.RPC("ConfigEntry.Apply", &args, &reply); err != nil {
		return nil, err
	}

	return reply, nil
}

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

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

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

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


Question:
Displays a form to create a new GalleryItem entity.

@Route("/new", name="admin_galleryitem_new")
@Method("GET")
@Template()

public function newAction()
    {
        $entity = new GalleryItem();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

public function visit(Visitor $visitor, Generator $generator, $data)
    {
        $generator->startObjectElement('TagList');
        $visitor->setHeader('Content-Type', $generator->getMediaType('TagList'));

        $generator->startAttribute('href', $data->path);
        $generator->endAttribute('href');

        $generator->startList('Tag');

        foreach ($data->tags as $restTag) {
            $generator->startObjectElement('Tag');
            $generator->startAttribute(
                'href',
                $this->router->generate(
                    'ezpublish_rest_eztags_loadTag',
                    ['tagPath' => trim($restTag->tag->pathString, '/')]
                )
            );
            $generator->endAttribute('href');
            $generator->endObjectElement('Tag');
        }

        $generator->endList('Tag');

        $generator->endObjectElement('TagList');
    }

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


Question:
Bulk export a set of results.

        :param ids: Int list of result IDs.
        :rtype: tuple `(io.BytesIO, 'filename')`

def bulk_export(self, ids, exclude_captures=False):

        return self.service.bulk_export(self.base, ids, params={'exclude_captures': exclude_captures})

def get_cgi_parameter_file(form: cgi.FieldStorage,
                           key: str) -> Optional[bytes]:

    (filename, filecontents) = get_cgi_parameter_filename_and_file(form, key)
    return filecontents

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


Question:
Get the kNN queries for the algorithm.

@param database Database to analyze
@param relation Relation to analyze
@param stepprog Progress logger, may be {@code null}
@return result

protected Pair<KNNQuery<O>, KNNQuery<O>> getKNNQueries(Database database, Relation<O> relation, StepProgress stepprog) {
    KNNQuery<O> knnComp, knnReach;
    if(comparisonDistanceFunction == reachabilityDistanceFunction || comparisonDistanceFunction.equals(reachabilityDistanceFunction)) {
      LOG.beginStep(stepprog, 1, "Materializing neighborhoods with respect to reference neighborhood distance function.");
      knnComp = DatabaseUtil.precomputedKNNQuery(database, relation, comparisonDistanceFunction, MathUtil.max(kcomp, kreach) + 1);
      knnReach = knnComp;
    }
    else {
      LOG.beginStep(stepprog, 1, "Not materializing distance functions, since we request each DBID once only.");
      knnComp = QueryUtil.getKNNQuery(relation, comparisonDistanceFunction, kreach + 1);
      knnReach = QueryUtil.getKNNQuery(relation, reachabilityDistanceFunction, kcomp + 1);
    }
    return new Pair<>(knnComp, knnReach);
  }

def _generate_reversed_sql(self, keys, changed_keys):

        for key in keys:
            if key not in changed_keys:
                continue
            app_label, sql_name = key
            old_item = self.from_sql_graph.nodes[key]
            new_item = self.to_sql_graph.nodes[key]
            if not old_item.reverse_sql or old_item.reverse_sql == RunSQL.noop or new_item.replace:
                continue

            # migrate backwards
            operation = ReverseAlterSQL(sql_name, old_item.reverse_sql, reverse_sql=old_item.sql)
            sql_deps = [n.key for n in self.from_sql_graph.node_map[key].children]
            sql_deps.append(key)
            self.add_sql_operation(app_label, sql_name, operation, sql_deps)

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


Question:
Sets headers that will instruct the client to cache this response.

@return static self reference

public function setCacheHeaders()
    {
        $cacheTime = 31536000; // 1 year
        $this->getHeaders()
            ->set('Expires', gmdate('D, d M Y H:i:s', time() + $cacheTime) . ' GMT')
            ->set('Pragma', 'cache')
            ->set('Cache-Control', 'max-age=' . $cacheTime);

        return $this;
    }

func formatMetaCacheV1(r io.ReadSeeker) (*formatCacheV1, error) {
	format := &formatCacheV1{}
	if err := jsonLoad(r, format); err != nil {
		return nil, err
	}
	return format, nil
}

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


Question:
Return the html tags including the css from the theme

@param string $themeId

@return string

public function openOrchestraCss($themeId)
    {
        $tags = '';

        if (isset($this->themes[$themeId]) && isset($this->themes[$themeId]['stylesheets'])) {
            $stylesheets = $this->themes[$themeId]['stylesheets'];
            foreach ($stylesheets as $stylesheet) {
                $tags .= $this->getHtmlTag($stylesheet, self::FILETYPE_CSS);
            }
        }

        return $tags;
    }

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

        return;
    }

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


Question: // SetBucketARNUpdate sets the BucketARNUpdate field's value.

func (s *S3ReferenceDataSourceUpdate) SetBucketARNUpdate(v string) *S3ReferenceDataSourceUpdate {
	s.BucketARNUpdate = &v
	return s
}

def update_resourcegroup(group,**kwargs):

    group_i                 = _get_group(group.id)
    group_i.name            = group.name
    group_i.description     = group.description
    group_i.status          = group.status

    db.DBSession.flush()

    return group_i

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


Question:
Registers services on the given app.

This method should only be used to configure services and parameters.
It should not get services.
@param Application $app

public function register(Application $app)
    {
        Assertion::isInstanceOf($app, \Alchemy\Phrasea\Application::class);

        $app['setup.validate-config'] = $app->protect(function (Request $request) use ($app) {
            if (0 === strpos($request->getPathInfo(), '/setup')) {
                if (!$app['phraseanet.configuration-tester']->isInstalled()) {
                    if (!$app['phraseanet.configuration-tester']->isBlank()) {
                        if ('setup_upgrade_instructions' !== $app['request']->attributes->get('_route')) {
                            return $app->redirectPath('setup_upgrade_instructions');
                        }
                    }
                } elseif (!$app['phraseanet.configuration-tester']->isBlank()) {
                    return $app->redirectPath('homepage');
                }
            } else {
                if (false === strpos($request->getPathInfo(), '/include/minify')) {
                    $app['firewall']->requireSetup();
                }
            }
        });
    }

func WithClients(
	transportType testutils.TransportType,
	keyValueYARPCServer examplepb.KeyValueYARPCServer,
	sinkYARPCServer examplepb.SinkYARPCServer,
	fooYARPCServer examplepb.FooYARPCServer,
	logger *zap.Logger,
	f func(*Clients) error,
) error {
	var procedures []transport.Procedure
	if keyValueYARPCServer != nil {
		procedures = append(procedures, examplepb.BuildKeyValueYARPCProcedures(keyValueYARPCServer)...)
	}
	if sinkYARPCServer != nil {
		procedures = append(procedures, examplepb.BuildSinkYARPCProcedures(sinkYARPCServer)...)
	}
	if fooYARPCServer != nil {
		procedures = append(procedures, examplepb.BuildFooYARPCProcedures(fooYARPCServer)...)
	}
	return testutils.WithClientInfo(
		"example",
		procedures,
		transportType,
		logger,
		func(clientInfo *testutils.ClientInfo) error {
			return f(
				&Clients{
					examplepb.NewKeyValueYARPCClient(clientInfo.ClientConfig),
					examplepb.NewSinkYARPCClient(clientInfo.ClientConfig),
					examplepb.NewFooYARPCClient(clientInfo.ClientConfig),
					examplepb.NewKeyValueYARPCClient(clientInfo.ClientConfig, protobuf.UseJSON),
					examplepb.NewSinkYARPCClient(clientInfo.ClientConfig, protobuf.UseJSON),
					examplepb.NewFooYARPCClient(clientInfo.ClientConfig, protobuf.UseJSON),
					examplepb.NewKeyValueClient(clientInfo.GRPCClientConn),
					examplepb.NewSinkClient(clientInfo.GRPCClientConn),
					examplepb.NewFooClient(clientInfo.GRPCClientConn),
					clientInfo.ContextWrapper,
				},
			)
		},
	)
}

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


Question:
Interesting events

@param string|Exception $messageOrException
@param array|Exception $contextOrException
@param array $context

public function info($messageOrException, $contextOrException = null, array $context = array()) {
        $this->log(LogLevel::INFO, $messageOrException, $contextOrException, $context);
    }

public function nextSpec($methodName)
    {
        if ($this->pointer >= count($this->chain)) {
            throw new \PHPUnit_Framework_AssertionFailedError("There are no more method calls expected given assigned ordering");
        }
        if ($this->pointer + 1 < count($this->chain)) {
            $next = $this->chain[$this->pointer + 1];
            if ($next[0] === $methodName) {
                // if the next method has the same name as the passed
                // $methodName, then advance the pointer and return the
                // given spec.
                $this->pointer++;

                return $next[1];
            }
        }

        if ($this->pointer === -1) {
            throw new \PHPUnit_Framework_AssertionFailedError(sprintf("Unexpected method invocation %s at call index %s, haven't seen any method calls yet", $methodName, $this->pointer, true));
        }
        $current = $this->chain[$this->pointer];
        if ($current[0] !== $methodName) {
            // if the current spec does not match the method name,
            // we do not have any other possible specs to return
            // so we throw an assertion failure with a print of every
            // method we've run so far:
            $methodsSoFar = [];
            for ($i = 0; $i <= $this->pointer; $i++) {
                $methodsSoFar[] = $this->chain[$i][0];
            }

            throw new \PHPUnit_Framework_AssertionFailedError(sprintf("Unexpected method invocation %s at call index %s, seen method calls so far: %s", $methodName, $this->pointer, print_r(implode($methodsSoFar, "\n"), true)));
        }

        return $current[1];
    }

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


Question:
Create an instance of the SparkPost Swift Transport driver.

@return \Illuminate\Mail\Transport\SparkPostTransport

protected function createSparkPostDriver()
    {
        $config = $this->app['config']->get('services.sparkpost', []);

        return new SparkPostTransport(
            $this->guzzle($config), $config['secret'], $config['options'] ?? []
        );
    }

def submit_offline_reports(self):

        smtp_enabled = bool(self._smtp)
        hq_enabled = bool(self._hq)
        offline_reports = self.get_offline_reports()
        logging.info('Submitting %d offline crash reports' % len(offline_reports))
        offline_reports = offline_reports[:self.send_at_most]

        if smtp_enabled:
            try:
                smtp_success = self._smtp_send_offline_reports(*offline_reports)
            except Exception as e:
                logging.error(e)
                smtp_success = [False] * len(offline_reports)
        else:
            smtp_success = [True] * len(offline_reports)

        if hq_enabled:
            try:
                hq_success = self._hq_send_offline_reports(*offline_reports)
            except Exception as e:
                logging.error(e)
                hq_success = [False] * len(offline_reports)
        else:
            hq_success = [True] * len(offline_reports)

        remaining_reports = self.delete_offline_reports()
        success = [s1 and s2 for (s1, s2) in zip(smtp_success, hq_success)]
        logging.info('%d crash reports successfully submitted' % success.count(True))
        logging.info('%d crash reports remain to be submitted' % len(remaining_reports))
        return all(success)

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


Question: address must a list instance. Or a string which will be transformed into a address

def send_request(self, target: str, *args, **kwargs):

        # TODO: Log error here if not found?
        address = self._get_address_from_source(target)
        if address is None:
            return

        args = json.dumps(args).encode('utf8')
        kwargs = json.dumps(kwargs).encode('utf8')

        # TODO: test that this works
        # NOTE: pop out command?
        frame = (*address, b'', b'MSG', args, kwargs)
        self.add_callback(self.command_socket.send_multipart, frame)

def get_out_ip_addr(cls, tenant_id):

        if tenant_id not in cls.serv_obj_dict:
            LOG.error("Fabric not prepared for tenant %s", tenant_id)
            return
        tenant_obj = cls.serv_obj_dict.get(tenant_id)
        return tenant_obj.get_out_ip_addr()

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


Question:
Use the metadata of `connection` to discover
details about the MongoDB deployment behind it
and persist the results in `store`.

@param {Connection} connection
@param {Function} done - Callback `(err, {Deployment})`
@return {Probe}
@api public

function Probe(connection, done) {
  if (!(this instanceof Probe)) {
    return new Probe(connection, done);
  }

  if (typeof connection === 'string') {
    connection = Connection.from(
      Deployment.getId(connection));
  }
  debug('connection is `%j`', connection);

  this.deployment = new Deployment({
    _id: Instance.getId(connection.getId()),
    name: connection.name
  });

  this.connection = connection;

  this.db = null;
  this.metadata = null;

  if (typeof done === 'function') {
    this.exec(done);
  }
}

def generate_manifest(self, progressbar=None):
        """"""
        items = dict()

        if progressbar:
            progressbar.label = "Generating manifest"

        for handle in self._storage_broker.iter_item_handles():
            key = dtoolcore.utils.generate_identifier(handle)
            value = self._storage_broker.item_properties(handle)
            items[key] = value
            if progressbar:
                progressbar.item_show_func = lambda x: handle
                progressbar.update(1)

        manifest = {
            "items": items,
            "dtoolcore_version": __version__,
            "hash_function": self._storage_broker.hasher.name
        }

        return manifest

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


Question:
// GetSimpleType returns the value of SimpleType if it is set or its
// zero value if it is unset.

func (v *Type) GetSimpleType() (o SimpleType) {
	if v != nil && v.SimpleType != nil {
		return *v.SimpleType
	}

	return
}

public static function setStringFormat(string $format)
    {
        switch ($format) {
            case 'raw':
                self::$format = 'raw';
                break;
            case 'basic':
                self::$format = 'basic';
                break;
            case 'full':
            default:
                self::$format = 'full';
                break;
        }
    }

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


Question:
Add a flush to this {@link ChannelOutboundBuffer}. This means all previous added messages are marked as flushed
and so you will be able to handle them.

public void addFlush() {
        // There is no need to process all entries if there was already a flush before and no new messages
        // where added in the meantime.
        //
        // See https://github.com/netty/netty/issues/2577
        Entry entry = unflushedEntry;
        if (entry != null) {
            if (flushedEntry == null) {
                // there is no flushedEntry yet, so start with the entry
                flushedEntry = entry;
            }
            do {
                flushed ++;
                if (!entry.promise.setUncancellable()) {
                    // Was cancelled so make sure we free up memory and notify about the freed bytes
                    int pending = entry.cancel();
                    decrementPendingOutboundBytes(pending, false, true);
                }
                entry = entry.next;
            } while (entry != null);

            // All flushed so reset unflushedEntry
            unflushedEntry = null;
        }
    }

def _erase_buffer(self, output_buffer):
        """"""

        erase_size = self._model.get(u'buffer_erase_size')

        buffer_type = u'storage'
        if output_buffer:
            buffer_type = u'streaming'

        old_readings = self._engine.popn(buffer_type, erase_size)

        # Now go through all of our walkers that could match and
        # update their availability counts and data buffer pointers
        for reading in old_readings:
            stream = DataStream.FromEncoded(reading.stream)

            for walker in self._queue_walkers:
                # Only notify the walkers that are on this queue
                if walker.selector.output == output_buffer:
                    walker.notify_rollover(stream)

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


Question:
Reads data for an event.
@param [String => Mixed] $opts
@return [String => Mixed]
@override ModuleViewed

public function read(array $opts) {
        return [array_merge(parent::read($opts)[0], [
            'recipe' => 'discussion_viewed',
            'discussion_url' => $opts['discussion']->url,
            'discussion_name' => $opts['discussion']->name,
            'discussion_description' => 'A Moodle discussion.',
            'discussion_type' => static::$xapiType.$opts['discussion']->type,
            'discussion_ext' => $opts['discussion'],
            'discussion_ext_key' => 'http://lrs.learninglocker.net/define/extensions/moodle_discussion',
        ])];
    }

def _parse_caps_cpu(node):
    '''

    '''
    result = {}
    for mode in node.findall('mode'):
        if not mode.get('supported') == 'yes':
            continue

        name = mode.get('name')
        if name == 'host-passthrough':
            result[name] = True

        elif name == 'host-model':
            host_model = {}
            model_node = mode.find('model')
            if model_node is not None:
                model = {
                    'name': model_node.text
                }

                vendor_id = model_node.get('vendor_id')
                if vendor_id:
                    model['vendor_id'] = vendor_id

                fallback = model_node.get('fallback')
                if fallback:
                    model['fallback'] = fallback
                host_model['model'] = model

            vendor = mode.find('vendor').text if mode.find('vendor') is not None else None
            if vendor:
                host_model['vendor'] = vendor

            features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')}
            if features:
                host_model['features'] = features

            result[name] = host_model

        elif name == 'custom':
            custom_model = {}
            models = {model.text: model.get('usable') for model in mode.findall('model')}
            if models:
                custom_model['models'] = models
            result[name] = custom_model

    return result

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


Question: // Escape escapes the provided identifier based on the EscType.

func (tl TypeLoader) Escape(typ EscType, s string) string {
	if e, ok := tl.Esc[typ]; ok && e != nil {
		return e(s)
	}

	return `"` + s + `"`
}

def write_layout(layout = nil, type = nil) # :nodoc:
      tag = 'c:layout'

      if layout
        @writer.tag_elements(tag)  { write_manual_layout(layout, type) }
      else
        @writer.empty_tag(tag)
      end
    end

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


Question:
Adds a substitution font to the list. The fonts in this list will be used if the original
font doesn't contain the needed glyphs.

@param font the font

public void addSubstitutionFont(BaseFont font) {
        if (substitutionFonts == null)
            substitutionFonts = new ArrayList();
        substitutionFonts.add(font);
    }

public function currency($options = array())
    {
        $options = new AnConfig($options);

        $options->append(array(
            'name' => 'currency',
            'prompt' => true,
        ));

        $selected = $options->selected;
        unset($options->selected);
        $currencies = array_combine(self::$ISO_CURRENCY_SYMBOLS, self::$ISO_CURRENCY_SYMBOLS);

        return $this->_html->select($options->name, array('options' => $currencies, 'selected' => $selected), AnConfig::unbox($options));
    }

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


Question:
Checks if smtp host is valid (tries to connect to it)

@param string $smtpHost currently used smtp server host name

@return bool

protected function _isValidSmtpHost($smtpHost)
    {
        $isSmtp = false;
        if ($smtpHost) {
            $match = [];
            $smtpPort = isset($this->SMTP_PORT)
                ? $this->SMTP_PORT
                : $this->smtpPort;
            if (Str::getStr()->preg_match('@^(.*?)(:([0-9]+))?$@i', $smtpHost, $match)) {
                $smtpHost = $match[1];
                if (isset($match[3]) && (int) $match[3] !== 0) {
                    $smtpPort = (int) $match[3];
                }
            }
            if ($isSmtp = (bool) ($rHandle = @fsockopen($smtpHost, $smtpPort, $errNo, $errStr, 30))) {
                // closing connection ..
                fclose($rHandle);
            }
        }

        return $isSmtp;
    }

public function sendEmail($email)
    {
        return send_mail(
            'no-reply',
            get_app_name(),
            $email, $this->subject,
            $this->body,
            'html',
            '/contact/html',
            [
                'title' => 'This is title',
                'contact_name' => $this->name,
                'contact_email' => $this->email,
            ]
        );
    }

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


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

func (s *CreateAssessmentTemplateInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "CreateAssessmentTemplateInput"}
	if s.AssessmentTargetArn == nil {
		invalidParams.Add(request.NewErrParamRequired("AssessmentTargetArn"))
	}
	if s.AssessmentTargetArn != nil && len(*s.AssessmentTargetArn) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("AssessmentTargetArn", 1))
	}
	if s.AssessmentTemplateName == nil {
		invalidParams.Add(request.NewErrParamRequired("AssessmentTemplateName"))
	}
	if s.AssessmentTemplateName != nil && len(*s.AssessmentTemplateName) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("AssessmentTemplateName", 1))
	}
	if s.DurationInSeconds == nil {
		invalidParams.Add(request.NewErrParamRequired("DurationInSeconds"))
	}
	if s.DurationInSeconds != nil && *s.DurationInSeconds < 180 {
		invalidParams.Add(request.NewErrParamMinValue("DurationInSeconds", 180))
	}
	if s.RulesPackageArns == nil {
		invalidParams.Add(request.NewErrParamRequired("RulesPackageArns"))
	}
	if s.UserAttributesForFindings != nil {
		for i, v := range s.UserAttributesForFindings {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "UserAttributesForFindings", i), err.(request.ErrInvalidParams))
			}
		}
	}

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

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

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

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


Question:
<b>SAX1 AttributeList, SAX2 Attributes</b> method (don't invoke on
parser);

@Override
    public String getType(int index) {
        if (index < 0 || index >= attributesList.size()) {
            return null;
        }
        String type = parser.getAttributeType(elementName, getQName(index));
        if (type == null) {
            return "CDATA";
        }
        // ... use DeclHandler.attributeDecl to see enumerations
        if (type == "ENUMERATION") {
            return "NMTOKEN";
        }
        return type;
    }

public static String encodeXmlAttribute(String str) {
    if (str == null) return null;
    int len = str.length();
    if (len == 0) return str;
    StringBuffer encoded = new StringBuffer();
    for (int i = 0; i < len; i++) {
      char c = str.charAt(i);
      if (c == '<') encoded.append("<");
      else if (c == '\"') encoded.append(""");
      else if (c == '>') encoded.append(">");
      else if (c == '\'') encoded.append("'");
      else if (c == '&') encoded.append("&");
      else encoded.append(c);
    }
    return encoded.toString();
  }

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


Question:
gets all subclass of the class or interface

@param string $class
@return array

public function getSubClasses($class)
    {
        $class = $this->normalize($class);
        if ($this->classExists($class)) {
            return $this->getSubclassOfClass($class);
        } elseif ($this->interfaceExists($class)) {
            return $this->getSubclassOfInterface($class);
        } else {
            throw new ClassNotExistException($class);
        }
    }

function showInterfaceIdlMethod(method, html) {
    var line = "\n   "

    var allParameters = method.parameters.concat(method.callbackParameters)

    line += getIdlType(method.returns)
    line += " " + method.name + " (" + getIdlParameterList(allParameters) + ");"
    html.push(line)
}

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


Question: // Next returns the next non-filtered result from the wrapped iterator

func (f *FilterIterator) Next() interface{} {
	for {
		if value := f.iter.Next(); value == nil || !f.filter(value) {
			return value
		}
	}
}

func (l *waiterList) PushFront(e *Entry) {
	waiterElementMapper{}.linkerFor(e).SetNext(l.head)
	waiterElementMapper{}.linkerFor(e).SetPrev(nil)

	if l.head != nil {
		waiterElementMapper{}.linkerFor(l.head).SetPrev(e)
	} else {
		l.tail = e
	}

	l.head = e
}

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


Question:
Create a new version of Mustermann::FileUtils using a different ::FileUtils module.
 @see DryRun
 @!visibility private

def with_file_utils(&block)
      Module.new do
        include Mustermann::FileUtils
        define_method(:f, &block)
        private(:f)
        extend self
      end
    end

def apply_configuration(yml)
      if yml.include?("packages")
        yml["packages"].each do |k, v|
          valid_data = validate_data("packages", v, PACKAGE_SCHEMA)
          @package_info[k] = valid_data
        end
      end

      if yml.include?("platforms")
        yml["platforms"].each do |k, v|
          valid_data = validate_data("platforms", v, PLATFORM_SCHEMA)
          @platform_info[k] = valid_data
        end
      end

      if yml.include?("compile")
        valid_data = validate_data("compile", yml["compile"], COMPILE_SCHEMA)
        valid_data.each { |k, v| @compile_info[k] = v }
      end

      if yml.include?("unittest")
        valid_data = validate_data("unittest", yml["unittest"], UNITTEST_SCHEMA)
        valid_data.each { |k, v| @unittest_info[k] = v }
      end

      self
    end

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


Question: // GetID returns the ID field if it's non-nil, zero value otherwise.

func (r *Repository) GetID() int64 {
	if r == nil || r.ID == nil {
		return 0
	}
	return *r.ID
}

public function offsetGet($name)
    {
        $result = null;

        if (isset($this->_data[$name])) {
            $result = $this->_data[$name]->value;
        }

        return $result;
    }

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


Question:
CertificateID to string

@param certificateID CertificateID
@return a string representation of CertificateID

private static String CertificateIDToString(CertificateID certificateID)
  {
    return String.format("CertID. NameHash: %s, KeyHash: %s, Serial Number: %s",
                         byteToHexString(certificateID.getIssuerNameHash()),
                         byteToHexString(certificateID.getIssuerKeyHash()),
                         MessageFormat.format("{0,number,#}",
                                              certificateID.getSerialNumber()));

  }

public void marshall(LoadBalancerTlsCertificate loadBalancerTlsCertificate, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getName(), NAME_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getArn(), ARN_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getSupportCode(), SUPPORTCODE_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getCreatedAt(), CREATEDAT_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getLocation(), LOCATION_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getResourceType(), RESOURCETYPE_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getTags(), TAGS_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getLoadBalancerName(), LOADBALANCERNAME_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getIsAttached(), ISATTACHED_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getDomainName(), DOMAINNAME_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getDomainValidationRecords(), DOMAINVALIDATIONRECORDS_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getFailureReason(), FAILUREREASON_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getIssuedAt(), ISSUEDAT_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getIssuer(), ISSUER_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getKeyAlgorithm(), KEYALGORITHM_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getNotAfter(), NOTAFTER_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getNotBefore(), NOTBEFORE_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getRenewalSummary(), RENEWALSUMMARY_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getRevocationReason(), REVOCATIONREASON_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getRevokedAt(), REVOKEDAT_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getSerial(), SERIAL_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getSignatureAlgorithm(), SIGNATUREALGORITHM_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getSubject(), SUBJECT_BINDING);
            protocolMarshaller.marshall(loadBalancerTlsCertificate.getSubjectAlternativeNames(), SUBJECTALTERNATIVENAMES_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: BGP Timers Setters

def timer_bgp_keepalive_hold_set(keepalive, hold)
      if keepalive == default_timer_bgp_keepalive &&
         hold == default_timer_bgp_holdtime
        @set_args[:state] = 'no'
        @set_args[:keepalive] = keepalive
        @set_args[:hold] = hold
      else
        @set_args[:state] = ''
        @set_args[:keepalive] = keepalive
        @set_args[:hold] = hold
      end
      config_set('bgp', 'timer_bgp_keepalive_hold', @set_args)
      set_args_keys_default
    end

func DefaultThrottle() *auditregistrationv1alpha1.WebhookThrottleConfig {
	return &auditregistrationv1alpha1.WebhookThrottleConfig{
		QPS:   utilpointer.Int64Ptr(DefaultQPS),
		Burst: utilpointer.Int64Ptr(DefaultBurst),
	}
}

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


Question:
// hasMountinfoOption checks if any of the passed any of the given option values
// are set in the passed in option string.

func hasMountinfoOption(opts string, vals ...string) bool {
	for _, opt := range strings.Split(opts, " ") {
		for _, val := range vals {
			if strings.HasPrefix(opt, val) {
				return true
			}
		}
	}
	return false
}

def _interface_exists(self, interface):
        """"""
        ios_cfg = self._get_running_config()
        parse = HTParser(ios_cfg)
        itfcs_raw = parse.find_lines("^interface " + interface)
        return len(itfcs_raw) > 0

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


Question:
// ReadConfig reads login and password configuration from ~/.netrc
// machine foo.com login username password 123456

func ReadConfig(uri, netrc string) (string, string) {
	u, err := url.Parse(uri)
	if err != nil {
		return "", ""
	}

	file, err := os.Open(netrc)
	if err != nil {
		return "", ""
	}
	defer file.Close()

	re := fmt.Sprintf(`^.*machine %s.*$`, u.Host)
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		s := scanner.Text()

		matched, err := regexp.MatchString(re, s)
		if err != nil {
			return "", ""
		}
		if matched {
			return parseLine(s)
		}
	}

	return "", ""
}

def reset!(options = {})
      MsRestAzure::Common::Configurable.keys.each do |key|
        default_value = MsRestAzure::Common::Default.options[key]
        instance_variable_set(:"@#{key}", options.fetch(key, default_value))
      end

      if(options[:credentials].nil?)
        # The user has not passed in the credentials. So, the SDK has to
        # build the credentials itself.
        fail ArgumentError, 'tenant_id is nil' if self.tenant_id.nil?
        fail ArgumentError, 'client_id is nil' if self.client_id.nil?
        fail ArgumentError, 'client_secret is nil' if self.client_secret.nil?
        fail ArgumentError, 'active_directory_settings is nil' if self.active_directory_settings.nil?

        self.credentials = MsRest::TokenCredentials.new(
            MsRestAzure::ApplicationTokenProvider.new(
                self.tenant_id, self.client_id, self.client_secret, self.active_directory_settings))
      else
        self.credentials = options[:credentials]
      end

      self
    end

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


Question: // DefaultThrottle is a default throttle config

func DefaultThrottle() *auditregistrationv1alpha1.WebhookThrottleConfig {
	return &auditregistrationv1alpha1.WebhookThrottleConfig{
		QPS:   utilpointer.Int64Ptr(DefaultQPS),
		Burst: utilpointer.Int64Ptr(DefaultBurst),
	}
}

public function setHttpBasic($username, $password, $domain)
    {
        $this->set(
            self::HTTP_BASIC_KEY . '/' . $this->escape($domain),
            ['username' => $username, 'password' => $password]
        );

        return $this;
    }

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


Question: // SetGroupName sets the GroupName field's value.

func (s *DescribeGroupInput) SetGroupName(v string) *DescribeGroupInput {
	s.GroupName = &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: Build the feed and return a Builder::XmlMarkup.

def make(options={})
      xm = Builder::XmlMarkup.new(options)
      xm.instruct! :xml

      xm.feed(:xmlns => 'http://www.w3.org/2005/Atom',
        :'xmlns:media' => 'http://search.yahoo.com/mrss/') {
        xm.title title
        xm.link :href => feed_url, :rel => 'self'
        if u = updated
          xm.updated u.xmlschema
        end
        xm.id site_url
        TinyAtom::author xm, feed_options
        feed_options.fetch(:hubs, []).each do |hub|
          xm.link :rel => 'hub', :href => hub
        end

        entries.each do |e|
          xm.entry {
            xm.title e[:title]
            xm.link :href => e[:link]
            xm.id entry_id(e)
            xm.updated e[:updated].xmlschema
            xm.summary(e[:summary])  if e[:summary]
            xm.content(e[:content])  if e[:content]

            (e[:authors] || [e]).each { |h| TinyAtom::author xm, h }
            (e[:enclosures] || [e]).each { |h| TinyAtom::enclosure xm, h }
            (e[:media_thumbnails] || [e]).each do |h|
              TinyAtom::media_thumbnail xm, h
            end
            TinyAtom::via xm, e
          }
        end
      }
    end

def render_file_set_status
      @file_set_status ||=
        if relevant_log_records.empty?
          "Fixity checks have not yet been run on this object"
        elsif failing_checks.empty?
          content_tag("span", "passed", class: "label label-success") + ' ' + render_existing_check_summary
        else
          content_tag("span", "FAIL", class: "label label-danger") + ' ' + render_existing_check_summary + render_failed_compact
        end
    end

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


Question: // Pretty indicates that the JSON response be indented and human readable.

func (s *NodesStatsService) Pretty(pretty bool) *NodesStatsService {
	s.pretty = pretty
	return s
}

public WebhookData parseWebhookData(String webhook) {
        if (webhook == null || webhook.trim()
                .length() <= 0) {
            return null;
        }
        webhook = LEFT_QUOTATION.matcher(webhook)
                .replaceAll("{");
        webhook = RIGHT_QUOTATION.matcher(webhook)
                .replaceAll("}");
        webhook = BACKLASH_QUOTATION.matcher(webhook)
                .replaceAll("\"");

        return FastjsonDecoder.decodeAsBean(webhook, WebhookData.class);
    }

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


Question:
@param string $id
@param array  $data
@param array  $headers

@throws Exception

@return array|string

public function removeScheduledResumption(string $id, array $data = [], array $headers = [])
    {
        $url = $this->url('subscriptions/%s/remove_scheduled_resumption', $id);

        return $this->post($url, $data, $headers);
    }

final public function output (){

        if($this->_outputOnlyHeaders){
            $this->sendHttpHeaders();
            return true;
        }

        $this->_httpHeaders['Content-Type'] =
                'application/atom+xml;charset=' . $this->charset;

        if(!$this->infos->updated){
            $this->infos->updated = date("Y-m-d H:i:s");
        }

        // generate the main content, in a buffer
        // so we can handle errors
        $this->_template->assign ('atom', $this->infos);
        $this->_template->assign ('items', $this->itemList);
        $this->_template->assign ('lang',$this->lang);
        $content = $this->_template->fetch ($this->_mainTpl);

        $this->sendHttpHeaders();
        echo '<?xml version="1.0" encoding="'. $this->charset .'"?>', "\n";
        $this->_outputXmlHeader ();
        echo $content;
        return true;
    }

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


Question:
Test id next sequence the constant?

@param constant constant pattern element
@return true if next sub sequence is constant.

public boolean nextIs(PatternConstant constant) {
        char[] cs = constant.getCharArray();
        int length = cs.length;

        if (length > textLength - offset) {
            return false;
        }

        if (!constant.isIgnoreCase()) {
            int i;
            //noinspection StatementWithEmptyBody
            for (i = 0; i < length && text[offset + i] == cs[i]; i++);
            return i == length;
        } else {
            for (int i = 0; i < length; i++) {
                char ct = text[offset + i];
                char cv = cs[i];
                if (
                        ct == cv ||
                                Character.toUpperCase(ct) == Character.toUpperCase(cv) ||
                                Character.toLowerCase(ct) == Character.toLowerCase(cv)
                        ) {
                    continue;
                }
                return false;
            }
            return true;
        }
    }

func listCmd(cf *ChaincodeCmdFactory) *cobra.Command {
	chaincodeListCmd = &cobra.Command{
		Use:   "list",
		Short: "Get the instantiated chaincodes on a channel or installed chaincodes on a peer.",
		Long:  "Get the instantiated chaincodes in the channel if specify channel, or get installed chaincodes on the peer",
		RunE: func(cmd *cobra.Command, args []string) error {
			return getChaincodes(cmd, cf)
		},
	}

	flagList := []string{
		"channelID",
		"installed",
		"instantiated",
		"peerAddresses",
		"tlsRootCertFiles",
		"connectionProfile",
	}
	attachFlags(chaincodeListCmd, flagList)

	return chaincodeListCmd
}

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


Question:
Deserializes the given byte array into to a newly allocated object.

@param bytes byte array to deserialize or {@code null} for {@code null} result
@return new allocated object or {@code null} for {@code null} input
@since 1.16

public static <S extends Serializable> S deserialize(byte[] bytes) throws IOException {
    if (bytes == null) {
      return null;
    }
    return deserialize(new ByteArrayInputStream(bytes));
  }

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

      return null;
   }

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


Question:
Display the individual post

@param $slug  Post's slug
@return view

public function DisplaySinglePost($slug)
    {
        // If this is a page, then display the page
        if ($this->isBladeFile($slug)) {
            return view('pages/' . $slug, [
                'DatesHelper'       => DatesHelper::class,
                'HTMLHelper'        => HTMLHelper::class,
                'ImagesHelper'      => $this->imagesHelper,
            ]);
        }

        // This slug refers to a single post
        $post = $this->repository->findEnabledPostBySlug($slug);

        if (count($post) == 0) {

            // post not found, so display the 404 page
            //return view('errors/404');
            return $this->home();
        }

        // Figure out if the post is using a specified featured image; or, if no such image,
        // then use the category's default image as this post's featured image.
        $post->featured_image = $this->imagesHelper->categoryImageDefaultOrSpecified($post->featured_image);

        // Resize the post's featured image -- if not yet resized.
        $this->imagesHelper->createPostResizedImageFiles($post->featured_image);

        // Set up the social media tags

        // first, set up the image
        if ($post->featured_image == "") {
            $post->featured_image = Config::get('lasallecmsfrontend.social_media_default_image');
        }
        $post->urlImage = $this->imagesHelper->urlOfImage($post->featured_image,600,600);

        // second, create the social media tag arrays
        $openGraph = HTMLHelper::createOpenGraphTagsForPost($post);
        $twitter   = HTMLHelper::createTwitterTagsForPost($post);
        $google    = HTMLHelper::createGoogleTagsForPost($post);

        // "Next" and "Previous" navigation within a single post... well, there can be multiple categories per post,
        //  so should the "Next" and "Previous" links refer to any ol' post regardless of category; or, should the
        //  "Next" and "Previous" links within a post refer strictly to posts assigned to the same category?
        //  Since my intention is to group posts by category, the answer is "assigned to the same category".
        //
        //  So... my intention is that POSTS assign to just one category, despite the ability to assign multiple categories.
        //  Hey, this multiple category thing is really intended for ecommerce, where the parent category = "Products".
        //  For regular ol' POSTS, my intention is a mandatory one category per post. Essentially creating a one-to-one
        //  relationship, which is my working assumption for "Next" and "Previous" single post navigation.

        // So, first of all, must be just one category for this post
        $category = $this->repository->findCategoryForPostById($post->id);

        if (count($category) == 1)
        {
            // Next post
            $nextPost     = $this->repository->getNextPost($category[0]->category_id, $post->publish_on);

            // Previous post
            $previousPost = $this->repository->getPreviousPost($category[0]->category_id, $post->publish_on);

            // The category's title
            $categoryTitle    = $this->repository->getCategoryTitleById($category[0]->category_id);
        }

        // tags
        $tagTitles = $this->repository->getTagTitlesByPostId($post->id);

        return view('posts/single_post', [
            'post'              => $post,
            'DatesHelper'       => DatesHelper::class,
            'HTMLHelper'        => HTMLHelper::class,
            'ImagesHelper'      => $this->imagesHelper,
            'openGraph'         => $openGraph,
            'twitter'           => $twitter,
            'google'            => $google,
            'nextPost'          => $nextPost,
            'previousPost'  => $previousPost,
            'categoryTitle'     => $categoryTitle,
            'tagTitles'         => $tagTitles,
        ]);
    }

def get_recent_linkbacks(number=5,
                         template='zinnia/tags/linkbacks_recent.html'):

    entry_published_pks = map(smart_text,
                              Entry.published.values_list('id', flat=True))
    content_type = ContentType.objects.get_for_model(Entry)

    linkbacks = get_comment_model().objects.filter(
        content_type=content_type,
        object_pk__in=entry_published_pks,
        flags__flag__in=[PINGBACK, TRACKBACK],
        is_public=True).order_by('-pk')[:number]

    linkbacks = linkbacks.prefetch_related('content_object')

    return {'template': template,
            'linkbacks': linkbacks}

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


Question:
// GobDecode overwrites the receiver, which must be a pointer,
// with the value represented by the byte slice, which was written
// by GobEncode, usually for the same concrete type.
// GobDecode([]byte) error

func (j *JsonHelper) GobDecode(data []byte) error {
	var mv map[string]interface{}
	if err := json.Unmarshal(data, &mv); err != nil {
		return err
	}
	*j = JsonHelper(mv)
	return nil
}

def _message_address_generate(self, beacon_config):

		address = None

		if beacon_config['wasp-general::network::beacon']['public_address'] != '':
			address = str(WIPV4SocketInfo.parse_address(
				beacon_config['wasp-general::network::beacon']['public_address']
			)).encode('ascii')

		if address is not None:
			address = WBeaconGouverneurMessenger.__message_splitter__ + address

			if beacon_config['wasp-general::network::beacon']['public_port'] != '':
				port = beacon_config.getint('wasp-general::network::beacon', 'public_port')
				address += WBeaconGouverneurMessenger.__message_splitter__ + str(port).encode('ascii')

		return address if address is not None else b''

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


Question: const LOCAL_CONFIG_FILE = path.resolve(process.cwd(), './.badge.json');

function readFromLocalConfig(parent){
    return readFile(config_file(parent), "utf8")
        .then(function(contents){
            return JSON.parse(contents);
        })
        .catch(function(){
            return {
                data: {},
                installed: [],
            };
        });
}

function (data) {
            var temp = addPath(validUrls, url.parse(data.href), bs.options.get("mode"));
            methods.sendUpdatedIfChanged(validUrls, temp, ui.socket);
        }

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


Question: Extracts the module version from a configuration

function getModuleVersionFromConfig(config) {
    if (config.moduleVersion === undefined && config.nodePackageName == CORDOVA) {
        // If no version is set, try to get the version from taco.json
        // This check is specific to the Cordova module
        if (utilities.fileExistsSync(path.join(config.projectPath, 'taco.json'))) {
            var version = require(path.join(config.projectPath, 'taco.json'))['cordova-cli'];

            if (version) {
                console.log('Cordova version set to ' + version + ' based on the contents of taco.json');
                return version;
            }
        }
    }

    return config.moduleVersion || process.env[makeDefaultEnvironmentVariable(config.nodePackageName)];
}

public function getPermFromRoute($route) {
    $menu_info = Config::get($this->config_path);

    foreach ($menu_info as $menu) {
      if ($menu[$this->route_variable_index] == $route) {
        return $menu[$this->pemissions_variable_index];
      }
    }
  }

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


Question:
Change [ Your Profile > Admin Color Scheme ] to Pressbooks default colors

@param int $id
@param object $user (optional)

public function forcePbColors( $id, $user = null ) {

		if ( is_numeric( $id ) ) {
			$user_id = $id;
		} elseif ( $user instanceof \WP_User ) {
			$user_id = $user->ID;
		} else {
			return;
		}

		update_user_option( $user_id, 'admin_color', 'pb_colors', true );
	}

def save(self, *args, **kwargs):
        """"""
        if not self.status:
            self.status = self.DRAFT
        # Published pages should always have a publication date
        if self.publication_date is None and self.status == self.PUBLISHED:
            self.publication_date = get_now()
        # Drafts should not, unless they have been set to the future
        if self.status == self.DRAFT:
            if settings.PAGE_SHOW_START_DATE:
                if (self.publication_date and
                        self.publication_date <= get_now()):
                    self.publication_date = None
            else:
                self.publication_date = None
        self.last_modification_date = get_now()
        super(Page, self).save(*args, **kwargs)
        # fix sites many-to-many link when the're hidden from the form
        if settings.PAGE_HIDE_SITES and self.sites.count() == 0:
            self.sites.add(Site.objects.get(pk=global_settings.SITE_ID))

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


Question:
Log a message, shown in highest verbosity mode.

@param string $message
@param array  $context

public function debug($message, array $context = [])
    {
        if ($this->logger instanceof LoggerInterface) {
            $this->logger->debug($message, $context);
        }
    }

public function build() {
    $options_data = $this->buildOptionsData();

    $out_text =
      $this->buildUsageLine($this->arguments_spec->getUsage(), $options_data);

    $options_text = '';
    if ($options_data['lines']) {
      foreach($options_data['lines'] as $option_line_data) {
        $options_text .= $this->buildOptionLine($option_line_data, $options_data)."\n";
      }

      $out_text .=
        "\n".
        ConsoleFormat::applyformatToText('bold','cyan','Options:')."\n".
        $options_text;
    }

    return $out_text;
  }

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


Question:
Set the KeyRange to limit the rows.
@param conf Job configuration you are about to run

public static void setInputRange(Configuration conf, List<IndexExpression> filter)
    {
        KeyRange range = new KeyRange().setRow_filter(filter);
        conf.set(INPUT_KEYRANGE_CONFIG, thriftToString(range));
    }

public static Object[] getSqlParams(String sqlPattern, Map map) {
        Object[] sqlParams = JdbcPatternUtil.getValues(JdbcPatternUtil.getCamelKeys(sqlPattern), map).toArray();
        for (int i = 0; i < sqlParams.length; i++) {
            if (sqlParams[i] instanceof Calendar) {//因为prepared statement不支持calendar类型,所以需要将其其中的calendar转为date
                sqlParams[i] = ((Calendar) sqlParams[i]).getTime();
            }
        }
        return sqlParams;
    }

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


Question:
Utility method to add an {@link IChemObject} to an {@link IAtomContainer}.

@param ac the {@link IAtomContainer} to add to
@param item the {@link IChemObject} to add

protected void addToAtomContainer(IAtomContainer ac, IChemObject item) {
        if (item instanceof IAtomContainer) {
            ac.add((IAtomContainer) item);
        } else if (item instanceof IAtom) {
            ac.addAtom((IAtom) item);
        } else if (item instanceof IBond) {
            ac.addBond((IBond) item);
        }
    }

func (kl *Kubelet) makeBlockVolumes(pod *v1.Pod, container *v1.Container, podVolumes kubecontainer.VolumeMap, blkutil volumepathhandler.BlockVolumePathHandler) ([]kubecontainer.DeviceInfo, error) {
	var devices []kubecontainer.DeviceInfo
	for _, device := range container.VolumeDevices {
		// check path is absolute
		if !filepath.IsAbs(device.DevicePath) {
			return nil, fmt.Errorf("error DevicePath `%s` must be an absolute path", device.DevicePath)
		}
		vol, ok := podVolumes[device.Name]
		if !ok || vol.BlockVolumeMapper == nil {
			klog.Errorf("Block volume cannot be satisfied for container %q, because the volume is missing or the volume mapper is nil: %+v", container.Name, device)
			return nil, fmt.Errorf("cannot find volume %q to pass into container %q", device.Name, container.Name)
		}
		// Get a symbolic link associated to a block device under pod device path
		dirPath, volName := vol.BlockVolumeMapper.GetPodDeviceMapPath()
		symlinkPath := path.Join(dirPath, volName)
		if islinkExist, checkErr := blkutil.IsSymlinkExist(symlinkPath); checkErr != nil {
			return nil, checkErr
		} else if islinkExist {
			// Check readOnly in PVCVolumeSource and set read only permission if it's true.
			permission := "mrw"
			if vol.ReadOnly {
				permission = "r"
			}
			klog.V(4).Infof("Device will be attached to container %q. Path on host: %v", container.Name, symlinkPath)
			devices = append(devices, kubecontainer.DeviceInfo{PathOnHost: symlinkPath, PathInContainer: device.DevicePath, Permissions: permission})
		}
	}

	return devices, nil
}

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


Question:
Serializes this PassportElementErrorFiles to a dictionary.

        :return: dictionary representation of this object.
        :rtype: dict

def to_array(self):

        array = super(PassportElementErrorFiles, self).to_array()
        array['source'] = u(self.source)  # py2: type unicode, py3: type str
        array['type'] = u(self.type)  # py2: type unicode, py3: type str
        array['file_hashes'] = self._as_array(self.file_hashes)  # type list of str
        array['message'] = u(self.message)  # py2: type unicode, py3: type str
        return array

def add_item(self, host, key, value, clock=None, state=0):

        if clock is None:
            clock = self.clock
        if self._config.data_type == "items":
            item = {"host": host, "key": key,
                    "value": value, "clock": clock, "state": state}
        elif self._config.data_type == "lld":
            item = {"host": host, "key": key, "clock": clock, "state": state,
                    "value": json.dumps({"data": value})}
        else:
            if self.logger: # pragma: no cover
                self.logger.error("Setup data_type before adding data")
            raise ValueError('Setup data_type before adding data')
        self._items_list.append(item)

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


Question:
Returns the URL to the published assets folder.
@return string an absolute URL to the published asset

public function getAssetsUrl() {

		if (isset($this->_assetsUrl)) {
			return $this->_assetsUrl;
		} else {
			return $this->_assetsUrl = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('booster.assets'), false, -1, $this->forceCopyAssets);
		}
	}

function configure(app, servernode) {
    var rootDir, publicDir;
    var resourceManager;
    var basepath;

    rootDir = servernode.rootDir;
    publicDir = path.join(rootDir, 'public');
    basepath = servernode.basepath || '';
    resourceManager = servernode.resourceManager;

    app.set('views', path.resolve(rootDir, 'views'));
    app.set('view engine', 'jade');
    app.set('view options', {layout: false});

    if (process.env.NODE_ENV === 'development') {
        app.use(express.static(publicDir));
        app.use(errorHandler());
    }
    else {
        app.use(express.static(publicDir, { maxAge: 3600000 }));
    }

    app.disable('x-powered-by');
    app.enable("jsonp callback");

    app.use(cookieParser());
    // app.use(bodyParser());
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    function sendFromPublic(type, req, res, headers) {
        var file, mimeType, charset, filePath;
        file = req.params[0];
        if (!file) return;

        // Build path in `public/`.
        file = path.join(type, file);

        // Build headers.
        if (!headers) {
            mimeType = mime.lookup(file);
            charset = mime.charsets.lookup(mimeType);
            headers = { 'Content-Type': mimeType };
            if (charset) headers.charset = charset;
        }

        // If it is not text, it was not cached.
        if (headers['Content-Type'].substring(0,4) !== 'text') {
            filePath = path.resolve(publicDir, file);
            res.sendFile(filePath);
            return;
        }

        // Already found in `public/` and cached.
        resourceManager.getFromPublic('/', file, function(cachedFile) {

            // File found in public (cached or loaded).
            if (cachedFile) {
                res.set(headers);
                res.status(200).send(cachedFile);
            }
            else {
                // Send 404.
                res.status(404).send('File not found.');
            }
        });
    }

    app.get(basepath + '/javascripts/*', function(req, res) {
        sendFromPublic('javascripts', req, res, {
            'Content-Type': 'text/javascript',
            'charset': 'utf-8'
        });
    });

    app.get(basepath + '/sounds/*', function(req, res) {
        sendFromPublic('sounds', req, res, {
            'Content-Type': 'sound/ogg'
        });
    });

    app.get(basepath + '/stylesheets/*', function(req, res) {
        sendFromPublic('stylesheets', req, res, {
            'Content-Type': 'text/css',
            'charset': 'utf-8'
        });
    });

    app.get(basepath + '/images/*', function(req, res) {
        sendFromPublic('images', req, res, {
            'Content-Type': 'image/png'
        });
    });

    app.get(basepath + '/pages/*', function(req, res) {
        sendFromPublic('pages', req, res, {
            'Content-Type': 'text/html',
            'charset': 'utf-8'
        });
    });

    app.get(basepath + '/lib/*', function(req, res) {
        sendFromPublic('lib', req, res);
    });

    app.get(basepath + '/', function(req, res, next) {
        var q, games = [];

        var gamesObj;
        var i, j;
        var colors;
        var name, card, color, filteredGames;

        if (servernode.defaultChannel) {
            next();
            return;
        }

        if (J.isEmpty(req.query)) {
            if (servernode.homePage === false ||
                servernode.homePage.enabled === false) {

                res.render('index_simple', {
                    title: 'Yay! nodeGame server is running.'
                });
            }
            else {
                colors = servernode.homePage.colors;
                gamesObj = servernode.info.games;
                listOfGames = J.keys(gamesObj);
                // Remove aliases.
                filteredGames = listOfGames.filter(function(name) {
                    return (!gamesObj[name].errored &&
                            (!gamesObj[name].alias ||
                             gamesObj[name].alias.indexOf(name) === -1));
                });
                if (J.isArray(servernode.homePage.cardsOrder)) {
                    filteredGames =
                        servernode.homePage.cardsOrder.filter(function(name) {
                            if (filteredGames.indexOf(name) !== -1) return true;
                            servernode.logger.error('homePage.cardsOrder ' +
                                                    'game not found: ' + name);
                        });
                }
                else {
                    filteredGames.sort();
                }
                i = 0;
                for (j = 0; j < filteredGames.length; j++) {
                    name = filteredGames[j];
                    if (i >= colors.length) i = 0;
                    color = colors[i];
                    // Mixout name and description from package.json
                    // if not in card, or if no card is defined.
                    card = J.mixout(gamesObj[name].info.card || {}, {
                        name: name.charAt(0).toUpperCase() + name.slice(1),
                        description: gamesObj[name].info.description
                    });
                    games.push({
                        name: card.name,
                        color: color,
                        url: card.url,
                        description: card.description,
                        publication: card.publication,
                        wiki: card.wiki,
                        icon: card.icon
                    });
                    i++;
                }
                res.render('homepage', {
                    title: servernode.homePage.title,
                    games: games,
                    nodeGameCard: servernode.homePage.nodeGameCard,
                    footerContent: servernode.homePage.footerContent,
                    logo: servernode.homePage.logo
                });
            }

            return;
        }

        if (servernode.enableInfoQuery) {

            q = req.query.q;
            if (!q) {
                res.status(400).send('Query must start with q=XXX');
                return;
            }

            switch(q) {
            case 'info':
                //console.log(servernode.info);
                res.status(200).send(servernode.info);
                break;

            case 'channels':
                //console.log(servernode.info);
                res.status(200).send(servernode.info.channels);
                break;

            case 'games':
                //console.log(servernode.info);
                res.status(200).send(servernode.info.games);
                break;
            default:
                res.status(400).send('Unknown query received.');
            }
        }
        else {
            res.status(403).end();
        }
    });

    return true;
}

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


Question:
d.free_resource_id(rid)

        Free resource id RID.  Attempts to free a resource id which
        isn't allocated by us are ignored.

def free_resource_id(self, rid):

        self.resource_id_lock.acquire()
        try:
            i = rid & self.info.resource_id_mask

            # Attempting to free a resource id outside our range
            if rid - i != self.info.resource_id_base:
                return None

            try:
                del self.resource_ids[i]
            except KeyError:
                pass
        finally:
            self.resource_id_lock.release()

def _get_db_refs(term):
    """"""
    db_refs = {}
    # Here we extract the text name of the Agent
    # There are two relevant tags to consider here.
    # The <text> tag typically contains a larger phrase surrounding the
    # term but it contains the term in a raw, non-canonicalized form.
    # The <name> tag only contains the name of the entity but it is
    # canonicalized. For instance, MAP2K1 appears as MAP-2-K-1.
    agent_text_tag = term.find('name')
    if agent_text_tag is not None:
        db_refs['TEXT'] = agent_text_tag.text
        # If we have some drum-terms, the matched-name of the first
        # drum-term (e.g. "MAP2K1") is a better value for TEXT than
        # the name of the TERM (e.g. "MAP-2-K-1") so we put that in there
        drum_terms = term.findall('drum-terms/drum-term')
        if drum_terms:
            matched_name = drum_terms[0].attrib.get('matched-name')
            if matched_name:
                db_refs['TEXT'] = matched_name

    # We make a list of scored grounding terms from the DRUM terms
    grounding_terms = _get_grounding_terms(term)
    if not grounding_terms:
        # This is for backwards compatibility with EKBs without drum-term
        # scored entries. It is important to keep for Bioagents
        # compatibility.
        dbid = term.attrib.get('dbid')
        if dbid:
            dbids = dbid.split('|')
            for dbname, dbid in [d.split(':') for d in dbids]:
                if not db_refs.get(dbname):
                    db_refs[dbname] = dbid
        return db_refs, None, []

    # This is the INDRA prioritization of grounding name spaces. Lower score
    # takes precedence.
    ns_priority = {
        'HGNC': 1,
        'UP': 1,
        'FPLX': 2,
        'CHEBI': 3,
        'PC': 3,
        'GO': 4,
        'FA': 5,
        'XFAM': 5,
        'NCIT': 5
    }
    # We get the top priority entry from each score group
    score_groups = itertools.groupby(grounding_terms, lambda x: x['score'])
    top_per_score_group = []
    ambiguities = []
    for score, group in score_groups:
        entries = list(group)
        for entry in entries:
            priority = 100
            for ref_ns, ref_id in entry['refs'].items():
                # Skip etc UP entries
                if ref_ns == 'UP' and ref_id == 'etc':
                    continue
                try:
                    priority = min(priority, ns_priority[ref_ns])
                except KeyError:
                    pass
                if ref_ns == 'UP':
                    if not up_client.is_human(ref_id):
                        priority = 4
            entry['priority'] = priority
        if len(entries) > 1:
            top_entry = entries[0]
            top_idx = 0
            for i, entry in enumerate(entries):
                # We take the lowest priority entry within the score group
                # as the top entry
                if entry['priority'] < top_entry['priority']:
                    # This is a corner case in which a protein family
                    # should be prioritized over a specific protein,
                    # specifically when HGNC was mapped from NCIT but
                    # FPLX was not mapped from NCIT, the HGNC shouldn't
                    # take precedence.
                    if entry.get('comment') == 'HGNC_FROM_NCIT' and \
                        'FPLX' in top_entry['refs'] and \
                        top_entry.get('comment') != 'FPLX_FROM_NCIT':
                        continue
                    top_entry = entry
                    top_idx = i
            for i, entry in enumerate(entries):
                if i == top_idx:
                    continue
                if (entry['priority'] - top_entry['priority']) <= 1:
                    ambiguities.append((top_entry, entry))
        else:
            top_entry = entries[0]
        top_per_score_group.append(top_entry)
    # Get the top priority for each score group
    priorities = [entry['priority'] for entry in top_per_score_group]

    # By default, we coose the top priority entry from the highest score group
    top_grounding = top_per_score_group[0]
    # Sometimes the top grounding has much lower priority and not much higher
    # score than the second grounding. Typically 1.0 vs 0.82857 and 5 vs 2.
    # In this case we take the second entry. A special case is handled where
    # a FPLX entry was mapped from FA, in which case priority difference of < 2
    # is also accepted.
    if len(top_per_score_group) > 1:
        score_diff = top_per_score_group[0]['score'] - \
                     top_per_score_group[1]['score']
        priority_diff = top_per_score_group[0]['priority'] - \
                        top_per_score_group[1]['priority']
        if score_diff < 0.2 and (priority_diff >= 2 or \
            top_per_score_group[0].get('comment') == 'FPLX_FROM_FA'):
            top_grounding = top_per_score_group[1]
    relevant_ambiguities = []
    for amb in ambiguities:
        if top_grounding not in amb:
            continue
        if top_grounding == amb[0]:
            relevant_ambiguities.append({'preferred': amb[0],
                                         'alternative': amb[1]})
        else:
            relevant_ambiguities.append({'preferred': amb[1],
                                         'alternative': amb[0]})

    for k, v in top_grounding['refs'].items():
        db_refs[k] = v

    # Now standardize db_refs to the INDRA standards
    # We need to add a prefix for CHEBI
    chebi_id = db_refs.get('CHEBI')
    if chebi_id and not chebi_id.startswith('CHEBI:'):
        db_refs['CHEBI'] = 'CHEBI:%s' % chebi_id
    # We need to strip the trailing version number for XFAM and rename to PF
    pfam_id = db_refs.get('XFAM')
    if pfam_id:
        pfam_id = pfam_id.split('.')[0]
        db_refs.pop('XFAM', None)
        db_refs['PF'] = pfam_id
    # We need to add GO prefix if it is missing
    go_id = db_refs.get('GO')
    if go_id:
        if not go_id.startswith('GO:'):
            db_refs['GO'] = 'GO:%s' % go_id
    # We need to deal with Nextprot families
    nxp_id = db_refs.get('FA')
    if nxp_id:
        db_refs.pop('FA', None)
        db_refs['NXPFA'] = nxp_id
    # We need to rename PC to PUBCHEM
    pc_id = db_refs.get('PC')
    if pc_id:
        db_refs.pop('PC', None)
        db_refs['PUBCHEM'] = pc_id

    # Here we also get and return the type, which is a TRIPS
    # ontology type. This is to be used in the context of
    # Bioagents.
    ont_type = top_grounding['type']

    return db_refs, ont_type, relevant_ambiguities

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


Question:
// ENVCHANGE stream
// http://msdn.microsoft.com/en-us/library/dd303449.aspx

func processEnvChg(sess *tdsSession) {
	size := sess.buf.uint16()
	r := &io.LimitedReader{R: sess.buf, N: int64(size)}
	for {
		var err error
		var envtype uint8
		err = binary.Read(r, binary.LittleEndian, &envtype)
		if err == io.EOF {
			return
		}
		if err != nil {
			badStreamPanic(err)
		}
		switch envtype {
		case envTypDatabase:
			sess.database, err = readBVarChar(r)
			if err != nil {
				badStreamPanic(err)
			}
			_, err = readBVarChar(r)
			if err != nil {
				badStreamPanic(err)
			}
		case envTypLanguage:
			// currently ignored
			// new value
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
			// old value
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
		case envTypCharset:
			// currently ignored
			// new value
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
			// old value
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
		case envTypPacketSize:
			packetsize, err := readBVarChar(r)
			if err != nil {
				badStreamPanic(err)
			}
			_, err = readBVarChar(r)
			if err != nil {
				badStreamPanic(err)
			}
			packetsizei, err := strconv.Atoi(packetsize)
			if err != nil {
				badStreamPanicf("Invalid Packet size value returned from server (%s): %s", packetsize, err.Error())
			}
			sess.buf.ResizeBuffer(packetsizei)
		case envSortId:
			// currently ignored
			// new value
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
			// old value, should be 0
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
		case envSortFlags:
			// currently ignored
			// new value
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
			// old value, should be 0
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
		case envSqlCollation:
			// currently ignored
			var collationSize uint8
			err = binary.Read(r, binary.LittleEndian, &collationSize)
			if err != nil {
				badStreamPanic(err)
			}

			// SQL Collation data should contain 5 bytes in length
			if collationSize != 5 {
				badStreamPanicf("Invalid SQL Collation size value returned from server: %d", collationSize)
			}

			// 4 bytes, contains: LCID ColFlags Version
			var info uint32
			err = binary.Read(r, binary.LittleEndian, &info)
			if err != nil {
				badStreamPanic(err)
			}

			// 1 byte, contains: sortID
			var sortID uint8
			err = binary.Read(r, binary.LittleEndian, &sortID)
			if err != nil {
				badStreamPanic(err)
			}

			// old value, should be 0
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
		case envTypBeginTran:
			tranid, err := readBVarByte(r)
			if len(tranid) != 8 {
				badStreamPanicf("invalid size of transaction identifier: %d", len(tranid))
			}
			sess.tranid = binary.LittleEndian.Uint64(tranid)
			if err != nil {
				badStreamPanic(err)
			}
			if sess.logFlags&logTransaction != 0 {
				sess.log.Printf("BEGIN TRANSACTION %x\n", sess.tranid)
			}
			_, err = readBVarByte(r)
			if err != nil {
				badStreamPanic(err)
			}
		case envTypCommitTran, envTypRollbackTran:
			_, err = readBVarByte(r)
			if err != nil {
				badStreamPanic(err)
			}
			_, err = readBVarByte(r)
			if err != nil {
				badStreamPanic(err)
			}
			if sess.logFlags&logTransaction != 0 {
				if envtype == envTypCommitTran {
					sess.log.Printf("COMMIT TRANSACTION %x\n", sess.tranid)
				} else {
					sess.log.Printf("ROLLBACK TRANSACTION %x\n", sess.tranid)
				}
			}
			sess.tranid = 0
		case envEnlistDTC:
			// currently ignored
			// new value, should be 0
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
			// old value
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
		case envDefectTran:
			// currently ignored
			// new value
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
			// old value, should be 0
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
		case envDatabaseMirrorPartner:
			sess.partner, err = readBVarChar(r)
			if err != nil {
				badStreamPanic(err)
			}
			_, err = readBVarChar(r)
			if err != nil {
				badStreamPanic(err)
			}
		case envPromoteTran:
			// currently ignored
			// old value, should be 0
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
			// dtc token
			// spec says it should be L_VARBYTE, so this code might be wrong
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
		case envTranMgrAddr:
			// currently ignored
			// old value, should be 0
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
			// XACT_MANAGER_ADDRESS = B_VARBYTE
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
		case envTranEnded:
			// currently ignored
			// old value, B_VARBYTE
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
			// should be 0
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
		case envResetConnAck:
			// currently ignored
			// old value, should be 0
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
			// should be 0
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
		case envStartedInstanceName:
			// currently ignored
			// old value, should be 0
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
			// instance name
			if _, err = readBVarChar(r); err != nil {
				badStreamPanic(err)
			}
		case envRouting:
			// RoutingData message is:
			// ValueLength                 USHORT
			// Protocol (TCP = 0)          BYTE
			// ProtocolProperty (new port) USHORT
			// AlternateServer             US_VARCHAR
			_, err := readUshort(r)
			if err != nil {
				badStreamPanic(err)
			}
			protocol, err := readByte(r)
			if err != nil || protocol != 0 {
				badStreamPanic(err)
			}
			newPort, err := readUshort(r)
			if err != nil {
				badStreamPanic(err)
			}
			newServer, err := readUsVarChar(r)
			if err != nil {
				badStreamPanic(err)
			}
			// consume the OLDVALUE = %x00 %x00
			_, err = readUshort(r)
			if err != nil {
				badStreamPanic(err)
			}
			sess.routedServer = newServer
			sess.routedPort = newPort
		default:
			// ignore rest of records because we don't know how to skip those
			sess.log.Printf("WARN: Unknown ENVCHANGE record detected with type id = %d\n", envtype)
			break
		}

	}
}

func (c *Client) SetModelEnvironVersion(tag names.ModelTag, v int) error {
	args := params.SetModelEnvironVersions{
		Models: []params.SetModelEnvironVersion{{
			ModelTag: tag.String(),
			Version:  v,
		}},
	}
	var results params.ErrorResults
	err := c.facade.FacadeCall("SetModelEnvironVersion", &args, &results)
	if err != nil {
		return errors.Trace(err)
	}
	return results.OneError()
}

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


Question:
create address from google maps api result

@param object $googleData Google single result
@return Coordinates

public static function create(object $googleData) : Coordinates
    {
        $build = new self($googleData);
        $address = $build->createCoordinatesFromGeometry();

        return $address;
    }

private function parseOptions(array $options): array
    {
        $child = $options['child'] ?? [];

        if (isset($options['header'])) {
            $options['extras'] = $options['extras'] ?? [];
            $options['extras'] = array_merge($options['extras'], ['header' => $options['header']]);
        }

        if (isset($options['divider'])) {
            $options['extras'] = $options['extras'] ?? [];
            $options['extras'] = array_merge($options['extras'], ['divider' => true]);
        }

        if (isset($options['icon'])) {
            $options['extras'] = $options['extras'] ?? [];
            $options['extras'] = array_merge($options['extras'], ['icon' => $options['icon']]);
        }

        if (isset($options['route']) && is_array($options['route'])) {
            $options['routeParameters'] = $options['route']['[parameters'] ?? [];
            $options['route'] = $options['route']['name'];
        }

        foreach ($this->parsers as $parser) {
            if ($result = $parser($options)) {
                $options = $result;
            }
        }

        unset($options['child']);

        return [
            'options' => $options,
            'child' => $child,
        ];
    }

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


Question:
Returns `True` if `obj` is a class implementing all of `interfaces` or an
    instance of such class.

    `interfaces` can be a single :term:`interface` class or an iterable of
    interface classes.

def isimplementation(obj, interfaces):

    if not inspect.isclass(obj):
        isimplementation(obj.__class__, interfaces)
    if not isinstance(interfaces, collections.Iterable):
        interfaces = [interfaces]
    return frozenset(interfaces).issubset(
        get_implemented_interfaces(obj)
    )

function _Type(
    type,       // :: String
    name,       // :: String
    url,        // :: String
    arity,      // :: NonNegativeInteger
    format,
    // :: Nullable ((String -> String, String -> String -> String) -> String)
    supertypes, // :: Array Type
    test,       // :: Any -> Boolean
    tuples      // :: Array (Array3 String (a -> Array b) Type)
  ) {
    var t = Object.create (Type$prototype);
    t._test = test;
    t._extractors = tuples.reduce (function(_extractors, tuple) {
      _extractors[tuple[0]] = tuple[1];
      return _extractors;
    }, {});
    t.arity = arity;  // number of type parameters
    t.extractors = Z.map (B (toArray), t._extractors);
    t.format = format || function(outer, inner) {
      return Z.reduce (function(s, tuple) {
        return s +
               outer (' ') +
               when (tuple[2].arity > 0)
                    (parenthesize (outer))
                    (inner (tuple[0]) (show (tuple[2])));
      }, outer (name), tuples);
    };
    t.keys = tuples.map (function(tuple) { return tuple[0]; });
    t.name = name;
    t.supertypes = supertypes;
    t.type = type;
    t.types = tuples.reduce (function(types, tuple) {
      types[tuple[0]] = tuple[2];
      return types;
    }, {});
    t.url = url;
    return t;
  }

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


Question:
/* (non-Javadoc)
@see nz.co.senanque.workflow.WorkflowManager#getProcessDefinition(java.lang.String)

@Override
	public ProcessDefinition getProcessDefinition(String name) {
		for (ProcessDefinition pd: m_allProcesses) {
			if (pd.getName().equals(name)) {
				return pd;
			}
		}
		return null;
	}

def connection_made(self, transport):

        self.transport = transport
        self.loop = transport.loop
        self._cmd_lock = asyncio.Lock(loop=self.loop)
        self._wd_lock = asyncio.Lock(loop=self.loop)
        self._cmdq = asyncio.Queue(loop=self.loop)
        self._msgq = asyncio.Queue(loop=self.loop)
        self._updateq = asyncio.Queue(loop=self.loop)
        self._readbuf = b''
        self._update_cb = None
        self._received_lines = 0
        self._msg_task = self.loop.create_task(self._process_msgs())
        self._report_task = None
        self._watchdog_task = None
        self.status = {}
        self.connected = True

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


Question:
Compute the repository credentials name

@return string

protected function computeCredentialsName($prefix = null) {
		if (!$prefix) {
			$paths = $this->get('paths');
			if ($paths && isset($paths['default'])) {
				$prefix = $paths['default'];
			}
		}
		preg_match('/([http:\/\/|https:\/\/|ssh:\/\/])*(\w@)*([\w\.\-_]{1,}+)/', $prefix, $prefix);
		if (count($prefix)) return end($prefix);
		return basename($this->repository->getDir());
    }

def git_repos(options = {})
      ensure_ready!(:authorization)
      response = connection.get(git_repo_path, options)
      checked_response_body(response)
    end

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


Question: // UpdateModel implements ModelUpdater.

func (s *store) UpdateModel(controllerName, modelName string, details ModelDetails) error {
	if err := ValidateControllerName(controllerName); err != nil {
		return errors.Trace(err)
	}
	if err := ValidateModel(modelName, details); err != nil {
		return errors.Trace(err)
	}

	releaser, err := s.acquireLock()
	if err != nil {
		return errors.Annotatef(err,
			"cannot acquire lock file for updating model %s on controller %s", modelName, controllerName,
		)
	}
	defer releaser.Release()

	return errors.Trace(updateModels(
		controllerName,
		func(models *ControllerModels) (bool, error) {
			oldDetails, ok := models.Models[modelName]
			if ok && details == oldDetails {
				return false, nil
			}
			if ok && oldDetails.ModelType == "" && details.ModelType != model.IAAS ||
				oldDetails.ModelType != "" && oldDetails.ModelType != details.ModelType {
				oldModelType := oldDetails.ModelType
				if oldModelType == "" {
					oldModelType = model.IAAS
				}
				return false, errors.Errorf(
					"model type was %q, cannot change to %q", oldModelType, details.ModelType)
			}
			models.Models[modelName] = details
			return true, nil
		},
	))
}

public void setUVs(float u, float v, float U, float V)
	{
		this.u = u;
		this.v = v;
		this.U = U;
		this.V = V;
	}

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


Question:
Get a Facebook user's feed
@return object Feed

public function getFacebookUser()
    {

        /**
         * Request a token from Facebook Graph API
         */
        $endpoint = 'https://graph.facebook.com/oauth/access_token';
        $data = array(
            'grant_type'    => 'client_credentials',
            'client_id'     => $this->args['api_user'],
            'client_secret' => $this->args['api_secret']
        );

        $curl = new \Modularity\Helper\Curl();
        $token = $curl->request('GET', $endpoint, $data);

        if (strpos($token, 'error') !== false) {
            $error = json_decode($token);
            return $error;
        }

        //Decode token
        $token = json_decode($token);

        /**
         * Request the posts
         */
        $endpoint = 'https://graph.facebook.com/' . $this->args['query'] . '/posts';
        $data = array(
            'access_token' => $token->access_token,
            'fields'       => 'from, full_picture, picture, message, created_time, object_id, link, name, caption, description, icon, type, status_type, likes'
        );
        $feed = $curl->request('GET', $endpoint, $data);

        //Valid data object
        if(isset(json_decode($feed)->data)) {
            return json_decode($feed)->data;
        }

        //Return whatever exists, let error handler fix the rest.
        return json_decode($feed);
    }

public function getIterator()
    {
        $resourcesGetMethod = $this->pageStreamingDescriptor->getResourcesGetMethod();
        foreach ($this->getResponseObject()->$resourcesGetMethod() as $element) {
            yield $element;
        }
    }

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