Question:
Determines the offset code of a forward contract from a schedule. Rounds the average period length to full months.

@param schedule The schedule.
@return The offset code as String

public static String getOffsetCodeFromSchedule(Schedule schedule) {

		double doubleLength = 0;
		for(int i = 0; i < schedule.getNumberOfPeriods(); i ++) {
			doubleLength += schedule.getPeriodLength(i);
		}
		doubleLength /= schedule.getNumberOfPeriods();

		doubleLength *= 12;
		int periodLength = (int) Math.round(doubleLength);

		String offsetCode = periodLength + "M";
		return offsetCode;
	}

public function getContentXmlAutomaticStylesSectionContent($numWorksheets)
    {
        $content = '<office:automatic-styles>';

        foreach ($this->getRegisteredStyles() as $style) {
            $content .= $this->getStyleSectionContent($style);
        }

        $content .= <<<EOD
<style:style style:family="table-column" style:name="co1">
    <style:table-column-properties fo:break-before="auto"/>
</style:style>
<style:style style:family="table-row" style:name="ro1">
    <style:table-row-properties fo:break-before="auto" style:row-height="15pt" style:use-optimal-row-height="true"/>
</style:style>
EOD;

        for ($i = 1; $i <= $numWorksheets; $i++) {
            $content .= <<<EOD
<style:style style:family="table" style:master-page-name="mp$i" style:name="ta$i">
    <style:table-properties style:writing-mode="lr-tb" table:display="true"/>
</style:style>
EOD;
        }

        $content .= '</office:automatic-styles>';

        return $content;
    }

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


Question: // Unmarshal wraps json.Unmarshal with options

func Unmarshal(data []byte, v interface{}, opts ...Option) error {
	if len(opts) == 0 {
		return json.Unmarshal(data, v)
	}
	buf := bytes.NewBuffer(data)
	node, err := Read(buf, opts...)
	if err != nil {
		return err
	}
	buf.Reset()
	if err := Write(buf, node); err != nil {
		return err
	}
	return json.Unmarshal(buf.Bytes(), v)
}

func (m *Marshaller) Encode(obj interface{}, w io.Writer) error {
	m.writer.w = w
	err := m.marshal.Marshal(obj)
	m.writer.w = nil
	return err
}

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


Question:
Returns the minimum label width required on this renderers font size.

        :param      labels | [<str>, ..]

def minimumLabelWidth(self):

        min_w = 0
        metrics = QFontMetrics(self.labelFont())
        for label in self.labels():
            min_w = max(min_w, metrics.width(label))

        return max(self._minimumLabelWidth,
                   min_w + self.horizontalLabelPadding())

def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_message(self, **kwargs):

        config = ET.Element("config")
        logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status")
        config = logical_chassis_fwdl_status
        output = ET.SubElement(logical_chassis_fwdl_status, "output")
        cluster_fwdl_entries = ET.SubElement(output, "cluster-fwdl-entries")
        fwdl_entries = ET.SubElement(cluster_fwdl_entries, "fwdl-entries")
        message = ET.SubElement(fwdl_entries, "message")
        message.text = kwargs.pop('message')

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

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


Question: // Critical formats a given message according to given params to log with level Critical.

func (dl *ConsoleLogger) Critical(message interface{}, params ...interface{}) {
	dl.logger.Criticalf(fmt.Sprintf("%s %s", caller(), fmt.Sprint(message)), params...)
}

def show_raslog_output_show_all_raslog_raslog_entries_severity(self, **kwargs):

        config = ET.Element("config")
        show_raslog = ET.Element("show_raslog")
        config = show_raslog
        output = ET.SubElement(show_raslog, "output")
        show_all_raslog = ET.SubElement(output, "show-all-raslog")
        raslog_entries = ET.SubElement(show_all_raslog, "raslog-entries")
        severity = ET.SubElement(raslog_entries, "severity")
        severity.text = kwargs.pop('severity')

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

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


Question:
Create an equivalent signature string for a NumPy gufunc.

        Unlike __str__, handles dimensions that don't map to Python
        identifiers.

def to_gufunc_string(self):

        all_dims = self.all_core_dims
        dims_map = dict(zip(sorted(all_dims), range(len(all_dims))))
        input_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims]
                           for core_dims in self.input_core_dims]
        output_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims]
                            for core_dims in self.output_core_dims]
        alt_signature = type(self)(input_core_dims, output_core_dims)
        return str(alt_signature)

def deep_force_unicode(value):

    if isinstance(value, (list, tuple, set)):
        value = type(value)(map(deep_force_unicode, value))
    elif isinstance(value, dict):
        value = type(value)(map(deep_force_unicode, value.items()))
    elif isinstance(value, Promise):
        value = force_text(value)
    return value

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


Question:
Maps a set of field definitions.

@param array[] $fields

@return array[]

protected function fields(array $fields)
    {
        $result = array();
        foreach ($fields as $id => $field) {
            if (!isset($field['id'])) {
                $field['id'] = $id;
            }
            if (!isset($field['name'])) {
                $field['name'] = $id;
            }
            $result[$id] = $this->field($field);
        }
        return $result;
    }

public function set($key, $value)
	{
		Arr::set($this->body, $key, $value);

		return $this;
	}

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


Question:
// SetRxMode allows to switch between the interrupt and the polling mode for Rx.
// The method is thread-safe.

func (memif *Memif) SetRxMode(queueID uint8, rxMode RxMode) (err error) {
	var cRxMode C.memif_rx_mode_t
	switch rxMode {
	case RxModeInterrupt:
		cRxMode = C.MEMIF_RX_MODE_INTERRUPT
	case RxModePolling:
		cRxMode = C.MEMIF_RX_MODE_POLLING
	default:
		cRxMode = C.MEMIF_RX_MODE_INTERRUPT
	}
	errCode := C.memif_set_rx_mode(memif.cHandle, cRxMode, C.uint16_t(queueID))
	return getMemifError(int(errCode))
}

def start_packet_groups(self, clear_time_stamps=True, *ports):

        port_list = self.set_ports_list(*ports)
        if clear_time_stamps:
            self.api.call_rc('ixClearTimeStamp {}'.format(port_list))
        self.api.call_rc('ixStartPacketGroups {}'.format(port_list))

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


Question: Create a new timer with only the name specified.

public static Timer newTimer(String name, TimeUnit unit) {
    return new BasicTimer(MonitorConfig.builder(name).build(), unit);
  }

func (s *SetLoadBalancerPoliciesOfListenerInput) SetLoadBalancerName(v string) *SetLoadBalancerPoliciesOfListenerInput {
	s.LoadBalancerName = &v
	return s
}

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


Question:
// ExtractProperties returns a flat list of properties from a tree of steps.
// If multiple step nodes have a property of the same name, the last one in the
// preorder traversal wins.

func ExtractProperties(s *Step) (*structpb.Struct, error) {
	finals := map[string]json.RawMessage{}

	var extract func(s *Step)
	extract = func(s *Step) {
		for _, p := range s.Property {
			finals[p.Name] = json.RawMessage(p.Value)
		}
		for _, substep := range s.GetSubstep() {
			if ss := substep.GetStep(); ss != nil {
				extract(ss)
			}
		}
	}
	extract(s)

	buf, err := json.Marshal(finals)
	if err != nil {
		panic("failed to marshal in-memory map to JSON")
	}

	ret := &structpb.Struct{}
	if err := jsonpb.Unmarshal(bytes.NewReader(buf), ret); err != nil {
		return nil, err
	}
	return ret, nil
}

def walk_target_deps_topological_order(self, target: Target):
        """"""
        all_deps = get_descendants(self.target_graph, target.name)
        for dep_name in topological_sort(self.target_graph):
            if dep_name in all_deps:
                yield self.targets[dep_name]

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


Question: Launch the game process.

def start(self, version=None, **kwargs):#game_version=None, data_version=None, **kwargs):
    """"""
    if not version:
        version = self.mostRecentVersion
    pysc2Version = lib.Version( # convert to pysc2 Version
        version.version,
        version.baseVersion,
        version.dataHash,
        version.fixedHash)
    return sc_process.StarcraftProcess(
                self,
                exec_path=self.exec_path(version.baseVersion),
                version=pysc2Version,
                **kwargs)

function DisplayOTron(model) {
    if (!(this instanceof DisplayOTron)) {
        return new DisplayOTron(model);
    }

    this.model = model;

    this.pythonProcess = null;

    this.reset();

    events.EventEmitter.call(this);
}

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


Question:
Add item to

@param string $relative_path
@param string $id If empty, path will convert to id
@param array $properties Default empty. If set, properties will be set.
@return string

public function addItem($relative_path, $id = '', array $properties = []){
		$id = $id ?: $this->pathToId($relative_path);
		// Avoid duplication
		foreach( $this->dom->manifest->item as $item ){
			/** @var \SimpleXMLElement $item */
			$attr = $item->attributes();
			if( isset($attr['id']) && $id == $attr['id'] ){
				return $id;
			}
		}
		// This is unique.
		$item = $this->dom->manifest->addChild('item');
		$item['id'] = $id;
		$item['href'] = $relative_path;
		$item['media-type'] = Mime::getTypeFromPath($relative_path);
		if( $properties ){
			$item['properties'] = implode(' ', $properties);
		}
		return $id;
	}

function (parameters) {

        /**
         * Job identifier.
         * @type {string}
         */
        this.hash = parameters.hash;

        /**
         * Array of hashes to {@link Artifact}s containing each requested result.
         * @type {string[]}
         */
        this.resultHashes = parameters.resultHashes || [];

        /**
         * Hash to an {@link Artifact} containing the union of all requests results.
         * @type {string}
         */
        this.resultSuperSet = parameters.resultSuperSet || null;

        this.userId = parameters.userId || [];

        /**
         * Current status of the job.
         * @type {string}
         */
        this.status = parameters.status || null;

        /**
         * Timestamp of when the job was created.
         * @type {string}
         */
        this.createTime = parameters.createTime || null;

        /**
         * Timestamp of when the job execution started by a worker.
         * @type {string}
         */
        this.startTime = parameters.startTime || null;

        /**
         * Timestamp of when the job execution finished on the worker.
         * @type {string}
         */
        this.finishTime = parameters.finishTime || null;

        /**
         * Id/label of the worker processing the job.
         * @type {string}
         */
        this.worker = parameters.worker || null;

        /**
         * Array of labels for the job.
         * @type {string[]}
         */
        this.labels = parameters.labels || [];

        /**
         * The (id) outputNumber (0, 1, 2, ...) of the latest {@link OutputInfo} (for this job) available on the server.
         * When no output is available the number is <b>null</b>.
         * @type {number}
         */
        this.outputNumber = typeof parameters.outputNumber === 'number' ? parameters.outputNumber : null;
    }

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


