Question: Converts a SAT.Polygon into a SVG path string.

function poly2path(polygon) {
  var pos = polygon.pos;
  var points = polygon.calcPoints;
  var result = 'M' + pos.x + ' ' + pos.y;
  result += 'M' + (pos.x + points[0].x) + ' ' + (pos.y + points[0].y);
  for (var i = 1; i < points.length; i++) {
    var point = points[i];
    result += 'L' + (pos.x + point.x) + ' ' + (pos.y + point.y);
  }
  result += 'Z';
  return result;
}

@Inline(value = "translate($1, null, $2, $3)")
	public void translate(List<? extends S> thePath, double curvilineCoord, double shiftCoord) {
		translate(thePath, null, curvilineCoord, shiftCoord);
	}

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


Question:
Gets the internationalized value for the supplied message key, using a file array as additional information.

@param aMessageKey A message key
@param aFileArray Additional details for the message
@return The internationalized message

protected String getI18n(final String aMessageKey, final File... aFileArray) {
        final String[] fileNames = new String[aFileArray.length];

        for (int index = 0; index < fileNames.length; index++) {
            fileNames[index] = aFileArray[index].getAbsolutePath();
        }

        return StringUtils.normalizeWS(myBundle.get(aMessageKey, fileNames));
    }

private static HashMap<String, String> loadMappings() {

        HashMap<String, String> mimeTypeToExtensionMap =
                new HashMap<String, String>();

        // First, check the user's home directory.

        String fileSep = System.getProperty("file.separator");
        StringBuffer buf = new StringBuffer();

        buf.append(System.getProperty("user.home"));
        buf.append(fileSep);
        buf.append(".mime.types");

        loadMIMETypesFile(buf.toString());

        // Now, check every directory in the classpath.

        String pathSep = System.getProperty("path.separator");
        String[] pathComponents = pathSep.split(" ");
        int i;

        for (i = 0; i < pathComponents.length; i++) {
            buf.setLength(0);
            buf.append(pathComponents[i]);
            buf.append(fileSep);
            buf.append("mime.types");

            loadMIMETypesFile(buf.toString());
        }

        // Finally, load the resource bundle.

        ResourceBundle bundle = ResourceBundle.getBundle(MIME_MAPPINGS_BUNDLE);
        for (Enumeration<?> e = bundle.getKeys(); e.hasMoreElements();) {
            String type = (String) e.nextElement();
            try {
                String[] extensions = bundle.getString(type).split(" ");

                if (mimeTypeToExtensionMap.get(type) == null) {
                    logger.debug("Internal: " + type + " -> \"" + extensions[0]
                            + "\"");
                    mimeTypeToExtensionMap.put(type, extensions[0]);
                }
            }

            catch (MissingResourceException ex) {
                logger.error("While reading internal bundle \""
                                  + MIME_MAPPINGS_BUNDLE
                                  + "\", got unexpected error on key \"" + type
                                  + "\"",
                          ex);
            }
        }
        return mimeTypeToExtensionMap;
    }

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


Question:
trim every single item of the array

@param arr
@return

public static String[] trimItems(String[] arr) {
	for (int i = 0; i < arr.length; i++) {
	    arr[i] = arr[i].trim();
	}
	return arr;
    }

def adapt_step_table!(parsed_step_table)
      # Saving off the original data
      parsed_step_table['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_step_table))

      # Removing parsed data for child elements in order to avoid duplicating data
      parsed_step_table['cuke_modeler_parsing_data'][:rows] = nil

      parsed_step_table['rows'] = []
      parsed_step_table[:rows].each do |row|
        adapt_table_row!(row)
      end
      parsed_step_table['rows'].concat(parsed_step_table.delete(:rows))
      parsed_step_table['line'] = parsed_step_table.delete(:location)[:line]
    end

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


Question:
Remove an XBPS repository from the system.

    repo
        url of repo to remove (persistent).

    CLI Examples:

    .. code-block:: bash

        salt '*' pkg.del_repo <repo url>

def del_repo(repo, **kwargs):
    '''

    '''

    try:
        _locate_repo_files(repo, rewrite=True)
    except IOError:
        return False
    else:
        return True

func (s *Action) History(ctx context.Context, c *cli.Context) error {
	name := c.Args().Get(0)
	showPassword := c.Bool("password")

	if name == "" {
		return ExitError(ctx, ExitUsage, nil, "Usage: %s history <NAME>", s.Name)
	}

	if !s.Store.Exists(ctx, name) {
		return ExitError(ctx, ExitNotFound, nil, "Secret not found")
	}

	revs, err := s.Store.ListRevisions(ctx, name)
	if err != nil {
		return ExitError(ctx, ExitUnknown, err, "Failed to get revisions: %s", err)
	}

	for _, rev := range revs {
		pw := ""
		if showPassword {
			sec, err := s.Store.GetRevision(ctx, name, rev.Hash)
			if err != nil {
				out.Debug(ctx, "Failed to get revision '%s' of '%s': %s", rev.Hash, name, err)
			}
			if err == nil {
				pw = " - " + sec.Password()
			}
		}
		out.Print(ctx, "%s - %s <%s> - %s - %s%s", rev.Hash[:8], rev.AuthorName, rev.AuthorEmail, rev.Date.Format(time.RFC3339), rev.Subject, pw)
	}
	return nil
}

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


Question:
// MaxFlow computes a maximum flow from s to t in a graph
// with nonnegative edge capacities.
// The time complexity is O(|E|²⋅|V|), where |E| is the number of edges
// and |V| the number of vertices in the graph.

func MaxFlow(g Iterator, s, t int) (flow int64, graph Iterator) {
	// Edmonds-Karp's algorithm
	n := g.Order()
	prev := make([]int, n)
	residual := Copy(g)
	for residualFlow(residual, s, t, prev) && flow < Max {
		pathFlow := Max
		for v := t; v != s; {
			u := prev[v]
			if c := residual.Cost(u, v); c < pathFlow {
				pathFlow = c
			}
			v = u
		}
		flow += pathFlow
		for v := t; v != s; {
			u := prev[v]
			residual.AddCost(u, v, residual.Cost(u, v)-pathFlow)
			residual.AddCost(v, u, residual.Cost(v, u)+pathFlow)
			v = u
		}
	}
	res := New(n)
	for v := 0; v < n; v++ {
		g.Visit(v, func(w int, c int64) (skip bool) {
			if flow := c - residual.Cost(v, w); flow > 0 {
				res.AddCost(v, w, flow)
			}
			return
		})
	}
	return flow, Sort(res)
}

private void visit(final ObjectGraphNode currentNode) {
		Object currentValue = currentNode.getValue();

		if (currentValue == null
				|| (currentValue instanceof java.lang.ref.SoftReference)
				|| currentNode.isPrimitive() || currentNode.isSimpleType()) {
			return;
		}

		if (isObjectVisited(currentNode)) {
			ObjectGraphNode ref = visitedNodes.get(currentValue);
			currentNode.setRefNode(ref);
			return;
		}

		markObjectVisited(currentNode);

		if (currentValue instanceof List) {
			// ArrayList's elementData is marked transient, and others may be as well, so we have to do this ourselves.
			visitList(currentNode);
		} else if (currentValue instanceof Map) {
			// HashMap's table is marked transient, and others may be as well, so we have to do this ourselves.
			visitMap(currentNode);
		} else if (currentValue instanceof ComponentModel) {
			// Special case for ComponentModel, so we can figure out if any fields are overridden
			visitComponentModel(currentNode);
		} else if (currentValue instanceof Field) {
			visitComplexType(currentNode);
			summariseNode(currentNode);
		} else if (currentValue.getClass().isArray()) {
			visitArray(currentNode);
		} else {
			visitComplexType(currentNode);
		}
	}

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


Question:
Get the number of times a string s appears in the node e.

@param Element
@param string - what to split on. Default is ","
@return number (integer)

function getCharCount(e, s) {
  s = s || ",";
  return getInnerText(e).split(s).length;
}

function readString(walker) {
    var startCode = walker.currentCode();
    var startIndex = walker.index;
    var charCode;

    walkLoop: while ((charCode = walker.nextCode())) {
        switch (charCode) {
            case 92: // \
                walker.go(1);
                break;
            case startCode:
                walker.go(1);
                break walkLoop;
        }
    }

    var literal = walker.cut(startIndex, walker.index);
    return {
        type: ExprType.STRING,
        // 处理字符转义
        value: (new Function('return ' + literal))()
    };
}

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


Question: // SetRepository sets the Repository field's value.

func (s *CreateRepositoryOutput) SetRepository(v *Repository) *CreateRepositoryOutput {
	s.Repository = v
	return s
}

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

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


Question:
Check if this object still exists in DB as record. Return TRUE if exists.

@return	bool

final public function existsInDb() {

		$class = get_called_class();
		$conds = implode(' AND ', $this->getSqlKeyConditions());

		$this->db->setQuery('SELECT COUNT(1) FROM `' . $class::TABLE_NAME . '` WHERE ' . $conds);

		return (bool)$this->db->loadCount($this->getId());

	}

func QueryNotFound(t *testing.T, repo grimoire.Repo) {
	t.Run("NotFound", func(t *testing.T) {
		user := User{}

		// find user error not found
		err := repo.From("users").Find(0).One(&user)
		assert.NotNil(t, err)
		assert.Equal(t, errors.NotFound, err.(errors.Error).Kind())
	})
}

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


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

public EClass getIfcHeatingValueMeasure() {
		if (ifcHeatingValueMeasureEClass == null) {
			ifcHeatingValueMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
					.getEClassifiers().get(683);
		}
		return ifcHeatingValueMeasureEClass;
	}

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: Get preferred host from DNS results.

def _get_preferred_host(self, result: ResolveResult) -> Tuple[str, str]:
        ''''''
        host_1 = result.first_ipv4.ip_address if result.first_ipv4 else None
        host_2 = result.first_ipv6.ip_address if result.first_ipv6 else None

        if not host_2:
            return host_1, None
        elif not host_1:
            return host_2, None

        preferred_host = self._happy_eyeballs_table.get_preferred(
            host_1, host_2)

        if preferred_host:
            return preferred_host, None
        else:
            return host_1, host_2

func (c *ConsulBackend) DetectHostAddr() (string, error) {
	agent := c.client.Agent()
	self, err := agent.Self()
	if err != nil {
		return "", err
	}
	addr, ok := self["Member"]["Addr"].(string)
	if !ok {
		return "", fmt.Errorf("unable to convert an address to string")
	}
	return addr, nil
}

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


Question:
// getSubnetInfoAsMap will return the subnet information
// for the getSubnetInfo as a map rather than a slice

func (e Environ) getSubnetInfoAsMap() (map[string]network.SubnetInfo, error) {
	subnets, err := e.getSubnetInfo()
	if err != nil {
		return nil, err
	}
	ret := make(map[string]network.SubnetInfo, len(subnets))
	for _, val := range subnets {
		ret[string(val.ProviderId)] = val
	}
	return ret, nil
}

func addBgp(ctx *cli.Context) {
	if len(ctx.Args()) < 1 {
		errExit(ctx, exitHelp, "Host name required", true)
	}

	hostname := ctx.Args()[0]
	routerip := ctx.String("router-ip")
	asid := ctx.String("as")
	neighboras := ctx.String("neighbor-as")
	neighbor := ctx.String("neighbor")

	//Error checks
	_, _, err := net.ParseCIDR(routerip)
	if err != nil {
		errExit(ctx, exitHelp, "Wrong CIDR format. Enter in x.x.x.x/len format", true)
	}

	ip := net.ParseIP(neighbor)
	if ip == nil {
		errExit(ctx, exitHelp, "Wrong IP format. Enter in x.x.x.x format", true)
	}

	if routerip == "" || asid == "" || neighbor == "" || neighboras == "" {
		errExit(ctx, exitHelp, "Missing attributes", true)
	}

	errCheck(ctx, getClient(ctx).BgpPost(&contivClient.Bgp{
		As:         asid,
		Hostname:   hostname,
		Neighbor:   neighbor,
		NeighborAs: neighboras,
		Routerip:   routerip,
	}))

}

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


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

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

def _get_token_from_query_string(self, request, refresh_token):

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

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


Question:
For MemoryObjectstore there is nothing to do.

@see com.ibm.ws.objectManager.ObjectStore#flush()

public synchronized void flush()
                    throws ObjectManagerException
    {
        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) {
            trace.entry(this,
                        cclass,
                        "flush");
            trace.exit(this,
                       cclass,
                       "flush");
        }
    }

