Question:
Return a new vector that has been moved towards the given target by
        the given extent.  The extent should be between 0 and 1.

def get_interpolated(self, target, extent):

        result = self.copy()
        result.interpolate(target, extent)
        return result

func (l *WAL) Remove(ctx context.Context, files []string) error {
	if !l.enabled {
		return nil
	}

	span, _ := tracing.StartSpanFromContext(ctx)
	defer span.Finish()

	l.mu.Lock()
	defer l.mu.Unlock()

	for i, fn := range files {
		span.LogKV(fmt.Sprintf("path-%d", i), fn)
		os.RemoveAll(fn)
	}

	// Refresh the on-disk size stats
	segments, err := SegmentFileNames(l.path)
	if err != nil {
		return err
	}
	l.tracker.SetSegments(uint64(len(segments)))

	var totalOldDiskSize int64
	for _, seg := range segments {
		stat, err := os.Stat(seg)
		if err != nil {
			return err
		}

		totalOldDiskSize += stat.Size()
	}
	l.tracker.SetOldSegmentSize(uint64(totalOldDiskSize))
	return nil
}

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


Question:
Returns all validated attributes

@return array
<code>
$res = [
'attribName' => (\DataFilter\Attribute)$obj,
..
];
</code>

public function getValidAttribs()
    {
        return array_combine(
            array_keys($this->validAttribs),
            array_map(function ($ref) {
                return $ref['attrib'];
            }, array_values($this->validAttribs))
        );
    }

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

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

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


Question: // The grpc handler

func (h *grpcHandler) Publish(ctx context.Context, msg *proto.Message) (*proto.Empty, error) {
	if len(msg.Topic) == 0 {
		return nil, merr.InternalServerError("go.micro.broker", "Topic not found")
	}

	m := &broker.Message{
		Header: msg.Header,
		Body:   msg.Body,
	}

	p := &grpcPublication{m: m, t: msg.Topic}

	h.g.RLock()
	for _, subscriber := range h.g.subscribers[msg.Topic] {
		if msg.Id == subscriber.id {
			// sub is sync; crufty rate limiting
			// so we don't hose the cpu
			subscriber.fn(p)
		}
	}
	h.g.RUnlock()
	return new(proto.Empty), nil
}

public function setTimePartConfig($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2\TimePartConfig::class);
        $this->writeOneof(8, $var);

        return $this;
    }

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


Question: // groupBy groups a generic array or slice by the path property key

func groupBy(entries interface{}, key string) (map[string][]interface{}, error) {
	return generalizedGroupByKey("groupBy", entries, key, func(groups map[string][]interface{}, value interface{}, v interface{}) {
		groups[value.(string)] = append(groups[value.(string)], v)
	})
}

func (ns *nurseryStore) getHeightBucketPath(tx *bbolt.Tx,
	height uint32) (*bbolt.Bucket, *bbolt.Bucket, *bbolt.Bucket) {

	// Retrieve the existing chain bucket for this nursery store.
	chainBucket := tx.Bucket(ns.pfxChainKey)
	if chainBucket == nil {
		return nil, nil, nil
	}

	// Retrieve the existing channel index.
	hghtIndex := chainBucket.Bucket(heightIndexKey)
	if hghtIndex == nil {
		return nil, nil, nil
	}

	// Serialize the provided block height and return the bucket matching
	// the serialized key.
	var heightBytes [4]byte
	byteOrder.PutUint32(heightBytes[:], height)

	return chainBucket, hghtIndex, hghtIndex.Bucket(heightBytes[:])
}

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


Question:
input

@param   string  $type
@param   string  $name
@param   string  $value
@param   array   $attributes
@return  Tag

public function input($type, $name, $value = null, array $attributes = [])
    {
        $tag = new Tag('input', $attributes);
        $tag->type = $type;
        $tag->name = $name;
        $tag->value = $value;
        return $tag;
    }

public function parse()
    {
        if (null === $this->html) {
            throw new HtmlPhpExcelException('You must provide html content first. Use setHtml() or setHtmlFile().');
        }

        $dom = new \DOMDocument();
        $dom->loadHTML($this->html);

        $xpath = new \DOMXPath($dom);
        $htmlTables = $xpath->query('.//table[contains(concat(" ", normalize-space(@class), " "), "'.$this->tableClass.'")]');

        $document = new Document();

        foreach ($htmlTables as $htmlTable) {

            $table = new Table();

            $htmlRows = $xpath->query('.//tr[contains(concat(" ", normalize-space(@class), " "), "'.$this->rowClass.'")]', $htmlTable);
            foreach($htmlRows as $htmlRow) {

                $row = new Row();
                $htmlCells = $xpath->query(
                     './/td[contains(concat(" ", normalize-space(@class), " "), "'.$this->cellClass.'")]
                    | .//th[contains(concat(" ", normalize-space(@class), " "), "'.$this->cellClass.'")]',
                    $htmlRow
                );

                foreach($htmlCells as $htmlCell) {
                    $cell = new Cell();
                    $cell->setValue($htmlCell->nodeValue);

                    foreach ($htmlCell->attributes as $attribute) {
                        $cell->addAttribute($attribute->name, $attribute->value);
                    }

                    if ('th' == $htmlCell->nodeName) {
                        $cell->setIsHeader(true);
                    }

                    $row->addCell($cell);
                }

                foreach ($htmlRow->attributes as $attribute) {
                    $row->addAttribute($attribute->name, $attribute->value);
                }

                $table->addRow($row);
            }

            foreach ($htmlTable->attributes as $attribute) {
                $table->addAttribute($attribute->name, $attribute->value);
            }

            $document->addTable($table);
        }

        return $document;
    }

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


Question:
Get a list of domains within a particular level of the hierarchy
@param hierarchy A dot-separated list giving the X-group, H-group, and/or
T-group (e.g. "1.1" for all members of the RIFT-related H-group)
@return
@throws IOException

@Override
	public List<EcodDomain> filterByHierarchy(String hierarchy) throws IOException {
		String[] xhtGroup = hierarchy.split("\\.");
		Integer xGroup = xhtGroup.length>0 ? Integer.parseInt(xhtGroup[0]) : null;
		Integer hGroup = xhtGroup.length>1 ? Integer.parseInt(xhtGroup[1]) : null;
		Integer tGroup = xhtGroup.length>2 ? Integer.parseInt(xhtGroup[2]) : null;

		List<EcodDomain> filtered = new ArrayList<EcodDomain>();
		for(EcodDomain d: getAllDomains()) {
			boolean match = true;
			if(xhtGroup.length>0) {
				match = match && xGroup.equals(d.getXGroup());
			}
			if(xhtGroup.length>1) {
				match = match && hGroup.equals(d.getHGroup());
			}
			if(xhtGroup.length>2) {
				match = match && tGroup.equals(d.getTGroup());
			}
			if(xhtGroup.length>3) {
				logger.warn("Ignoring unexpected additional parts of ECOD {}",hierarchy);
			}
			if(match) {
				filtered.add(d);
			}
		}
		return filtered;
	}

private function dumpStructure() {
    dump("Requesters:");
    dump($this->requesters);

    dump("Request roots:");
    dump($this->requestRoots);

    dump("Request paths:");
    dump($this->requestPaths);

    dump("Local names:");
    dump($this->localNames);

    if (isset($this->tree)) {
      dump("Containment tree:");
      dump($this->tree);
    }
  }

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


Question: store as digests to save space

