Question:
// Useful for signing query string (including DEFLATED AuthnRequest) when
// using HTTP-Redirect to make a signed request.
// See 3.4.4.1 DEFLATE Encoding of https://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf

func (ctx *SigningContext) SignString(content string) ([]byte, error) {
	hash := ctx.Hash.New()
	if ln, err := hash.Write([]byte(content)); err != nil {
		return nil, fmt.Errorf("error calculating hash: %v", err)
	} else if ln < 1 {
		return nil, fmt.Errorf("zero length hash")
	}
	digest := hash.Sum(nil)

	var signature []byte
	if key, _, err := ctx.KeyStore.GetKeyPair(); err != nil {
		return nil, fmt.Errorf("unable to fetch key for signing: %v", err)
	} else if signature, err = rsa.SignPKCS1v15(rand.Reader, key, ctx.Hash, digest); err != nil {
		return nil, fmt.Errorf("error signing: %v", err)
	}
	return signature, nil
}

private function serializeAce(Writer $writer, array $ace)
    {
        $writer->startElement('{DAV:}ace');

        switch ($ace['principal']) {
            case '{DAV:}authenticated':
                $principal = new Principal(Principal::AUTHENTICATED);
                break;
            case '{DAV:}unauthenticated':
                $principal = new Principal(Principal::UNAUTHENTICATED);
                break;
            case '{DAV:}all':
                $principal = new Principal(Principal::ALL);
                break;
            default:
                $principal = new Principal(Principal::HREF, $ace['principal']);
                break;
        }

        $writer->writeElement('{DAV:}principal', $principal);
        $writer->startElement('{DAV:}grant');
        $writer->startElement('{DAV:}privilege');

        $writer->writeElement($ace['privilege']);

        $writer->endElement(); // privilege
        $writer->endElement(); // grant

        if (!empty($ace['protected'])) {
            $writer->writeElement('{DAV:}protected');
        }

        $writer->endElement(); // ace
    }

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


Question: // Shutdown implements the DiskBlockCache interface for DiskBlockCacheLocal.

func (cache *DiskBlockCacheLocal) Shutdown(ctx context.Context) {
	// Wait for the cache to either finish starting or error.
	select {
	case <-cache.startedCh:
	case <-cache.startErrCh:
		return
	}
	cache.lock.Lock()
	defer cache.lock.Unlock()
	// shutdownCh has to be checked under lock, otherwise we can race.
	select {
	case <-cache.shutdownCh:
		cache.log.CWarningf(ctx, "Shutdown called more than once")
	default:
	}
	close(cache.shutdownCh)
	if cache.blockDb == nil {
		return
	}
	cache.closer()
	cache.blockDb = nil
	cache.metaDb = nil
	cache.tlfDb = nil
	if cache.useLimiter() {
		cache.config.DiskLimiter().onSimpleByteTrackerDisable(ctx,
			cache.cacheType, int64(cache.getCurrBytes()))
	}
	cache.hitMeter.Shutdown()
	cache.missMeter.Shutdown()
	cache.putMeter.Shutdown()
	cache.updateMeter.Shutdown()
	cache.evictCountMeter.Shutdown()
	cache.evictSizeMeter.Shutdown()
	cache.deleteCountMeter.Shutdown()
	cache.deleteSizeMeter.Shutdown()
}

public static FileSystem getWriterFileSystem(State state, int numBranches, int branchId)
      throws IOException {
    return HadoopUtils.getOptionallyThrottledFileSystem(WriterUtils.getWriterFS(state, numBranches, branchId), state);
  }

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