Question:
@param ValidatorMap $map
@param string       $str

@return boolean

public function isValid(ValidatorMap $map, $str)
    {
        $len = function_exists('mb_strlen') ? mb_strlen($str) : strlen($str);

        return $len <= intval($map->getValue());
    }

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

      valid
    end

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


Question:
Bootstrap any application services.

@return void

public function boot()
    {
        $this->publishes([__DIR__ . '/../../database/migrations/' => database_path('migrations')], 'migrations');
        $this->publishes([__DIR__ . '/../../config/analytics.php' => config_path('analytics.php')], 'config');

        $this->loadTranslationsFrom(__DIR__ . '/../../resources/lang', 'analytics');
        $this->loadViewsFrom(__DIR__ . '/../../resources/views', 'analytics');

        $this->mergeConfigFrom(
            __DIR__ . '/../../config/analytics.php', 'analytics'
        );

        if (!$this->app->routesAreCached() && config('analytics.default_routes', true)) {
            require __DIR__ . '/../Http/routes.php';
        }
    }

func (c *Client) Status(patterns []string) (*params.FullStatus, error) {
	var result params.FullStatus
	p := params.StatusParams{Patterns: patterns}
	if err := c.facade.FacadeCall("FullStatus", p, &result); err != nil {
		return nil, err
	}
	// Older servers don't fill out model type, but
	// we know a missing type is an "iaas" model.
	if result.Model.Type == "" {
		result.Model.Type = model.IAAS.String()
	}
	return &result, nil
}

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


Question:
Check validity of cached data.

@param string $id  The identifier of this data.
@param string $tag  The tag that was passed to addCacheItem.
@return bool  TRUE if the data is valid, FALSE if not.

public function isCacheValid($id, $tag = null)
    {
        assert('is_string($id)');
        assert('is_null($tag) || is_string($tag)');

        $cacheFile = strval($this->cacheDirectory).'/'.$id;
        if (!file_exists($cacheFile)) {
            return false;
        }

        $expireFile = $cacheFile.'.expire';
        if (!file_exists($expireFile)) {
            return false;
        }

        $expireData = @file_get_contents($expireFile);
        if ($expireData === false) {
            return false;
        }

        $expireData = explode(':', $expireData, 2);

        $expireTime = intval($expireData[0]);
        if ($expireTime <= time()) {
            return false;
        }

        if (count($expireData) === 1) {
            $expireTag = null;
        } else {
            $expireTag = $expireData[1];
        }
        if ($expireTag !== $tag) {
            return false;
        }

        return true;
    }

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

        return $reply;
    }

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


Question:
Returns the total amount of results for this query

@return int

public function count()
    {
        if ($this->action() !== self::ACTION_READ) {
            return 0;
        }

        if (!$this->__resultSet) {
            $this->_execute();
        }

        if ($this->__resultSet) {
            return $this->__resultSet->total();
        }

        return 0;
    }

protected function _ensureTrackData()
    {
        if (! isset($this->_respTrackData['gtr_code'], $this->_respTrackData['gtr_name'])) {
            $select = $this->db->select();
            $select->from('gems__tracks')
                ->where('gtr_id_track = ?', $this->_respTrackData['gr2t_id_track']);

            if ($trackData = $this->db->fetchRow($select)) {
                $this->_respTrackData = $this->_respTrackData + $trackData;
            } else {
                $trackId = $this->_respTrackId;
                throw new \Gems_Exception("Track data missing for respondent track $trackId.");
            }
        }
    }

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


Question:
Inclusive
@returns {*}

function pointRectangleSimple(p, a1, a2) {
    if (!(a1.x > p.x ||
        a2.x < p.x ||
        a1.y > p.y ||
        a2.y < p.y))
        return {result: collision.INSIDE};
    return {result: collision.OUTSIDE};
}

def new_select
      quant_list = [ :ALL, :DISTINCT ]
      select_list = [ :ASTERISK, :STRING ]

      select_tok = Tree::Select.new(basic_options)

      # handle an optional set quantifier (ALL or DISTINCT)
      if quant_list.include? peek_token.token
        select_tok.set_quantifier = read_token.token
      end

      # handle a select list (ASTERISK or search terms)
      if select_list.include? peek_token.token

        # read in all search terms from the query:
        while peek_token.token == :STRING
          select_tok.add_search_term(read_token.lexeme)
          read_token if peek_token.token == :COMMA
        end

      else
        raise SyntaxError "No valid select list given (#{error_location})"
      end

      select_tok
    end

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


Question:
// MakeCACertKeyPair generates asymmetric private key and certificate
// for CA, suitable for signing certificates

func (u CertTestUtil) MakeCACertKeyPair(caName, ouName string, keyValidPeriod time.Duration) (caCertTpl *x509.Certificate, caCertBytes []byte, caPrivKey *rsa.PrivateKey, err error) {
	caPrivKey, err = rsa.GenerateKey(rand.Reader, keyBitsDefault)
	if err != nil {
		return nil, nil, nil, err
	}
	caPubKey := caPrivKey.Public()
	caPubBytes, err := x509.MarshalPKIXPublicKey(caPubKey)
	if err != nil {
		return nil, nil, nil, err
	}
	caPubSha256 := sha256.Sum256(caPubBytes)
	caCertTpl = &x509.Certificate{
		SignatureAlgorithm: defaultSignatureAlgorithm,
		PublicKeyAlgorithm: defaultPublicKeyAlgorithm,
		Version:            3,
		SerialNumber:       big.NewInt(1),
		Subject: pkix.Name{
			CommonName: caName,
		},
		NotBefore:             time.Now(),
		NotAfter:              time.Now().Add(keyValidPeriod),
		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
		BasicConstraintsValid: true,
		MaxPathLenZero:        true,
		IsCA:                  true,
		SubjectKeyId:          caPubSha256[:],
	}
	caCertBytes, err = x509.CreateCertificate(rand.Reader, caCertTpl, caCertTpl, caPubKey, caPrivKey)
	if err != nil {
		return nil, nil, nil, err
	}
	return caCertTpl, caCertBytes, caPrivKey, nil
}

def _tls_auth_encrypt(self, s):

        write_seq_num = struct.pack("!Q", self.tls_session.wcs.seq_num)
        self.tls_session.wcs.seq_num += 1
        add_data = (write_seq_num +
                    pkcs_i2osp(self.type, 1) +
                    pkcs_i2osp(self.version, 2) +
                    pkcs_i2osp(len(s), 2))
        return self.tls_session.wcs.cipher.auth_encrypt(s, add_data,
                                                        write_seq_num)

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


Question:
Run

@access public

public function run() {
		// initializing
		$this->max_processes = Config::$max_processes;

		// unlocking all transactions in case the process did not stop properly
		Transaction::unlock_all();

		// initializing the processes array to free slots
		for ($i = 0; $i <= $this->max_processes; $i++) {
			$this->processes[$i] = -1;
		}

		// run forever
		while (true) {

			// counters for parallels and non-parallel transactions
			$not_parallel_free = 0;
			$parallels_free = 0;

			// cleaning processes array before to begin
			$this->clean_slots($not_parallel_free, $parallels_free);
			while ($not_parallel_free + $parallels_free == 0) {				// if all slots are used then sleep
				usleep(100000);												// for 1/10 second and see if one or
				$this->clean_slots($not_parallel_free, $parallels_free);	// more slot got freed
			}

			try {
				$transactions = Transaction::get_runnable();
			} catch (\ErrorException $e) {
				// FIXME: this doesn't work as expected, impossible to catch database server off and retry in a second
				printf("%s\n", $e->getMessage());
				sleep(1);
				continue;
			}
			if (count($transactions) == 0) {	// if there is no transaction to
				sleep(1);						// process then sleep for a second
				continue;						// and start over
			}

			// testing every slot and if empty looking for a transaction to start
			for ($i = 0; $i < $this->max_processes; $i++) {
				if ($this->is_slot_free($i)) {
					if ($i == 0) {
						$transaction = $this->get_first_transaction($transactions, false);
					} else {
						$transaction = $this->get_first_transaction($transactions, true);
					}
					if ($transaction != null) {
//printf("Slot %d -> %s (%d)\n", $i, $transaction->classname, $transaction->id);
						$sleep = 0; // as the queue of transactions is not empty, we won't sleep
						\Skeleton\Database\Database::reset();
						$pid = pcntl_fork();
						if ($pid == -1) {
							die('Could not fork');
						} else if ($pid) {
							// PARENT
							$this->lock_slot($i, $pid);
						} else {
							// CHILD
							cli_set_process_title(strtolower($transaction->classname) . ' (' . $transaction->id . ')');
							$runner = new Runner();
							$runner->run_transaction($transaction);
							$transaction->unlock();
							exit;
						}
					}
				}
			}
		}
	}

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

    return DXHTTPRequest('/%s/setVisibility' % object_id, input_params, always_retry=always_retry, **kwargs)

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


Question: creates a new DBUS.MESSAGE_TYPE_SIGNAL message.

def new_signal(celf, path, iface, name) :
        ""
        result = dbus.dbus_message_new_signal(path.encode(), iface.encode(), name.encode())
        if result == None :
            raise CallFailed("dbus_message_new_signal")
        #end if
        return \
            celf(result)

func DetermineTxTypeString(msgTx *wire.MsgTx) string {
	switch stake.DetermineTxType(msgTx) {
	case stake.TxTypeSSGen:
		return "Vote"
	case stake.TxTypeSStx:
		return "Ticket"
	case stake.TxTypeSSRtx:
		return "Revocation"
	default:
		return "Regular"
	}
}

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


Question: // See: http://duktape.org/api.html#duk_push_error_object

func (d *Context) PushErrorObject(errCode int, format string, value interface{}) {
	__str__ := C.CString(fmt.Sprintf(format, value))
	C._duk_push_error_object(d.duk_context, C.duk_errcode_t(errCode), __str__)
	C.free(unsafe.Pointer(__str__))
}

def dumpable_obj(obj):
    ''' '''

    if isinstance(obj, list):
        _return_list = []
        for item in obj:
            if isinstance(item, list):
                _return_list.append(dumpable_obj(item))
            elif isinstance(item, set):
                _return_list.append(list(item))
            elif isinstance(item, dict):
                _return_list.append(dumpable_obj(item))
            else:
                try:
                    json.dumps(item)
                    _return_list.append(item)
                except:
                    _return_list.append(str(type(item)))
        return _return_list
    elif isinstance(obj, set):
        return list(obj)
    elif isinstance(obj, dict):
        _return_obj = {}
        for key, item in obj.items():
            if isinstance(item, list):
                _return_obj[key] = dumpable_obj(item)
            elif isinstance(item, set):
                _return_obj[key] = list(item)
            elif isinstance(item, dict):
                _return_obj[key] = dumpable_obj(item)
            else:
                try:
                    json.dumps(item)
                    _return_obj[key] = item
                except:
                    _return_obj[key] = str(type(item))
        return _return_obj
    else:
        try:
            json.dumps(obj)
            return obj
        except:
            return str(type(obj))

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