private static String toDigest(String input) {
        md.reset();
        try {
            md.update(input.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
        }
        String result = com.ibm.ws.common.internal.encoder.Base64Coder.base64EncodeToString(md.digest());
        //String result = Base64.getEncoder().encodeToString(md.digest());  // java8 only
        return result;
    }

def _flush(self):

        # Upload segment with workers
        name = self._segment_name % self._seek
        response = self._workers.submit(
            self._client.put_object, self._container, name,
            self._get_buffer())

        # Save segment information in manifest
        self._write_futures.append(dict(
            etag=response, path='/'.join((self._container, name))))

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


Question: // Trending returns a trending response from the Giphy API

func (c *Client) Trending(args ...[]string) (Trending, error) {
	path := fmt.Sprintf("/gifs/trending?limit=%v", c.Limit)
	req, err := c.NewRequest(path)
	if err != nil {
		return Trending{}, err
	}

	var res Trending
	if _, err = c.Do(req, &res); err != nil {
		return res, err
	}

	if len(res.Data) == 0 {
		return res, ErrNoTrendingImagesFound
	}

	return res, nil
}

def chain_specs(specs):

    LOG.info("Parsing %s specs", len(specs))
    # First spec is always an input
    pin = pypein.input_for(specs[0]).__iter__()
    # If only an input spec was provided, then use json for output
    if len(specs) == 1:
        pout = pypeout.output_for("json")
    else:
        # Middle specs are filters that successively wrap input
        for s in specs[1:-1]:
            pin = pypef.filter_for(s).filter(pin)
        # Assume output on last spec, but it may be a filter.
        # If last spec is a filter, use json for output
        try:
            pout = pypeout.output_for(specs[-1])
        except pypeout.NoSuchOutputException:
            pin = pypef.filter_for(specs[-1]).filter(pin)
            pout = pypeout.output_for("json")
    return pout, pin

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


Question:
Creates a DiGraphIterator. It will iterate once for every node.
@param root
@param edges

public static <T> DiGraphIterator<T> getInstance(T root, Function<? super T, ? extends Collection<T>> edges)
    {
        return new DiGraphIterator<>(root, (y)->edges.apply(y).stream());
    }

def parent(self, parent):

        self._parent = parent
        self.graph.add(
            (self.asNode(), RDF_NAMESPACES.CAPITAINS.parent, parent.asNode())
        )
        parent._add_member(self)

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


Question:
Get visitor IP address

@param ConnectionInterface $conn
@throws \Sonar\Exceptions\AppServiceException
@return string

private function getLanguage(ConnectionInterface $conn) {

        if($conn->WebSocket instanceof \StdClass) {
            $language = $conn->WebSocket->request->getHeader('Accept-Language');
            $language = trim(strtoupper(substr($language, 0, 2)));

            return (empty($language) === false) ? $language :'Unknown';
        }
        throw new AppServiceException('Language not defined');
    }

public void setConnectIps(java.util.Collection<String> connectIps) {
        if (connectIps == null) {
            this.connectIps = null;
            return;
        }

        this.connectIps = new com.amazonaws.internal.SdkInternalList<String>(connectIps);
    }

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


Question:
Check if the cookie is valid according to RFC 6265

@return bool|string Returns true if valid or an error message if invalid

public function validate()
    {
        // Names must not be empty, but can be 0
        $name = $this->getName();
        if (empty($name) && !is_numeric($name)) {
            return 'The cookie name must not be empty';
        }

        // Check if any of the invalid characters are present in the cookie name
        if (strpbrk($name, self::getInvalidCharacters()) !== false) {
            return 'The cookie name must not contain invalid characters: ' . $name;
        }

        // Value must not be empty, but can be 0
        $value = $this->getValue();
        if (empty($value) && !is_numeric($value)) {
            return 'The cookie value must not be empty';
        }

        // Domains must not be empty, but can be 0
        // A "0" is not a valid internet domain, but may be used as server name in a private network
        $domain = $this->getDomain();
        if (empty($domain) && !is_numeric($domain)) {
            return 'The cookie domain must not be empty';
        }

        return true;
    }

public function isValid($token)
    {
        $this->validatePrepared();

        return $this->sessionBag->has(self::CSRF_TKN_NAME) &&
               $this->sessionBag->has(self::CSRF_TKN_TIME) &&
               $this->sessionBag->get(self::CSRF_TKN_NAME) === $token;
    }

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


Question:
Check session - read & update cookies, setup session state machine and register callbacks.

This must be called before using any state machines. No transitions
are invoked at this point, only the session state machine reference
is created.

public function checkSession()
	{
		// Get session token
		$session_token = isset($_COOKIE[$this->cookie_name]) ? $_COOKIE[$this->cookie_name]
			: (isset($_SERVER['HTTP_AUTH_TOKEN']) ? $_SERVER['HTTP_AUTH_TOKEN'] : null);

		// Get reference to session state machine
		if ($session_token) {
			// Get session machine ref
			$session_id = (array) $this->session_machine_ref_prefix;
			$session_id[] = $session_token;
			$this->session_machine = $this->smalldb->ref($session_id);

			// Check session
			if ($this->session_machine->state == '') {
				// Invalid token
				$this->session_machine = $this->smalldb->ref($this->session_machine_null_ref);
			} else {
				// TODO: Validate token, not only session existence, and check whether session is in valid state (invoke a transition to check).

				// TODO: Session should tell how long it will last so the cookie should have the same duration.

				// Token is good - refresh cookie
				setcookie($this->cookie_name, $session_token, time() + $this->cookie_ttl, '/', null, !empty($_SERVER['HTTPS']), true);
			}
		} else {
			// No token
			$this->session_machine = $this->smalldb->ref($this->session_machine_null_ref);
		}

		// Update token on state change
		$t = $this;
		$this->session_machine->afterTransition()->addListener(function($ref, $transition_name, $arguments, $return_value, $returns) use ($t) {
			if (!$ref->state) {
				// Remove cookie when session is terminated
				setcookie($t->cookie_name, null, time() + $t->cookie_ttl, '/', null, !empty($_SERVER['HTTPS']), true);
				if (isset($_SESSION)) {
					// Kill PHP session if in use
					session_regenerate_id(true);
				}
			} else {
				// Update cookie on state change
				setcookie($t->cookie_name, $ref->id, time() + $t->cookie_ttl, '/', null, !empty($_SERVER['HTTPS']), true);
			}
		});

		// Everything else is up to the state machine
	}

def schedule_cycles(minutes,location_id,conditions = {})

			products = Auth.configuration.product_class.constantize.all if conditions.blank?

			products = Auth.configuration.product_class.constantize.where(conditions) if !conditions.blank?

			minutes.keys.each do |epoch|

				products.each do |product|

					all_cycles_valid = true
					product.cycles.each do |cycle|

						all_cycles_valid = cycle.requirements_satisfied(epoch + cycle.time_since_prev_cycle.minutes*60,location_id)

					end

					## just because the cycles are valid, it means we have workers, but how many?
					## that also has to be returned by the cycle validity statements

					if all_cycles_valid == true
						cycle_chain = []
						product.cycles.each do |cycle|
							epoch_at_which_to_add = epoch + cycle.time_since_prev_cycle.minutes*60
							cycle_to_add = cycle.dup
							cycle_to_add.start_time = epoch_at_which_to_add
							cycle_to_add.end_time = cycle_to_add.start_time + cycle_to_add.duration
							cycle_to_add.cycle_chain = cycle_chain
							if minutes[epoch_at_which_to_add]

								add_to_previous_rolling_n_minutes(minutes,epoch_at_which_to_add,cycle_to_add)

								minutes[epoch_at_which_to_add].cycles << cycle_to_add

								cycle_chain << cycle_to_add.id.to_s
							else
								#raise "necessary minute not in range."
							end
						end
					end
				end
			end
			minutes
		end

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


Question:
remove Unrealizable In Array

@param array &$array

@return array

private function removeUnrealizableInArray(array &$array)
    {
        $this->removeReferenceItemInArray($array);
        foreach ($array as &$value) {
            if (is_object($value)) {
                $value = $this->removeUnserializable($value);
            }
            if (is_array($value)) {
                $this->removeUnrealizableInArray($value);
            }
            if ($this->isUnserializable($value)) {
                $value = null;
            }
        }

        return $array;
    }

func safeArrayDestroyDescriptor(safearray *SafeArray) (err error) {
	err = convertHresultToError(procSafeArrayDestroyDescriptor.Call(uintptr(unsafe.Pointer(safearray))))
	return
}

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


Question: // StochRsi - Stochastic Relative Strength Index

func StochRsi(inReal []float64, inTimePeriod int, inFastKPeriod int, inFastDPeriod int, inFastDMAType MaType) ([]float64, []float64) {

	outFastK := make([]float64, len(inReal))
	outFastD := make([]float64, len(inReal))

	lookbackSTOCHF := (inFastKPeriod - 1) + (inFastDPeriod - 1)
	lookbackTotal := inTimePeriod + lookbackSTOCHF
	startIdx := lookbackTotal
	tempRSIBuffer := Rsi(inReal, inTimePeriod)
	tempk, tempd := StochF(tempRSIBuffer, tempRSIBuffer, tempRSIBuffer, inFastKPeriod, inFastDPeriod, inFastDMAType)

	for i := startIdx; i < len(inReal); i++ {
		outFastK[i] = tempk[i]
		outFastD[i] = tempd[i]
	}

	return outFastK, outFastD
}

def rescue(env, identifier):
    """"""

    vsi = SoftLayer.VSManager(env.client)
    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    if not (env.skip_confirmations or
            formatting.confirm("This action will reboot this VSI. Continue?")):
        raise exceptions.CLIAbort('Aborted')

    vsi.rescue(vs_id)

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


Question:
Return a comparison condition against null

@param string $field
@param bool $positive Set to FALSE to perform a IS NOT NULL comparison
@return string

final public function sqlIsNull(string $field, bool $positive = true): string
    {
        if (! $positive) {
            trigger_error(
                __METHOD__ . ' with argument $positive = false is deprecated, use DBAL::sqlIsNotNull',
                E_USER_NOTICE
            );
            return $this->sqlIsNotNull($field);
        }
        return $field . ' IS NULL';
    }

public function check_notify(){
        /*获取xml*/
        $xml=file_get_contents('php://input', 'r');
        /*转成php数组*/
        $data=$this->to_array($xml);
        /*保存原sign*/
        $data_sign=$data['sign'];
        /*sign不参与签名*/
        unset($data['sign']);
        $sign=$this->make_sign($data);

        /*判断签名是否正确  判断支付状态*/
        if ($sign===$data_sign && $data['return_code']=='SUCCESS' && $data['result_code']=='SUCCESS') {
            $result=$data;
        }else{
            $result=false;
        }
        // 返回状态给微信服务器,该动作转由外部控制
        /*if ($result) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;*/
        return $result;
    }

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


Question: // SetCodeDeliveryDetails sets the CodeDeliveryDetails field's value.

func (s *SignUpOutput) SetCodeDeliveryDetails(v *CodeDeliveryDetailsType) *SignUpOutput {
	s.CodeDeliveryDetails = v
	return s
}

def _flatten_lane_details(runinfo):

    out = []
    for ldetail in runinfo["details"]:
        # handle controls
        if "project_name" not in ldetail and ldetail["description"] == "control":
            ldetail["project_name"] = "control"
        for i, barcode in enumerate(ldetail.get("multiplex", [{}])):
            cur = copy.deepcopy(ldetail)
            cur["name"] = "%s-%s" % (ldetail["name"], i + 1)
            cur["description"] = barcode.get("name", ldetail["description"])
            cur["bc_index"] = barcode.get("sequence", "")
            cur["project_name"] = clean_name(ldetail["project_name"])
            out.append(cur)
    return out

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


Question: // SetCurrencyCode sets the CurrencyCode field's value.

func (s *ReservedDBInstance) SetCurrencyCode(v string) *ReservedDBInstance {
	s.CurrencyCode = &v
	return s
}

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

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

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


Question: // UnmarshalJSON implements the json.Unmarshaler interface.

func (tr *TimeRange) UnmarshalJSON(b []byte) error {
	var mixed interface{}
	var err error

	json.Unmarshal(b, &mixed)

	value, _ := mixed.(map[string]interface{})["start"]
	t, _ := time.Parse("2006-01-02", value.(string))
	tr.Start = t

	value, _ = mixed.(map[string]interface{})["end"]
	t, _ = time.Parse("2006-01-02", value.(string))
	tr.End = t

	return err
}

public void setDeserialization(Map<DeserializationFeature, Boolean> deserialization) {
        if (CollectionUtils.isNotEmpty(deserialization)) {
            this.deserialization = deserialization;
        }
    }

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


Question:
Register class in main query

@param $type
@param $actions
@param Generator $generator
@throws \Exception

private function register($type, $actions, Generator $generator)
    {
        $classes = [
            'Query' =>[
                'namespace' => 'GraphQL\\Query',
                'template' => 'Query.tpl.php',
            ],
            'Mutation' =>[
                'namespace' => 'GraphQL\\Mutation',
                'template' => 'Mutation.tpl.php',
            ],
        ];

        $class = $classes[$type];
        $classNameDetails = $generator->createClassNameDetails(
            $type.'Type',
            $class['namespace']
        );

        $classFields = [];
        $fileName = $this->fileManager->getRelativePathForFutureClass($classNameDetails->getFullName());
        $classObjectFullName = $classNameDetails->getFullName();
        if(is_file($fileName)) {
            $classObject = $this->{lcfirst($type).'Type'};
            foreach ($classObject->getFields() as $classField) {
                $classFields[] = [
                    'fullName' => get_class($classField),
                    'shortName' => Str::getShortClassName(get_class($classField))
                ];
            }

            $tmpFileName = $fileName.'.bak';
            rename($fileName, $tmpFileName);
        }

        $generator->generateClass(
            $classNameDetails->getFullName(),
            dirname(dirname(__FILE__)) . '/Resources/skeleton/' . $class['template'],
            [
                'fields' => array_merge($classFields, [$actions])
            ]

        );

        $generator->writeChanges();

        if(is_file($fileName) && isset($tmpFileName)) {
            unlink($tmpFileName);
        }
    }

def get_args():
    """"""
    parser = argparse.ArgumentParser(
        prog=__title__,
        description=__description__,
    )
    parser.add_argument(
        '--testdb', action='store_true',
        help='create and use a database with test users'
    )
    parser.add_argument(
        '-v', '--verbose', action='store_true',
        help='print a detailed log'
    )
    parser.add_argument(
        '--debug', action='store_true',
        help='print debug log'
    )
    parser.add_argument(
        '--log-sql', action='store_true',
        help='log sql transactions'
    )
    parser.add_argument(
        '-V', '--version', action='store_true',
        help='print version info and exit'
    )
    parser.add_argument(
        '--tk', action='store_true',
        help='use old tk interface'
    )
    return parser.parse_args()

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


Question:
Largest Rectangular Area in a Histogram

    :param H: histogram table
    :returns: area, left, height, right, rect. is [0, height] * [left, right)
    :complexity: linear

def rectangles_from_histogram(H):

    best = (float('-inf'), 0, 0, 0)
    S = []
    H2 = H + [float('-inf')]  # extra element to empty the queue
    for right in range(len(H2)):
        x = H2[right]
        left = right
        while len(S) > 0 and S[-1][1] >= x:
            left, height = S.pop()
            # first element is area of candidate
            rect = (height * (right - left), left, height, right)
            if rect > best:
                best = rect
        S.append((left, x))
    return best

private function key_list()
    {
        $this->enigma->load_engine();

        $pagesize = $this->rc->config->get('pagesize', 100);
        $page     = max(intval(rcube_utils::get_input_value('_p', rcube_utils::INPUT_GPC)), 1);
        $search   = rcube_utils::get_input_value('_q', rcube_utils::INPUT_GPC);

        // Get the list
        $list = $this->enigma->engine->list_keys($search);

        if ($list && ($list instanceof enigma_error))
            $this->rc->output->show_message('enigma.keylisterror', 'error');
        else if (empty($list))
            $this->rc->output->show_message('enigma.nokeysfound', 'notice');
        else if (is_array($list)) {
            // Save the size
            $listsize = count($list);

            // Sort the list by key (user) name
            usort($list, array('enigma_key', 'cmp'));

            // Slice current page
            $list = array_slice($list, ($page - 1) * $pagesize, $pagesize);
            $size = count($list);

            // Add rows
            foreach ($list as $key) {
                $this->rc->output->command('enigma_add_list_row', array(
                        'name'  => rcube::Q($key->name),
                        'id'    => $key->id,
                        'flags' => $key->is_private() ? 'p' : ''
                ));
            }
        }

        $this->rc->output->set_env('rowcount', $size);
        $this->rc->output->set_env('search_request', $search);
        $this->rc->output->set_env('pagecount', ceil($listsize/$pagesize));
        $this->rc->output->set_env('current_page', $page);
        $this->rc->output->command('set_rowcount',
            $this->get_rowcount_text($listsize, $size, $page));

        $this->rc->output->send();
    }

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


Question:
SelectValues
@param string $xpath
@param IXmlNamespaceResolver $resolver
@param IDictionary<XmlQualifiedName, object> $vars
@return IEnumerable<Object>

public static function SelectValuesWithParamAndResolver( $xpath, $resolver, $vars )
	{
		/**
		 * @var XPath2NodeIterator $iter
		 */
		$iter = XPath2NodeIterator::Create( Compile( $xpath, $resolver )->EvaluateWithVars( null, $vars ) );
		while ( $iter->MoveNext() )
		{
			yield $iter->getCurrent()->GetTypedValue();
		}
	}

def process_children(self, node, path, level, parent=None):

        data_parent = parent if parent else node
        chs = node.i_children
        for ch in chs:
            if ch.keyword in ["choice", "case"]:
                self.process_children(ch, path, level, node)
                continue
            p = path + "/" + self.qname(ch)
            tmpl = self.xsl_template(p)
            ct = self.xsl_calltemplate(ch.keyword, tmpl)
            self.xsl_withparam("level", "%d" % level, ct)
            if (data_parent.i_module is None or
                ch.i_module.i_modulename != data_parent.i_module.i_modulename):
                self.xsl_withparam("nsid", ch.i_module.i_modulename + ":", ct)
            if ch.keyword in ["leaf", "leaf-list"]:
                self.type_param(ch, ct)
            elif ch.keyword != "anyxml":
                offset = 2 if ch.keyword == "list" else 1
                self.process_children(ch, p, level + offset)

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


Question:
Get a resource from the trimesh/resources folder.

    Parameters
    -------------
    name: str, location relative to trimesh/resources

    Returns
    -------------
    resource: str, string of file data

def get_resource(name):

    # get the resource
    resource = resource_string('trimesh',
                               os.path.join('resources', name))
    # make sure we return it as a string
    if hasattr(resource, 'decode'):
        return resource.decode('utf-8')
    return resource

def _render_filenames(filenames, zip_file, saltenv, template):
    '''

    '''
    if not template:
        return (filenames, zip_file)

    # render the path as a template using path_template_engine as the engine
    if template not in salt.utils.templates.TEMPLATE_REGISTRY:
        raise CommandExecutionError(
            'Attempted to render file paths with unavailable engine '
            '{0}'.format(template)
        )

    kwargs = {}
    kwargs['salt'] = __salt__
    kwargs['pillar'] = __pillar__
    kwargs['grains'] = __grains__
    kwargs['opts'] = __opts__
    kwargs['saltenv'] = saltenv

    def _render(contents):
        '''
        Render :param:`contents` into a literal pathname by writing it to a
        temp file, rendering that file, and returning the result.
        '''
        # write out path to temp file
        tmp_path_fn = salt.utils.files.mkstemp()
        with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_:
            fp_.write(salt.utils.stringutils.to_str(contents))
        data = salt.utils.templates.TEMPLATE_REGISTRY[template](
            tmp_path_fn,
            to_str=True,
            **kwargs
        )
        salt.utils.files.safe_rm(tmp_path_fn)
        if not data['result']:
            # Failed to render the template
            raise CommandExecutionError(
                'Failed to render file path with error: {0}'.format(
                    data['data']
                )
            )
        else:
            return data['data']

    filenames = _render(filenames)
    zip_file = _render(zip_file)
    return (filenames, zip_file)

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


Question: Register the pivot generator

protected function registerPivot()
    {
        $this->app['generate.pivot'] = $this->app->share(function($app)
        {
            return new PivotGeneratorCommand;
        });

        $this->commands('generate.pivot');
    }

public function getRanMigrations()
    {
        $query = $this->resolveConnection($this->connection)->table($this->table);

        return $query->orderBy('batch', 'desc')->orderBy('migration', 'desc')->get();
    }

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


Question:
Get instance.

@param string $className

@return Notification

@throws \RuntimeException

public static function getInstance($className = '')
    {
        if ($className !== '') {
            try {
                $ref = new \ReflectionClass($className);
                if ($ref->isSubclassOf('\MehrAlsNix\Notifier\Notification')) {
                    self::$instance = $ref->newInstance();
                }
            } catch (\ReflectionException $re) {
                throw new \RuntimeException($re->getMessage());
            }
        } elseif (!self::$instance instanceof Notification) {
            self::$instance = self::fetch();
        }

        return self::$instance;
    }

public static function run(App $app, ?Config $config = null): void
    {
        \ini_set('display_errors', '0');
        \ini_set('html_errors', '0');

        $k1 = new static($config);
        $k1->runApp($app);
    }

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


Question: // SetNextPageToken sets the NextPageToken field's value.

func (s *GetReservationPurchaseRecommendationInput) SetNextPageToken(v string) *GetReservationPurchaseRecommendationInput {
	s.NextPageToken = &v
	return s
}

def _get_token_from_query_string(self, request, refresh_token):

        if refresh_token:
            query_string_token_name_key = "query_string_refresh_token_name"
        else:
            query_string_token_name_key = "query_string_access_token_name"
        query_string_token_name = getattr(
            self.config, query_string_token_name_key
        )
        return request.args.get(query_string_token_name(), None)

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


Question:
Small wrapper around `unserialize` so we can pass in `$allowedClasses`
if the PHP verison 7+

@param string $str the string to unserialize
@return object|false

private function doUnserialize($str)
    {
        $m = $this->allowedClasses ? @unserialize($str, [
            'allowed_classes' => $this->allowedClasses,
        ]) : @unserialize($str);

        if (false === $m) {
            $err = error_get_last();
            throw new SerializationError(sprintf(
                'Error unserializing message: %s',
                $err && isset($err['message']) ? $err['message'] : 'unknown error'
            ));
        }

        return $m;
    }

public function encode(array $data)
    {
        $data = $this->escapeFloatsIfNeeded($data);

        $json = json_encode($data, $this->jsonEncodeOptions);
        if ($json === false || json_last_error() != JSON_ERROR_NONE) {
            if (json_last_error() != JSON_ERROR_UTF8) {
                throw new JsonSerializerException('Invalid data to encode to JSON. Error: ' . json_last_error_msg());
            }

            $data = $this->encodeNonUtf8ToUtf8($data);
            $json = json_encode($data, $this->jsonEncodeOptions);

            if ($json === false || json_last_error() != JSON_ERROR_NONE) {
                throw new JsonSerializerException('Invalid data to encode to JSON. Error: ' . json_last_error_msg());
            }
        }

        return $this->unescapeFloatsIfNeeded($json);
    }

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


Question:
@param int    $num
@param int    $power
@param string $powsuffix

@return string

protected function toWords($num, $power = 0, $powsuffix = '')
    {
        $ret = '';

        // add a minus sign
        if (substr($num, 0, 1) == '-') {
            $ret = $this->wordSeparator . $this->minus;
            $num = substr($num, 1);
        }

        // strip excessive zero signs and spaces
        $num = trim($num);
        $num = preg_replace('/^0+/', '', $num);

        if (strlen($num) > 3) {
            $maxp = strlen($num) - 1;
            $curp = $maxp;
            for ($p = $maxp; $p > 0; --$p) { // power

                // check for highest power
                if (isset(self::$exponent[$p])) {
                    // send substr from $curp to $p
                    $snum = substr($num, $maxp - $curp, $curp - $p + 1);
                    $snum = preg_replace('/^0+/', '', $snum);
                    if ($snum !== '') {
                        $cursuffix = self::$exponent[$power][count(self::$exponent[$power]) - 1];
                        if ($powsuffix != '') {
                            $cursuffix .= $this->wordSeparator . $powsuffix;
                        }

                        $ret .= $this->toWords($snum, $p, $cursuffix);
                    }
                    $curp = $p - 1;
                    continue;
                }
            }
            $num = substr($num, $maxp - $curp, $curp - $p + 1);
            if ($num == 0) {
                return $ret;
            }
        } elseif ($num == 0 || $num == '') {
            return $this->wordSeparator . self::$digits[0];
        }

        $h = $t = $d = 0;

        switch (strlen($num)) {
            case 3:
                $h = (int) substr($num, -3, 1);

            case 2:
                $t = (int) substr($num, -2, 1);

            case 1:
                $d = (int) substr($num, -1, 1);
                break;

            case 0:
                return;
                break;
        }

        if ($h) {
            $ret .= $this->wordSeparator . self::$digits[$h] . $this->wordSeparator . 'honderd';
        }

        // add digits only in <0>,<1,9> and <21,inf>
        if ($t != 1 && $d > 0) {
            if ($t > 0) {
                $ret .= self::$digits[$d] . 'en';
            } else {
                $ret .= self::$digits[$d];
                if ($d == 1) {
                    if ($power == 0) {
                        $ret .= 's'; // fuer eins
                    } else {
                        if ($power != 3) {  // tausend ausnehmen
                            $ret .= ''; // fuer eine
                        }
                    }
                }
            }
        }

        // ten, twenty etc.
        switch ($t) {
            case 9:
            case 8:
            case 7:
            case 6:
            case 5:
                $ret .= $this->wordSeparator . self::$digits[$t] . 'tig';
                break;

            case 4:
                $ret .= $this->wordSeparator . 'veertig';
                break;

            case 3:
                $ret .= $this->wordSeparator . 'dertig';
                break;

            case 2:
                $ret .= $this->wordSeparator . 'twintig';
                break;

            case 1:
                switch ($d) {
                    case 0:
                        $ret .= $this->wordSeparator . 'tien';
                        break;

                    case 1:
                        $ret .= $this->wordSeparator . 'elf';
                        break;

                    case 2:
                        $ret .= $this->wordSeparator . 'twaalf';
                        break;

                    case 3:
                        $ret .= $this->wordSeparator . 'dertien';
                        break;

                    case 4:
                        $ret .= $this->wordSeparator . 'veertien';
                        break;

                    case 5:
                    case 6:
                    case 7:
                    case 8:
                    case 9:
                        $ret .= $this->wordSeparator . self::$digits[$d] . 'tien';
                        break;
                }
                break;
        }

        if ($power > 0) {
            if (isset(self::$exponent[$power])) {
                $lev = self::$exponent[$power];
            }

            if (!isset($lev) || !is_array($lev)) {
                return null;
            }

            if ($power == 3) {
                $ret .= $this->wordSeparator . $lev[0];
            } elseif ($d == 1 && ($t + $h) == 0) {
                $ret .= self::$exponentWordSeparator . $lev[0] . self::$exponentWordSeparator;
            } else {
                $ret .= self::$exponentWordSeparator . $lev[1] . self::$exponentWordSeparator;
            }
        }

        if ($powsuffix != '') {
            $ret .= $this->wordSeparator . $powsuffix;
        }

        return $ret;
    }

public function set_defaults() {
		// General attributes.
		$this->set_tags_to_ignore();
		$this->set_classes_to_ignore();
		$this->set_ids_to_ignore();

		// Smart characters.
		$this->set_smart_quotes();
		$this->set_smart_quotes_primary();
		$this->set_smart_quotes_secondary();
		$this->set_smart_quotes_exceptions();
		$this->set_smart_dashes();
		$this->set_smart_dashes_style();
		$this->set_smart_ellipses();
		$this->set_smart_diacritics();
		$this->set_diacritic_language();
		$this->set_diacritic_custom_replacements();
		$this->set_smart_marks();
		$this->set_smart_ordinal_suffix();
		$this->set_smart_ordinal_suffix_match_roman_numerals();
		$this->set_smart_math();
		$this->set_smart_fractions();
		$this->set_smart_exponents();

		// Smart spacing.
		$this->set_single_character_word_spacing();
		$this->set_fraction_spacing();
		$this->set_unit_spacing();
		$this->set_french_punctuation_spacing();
		$this->set_units();
		$this->set_dash_spacing();
		$this->set_dewidow();
		$this->set_max_dewidow_length();
		$this->set_max_dewidow_pull();
		$this->set_dewidow_word_number();
		$this->set_wrap_hard_hyphens();
		$this->set_url_wrap();
		$this->set_email_wrap();
		$this->set_min_after_url_wrap();
		$this->set_space_collapse();
		$this->set_true_no_break_narrow_space();

		// Character styling.
		$this->set_style_ampersands();
		$this->set_style_caps();
		$this->set_style_initial_quotes();
		$this->set_style_numbers();
		$this->set_style_hanging_punctuation();
		$this->set_initial_quote_tags();

		// Hyphenation.
		$this->set_hyphenation();
		$this->set_hyphenation_language();
		$this->set_min_length_hyphenation();
		$this->set_min_before_hyphenation();
		$this->set_min_after_hyphenation();
		$this->set_hyphenate_headings();
		$this->set_hyphenate_all_caps();
		$this->set_hyphenate_title_case();
		$this->set_hyphenate_compounds();
		$this->set_hyphenation_exceptions();

		// Parser error handling.
		$this->set_ignore_parser_errors();
	}

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


Question: Returns the combined filter of the wrapped executors.

public Filter<S> getFilter() {
        Filter<S> filter = null;
        for (QueryExecutor<S> executor : mExecutors) {
            Filter<S> subFilter = executor.getFilter();
            filter = filter == null ? subFilter : filter.or(subFilter);
        }
        return filter;
    }

function noWrapper() {
      var noWrapper = this.slim && !this.transition;

      if (noWrapper && this.children().length > 1) {
        console.warn('[portal-vue]: PortalTarget with `slim` option received more than one child element.');
      }

      return noWrapper;
    }

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


Question:
// Fetch downloads the provided content into containerd's content store
// and returns a non-platform specific image reference

func (c *Client) Fetch(ctx context.Context, ref string, opts ...RemoteOpt) (images.Image, error) {
	fetchCtx := defaultRemoteContext()
	for _, o := range opts {
		if err := o(c, fetchCtx); err != nil {
			return images.Image{}, err
		}
	}

	if fetchCtx.Unpack {
		return images.Image{}, errors.New("unpack on fetch not supported, try pull")
	}

	if fetchCtx.PlatformMatcher == nil {
		if len(fetchCtx.Platforms) == 0 {
			fetchCtx.PlatformMatcher = platforms.All
		} else {
			var ps []ocispec.Platform
			for _, s := range fetchCtx.Platforms {
				p, err := platforms.Parse(s)
				if err != nil {
					return images.Image{}, errors.Wrapf(err, "invalid platform %s", s)
				}
				ps = append(ps, p)
			}

			fetchCtx.PlatformMatcher = platforms.Any(ps...)
		}
	}

	ctx, done, err := c.WithLease(ctx)
	if err != nil {
		return images.Image{}, err
	}
	defer done(ctx)

	return c.fetch(ctx, fetchCtx, ref, 0)
}

func (c *Conn) AlbumInfo(album *Album) (*AlbumInfo, error) {
	var out struct {
		Album *AlbumInfo
	}
	if err := c.do("smugmug.albums.getInfo", &out,
		"AlbumID", itoa64(album.ID),
		"AlbumKey", album.Key,
	); err != nil {
		return nil, err
	}

	if out.Album == nil || out.Album.ID == 0 {
		return nil, fmt.Errorf("unable to parse SmugMug result")
	}
	return out.Album, nil
}

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


Question:
@param string|integer $key
@param integer $length

@return boolean

static public function validateNumber($key, $length = 4)
    {
        if (!is_numeric($key)) {
            return false;
        }

        if (strlen($key) < $length) {
            return false;
        }

        return true;
    }

public Object getDefaultValue(Parameter parameter) {
    Class<?> type = parameter.getType();

    if (TypeUtils.isaString(type)) {
      return getStringDefaultValue(parameter);
    }

    if (TypeUtils.isaByte(type)) {
      return getByteDefaultValue(parameter);
    }

    if (TypeUtils.isaShort(type)) {
      return getShortDefaultValue(parameter);
    }

    if (TypeUtils.isaInteger(type)) {
      return getIntegerDefaultValue(parameter);
    }

    if (TypeUtils.isaLong(type)) {
      return getLongDefaultValue(parameter);
    }

    if (TypeUtils.isaFloat(type)) {
      return getFloatDefaultValue(parameter);
    }

    if (TypeUtils.isaDouble(type)) {
      return getDoubleDefaultValue(parameter);
    }

    if (TypeUtils.isaCharacter(type)) {
      return getCharacterDefaultValue(parameter);
    }

    if (TypeUtils.isaBoolean(type)) {
      return getBooleanDefaultValue(parameter);
    }

    return null;
  }

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


Question: Clear identities relationships and enrollments data

def __reset_unique_identities(self):
        """"""

        self.log("Reseting unique identities...")

        self.log("Clearing identities relationships")

        nids = 0
        uidentities = api.unique_identities(self.db)

        for uidentity in uidentities:
            for identity in uidentity.identities:
                api.move_identity(self.db, identity.id, identity.id)
                nids += 1

        self.log("Relationships cleared for %s identities" % nids)

        self.log("Clearing enrollments")

        with self.db.connect() as session:
            enrollments = session.query(Enrollment).all()

            for enr in enrollments:
                session.delete(enr)

        self.log("Enrollments cleared")

public static function delete_data_for_users(approved_userlist $userlist) {
        $context = $userlist->get_context();

        if ($context instanceof \context_user) {
            static::delete_data($context->instanceid);
        }
    }

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


Question:
endregion
@param {String} pattern

@class _GpfLikeContext
@constructor

function _GpfPathMatcher (pattern) {
    /*jshint validthis:true*/
/*#ifdef(DEBUG)*/
    this._dbgSource = pattern;
/*#endif*/

    if ("!" === pattern.charAt(0)) {
        this.negative = true;
        pattern = pattern.substr(1);
    }

    _gpfCheckPathMatcherGeneric(this, pattern);
}

public void resolveToStringStyle(File file, int lineIndex) {
        if (toStringStyle.equals("smart")) {
            toStringStyle = (bean.isImmutable() ? "field" : "getter");
        }
        if (toStringStyle.equals("omit") ||
                toStringStyle.equals("getter") ||
                toStringStyle.equals("field")) {
            return;
        }
        throw new BeanCodeGenException("Invalid toString style: " + toStringStyle +
                " in " + getBean().getTypeRaw() + "." + getPropertyName(), file, lineIndex);
    }

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


Question:
Applies the defaults described by the this schema to the given
        document instance as appropriate. Defaults are only applied to
        fields which are currently unset.

def apply_defaults(self, instance):
        """"""
        for field, spec in self.doc_spec.iteritems():
            field_type = spec['type']
            if field not in instance:
                if 'default' in spec:
                    default = spec['default']
                    if callable(default):
                        instance[field] = default()
                    else:
                        instance[field] = copy.deepcopy(default)
            # Determine if a value already exists for the field
            if field in instance:
                value = instance[field]

                # recurse into nested docs
                if isinstance(field_type, Schema) and isinstance(value, dict):
                    field_type.apply_defaults(value)

                elif isinstance(field_type, Array) and isinstance(field_type.contained_type, Schema) and isinstance(value, list):
                    for item in value:
                        field_type.contained_type.apply_defaults(item)

def _add_namespace(marc_xml):

    dom = marc_xml

    if isinstance(dom, basestring):
        dom = dhtmlparser.parseString(marc_xml)

    root = dom.find("root")
    if root:
        root[0].params = {}

    for record in dom.find("record"):
        record.params = {}

    collections = dom.find("collection")
    if not collections:
        record = dom.find("record")[0]
        return XML_TEMPLATE.replace("$CONTENT", str(record))

    for col in collections:
        col.params["xmlns"] = "http://www.loc.gov/MARC21/slim"
        col.params["xmlns:xsi"] = "http://www.w3.org/2001/XMLSchema-instance"
        col.params["xsi:schemaLocation"] = "http://www.loc.gov/MARC21/slim " + \
                   "http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"

    return str(dom)

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


Question:
// applyString takes 'src' and overwrites target with it, unless 'src' is empty
// returns 'True' if 'src' was not empty

func applyString(src string, target *string) bool {
	if src != "" {
		*target = src
		return true
	}
	return false
}

function(expr, ext){
    var rawget, ext = this.__ext__, touched = {};
    if(expr.type !== 'expression' || expr.touched) return expr;

    rawget = expr.get;
    if(!rawget){
      rawget = expr.get = new Function(_.ctxName, _.extName , _.prefix+ "return (" + expr.body + ")");
      expr.body = null;
    }
    touched.get = !ext? rawget: function(context, e){
      return rawget( context, e || ext )
    }

    if(expr.setbody && !expr.set){
      var setbody = expr.setbody;
      var filters = expr.filters;
      var self = this;
      if(!filters || !_.some(filters, function(filter){ return !self._f_(filter).set }) ){
        expr.set = function(ctx, value, ext){
          expr.set = new Function(_.ctxName, _.setName , _.extName, _.prefix + setbody);
          return expr.set(ctx, value, ext);
        }
      }
      expr.filters = expr.setbody = null;
    }
    if(expr.set){
      touched.set = !ext? expr.set : function(ctx, value){
        return expr.set(ctx, value, ext);
      }
    }

    touched.type = 'expression';
    touched.touched = true;
    touched.once = expr.once || expr.constant;
    return touched
  }

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


Question:
Called by the underlying transport when a connection is made.

        :param transport: The transport representing the connection.

def connection_made(self, transport):

        # Save the underlying transport
        self._transport = transport

        # Call connection_made() on the client protocol, passing
        # ourself as the transport
        self._client.connection_made(self)

def _update_service_profile(self, handle, service_profile,
                                vlan_id, ucsm_ip):

        virtio_port_list = (
            CONF.ml2_cisco_ucsm.ucsms[ucsm_ip].ucsm_virtio_eth_ports)

        eth_port_paths = ["%s%s" % (service_profile, ep)
            for ep in virtio_port_list]

        vlan_name = self.make_vlan_name(vlan_id)

        try:
            obj = handle.query_dn(service_profile)

            if not obj:
                LOG.debug('UCS Manager network driver could not find '
                          'Service Profile %s in UCSM %s',
                          service_profile, ucsm_ip)
                return False

            for eth_port_path in eth_port_paths:
                eth = handle.query_dn(eth_port_path)

                if eth:
                    eth_if = self.ucsmsdk.vnicEtherIf(
                        parent_mo_or_dn=eth,
                        name=vlan_name,
                        default_net="no")

                    handle.add_mo(eth_if)

                    if not eth_if:
                        LOG.debug('UCS Manager network driver could not '
                                  'update Service Profile %s with vlan %d',
                                  service_profile, vlan_id)
                        return False
                else:
                    LOG.debug('UCS Manager network driver did not find '
                              'ethernet port at %s', eth_port_path)

            handle.commit()
            return True

        except Exception as e:
            return self._handle_ucsm_exception(e, 'Service Profile',
                                               vlan_name, ucsm_ip)

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


Question:
Updates a model.

@param {Bookshelf.Model} model - A bookshelf model instance
@param {Object} params - An object containing the params from the request.
@returns {Promise.Bookshelf.Model|null} -
The updated model or null if nothing has changed.

function update(model) {
  var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

  if (!model) {
    throw new Error('No model provided.');
  }
  var currentState = model.toJSON({ shallow: true });
  currentState.id = String(currentState.id);

  return _destructure2['default'](model, params).then(function (destructured) {
    var attributes = destructured.attributes;
    var relations = destructured.relations;

    return _transact2['default'](model, function (transaction) {
      return model.save(attributes, {
        patch: true,
        method: 'update',
        transacting: transaction
      }).tap(function (model) {
        return _relate2['default'](model, relations, 'update', transaction);
      }).then(function (model) {
        // if model didn't change, return null
        // model.previousAttributes() is broken.
        // https://github.com/tgriesser/bookshelf/issues/326
        var updatedState = model.toJSON({ shallow: true });
        updatedState.id = String(updatedState.id);
        return _lodash2['default'].isEqual(currentState, updatedState) ? null : model;
      });
    });
  });
}

public static QuerySnapshot withChanges(
      final Query query,
      Timestamp readTime,
      final DocumentSet documentSet,
      final List<DocumentChange> documentChanges) {
    return new QuerySnapshot(query, readTime) {
      volatile List<QueryDocumentSnapshot> documents;

      @Nonnull
      @Override
      public List<QueryDocumentSnapshot> getDocuments() {
        if (documents == null) {
          synchronized (documentSet) {
            if (documents == null) {
              documents = documentSet.toList();
            }
          }
        }
        return Collections.unmodifiableList(documents);
      }

      @Nonnull
      @Override
      public List<DocumentChange> getDocumentChanges() {
        return Collections.unmodifiableList(documentChanges);
      }

      @Override
      public int size() {
        return documentSet.size();
      }

      @Override
      public boolean equals(Object o) {
        if (this == o) {
          return true;
        }
        if (o == null || getClass() != o.getClass()) {
          return false;
        }
        QuerySnapshot that = (QuerySnapshot) o;
        return Objects.equals(query, that.query)
            && Objects.equals(this.size(), that.size())
            && Objects.equals(this.getDocumentChanges(), that.getDocumentChanges())
            && Objects.equals(this.getDocuments(), that.getDocuments());
      }

      @Override
      public int hashCode() {
        return Objects.hash(query, this.getDocumentChanges(), this.getDocuments());
      }
    };
  }

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


Question: Iterate over keyboard shortcuts.

def iter_shortcuts():
    """"""
    for context_name, keystr in CONF.items('shortcuts'):
        context, name = context_name.split("/", 1)
        yield context, name, keystr

func (collection *Collection) SearchItems(profile string) ([]Item, error) {
  attributes := make(map[string]string)
  attributes["profile"] = profile

  var paths []dbus.ObjectPath

  err := collection.dbus.Call("org.freedesktop.Secret.Collection.SearchItems", 0, attributes).Store(&paths)
  if err != nil {
    return []Item{}, err
  }

  items := []Item{}
  for _, path := range paths {
    items = append(items, *NewItem(collection.conn, path))
  }

  return items, nil
}

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


Question:
Create an array of elements from the schema document
@param bool $forceNodeProcessing Set to make sure element types are processed.  Typically this will only be set
true after *including* another schema because the namespace is the same.
@return void

private function indexElements( $forceNodeProcessing )
	{
		$types = $this->context->types;
		$isTaxonomySchema = $this->xbrlDocument->getName() == 'schema' && ! isset( XBRL_Constants::$standardPrefixes[ $this->getPrefix() ] );

		if ( $forceNodeProcessing || ! $types->hasProcessedSchema( $this->prefix ) || ! $types->getPrefixForNamespace( $this->getNamespace() ) )
		{
			$types->processNode( $this->xbrlDocument, $this->xbrlDocument->getName(), $this->getPrefix(), true );
		}

		foreach ( $this->xbrlDocument->children( XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_SCHEMA ] ) as $nodeKey => $node )
		{
			if ( $nodeKey == 'redefine' )
			{
				if ( XBRL::isValidating() )
				$this->log()->taxonomy_validation( "5.1.5", "The 'redefine' tag is prohibited in XBRL schema taxonomies", array() );
				continue;
			}

			if ( $nodeKey == 'element' )
			{
				$attributes = $node->attributes();

				$id = (string) $attributes['id'];
				$name = (string) $attributes['name'];

				if ( empty( $id ) )
				{
					$id = $name;
				}
				else if ( empty( $name ) )
				{
					$name = $id;
				}

				$element = array(
					'id' => $id,
					'name' => $name,
					'type' => (string) $attributes['type'],
					'substitutionGroup' => $this->normalizePrefix( (string) $attributes['substitutionGroup'], $this ),
					'abstract' => (string) $attributes['abstract'] === 'true' ? 1 : 0,
					'nillable' => (string) $attributes['nillable'] === 'true' ? 1 : 0,
				);

				$this->indexXDT( $types, $node, $element );
				$this->indexCustom( $types, $node, $element );

				if ( $isTaxonomySchema )
				{
					$element['node'] = $node; // Keep this temporarily
					// $element['nodeKey'] = $nodeKey; // Keep this temporarily
				}

				$xbrliAttributes = $node->attributes( XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_XBRLI ] );

				if ( property_exists( $xbrliAttributes, 'periodType' ) )
				{
					$element['periodType'] = (string) $xbrliAttributes['periodType'];
				}

				if ( property_exists( $xbrliAttributes, 'balance' ) )
				{
					$element['balance'] = (string) $xbrliAttributes['balance'];
				}

				$this->elementIndex[ $id ] = $element;

			}
		}

		$taxonomy_namespace = $this->getNamespace();
		// Its possible that when multiple versions of a taxonomy are loaded that the
		// same prefix will appear.  Assume the first loaded is the correct one to use.
		if ( ! $types->hasProcessedSchema( $this->prefix ) )
		{
			$types->setProcessedSchema( $this->prefix, $taxonomy_namespace );
		}
	}