def reset(self):

        self.indexCount = 0
        indexDir = self.store.newDirectory(self.indexDirectory)
        if indexDir.exists():
            indexDir.remove()
        for src in self.getSources():
            src.removeReliableListener(self)
            src.addReliableListener(self, style=iaxiom.REMOTE)

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


Question: Collapse comment beloging to user.

def collapse(self, id_user):
        """"""
        c = CmtCOLLAPSED(id_bibrec=self.id_bibrec, id_cmtRECORDCOMMENT=self.id,
                         id_user=id_user)
        db.session.add(c)
        db.session.commit()

function changeAnnotationState(combo, username) {
    combo.annotations.forEach(function(anno) {
      anno.state = combo.state;
    });

    contentLib.indexContentItem({uri: combo.uri}, { member: username , annotations: combo.annotations} );
  }

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


Question: Cancel a job by id

def cancel(id)
      Log.warn "Cancelling job id #{id}"
      job = @jobs_by_id[id]
      job.status = Executor::STATUS_ERROR
      job.owner = nil
      job.time_end = Time.now
      @queue.delete(job)
    end

func (s *TasksCancelService) TaskId(taskId string) *TasksCancelService {
	s.taskId = taskId
	return s
}

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


Question: convert a transcript (n.) interval to a genomic (g.) interval

def n_to_g(self, n_interval):
        """"""

        frs, fre = n_interval.start.base - 1, n_interval.end.base - 1
        start_offset, end_offset = n_interval.start.offset, n_interval.end.offset

        if self.strand == -1:
            fre, frs = self.tgt_len - frs - 1, self.tgt_len - fre - 1
            start_offset, end_offset = -end_offset, -start_offset

        # returns the genomic range start (grs) and end (gre)
        grs, _, grs_cigar = self._map(
            from_pos=self.tgt_pos, to_pos=self.ref_pos, pos=frs, base="start")
        gre, _, gre_cigar = self._map(
            from_pos=self.tgt_pos, to_pos=self.ref_pos, pos=fre, base="end")
        grs, gre = grs + self.gc_offset + 1, gre + self.gc_offset + 1
        gs, ge = grs + start_offset, gre + end_offset

        # The returned interval would be uncertain when locating at alignment gaps
        return hgvs.location.Interval(
            start=hgvs.location.SimplePosition(gs, uncertain=n_interval.start.uncertain),
            end=hgvs.location.SimplePosition(ge, uncertain=n_interval.end.uncertain),
            uncertain=grs_cigar in 'DI' or gre_cigar in 'DI')

def update(gandi, fqdn, name, type, value, ttl, file):

    domains = gandi.dns.list()
    domains = [domain['fqdn'] for domain in domains]
    if fqdn not in domains:
        gandi.echo('Sorry domain %s does not exist' % fqdn)
        gandi.echo('Please use one of the following: %s' % ', '.join(domains))
        return

    content = ''
    if file:
        content = file.read()
    elif not sys.stdin.isatty():
        content = click.get_text_stream('stdin').read()

    content = content.strip()
    if not content and not name and not type and not value:
        click.echo('Cannot find parameters for zone content to update.')
        return

    if name and type and not value:
        click.echo('You must provide one or more value parameter.')
        return

    result = gandi.dns.update_record(fqdn, name, type, value, ttl, content)
    gandi.echo(result['message'])

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


Question:
Attempt to get provisioning state from resource.
        :param requests.Response response: latest REST call response.
        :returns: Status if found, else 'None'.

def _get_provisioning_state(self, response):

        if self._is_empty(response):
            return None
        body = response.json()
        return body.get("properties", {}).get("provisioningState")

func (api *API) ZoneRailgunDetails(zoneID, railgunID string) (ZoneRailgun, error) {
	uri := "/zones/" + zoneID + "/railguns/" + railgunID
	res, err := api.makeRequest("GET", uri, nil)
	if err != nil {
		return ZoneRailgun{}, errors.Wrap(err, errMakeRequestError)
	}
	var r zoneRailgunResponse
	if err := json.Unmarshal(res, &r); err != nil {
		return ZoneRailgun{}, errors.Wrap(err, errUnmarshalError)
	}
	return r.Result, nil
}

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


Question:
Format a path to be compared with another formatted path
Ouptut a path formatted like this : /lvl1/lvl2/lvl3/ (/ if no path)

@param string $path

@return string

protected function formatPath($path)
    {
        $path = trim($path, '/') . '/';
        if (strlen($path) > 1) {
            $path = '/' . $path;
        }

        return $path;
    }

protected function createFilepath(string $folder, string $filename): string
    {
        $separator = '';
        if (!\in_array($folder[-1], ['/', '\\'], true)) {
            $separator = \DIRECTORY_SEPARATOR;
        }

        return $folder . $separator . $filename;
    }

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


Question: // SetSubnetIds sets the SubnetIds field's value.

func (s *CreateCacheSubnetGroupInput) SetSubnetIds(v []*string) *CreateCacheSubnetGroupInput {
	s.SubnetIds = v
	return s
}

def enable(iface):
    '''

    '''
    if is_enabled(iface):
        return True
    cmd = ['netsh', 'interface', 'set', 'interface',
           'name={0}'.format(iface),
           'admin=ENABLED']
    __salt__['cmd.run'](cmd, python_shell=False)
    return is_enabled(iface)

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


Question:
Returns a formated time String from a Date value,
the formatting based on the provided options.<p>

@param date the Date object to format as String
@param format the format to use

@return the formatted time

public static String getTime(Date date, Format format) {

        DateTimeFormat df;
        switch (format) {
            case FULL:
                df = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.TIME_FULL);
                break;
            case LONG:
                df = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.TIME_LONG);
                break;
            case MEDIUM:
                df = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.TIME_MEDIUM);
                break;
            case SHORT:
                df = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.TIME_SHORT);
                break;
            default:
                // can never happen, just to prevent stupid warning
                return "";
        }
        return df.format(date);
    }

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

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

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

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

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

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

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

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

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

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

    return null;
  }

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


Question: // Equals compares two epochs and returns true if they refer to the same time period.

func (e *Epoch) Equals(epoch Epoch) bool {
	return e.Level == epoch.Level && e.Base() == epoch.Base()
}

function (x, y, settings) {
            /**
             * constant for the overlaps method
             * @public
             * @constant
             * @type String
             * @name CHECKMETHOD_OVERLAP
             * @memberOf me.DroptargetEntity
             */
            this.CHECKMETHOD_OVERLAP = "overlaps";
            /**
             * constant for the contains method
             * @public
             * @constant
             * @type String
             * @name CHECKMETHOD_CONTAINS
             * @memberOf me.DroptargetEntity
             */
            this.CHECKMETHOD_CONTAINS = "contains";
            /**
             * the checkmethod we want to use
             * @public
             * @constant
             * @type String
             * @name checkMethod
             * @memberOf me.DroptargetEntity
             */
            this.checkMethod = null;
            this._super(Entity, "init", [x, y, settings]);
            Event.subscribe(Event.DRAGEND, this.checkOnMe.bind(this));
            this.checkMethod = this[this.CHECKMETHOD_OVERLAP];
        }

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


Question: Test existence of a yield section

public function isYieldable($yield = self::DEFAULT_YIELD) {
		return (!empty($this->tpl['layout']['yields'][$yield]) && file_exists($this->getTemplatePath($this->tpl['layout']['yields'][$yield])));
	}

public function do_exists($key)
    {
        $context = $this->_context;

        return isset($context->data[$key]) && $context->data[$key]['deadline'] >= time();
    }

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


Question: // GetAllProvisionWatchers provides a mock function with given fields:

