Question:
Run the callbacks and then persist this object in the datastore.

 @since 0.2.0

def save(_options = {})
      self.class.create_table

      if new_record?
        conditions = { unless_exists: [self.class.hash_key] }
        conditions[:unless_exists] << range_key if range_key

        run_callbacks(:create) { persist(conditions) }
      else
        persist
      end
    end

def update_function_configuration(self, vpc_config):

        LOG.info('Updating configuration for lambda function: %s', self.app_name)

        try:
            self.lambda_client.update_function_configuration(
                Environment=self.lambda_environment,
                FunctionName=self.app_name,
                Runtime=self.runtime,
                Role=self.role_arn,
                Handler=self.handler,
                Description=self.description,
                Timeout=int(self.timeout),
                MemorySize=int(self.memory),
                VpcConfig=vpc_config)

            if self.concurrency_limit:
                self.lambda_client.put_function_concurrency(
                    FunctionName=self.app_name,
                    ReservedConcurrentExecutions=self.concurrency_limit
                )
            else:
                self.lambda_client.delete_function_concurrency(FunctionName=self.app_name)

        except boto3.exceptions.botocore.exceptions.ClientError as error:
            if 'CreateNetworkInterface' in error.response['Error']['Message']:
                message = '{0} is missing "ec2:CreateNetworkInterface"'.format(self.role_arn)
                LOG.debug(message)
                raise SystemExit(message)

            raise
        LOG.info('Updating Lambda function tags')

        lambda_arn = get_lambda_arn(self.app_name, self.env, self.region)
        self.lambda_client.tag_resource(Resource=lambda_arn, Tags={'app_group': self.group, 'app_name': self.app_name})

        LOG.info("Successfully updated Lambda configuration.")

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


Question:
Return the IP address of the current user

@return string ip address

public static function ip()
    {
        if (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('HTTP_X_FORWARDED')) {
            $ip = getenv('HTTP_X_FORWARDED');
        } elseif (getenv('HTTP_FORWARDED_FOR')) {
            $ip = getenv('HTTP_FORWARDED_FOR');
        } elseif (getenv('HTTP_FORWARDED')) {
            $ip = getenv('HTTP_FORWARDED');
        } elseif (getenv('REMOTE_ADDR')){
            $ip = getenv('REMOTE_ADDR');
        } else {
            $ip = 'UNKNOWN';
        }

        return $ip;
    }

function set_login( $uname = '', $passwd = '' )
    {
        if ( strlen($uname) > 0 )
        {
            $this->remote_uname = $uname;
        }

        if ( strlen($passwd) > 0 )
        {
            $this->remote_passwd = $passwd;
        }

    }

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


Question:
// insert adds the provided key to this node and returns any ID that has
// been overwritten.  This method should only be called on leaf nodes.

func (n *Node) insert(comparator Comparator, key *Key) *Key {
	var overwrittenKey *Key
	i := n.search(comparator, key.Value)
	if i == len(n.ChildValues) {
		n.ChildValues = append(n.ChildValues, key.Value)
	} else {
		if n.ChildValues[i] == key.Value {
			overwrittenKey = n.ChildKeys[i]
			n.ChildKeys[i] = key
			return overwrittenKey
		} else {
			n.ChildValues = append(n.ChildValues, 0)
			copy(n.ChildValues[i+1:], n.ChildValues[i:])
			n.ChildValues[i] = key.Value
		}
	}

	if n.IsLeaf && i == len(n.ChildKeys) {
		n.ChildKeys = append(n.ChildKeys, key)
	} else {
		n.ChildKeys = append(n.ChildKeys, nil)
		copy(n.ChildKeys[i+1:], n.ChildKeys[i:])
		n.ChildKeys[i] = key
	}

	return overwrittenKey
}

def _do_document(self, node):
        ''''''

        self.documentOrder = _LesserElement
        for child in node.childNodes:
            if child.nodeType == Node.ELEMENT_NODE:
                self.documentOrder = _Element        # At document element
                self._do_element(child)
                self.documentOrder = _GreaterElement # After document element
            elif child.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
                self._do_pi(child)
            elif child.nodeType == Node.COMMENT_NODE:
                self._do_comment(child)
            elif child.nodeType == Node.DOCUMENT_TYPE_NODE:
                pass
            else:
                raise TypeError, str(child)

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


Question: Marshall the given parameter object.

public void marshall(DescribeEventAggregatesRequest describeEventAggregatesRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeEventAggregatesRequest.getFilter(), FILTER_BINDING);
            protocolMarshaller.marshall(describeEventAggregatesRequest.getAggregateField(), AGGREGATEFIELD_BINDING);
            protocolMarshaller.marshall(describeEventAggregatesRequest.getMaxResults(), MAXRESULTS_BINDING);
            protocolMarshaller.marshall(describeEventAggregatesRequest.getNextToken(), NEXTTOKEN_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question: Method: read_wmc_Server

function(layerContext, node) {
        layerContext.version = node.getAttribute("version");
         layerContext.url = this.getOnlineResource_href(node);
         layerContext.metadata.servertitle = node.getAttribute("title");
    }

public alluxio.grpc.MetricValue getMetricsOrDefault(
      java.lang.String key,
      alluxio.grpc.MetricValue defaultValue) {
    if (key == null) { throw new java.lang.NullPointerException(); }
    java.util.Map<java.lang.String, alluxio.grpc.MetricValue> map =
        internalGetMetrics().getMap();
    return map.containsKey(key) ? map.get(key) : defaultValue;
  }

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


Question:
@return void

@throws MappingException

private function makeGenerator()
    {
        if ($this->generatorStrategy !== null) {
            switch ($this->generatorStrategy) {
                case self::GENERATOR_TYPE_ALNUM:
                    $this->generator = new AlnumGenerator($this->className, $this->name);

                    if (isset($this->generatorOptions['pad'])) {
                        $this->generator->setPad($this->generatorOptions['pad']);
                    }
                    if (isset($this->generatorOptions['chars'])) {
                        $this->generator->setChars($this->generatorOptions['chars']);
                    } elseif (isset($this->generatorOptions['awkwardSafe'])) {
                        $this->generator->setAwkwardSafeMode($this->generatorOptions['awkwardSafe']);
                    }

                    break;

                case self::GENERATOR_TYPE_INCREMENT:
                    $this->generator = new IncrementGenerator($this->className, $this->name);

                    if (isset($this->generatorOptions['hash'])) {
                        $this->generator->setHash($this->generatorOptions['key']);
                    }
                    if (isset($this->generatorOptions['range'])) {
                        $this->generator->setRange($this->generatorOptions['range']);
                    }
                    if (isset($this->generatorOptions['startingValue'])) {
                        $this->generator->setStartingValue($this->generatorOptions['startingValue']);
                    }
                    if (isset($this->generatorOptions['table'])) {
                        $this->generator->setTable($this->generatorOptions['table']);
                    }

                    break;

                case self::GENERATOR_TYPE_UUID:
                    $this->generator = new UuidGenerator();

                    if (isset($this->generatorOptions['salt'])) {
                        $this->generator->setSalt($this->generatorOptions['salt']);
                    }

                    break;

                case self::GENERATOR_TYPE_CUSTOM:
                    if (empty($this->generatorOptions['class'])) {
                        throw MappingException::missingCustomGeneratorClass($this);
                    }

                    $customGenerator = new $this->generatorOptions['class'];
                    if (!$customGenerator instanceof ValueGenerator) {
                        throw MappingException::classIsNotAValidGenerator(get_class($customGenerator));
                    }

                    $methods = get_class_methods($customGenerator);
                    foreach ($this->generatorOptions as $name => $value) {
                        $method = 'set' . ucfirst($name);
                        if (!in_array($method, $methods)) {
                            throw MappingException::missingGeneratorSetter(get_class($customGenerator), $name);
                        }

                        $customGenerator->$method($value);
                    }

                    $this->generator = $customGenerator;

                    break;

                default:
                    throw new MappingException('Unknown generator type: ' . $this->generatorStrategy);
            }
        }
    }

public static final Response OK(Representation r, HeaderField ... header){
        return new Response(ResponseCode.OK, r, header);
    }

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


Question:
returns a link that restricts the current search to the category.

@return string

public function GetSearchRestrictionLink()
    {
        // get current search... then add filter
        $oShop = TdbShop::GetInstance();
        $oSearchCache = &$oShop->GetActiveSearchObject();
        //$oSearchCache->aFilter[TdbShopManufacturer::FILTER_KEY_NAME] = $this->id;
        return $oSearchCache->GetSearchLink(array(TdbShopManufacturer::FILTER_KEY_NAME => $this->id));
    }

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

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


Question:
Taken from ``django.contrib.admin.autodiscover`` and used to run
    any calls to the ``processor_for`` decorator.

def autodiscover():

    global LOADED
    if LOADED:
        return
    LOADED = True
    for app in get_app_name_list():
        try:
            module = import_module(app)
        except ImportError:
            pass
        else:
            try:
                import_module("%s.page_processors" % app)
            except:
                if module_has_submodule(module, "page_processors"):
                    raise

def add_network_to_dhcp_agent(self, dhcp_agent, body=None):
        """"""
        return self.post((self.agent_path + self.DHCP_NETS) % dhcp_agent,
                         body=body)

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


Question:
Read a single integer from the current file.

@return int

protected function readInteger()
    {
        if ($this->littleEndian) {
            $result = unpack('Vint', fread($this->file, 4));
        } else {
            $result = unpack('Nint', fread($this->file, 4));
        }

        return $result['int'];
    }

public static BufferedReader newBufferedReader(Path path, Charset charset) throws IOException {
        return new BufferedReader(new InputStreamReader(newInputStream(path), charset));
    }

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


Question:
Sets the session namespace

@param string $name

public function setNamespace($name)
	{
		$this->config['namespace'] = is_bool($name) ? $name : (string) $name;

		if ($this->config['namespace'] === true)
		{
			$this->config['namespace'] = $this->app ? $app->getName() : false;
		}

		$this->data->setNamespace($this->config['namespace']);
	}

public function addExpression(
            O\Expression $expression,
            IParameterHasher $hasher,
            IFunction $context = null,
            $data = null
    ) {
        $this->parameters[] = new ExpressionParameter($expression, $hasher, $context, $data);
    }

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


Question:
Scope query with all the given widgets.

@param \Illuminate\Database\Eloquent\Builder $query
@param int|string|array|\ArrayAccess|WidgetModelContract $widgets
@param string $column

@return \Illuminate\Database\Eloquent\Builder

public function scopeWithAllWidgets(Builder $query, $widgets, string $column = 'id'): Builder
    {
        $widgets = static::isWidgetsStringBased($widgets)
            ? $widgets : static::hydrateWidgets($widgets)->pluck($column);

        collect($widgets)->each(function ($widget) use ($query, $column) {
            $query->whereHas('widgets', function (Builder $query) use ($widget, $column) {
                return $query->where($column, $widget);
            });
        });

        return $query;
    }

public function getQueryString()
    {
        $dialect = Dialect::create($this->_adapter->getDialect(), $this);
        return $dialect->getSqlStatement();
    }

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


Question: Remove from sys.modules the modules imported by the debuggee.

def reset(self):
        """"""
        if not self.hooked:
            self.hooked = True
            sys.path_hooks.append(self)
            sys.path.insert(0, self.PATH_ENTRY)
            return

        for modname in self:
            if modname in sys.modules:
                del sys.modules[modname]
                submods = []
                for subm in sys.modules:
                    if subm.startswith(modname + '.'):
                        submods.append(subm)
                # All submodules of modname may not have been imported by the
                # debuggee, but they are still removed from sys.modules as
                # there is no way to distinguish them.
                for subm in submods:
                    del sys.modules[subm]
        self[:] = []

def Unregister(self, name):

    precondition.AssertType(name, Text)

    try:
      del self._constructors[name]
    except KeyError:
      raise ValueError("Constructor with name '%s' is not registered" % name)

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


Question:
List consumer group

        :type project: string
        :param project: project name

        :type logstore: string
        :param logstore: logstore name

        :return: ListConsumerGroupResponse

def list_consumer_group(self, project, logstore):

        resource = "/logstores/" + logstore + "/consumergroups"
        params = {}
        headers = {}

        (resp, header) = self._send("GET", project, None, resource, params, headers)
        return ListConsumerGroupResponse(resp, header)

func TextProducer() Producer {
	return ProducerFunc(func(writer io.Writer, data interface{}) error {
		if writer == nil {
			return errors.New("TextProducer requires a writer") // early exit
		}

		if data == nil {
			return errors.New("no data given to produce text from")
		}

		if tm, ok := data.(encoding.TextMarshaler); ok {
			txt, err := tm.MarshalText()
			if err != nil {
				return fmt.Errorf("text producer: %v", err)
			}
			_, err = writer.Write(txt)
			return err
		}

		if str, ok := data.(error); ok {
			_, err := writer.Write([]byte(str.Error()))
			return err
		}

		if str, ok := data.(fmt.Stringer); ok {
			_, err := writer.Write([]byte(str.String()))
			return err
		}

		v := reflect.Indirect(reflect.ValueOf(data))
		if t := v.Type(); t.Kind() == reflect.Struct || t.Kind() == reflect.Slice {
			b, err := swag.WriteJSON(data)
			if err != nil {
				return err
			}
			_, err = writer.Write(b)
			return err
		}
		if v.Kind() != reflect.String {
			return fmt.Errorf("%T is not a supported type by the TextProducer", data)
		}

		_, err := writer.Write([]byte(v.String()))
		return err
	})
}

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


Question:
Lists all of the available REST API operations.

@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object

public ServiceFuture<OperationListResultInner> listAsync(final ServiceCallback<OperationListResultInner> serviceCallback) {
        return ServiceFuture.fromResponse(listWithServiceResponseAsync(), serviceCallback);
    }

public void putListener(CallbackType callbackType, Method method) {
    if (callbacks == null) {
      callbacks = new EnumMap<>(CallbackType.class);
    }
    Method oldMethod = callbacks.put(callbackType, method);
    if (oldMethod != null) {
      String format = "Class %s has at least two methods, %s and %s, with annotation of %s. "
          + "At most one method is allowed for a given callback type. ";
      String message = String.format(format, listenerClass.getName(), oldMethod.getName(),
          method.getName(), callbackType.getAnnotationClass().getName());
      throw new EntityManagerException(message);
    }
  }

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


Question:
Sets the default action to update a resource. If the resource is
 singular, updates the parent's associated resource. Otherwise, updates the
 resource directly.

def default_action_block
      proc do
        begin
          record = if resource.singular
                    parent_model = resource.parent.model.find(parent_resource_id)
                    parent_model.send resource.name
                  else
                    record = model.find(params[:id])
                  end

          record.update(instance_eval(&@strong_params))
          body record.reload
        rescue ActionController::ParameterMissing => error
          body error.message
          status :bad_request
        end
      end
    end

public function deleteAction(Request $request, Role $role, RoleAssignment $roleAssignment): Response
    {
        $this->denyAccessUnlessGranted(new Attribute('role', 'assign'));
        $form = $this->formFactory->deleteRoleAssignment(
            new RoleAssignmentDeleteData($roleAssignment)
        );
        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            $result = $this->submitHandler->handle($form, function (RoleAssignmentDeleteData $data) use ($role) {
                $roleAssignment = $data->getRoleAssignment();
                $this->roleService->removeRoleAssignment($roleAssignment);

                $this->notificationHandler->success(
                    $this->translator->trans(
                        /** @Desc("Assignment on role '%role%' removed.") */
                        'role.assignment_delete.success',
                        ['%role%' => $role->identifier],
                        'role'
                    )
                );

                return new RedirectResponse($this->generateUrl('ezplatform.role.view', [
                    'roleId' => $role->id,
                ]));
            });

            if ($result instanceof Response) {
                return $result;
            }
        }

        return $this->redirect($this->generateUrl('ezplatform.role.view', [
            'roleId' => $role->id,
        ]));
    }

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