Question:
/*
(non-Javadoc)
@see org.fcrepo.server.security.xacml.pdp.data.PolicyDataManager#getPolicy(java.lang.String)

@Override
    public AbstractPolicy getPolicy(String name, PolicyFinder policyFinder) throws PolicyIndexException {
        readLock.lock();
        try {
            logger.debug("Getting policy named: " + name);
            if (policies.containsKey(name)) {
                return handleDocument(m_policyReader.readPolicy(policies.get(name)), policyFinder);
            } else {
                throw new PolicyIndexException("Attempting to get non-existent policy " + name);
            }
        } catch (ParsingException pe) {
            throw new PolicyIndexException(pe.getMessage(),pe);
        } finally {
            readLock.unlock();
        }
    }

public Value get(String name) {
        if (name.length() > 1) {
            int dot;
            if (name.charAt(0) == LPAREN) {
                int start = name.indexOf(RPAREN);
                dot = name.indexOf(DOT, start);
            } else {
                dot = name.indexOf(DOT);
            }
            if (dot > 0) {
                String fieldName = name.substring(0, dot);
                String rest = name.substring(dot + 1);
                Key key = createKey(fieldName);
                Value value = fields.get(key);
                if (!value.isMessageType()) {
                    throw new ParserException("Invalid option name: %s", name);
                }
                DynamicMessage msg = value.getMessage();
                return msg.get(rest);
            } else {
                Key key = createKey(name);
                return fields.get(key);
            }
        } else {
            Key key = Key.field(name);
            return fields.get(key);
        }
    }

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


Question:
Add another to a call bridge

@param caller -> PhoneNumber
@param callee -> PhoneNumber
@param args -> Call's arguments (see in function)

public function callParty($caller, $callee, $args)
    {
      $new_call = Call::create($caller, $callee, $this->id, $args);
      $this->calls ++;

      return Constructor::Make($this, $data->get());
    }

static ElementAttributes createElementAttributes(String tag) {
        // Parsing strings
        // <!--$includetemplate$aggregated2$templatewithparams.jsp$-->
        // or
        // <!--$includeblock$aggregated2$$(block)$myblock$-->
        // in order to retrieve driver, page and name attributes
        Pattern pattern = Pattern.compile("(?<=\\$)(?:[^\\$]|\\$\\()*(?=\\$)");
        Matcher matcher = pattern.matcher(tag);
        List<String> listparameters = new ArrayList<>();
        while (matcher.find()) {
            listparameters.add(matcher.group());
        }

        String[] parameters = listparameters.toArray(new String[listparameters.size()]);

        Driver driver;
        String page = "";
        String name = null;

        if (parameters.length > 1) {
            driver = DriverFactory.getInstance(parameters[1]);
        } else {
            driver = DriverFactory.getInstance();
        }

        if (parameters.length > 2) {
            page = parameters[2];
        }

        if (parameters.length > 3) {
            name = parameters[3];
        }
        return new ElementAttributes(driver, page, name);

    }

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


Question:
Checks whether the folder exists for fileName, and creates it if necessary.

@param fileName folder name.
@throws IOException an IO exception.

public static void checkFolderForFile(String fileName) throws IOException {

		if (fileName.lastIndexOf(File.separator) > 0) {
			String folder = fileName.substring(0, fileName.lastIndexOf(File.separator));
			directoryCheck(folder);
		}
	}

public static LocalCall<String> mkdir(String path, String mode) {
        return mkdir(path, Optional.empty(), Optional.empty(), Optional.of(mode));
    }

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


Question: Executes sql against db_name in a thread

async def execute(
        self,
        db_name,
        sql,
        params=None,
        truncate=False,
        custom_time_limit=None,
        page_size=None,
    ):
        """"""
        page_size = page_size or self.page_size

        def sql_operation_in_thread(conn):
            time_limit_ms = self.sql_time_limit_ms
            if custom_time_limit and custom_time_limit < time_limit_ms:
                time_limit_ms = custom_time_limit

            with sqlite_timelimit(conn, time_limit_ms):
                try:
                    cursor = conn.cursor()
                    cursor.execute(sql, params or {})
                    max_returned_rows = self.max_returned_rows
                    if max_returned_rows == page_size:
                        max_returned_rows += 1
                    if max_returned_rows and truncate:
                        rows = cursor.fetchmany(max_returned_rows + 1)
                        truncated = len(rows) > max_returned_rows
                        rows = rows[:max_returned_rows]
                    else:
                        rows = cursor.fetchall()
                        truncated = False
                except sqlite3.OperationalError as e:
                    if e.args == ('interrupted',):
                        raise InterruptedError(e)
                    print(
                        "ERROR: conn={}, sql = {}, params = {}: {}".format(
                            conn, repr(sql), params, e
                        )
                    )
                    raise

            if truncate:
                return Results(rows, truncated, cursor.description)

            else:
                return Results(rows, False, cursor.description)

        with trace("sql", (db_name, sql.strip(), params)):
            results = await self.execute_against_connection_in_thread(
                db_name, sql_operation_in_thread
            )
        return results

public function exec()
    {
        $result = $this->connection()->prepare($this->assemble());

        foreach ($this->valuesToBind as $key => $value) {
            $result->bindValue(":{$key}", $value);
        }

        return $result->model($this->model)->exec();
    }

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


Question:
Creates oauth exception from response.

@param  ResponseInterface $response
@param  string $data Parsed response data
@return IdentityProviderException

public static function oauthException(ResponseInterface $response, $data)
    {
        $message = $response->getReasonPhrase();
        if (isset($data['errors']) && ($decoded = json_encode($data['errors']))) {
            $message .= $decoded;
        }

        return new static($message, $response->getStatusCode(), (string)$response->getBody());
    }

func (c *RolesController) List(ctx *app.ListRolesContext) error {
	if ctx.ResourceType == nil { // todo: check for empty string too?
		return jsonapi.JSONErrorResponse(ctx, errors.NewBadParameterError("resource_type", "nil"))
	}

	var roleScopes []role.RoleDescriptor

	_, err := c.app.ResourceTypeRepository().Lookup(ctx, *ctx.ResourceType)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting roles for the resource type")
		// if not found, then NotFoundError would be returned,
		// hence returning the error as is.
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	roleScopes, err = c.app.RoleManagementService().ListAvailableRolesByResourceType(ctx, *ctx.ResourceType)

	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting available roles for the resource")
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	respRoles := convertRoleScopeToAppRoles(roleScopes)
	res := &app.Roles{
		Data: respRoles,
	}
	return ctx.OK(res)
}

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


Question:
Set the cache class.

@param $class string the class name to set

public function setCacheClass($class)
  {
    $prev = $this->configuration['cache_class'];
    if (!isset($this->configuration['classes'][$class]) &&
        isset($this->configuration['classes'][$prev])) {
      $this->configuration['classes'][$class] =
          $this->configuration['classes'][$prev];
    }
    $this->configuration['cache_class'] = $class;
  }

func (t *Template) GetAllAWSElastiCacheParameterGroupResources() map[string]*resources.AWSElastiCacheParameterGroup {
	results := map[string]*resources.AWSElastiCacheParameterGroup{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSElastiCacheParameterGroup:
			results[name] = resource
		}
	}
	return results
}

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


Question:
Inititialze mask lookup table.
Maps loopy_v values to bitmasks for attribute bytes to get the correct palette value.

function initMasks() {
	var i, mask,
	    result = new Uint8Array( 0x10000 );

	for ( i = 0; i < 0x10000; i++ ) {
		mask = 3;
		if ( i & 0x2 ) {
			// right
			mask <<= 2;
		}
		if ( i & 0x40 ) {
			// bottom
			mask <<= 4;
		}

		result[ i ] = mask;
	}

	return result;
}

def set_indexing(self, index_template):

        objs = object_session(self)

        if self.index.indimp != index_template.imp_name:
            self._refresh_datatable_schema()

        self.index.name = index_template.name
        self.index.indimp = index_template.imp_name
        self.index.case = index_template.case
        self.index.setkwargs(**index_template.kwargs)
        objs.commit()

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


Question:
Clean a directory.

@param string $dir
The directory to clean.
@param int $keep
The number of items to keep.

protected function cleanDir($dir, $keep)
    {
        $finder = clone $this->finder;
        $finder->in($dir);
        $finder->depth(0);
        $this->doSort($finder);
        $items = iterator_to_array($finder->getIterator());
        if ($keep) {
            array_splice($items, -$keep);
        }
        while ($items) {
            $item = reset($items);
            try {
                $this->fs->chmod($item, 0777, 0000, true);
            } catch (IOException $e) {
                // If chmod didn't work and the exception contains a path, try
                // to remove anyway.
                $path = $e->getPath();
                if ($path && realpath($path) !== realpath($item)) {
                    $this->fs->remove($path);
                    continue;
                }
            }
            $this->fs->remove($item);
            array_shift($items);
        }
    }

public function curlDELETE($curlUrl)
  {

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $curlUrl);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'Accept: application/json',
      'Content-Type: application/json',
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $jsonResult = curl_exec($ch);
    $results[0] = json_decode($jsonResult);
    $results[1] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $this->statHat->ezCount('MB_Toolbox: MB_Toolbox_cURL: curlDELETE', 1);

    return $results;
  }

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


Question:
Process the TPVObject, all params required.

@param tpv The time-position-velocity object to process
@param processor Processor that handles the exchange.
@param endpoint GpsdEndpoint receiving the exchange.

public static void consumeTPVObject(TPVObject tpv, Processor processor, GpsdEndpoint endpoint, ExceptionHandler exceptionHandler) {
        // Simplify logging when https://github.com/taimos/GPSd4Java/pull/19 is merged into upstream.
        LOG.debug("About to consume TPV object {},{} from {}", tpv.getLatitude(), tpv.getLongitude(), endpoint);

        Validate.notNull(tpv);
        Validate.notNull(processor);
        Validate.notNull(endpoint);

        GpsCoordinates coordinates = gpsCoordinates(new Date(new Double(tpv.getTimestamp()).longValue()), tpv.getLatitude(), tpv.getLongitude());
        Exchange exchange = anExchange(endpoint.getCamelContext()).withPattern(OutOnly).
                withHeader(TPV_HEADER, tpv).withBody(coordinates).build();

        try {
            processor.process(exchange);
        } catch (Exception e) {
            exceptionHandler.handleException(e);
        }
    }

def match(self, request, service):

		uri = self.normalize_uri(request.path())

		if request.session().protocol() not in self.protocols:
			return

		if request.method() not in self.methods:
			return

		if self.virtual_hosts and request.virtual_host() not in self.virtual_hosts:
			return

		if self.ports and int(request.session().server_address().port()) not in self.ports:
			return

		match_obj = self.re_pattern.match(uri)

		if not match_obj:
			return

		presenter_action = self.action
		presenter_args = self.presenter_args.copy()

		for i in range(len(self.route_args)):
			if self.route_args[i] == 'action':
				presenter_action = match_obj.group(i + 1)
			else:
				presenter_args[self.route_args[i]] = match_obj.group(i + 1)

		return WWebTargetRoute(self.presenter, presenter_action, self, service.route_map(), **presenter_args)

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


Question:
Lower triangle of an array.
    Return a copy of an array with elements above the k-th diagonal zeroed.
    Need a multi-dimensional version here because numpy.tril does not
    broadcast for numpy verison < 1.9.

def tril(array, k=0):
    ''''''
    try:
        tril_array = np.tril(array, k=k)
    except:
        # have to loop
        tril_array = np.zeros_like(array)
        shape = array.shape
        otherdims = shape[:-2]
        for index in np.ndindex(otherdims):
            tril_array[index] = np.tril(array[index], k=k)
    return tril_array

def _get_row_sparse(self, arr_list, ctx, row_id):

        # get row sparse params based on row ids
        if not isinstance(row_id, ndarray.NDArray):
            raise TypeError("row_id must have NDArray type, but %s is given"%(type(row_id)))
        if not self._trainer:
            raise RuntimeError("Cannot get row_sparse data for Parameter '%s' when no " \
                               "Trainer is created with it."%self.name)
        results = self._check_and_get(arr_list, ctx)

        # fetch row sparse params from the trainer
        self._trainer._row_sparse_pull(self, results, row_id)
        return results

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


Question: Get SNMP values from 2nd host.

def get_snmp_from_host2(self):

        if not self.snmp2:
            self.activity_value2 = None
        else:
            response = self.snmp2.get_oids(activity_oid)
            self.activity_value2 = activity[int(response[0])]

function writeNaptr(buff, val, label_index) {
  assertUndefined(val.order, 'NAPTR record requires "order"');
  assertUndefined(val.preference, 'NAPTR record requires "preference"');
  assertUndefined(val.flags, 'NAPTR record requires "flags"');
  assertUndefined(val.service, 'NAPTR record requires "service"');
  assertUndefined(val.regexp, 'NAPTR record requires "regexp"');
  assertUndefined(val.replacement, 'NAPTR record requires "replacement"');
  buff.writeUInt16BE(val.order & 0xFFFF);
  buff.writeUInt16BE(val.preference & 0xFFFF);
  buff.writeUInt8(val.flags.length);
  buff.write(val.flags, val.flags.length, 'ascii');
  buff.writeUInt8(val.service.length);
  buff.write(val.service, val.service.length, 'ascii');
  buff.writeUInt8(val.regexp.length);
  buff.write(val.regexp, val.regexp.length, 'ascii');
  namePack(val.replacement, buff, label_index);
  return WRITE_RESOURCE_DONE;
}

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


Question:
Determines if routes has to be authorized.

@return bool

protected function hasToBeAuthorized()
    {
        if ( in_array($this->route->getName(), self::$except) ) return false;

        return (bool) $this->route->getName();
    }

public function any( $uri, $action = null )
	{
		$verbs = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'];

		return $this->addRoute( $verbs, $uri, $action );
	}

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


Question: Couple NIC to vswitch by adding vswitch into user direct.

def _couple_nic(self, userid, vdev, vswitch_name,
                    active=False):
        """"""
        if active:
            self._is_active(userid)

        msg = ('Start to couple nic device %(vdev)s of guest %(vm)s '
               'with vswitch %(vsw)s'
                % {'vdev': vdev, 'vm': userid, 'vsw': vswitch_name})
        LOG.info(msg)
        requestData = ' '.join((
            'SMAPI %s' % userid,
            "API Virtual_Network_Adapter_Connect_Vswitch_DM",
            "--operands",
            "-v %s" % vdev,
            "-n %s" % vswitch_name))

        try:
            self._request(requestData)
        except exception.SDKSMTRequestFailed as err:
            LOG.error("Failed to couple nic %s to vswitch %s for user %s "
                      "in the guest's user direct, error: %s" %
                      (vdev, vswitch_name, userid, err.format_message()))
            self._couple_inactive_exception(err, userid, vdev, vswitch_name)

        # the inst must be active, or this call will failed
        if active:
            requestData = ' '.join((
                'SMAPI %s' % userid,
                'API Virtual_Network_Adapter_Connect_Vswitch',
                "--operands",
                "-v %s" % vdev,
                "-n %s" % vswitch_name))

            try:
                self._request(requestData)
            except (exception.SDKSMTRequestFailed,
                    exception.SDKInternalError) as err1:
                results1 = err1.results
                msg1 = err1.format_message()
                if ((results1 is not None) and
                    (results1['rc'] == 204) and
                    (results1['rs'] == 20)):
                    LOG.warning("Virtual device %s already connected "
                                "on the active guest system", vdev)
                else:
                    persist_OK = True
                    requestData = ' '.join((
                        'SMAPI %s' % userid,
                        'API Virtual_Network_Adapter_Disconnect_DM',
                        "--operands",
                        '-v %s' % vdev))
                    try:
                        self._request(requestData)
                    except (exception.SDKSMTRequestFailed,
                            exception.SDKInternalError) as err2:
                        results2 = err2.results
                        msg2 = err2.format_message()
                        if ((results2 is not None) and
                            (results2['rc'] == 212) and
                            (results2['rs'] == 32)):
                            persist_OK = True
                        else:
                            persist_OK = False
                    if persist_OK:
                        self._couple_active_exception(err1, userid, vdev,
                                                      vswitch_name)
                    else:
                        raise exception.SDKNetworkOperationError(rs=3,
                                    nic=vdev, vswitch=vswitch_name,
                                    couple_err=msg1, revoke_err=msg2)

        """Update information in switch table."""
        self._NetDbOperator.switch_update_record_with_switch(userid, vdev,
                                                             vswitch_name)
        msg = ('Couple nic device %(vdev)s of guest %(vm)s '
               'with vswitch %(vsw)s successfully'
                % {'vdev': vdev, 'vm': userid, 'vsw': vswitch_name})
        LOG.info(msg)

def _rt_state_update(route_table_id, dcidr, router_ip="(none)",
                     instance_id="(none)", eni_id="(none)",
                     old_router_ip="(none)", msg="(none)"):

    buf = "inst: %s, eni: %s, r_ip: %-15s, o_r_ip: %-15s, msg: %s" % \
          (instance_id, eni_id, router_ip, old_router_ip, msg)
    CURRENT_STATE.vpc_state.setdefault('route_tables', {}). \
                            setdefault(route_table_id, {})[dcidr] = buf

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


Question: // unmarshalIdentityResponse converts a resp.Body (JSON) into an IdentityResponse

func unmarshalIdentityResponse(resp *http.Response) (identityResp *common.IdentityResponse, err error) {
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}

	defer func() {
		if errClose := resp.Body.Close(); errClose != nil {
			log.ErrorC("error closing response body", errClose, nil)
		}
	}()

	err = json.Unmarshal(b, &identityResp)
	return
}

func (self *RawDispatcher) AddResourceSeparateUdid(node *RestNode, name string, wireExample interface{}, index RestIndex,
	find RestFindUdid, post RestPost, put RestPutUdid, del RestDeleteUdid) {
	t := self.validateType(wireExample)
	obj := &restObjUdid{
		restShared: restShared{
			typ:   t,
			name:  name,
			index: index,
			post:  post,
		},
		find: find,
		del:  del,
		put:  put,
	}
	node.ResUdid[strings.ToLower(name)] = obj
}

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


Question: Return parallelpiped unit cell lattice matrix.

def unit_cell_to_lattice_array(cryst):
    """"""
    a_, b_, c_, alpha, beta, gamma = cryst
    # Convert angles from degrees to radians.
    r_alpha = np.deg2rad(alpha)
    r_beta = np.deg2rad(beta)
    r_gamma = np.deg2rad(gamma)
    # Calculate unit cell volume that is neccessary.
    volume = a_ * b_ * c_ * (
        1 - np.cos(r_alpha)**2 - np.cos(r_beta)**2 - np.cos(r_gamma)**2 + 2 *
        np.cos(r_alpha) * np.cos(r_beta) * np.cos(r_gamma))**0.5
    # Create the orthogonalisation Matrix (M^-1) - lattice matrix
    a_x = a_
    a_y = b_ * np.cos(r_gamma)
    a_z = c_ * np.cos(r_beta)
    b_x = 0
    b_y = b_ * np.sin(r_gamma)
    b_z = c_ * (
        np.cos(r_alpha) - np.cos(r_beta) * np.cos(r_gamma)) / np.sin(r_gamma)
    c_x = 0
    c_y = 0
    c_z = volume / (a_ * b_ * np.sin(r_gamma))
    lattice_array = np.array(
        [[a_x, a_y, a_z], [b_x, b_y, b_z], [c_x, c_y, c_z]])
    return lattice_array

def _flatten_lane_details(runinfo):

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

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


Question:
If an equality (==) expression has double-parentheses, remove one set.
This avoids clang's -Wparentheses-equality warning.

@Override
  public void endVisit(ParenthesizedExpression node) {
    Expression expr = node.getExpression();
    if (expr instanceof ParenthesizedExpression) {
      Expression inner = ((ParenthesizedExpression) expr).getExpression();
      if (isEqualityExpression(inner)) {
        node.replaceWith(TreeUtil.remove(expr));
      }
    } else if (!(node.getParent() instanceof Expression) && isEqualityExpression(expr)) {
      node.replaceWith(TreeUtil.remove(expr));
    }
  }

public function compile(CompilationContext $compilationContext)
    {
        /*
         * Set the method currently being compiled
         */
        $compilationContext->currentMethod = $this;

        /*
         * Initialize the method warm-up to null
         */
        $compilationContext->methodWarmUp = null;

        /**
         * Assign pre-made compilation passes.
         */
        $localContext = $this->localContext;
        $typeInference = $this->typeInference;
        $callGathererPass = $this->callGathererPass;

        /**
         * Initialization of parameters happens in a fictitious external branch.
         */
        $branch = new Branch();
        $branch->setType(Branch::TYPE_EXTERNAL);
        /**
         * BranchManager helps to create graphs of conditional/loop/root/jump branches.
         */
        $branchManager = new BranchManager();
        $branchManager->addBranch($branch);

        $compilationContext->branchManager = $branchManager;

        /**
         * Every method has its own symbol table.
         */
        $symbolTable = new SymbolTable($compilationContext);
        if ($localContext) {
            $symbolTable->setLocalContext($localContext);
        }

        if ($this->staticVariables) {
            foreach ($this->staticVariables as $var) {
                $localVar = clone $var;
                $localVar->setIsExternal(true);
                $localVar->setLocalOnly(true);
                $localVar->setType('variable');
                $symbolTable->addRawVariable($localVar);
            }
        }

        /**
         * Parameters has an additional extra mutation.
         */
        $parameters = $this->parameters;
        if ($localContext) {
            if (\is_object($parameters)) {
                foreach ($parameters->getParameters() as $parameter) {
                    $localContext->increaseMutations($parameter['name']);
                }
            }
        }

        /**
         * Cache Manager manages function calls, method calls and class entries caches.
         */
        $cacheManager = new CacheManager();
        $cacheManager->setGatherer($callGathererPass);

        $compilationContext->cacheManager = $cacheManager;
        $compilationContext->typeInference = $typeInference;
        $compilationContext->symbolTable = $symbolTable;

        $oldCodePrinter = $compilationContext->codePrinter;

        /**
         * Change the code printer to a single method instance.
         */
        $codePrinter = new CodePrinter();
        $compilationContext->codePrinter = $codePrinter;

        /*
         * Set an empty function cache
         */
        $compilationContext->functionCache = null;

        /*
         * Reset try/catch and loop counter
         */
        $compilationContext->insideCycle = 0;
        $compilationContext->insideTryCatch = 0;
        $compilationContext->currentTryCatch = 0;

        if (\is_object($parameters)) {
            /**
             * Round 1. Create variables in parameters in the symbol table.
             */
            $classCastChecks = [];
            $substituteVars = [];
            foreach ($parameters->getParameters() as $parameter) {
                /*
                 * Change dynamic variables to low level types
                 */
                if ($typeInference) {
                    if (isset($parameter['data-type'])) {
                        if ('variable' == $parameter['data-type']) {
                            $type = $typeInference->getInferedType($parameter['name']);
                            if (\is_string($type)) {
                                /* promote polymorphic parameters to low level types */
                            }
                        }
                    } else {
                        $type = $typeInference->getInferedType($parameter['name']);
                        if (\is_string($type)) {
                            /* promote polymorphic parameters to low level types */
                        }
                    }
                }

                $symbolParam = null;

                if (isset($parameter['data-type'])) {
                    switch ($parameter['data-type']) {
                        case 'object':
                        case 'callable':
                        case 'resource':
                        case 'variable':
                            $symbol = $symbolTable->addVariable($parameter['data-type'], $parameter['name'], $compilationContext);
                            /* TODO: Move this to the respective backend, which requires refactoring how this works */
                            if ($compilationContext->backend->isZE3()) {
                                $symbol->setIsDoublePointer(true);
                                $substituteVars[$parameter['name']] = $symbolTable->addVariable('variable', $parameter['name'].'_sub', $compilationContext);
                            }
                            break;

                        default:
                            $symbol = $symbolTable->addVariable($parameter['data-type'], $parameter['name'], $compilationContext);
                            $symbolParam = $symbolTable->addVariable('variable', $parameter['name'].'_param', $compilationContext);
                            /* TODO: Move this to the respective backend, which requires refactoring how this works */
                            if ($compilationContext->backend->isZE3()) {
                                $symbolParam->setIsDoublePointer(true);
                            }
                            if ('string' == $parameter['data-type'] || 'array' == $parameter['data-type']) {
                                $symbol->setMustInitNull(true);
                            }
                            break;
                    }
                } else {
                    $symbol = $symbolTable->addVariable('variable', $parameter['name'], $compilationContext);
                }

                /* ZE3 only */
                if (isset($substituteVars[$parameter['name']])) {
                    $substituteVar = $substituteVars[$parameter['name']];
                    $substituteVar->increaseUses();
                }

                /*
                 * Some parameters can be read-only
                 */
                if (isset($parameter['const']) && $parameter['const']) {
                    $symbol->setReadOnly(true);
                    if (\is_object($symbolParam)) {
                        $symbolParam->setReadOnly(true);
                    }
                }

                if (\is_object($symbolParam)) {
                    /*
                     * Parameters are marked as 'external'
                     */
                    $symbolParam->setIsExternal(true);

                    /*
                     * Assuming they're initialized
                     */
                    $symbolParam->setIsInitialized(true, $compilationContext);

                    /*
                     * Initialize auxiliary parameter zvals to null
                     */
                    $symbolParam->setMustInitNull(true);

                    /*
                     * Increase uses
                     */
                    $symbolParam->increaseUses();
                } else {
                    if (isset($parameter['default'])) {
                        if (isset($parameter['data-type'])) {
                            if ('variable' == $parameter['data-type']) {
                                $symbol->setMustInitNull(true);
                            }
                        } else {
                            $symbol->setMustInitNull(true);
                        }
                    }
                }

                /*
                 * Original node where the variable was declared
                 */
                $symbol->setOriginal($parameter);

                /*
                 * Parameters are marked as 'external'
                 */
                $symbol->setIsExternal(true);

                /*
                 * Assuming they're initialized
                 */
                $symbol->setIsInitialized(true, $compilationContext);

                /*
                 * Variables with class/type must be objects across the execution
                 */
                if (isset($parameter['cast'])) {
                    $symbol->setDynamicTypes('object');
                    $symbol->setClassTypes($compilationContext->getFullName($parameter['cast']['value']));
                    $classCastChecks[] = [$symbol, $parameter];
                } else {
                    if (isset($parameter['data-type'])) {
                        if ('variable' == $parameter['data-type']) {
                            $symbol->setDynamicTypes('undefined');
                        }
                    } else {
                        $symbol->setDynamicTypes('undefined');
                    }
                }
            }
        }

        $compilationContext->backend->onPreCompile($this, $compilationContext);

        /*
         * Compile the block of statements if any
         */
        if (\is_object($this->statements)) {
            if ($this->hasModifier('static')) {
                $compilationContext->staticContext = true;
            } else {
                $compilationContext->staticContext = false;
            }

            /*
             * Compile the statements block as a 'root' branch
             */
            $this->statements->compile($compilationContext, false, Branch::TYPE_ROOT);
        }

        /**
         * Initialize variable default values.
         */
        $initVarCode = $compilationContext->backend->initializeVariableDefaults($symbolTable->getVariables(), $compilationContext);

        /**
         * Fetch parameters from vm-top.
         */
        $initCode = '';
        $code = '';
        if (\is_object($parameters)) {
            /**
             * Round 2. Fetch the parameters in the method.
             */
            $params = [];
            $requiredParams = [];
            $optionalParams = [];
            $numberRequiredParams = 0;
            $numberOptionalParams = 0;
            foreach ($parameters->getParameters() as $parameter) {
                if (isset($parameter['data-type'])) {
                    $dataType = $parameter['data-type'];
                } else {
                    $dataType = 'variable';
                }

                switch ($dataType) {
                    case 'object':
                    case 'callable':
                    case 'resource':
                    case 'variable':
                        if (!$this->isInternal()) {
                            $params[] = '&'.$parameter['name'];
                        } else {
                            $params[] = $parameter['name'];
                        }
                        break;

                    default:
                        if (!$this->isInternal()) {
                            $params[] = '&'.$parameter['name'].'_param';
                        } else {
                            $params[] = $parameter['name'].'_param';
                        }
                        break;
                }

                if (isset($parameter['default'])) {
                    $optionalParams[] = $parameter;
                    ++$numberOptionalParams;
                } else {
                    $requiredParams[] = $parameter;
                    ++$numberRequiredParams;
                }
            }

            /**
             * Pass the write detector to the method statement block to check if the parameter
             * variable is modified so as do the proper separation.
             */
            $parametersToSeparate = [];
            if (\is_object($this->statements)) {
                /*
                 * If local context is not available
                 */
                if (!$localContext) {
                    $writeDetector = new WriteDetector();
                }

                foreach ($parameters->getParameters() as $parameter) {
                    if (isset($parameter['data-type'])) {
                        $dataType = $parameter['data-type'];
                    } else {
                        $dataType = 'variable';
                    }

                    switch ($dataType) {
                        case 'variable':
                        case 'string':
                        case 'array':
                        case 'resource':
                        case 'object':
                        case 'callable':
                            $name = $parameter['name'];
                            if (!$localContext) {
                                if ($writeDetector->detect($name, $this->statements->getStatements())) {
                                    $parametersToSeparate[$name] = true;
                                }
                            } else {
                                if ($localContext->getNumberOfMutations($name) > 1) {
                                    $parametersToSeparate[$name] = true;
                                }
                            }
                            break;
                    }
                }
            }

            /*
             * Initialize required parameters
             */
            foreach ($requiredParams as $parameter) {
                if (isset($parameter['mandatory'])) {
                    $mandatory = $parameter['mandatory'];
                } else {
                    $mandatory = 0;
                }

                if (isset($parameter['data-type'])) {
                    $dataType = $parameter['data-type'];
                } else {
                    $dataType = 'variable';
                }

                if ('variable' != $dataType) {
                    /*
                     * Assign value from zval to low level type
                     */
                    if ($mandatory) {
                        $initCode .= $this->checkStrictType($parameter, $compilationContext);
                    } else {
                        $initCode .= $this->assignZvalValue($parameter, $compilationContext);
                    }
                }

                switch ($dataType) {
                    case 'variable':
                    case 'resource':
                    case 'object':
                    case 'callable':
                        if (isset($parametersToSeparate[$parameter['name']])) {
                            $symbolTable->mustGrownStack(true);
                            $initCode .= "\t".'ZEPHIR_SEPARATE_PARAM('.$parameter['name'].');'.PHP_EOL;
                        }
                        break;
                }
            }

            /*
             * Initialize optional parameters
             */
            foreach ($optionalParams as $parameter) {
                if (isset($parameter['mandatory'])) {
                    $mandatory = $parameter['mandatory'];
                } else {
                    $mandatory = 0;
                }

                if (isset($parameter['data-type'])) {
                    $dataType = $parameter['data-type'];
                } else {
                    $dataType = 'variable';
                }

                switch ($dataType) {
                    case 'object':
                    case 'callable':
                    case 'resource':
                    case 'variable':
                        $name = $parameter['name'];
                        break;

                    default:
                        $name = $parameter['name'].'_param';
                        break;
                }

                /**
                 * Assign the default value according to the variable's type.
                 */
                $targetVar = $compilationContext->symbolTable->getVariableForWrite($name, $compilationContext);
                $initCode .= "\t".$compilationContext->backend->ifVariableValueUndefined($targetVar, $compilationContext, false, false).PHP_EOL;

                if ($compilationContext->backend->isZE3()) {
                    if ($targetVar->isDoublePointer() && isset($substituteVars[$parameter['name']])) {
                        $substituteVar = $substituteVars[$parameter['name']];
                        $initCode .= "\t\t".$targetVar->getName().' = &'.$substituteVar->getName().';'.PHP_EOL;
                    }
                }
                $initCode .= $this->assignDefaultValue($parameter, $compilationContext);

                if (isset($parametersToSeparate[$name]) || 'variable' != $dataType) {
                    $initCode .= "\t".'} else {'.PHP_EOL;
                    if (isset($parametersToSeparate[$name])) {
                        $initCode .= "\t\t".'ZEPHIR_SEPARATE_PARAM('.$name.');'.PHP_EOL;
                    } else {
                        if ($mandatory) {
                            $initCode .= $this->checkStrictType($parameter, $compilationContext, $mandatory);
                        } else {
                            $initCode .= "\t".$this->assignZvalValue($parameter, $compilationContext);
                        }
                    }
                }

                $initCode .= "\t".'}'.PHP_EOL;
            }

            /*
             * Fetch the parameters to zval pointers
             */
            $codePrinter->preOutputBlankLine();

            if (!$this->isInternal()) {
                $compilationContext->headersManager->add('kernel/memory');
                if ($symbolTable->getMustGrownStack()) {
                    $code .= "\t".'zephir_fetch_params(1, '.$numberRequiredParams.', '.$numberOptionalParams.', '.implode(', ', $params).');'.PHP_EOL;
                } else {
                    $code .= "\t".'zephir_fetch_params(0, '.$numberRequiredParams.', '.$numberOptionalParams.', '.implode(', ', $params).');'.PHP_EOL;
                }
            } else {
                foreach ($params as $param) {
                    /* TODO: Migrate all this code to codeprinter, get rid of temp code printer */
                    $tempCodePrinter = new CodePrinter();
                    $realCodePrinter = $compilationContext->codePrinter;
                    $compilationContext->codePrinter = $tempCodePrinter;
                    $paramVar = $compilationContext->symbolTable->getVariableForRead($param, $compilationContext);
                    $compilationContext->backend->assignZval($paramVar, $param.'_ext', $compilationContext);
                    $code .= "\t".$tempCodePrinter->getOutput().PHP_EOL;
                    $compilationContext->codePrinter = $realCodePrinter;
                }
            }
            $code .= PHP_EOL;
        }

        $code .= $initCode.$initVarCode;
        $codePrinter->preOutput($code);

        $compilationContext->headersManager->add('kernel/object');
        /*
         * Fetch used superglobals
         */
        foreach ($symbolTable->getVariables() as $name => $variable) {
            if ($variable->isSuperGlobal()) {
                $globalVar = $symbolTable->getVariable($name);
                $codePrinter->preOutput("\t".$compilationContext->backend->fetchGlobal($globalVar, $compilationContext, false));
            }
            if ($variable->isLocalSatic()) {
                $staticVar = $symbolTable->getVariable($name);

                $codePrinter->preOutput(sprintf(
                    "\t".'zephir_read_static_property_ce(%s%s, %s, SL("%s"), PH_NOISY_CC%s);',
                    $staticVar->isDoublePointer() ? '' : '&',
                    $staticVar->getName(),
                    $this->classDefinition->getClassEntry(),
                    $staticVar->getName(),
                    ''
                ));
            }
        }

        /*
         * Grow the stack if needed
         */
        if ($symbolTable->getMustGrownStack()) {
            $compilationContext->headersManager->add('kernel/memory');
            $codePrinter->preOutput("\t".'ZEPHIR_MM_GROW();');
        }

        /**
         * Check if there are unused variables.
         */
        $usedVariables = [];
        $classDefinition = $this->getClassDefinition();
        if ($classDefinition) {
            $completeName = $classDefinition->getCompleteName();
        } else {
            $completeName = '[unknown]';
        }

        foreach ($symbolTable->getVariables() as $variable) {
            if ($variable->getNumberUses() <= 0) {
                if (false == $variable->isExternal()) {
                    $compilationContext->logger->warning(
                        'Variable "'.$variable->getName().'" declared but not used in '.$completeName.'::'.$this->getName(),
                        ['unused-variable', $variable->getOriginal()]
                    );
                    continue;
                }
                $compilationContext->logger->warning(
                    'Variable "'.$variable->getName().'" declared but not used in '.$completeName.'::'.$this->getName(),
                    ['unused-variable-external', $variable->getOriginal()]
                );
            }

            if ('this_ptr' != $variable->getName() && 'return_value' != $variable->getName() && 'return_value_ptr' != $variable->getName()) {
                $type = $variable->getType();
                if (!isset($usedVariables[$type])) {
                    $usedVariables[$type] = [];
                }
                $usedVariables[$type][] = $variable;
            }
        }

        /*
         * Check if there are assigned but not used variables
         * Warn whenever a variable is unused aside from its declaration.
         */
        foreach ($symbolTable->getVariables() as $variable) {
            if (true == $variable->isExternal() || $variable->isTemporal()) {
                continue;
            }

            if ('this_ptr' == $variable->getName() || 'return_value' == $variable->getName() || 'return_value_ptr' == $variable->getName() || 'ZEPHIR_LAST_CALL_STATUS' == $variable->getName()) {
                continue;
            }

            if (!$variable->isUsed()) {
                $node = $variable->getLastUsedNode();
                if (\is_array($node)) {
                    $expression = isset($node['expr']) ? $node['expr'] : $node;
                    $compilationContext->logger->warning(
                        'Variable "'.$variable->getName().'" assigned but not used in '.$completeName.'::'.$this->getName(),
                        ['unused-variable', $expression]
                    );
                } else {
                    $compilationContext->logger->warning(
                        'Variable "'.$variable->getName().'" assigned but not used in '.$completeName.'::'.$this->getName(),
                        ['unused-variable', $variable->getOriginal()]
                    );
                }
            }
        }

        if (\count($usedVariables)) {
            $codePrinter->preOutputBlankLine();
        }

        /**
         * Generate the variable definition for variables used.
         */
        $initCode = "\t".implode(PHP_EOL."\t", $compilationContext->backend->declareVariables($this, $usedVariables, $compilationContext));
        if ($initCode) {
            $codePrinter->preOutput($initCode);
        }

        /*
         * Finalize the method compilation
         */
        if (\is_object($this->statements)) {
            /**
             * If the last statement is not a 'return' or 'throw' we need to
             * restore the memory stack if needed.
             */
            $lastType = $this->statements->getLastStatementType();

            if ('return' != $lastType && 'throw' != $lastType && !$this->hasChildReturnStatementType($this->statements->getLastStatement())) {
                if ($symbolTable->getMustGrownStack()) {
                    $compilationContext->headersManager->add('kernel/memory');
                    $codePrinter->output("\t".'ZEPHIR_MM_RESTORE();');
                }

                /*
                 * If a method has return-type hints we need to ensure the last statement is a 'return' statement
                 */
                if ($this->hasReturnTypes()) {
                    throw new CompilerException(
                        'Reached end of the method without returning a valid type specified in the return-type hints',
                        $this->expression['return-type']
                    );
                }
            }
        }

        $compilationContext->backend->onPostCompile($this, $compilationContext);

        /**
         * Remove macros that grow/restore the memory frame stack if it wasn't used.
         */
        $code = $this->removeMemoryStackReferences($symbolTable, $codePrinter->getOutput());

        /*
         * Restore the compilation context
         */
        $oldCodePrinter->output($code);
        $compilationContext->codePrinter = $oldCodePrinter;

        $compilationContext->branchManager = null;
        $compilationContext->cacheManager = null;
        $compilationContext->typeInference = null;

        $codePrinter->clear();

        return null;
    }

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