protected function _processMethods($parent)
    {
        foreach ($parent->tree as $child) {
            if (!$child->processable) {
                continue;
            }
            $process = (
                $child->type === 'function' &&
                $child->isMethod &&
                !isset($child->visibility['abstract'])
            );
            if ($process) {
                $code = $this->_classes['node'];
                $before = new $code($this->_before($child->isGenerator, $child->isVoid), 'code');
                $before->parent = $child;
                $before->function = $child;
                $before->processable = false;
                $before->namespace = $child->namespace;
                array_unshift($child->tree, $before);
            }
        }
    }

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


Question: // Cos computes the cosine of a signal.

func (as ArraySpec) Cos() Input {
	return as.proc(func(i Input) Input {
		return i.Cos()
	})
}

func (o HostNetworkSystem) QueryNetworkHint(ctx context.Context, device []string) error {
	req := types.QueryNetworkHint{
		This:   o.Reference(),
		Device: device,
	}

	_, err := methods.QueryNetworkHint(ctx, o.c, &req)
	if err != nil {
		return err
	}

	return nil
}

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


Question: Step 3. App query billing statistics grouped by servers within DE1 Datacenter

@Test(groups = {SAMPLES})
    public void getDE1BillingStatsGroupedByServers() {
        List<BillingStatsEntry> stats = statisticsService
            .billingStats()
            .forDataCenters(
                new DataCenterFilter()
                    .dataCenters(DE_FRANKFURT)
            )
            .groupByServer();

        assertNotNull(stats);
    }