Question: Set the nick for the duration of the context.

def as_nick(self, name):

        orig = self.get_nickname()
        self.nick(name)
        try:
            yield orig
        finally:
            self.nick(orig)

def nic_name_to_host(nic_name):

	from netifaces import ifaddresses, AF_INET
	host = ifaddresses(nic_name).setdefault(AF_INET, [{'addr': 'No IP addr'}] )[0]['addr']
	return(host)

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


Question:
Creates a Table object based on this TableAttributes object.
@return a com.lowagie.text.Table object
@throws BadElementException

public Table createTable() throws BadElementException {
		if (content.isEmpty()) throw new BadElementException("Trying to create a table without rows.");
		SimpleCell row = (SimpleCell)content.get(0);
		SimpleCell cell;
		int columns = 0;
		for (Iterator i = row.getContent().iterator(); i.hasNext(); ) {
			cell = (SimpleCell)i.next();
			columns += cell.getColspan();
		}
		float[] widths = new float[columns];
		float[] widthpercentages = new float[columns];
		Table table = new Table(columns);
		table.setAlignment(alignment);
		table.setSpacing(cellspacing);
		table.setPadding(cellpadding);
		table.cloneNonPositionParameters(this);
		int pos;
		for (Iterator rows = content.iterator(); rows.hasNext(); ) {
			row = (SimpleCell)rows.next();
			pos = 0;
			for (Iterator cells = row.getContent().iterator(); cells.hasNext(); ) {
				cell = (SimpleCell)cells.next();
				table.addCell(cell.createCell(row));
				if (cell.getColspan() == 1) {
					if (cell.getWidth() > 0) widths[pos] = cell.getWidth();
					if (cell.getWidthpercentage() > 0) widthpercentages[pos] = cell.getWidthpercentage();
				}
				pos += cell.getColspan();
			}
		}
		float sumWidths = 0f;
		for(int i = 0; i < columns; i++) {
			if (widths[i] == 0) {
				sumWidths = 0;
				break;
			}
			sumWidths += widths[i];
		}
		if (sumWidths > 0) {
			table.setWidth(sumWidths);
			table.setLocked(true);
			table.setWidths(widths);
		}
		else {
			for(int i = 0; i < columns; i++) {
				if (widthpercentages[i] == 0) {
					sumWidths = 0;
					break;
				}
				sumWidths += widthpercentages[i];
			}
			if (sumWidths > 0) {
				table.setWidths(widthpercentages);
			}
		}
		if (width > 0) {
			table.setWidth(width);
			table.setLocked(true);
		}
		else if (widthpercentage > 0) {
			table.setWidth(widthpercentage);
		}
		return table;
	}

public function onConfigureTreeNode(ConfigureEvent $event)
    {
        $configuration = $event->getConfiguration();
        $request = $configuration->get('request');
        $node = $configuration->get('treeNode');

        $language = $request->getLocale();
        $countryCode = $request->attributes->get('_country');

        if (!$countryCode) {
            return;
        }

        if (!$this->countries->contains($countryCode)) {
            throw new NotFoundHttpException("Country $countryCode not configured.");
        }

        $country = $this->countries->get($countryCode);

        if (!$country->getLanguages()->contains($language)) {
            throw new NotFoundHttpException("Language $language not configured for country $country.");
        }

        if (!$this->nodeChecker->isAllowed($node, $countryCode, $language)) {
            throw new NotFoundHttpException("Language $language not allowed for country $country.");
        }
    }

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


Question: Handle the command.

public function handle()
    {
        $name = ucfirst($this->argument('name'));

        $process = Middleware::create($name);

        $this->show($process, $name);
    }

func (c *downloadCommand) Info() *cmd.Info {
	return jujucmd.Info(&cmd.Info{
		Name:    "download-backup",
		Args:    "<ID>",
		Purpose: "Get an archive file.",
		Doc:     downloadDoc,
	})
}

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


Question: // NewNonInteractiveDeferredLoadingClientConfig creates a ConfigClientClientConfig using the passed context name

func NewNonInteractiveDeferredLoadingClientConfig(loadingRules *ClientConfigLoadingRules, overrides *ConfigOverrides) ClientConfig {
	return DeferredLoadingClientConfig{loadingRules, overrides, nil}
}

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

	return nil, false
}

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


Question:
// ENV foo bar
//
// Sets the environment variable foo to bar, also makes interpolation
// in the dockerfile available from the next statement on via ${foo}.
//

func env(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string) error {
	if len(args) == 0 {
		return errAtLeastOneArgument("ENV")
	}

	if len(args)%2 != 0 {
		// should never get here, but just in case
		return errTooManyArguments("ENV")
	}

	// TODO/FIXME/NOT USED
	// Just here to show how to use the builder flags stuff within the
	// context of a builder command. Will remove once we actually add
	// a builder command to something!
	/*
		flBool1 := b.flags.AddBool("bool1", false)
		flStr1 := b.flags.AddString("str1", "HI")

		if err := b.flags.Parse(); err != nil {
			return err
		}

		fmt.Printf("Bool1:%v\n", flBool1)
		fmt.Printf("Str1:%v\n", flStr1)
	*/

	for j := 0; j < len(args); j++ {
		// name  ==> args[j]
		// value ==> args[j+1]
		newVar := args[j] + "=" + args[j+1] + ""
		gotOne := false
		for i, envVar := range b.RunConfig.Env {
			envParts := strings.SplitN(envVar, "=", 2)
			if envParts[0] == args[j] {
				b.RunConfig.Env[i] = newVar
				b.Env = append([]string{newVar}, b.Env...)
				gotOne = true
				break
			}
		}
		if !gotOne {
			b.RunConfig.Env = append(b.RunConfig.Env, newVar)
			b.Env = append([]string{newVar}, b.Env...)
		}
		j++
	}

	return nil
}

def _build_egg(egg, archive_filename, to_dir):
    """"""
    with archive_context(archive_filename):
        # building an egg
        log.warn('Building a Setuptools egg in %s', to_dir)
        _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
    # returning the result
    log.warn(egg)
    if not os.path.exists(egg):
        raise IOError('Could not build the egg.')

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


Question:
Restricts the binary file size if necessary

@param int $length The total length
@return int The limited length if a limit was specified.

private function limit_filesize($length) {

        // Limit to $this->filesizelimit.
        if (is_numeric($this->filesizelimit) && $length > $this->filesizelimit) {
            $length = floor($this->filesizelimit);
        }

        return $length;
    }

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

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

	return nil
}

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


Question:
Transforms the regular socket.socket to an ssl.SSLSocket for secure
        connections. Any arguments are passed to ssl.wrap_socket:
        http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket

def enable_ssl(self, *args, **kwargs):

        if self.handshake_sent:
            raise SSLError('can only enable SSL before handshake')

        self.secure = True
        self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)

def get_deprecated_msg(self, wrapped, instance):

        if instance is None:
            if inspect.isclass(wrapped):
                fmt = "Call to deprecated class {name}."
            else:
                fmt = "Call to deprecated function (or staticmethod) {name}."
        else:
            if inspect.isclass(instance):
                fmt = "Call to deprecated class method {name}."
            else:
                fmt = "Call to deprecated method {name}."
        if self.reason:
            fmt += " ({reason})"
        if self.version:
            fmt += " -- Deprecated since version {version}."
        return fmt.format(name=wrapped.__name__,
                          reason=self.reason or "",
                          version=self.version or "")

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


Question:
Add or remove a movie to an accounts favorite list.

@param  integer $accountId
@param  integer $mediaId
@param  boolean $isFavorite
@param  string  $mediaType  Either movie or tv
@return mixed

public function favorite($accountId, $mediaId, $isFavorite = true, $mediaType = 'movie')
    {
        return $this->postJson('account/' . $accountId . '/favorite', [
            'media_id'   => $mediaId,
            'media_type' => $mediaType,
            'favorite'   => $isFavorite
        ]);
    }

func (s *VolumeService) NewExtractVolumeParams(id string, mode string, zoneid string) *ExtractVolumeParams {
	p := &ExtractVolumeParams{}
	p.p = make(map[string]interface{})
	p.p["id"] = id
	p.p["mode"] = mode
	p.p["zoneid"] = zoneid
	return p
}

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


Question: Print a message about the GO DAG Plot we are NOT plotting.

def _no_ntplt(self, ntplt):
        """"""
        sys.stdout.write("  {GO_USR:>6,} usr {GO_ALL:>6,} GOs  DID NOT WRITE: {B} {D}\n".format(
            B=self.grprobj.get_fout_base(ntplt.hdrgo),
            D=ntplt.desc,
            GO_USR=len(ntplt.gosubdag.go_sources),
            GO_ALL=len(ntplt.gosubdag.go2obj)))

private void checkQueueSize() {
        int queueSize = getQueueSize();
        if (SEND_QUEUE_SIZE_WARNING_THRESHOLD > 0 && queueSize >= SEND_QUEUE_SIZE_WARNING_THRESHOLD) {
            logger.warn("The Gerrit send commands queue contains {} items!"
                    + " Something might be stuck, or your system can't process the commands fast enough."
                    + " Try to increase the number of sending worker threads."
                    + " Current thread-pool size: {}",
                    queueSize, executor.getPoolSize());
            logger.info("Nr of active pool-threads: {}", executor.getActiveCount());
        }
    }

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


Question: Calculates the request payload size

def calculate_size(name, include_value, local_only):

    data_size = 0
    data_size += calculate_size_str(name)
    data_size += BOOLEAN_SIZE_IN_BYTES
    data_size += BOOLEAN_SIZE_IN_BYTES
    return data_size

protected function createStringPayload($job, $data)
    {
        return [
            'displayName' => is_string($job) ? explode('@', $job)[0] : null,
            'job' => $job, 'maxTries' => null,
            'timeout' => null, 'data' => $data,
        ];
    }

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


Question:
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated

@Override
	public EClass getIfcCostValue() {
		if (ifcCostValueEClass == null) {
			ifcCostValueEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
					.get(151);
		}
		return ifcCostValueEClass;
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

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


Question:
Convert from snake_case to CamelCase

    If upper is set, then convert to upper CamelCase, otherwise the first character
    keeps its case.

def snake_to_camel(s, upper=True):

    s = _re_snake_to_camel.sub(lambda m: m.group(2).upper(), s)
    if upper:
        s = s[:1].upper() + s[1:]
    return s

function captureMessage($message, $params=[], $data=[], $stack = false, $vars = null) {
        // Gracefully handle messages which contain formatting characters, but were not
        // intended to be used with formatting.
        if (!empty($params)) {
            $formatted_message = vsprintf($message, $params);
        } else {
            $formatted_message = $message;
        }
		// support legacy method of passing in a level name as the third arg
        $data = is_null($data) ? [] : (!is_array($data) ? ['level' => $data] : $data);
        $data['message'] = $formatted_message;
        $data['sentry.interfaces.Message'] = array(
            'message' => $message,
            'params' => $params,
            'formatted' => $formatted_message,
        );
        return $this->capture($data, $stack, $vars);
    }

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


Question:
Create or save a Role to the Nexpose console.

 @param [Connection] nsc Nexpose connection.

def save(nsc)
      if @existing
        xml = nsc.make_xml('RoleUpdateRequest')
      else
        xml = nsc.make_xml('RoleCreateRequest')
      end
      xml.add_element(as_xml)

      response  = APIRequest.execute(nsc.url, xml, '1.2', { timeout: nsc.timeout, open_timeout: nsc.open_timeout })
      xml       = REXML::XPath.first(response.res, 'RoleCreateResponse')
      @id       = xml.attributes['id'].to_i unless @existing
      @existing = true
      response.success
    end

public function register($username, $password)
    {
        $userData = [
            'auth' => [
                'type' => 'm.login.dummy'
            ],
            'bind_email' => false,
            'bind_msisdn' => false,
            'password' => $password,
            'x_show_msisdn' => false
        ];

        if ($username) {
            $userData['username'] = $username;
        }

        $data = $this->matrix()->request('POST', $this->endpoint('register'), $userData, [
            'kind' => 'user'
        ]);
        $this->setData($data);
        return $this->data;
    }

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


Question:
Creates one or more symbolic links.
@param {Object[]} symlinks - Symlink details
@param {string} symlinks[].src - Source file path
@param {string} symlinks[].dest - Symbolic link file path

function createSymlinks(symlinks) {
    let path = require('path');
    let fs = require('fs');
    let del = require('del');

    del.sync(symlinks.map(sl => sl.dest));
    try {
        symlinks.forEach(sl => {
            let src = path.resolve(sl.src);
            fs.symlinkSync(src, sl.dest);
        });
    } catch (err) {
        console.error(err);
        if (err.code === 'EPERM' && err.errno === -4048) {
            console.error('***************************');
            console.error('*** PLEASE RUN AS ADMIN ***');
            console.error('***************************');
        }
    }
}

def obj_to_file(obj, filename, filetype='auto', ndarray_to_list=False, squeeze=True):
    '''

    '''
    # import json
    # with open(filename, mode='w') as f:
    #    json.dump(annotation,f)
    if ndarray_to_list:
        obj = ndarray_to_list_in_structure(obj, squeeze=squeeze)

    # write to yaml
    d = os.path.dirname(os.path.abspath(filename))
    if not os.path.exists(d):
        os.makedirs(d)

    if filetype == 'auto':
        _, ext = os.path.splitext(filename)
        filetype = ext[1:]

    if filetype in ('yaml', 'yml'):
        # import yaml
        from ruamel.yaml import YAML
        yaml = YAML(typ="unsafe")
        with open(filename, 'wt', encoding="utf-8") as f:
            yaml.dump(obj, f)
        # if sys.version_info.major == 2:
        #     with open(filename, 'wb') as f:
        #         yaml.dump(obj, f, encoding="utf-8")
        # else:
        #     with open(filename, "w", encoding="utf-8") as f:
        #         yaml.dump(obj, f)
    elif filetype in ('pickle', 'pkl'):
        f = open(filename, 'wb')
        logger.info("filename " + filename)
        # if sys.version_info[0] < 3: import cPickle as pickle
        # else: import _pickle as pickle
        import pickle
        pickle.dump(obj, f, -1)
        f.close
    elif filetype in ('streamingpicklezip', 'spklz'):
        # this is not working :-(
        import gzip
        import sPickle as pickle
        f = gzip.open(filename, 'wb', compresslevel=1)
        # f = open(filename, 'wb')
        pickle.s_dump(obj, f)
        f.close
    elif filetype in ('picklezip', 'pklz'):
        import gzip
        if sys.version_info[0] < 3: import cPickle as pickle
        else: import _pickle as pickle
        f = gzip.open(filename, 'wb', compresslevel=1)
        # f = open(filename, 'wb')
        pickle.dump(obj, f)
        f.close
    elif filetype in('mat'):

        import scipy.io as sio
        sio.savemat(filename, obj)
    else:
        logger.error('Unknown filetype ' + filetype)

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


Question:
Retrieves the scope information for a given scope source system ID

@param collectorId

@return projects

@Override
	public List<Scope>  getScopesByCollector(ObjectId collectorId) {
		List<Scope> scopes = scopeRepository.findByCollectorId(collectorId);

		//clean up needed for < > characters
		for (Scope scope : scopes) {
			scope.setName(  scope.getName().replaceAll("[<>]", "")  );
			scope.setProjectPath(  scope.getProjectPath().replaceAll("[<>]", "")  );
		}

		return scopes;
	}

private static void setScope(TokenRequest tokenRequest, Jwt jwt) {
        if(jwt.getKey() != null && !jwt.getKey().getScopes().isEmpty()) {
            tokenRequest.setScope(new ArrayList<String>() {{ addAll(jwt.getKey().getScopes()); }});
        }
    }

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


Question:
Gets the full HTML content associated with the given exception.

@param \Exception|FlattenException $exception An \Exception or FlattenException instance

@return string The HTML content as a string

public function getHtml($exception)
    {
        if (!$exception instanceof FlattenException) {
            $exception = FlattenException::create($exception);
        }

        return $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
    }

async function createDispatcher(options={}){

    // merge options
    const opt = {
        template: options.template || _path.join(__dirname, '../assets/template.ejs'),
        css: options.css || _path.join(__dirname, '../assets/layout.css'),
        lang: options.lang || 'en_US',
        footer: options.footer || null
    };

    // load page template
    const tpl = await _fs.readFile(opt.template, 'utf8');

    // load styles
    const css = await _fs.readFile(opt.css, 'utf8');

    // load page definitions
    const pages = await _jsonReader(_path.join(__dirname, '../i18n/pages-' + opt.lang + '.json'));

    // multi-type support
    // @see https://github.com/expressjs/express/blob/master/examples/error-pages/index.js
    return function dispatchRequest(page, httpStatusCode, req, res){
        // page available ?
        if (!pages[page]){
            // use "internal server error" as default
            page = '500';
            httpStatusCode = null;
        }

        // set http status code
        res.status(httpStatusCode || 500);

        // extract page date
        const pageData = pages[page];

        // multiple response formats
        res.format({
            // standard http-error-pages
            html: function(){
                res.type('.html');
                res.send(_render(tpl, css, {
                    code: httpStatusCode,
                    title: pageData.title,
                    message: pageData.message,
                    footer: opt.footer
                }))
            },

            // json
            json: function(){
                res.json({
                    error: pageData.title + ' - ' + pageData.message
                })
            },

            // text response
            default: function(){
                // plain text
                res.type('.txt').send(pageData.title + ' - ' + pageData.message);
            }
        })
    }
}

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


Question: // Unmount attempts to unmount the localPath

func Unmount(driver Driver, localPath string) error {
	// check if the driver is installed
	if err := driver.Installed(); err != nil {
		return err
	}

	// verify mount
	var mountInfo proc.NFSMountInfo
	if err := driver.Info(localPath, &mountInfo); err != nil {
		glog.Errorf("Could not get volume info for %s: %s", localPath, err)
		return err
	}

	if err := driver.Unmount(localPath); err != nil {
		glog.Errorf("Could not unmount %s: %s", localPath, err)
		return err
	}

	return nil
}

func (c *FakeGroups) Delete(name string, options *v1.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewRootDeleteAction(groupsResource, name), &user.Group{})
	return err
}

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


Question:
// AwaitReachable tries to make a TCP connection to addr regularly.
// It returns an error if it's unable to make a connection before maxWait.

func AwaitReachable(addr string, maxWait time.Duration) error {
	done := time.Now().Add(maxWait)
	for time.Now().Before(done) {
		c, err := net.Dial("tcp", addr)
		if err == nil {
			c.Close()
			return nil
		}
		time.Sleep(100 * time.Millisecond)
	}
	return fmt.Errorf("%v unreachable for %v", addr, maxWait)
}

def get_neighbors( self, peer_hostport, con=None, path=None, peer_table=None ):

        if path is None:
            path = self.atlasdb_path

        if self.neighbors_timeout is None:
            self.neighbors_timeout = atlas_neighbors_timeout()

        peer_hostport = self.canonical_peer( peer_hostport )

        neighbors = None
        if peer_hostport == self.my_hostport:
            neighbors = atlas_get_live_neighbors( None, peer_table=peer_table )
        else:
            neighbors = atlas_peer_get_neighbors( self.my_hostport, peer_hostport, timeout=self.neighbors_timeout, peer_table=peer_table, path=path, con=con )

        if neighbors is not None:
            log.debug("%s: neighbors of %s are (%s): %s" % (self.my_hostport, peer_hostport, len(neighbors), ",".join(neighbors)))
        else:
            log.error("%s: failed to ask %s for neighbors" % (self.my_hostport, peer_hostport))

        return neighbors

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


Question: // PendingFollowRequests returns pending follow requests.

func (account *Account) PendingFollowRequests() ([]User, error) {
	insta := account.inst
	resp, err := insta.sendRequest(
		&reqOptions{
			Endpoint: urlFriendshipPending,
		},
	)
	if err != nil {
		return nil, err
	}

	var result struct {
		Users []User `json:"users"`
		// TODO: pagination
		// TODO: SuggestedUsers
		Status string `json:"status"`
	}
	err = json.Unmarshal(resp, &result)
	if err != nil {
		return nil, err
	}
	if result.Status != "ok" {
		return nil, fmt.Errorf("bad status: %s", result.Status)
	}

	return result.Users, nil
}

public function check()
    {
        $this->pingBinFactory();

        $ipAddress = ip_address_from_hostname($this->target->hostname);

        $latency = $this->ping($ipAddress);

        $latencyFormatted = $latency ? "{$latency}ms" : 'error!';

        $this->target->setDisplay(
            "{$this->target->name} ({$latencyFormatted})"
        );

        if ($latency === false || $latency > $this->target->acceptedLatency) {
            $result = $this->makeResult(
                false,
                sprintf(
                    $this->target->getErrorMessage(),
                    $this->hosnameAndIp($this->target->hostname, $ipAddress),
                    $latency === false ? '[ping error]' : $latency,
                    $this->target->acceptedLatency
                )
            );
        } else {
            $result = $this->makeHealthyResult();
        }

        return $result->setValue($latency)->setValueHuman("{$latency}ms");
    }

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