Question:
convert channelsArray to bitmask format

        Args:
            channelsArray: channel array (i.e. [21, 22])

        Returns:
            bitmask format corresponding to a given channel array

def __convertChannelMask(self, channelsArray):

        maskSet = 0

        for eachChannel in channelsArray:
            mask = 1 << eachChannel
            maskSet = (maskSet | mask)

        return maskSet

func MakeTagsKey(keys []string, tags models.Tags) []byte {
	// precondition: keys is sorted
	// precondition: models.Tags is sorted

	// Empty maps marshal to empty bytes.
	if len(keys) == 0 || len(tags) == 0 {
		return nil
	}

	sel := make([]int, 0, len(keys))

	sz := 0
	i, j := 0, 0
	for i < len(keys) && j < len(tags) {
		if keys[i] < string(tags[j].Key) {
			i++
		} else if keys[i] > string(tags[j].Key) {
			j++
		} else {
			sel = append(sel, j)
			sz += len(keys[i]) + len(tags[j].Value)
			i++
			j++
		}
	}

	if len(sel) == 0 {
		// no tags matched the requested keys
		return nil
	}

	sz += (len(sel) * 2) - 1 // selected tags, add separators

	// Generate marshaled bytes.
	b := make([]byte, sz)
	buf := b
	for _, k := range sel {
		copy(buf, tags[k].Key)
		buf[len(tags[k].Key)] = '|'
		buf = buf[len(tags[k].Key)+1:]
	}

	for i, k := range sel {
		copy(buf, tags[k].Value)
		if i < len(sel)-1 {
			buf[len(tags[k].Value)] = '|'
			buf = buf[len(tags[k].Value)+1:]
		}
	}

	return b
}

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