def cli(env):
    """"""

    mgr = SoftLayer.LoadBalancerManager(env.client)

    table = formatting.Table(['price_id', 'capacity', 'description', 'price'])

    table.sortby = 'price'
    table.align['price'] = 'r'
    table.align['capacity'] = 'r'
    table.align['id'] = 'r'

    packages = mgr.get_lb_pkgs()

    for package in packages:
        table.add_row([
            package['prices'][0]['id'],
            package.get('capacity'),
            package['description'],
            '%.2f' % float(package['prices'][0]['recurringFee'])
        ])

    env.fout(table)

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


Question:
Register the service provider.

@return void

public function register()
	{
		$this->app->singleton('driver', function()
		{
			$db = $this->app['db']->connection()->getPdo();

			return new EloquentDriver($db, $this->app['Str']);
		});

		$this->app->bind('fixture', function()
		{
		    $fixture = Fixture::getInstance();
		    $fixture->setDriver($this->app['driver']);
		    $fixture->setConfig($this->app['config']->get('fixture-l4::config'));

		    return $fixture;
		});
	}

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

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


Question: url:        null, type:       'GET',

function( mockHandler, requestSettings ) {
			if ( mockHandler.logging === false ||
				 ( typeof mockHandler.logging === 'undefined' && $.mockjaxSettings.logging === false ) ) {
				return;
			}
			if ( window.console && console.log ) {
				var message = 'MOCK ' + requestSettings.type.toUpperCase() + ': ' + requestSettings.url;
				var request = $.extend({}, requestSettings);

				if (typeof console.log === 'function') {
					console.log(message, request);
				} else {
					try {
						console.log( message + ' ' + JSON.stringify(request) );
					} catch (e) {
						console.log(message);
					}
				}
			}
		}