func (_m *DBClient) GetAllProvisionWatchers() ([]models.ProvisionWatcher, error) {
	ret := _m.Called()

	var r0 []models.ProvisionWatcher
	if rf, ok := ret.Get(0).(func() []models.ProvisionWatcher); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]models.ProvisionWatcher)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func() error); ok {
		r1 = rf()
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

func (mp *MultipointExample) Reserve(pc *framework.PluginContext, pod *v1.Pod, nodeName string) *framework.Status {
	mp.numRuns++
	return nil
}

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


Question: // SetResourceRole sets the ResourceRole field's value.

func (s *RDSDataSpec) SetResourceRole(v string) *RDSDataSpec {
	s.ResourceRole = &v
	return s
}

def up(self, role, root_priority, root_times):

        self.port_priority = root_priority
        self.port_times = root_times

        state = (PORT_STATE_LISTEN if self.config_enable
                 else PORT_STATE_DISABLE)
        self._change_role(role)
        self._change_status(state)

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


Question:
Check if the particular key exists in the storage

    :param key: name of the key which existence need to be checked
    :return:

    :type key str
    :rtype bool

def exists(self, key):

    if key in self._keystore and not self._keystore[key].is_expired:
      return True
    elif key in self._keystore and self._keystore[key].is_expired:
      self.delete(key)
      return False

    return False

public function getParameter( $parameter )
    {

        self::isParameterAllowed( $parameter );

        $value = $this->query(new Raw("SHOW {$parameter}"))->fetch( Result::FETCH_SINGLE );

        return ( $value === 'true' or $value === 'false' )
            ? \Bond\boolval( $value )
            : $value;

    }

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


Question:
// ParseBody performs protocol specific unmarshalling of the response data into the given result.
// If the given field is non-empty, the contents of that field will be parsed into the given result.

func (r *httpJSONResponse) ParseBody(field string, result interface{}) error {
	if r.bodyObject == nil {
		bodyMap := make(map[string]*json.RawMessage)
		if err := json.Unmarshal(r.rawResponse, &bodyMap); err != nil {
			return driver.WithStack(err)
		}
		r.bodyObject = bodyMap
	}
	if result != nil {
		if err := parseBody(r.bodyObject, field, result); err != nil {
			return driver.WithStack(err)
		}
	}
	return nil
}

func (h *handlerManager) DryUplink(ctx context.Context, in *pb.DryUplinkMessage) (*pb.DryUplinkResult, error) {
	app := in.App

	flds := ""
	valid := true
	var logs []*pb.LogEntry
	var decoder PayloadDecoder
	switch application.PayloadFormat(app.PayloadFormat) {
	case "", application.PayloadFormatCustom:
		decoder = &CustomUplinkFunctions{
			Decoder:   app.Decoder,
			Converter: app.Converter,
			Validator: app.Validator,
			Logger:    functions.NewEntryLogger(),
		}
	case application.PayloadFormatCayenneLPP:
		decoder = &cayennelpp.Decoder{}
	default:
		return nil, errors.NewErrInvalidArgument("App", "unknown payload format")
	}

	fields, val, err := decoder.Decode(in.Payload, uint8(in.Port))
	if err != nil {
		return nil, err
	}

	valid = val
	logs = decoder.Log()

	marshalled, err := json.Marshal(fields)
	if err != nil {
		return nil, err
	}

	flds = string(marshalled)

	return &pb.DryUplinkResult{
		Payload: in.Payload,
		Fields:  flds,
		Valid:   valid,
		Logs:    logs,
	}, nil
}

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


Question:
アプリケーション変数を設定します。

@param	string	$name		アプリケーション変数名
@param	mixed	$value		アプリケーション変数値
@param	bool	$const_flag	上書き禁止設定

public static function SetClassVar ($name, $value, $const_flag = false) {
		$name = Arrays::AdjustArray($name);
		if ($const_flag && Arrays::AdjustValue(static::$_ApplicationVariableTrait_ConstList, implode('=>', Arrays::AdjustArray($name)))) {
			throw CoreException::RaiseSystemError('%s is constant', [implode(' => ', $name)]);
		}
		static::$_ApplicationVariableTrait_Data = Arrays::SetLowest(static::$_ApplicationVariableTrait_Data, $name, $value);
		static::$_ApplicationVariableTrait_ConstList[implode('=>', Arrays::AdjustArray($name))] = $const_flag;
	}

def init_parser(self):

        parser = argparse.ArgumentParser(description='ROCA TLS Fingerprinter')

        parser.add_argument('--debug', dest='debug', default=False, action='store_const', const=True,
                            help='Debugging logging')

        parser.add_argument('--dump', dest='dump', default=False, action='store_const', const=True,
                            help='Dump all processed info')

        parser.add_argument('--flatten', dest='flatten', default=False, action='store_const', const=True,
                            help='Flatten the dump')

        parser.add_argument('--indent', dest='indent', default=False, action='store_const', const=True,
                            help='Indent the dump')

        parser.add_argument('--hosts', dest='hosts', default=False, action='store_const', const=True,
                            help='Arguments are host names not file names')

        parser.add_argument('files', nargs=argparse.ZERO_OR_MORE, default=[],
                            help='files to process')
        return parser

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


Question: // String returns a human readable description of the Keystone.

func (k *Keystone) String() string {
	return fmt.Sprintf("%s --> %s", k.InKey, k.OutKey)
}

function ClassProperty(node, print) {
  print.list(node.decorators, { separator: "" });

  if (node["static"]) this.push("static ");
  print.plain(node.key);
  print.plain(node.typeAnnotation);
  if (node.value) {
    this.space();
    this.push("=");
    this.space();
    print.plain(node.value);
  }
  this.semicolon();
}

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


Question:
Creates state persister table
@throws CException

protected function createTable()
	{
		try
		{
			$command=$this->db->createCommand();
			$command->createTable($this->stateTableName,array(
				$this->keyField=>'string NOT NULL',
				$this->valueField=>'text NOT NULL',
				'PRIMARY KEY ('.$this->db->quoteColumnName($this->keyField).')'
			));
		}
		catch (CDbException $e)
		{
			throw new CException(Yii::t('yii','Can\'t create state persister table. Check CREATE privilege for \'{db}\' connection user or create table manually with SQL: {sql}.',array('{db}'=>$this->dbComponent,'{sql}'=>$command->text ) ) );
		}
	}

public TStatus toTStatus() {
    // TODO: convert sqlState, etc.
    TStatus tStatus = new TStatus(TStatusCode.ERROR_STATUS);
    tStatus.setSqlState(getSQLState());
    tStatus.setErrorCode(getErrorCode());
    tStatus.setErrorMessage(getMessage());
    tStatus.setInfoMessages(toString(this));
    return tStatus;
  }

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


Question:
Sets date in the embedded day Picker.
This function assumes there is a "datesRow" aggregation.
So callers must take care.
@param oDate
@return {void}
@private

function _setDateInDatesRow(oDate) {

		var oDatesRow = this.getAggregation("datesRow");
		var oHeader = this.getAggregation("header");

		if (!this.getPickerPopup()) {
			// set number of days - but max number of days of this month
			var oLastDayOfMonth = new UniversalDate(oDate.getTime());
			oLastDayOfMonth.setUTCDate(1);
			oLastDayOfMonth.setUTCMonth(oLastDayOfMonth.getUTCMonth() + 1);
			oLastDayOfMonth.setUTCDate(0);
			var iDays = oDatesRow.getDays();

			// set start day and selected day
			var oStartDate = new UniversalDate(oDate.getTime());
			oStartDate.setUTCDate( 1 + (Math.ceil(oDate.getUTCDate() / iDays) - 1) * iDays );
			if (oLastDayOfMonth.getUTCDate() - oStartDate.getUTCDate() < iDays) {
				oStartDate.setUTCDate(oLastDayOfMonth.getUTCDate() - iDays + 1);
			}

			oDatesRow.setStartDate(CalendarUtils._createLocalDate(oStartDate, true));

			var iYear = oStartDate.getJSDate().getUTCFullYear();
			var iYearMax = this._oMaxDate.getJSDate().getUTCFullYear();
			var iYearMin = this._oMinDate.getJSDate().getUTCFullYear();
			var iMonth = oStartDate.getJSDate().getUTCMonth();
			var iMonthMax = this._oMaxDate.getJSDate().getUTCMonth();
			var iMonthMin = this._oMinDate.getJSDate().getUTCMonth();
			var iDate = oStartDate.getJSDate().getUTCDate();
			var iDateMax = this._oMaxDate.getJSDate().getUTCDate();
			var iDateMin = this._oMinDate.getJSDate().getUTCDate();

			if (iDate <= 1 || (iYear == iYearMin && iMonth == iMonthMin && iDate <= iDateMin)) {
				oHeader.setEnabledPrevious(false);
			} else {
				oHeader.setEnabledPrevious(true);
			}

			if ((iDate + iDays) >= oLastDayOfMonth.getUTCDate() || (iYear == iYearMax && iMonth == iMonthMax && iDate >= iDateMax)) {
				oHeader.setEnabledNext(false);
			} else {
				oHeader.setEnabledNext(true);
			}
		} else {
			oHeader.setEnabledPrevious(false);
			oHeader.setEnabledNext(false);
		}

		oDatesRow.setDate(CalendarUtils._createLocalDate(oDate, true));
	}

@Override
    @SuppressWarnings("unchecked")
    public D plus(TemporalAmount amount) {
        return (D) ChronoLocalDate.super.plus(amount);
    }

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


Question: Generate the formal parameter builder implementation.

protected void generateTypeParameterBuilderImpl() {
		final TypeReference builderInterface = getTypeParameterBuilderInterface();
		final TypeReference builder = getTypeParameterBuilderImpl();
		final StringConcatenationClient content = new StringConcatenationClient() {
			@Override
			protected void appendTo(TargetStringConcatenation it) {
				it.append("/** Builder of a " + getLanguageName() //$NON-NLS-1$
					+ " type parameter."); //$NON-NLS-1$
				it.newLine();
				it.append(" */"); //$NON-NLS-1$
				it.newLine();
				it.append("@SuppressWarnings(\"all\")"); //$NON-NLS-1$
				it.newLine();
				it.append("public class "); //$NON-NLS-1$
				it.append(builder.getSimpleName());
				it.append(" extends "); //$NON-NLS-1$
				it.append(getAbstractBuilderImpl());
				it.append(" implements "); //$NON-NLS-1$
				it.append(builderInterface);
				it.append(" {"); //$NON-NLS-1$
				it.newLineIfNotEmpty();
				it.newLine();
				it.append(generateMembers(false, false));
				it.append("}"); //$NON-NLS-1$
				it.newLineIfNotEmpty();
				it.newLine();
			}
		};
		final JavaFileAccess javaFile = getFileAccessFactory().createJavaFile(builder, content);
		javaFile.writeTo(getSrcGen());
	}

protected String[] getParameterNameQualifiers() {
        String[] nameQualifiersCopy = new String[_nameQualifiers.length];
        System.arraycopy(_nameQualifiers, 0, nameQualifiersCopy, 0, _nameQualifiers.length);
        return nameQualifiersCopy;
    }

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


Question: Create a function that returns the tokens for a given line.

def _get_tokens_for_line_func(self, cli, document):

        # Cache using `document.text`.
        def get_tokens_for_line():
            return self.lexer.lex_document(cli, document)

        return self._token_cache.get(document.text, get_tokens_for_line)

def get_func_lno(self, funcname):
        """"""

        class FuncLineno(ast.NodeVisitor):
            def __init__(self):
                self.clss = []

            def generic_visit(self, node):
                for child in ast.iter_child_nodes(node):
                    for item in self.visit(child):
                        yield item

            def visit_ClassDef(self, node):
                self.clss.append(node.name)
                for item in self.generic_visit(node):
                    yield item
                self.clss.pop()

            def visit_FunctionDef(self, node):
                # Only allow non nested function definitions.
                name = '.'.join(itertools.chain(self.clss, [node.name]))
                yield name, node.lineno

        if self.functions_firstlno is None:
            self.functions_firstlno = {}
            for name, lineno in FuncLineno().visit(self.node):
                if (name not in self.functions_firstlno or
                        self.functions_firstlno[name] < lineno):
                    self.functions_firstlno[name] = lineno
        try:
            return self.functions_firstlno[funcname]
        except KeyError:
            raise BdbSourceError('{}: function "{}" not found.'.format(
                self.filename, funcname))

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


Question:
Returns the database connection for this component.
@return \CDbConnection the connection component.
@throws \CException if the component does not exist or is not an instance of CDbConnection.

public function getDbConnection()
    {
        if (!Yii::app()->hasComponent($this->connectionID)) {
            throw new CException(sprintf('Connection component "%s" does not exist.', $this->connectionID));
        }
        $db = Yii::app()->getComponent($this->connectionID);
        if (!$db instanceof CDbConnection) {
            throw new CException(sprintf(
                'Connection component "%s" is not an instance of CDbConnection.',
                $this->connectionID
            ));
        }
        return $db;
    }

public void lockContainerpage(final I_CmsSimpleCallback<Boolean> callback) {

        if (m_lockStatus == LockStatus.locked) {
            callback.execute(Boolean.TRUE);
        } else if (m_lockStatus == LockStatus.failed) {
            callback.execute(Boolean.FALSE);
        } else {
            I_CmsSimpleCallback<String> call = new I_CmsSimpleCallback<String>() {

                public void execute(String lockError) {

                    if (lockError == null) {
                        onLockSuccess();
                        callback.execute(Boolean.TRUE);
                    } else {
                        onLockFail(lockError);
                        callback.execute(Boolean.FALSE);
                    }
                }
            };

            if (getData().getDetailContainerPage() != null) {
                CmsCoreProvider.get().lockOrReturnError(getData().getDetailContainerPage(), getLoadTime(), call);
            } else {
                CmsCoreProvider.get().lockOrReturnError(CmsCoreProvider.get().getStructureId(), getLoadTime(), call);
            }
        }
    }

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


Question:
// WithField creates an entry from the standard logger and adds a field to
// it. If you want multiple fields, use `WithFields`.
//
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
// or Panic on the Entry it returns.

func WithField(key string, value interface{}) LogEntry {
	return &logEntry{log.WithField(key, value)}
}

protected function compilePropertyDefinitions(ClassBuilder $builder, StreamWriter $writer)
    {
        foreach ($builder->getProperties() as $property) {
            /* @var PropertyBuilder $property */

            $writer->indent()->writeLine('/**');
            $comments = $property->getComments();
            if (count($comments)) {
                foreach ($comments as $comment) {
                    $comment = trim(ltrim($comment, '>'));
                    $writer->indent()->write(' * ')->writeLine($comment);
                }
                $writer->indent()
                    ->write(' * ')
                    ->writeLine();
            }
            $writer->indent()->write(' * @var');
            if ($type = $property->getType()) {
                $writer->write(' ' . $property->getType());
            }
            $writer->write(' $' . $property->getName())
                ->writeLine()
                ->indent()->writeLine(' */');

            $writer->indent()
                ->write($property->getVisibility())
                ->write(' ')
                ->writeLine('$'.$property->getName().';')
                ->writeLine();
        }

        $writer->writeLine();
    }

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


Question:
@param string $publicUrl

@return self

@throws \InvalidArgumentException

public static function createFromPublicUrl($publicUrl)
    {
        if (!is_string($publicUrl) || empty(trim($publicUrl))) {
            throw new \InvalidArgumentException(
                'The given public URL is no valid teaser image resource.',
                1453748046211
            );
        }

        $path = parse_url($publicUrl, PHP_URL_PATH);

        if (false === $path) {
            throw new \InvalidArgumentException(
                'The given public URL of the teaser image resource is malformed.',
                1453748765907
            );
        }

        $resource = new Resource;
        $resource->value = (string) $path;

        return $resource;
    }

final public function run(int $argc, array $argv)
    {
        $ar = new ArgsManager();
        $ar->getArgs($argc, $argv);
    }

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


Question:
Train the model actual model

        Updates weights / variables, computes and returns the training and validation accuracy

def _train_lbfgs(self, X_feat_train, X_seq_train, y_train,
                     X_feat_valid, X_seq_valid, y_valid,
                     graph, var, other_var,
                     early_stop_patience=None,
                     n_cores=3):

        tic = time.time()
        # take out the parameters for conveience
        n_epochs = self._param["n_epochs"]
        print_every = self._param["print_every"]
        step_size = self._param["step_size"]
        num_steps = n_epochs

        print('Number of epochs:', n_epochs)
        # print("Number of steps per epoch:", num_steps)
        # print("Number of total steps:", num_steps * n_epochs)

        # move into the graph and start the model
        loss_history = []
        train_acc_vec = []
        valid_acc_vec = []
        step_history = []

        with tf.Session(graph=graph, config=tf.ConfigProto(
                use_per_session_threads=True,
                inter_op_parallelism_threads=n_cores,
                intra_op_parallelism_threads=n_cores)) as sess:

            sess.run(other_var["init"])

            best_performance = None
            best_performance_epoch = 0
            for step in range(n_epochs):
                # run the model (sess.run)
                # compute the optimizer, loss and train_prediction in the graph
                # save the last two as l and predictions

                # put thet data into TF form:
                feed_dict = {other_var["tf_X_seq"]: X_seq_train, other_var["tf_y"]: y_train,
                             other_var["tf_X_feat"]: X_feat_train,
                             other_var["tf_step_size"]: step_size}

                # run the optimizer
                # https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/opt/python/training/external_optimizer.py#L115
                other_var["optimizer"].minimize(sess, feed_dict=feed_dict)
                l = sess.run(other_var["loss"], feed_dict=feed_dict)
                loss_history.append(l)  # keep storing the full loss history

                # sometimes print the actual training prediction (l)
                if (step % print_every == 0):
                    train_accuracy = self._accuracy_in_session(sess, other_var,
                                                               X_feat_train, X_seq_train, y_train)
                    valid_accuracy = self._accuracy_in_session(sess, other_var,
                                                               X_feat_valid, X_seq_valid, y_valid)
                    # append the prediction accuracies
                    train_acc_vec.append(train_accuracy)
                    valid_acc_vec.append(valid_accuracy)
                    step_history.append(step / num_steps)
                    print('Step %4d: loss %f, train mse: %f, validation mse: %f' %
                          (step, l, train_accuracy, valid_accuracy))
                    # check if this is the best accuracy
                    if best_performance is None or valid_accuracy <= best_performance:
                        best_performance = valid_accuracy
                        best_performance_epoch = step

                if early_stop_patience is not None and step > best_performance_epoch + early_stop_patience:
                    print("Early stopping. best_performance_epoch: %d, best_performance: %f" %
                          (best_performance_epoch, best_performance))
                    break

            # get the test accuracies
            train_accuracy_final = self._accuracy_in_session(sess, other_var,
                                                             X_feat_train, X_seq_train, y_train)
            valid_accuracy_final = self._accuracy_in_session(sess, other_var,
                                                             X_feat_valid, X_seq_valid, y_valid)
            print('Validation accuracy final: %f' % valid_accuracy_final)

            # store the fitted weights
            var_res = self._get_var_res_sess(sess, var)

            # store also the quasi splines fit

            if self._param["n_splines"] is not None:
                self._splines["quasi_X"] = [self._predict_in_session(sess, other_var,
                                                                     X_feat_train[i:(i + 1)],
                                                                     X_seq_train[i:(i + 1)],
                                                                     variable="spline_quasi_X")
                                            for i in range(X_feat_train.shape[0])]
                # transform into the appropriate form
                self._splines["quasi_X"] = np.concatenate([x[0][np.newaxis] for x in self._splines["quasi_X"]])

            accuracy = {
                "loss_history": np.array(loss_history),
                "step_history": np.array(step_history),
                "train_acc_history": np.array(train_acc_vec),
                "val_acc_history": np.array(valid_acc_vec),
                "train_acc_final": train_accuracy_final,
                "val_acc_final": valid_accuracy_final,
                "best_val_acc": best_performance,
                "best_val_acc_epoch": best_performance_epoch,
                "test_acc_final": None,  # test_accuracy_final,
                "y_test": None,  # y_test,
                "y_test_prediction": None,  # test_prediction.eval(),
                "id_vec_test": None  # id_vec_test
            }
            self._accuracy = accuracy

        toc = time.time()
        exec_time = toc - tic
        self._exec_time = exec_time
        print('That took %fs' % exec_time)
        # weights = {"motif_base_weights": motif_base_weights,
        #            "motif_weights": motif_weights,
        #            "motif_bias": motif_bias,
        #            "final_bias": final_bias,
        #            "feature_weights": feature_weights,
        #            "spline_pred": spline_pred
        #            }
        return var_res

def _supervised_evaluation_error_checking(targets, predictions):

    _raise_error_if_not_sarray(targets, "targets")
    _raise_error_if_not_sarray(predictions, "predictions")
    if (len(targets) != len(predictions)):
        raise _ToolkitError(
         "Input SArrays 'targets' and 'predictions' must be of the same length.")

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


Question:
Return TRUE when the input has the required keys, othewise it will return an arrays
containing the list of required keys

@param array $input

@return array|bool

public function hasRequiredKeys(array $input)
    {
        $control = array_intersect($this->required, array_keys($input));

        if ($this->required !== $control)
        {
            return $this->required;
        }

        return true;
    }

public function checkValueInArray(string $property, string $value) : string
    {
        switch ($property) {
            case 'Device_Pointing_Method':
                // This property is taken from http://www.scientiamobile.com/wurflCapability
                $allowedValues = [
                    'joystick', 'stylus', 'touchscreen', 'clickwheel', 'trackpad', 'trackball', 'mouse', 'unknown',
                ];

                break;
            case 'Browser_Bits':
            case 'Platform_Bits':
                $allowedValues = [
                    0, 8, 16, 32, 64,
                ];

                break;
            default:
                throw new \InvalidArgumentException('Property "' . $property . '" is not defined to be validated');
        }

        if (in_array($value, $allowedValues)) {
            return $value;
        }

        throw new \InvalidArgumentException(
            'invalid value given for Property "' . $property . '": given value "' . $value . '", allowed: '
            . json_encode($allowedValues)
        );
    }

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


Question:
This is ONLY called during a veto operation. It calls the super class
{@link #setProperty}.

@param key Property name
@param oldValue Previous value of property

private void superSetProperty(String key, String oldValue)
    {
        if (oldValue != null) {
            super.setProperty(key, oldValue);
        }
    }

public function setParameters($values) {
    foreach ($values as $name => $value) {
      $this->setParameter($name, $value);
    }
  }

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


Question:
// Sample selects a given number of elements from a sequence with uniform random
// distribution. Selection is done without replacement.

func (t Term) Sample(args ...interface{}) Term {
	return constructMethodTerm(t, "Sample", p.Term_SAMPLE, args, map[string]interface{}{})
}

private static void omitEdge(int[] edges, int[] idx, int[] sizes, int omit) {
    for(int i = 0; i < idx.length; i++) {
      idx[i] = i;
    }
    Arrays.fill(sizes, 1);
    for(int i = 0, j = 0, e = edges.length - 1; j < e; i++, j += 2) {
      if(i == omit) {
        continue;
      }
      int ea = edges[j + 1], eb = edges[j];
      if(eb < ea) { // Swap
        int tmp = eb;
        eb = ea;
        ea = tmp;
      }
      final int pa = follow(ea, idx), pb = follow(eb, idx);
      assert (pa != pb) : "Must be disjoint - MST inconsistent.";
      sizes[idx[pa]] += sizes[idx[pb]];
      idx[pb] = idx[pa];
    }
  }

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


Question:
Locates the specified body's occupant info in the specified location, applies the supplied
occupant info operation to it and then broadcasts the updated info (assuming the occop
returned true indicating that an update was made).

public <T extends OccupantInfo> boolean updateOccupantInfo (
        BodyObject body, OccupantInfo.Updater<T> updater)
    {
        PlaceManager pmgr = _plreg.getPlaceManager(body.getPlaceOid());
        return (pmgr == null) ? false : pmgr.updateOccupantInfo(body.getOid(), updater);
    }

def update_business_values(self):

        for elt in self.all_my_hosts_and_services():
            if not elt.is_problem:
                was = elt.business_impact
                elt.update_business_impact_value(self.hosts, self.services,
                                                 self.timeperiods, self.businessimpactmodulations)
                new = elt.business_impact
                # Ok, the business_impact change, we can update the broks
                if new != was:
                    self.get_and_register_status_brok(elt)

        # When all impacts and classic elements are updated,
        # we can update problems (their value depend on impacts, so
        # they must be done after)
        for elt in self.all_my_hosts_and_services():
            # We first update impacts and classic elements
            if elt.is_problem:
                was = elt.business_impact
                elt.update_business_impact_value(self.hosts, self.services,
                                                 self.timeperiods, self.businessimpactmodulations)
                new = elt.business_impact
                # Maybe one of the impacts change it's business_impact to a high value
                # and so ask for the problem to raise too
                if new != was:
                    self.get_and_register_status_brok(elt)

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


Question:
Set the rule that the current rule is an alias of.

@param string $alias The name of an entry in the container to point to.
@return $this

public function setAliasOf($alias) {
        $alias = $this->normalizeID($alias);

        if ($alias === $this->currentRuleName) {
            trigger_error("You cannot set alias '$alias' to itself.", E_USER_NOTICE);
        } else {
            $this->currentRule['aliasOf'] = $alias;
        }
        return $this;
    }

public function getIndexRealname($index)
    {
        if (isset($this->indexAliasMap[$index])) {
            return $this->indexAliasMap[$index];
        }

        return $index;
    }

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


Question:
Deploy network in equipments and set column 'active = 1' in tables redeipv4

        :param id_networkv4: ID for NetworkIPv4

        :return: Equipments configuration output

def deploy(self, id_networkv4):

        data = dict()
        uri = 'api/networkv4/%s/equipments/' % id_networkv4

        return super(ApiNetworkIPv4, self).post(uri, data=data)

func addBgp(ctx *cli.Context) {
	if len(ctx.Args()) < 1 {
		errExit(ctx, exitHelp, "Host name required", true)
	}

	hostname := ctx.Args()[0]
	routerip := ctx.String("router-ip")
	asid := ctx.String("as")
	neighboras := ctx.String("neighbor-as")
	neighbor := ctx.String("neighbor")

	//Error checks
	_, _, err := net.ParseCIDR(routerip)
	if err != nil {
		errExit(ctx, exitHelp, "Wrong CIDR format. Enter in x.x.x.x/len format", true)
	}

	ip := net.ParseIP(neighbor)
	if ip == nil {
		errExit(ctx, exitHelp, "Wrong IP format. Enter in x.x.x.x format", true)
	}

	if routerip == "" || asid == "" || neighbor == "" || neighboras == "" {
		errExit(ctx, exitHelp, "Missing attributes", true)
	}

	errCheck(ctx, getClient(ctx).BgpPost(&contivClient.Bgp{
		As:         asid,
		Hostname:   hostname,
		Neighbor:   neighbor,
		NeighborAs: neighboras,
		Routerip:   routerip,
	}))

}

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


Question:
Get all relations from the API that have his object as members.

 The optional parameter is an Rosemary::API object. If none is specified
 the default OSM API is used.

 Returns an array of Relation objects or an empty array.

def get_relations_from_api(api=Rosemary::API.new)
      api.get_relations_referring_to_object(type, self.id.to_i)
    end

protected function attr($path, $name, $val=false) {
		if (!isset($this->defaults[$name])) {
			return false;
		}

		$perm = null;

		if ($this->access) {
			if (is_array($this->access)) {
				$obj    = $this->access[0];
				$method = $this->access[1];
				$perm   = $obj->{$method}($name, $path, $this->options['accessControlData'], $this);
			} else {
				$func = $this->access;
				$perm = $func($name, $path, $this->options['accessControlData'], $this);
			}

			if ($perm !== null) {
				return !!$perm;
			}
		}

		for ($i = 0, $c = count($this->attributes); $i < $c; $i++) {
			$attrs = $this->attributes[$i];
			$p = $this->separator.$this->_relpath($path);
			if (isset($attrs[$name]) && isset($attrs['pattern']) && preg_match($attrs['pattern'], $p)) {
				$perm = $attrs[$name];
			}
		}

		return $perm === null ? $this->defaults[$name] : !!$perm;
	}

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


Question: // NewMockVolumeAPIClient creates a new mock instance

func NewMockVolumeAPIClient(ctrl *gomock.Controller) *MockVolumeAPIClient {
	mock := &MockVolumeAPIClient{ctrl: ctrl}
	mock.recorder = &MockVolumeAPIClientMockRecorder{mock}
	return mock
}

protected function initQueue($ipc_filename, $msg_type)
    {
        $this->key_t = $this->getIpcKey($ipc_filename, $msg_type);
        $this->queue = \msg_get_queue($this->key_t);
        if (!$this->queue) throw new \RuntimeException('msg_get_queue failed');
    }

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


Question:
Export all user data for the specified user, in the specified contexts.

@param approved_contextlist $contextlist The approved contexts to export information for.

public static function export_user_data(approved_contextlist $contextlist) {
        global $DB;

        // Get the course.
        list($select, $params) = $DB->get_in_or_equal($contextlist->get_contextids(), SQL_PARAMS_NAMED);
        $params['contextcourse'] = CONTEXT_COURSE;

        $sql = "SELECT c.*
                FROM {course} c
                JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
                WHERE ctx.id $select";

        $courses = $DB->get_recordset_sql($sql, $params);

        foreach ($courses as $course) {
            $coursecompletion = \core_completion\privacy\provider::get_course_completion_info($contextlist->get_user(), $course);
            writer::with_context(\context_course::instance($course->id))->export_data(
                    [get_string('privacy:completionpath', 'course')], (object) $coursecompletion);
            // Get user's favourites information for the particular course.
            $coursefavourite = \core_favourites\privacy\provider::get_favourites_info_for_user($contextlist->get_user()->id,
                    \context_course::instance($course->id), 'core_course', 'courses', $course->id);
            if ($coursefavourite) { // If the course has been favourited by the user, include it in the export.
                writer::with_context(\context_course::instance($course->id))->export_data(
                        [get_string('privacy:favouritespath', 'course')], (object) $coursefavourite);
            }
        }
        $courses->close();
    }

public function permissionSave(Permission $permission)
    {
        if ($permission->permission_id) {
            $query = "
                UPDATE
                    auth_permission
                SET
                    `name` = :name, description = :description, updated_on = " . $this->sql_time_func . "
                WHERE
                    permission_id = :permission_id
            ";
        } else {
            $query = "
                INSERT INTO
                    auth_permission (`name`, description, updated_on, added_on)
                VALUES
                    (:name, :description, " . $this->sql_time_func . ", " . $this->sql_time_func . ")
            ";
        }
        $cur = $this->db->prepare($query);
        $cur->bindParam(":name", $permission->name, PDO::PARAM_STR, 32);
        $cur->bindParam(":description", $permission->description, PDO::PARAM_STR);
        if ($permission->permission_id) {
            $cur->bindParam(":permission_id", $permission->permission_id, PDO::PARAM_INT);
        }
        $this->db->beginTransaction();
        try {
            $cur->execute();
            if (!$permission->permission_id) {
                $permission->permission_id = $this->db->lastInsertId();
            }
            $this->db->commit();
        } catch (PDOException $db_err) {
            $this->db->rollBack();
            if ($this->logger) {
                $this->logger->error("Failed to create/update permission", ['exception' => $db_err]);
            }
            return false;
        }
        return true;
    }

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


Question:
@param Request $request

@return Response
@throws \Exception

public function doRequest($request)
    {
        $this->createApplication();
        $zendRequest = $this->application->getRequest();

        $uri = new HttpUri($request->getUri());
        $queryString = $uri->getQuery();
        $method = strtoupper($request->getMethod());

        $zendRequest->setCookies(new Parameters($request->getCookies()));

        $query = [];
        $post = [];
        $content = $request->getContent();
        if ($queryString) {
            parse_str($queryString, $query);
        }

        if ($method !== HttpRequest::METHOD_GET) {
            $post = $request->getParameters();
        }

        $zendRequest->setQuery(new Parameters($query));
        $zendRequest->setPost(new Parameters($post));
        $zendRequest->setFiles(new Parameters($request->getFiles()));
        $zendRequest->setContent($content);
        $zendRequest->setMethod($method);
        $zendRequest->setUri($uri);
        $requestUri = $uri->getPath();
        if (!empty($queryString)) {
            $requestUri .= '?' . $queryString;
        }

        $zendRequest->setRequestUri($requestUri);

        $zendRequest->setHeaders($this->extractHeaders($request));
        $this->application->run();

        // get the response *after* the application has run, because other ZF
        //     libraries like API Agility may *replace* the application's response
        //
        $zendResponse = $this->application->getResponse();

        $this->zendRequest = $zendRequest;

        $exception = $this->application->getMvcEvent()->getParam('exception');
        if ($exception instanceof \Exception) {
            throw $exception;
        }

        $response = new Response(
            $zendResponse->getBody(),
            $zendResponse->getStatusCode(),
            $zendResponse->getHeaders()->toArray()
        );

        return $response;
    }

public function assertSatisfied()
    {
        foreach ($this->expectations as $expectation) {
            if (!$expectation->isSatisfied()) {
                $comment = $expectation->commentOn($expectation->getMethod(), []);

                if (!$comment) {
                    $comment = "Unsatisfied expectation for method " . $expectation->getMethod();
                }

                throw new UnsatisfiedExpectationException($comment);
            }
        }
    }

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


Question: Tries conversion of any value to a boolean (called a 'Logical Value' in Excel lingo)

public static boolean toBoolean(Object value, EvaluationContext ctx) {
        if (value instanceof Boolean) {
            return (Boolean) value;
        }
        else if (value instanceof Integer) {
            return ((Integer) value) != 0;
        }
        else if (value instanceof BigDecimal) {
            return !value.equals(BigDecimal.ZERO);
        }
        else if (value instanceof String) {
            String strVal = (String) value;
            if (strVal.equalsIgnoreCase("TRUE")) {
                return true;
            }  else if (strVal.equalsIgnoreCase("FALSE")) {
                return false;
            }
        }
        else if (value instanceof LocalDate || value instanceof OffsetTime || value instanceof ZonedDateTime) {
            return true;
        }

        throw new EvaluationError("Can't convert '" + value + "' to a boolean");
    }

func (vr *ValidationResult) Log(ctx context.Context) {
	for _, msg := range vr.Messages {
		lvl := logging.Info
		switch msg.Severity {
		case "WARNING":
			lvl = logging.Warning
		case "ERROR", "CRITICAL":
			lvl = logging.Error
		}
		logging.Logf(ctx, lvl, "%s: %s", msg.Path, msg.Text)
	}
}

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


Question:
Before bootstrap run process.

@see \luya\base\BaseBootstrap::beforeRun()

public function beforeRun($app)
    {
        foreach ($app->tags as $name => $config) {
            TagParser::inject($name, $config);
        }

        foreach ($this->getModules() as $id => $module) {
            foreach ($module->urlRules as $key => $rule) {
                if (is_string($key)) {
                    $this->_urlRules[$key] = $rule;
                } else {
                    $this->_urlRules[] = $rule;
                }
            }

            // get all api rules (since 1.0.10)
            foreach ($module->apiRules as $endpoint => $rule) {
                $this->_apiRules[$endpoint] = $rule;
            }

            /**
             * 'api-admin-user' => 'admin\apis\UserController',
             * 'api-cms-navcontainer' => 'admin\apis\NavContainerController'
             */
            foreach ($module->apis as $alias => $class) {
                $this->_apis[$alias] = ['class' => $class, 'module' => $module];
            }

            foreach ($module->tags as $name => $config) {
                TagParser::inject($name, $config);
            }
        }
    }

private function load_command_config_file($file, $prefix) {

    $yaml = $this->sm->get('pegase.component.yaml.spyc');
    $data = $yaml->parse($file);
    $mm = $this->sm->get('pegase.core.module_manager');

    foreach($data as $command_name => $command) {

      if(key_exists('prefix', $command)) {
        $prefix_to_add = $command['prefix'];
      }
      else
        $prefix_to_add = $command_name;

      if(key_exists('class', $command) && key_exists('method', $command)) {

        if(!key_exists('parameters', $command))
          $command['parameters'] = null;

        if(!key_exists('options', $command))
          $command['options'] = null;

        $this->add_command(array(
          'name' => $prefix . $prefix_to_add,
          'class' => $command['class'],
          'method' => $command['method'],
          'parameters' => $command['parameters'],
          'options' => $command['options']
        ));
      }
      else if(key_exists('import', $command)) {
        $this->load_command_config_file(
          $mm->get_file($command['import']['module'], $command['import']['file']),
          $prefix . $prefix_to_add);
      }
    }
  }

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


Question:
Append code for creating variable with bool if it's instance of list
        with a name ``{variable}_is_list``. Similar to `create_variable_with_length`.

def create_variable_is_list(self):

        variable_name = '{}_is_list'.format(self._variable)
        if variable_name in self._variables:
            return
        self._variables.add(variable_name)
        self.l('{variable}_is_list = isinstance({variable}, list)')

def _make_attr_element_from_typeattr(parent, type_attr_i):

    attr = _make_attr_element(parent, type_attr_i.attr)

    if type_attr_i.unit_id is not None:
        attr_unit    = etree.SubElement(attr, 'unit')
        attr_unit.text = units.get_unit(type_attr_i.unit_id).abbreviation

    attr_is_var    = etree.SubElement(attr, 'is_var')
    attr_is_var.text = type_attr_i.attr_is_var

    if type_attr_i.data_type is not None:
        attr_data_type    = etree.SubElement(attr, 'data_type')
        attr_data_type.text = type_attr_i.data_type

    if type_attr_i.data_restriction is not None:
        attr_data_restriction    = etree.SubElement(attr, 'restrictions')
        attr_data_restriction.text = type_attr_i.data_restriction

    return attr

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


Question: length of largest insertion

def max_insertion(seqs, gene, domain):

    seqs = [i[2] for i in list(seqs.values()) if i[2] != [] and i[0] == gene and i[1] == domain]
    lengths = []
    for seq in seqs:
        for ins in seq:
            lengths.append(int(ins[2]))
    if lengths == []:
        return 100
    return max(lengths)

public static INDArray max(INDArray ndArray, double k, boolean dup) {
        return exec(dup ? new ScalarMax(ndArray, null, ndArray.ulike(), k) : new ScalarMax(ndArray, k));
    }

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


Question: Calculate loss of the supplied rollout

def calculate_gradient(self, batch_info, device, model, rollout):

        assert isinstance(rollout, Trajectories), "ACER algorithm requires trajectory input"

        local_epsilon = 1e-6

        evaluator = model.evaluate(rollout)

        actions = evaluator.get('rollout:actions')
        rollout_probabilities = torch.exp(evaluator.get('rollout:logprobs'))

        # We calculate the trust-region update with respect to the average model
        if self.trust_region:
            self.update_average_model(model)

        logprobs = evaluator.get('model:logprobs')
        q = evaluator.get('model:q')

        # Selected action values
        action_logprobs = select_indices(logprobs, actions)
        action_q = select_indices(q, actions)

        # We only want to propagate gradients through specific variables
        with torch.no_grad():
            model_probabilities = torch.exp(logprobs)

            # Importance sampling correction - we must find the quotient of probabilities
            rho = model_probabilities / (rollout_probabilities + local_epsilon)

            # Probability quotient only for selected actions
            actions_rho = select_indices(rho, actions)

            # Calculate policy state values
            model_state_values = (model_probabilities * q).sum(dim=1)

            trajectory_rewards = rollout.transition_tensors['rewards']
            trajectory_dones = rollout.transition_tensors['dones']

            q_retraced = self.retrace(
                trajectory_rewards,
                trajectory_dones,
                action_q.reshape(trajectory_rewards.size()),
                model_state_values.reshape(trajectory_rewards.size()),
                actions_rho.reshape(trajectory_rewards.size()),
                rollout.rollout_tensors['final_values']
            ).flatten()

            advantages = q_retraced - model_state_values
            importance_sampling_coefficient = torch.min(actions_rho, self.rho_cap * torch.ones_like(actions_rho))

            explained_variance = 1 - torch.var(q_retraced - action_q) / torch.var(q_retraced)

        # Entropy of the policy distribution
        policy_entropy = torch.mean(model.entropy(logprobs))
        policy_gradient_loss = -torch.mean(advantages * importance_sampling_coefficient * action_logprobs)

        # Policy gradient bias correction
        with torch.no_grad():
            advantages_bias_correction = q - model_state_values.view(model_probabilities.size(0), 1)
            bias_correction_coefficient = F.relu(1.0 - self.rho_cap / (rho + local_epsilon))

        # This sum is an expectation with respect to action probabilities according to model policy
        policy_gradient_bias_correction_gain = torch.sum(
            logprobs * bias_correction_coefficient * advantages_bias_correction * model_probabilities,
            dim=1
        )

        policy_gradient_bias_correction_loss = - torch.mean(policy_gradient_bias_correction_gain)

        policy_loss = policy_gradient_loss + policy_gradient_bias_correction_loss

        q_function_loss = 0.5 * F.mse_loss(action_q, q_retraced)

        if self.trust_region:
            with torch.no_grad():
                average_evaluator = self.average_model.evaluate(rollout)
                average_action_logits = average_evaluator.get('model:logprobs')

            actor_loss = policy_loss - self.entropy_coefficient * policy_entropy
            q_loss = self.q_coefficient * q_function_loss

            actor_gradient = torch.autograd.grad(-actor_loss, logprobs, retain_graph=True)[0]

            # kl_divergence = model.kl_divergence(average_action_logits, action_logits).mean()
            # kl_divergence_grad = torch.autograd.grad(kl_divergence, action_logits, retain_graph=True)

            # Analytically calculated derivative of KL divergence on logits
            # That makes it hardcoded for discrete action spaces
            kl_divergence_grad_symbolic = - torch.exp(average_action_logits) / logprobs.size(0)

            k_dot_g = (actor_gradient * kl_divergence_grad_symbolic).sum(dim=-1)
            k_dot_k = (kl_divergence_grad_symbolic ** 2).sum(dim=-1)

            adjustment = (k_dot_g - self.trust_region_delta) / k_dot_k
            adjustment_clipped = adjustment.clamp(min=0.0)

            actor_gradient_updated = actor_gradient - adjustment_clipped.view(adjustment_clipped.size(0), 1)

            # Populate gradient from the newly updated fn
            logprobs.backward(gradient=-actor_gradient_updated, retain_graph=True)
            q_loss.backward(retain_graph=True)
        else:
            # Just populate gradient from the loss
            loss = policy_loss + self.q_coefficient * q_function_loss - self.entropy_coefficient * policy_entropy

            loss.backward()

        return {
            'policy_loss': policy_loss.item(),
            'policy_gradient_loss': policy_gradient_loss.item(),
            'policy_gradient_bias_correction': policy_gradient_bias_correction_loss.item(),
            'avg_q_selected': action_q.mean().item(),
            'avg_q_retraced': q_retraced.mean().item(),
            'q_loss': q_function_loss.item(),
            'policy_entropy': policy_entropy.item(),
            'advantage_norm': torch.norm(advantages).item(),
            'explained_variance': explained_variance.item(),
            'model_prob_std': model_probabilities.std().item(),
            'rollout_prob_std': rollout_probabilities.std().item()
        }

def dRV_2(self,dt):

        return -self.orbpop_long.dRV(dt) * (self.orbpop_long.M1/(self.orbpop_long.M1 + self.orbpop_long.M2)) +\
            self.orbpop_short.dRV(dt,com=True)

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


Question: // ReadResponse reads a server response into the received o.

func (o *PatchConfigReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {

	case 200:
		result := NewPatchConfigOK()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil

	case 400:
		result := NewPatchConfigBadRequest()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	case 500:
		result := NewPatchConfigFailure()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	default:
		return nil, runtime.NewAPIError("unknown error", response, response.Code())
	}
}

function processBody() {
      $data = '';
      $counter = 0;

      do {
        $status = socket_get_status($this->socket);
        if ($status['eof'] == 1) {
          break;
        }

        if ($status['unread_bytes'] > 0) {
          $buffer = fread($this->socket, $status['unread_bytes']);
          $counter = 0;
        } else {
          $buffer = fread($this->socket, 128);
          $counter++;
          usleep(2);
        }

        $data .= $buffer;
      } while ( ($status['unread_bytes'] > 0) || ($counter++ < 10) );

      return $data;
    }

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


Question:
Creates a <div> tag. (Shortcut function.)

@param string $content HTML content of tag
@param string $class Optional CSS class (or classes as space-separated list)
@param array $attributes Optional other attributes as array
@return string HTML code for div

public static function div($content, $class = '', array $attributes = null) {
        return self::tag('div', $content, self::add_class($class, $attributes));
    }

function namedParameterList()
    {
        $def = array( $this->Name => array( 'context' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => false ),
                                            'comment' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => '' ),
                                            'arguments' => array( 'type' => 'hash',
                                                                  'required' => false,
                                                                  'default' => false ) ),
                      $this->ExtensionName => array( 'extension' => array( 'type' => 'string',
                                                                           'required' => true,
                                                                           'default' => false ),
                                                     'context' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => false ),
                                                     'comment' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => '' ),
                                                     'arguments' => array( 'type' => 'hash',
                                                                           'required' => false,
                                                                           'default' => false ) ) );
        $def[ $this->DynamicName ] = $def[ $this->Name ];
        return $def;
    }

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


