Question: // New returns a new instance of translator for the 'en_IN' locale

func New() locales.Translator {
	return &en_IN{
		locale:                 "en_IN",
		pluralsCardinal:        []locales.PluralRule{2, 6},
		pluralsOrdinal:         []locales.PluralRule{2, 3, 4, 6},
		pluralsRange:           []locales.PluralRule{6},
		decimal:                ".",
		group:                  ",",
		minus:                  "-",
		percent:                "%",
		perMille:               "‰",
		timeSeparator:          ":",
		inifinity:              "∞",
		currencies:             []string{"ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", "ANG", "AOA", "AOK", "AON", "AOR", "ARA", "ARL", "ARM", "ARP", "ARS", "ATS", "AUD", "AWG", "AZM", "AZN", "BAD", "BAM", "BAN", "BBD", "BDT", "BEC", "BEF", "BEL", "BGL", "BGM", "BGN", "BGO", "BHD", "BIF", "BMD", "BND", "BOB", "BOL", "BOP", "BOV", "BRB", "BRC", "BRE", "BRL", "BRN", "BRR", "BRZ", "BSD", "BTN", "BUK", "BWP", "BYB", "BYN", "BYR", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLE", "CLF", "CLP", "CNH", "CNX", "CNY", "COP", "COU", "CRC", "CSD", "CSK", "CUC", "CUP", "CVE", "CYP", "CZK", "DDM", "DEM", "DJF", "DKK", "DOP", "DZD", "ECS", "ECV", "EEK", "EGP", "ERN", "ESA", "ESB", "ESP", "ETB", "EUR", "FIM", "FJD", "FKP", "FRF", "GBP", "GEK", "GEL", "GHC", "GHS", "GIP", "GMD", "GNF", "GNS", "GQE", "GRD", "GTQ", "GWE", "GWP", "GYD", "HKD", "HNL", "HRD", "HRK", "HTG", "HUF", "IDR", "IEP", "ILP", "ILR", "ILS", "INR", "IQD", "IRR", "ISJ", "ISK", "ITL", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRH", "KRO", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LTT", "LUC", "LUF", "LUL", "LVL", "LVR", "LYD", "MAD", "MAF", "MCF", "MDC", "MDL", "MGA", "MGF", "MKD", "MKN", "MLF", "MMK", "MNT", "MOP", "MRO", "MTL", "MTP", "MUR", "MVP", "MVR", "MWK", "MXN", "MXP", "MXV", "MYR", "MZE", "MZM", "MZN", "NAD", "NGN", "NIC", "NIO", "NLG", "NOK", "NPR", "NZD", "OMR", "PAB", "PEI", "PEN", "PES", "PGK", "PHP", "PKR", "PLN", "PLZ", "PTE", "PYG", "QAR", "RHD", "ROL", "RON", "RSD", "RUB", "RUR", "RWF", "SAR", "SBD", "SCR", "SDD", "SDG", "SDP", "SEK", "SGD", "SHP", "SIT", "SKK", "SLL", "SOS", "SRD", "SRG", "SSP", "STD", "STN", "SUR", "SVC", "SYP", "SZL", "THB", "TJR", "TJS", "TMM", "TMT", "TND", "TOP", "TPE", "TRL", "TRY", "TTD", "TWD", "TZS", "UAH", "UAK", "UGS", "UGX", "USD", "USN", "USS", "UYI", "UYP", "UYU", "UZS", "VEB", "VEF", "VND", "VNN", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XEU", "XFO", "XFU", "XOF", "XPD", "XPF", "XPT", "XRE", "XSU", "XTS", "XUA", "XXX", "YDD", "YER", "YUD", "YUM", "YUN", "YUR", "ZAL", "ZAR", "ZMK", "ZMW", "ZRN", "ZRZ", "ZWD", "ZWL", "ZWR"},
		currencyPositivePrefix: " ",
		currencyNegativePrefix: " ",
		monthsAbbreviated:      []string{"", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"},
		monthsNarrow:           []string{"", "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"},
		monthsWide:             []string{"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"},
		daysAbbreviated:        []string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"},
		daysNarrow:             []string{"S", "M", "T", "W", "T", "F", "S"},
		daysShort:              []string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"},
		daysWide:               []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"},
		periodsAbbreviated:     []string{"am", "pm"},
		periodsNarrow:          []string{"a", "p"},
		periodsWide:            []string{"am", "pm"},
		erasAbbreviated:        []string{"BC", "AD"},
		erasNarrow:             []string{"B", "A"},
		erasWide:               []string{"Before Christ", "Anno Domini"},
		timezones:              map[string]string{"LHDT": "Lord Howe Daylight Time", "HNPM": "St. Pierre & Miquelon Standard Time", "PDT": "Pacific Daylight Time", "AKST": "Alaska Standard Time", "HEOG": "West Greenland Summer Time", "VET": "Venezuela Time", "HEPM": "St. Pierre & Miquelon Daylight Time", "WIT": "Eastern Indonesia Time", "COST": "Colombia Summer Time", "CHADT": "Chatham Daylight Time", "BOT": "Bolivia Time", "ACWDT": "Australian Central Western Daylight Time", "HAST": "Hawaii-Aleutian Standard Time", "HEPMX": "Mexican Pacific Daylight Time", "AEST": "Australian Eastern Standard Time", "ACWST": "Australian Central Western Standard Time", "HKST": "Hong Kong Summer Time", "GYT": "Guyana Time", "CST": "Central Standard Time", "AEDT": "Australian Eastern Daylight Time", "BT": "Bhutan Time", "SRT": "Suriname Time", "CHAST": "Chatham Standard Time", "JST": "Japan Standard Time", "HEEG": "East Greenland Summer Time", "MDT": "Macau Summer Time", "EAT": "East Africa Time", "CLST": "Chile Summer Time", "HECU": "Cuba Daylight Time", "PST": "Pacific Standard Time", "AST": "Atlantic Standard Time", "IST": "India Standard Time", "HNNOMX": "Northwest Mexico Standard Time", "TMST": "Turkmenistan Summer Time", "ARST": "Argentina Summer Time", "WAT": "West Africa Standard Time", "NZST": "New Zealand Standard Time", "NZDT": "New Zealand Daylight Time", "HNOG": "West Greenland Standard Time", "WEZ": "Western European Standard Time", "WITA": "Central Indonesia Time", "OEZ": "Eastern European Standard Time", "HADT": "Hawaii-Aleutian Daylight Time", "COT": "Colombia Standard Time", "UYT": "Uruguay Standard Time", "UYST": "Uruguay Summer Time", "ADT": "Atlantic Daylight Time", "WIB": "Western Indonesia Time", "MEZ": "Central European Standard Time", "CLT": "Chile Standard Time", "HNPMX": "Mexican Pacific Standard Time", "SAST": "South Africa Standard Time", "HAT": "Newfoundland Daylight Time", "AWDT": "Australian Western Daylight Time", "EDT": "Eastern Daylight Time", "MYT": "Malaysia Time", "LHST": "Lord Howe Standard Time", "WART": "Western Argentina Standard Time", "WARST": "Western Argentina Summer Time", "GMT": "Greenwich Mean Time", "ChST": "Chamorro Standard Time", "HNCU": "Cuba Standard Time", "CDT": "Central Daylight Time", "ACST": "Australian Central Standard Time", "∅∅∅": "Peru Summer Time", "WAST": "West Africa Summer Time", "GFT": "French Guiana Time", "HNEG": "East Greenland Standard Time", "MESZ": "Central European Summer Time", "TMT": "Turkmenistan Standard Time", "ART": "Argentina Standard Time", "AWST": "Australian Western Standard Time", "JDT": "Japan Daylight Time", "AKDT": "Alaska Daylight Time", "ACDT": "Australian Central Daylight Time", "HNT": "Newfoundland Standard Time", "MST": "Macau Standard Time", "CAT": "Central Africa Time", "OESZ": "Eastern European Summer Time", "WESZ": "Western European Summer Time", "EST": "Eastern Standard Time", "HENOMX": "Northwest Mexico Daylight Time", "SGT": "Singapore Standard Time", "ECT": "Ecuador Time", "HKT": "Hong Kong Standard Time"},
	}
}

def save(self, page, language, data, change, extra_data=None):
        """"""
        # if this placeholder is untranslated, we save everything
        # in the default language
        if self.untranslated:
            language = settings.PAGE_DEFAULT_LANGUAGE

        # the page is being changed
        if change:
            # we need create a new content if revision is enabled
            if(settings.PAGE_CONTENT_REVISION and self.name
                not in settings.PAGE_CONTENT_REVISION_EXCLUDE_LIST):
                Content.objects.create_content_if_changed(
                    page,
                    language,
                    self.name,
                    data
                )
            else:
                Content.objects.set_or_create_content(
                    page,
                    language,
                    self.name,
                    data
                )
        # the page is being added
        else:
            Content.objects.set_or_create_content(
                page,
                language,
                self.name,
                data
            )

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


Question:
Filter the values of the given column.

@param columnId The name of the column to filter.
@param intervalList A list of interval selections to filter for.

public void filterApply(String columnId, List<Interval> intervalList) {
        if (displayerSettings.isFilterEnabled()) {

            // For string column filters, init the group interval selection operation.
            DataSetGroup groupOp = dataSetHandler.getGroupOperation(columnId);
            groupOp.setSelectedIntervalList(intervalList);

            // Notify to those interested parties the selection event.
            if (displayerSettings.isFilterNotificationEnabled()) {
                for (DisplayerListener listener : listenerList) {
                    listener.onFilterEnabled(this, groupOp);
                }
            }
            // Drill-down support
            if (displayerSettings.isFilterSelfApplyEnabled()) {
                dataSetHandler.drillDown(groupOp);
                redraw();
            }
        }
    }

protected String buildDeleteSQL(final TableMetadata metadata, final Class<? extends Object> type,
			final SqlConfig sqlConfig, final boolean addCondition) {
		StringBuilder sql = new StringBuilder("DELETE ").append("/* ")
				.append(sqlConfig.getSqlAgentFactory().getSqlIdKeyName()).append(" */")
				.append(" FROM ").append(metadata.getTableIdentifier()).append("").append(System.lineSeparator());

		if (addCondition) {
			boolean firstFlag = true;
			sql.append("WHERE").append(System.lineSeparator());

			List<? extends Column> cols = !metadata.getKeyColumns().isEmpty() ? metadata.getKeyColumns()
					: Arrays
							.asList(metadata.getColumns().get(0));
			for (TableMetadata.Column col : cols) {
				StringBuilder parts = new StringBuilder().append("\t");
				if (firstFlag) {
					if (col.isNullable()) {
						parts.append("AND ");
					} else {
						parts.append("    ");
					}
					firstFlag = false;
				} else {
					parts.append("AND ");
				}
				parts.append(col.getColumnIdentifier()).append(" = ").append("/*").append(col.getCamelColumnName())
						.append("*/''").append(System.lineSeparator());
				if (col.isNullable()) {
					wrapIfComment(sql, parts, col);
				} else {
					sql.append(parts);
				}
			}
		}
		return sql.toString();
	}

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


Question: assumed to be dev time frame, if this is to be used for production it should be enhanced

function set(url, content, mimeType) {
			if (url.charAt(0) !== '/') { url = '/'+url; }
			var point = getPoint(url) || new KnownPoint(url);
			// console.info('new url:',url, mimeType);
			point.content = content;
			point.mimeType = mimeType;
    }

def bdd_common_before_scenario(context_or_world, scenario, no_driver=False):

    # Initialize and connect driver wrapper
    start_driver(context_or_world, no_driver)

    # Add assert screenshot methods with scenario configuration
    add_assert_screenshot_methods(context_or_world, scenario)

    # Configure Jira properties
    save_jira_conf()

    context_or_world.logger.info("Running new scenario: %s", scenario.name)

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


Question:
Set options in modifications.
        All options will be stored since it should be grouped in the DB.

def modifie_options(self, field_option, value):
        """"""
        options = dict(self["options"] or {}, **{field_option: value})
        self.modifications["options"] = options

public function definition() {
        $this->course = $this->_customdata['course'];
        $this->modules = $this->_customdata['modules'];

        $mform = $this->_form;

        foreach ($this->modules as $modid => $module) {
            $mform->addElement('hidden', 'modids['.$modid.']', $modid);
            $mform->setType('modids['.$modid.']', PARAM_INT);
        }

        parent::definition();

        $modform = $this->get_module_form();
        if ($modform) {
            $modnames = array_keys($this->get_module_names());
            $modname = $modnames[0];
            // Pre-fill the form with the current completion rules of the first selected module type.
            list($module, $context, $cw, $cmrec, $data) = prepare_new_moduleinfo_data($this->course, $modname, 0);
            $data = (array)$data;
            $modform->data_preprocessing($data);
            // Unset fields that will conflict with this form and set data to this form.
            unset($data['cmid']);
            unset($data['modids']);
            unset($data['id']);
            $this->set_data($data);
        }
    }

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


Question:
Currently does not use the proxied driver
        TODO: Be able to use cookies just like headers is used here
        :return: the path of the file that was saved

def download(self, url, save_path, header={}, redownload=False):

        if save_path is None:
            logger.error("save_path cannot be None")
            return None

        # Get headers of current web driver
        header = self.get_headers()
        if len(header) > 0:
            # Add more headers if needed
            header.update(header)

        logger.debug("Download {url} to {save_path}".format(url=url, save_path=save_path))

        save_location = cutil.norm_path(save_path)
        if redownload is False:
            # See if we already have the file
            if os.path.isfile(save_location):
                logger.debug("File {save_location} already exists".format(save_location=save_location))
                return save_location

        # Create the dir path on disk
        cutil.create_path(save_location)

        if url.startswith('//'):
            url = "http:" + url
        try:
            with urllib.request.urlopen(urllib.request.Request(url, headers=header)) as response,\
            open(save_location, 'wb') as out_file:
                data = response.read()
                out_file.write(data)

        except urllib.error.HTTPError as e:
            save_location = None
            # We do not need to show the user 404 errors
            if e.code != 404:
                logger.exception("Download Http Error {url}".format(url=url))

        except Exception:
            save_location = None
            logger.exception("Download Error: {url}".format(url=url))

        return save_location

public function save(HTTPRequest $request)
    {
        if ($this->changedData) {
            $this->finalize($request);

            if (!$this->isStarted()) {
                $this->start($request);
            }

            // Apply all changes recursively, implicitly writing them to the actual PHP session store.
            $this->recursivelyApplyChanges($this->changedData, $this->data, $_SESSION);
        }
    }

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


Question:
// rangeToCIDRs converts the range of IPs covered by firstIP and lastIP to
// a list of CIDRs that contains all of the IPs covered by the range.

func rangeToCIDRs(firstIP, lastIP net.IP) []*net.IPNet {

	// First, create a CIDR that spans both IPs.
	spanningCIDR := createSpanningCIDR(netWithRange{&firstIP, &lastIP, nil})
	spanningRange := ipNetToRange(spanningCIDR)
	firstIPSpanning := spanningRange.First
	lastIPSpanning := spanningRange.Last

	cidrList := []*net.IPNet{}

	// If the first IP of the spanning CIDR passes the lower bound (firstIP),
	// we need to split the spanning CIDR and only take the IPs that are
	// greater than the value which we split on, as we do not want the lesser
	// values since they are less than the lower-bound (firstIP).
	if bytes.Compare(*firstIPSpanning, firstIP) < 0 {
		// Split on the previous IP of the first IP so that the right list of IPs
		// of the partition includes the firstIP.
		prevFirstRangeIP := getPreviousIP(firstIP)
		var bitLen int
		if prevFirstRangeIP.To4() != nil {
			bitLen = ipv4BitLen
		} else {
			bitLen = ipv6BitLen
		}
		_, _, right := partitionCIDR(spanningCIDR, net.IPNet{IP: prevFirstRangeIP, Mask: net.CIDRMask(bitLen, bitLen)})

		// Append all CIDRs but the first, as this CIDR includes the upper
		// bound of the spanning CIDR, which we still need to partition on.
		cidrList = append(cidrList, right...)
		spanningCIDR = *right[0]
		cidrList = cidrList[1:]
	}

	// Conversely, if the last IP of the spanning CIDR passes the upper bound
	// (lastIP), we need to split the spanning CIDR and only take the IPs that
	// are greater than the value which we split on, as we do not want the greater
	// values since they are greater than the upper-bound (lastIP).
	if bytes.Compare(*lastIPSpanning, lastIP) > 0 {
		// Split on the next IP of the last IP so that the left list of IPs
		// of the partition include the lastIP.
		nextFirstRangeIP := GetNextIP(lastIP)
		var bitLen int
		if nextFirstRangeIP.To4() != nil {
			bitLen = ipv4BitLen
		} else {
			bitLen = ipv6BitLen
		}
		left, _, _ := partitionCIDR(spanningCIDR, net.IPNet{IP: nextFirstRangeIP, Mask: net.CIDRMask(bitLen, bitLen)})
		cidrList = append(cidrList, left...)
	} else {
		// Otherwise, there is no need to partition; just use add the spanning
		// CIDR to the list of networks.
		cidrList = append(cidrList, &spanningCIDR)
	}
	return cidrList
}

public Selector visitSelector(CSSParser.SelectorContext ctx) {
        if (ctxHasErrorNode(ctx)) {
            statement_stack.peek().invalid = true;
            return null;
        }
        selector_stack.push(new selector_scope());
        cz.vutbr.web.css.Selector sel;
        logEnter("selector");
        selector_stack.peek().s = sel = (cz.vutbr.web.css.Selector) rf.createSelector().unlock();
        if (ctx.IDENT() != null || ctx.ASTERISK() != null) {
            cz.vutbr.web.css.Selector.ElementName en = rf.createElement(cz.vutbr.web.css.Selector.ElementName.WILDCARD);
            if (ctx.IDENT() != null) {
                en.setName(extractTextUnescaped(ctx.IDENT().getText()));
            }
            //log.debug("Adding element name: {}.", en.getName());
            selector_stack.peek().s.add(en);
        }
        for (CSSParser.SelpartContext selpartctx : ctx.selpart()) {
            visitSelpart(selpartctx);
        }

        logLeave("selector");
        selector_stack.pop();
        return sel;
    }

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


Question:
Set the data that will be appended to the <book>.ent file when built.

@param entities The data to be appended.

public void setEntities(final String entities) {
        if (entities == null && this.entities == null) {
            return;
        } else if (entities == null) {
            removeChild(this.entities);
            this.entities = null;
        } else if (this.entities == null) {
            this.entities = new KeyValueNode<String>(CommonConstants.CS_ENTITIES_TITLE, entities);
            appendChild(this.entities, false);
        } else {
            this.entities.setValue(entities);
        }
    }

void writeConfigPropsXml(List<ConfigPropType> props, Writer out, int indent) throws IOException
   {
      if (props == null || props.size() == 0)
         return;
      for (ConfigPropType prop : props)
      {
         writeIndent(out, indent);
         out.write("<config-property>");
         writeEol(out);

         writeIndent(out, indent + 1);
         out.write("<config-property-name>" + prop.getName() + "</config-property-name>");
         writeEol(out);
         writeIndent(out, indent + 1);
         out.write("<config-property-type>java.lang." + prop.getType() + "</config-property-type>");
         writeEol(out);
         writeIndent(out, indent + 1);
         out.write("<config-property-value>" + prop.getValue() + "</config-property-value>");
         writeEol(out);

         writeIndent(out, indent);
         out.write("</config-property>");
         writeEol(out);
         writeEol(out);
      }
   }

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


Question: // Get implements storage.Storage.

func (s *Storage) Get(c context.Context, req storage.GetRequest, cb storage.GetCallback) error {
	recs := []*rec(nil)
	err := s.run(func() error {
		ls := s.getLogStreamLocked(req.Project, req.Path, false)
		if ls == nil {
			return storage.ErrDoesNotExist
		}

		limit := len(ls.logs)
		if req.Limit > 0 && req.Limit < limit {
			limit = req.Limit
		}
		if s.MaxGetCount > 0 && s.MaxGetCount < limit {
			limit = s.MaxGetCount
		}

		// Grab all records starting from our start index.
		for idx := req.Index; idx <= ls.latestIndex; idx++ {
			if le, ok := ls.logs[idx]; ok {
				recs = append(recs, &rec{
					index: idx,
					data:  le,
				})
			}

			if len(recs) >= limit {
				break
			}
		}
		return nil
	})
	if err != nil {
		return err
	}

	// Punt all of the records upstream. We copy the data to prevent the
	// callback from accidentally mutating it. We reuse the data buffer to try
	// and catch errors when the callback retains the data.
	for _, r := range recs {
		var dataCopy []byte
		if !req.KeysOnly {
			dataCopy = make([]byte, len(r.data))
			copy(dataCopy, r.data)
		}
		if !cb(storage.MakeEntry(dataCopy, r.index)) {
			break
		}
	}

	return nil
}

def create(model_config, backend, checkpoint_strategy, streaming=None):

    return ClassicStorage(
        model_config=model_config,
        backend=backend,
        checkpoint_strategy=checkpoint_strategy,
        streaming=streaming
    )

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


Question:
Populate the controller's protected properties

@return void

private function init()
    {
        // Set the layout from the Config file
        $this->layout = View::make(config('decoy.core.layout'));

        // Store the controller class for routing
        $this->controller = get_class($this);

        // Get the controller name
        $controller_name = $this->controllerName($this->controller);

        // Make a default title based on the controller name
        if (empty($this->title)) {
            $this->title = $this->title($controller_name);
        }

        // Figure out what the show view should be.  This is the path to the show
        // view file.  Such as 'admin.news.edit'
        if (empty($this->show_view)) {
            $this->show_view = $this->detailPath($this->controller);
        }

        // Try to suss out the model by singularizing the controller
        if (empty($this->model)) {
            $this->model = $this->model($this->controller);
            if (!class_exists($this->model)) {
                $this->model = null;
            }
        }

        // If the input contains info on the parent, immediately instantiate
        // the parent instance.  These are populated by some AJAX calls like
        // autocomplete on a many to many and the attach method.
        if (($parent_id = request('parent_id'))
            && ($parent_controller = request('parent_controller'))) {
            $parent_model_class = $this->model($parent_controller);
            $this->parent($parent_model_class::findOrFail($parent_id));
        }
    }

public function data($raw = false)
    {
        $data = array(
            'count' => $this->count,
            'results' => parent::data($raw),
            'pages' => $this->pages,
            'page' => $this->page
        );

        return $data;
    }

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


Question:
// ExpandString injects the variables into the Yaml configuration string using
// a ${key} template parameter with limited support for bash string functions.

func ExpandString(config string, envs map[string]string) string {
	if envs == nil || len(envs) == 0 {
		return config
	}
	keys := []string{}
	for k := range envs {
		keys = append(keys, k)
	}
	sort.Sort(sort.Reverse(sort.StringSlice(keys)))
	expanded := config
	for _, k := range keys {
		v := envs[k]

		for _, substitute := range substitutors {
			expanded = substitute(expanded, k, v)
		}
	}
	return expanded
}

def find_value_for_constant(name)
      constant = YARD::Registry.all(:constant).find{|c| c.name == name.to_sym }
      log.warn "StepTransformer#find_value_for_constant : Could not find the CONSTANT [#{name}] using the string value." unless constant
      constant ? strip_regex_from(constant.value) : name
    end

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


Question:
getFormatClass

@param string $format

@return  string|\Windwalker\Structure\Format\FormatInterface

@throws  \DomainException

@since   2.1

public static function getFormatClass($format)
    {
        // Return a namespace in a given format
        $class = sprintf('%s\Format\%sFormat', __NAMESPACE__, ucfirst(strtolower($format)));

        if (!class_exists($class)) {
            throw new \DomainException(
                sprintf(
                    'Structure format: %s not supported. Class: %s not found.',
                    $format,
                    $class
                )
            );
        }

        return $class;
    }

func (ue UnpackingError) Error() string {
	var dv string
	var dt string
	k := ue.Destination.Kind()
	switch k {
	case reflect.Ptr:
		dt = fmt.Sprintf("%s", ue.Destination.Type().Elem())
		if !ue.Destination.IsNil() {
			dv = fmt.Sprintf("%v", ue.Destination.Elem().Interface())
		} else {
			dv = "nil"

		}
	case reflect.Invalid:
		dv = "invalid"
		dt = dv
	default:
		dv = fmt.Sprintf("%v", ue.Destination.Interface())
		dt = fmt.Sprintf("%s", ue.Destination.Type())
	}

	return fmt.Sprintf("Error unpacking %v(%T) into %s(%s):%v",
		ue.Source,
		ue.Source,
		dv,
		dt,
		ue.Err)
}

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


Question:
Creates a new mark.

@param Result $result
@param User   $user
@param string $mark

@return mark

public function createMark(Result $result, User $user, $mark)
    {
        $mark = new Mark($result, $user, $mark);
        $this->om->persist($mark);
        $this->om->flush();

        $newMarkEvent = new LogResultsNewMarkEvent($mark);
        $this->dispatcher->dispatch('log', $newMarkEvent);

        return $mark;
    }

public function process(array $data, array $config)
	{
		// Intersect the data given the with the data keys provided.
		$specifiedData = array_intersect_key($data, array_flip(array_keys($config)));

		// Unset password if null, otherwise hash it for saving.
		if(array_key_exists('password', $specifiedData))
		{
			// Unset password rules if null.
			if(is_null($specifiedData['password']))
			{
				unset($rules['password']);
			}
		}

		// Validate and set our errors if they exist.
		$this->errorPayload = $this->validator->validate($specifiedData, $config);

		// Return sanitized data if no validation errors exist.
		if($this->errorPayload->getStatus() == Payload::STATUS_VALID)
		{
			// Hash password if present.
			if(array_key_exists('password', $specifiedData))
			{
				$specifiedData['password'] = Hash::make($specifiedData['password']);
			}

			return new Payload($specifiedData, Payload::STATUS_VALID);
		}

		return $this->errorPayload;
	}

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


Question:
@param EncodingParametersInterface|null $parameters

@return int|null

protected function getPageNumber(EncodingParametersInterface $parameters)
    {
        $paging = $parameters->getPaginationParameters();
        return isset($paging[self::PARAM_PAGING_NUMBER]) ? $paging[self::PARAM_PAGING_NUMBER] : null;
    }

public MessageProtocol withCharset(String charset) {
        return new MessageProtocol(contentType, Optional.ofNullable(charset), version);
    }

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


Question: Query Salesforce for more records and rewind iterator

protected function queryMore()
    {
        $result = $this->client->queryMore($this->queryResult->getQueryLocator());
        $this->setQueryResult($result);
        $this->rewind();
    }

func (cur *seriesCursor) Next() (*SeriesCursorRow, error) {
	for {
		// Read series keys for next measurement if no more keys remaining.
		// Exit if there are no measurements remaining.
		if cur.ofs == len(cur.keys) {
			m, err := cur.mitr.Next()
			if err != nil {
				return nil, err
			} else if m == nil {
				return nil, nil
			}

			if err := cur.readSeriesKeys(m); err != nil {
				return nil, err
			}
			continue
		}

		cur.row.Name, cur.row.Tags = tsdb.ParseSeriesKey(cur.keys[cur.ofs])
		cur.ofs++
		return &cur.row, nil
	}
}

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


Question:
Sets the data opType

@param dtype

@Override
    public void setDType(DataType dtype) {
        assert dtype == DataType.DOUBLE || dtype == DataType.FLOAT
                        || dtype == DataType.INT : "Invalid opType passed, must be float or double";
        // this.dtype = dtype;
    }

public Type[] getParameterTypes() {
        Type[] types = new Type[parameterNames.size()];
        for (int i = 0; i < types.length; i++) {
            types[i] = String.class;
        }

        return types;
    }

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


Question:
Handel the method call.

@param  Color   $color   the color object the function was called on
@param  string  $method  the method name
@param  array   $args    arguments
@return mixed            this will be returned to the client code

public function trigger(Color $color, $method, $args)
    {
        if (is_callable(array($this, $method))) {
            array_unshift($args, $color);

            return call_user_func_array(array($this, $method), $args);
        }

        return null;
    }

public static function url($identifier, $data = null, $domain = null) {

		if(false === is_string($identifier)) {
			return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($identifier)), E_USER_ERROR);
		}

		if(false === static :: routeExists($identifier)) {
			return trigger_error(sprintf('Route identifier "%s" not found in routes.php', $identifier), E_USER_ERROR);
		}

		if(null !== $data && false === is_string($data) && false === is_array($data)) {
			return trigger_error(sprintf('Argument 2 passed to %s() must be of the type array or string, "%s" given', __METHOD__, gettype($data)), E_USER_ERROR);
		}

		if(null !== $domain && false === is_string($domain)) {
			return trigger_error(sprintf('Argument 3 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($domain)), E_USER_ERROR);
		}

		if(true === is_string($data)) {
			$data = [$data];
		}

		if(null === $data) {
			$data = [];
		}

		$route 		= static :: getRoute($identifier);
		$url 		= $route -> getUrl();
		$parameters = 0;
		$optionals  = 0;

		if(preg_match_all('#\{(.*?)(\?)?\}#i', $url, $matches)) {

			foreach($matches[2] as $optional) {

				if('?' === $optional) {

					$optionals++;
					continue;
				}

				$parameters++;
			}

			if(count($data) < $parameters) {
				return trigger_error(sprintf('Incorrect number of parameters given for Router url with identifier "%s". Expecting %s, got %s with %s optional', $route -> getIdentifier(), count($matches[2]), count($data), $optionals), E_USER_ERROR);
			}

			foreach($matches[0] as $index => $match) {

				$match 		= $matches[0][$index];
				$type 		= $matches[1][$index];
				$optional 	= $matches[2][$index];
				$where 		= $route -> getWhere();
				$replace 	= static :: $types['string'];

				if(true === isset(static :: $types[$type])) {
					$replace = static :: $types[$type];
				}

				if(true === is_array($where)) {

					foreach($where as $key => $regex) {

						if($key === $type) {

							$replace =$regex;
							break;
						}
					}
				}

				if(true === isset($data[$index])) {

					if(false === is_string($data[$index]) && false === is_numeric($data[$index])) {
						return trigger_error(sprintf('Router url width id "%s" expects parameters to be a String', $route -> getIdentifier()));
					}

					if(preg_match('#' . $replace . '#i', $data[$index])) {
						$url = preg_replace('#'. preg_quote($match) .'#i', $data[$index], $url, 1);
					}
					else {
						return trigger_error(sprintf('Parameters given to router url width id "%s" do not match. Trying to match regular expression pattern "%s" with "%s" as subject', $route -> getIdentifier(), $replace, $data[$index]));
					}
				}
				elseif('' !== $optional) {
					$url = preg_replace('#'. '/?' . preg_quote($match) .'#i', '', $url, 1);
				}
			}
		}

		if(null !== $domain && false === static :: domainExists($domain)) {
			return trigger_error(sprintf('Domain "%s" does not exists in routes.php', $domain), E_USER_ERROR);
		}

		//Check if routes has a prefix and add it if it does
		$prefix = $route -> getPrefix();

		if(true === isset($prefix['url'])) {
			$url = $prefix['url'] . $url;
		}

		return (null !== $domain ? rtrim($domain, '/') . '/' : '') . $url;
	}

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


Question:
Validate a setting is a bool.

    Returns:
        bool: The value as a boolean.

    Raises:
        ValueError: If the value can't be parsed as a bool string or isn't already bool.

def _validate_bool(value):

    if isinstance(value, six.text_type):
        if value.strip().lower() == 'true':
            value = True
        elif value.strip().lower() == 'false':
            value = False
        else:
            raise ValueError('"{}" must be a boolean ("True" or "False")'.format(value))

    if not isinstance(value, bool):
        raise ValueError('"{}" is not a boolean value.'.format(value))

    return value

def parse_temperature_response(
        temperature_string: str) -> Mapping[str, Optional[float]]:
    '''

    '''
    err_msg = 'Unexpected argument to parse_temperature_response: {}'.format(
        temperature_string)
    if not temperature_string or \
            not isinstance(temperature_string, str):
        raise ParseError(err_msg)
    parsed_values = temperature_string.strip().split(' ')
    if len(parsed_values) < 2:
        log.error(err_msg)
        raise ParseError(err_msg)

    data = {
        parse_key_from_substring(s): parse_number_from_substring(s)
        for s in parsed_values[:2]
    }
    if 'C' not in data or 'T' not in data:
        raise ParseError(err_msg)
    data = {
        'current': data['C'],
        'target': data['T']
    }
    return data

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


Question:
Writes contents to the file

@param string $contents
@return $this

public function write($contents) {
		$dir = new Directory($this->getDirname());
		$dir->make();

		file_put_contents($this->pathname, $contents);
		return $this;
	}

public static void write(Path self, String text) throws IOException {
        Writer writer = null;
        try {
            writer = new OutputStreamWriter(Files.newOutputStream(self), Charset.defaultCharset());
            writer.write(text);
            writer.flush();

            Writer temp = writer;
            writer = null;
            temp.close();
        } finally {
            closeWithWarning(writer);
        }
    }

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


Question:
getLoaderConfig

@return mixed

protected function getLoaderConfig()
    {
        return [
            LoaderInterface::FROM_STRING     => false,
            LoaderInterface::SIMPLEXML       => false,
            LoaderInterface::DOM_CLASS       => __NAMESPACE__.'\\Dom\DOMDocument',
            LoaderInterface::SIMPLEXML_CLASS => __NAMESPACE__.'\\SimpleXMLElement'
        ];
    }

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

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


Question:
@param   DOMElement $element    The element to add the attributes to
@param   array      $attributes The attributes to add
@param   array      $skip       List of attributes to skip

@return  void

private function addAttributes($element, $attributes, $skip = [])
    {
        foreach ($attributes as $key => $value) {
            if (in_array($key, $skip) || is_null($value)) {
                continue;
            }

            $element->setAttribute($key, $value);
        }
    }

function parse (buffer, doc, options, key) {
  switch (doc.type) {
    case 'text':
      return [...buffer, doc.content]
    case 'tag': {
      let children = reactify(doc.children, options, key)
      if (!children.length) {
        children = null
      }
      if (doc.name.startsWith(COMMENT_TAG)) {
        return [...buffer, ...children]
      }
      const tag = options.mappings[doc.name] || DEFAULT_TAG
      if (tag.fromMarkup) {
        doc.attrs = tag.fromMarkup(doc.attrs)
      }
      if (tag === DEFAULT_TAG && !doc.attrs.as) {
        doc.attrs.as = doc.name
      }
      if (doc.attrs.class) {
        // Rename class to className for React compatibility
        doc.attrs.className = doc.attrs.class
        delete doc.attrs.class
      }
      return [...buffer, createElement(tag, { key, ...doc.attrs }, children)]
    }
    default:
      return buffer
  }
}

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


Question:
Decorator for cmd methods

    Parses arguments from the arg string and passes them to the method as *args
    and **kwargs.

def repl_command(fxn):

    @functools.wraps(fxn)
    def wrapper(self, arglist):
        """Wraps the command method"""
        args = []
        kwargs = {}
        if arglist:
            for arg in shlex.split(arglist):
                if "=" in arg:
                    split = arg.split("=", 1)
                    kwargs[split[0]] = split[1]
                else:
                    args.append(arg)
        return fxn(self, *args, **kwargs)

    return wrapper

def get_arglist(self, objtxt):
        """"""
        obj, valid = self._eval(objtxt)
        if valid:
            return getargtxt(obj)

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


Question:
Takes a list of rows and a column and returns the most frequent values (one or more) under
        that column in those rows.

def mode_string(self, rows: List[Row], column: StringColumn) -> List[str]:

        most_frequent_list = self._get_most_frequent_values(rows, column)
        if not most_frequent_list:
            return []
        if not all([isinstance(value, str) for value in most_frequent_list]):
            raise ExecutionError(f"Invalid values for mode_string: {most_frequent_list}")
        return most_frequent_list

public void init(BaseField field, GridScreenParent gridScreen, Record recGrid, boolean bCreateSortOrder)
    {
        m_recGrid = recGrid;
        m_bCreateSortOrder = bCreateSortOrder;
        super.init(field, gridScreen, null);
        m_iKeyAreaArray = new String[MAX_ARRAY_SIZE];
        for (int i = 0; i < MAX_ARRAY_SIZE; i++)
            m_iKeyAreaArray[i] = null;
        m_iNextArrayIndex = 0;
    }

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


Question:
Creates Swift library object, from given array configuration.
@param array $config object configuration
@return Object created object
@throws \yii\base\InvalidConfigException on invalid configuration.

protected function createSwiftObject(array $config)
    {
        if (isset($config['class'])) {
            $className = $config['class'];
            unset($config['class']);
        } else {
            throw new InvalidConfigException('Object configuration must be an array containing a "class" element.');
        }

        if (isset($config['constructArgs'])) {
            $args = [];
            foreach ($config['constructArgs'] as $arg) {
                if (is_array($arg) && isset($arg['class'])) {
                    $args[] = $this->createSwiftObject($arg);
                } else {
                    $args[] = $arg;
                }
            }
            unset($config['constructArgs']);
            $object = Yii::createObject($className, $args);
        } else {
            $object = Yii::createObject($className);
        }

        if (!empty($config)) {
            $reflection = new \ReflectionObject($object);
            foreach ($config as $name => $value) {
                if ($reflection->hasProperty($name) && $reflection->getProperty($name)->isPublic()) {
                    $object->$name = $value;
                } else {
                    $setter = 'set' . $name;
                    if ($reflection->hasMethod($setter) || $reflection->hasMethod('__call')) {
                        $object->$setter($value);
                    } else {
                        throw new InvalidConfigException('Setting unknown property: ' . $className . '::' . $name);
                    }
                }
            }
        }

        return $object;
    }

private function parseModel($definition, $xml = true) {
        $model = strpos($definition, '\\') === false ?
            $this->modelsNamespace . '\\' . $definition :
            $definition;

        if (!is_subclass_of($model, ApiModel::class)) {
            throw new Exception("The model definition for $model was not found", 501);
        }

        $ret = [
            'type' => 'object',
        ];

        $class = new ReflectionClass($model);

        $properties =  $this->parseProperties($class);
        foreach ($properties as $name => &$property) {
            if (isset($property['required'])) {
                unset($property['required']);
                if (!isset($ret['required'])) {
                    $ret['required'] = [];
                }
                $ret['required'][] = $name;
            }
        }
        $ret['properties'] = $properties;

        if ($xml) {
            $ret['xml'] = ['name' => $definition];
        }

        return $ret;
    }

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


Question: //Get gets the user profile information from Oauth provider

func (s *userProfileService) Get(ctx context.Context, accessToken string, profileURL string) (*provider.OAuthUserProfileResponse, error) {

	userProfileResponse := provider.OAuthUserProfileResponse{}

	req, err := http.NewRequest("GET", profileURL, nil)
	if err != nil {
		return nil, errors.NewInternalError(ctx, err)
	}
	req.Header.Add("Authorization", "Bearer "+accessToken)
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json, text/plain, */*")

	resp, err := s.client.Do(req)

	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"user_profile_url": profileURL,
			"err":              err,
		}, "Unable to fetch oauth user profile")
		return nil, errors.NewInternalError(ctx, err)
	} else if resp != nil {
		defer rest.CloseResponse(resp)
	}

	if resp.StatusCode != http.StatusOK {
		bodyString := rest.ReadBody(resp.Body)
		log.Error(ctx, map[string]interface{}{
			"response_status":  resp.Status,
			"response_body":    bodyString,
			"user_profile_url": profileURL,
		}, "Unable to fetch oauth user profile")
		if resp.StatusCode == 400 {
			return nil, errors.NewUnauthorizedError(bodyString)
		}
		return nil, errors.NewInternalError(ctx, errs.Errorf("received a non-200 response %s while fetching oauth user profile %s", resp.Status, profileURL))
	}

	err = json.NewDecoder(resp.Body).Decode(&userProfileResponse)
	return &userProfileResponse, err
}

private <TResponse> TResponse callServiceGetApi(
            String path, Map<String, String> queryParams,
            Class<TResponse> responseClass) throws AuthleteApiException
    {
        return callGetApi(mServiceCredentials, path, queryParams, responseClass);
    }

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


Question:
Parse manifest file

    :param str manifest_path: Path to manifest file
    :return: samples
    :rtype: list[str, list]

def parse_manifest(manifest_path):

    samples = []
    with open(manifest_path, 'r') as f:
        for line in f:
            if not line.isspace() and not line.startswith('#'):
                sample = line.strip().split('\t')
                require(2 <= len(sample) <= 3, 'Bad manifest format! '
                                               'Expected UUID\tURL1\t[URL2] (tab separated), got: {}'.format(sample))
                uuid = sample[0]
                urls = sample[1:]
                for url in urls:
                    require(urlparse(url).scheme and urlparse(url), 'Invalid URL passed for {}'.format(url))
                samples.append([uuid, urls])
    return samples

def load_pubkeys(loadpath, pubkeys):

    """"""

    filenames = os.listdir(loadpath)
    logger.debug('loading authorized pubkeys {0}'.format(filenames))
    for filename in filenames:
        pubkeys.append(open(join(loadpath, filename)).read())

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


Question:
GETs top links from this subreddit.  Calls :meth:`narwal.Reddit.top`.

        :param limit: max number of links to return

def top(self, limit=None):

        return self._reddit.top(self.display_name, limit=limit)

private function generateRule($ruleset)
    {
        $regex = '';
        $content = 'index.php';

        $count = 0;
        $total = count($ruleset);

        foreach($ruleset as $ruleChunk)
        {
            $count++;

            if($count === 1) {
                $content .= '?post_type=' . $this->postType->postType;
            }

            if(preg_match('/\{\w+\}/', $ruleChunk))
            {
                // Add to the url catcher
                $regex .= '/([^/]+)';

                // Add to the query string
                $string = preg_match('/\{(.*?)\}/', $ruleChunk, $matches);
                $index = '$matches[' . ($count - 1) . ']';
                $content .= '&' . $matches[1] . '=' . $index;
            }
            else
            {
                // Add to the url catcher
                $regex .= '/' . $ruleChunk;
            }
        }

        $regex .= '/?$';

        return array($regex, $content);
    }

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


Question:
Defines if alarm markers should be drawn.
@param VISIBLE

public void setAlarmsVisible(final boolean VISIBLE) {
        if (null == alarmsVisible) {
            _alarmsVisible = VISIBLE;
            fireTileEvent(REDRAW_EVENT);
        } else {
            alarmsVisible.set(VISIBLE);
        }
    }

function report (info) {
  if (!info) {
    return null
  }

  const { name, current, latest } = info

  if (!name || !current || !latest) {
    return null
  }

  const messages = [
    `update available ${chalk.dim(current)} → ${chalk.green(latest)}`,
    `Run ${chalk.cyan('npm i ' + name + ' -D')} to update`
  ]

  const boxenOptions = {
    padding: 1,
    margin: 1,
    align: 'center',
    borderColor: 'yellow',
    borderStyle: 'round'
  }

  return boxen(messages.join('\n'), boxenOptions)
}

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


Question: // Read implements the Reader interface for syntheticByteStream

func (s *syntheticByteStream) Read(p []byte) (int, error) {
	s.mu.Lock()
	defer s.mu.Unlock()

	start := s.offset
	end := start + int64(len(p))
	var err error
	if end >= s.size {
		err = io.EOF
		end = s.size
	}

	for idx := start; idx < end; idx++ {
		p[idx-start] = s.factory(idx)
	}

	s.offset = end

	return int(end - start), err
}

public static String getString(byte[] bytes, String encoding) {
        try {
            return new String(bytes, encoding);
        } catch(UnsupportedEncodingException e) {
            throw new IllegalArgumentException(encoding + " is not a known encoding name.", e);
        }
    }

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


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

@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case AfplibPackage.GCLINERG__XPOS:
				setXPOS((Integer)newValue);
				return;
			case AfplibPackage.GCLINERG__YPOS:
				setYPOS((Integer)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

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:
From the API:

        Returns the 10 most recent files accepted by the 'magic' file selection
        algorithm. Currently any files with 10 or more likes are magic.

        Returns:
            List of SharedFile objects

def get_magic_shake(self, before=None, after=None):

        if before and after:
            raise Exception("You cannot specify both before and after keys")

        endpoint = '/api/magicfiles'

        if before:
            endpoint += '/before/{key}'.format(key=before)
        elif after:
            endpoint += '/after/{key}'.format(key=after)

        data = self._make_request("GET", endpoint=endpoint)
        return [SharedFile.NewFromJSON(sf) for sf in data['magicfiles']]

func (f *IndexFile) bytes() int {
	var b int
	// Do not count f.data contents because it is mmap'd
	b += int(unsafe.Sizeof(f.data))
	b += int(unsafe.Sizeof(f.res))
	b += int(unsafe.Sizeof(f.sfile))
	b += int(unsafe.Sizeof(f.sfileref))
	// Do not count SeriesFile because it belongs to the code that constructed this IndexFile.
	b += int(unsafe.Sizeof(f.tblks))
	for k, v := range f.tblks {
		// Do not count TagBlock contents, they all reference f.data
		b += int(unsafe.Sizeof(k)) + len(k)
		b += int(unsafe.Sizeof(*v))
	}
	b += int(unsafe.Sizeof(f.mblk)) + f.mblk.bytes()
	b += int(unsafe.Sizeof(f.seriesIDSetData) + unsafe.Sizeof(f.tombstoneSeriesIDSetData))
	// Do not count contents of seriesIDSetData or tombstoneSeriesIDSetData: references f.data
	b += int(unsafe.Sizeof(f.level) + unsafe.Sizeof(f.id))
	b += 24 // mu RWMutex is 24 bytes
	b += int(unsafe.Sizeof(f.compacting))
	b += int(unsafe.Sizeof(f.path)) + len(f.path)

	return b
}

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


Question: Retrieve values for graphs.

def retrieveVals(self):
        """"""
        file_stats = self._fileInfo.getContainerStats()
        for contname in self._fileContList:
            stats = file_stats.get(contname)
            if stats is not None:
                if self.hasGraph('rackspace_cloudfiles_container_size'):
                    self.setGraphVal('rackspace_cloudfiles_container_size', contname,
                                     stats.get('size'))
                if self.hasGraph('rackspace_cloudfiles_container_count'):
                    self.setGraphVal('rackspace_cloudfiles_container_count', contname,
                                     stats.get('count'))

function PlotLineOrBand(options) {
			var plotLine = this;
			if (options) {
				plotLine.options = options;
				plotLine.id = options.id;
			}

			//plotLine.render()
			return plotLine;
		}

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


Question:
将评论取消精选
@param $msg_data_id
@param $user_comment_id
@param null $index
@return bool
@throws Exception

public function unMarkComment($msg_data_id, $user_comment_id, $index = null) {
        $args = $this->getUnMarkComment()->parameters(
            compact('msg_data_id', 'user_comment_id', 'index'))->json();
        return $args['errcode'] == 0;
    }

public function build(ResultSpec $result): string
    {
        $response = [];
        $units = $result->getResults();

        foreach ($units as $unit) {
            /** @var AbstractResult $unit */
            if ($unit instanceof Result) {
                /** @var Result $unit */
                $response[] = [
                    'jsonrpc' => '2.0',
                    'result' => $this->preBuild($unit->getResult()),
                    'id'     => $unit->getId()
                ];
            } elseif ($unit instanceof Error) {
                /** @var Error $unit */
                $baseException = $unit->getBaseException();
                $response[] = [
                    'jsonrpc' => '2.0',
                    'error' => [
                        'code'    => $baseException->getJsonRpcCode(),
                        'message' => $this->getErrorMessage($baseException->getJsonRpcCode()),
                        'data'    => $baseException->getJsonRpcData()
                    ],
                    'id' => $unit->getId()
                ];
            }
        }

        if (empty($response)) {
            return '';
        }

        if ($result->isSingleResult()) {
            return json_encode($response[0]);
        }

        return json_encode($response);
    }

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