public Javalin put(@NotNull String path, @NotNull Handler handler, @NotNull Set<Role> permittedRoles) {
        return addHandler(HandlerType.PUT, path, handler, permittedRoles);
    }

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


Question: // SetTags sets the Tags field's value.

func (s *PutRuleInput) SetTags(v []*Tag) *PutRuleInput {
	s.Tags = v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question:
Creates a composite AND predicate from the given predicates.

@param <T> the element type parameter
@param predicates the predicates to be composed
@return the composite predicate

public static <T> Predicate<T> and(Predicate<T>... predicates) {
        dbc.precondition(predicates != null, "predicates is null");
        return Logic.Unary.and(Iterations.iterable(predicates));
    }

private AggregationBuilder addHavingClause(Expression havingExpression, AggregationBuilder aggregationBuilder,
            EntityMetadata entityMetadata)
    {
        if (havingExpression instanceof ComparisonExpression)
        {
            Expression expression = ((ComparisonExpression) havingExpression).getLeftExpression();
            if (!isAggregationExpression(expression))
            {
                logger.error("Having clause conditions over non metric aggregated are not supported.");
                throw new UnsupportedOperationException(
                        "Currently, Having clause without Metric aggregations are not supported.");
            }

            return checkIfKeyExists(expression.toParsedText()) ? aggregationBuilder
                    .subAggregation(getMetricsAggregation(expression, entityMetadata)) : aggregationBuilder;
        }
        else if (havingExpression instanceof AndExpression)
        {
            AndExpression andExpression = (AndExpression) havingExpression;
            addHavingClause(andExpression.getLeftExpression(), aggregationBuilder, entityMetadata);
            addHavingClause(andExpression.getRightExpression(), aggregationBuilder, entityMetadata);

            return aggregationBuilder;
        }
        else if (havingExpression instanceof OrExpression)
        {
            OrExpression orExpression = (OrExpression) havingExpression;
            addHavingClause(orExpression.getLeftExpression(), aggregationBuilder, entityMetadata);
            addHavingClause(orExpression.getRightExpression(), aggregationBuilder, entityMetadata);

            return aggregationBuilder;
        }
        else
        {
            logger.error(havingExpression + "not supported in having clause.");
            throw new UnsupportedOperationException(havingExpression + "not supported in having clause.");
        }
    }

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


Question:
Parse a literal provided as part of a GraphQL query string into a Carbon instance.

@param  \GraphQL\Language\AST\Node  $valueNode
@param  mixed[]|null  $variables
@return \Carbon\Carbon

@throws \GraphQL\Error\Error

public function parseLiteral($valueNode, ?array $variables = null): Carbon
    {
        if (! $valueNode instanceof StringValueNode) {
            throw new Error(
                'Query error: Can only parse strings got: '.$valueNode->kind,
                [$valueNode]
            );
        }

        return $this->tryParsingDateTime($valueNode->value, Error::class);
    }

func (_class HostMetricsClass) GetRecord(sessionID SessionRef, self HostMetricsRef) (_retval HostMetricsRecord, _err error) {
	_method := "host_metrics.get_record"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertHostMetricsRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertHostMetricsRecordToGo(_method + " -> ", _result.Value)
	return
}

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


Question:
/* (non-Javadoc)
@see org.danann.cernunnos.cache.CacheHelper.Factory#isThreadSafe(java.lang.Object, java.lang.Object)

@Override
    public boolean isThreadSafe(Tuple<ScriptEngine, String> key, ScriptEvaluator instance) {
        final ScriptEngineFactory factory = key.first.getFactory();
        final Object threadingAbility = factory.getParameter("THREADING");
        return threadingAbility != null && ("THREAD-ISOLATED".equals(threadingAbility) || "STATELESS".equals(threadingAbility));
    }

public static void executeIn(ClassLoader loader, Runnable task) throws Exception
   {
      if (task == null)
         return;

      if (log.isLoggable(Level.FINE))
      {
         log.fine("ClassLoader [" + loader + "] task began.");
      }
      ClassLoader original = SecurityActions.getContextClassLoader();
      try
      {
         SecurityActions.setContextClassLoader(loader);
         task.run();
      }
      finally
      {
         SecurityActions.setContextClassLoader(original);
         if (log.isLoggable(Level.FINE))
         {
            log.fine("ClassLoader [" + loader + "] task ended.");
         }
      }
   }

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


Question:
// SetSlavePosition sets the replication position at which the slave will resume
// when its replication is started.

func (mysqld *Mysqld) SetSlavePosition(ctx context.Context, pos mysql.Position) error {
	conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
	if err != nil {
		return err
	}
	defer conn.Recycle()

	cmds := conn.SetSlavePositionCommands(pos)
	log.Infof("Executing commands to set slave position: %v", cmds)
	return mysqld.executeSuperQueryListConn(ctx, conn, cmds)
}

def _maybe_connect(self, node_id):
        """"""
        with self._lock:
            conn = self._conns.get(node_id)

            if conn is None:
                broker = self.cluster.broker_metadata(node_id)
                assert broker, 'Broker id %s not in current metadata' % (node_id,)

                log.debug("Initiating connection to node %s at %s:%s",
                          node_id, broker.host, broker.port)
                host, port, afi = get_ip_port_afi(broker.host)
                cb = WeakMethod(self._conn_state_change)
                conn = BrokerConnection(host, broker.port, afi,
                                        state_change_callback=cb,
                                        node_id=node_id,
                                        **self.config)
                self._conns[node_id] = conn

            # Check if existing connection should be recreated because host/port changed
            elif self._should_recycle_connection(conn):
                self._conns.pop(node_id)
                return False

            elif conn.connected():
                return True

            conn.connect()
            return conn.connected()

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


Question:
{@inheritdoc}
@see \Zend\ServiceManager\DelegatorFactoryInterface::createDelegatorWithName()

public function createDelegatorWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName, $callback)
    {
        $config = $callback();

        if ($config instanceof Configuration) {
            $pathManager = $serviceLocator->get('PathManager');
            $dir = $config->getProxyDir();
            $dir = (strpos($dir, 'data/') === 0)? substr($dir, 0, 5) : 'doctrine/proxies';

            $config->setProxyDir($pathManager->get('var', $dir));
        }

        return $config;
    }

public function init()
    {
        $children = array();
        foreach ($this->children as $child_widget) {
            $children[] = $this->remove($child_widget);
        }

        $disclosure = new SwatDisclosure();
        $disclosure->id = $disclosure->getUniqueId();
        $prototype_id = $disclosure->id;

        foreach ($children as $child_widget) {
            $disclosure->add($child_widget);
        }

        $this->add($disclosure);

        parent::init();

        foreach ($this->replicators as $id => $title) {
            $disclosure = $this->getWidget($prototype_id, $id);
            $disclosure->title = $title;
        }
    }

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


Question:
Handle an incoming request.

@param  \Illuminate\Http\Request  $request
@param  \Closure  $next
@return mixed

public function handle($request, Closure $next)
    {
        if ($this->auth->check() && $this->auth->user()->is_admin === 1) {
            return redirect(config('laramanager.home_uri'));
        }

        return $next($request);
    }

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:
Convert a JDOM Element to a DOM Element

@param node

@return

public static org.w3c.dom.Element convert(org.jdom2.Element node) throws JDOMException
	{
		if (node == null)
			return null; // Convert null->null

		try
		{
			DOMOutputter outputter = new DOMOutputter();

			return outputter.output(node);
		}
		catch (JDOMException e)
		{
			throw new RuntimeException("Error converting JDOM to DOM: " + e.getMessage(), e);
		}
	}

public static Document toDocument(String xml) {
		try {

			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
					.newInstance();
			documentBuilderFactory.setNamespaceAware(true);
			documentBuilderFactory.setIgnoringElementContentWhitespace(true);
			documentBuilderFactory.isIgnoringComments();
			documentBuilderFactory.setCoalescing(true);

			DocumentBuilder documentBuilder = documentBuilderFactory
					.newDocumentBuilder();

			InputSource inputSource = new InputSource();

			inputSource.setCharacterStream(new StringReader(xml));

			Document document = documentBuilder.parse(inputSource);

			removeUnusedNamespaces(document);

			return document;

		} catch (ParserConfigurationException e) {
			throw new RuntimeException(e);
		} catch (SAXException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

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


Question:
Change permission.

@param (string) $file file
@param (mixed)  $mode mode

@since 3.0.0

@return bool

public function chmod($file, $mode)
    {
        return ($this->isConnected() === true) ? ftp_chmod($this->getConnection(), $mode, $file) : false;
    }

public static function routes()
    {
        $middleware = [ CreateDefaultFolder::class, MultiUser::class ];
        $as = 'unisharp.lfm.';
        $namespace = '\\UniSharp\\LaravelFilemanager\\Controllers\\';

        Route::group(compact('middleware', 'as', 'namespace'), function () {

            // display main layout
            Route::get('/', [
                'uses' => 'LfmController@show',
                'as' => 'show',
            ]);

            // display integration error messages
            Route::get('/errors', [
                'uses' => 'LfmController@getErrors',
                'as' => 'getErrors',
            ]);

            // upload
            Route::any('/upload', [
                'uses' => 'UploadController@upload',
                'as' => 'upload',
            ]);

            // list images & files
            Route::get('/jsonitems', [
                'uses' => 'ItemsController@getItems',
                'as' => 'getItems',
            ]);

            Route::get('/move', [
                'uses' => 'ItemsController@move',
                'as' => 'move',
            ]);

            Route::get('/domove', [
                'uses' => 'ItemsController@domove',
                'as' => 'domove'
            ]);

            // folders
            Route::get('/newfolder', [
                'uses' => 'FolderController@getAddfolder',
                'as' => 'getAddfolder',
            ]);

            // list folders
            Route::get('/folders', [
                'uses' => 'FolderController@getFolders',
                'as' => 'getFolders',
            ]);

            // crop
            Route::get('/crop', [
                'uses' => 'CropController@getCrop',
                'as' => 'getCrop',
            ]);
            Route::get('/cropimage', [
                'uses' => 'CropController@getCropimage',
                'as' => 'getCropimage',
            ]);
            Route::get('/cropnewimage', [
                'uses' => 'CropController@getNewCropimage',
                'as' => 'getCropimage',
            ]);

            // rename
            Route::get('/rename', [
                'uses' => 'RenameController@getRename',
                'as' => 'getRename',
            ]);

            // scale/resize
            Route::get('/resize', [
                'uses' => 'ResizeController@getResize',
                'as' => 'getResize',
            ]);
            Route::get('/doresize', [
                'uses' => 'ResizeController@performResize',
                'as' => 'performResize',
            ]);

            // download
            Route::get('/download', [
                'uses' => 'DownloadController@getDownload',
                'as' => 'getDownload',
            ]);

            // delete
            Route::get('/delete', [
                'uses' => 'DeleteController@getDelete',
                'as' => 'getDelete',
            ]);

            Route::get('/demo', 'DemoController@index');
        });
    }

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


Question:
Retourne le nom de la règle à partir de sa composition complète.

@param string $rule Règle compléte.

@return string Nom de la règle.

protected function getRuleName($rule)
    {
        /* Retire le caractère de négation de la fonction. */
        $function = $rule[ 0 ] == '!'
            ? substr($rule, 1)
            : $rule;

        /* Sépare le nom de la fonction si elle a des arguments. */
        if (($name = strstr($function, ':', true)) !== false) {
            return strtolower($name);
        }

        return strtolower($function);
    }

