Question:
@param int $limit

@return string[]

public function getUserAgents($limit = 0)
    {
        $counter = 0;

        foreach ($this->loadFromPath() as $test) {
            if ($limit && $counter >= $limit) {
                return;
            }

            yield trim($test->ua);
            ++$counter;
        }
    }

public function parse($annotation, \ReflectionClass $refClass, Endpoint $endpoint)
    {
        $query = new QueryDefinition();

        if ($annotation->name) {
            $query->setName($annotation->name);
        } else {
            $query->setName(lcfirst(ClassUtils::getDefaultName($refClass->getName())));
        }

        $endpoint->addQuery($query);

        if ($annotation->type) {
            $type = TypeUtil::normalize($annotation->type);
            if (class_exists($annotation->type)) {
                $type = $endpoint->getTypeForClass($annotation->type);
            }
            if ($endpoint->hasType($type)) {
                $query->setNode($type);
            }
            $query->setType($type);
        }

        $query->setList(TypeUtil::isTypeList($annotation->type));
        $query->setNonNull(TypeUtil::isTypeNonNull($annotation->type));
        $query->setNonNullList(TypeUtil::isTypeNonNullList($annotation->type));

        if (!$query->getType()) {
            $nodeType = ClassUtils::getNodeFromClass($refClass->getName());
            $objectDefinition = null;
            if ($nodeType && $endpoint->hasType($nodeType)) {
                $objectDefinition = $endpoint->getType($nodeType);
            }
            if ($objectDefinition) {
                $query->setType($objectDefinition->getName());
                $query->setNode($objectDefinition->getName());
            } else {
                //avoid throw Exception when the schema is empty
                //when the schema is empty the NodeInterface has not been loaded
                //then the node(id) and nodes(ids) queries fails
                if ('Node' === $nodeType) {
                    $endpoint->removeQuery($query->getName());

                    return;
                }

                $error = sprintf('Does not exist any valid type for class "%s"', $refClass->getName());
                throw new \RuntimeException($error);
            }
        }

        if ($annotation->arguments) {
            foreach ($annotation->arguments as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        } else {
            $argAnnotations = $this->reader->getClassAnnotations($refClass);
            foreach ($argAnnotations as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        }

        $query->setResolver($annotation->resolver ?? $refClass->getName());
        $query->setDeprecationReason($annotation->deprecationReason);
        $query->setDescription($annotation->description);

        foreach ($annotation->options as $option => $value) {
            $query->setMeta($option, $value);
        }
    }

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


Question: Returns the names for the help option.

def get_help_option_names(self, ctx):
        """"""
        all_names = set(ctx.help_option_names)
        for param in self.params:
            all_names.difference_update(param.opts)
            all_names.difference_update(param.secondary_opts)
        return all_names

func ShowCommandHelpAndExit(c *Context, command string, code int) {
	ShowCommandHelp(c, command)
	os.Exit(code)
}

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


Question:
Generates a MAIN tag with role attribute.

@return an HtmlTree object for the MAIN tag

public static HtmlTree MAIN() {
        HtmlTree htmltree = new HtmlTree(HtmlTag.MAIN);
        htmltree.setRole(Role.MAIN);
        return htmltree;
    }

def _wns_prepare_toast(data, **kwargs):

	root = ET.Element("toast")
	visual = ET.SubElement(root, "visual")
	binding = ET.SubElement(visual, "binding")
	binding.attrib["template"] = kwargs.pop("template", "ToastText01")
	if "text" in data:
		for count, item in enumerate(data["text"], start=1):
			elem = ET.SubElement(binding, "text")
			elem.text = item
			elem.attrib["id"] = str(count)
	if "image" in data:
		for count, item in enumerate(data["image"], start=1):
			elem = ET.SubElement(binding, "img")
			elem.attrib["src"] = item
			elem.attrib["id"] = str(count)
	return ET.tostring(root)

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


Question: // Will fetch the activation token for an import.

func fetchActivation(url string) string {
	// FIXME(dlc) - Make configurable.
	c := &http.Client{Timeout: 2 * time.Second}
	resp, err := c.Get(url)
	if err != nil || resp == nil {
		return ""
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return ""
	}
	return string(body)
}

@Override
    public boolean canImport(String mediaType) {
        return (MediaType.NATIVE_MEDIATYPE_SYNTAX_MAP.containsKey(mediaType) ||
                this.serviceTransformationEngine.canTransform(mediaType));
    }

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


Question:
save or update this cluster in Ariane Server
        :return:

def save(self):

        LOGGER.debug("Cluster.save")
        post_payload = {}
        consolidated_containers_id = []

        if self.id is not None:
            post_payload['clusterID'] = self.id

        if self.name is not None:
            post_payload['clusterName'] = self.name

        if self.containers_id is not None:
            consolidated_containers_id = copy.deepcopy(self.containers_id)
        if self.containers_2_rm is not None:
            for container_2_rm in self.containers_2_rm:
                if container_2_rm.id is None:
                    container_2_rm.sync()
                consolidated_containers_id.remove(container_2_rm.id)
        if self.containers_2_add is not None:
            for container_2_add in self.containers_2_add:
                if container_2_add.id is None:
                    container_2_add.save()
                consolidated_containers_id.append(container_2_add.id)
        post_payload['clusterContainersID'] = consolidated_containers_id

        params = SessionService.complete_transactional_req({'payload': json.dumps(post_payload)})
        if MappingService.driver_type != DriverFactory.DRIVER_REST:
            params['OPERATION'] = 'createCluster'
            args = {'properties': params}
        else:
            args = {
                'http_operation': 'POST',
                'operation_path': '',
                'parameters': params
            }

        response = ClusterService.requester.call(args)

        if MappingService.driver_type != DriverFactory.DRIVER_REST:
            response = response.get()

        if response.rc != 0:
            LOGGER.warning('Cluster.save - Problem while saving cluster' + self.name +
                           '. Reason: ' + str(response.response_content) + ' - ' + str(response.error_message) +
                           " (" + str(response.rc) + ")")
            if response.rc == 500 and ArianeMappingOverloadError.ERROR_MSG in response.error_message:
                raise ArianeMappingOverloadError("Cluster.save", ArianeMappingOverloadError.ERROR_MSG)
            # traceback.print_stack()
        else:
            self.id = response.response_content['clusterID']
            if self.containers_2_add is not None:
                for container_2_add in self.containers_2_add:
                    container_2_add.sync()
            if self.containers_2_rm is not None:
                for container_2_rm in self.containers_2_rm:
                    container_2_rm.sync()
            self.sync(json_obj=response.response_content)
        self.containers_2_add.clear()
        self.containers_2_rm.clear()

private Canal doToModel(CanalDO canalDo) {
        Canal canal = new Canal();
        try {
            canal.setId(canalDo.getId());
            canal.setName(canalDo.getName());
            canal.setStatus(canalDo.getStatus());
            canal.setDesc(canalDo.getDescription());
            CanalParameter parameter = canalDo.getParameters();
            AutoKeeperCluster zkCluster = autoKeeperClusterService.findAutoKeeperClusterById(parameter.getZkClusterId());
            if (zkCluster != null) {
                parameter.setZkClusters(Arrays.asList(StringUtils.join(zkCluster.getServerList(), ',')));
            }
            canal.setCanalParameter(canalDo.getParameters());
            canal.setGmtCreate(canalDo.getGmtCreate());
            canal.setGmtModified(canalDo.getGmtModified());
        } catch (Exception e) {
            logger.error("ERROR ## change the canal Do to Model has an exception");
            throw new ManagerException(e);
        }

        return canal;
    }

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


Question:
Sets the color as a String.<p>

@param value the color to set

public void setColor(String value) {

        if (COLOR_TRANSPARENT.indexOf(value) == 0) {
            setColor(Simapi.COLOR_TRANSPARENT);
        } else {
            setColor(CmsStringUtil.getColorValue(value, Simapi.COLOR_TRANSPARENT, SCALE_PARAM_COLOR));
        }
    }

def highlight(self, **kwargs):

        self.debug_log("Highlighting element")

        style = kwargs.get('style')
        highlight_time = kwargs.get('highlight_time', .3)

        driver = self._element._parent

        try:
            original_style = self._element.get_attribute('style')

            driver.execute_script(
                "arguments[0].setAttribute('style', arguments[1]);",
                self._element,
                style
            )
        except Exception as e:
            self.error_log("highlight exception: %s" % str(e))

        sleep(highlight_time)

        try:
            driver.execute_script(
                "arguments[0].setAttribute('style', arguments[1]);",
                self._element,
                original_style
            )
        except Exception as e:
            self.error_log("highlight exception: %s" % str(e))

        return True

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


Question:
Check that dependencies are installed:
    - require git 2.7+, so that credential-cache--daemon ignores SIGHUP
        https://github.com/git/git/blob/v2.7.0/credential-cache--daemon.c

def check_dependencies():

    # Check that git is installed
    if not shutil.which("git"):
        raise Error(_("You don't have git. Install git, then re-run!"))

    # Check that git --version > 2.7
    version = subprocess.check_output(["git", "--version"]).decode("utf-8")
    matches = re.search(r"^git version (\d+\.\d+\.\d+).*$", version)
    if not matches or pkg_resources.parse_version(matches.group(1)) < pkg_resources.parse_version("2.7.0"):
        raise Error(_("You have an old version of git. Install version 2.7 or later, then re-run!"))

func Identity(cfg *config.Config) fx.Option {
	// PeerID

	cid := cfg.Identity.PeerID
	if cid == "" {
		return fx.Error(errors.New("identity was not set in config (was 'ipfs init' run?)"))
	}
	if len(cid) == 0 {
		return fx.Error(errors.New("no peer ID in config! (was 'ipfs init' run?)"))
	}

	id, err := peer.IDB58Decode(cid)
	if err != nil {
		return fx.Error(fmt.Errorf("peer ID invalid: %s", err))
	}

	// Private Key

	if cfg.Identity.PrivKey == "" {
		return fx.Options( // No PK (usually in tests)
			fx.Provide(PeerID(id)),
			fx.Provide(pstoremem.NewPeerstore),
		)
	}

	sk, err := cfg.Identity.DecodePrivateKey("passphrase todo!")
	if err != nil {
		return fx.Error(err)
	}

	return fx.Options( // Full identity
		fx.Provide(PeerID(id)),
		fx.Provide(PrivateKey(sk)),
		fx.Provide(pstoremem.NewPeerstore),

		fx.Invoke(libp2p.PstoreAddSelfKeys),
	)
}

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


Question:
Verifies whether the user has permission to grant all of the provided roles.  If not it throws an UnauthorizedException.
@throws UnauthorizedException User did not have the permission to grant at least one role.

private void verifyPermissionToGrantRoles(Subject subject, Iterable<RoleIdentifier> roleIds) {
        Set<RoleIdentifier> unauthorizedIds = Sets.newTreeSet();
        boolean anyAuthorized = false;

        for (RoleIdentifier roleId : roleIds) {
            // Verify the caller has permission to grant this role
            if (subject.hasPermission(Permissions.grantRole(roleId))) {
                anyAuthorized = true;
            } else {
                unauthorizedIds.add(roleId);
            }
        }

        if (!unauthorizedIds.isEmpty()) {
            // If the caller was not authorized to assign any of the provided roles raise a generic exception, otherwise
            // the exception provides insight as to which roles were unauthorized.  This provides some helpful feedback
            // where appropriate without exposing potentially exploitable information about whether the subject's API key
            // is valid.
            if (!anyAuthorized) {
                throw new UnauthorizedException();
            } else {
                throw new UnauthorizedException("Not authorized for roles: " + Joiner.on(", ").join(unauthorizedIds));
            }
        }
    }

func FilterTLFEarlyExitError(ctx context.Context, err error, log logger.Logger, name tlf.CanonicalName) (
	exitEarly bool, retErr error) {
	switch err := errors.Cause(err).(type) {
	case nil:
		// No error.
		return false, nil

	case TlfDoesNotExist:
		log.CDebugf(ctx,
			"TLF %s does not exist, so pretending it's empty",
			name)
		return true, nil

	case tlfhandle.WriteAccessError, kbfsmd.ServerErrorWriteAccess,
		libkbfs.NonExistentTeamForHandleError:
		// No permission to create TLF, so pretend it's still
		// empty.
		//
		// In theory, we need to invalidate this once the TLF
		// is created, but in practice, the Linux kernel
		// doesn't cache readdir results, and probably not
		// OSXFUSE either.
		log.CDebugf(ctx,
			"No permission to write to %s, so pretending it's empty",
			name)
		return true, nil

	default:
		if strings.Contains(err.Error(), "need writer access") {
			// The service returns an untyped error when we try to
			// write a TLF ID into an implicit team sigchain without
			// writer permissions.
			log.CDebugf(ctx,
				"No permission to write to %s, so pretending it's empty",
				name)
			return true, nil
		}

		// Some other error.
		return false, err
	}
}

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


Question:
To be called at node startup - it purges all job instances associated to this node.

@param cnx
@param node

private void purgeDeadJobInstances(DbConn cnx, Node node)
    {
        for (JobInstance ji : JobInstance.select(cnx, "ji_select_by_node", node.getId()))
        {
            try
            {
                cnx.runSelectSingle("history_select_state_by_id", String.class, ji.getId());
            }
            catch (NoResultException e)
            {
                History.create(cnx, ji, State.CRASHED, Calendar.getInstance());
                Message.create(cnx,
                        "Job was supposed to be running at server startup - usually means it was killed along a server by an admin or a crash",
                        ji.getId());
            }

            cnx.runUpdate("ji_delete_by_id", ji.getId());
        }
        cnx.commit();
    }

def delete_ptr_records(self, device, ip_address=None):

        device_type = self._resolve_device_type(device)
        href, svc_name = self._get_ptr_details(device, device_type)
        uri = "/rdns/%s?href=%s" % (svc_name, href)
        if ip_address:
            uri = "%s&ip=%s" % (uri, ip_address)
        resp, resp_body = self._async_call(uri, method="DELETE",
                has_response=False,
                error_class=exc.PTRRecordDeletionFailed)
        return resp_body.get("status") == "COMPLETED"

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


Question:
// ValidateImageStreamStatusUpdateWithWhitelister tests required fields for an ImageStream status update.
// Additionally, it validates each new image reference against registry whitelist.

func ValidateImageStreamStatusUpdateWithWhitelister(
	whitelister whitelist.RegistryWhitelister,
	newStream, oldStream *imageapi.ImageStream,
) field.ErrorList {
	errs := validation.ValidateObjectMetaUpdate(&newStream.ObjectMeta, &oldStream.ObjectMeta, field.NewPath("metadata"))
	insecureRepository := isRepositoryInsecure(newStream)

	oldRefs := collectImageStreamStatusImageReferences(oldStream)
	newRefs := collectImageStreamStatusImageReferences(newStream)

	for refString, rfs := range newRefs {
		// allow to manipulate not whitelisted references if already present in the image stream
		if _, ok := oldRefs[refString]; ok {
			continue
		}
		ref, err := imageapi.ParseDockerImageReference(refString)
		if err != nil {
			for _, rf := range rfs {
				errs = append(errs, field.Invalid(rf.path, refString, err.Error()))
			}
			continue
		}

		if whitelister == nil {
			continue
		}

		insecure := insecureRepository
		if !insecure {
			for _, rf := range rfs {
				if rf.insecure {
					insecure = true
					break
				}
			}
		}
		transport := getWhitelistTransportForFlag(insecure, true)
		if err := whitelister.AdmitDockerImageReference(&ref, transport); err != nil {
			// TODO: should we whitelist references imported based on whitelisted/old spec?
			// report error for each tag/history item having this reference
			for _, rf := range rfs {
				errs = append(errs, field.Forbidden(rf.path, err.Error()))
			}
		}
	}

	return errs
}

public function toStreamContextArray(): array
    {
        $options = [
            'crypto_method' => $this->toStreamCryptoMethod(),
            'peer_name' => $this->peerName,
            'verify_peer' => $this->verifyPeer,
            'verify_peer_name' => $this->verifyPeer,
            'verify_depth' => $this->verifyDepth,
            'ciphers' => $this->ciphers ?? \OPENSSL_DEFAULT_STREAM_CIPHERS,
            'capture_peer_cert' => $this->capturePeer,
            'capture_peer_cert_chain' => $this->capturePeer,
            'SNI_enabled' => $this->sniEnabled,
        ];

        if ($this->certificate !== null) {
            $options['local_cert'] = $this->certificate->getCertFile();

            if ($this->certificate->getCertFile() !== $this->certificate->getKeyFile()) {
                $options['local_pk'] = $this->certificate->getKeyFile();
            }
        }

        if ($this->caFile !== null) {
            $options['cafile'] = $this->caFile;
        }

        if ($this->caPath !== null) {
            $options['capath'] = $this->caPath;
        }

        if (\OPENSSL_VERSION_NUMBER >= 0x10100000) {
            $options['security_level'] = $this->securityLevel;
        }

        return ['ssl' => $options];
    }

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


Question: do x=x+(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys. x must be large enough to hold the answer.

function addShift_(x, y, ys) {
  var i, c, k, kk;
  k=x.length<ys+y.length ? x.length : ys+y.length;
  kk=x.length;
  for (c=0, i=ys; i<k; i++) {
    c+=x[i]+y[i-ys];
    x[i]=c & mask;
    c>>=bpe;
  }
  for (i=k; c && i<kk; i++) {
    c+=x[i];
    x[i]=c & mask;
    c>>=bpe;
  }
}

public static long[] hash(final long[] key, final long seed) {
    final HashState hashState = new HashState(seed, seed);
    final int longs = key.length; //in longs

    // Number of full 128-bit blocks of 2 longs (the body).
    // Possible exclusion of a remainder of 1 long.
    final int nblocks = longs >>> 1; //longs / 2

    // Process the 128-bit blocks (the body) into the hash
    for (int i = 0; i < nblocks; i++ ) {
      final long k1 = key[i << 1]; //0, 2, 4, ...
      final long k2 = key[(i << 1) + 1]; //1, 3, 5, ...
      hashState.blockMix128(k1, k2);
    }

    // Get the tail index, remainder length
    final int tail = nblocks << 1; // 2 longs / block
    final int rem = longs - tail; // remainder longs: 0,1

    // Get the tail
    final long k1 = (rem == 0) ? 0 : key[tail]; //k2 -> 0
    // Mix the tail into the hash and return
    return hashState.finalMix128(k1, 0, longs << 3); //convert to bytes
  }

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


Question: Determine if {@code this} is a an implicit subtype of {@code superType}.

final boolean isStructuralSubtype(ObjectType superType,
      ImplCache implicitImplCache, SubtypingMode subtypingMode) {
    // Union types should be handled by isSubtype already
    checkArgument(!this.isUnionType());
    checkArgument(!superType.isUnionType());
    Preconditions.checkArgument(superType.isStructuralType(),
        "isStructuralSubtype should be called with structural supertype. Found %s", superType);

    MatchStatus cachedResult = implicitImplCache.checkCache(this, superType);
    if (cachedResult != null) {
      return cachedResult.subtypeValue();
    }

    boolean result =
        isStructuralSubtypeHelper(
            this, superType, implicitImplCache, subtypingMode, VOIDABLE_PROPS_ARE_OPTIONAL);
    return implicitImplCache.updateCache(this, superType, MatchStatus.valueOf(result));
  }

public static TemplateMetadata fromTemplate(TemplateNode template) {
    TemplateMetadata.Builder builder =
        builder()
            .setTemplateName(template.getTemplateName())
            .setSourceLocation(template.getSourceLocation())
            .setSoyFileKind(SoyFileKind.SRC)
            .setContentKind(template.getContentKind())
            .setStrictHtml(template.isStrictHtml())
            .setDelPackageName(template.getDelPackageName())
            .setVisibility(template.getVisibility())
            .setParameters(Parameter.directParametersFromTemplate(template))
            .setDataAllCallSituations(DataAllCallSituation.fromTemplate(template));
    switch (template.getKind()) {
      case TEMPLATE_BASIC_NODE:
        builder.setTemplateKind(Kind.BASIC);
        break;
      case TEMPLATE_DELEGATE_NODE:
        builder.setTemplateKind(Kind.DELTEMPLATE);
        TemplateDelegateNode deltemplate = (TemplateDelegateNode) template;
        builder.setDelTemplateName(deltemplate.getDelTemplateName());
        builder.setDelTemplateVariant(deltemplate.getDelTemplateVariant());
        break;
      case TEMPLATE_ELEMENT_NODE:
        builder.setTemplateKind(Kind.ELEMENT);
        break;
      default:
        throw new AssertionError("unexpected template kind: " + template.getKind());
    }
    return builder.build();
  }

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


Question:
Add the requested query string arguments to the Request.

@param request Request to add query string arguments to

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

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

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

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

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

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

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

public static void initServletRequest(ServletRequest servletRequest, URLTemplatesFactory templatesFactory)
    {
        assert servletRequest != null : "The ServletRequest cannot be null.";

        if (servletRequest == null) {
            throw new IllegalArgumentException("The ServletRequest cannot be null.");
        }

        servletRequest.setAttribute(URL_TEMPLATE_FACTORY_ATTR, templatesFactory);
    }

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


Question:
Set the line breaks

@param int[] $lineBreaks Array of integers
@throws DomainException
@return $this

public function setLineBreaks(array $lineBreaks)
    {
        foreach ($lineBreaks as $lb) {
            if (!is_int($lb)) {
                throw new DomainException("lineBreaks array is expected to contain only integers");
            }
            $this->lineBreaks[] = $lb;
        }

        return $this;
    }

public function insert($table, $data, $statements)
    {
        $input = [
            'columns' => '',
            'values' => ''
        ];

        $query = 'INSERT INTO `' . $table . '` ';

        foreach ($data as $column => $value) {
            $input['columns'] .= $column . ', ';

            $value = (is_null($statements) && is_string($value)) ? "'$value'" : $value;

            $input['values'] .= $value . ', ';
        }

        $query .= '(' . rtrim(trim($input['columns']), ',') . ') ';

        $query .= 'VALUES (' . rtrim(trim($input['values']), ',') . ')';

        return $this->query($query, 'INSERT');
    }

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


Question: Allows to specify additional cases for a specific type of generic arguments (matched by instanceOf). Null classes can be provided in case of arguments that do not matter.

@Nonnull
	public <V1 extends T1, V2 extends T2> LBiObjDblConsumerBuilder<T1, T2> casesOf(Class<V1> argC1, Class<V2> argC2, Consumer<LBiObjDblConsumerBuilder<V1, V2>> pcpConsumer) {
		PartialCase.The pc = partialCaseFactoryMethod((a1, a2, a3) -> (argC1 == null || argC1.isInstance(a1)) && (argC2 == null || argC2.isInstance(a2)));

		pc.specifySubCases((Consumer) pcpConsumer);
		return self();
	}

public static Block createMapBlockInternal(
            TypeManager typeManager,
            Type keyType,
            int startOffset,
            int positionCount,
            Optional<boolean[]> mapIsNull,
            int[] offsets,
            Block keyBlock,
            Block valueBlock,
            HashTables hashTables)
    {
        // TypeManager caches types. Therefore, it is important that we go through it instead of coming up with the MethodHandles directly.
        // BIGINT is chosen arbitrarily here. Any type will do.
        MapType mapType = (MapType) typeManager.getType(new TypeSignature(StandardTypes.MAP, TypeSignatureParameter.of(keyType.getTypeSignature()), TypeSignatureParameter.of(BIGINT.getTypeSignature())));
        return MapBlock.createMapBlockInternal(startOffset, positionCount, mapIsNull, offsets, keyBlock, valueBlock, hashTables, keyType, mapType.keyBlockNativeEquals, mapType.keyNativeHashCode, mapType.keyBlockHashCode);
    }

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


Question:
Normalizes the tablecolumns-array.

@param array $columns Columns to normalize.
@return array

protected function _normalizeTableColumns($columns)
    {
        $_defaults = [
            'get' => false,
            'before' => '',
            'after' => '',
        ];
        $result = [];

        foreach ($columns as $name => $options) {
            if (is_array($options)) {
                $_defaults['get'] = $name;
                $result[$name] = array_merge($_defaults, $options);
            } else {
                $_defaults['get'] = $options;
                $result[$options] = $_defaults;
            }
        }
        return $result;
    }

private function renderRowHtml()
    {
        $data = $this->getTable()->getData();
        $headers = $this->getTable()->getHeaders();
        $render = '';

        foreach ($data as $rowData) {
            $this->setActualRow($rowData);
            $rowRender = '';

            foreach ($headers as $name => $options) {
                $rowRender .= $this->getTable()->getHeader($name)->getCell()->render('html');
            }

            foreach ($this->decorators as $decorator) {
                $decorator->render('');
            }

            $render .= sprintf('<tr %s>%s</tr>', $this->getAttributes(), $rowRender);
            $this->clearVar();
        }
        return $render;
    }

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


Question:
Copy the contents of the temporary file somewhere else. Finalizes prior to saving.

        :param name: File path.
        :type name: unicode | str

def save(self, name):

        self.finalize()
        with open(name, 'wb+') as f:
            buf = self._fileobj.read()
            while buf:
                f.write(buf)
                buf = self._fileobj.read()

def parseBasicOptions(parser):

    (options, args) = parser.parse_args()

    setLoggingFromOptions(options)

    #Set up the temp dir root
    if options.tempDirRoot == "None":
        options.tempDirRoot = os.getcwd()

    return options, args

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


Question:
Loads realpath_cache_size from php.ini and converts it to int.

(e.g. 16k is converted to 16384 int)

@return int

protected function getRealpathCacheSize()
    {
        $size = ini_get('realpath_cache_size');
        $size = trim($size);
        $unit = '';
        if (!ctype_digit($size)) {
            $unit = strtolower(substr($size, -1, 1));
            $size = (int) substr($size, 0, -1);
        }
        switch ($unit) {
            case 'g':
                return $size * 1024 * 1024 * 1024;
            case 'm':
                return $size * 1024 * 1024;
            case 'k':
                return $size * 1024;
            default:
                return (int) $size;
        }
    }

public static function getVec3($valueX, $valueY = null, $valueZ = null)
    {
        if (is_array($valueX)) {
            $valueZ = (isset($valueX[2]) ? $valueX[2] : 0.);
            $valueY = (isset($valueX[1]) ? $valueX[1] : 0.);
            $valueX = (isset($valueX[0]) ? $valueX[0] : 0.);
        }
        return "<" . static::getReal($valueX) . "," . static::getReal($valueY) . "," . static::getReal($valueZ) . ">";
    }

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


Question: Removes the last item in the list.

private void popLastItem() {
        KeyValue<K,V> lastKV = items.last();
        items.remove(lastKV);
        index.remove(lastKV.key);
    }

public function popChild()
    {
        // Rewind if current iterator is not valid
        if (! $this->children->valid() )
            $this->children->rewind();

        // If current iterator is still not valid it means there are no children anymore
        if (! $this->children->valid() )
            return false;

        $child = $this->children->current();
        $this->children->detach( $child );
        return $child;
    }

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


Question:
Updates the variable that maintains exponential moving averages of
        individual and pairwise unit activiy

def update_statistics(self, activityVectors):
        """"""
        Y = activityVectors
        n = self.output_size
        A = np.zeros((n, n))
        batchSize = len(Y)

        for y in Y:
            active_units = np.where( y == 1 )[0]
            for i in active_units:
                for j in active_units:
                    A[i,j] += 1.

        A = A/batchSize
        self.average_activity = self.exponential_moving_average(self.average_activity, A, self.smoothing_period)

def active_vectors_info(self):
        """"""
        if not hasattr(self, '_active_vectors_info'):
            self._active_vectors_info = [POINT_DATA_FIELD, None] # field and name
        _, name = self._active_vectors_info

        # rare error where scalar name isn't a valid scalar
        if name not in self.point_arrays:
            if name not in self.cell_arrays:
                name = None

        return self._active_vectors_info

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


Question:
Sets the item values from the given array.

@param array $list Associative list of item keys and their values
@return array Associative list of keys and their values that are unknown

public function fromArray( array $list )
	{
		$unknown = array();
		$list = parent::fromArray( $list );

		foreach( $list as $key => $value )
		{
			switch( $key )
			{
				case 'order.base.address.baseid': $this->setBaseId( $value ); break;
				case 'order.base.address.addressid': $this->setAddressId( $value ); break;
				case 'order.base.address.type': $this->setType( $value ); break;
				default: $unknown[$key] = $value;
			}
		}

		return $unknown;
	}

public function addReturnTypes(Context $context)
    {
        if ($this->return_vars_in_scope !== null) {
            $this->return_vars_in_scope = TypeAnalyzer::combineKeyedTypes(
                $context->vars_in_scope,
                $this->return_vars_in_scope
            );
        } else {
            $this->return_vars_in_scope = $context->vars_in_scope;
        }

        if ($this->return_vars_possibly_in_scope !== null) {
            $this->return_vars_possibly_in_scope = array_merge(
                $context->vars_possibly_in_scope,
                $this->return_vars_possibly_in_scope
            );
        } else {
            $this->return_vars_possibly_in_scope = $context->vars_possibly_in_scope;
        }
    }

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


Question: query statement generation

public function getQueryStatements($table){
		// field declaration
		$query = array();
		array_push($query, $this->name . ' ' . $this->type);
		if($this->nullable == false)
			array_push($query, ' NOT NULL');
		else array_push($query, ' NULL');
		if(isset($this->default_value)){
			$value = $this->default_value;
			if($this->type == 'BOOL')
				$value = ($this->default_value)?1:0;
			array_push($query, " DEFAULT '$value'");
		}
		if($this->auto_increments && $this->type == 'INT')
			array_push($query, ' AUTO_INCREMENT');
		// constraints
		if($this->primary)
			array_push($query, ",\n\t" . 'CONSTRAINT PK_' . $this->name . ' PRIMARY KEY (' . $this->name . ')');
		if($this->unique)
			array_push($query, ",\n\t" . 'CONSTRAINT UC_' . $this->name . ' UNIQUE KEY (' . $this->name . ')');
		if($this->foreign)
			array_push($query, ",\n\tCONSTRAINT FK_$table" . $this->foreign_class . '_' . $this->name .
				' FOREIGN KEY (' . $this->name . ") REFERENCES " . $this->foreign_class . " (" . $this->foreign_property . ')');

		return implode($query);
	}

public static List<String> parseSQLStatements(String path, String name) {
		return parseSQLStatements("/" + path + "/" + name);
	}

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


Question:
Checks if a group element is allowed in a container with a given type.<p>

@param containerType the container type spec (comma separated)
@param groupContainer the group

@return true if the group is allowed in the container

public static boolean checkGroupAllowed(String containerType, CmsGroupContainerBean groupContainer) {

        return !Sets.intersection(CmsContainer.splitType(containerType), groupContainer.getTypes()).isEmpty();
    }

def customerMeetsRequirement(self, customer, danceRole=None, registration=None):
        '''

        '''

        cust_reqs = self.customerrequirement_set.filter(customer=customer,met=True)
        if customer:
            cust_priors = customer.eventregistration_set.filter(event__series__isnull=False)
        else:
            cust_priors = EventRegistration.objects.none()

        # If there's an explicit object stating that this customer meets the requirement, then we're done.
        if self.roleEnforced and danceRole and cust_reqs.filter(role=danceRole).exists():
            return True
        elif not self.roleEnforced and cust_reqs.exists():
            return True
        elif self.roleEnforced and not danceRole:
            return False

        # Go through each item for this requirement and see if the customer meets that item
        for item in self.requirementitem_set.all():
            filter_dict = {}
            if item.requiredLevel:
                filter_dict['event__series__classDescription__danceTypeLevel'] = item.requiredLevel
            if item.requiredClass:
                filter_dict['event__series__classDescription'] = item.requiredClass
            if self.roleEnforced:
                filter_dict['role'] = danceRole

            current_matches = 0
            overlap_matches = 0
            nonconcurrent_filter = {'event__endTime__lte': timezone.now()}

            if registration:

                if isinstance(registration,Registration):
                    current_matches = registration.eventregistration_set.filter(**filter_dict).count()
                elif isinstance(registration,TemporaryRegistration):
                    current_matches = registration.temporaryeventregistration_set.filter(**filter_dict).count()

                nonconcurrent_filter = {'event__endTime__lte': registration.firstSeriesStartTime}
                overlap_matches = cust_priors.filter(**filter_dict).exclude(**nonconcurrent_filter).filter(
                    event__startTime__lte=registration.lastSeriesEndTime,
                ).count()

            priors_matches = cust_priors.filter(**filter_dict).filter(**nonconcurrent_filter).count()

            # The number of matches depends on the concurrency rule for this item
            if item.concurrentRule == item.ConcurrencyRule.prohibited:
                matches = priors_matches
            elif item.concurrentRule == item.ConcurrencyRule.allowOneOverlapClass:
                matches = priors_matches + \
                    cust_priors.filter(**filter_dict).exclude(**nonconcurrent_filter).filter(
                        event__startTime__lte=registration.getTimeOfClassesRemaining(1)
                    ).count()
            elif item.concurrentRule == item.ConcurrencyRule.allowTwoOverlapClasses:
                matches = priors_matches + \
                    cust_priors.filter(**filter_dict).exclude(**nonconcurrent_filter).filter(
                        event__startTime__lte=registration.getTimeOfClassesRemaining(2)
                    ).count()
            elif item.concurrentRule == item.ConcurrencyRule.allowed:
                matches = priors_matches + overlap_matches + \
                    (current_matches if isinstance(registration,TemporaryRegistration) else 0)
            elif item.concurrentRule == item.ConcurrencyRule.required:
                matches = overlap_matches + current_matches

            if matches >= item.quantity:
                # If this is an 'or' or a 'not' requirement, then we are done
                if self.booleanRule == self.BooleanChoice.booleanOr:
                    return True
                if self.booleanRule == self.BooleanChoice.booleanNot:
                    return False
            else:
                # If this is an 'and' requirement and we didn't meet, then we are done
                if self.booleanRule == self.BooleanChoice.booleanAnd:
                    return False

        # If we got this far, then either all 'and' requirements were met, or all 'or' and 'not' requirements were not met
        if self.booleanRule == self.BooleanChoice.booleanOr or self.requirementitem_set.count() == 0:
            return False
        return True

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


Question:
Get list of properties and their various options for the supplied
 ComplexType name.
 @param type_name [to_s]
 @return [Hash]
 @api private

def properties_for_complex_type(type_name)
      type_definition = metadata.xpath("//ComplexType[@Name='#{type_name}']").first
      raise ArgumentError, "Unknown ComplexType: #{type_name}" if type_definition.nil?
      properties_to_return = {}
      type_definition.xpath('./Property').each do |property_xml|
        property_name, property = process_property_from_xml(property_xml)
        properties_to_return[property_name] = property
      end
      properties_to_return
    end

def client_data(typ, challenge)
      JSON.dump(
        challenge: challenge,
        origin: app_id,
        typ: typ
      )
    end

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


Question:
Renders a single file with the rST tool.

@param string $tool conversion tool to use
@param string $source rST source file
@param string $targetFile target file name

@return void

@throws BuildException When the conversion fails

protected function renderFile($tool, $source, $targetFile)
    {
        if ($this->uptodate && file_exists($targetFile)
            && filemtime($source) <= filemtime($targetFile)
        ) {
            //target is up to date
            return;
        }
        //work around a bug in php by replacing /./ with /
        $targetDir = str_replace('/./', '/', dirname($targetFile));
        if (!is_dir($targetDir)) {
            $this->log("Creating directory '$targetDir'", Project::MSG_VERBOSE);
            mkdir($targetDir, $this->mode, true);
        }

        $cmd = $tool
            . ' --exit-status=2'
            . ' ' . $this->toolParam
            . ' ' . escapeshellarg($source)
            . ' ' . escapeshellarg($targetFile)
            . ' 2>&1';

        $this->log('command: ' . $cmd, Project::MSG_VERBOSE);
        exec($cmd, $arOutput, $retval);
        if ($retval != 0) {
            $this->log(implode("\n", $arOutput), Project::MSG_INFO);
            throw new BuildException('Rendering rST failed');
        }
        $this->log(implode("\n", $arOutput), Project::MSG_DEBUG);
    }

def tar(self, appname, appversion):

        name_tmpl = '%(app)s-%(version)s-%(time)s.tar.bz2'
        time = utc.now()
        name = name_tmpl % {'app': appname,
                            'version': appversion,
                            'time': time.strftime('%Y-%m-%dT%H-%M')}

        if not os.path.exists(TARBALL_HOME):
            os.mkdir(TARBALL_HOME)
        tarball = os.path.join(TARBALL_HOME, name)
        tar_params = {'filename': tarball, 'folder': self.folder}
        tar_result = run('tar -C %(folder)s -cjf %(filename)s .' % tar_params)
        tar_result.raise_for_status()
        return Build(appname, appversion, time, tarball)

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


Question:
@return mixed

@throws \InvalidArgumentException
@throws Exceptions\RequestNotFound
@throws Exceptions\DisplayNone
@throws NotFound

public function execute()
    {
        $name = $this->request()->attribute($this->attribute);

        if ($this->methodExists($name))
        {
            /**
             * @var Controller $instance
             */
            $instance = $this->instance($name);

            return $instance->execute();
        }

        throw new NotFound('Controller \'' . $name . '\' not found!');
    }

public function dispatch(string $method, string $url): array
    {
        $route = $this->match($url);

        $result = [
            'method' => $method,
            'url' => $url,
        ];

        if (!$route) {
            $result['error'] = 404;
        } elseif (isset($route['methods'][$method])) {
            $params = $route['params'];
            $handler = $route['methods'][$method];

            if (!$handler instanceof \Closure) {
                if (isset($handler['params'])) {
                    $params += $handler['params'];
                }

                $handler = [
                    'app' => $handler['app'] ?? $params['app'] ?? null,
                    'controller' => $handler['controller'] ?? $params['controller'] ?? null,
                    'action' => $handler['action'] ?? $params['action'] ?? null,
                ];
            }

            $result += [
                'route' => $route['route'],
                'params' => $params,
                'handler' => $handler,
            ];
        } else {
            $result += [
                'error' => 405,
                'route' => $route['route'],
                'params' => $route['params'],
                'allowed' => \array_keys($route['methods']),
            ];
        }

        return $this->result = $result;
    }

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


Question:
// createDefaultHTTPClient Creates an HTTP client with a reasonable timeout value
// and potentially a custom *x509.CertPool
// based on the caCertificatesEnvVar environment variable (see the `initCertPool` function)

func createDefaultHTTPClient() *http.Client {
	return &http.Client{
		Transport: &http.Transport{
			Proxy: http.ProxyFromEnvironment,
			DialContext: (&net.Dialer{
				Timeout:   30 * time.Second,
				KeepAlive: 30 * time.Second,
			}).DialContext,
			TLSHandshakeTimeout:   15 * time.Second,
			ResponseHeaderTimeout: 15 * time.Second,
			ExpectContinueTimeout: 1 * time.Second,
			TLSClientConfig: &tls.Config{
				ServerName: os.Getenv(caServerNameEnvVar),
				RootCAs:    initCertPool(),
			},
		},
	}
}

protected function initPrivateCertificate()
    {
        if (!empty($this->privateCertificateFile)) {
            if (!file_exists($this->privateCertificateFile)) {
                throw new InvalidConfigException("Private certificate file '{$this->privateCertificateFile}' does not exist!");
            }
            return file_get_contents($this->privateCertificateFile);
        }
        return '';
    }

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


Question:
Set the upper left 3x3 submatrix of this {@link Matrix4d} to that of the given {@link Matrix4dc}
and don't change the other elements.

@param mat
the {@link Matrix4dc}
@return this

public Matrix4d set3x3(Matrix4dc mat) {
        m00 = mat.m00();
        m01 = mat.m01();
        m02 = mat.m02();
        m10 = mat.m10();
        m11 = mat.m11();
        m12 = mat.m12();
        m20 = mat.m20();
        m21 = mat.m21();
        m22 = mat.m22();
        properties &= mat.properties() & ~(PROPERTY_PERSPECTIVE);
        return this;
    }

public Matrix3d scale(double xyz, Matrix3d dest) {
        return scale(xyz, xyz, xyz, dest);
    }

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


Question:
发送es restful sql请求/_xpack/sql，获取返回值，返回值类型由beanType决定
@param beanType
@param entity

@param <T>
@return
@throws ElasticSearchException

public <T> SQLResult<T>  fetchQuery(Class<T> beanType,  String entity) throws ElasticSearchException {
		SQLRestResponse result = this.client.executeRequest("/_xpack/sql",entity,   new SQLRestResponseHandler());
		SQLResult<T> datas = ResultUtil.buildFetchSQLResult(  result,  beanType,  (SQLResult<T> )null);
		datas.setClientInterface(this);
		return datas;
	}

protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
	{
		xen_hotfix_responses result = (xen_hotfix_responses) service.get_payload_formatter().string_to_resource(xen_hotfix_responses.class, response);
		if(result.errorcode != 0)
		{
			if (result.errorcode == SESSION_NOT_EXISTS)
				service.clear_session();
			throw new nitro_exception(result.message, result.errorcode, (base_response [])result.xen_hotfix_response_array);
		}
		xen_hotfix[] result_xen_hotfix = new xen_hotfix[result.xen_hotfix_response_array.length];

		for(int i = 0; i < result.xen_hotfix_response_array.length; i++)
		{
			result_xen_hotfix[i] = result.xen_hotfix_response_array[i].xen_hotfix[0];
		}

		return result_xen_hotfix;
	}

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


Question:
Change a user's password.

@param  stdClass  $user      User table object
@param  string  $newpassword Plaintext password
@return bool                 True on success

function user_update_password($user, $newpassword) {
        global $DB;

        if ($this->is_internal()) {
            $puser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
            // This will also update the stored hash to the latest algorithm
            // if the existing hash is using an out-of-date algorithm (or the
            // legacy md5 algorithm).
            if (update_internal_user_password($puser, $newpassword)) {
                $user->password = $puser->password;
                return true;
            } else {
                return false;
            }
        } else {
            // We should have never been called!
            return false;
        }
    }

private function formatAction(Action $action)
    {
        $info = [
            'envelope' => 'JSON-RPC-2.0',
            'transport' => 'POST',
            'name' => $action->getName(),
            'description' => $action->getDescription(),
            'parameters' => []
        ];

        foreach ($action->getParameters() as $parameter) {
            $parameterInfo = [
                'name' => $parameter->getName(),
                'type' => $parameter->getType(),
                'description' => $parameter->getDescription(),
                'required' => $parameter->isRequired()
            ];

            if (!$parameter->isRequired()) {
                $parameterInfo['default'] = $parameter->getDefault();
            }

            $info['parameters'][] = $parameterInfo;
        }

        if ($action->getResponse()) {
            $response = $action->getResponse();

            $info['response'] = $response->toArray();
        }

        return $info;
    }

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


Question:
Returns the language of message source.

@return string

private function _getSourceLanguage()
    {
        $languageSourceSearch = Yii::$app->request->get('LanguageSourceSearch', []);

        return isset($languageSourceSearch['source']) ? $languageSourceSearch['source'] : Yii::$app->sourceLanguage;
    }

public void marshall(DetectDominantLanguageRequest detectDominantLanguageRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(detectDominantLanguageRequest.getText(), TEXT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question: Returns a list of

def diff_snapshots(self,snapshot_a,snapshot_b,save = True, diff=None):

        file_revisions_a = snapshot_a.file_revisions
        file_revisions_b = snapshot_b.file_revisions

        file_revisions_diff = diff_objects(file_revisions_a,
                                           file_revisions_b,
                                           file_revision_key,
                                           file_revision_comparator)

        #We just generate code objects and issues
        #for the modified file revisions, to save time when diffing.

        logger.debug("Generating list of modified file revisions...")
        modified_file_revisions_by_path = {}
        for fr_type in ('modified','added','deleted'):
            for fr in file_revisions_diff[fr_type]:
                if not fr.path in modified_file_revisions_by_path:
                    modified_file_revisions_by_path[fr.path] = fr

        logger.debug("Generating list of modified issues...")

        modified_file_revisions_a = [fr for fr in file_revisions_a
                                     if fr.path in modified_file_revisions_by_path]
        modified_file_revisions_b = [fr for fr in file_revisions_b
                                     if fr.path in modified_file_revisions_by_path]

        if modified_file_revisions_a:
            #to do: check the file revisions chunk-wise to avoid DB query errors
            issue_occurrences_a = self.project.backend.filter(IssueOccurrence,
                                         {
                                            'file_revision' : {'$in' : modified_file_revisions_a}
                                         },
                                      include = ('file_revision','issue'))
        else:
            issue_occurrences_a = []

        if modified_file_revisions_b:
            #to do: check the file revisions chunk-wise to avoid DB query errors
            issue_occurrences_b = self.project.backend.filter(IssueOccurrence,
                                           {
                                            'file_revision' : {'$in' : modified_file_revisions_b}
                                            },
                                      include = ('file_revision','issue'))
        else:
            issue_occurrences_b = []

        logger.debug("Diffing issues (%d in A, %d in B)" % (len(issue_occurrences_a),
                                                           len(issue_occurrences_b)))

        issue_occurrences_diff = diff_objects(issue_occurrences_a,
                                              issue_occurrences_b,
                                              issue_occurrence_key,
                                              issue_occurrence_comparator)

        logger.debug("Diffing summary...")
        summary_diff = self.diff_summaries(snapshot_a,snapshot_b)

        if diff is None:
            diff = Diff({'summary' : summary_diff,
                        'snapshot_a' : snapshot_a,
                        'project' : self.project,
                        'configuration' : self.project.configuration,
                        'snapshot_b' : snapshot_b})
            #we generate the hash value for this diff
            hasher = Hasher()
            hasher.add(diff.snapshot_a.hash)
            hasher.add(diff.snapshot_b.hash)
            diff.hash = hasher.digest.hexdigest()
        elif save:
            with self.project.backend.transaction():
                self.project.backend.filter(DiffFileRevision,{'diff' : diff}).delete()
                self.project.backend.filter(DiffIssueOccurrence,{'diff' : diff}).delete()
        if save:
            with self.project.backend.transaction():
                self.project.backend.save(diff)

        diff_file_revisions = []

        with self.project.backend.transaction():
            for key,file_revisions in file_revisions_diff.items():
                for file_revision in file_revisions:
                    hasher = Hasher()
                    hasher.add(file_revision.hash)
                    hasher.add(diff.hash)
                    hasher.add(key)
                    diff_file_revision = DiffFileRevision({
                                            'diff' : diff,
                                            'file_revision' : file_revision,
                                            'hash' : hasher.digest.hexdigest(),
                                            'key' : key})
                    if save:
                        self.project.backend.save(diff_file_revision)
                    diff_file_revisions.append(diff_file_revision)

        diff_issue_occurrences = []
        mapping = {'deleted' : 'fixed','added' : 'added'}
        with self.project.backend.transaction():
            for key,issue_occurrences in issue_occurrences_diff.items():
                if not key in mapping:
                    continue
                for issue_occurrence in issue_occurrences:
                    hasher = Hasher()
                    hasher.add(issue_occurrence.hash)
                    hasher.add(diff.hash)
                    hasher.add(mapping[key])
                    diff_issue_occurrence = DiffIssueOccurrence({
                            'diff' : diff,
                            'hash' : hasher.digest.hexdigest(),
                            'issue_occurrence' : issue_occurrence,
                            'key' : mapping[key]
                        })
                    if save:
                        self.project.backend.save(diff_issue_occurrence)
                    diff_issue_occurrences.append(diff_issue_occurrence)

        return diff,diff_file_revisions,diff_issue_occurrences

public function selectMany($select=null)
    {
        $select = LambdaUtils::toSelectCallable($select);

        $result = array();
        foreach($this as $key => $record)
        {
            $temp = call_user_func($select, $record, $key);
            if(is_array($temp) || $temp instanceof \Iterator)
            {
                foreach($temp as $tempitem)
                {
                    $result[] = $tempitem;
                }
            }
            else
            {
                $result[] = $temp;
            }
        }
        return new ArrayList($result);
    }

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


Question:
Stores a value to cache

@param string $key
@param mixed $value
@param integer $ttl Time to live in seconds
@return void

public function set($key, $value, $ttl)
    {
        $this->arrayCache->set($key, $value, $ttl, time());
        return $this;
    }

function(packedValue)
    {

        var result;

        var t = typeof(packedValue);
        if (t == "number" || t == "string" || t == "boolean" || packedValue == null || packedValue == undefined)
        {
            result = this.handleError(packedValue);
        }
        else if (packedValue instanceof Array)
        {
            result = [];
            for (var i = 0; i < packedValue.length; i++)
            {
                result[i] = this.deserialize(packedValue[i]);
            }
        }
        else if (t == "object")
        {
            for(var i = 0; i < packedValue.newTypes.length; i++)
            {
                this.addTypeDataToCache(packedValue.newTypes[i]);
            }
            for (var aRefID in packedValue.newRefs)
            {
                this.createProxy(aRefID, packedValue.newRefs[aRefID]);
            }
            if (packedValue.type == FABridge.TYPE_PRIMITIVE)
            {
                result = packedValue.value;
            }
            else if (packedValue.type == FABridge.TYPE_ASFUNCTION)
            {
                result = this.getFunctionProxy(packedValue.value);
            }
            else if (packedValue.type == FABridge.TYPE_ASINSTANCE)
            {
                result = this.getProxy(packedValue.value);
            }
            else if (packedValue.type == FABridge.TYPE_ANONYMOUS)
            {
                result = packedValue.value;
            }
        }
        return result;
    }

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


Question: // SetDeletedBranch sets the DeletedBranch field's value.

func (s *DeleteBranchOutput) SetDeletedBranch(v *BranchInfo) *DeleteBranchOutput {
	s.DeletedBranch = v
	return s
}

def get_branch_by_id(self, branch_id):

        for branch in self.branches:
            if branch.branch_id == branch_id:
                return branch
        raise AssertionError("couldn't find branch '%s'" % branch_id)

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


Question: Return numpy.recarray as dict.

def recarray2dict(recarray):
    """"""
    # TODO: subarrays
    result = {}
    for descr, value in zip(recarray.dtype.descr, recarray):
        name, dtype = descr[:2]
        if dtype[1] == 'S':
            value = bytes2str(stripnull(value))
        elif value.ndim < 2:
            value = value.tolist()
        result[name] = value
    return result

def compute_settings(args, rc_settings):

    settings = {}
    for key, value in args.items():
        if key in ['reverse', 'opposite']:
            settings[key] = value ^ rc_settings.get(key, False)
        else:
            settings[key] = value or rc_settings.get(key)

    if not settings['size']:
        settings['size'] = DEFAULT_SIZE
    return settings

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


Question:
Converts a given name into url save and readable urlanme.
 Uses rails parameterize, but converts german umlauts before.

 @returns String

def convert_to_urlname(name)
      name
        .gsub(/[äÄ]/, 'ae')
        .gsub(/[üÜ]/, 'ue')
        .gsub(/[öÖ]/, 'oe')
        .gsub(/[ß]/, 'ss')
        .parameterize
    end

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

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


Question:
@param int $first_party_id
@param int $second_party_id

@return \Illuminate\Database\Eloquent\Builder

public function characterWalletJournalInteractions(int $first_party_id, int $second_party_id) : Builder
    {

        return CharacterWalletJournal::with('first_party', 'second_party')
            ->where('first_party_id', '=', $first_party_id)
            ->where('second_party_id', '=', $second_party_id);

    }

public function initializeArguments()
    {
        parent::initializeArguments();
        $this->registerArgument('results', '\Solarium\QueryType\Select\Result\Result', 'Query results', true);
        $this->registerArgument('document', '\Solarium\QueryType\Select\Result\Document', 'Result document to work on',
            true);
        $this->registerArgument('field', 'string', 'name of field in document to highlight', true);
        $this->registerArgument('alternateField', 'string',
            'name of alternate field in document to use for highlighting', false, null);
        $this->registerArgument('index', 'int', 'if the field is an array: index of the single element to highlight',
            false);
        $this->registerArgument('idKey', 'string', 'name of the field in document that is its ID', false, 'id');
        $this->registerArgument('highlightTagOpen', 'string', 'opening tag to insert to begin highlighting', false,
            '');
        $this->registerArgument('highlightTagClose', 'string', 'closing tag to insert to end highlighting', false,
            '');
        $this->registerArgument('raw', 'boolean', 'whether to not HTML escape the output', false, false);
    }

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


Question: // StringDiff diffs a and b and returns a human readable diff.

func StringDiff(a, b string) string {
	ba := []byte(a)
	bb := []byte(b)
	out := []byte{}
	i := 0
	for ; i < len(ba) && i < len(bb); i++ {
		if ba[i] != bb[i] {
			break
		}
		out = append(out, ba[i])
	}
	out = append(out, []byte("\n\nA: ")...)
	out = append(out, ba[i:]...)
	out = append(out, []byte("\n\nB: ")...)
	out = append(out, bb[i:]...)
	out = append(out, []byte("\n\n")...)
	return string(out)
}

def logs_handle_job(job_uuid: str,
                    job_name: str,
                    log_lines: Optional[Union[str, Iterable[str]]],
                    temp: bool = True) -> None:
    """"""
    handle_job_logs(job_uuid=job_uuid,
                    job_name=job_name,
                    log_lines=log_lines,
                    temp=temp)

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


Question:
// ExtractRootPaths extracts the root paths from the supplied list of paths.
// The resulting root path will not contain any file separators, but there
// may be duplicates.
// So "/content/section/" becomes "content"

func ExtractRootPaths(paths []string) []string {
	r := make([]string, len(paths))
	for i, p := range paths {
		root := filepath.ToSlash(p)
		sections := strings.Split(root, "/")
		for _, section := range sections {
			if section != "" {
				root = section
				break
			}
		}
		r[i] = root
	}
	return r

}

public function readDirectory($directory, $recursive = true)
    {
        if (is_dir($directory) === false) {
            return false;
        }

        try {
            $resource = opendir($directory);
            $contents = array();

            while (false !== ($item = readdir($resource)))
            {
                if (in_array($item, array('.', '..'))
                    || substr($item, 0, 1) == '_') {
                    continue;
                }

                $absoluteItem = $directory . DIRECTORY_SEPARATOR . $item;
                if ($recursive === true && is_dir($absoluteItem)) {
                    $contents[$item] = $this->readDirectory($absoluteItem, $recursive);
                } else {
                    $contents[$item] = $absoluteItem;
                }
            }
        } catch(\Exception $e) {
            return false;
        }

        return $contents;
    }

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


Question: Disconnect from all MongoDB Clients.

def _disconnect(self):
        """"""
        for cluster in self._clusters:
            if 'connection' in cluster:
                connection = cluster.pop('connection')
                connection.close()
        # Remove all attributes that are database names so that next time
        # when they are accessed, __getattr__ will be called and will create
        # new Clients
        for dbname in self._mapped_databases:
            self.__delattr__(dbname)
        self._mapped_databases = []

def check_member_state(self):
        """"""
        bad_states = (0, 3, 4, 5, 6, 9)
        try:
            rs_status = self.run_command('replSetGetStatus')
            bad_members = [member for member in rs_status['members']
                           if member['state'] in bad_states]
            if bad_members:
                return False
        except pymongo.errors.AutoReconnect:
            # catch 'No replica set primary available' Exception
            return False
        logger.debug("all members in correct state")
        return True

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


Question:
список пользователей в виде id=>username
@return array

public static function getUsersArray(): array
    {
        return static::find()->select(['username', 'id'])->where(['status_id' => self::STATUS_ACTIVE])->indexBy('id')->orderBy(['id' => SORT_ASC])->column();
    }

protected function assert_rating_matches($expected, $stored) {
        $this->assertEquals($expected->rating, $stored->rating);
        $this->assertEquals($expected->userid, $stored->author);
    }

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


Question:
// Computes a hash of 4 characters for the given gateway name.
// This will be used for routing of replies.

func getReplyPrefixForGateway(name string) []byte {
	sha := sha256.New()
	sha.Write([]byte(name))
	fullHash := []byte(fmt.Sprintf("%x", sha.Sum(nil)))
	prefix := make([]byte, 0, len(gwReplyPrefix)+5)
	prefix = append(prefix, gwReplyPrefix...)
	prefix = append(prefix, fullHash[:4]...)
	prefix = append(prefix, '.')
	return prefix
}

func Render(typ Type, input interface{}, urlPrefix string, metas map[string]string) []byte {
	var rawBytes []byte
	switch v := input.(type) {
	case []byte:
		rawBytes = v
	case string:
		rawBytes = []byte(v)
	default:
		panic(fmt.Sprintf("unrecognized input content type: %T", input))
	}

	urlPrefix = strings.TrimRight(strings.Replace(urlPrefix, " ", "%20", -1), "/")
	var rawHTML []byte
	switch typ {
	case MARKDOWN:
		rawHTML = RawMarkdown(rawBytes, urlPrefix)
	case ORG_MODE:
		rawHTML = RawOrgMode(rawBytes, urlPrefix)
	default:
		return rawBytes // Do nothing if syntax type is not recognized
	}

	rawHTML = postProcessHTML(rawHTML, urlPrefix, metas)
	return SanitizeBytes(rawHTML)
}

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


Question:
Command DevLockStatus

@param deviceName device name
@return lock status
@throws DevFailed

@Command(name = "DevLockStatus", inTypeDesc = DEVICE_NAME, outTypeDesc = "Device locking status")
    public DevVarLongStringArray devLockStatus(final String deviceName) throws DevFailed {
        DevVarLongStringArray result = null;
        int nbClasses = 0;
        final String fullDeviceName = TangoUtil.getfullNameForDevice(deviceName);
        for (final DeviceClassBuilder deviceClass : classList) {
            if (deviceClass.containsDevice(fullDeviceName)) {
                result = deviceClass.getDeviceImpl(fullDeviceName).getLockStatus();
                logger.debug("DevLockStatus {} {}", Arrays.toString(result.lvalue), Arrays.toString(result.svalue));
                xlogger.exit();
                break;
            }
            nbClasses++;
        }
        if (nbClasses == classList.size()) {
            throw DevFailedUtils.newDevFailed(ExceptionMessages.DEVICE_NOT_FOUND, deviceName + DOES_NOT_EXISTS);
        }
        return result;
    }

public static function execute($value, ContextInterface $context): array
    {
        if (is_string($value) === true) {
            $lcValue = strtolower($value);
            if ($lcValue === 'true' || $lcValue === '1' || $lcValue === 'on' || $lcValue === 'yes') {
                $reply = static::createSuccessReply(true);
            } elseif ($lcValue === 'false' || $lcValue === '0' || $lcValue === 'off' || $lcValue === 'no') {
                $reply = static::createSuccessReply(false);
            } else {
                $reply = static::createErrorReply($context, $value, ErrorCodes::IS_BOOL, Messages::IS_BOOL, []);
            }
        } elseif (is_bool($value) === true) {
            $reply = static::createSuccessReply($value);
        } else {
            $reply = static::createErrorReply($context, $value, ErrorCodes::IS_BOOL, Messages::IS_BOOL, []);
        }

        return $reply;
    }

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


Question:
Consumes a word for each trie, updating respective states.

        :param word_ids: The set of word IDs.

def consume(self, word_ids: mx.nd.NDArray) -> None:

        word_ids = word_ids.asnumpy().tolist()
        for i, word_id in enumerate(word_ids):
            if self.global_avoid_states:
                self.global_avoid_states[i] = self.global_avoid_states[i].consume(word_id)
            if self.local_avoid_states:
                self.local_avoid_states[i] = self.local_avoid_states[i].consume(word_id)

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:
Determines the request method.

@return string

protected function determineMethod(): string
	{
		$this->realMethod = $method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));

		if($method === 'POST')
		{
			return strtoupper($this->post->get('REQUEST_METHOD_OVERRIDE', $this->server->get('HTTP_X_HTTP_METHOD_OVERRIDE', 'POST')));
		}

		return $method;
	}

public ResultResponseUtil status(IReturnCode iReturnCode) {
        this.setCode(iReturnCode.getCode());
        this.setMsg(iReturnCode.getMsg());
        return this;
    }

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


Question:
@return string

@throws QueryException when id or document_name is null

public function getQuery()
    {
        $idField = $this->documentKey;

        if ($idField == null) {
            throw new QueryException('id should not be null');
        }

        $documentLimitation = $this->createFilterQuery('id')->setQuery(sprintf('id:%s', $idField));
        $this->addFilterQuery($documentLimitation);

        $this->setQuery('*:*');

        return parent::getQuery();
    }

public static <A> CollQuery<A> from(Path<A> path, Iterable<A> col) {
        return new CollQuery<Void>().from(path, col).select(path);
    }

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


Question: Removes a property from this set.

public PropertySet remove( String property)
    {
    String candidate = StringUtils.trimToNull( property);
    if( candidate != null)
      {
      properties_.remove( candidate, 1);
      }

    return this;
    }

private boolean isRemoved(HeaderType<?> headerType)
	{
		for (HeaderType<?> type : mRemovedHeaderTypes)
		{
			if (type.equals(headerType))
			{
				return true;
			}
		}
		return false;
	}

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


Question: // verifyPerkeepRoot sets pkRoot and crashes if dir isn't the Perkeep root directory.

func verifyPerkeepRoot() {
	var err error
	pkRoot, err = os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get current directory: %v", err)
	}
	testFile := filepath.Join(pkRoot, "pkg", "blob", "ref.go")
	if _, err := os.Stat(testFile); err != nil {
		log.Fatalf("make.go must be run from the Perkeep src root directory (where make.go is). Current working directory is %s", pkRoot)
	}

	// we can't rely on perkeep.org/cmd/pk with modules on as we have no assurance
	// the current dir is $GOPATH/src/perkeep.org, so we use ./cmd/pk instead.
	cmd := exec.Command("go", "list", "-f", "{{.Target}}", "./cmd/pk")
	if os.Getenv("GO111MODULE") == "off" || *buildWebUI {
		// if we're building the webUI we need to be in "legacy" GOPATH mode, so in
		// $GOPATH/src/perkeep.org
		if err := validateDirInGOPATH(pkRoot); err != nil {
			log.Fatalf("We're running in GO111MODULE=off mode, either because you set it, or because you want to build the Web UI, so we need to be in a GOPATH, but: %v", err)
		}
		cmd = exec.Command("go", "list", "-f", "{{.Target}}", "perkeep.org/cmd/pk")
	}
	cmd.Stderr = os.Stderr
	out, err := cmd.Output()
	if err != nil {
		log.Fatalf("Could not run go list to find install dir: %v, %s", err, out)
	}
	binDir = filepath.Dir(strings.TrimSpace(string(out)))
}

def _get_zk_path_children(self, zk_conn, zk_path, name_for_error):
        """"""
        children = []
        try:
            children = zk_conn.get_children(zk_path)
        except NoNodeError:
            self.log.info('No zookeeper node at %s', zk_path)
        except Exception:
            self.log.exception('Could not read %s from %s', name_for_error, zk_path)
        return children

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


Question: // Get returns a specified direction of the quad.

func (q InternalQuad) Get(d quad.Direction) graph.Value {
	switch d {
	case quad.Subject:
		return q.Subject
	case quad.Predicate:
		return q.Predicate
	case quad.Object:
		return q.Object
	case quad.Label:
		return q.Label
	default:
		return nil
	}
}

function lineTop (){
    var l = line(chars.top
               , chars['top-left'] || chars.top
               , chars['top-right'] ||  chars.top
               , chars['top-mid']);
    if (l)
      ret += l + "\n";
  }

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


Question:
/*!
Runs the optimizer

static function optimize( $useComments, &$php, $tpl, &$tree, &$resourceData )
    {
        /* If for some reason we don't have elements, simply return */
        if (! is_array( $tree[1] ) )
            return;

        $addNodeInit = false;

        /* Loop through the children of the root */
        foreach ( $tree[1] as $key => $kiddie )
        {
            /* Analyse per node type */
            switch ( $kiddie[0] )
            {
                case eZTemplate::NODE_INTERNAL_OUTPUT_SPACING_INCREASE:
                case eZTemplate::NODE_INTERNAL_SPACING_DECREASE:
                    /* Removing unnecessary whitespace changes */
                    unset( $tree[1][$key] );
                    break;
                case 3: /* Variable */
                    if ( isset( $tree[1][$key + 1] ) and
                         ( $tree[1][$key + 1][0] == eZTemplate::NODE_INTERNAL_RESOURCE_ACQUISITION ) and
                         isset( $resourceData['class-info'] ) )
                    {
                        $ret = eZTemplateOptimizer::optimizeResourceAcquisition(
                            $useComments, $php, $tpl,
                            $tree[1][$key], $tree[1][$key + 1], $resourceData );
                        /* We only unset the tree node when the optimization
                         * function returns false, as that means that the
                         * optimization could not be made. */
                        if ($ret)
                        {
                            unset( $tree[1][$key] );
                        }
                    }
                    else
                    {
                        $ret = eZTemplateOptimizer::optimizeVariable( $useComments, $php, $tpl, $tree[1][$key][2], $resourceData );
                        if ( $ret & 1 )
                            $addNodeInit = true;
                    }
                    break;
            }
        }
        if ( $addNodeInit )
        {
            $initializer = array( eZTemplate::NODE_OPTIMIZED_INIT, null, false );
            array_unshift( $tree[1], $initializer );
        }
    }

public function setCompiler(Compiler $compiler)
    {
        $this->compiler = $compiler;
        $this->compiler->setParser($this);

        return $this;
    }

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


Question:
Giving a string, try to return the container service or parameter if exists
This method can be call by array_walk or array_walk_recursive.

@param mixed $item

@return mixed

public function getContainerValues(&$item)
    {
        if (false === is_object($item) && false === is_array($item)) {
            $item = $this->getContainerServices($this->getContainerParameters($item));
        }

        return $item;
    }

public function setProviders($providers)
    {
        $this->guardForArrayOrTraversable($providers);

        foreach ($providers as $provider) {
            $this->addProvider($provider);
        }
    }

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


Question: // Snapshot returns a copy of the values of all registered counters and gauges.

func Snapshot() (c map[string]uint64, g map[string]int64) {
	hm.Lock()
	defer hm.Unlock()

	gm.Lock()
	defer gm.Unlock()

	cm.Lock()
	defer cm.Unlock()

	for _, init := range inits {
		init()
	}

	c = make(map[string]uint64, len(counters)+len(counterFuncs))
	for n, v := range counters {
		c[n] = v
	}

	for n, f := range counterFuncs {
		c[n] = f()
	}

	g = make(map[string]int64, len(gauges))
	for n, f := range gauges {
		g[n] = f()
	}

	return
}

public function init(array $params = array()) {
        if (count($params) !== count($this->_config)) {
            throw new Garp_Browsebox_Exception('Number of parameters does not match the number of required parameters in filter "'.$this->getId().'"');
        }
        $this->_values = $params;
    }

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


Question: Returns the keyword arguments for instantiating the form.

def get_form_kwargs(self, key):

        kwargs = super(MultipleModelFormMixin, self).get_form_kwargs(key)
        if hasattr(self, '{}_object'.format(key)):
            kwargs.update({'instance': getattr(self, '{}_object'.format(key))})
        return kwargs

def _init_metadata(self, **kwargs):
        """"""
        osid_objects.OsidObjectForm._init_metadata(self, **kwargs)
        self._rubric_default = self._mdata['rubric']['default_id_values'][0]
        self._level_default = self._mdata['level']['default_id_values'][0]

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


Question: // NewService creates a new configured ID service.

func NewService(config ServiceConfig) (Service, error) {
	// Dependencies.
	if config.RandomService == nil {
		return nil, maskAnyf(invalidConfigError, "random service must not be empty")
	}

	// Settings.
	if config.HashChars == "" {
		return nil, maskAnyf(invalidConfigError, "hash characters must not be empty")
	}
	if config.Length == 0 {
		return nil, maskAnyf(invalidConfigError, "length must not be empty")
	}

	newService := &service{
		// Dependencies.
		random: config.RandomService,

		// Settings.
		hashChars: config.HashChars,
		length:    config.Length,
	}

	return newService, nil
}

func (s *SqlRunConfiguration) SetInputId(v string) *SqlRunConfiguration {
	s.InputId = &v
	return s
}

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


Question:
Creates signature objects from known signature versions.

This provider currently recognizes the following signature versions:

- v4: Signature version 4.
- anonymous: Does not sign requests.

@return callable

public static function version()
    {
        return function ($version, $service, $region) {
            switch ($version) {
                case 's3v4':
                case 'v4':
                    return !empty(self::$s3v4SignedServices[$service])
                        ? new S3SignatureV4($service, $region)
                        : new SignatureV4($service, $region);
                case 'v4-unsigned-body':
                    return new SignatureV4($service, $region, ['unsigned-body' => 'true']);
                case 'anonymous':
                    return new AnonymousSignature();
                default:
                    return null;
            }
        };
    }

protected function processMime($mime)
    {
        $vendor             = $this->getContainer()->get(Application::CONTAINER_ID_VENDOR);
        $apiVersion         = $this->getContainer()->get(Application::CONTAINER_ID_API_VERSION);
        $apiVersionRegExp   = Application::API_VERSION_REG_EXP;
        $format             = null;

        if (preg_match(
            '#application/vnd\.' . $vendor . '-v' . $apiVersionRegExp . '\+(xml|json)#',
            $mime,
            $matches
        )) {
            list($mime, $apiVersion, $format) = $matches;
        } elseif (preg_match(
            '#application/vnd\.' . $vendor . '\+(xml|json).*?version=' . $apiVersionRegExp . '#',
            $mime,
            $matches
        )) {
            list($mime, $format, $apiVersion) = $matches;
        } elseif ('application/json' === $mime) {
            $format = 'json';
            $mime   = 'application/vnd.' . $vendor . '-v' . $apiVersion . '+json';
        } elseif ('application/xml' === $mime) {
            $format = 'xml';
            $mime   = 'application/vnd.' . $vendor . '-v' . $apiVersion . '+xml';
        }

        return new MimeProcessResult($mime, $vendor, $apiVersion, $format);
    }

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


protected function addPagingToParameters($parameters = null, $page_offset = null, $items_per_page = null)
    {
        if ($parameters === null) {
            $parameters = [];
        }
        if ($page_offset === null) {
            $page_offset = 0;
        }
        if ($items_per_page === null) {
            $items_per_page = 50;
        }

        $parameters['pg'] = (string) $page_offset;
        $parameters['limit'] = (string) $items_per_page;

        return $parameters;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        G2.dispose();
    }

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


Question:
REST endpoint for retrieving all features for a given sprint and team
(the sprint is derived)

@param teamId
A given scope-owner's source-system ID
@return A data response list of type Feature containing all features for
the given team and current sprint

@RequestMapping(value = "/feature/{number}", method = GET, produces = APPLICATION_JSON_VALUE)
	public DataResponse<List<Feature>> story(
			@RequestParam(value = "component", required = true) String cId,
			@PathVariable(value = "number") String storyNumber) {
		ObjectId componentId = new ObjectId(cId);
		return this.featureService.getStory(componentId, storyNumber);
	}

public function siteTitleSearchAction()
    {
        $query = $this->getEvent()->getRouteMatch()->getParam('query');
        $entityMgr = $this->getServiceLocator()->get(
            'Doctrine\ORM\EntityManager'
        );

        $currentSite = $this->getServiceLocator()->get(
            \Rcm\Service\CurrentSite::class
        );
        $siteId = $currentSite->getSiteId();

        $results = $entityMgr->createQuery(
            '
                select page.name, page.pageTitle, page.pageType from Rcm\\Entity\\Page page
                join page.site site
                where (page.name like :query or page.pageTitle like :query) and site.siteId like :siteId
            '
        )->setParameter('query', '%' . $query . '%')
            ->setParameter('siteId', '%' . $siteId . '%')
            ->getResult();

        $pageNames = [];
        foreach ($results as $result) {
            $pageNames[$result['name']] = [
                'title' => $result['pageTitle'],
                'url' => $this->urlToPage($result['name'], $result['pageType'])
            ];
        }

        return new JsonModel($pageNames);
    }

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


Question:
Query for features in the WGS84 projected bounding box

@param boundingBox query bounding box in WGS84 projection
@return feature index results, must be closed

public FeatureIndexResults queryFeatures(BoundingBox boundingBox) {
        FeatureIndexResults results = queryFeatures(boundingBox, null);
        return results;
    }

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: Performs a mail merge for the specified campaign.

def set_campaign_merge(targets, campaign_id)
    login! unless logged_in?
    json = <<-EOF
      {
        "session": "#{@sugar_session_id}",
        "targets": #{targets.to_json},
        "campaign-id": "#{campaign_id}"
      }
    EOF
    json.gsub!(/^\s{6}/,'')
    send!(:set_campaign_merge, json)
  end

public static void main(String[] args) throws Throwable {
		CliArguments arguments = CliArguments.parse(args);
		if (arguments.isSet() && !arguments.isUsageMode()) {
			CliRunner runner = new CliRunner(arguments);
			try {
				runner.run();
			} finally {
				runner.close();
			}
		} else {
			PrintWriter out = new PrintWriter(System.out);
			printUsage(out);
			FileHelper.safeClose(out);
		}
	}

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


@Override
	@SuppressWarnings("unchecked")
	public void initialize() throws Exception {

		final TypeComparator<IT2> solutionSetComparator;

		// grab a handle to the hash table from the iteration broker
		if (taskContext instanceof AbstractIterativeTask) {
			AbstractIterativeTask<?, ?> iterativeTaskContext = (AbstractIterativeTask<?, ?>) taskContext;
			String identifier = iterativeTaskContext.brokerKey();
			Object table = SolutionSetBroker.instance().get(identifier);

			if (table instanceof CompactingHashTable) {
				this.hashTable = (CompactingHashTable<IT2>) table;
				solutionSetSerializer = this.hashTable.getBuildSideSerializer();
				solutionSetComparator = this.hashTable.getBuildSideComparator().duplicate();
			}
			else if (table instanceof JoinHashMap) {
				this.objectMap = (JoinHashMap<IT2>) table;
				solutionSetSerializer = this.objectMap.getBuildSerializer();
				solutionSetComparator = this.objectMap.getBuildComparator().duplicate();
			}
			else {
				throw new RuntimeException("Unrecognized solution set index: " + table);
			}
		}
		else {
			throw new Exception("The task context of this driver is no iterative task context.");
		}

		TaskConfig config = taskContext.getTaskConfig();
		ClassLoader classLoader = taskContext.getUserCodeClassLoader();

		TypeComparatorFactory<IT1> probeSideComparatorFactory = config.getDriverComparator(0, classLoader);

		this.probeSideSerializer = taskContext.<IT1>getInputSerializer(0).getSerializer();
		this.probeSideComparator = probeSideComparatorFactory.createComparator();

		ExecutionConfig executionConfig = taskContext.getExecutionConfig();
		objectReuseEnabled = executionConfig.isObjectReuseEnabled();

		if (objectReuseEnabled) {
			solutionSideRecord = solutionSetSerializer.createInstance();
		};

		TypePairComparatorFactory<IT1, IT2> factory = taskContext.getTaskConfig().getPairComparatorFactory(taskContext.getUserCodeClassLoader());
		pairComparator = factory.createComparator12(this.probeSideComparator, solutionSetComparator);
	}

public static byte[] decode( byte[] source, int off, int len )
    {
        int    len34   = len * 3 / 4;
        byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
        int    outBuffPosn = 0;

        byte[] b4        = new byte[4];
        int    b4Posn    = 0;
        int    i         = 0;
        byte   sbiCrop   = 0;
        byte   sbiDecode = 0;
        for( i = 0; i < len; i++ )
        {
            sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
            sbiDecode = DECODABET[ sbiCrop ];

            if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better
            {
                if( sbiDecode >= EQUALS_SIGN_ENC )
                {
                    b4[ b4Posn++ ] = sbiCrop;
                    if( b4Posn > 3 )
                    {
                        outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn );
                        b4Posn = 0;

                        // If that was the equals sign, break out of 'for' loop
                        if( sbiCrop == EQUALS_SIGN )
                            break;
                    }   // end if: quartet built

                }   // end if: equals sign or better

            }   // end if: white space, equals sign or better
            else
            {
				LoggerFactory.getDefaultLogger().error( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
                return null;
            }   // end else:
        }   // each input character

        byte[] out = new byte[ outBuffPosn ];
        System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
        return out;
    }

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


Question:
@param Constraint $constraint
@param string     $documentationKey

@return mixed|null Return null if value does not exist

protected function getPayloadDocValue(Constraint $constraint, string $documentationKey)
    {
        return $this->hasPayloadDocKey($constraint, $documentationKey)
            ? $constraint->payload[self::PAYLOAD_DOCUMENTATION_KEY][$documentationKey]
            : null
        ;
    }

protected XmlElement buildSqlClause(IntrospectedTable introspectedTable) {

    XmlElement sql = new XmlElement("sql");
    sql.addAttribute(new Attribute("id", IDENTIFIERS_ARRAY_CONDITIONS));

    XmlElement foreach = new XmlElement("foreach");
    foreach.addAttribute(new Attribute("collection", "array"));
    foreach.addAttribute(new Attribute("item", "item"));
    foreach.addAttribute(new Attribute("index", "index"));
    foreach.addAttribute(new Attribute("separator", " and "));

    StringBuilder sb = new StringBuilder();
    for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) {
      XmlElement isEqualElement = new XmlElement("if");
      sb.setLength(0);
      sb.append("item == \'");
      sb.append(introspectedColumn.getJavaProperty());
      sb.append("\'");
      isEqualElement.addAttribute(new Attribute("test", sb.toString()));
      foreach.addElement(isEqualElement);

      sb.setLength(0);
      sb.append(MyBatis3FormattingUtilities.getAliasedEscapedColumnName(introspectedColumn));
      sb.append(" = ");
      sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, PROPERTY_PREFIX));

      isEqualElement.addElement(new TextElement(sb.toString()));
    }

    sql.addElement(foreach);
    return sql;
  }

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


Question:
Returns a list of IPs assigned to a domain.

@return IndexResponse|ResponseInterface

public function domainIndex(string $domain)
    {
        Assert::stringNotEmpty($domain);

        $response = $this->httpGet(sprintf('/v3/domains/%s/ip', $domain));

        return $this->hydrateResponse($response, IndexResponse::class);
    }

public void marshall(DnsConfig dnsConfig, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(dnsConfig.getNamespaceId(), NAMESPACEID_BINDING);
            protocolMarshaller.marshall(dnsConfig.getRoutingPolicy(), ROUTINGPOLICY_BINDING);
            protocolMarshaller.marshall(dnsConfig.getDnsRecords(), DNSRECORDS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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