Question: Writes out data for a single source.

def write_source(self, source, comment=None, reject=False):

        if not self._header_written:
            observations = [reading.get_observation() for reading in source.get_readings()]
            self.write_headers(observations, self.sys_header)

        self._write_source(source, comment=comment, reject=reject)

def parse(self, limit=None):

        if limit is not None:
            LOG.info("Only parsing first %s rows fo each file", str(limit))

        LOG.info("Parsing files...")

        self._process_straininfo(limit)
        # the following will provide us the hash-lookups
        # These must be processed in a specific order

        # mapping between assays and ontology terms
        self._process_ontology_mappings_file(limit)
        # this is the metadata about the measurements
        self._process_measurements_file(limit)
        # get all the measurements per strain
        self._process_strainmeans_file(limit)

        # The following will use the hash populated above
        # to lookup the ids when filling in the graph
        self._fill_provenance_graph(limit)

        LOG.info("Finished parsing.")
        return

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


Question: note: this method was taken from the mongoose project

function CustomError(msg) {
    BaseError.call(this);
    Error.captureStackTrace(this, arguments.callee);
    this.message = msg || defaultMessage || 'An error occurred';
    this.name = name;
    this.code = code;
  }

private function registerCommands()
    {
        // monashee:backup
        $this->app['command.monashee.backup'] = $this->app->share(function() {
            return $this->app->make('Monashee\Backup\Commands\MonasheeBackup');
        });

        $this->commands('command.monashee.backup');
    }

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


Question:
Returns the size of the file in bytes.

@access public
@author Jerome Bogaerts <jerome@taotesting.com>
@return int

public function getSize()
    {
        if (is_null($this->size)) {
            $this->size = is_null($this->getFile()) ? 0 : $this->getFile()->getSize();
        }
        return $this->size;
    }

def do_quality(self, quality):
        """"""
        infile = self.tmpfile
        outfile = self.basename + '.col'
        # Quality (bit-depth):
        if (quality == 'grey' or quality == 'gray'):
            if (self.shell_call('cat ' + infile + ' | ' + self.ppmtopgm + ' > ' + outfile)):
                raise IIIFError(
                    text="Oops... got nonzero output from ppmtopgm.")
            self.tmpfile = outfile
        elif (quality == 'bitonal'):
            if (self.shell_call('cat ' + infile + ' | ' + self.ppmtopgm + ' | ' + self.pamditherbw + ' > ' + outfile)):
                raise IIIFError(
                    text="Oops... got nonzero output from ppmtopgm.")
            self.tmpfile = outfile
        elif ((quality == 'native' and self.api_version < '2.0') or
              (quality == 'default' and self.api_version >= '2.0') or
              quality == 'color'):
            self.tmpfile = infile
        else:
            raise IIIFError(code=400, parameter='quality',
                            text="Unknown quality parameter value requested.")

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


Question: // Pick adds the given fields to the result

func (b *Base) Pick(keys ...string) Serializer {
	return b.PickFunc(identity, keys...)
}

public function generate($type)
    {
        return function ($row, $control, $templates = []) use ($type) {
            $data = $this->buildFieldByType($type, $row, $control);
            return $this->render($templates, $data);
        };
    }

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


Question: Alternate version of Index that uses the embed master view.