public function get($name, $isHtml = false)
    {
        $name = self::normalizeName($name);

        if (strpos($name, '[') !== false) {
            $names = explode('[', str_replace(']', '', $name));
            $key = array_shift($names);
            $item = isset($this->parameters[$key]) ? $this->parameters[$key] : [];

            foreach ($names as $key) {
                if (!isset($item[$key])) {
                    return;
                }

                $item = $item[$key];
            }

            return $isHtml ? $item : self::toPlainValue($item);
        }

        if (isset($this->parameters[$name])) {
            return $isHtml ? $this->parameters[$name] : self::toPlainValue($this->parameters[$name]);
        }
    }

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


Question: Write project to directory

def write(self):

        # write data
        self.project_manager.writeInput(session=self.db_session,
                                        directory=self.project_directory,
                                        name=self.project_manager.name)

func (j *mdIDJournal) move(newDir string) (oldDir string, err error) {
	return j.j.move(newDir)
}

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


Question:
Get folder details for a file id.
        :param file_id: str: uuid of the file
        :return: File

def get_file_by_id(self, file_id):

        return self._create_item_response(
            self.data_service.get_file(file_id),
            File
        )

private function normalizeFileUri(array $uriSegments): string
    {
        $path  = $uriSegments['path'];
        $auth  = !$uriSegments['user'] ? '' : "{$uriSegments['user']}:{$uriSegments['pass']}@";
        $query = !$uriSegments['query'] ? '' : "?{$uriSegments['query']}";
        $port  = !$uriSegments['port'] ? '' : ":{$uriSegments['port']}";
        $host  = !$uriSegments['host'] ? '' : "{$uriSegments['scheme']}://$auth{$uriSegments['host']}{$port}";

        if (substr($path, 0, 1) !== '/') {
            $path = "$this->directory/$path";
        }

        return "{$host}{$path}{$query}";
    }

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