Question:
Imperial Gallons

@return

public MDecimal getImpGallon() {
		MDecimal result = new MDecimal(currentUnit.getConverterTo(GALLON_UK)
				.convert(doubleValue()));
		logger.trace(MMarker.GETTER,
				"Converting from {} to Imperial Gallons : {}", currentUnit,
				result);
		return result;
	}

func (j *JsonHelper) GobDecode(data []byte) error {
	var mv map[string]interface{}
	if err := json.Unmarshal(data, &mv); err != nil {
		return err
	}
	*j = JsonHelper(mv)
	return nil
}

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


Question: // Infof info log

func (logger *Logger) Infof(m string, args ...interface{}) {
	logger.log(INFO, m, args...)
}

func (r *Containerd) ContainerLogCmd(id string, len int, follow bool) string {
	return criContainerLogCmd(id, len, follow)
}

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


Question:
Execute a raw SQL query on the database.

@param string $sql Raw SQL string to execute.
@param array &$values Optional array of bind values
@return mixed A result set object

public function query($sql, &$values=array())
	{
		if ($this->logging)
		{
			if ($values) {
				$this->logger->addInfo($sql, $values);
			} else {
				$this->logger->addInfo($sql);
			}
		}

		$this->lastQuery = $sql;
		try {
			if (!($sth = $this->connection->prepare($sql)))
				throw new DatabaseException($this);
		} catch (PDOException $e) {
			throw new DatabaseException($this);
		}

		$sth->setFetchMode(PDO::FETCH_ASSOC);

		try {
			if (!$sth->execute($values))
				throw new DatabaseException($this);
		} catch (PDOException $e) {
			throw new DatabaseException($e);
		}
		return $sth;
	}