Question:
Checks if a magic property is exists

@param string $key
@return boolean

protected function magicIsset($key)
    {
        if (!$this->magicInited) {
            $this->magicInit();
        }
        $exists = &$this->magicFields['exists'];
        if (!array_key_exists($key, $exists)) {
            if (array_key_exists($key, $this->magicFields['fields'])) {
                $exists[$key] = true;
            } elseif (isset($this->magicFields['loaders'][$key])) {
                $exists[$key] = true;
            } else {
                $exists[$key] = $this->magicExistsField($key);
            }
        }
        return $exists[$key];
    }

public function addBooleanAccessorOpen(&$script, Column $column)
    {
        $name = self::getBooleanAccessorName($column);
        $visibility = $column->getAccessorVisibility();

        $script .= "
    ".$visibility." function $name(";
        if ($column->isLazyLoad()) {
            $script .= "ConnectionInterface \$con = null";
        }

        $script .= ")
    {";
    }

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


Question:
@param string|array $authorization
@param string $html

@return \Spatie\Menu\Laravel\Menu

public function htmlIfCan($authorization, string $html)
    {
        return $this->addIfCan($authorization, Html::raw($html));
    }

function (arg) {
    var self = this;

    var argType = arg[0];
    var argValue = arg[1];

    var argCode;
    switch (argType) {
    case 'STRING':
    case 'NUMBER':
    case 'BOOLEAN':
    case 'NULL':
      argCode = BlazeTools.toJSLiteral(argValue);
      break;
    case 'PATH':
      argCode = self.codeGenPath(argValue);
      break;
    case 'EXPR':
      // The format of EXPR is ['EXPR', { type: 'EXPR', path: [...], args: { ... } }]
      argCode = self.codeGenMustache(argValue.path, argValue.args, 'dataMustache');
      break;
    default:
      // can't get here
      throw new Error("Unexpected arg type: " + argType);
    }

    return argCode;
  }

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


Question: After save create order instance for sending instance for orderable models.

def post_save(sender, instance, created, **kwargs):

    # Only create order model instances for
    # those modules specified in settings.
    model_label = '.'.join([sender._meta.app_label, sender._meta.object_name])
    labels = resolve_labels(model_label)

    order_field_names = is_orderable(model_label)
    if order_field_names:
        orderitem_set = getattr(
            instance,
            resolve_order_item_related_set_name(labels)
        )
        if not orderitem_set.all():
            fields = {}
            for order_field_name in order_field_names:
                fields[order_field_name] = 1
            orderitem_set.model.objects.create(item=instance, **fields)
            sanitize_order(orderitem_set.model)

public function stepUpdateRecordState($type, $id, $state) {
		$class = $this->convertTypeToClass($type);
		$obj = $this->fixtureFactory->get($class, $id);
		if(!$obj) {
			throw new \InvalidArgumentException(sprintf(
				'Can not find record "%s" with identifier "%s"',
				$type,
				$id
			));
		}

		switch($state) {
			case 'published':
				$obj->publish('Stage', 'Live');
				break;
			case 'not published':
			case 'unpublished':
				$oldMode = \Versioned::get_reading_mode();
				\Versioned::reading_stage('Live');
				$clone = clone $obj;
				$clone->delete();
				\Versioned::reading_stage($oldMode);
				break;
			case 'deleted':
				$obj->delete();
				break;
			default:
				throw new \InvalidArgumentException(sprintf(
					'Invalid state: "%s"', $state
				));
		}
	}

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


Question: // Expect a flow value node.

func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool {
	if simple {
		if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) {
			return false
		}
	} else {
		if emitter.canonical || emitter.column > emitter.best_width {
			if !yaml_emitter_write_indent(emitter) {
				return false
			}
		}
		if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) {
			return false
		}
	}
	emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE)
	return yaml_emitter_emit_node(emitter, event, false, false, true, false)
}