Question: Prepare template data variables before output

protected function prepareDataOutput()
    {
        $this->data['_css'] = $this->getCss();

        foreach (array('top', 'bottom') as $position) {
            $this->data["_js_$position"] = $this->getJs($position);
            $this->setJsTranslation($this->data["_js_$position"]);
        }

        $this->hook->attach('template.data', $this->data, $this);

        gplcart_array_sort($this->data['_css']);
        gplcart_array_sort($this->data['_js_top']);
        gplcart_array_sort($this->data['_js_bottom']);
    }

protected function compileTemplate($fileName)
    {
        try {
            $this->
                twigView->
                getTwig()->
                loadTemplate($fileName);
            $this->out('<success>' . $fileName . '</success>');
        } catch (\Exception $exception) {
            $this->out('<error>' . $fileName . '</error>');
            $this->out('<error>' . $exception->getMessage() . '</error>');
        }
    }

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


Question:
Credit goes to mgutt
http://www.programmierer-forum.de/function-imagecreatefrombmp-welche-variante-laeuft-t143137.htm
Modified by Fabien Menager to support RGB555 BMP format

public static function imagecreatefrombmp($filename, $context = null)
    {
        if (!function_exists("imagecreatetruecolor")) {
            trigger_error("The PHP GD extension is required, but is not installed.", E_ERROR);
            return false;
        }

        // version 1.00
        if (!($fh = fopen($filename, 'rb'))) {
            trigger_error('imagecreatefrombmp: Can not open ' . $filename, E_USER_WARNING);
            return false;
        }

        $bytes_read = 0;

        // read file header
        $meta = unpack('vtype/Vfilesize/Vreserved/Voffset', fread($fh, 14));

        // check for bitmap
        if ($meta['type'] != 19778) {
            trigger_error('imagecreatefrombmp: ' . $filename . ' is not a bitmap!', E_USER_WARNING);
            return false;
        }

        // read image header
        $meta += unpack('Vheadersize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vcolors/Vimportant', fread($fh, 40));
        $bytes_read += 40;

        // read additional bitfield header
        if ($meta['compression'] == 3) {
            $meta += unpack('VrMask/VgMask/VbMask', fread($fh, 12));
            $bytes_read += 12;
        }

        // set bytes and padding
        $meta['bytes'] = $meta['bits'] / 8;
        $meta['decal'] = 4 - (4 * (($meta['width'] * $meta['bytes'] / 4) - floor($meta['width'] * $meta['bytes'] / 4)));
        if ($meta['decal'] == 4) {
            $meta['decal'] = 0;
        }

        // obtain imagesize
        if ($meta['imagesize'] < 1) {
            $meta['imagesize'] = $meta['filesize'] - $meta['offset'];
            // in rare cases filesize is equal to offset so we need to read physical size
            if ($meta['imagesize'] < 1) {
                $meta['imagesize'] = @filesize($filename) - $meta['offset'];
                if ($meta['imagesize'] < 1) {
                    trigger_error('imagecreatefrombmp: Can not obtain filesize of ' . $filename . '!', E_USER_WARNING);
                    return false;
                }
            }
        }

        // calculate colors
        $meta['colors'] = !$meta['colors'] ? pow(2, $meta['bits']) : $meta['colors'];

        // read color palette
        $palette = array();
        if ($meta['bits'] < 16) {
            $palette = unpack('l' . $meta['colors'], fread($fh, $meta['colors'] * 4));
            // in rare cases the color value is signed
            if ($palette[1] < 0) {
                foreach ($palette as $i => $color) {
                    $palette[$i] = $color + 16777216;
                }
            }
        }

        // ignore extra bitmap headers
        if ($meta['headersize'] > $bytes_read) {
            fread($fh, $meta['headersize'] - $bytes_read);
        }

        // create gd image
        $im = imagecreatetruecolor($meta['width'], $meta['height']);
        $data = fread($fh, $meta['imagesize']);

        // uncompress data
        switch ($meta['compression']) {
            case 1:
                $data = Helpers::rle8_decode($data, $meta['width']);
                break;
            case 2:
                $data = Helpers::rle4_decode($data, $meta['width']);
                break;
        }

        $p = 0;
        $vide = chr(0);
        $y = $meta['height'] - 1;
        $error = 'imagecreatefrombmp: ' . $filename . ' has not enough data!';

        // loop through the image data beginning with the lower left corner
        while ($y >= 0) {
            $x = 0;
            while ($x < $meta['width']) {
                switch ($meta['bits']) {
                    case 32:
                    case 24:
                        if (!($part = substr($data, $p, 3 /*$meta['bytes']*/))) {
                            trigger_error($error, E_USER_WARNING);
                            return $im;
                        }
                        $color = unpack('V', $part . $vide);
                        break;
                    case 16:
                        if (!($part = substr($data, $p, 2 /*$meta['bytes']*/))) {
                            trigger_error($error, E_USER_WARNING);
                            return $im;
                        }
                        $color = unpack('v', $part);

                        if (empty($meta['rMask']) || $meta['rMask'] != 0xf800) {
                            $color[1] = (($color[1] & 0x7c00) >> 7) * 65536 + (($color[1] & 0x03e0) >> 2) * 256 + (($color[1] & 0x001f) << 3); // 555
                        } else {
                            $color[1] = (($color[1] & 0xf800) >> 8) * 65536 + (($color[1] & 0x07e0) >> 3) * 256 + (($color[1] & 0x001f) << 3); // 565
                        }
                        break;
                    case 8:
                        $color = unpack('n', $vide . substr($data, $p, 1));
                        $color[1] = $palette[$color[1] + 1];
                        break;
                    case 4:
                        $color = unpack('n', $vide . substr($data, floor($p), 1));
                        $color[1] = ($p * 2) % 2 == 0 ? $color[1] >> 4 : $color[1] & 0x0F;
                        $color[1] = $palette[$color[1] + 1];
                        break;
                    case 1:
                        $color = unpack('n', $vide . substr($data, floor($p), 1));
                        switch (($p * 8) % 8) {
                            case 0:
                                $color[1] = $color[1] >> 7;
                                break;
                            case 1:
                                $color[1] = ($color[1] & 0x40) >> 6;
                                break;
                            case 2:
                                $color[1] = ($color[1] & 0x20) >> 5;
                                break;
                            case 3:
                                $color[1] = ($color[1] & 0x10) >> 4;
                                break;
                            case 4:
                                $color[1] = ($color[1] & 0x8) >> 3;
                                break;
                            case 5:
                                $color[1] = ($color[1] & 0x4) >> 2;
                                break;
                            case 6:
                                $color[1] = ($color[1] & 0x2) >> 1;
                                break;
                            case 7:
                                $color[1] = ($color[1] & 0x1);
                                break;
                        }
                        $color[1] = $palette[$color[1] + 1];
                        break;
                    default:
                        trigger_error('imagecreatefrombmp: ' . $filename . ' has ' . $meta['bits'] . ' bits and this is not supported!', E_USER_WARNING);
                        return false;
                }
                imagesetpixel($im, $x, $y, $color[1]);
                $x++;
                $p += $meta['bytes'];
            }
            $y--;
            $p += $meta['decal'];
        }
        fclose($fh);
        return $im;
    }

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