Question:
Returns whether the value can be used as a standard integer.

        >>> is_int_like(4)
        True
        >>> is_int_like(4.0)
        False
        >>> is_int_like("4")
        False
        >>> is_int_like("abc")
        False

def is_int_like(value):

    try:
        if isinstance(value, int): return True
        return int(value) == value and str(value).isdigit()
    except:
        return False

def dump_stats(self, pattern):

        if not isinstance(pattern, basestring):
            raise TypeError("pattern can only be an instance of type basestring")
        self._call("dumpStats",
                     in_p=[pattern])

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


Question:
Looks for "@steal" in the dependency graph
@param {Object} graph - The dependency graph
@return {boolean} true if found, false otherwise

function includesAtSteal(graph) {
	var found = false;

	var isAtSteal = function(name) {
		return name === "@steal";
	};

	keys(graph).forEach(function(name) {
		var node = graph[name];

		if (isPluginExcludedFromBuild(node)) {
			return;
		}

		if (isAtSteal(name)) {
			return (found = true);
		}

		defaultTo(node.dependencies, []).forEach(function(depName) {
			if (isAtSteal(depName)) {
				return (found = true);
			}
		});
	});

	return found;
}

private function addWhereForSharing(QueryBuilder $qb, array $subjects, array $sids)
    {
        $where = '';
        $parameters = [];

        foreach ($subjects as $i => $subject) {
            $class = 'subject'.$i.'_class';
            $id = 'subject'.$i.'_id';
            $parameters[$class] = $subject->getType();
            $parameters[$id] = $subject->getIdentifier();
            $where .= '' === $where ? '' : ' OR ';
            $where .= sprintf('(s.subjectClass = :%s AND s.subjectId = :%s)', $class, $id);
        }

        $qb->where($where);

        foreach ($parameters as $key => $value) {
            $qb->setParameter($key, $value);
        }

        return $this->addWhereSecurityIdentitiesForSharing($qb, $sids);
    }

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


Question:
/*
preset can be one of four possibilities:
preset = 'default'
preset = ['default', {}]
preset = function <- to be invoked
preset = {plugins: []} <- already invoked function

function resolvePreset(preset) {
  let fn, options;

  if (Array.isArray(preset)) {
    fn = preset[0];
    options = preset[1];
  } else {
    fn = preset;
    options = {};
  }

  // For JS setups where we invoked the preset already
  if (preset.plugins) {
    return Promise.resolve(preset.plugins);
  }

  // Provide an alias for the default preset, as it is built-in.
  if (fn === 'default') {
    return Promise.resolve(require('cssnano-preset-default')(options).plugins);
  }

  // For non-JS setups; we'll need to invoke the preset ourselves.
  if (typeof fn === 'function') {
    return Promise.resolve(fn(options).plugins);
  }

  // Try loading a preset from node_modules
  if (isResolvable(fn)) {
    return Promise.resolve(require(fn)(options).plugins);
  }

  const sugar = `cssnano-preset-${fn}`;

  // Try loading a preset from node_modules (sugar)
  if (isResolvable(sugar)) {
    return Promise.resolve(require(sugar)(options).plugins);
  }

  // If all else fails, we probably have a typo in the config somewhere
  throw new Error(
    `Cannot load preset "${fn}". Please check your configuration for errors and try again.`
  );
}

def put(self, template_name):
        """"""
        self.reqparse.add_argument('template', type=str, required=True)
        args = self.reqparse.parse_args()

        template = db.Template.find_one(template_name=template_name)

        if not template:
            return self.make_response('No such template found', HTTP.NOT_FOUND)

        changes = diff(template.template, args['template'])
        template.template = args['template']
        template.is_modified = True

        db.session.add(template)
        db.session.commit()
        auditlog(
            event='template.update',
            actor=session['user'].username,
            data={
                'template_name': template_name,
                'template_changes': changes
            }
        )

        return self.make_response('Template {} has been updated'.format(template_name))

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


Question:
Renders template

@param string $template
Name of template

public function render($template = 'Index'): string
    {
        $class = '\Themes\\' . $this->theme . '\\' . $template . 'Template';

        $template = new $class($this);

        ob_start();

        $template->render();

        $result = ob_get_clean();

        return $result;
    }

protected function generateStandardUrl(array $urlParameters = array(), $absolute = false)
    {
        $urlParameters = $this->addRequestVariablesToUrlParameters($urlParameters);

        $anchor = '';
        if ($this->hasAnchor())
        {
            $anchor = '#'.$this->getAnchor();
        }

        return $this->getRouter()->generate($this->getRouteName(), $urlParameters, $absolute) . $anchor;
    }

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


Question: Returns the needed text to automatically document a module in RSF/sphinx

def GetModuleText(heading, name, showprivate=False):
        """"""
        und = '='*len(heading)
        if showprivate:
            opts = ':private-members:'
        else:
            opts = ''
        return r'''

%s
%s

.. automodule:: %s
    %s

''' % (heading, und, name, opts)

def output(self, _filename):

        for contract in self.slither.contracts_derived:
            txt = "\nContract %s"%contract.name
            table = PrettyTable(["Function",
                                 "require or assert"])
            for function in contract.functions:
                require = function.all_slithir_operations()
                require = [ir for ir in require if isinstance(ir, SolidityCall) and ir.function in require_or_assert]
                require = [ir.node for ir in require]
                table.add_row([function.name, self._convert([str(m.expression) for m in set(require)])])
            txt += "\n"+str(table)
            self.info(txt)

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


Question: Simple method to retrieve the current action, on the current WorkflowInstance

public function getCurrentAction()
    {
        $join = '"WorkflowAction"."ID" = "WorkflowActionInstance"."BaseActionID"';
        $action = WorkflowAction::get()
            /** @skipUpgrade */
            ->leftJoin('WorkflowActionInstance', $join)
            ->where('"WorkflowActionInstance"."ID" = '.$this->CurrentActionID)
            ->first();
        if (!$action) {
            return 'N/A';
        }
        return $action->getField('Title');
    }

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

	return nil, false
}

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


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

func (s *GetRelationalDatabaseEventsOutput) SetNextPageToken(v string) *GetRelationalDatabaseEventsOutput {
	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:
Given a parsed feed, return the links to its entries, including ones
        which disappeared (as a quick-and-dirty way to support deletions)

def entry_links(self):

        return {entry['link'] for entry in self.feed.entries if entry and entry.get('link')}

def _create_part(self, action, data, **kwargs):
        """"""
        # suppress_kevents should be in the data (not the query_params)
        if 'suppress_kevents' in kwargs:
            data['suppress_kevents'] = kwargs.pop('suppress_kevents')

        # prepare url query parameters
        query_params = kwargs
        query_params['select_action'] = action

        response = self._request('POST', self._build_url('parts'),
                                 params=query_params,  # {"select_action": action},
                                 data=data)

        if response.status_code != requests.codes.created:
            raise APIError("Could not create part, {}: {}".format(str(response), response.content))

        return Part(response.json()['results'][0], client=self)

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


Question:
Calculates the value to set a component.
@param float $value
@param float $scale
@return float

protected function setComponent(float $value, float $scale): float
    {
        return ($scale < 0) ? (1 - $value / -$scale) : ($value / $scale);
    }

func ToRenderValuesCaps(chrt *chart.Chart, chrtVals *chart.Config, options ReleaseOptions, caps *Capabilities) (Values, error) {

	top := map[string]interface{}{
		"Release": map[string]interface{}{
			"Name":      options.Name,
			"Time":      options.Time,
			"Namespace": options.Namespace,
			"IsUpgrade": options.IsUpgrade,
			"IsInstall": options.IsInstall,
			"Revision":  options.Revision,
			"Service":   "Tiller",
		},
		"Chart":        chrt.Metadata,
		"Files":        NewFiles(chrt.Files),
		"Capabilities": caps,
	}

	vals, err := CoalesceValues(chrt, chrtVals)
	if err != nil {
		return top, err
	}

	top["Values"] = vals
	return top, nil
}

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


Question:
Display page list.

@return Response

public function date($date)
    {
        $events = $this->repository->findEventsByDate($date);

        if (empty($events)) {
            abort(404);
        }

        return view('cms-frontend::events.date')->with('events', $events);
    }

public function getHomePurchasables(
        $limit = 0,
        $useStock = true
    ) {
        $queryBuilder = $this->createQueryBuilder('p');

        $this->addPerformanceJoinsToQueryBuilder($queryBuilder);
        $this->addStockPropertiesToQueryBuilder(
            $queryBuilder,
            $useStock
        );

        $query = $queryBuilder
            ->andWhere('p.enabled = :enabled')
            ->andWhere('p.showInHome = :showInHome')
            ->setParameter('enabled', true)
            ->setParameter('showInHome', true)
            ->orderBy('p.updatedAt', 'DESC');

        if ($limit > 0) {
            $query->setMaxResults($limit);
        }

        return $query
            ->getQuery()
            ->getResult();
    }

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


Question:
Resume halted engine environment.

@hidden
@deprecated

public function engineResume()
    {
        $this->executeCommandHook(__FUNCTION__, 'before');
        $this->executeExistingCommand('env:resume');
        $this->executeCommandHook(__FUNCTION__, 'after');

        return $this;
    }

@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case DroolsPackage.ON_ENTRY_SCRIPT_TYPE__SCRIPT:
				setScript(SCRIPT_EDEFAULT);
				return;
			case DroolsPackage.ON_ENTRY_SCRIPT_TYPE__SCRIPT_FORMAT:
				setScriptFormat(SCRIPT_FORMAT_EDEFAULT);
				return;
		}
		super.eUnset(featureID);
	}

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


Question: // NewWriter returns a new Writer whose buffer has the DefaultWriteBuffer size.

func NewWriter(dest io.Writer, state ws.State, op ws.OpCode) *Writer {
	return NewWriterBufferSize(dest, state, op, 0)
}

public function write( $card, $charsetIn = NULL, $charsetOut = NULL )
	{
		return $this->save( $this->fileName, $card, $charsetIn, $charsetOut );
	}

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


Question: Auto Generated Code

def confd_state_ha_master_node_id(self, **kwargs):

        config = ET.Element("config")
        confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
        ha = ET.SubElement(confd_state, "ha")
        master_node_id = ET.SubElement(ha, "master-node-id")
        master_node_id.text = kwargs.pop('master_node_id')

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

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

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

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