private final boolean block(Data data, Body body) throws TemplateException {
	if (!data.srcCode.forwardIfCurrent('{')) return false;
	comments(data);
	if (data.srcCode.forwardIfCurrent('}')) {

	    return true;
	}
	statements(data, body, false);

	if (!data.srcCode.forwardIfCurrent('}')) throw new TemplateException(data.srcCode, "Missing ending [}]");
	return true;
    }

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


Question: //GetRect get rect of img

func (i *ImageObj) GetRect() *Rect {

	rect, err := i.getRect()
	if err != nil {
		log.Fatalf("%+v", err)
	}
	return rect
}

protected function handleImageManipulation(ImageInterface $image, array $data): ImageInterface
    {
        $width = $data['width'];
        $height = $data['height'];

        if (isset($data['dimension'])) {
            $width = $height = $data['dimension'];
        }

        return $image->resize(new Box($width, $height), $data['filter']);
    }

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


Question:
Retrieve the consentCODE to use for rejected responses by the survey system
The mapping of actual consents to consentCODEs is done in the gems__consents table

@return string Default value is 'do not use'
@throws \Gems_Exception_Coding

public function getConsentRejected()
    {
        if ($this->project->offsetExists('consentRejected')) {
            return $this->project->consentRejected;
        }

        // Remove in 1.7.3
        if ($this->project->offsetExists('concentRejected')) {
            throw new \Gems_Exception_Coding('project.ini setting was changed from "concentRejected" to "consentRejected", please update your project.ini');
        }

        return 'do not use';
    }