Question:
// offsetCommit commits the specified topic partition offsets
//
// See http://kafka.apache.org/protocol.html#The_Messages_OffsetCommit

func (c *Conn) offsetCommit(request offsetCommitRequestV3) (offsetCommitResponseV3, error) {
	var response offsetCommitResponseV3

	err := c.writeOperation(
		func(deadline time.Time, id int32) error {
			return c.writeRequest(offsetCommitRequest, v3, id, request)
		},
		func(deadline time.Time, size int) error {
			return expectZeroSize(func() (remain int, err error) {
				return (&response).readFrom(&c.rbuf, size)
			}())
		},
	)
	if err != nil {
		return offsetCommitResponseV3{}, err
	}
	for _, r := range response.Responses {
		for _, pr := range r.PartitionResponses {
			if pr.ErrorCode != 0 {
				return offsetCommitResponseV3{}, Error(pr.ErrorCode)
			}
		}
	}

	return response, nil
}

public static <C> SlicePredicate getPredicate(ColumnSlice<C> columns, Serializer<C> colSer) {
        // Get all the columns
        if (columns == null) {
            SlicePredicate predicate = new SlicePredicate();
            predicate.setSlice_range(new SliceRange(ByteBuffer.wrap(new byte[0]), ByteBuffer.wrap(new byte[0]), false,
                    Integer.MAX_VALUE));
            return predicate;
        }
        // Get a specific list of columns
        if (columns.getColumns() != null) {
            SlicePredicate predicate = new SlicePredicate();
            predicate.setColumn_namesIsSet(true);
            predicate.column_names = colSer.toBytesList(columns.getColumns());
            return predicate;
        }
        else {
            SlicePredicate predicate = new SlicePredicate();
            predicate.setSlice_range(new SliceRange((columns.getStartColumn() == null) ? ByteBuffer.wrap(new byte[0])
                    : ByteBuffer.wrap(colSer.toBytes(columns.getStartColumn())),
                    (columns.getEndColumn() == null) ? ByteBuffer.wrap(new byte[0]) : ByteBuffer.wrap(colSer
                            .toBytes(columns.getEndColumn())), columns.getReversed(), columns.getLimit()));
            return predicate;
        }
    }

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


Question:
// ThroughputServer is the server side -- very much equivalent to local_thr in
// nanomsg/perf.  It does the measurement by counting packets received.

func ThroughputServer(addr string, msgSize int, count int) {
	s, err := pair.NewSocket()
	if err != nil {
		log.Fatalf("Failed to make new pair socket: %v", err)
	}
	defer s.Close()

	all.AddTransports(s)
	l, err := s.NewListener(addr, nil)
	if err != nil {
		log.Fatalf("Failed to make new listener: %v", err)
	}

	// Disable TCP no delay, please! - only valid for TCP
	l.SetOption(mangos.OptionNoDelay, false)

	// Make sure we linger a bit on close...
	err = s.SetOption(mangos.OptionLinger, time.Second)
	if err != nil {
		log.Fatalf("Failed set Linger: %v", err)
	}

	err = l.Listen()
	if err != nil {
		log.Fatalf("Failed to listen: %v", err)
	}

	msg, err := s.RecvMsg()
	if err != nil {
		log.Fatalf("Failed to receive start message: %v", err)
	}
	msg.Free()

	start := time.Now()

	for i := 0; i != count; i++ {
		msg, err := s.RecvMsg()
		if err != nil {
			log.Fatalf("Failed to recv: %v", err)
		}
		if len(msg.Body) != msgSize {
			log.Fatalf("Received wrong message size: %d != %d", len(msg.Body), msgSize)
		}
		// return to cache to avoid GC
		msg.Free()
	}

	finish := time.Now()

	delta := finish.Sub(start)
	deltasec := float64(delta) / float64(time.Second)
	msgpersec := float64(count) / deltasec
	mbps := (float64((count)*8*msgSize) / deltasec) / 1000000.0
	fmt.Printf("message size: %d [B]\n", msgSize)
	fmt.Printf("message count: %d\n", count)
	fmt.Printf("throughput: %d [msg/s]\n", uint64(msgpersec))
	fmt.Printf("throughput: %.3f [Mb/s]\n", mbps)
}

public static protocoludp_stats get(nitro_service service) throws Exception{
		protocoludp_stats obj = new protocoludp_stats();
		protocoludp_stats[] response = (protocoludp_stats[])obj.stat_resources(service);
		return response[0];
	}

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


Question: // Describe returns the description of a roleBinding

func (d *RoleBindingDescriber) Describe(namespace, name string, settings describe.DescriberSettings) (string, error) {
	c := d.c.RoleBindings(namespace)
	roleBinding, err := c.Get(name, metav1.GetOptions{})
	if err != nil {
		return "", err
	}

	var role *authorizationapi.Role
	if len(roleBinding.RoleRef.Namespace) == 0 {
		var clusterRole *authorizationapi.ClusterRole
		clusterRole, err = d.c.ClusterRoles().Get(roleBinding.RoleRef.Name, metav1.GetOptions{})
		role = authorizationapi.ToRole(clusterRole)
	} else {
		role, err = d.c.Roles(roleBinding.RoleRef.Namespace).Get(roleBinding.RoleRef.Name, metav1.GetOptions{})
	}

	return DescribeRoleBinding(roleBinding, role, err)
}

public void addPackageDescr(PackageDescr descr) {
        try {

            PackageDescrVisitor ruleFlattener = new PackageDescrVisitor( result.getVerifierData(),
                                                                         jars );

            ruleFlattener.visitPackageDescr( descr );

        } catch ( Throwable t ) {
            t.printStackTrace();
        }
    }

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


Question:
Redirect true if
1) Not admin page request
2) Not an ajax request
3) SG Config is valid (active, api_key, shop_number, customer_number)
4) SG Module enabled for this store

@return bool
@throws \Magento\Framework\Exception\LocalizedException

public function isAllowed()
    {
        /** @var \Magento\Framework\App\Request\Http $req */
        $req = $this->context->getRequest();

        if ($this->legacyContext->getAppState()->getAreaCode() !== FrontNameResolver::AREA_CODE
            && !$req->isAjax()
            && $this->sgConfig->isValid()
        ) {
            return true;
        }

        return false;
    }

protected function crawledBadUrls(): bool
    {
        return collect($this->urlsGroupedByStatusCode)->keys()->filter(function ($statusCode) {
            return ! $this->isSuccessOrRedirect($statusCode);
        })->count() > 0;
    }

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


Question:
生成当前实体的resultMap对象

@param configuration
@return

public static ResultMap getResultMap(Configuration configuration,Class<?> entityClass) {
        List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();

        Set<ColumnMapper> entityClassColumns = EntityHelper.getEntityMapper(entityClass).getColumnsMapper();
        for (ColumnMapper entityColumn : entityClassColumns) {
            ResultMapping.Builder builder = new ResultMapping.Builder(configuration, entityColumn.getProperty(), entityColumn.getColumn(), entityColumn.getJavaType());
            if (entityColumn.getJdbcType() != null) {
                builder.jdbcType(entityColumn.getJdbcType());
            }

            List<ResultFlag> flags = new ArrayList<ResultFlag>();
            if (entityColumn.isId()) {
                flags.add(ResultFlag.ID);
            }
            builder.flags(flags);
            builder.lazy(false);
            resultMappings.add(builder.build());
        }
        ResultMap.Builder builder = new ResultMap.Builder(configuration, "BaseResultMap", entityClass, resultMappings, true);
        return builder.build();
    }

public void setMatchReturnValue(String filterReturnValue) {
    if (filterReturnValue.equalsIgnoreCase("accept")) {
      matchReturnValue = ACCEPT;
    } else if (filterReturnValue.equalsIgnoreCase("deny")) {
      matchReturnValue = DENY;
    } else if (filterReturnValue.equalsIgnoreCase("neutral")) {
      matchReturnValue = NEUTRAL;
    } else {
      LogLog.error("invalid matchReturnValue: " + filterReturnValue);
    }
  }

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