Question: Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with the given name can be found.

function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) {
            var result;
            var lastLocation;
            var propertyWithInvalidInitializer;
            var errorLocation = location;
            var grandparent;
            var isInExternalModule = false;
            loop: while (location) {
                // Locals of a source file are not in scope (because they get merged into the global symbol table)
                if (location.locals && !isGlobalSourceFile(location)) {
                    if (result = getSymbol(location.locals, name, meaning)) {
                        var useResult = true;
                        if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
                            // symbol lookup restrictions for function-like declarations
                            // - Type parameters of a function are in scope in the entire function declaration, including the parameter
                            //   list and return type. However, local types are only in scope in the function body.
                            // - parameters are only in the scope of function body
                            // This restriction does not apply to JSDoc comment types because they are parented
                            // at a higher level than type parameters would normally be
                            if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 273 /* JSDocComment */) {
                                useResult = result.flags & 262144 /* TypeParameter */
                                    ? lastLocation === location.type ||
                                        lastLocation.kind === 142 /* Parameter */ ||
                                        lastLocation.kind === 141 /* TypeParameter */
                                    : false;
                            }
                            if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) {
                                // parameters are visible only inside function body, parameter list and return type
                                // technically for parameter list case here we might mix parameters and variables declared in function,
                                // however it is detected separately when checking initializers of parameters
                                // to make sure that they reference no variables declared after them.
                                useResult =
                                    lastLocation.kind === 142 /* Parameter */ ||
                                        (lastLocation === location.type &&
                                            result.valueDeclaration.kind === 142 /* Parameter */);
                            }
                        }
                        if (useResult) {
                            break loop;
                        }
                        else {
                            result = undefined;
                        }
                    }
                }
                switch (location.kind) {
                    case 256 /* SourceFile */:
                        if (!ts.isExternalOrCommonJsModule(location))
                            break;
                        isInExternalModule = true;
                    case 225 /* ModuleDeclaration */:
                        var moduleExports = getSymbolOfNode(location).exports;
                        if (location.kind === 256 /* SourceFile */ || ts.isAmbientModule(location)) {
                            // It's an external module. First see if the module has an export default and if the local
                            // name of that export default matches.
                            if (result = moduleExports["default"]) {
                                var localSymbol = ts.getLocalSymbolForExportDefault(result);
                                if (localSymbol && (result.flags & meaning) && localSymbol.name === name) {
                                    break loop;
                                }
                                result = undefined;
                            }
                            // Because of module/namespace merging, a module's exports are in scope,
                            // yet we never want to treat an export specifier as putting a member in scope.
                            // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
                            // Two things to note about this:
                            //     1. We have to check this without calling getSymbol. The problem with calling getSymbol
                            //        on an export specifier is that it might find the export specifier itself, and try to
                            //        resolve it as an alias. This will cause the checker to consider the export specifier
                            //        a circular alias reference when it might not be.
                            //     2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
                            //        an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
                            //        which is not the desired behavior.
                            if (moduleExports[name] &&
                                moduleExports[name].flags === 8388608 /* Alias */ &&
                                ts.getDeclarationOfKind(moduleExports[name], 238 /* ExportSpecifier */)) {
                                break;
                            }
                        }
                        if (result = getSymbol(moduleExports, name, meaning & 8914931 /* ModuleMember */)) {
                            break loop;
                        }
                        break;
                    case 224 /* EnumDeclaration */:
                        if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
                            break loop;
                        }
                        break;
                    case 145 /* PropertyDeclaration */:
                    case 144 /* PropertySignature */:
                        // TypeScript 1.0 spec (April 2014): 8.4.1
                        // Initializer expressions for instance member variables are evaluated in the scope
                        // of the class constructor body but are not permitted to reference parameters or
                        // local variables of the constructor. This effectively means that entities from outer scopes
                        // by the same name as a constructor parameter or local variable are inaccessible
                        // in initializer expressions for instance member variables.
                        if (ts.isClassLike(location.parent) && !(location.flags & 32 /* Static */)) {
                            var ctor = findConstructorDeclaration(location.parent);
                            if (ctor && ctor.locals) {
                                if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) {
                                    // Remember the property node, it will be used later to report appropriate error
                                    propertyWithInvalidInitializer = location;
                                }
                            }
                        }
                        break;
                    case 221 /* ClassDeclaration */:
                    case 192 /* ClassExpression */:
                    case 222 /* InterfaceDeclaration */:
                        if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) {
                            if (lastLocation && lastLocation.flags & 32 /* Static */) {
                                // TypeScript 1.0 spec (April 2014): 3.4.1
                                // The scope of a type parameter extends over the entire declaration with which the type
                                // parameter list is associated, with the exception of static member declarations in classes.
                                error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
                                return undefined;
                            }
                            break loop;
                        }
                        if (location.kind === 192 /* ClassExpression */ && meaning & 32 /* Class */) {
                            var className = location.name;
                            if (className && name === className.text) {
                                result = location.symbol;
                                break loop;
                            }
                        }
                        break;
                    // It is not legal to reference a class's own type parameters from a computed property name that
                    // belongs to the class. For example:
                    //
                    //   function foo<T>() { return '' }
                    //   class C<T> { // <-- Class's own type parameter T
                    //       [foo<T>()]() { } // <-- Reference to T from class's own computed property
                    //   }
                    //
                    case 140 /* ComputedPropertyName */:
                        grandparent = location.parent.parent;
                        if (ts.isClassLike(grandparent) || grandparent.kind === 222 /* InterfaceDeclaration */) {
                            // A reference to this grandparent's type parameters would be an error
                            if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) {
                                error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
                                return undefined;
                            }
                        }
                        break;
                    case 147 /* MethodDeclaration */:
                    case 146 /* MethodSignature */:
                    case 148 /* Constructor */:
                    case 149 /* GetAccessor */:
                    case 150 /* SetAccessor */:
                    case 220 /* FunctionDeclaration */:
                    case 180 /* ArrowFunction */:
                        if (meaning & 3 /* Variable */ && name === "arguments") {
                            result = argumentsSymbol;
                            break loop;
                        }
                        break;
                    case 179 /* FunctionExpression */:
                        if (meaning & 3 /* Variable */ && name === "arguments") {
                            result = argumentsSymbol;
                            break loop;
                        }
                        if (meaning & 16 /* Function */) {
                            var functionName = location.name;
                            if (functionName && name === functionName.text) {
                                result = location.symbol;
                                break loop;
                            }
                        }
                        break;
                    case 143 /* Decorator */:
                        // Decorators are resolved at the class declaration. Resolving at the parameter
                        // or member would result in looking up locals in the method.
                        //
                        //   function y() {}
                        //   class C {
                        //       method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
                        //   }
                        //
                        if (location.parent && location.parent.kind === 142 /* Parameter */) {
                            location = location.parent;
                        }
                        //
                        //   function y() {}
                        //   class C {
                        //       @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
                        //   }
                        //
                        if (location.parent && ts.isClassElement(location.parent)) {
                            location = location.parent;
                        }
                        break;
                }
                lastLocation = location;
                location = location.parent;
            }
            if (result && nameNotFoundMessage && noUnusedIdentifiers) {
                result.isReferenced = true;
            }
            if (!result) {
                result = getSymbol(globals, name, meaning);
            }
            if (!result) {
                if (nameNotFoundMessage) {
                    if (!errorLocation ||
                        !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) &&
                            !checkAndReportErrorForExtendingInterface(errorLocation)) {
                        error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg));
                    }
                }
                return undefined;
            }
            // Perform extra checks only if error reporting was requested
            if (nameNotFoundMessage) {
                if (propertyWithInvalidInitializer) {
                    // We have a match, but the reference occurred within a property initializer and the identifier also binds
                    // to a local variable in the constructor where the code will be emitted.
                    var propertyName = propertyWithInvalidInitializer.name;
                    error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg));
                    return undefined;
                }
                // Only check for block-scoped variable if we are looking for the
                // name with variable meaning
                //      For example,
                //          declare module foo {
                //              interface bar {}
                //          }
                //      const foo/*1*/: foo/*2*/.bar;
                // The foo at /*1*/ and /*2*/ will share same symbol with two meaning
                // block - scope variable and namespace module. However, only when we
                // try to resolve name in /*1*/ which is used in variable position,
                // we want to check for block- scoped
                if (meaning & 2 /* BlockScopedVariable */) {
                    var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
                    if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */) {
                        checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
                    }
                }
                // If we're in an external module, we can't reference value symbols created from UMD export declarations
                if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) {
                    var decls = result.declarations;
                    if (decls && decls.length === 1 && decls[0].kind === 228 /* NamespaceExportDeclaration */) {
                        error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name);
                    }
                }
            }
            return result;
        }