def eac3_analog_to_digital_converter_type=(eac3_analog_to_digital_converter_type)
      validator = EnumAttributeValidator.new('String', ["standard", "hdcd"])
      unless validator.valid?(eac3_analog_to_digital_converter_type)
        fail ArgumentError, "invalid value for 'eac3_analog_to_digital_converter_type', must be one of #{validator.allowable_values}."
      end
      @eac3_analog_to_digital_converter_type = eac3_analog_to_digital_converter_type
    end

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


Question: // RegisterFactory allows a client implementation to register itself.

func RegisterFactory(name string, factory Factory) {
	if _, ok := factories[name]; ok {
		log.Fatalf("RegisterFactory: %s already exists", name)
	}
	factories[name] = factory
}

protected function generateRegex(
        string $regex,
        ?NodeInterface $parent,
        ?string $name
    ): NodeInterface{
        $node   = new RegexNode($this, $parent, $name);

        $node->setRegex($regex);

        return $node;
    }

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


Question: Outputs a direct error.

protected function errorResponse()
    {
        if(!empty($this->data['openid_return_to'])) {
            $response = array(
            'openid.mode'  => 'error',
            'openid.error' => 'Invalid request'
            );
            $this->redirect($this->response($response));
        } else {
            header('HTTP/1.1 400 Bad Request');
            $response = array(
                'ns' => $this->ns,
                'error' => 'Invalid request'
                );
            echo $this->keyValueForm($response);
        }
        die();
    }