Question:
Save the assembled Cytoscape JS network in a js file.

        Parameters
        ----------
        file_name : Optional[str]
            The name of the file to save the Cytoscape JS network to.
            Default: model.js

def save_model(self, fname='model.js'):

        exp_colorscale_str = json.dumps(self._exp_colorscale)
        mut_colorscale_str = json.dumps(self._mut_colorscale)
        cyjs_dict = {'edges': self._edges, 'nodes': self._nodes}
        model_str = json.dumps(cyjs_dict, indent=1, sort_keys=True)
        model_dict = {'exp_colorscale_str': exp_colorscale_str,
                      'mut_colorscale_str': mut_colorscale_str,
                      'model_elements_str': model_str}
        s = ''
        s += 'var exp_colorscale = %s;\n' % model_dict['exp_colorscale_str']
        s += 'var mut_colorscale = %s;\n' % model_dict['mut_colorscale_str']
        s += 'var model_elements = %s;\n' % model_dict['model_elements_str']
        with open(fname, 'wb') as fh:
            fh.write(s.encode('utf-8'))

def sec_overview(self):

        """ Data sources overview: table with metric summaries"""
        metrics = self.config['overview']['activity_metrics']
        file_name = self.config['overview']['activity_file_csv']

        data_path = os.path.join(self.data_dir, "data")
        file_name = os.path.join(data_path, file_name)

        logger.debug("CSV file %s generation in progress", file_name)

        csv = 'metricsnames,netvalues,relativevalues,datasource\n'
        for metric in metrics:
            # comparing current metric month count with previous month
            es_index = self.get_metric_index(metric)
            ds = metric.ds.name
            m = metric(self.es_url, es_index, start=self.start, end=self.end)
            (last, percentage) = m.get_trend()
            csv += "%s,%i,%i,%s" % (metric.name, last, percentage, ds)
            csv += "\n"
        os.makedirs(os.path.dirname(file_name), exist_ok=True)
        with open(file_name, "w") as f:
            # Hack, we need to fix LaTeX escaping in a central place
            csv = csv.replace("_", r"\_")
            f.write(csv)

        logger.debug("CSV file: %s was generated", file_name)

        """
        Git Authors:

        description: average number of developers per month by quarters
        (so we have the average number of developers per month during
        those three months). If the approach is to work at the level of month,
        then just the number of developers per month.
        """

        author = self.config['overview']['author_metrics'][0]
        csv_labels = 'labels,' + author.id
        file_label = author.ds.name + "_" + author.id
        title_label = author.name + " per " + self.interval
        self.__create_csv_eps(author, None, csv_labels, file_label, title_label)

        logger.debug("CSV file %s generation in progress", file_name)

        bmi = []
        ttc = []  # time to close

        csv_labels = ''
        for m in self.config['overview']['bmi_metrics']:
            metric = m(self.es_url, self.get_metric_index(m),
                       start=self.end_prev_month, end=self.end)
            csv_labels += m.id + ","
            bmi.append(metric.get_agg())

        for m in self.config['overview']['time_to_close_metrics']:
            metric = m(self.es_url, self.get_metric_index(m),
                       start=self.end_prev_month, end=self.end)
            csv_labels += m.id + ","
            ttc.append(metric.get_agg())

        csv = csv_labels[:-1] + "\n"  # remove last comma
        csv = csv.replace("_", "")
        for val in bmi:
            csv += "%s," % (self.str_val(val))
        for val in ttc:
            csv += "%s," % (self.str_val(val))
        if csv[-1] == ',':
            csv = csv[:-1]

        data_path = os.path.join(self.data_dir, "data")
        file_name = os.path.join(data_path, 'efficiency.csv')
        os.makedirs(os.path.dirname(file_name), exist_ok=True)
        with open(file_name, "w") as f:
            f.write(csv)

        logger.debug("CSV file: %s was generated", file_name)

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


Question:
Eliminate the candidate with the lowest number of votes
and reallocated their votes.
p. 51.

@param Candidate[] $candidates Array of active candidates

@return int Number of candidates eliminated

protected function eliminateCandidates(array $candidates): int
    {
        $minimumCandidates = $this->getLowestCandidates($candidates);
        $count = count($minimumCandidates);

        // p. 52(2)(b) - the returning officer shall decide, by lot, which of those
        // candidates is to be excluded.
        // We do not look back on previous rounds at all as per p. 52(2)(a)
        $minimumCandidate = $minimumCandidates[(array_rand($minimumCandidates))];

        $this->logger->notice(sprintf('There were %d joint lowest candidates,
            %d was randomly selected to be eliminated', $count, $minimumCandidate->getId()));

        $this->transferEliminatedVotes($minimumCandidate);
        $minimumCandidate->setState(Candidate::DEFEATED);

        return count($minimumCandidates);
    }

private function minFightersCheck()
    {
        $fighters = $this->getFighters();
        $areas = $this->settings->fightingAreas;
        $fighterType = $this->championship->category->isTeam
            ? trans_choice('laravel-tournaments::core.team', 2)
            : trans_choice('laravel-tournaments::core.competitor', 2);

        $minFighterCount = $fighters->count() / $areas;

        if ($this->settings->hasPreliminary && $fighters->count() / ($this->settings->preliminaryGroupSize * $areas) < 1) {
            throw new TreeGenerationException(trans('laravel-tournaments::core.min_competitor_required', [
                'number' => $this->settings->preliminaryGroupSize * $areas,
                'fighter_type' => $fighterType,
            ]), 422);
        }

        if ($minFighterCount < ChampionshipSettings::MIN_COMPETITORS_BY_AREA) {
            throw new TreeGenerationException(trans('laravel-tournaments::core.min_competitor_required', [
                'number' => ChampionshipSettings::MIN_COMPETITORS_BY_AREA,
                'fighter_type' => $fighterType,
            ]), 422);
        }
    }

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


Question: // Dot returns the dot product of two vectors.

public void add(double lat, double lon, long time, T t, R id) {
        add(lat, lon, time, t, of(id));
    }

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


Question:
设置treeDatas值

@param treeDatas

public TreeData children(TreeData... treeDatas) {
        if (treeDatas == null || treeDatas.length == 0) {
            return this;
        }
        this.children().addAll(Arrays.asList(treeDatas));
        return this;
    }

private function getParam(string $name, string $default = null): ?string
	{
		return $this->request->getPost($name, $default);
	}

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


Question:
Cuts the text (hard) at the given position, if its longer than given length

it appends (when cut) the $ender to the string
@return string

public static function cut($string, $length, $ender = '…') {
    $length = (int) $length;
    if (mb_strlen($string) > $length) {
      $string = mb_substr($string,0,$length).$ender;
    }
    return $string;
  }

def _output_results(
            self):

        self.log.info('starting the ``_output_results`` method')

        content = ""
        maxNameLen = 0

        for r in self.results:
            if maxNameLen < len(r["ned_name"]):
                maxNameLen = len(r["ned_name"])

        if len(self.results) == 0:
            content += "No resuls found"
        else:
            thisHeader = "| "
            thisLine = "| "
            for head in self.headers:
                if head == "ned_name":
                    s = maxNameLen
                else:
                    s = self.resultSpacing
                thisHeader += str(head).ljust(s,
                                              ' ') + " | "
                thisLine += ":".ljust(s,
                                      '-') + " | "
            content += thisHeader
            content += "\n" + thisLine
            for r in self.results:
                thisRow = "| "
                for head in self.headers:
                    if head == "ned_name":
                        s = maxNameLen
                    else:
                        s = self.resultSpacing
                    thisRow += str(r[head]).ljust(s,
                                                  ' ') + " | "
                content += "\n" + thisRow

        if self.quiet == False:
            print content
        if self.outputFilePath:
            import codecs
            writeFile = codecs.open(
                self.outputFilePath, encoding='utf-8', mode='w')
            writeFile.write(content)
            writeFile.close()

        self.log.info('completed the ``_output_results`` method')
        return None

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


Question:
Returns the file path as an absolute path.

@since 1.0.0

@throws FilePathLogicException if the file path could not be made absolute.

@return FilePathInterface The file path as an absolute path.

public function toAbsolute(): FilePathInterface
    {
        if ($this->myAboveBaseLevel > 0) {
            throw new FilePathLogicException('File path "' . $this->__toString() . '" can not be made absolute: Relative path is above base level.');
        }

        return new self(true, $this->myAboveBaseLevel, $this->myDrive, $this->myDirectoryParts, $this->myFilename);
    }

public Blade start(Class<?> mainCls, String... args) {
        try {
            this.loadConfig(args);

            this.bootClass = mainCls;
            eventManager.fireEvent(EventType.SERVER_STARTING, new Event().attribute("blade", this));

            Thread thread = new Thread(() -> {
                try {
                    server.start(Blade.this);
                    latch.countDown();
                    server.join();
                } catch (BindException e) {
                    log.error("Bind address error\n", e);
                    System.exit(0);
                } catch (Exception e) {
                    startupExceptionHandler.accept(e);
                }
            });

            String threadName = null != this.threadName ? this.threadName : environment.get(ENV_KEY_APP_THREAD_NAME, null);
            threadName = null != threadName ? threadName : DEFAULT_THREAD_NAME;

            thread.setName(threadName);
            thread.start();

            this.started = true;

            Thread resourceFilesRefreshThread = new Thread(() -> {
                try {
                    FileChangeDetector fileChangeDetector = new FileChangeDetector(environment.get(ENV_KEY_AUTO_REFRESH_DIR).get());
                    fileChangeDetector.processEvent((event, filePath) -> {
                        try {
                            //TODO: add support for Create and Delete
                            if (event.equals(StandardWatchEventKinds.ENTRY_MODIFY)) {
                                Path destPath = FileChangeDetector.getDestPath(filePath, environment);
                                Files.copy(filePath, destPath, StandardCopyOption.REPLACE_EXISTING);
                            }
                        } catch (IOException e) {
                            log.error("Exception when trying to copy updated file");
                            startupExceptionHandler.accept(e);
                        }
                    });
                } catch (IOException e) {
                    startupExceptionHandler.accept(e);
                }
            });

            if (devMode() && isAutoRefreshDir()) {
                log.info("auto refresh is enabled");
                resourceFilesRefreshThread.start();
            }
        } catch (Exception e) {
            startupExceptionHandler.accept(e);
        }
        return this;

    }

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


Question:
Method is used to retrieve a URI from a configuration key.

@param config Config to read
@param key    Key to read
@return URI for the value.

public static URI uri(AbstractConfig config, String key) {
    final String value = config.getString(key);
    return uri(key, value);
  }

public static ComponentAccessToken api_component_token(String component_appid, String component_appsecret, String component_verify_ticket) {
        String postJsonData = String.format("{\"component_appid\":\"%1$s\" ,\"component_appsecret\": \"%2$s\",\"component_verify_ticket\": \"%3$s\"}",
                component_appid,
                component_appsecret,
                component_verify_ticket);
        HttpUriRequest httpUriRequest = RequestBuilder.post()
                .setHeader(jsonHeader)
                .setUri(BASE_URI + "/cgi-bin/component/api_component_token")
                .setEntity(new StringEntity(postJsonData, Charset.forName("utf-8")))
                .build();
        return LocalHttpClient.executeJsonResult(httpUriRequest, ComponentAccessToken.class);
    }

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


Question:
Returns the type of this kvstore.

        Returns
        -------
        type : str
            the string type

def type(self):

        kv_type = ctypes.c_char_p()
        check_call(_LIB.MXKVStoreGetType(self.handle, ctypes.byref(kv_type)))
        return py_str(kv_type.value)

public final void setItsType(final EShopItemType pItsType) {
    this.itsType = pItsType;
    if (this.itsId == null) {
      this.itsId = new IdI18nSpecificInList();
    }
    this.itsId.setItsType(this.itsType);
  }

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


Question: // AddMember notifies an existing etcd cluster that a new member is joining

func (c *Client) AddMember(name string, peerAddrs string) ([]Member, error) {
	// Parse the peer address, required to add the client URL later to the list
	// of endpoints for this client. Parsing as a first operation to make sure that
	// if this fails no member addition is performed on the etcd cluster.
	parsedPeerAddrs, err := url.Parse(peerAddrs)
	if err != nil {
		return nil, errors.Wrapf(err, "error parsing peer address %s", peerAddrs)
	}

	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   c.Endpoints,
		DialTimeout: 20 * time.Second,
		TLS:         c.TLS,
	})
	if err != nil {
		return nil, err
	}
	defer cli.Close()

	// Adds a new member to the cluster
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	resp, err := cli.MemberAdd(ctx, []string{peerAddrs})
	cancel()
	if err != nil {
		return nil, err
	}

	// Returns the updated list of etcd members
	ret := []Member{}
	for _, m := range resp.Members {
		// fixes the entry for the joining member (that doesn't have a name set in the initialCluster returned by etcd)
		if m.Name == "" {
			ret = append(ret, Member{Name: name, PeerURL: m.PeerURLs[0]})
		} else {
			ret = append(ret, Member{Name: m.Name, PeerURL: m.PeerURLs[0]})
		}
	}

	// Add the new member client address to the list of endpoints
	c.Endpoints = append(c.Endpoints, GetClientURLByIP(parsedPeerAddrs.Hostname()))

	return ret, nil
}