private function _mysqli()
    {
        if (!isset($this->_link)) {
            mysqli_report(MYSQLI_REPORT_OFF);

            if(!$this->_link = mysqli_init())
                throw new Exception("Mysql initialization failed");

            $sqlMode = $this->_strict ? 'TRADITIONAL' : '';
            $this->_link->options(MYSQLI_INIT_COMMAND, "SET SESSION sql_mode = '{$sqlMode}'");
            $this->_link->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);

            @$this->_link->real_connect(
                $this->_dsn->host, $this->_dsn->user, $this->_dsn->pass,
                $this->_dsn->database, $this->_dsn->port
            );

            if ($this->_link->connect_error)
                throw new Exception("Failed to connect to mysql: {$this->_link->connect_error}", $this->_link->connect_errno);

            if (!$this->_link->set_charset($this->_charset))
                throw new Exception(sprintf("Error setting character to %s: %s", $this->_charset, $this->_link->error));
        }

        return $this->_link;
    }

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


Question:
Sets the site value for this URI.

 @param [String, #to_str] new_site The new site value.

def site=(new_site)
      if new_site
        if !new_site.respond_to?(:to_str)
          raise TypeError, "Can't convert #{new_site.class} into String."
        end
        new_site = new_site.to_str
        # These two regular expressions derived from the primary parsing
        # expression
        self.scheme = new_site[/^(?:([^:\/?#]+):)?(?:\/\/(?:[^\/?#]*))?$/, 1]
        self.authority = new_site[
          /^(?:(?:[^:\/?#]+):)?(?:\/\/([^\/?#]*))?$/, 1
        ]
      else
        self.scheme = nil
        self.authority = nil
      end
    end

def translated_attributes
      attributes = {}
      translations = []
      translations << { :var => 'client_id', :xml_var => 'ClientID' }
      translations << { :var => 'concat', :xml_var => 'Concat' }
      translations << { :var => 'from', :xml_var => 'From' }
      translations << { :var => 'invalid_char_action', :xml_var => 'InvalidCharAction' }
      translations << { :var => 'content', :xml_var => 'Content' }
      translations << { :var => 'to', :xml_var => 'To' }
      translations << { :var => 'truncate', :xml_var => 'Truncate' }
      translations << { :var => 'wrapper_id', :xml_var => 'WrapperID' }

      translations.each do |t|
        self.instance_variable_set( "@#{t[:var]}", @api.instance_variable_get( "@#{t[:var]}" ) ) if self.instance_variable_get( "@#{t[:var]}" ).nil?
        attributes[ t[:xml_var] ] = self.instance_variable_get( "@#{t[:var]}" ) unless self.instance_variable_get( "@#{t[:var]}" ).nil?
      end

      attributes
    end

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


Question:
Copy if anyconfig.utils.get_file_extension is not available.

    >>> get_file_extension("/a/b/c")
    ''
    >>> get_file_extension("/a/b.txt")
    'txt'
    >>> get_file_extension("/a/b/c.tar.xz")
    'xz'

def get_file_extension(filepath):

    _ext = os.path.splitext(filepath)[-1]
    if _ext:
        return _ext[1:] if _ext.startswith('.') else _ext

    return ''

def extract_tarfile(archive_name, destpath):
    ""
    archive = tarfile.open(archive_name)
    archive.extractall(destpath)

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


Question:
@param int $keep
@param string $status

@return array

@throws \eZ\Publish\Core\Base\Exceptions\InvalidArgumentException

protected function getObjectsIds($keep, $status)
    {
        $query = $this->connection->createQueryBuilder()
                ->select('c.id')
                ->from('ezcontentobject', 'c')
                ->join('c', 'ezcontentobject_version', 'v', 'v.contentobject_id = c.id')
                ->groupBy('c.id', 'v.status')
                ->having('count(c.id) > :keep');
        $query->setParameter('keep', $keep);

        if ($status !== self::VERSION_ALL) {
            $query->where('v.status = :status');
            $query->setParameter('status', $this->mapStatusToVersionInfoStatus($status));
        } else {
            $query->andWhere('v.status != :status');
            $query->setParameter('status', $this->mapStatusToVersionInfoStatus(self::VERSION_PUBLISHED));
        }

        $stmt = $query->execute();

        return $stmt->fetchAll(PDO::FETCH_COLUMN);
    }

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:
Given a plugin name, load plugin cls from plugin directory.
    Will throw an exception if no plugin can be found.

def load_plugin(plugin_name):

    plugin_cls = plugin_map.get(plugin_name, None)
    if not plugin_cls:
        try:
            plugin_module_name, plugin_cls_name = plugin_name.split(":")
            plugin_module = import_module(plugin_module_name)
            plugin_cls = getattr(plugin_module, plugin_cls_name)
        except ValueError:
            raise click.ClickException(
                '"{}" is not a valid plugin path'.format(plugin_name)
            )
        except ImportError:
            raise click.ClickException(
                '"{}" does not name a Python module'.format(
                    plugin_module_name
                )
            )
        except AttributeError:
            raise click.ClickException(
                'Module "{}" does not contain the class "{}"'.format(
                    plugin_module_name, plugin_cls_name
                )
            )
    return plugin_cls

public static ExpressionException invalidKey(Config config, Struct sct, Key key, String in) {
	String appendix = StringUtil.isEmpty(in, true) ? "" : " in the " + in;
	Iterator<Key> it = sct.keyIterator();
	Key k;

	while (it.hasNext()) {
	    k = it.next();
	    if (k.equals(key)) return new ExpressionException("the value from key [" + key.getString() + "] " + appendix + " is NULL, which is the same as not existing in CFML");
	}
	config = ThreadLocalPageContext.getConfig(config);
	if (config != null && config.debug()) return new ExpressionException(ExceptionUtil.similarKeyMessage(sct, key.getString(), "key", "keys", in, true));

	return new ExpressionException("key [" + key.getString() + "] doesn't exist" + appendix);
    }

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


Question:
Get the WriteFuture with a timeout based on the length of the slice to write.

@param sliceLength
@return true if successful and false otherwise

private boolean acquireWriteFuture(int sliceLength) {
        if (sliceLength > 0) {
            Object writeResult = null;
            // determine a good timeout value based on the slice length to write
            int timeout = sliceLength * 500;
            // check for existing future
            if (writerFuture != null) {
                try {
                    // wait for a result from the last writer
                    writeResult = writerFuture.get(timeout, TimeUnit.MILLISECONDS);
                } catch (Exception e) {
                    log.warn("Exception waiting for write result. Timeout: {}ms", timeout, e);
                    return false;
                }
            }
            log.debug("Write future result (expect null): {}", writeResult);
            return true;
        }
        return false;
    }

def _flush(self):

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

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

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


Question:
common destroy data method for class data lists

@param string $key
@param string $type
@return $this

protected function _genericDestroy($key, $type)
    {
        $listName = $this->_getCorrectList($type);

        if ($key) {
            $list = &$this->$listName;
            unset ($list[$key]);
        }
        $this->$listName = [];

        return $this;
    }

def get_delete_api(self, resource):

        parameters = self.delete_item_parameters(resource)

        get_item_api = {
            'path': '/%s/{id}/' % resource.get_api_name(),
            'description': 'Operations on %s' % resource.model.__name__,
            "responseClass": "void",
            'operations': [
                {
                    'httpMethod': 'DELETE',
                    'nickname': 'delete%s' % resource.model.__name__,
                    'summary': 'Delete %s by its unique ID' %
                               resource.model.__name__,
                    'parameters': parameters,
                }
            ]
        }

        return get_item_api

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


Question:
@param Drop $drop

@return array

public function serialize(Drop $drop)
    {
        return [
            'id' => $drop->getUuid(),
            'user' => $drop->getUser() ? $this->userSerializer->serialize($drop->getUser()) : null,
            'dropDate' => $drop->getDropDate() ? $drop->getDropDate()->format('Y-m-d H:i') : null,
            'score' => $drop->getScore(),
            'reported' => $drop->isReported(),
            'finished' => $drop->isFinished(),
            'autoClosedDrop' => $drop->getAutoClosedDrop(),
            'unlockedDrop' => $drop->isUnlockedDrop(),
            'unlockedUser' => $drop->isUnlockedUser(),
            'teamId' => $drop->getTeamUuid(),
            'teamName' => $drop->getTeamName(),
            'documents' => $this->getDocuments($drop),
            'corrections' => $this->getCorrections($drop),
            'users' => $this->getUsers($drop),
        ];
    }

public function actionDrop()
    {
        $stdout = '';
        foreach ($this->db->schema->getTableSchemas() as $table) {
            if ($table->name === $this->migrationTable) {
                continue;
            }
            $stdout .= static::generateDropTable($table->name);
            if (!empty($table->foreignKeys)) {
                $stdout .= ' // fk: ';

                foreach ($table->foreignKeys as $fk) {
                    foreach ($fk as $k => $v) {
                        if (0 === $k) {
                            continue;
                        }
                        $stdout .= "$k, ";
                    }
                }
                $stdout = rtrim($stdout, ', ');
            }
            $stdout .= "\n";
        }
        $this->stdout($stdout);
    }

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


Question:
Factory method for Endpoint list
@param client the user client
@param domainId the domain id.
@param page the starting page.
@param size the page size.
@return the Endpoint list.

public static ResourceList<Endpoint> list(final BandwidthClient client, final String domainId, final int page, final int size) {
        assert(domainId != null);
        assert(page  >= 0);
        assert(size > 0);
        final String resourceUri = String.format(client.getUserResourceUri(BandwidthConstants.ENDPOINTS_URI_PATH), domainId);
        final ResourceList<Endpoint> endpoints = new ResourceList<Endpoint>(page, size, resourceUri, Endpoint.class);
        endpoints.setClient(client);
        endpoints.initialize();
        return endpoints;
    }

public void marshall(DescribeDomainControllersRequest describeDomainControllersRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeDomainControllersRequest.getDirectoryId(), DIRECTORYID_BINDING);
            protocolMarshaller.marshall(describeDomainControllersRequest.getDomainControllerIds(), DOMAINCONTROLLERIDS_BINDING);
            protocolMarshaller.marshall(describeDomainControllersRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(describeDomainControllersRequest.getLimit(), LIMIT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
@param string $key
@param string $replacement
@param bool   $existingOnly

@return Promise
@yield bool

public function rename($key, $replacement, $existingOnly = false) {
        $cmd = $existingOnly ? 'renamenx' : 'rename';

        return $this->send([$cmd, $key, $replacement], function ($response) use ($existingOnly) {
            return $existingOnly || (bool) $response;
        });
    }

def addReplaceDBPage( dbid, pageid, pagename, pagetype, pagebody, ignoreError = nil )

      @dbid, @pageid, @pagename, @pagetype, @pagebody, @ignoreError = dbid, pageid, pagename, pagetype, pagebody, ignoreError

      if pageid
         xmlRequestData = toXML( :pageid, @pageid )
      elsif pagename
         xmlRequestData = toXML( :pagename, @pagename )
      else
         raise "addReplaceDBPage: missing pageid or pagename"
      end

      xmlRequestData << toXML( :pagetype, @pagetype )
      xmlRequestData << toXML( :pagebody, encodeXML( @pagebody ) )
      xmlRequestData << toXML( :ignoreError, "1" ) if @ignoreError

      sendRequest( :addReplaceDBPage, xmlRequestData )

      @pageid = getResponseValue( :pageid )
      @pageid ||= getResponseValue( :pageID ) # temporary

      return self if @chainAPIcalls
      @pageid
    end

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


Question: Validate configuration.

def validate(defaults, metadata, config):

    for path, _, default, parent, value in zip_dicts(defaults, config):
        if isinstance(default, Requirement):
            # validate the current value and assign the output
            parent[path[-1]] = default.validate(metadata, path, value)

public function setConfig(array $config, $loopMerge = true)
    {
        $this->config = $loopMerge ? Arr::merge($this->config, $config) : $config;

        return $this;
    }

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


Question:
Peeks for token into the FIFO.

        Performs the same function as readuntil() without removing data from the
        FIFO. See readuntil() for further information.

def peekuntil(self, token, size=0):

        self.__append()

        i = self.buf.find(token, self.pos)
        if i < 0:
            index = max(len(token) - 1, size)
            newpos = max(len(self.buf) - index, self.pos)
            return False, self.buf[self.pos:newpos]

        newpos = i + len(token)
        return True, self.buf[self.pos:newpos]

def _load_file(self, log_file, message_name_filter_list):

        if isinstance(log_file, str):
            self._file_handle = open(log_file, "rb")
        else:
            self._file_handle = log_file

        # parse the whole file
        self._read_file_header()
        self._last_timestamp = self._start_timestamp
        self._read_file_definitions()

        if self.has_data_appended and len(self._appended_offsets) > 0:
            if self._debug:
                print('This file has data appended')
            for offset in self._appended_offsets:
                self._read_file_data(message_name_filter_list, read_until=offset)
                self._file_handle.seek(offset)

        # read the whole file, or the rest if data appended
        self._read_file_data(message_name_filter_list)

        self._file_handle.close()
        del self._file_handle

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


Question:
return column names as Key from a query

@param qry
@return

public static Key[] getColumnNames(Query qry) {
	Query qp = Caster.toQuery(qry, null);

	if (qp != null) return qp.getColumnNames();
	String[] strNames = qry.getColumns();
	Key[] names = new Key[strNames.length];
	for (int i = 0; i < names.length; i++) {
	    names[i] = KeyImpl.getInstance(strNames[i]);
	}
	return names;
    }

public void getModelGeneratedKey(Model<?> model, PreparedStatement pst, Table table) throws SQLException {
		String[] pKeys = table.getPrimaryKey();
		ResultSet rs = pst.getGeneratedKeys();
		for (String pKey : pKeys) {
			if (model.get(pKey) == null || isOracle()) {
				if (rs.next()) {
					Class<?> colType = table.getColumnType(pKey);
					if (colType != null) {	// 支持没有主键的用法，有人将 model 改造成了支持无主键:济南-费小哥
						if (colType == Integer.class || colType == int.class) {
							model.set(pKey, rs.getInt(1));
						} else if (colType == Long.class || colType == long.class) {
							model.set(pKey, rs.getLong(1));
						} else if (colType == BigInteger.class) {
							processGeneratedBigIntegerKey(model, pKey, rs.getObject(1));
						} else {
							model.set(pKey, rs.getObject(1));	// It returns Long for int colType for mysql
						}
					}
				}
			}
		}
		rs.close();
	}

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


public List<String> getAnnotations() {
        AnnotationBuilder result = new AnnotationBuilder();
        result.add(getNotNullAnnotation());
        return result.getAnnotations();
    }

def process_input_buffer():
    """"""
    from polysh.control_commands_helpers import handle_control_command
    data = the_stdin_thread.input_buffer.get()
    remote_dispatcher.log(b'> ' + data)

    if data.startswith(b':'):
        try:
            handle_control_command(data[1:-1].decode())
        except UnicodeDecodeError as e:
            console_output(b'Could not decode command.')
        return

    if data.startswith(b'!'):
        try:
            retcode = subprocess.call(data[1:], shell=True)
        except OSError as e:
            if e.errno == errno.EINTR:
                console_output(b'Child was interrupted\n')
                retcode = 0
            else:
                raise
        if retcode > 128 and retcode <= 192:
            retcode = 128 - retcode
        if retcode > 0:
            console_output('Child returned {:d}\n'.format(retcode).encode())
        elif retcode < 0:
            console_output('Child was terminated by signal {:d}\n'.format(
                -retcode).encode())
        return

    for r in dispatchers.all_instances():
        try:
            r.dispatch_command(data)
        except asyncore.ExitNow as e:
            raise e
        except Exception as msg:
            raise msg
            console_output('{} for {}, disconnecting\n'.format(
                str(msg), r.display_name).encode())
            r.disconnect()
        else:
            if r.enabled and r.state is remote_dispatcher.STATE_IDLE:
                r.change_state(remote_dispatcher.STATE_RUNNING)

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


Question:
Set stretch factors.

        Parameters
        ----------
        scale_x_base, scale_y_base : float
            Stretch factors for X and Y, respectively.

def set_scale_base_xy(self, scale_x_base, scale_y_base):

        self.t_.set(scale_x_base=scale_x_base, scale_y_base=scale_y_base)

def write_to_screen(self, cli, screen, mouse_handlers, write_position):

        if not self.children:
            return

        sizes = self._divide_widths(cli, write_position.width)

        if self.report_dimensions_callback:
            self.report_dimensions_callback(cli, sizes)

        # If there is not enough space.
        if sizes is None:
            self.window_too_small.write_to_screen(
                cli, screen, mouse_handlers, write_position)
            return

        # Calculate heights, take the largest possible, but not larger than write_position.extended_height.
        heights = [child.preferred_height(cli, width, write_position.extended_height).preferred
                   for width, child in zip(sizes, self.children)]
        height = max(write_position.height, min(write_position.extended_height, max(heights)))

        # Draw child panes.
        ypos = write_position.ypos
        xpos = write_position.xpos

        for s, c in zip(sizes, self.children):
            c.write_to_screen(cli, screen, mouse_handlers, WritePosition(xpos, ypos, s, height))
            xpos += s

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


Question:
Delete method

@param string $id Dashboard id.
@return \Cake\Http\Response|void|null Redirects to index.

public function delete(string $id)
    {
        $this->request->allowMethod(['post', 'delete']);
        $dashboard = $this->Dashboards->get($id);

        if ($this->Dashboards->delete($dashboard)) {
            /** @var \Search\Model\Table\WidgetsTable */
            $widgetTable = TableRegistry::get('Search.Widgets');
            $widgetTable->trashAll([
                'dashboard_id' => $id
            ]);

            $this->Flash->success((string)__('The dashboard has been deleted.'));
        } else {
            $this->Flash->error((string)__('The dashboard could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }

func (c *Client) DeleteDomain(p *DeleteDomainParameter) (*Result, error) {
	obj, err := c.Request("deleteDomain", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Result), err
}

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


Question:
Whether this is a method or function.

        :returns: 'method' if this is a method, 'function' otherwise.
        :rtype: str

def type(self):

        # pylint: disable=no-member
        if self.args.args and self.args.args[0].name == "self":
            if isinstance(self.parent.scope(), ClassDef):
                return "method"
        return "function"

func (*Model) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
	return _Model_OneofMarshaler, _Model_OneofUnmarshaler, _Model_OneofSizer, []interface{}{
		(*Model_TranslationModelMetadata)(nil),
		(*Model_ImageClassificationModelMetadata)(nil),
		(*Model_TextClassificationModelMetadata)(nil),
		(*Model_ImageObjectDetectionModelMetadata)(nil),
		(*Model_VideoClassificationModelMetadata)(nil),
		(*Model_TextExtractionModelMetadata)(nil),
		(*Model_TablesModelMetadata)(nil),
		(*Model_TextSentimentModelMetadata)(nil),
	}
}

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


Question: Converts a {@link SafeUrlProto} into a Soy {@link SanitizedContent} of kind URI.

public static SanitizedContent fromSafeUrlProto(SafeUrlProto url) {
    return SanitizedContent.create(SafeUrls.fromProto(url).getSafeUrlString(), ContentKind.URI);
  }

func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool {

	// Force new line.
	if parser.mark.column != 0 {
		parser.mark.column = 0
		parser.mark.line++
	}

	// Reset the indentation level.
	if !yaml_parser_unroll_indent(parser, -1) {
		return false
	}

	// Reset simple keys.
	if !yaml_parser_remove_simple_key(parser) {
		return false
	}

	parser.simple_key_allowed = false

	// Create the STREAM-END token and append it to the queue.
	token := yaml_token_t{
		typ:        yaml_STREAM_END_TOKEN,
		start_mark: parser.mark,
		end_mark:   parser.mark,
	}
	yaml_insert_token(parser, -1, &token)
	return true
}

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


Question:
@param PointAnnotation $objectAnnotation
@param string          $className

@return void

private static function collectPointAnnotation(PointAnnotation $objectAnnotation, string $className)
    {
        if (!isset(self::$aspects[$className])) {
            return null;
        }

        $include = $objectAnnotation->getInclude();
        $exclude = $objectAnnotation->getExclude();

        self::$aspects[$className]['point']['annotation'] = [
            'include' => $include,
            'exclude' => $exclude,
        ];
    }

public function InstanceOfExpression()
    {
        $instanceOfExpression = new AST\InstanceOfExpression($this->IdentificationVariable());

        if ($this->lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $instanceOfExpression->not = true;
        }

        $this->match(Lexer::T_INSTANCE);
        $this->match(Lexer::T_OF);

        $exprValues = array();

        if ($this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) {
            $this->match(Lexer::T_OPEN_PARENTHESIS);

            $exprValues[] = $this->InstanceOfParameter();

            while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
                $this->match(Lexer::T_COMMA);

                $exprValues[] = $this->InstanceOfParameter();
            }

            $this->match(Lexer::T_CLOSE_PARENTHESIS);

            $instanceOfExpression->value = $exprValues;

            return $instanceOfExpression;
        }

        $exprValues[] = $this->InstanceOfParameter();

        $instanceOfExpression->value = $exprValues;

        return $instanceOfExpression;
    }

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


Question:
Filters the current page of results by the given column and value.

@param columnName String column name to filter by
@param filterValue Serializable matching value
@return List results
@throws HelloSignException thrown if the column name is invalid

public List<E> filterCurrentPageBy(String columnName, Serializable filterValue) throws HelloSignException {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        @SuppressWarnings("unchecked")
        Class<E> clazz = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
        return getList(clazz, listKey, filterValue, columnName);
    }

public static Result convert(final Object res) throws QConnectorException {
		if (res == null) {
			return new EmptyResult();
		}
		// table
		if (res instanceof c.Flip) {
			return new FlipResult("", (c.Flip) res);
		}
		// dict
		if (res instanceof c.Dict) {
			final c.Dict dict = (c.Dict) res;
			if ((dict.x instanceof c.Flip) && (dict.y instanceof c.Flip)) {
				final c.Flip key = (c.Flip) dict.x;
				final c.Flip data = (c.Flip) dict.y;
				return new FlipFlipResult("", key, data);
			}
		}
		if (res instanceof Object[]) {
			final Object[] oa = (Object[]) res;
			if ((oa.length == 2) && (oa[0] instanceof String) && (oa[1] instanceof c.Flip)) {
				final String table = (String) oa[0];
				final c.Flip flip = (c.Flip) oa[1];
				return new FlipResult(table, flip);
			} else if ((oa.length == 3) && (oa[1] instanceof String) && (oa[2] instanceof c.Flip)) {
				final String table = (String) oa[1];
				final c.Flip flip = (c.Flip) oa[2];
				return new FlipResult(table, flip);
			} else {
				return new ListResult<Object>(oa);
			}
		}
		// list
		if (res instanceof byte[]) {
			return new ListResult<Byte>(ArrayUtils.toObject((byte[]) res));
		}

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


Question:
Make regex string for ``PluggableSite`` urlpatterns: prepend url
            with parent object's url and app name.

            See also: http://code.djangoproject.com/ticket/11559.

def make_regex(self, url):
        '''

        '''
        return r"^%s/%s%s$" % (self.object_getter.regex, self.app_name, url)

def requires_product_environment(func, *args, **kws):

    from django_productline import startup
    startup.select_product()
    return func(*args, **kws)

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


Question:
First, resolves correct instance of WebPage.  Next, handles security
mode, authentication check, and redirects.  Anything left goes on to doGet.

@see  #doGet(WebSiteRequest,HttpServletResponse)

@Override
	final protected void reportingDoGet(HttpServletRequest httpReq, HttpServletResponse resp) throws ServletException, IOException, SQLException {
		WebSiteRequest req=getWebSiteRequest(httpReq);
		WebPage page=getWebPage(getClass(), req);
		// Logout when requested
		boolean isLogout="true".equals(req.getParameter("logout_requested"));
		if(isLogout) req.logout(resp);

		// Check authentication first and return HTTP error code
		boolean alreadyDone=false;
		if("true".equals(req.getParameter("login_requested"))) {
			page.printLoginForm(page, new LoginException("Please Login"), req, resp);
			alreadyDone = true;
		}
		if(!alreadyDone) {
			try {
				WebSiteUser user=req.getWebSiteUser(resp);
				if(!page.canAccess(user)) {
					page.printUnauthorizedPage(page, req, resp);
					alreadyDone=true;
				}
			} catch(LoginException err) {
				page.printLoginForm(page, err, req, resp);
				alreadyDone=true;
			}
		}
		if(!alreadyDone) {
			String redirect=page.getRedirectURL(req);
			if(redirect!=null) {
				ServletUtil.sendRedirect(req, resp, redirect, page.getRedirectType());
			} else {
				page.doGet(req, resp);
			}
		}
	}

public static Cookie findCookie(HttpServletRequest request, String name) {
        if (request != null) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(name)) {
                        return cookie;
                    }
                }
            }
        }
        return null;
    }

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


Question:
Edit Action
GET | PUT

@param $id

public function edit($id)
    {
        $this->request->allowMethod(['get', 'put']);

        $menu = $this->Menus->get($id);

        if ($this->request->is('put')) {
            $menu = $this->Menus->patchEntity($menu, $this->request->data);
            if ($this->Menus->save($menu)) {
                $this->Flash->success(__d('wasabi_core', 'The menu <strong>{0}</strong> has been saved.', $this->request->data['name']));
                $this->redirect(['action' => 'index']);
                return;
            } else {
                $this->Flash->error($this->formErrorMessage);
            }
        }
        $this->set([
            'menu' => $menu,
            'menuItems' => $this->MenuItems->find('threaded', ['order' => ['lft' => 'ASC']])->where(['MenuItems.menu_id' => $id])->hydrate(false)
        ]);
        $this->render('add');
    }

function setActionParameter( $parameterName, $parameterValue, $view = '' )
    {
        if ( $view == '' )
            $view = self::currentView();
        $this->ViewActionParameters[$view][$parameterName] = $parameterValue;
    }

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


Question:
{@inheritdoc}

@throws Exception

public function offsetSet($key, $value)
    {
        if ($key === null) {
            $this->items[] = $this->referenceEntityFactory($value);
        } else {
            $this->items[$key] = $this->referenceEntityFactory($value);
        }
    }

private void exportInternalAPI(ClassLoader cl) {
        String[] packages = {
            "com.sun.tools.doclets",
            "com.sun.tools.doclets.standard",
            "com.sun.tools.doclets.internal.toolkit",
            "com.sun.tools.doclets.internal.toolkit.taglets",
            "com.sun.tools.doclets.internal.toolkit.builders",
            "com.sun.tools.doclets.internal.toolkit.util",
            "com.sun.tools.doclets.internal.toolkit.util.links",
            "com.sun.tools.doclets.formats.html",
            "com.sun.tools.doclets.formats.html.markup"
        };

        try {
            Method getModuleMethod = Class.class.getDeclaredMethod("getModule");
            Object thisModule = getModuleMethod.invoke(getClass());

            Class<?> moduleClass = Class.forName("java.lang.Module");
            Method addExportsMethod = moduleClass.getDeclaredMethod("addExports", String.class, moduleClass);

            Method getUnnamedModuleMethod = ClassLoader.class.getDeclaredMethod("getUnnamedModule");
            Object target = getUnnamedModuleMethod.invoke(cl);

            for (String pack : packages) {
                addExportsMethod.invoke(thisModule, pack, target);
            }
        } catch (Exception e) {
            // do nothing
        }
    }

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


Question:
Monkey patching PIL.Image.open method

    Args:
        enabled (bool): If the monkey patch should be activated or deactivated.

def monkey_patch(enabled=True):

    if enabled:
        Image.open = imdirect_open
    else:
        Image.open = pil_open

def deprecated(context):
    """"""
    tar = context.get('tar', None)

    # at least 1 of tarExtract or tarArchive must exist in context
    tar_extract, tar_archive = context.keys_of_type_exist(
        ('tarExtract', list),
        ('tarArchive', list))

    found_at_least_one = (tar_extract.key_in_context
                          or tar_archive.key_in_context)

    if tar and not found_at_least_one:
        return
    elif found_at_least_one:
        tar = context['tar'] = {}

    if tar_extract.key_in_context and tar_extract.is_expected_type:
        tar['extract'] = context[tar_extract.key]

    if tar_archive.key_in_context and tar_archive.is_expected_type:
        tar['archive'] = context[tar_archive.key]

    if 'tarFormat' in context:
        tar['format'] = context['tarFormat']

    logger.warning("tarExtract and tarArchive are deprecated. They will "
                   "stop working upon the next major release. "
                   "Use the new context key env instead. It's a lot "
                   "better, promise! For the moment pypyr is creating the "
                   "new env key for you under the hood.")

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


Question:
// CreatePlanCost corresponds to the POST /id/plan/:id/cost endpoint.
//
// Get plan cost
// Get how much a plan would cost when using a set of features

func (c *IDClient) CreatePlanCost(ctx context.Context, id gomanifold.ID, planCostRequest *PlanCostRequest) (*Price, error) {
	idBytes, err := id.MarshalText()
	if err != nil {
		return nil, err
	}

	p := fmt.Sprintf("/id/plan/%s/cost", string(idBytes))

	req, err := c.backend.NewRequest(http.MethodPost, p, nil, planCostRequest)
	if err != nil {
		return nil, err
	}

	var resp Price
	_, err = c.backend.Do(ctx, req, &resp, func(code int) error {
		switch code {
		case 400, 404, 500:
			return &Error{}
		default:
			return nil
		}
	})
	if err != nil {
		return nil, err
	}

	return &resp, nil
}

func (c *Client) PutPolicy(vhost string, name string, policy Policy) (res *http.Response, err error) {
	body, err := json.Marshal(policy)
	if err != nil {
		return nil, err
	}

	req, err := newRequestWithBody(c, "PUT", "policies/"+PathEscape(vhost)+"/"+PathEscape(name), body)
	if err != nil {
		return nil, err
	}

	res, err = executeRequest(c, req)
	if err != nil {
		return nil, err
	}

	return res, nil
}

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


Question:
Count the competencies (visible to this user) in this course.

@param int $courseid The course id to check.
@param int $competencyid Competency id.
@return int

public static function add_competency_to_course($courseid, $competencyid) {
        $params = self::validate_parameters(self::add_competency_to_course_parameters(), array(
            'courseid' => $courseid,
            'competencyid' => $competencyid,
        ));
        self::validate_context(context_course::instance($params['courseid']));
        return api::add_competency_to_course($params['courseid'], $params['competencyid']);
    }

public static function get_metadata(collection $collection) : collection {
        $collection->add_database_table('scorm_scoes_track', [
                'userid' => 'privacy:metadata:userid',
                'attempt' => 'privacy:metadata:attempt',
                'element' => 'privacy:metadata:scoes_track:element',
                'value' => 'privacy:metadata:scoes_track:value',
                'timemodified' => 'privacy:metadata:timemodified'
            ], 'privacy:metadata:scorm_scoes_track');

        $collection->add_database_table('scorm_aicc_session', [
                'userid' => 'privacy:metadata:userid',
                'scormmode' => 'privacy:metadata:aicc_session:scormmode',
                'scormstatus' => 'privacy:metadata:aicc_session:scormstatus',
                'attempt' => 'privacy:metadata:attempt',
                'lessonstatus' => 'privacy:metadata:aicc_session:lessonstatus',
                'sessiontime' => 'privacy:metadata:aicc_session:sessiontime',
                'timecreated' => 'privacy:metadata:aicc_session:timecreated',
                'timemodified' => 'privacy:metadata:timemodified',
            ], 'privacy:metadata:scorm_aicc_session');

        $collection->add_external_location_link('aicc', [
                'data' => 'privacy:metadata:aicc:data'
            ], 'privacy:metadata:aicc:externalpurpose');

        return $collection;
    }

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


Question:
// Fatal logs message at level="fatal", then calls
// os.Exit(1)

func (l *Logger) Fatal(v ...interface{}) {
	l.Emit(1, fmt.Sprint(v...), nil)
	os.Exit(1)
}

func (mr *mlReader) readRawNode() error {
	var buf bytes.Buffer
	for {
		r, rc, err := mr.readRune()
		switch {
		case err != nil:
			return err
		case rc == rcEOF:
			return errors.New(ErrReader, errorMessages, "unexpected end of file while reading a raw node")
		case rc == rcExclamation:
			r, rc, err = mr.readRune()
			switch {
			case err != nil:
				return err
			case rc == rcEOF:
				return errors.New(ErrReader, errorMessages, "unexpected end of file while reading a raw node")
			case rc == rcClose:
				return mr.builder.RawNode(buf.String())
			}
			buf.WriteRune(chExclamation)
			buf.WriteRune(r)
		default:
			buf.WriteRune(r)
		}
	}
}

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


Question: // LaunchTask is part of Manager interface.

func (m TaskManager) LaunchTask(c context.Context, ctl task.Controller) error {
	cfg := ctl.Task().(*messages.NoopTask)

	sleepFor := time.Duration(cfg.SleepMs) * time.Millisecond
	if sleepFor == 0 {
		sleepFor = 20 * time.Second
	}
	ctl.DebugLog("Running noop task for %s", sleepFor)
	clock.Sleep(c, sleepFor)

	for i := int64(0); i < cfg.TriggersCount; i++ {
		ctl.EmitTrigger(c, &internal.Trigger{
			Id:      fmt.Sprintf("noop:%d:%d", ctl.InvocationID(), i),
			Payload: &internal.Trigger_Noop{Noop: &api.NoopTrigger{}},
		})
	}

	ctl.State().Status = task.StatusSucceeded
	return nil
}

func (c *FakeApplications) Get(name string, options v1.GetOptions) (result *v1alpha1.Application, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewGetAction(applicationsResource, c.ns, name), &v1alpha1.Application{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.Application), err
}

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


Question:
name the route and bind name to router.
@param string $name
@param Router $router
@param bool   $register

public function namedTo(string $name, Router $router, bool $register = false): void
    {
        // not empty
        if ($name = $this->setName($name)->name) {
            if ($register) {
                $router->addRoute($this);
            } else {
                $router->nameRoute($name, $this);
            }
        }
    }

public function getController(Request $request)
    {
        $controller = $request->attributes->get('controller');

        if($request->attributes->has('_sub_request') && $request->attributes->get('_sub_request'))
        {
            $controller = $request->attributes->get('_controller');
        }

        if (!$controller)
        {
            if (null !== $this->logger)
            {
                $this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing');
            }

            return false;
        }

        if(is_array($controller))
        {
            return $controller;
        }

        if(is_object($controller))
        {
            if (method_exists($controller, '__invoke'))
            {
                return $controller;
            }

            throw new \InvalidArgumentException(sprintf('Controller "%s" for URI "%s" is not callable.', get_class($controller), $request->getPathInfo()));
        }

        $prepare = $this->prepare($request->attributes->all());

        $request->attributes->set('_bundle', $prepare['bundle']);
        $request->attributes->set('_controller', strtolower($prepare['parts'][1]));
        $request->attributes->set('_action', strtolower($prepare['parts'][2]));

        $callable = array($this->instantiateController($prepare['controller']), $prepare['action']);

        $request->attributes->set('_callable', $callable);

        if (!is_callable($callable))
        {
            throw new \InvalidArgumentException(sprintf('Controller "%s" for URI "%s" is not callable.', $controller, $request->getPathInfo()));
        }

        return $callable;
    }

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