function unexpectedTokenError(token, message) {
        var value, msg = message || Messages.UnexpectedToken;

        if (token) {
            if (!message) {
                msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
                    (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
                    (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
                    (token.type === Token.StringLiteral) ? Messages.UnexpectedString :
                    (token.type === Token.Template) ? Messages.UnexpectedTemplate :
                    Messages.UnexpectedToken;

                if (token.type === Token.Keyword) {
                    if (isFutureReservedWord(token.value)) {
                        msg = Messages.UnexpectedReserved;
                    } else if (strict && isStrictModeReservedWord(token.value)) {
                        msg = Messages.StrictReservedWord;
                    }
                }
            }

            value = (token.type === Token.Template) ? token.value.raw : token.value;
        } else {
            value = 'ILLEGAL';
        }

        msg = msg.replace('%0', value);

        return (token && typeof token.lineNumber === 'number') ?
            createError(token.lineNumber, token.start, msg) :
            createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg);
    }

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


Question:
Retrieve an L{inevow.IResource} to render the contents of the given
        module.

def locateChild(self, ctx, segments):

        if len(segments) != 2:
            return NotFound
        hashCode, moduleName = segments
        cachedModule = self.getModule(moduleName)
        return static.Data(
            cachedModule.fileContents,
            'text/javascript', expires=(60 * 60 * 24 * 365 * 5)), []

func (r Resources) upsert(method string, route string, resource *Resource) error {
	currentNode := r

	parts := strings.Split(route, "/")
	if len(parts) > 0 {
		last := len(parts) - 1

		// Upsert route of the resource.
		for _, part := range parts[:last] {
			if part == "" {
				continue
			}
			part = "/" + part

			node, found := currentNode[part]
			if !found {
				node = &Resource{
					Resources: Resources{},
					Responses: Responses{},
				}

				currentNode[part] = node
			}
			currentNode = node.Resources
		}

		if parts[last] != "" {
			// Upsert resource into the very bottom of the node tree.
			part := "/" + parts[last]
			node, found := currentNode[part]
			if !found {
				node = &Resource{
					Resources: Resources{},
					Responses: Responses{},
				}
			}
			currentNode[part] = node
			currentNode = node.Resources
		}
	}

	method = strings.ToLower(method)
	if _, found := currentNode[method]; found {
		return nil
		// return fmt.Errorf("duplicated method route: %v %v", method, route)
	}

	currentNode[method] = resource

	return nil
}

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


Question:
Generate the pattern preview

@return string HTML code

public function preview()
	{
		$strPreview = '

' . $this->label . '

';

		if ($this->multiPage)
		{
			$strPreview .= '
 Articletitle1

 Articletitle2

 Articletitle3
';
		}
		else
		{
			$strPreview .= '
 Articletitle
';
		}

		$strPreview .= '

Change selection

' . $this->description . '

';

		return $strPreview;
	}

public function predictEncoded($hash, $modelType, $language = null)
    {
        return $this->predict(
            [
                'base64' => $hash,
            ],
            $modelType,
            $language
        );
    }

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


Question:
:field: field with the data
            :filters_: additional filters to find the date

def get_last_date(self, field, filters_=[]):
        '''

        '''

        last_date = self.get_last_item_field(field, filters_=filters_)

        return last_date

def getUpdated(self, sObjectType, startDate, endDate):
    '''

    '''
    self._setHeaders('getUpdated')
    return self._sforce.service.getUpdated(sObjectType, startDate, endDate)

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


Question:
Return the entire dataset of the underlying database.

@return mixed

public function get()
    {
        $rows = [];

        foreach ($this->db as $key => $value) {
            $rows[] = (object) [
                'key'   => $key,
                'value' => is_string($value) ? $value : print_r($value, true),
            ];
        }

        return $rows;
    }

private void populateMetaData() throws SQLException
   {
      m_meta.clear();

      ResultSetMetaData meta = m_rs.getMetaData();
      int columnCount = meta.getColumnCount() + 1;
      for (int loop = 1; loop < columnCount; loop++)
      {
         String name = meta.getColumnName(loop);
         Integer type = Integer.valueOf(meta.getColumnType(loop));
         m_meta.put(name, type);
      }
   }

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


Question:
Operates exactly as {@link #set(int, java.lang.Double) }
@param index the index to set
@param element the value to set
@return the previous value at said index

public double set(int index, double element)
    {
        boundsCheck(index);
        double ret = get(index);
        array[index] = element;
        return ret;
    }

public CachedResultSet putResultSet(String name, CachedResultSet rs) {
        return _rsets.put(name, rs);
    }

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


Question:
Push a raw payload onto the queue.

@param  string  $payload
@param  string  $queue
@param  array   $options
@return mixed

public function pushRaw($payload, $queue = null, array $options = array())
	{
		return $this->pheanstalk->useTube($this->getQueue($queue))->put($payload);
	}

def add_arguments(cls, subparsers, dirs):

        parser = subparsers.add_parser(
            'packet',
            help='Packet Bare Metal',
            formatter_class=lambda prog: argparse.ArgumentDefaultsHelpFormatter(prog, max_help_position=40, width=120))

        m = parser.add_argument_group('Mandatory Packet Parameters') # pylint: disable=invalid-name

        g = m.add_mutually_exclusive_group(required=False) # pylint: disable=invalid-name
        g.add_argument('-create-demand',
                       action='store_true',
                       help='Create an on demand based bare metal device instance.')

        g.add_argument('-create-spot',
                       action='store_true',
                       help='Create a spot price based bare metal device instance.')

        g.add_argument('-reboot',
                       nargs='?',
                       const=-1,
                       metavar='n',
                       help='Reboot active instances.')

        g.add_argument('-stop',
                       nargs='?',
                       const=-1,
                       metavar='n',
                       help='Stop active instances.')

        g.add_argument('-terminate',
                       nargs='?',
                       const=-1,
                       metavar='n',
                       help='Terminate active instances.')

        o = parser.add_argument_group('Optional Parameters') # pylint: disable=invalid-name
        o.add_argument('-create-volume',
                       nargs='+',
                       type=str,
                       metavar='s',
                       help='Create storage: <plan> <size> <region> <description>')

        o.add_argument('-conf',
                       metavar='path',
                       type=argparse.FileType(),
                       default=os.path.join(dirs.user_config_dir, 'examples', 'packet', 'packet.json'),
                       help='Packet configuration')

        o.add_argument('-list-projects',
                       action='store_true',
                       help='List available projects.')

        o.add_argument('-list-plans',
                       action='store_true',
                       help='List available plans.')

        o.add_argument('-list-operating-systems',
                       action='store_true',
                       help='List available operating systems.')

        o.add_argument('-list-spot-prices',
                       action='store_true',
                       help='List spot prices.')

        o.add_argument('-list-facilities',
                       action='store_true',
                       help='List available facilities.')

        o.add_argument('-list-devices',
                       action='store_true',
                       help='List devices under given project name.')

        o.add_argument('-project',
                       metavar='project',
                       type=str,
                       default='fuzzing',
                       help='The project to perform operations on.')
        o.add_argument('-tags',
                       metavar='seq',
                       nargs='+',
                       type=str,
                       help='Tags associated with the instance.')
        o.add_argument('-region',
                       metavar='region',
                       type=str,
                       default='nrt1',
                       help='The facility in which the instance is going to run.')
        o.add_argument('-os',
                       metavar='name',
                       type=str,
                       default='ubuntu_18_04',
                       help='The operating system for the created instance.')
        o.add_argument('-plan',
                       metavar='name',
                       type=str,
                       default='baremetal_0',
                       help='The instance type to run.')
        o.add_argument('-max-spot-price',
                       metavar='#',
                       type=float,
                       default='0.05',
                       help='Max price for spot instances.')
        o.add_argument('-count',
                       metavar='#',
                       type=int,
                       default='1',
                       help='The amount of devices to be spawned.')
        o.add_argument('-only',
                       metavar='k=v',
                       nargs='+',
                       type=str,
                       help='Filter instances by criterias.')
        o.add_argument('-version',
                       action='version',
                       version='%(prog)s {}'.format(cls.VERSION),
                       help=argparse.SUPPRESS)

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


Question:
Returns transcript format.

    Arguments:
        transcript_content (str): Transcript file content.

def get_transcript_format(transcript_content):

    try:
        sjson_obj = json.loads(transcript_content)
    except ValueError:
        # With error handling (set to 'ERROR_RAISE'), we will be getting
        # the exception if something went wrong in parsing the transcript.
        srt_subs = SubRipFile.from_string(transcript_content, error_handling=SubRipFile.ERROR_RAISE)
        if len(srt_subs) > 0:
            return TranscriptFormat.SRT
    return TranscriptFormat.SJSON

def create_transient_document(file_name, mime_type, file_handle)
      transient_document_response = Echochamber::Request.create_transient_document(token, file_name, file_handle, mime_type)
      transient_document_response.fetch("transientDocumentId")
    end

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


Question: Make the rule fail if an escape char was found

function hasEscapeFirst (data, offset) {
    isBuffer = (!isQuiet && typeof data !== 'string')
    escaped = (this.prev.idx > 0)

    return escaped
      ? ( escapeOffset = offset - escLength, -1 )
      //HACK to bypass the trimLeft/trimRight properties
      : ( this.prev.prev.length = leftLength + 1, atok.offset--, 1 )
  }

public function rsyncValidate(CommandData $commandData) {
    if (preg_match("/^@prod/", $commandData->input()->getArgument('target'))) {
      throw new \Exception(dt('Per !file, you may never rsync to the production site.', ['!file' => __FILE__]));
    }
  }

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


Question:
Simple test for pcap magic bytes in supplied file.

    :param pcap: File path to Pcap file to check
    :returns: True if content is pcap (magic bytes present), otherwise False.

def is_pcap(pcap):

    with open(pcap, 'rb') as tmp:
        header = tmp.read(4)
        # check for both big/little endian
        if header == b"\xa1\xb2\xc3\xd4" or \
           header == b"\xd4\xc3\xb2\xa1":
            return True
        return False

public void marshall(Tape tape, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(tape.getTapeARN(), TAPEARN_BINDING);
            protocolMarshaller.marshall(tape.getTapeBarcode(), TAPEBARCODE_BINDING);
            protocolMarshaller.marshall(tape.getTapeCreatedDate(), TAPECREATEDDATE_BINDING);
            protocolMarshaller.marshall(tape.getTapeSizeInBytes(), TAPESIZEINBYTES_BINDING);
            protocolMarshaller.marshall(tape.getTapeStatus(), TAPESTATUS_BINDING);
            protocolMarshaller.marshall(tape.getVTLDevice(), VTLDEVICE_BINDING);
            protocolMarshaller.marshall(tape.getProgress(), PROGRESS_BINDING);
            protocolMarshaller.marshall(tape.getTapeUsedInBytes(), TAPEUSEDINBYTES_BINDING);
            protocolMarshaller.marshall(tape.getKMSKey(), KMSKEY_BINDING);
            protocolMarshaller.marshall(tape.getPoolId(), POOLID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Call a modifier from widget
@param {number} index
@param {?Array.<*>} arguments_array
@returns {*}

function(index, arguments_array) {

		return this._modifier_descriptors[index].widget.callModifier(this._modifier_descriptors[index].callback_name, arguments_array);

	}

public function setModel($model, $ids = [])
    {
        $this->model = $model;
        $this->ids = Arr::wrap($ids);

        $this->message = "No query results for model [{$model}]";

        if (count($this->ids) > 0) {
            $this->message .= ' '.implode(', ', $this->ids);
        } else {
            $this->message .= '.';
        }

        return $this;
    }

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


Question:
Returns the raw text content of a given VFS resource containing HTML data.<p>

@see org.opencms.search.documents.I_CmsSearchExtractor#extractContent(CmsObject, CmsResource, I_CmsSearchIndex)

public I_CmsExtractionResult extractContent(CmsObject cms, CmsResource resource, I_CmsSearchIndex index)
    throws CmsIndexException, CmsException {

        logContentExtraction(resource, index);
        CmsFile file = readFile(cms, resource);
        try {
            CmsProperty encProp = cms.readPropertyObject(
                resource,
                CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING,
                true);
            String encoding = encProp.getValue(OpenCms.getSystemInfo().getDefaultEncoding());
            return CmsExtractorHtml.getExtractor().extractText(file.getContents(), encoding);
        } catch (Exception e) {
            throw new CmsIndexException(
                Messages.get().container(Messages.ERR_TEXT_EXTRACTION_1, resource.getRootPath()),
                e);
        }
    }

public function extractText($sKey, $mValue)
    {
        $oCdn = Factory::service('Cdn', 'nails/module-cdn');
        $oObj = $oCdn->getObject($mValue);

        $sOut = $oObj->file->name->human . ' (' . $oObj->file->size->human . ')';
        $sOut .= 'id, true) . '" class="btn btn-xs btn-primary pull-right">Download';

        return $sOut;
    }

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


Question: Use this API to fetch the statistics of all authorizationpolicylabel_stats resources that are configured on netscaler.

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

def get_token(self):
        """"""
        signed_headers = self._get_v4_signed_headers()
        for header in self.HEADERS:
            signed_headers[header] = self.HEADERS[header]

        resp = post_with_retry(self.cerberus_url + '/v2/auth/sts-identity', headers=signed_headers)
        throw_if_bad_response(resp)

        token = resp.json()['client_token']
        iam_principal_arn = resp.json()['metadata']['aws_iam_principal_arn']
        if self.verbose:
            print('Successfully authenticated with Cerberus as {}'.format(iam_principal_arn), file=sys.stderr)
        logger.info('Successfully authenticated with Cerberus as {}'.format(iam_principal_arn))

        return token

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


Question:
Check a filter for a match

@param \Gems\Agenda\Gems_Agenda_Appointment $appointment
@return boolean

public function matchAppointment(\Gems_Agenda_Appointment $appointment)
    {
        if (true !== $this->_locations) {
            if (isset($this->_locations[$appointment->getLocationId()])) {
                return true;
            }
        }
        return false;
    }

public function index() {
		if (Configure::read('Queue.isSearchEnabled') !== false && Plugin::isLoaded('Search')) {
			$query = $this->QueuedJobs->find('search', ['search' => $this->request->getQuery()]);
		} else {
			$query = $this->QueuedJobs->find();
		}
		$queuedJobs = $this->paginate($query);

		$this->set(compact('queuedJobs'));
		$this->helpers[] = 'Tools.Format';
		$this->helpers[] = 'Tools.Time';
		$this->helpers[] = 'Shim.Configure';

		if (Configure::read('Queue.isSearchEnabled') !== false && Plugin::isLoaded('Search')) {
			$jobTypes = $this->QueuedJobs->find()->where()->find('list', ['keyField' => 'job_type', 'valueField' => 'job_type'])->distinct('job_type')->toArray();
			$this->set(compact('jobTypes'));
		}
	}

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


Question:
Gets allowable values of the enum
@return string[]

public function getLocationFlagAllowableValues()
    {
        return [
            self::LOCATION_FLAG_AUTO_FIT,
            self::LOCATION_FLAG_CARGO,
            self::LOCATION_FLAG_CORPSE_BAY,
            self::LOCATION_FLAG_DRONE_BAY,
            self::LOCATION_FLAG_FLEET_HANGAR,
            self::LOCATION_FLAG_DELIVERIES,
            self::LOCATION_FLAG_HIDDEN_MODIFIERS,
            self::LOCATION_FLAG_HANGAR,
            self::LOCATION_FLAG_HANGAR_ALL,
            self::LOCATION_FLAG_LO_SLOT0,
            self::LOCATION_FLAG_LO_SLOT1,
            self::LOCATION_FLAG_LO_SLOT2,
            self::LOCATION_FLAG_LO_SLOT3,
            self::LOCATION_FLAG_LO_SLOT4,
            self::LOCATION_FLAG_LO_SLOT5,
            self::LOCATION_FLAG_LO_SLOT6,
            self::LOCATION_FLAG_LO_SLOT7,
            self::LOCATION_FLAG_MED_SLOT0,
            self::LOCATION_FLAG_MED_SLOT1,
            self::LOCATION_FLAG_MED_SLOT2,
            self::LOCATION_FLAG_MED_SLOT3,
            self::LOCATION_FLAG_MED_SLOT4,
            self::LOCATION_FLAG_MED_SLOT5,
            self::LOCATION_FLAG_MED_SLOT6,
            self::LOCATION_FLAG_MED_SLOT7,
            self::LOCATION_FLAG_HI_SLOT0,
            self::LOCATION_FLAG_HI_SLOT1,
            self::LOCATION_FLAG_HI_SLOT2,
            self::LOCATION_FLAG_HI_SLOT3,
            self::LOCATION_FLAG_HI_SLOT4,
            self::LOCATION_FLAG_HI_SLOT5,
            self::LOCATION_FLAG_HI_SLOT6,
            self::LOCATION_FLAG_HI_SLOT7,
            self::LOCATION_FLAG_ASSET_SAFETY,
            self::LOCATION_FLAG_LOCKED,
            self::LOCATION_FLAG_UNLOCKED,
            self::LOCATION_FLAG_IMPLANT,
            self::LOCATION_FLAG_QUAFE_BAY,
            self::LOCATION_FLAG_RIG_SLOT0,
            self::LOCATION_FLAG_RIG_SLOT1,
            self::LOCATION_FLAG_RIG_SLOT2,
            self::LOCATION_FLAG_RIG_SLOT3,
            self::LOCATION_FLAG_RIG_SLOT4,
            self::LOCATION_FLAG_RIG_SLOT5,
            self::LOCATION_FLAG_RIG_SLOT6,
            self::LOCATION_FLAG_RIG_SLOT7,
            self::LOCATION_FLAG_SHIP_HANGAR,
            self::LOCATION_FLAG_SPECIALIZED_FUEL_BAY,
            self::LOCATION_FLAG_SPECIALIZED_ORE_HOLD,
            self::LOCATION_FLAG_SPECIALIZED_GAS_HOLD,
            self::LOCATION_FLAG_SPECIALIZED_MINERAL_HOLD,
            self::LOCATION_FLAG_SPECIALIZED_SALVAGE_HOLD,
            self::LOCATION_FLAG_SPECIALIZED_SHIP_HOLD,
            self::LOCATION_FLAG_SPECIALIZED_SMALL_SHIP_HOLD,
            self::LOCATION_FLAG_SPECIALIZED_MEDIUM_SHIP_HOLD,
            self::LOCATION_FLAG_SPECIALIZED_LARGE_SHIP_HOLD,
            self::LOCATION_FLAG_SPECIALIZED_INDUSTRIAL_SHIP_HOLD,
            self::LOCATION_FLAG_SPECIALIZED_AMMO_HOLD,
            self::LOCATION_FLAG_SPECIALIZED_COMMAND_CENTER_HOLD,
            self::LOCATION_FLAG_SPECIALIZED_PLANETARY_COMMODITIES_HOLD,
            self::LOCATION_FLAG_SPECIALIZED_MATERIAL_BAY,
            self::LOCATION_FLAG_SUB_SYSTEM_SLOT0,
            self::LOCATION_FLAG_SUB_SYSTEM_SLOT1,
            self::LOCATION_FLAG_SUB_SYSTEM_SLOT2,
            self::LOCATION_FLAG_SUB_SYSTEM_SLOT3,
            self::LOCATION_FLAG_SUB_SYSTEM_SLOT4,
            self::LOCATION_FLAG_SUB_SYSTEM_SLOT5,
            self::LOCATION_FLAG_SUB_SYSTEM_SLOT6,
            self::LOCATION_FLAG_SUB_SYSTEM_SLOT7,
            self::LOCATION_FLAG_FIGHTER_BAY,
            self::LOCATION_FLAG_FIGHTER_TUBE0,
            self::LOCATION_FLAG_FIGHTER_TUBE1,
            self::LOCATION_FLAG_FIGHTER_TUBE2,
            self::LOCATION_FLAG_FIGHTER_TUBE3,
            self::LOCATION_FLAG_FIGHTER_TUBE4,
            self::LOCATION_FLAG_MODULE,
        ];
    }

function yy_r130()
    {
        $this->_retvalue = '[' . $this->compiler->compileTag('private_special_variable', array(), '[\'section\'][\'' .
                                                                                $this->yystack[ $this->yyidx +
                                                                                - 1 ]->minor .
                                                                                '\'][\'index\']') . ']';
    }

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


Question:
Execute the console command.

@return void

@throws \RuntimeException

public function fire()
	{
		$iron = $this->laravel['queue']->connection();

		if ( ! $iron instanceof IronQueue)
		{
			throw new RuntimeException("Iron.io based queue must be default.");
		}

		$iron->getIron()->updateQueue($this->argument('queue'), $this->getQueueOptions());

		$this->line('<info>Queue subscriber added:</info> <comment>'.$this->argument('url').'</comment>');
	}

func (c *Subcommand) printError(err error) {
	if _, ok := err.(CommandLineError); ok {
		fmt.Fprintf(os.Stderr, "Bad command line: %s.\n\n", err)
		c.Flags.Usage()
	} else {
		os.Stderr.WriteString(strings.Join(CollectErrorMessages(err, nil), "\n"))
		os.Stderr.WriteString("\n")
	}
}

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


Question:
Multibyte version of ucfirst()
@since 2.0.6

protected static function mbUcFirst($string)
    {
        $firstChar = mb_strtoupper(mb_substr($string, 0, 1, 'utf-8'), 'utf-8');
        return $firstChar . mb_substr($string, 1, mb_strlen($string, 'utf-8'), 'utf-8');
    }

def content_encoding
      if content_type = headers["content-type"]
        mime_type, charset = content_type.split(SEMICOLON, 2)
        charset = charset[CHARSET_OFFSET] if charset
        charset ||= EMPTY

        if charset.empty? and mime_type.start_with?("text/")
          Encoding::UTF_8
        elsif charset.empty?
          Encoding::BINARY
        else
          ENCODINGS[charset] or raise StompParser::InvalidEncodingError, "invalid encoding #{charset.inspect}"
        end
      else
        Encoding::BINARY
      end
    end

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


Question:
Returns the SQLAlchemy :class:`IdentifierPreparer` in use for the dialect
    being used.

    Args:
        mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
            :class:`Dialect` object

    Returns: an :class:`IdentifierPreparer`

def get_preparer(mixed: Union[SQLCompiler, Engine,
                              Dialect]) -> IdentifierPreparer:

    dialect = get_dialect(mixed)
    # noinspection PyUnresolvedReferences
    return dialect.preparer(dialect)

protected function registerClassAliases()
    {
        $serviceAliases = [
            \Dingo\Api\Http\Request::class => \Dingo\Api\Contract\Http\Request::class,
            'api.dispatcher' => \Dingo\Api\Dispatcher::class,
            'api.http.validator' => \Dingo\Api\Http\RequestValidator::class,
            'api.http.response' => \Dingo\Api\Http\Response\Factory::class,
            'api.router' => \Dingo\Api\Routing\Router::class,
            'api.router.adapter' => \Dingo\Api\Contract\Routing\Adapter::class,
            'api.auth' => \Dingo\Api\Auth\Auth::class,
            'api.limiting' => \Dingo\Api\Http\RateLimit\Handler::class,
            'api.transformer' => \Dingo\Api\Transformer\Factory::class,
            'api.url' => \Dingo\Api\Routing\UrlGenerator::class,
            'api.exception' => [\Dingo\Api\Exception\Handler::class, \Dingo\Api\Contract\Debug\ExceptionHandler::class],
        ];

        foreach ($serviceAliases as $key => $aliases) {
            foreach ((array) $aliases as $alias) {
                $this->app->alias($key, $alias);
            }
        }
    }

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


Question:
Adds the.

@param array the array
@param v the v
@return the byte[]

public static byte[] add(byte[] array, byte v) {
		byte[] newArray = new byte[array.length + 1];
		System.arraycopy(array, 0, newArray, 0, array.length);
		newArray[array.length] = v;
		return newArray;
	}

public Metadata readNextMetadata() throws IOException {
        Metadata metadata = null;

        boolean isLast = (bitStream.readRawUInt(Metadata.STREAM_METADATA_IS_LAST_LEN) != 0);
        int type = bitStream.readRawUInt(Metadata.STREAM_METADATA_TYPE_LEN);
        int length = bitStream.readRawUInt(Metadata.STREAM_METADATA_LENGTH_LEN);

        if (type == Metadata.METADATA_TYPE_STREAMINFO) {
        	metadata = streamInfo = new StreamInfo(bitStream, length, isLast);
            pcmProcessors.processStreamInfo((StreamInfo)metadata);
        } else if (type == Metadata.METADATA_TYPE_SEEKTABLE) {
        	metadata = seekTable = new SeekTable(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_APPLICATION) {
            metadata = new Application(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_PADDING) {
            metadata = new Padding(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_VORBIS_COMMENT) {
            metadata = vorbisComment = new VorbisComment(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_CUESHEET) {
	    metadata = new CueSheet(bitStream, length, isLast);
	} else if (type == Metadata.METADATA_TYPE_PICTURE) {
	    metadata = new Picture(bitStream, length, isLast);
        } else {
            metadata = new Unknown(bitStream, length, isLast);
        }
        frameListeners.processMetadata(metadata);
        //if (isLast) state = DECODER_SEARCH_FOR_FRAME_SYNC;
        return metadata;
    }

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


Question: Returns true if this stream was closed.

private boolean closeInternal(ErrorCode errorCode, @Nullable IOException errorException) {
    assert (!Thread.holdsLock(this));
    synchronized (this) {
      if (this.errorCode != null) {
        return false;
      }
      if (source.finished && sink.finished) {
        return false;
      }
      this.errorCode = errorCode;
      this.errorException = errorException;
      notifyAll();
    }
    connection.removeStream(id);
    return true;
  }

private function readPipesForOutput($caller, $blocking = false)
    {
        if ($this->outputDisabled) {
            throw new LogicException('Output has been disabled.');
        }

        $this->requireProcessIsStarted($caller);

        $this->updateStatus($blocking);
    }

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