public function pfAdd($key, $element, ...$elements) {
        return $this->send(array_merge(['pfadd', $key], (array) $element, $elements), function ($response) {
            return (bool) $response;
        });
    }

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


Question: Perform default query orderBy clause.

protected function defaultOrdering()
    {
        collect($this->request->orderableColumns())
            ->map(function ($orderable) {
                $orderable['name'] = $this->getColumnName($orderable['column'], true);

                return $orderable;
            })
            ->reject(function ($orderable) {
                return $this->isBlacklisted($orderable['name']) && ! $this->hasOrderColumn($orderable['name']);
            })
            ->each(function ($orderable) {
                $column = $this->resolveRelationColumn($orderable['name']);

                if ($this->hasOrderColumn($column)) {
                    $this->applyOrderColumn($column, $orderable);
                } else {
                    $nullsLastSql = $this->getNullsLastSql($column, $orderable['direction']);
                    $normalSql = $this->wrap($column) . ' ' . $orderable['direction'];
                    $sql = $this->nullsLast ? $nullsLastSql : $normalSql;
                    $this->query->orderByRaw($sql);
                }
            });
    }

public function setSort($field,$sort = false)
    {
        $this->sort_field = $field;
        $this->sort_state = $sort;
        return $this;
    }

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


Question:
// RemoveGlob removes all paths, matching pattern, from the index. If pattern
// matches a directory path, all directory contents are removed from the index
// recursively.

func (w *Worktree) RemoveGlob(pattern string) error {
	idx, err := w.r.Storer.Index()
	if err != nil {
		return err
	}

	entries, err := idx.Glob(pattern)
	if err != nil {
		return err
	}

	for _, e := range entries {
		file := filepath.FromSlash(e.Name)
		if _, err := w.Filesystem.Lstat(file); err != nil && !os.IsNotExist(err) {
			return err
		}

		if _, err := w.doRemoveFile(idx, file); err != nil {
			return err
		}

		dir, _ := filepath.Split(file)
		if err := w.removeEmptyDirectory(dir); err != nil {
			return err
		}
	}

	return w.r.Storer.SetIndex(idx)
}

func (l *lcowfs) Rel(basepath, targpath string) (string, error) {
	baseVol := ""
	targVol := ""
	base := l.Clean(basepath)
	targ := l.Clean(targpath)
	if sameWord(targ, base) {
		return ".", nil
	}
	base = base[len(baseVol):]
	targ = targ[len(targVol):]
	if base == "." {
		base = ""
	}
	// Can't use IsAbs - `\a` and `a` are both relative in Windows.
	baseSlashed := len(base) > 0 && base[0] == l.Separator()
	targSlashed := len(targ) > 0 && targ[0] == l.Separator()
	if baseSlashed != targSlashed || !sameWord(baseVol, targVol) {
		return "", errors.New("Rel: can't make " + targpath + " relative to " + basepath)
	}
	// Position base[b0:bi] and targ[t0:ti] at the first differing elements.
	bl := len(base)
	tl := len(targ)
	var b0, bi, t0, ti int
	for {
		for bi < bl && base[bi] != l.Separator() {
			bi++
		}
		for ti < tl && targ[ti] != l.Separator() {
			ti++
		}
		if !sameWord(targ[t0:ti], base[b0:bi]) {
			break
		}
		if bi < bl {
			bi++
		}
		if ti < tl {
			ti++
		}
		b0 = bi
		t0 = ti
	}
	if base[b0:bi] == ".." {
		return "", errors.New("Rel: can't make " + targpath + " relative to " + basepath)
	}
	if b0 != bl {
		// Base elements left. Must go up before going down.
		seps := strings.Count(base[b0:bl], string(l.Separator()))
		size := 2 + seps*3
		if tl != t0 {
			size += 1 + tl - t0
		}
		buf := make([]byte, size)
		n := copy(buf, "..")
		for i := 0; i < seps; i++ {
			buf[n] = l.Separator()
			copy(buf[n+1:], "..")
			n += 3
		}
		if t0 != tl {
			buf[n] = l.Separator()
			copy(buf[n+1:], targ[t0:])
		}
		return string(buf), nil
	}
	return targ[t0:], nil
}

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


Question:
Fills in the RGB colors in the destination buffer.  alpha01 indicates
how many alpha components there are in the dest array; it will be either
0 (RGB array) or 1 (RGBA array).

function ColorSpace_fillRgb(dest, originalWidth,
                                         originalHeight, width, height,
                                         actualHeight, bpc, comps, alpha01) {
      var count = originalWidth * originalHeight;
      var rgbBuf = null;
      var numComponentColors = 1 << bpc;
      var needsResizing = originalHeight !== height || originalWidth !== width;
      var i, ii;

      if (this.isPassthrough(bpc)) {
        rgbBuf = comps;
      } else if (this.numComps === 1 && count > numComponentColors &&
          this.name !== 'DeviceGray' && this.name !== 'DeviceRGB') {
        // Optimization: create a color map when there is just one component and
        // we are converting more colors than the size of the color map. We
        // don't build the map if the colorspace is gray or rgb since those
        // methods are faster than building a map. This mainly offers big speed
        // ups for indexed and alternate colorspaces.
        //
        // TODO it may be worth while to cache the color map. While running
        // testing I never hit a cache so I will leave that out for now (perhaps
        // we are reparsing colorspaces too much?).
        var allColors = bpc <= 8 ? new Uint8Array(numComponentColors) :
                                   new Uint16Array(numComponentColors);
        var key;
        for (i = 0; i < numComponentColors; i++) {
          allColors[i] = i;
        }
        var colorMap = new Uint8Array(numComponentColors * 3);
        this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc,
                          /* alpha01 = */ 0);

        var destPos, rgbPos;
        if (!needsResizing) {
          // Fill in the RGB values directly into |dest|.
          destPos = 0;
          for (i = 0; i < count; ++i) {
            key = comps[i] * 3;
            dest[destPos++] = colorMap[key];
            dest[destPos++] = colorMap[key + 1];
            dest[destPos++] = colorMap[key + 2];
            destPos += alpha01;
          }
        } else {
          rgbBuf = new Uint8Array(count * 3);
          rgbPos = 0;
          for (i = 0; i < count; ++i) {
            key = comps[i] * 3;
            rgbBuf[rgbPos++] = colorMap[key];
            rgbBuf[rgbPos++] = colorMap[key + 1];
            rgbBuf[rgbPos++] = colorMap[key + 2];
          }
        }
      } else {
        if (!needsResizing) {
          // Fill in the RGB values directly into |dest|.
          this.getRgbBuffer(comps, 0, width * actualHeight, dest, 0, bpc,
                            alpha01);
        } else {
          rgbBuf = new Uint8Array(count * 3);
          this.getRgbBuffer(comps, 0, count, rgbBuf, 0, bpc,
                            /* alpha01 = */ 0);
        }
      }

      if (rgbBuf) {
        if (needsResizing) {
          PDFImage.resize(rgbBuf, bpc, 3, originalWidth, originalHeight, width,
                          height, dest, alpha01);
        } else {
          rgbPos = 0;
          destPos = 0;
          for (i = 0, ii = width * actualHeight; i < ii; i++) {
            dest[destPos++] = rgbBuf[rgbPos++];
            dest[destPos++] = rgbBuf[rgbPos++];
            dest[destPos++] = rgbBuf[rgbPos++];
            destPos += alpha01;
          }
        }
      }
    }

func (def *Synthdef) writeParams(w io.Writer) error {
	// write number of params
	if err := binary.Write(w, byteOrder, int32(len(def.ParamNames))); err != nil {
		return err
	}
	// write initial param values
	for _, val := range def.InitialParamValues {
		if err := binary.Write(w, byteOrder, val); err != nil {
			return err
		}
	}
	// write number of param names
	if err := binary.Write(w, byteOrder, int32(len(def.ParamNames))); err != nil {
		return err
	}
	// write param names
	for _, p := range def.ParamNames {
		if err := p.Write(w); err != nil {
			return err
		}
	}
	return nil
}

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