protected function itemTypeError(string $method, $item): string
    {
        $itemType = is_object($item) ? get_class($item) : gettype($item);

        return sprintf(
            '%s::%s expects item type (%s); received (%s) %s',
            static::class,
            $method,
            $this->itemType(),
            $itemType,
            VarPrinter::toString($item)
        );
    }

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


Question:
Given the command args, take an series of input files containing
    GenesisData, combine all the batches into one GenesisData, and output the
    result into a new file.

def do_genesis(args, data_dir=None):

    if data_dir is None:
        data_dir = get_data_dir()

    if not os.path.exists(data_dir):
        raise CliException(
            "Data directory does not exist: {}".format(data_dir))

    genesis_batches = []
    for input_file in args.input_file:
        print('Processing {}...'.format(input_file))
        input_data = BatchList()
        try:
            with open(input_file, 'rb') as in_file:
                input_data.ParseFromString(in_file.read())
        except:
            raise CliException('Unable to read {}'.format(input_file))

        genesis_batches += input_data.batches

    _validate_depedencies(genesis_batches)
    _check_required_settings(genesis_batches)

    if args.output:
        genesis_file = args.output
    else:
        genesis_file = os.path.join(data_dir, 'genesis.batch')

    print('Generating {}'.format(genesis_file))
    output_data = GenesisData(batches=genesis_batches)
    with open(genesis_file, 'wb') as out_file:
        out_file.write(output_data.SerializeToString())