public function Embed($DiscussionID = '', $DiscussionStub = '', $Offset = '', $Limit = '') {
      $this->Title(T('Comments'));
      $this->AddDefinition('DoInform', '0'); // Suppress inform messages on embedded page.
      $this->AddDefinition('SelfUrl', Gdn::Request()->PathAndQuery());
      $this->AddDefinition('Embedded', TRUE);
      $this->CanEditComments = FALSE; // Don't show the comment checkboxes on the embed comments page
      $this->Theme = C('Garden.CommentsTheme', $this->Theme);
      Gdn_Theme::Section('Comments');

      // Add some css to help with the transparent bg on embedded comments
      if ($this->Head)
         $this->Head->AddString('<style type="text/css">
body { background: transparent !important; }
</style>');
      $Session = Gdn::Session();
      $this->AddJsFile('jquery.gardenmorepager.js');
      $this->AddJsFile('jquery.autogrow.js');
      $this->AddJsFile('discussion.js');
      $this->RemoveJsFile('autosave.js');
      $this->MasterView = 'empty';

      // Define incoming variables (prefer querystring parameters over method parameters)
      $DiscussionID = (is_numeric($DiscussionID) && $DiscussionID > 0) ? $DiscussionID : 0;
      $DiscussionID = GetIncomingValue('vanilla_discussion_id', $DiscussionID);
      $Offset = GetIncomingValue('Offset', $Offset);
      $Limit = GetIncomingValue('Limit', $Limit);
      $vanilla_identifier = GetIncomingValue('vanilla_identifier', '');
      // Only allow vanilla identifiers of 32 chars or less - md5 if larger
      if (strlen($vanilla_identifier) > 32) {
         $vanilla_identifier = md5($vanilla_identifier);
      }
      $vanilla_type = GetIncomingValue('vanilla_type', 'page');
      $vanilla_url = GetIncomingValue('vanilla_url', '');
      $vanilla_category_id = GetIncomingValue('vanilla_category_id', '');
      $ForeignSource = array(
         'vanilla_identifier' => $vanilla_identifier,
         'vanilla_type' => $vanilla_type,
         'vanilla_url' => $vanilla_url,
         'vanilla_category_id' => $vanilla_category_id
      );
      $this->SetData('ForeignSource', $ForeignSource);

      $SortComments = C('Garden.Embed.SortComments') == 'desc' ? 'desc' : 'asc';
      $this->SetData('SortComments', $SortComments);

      // Retrieve the discussion record.
      $Discussion = FALSE;
      if ($DiscussionID > 0) {
         $Discussion = $this->DiscussionModel->GetID($DiscussionID);
      } else if ($vanilla_identifier != '' && $vanilla_type != '') {
         $Discussion = $this->DiscussionModel->GetForeignID($vanilla_identifier, $vanilla_type);
      }

      if ($Discussion) {
         $this->SetData('Discussion', $Discussion, TRUE);
         $this->SetData('DiscussionID', $Discussion->DiscussionID, TRUE);
         $this->Title($this->Discussion->Name);

         // Actual number of comments, excluding the discussion itself
         $ActualResponses = $this->Discussion->CountComments;
         // Define the query offset & limit
         if (!is_numeric($Limit) || $Limit < 0)
            $Limit = C('Garden.Embed.CommentsPerPage', 30);

         $OffsetProvided = $Offset != '';
         list($Offset, $Limit) = OffsetLimit($Offset, $Limit);
         $this->Offset = $Offset;
         if (C('Vanilla.Comments.AutoOffset')) {
            if ($ActualResponses <= $Limit)
               $this->Offset = 0;

            if ($this->Offset == $ActualResponses)
               $this->Offset -= $Limit;
         } else if ($this->Offset == '')
            $this->Offset = 0;

         if ($this->Offset < 0)
            $this->Offset = 0;

         // Set the canonical url to have the proper page title.
         $this->CanonicalUrl(DiscussionUrl($Discussion, PageNumber($this->Offset, $Limit)));

         // Load the comments.
         $CurrentOrderBy = $this->CommentModel->OrderBy();
         if (StringBeginsWith(GetValueR('0.0', $CurrentOrderBy), 'c.DateInserted'))
            $this->CommentModel->OrderBy('c.DateInserted '.$SortComments); // allow custom sort

         $this->SetData('Comments', $this->CommentModel->Get($this->Discussion->DiscussionID, $Limit, $this->Offset), TRUE);

         if (count($this->CommentModel->Where()) > 0)
            $ActualResponses = FALSE;

         $this->SetData('_Count', $ActualResponses);

         // Build a pager
         $PagerFactory = new Gdn_PagerFactory();
         $this->EventArguments['PagerType'] = 'MorePager';
         $this->FireEvent('BeforeBuildPager');
         $this->Pager = $PagerFactory->GetPager($this->EventArguments['PagerType'], $this);
         $this->Pager->ClientID = 'Pager';
         $this->Pager->MoreCode = 'More Comments';
         $this->Pager->Configure(
            $this->Offset,
            $Limit,
            $ActualResponses,
            'discussion/embed/'.$this->Discussion->DiscussionID.'/'.Gdn_Format::Url($this->Discussion->Name).'/%1$s'
         );
         $this->Pager->CurrentRecords = $this->Comments->NumRows();
         $this->FireEvent('AfterBuildPager');
      }

      // Define the form for the comment input
      $this->Form = Gdn::Factory('Form', 'Comment');
      $this->Form->Action = Url('/vanilla/post/comment/');
      $this->Form->AddHidden('CommentID', '');
      $this->Form->AddHidden('Embedded', 'true'); // Tell the post controller that this is an embedded page (in case there are custom views it needs to pick up from a theme).
      $this->Form->AddHidden('DisplayNewCommentOnly', 'true'); // Only load/display the new comment after posting (don't load all new comments since the page last loaded).

      if ($this->Request->Get('title')) {
         $this->Form->SetValue('Name', $this->Request->Get('title'));
      }

      if ($Discussion) {
         $this->Form->AddHidden('DiscussionID', $Discussion->DiscussionID);
      }

      foreach ($ForeignSource as $Key => $Val) {
         // Drop the foreign source information into the form so it can be used if creating a discussion
         $this->Form->AddHidden($Key, $Val);
         // Also drop it into the definitions so it can be picked up for stashing comments
         $this->AddDefinition($Key, $Val);
      }

      // Retrieve & apply the draft if there is one:
      $Draft = FALSE;
      if (Gdn::Session()->UserID && $Discussion) {
         $DraftModel = new DraftModel();
         $Draft = $DraftModel->Get($Session->UserID, 0, 1, $Discussion->DiscussionID)->FirstRow();
         $this->Form->AddHidden('DraftID', $Draft ? $Draft->DraftID : '');
      }

      if ($Draft)
         $this->Form->SetFormValue('Body', $Draft->Body);
      else {
         // Look in the session stash for a comment
         $StashComment = $Session->Stash('CommentForForeignID_'.$ForeignSource['vanilla_identifier'], '', FALSE);
         if ($StashComment)
            $this->Form->SetFormValue('Body', $StashComment);
      }

      // Deliver JSON data if necessary
      if ($this->_DeliveryType != DELIVERY_TYPE_ALL) {
         if ($this->Discussion) {
            $this->SetJson('LessRow', $this->Pager->ToString('less'));
            $this->SetJson('MoreRow', $this->Pager->ToString('more'));
         }
         $this->View = 'comments';
      }

      if ($SortComments == 'desc')
         $this->AddDefinition('PrependNewComments', '1');

      // Report the discussion id so js can use it.
      if ($Discussion)
         $this->AddDefinition('DiscussionID', $Discussion->DiscussionID);

      $this->FireEvent('BeforeDiscussionRender');
      $this->Render();
   }

def makeindex_runs(self, gloss_files):
        '''

        '''
        gloss_changed = False
        for gloss in self.glossaries:
            make_gloss = False
            ext_i, ext_o = self.glossaries[gloss]
            fname_in = '%s.%s' % (self.project_name, ext_i)
            fname_out = '%s.%s' % (self.project_name, ext_o)
            if re.search('No file %s.' % fname_in, self.out):
                make_gloss = True
            if not os.path.isfile(fname_out):
                make_gloss = True
            else:
                with open(fname_out) as fobj:
                    try:
                        if gloss_files[gloss] != fobj.read():
                            make_gloss = True
                    except KeyError:
                        make_gloss = True

            if make_gloss:
                self.log.info('Running makeindex (%s)...' % gloss)
                try:
                    cmd = ['makeindex', '-q', '-s',
                           '%s.ist' % self.project_name,
                           '-o', fname_in, fname_out]
                    with open(os.devnull, 'w') as null:
                        Popen(cmd, stdout=null).wait()
                except OSError:
                    self.log.error(NO_LATEX_ERROR % 'makeindex')
                    sys.exit(1)
                gloss_changed = True

        return gloss_changed

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


Question:
Set the action name

@param string $value
@return Abstract

public function setActionName($value)
        {
            $this->_action = $value;
            /**
             * @see ZF-3465
             */
            if (null === $value) {
                $this->setParam($this->getActionKey(), $value);
            }
            return $this;
        }

public void setReturnType(String type) {
		if (!Strings.isEmpty(type)
				&& !Objects.equals("void", type)
				&& !Objects.equals(Void.class.getName(), type)) {
			this.sarlAction.setReturnType(newTypeRef(container, type));
		} else {
			this.sarlAction.setReturnType(null);
		}
	}

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


Question:
https://redis.io/commands/info

@param jedis   jedis object
@param section server, clients, memory, persistence, stats, replication, cpu, commandstats, cluster, keyspace
@return info string

public static String info(Jedis jedis, String section) {
        if (section == null || "".equals(section))
            return jedis.info();
        else
            return jedis.info(section);
    }

def create_node(**kwargs):
    '''

    '''
    name = kwargs['name']
    size = kwargs['size']
    image = kwargs['image']
    location = kwargs['location']
    networks = kwargs.get('networks')
    tag = kwargs.get('tag')
    locality = kwargs.get('locality')
    metadata = kwargs.get('metadata')
    firewall_enabled = kwargs.get('firewall_enabled')

    create_data = {
        'name': name,
        'package': size['name'],
        'image': image['name'],
    }
    if networks is not None:
        create_data['networks'] = networks

    if locality is not None:
        create_data['locality'] = locality

    if metadata is not None:
        for key, value in six.iteritems(metadata):
            create_data['metadata.{0}'.format(key)] = value

    if tag is not None:
        for key, value in six.iteritems(tag):
            create_data['tag.{0}'.format(key)] = value

    if firewall_enabled is not None:
        create_data['firewall_enabled'] = firewall_enabled

    data = salt.utils.json.dumps(create_data)

    ret = query(command='my/machines', data=data, method='POST',
                location=location)
    if ret[0] in VALID_RESPONSE_CODES:
        return ret[1]
    else:
        log.error('Failed to create node %s: %s', name, ret[1])

    return {}

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


Question:
@param             $code
@param string|null $email

@return bool

public function check($code, string $email = null)
    {
        try {
            $this->prep($code, $email);
            return true;
        } catch (DoormanException $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }

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

      valid
    end

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


Question:
获取配置

@param string $sName 配置的命名空间
@static
@access public
@return array

public static function get($sName) {
		$aReturn =& static::$_lStore[$sName];

		if (!$aReturn) {

			$sFileDefault =& static::$_lFileDefault[$sName];
			$sFile =& static::$_lFile[$sName];

			if (!$sFile && static::$_sDir) {
				$sGuess = static::$_sDir . $sName . '.php';
				if (file_exists($sGuess)) {
					$sFile = $sGuess;
				}
			}

			$aReturn = array_replace_recursive(
				$sFileDefault ? require $sFileDefault : [],
				$sFile ? require $sFile : []
			);
		}
		return $aReturn;
	}

protected function extractPayload($model, $comments = '')
    {
        $payload = [];
        preg_match('/@payload\ (.*)\n/i', $comments, $doc);
        $isArray = false;
        if (count($doc)) {
            $namespace = str_replace('{__API__}', $model, $doc[1]);
            if (false !== strpos($namespace, '[') && false !== strpos($namespace, ']')) {
                $namespace = str_replace(']', '', str_replace('[', '', $namespace));
                $isArray = true;
            }
            $payload = $this->extractModelFields($namespace);
            $reflector = new \ReflectionClass($namespace);
            $shortName = $reflector->getShortName();
        } else {
            $namespace = $model;
            $shortName = $model;
        }

        return [$namespace, $shortName, $payload, $isArray];
    }

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


Question:
how to reset array keys here?
as when jsonencoded the keys must be reset
not sure you would always want to reset as may need
to maintain sometimes?

public function sort(callable $callback = null)
    {
        $items = $this->getArrayCopy();
        $callback ? uasort($items, $callback) : asort($items);
        return new static($items);
    }

public function set(string $uri, string $query, EsiResponse $data)
    {

        if ($this->is_memcached)
            $this->memcached->set($this->buildCacheKey($uri, $query), serialize($data), 0);
        else
            $this->memcached->set($this->buildCacheKey($uri, $query), serialize($data), $this->flags, 0);
    }

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


Question:
// GetAWSKinesisStreamConsumerWithName retrieves all AWSKinesisStreamConsumer items from an AWS CloudFormation template
// whose logical ID matches the provided name. Returns an error if not found.

func (t *Template) GetAWSKinesisStreamConsumerWithName(name string) (*resources.AWSKinesisStreamConsumer, error) {
	if untyped, ok := t.Resources[name]; ok {
		switch resource := untyped.(type) {
		case *resources.AWSKinesisStreamConsumer:
			return resource, nil
		}
	}
	return nil, fmt.Errorf("resource %q of type AWSKinesisStreamConsumer not found", name)
}

def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'consumption_preference_category_id' in _dict:
            args['consumption_preference_category_id'] = _dict.get(
                'consumption_preference_category_id')
        else:
            raise ValueError(
                'Required property \'consumption_preference_category_id\' not present in ConsumptionPreferencesCategory JSON'
            )
        if 'name' in _dict:
            args['name'] = _dict.get('name')
        else:
            raise ValueError(
                'Required property \'name\' not present in ConsumptionPreferencesCategory JSON'
            )
        if 'consumption_preferences' in _dict:
            args['consumption_preferences'] = [
                ConsumptionPreferences._from_dict(x)
                for x in (_dict.get('consumption_preferences'))
            ]
        else:
            raise ValueError(
                'Required property \'consumption_preferences\' not present in ConsumptionPreferencesCategory JSON'
            )
        return cls(**args)

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


Question:
// GetImageInfo returns information about the registered image specified by
// imageStr. If the image has not been registered, nil is returned. The
// internal error is not modified by this method.

func (f *Fpdf) GetImageInfo(imageStr string) (info *ImageInfoType) {
	return f.images[imageStr]
}

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

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


Question: Convert from a native Python `datetime.time` value.

def from_native(cls, t):

        second = (1000000 * t.second + t.microsecond) / 1000000
        return Time(t.hour, t.minute, second, t.tzinfo)

def transformToNative(self):

        if self.isNative or not self.behavior or not self.behavior.hasNative:
            return self
        else:
            self_orig = copy.copy(self)
            try:
                return self.behavior.transformToNative(self)
            except Exception as e:
                # wrap errors in transformation in a ParseError
                lineNumber = getattr(self, 'lineNumber', None)

                if isinstance(e, ParseError):
                    if lineNumber is not None:
                        e.lineNumber = lineNumber
                    raise
                else:
                    msg = "In transformToNative, unhandled exception on line {0}: {1}: {2}"
                    msg = msg.format(lineNumber, sys.exc_info()[0], sys.exc_info()[1])
                    msg = msg + " (" + str(self_orig) + ")"
                    raise ParseError(msg, lineNumber)

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


Question:
// parseVaultTokenFromJWT returns a string iff the token was a JWT and we could
// extract the original token ID from inside

func parseVaultTokenFromJWT(token string) *string {
	if strings.Count(token, ".") != 2 {
		return nil
	}

	parsedJWT, err := squarejwt.ParseSigned(token)
	if err != nil {
		return nil
	}

	var claims squarejwt.Claims
	if err = parsedJWT.UnsafeClaimsWithoutVerification(&claims); err != nil {
		return nil
	}

	return &claims.ID
}

func ConvertCommentResourceID(request *http.Request, comment comment.Comment, additional ...CommentConvertFunc) *app.Comment {
	c := &app.Comment{
		Type: APIStringTypeComments,
		ID:   &comment.ID,
	}
	for _, add := range additional {
		add(request, &comment, c)
	}
	return c
}

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


Question:
Creates a PDO DSN for the adapter from $this->_config settings.

@return string

protected function _dsn()
    {
        $this->_checkRequiredOptions($this->_config);

        // check if using full connection string
        if (array_key_exists('host', $this->_config)) {
            $dsn = ';DATABASE=' . $this->_config['dbname']
            . ';HOSTNAME=' . $this->_config['host']
            . ';PORT='     . $this->_config['port']
            // PDO_IBM supports only DB2 TCPIP protocol
            . ';PROTOCOL=' . 'TCPIP;';
        } else {
            // catalogued connection
            $dsn = $this->_config['dbname'];
        }
        return $this->_pdoType . ': ' . $dsn;
    }

function parseDB(callback) {
    pgStructure(getConfig('database.host'), getConfig('database.database'), getConfig('database.user'),
        getConfig('database.password'), { port: getConfig('database.port'), schema: getConfig('database.schema') },
        callback);
}

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


Question:
Berechnet die Pruefziffer des uebergebenen Wertes. Die Berechung stammt
aus https://de.wikipedia.org/wiki/Luhn-Algorithmus#Java.

@param wert Wert (ohne Pruefziffer)
@return errechnete Pruefziffer

public String berechnePruefziffer(String wert) {
        int sum = getQuersumme(wert);
        return Integer.toString((10 - sum % 10) % 10);
    }

def rerank(args: argparse.Namespace):

    reranker = Reranker(args.metric, args.return_score)

    with utils.smart_open(args.reference) as reference, utils.smart_open(args.hypotheses) as hypotheses:
        for i, (reference_line, hypothesis_line) in enumerate(zip(reference, hypotheses), 1):
            reference = reference_line.strip()
            # Expects a JSON object with keys containing at least 'translations',
            # as returned by sockeye.translate's nbest output
            hypotheses = json.loads(hypothesis_line.strip())
            utils.check_condition('translations' in hypotheses,
                                  "Reranking requires nbest JSON input with 'translations' key present.")
            num_hypotheses = len(hypotheses['translations'])

            if not num_hypotheses > 1:
                logger.info("Line %d contains %d hypotheses. Nothing to rerank.", i, num_hypotheses)
                reranked_hypotheses = hypotheses
            else:
                reranked_hypotheses = reranker.rerank(hypotheses, reference)

            if args.output_best:
                if not num_hypotheses:
                    print()
                else:
                    print(reranked_hypotheses['translations'][0])
            else:
                print(json.dumps(reranked_hypotheses, sort_keys=True))

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


Question: display resource with specific id

public function show($id)
    {
        if(Request::isAjax()){
            $user = null;
            $message = '';

            try{
                $user = Sentry::findUserById($id);
            }catch(Exception $e){
                $message = $e->getMessage();
            }

            Response::headers()->set('Content-Type', 'application/json');
            Response::setBody(json_encode(
                array(
                    'success'   => !is_null($user),
                    'data'      => !is_null($user) ? $user->toArray() : $user,
                    'message'   => $message,
                    'code'      => is_null($user) ? 404 : 200
                )
            ));
        }else{

        }
    }

public function addHideId($hideId)
    {
        $hideIds = $this->getHideIds();

        if (!in_array($hideId, $hideIds)) {
            $hideIds[] = $hideId;
            $this->setHideIds($hideIds);
        }

        return $this;
    }

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


Question:
Attempt to create an AuthToken from user credentials.

@param array $credentials
@return bool|AuthToken

public function attempt(array $credentials) {
    $user = $this->users->retrieveByCredentials($credentials);

    if($user instanceof UserInterface && $this->users->validateCredentials($user, $credentials)) {
       return $this->create($user);
    }

    return false;
  }

private function check_signature(){
        if (!isset($this->config['token']) || empty($this->config['token'])) throw new \Exception('token is not defined!');
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $tmp = [$this->config['token'],$timestamp,$nonce];
        sort($tmp,SORT_STRING);
        $tmp_str = implode($tmp);
        $tmp_str = sha1($tmp_str);
        if ($tmp_str == $signature) return true;
        return false;
    }

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


Question: Auto Generated Code

def show_fibrechannel_interface_info_output_show_fibrechannel_interface_portsgroup_rbridgeid(self, **kwargs):

        config = ET.Element("config")
        show_fibrechannel_interface_info = ET.Element("show_fibrechannel_interface_info")
        config = show_fibrechannel_interface_info
        output = ET.SubElement(show_fibrechannel_interface_info, "output")
        show_fibrechannel_interface = ET.SubElement(output, "show-fibrechannel-interface")
        portsgroup_rbridgeid = ET.SubElement(show_fibrechannel_interface, "portsgroup-rbridgeid")
        portsgroup_rbridgeid.text = kwargs.pop('portsgroup_rbridgeid')

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

private function populateAvailableTypes($onlyAutowiringTypes = false)
    {
        $this->types = array();
        if (!$onlyAutowiringTypes) {
            $this->ambiguousServiceTypes = array();
        }

        foreach ($this->container->getDefinitions() as $id => $definition) {
            $this->populateAvailableType($id, $definition, $onlyAutowiringTypes);
        }
    }

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


Question:
load data from the given url, set it to JSON editor and load
the zoomable circles.

function loadData(dataUrl, jsonEditor) {

    // jQuery getJSON will read the file from a Web resources.
    $.getJSON(dataUrl, function(data) {
    //$.getJSON('data/simple-zoomable-circle.json', function(data) {
        // set data to JSON editor.
        jsonEditor.set(data);
        // update the JSON source code
        $('#jsonstring').html(JSON.stringify(data, null, 2));
        // remove the existing one.
        $('#svgpreview').empty();
        // build the circles...
        var options = {
          "margin":10,
          "diameter":500
        };
        $("#svgpreview").zoomableCircles(options, data);
        //console.log(JSON.stringify(data));
    });
}

@Override
  public Element useMarker(SVGPlot plot, Element parent, double x, double y, int stylenr, double size) {
    Element marker = plot.svgCircle(x, y, size * .5);
    final String col;
    if(stylenr == -1) {
      col = dotcolor;
    }
    else if(stylenr == -2) {
      col = greycolor;
    }
    else {
      col = colors.getColor(stylenr);
    }
    SVGUtil.setStyle(marker, SVGConstants.CSS_FILL_PROPERTY + ":" + col);
    parent.appendChild(marker);
    return marker;
  }

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


Question:
creates a search object and sets base criteria

@param boolean $default
@return MW_Common_Criteria_Interface

public function createSearch($default = false)
	{
		if( $default === true )
		{
			$object = $this->_createSearch( 'media' );
			$langid = $this->_getContext()->getLocale()->getLanguageId();

			if( $langid !== null )
			{
				$temp = array(
					$object->compare( '==', 'media.languageid', $langid ),
					$object->compare( '==', 'media.languageid', null ),
				);

				$expr = array(
					$object->getConditions(),
					$object->combine( '||', $temp ),
				);

				$object->setConditions( $object->combine( '&&', $expr ) );
			}

			return $object;
		}

		return parent::createSearch();
	}

protected void addCriteria(String column, String operator) {
    if (this.sbClause.length() == 0) {
      this.sbClause.append("WHERE");
    } else {
      this.sbClause.append(" AND");
    }
    this.sbClause.append(' ');
    this.sbClause.append(column);
    this.sbClause.append(' ');
    this.sbClause.append(operator);
    this.sbClause.append(" ?");
  }

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


Question: returns true of all keys are equal

def all_equal(keys, axis=semantics.axis_default):
    """"""
    index = as_index(keys, axis)
    return index.groups == 1

static function assertLooselyIdenticalIterable(iterable $expected, $actual, bool $canonicalizeKeys = false, string $message = '')
    {
        static::assertThat($actual, static::looselyIdenticalIterable($expected, $canonicalizeKeys), $message);
    }

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


Question: // NetworkConnect provides a mock function with given fields: ctx, _a1, _a2, config

func (_m *APIClient) NetworkConnect(ctx context.Context, _a1 string, _a2 string, config *network.EndpointSettings) error {
	ret := _m.Called(ctx, _a1, _a2, config)

	var r0 error
	if rf, ok := ret.Get(0).(func(context.Context, string, string, *network.EndpointSettings) error); ok {
		r0 = rf(ctx, _a1, _a2, config)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

func (context Context) Get(name string) (interface{}, bool) {
	if value, ok := context.Options[name]; ok {
		return value, true
	}

	return nil, false
}

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


Question:
Build class constructor that can be used with the <kw>new</kw> keyword
@param {_cClassData} class_data
@returns {function} The class constructor

function(class_data) {

		var prototype = {},
			skeleton = class_data.skeleton,
			serialized_value,
			constructor_actions = [],
			name,
			source,
			constructor,
			object_properties,
			uses_references = false,
			is_monomorphic = class_data.is_monomorphic;

		for (name in skeleton) {

			switch (skeleton[name].type) {
				case this.MEMBER_TYPES.STRING:
					if (is_monomorphic) {
						serialized_value = Firestorm.String.quote(skeleton[name].value);
					} else {
						prototype[name] = skeleton[name].value;
					}
					break;
				case this.MEMBER_TYPES.PRIMITIVE: // null, boolean, number
					if (is_monomorphic) {
						serialized_value = skeleton[name].value + '';
					} else {
						prototype[name] = skeleton[name].value;
					}
					break;
				case this.MEMBER_TYPES.EMPTY_ARRAY:
					serialized_value = "[]";
					break;
				case this.MEMBER_TYPES.INLINE_ARRAY:
					serialized_value = this._serializeInlineArray(skeleton[name].value);
					break;
				case this.MEMBER_TYPES.REGEXP:
				case this.MEMBER_TYPES.FUNCTION:
					prototype[name] = class_data.references[skeleton[name].index];
					break;
				case this.MEMBER_TYPES.SLICE_ARRAY:
					serialized_value = 'r[' + skeleton[name].index + '].slice()';
					uses_references = true;
					break;
				case this.MEMBER_TYPES.OBJECT:
					object_properties = [];
					if (this._serializeSkeleton(skeleton[name].skeleton, class_data, "\t", object_properties)) {
						uses_references = true;
					}
					serialized_value = object_properties.length
						? "{\n\t" + object_properties.join(",\n\t") + "\n}"
						: "{}";
					break;
				default:
					Lava.t("[_buildRealConstructor] unknown property descriptor type: " + skeleton[name].type);
			}

			if (serialized_value) {

				if (Lava.VALID_PROPERTY_NAME_REGEX.test(name)) {

					constructor_actions.push('this.' + name + ' = ' + serialized_value);

				} else {

					constructor_actions.push('this[' + Firestorm.String.quote(name) + '] = ' + serialized_value);

				}

				serialized_value = null;

			}

		}

		for (name in class_data.shared) {

			prototype[name] = class_data.shared[name];

		}

		prototype.Class = class_data;

		source = (uses_references ? ("var r=this.Class.references;\n") : '')
			+ constructor_actions.join(";\n")
			+ ";";

		if (class_data.skeleton.init) {

			source += "\nthis.init.apply(this, arguments);";

		}

		constructor = new Function(source);
		// for Chrome we could assign prototype object directly,
		// but in Firefox this will result in performance degradation
		Firestorm.extend(constructor.prototype, prototype);
		return constructor;

	}

def _generate_union_class_variant_creators(self, ns, data_type):

        for field in data_type.fields:
            if not is_void_type(field.data_type):
                field_name = fmt_func(field.name)
                field_name_reserved_check = fmt_func(field.name, check_reserved=True)
                if is_nullable_type(field.data_type):
                    field_dt = field.data_type.data_type
                else:
                    field_dt = field.data_type
                self.emit('@classmethod')
                self.emit('def {}(cls, val):'.format(field_name_reserved_check))
                with self.indent():
                    self.emit('"""')
                    self.emit_wrapped_text(
                        'Create an instance of this class set to the ``%s`` '
                        'tag with value ``val``.' % field_name)
                    self.emit()
                    self.emit(':param {} val:'.format(
                        self._python_type_mapping(ns, field_dt)))
                    self.emit(':rtype: {}'.format(
                        self._python_type_mapping(ns, data_type)))
                    self.emit('"""')
                    self.emit("return cls('{}', val)".format(field_name))
                self.emit()

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


Question:
api :POST, "/hypervisors", N_("Update the hypervisors information for environment")
desc 'See virt-who tool for more details.'

def hypervisors_update
      login = User.consumer? ? User.anonymous_api_admin.login : User.current.login
      task = User.as(login) do
        params['owner'] = @organization.label #override owner label if
        params['env'] = nil #hypervisors don't need an environment
        sync_task(::Actions::Katello::Host::Hypervisors, params.except(:controller, :action, :format).to_h)
      end
      render :json => task.output[:results]
    end

def role_create(role, principal, endpoint_id):

    principal_type, principal_val = principal

    client = get_client()

    if principal_type == "identity":
        principal_val = maybe_lookup_identity_id(principal_val)
        if not principal_val:
            raise click.UsageError(
                "Identity does not exist. "
                "Use --provision-identity to auto-provision an identity."
            )
    elif principal_type == "provision-identity":
        principal_val = maybe_lookup_identity_id(principal_val, provision=True)
        principal_type = "identity"

    role_doc = assemble_generic_doc(
        "role", principal_type=principal_type, principal=principal_val, role=role
    )

    res = client.add_endpoint_role(endpoint_id, role_doc)
    formatted_print(res, simple_text="ID: {}".format(res["id"]))

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


Question:
Method: update
Update the size of the bars, and the labels they contain.

function() {
        var res = this.map.getResolution();
        if (!res) {
            return;
        }

        var curMapUnits = this.map.getUnits();
        var inches = OpenLayers.INCHES_PER_UNIT;

        // convert maxWidth to map units
        var maxSizeData = this.maxWidth * res * inches[curMapUnits];
        var geodesicRatio = 1;
        if(this.geodesic === true) {
            var maxSizeGeodesic = (this.map.getGeodesicPixelSize().w ||
                0.000001) * this.maxWidth;
            var maxSizeKilometers = maxSizeData / inches["km"];
            geodesicRatio = maxSizeGeodesic / maxSizeKilometers;
            maxSizeData *= geodesicRatio;
        }

        // decide whether to use large or small scale units
        var topUnits;
        var bottomUnits;
        if(maxSizeData > 100000) {
            topUnits = this.topOutUnits;
            bottomUnits = this.bottomOutUnits;
        } else {
            topUnits = this.topInUnits;
            bottomUnits = this.bottomInUnits;
        }

        // and to map units units
        var topMax = maxSizeData / inches[topUnits];
        var bottomMax = maxSizeData / inches[bottomUnits];

        // now trim this down to useful block length
        var topRounded = this.getBarLen(topMax);
        var bottomRounded = this.getBarLen(bottomMax);

        // and back to display units
        topMax = topRounded / inches[curMapUnits] * inches[topUnits];
        bottomMax = bottomRounded / inches[curMapUnits] * inches[bottomUnits];

        // and to pixel units
        var topPx = topMax / res / geodesicRatio;
        var bottomPx = bottomMax / res / geodesicRatio;

        // now set the pixel widths
        // and the values inside them

        if (this.eBottom.style.visibility == "visible"){
            this.eBottom.style.width = Math.round(bottomPx) + "px";
            this.eBottom.innerHTML = bottomRounded + " " + bottomUnits ;
        }

        if (this.eTop.style.visibility == "visible"){
            this.eTop.style.width = Math.round(topPx) + "px";
            this.eTop.innerHTML = topRounded + " " + topUnits;
        }

    }

public function setLineEnd($value)
    {
        $this->_validateInt('LineEnd', $value);

        if ($this->data['line_end'] === $value) {
            return;
        }

        $this->data['line_end'] = $value;

        $this->_setModified('line_end');
    }

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


Question: Depth of the smallest HEALPix cells found in the MOC instance.

def max_order(self):

        # TODO: cache value
        combo = int(0)
        for iv in self._interval_set._intervals:
            combo |= iv[0] | iv[1]

        ret = AbstractMOC.HPY_MAX_NORDER - (utils.number_trailing_zeros(combo) // 2)
        if ret < 0:
            ret = 0

        return ret

func (c *Command) addHelpGroup(showHelp func() error) *Group {
	var help struct {
		ShowHelp func() error `short:"h" long:"help" description:"Show this help message"`
	}

	help.ShowHelp = showHelp
	ret, _ := c.AddGroup("Help Options", "", &help)
	ret.isBuiltinHelp = true

	return ret
}

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


Question: // SetState sets the State field's value.

func (s *DescribeUserOutput) SetState(v string) *DescribeUserOutput {
	s.State = &v
	return s
}

func (b UpdateMap) Get(ns, coll, key string) *statedb.VersionedValue {
	nsPvtBatch, ok := b[ns]
	if !ok {
		return nil
	}
	return nsPvtBatch.Get(coll, key)
}

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


Question:
Return the normalized email address, removing

    :param str email_address: The normalized email address
    :param bool resolve: Resolve the domain
    :rtype: str

def normalize(email_address, resolve=True):

    address = utils.parseaddr(email_address)
    local_part, domain_part = address[1].lower().split('@')

    # Plus addressing is supported by Microsoft domains and FastMail
    if domain_part in MICROSOFT_DOMAINS:
        if '+' in local_part:
            local_part = local_part.split('+')[0]

    # GMail supports plus addressing and throw-away period delimiters
    elif _is_gmail(domain_part, resolve):
        local_part = local_part.replace('.', '').split('+')[0]

    # Yahoo domain handling of - is like plus addressing
    elif _is_yahoo(domain_part, resolve):
        if '-' in local_part:
            local_part = local_part.split('-')[0]

    # FastMail has domain part username aliasing and plus addressing
    elif _is_fastmail(domain_part, resolve):
        domain_segments = domain_part.split('.')
        if len(domain_segments) > 2:
            local_part = domain_segments[0]
            domain_part = '.'.join(domain_segments[1:])
        elif '+' in local_part:
            local_part = local_part.split('+')[0]

    return '@'.join([local_part, domain_part])

protected function buildPostTypeData($singular, $plural, $args)
    {
        $singular = ucwords($singular);
        $plural   = ucwords($plural);

        $labels = [
            'name'               => __($plural, LARAPRESS_TEXTDOMAIN),
            'singular_name'      => __($singular, LARAPRESS_TEXTDOMAIN),
            'add_new'            => __('Add New', LARAPRESS_TEXTDOMAIN),
            'add_new_item'       => __('Add New ' . $singular, LARAPRESS_TEXTDOMAIN),
            'edit_item'          => __('Edit ' . $singular, LARAPRESS_TEXTDOMAIN),
            'new_item'           => __('New ' . $singular, LARAPRESS_TEXTDOMAIN),
            'all_items'          => __('All ' . $plural, LARAPRESS_TEXTDOMAIN),
            'view_item'          => __('View ' . $singular, LARAPRESS_TEXTDOMAIN),
            'search_items'       => __('Search ' . $singular, LARAPRESS_TEXTDOMAIN),
            'not_found'          => __('No ' . strtolower($singular) . ' found', LARAPRESS_TEXTDOMAIN),
            'not_found_in_trash' => __('No ' . strtolower($singular) . ' found in trash', LARAPRESS_TEXTDOMAIN),
            'parent_item_colon'  => '',
            'menu_name'          => __($plural, LARAPRESS_TEXTDOMAIN)
        ];

        return array_merge(
            [
                'label'         => __($plural, LARAPRESS_TEXTDOMAIN),
                'labels'        => $labels,
                'description'   => '',
                'public'        => true,
                'menu_position' => 20,
                'has_archive'   => true
            ],
            $args
        );
    }

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


Question:
Get a cached dictionary related to an individual resourceid.

        :param resourceid: String resource id.
        :return: dict

def get_resource_cache(resourceid):

        if not resourceid:
            raise ResourceInitError("Resource id missing")
        if not DutInformationList._cache.get(resourceid):
            DutInformationList._cache[resourceid] = dict()
        return DutInformationList._cache[resourceid]

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

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

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


Question:
{@inheritdoc}

@return string

public function evaluate()
    {
        $glue = $this->getGlue();
        $parentResult = parent::evaluate();
        if ($parentResult !== []) {
            return implode($glue, $parentResult);
        }
        return null;
    }

def docx_docx_gen_text(doc: DOCX_DOCUMENT_TYPE,
                       config: TextProcessingConfig) -> Iterator[str]:
    # only called if docx loaded

    if in_order:
        for thing in docx_docx_iter_block_items(doc):
            if isinstance(thing, docx.text.paragraph.Paragraph):
                yield docx_process_simple_text(thing.text, config.width)
            elif isinstance(thing, docx.table.Table):
                yield docx_process_table(thing, config)
    else:
        for paragraph in doc.paragraphs:
            yield docx_process_simple_text(paragraph.text, config.width)
        for table in doc.tables:
            yield docx_process_table(table, config)

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


Question: Check that the prompts are strings

def _check_prompts(pre_prompt, post_prompt):
    ''''''
    if not isinstance(pre_prompt, str):
        raise TypeError("The pre_prompt was not a string!")
    if post_prompt is not _NO_ARG and not isinstance(post_prompt, str):
        raise TypeError("The post_prompt was given and was not a string!")

def setHint(self, text):

        texts = nativestring(text).split(' ')

        for i, text in enumerate(texts):
            editor = self.editorAt(i)
            if not editor:
                break

            editor.setHint(text)

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


Question: // SetDataSizeInBytes sets the DataSizeInBytes field's value.

func (s *DataSource) SetDataSizeInBytes(v int64) *DataSource {
	s.DataSizeInBytes = &v
	return s
}

def calculate_size(name, data_list):

    data_size = 0
    data_size += calculate_size_str(name)
    data_size += INT_SIZE_IN_BYTES
    for data_list_item in data_list:
        data_size += calculate_size_data(data_list_item)
    return data_size

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


Question: Plot the components of a given colormap.

def plot_colormap_components(cmap):
    """"""
    from ._helpers import set_ax_labels  # recursive import protection

    plt.figure(figsize=[8, 4])
    gs = grd.GridSpec(3, 1, height_ratios=[1, 10, 1], hspace=0.05)
    # colorbar
    ax = plt.subplot(gs[0])
    gradient = np.linspace(0, 1, 256)
    gradient = np.vstack((gradient, gradient))
    ax.imshow(gradient, aspect="auto", cmap=cmap, vmin=0., vmax=1.)
    ax.set_title(cmap.name, fontsize=20)
    ax.set_axis_off()
    # components
    ax = plt.subplot(gs[1])
    x = np.arange(cmap.N)
    colors = cmap(x)
    r = colors[:, 0]
    g = colors[:, 1]
    b = colors[:, 2]
    RGB_weight = [0.299, 0.587, 0.114]
    k = np.sqrt(np.dot(colors[:, :3] ** 2, RGB_weight))
    r.clip(0, 1, out=r)
    g.clip(0, 1, out=g)
    b.clip(0, 1, out=b)
    xi = np.linspace(0, 1, x.size)
    plt.plot(xi, r, "r", linewidth=5, alpha=0.6)
    plt.plot(xi, g, "g", linewidth=5, alpha=0.6)
    plt.plot(xi, b, "b", linewidth=5, alpha=0.6)
    plt.plot(xi, k, "k", linewidth=5, alpha=0.6)
    ax.set_xlim(0, 1)
    ax.set_ylim(-0.1, 1.1)
    set_ax_labels(ax=ax, xlabel=None, xticks=False, ylabel="intensity")
    # grayified colorbar
    cmap = grayify_cmap(cmap)
    ax = plt.subplot(gs[2])
    gradient = np.linspace(0, 1, 256)
    gradient = np.vstack((gradient, gradient))
    ax.imshow(gradient, aspect="auto", cmap=cmap, vmin=0., vmax=1.)
    ax.set_axis_off()

function(arg) {
			return gui.TrackerPlugin.prototype._breakdown.call(this, arg).map(function(type) {
				return type === 'transitionend' ? this._transitionend() : type;
			}, this);
		}

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


Question: Get the used CV folds

def _get_folds(n_rows, n_folds, use_stored):

        # n_folds = self._n_folds
        # use_stored = self._use_stored_folds
        # n_rows = self._n_rows

        if use_stored is not None:
            # path = '~/concise/data-offline/lw-pombe/cv_folds_5.json'
            with open(os.path.expanduser(use_stored)) as json_file:
                json_data = json.load(json_file)

            # check if we have the same number of rows and folds:
            if json_data['N_rows'] != n_rows:
                raise Exception('N_rows from folds doesnt match the number of rows of X_seq, X_feat, y')

            if json_data['N_folds'] != n_folds:
                raise Exception('n_folds dont match', json_data['N_folds'], n_folds)

            kf = [(np.array(train), np.array(test)) for (train, test) in json_data['folds']]
        else:
            kf = KFold(n_splits=n_folds).split(np.zeros((n_rows, 1)))

        # store in a list
        i = 1
        folds = []
        for train, test in kf:
            fold = "fold_" + str(i)
            folds.append((fold, train, test))
            i = i + 1
        return folds

def is_collapsed(self, id_user):
        """"""
        return CmtCOLLAPSED.query.filter(db.and_(
            CmtCOLLAPSED.id_bibrec == self.id_bibrec,
            CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id,
            CmtCOLLAPSED.id_user == id_user)).count() > 0

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


Question: Write plist file based on our generated tree.

def _write_plist(self, root):
        """"""
        # prettify the XML
        indent_xml(root)

        tree = ElementTree.ElementTree(root)
        with open(self.preferences_file, "w") as prefs_file:
            prefs_file.write(
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" "
                "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
                "<plist version=\"1.0\">\n")
            tree.write(prefs_file, xml_declaration=False, encoding="utf-8")
            prefs_file.write("</plist>")

def _format_subtree(self, subtree):
        """"""
        subtree['children'] = list(subtree['children'].values())
        for child in subtree['children']:
            self._format_subtree(child)
        return subtree

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


Question: // UnmarshalJSON sets the object from the provided JSON representation

func (l *OpsWorksStackChefConfigurationList) UnmarshalJSON(buf []byte) error {
	// Cloudformation allows a single object when a list of objects is expected
	item := OpsWorksStackChefConfiguration{}
	if err := json.Unmarshal(buf, &item); err == nil {
		*l = OpsWorksStackChefConfigurationList{item}
		return nil
	}
	list := []OpsWorksStackChefConfiguration{}
	err := json.Unmarshal(buf, &list)
	if err == nil {
		*l = OpsWorksStackChefConfigurationList(list)
		return nil
	}
	return err
}

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

func (u *User) GetLocation() string {
	if u == nil || u.Location == nil {
		return ""
	}
	return *u.Location
}

func NewGlobalPositionInt(TIME_BOOT_MS uint32, LAT int32, LON int32, ALT int32, RELATIVE_ALT int32, VX int16, VY int16, VZ int16, HDG uint16) *GlobalPositionInt {
	m := GlobalPositionInt{}
	m.TIME_BOOT_MS = TIME_BOOT_MS
	m.LAT = LAT
	m.LON = LON
	m.ALT = ALT
	m.RELATIVE_ALT = RELATIVE_ALT
	m.VX = VX
	m.VY = VY
	m.VZ = VZ
	m.HDG = HDG
	return &m
}

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


Question:
Return the number of enabled jobs.

		:return: The number of jobs that are enabled.
		:rtype: int

def job_count_enabled(self):

		enabled = 0
		for job_desc in self._jobs.values():
			if job_desc['enabled']:
				enabled += 1
		return enabled

def __register_types(self):

        try:
            for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.types']['plugins']:
                cls = entry_point.load()
                self.types[ResourceType.get(cls.resource_type).resource_type_id] = cls
                logger.debug('Registered resource type {}'.format(cls.__name__))
        except SQLAlchemyError as ex:
            logger.warning('Failed loading type information: {}'.format(ex))

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


Question:
Prints the time a query took to run.
@return void

protected function print_debug_time() {
        if (!$this->get_debug()) {
            return;
        }
        $time = $this->query_time();
        $message = "Query took: {$time} seconds.\n";
        if (CLI_SCRIPT) {
            echo $message;
            echo "--------------------------------\n";
        } else if (AJAX_SCRIPT) {
            error_log($message);
            error_log("--------------------------------");
        } else {
            echo s($message);
            echo "<hr />\n";
        }
    }

func (h *Timing) ServerResponseTime(serverResponseTime int64) *Timing {
	h.serverResponseTime = serverResponseTime
	h.serverResponseTimeSet = true
	return h
}

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


Question:
Returns a recent entry, latest entry is not considered recent
if the creation day is the same as today.
@return self

public static function getRecent($user)
    {
        $records = static::where('user_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->limit(2)
            ->get()
        ;

        if (!count($records)) {
            return null;
        }

        $first = $records->first();

        return !$first->created_at->isToday() ? $first : $records->pop();
    }

public function store()
    {
        $attributes = request()->validate(Page::$rules, Page::$messages);

        $attributes['is_header'] = boolval(input('is_header'));
        $attributes['is_hidden'] = boolval(input('is_hidden'));
        $attributes['is_footer'] = boolval(input('is_footer'));
        $attributes['is_featured'] = boolval(input('is_featured'));
        $attributes['url_parent_id'] = ($attributes['url_parent_id'] == 0 ? $attributes['parent_id'] : $attributes['url_parent_id']);

        $page = $this->createEntry(Page::class, $attributes);

        if ($page) {
            $page->updateUrl()->save();
            $page->banners()->sync(input('banners'));
        }

        return redirect_to_resource();
    }

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


Question:
Asynchronously schedules the compression of this file.

<p>
Once the file is compressed, the original will be removed and
the further reading will be done from the compressed stream.

public void compress() {
        compressionThread.submit(new Runnable() {
            public void run() {
                try {
                    try (InputStream in = read();
                         OutputStream os = Files.newOutputStream(gz.toPath());
                         OutputStream out = new GZIPOutputStream(os)) {
                        org.apache.commons.io.IOUtils.copy(in, out);
                    }
                    // if the compressed file is created successfully, remove the original
                    file.delete();
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "Failed to compress "+file,e);
                    gz.delete(); // in case a processing is left in the middle
                }
            }
        });
    }

def cancel(context, jobs, analysis_id):
    """"""
    analysis_obj = context.obj['store'].analysis(analysis_id)
    if analysis_obj is None:
        click.echo('analysis not found')
        context.abort()
    elif analysis_obj.status != 'running':
        click.echo(f"analysis not running: {analysis_obj.status}")
        context.abort()

    config_path = Path(analysis_obj.config_path)
    with config_path.open() as config_stream:
        config_raw = ruamel.yaml.safe_load(config_stream)
    config_data = parse_config(config_raw)

    log_path = Path(f"{config_data['log_path']}")
    if not log_path.exists():
        click.echo(f"missing MIP log file: {log_path}")
        context.abort()

    with log_path.open() as log_stream:
        all_jobs = job_ids(log_stream)

    if jobs:
        for job_id in all_jobs:
            click.echo(job_id)
    else:
        for job_id in all_jobs:
            LOG.debug(f"cancelling job: {job_id}")
            process = subprocess.Popen(['scancel', job_id])
            process.wait()

        analysis_obj.status = 'canceled'
        context.obj['store'].commit()
        click.echo('cancelled analysis successfully!')

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


Question:
Check if a value is inside of a range defined in the thresholds.
This check is based on Nagios range definition.
http://nagiosplug.sourceforge.net/developer-guidelines.html#THRESHOLDFORMAT

protected boolean valueCheck(double value, String simpleRange) {
		if (simpleRange.isEmpty()) {
			return false;
		}

		if (simpleRange.endsWith(":")) {
			return value < Double.parseDouble(simpleRange.replace(":", ""));

		}

		if (simpleRange.startsWith("~:")) {
			return value > Double.parseDouble(simpleRange.replace("~:", ""));

		}

		if (simpleRange.startsWith("@")) {
			String[] values = simpleRange.replace("@", "").split(":");
			return value >= Double.parseDouble(values[0]) && value <= Double.parseDouble(values[1]);
		}

		if (simpleRange.matches("^-{0,1}[0-9]+:-{0,1}[0-9]+$")) {
			String[] values = simpleRange.split(":");
			return value < Double.parseDouble(values[0]) || value > Double.parseDouble(values[1]);
		}

		return simpleRange.matches("^-{0,1}[0-9]+$") && (0 > value || value > Double.parseDouble(simpleRange));
	}

function writeNaptr(buff, val, label_index) {
  assertUndefined(val.order, 'NAPTR record requires "order"');
  assertUndefined(val.preference, 'NAPTR record requires "preference"');
  assertUndefined(val.flags, 'NAPTR record requires "flags"');
  assertUndefined(val.service, 'NAPTR record requires "service"');
  assertUndefined(val.regexp, 'NAPTR record requires "regexp"');
  assertUndefined(val.replacement, 'NAPTR record requires "replacement"');
  buff.writeUInt16BE(val.order & 0xFFFF);
  buff.writeUInt16BE(val.preference & 0xFFFF);
  buff.writeUInt8(val.flags.length);
  buff.write(val.flags, val.flags.length, 'ascii');
  buff.writeUInt8(val.service.length);
  buff.write(val.service, val.service.length, 'ascii');
  buff.writeUInt8(val.regexp.length);
  buff.write(val.regexp, val.regexp.length, 'ascii');
  namePack(val.replacement, buff, label_index);
  return WRITE_RESOURCE_DONE;
}

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


Question:
Encodes the given *obj* to json and wraps it in a response.

    :return:
      A Flask response.

def make_ujson_response(obj, status_code=200):

    json_encoded = ujson.encode(obj, ensure_ascii=False, double_precision=-1)
    resp = make_response(json_encoded)
    resp.mimetype = 'application/json'
    resp.content_type = 'application/json; charset=utf-8'
    resp.status_code = status_code
    return resp

def ToJson(self):

        type = ''
        if self.Type == StateType.Validator:
            type = 'Validator'
        elif self.Type == StateType.Account:
            type = 'Account'

        return {
            'type': type,
            'key': self.Key.hex(),
            'field': self.Field,
            'value': self.Value.hex()
        }

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


Question:
Returns the resource info based on the full path of the resource.

@param $fullPathName

@return array
@throws BuildException

protected function getResourceInfo($fullPathName)
  {
    foreach ($this->resourceFilesInfo as $info)
    {
      if ($info['full_path_name']===$fullPathName)
      {
        return $info;
      }
    }

    $this->logError("Unknown resource file '%s'", $fullPathName);

    return null;
  }

public function redirectLocation(Request $request)
    {
        if ($request->query->has('id')) {
            $location = $this->locationService->loadLocation($request->query->get('id'));
        } elseif ($request->query->has('remoteId')) {
            $location = $this->locationService->loadLocationByRemoteId($request->query->get('remoteId'));
        } elseif ($request->query->has('urlAlias')) {
            $urlAlias = $this->urlAliasService->lookup($request->query->get('urlAlias'));
            $location = $this->locationService->loadLocation($urlAlias->destination);
        } else {
            throw new BadRequestException("At least one of 'id', 'remoteId' or 'urlAlias' parameters is required.");
        }

        return new Values\TemporaryRedirect(
            $this->router->generate(
                'ezpublish_rest_loadLocation',
                array(
                    'locationPath' => trim($location->pathString, '/'),
                )
            )
        );
    }

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


Question:
Modifies a list of documents

@param Document[] $documents
@param array $processingConfiguration

public function processDocuments(array $documents, array $processingConfiguration) {
        foreach ($documents as $document) {
            $this->processDocument($document, $processingConfiguration);
        }
    }

private void loadParsevalParameters() {
    this.parsevalParser.addArgument("-l", "--language").required(true)
        .choices("ca", "de", "en", "es", "eu", "fr", "it")
        .help("Choose language.\n");
    this.parsevalParser.addArgument("-m", "--model").required(false)
        .setDefault(Flags.DEFAULT_EVALUATE_MODEL)
        .help("Pass the model to evaluate as a parameter.\n");
    this.parsevalParser.addArgument("-t", "--testset").required(true)
        .help("The test or reference corpus.\n");
    this.parsevalParser.addArgument("--clearFeatures").required(false)
        .choices("yes", "no", "docstart").setDefault(Flags.DEFAULT_FEATURE_FLAG)
        .help("Reset the adaptive features; defaults to 'no'.\n");
  }

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


Question:
Simplified template rendering

@param string $templatePathAndFilename
@param array $contextVariables
@return string

protected function renderSimpleTemplate($templatePathAndFilename, array $contextVariables)
    {
        $content = file_get_contents($templatePathAndFilename);
        foreach ($contextVariables as $key => $value) {
            $content = str_replace('{' . $key . '}', $value, $content);
        }
        return $content;
    }

protected function cmdExport() /*: void*/
    {
        /**
         * @see simplecomplex_config_cli()
         */
        $container = Dependency::container();
        // Validate input. ---------------------------------------------
        $store = '';
        if (empty($this->command->arguments['store'])) {
            $this->command->inputErrors[] = !isset($this->command->arguments['store']) ? 'Missing \'store\' argument.' :
                'Empty \'store\' argument.';
        } else {
            $store = $this->command->arguments['store'];
            if (!ConfigKey::validate($store)) {
                $this->command->inputErrors[] = 'Invalid \'store\' argument.';
            }
        }
        $target_file = '';
        if (empty($this->command->arguments['target-file'])) {
            $this->command->inputErrors[] = !isset($this->command->arguments['target-file']) ?
                'Missing \'target-file\' argument.' : 'Empty \'target-file\' argument.';
        } else {
            $target_file = $this->command->arguments['target-file'];
        }

        $from_sources = !empty($this->command->options['from-sources']);
        $format = !empty($this->command->options['format']) ? $this->command->options['format'] : 'JSON';
        $unescaped = !empty($this->command->options['unescaped']);
        $pretty = !empty($this->command->options['pretty']);

        // Pre-confirmation --yes/-y ignored for this command.
        if ($this->environment->riskyCommandRequireConfirm && $this->command->preConfirmed) {
            $this->command->inputErrors[] = 'Pre-confirmation \'yes\'/-y option not supported for this command,'
                . "\n" . 'unless env var PHP_LIB_SIMPLECOMPLEX_UTILS_CLI_SKIP_CONFIRM'
                . "\n" . 'or .risky_command_skip_confirm file in document root.';
        }
        if ($this->command->inputErrors) {
            foreach ($this->command->inputErrors as $msg) {
                $this->environment->echoMessage(
                    $this->environment->format($msg, 'hangingIndent'),
                    'notice'
                );
            }
            // This command's help text.
            $this->environment->echoMessage("\n" . $this->command);
            exit;
        }
        // Display command and the arg values used.---------------------
        if ($this->environment->riskyCommandRequireConfirm || !$this->command->preConfirmed) {
            $this->environment->echoMessage(
                $this->environment->format(
                    $this->environment->format($this->command->name, 'emphasize')
                    . "\n" . 'store: ' . $store
                    . "\n" . 'target-file: ' . $target_file
                    . (!$this->command->options ? '' : ("\n--" . join(' --', array_keys($this->command->options)))),
                    'hangingIndent'
                )
            );
        }
        // Request confirmation, ignore --yes/-y pre-confirmation option;
        // unless .risky_command_skip_confirm file placed in document root.
        if ($this->environment->riskyCommandRequireConfirm) {
            if (!$this->environment->confirm(
                'Export that config store from ' . (!$from_sources ? 'cache' : 'sources')
                . ' - will overwrite the target file (if exists)?'
                . "\n" . 'Type \'yes\' to continue:',
                ['yes'],
                '',
                'Aborted exporting config store.'
            )) {
                exit;
            }
        } elseif (!$this->command->preConfirmed && !$this->environment->confirm(
                'Export that config store from ' . (!$from_sources ? 'cache' : 'sources')
                . ' - will overwrite the target file (if exists)?'
                . "\n" . 'Type \'yes\' or \'y\' to continue:',
                ['yes', 'y'],
                '',
                'Aborted exporting config store.'
            )) {
            exit;
        }
        // Check if the command is doable.------------------------------
        // Nothing to check here.
        if ($store == 'global' && $container->has('config')) {
            /** @var IniSectionedConfig $config_store */
            $config_store = $container->get('config');
        } else {
            $config_class = static::CLASS_CONFIG;
            /** @var IniSectionedConfig $config_store */
            $config_store = new $config_class($store);
        }
        // Do it.
        if (!$config_store->export(
            $target_file,
            [
                'fromSources' => $from_sources,
                'format' => strtoupper($format),
                'unescaped' => $unescaped,
                'pretty' => $pretty,
            ]
        )) {
            $this->environment->echoMessage('Failed to export config store[' . $store . '].', 'error');
        } elseif (!$this->command->silent) {
            $this->environment->echoMessage(
                'Exported config store[' . $store . '] from ' . (!$from_sources ? 'cache' : 'sources')
                . ' to target file[' . $target_file . '].',
                'success'
            );
        }
        exit;
    }

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


Question:
Set the avatar/image size in pixels.

@param int $size

@return $this

public function size( $size ) {
		$this->width  = (int) $size;
		$this->height = (int) $size;

		return $this;
	}

def update_logo_preview(self):
        """"""
        logo_path = self.organisation_logo_path_line_edit.text()
        if os.path.exists(logo_path):
            icon = QPixmap(logo_path)
            label_size = self.organisation_logo_label.size()
            label_size.setHeight(label_size.height() - 2)
            label_size.setWidth(label_size.width() - 2)
            scaled_icon = icon.scaled(
                label_size, Qt.KeepAspectRatio)
            self.organisation_logo_label.setPixmap(scaled_icon)
        else:
            self.organisation_logo_label.setText(tr("Logo not found"))

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


Question:
This moves the read files and renames the glob, outputs a new
        ConfigParse object with updated values

def sym_reads_new_config(self, newDir, sym=False, mv=False):
        """"""
        newParams = copy.copy(self)
        for i in range(0,len(self.params["lib_seq"])):
            lib_seq = self.params["lib_seq"][i]
            #update the glob
            newParams.params["lib_seq"][i]["globs"] = [os.path.join(
                newDir,os.path.basename(x)) for x in lib_seq["globs"]]
            #now update the file paths and move/symlink if necessary
            for j in range(0, len(lib_seq["pairs"])):
                forward, reverse = lib_seq["pairs"][j]
                new_forward = os.path.join(newDir, os.path.basename(forward))
                new_reverse = os.path.join(newDir, os.path.basename(reverse))
                #move or symlink the files
                if sym:
                    for each in [new_forward, new_reverse]:
                        if os.path.exists(each):
                            raise ValueError("""Attempted to make a symlink for
                            a reads file, but it already exists. Chances are
                            that you used the same reads for two lines in the
                            Meraculous config file""")
                    os.symlink(forward, new_forward)
                    os.symlink(reverse, new_reverse)
                #update the reads in the new config
                newParams.params["lib_seq"][i]["pairs"][j] = [new_forward, new_reverse]
        return newParams

def _parse_hostvar_dir(self, inventory_path):

        # inventory_path could point to a `hosts` file, or to a dir. So we
        # construct the location to the `host_vars` differently.
        if os.path.isdir(inventory_path):
            path = os.path.join(inventory_path, 'host_vars')
        else:
            path = os.path.join(os.path.dirname(inventory_path), 'host_vars')

        self.log.debug("Parsing host vars (dir): {0}".format(path))
        if not os.path.exists(path):
            self.log.info("No such dir {0}".format(path))
            return

        for entry in os.listdir(path):
            # Skip .git folder
            if entry == '.git':
                continue
            full_path = os.path.join(path, entry)

            # file or dir name is the hostname
            hostname = strip_exts(entry, ('.yml', '.yaml', '.json'))

            if os.path.isfile(full_path):
                # Parse contents of file as host vars.
                self._parse_hostvar_file(hostname, full_path)
            elif os.path.isdir(full_path):
                # Parse each file in the directory as a file containing
                # variables for the host.
                for file_entry in os.listdir(full_path):
                    p = os.path.join(full_path, file_entry)
                    if not os.path.isdir(p):
                        self._parse_hostvar_file(hostname, p)

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


Question:
Common helper for set_userflags and unset_userflags.

 @api private

def op_userflags(*flags, &block)
      # Avoid an unnecessary set + commit operation.
      return if flags.empty?

      unrecognized_flags = flags.reject { |flag| ADS_USERFLAGS.keys.include?(flag) }
      unless unrecognized_flags.empty?
        raise ArgumentError, _("Unrecognized ADS UserFlags: %{unrecognized_flags}") % { unrecognized_flags: unrecognized_flags.join(', ') }
      end

      self['UserFlags'] = flags.inject(self['UserFlags'], &block)
    end

def refresh(cls):

        # clear the old values in _flag_map
        try:
            del cls._flag_map["t"]
        except KeyError:
            pass

        try:
            del cls._flag_map["-"]
        except KeyError:
            pass

        # set the value given the git version
        if Git().version_info[:2] >= (2, 10):
            cls._flag_map["t"] = cls.TAG_UPDATE
        else:
            cls._flag_map["-"] = cls.TAG_UPDATE

        return True

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


Question:
// isPackage reports whether pkg has path as the canonical path,
// taking into account vendoring effects

func isPackage(pkg *types.Package, path string) bool {
	if pkg == nil {
		return false
	}

	return pkg.Path() == path ||
		strings.HasSuffix(pkg.Path(), "/vendor/"+path)
}

def search_fast(self, text):
    """"""

    resp = self.impl.get(
        "{base_url}/{text}/json".format(base_url=self.base_url, text=text)
    )
    return resp.json()["info"]["package_url"]

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


Question: // SetSecurityGroupIds sets the SecurityGroupIds field's value.

func (s *DevEndpoint) SetSecurityGroupIds(v []*string) *DevEndpoint {
	s.SecurityGroupIds = v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

    if (isLog(4)) {
      log("change getfield " + owner + " name:" + name);
    }
    typeQueryUser = true;
  }

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


Question:
// ResumeDevice is the programmatic example of "dmsetup resume".
// It un-suspends the specified device.

func ResumeDevice(name string) error {
	task, err := TaskCreateNamed(deviceResume, name)
	if task == nil {
		return err
	}

	cookie := new(uint)
	if err := task.setCookie(cookie, 0); err != nil {
		return fmt.Errorf("devicemapper: Can't set cookie %s", err)
	}
	defer UdevWait(cookie)

	if err := task.run(); err != nil {
		return fmt.Errorf("devicemapper: Error running deviceResume %s", err)
	}

	return nil
}

def hardware_custom_profile_kap_custom_profile_bfd_l3_bfd_l3_hello_interval(self, **kwargs):

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

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

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


Question: // UnmarshalJSON decodes JSON into a set

func (s *Set) UnmarshalJSON(data []byte) error {
	var vv []string
	if err := json.Unmarshal(data, &vv); err != nil {
		return err
	}

	*s = *Use(vv...)
	return nil
}

public static <E extends Enum<E>> EnumSetJsonDeserializer<E> newInstance( EnumJsonDeserializer<E> deserializer ) {
        return new EnumSetJsonDeserializer<E>( deserializer );
    }

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