Question:
Compile expression list.

@return string

protected function compileExpressions()
    {
        if (count($this->expressions) === 0) {
            throw new BadMethodCallException('Can\'t compile an empty expression');
        }
        if (count($this->expressions) === 1) {
            return reset($this->expressions);
        }

        $parts = [];

        foreach ($this->expressions as $expr) {
            $expr = '(?:' . $expr . ')';

            $parts[] = $expr;
        }

        return '(?:' . implode('|', $parts) . ')';
    }

def _rt_parse_execs(self, statement, element, mode, lineparser):
        """"""
        #This is the same deal as with _rt_parse_types() below.
        if mode == "insert":
            enew, start, end = self.xparser.parse_signature(statement, element, element)
            if enew is not None:
                enew.start, enew.end = lineparser.absolute_charindex(statement, start, end)
                enew.incomplete = True
                element.executables[enew.name.lower()] = enew
                lineparser.additions.append((enew, element))

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


Question: Returns Root Mean Squared Error for this layer's pattern.

def RMSError(self):

        tss = self.TSSError()
        return math.sqrt(tss / self.size)

def rm(self, filename):
        """"""
        command = """
            try:
                import os
            except ImportError:
                import uos as os
            os.remove('{0}')
        """.format(
            filename
        )
        self._pyboard.enter_raw_repl()
        try:
            out = self._pyboard.exec_(textwrap.dedent(command))
        except PyboardError as ex:
            message = ex.args[2].decode("utf-8")
            # Check if this is an OSError #2, i.e. file/directory doesn't exist
            # and rethrow it as something more descriptive.
            if message.find("OSError: [Errno 2] ENOENT") != -1:
                raise RuntimeError("No such file/directory: {0}".format(filename))
            # Check for OSError #13, the directory isn't empty.
            if message.find("OSError: [Errno 13] EACCES") != -1:
                raise RuntimeError("Directory is not empty: {0}".format(filename))
            else:
                raise ex
        self._pyboard.exit_raw_repl()

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


Question:
set the no proxy setting

@param string $list either string or array

@return void

private function setNoProxyList($list)
    {
        if (is_array($list)) {
            $this->proxySettings['no'] = array_map('trim', $list);
            return;
        }

        if (is_string($list) && strpos($list, ',') !== false) {
            $this->proxySettings['no'] = explode(',', $list);
        } elseif (is_string($list) && strpos($list, ' ') !== false) {
            $this->proxySettings['no'] = explode(' ', $list);
        }
        $this->proxySettings['no'] = array_map('trim', $this->proxySettings['no']);
    }

def get_users_list(options={})
      content_type = {'Content-Type' => 'application/json'}
      content_type.merge!(options[:headers]) if options[:headers]

      uri = build_uri("/accounts/#{@acct_id}/users?additional_info=true")

      request = Net::HTTP::Get.new(uri.request_uri, headers(options[:headers]))
      http = initialize_net_http_ssl(uri)
      response = http.request(request)
      generate_log(request, response, uri)

      parsed_response = JSON.parse(response.body)
      (parsed_response || {}).fetch("users", [])
    end

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


Question:
Equivalent to enzyme's 'mount' method.
@param {string} node React Component that requires react-intl.
@return {object}

function mountWithIntl (node, { context, childContextTypes } = {}) {
    const intlProvider = new IntlProvider({locale: locale, messages }, {});
    const { intl } = intlProvider.getChildContext();
    return mount(React.cloneElement(node, { intl }), {
        context: Object.assign({}, context, {intl}),
        childContextTypes: Object.assign({}, { intl: intlShape }, childContextTypes)
    });
}

public function nodes()
    {
        $request = $this->createRequestInstance(self::CAT_NODES, null, null);

        return $this->client->send($request);
    }

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


Question: // ReadCommand reads the next command.

func (rd *Reader) ReadCommand() (Command, error) {
	if len(rd.cmds) > 0 {
		cmd := rd.cmds[0]
		rd.cmds = rd.cmds[1:]
		return cmd, nil
	}
	cmds, err := rd.readCommands(nil)
	if err != nil {
		return Command{}, err
	}
	rd.cmds = cmds
	return rd.ReadCommand()
}

def lookup(topic)
      if @cache.has_key? topic
        @cache[topic]
      else
        require_frontend

        etopic = case @shell_escape
        when :unix
          Tools.shell_escape(topic)
        when :windows
          Tools.win_shell_escape(topic)
        else
          topic
        end

        cmd = @frontend % etopic
        ##p "cmd", cmd
        content = `#{cmd} 2>&1`
        ##p "content", content

        # NOTES:
        # * Windows' ri always returns 0 even if article is not found. Work around it with a hack.
        # * Unix's ri sometimes returns 0 when it offers suggestions. Try `ri Object#is_ax?`.
        @cache[topic] = if $?.exitstatus != 0 or content.lines.count < 4
          nil
        else
          content
        end
      end
    end

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


Question:
Add an integer to the stream.

        :param int n: integer to add

def add_size(self, n):

        self.packet.write(struct.pack('>I', n))
        return self

function _normalizeUploadParams(file, options, callback) {
    if (!file) {
        callback(new Error('The "file" parameter is empty.'))
        return
    }

    if (!(is.string(file) || is.buffer(file) || is.readableStream(file))) {
        callback(new Error('The "file" parameter is invalid, it must be a String, Buffer, or ReadableStream'))
        return
    }

    if (is.string(file)) {
        fs.stat(file, function(err, stats) {
            if (err || !stats) {
                callback(new Error('File [' + file + '] is not exists!'))
                return
            }

            options.size = stats.size
            if (!options.ext) {
                options.ext = path.extname(file)
                if (options.ext) {
                    // 去掉.
                    options.ext = options.ext.substring(1)
                }
            }
            callback(null)
        })
        return
    }

    if (is.readableStream(file) && !options.size) {
        callback(new Error('when the "file" parameter\'s is ReadableStream, options.size must specified'))
        return
    }

    if (is.buffer(file)) {
        options.size = file.length
    }

    callback(null)
}

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


Question: Send the email via the MailHost tool

def send(self, msg_string, immediate=True):

        try:
            mailhost = api.get_tool("MailHost")
            mailhost.send(msg_string, immediate=immediate)
        except SMTPException as e:
            logger.error(e)
            return False
        except socket.error as e:
            logger.error(e)
            return False
        return True

func (s *Organization) SetMasterAccountEmail(v string) *Organization {
	s.MasterAccountEmail = &v
	return s
}

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


Question: // SetResourceARN sets the ResourceARN field's value.

func (s *KinesisStreamsOutput) SetResourceARN(v string) *KinesisStreamsOutput {
	s.ResourceARN = &v
	return s
}

public <T> T getField(String locale, String key) {
    return localize(locale).getField(key);
  }

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


Question: Turn underline cursor visibility on/off

def cursor(self, status):
        """"""
        self._display_control = ByteUtil.apply_flag(self._display_control, Command.CURSOR_ON, status)
        self.command(self._display_control)

public function showMarker( $bool = true )
	{
	    if ( $this->jsWriter instanceOf \Altamira\JsWriter\Ability\Lineable ) {
	        $this->jsWriter->setSeriesShowMarker( $this->getTitle(), $bool );
	    }
	    return $this;
	}

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


Question:
Gets JS Doc that should be retained on a class. Used to upgrade ES5 to ES6 classes and separate
class from constructor comments.

@JsMethod(name = "getClassJsDoc", namespace = "jscomp")
  public static String getClassJsDoc(String jsDoc) {
    if (Strings.isNullOrEmpty(jsDoc)) {
      return null;
    }
    Config config =
        Config.builder()
            .setLanguageMode(LanguageMode.ECMASCRIPT3)
            .setStrictMode(Config.StrictMode.SLOPPY)
            .setJsDocParsingMode(JsDocParsing.INCLUDE_DESCRIPTIONS_WITH_WHITESPACE)
            .build();
    JsDocInfoParser parser =
        new JsDocInfoParser(
            // Stream expects us to remove the leading /**
            new JsDocTokenStream(jsDoc.substring(3)),
            jsDoc,
            0,
            null,
            config,
            ErrorReporter.NULL_INSTANCE);
    parser.parse();
    JSDocInfo parsed = parser.retrieveAndResetParsedJSDocInfo();
    JSDocInfo classComments = parsed.cloneClassDoc();
    JSDocInfoPrinter printer =
        new JSDocInfoPrinter(/* useOriginalName= */ true, /* printDesc= */ true);
    String comment = printer.print(classComments);
    // Don't return empty comments, return null instead.
    if (comment == null || RegExp.compile("\\s*/\\*\\*\\s*\\*/\\s*").test(comment)) {
      return null;
    }
    return comment.trim();
  }

function(location, name) {

  this.location = location;
  this.name = name;

  if (this.isUrl(location)) {
    if (this.name)
      this.name = require('sanitize-filename')(this.name, {replacement: '_'});
    if (typeof window === 'undefined')
      this.request = require('request').defaults({headers: {'User-Agent': 'limberest'}});
    else
      this.request = require('browser-request');
  }
  else {
    this.storage = new Storage(this.location, this.name);
  }

  this.path = this.location;
  if (this.name)
    this.path += '/' + this.name;
}

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


Question: // GetN returns the N closest distinct elements to the name input in the circle.

func (c *Consistent) GetN(name string, n int) ([]string, error) {
	c.RLock()
	defer c.RUnlock()

	if len(c.circle) == 0 {
		return nil, ErrEmptyCircle
	}

	if c.count < int64(n) {
		n = int(c.count)
	}

	var (
		key   = c.hashKey(name)
		i     = c.search(key)
		start = i
		res   = make([]string, 0, n)
		elem  = c.circle[c.sortedHashes[i]]
	)

	res = append(res, elem)

	if len(res) == n {
		return res, nil
	}

	for i = start + 1; i != start; i++ {
		if i >= len(c.sortedHashes) {
			i = 0
		}
		elem = c.circle[c.sortedHashes[i]]
		if !sliceContainsMember(res, elem) {
			res = append(res, elem)
		}
		if len(res) == n {
			break
		}
	}

	return res, nil
}

func (p Path) AllFields() []interface{} {
	nodes := make([]interface{}, len(p.Nodes))
	for i, node := range p.Nodes {
		nodes[i] = node
	}
	relationships := make([]interface{}, len(p.Relationships))
	for i, relationship := range p.Relationships {
		relationships[i] = relationship
	}
	sequences := make([]interface{}, len(p.Sequence))
	for i, sequence := range p.Sequence {
		sequences[i] = sequence
	}
	return []interface{}{nodes, relationships, sequences}
}

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