def _create_filefunction(self, name, spectrum_pars):
        """"""

        spectrum_pars = {} if spectrum_pars is None else spectrum_pars

        if 'loge' in spectrum_pars:
            loge = spectrum_pars.get('loge')
        else:
            ebinsz = (self.log_energies[-1] -
                      self.log_energies[0]) / self.enumbins
            loge = utils.extend_array(self.log_energies, ebinsz, 0.5, 6.5)

        # Get the values
        dnde = np.zeros(len(loge))
        if 'dnde' in spectrum_pars:
            dnde = spectrum_pars.get('dnde')
        else:
            dnde = np.array([self.like[name].spectrum()(pyLike.dArg(10 ** egy))
                             for egy in loge])

        filename = \
            os.path.join(self.workdir,
                         '%s_filespectrum.txt' % (name.lower().replace(' ', '_')))

        # Create file spectrum txt file
        np.savetxt(filename, np.vstack((10**loge, dnde)).T)
        self.like.setSpectrum(name, str('FileFunction'))

        self.roi[name]['Spectrum_Filename'] = filename
        # Update
        for c in self.components:
            src = c.like.logLike.getSource(str(name))
            spectrum = src.spectrum()

            spectrum.getParam(str('Normalization')).setBounds(1E-3, 1E3)

            file_function = pyLike.FileFunction_cast(spectrum)
            file_function.readFunction(str(filename))
            c.roi[name]['Spectrum_Filename'] = filename

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


Question:
Begin Conditional Internal Capture

@param mixed $cond condition
@param int   $pos  position
@param array $attr The additional attributes

@return null

@access public

public function beginCondInternal($cond, $pos = 100, array $attr = array())
    {
        $this->capture[] = array($cond, $pos, $attr);
        ob_start();
    }

def emit_code_from_ir(compound_match_query, compiler_metadata):
    """"""
    # If the compound match query contains only one match query,
    # just call `emit_code_from_single_match_query`
    # If there are multiple match queries, construct the query string for each
    # individual query and combine them as follows.
    #
    # SELECT EXPAND($result)
    # LET
    #    $optional__0 = (
    #        <query_string_0>
    #    ),
    #    $optional__1 = (
    #        <query_string_1>
    #    ),
    #    $optional__2 = (
    #        <query_string_2>
    #    ),
    #
    #    . . .
    #
    #    $result = UNIONALL($optional__0, $optional__1, . . . )

    match_queries = compound_match_query.match_queries
    if len(match_queries) == 1:
        query_string = emit_code_from_single_match_query(match_queries[0])
    elif len(match_queries) > 1:
        query_string = emit_code_from_multiple_match_queries(match_queries)
    else:
        raise AssertionError(u'Received CompoundMatchQuery with an empty list of MatchQueries: '
                             u'{}'.format(match_queries))

    return query_string

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


Question: // And implements And with other conditions

func (ne Ne) And(conds ...Cond) Cond {
	return And(ne, And(conds...))
}

public boolean contains(int xp, int yp) {
		if (xp < x) {
			return false;
		}
		if (yp < y) {
			return false;
		}
		if (xp >= x+width) {
			return false;
		}
		if (yp >= y+height) {
			return false;
		}

		return true;
	}

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


Question:
// NewPodConfig creates an object that can merge many configuration sources into a stream
// of normalized updates to a pod configuration.

func NewPodConfig(mode PodConfigNotificationMode, recorder record.EventRecorder) *PodConfig {
	updates := make(chan kubetypes.PodUpdate, 50)
	storage := newPodStorage(updates, mode, recorder)
	podConfig := &PodConfig{
		pods:    storage,
		mux:     config.NewMux(storage),
		updates: updates,
		sources: sets.String{},
	}
	return podConfig
}

def add_item(self, host, key, value, clock=None, state=0):

        if clock is None:
            clock = self.clock
        if self._config.data_type == "items":
            item = {"host": host, "key": key,
                    "value": value, "clock": clock, "state": state}
        elif self._config.data_type == "lld":
            item = {"host": host, "key": key, "clock": clock, "state": state,
                    "value": json.dumps({"data": value})}
        else:
            if self.logger: # pragma: no cover
                self.logger.error("Setup data_type before adding data")
            raise ValueError('Setup data_type before adding data')
        self._items_list.append(item)

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


Question: line 315 "BehaviorTreeReader.rl"

private static boolean containsFloatingPointCharacters (String value) {
		for (int i = 0, n = value.length(); i < n; i++) {
			switch (value.charAt(i)) {
			case '.':
			case 'E':
			case 'e':
				return true;
			}
		}
		return false;
	}

func LiteralStr(node Node) (string, bool) {
	if lit, ok := node.(*StringLiteral); ok {
		return lit.Value, true
	}

	if lit, ok := node.(*BooleanLiteral); ok {
		return lit.Canonical(), true
	}

	if lit, ok := node.(*NumberLiteral); ok {
		return lit.Canonical(), true
	}

	return "", false
}

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


Question:
验证是否为符合规则的 "boolean" 值，如果有验证不通过的情况，将通过 model 的 addError 方法添加错误信息
@param \Abstracts\Model $object
@param string $attribute
@throws \Exception

protected function validateAttribute($object, $attribute)
    {
        $value = $object->{$attribute};
        if ($this->isEmpty($value)) {
            $this->validateEmpty($object, $attribute);
            return;
        }
        if (
            (!$this->strict && $value != $this->trueValue && $value != $this->falseValue)
            || ($this->strict && $value !== $this->trueValue && $value !== $this->falseValue)
        ) {
            $this->addError($object, $attribute, $this->message, [
                '{true}' => $this->trueValue,
                '{false}' => $this->falseValue,
            ]);
        }
    }

public function addRoute($route)
    {
        if (!$route instanceof Route && !is_array($route)) {
            throw new \LogicException('Route invalid. Expected Route instance or array.');
        } elseif ($route instanceof Route) {
            $name = $route->getName();
            if (isset($this->routes[$name])) {
                throw new \LogicException(sprintf('Trying to register two routes with the same name "%s"', $name));
            }
            $this->routes[$route->getName()] = $route;
        } elseif (is_array($route) && !count($route) == 4) {
            throw new \LogicException('Array Route invalid. Expected array(string|array method, string pattern, callback|string action, string name).');
        } else {
            list($methods, $patternUri, $action, $name) = array_values($route);

            $this->routes[$name] = new Route($methods, $patternUri, $action, $name);
        }

        return $this;
    }

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


Question: raises *NoResult* exception if no result has been set

def get_result(self):

        self._process()
        if not self.has_result:
            raise NoResult
        return self.res_queue.popleft()

public function run(
        string $method,
        string $uri,
        array $headers,
        string $body
    ) {
        if ($this->router === null) {
            return;
        }

        try {
            $response = $this->router->run($method, $uri, $headers, $body);
            if ($response !== null) {
                $response->output();
            }
        } catch (RouterException $e) {
            $e->getResponse()->output();
        }
    }

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


Question: // SetAutomatedSnapshotRetentionPeriod sets the AutomatedSnapshotRetentionPeriod field's value.

func (s *PendingModifiedValues) SetAutomatedSnapshotRetentionPeriod(v int64) *PendingModifiedValues {
	s.AutomatedSnapshotRetentionPeriod = &v
	return s
}

def set(self, key, value):

        self._check_limit()
        _expire = time.time() + self._timeout if self._timeout else None
        self._store[key] = (value, _expire)

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


Question:
Release a specific TCP port number

        :param port: TCP port number
        :param project: Project instance

def release_tcp_port(self, port, project):

        if port in self._used_tcp_ports:
            self._used_tcp_ports.remove(port)
            project.remove_tcp_port(port)
            log.debug("TCP port {} has been released".format(port))

function (parameters) {

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

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

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

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

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

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

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

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

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

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

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

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


Question: Execute the build process.

public function build()
    {
        $this->classMetadata->mergeExtension($this->getExtensionName(), [
            $this->key => $this->fieldName,
        ]);
    }

func RunCommand(factory app.ProjectFactory) cli.Command {
	return cli.Command{
		Name:   "run",
		Usage:  "Run a one-off command",
		Action: app.WithProject(factory, app.ProjectRun),
		Flags: []cli.Flag{
			cli.BoolFlag{
				Name:  "d",
				Usage: "Detached mode: Run container in the background, print new container name.",
			},
		},
	}
}

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