Question:
Removes the cp option value where uuid = ? and groupId = ? from the database.

@param uuid the uuid
@param groupId the group ID
@return the cp option value that was removed

public static CPOptionValue removeByUUID_G(String uuid, long groupId)
		throws com.liferay.commerce.product.exception.NoSuchCPOptionValueException {
		return getPersistence().removeByUUID_G(uuid, groupId);
	}

def get_create_option(self, context, q):
        """"""
        create_option = []
        display_create_option = False
        if self.create_field and q:
            page_obj = context.get('page_obj', None)
            if page_obj is None or page_obj.number == 1:
                display_create_option = True

        if display_create_option and self.has_add_permission(self.request):
            '''
            Generate querysets of Locations, StaffMembers, and Users that
            match the query string.
            '''
            for s in Location.objects.filter(
                Q(
                    Q(name__istartswith=q) & Q(transactionparty__isnull=True)
                )
            ):
                create_option += [{
                    'id': 'Location_%s' % s.id,
                    'text': _('Generate from location "%(location)s"') % {'location': s.name},
                    'create_id': True,
                }]

            for s in StaffMember.objects.filter(
                Q(
                    (Q(firstName__istartswith=q) | Q(lastName__istartswith=q)) &
                    Q(transactionparty__isnull=True)
                )
            ):
                create_option += [{
                    'id': 'StaffMember_%s' % s.id,
                    'text': _('Generate from staff member "%(staff_member)s"') % {'staff_member': s.fullName},
                    'create_id': True,
                }]

            for s in User.objects.filter(
                Q(
                    (Q(first_name__istartswith=q) | Q(last_name__istartswith=q)) &
                    Q(staffmember__isnull=True) & Q(transactionparty__isnull=True)
                )
            ):
                create_option += [{
                    'id': 'User_%s' % s.id,
                    'text': _('Generate from user "%(user)s"') % {'user': s.get_full_name()},
                    'create_id': True,
                }]

            # Finally, allow creation from a name only.
            create_option += [{
                'id': q,
                'text': _('Create "%(new_value)s"') % {'new_value': q},
                'create_id': True,
            }]
        return create_option

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


Question: // Timing implements xstats.Sender interface

func (s *sender) Timing(stat string, duration time.Duration, tags ...string) {
	s.c <- fmt.Sprintf("%s:%f|ms%s\n", stat, duration.Seconds()*1000, t(tags))
}

def add!(&blk)
      t = Benchmark.measure(&blk)
      @utime  = utime + t.utime
      @stime  = stime + t.stime
      @cutime = cutime + t.cutime
      @cstime = cstime + t.cstime
      @real   = real + t.real
      self
    end

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


Question:
Generate sort field options available to choose.

@return array

private function getSortFieldChoices()
    {
        $choices = [];
        foreach ($this->getSortFieldValues() as $sortField) {
            $choices[$this->getSortFieldLabel($sortField)] = $sortField;
        }

        return $choices;
    }

public function changeSort(int $id, ?int $prevId, ?int $nextId)
	{
		$this->mapper->changeSort('position', $id, $prevId, $nextId);
	}

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


Question:
// populateAttr should only be called once n.ss is known to be set and
// non-nil

func (n *node) populateAttr() error {
	meta := n.meta

	n.attr.Mode = meta.FileMode()

	if n.fs.IgnoreOwners {
		n.attr.Uid = uint32(os.Getuid())
		n.attr.Gid = uint32(os.Getgid())
		executeBit := n.attr.Mode & 0100
		n.attr.Mode = (n.attr.Mode ^ n.attr.Mode.Perm()) | 0400 | executeBit
	} else {
		n.attr.Uid = uint32(meta.MapUid())
		n.attr.Gid = uint32(meta.MapGid())
	}

	// TODO: inode?

	if mt := meta.ModTime(); !mt.IsZero() {
		n.attr.Mtime = mt
	} else {
		n.attr.Mtime = n.pnodeModTime
	}

	switch meta.Type() {
	case "file":
		n.attr.Size = uint64(meta.PartsSize())
		n.attr.Blocks = 0 // TODO: set?
		n.attr.Mode |= 0400
	case "directory":
		n.attr.Mode |= 0500
	case "symlink":
		n.attr.Mode |= 0400
	default:
		Logger.Printf("unknown attr ss.Type %q in populateAttr", meta.Type())
	}
	return nil
}

def fake2db_sqlite_initiator(self, number_of_rows, name=None, custom=None):
        '''
        '''
        rows = number_of_rows
        conn = self.database_caller_creator(name)

        if custom:
            self.custom_db_creator(rows, conn, custom)
            conn.close()
            sys.exit(0)

        self.data_filler_simple_registration(rows, conn)
        self.data_filler_detailed_registration(rows, conn)
        self.data_filler_company(rows, conn)
        self.data_filler_user_agent(rows, conn)
        self.data_filler_customer(rows, conn)
        conn.close()

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


Question:
Returns true if the fingerprint was detected in the key
        :param modulus:
        :return:

def has_fingerprint_moduli(self, modulus):

        if not self.is_acceptable_modulus(modulus):
            return False

        self.tested += 1
        for i in range(0, len(self.primes)):
            if (1 << (modulus % self.primes[i])) & self.prints[i] == 0:
                return False

        self.found += 1
        return True

public function handleUserRegistrationComplete(FOSFilterUserResponseEvent $event)
    {
        $user = $event->getUser();

        if ($user instanceof PKEncryptionEnabledUserInterface) {
            $this->encryptionService->handleUserPostCreation($user);
        }
    }

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


Question:
Returns the name of the idfield of the given entity. If no id field exists, null is returned.

@return the name of the idproperty, or null if no geometryproperty exists

public String getIdName() {
        String result = null;
        if (idAccessor != null) {
            result = idAccessor.getPropertyName();
        }
        return result;
    }

public void loadRTreeIndex(String tableName, String geometryColumnName,
			String idColumnName) {

		String sqlName = GeoPackageProperties.getProperty(SQL_PROPERTY,
				LOAD_PROPERTY);
		executeSQL(sqlName, tableName, geometryColumnName, idColumnName);
	}

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


Question:
Called whenever a log message is received on the java side.
<p>
Adds the log record to the log buffer. If the log buffer is full and
the driver has already been initialized, flush the buffer of the logs.

@Override
  public void publish(final LogRecord record) {
    if (record == null) {
      return;
    }

    if (!isLoggable(record)) {
      return;
    }

    synchronized (this) {
      this.logs.add(record);
      if (!this.driverInitialized || this.logs.size() < BUFFER_LEN) {
        return;
      }
    }

    logAll();
  }

@Override
	public void start() throws PacketTransportException
    {
        try
        {
        	NetworkInputChannel inputChannel =
        		new NetworkInputChannel(initialPacketBufferSize,
        				                new TcpBufferedInputStream(socket.getInputStream(),streamRecvBufferSize));
        	NetworkOutputChannel outputChannel =
        		new NetworkOutputChannel(initialPacketBufferSize,
        				                 new TcpBufferedOutputStream(socket.getOutputStream(),streamSendBufferSize));

            sender = new TcpPacketSender(this,
            		                     outputChannel,
            		                     listener,
            		                     client ? pingInterval : -1,
            		                     sendQueueMaxSize);

            receiver = new TcpPacketReceiver(this,
            								 inputChannel,
            		                         listener,
            		                         pingInterval,
            		                         client ? -1 : maxPacketSize);

            senderThread = new Thread(sender,"TcpPacketSender["+(client ? "client" : "server")+"]");
            senderThread.start();

            receiverThread = new Thread(receiver,"TcpPacketReceiver["+(client ? "client" : "server")+"]");
            receiverThread.start();
        }
        catch (Exception e)
        {
            log.error("#"+id+" cannot start TCP packet I/O handlers",e);
            throw new PacketTransportException("Cannot start TCP packet I/O handlers : "+e.toString());
        }
    }

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


Question:
// Generate a UUID based on the SHA-1 hash of a namespace identifier
// and a name.

func NewV5(ns *UUID, name []byte) (u *UUID, err error) {
	u = new(UUID)
	// Set all bits to truncated SHA1 hash generated from namespace
	// and name.
	u.setBytesFromHash(sha1.New(), ns[:], name)
	u.setVariant(ReservedRFC4122)
	u.setVersion(5)
	return
}

def new
      @script_licence = Script::Licence.new
      @script_licence.user_id = current_user.id
      @script_licence.org_id = current_user.org_id
    end

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


Question:
Get Assembled Path As String

- don`t call normalize path inside this method
normalizing does happen when needed by call
::normalize

@return string

function toString()
    {
        $parts = array();
        if ( ($r = parent::toString()) !== '' )
            ## avoid double slash trail issue
            $parts[] = ($r == $this->getSeparator()) ? '' : $r;
        if ( ($r = $this->getBasename()) !== '')
            $parts[] = $r;

        return implode($this->getSeparator(), $parts);
    }

public function getPathFromUrl($url)
    {
        $basename = $this->storageUrl ? basename($this->storageUrl) : basename($this->storageDir);
        $basename && $url = preg_replace("/(.*$basename\/)/", '', $url);
        return $url;
    }

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


Question:
使用用户词典合并粗分结果，并将用户词语收集到全词图中
@param vertexList 粗分结果
@param wordNetAll 收集用户词语到全词图中
@return 合并后的结果

protected static List<Vertex> combineByCustomDictionary(List<Vertex> vertexList, final WordNet wordNetAll)
    {
        return combineByCustomDictionary(vertexList, CustomDictionary.dat, wordNetAll);
    }

def main(list_ids, model, contact_server, raw_data_id, show_raw,
         mysql_cfg='mysql_online'):
    """"""
    if list_ids:
        preprocessing_desc, _, _ = _get_system(model)
        raw_datapath = os.path.join(utils.get_project_root(),
                                    preprocessing_desc['data-source'])
        _list_ids(raw_datapath)
    else:
        if contact_server:
            data = _fetch_data_from_server(raw_data_id, mysql_cfg)
            print("hwrt version: %s" % hwrt.__version__)
            if data is not None:
                display_data(data['data'], data['id'], model, show_raw)
        else:
            logging.info("RAW_DATA_ID %i does not exist or "
                         "database connection did not work.", raw_data_id)
            # The data was not on the server / the connection to the server did
            # not work. So try it again with the model data
            preprocessing_desc, _, _ = _get_system(model)
            raw_datapath = os.path.join(utils.get_project_root(),
                                        preprocessing_desc['data-source'])
            handwriting = _get_data_from_rawfile(raw_datapath, raw_data_id)
            if handwriting is None:
                logging.info("Recording with ID %i was not found in %s",
                             raw_data_id,
                             raw_datapath)
            else:
                print("hwrt version: %s" % hwrt.__version__)
                display_data(handwriting.raw_data_json,
                             handwriting.formula_id,
                             model,
                             show_raw)

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


Question:
Forces an authentication to bypass checkpoints.

@param  \Cartalyst\Sentinel\Users\UserInterface|array  $credentials
@param  bool  $remember
@return \Cartalyst\Sentinel\Users\UserInterface|bool

public function forceAuthenticate($credentials, $remember = false)
    {
        return $this->bypassCheckpoints(function ($sentinel) use ($credentials, $remember) {
            return $sentinel->authenticate($credentials, $remember);
        });
    }

public function logInRememberMe(array $user): bool
    {
        if (!$user) {
            return false;
        }

        $this->session->set('user', $user);

        return true;
    }

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


Question: // 32 - leadingZero(n-1)

func ceilLog2(n int) int {
	assert(n >= 1)
	if n == 1 {
		return 0
	}
	n--
	ans := 0
	for n > 0 {
		n >>= 1
		ans++
	}
	return ans
}

public Card bankCode(final Integer bankCode) {
        if (bankCode == null) {
            this.bankCode = null;
        } else {
            this.bankCode = String.format("%03d", bankCode);
        }
        return this;
    }

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


Question:
@param $tag
@param array $attrs

@return ProtocolNode

public function getChild($tag, $attrs = [])
    {
        $ret = null;
        if ($this->children) {
            if (is_int($tag)) {
                if (isset($this->children[$tag])) {
                    return $this->children[$tag];
                } else {
                    return;
                }
            }
            foreach ($this->children as $child) {
                if (strcmp($child->tag, $tag) == 0) {
                    $found = true;
                    foreach ($attrs as $key => $value) {
                        if (strcmp($child->getAttribute($key), $value) != 0) {
                            $found = false;
                            break;
                        }
                    }
                    if ($found) {
                        return $child;
                    }
                }
                $ret = $child->getChild($tag, $attrs);
                if ($ret) {
                    return $ret;
                }
            }
        }
    }

def parse(node)
      node.xpath('*').each do |node_child|
        case node_child.name
        when 'solidFill'
          @type = :solid
          @color = Color.new(parent: self).parse_color_model(node_child)
        when 'gradFill'
          @type = :gradient
          @color = GradientColor.new(parent: self).parse(node_child)
        when 'noFill'
          @color = :none
          @type = :none
        when 'srgbClr'
          @color = Color.new(parent: self).parse_hex_string(node_child.attribute('val').value)
        when 'schemeClr'
          @color = Color.new(parent: self).parse_scheme_color(node_child)
        end
      end
      self
    end

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


Question:
Gets all the versions of this object, in incremental order

@param   ConnectionInterface $con the connection to use

@return  ObjectCollection|ChildSkillVersion[] A list of ChildSkillVersion objects

public function getAllVersions($con = null)
    {
        $criteria = new Criteria();
        $criteria->addAscendingOrderByColumn(SkillVersionTableMap::COL_VERSION);

        return $this->getSkillVersions($criteria, $con);
    }

func (c *FakeServiceAccounts) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *corev1.ServiceAccount, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewPatchSubresourceAction(serviceaccountsResource, c.ns, name, pt, data, subresources...), &corev1.ServiceAccount{})

	if obj == nil {
		return nil, err
	}
	return obj.(*corev1.ServiceAccount), err
}

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


Question: Update battery capacity stats using the input method.

def update(self):
        """"""
        # Init new stats
        stats = self.get_init_value()

        if self.input_method == 'local':
            # Update stats
            self.glancesgrabbat.update()
            stats = self.glancesgrabbat.get()

        elif self.input_method == 'snmp':
            # Update stats using SNMP
            # Not avalaible
            pass

        # Update the stats
        self.stats = stats

        return self.stats

func NewDevstatCollector() (Collector, error) {
	return &devstatCollector{
		bytesDesc: prometheus.NewDesc(
			prometheus.BuildFQName(namespace, devstatSubsystem, "bytes_total"),
			"The total number of bytes transferred for reads and writes on the device.",
			[]string{"device"}, nil,
		),
		transfersDesc: prometheus.NewDesc(
			prometheus.BuildFQName(namespace, devstatSubsystem, "transfers_total"),
			"The total number of transactions completed.",
			[]string{"device"}, nil,
		),
		blocksDesc: prometheus.NewDesc(
			prometheus.BuildFQName(namespace, devstatSubsystem, "blocks_total"),
			"The total number of bytes given in terms of the devices blocksize.",
			[]string{"device"}, nil,
		),
	}, nil
}

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


Question:
Load required options

@param string $options

public function load_options( string $options )
    {
        // get constants
        $reflect = new \ReflectionClass( $options );
        $options = $reflect->getConstants();

        // iterate needed params
        foreach ( $options as $option => $default ) {
            $key = strtolower( $option ); //
            $env = getenv( $option );
            $this->options[ $key ] = get_option( $key, $default );
            // overload env variables
            $this->options[ $key ] = ! $env ? $this->options[ $key ] : $env;
        }
    }

function() {
        serviceFactory.optionalDeps = {}
        _.each(arguments, function(depName) {
          serviceFactory.optionalDeps[depName] = true
        })
      }

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


Question:
Verify configuration.

@return TreeBuilder

public function getConfigTreeBuilder(): TreeBuilder
    {
        $rootName = $this->getRootName();
        if (method_exists(TreeBuilder::class, 'getRootNode')) {
            $treeBuilder = /* @scrutinizer ignore-call */ new TreeBuilder($rootName);
            $rootNode = /* @scrutinizer ignore-call */ $treeBuilder->getRootNode();
        } else {
            $treeBuilder = new TreeBuilder();
            $rootNode = $treeBuilder->Root($rootName);
        }
        $this->build($rootNode);

        return $treeBuilder;
    }

protected function initBranches(VcsDriverInterface $driver)
    {
        foreach ($driver->getBranches() as $branch => $identifier) {
            if (\is_array($this->rootData) && $branch === $driver->getRootIdentifier()) {
                $this->preInitBranchPackage($driver, $this->rootData, $branch, $identifier);

                continue;
            }

            $this->preInitBranchLazyPackage($driver, $branch, $identifier);
        }

        if (!$this->verbose) {
            $this->io->overwrite('', false);
        }
    }

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


Question:
Convert the machine list argument from a list of names into a mapping of logical names to
  physical hosts. This is similar to the _parse_configs function but separated to provide the
  opportunity for extension and additional checking of machine access

def make_machine_mapping(machine_list):

  if machine_list is None:
    return {}
  else:
    mapping = {}
    for pair in machine_list:
      if (constants.MACHINE_SEPARATOR not in pair) or (pair.count(constants.MACHINE_SEPARATOR) != 1):
        raise ValueError("machine pairs must be passed as two strings separted by a %s", constants.MACHINE_SEPARATOR)
      (logical, physical) = pair.split(constants.MACHINE_SEPARATOR)
      # add checks for reachability
      mapping[logical] = physical
    return mapping

func (s *DescribePipelinesInput) SetPipelineIds(v []*string) *DescribePipelinesInput {
	s.PipelineIds = v
	return s
}

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


Question:
统一下单
@param string $openid 调用【网页授权获取用户信息】接口获取到用户在该公众号下的Openid
@param float $totalFee 收款总费用 单位元
@param string $outTradeNo 唯一的订单号
@param string $orderName 订单名称
@param string $notifyUrl 支付结果通知url 不要有问号
@param string $timestamp 支付时间
@return string

public function createJsBizPackage($code, $totalFee, $outTradeNo, $orderName, $notifyUrl)
    {
        $config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apiKey,
        );
        $orderName = iconv('GBK','UTF-8',$orderName);
        $unified = array(
            'appid' => $config['appid'],
            'attach' => 'pay',             //商家数据包，原样返回，如果填写中文，请注意转换为utf-8
            'body' => $orderName,
            'mch_id' => $config['mch_id'],
            'nonce_str' => self::createNonceStr(),
            'notify_url' => $notifyUrl,
            'openid' => $this->_getSession($code)->openid,            //rade_type=JSAPI，此参数必传
            'out_trade_no' => $outTradeNo,
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
            'total_fee' => intval($totalFee * 100),       //单位 转为分
            'trade_type' => 'JSAPI',
        );
        $unified['sign'] = self::getSign($unified, $config['key']);
        $responseXml = self::curlPost('https://api.mch.weixin.qq.com/pay/unifiedorder', self::arrayToXml($unified));
        $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($unifiedOrder === false) {
            die('parse xml error');
        }
        if ($unifiedOrder->return_code != 'SUCCESS') {
            die($unifiedOrder->return_msg);
        }
        if ($unifiedOrder->result_code != 'SUCCESS') {
            die($unifiedOrder->err_code);
        }
        $timestamp = time();
        $arr = array(
            "appId" => $config['appid'],
            "timeStamp" => "$timestamp",        //这里是字符串的时间戳，不是int，所以需加引号
            "nonceStr" => self::createNonceStr(),
            "package" => "prepay_id=" . $unifiedOrder->prepay_id,
            "signType" => 'MD5',
        );
        $arr['paySign'] = self::getSign($arr, $config['key']);
        return $arr;
    }

public function buildSignature()
    {
        // Re-create the VPSSignature.
        // Note that an ABORT notification for a TOKEN request type flips back to
        // the transaction format. We'll try merging these.

        $VPSTxId = $this->getVPSTxId();

        if ($this->getTxType() === Response::TXTYPE_TOKEN
            && $this->getStatus() === Response::SAGEPAY_STATUS_OK
        ) {
            // For some bizarre reason, the VPSTxId is hashed at the Sage Pay gateway
            // without its curly brackets, so we must do the same to validate the hash.
            // This only happens for a valid TOKEN request, and not for an aborted
            // TOKEN request.
            // The successful TOKEN request also does not include the card details, even
            // though they are present. The ABORTed token request does include the address
            // result details in the signature, even though they are no relevant.

            $VPSTxId = str_replace(['{', '}'], '', $VPSTxId);
        }

        // Transaction types PAYMENT, DEFERRED and AUTHENTICATE (when suppoted)
        // and non-transaction TOKEN request.

        $signatureData = array(
            $VPSTxId,
            // VendorTxCode
            $this->getTransactionId(),
            $this->getStatus(),
            $this->getTxAuthNo(),
            strtolower($this->getVendor()),
            $this->getAVSCV2(),
            ($this->getTxType() === Response::TXTYPE_TOKEN ? $this->getToken() : ''),
            // As saved in the merchant application.
            $this->getSecurityKey(),
        );

        if ($this->getTxType() !== Response::TXTYPE_TOKEN
            || $this->getStatus() !== Response::SAGEPAY_STATUS_OK
        ) {
            // Do not use any of these fields for a successful TOKEN transaction,
            // even though some of them may be present.

            $signatureData = array_merge(
                $signatureData,
                array(
                    // Details for AVSCV2:
                    $this->getAddressResult(),
                    $this->getPostCodeResult(),
                    $this->getCV2Result(),
                    //
                    $this->getGiftAid(),
                    $this->get3DSecureStatus(),
                    $this->getCAVV(),
                    $this->getAddressStatus(),
                    $this->getPayerStatus(),
                    $this->getCardType(),
                    $this->getLast4Digits(),
                    // New for protocol v3.00
                    $this->getDeclineCode(),
                    $this->getExpiryDate(),
                    $this->getFraudResponse(),
                    $this->getBankAuthCode(),
                )
            );
        }

        return md5(implode('', $signatureData));
    }

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


Question: ============DOWNLOAD ASYNC===============

public static void downloadAsync(String url, String file, HttpCallback<File> callback) {
        downloadAsync(url, file, null, callback, new StrParam[0]);
    }

def sync(self):

        if self._sync is None:
            self._sync = Sync(self)
        return self._sync

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


Question:
Check if surefire plugin is available and if correct version is
used (we require 2.13 or higher, as previous versions do not
support excludesFile).

protected void checkSurefirePlugin(Plugin plugin, String[] nonSupportedVersions, String minSupported) throws MojoExecutionException {
        // Check if plugin is available.
        if (plugin == null) {
            throw new MojoExecutionException("Surefire plugin not avaialble");
        }
        String version = plugin.getVersion();
        for (String nonSupportedVersion : nonSupportedVersions) {
            if (version.equals(nonSupportedVersion)) {
                throw new MojoExecutionException("Not supported surefire version; version has to be " + minSupported + " or higher");
            }
        }
    }

def inject_solr_document_behavior
      file_path = 'app/models/solr_document.rb'
      if File.exist?(file_path)
        inject_into_file file_path, after: /include Blacklight::Solr::Document.*$/ do
          "\n  # Adds GeoWorks behaviors to the SolrDocument.\n" \
            "  include GeoWorks::SolrDocumentBehavior\n"
        end
      else
        Rails.logger.info "     \e[31mFailure\e[0m  GeoWorks requires a SolrDocument object. This generators assumes that the model is defined in the file #{file_path}, which does not exist."
      end
    end

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


Question:
Display splash, and launch app.
@param args the command line arguments

public static void main(String[] args)
    {
        String splashImage = Splash.getParam(args, SPLASH);
        if ((splashImage == null) || (splashImage.length() == 0))
            splashImage = DEFAULT_SPLASH;
        URL url = Splash.class.getResource(splashImage);
        if (url == null)
            if (ClassServiceUtility.getClassService().getClassFinder(null) != null)
                url = ClassServiceUtility.getClassService().getClassFinder(null).findResourceURL(splashImage, null);

        Container container = null;
        Splash.splash(container, url);
        String main = Splash.getParam(args, MAIN);
        if ((main == null) || (main.length() == 0))
            main = ROOT_PACKAGE + "Thin";
        else if (main.charAt(0) == '.')
            main = ROOT_PACKAGE + main.substring(1);
        Splash.invokeMain(main, args);
        Splash.disposeSplash();
    }

func (toolkit BashToolkit) StepRunCommandArguments(step stepmanModels.StepModel, sIDData models.StepIDData, stepAbsDirPath string) ([]string, error) {
	entryFile := "step.sh"
	if step.Toolkit != nil && step.Toolkit.Bash != nil && step.Toolkit.Bash.EntryFile != "" {
		entryFile = step.Toolkit.Bash.EntryFile
	}

	stepFilePath := filepath.Join(stepAbsDirPath, entryFile)
	cmd := []string{"bash", stepFilePath}
	return cmd, nil
}

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


Question: Create the ragged array that will be filled when we ask for items.

def allocate_buffers(self):
        ""
        if self.ite_len is None: len(self)
        self.idx   = LanguageModelPreLoader.CircularIndex(len(self.dataset.x.items), not self.backwards)
        self.batch = np.zeros((self.bs, self.bptt+1), dtype=np.int64)
        self.batch_x, self.batch_y = self.batch[:,0:self.bptt], self.batch[:,1:self.bptt+1]
        #ro: index of the text we're at inside our datasets for the various batches
        self.ro    = np.zeros(self.bs, dtype=np.int64)
        #ri: index of the token we're at inside our current text for the various batches
        self.ri    = np.zeros(self.bs, dtype=np.int)

def get_experiments
      @experiments ||= begin
        # fetch our data from the cache
        data = Gxapi.with_error_handling do
          # handle caching
          self.list_experiments_from_cache
        end
        # turn into Gxapi::Ostructs
        (data || []).collect{|data| Ostruct.new(data)}
      end
    end

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


Question:
Returns a listener, which allows to finish the last step, when the activity is used as a
wizard.

@return The listener, which has been created, as an instance of the type {@link
View.OnClickListener}. The listener may not be null

@NonNull
    private View.OnClickListener createFinishButtonListener() {
        return new View.OnClickListener() {

            @Override
            public void onClick(final View v) {
                notifyOnFinish();
            }

        };
    }

public function loadListeners($manager = null, $scope = null) {
		if (!($manager instanceof CakeEventManager)) {
			$scope = $manager;
			$_this = $this;
		} else {
			$_this = $manager;
		}

		empty($_this->loadedListeners['Common'])
		&& $_this->loadedListeners['Common'] = new CommonEventListener();

		(empty($_this->loadedScopes['Common']) || !in_array($scope, (array) $_this->loadedScopes['Common']))
		&& $_this->loadedScopes['Common'][] = $scope
		&& $_this->attachByScope($_this->loadedListeners['Common'], $_this, $scope);

		$_this->implementedEvents['Common'] = array_keys($_this->loadedListeners['Common']->implementedEvents());

		foreach ($_this->listPlugins() as $plugin) {
			if (isset($_this->loadedListeners[$plugin])) {
				if (
					$_this->loadedListeners[$plugin]
					&& !empty($scope)
					&& !in_array($scope, (array) $_this->loadedScopes[$plugin])
				) {
					$_this->loadedScopes[$plugin][] = $scope;
					$_this->attachByScope($_this->loadedListeners[$plugin], $_this, $scope);
				}
				continue;
			}

			$class = $plugin . 'EventListener';

			if (ClassRegistry::isKeySet($class)) {
				$_this->loadedListeners[$plugin] = ClassRegistry::getObject($class);
			} else if (file_exists(CakePlugin::path($plugin) . 'Event' . DS . $class . '.php')) {
				App::uses($class, $plugin . '.Event');
				$_this->loadedListeners[$plugin] = new $class();
			} else {
				$_this->loadedListeners[$plugin] = false;
				continue;
			}

			$_this->loadedScopes[$plugin] = array();
			$_this->implementedEvents[$plugin] = array_keys($_this->loadedListeners[$plugin]->implementedEvents());

			if (empty($scope)) {
				$_this->attach($_this->loadedListeners[$plugin]);
			} else if (!in_array($scope, $_this->loadedScopes[$plugin])) {
				$_this->loadedScopes[$plugin][] = $scope;
				$_this->attachByScope($_this->loadedListeners[$plugin], $_this, $scope);
			}
		}

		if ((!Reveal::is('Page.test') || empty($_GET['plugin'])) && !isset($_this->loadedListeners['App'])) {
			if (file_exists(APP . 'Event' . DS . 'AppEventListener.php')) {
				App::uses('AppEventListener', 'Event');
				$_this->loadedListeners['App'] = new AppEventListener();
				$_this->loadedScopes['App'] = array();
				$_this->implementedEvents['App'] = array_keys($_this->loadedListeners['App']->implementedEvents());
				if (empty($scope)) {
					$_this->attach($_this->loadedListeners['App']);
				} else if (!in_array($scope, $_this->loadedScopes['App'])) {
					$_this->loadedScopes['App'][] = $scope;
					$_this->attachByScope($_this->loadedListeners['App'], $_this, $scope);
				}
			}
		} else if (
			isset($_this->loadedListeners['App'])
			&& $_this->loadedListeners['App']
			&& !empty($scope)
			&& !in_array($scope, $_this->loadedScopes['App'])
		) {
			$_this->loadedScopes['App'][] = $scope;
			$_this->attachByScope($_this->loadedListeners['App'], $_this, $scope);
		}

		return $_this;
	}

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


Question:
Creates a copy of the supplied multimap with its keys transformed by the supplied function.

The {@code  function} must never return null and the input multimap must contain no nulls.

public static <K1, K2, V> ImmutableSetMultimap<K2, V> copyWithTransformedKeys(
      final SetMultimap<K1,V> setMultimap,
      final Function<? super K1, ? extends K2> function) {
    final ImmutableSetMultimap.Builder<K2,V> ret = ImmutableSetMultimap.builder();
    for (final Map.Entry<K1, V> entry : setMultimap.entries()) {
      // nulls banned by contract
      //noinspection ConstantConditions
      ret.put( function.apply(entry.getKey()), entry.getValue());
    }
    return ret.build();
  }

func (m *Map) DumpIfExists(hash map[string][]string) error {
	found, err := m.exist()
	if err != nil {
		return err
	}

	if found {
		return m.Dump(hash)
	}

	return nil
}

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


Question:
Returns the raw info array

@return array
@recursive

public function raw()
	{
		// unpack
		$raw = [];
		foreach ($this->info as $key => $info)
		{
			if (is_array($info))
			{
				$info = $this->unpack($info);
			}
			// check if it's just a single object
			if ($info instanceof AbstractDto)
			{
				$info = $info->raw();
			}
			// set the raw value
			$raw[$key] = $info;
		}

		return $raw;
	}

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

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

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

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

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

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


Question:
Proxy Password ~
The password required to authenticate to your proxy server.

@param string $value

@return $this

public function setCoreProxyPassword($value)
    {
        $this->setFieldName('proxy_password');
        $this->loadObject(true);
        $this->setFieldValue($value);

        return $this;
    }

public void marshall(ResetUserPasswordRequest resetUserPasswordRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(resetUserPasswordRequest.getDirectoryId(), DIRECTORYID_BINDING);
            protocolMarshaller.marshall(resetUserPasswordRequest.getUserName(), USERNAME_BINDING);
            protocolMarshaller.marshall(resetUserPasswordRequest.getNewPassword(), NEWPASSWORD_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:
Converts Maltego entity definition files to Canari python classes.
    Excludes Maltego built-in entities by default.

def generate_entities(ctx, output_path, mtz_file, exclude_namespace, namespace, maltego_entities, append, entity):
    """"""
    from canari.commands.generate_entities import generate_entities
    generate_entities(
        ctx.project, output_path, mtz_file, exclude_namespace, namespace, maltego_entities, append, entity)

def get_cached_translated_field(instance, field_name, language_code=None, use_fallback=False):

    if language_code is None:
        language_code = instance.get_current_language()

    # In django-parler 1.1 the order of the arguments was fixed, It used to be language_code, field_name
    # This serves as detection against backwards incompatibility issues.
    if len(field_name) <= 5 and len(language_code) > 5:
        raise RuntimeError("Unexpected language code, did you swap field_name, language_code?")

    translated_model = instance._parler_meta.get_model_by_field(field_name)
    values = _get_cached_values(instance, translated_model, language_code, use_fallback)
    if not values:
        return None

    # Allow older cached versions where the field didn't exist yet.
    return values.get(field_name, None)

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


Question:
Translate.

<p>If the given <var>path</var> contains only one segment,
the transformation will follow the segment's direction.

@param thePath the path to follow.
@param curvilineCoord the curviline translation.
@param shiftCoord the shifting translation.

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

public static function BuildPathOptions(array $options = [])
    {
        // Size flag
        $sizeFlag = sprintf( '-%sx%s', $options['width'], $options['height'] );

        // Resize flag
        $resizeFlag = $options[ 'resize' ] ? '-resize' : '';

        // focus point flag
        $focusPointFlag = '';
        if (!$options['resize'] && ( $options[ 'focusX' ] || $options['focusY'] )) {
            $focusPointFlag = sprintf( '-[%sx%s]', $options['focusX'], $options['focusY'] );
        }

        return sprintf( '%s%s%s', $sizeFlag, $focusPointFlag, $resizeFlag );
    }

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


Question:
Check the input data types of the state

        Checks all input data ports if the handed data is not of the specified type and generate an error logger message
        with details of the found type conflict.

def check_input_data_type(self):

        for data_port in self.input_data_ports.values():
            if data_port.name in self.input_data and self.input_data[data_port.name] is not None:
                #check for class
                if not isinstance(self.input_data[data_port.name], data_port.data_type):
                    logger.error("{0} had an data port error: Input of execute function must be of type '{1}' not '{2}'"
                                 " as current value '{3}'".format(self, data_port.data_type.__name__,
                                                               type(self.input_data[data_port.name]).__name__,
                                                               self.input_data[data_port.name]))

private boolean isTypedTimeFullyLegal() {
        if (mIs24HourMode) {
            // For 24-hour mode, the time is legal if the hours and minutes are each legal. Note:
            // getEnteredTime() will ONLY call isTypedTimeFullyLegal() when NOT in 24hour mode.
            Boolean[] enteredZeros = {false, false, false};
            int[] values = getEnteredTime(enteredZeros);
            return (values[0] >= 0 && values[1] >= 0 && values[1] < 60 && values[2] >= 0 && values[2] < 60);
        } else {
            // For AM/PM mode, the time is legal if it contains an AM or PM, as those can only be
            // legally added at specific times based on the tree's algorithm.
            return (mTypedTimes.contains(getAmOrPmKeyCode(AM)) ||
                    mTypedTimes.contains(getAmOrPmKeyCode(PM)));
        }
    }

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


Question:
Store the content folder.

@param string $source
Path on file system to content directory.
@param array $content
Content properties

public function saveContent($source, $content) {
    $dest = "{$this->path}/content/{$content['id']}";

    // Remove any old content
    \H5PCore::deleteFileTree($dest);

    self::copyFileTree($source, $dest);
  }

public function parseConfig($config)
	{
    	if(isset($config['watermarkFile'])) {
			// This also call setWatermarkFullPath
			$this->openWatermark($config['watermarkFile']);
    	}

    	if(isset($config['tmpDir'])) {
			$this->setWatermarkTmpDir($config['tmpDir']);
    	}

        return $this;
	}

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


Question: import potentials from a directory

def _read_potentials(self, pot_dir):

        if self.assignments['potentials'] is not None:
            print('Potentials already imported. Will not overwrite!')
            return
        else:
            self.assignments['potentials'] = {}

        pot_files = sorted(glob(pot_dir + os.sep + 'pot*.dat'))
        for nr, filename in enumerate(pot_files):
            with open(filename, 'r') as fid:
                pot_data = np.loadtxt(fid)

                nids = self.nodeman.add_data(
                    pot_data[:, 2:4],
                )
                # store cids for later retrieval
                self.assignments['potentials'][nr] = nids

def extract_all_snow_tweets_from_disk_generator(json_folder_path):

    # Get a generator with all file paths in the folder
    json_file_path_generator = (json_folder_path + "/" + name for name in os.listdir(json_folder_path))

    for path in json_file_path_generator:
        for tweet in extract_snow_tweets_from_file_generator(path):
            yield tweet

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


Question: // getConfig returns a config for test cases

func getConfig(t *testing.T) *cfg.Config {
	c := cfg.ResetTestRoot(t.Name())

	// and we use random ports to run in parallel
	tm, rpc, grpc := makeAddrs()
	c.P2P.ListenAddress = tm
	c.RPC.ListenAddress = rpc
	c.RPC.GRPCListenAddress = grpc
	return c
}

public function getEnvOption($key, $default = null)
    {
        if (!array_key_exists('environments', $this->configuration) || !is_array($this->configuration['environments'])) {
            return $default;
        }

        if (!array_key_exists($this->environment, $this->configuration['environments'])) {
            return $default;
        }

        if (array_key_exists($key, $this->configuration['environments'][$this->environment])) {
            return $this->configuration['environments'][$this->environment][$key];
        }

        return $default;
    }

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


Question:
Set property attribute, nerge new values with old values
@param array $arValue

protected function setPropertyAttribute($arValue)
    {
        if (is_string($arValue)) {
            $arValue = $this->fromJson($arValue);
        }

        if (empty($arValue) || !is_array($arValue)) {
            return;
        }

        $arPropertyList = $this->property;
        if (empty($arPropertyList)) {
            $arPropertyList = [];
        }

        foreach ($arValue as $sKey => $sValue) {
            $arPropertyList[$sKey] = $sValue;
        }

        $this->attributes['property'] = $this->asJson($arPropertyList);
    }

public function setProfessionalDescriptions($descriptions)
    {
        foreach ($descriptions as $description) {
            $description->setVariety($this);
        }
        $this->professional_descriptions = $descriptions;

        return $this;
    }

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


Question: // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.

func (in *AuditSink) DeepCopyInto(out *AuditSink) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
	in.Spec.DeepCopyInto(&out.Spec)
	return
}

def to_gufunc_string(self):

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

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


Question:
Return the date of a backup file

@param string $file a backup file path
@param string $ext

@return \DateTime|null

private function getBackupFileDate($file, $ext = 'php')
    {
        $matches = [];

        if (preg_match('@^(.*)([0-9]{8}_[0-9]{6})\\.'.$ext.'$@', $file, $matches) === 1) {
            return \DateTime::createFromFormat(self::BACKUP_DATE_FORMAT, $matches[2]);
        }
        // @codeCoverageIgnoreStart
        // Cannot happen because of glob but safer
        else {
            return null;
        }
        // @codeCoverageIgnoreEnd
    }

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

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


Question: Move the current item to the next in list.

private void moveToNext() {
        if (controller != null) {
            currentItemIndex = controller.nextItem(this, currentItemIndex);
        } else {
            currentItemIndex = defaultController.nextItem(this, currentItemIndex);
        }
    }

func (c *LRU) Put(b bgzf.Block) (evicted bgzf.Block, retained bool) {
	c.mu.Lock()
	defer c.mu.Unlock()

	var d bgzf.Block
	if _, ok := c.table[b.Base()]; ok {
		return b, false
	}
	used := b.Used()
	if len(c.table) == c.cap {
		if !used {
			return b, false
		}
		d = c.root.prev.b
		remove(c.root.prev, c.table)
	}
	n := &node{b: b}
	c.table[b.Base()] = n
	if used {
		insertAfter(&c.root, n)
	} else {
		insertAfter(c.root.prev, n)
	}
	return d, true
}

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


Question:
Delays for a given amount of time and then fulfills the returned promise.

@param {int} milliseconds The number of milliseconds to delay
@return {Promise} A promise that will be fulfilled after the delay

function (milliseconds) {
            var deferred,
                timer = setTimeout(function () {
                    deferred.emitSuccess();
                }, milliseconds),
                canceller = function () {
                    clearTimeout(timer);
                };
            deferred = new Deferred(canceller);
            return deferred.getPromise();
        }

public Observable<ServiceResponse<Void>> deleteValueWithServiceResponseAsync(String tagName, String tagValue) {
        if (tagName == null) {
            throw new IllegalArgumentException("Parameter tagName is required and cannot be null.");
        }
        if (tagValue == null) {
            throw new IllegalArgumentException("Parameter tagValue is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.deleteValue(tagName, tagValue, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = deleteValueDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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


Question: // Validation functions

func validateTemplatesDir(templatesPath string) error {
	if fi, err := os.Stat(templatesPath); err != nil {
		return errors.New("directory not found")
	} else if err == nil && !fi.IsDir() {
		return errors.New("not a directory")
	}
	return nil
}

public boolean isValid(String value) {
        if (value == null) {
            return false;
        }
        for (Pattern pattern : patterns) {
            if (pattern.matcher(value).matches()) {
                return true;
            }
        }
        return false;
    }

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


Question:
Retrieve single trashed item or all
@param int $id
@return Model/Collection

public function getTrash($id = null){
        if(!is_null($id)){
            return $this->getTrashedItem($id);
        }
        return $this->model->onlyTrashed()->get();
    }

func (api API) DeleteWorkersKV(ctx context.Context, namespaceID, key string) (Response, error) {
	uri := fmt.Sprintf("/accounts/%s/storage/kv/namespaces/%s/values/%s", api.OrganizationID, namespaceID, key)
	res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil)
	if err != nil {
		return Response{}, errors.Wrap(err, errMakeRequestError)
	}

	result := Response{}
	if err := json.Unmarshal(res, &result); err != nil {
		return result, errors.Wrap(err, errUnmarshalError)
	}
	return result, err
}

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


Question:
Connects to a queue with the given name, the object returned
can be used to configure and create a new one.

@param string $name
@param array $options
@return AMQPQueue

public function queue($name, $options = [])
    {
        if (empty($this->_queues[$name])) {
            $channel = $this->channel($name, $options);
            $queue = new AMQPQueue($channel);
            $queue->setName($name);

            if (!empty($options['flags'])) {
                $queue->setFlags($options['flags']);
            }

            $this->_queues[$name] = $queue;
        }

        return $this->_queues[$name];
    }

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

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


Question:
Create a new stream based on the input type.

@param string $resource
@param array $options
@return StreamInterface
@throws InvalidStreamException

public static function create($resource = '', array $options = []): StreamInterface
    {
        switch (gettype($resource)) {
            case 'string':
                $stream = fopen('php://temp', 'r+');
                if ($resource !== '') {
                    fwrite($stream, $resource);
                    fseek($stream, 0);
                }
                return new Stream($stream, $options);
            case 'resource':
                return new Stream($resource, $options);
            case 'object':
                if ($resource instanceof StreamInterface) {
                    return $resource;
                } elseif ($resource instanceof \Traversable) {
                    return new IteratorStream($resource, $options);
                } elseif (method_exists($resource, '__toString')) {
                    return static::createStream((string)$resource, $options);
                }
                break;
            case 'NULL':
                return new Stream('php://temp', 'r+');
        }

        throw new InvalidStreamException(
            'Invalid resource type: ' . gettype($resource)
        );
    }

@Override
    public T addAsLibraries(File... resources) throws IllegalArgumentException {
        Validate.notNull(resources, "Resources must be specified");
        for (File resource : resources) {
            addAsLibrary(resource);
        }
        return covarientReturn();
    }

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


Question:
Generate role for IAM cloudformation template
        :param name: Name of role
        :param policies: List of policies to attach to this role (False = none)
        :return: Ref to new role

def build_role(self, name, policies=False):

        # Build role template
        if policies:
            role = self.__template.add_resource(
                Role(
                    self.name_strip(name),
                    AssumeRolePolicyDocument=Policy(
                        Version=self.VERSION_IAM,
                        Statement=[
                            Statement(
                                Effect=Allow,
                                Principal=Principal(
                                    "Service", self.__role_principals
                                ),
                                Action=[AssumeRole],
                            )
                        ]
                    ),
                    Path=self.__role_path,
                    ManagedPolicyArns=policies,
                ))
            # Add role to list for default policy
            self.__roles_list.append(troposphere.Ref(role))
        else:
            role = self.__template.add_resource(
                Role(
                    self.name_strip(name),
                    AssumeRolePolicyDocument=Policy(
                        Version=self.VERSION_IAM,
                        Statement=[
                            Statement(
                                Effect=Allow,
                                Principal=Principal(
                                    "Service", self.__role_principals
                                ),
                                Action=[AssumeRole],
                            )
                        ]
                    ),
                    Path=self.__role_path,
                ))
            # Add role to list for default policy
            self.__roles_list.append(troposphere.Ref(role))

        return role

private function parseRuleDefinition($key, $definition): Rule
    {
        if (is_string($definition)) {

            $parts = preg_split('/:/', $definition, 2);

            $factory_name = $parts[0];
            $parameters = $parts[1] ?? null;

            $parameters = ! is_null($parameters)
                ? explode(',', $parameters)
                : [];

            $factory_name = trim($factory_name);
            $parameters = array_map('trim', $parameters);

            $factory = $this->getRuleFactory($factory_name);

            $name = is_string($key) ? $key : $factory_name;
            $validate = $factory($parameters);

            return new Rule($name, $validate);

        }

        // is_callable must be AFTER is_string, otherwise factories named like a
        // php function can't be used (ex: date).
        if (is_callable($definition)) {

            return new Rule((string) $key, $definition);

        }

        throw new InvalidRuleFormatException($definition);
    }

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


Question: Make sure the source path is correct in that it exists and appears to point to the root of the repo we want.

function validateSourcePath(sourcePath) {
    const materialPackageJSONPath = pathUtils.resolve(sourcePath, 'package.json');

    return fs.readFileAsync(materialPackageJSONPath, { encoding: 'UTF8' })
        .then(materialPackageJSONString => {
            const package = JSON.parse(materialPackageJSONString);
            if (package.name !== sourcePackageName) {
                throw new Error(`Source path ${sourcePath} does not appear to be a clone of https://github.com/callemall/material-ui`);
            }
            return sourcePath;
        });
}

private function cloneFromGit()
    {
        $this->tmpDirectory = tmpPath().'/'.time();
        GitRepository::cloneRepository($this->gitURL, $this->tmpDirectory);
        return $this;
    }

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


Question: doc: http://open.youku.com/docs/doc?id=62

def find_shows_by_category(self, category, genre=None, area=None,
                               release_year=None, paid=None,
                               orderby='view-today-count',
                               streamtypes=None, person=None,
                               page=1, count=20):

        url = 'https://openapi.youku.com/v2/shows/by_category.json'
        params = {
            'client_id': self.client_id,
            'category': category,
            'genre': genre,
            'area': area,
            'release_year': release_year,
            'paid': paid,
            'orderby': orderby,
            'streamtypes': streamtypes,
            'person': person,
            'page': page,
            'count': count
        }
        params = remove_none_value(params)
        r = requests.get(url, params=params)
        check_error(r)
        return r.json()

function getBaseUrl (hostUrl, psaDoc, relType, desc) {
  assert(psaDoc && typeof psaDoc === 'object', 'Invalid PSA service description document')
  assert(psaDoc.links && Array.isArray(psaDoc.links), 'Invalid PSA service description document (no links array)')
  var link = psaDoc.links.find(link => {
    var rel = link.rel
    return rel && typeof rel === 'string' && rel.indexOf(relType) !== -1
  })
  if (!link) {
    throw new Error(`Service does not provide the pinning-service ${desc} API (rel ${relType})`)
  }
  var href = link.href
  assert(href && typeof href === 'string', 'Invalid PSA service description document (no href on API link)')
  if (href.startsWith('/')) {
    href = hostUrl + link.href
  }
  return href
}

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


Question:
// SortedList returns the labels as a sorted list, separated by semicolon
//
// DO NOT BREAK THE FORMAT OF THIS. THE RETURNED STRING IS USED AS KEY IN
// THE KEY-VALUE STORE.

func (l Labels) SortedList() []byte {
	var keys []string
	for k := range l {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	result := ""
	for _, k := range keys {
		result += l[k].FormatForKVStore()
	}

	return []byte(result)
}

private static void appendKeyValue(StringBuffer str, String key, String value) {

        str.append(key);
        if (value == IS_USED) {
            str.append(";");
        } else {
            str.append("=(");
            str.append(value);
            str.append(");");
        }
    }

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


Question:
/*
---------------
Document events
---------------

@Override
    public void handleDocumentStart(
            final long startTimeNanos, final int line, final int col)
            throws ParseException {

        this.selection.levels[this.selectionIndex].selectors = this.selectors;

        this.documentStartEndHandler.handleDocumentStart(startTimeNanos, line, col);

    }

function appendElement (hander,node) {
    if (!hander.currentElement) {
        hander.doc.appendChild(node);
    } else {
        hander.currentElement.appendChild(node);
    }
}

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


Question:
Parses a name object from the passed tokenizer and stream-reader.

@param Tokenizer $tokenizer
@param StreamReader $streamReader
@return self

public static function parse(Tokenizer $tokenizer, StreamReader $streamReader)
    {
        $v = new self;
        if (\strspn($streamReader->getByte(), "\x00\x09\x0A\x0C\x0D\x20()<>[]{}/%") === 0) {
            $v->value = (string) $tokenizer->getNextToken();
            return $v;
        }

        $v->value = '';
        return $v;
    }

protected function filter()
	{
		foreach ($this->filters as $attribute => $filters) {
			// Check if the attribute is present in the input data
			if (!array_key_exists($attribute, $this->data)) {
				continue;
			}

			$data = $this->data[$attribute];

			foreach ($filters as $filter) {
				// The format for specifying filter and parameters follows an
				// easy {filter}:{parameters} formatting convention.
				if (strpos($filter, ':') !== false) {
					list($filter, $parameterList) = explode(':', $filter, 2);
					$parameters = explode(',', $parameterList);
				} else {
					$parameters = [];
				}

				if (method_exists($this, $this->camelCase($filter))) {
					$data = $this->filterWalker($filter, $data, $parameters);
				} elseif (isset($this->extensions[$filter])) {
					$data = $this->filterExtensionWalker($filter, $data, $parameters);
				} else {
					throw new \Exception("'$filter' is not a valid filter.");
				}
			}

			$this->filteredData[$attribute] = $data;
		}

		return $this->filteredData;
	}

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


Question:
Build the mail representation of the notification.

@param  mixed  $notifiable
@return \Illuminate\Notifications\Messages\MailMessage

public function toMail($notifiable)
    {
        // check if Chronos path or app
        $request = \Route::getCurrentRequest();
        $reset_url = $request->is('admin/*') || $request->is('admin/*') ? route('chronos.auth.password_reset_form', $this->token) : url('password/reset', $this->token);

        return (new MailMessage)
            ->line('You are receiving this email because we received a password reset request for your account.')
            ->action('Reset Password', $reset_url)
            ->line('If you did not request a password reset, no further action is required.');
    }

def _sendMsg(self, type, msg):

        if self.ALERT_STATUS and type in self.ALERT_TYPES:
            self._configMailer()
            self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg)

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


Question:
Test if there have been too many calls

        :rtype boolean

def has_too_many_calls(self):

        if self.has_exact and self._call_count > self._exact:
            return True
        if self.has_maximum and self._call_count > self._maximum:
            return True
        return False

def check_elastic(self):
        '''

        '''
        if self.elastic and self.elastic_kick_in == self.limit:
            value = self.redis_conn.zcard(self.window_key)
            if self.limit - value > self.elastic_buffer:
                return True
        return False

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


Question: // SetFromResourceName sets the FromResourceName field's value.

func (s *ExportSnapshotRecordSourceInfo) SetFromResourceName(v string) *ExportSnapshotRecordSourceInfo {
	s.FromResourceName = &v
	return s
}

def _generate_resource_dict(self):

        resource_dict = {}

        resource_dict['Type'] = self.resource_type

        if self.depends_on:
            resource_dict['DependsOn'] = self.depends_on

        resource_dict.update(self.resource_attributes)

        properties_dict = {}
        for name in self.property_types:
            value = getattr(self, name)
            if value is not None:
                properties_dict[name] = value

        resource_dict['Properties'] = properties_dict

        return resource_dict

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


Question:
Converts the input to the specified options.

Options is
```
array(
key => null|newKey|array('key' => newKey, 'type' => string, 'parse' => callable)
)
```
@param array  $input
@param array  $options
@return array

static function applyOptions(array $input, array $options) {
        $data = array();

        foreach($input as $key => $val) {
            if(!isset($options[$key])) {
                continue;
            }

            if(\is_array($options[$key])) {
                if(!empty($options[$key]['parse'])) {
                    $call = $options[$key]['parse'];
                    $val = $call($val);
                }

                if(!empty($options[$key]['type'])) {
                    $val = self::typecastVariable($val, $options[$key]['type']);
                }

                $key = $options[$key]['key'] ?? $key;
            } elseif(!empty($options[$key])) {
                $key = $options[$key];
            }

            $data[$key] = $val;
        }

        return $data;
    }

protected function typecastValue($value, $type)
    {
        if (is_scalar($type)) {
            if (is_object($value) && method_exists($value, '__toString')) {
                $value = $value->__toString();
            }

            switch ($type) {
                case self::TYPE_INTEGER:
                    return (int)$value;
                case self::TYPE_FLOAT:
                    return (float)$value;
                case self::TYPE_BOOLEAN:
                    return (bool)$value;
                case self::TYPE_STRING:
                    return (string)$value;
                case self::TYPE_JSON:
                    return is_string($value) ? $value : json_encode($value);
                case self::TYPE_IMPLODE:
                    return is_string($value) ? $value : (string)implode($this->delimiter, $value);
                case self::TYPE_SERIALIZE:
                    return is_string($value) ? $value : serialize($value);
                default:
                    throw new InvalidParamException("Unsupported type '{$type}'");
            }
        }

        return call_user_func($type, $value);
    }

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


Question: // Single state to single state, assumed default state name.

func (m *Meta) backendMigrateState_s_s(opts *backendMigrateOpts) error {
	log.Printf("[TRACE] backendMigrateState: migrating %q workspace to %q workspace", opts.oneEnv, opts.twoEnv)

	stateOne, err := opts.One.StateMgr(opts.oneEnv)
	if err != nil {
		return fmt.Errorf(strings.TrimSpace(
			errMigrateSingleLoadDefault), opts.OneType, err)
	}
	if err := stateOne.RefreshState(); err != nil {
		return fmt.Errorf(strings.TrimSpace(
			errMigrateSingleLoadDefault), opts.OneType, err)
	}

	// Do not migrate workspaces without state.
	if stateOne.State().Empty() {
		log.Print("[TRACE] backendMigrateState: source workspace has empty state, so nothing to migrate")
		return nil
	}

	stateTwo, err := opts.Two.StateMgr(opts.twoEnv)
	if err == backend.ErrDefaultWorkspaceNotSupported {
		// If the backend doesn't support using the default state, we ask the user
		// for a new name and migrate the default state to the given named state.
		stateTwo, err = func() (statemgr.Full, error) {
			log.Print("[TRACE] backendMigrateState: target doesn't support a default workspace, so we must prompt for a new name")
			name, err := m.UIInput().Input(context.Background(), &terraform.InputOpts{
				Id: "new-state-name",
				Query: fmt.Sprintf(
					"[reset][bold][yellow]The %q backend configuration only allows "+
						"named workspaces![reset]",
					opts.TwoType),
				Description: strings.TrimSpace(inputBackendNewWorkspaceName),
			})
			if err != nil {
				return nil, fmt.Errorf("Error asking for new state name: %s", err)
			}

			// Update the name of the target state.
			opts.twoEnv = name

			stateTwo, err := opts.Two.StateMgr(opts.twoEnv)
			if err != nil {
				return nil, err
			}

			// If the currently selected workspace is the default workspace, then set
			// the named workspace as the new selected workspace.
			if m.Workspace() == backend.DefaultStateName {
				if err := m.SetWorkspace(opts.twoEnv); err != nil {
					return nil, fmt.Errorf("Failed to set new workspace: %s", err)
				}
			}

			return stateTwo, nil
		}()
	}
	if err != nil {
		return fmt.Errorf(strings.TrimSpace(
			errMigrateSingleLoadDefault), opts.TwoType, err)
	}
	if err := stateTwo.RefreshState(); err != nil {
		return fmt.Errorf(strings.TrimSpace(
			errMigrateSingleLoadDefault), opts.TwoType, err)
	}

	// Check if we need migration at all.
	// This is before taking a lock, because they may also correspond to the same lock.
	one := stateOne.State()
	two := stateTwo.State()

	// no reason to migrate if the state is already there
	if one.Equal(two) {
		// Equal isn't identical; it doesn't check lineage.
		sm1, _ := stateOne.(statemgr.PersistentMeta)
		sm2, _ := stateTwo.(statemgr.PersistentMeta)
		if one != nil && two != nil {
			if sm1 == nil || sm2 == nil {
				log.Print("[TRACE] backendMigrateState: both source and destination workspaces have no state, so no migration is needed")
				return nil
			}
			if sm1.StateSnapshotMeta().Lineage == sm2.StateSnapshotMeta().Lineage {
				log.Printf("[TRACE] backendMigrateState: both source and destination workspaces have equal state with lineage %q, so no migration is needed", sm1.StateSnapshotMeta().Lineage)
				return nil
			}
		}
	}

	if m.stateLock {
		lockCtx := context.Background()

		lockerOne := clistate.NewLocker(lockCtx, m.stateLockTimeout, m.Ui, m.Colorize())
		if err := lockerOne.Lock(stateOne, "migration source state"); err != nil {
			return fmt.Errorf("Error locking source state: %s", err)
		}
		defer lockerOne.Unlock(nil)

		lockerTwo := clistate.NewLocker(lockCtx, m.stateLockTimeout, m.Ui, m.Colorize())
		if err := lockerTwo.Lock(stateTwo, "migration destination state"); err != nil {
			return fmt.Errorf("Error locking destination state: %s", err)
		}
		defer lockerTwo.Unlock(nil)

		// We now own a lock, so double check that we have the version
		// corresponding to the lock.
		log.Print("[TRACE] backendMigrateState: refreshing source workspace state")
		if err := stateOne.RefreshState(); err != nil {
			return fmt.Errorf(strings.TrimSpace(
				errMigrateSingleLoadDefault), opts.OneType, err)
		}
		log.Print("[TRACE] backendMigrateState: refreshing target workspace state")
		if err := stateTwo.RefreshState(); err != nil {
			return fmt.Errorf(strings.TrimSpace(
				errMigrateSingleLoadDefault), opts.OneType, err)
		}

		one = stateOne.State()
		two = stateTwo.State()
	}

	var confirmFunc func(state.State, state.State, *backendMigrateOpts) (bool, error)
	switch {
	// No migration necessary
	case one.Empty() && two.Empty():
		log.Print("[TRACE] backendMigrateState: both source and destination workspaces have empty state, so no migration is required")
		return nil

	// No migration necessary if we're inheriting state.
	case one.Empty() && !two.Empty():
		log.Print("[TRACE] backendMigrateState: source workspace has empty state, so no migration is required")
		return nil

	// We have existing state moving into no state. Ask the user if
	// they'd like to do this.
	case !one.Empty() && two.Empty():
		log.Print("[TRACE] backendMigrateState: target workspace has empty state, so might copy source workspace state")
		confirmFunc = m.backendMigrateEmptyConfirm

	// Both states are non-empty, meaning we need to determine which
	// state should be used and update accordingly.
	case !one.Empty() && !two.Empty():
		log.Print("[TRACE] backendMigrateState: both source and destination workspaces have states, so might overwrite destination with source")
		confirmFunc = m.backendMigrateNonEmptyConfirm
	}

	if confirmFunc == nil {
		panic("confirmFunc must not be nil")
	}

	if !opts.force {
		// Abort if we can't ask for input.
		if !m.input {
			log.Print("[TRACE] backendMigrateState: can't prompt for input, so aborting migration")
			return errors.New("error asking for state migration action: input disabled")
		}

		// Confirm with the user whether we want to copy state over
		confirm, err := confirmFunc(stateOne, stateTwo, opts)
		if err != nil {
			log.Print("[TRACE] backendMigrateState: error reading input, so aborting migration")
			return err
		}
		if !confirm {
			log.Print("[TRACE] backendMigrateState: user cancelled at confirmation prompt, so aborting migration")
			return nil
		}
	}

	// Confirmed! We'll have the statemgr package handle the migration, which
	// includes preserving any lineage/serial information where possible, if
	// both managers support such metadata.
	log.Print("[TRACE] backendMigrateState: migration confirmed, so migrating")
	if err := statemgr.Migrate(stateTwo, stateOne); err != nil {
		return fmt.Errorf(strings.TrimSpace(errBackendStateCopy),
			opts.OneType, opts.TwoType, err)
	}
	if err := stateTwo.PersistState(); err != nil {
		return fmt.Errorf(strings.TrimSpace(errBackendStateCopy),
			opts.OneType, opts.TwoType, err)
	}

	// And we're done.
	return nil
}

func (api *API) GetTransfers(seed Trytes, options GetTransfersOptions) (bundle.Bundles, error) {
	options = getTransfersDefaultOptions(options)
	if err := Validate(
		ValidateSeed(seed), ValidateSecurityLevel(options.Security),
		ValidateStartEndOptions(options.Start, options.End),
	); err != nil {
		return nil, err
	}
	addresses, err := api.GetNewAddress(seed, options.ToGetNewAddressOptions())
	if err != nil {
		return nil, err
	}
	return api.GetBundlesFromAddresses(addresses, options.InclusionStates)
}

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


Question: Delete all the data in a named timeseries.

def delete(self, name):
    '''

    '''
    keys = self._client.keys('%s%s:*'%(self._prefix,name))

    pipe = self._client.pipeline(transaction=False)
    for key in keys:
      pipe.delete( key )
    pipe.execute()

    # Could be not technically the exact number of keys deleted, but is a close
    # enough approximation
    return len(keys)

function(toDelete, evtStck) {
    let len = toDelete.length
    for (let i = 0; len > i; len--) {
      evtStck.splice(toDelete[len - 1], 1)
    }
  }

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


Question:
// batchExecute Uses sync.WaitGroup to run commands using multiple goroutines,
// and waits for their return

func (clnt *Client) batchExecute(policy *BatchPolicy, keys []*Key, cmd batcher) error {
	batchNodes, err := newBatchNodeList(clnt.cluster, policy, keys)
	if err != nil {
		return err
	}

	var wg sync.WaitGroup

	// Use a goroutine per namespace per node
	errs := []error{}
	errm := new(sync.Mutex)

	for _, batchNode := range batchNodes {
		// There may be multiple goroutines for a single node because the
		// wire protocol only allows one namespace per command.  Multiple namespaces
		// require multiple goroutines per node.
		batchNode.splitByNamespace(keys)

		wg.Add(len(batchNode.BatchNamespaces))
	}

	for _, batchNode := range batchNodes {
		for _, bns := range batchNode.BatchNamespaces {
			newCmd := cmd.cloneBatchCommand(batchNode, bns)
			go func(cmd command) {
				defer wg.Done()
				if err := cmd.Execute(); err != nil {
					errm.Lock()
					errs = append(errs, err)
					errm.Unlock()
				}
			}(newCmd)
		}
	}

	wg.Wait()
	return mergeErrors(errs)
}

async def start(self, ctx: Context):

        for alias in self.component_configs:
            if alias not in self.child_components:
                self.add_component(alias)

        tasks = [component.start(ctx) for component in self.child_components.values()]
        if tasks:
            await asyncio.gather(*tasks)

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


Question:
<p>
The input {@link Date} is converted into a {@link LocalDate} with the given
{@link Chronology}
</p>

@param chronology {@link Chronology} to be used
@return the {@link LocalDate} created from the input and arguments

public static final <T extends Date> Function<T, LocalDate> dateToLocalDate(Chronology chronology) {
		return FnLocalDate.dateToLocalDate(chronology);
	}

@Override
    protected AstNode parseCreateStatement( DdlTokenStream tokens,
                                            AstNode parentNode ) throws ParsingException {
        assert tokens != null;
        assert parentNode != null;

        if (tokens.matches(STMT_CREATE_INDEX) || tokens.matches(STMT_CREATE_UNIQUE_INDEX)) {
            return parseCreateIndex(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_FUNCTION)) {
            return parseCreateFunction(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_PROCEDURE)) {
            return parseCreateProcedure(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_ROLE)) {
            return parseCreateRole(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_SYNONYM)) {
            return parseCreateSynonym(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_TRIGGER)) {
            return parseCreateTrigger(tokens, parentNode);
        }

        return super.parseCreateStatement(tokens, parentNode);

    }

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


Question:
Checks the values inside `filters`
    https://docs.docker.com/engine/api/v1.29/#operation/ServiceList
    Returns a new dictionary in the format `map[string][]string` jsonized

def clean_filters(filters: Mapping = None) -> str:

    if filters and isinstance(filters, dict):
        for k, v in filters.items():
            if not isinstance(v, list):
                v = [v]
            filters[k] = v

    return json.dumps(filters)

def to_dict(self):
        ''''''
        d = {'connectorId': self.connector_id,
                'name': self.name,
                'dataType': self.data_type,
                'interfaceType': self.interface_type,
                'dataflowType': self.data_flow_type,
                'sourceDataPort': self.source_data_port.to_dict(),
                'targetDataPort': self.target_data_port.to_dict()}
        if self.visible != True:
            d[RTS_EXT_NS_YAML + 'visible'] = self.visible
        if self.subscription_type:
            d['subscriptionType'] = self.subscription_type
        if self.push_interval:
            d['pushInterval'] = self.push_interval
        if self.comment:
            d[RTS_EXT_NS_YAML + 'comment'] = self.comment
        props = []
        for name in self.properties:
            p = {'name': name}
            if self.properties[name]:
                p['value'] = str(self.properties[name])
            props.append(p)
        if props:
            d[RTS_EXT_NS_YAML + 'properties'] = props
        return d

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


Question: Scan for collectors to load from path

def load_collectors_from_paths(paths):

    # Initialize return value
    collectors = {}

    if paths is None:
        return

    if isinstance(paths, basestring):
        paths = paths.split(',')
        paths = map(str.strip, paths)

    load_include_path(paths)

    for path in paths:
        # Get a list of files in the directory, if the directory exists
        if not os.path.exists(path):
            raise OSError("Directory does not exist: %s" % path)

        if path.endswith('tests') or path.endswith('fixtures'):
            return collectors

        # Load all the files in path
        for f in os.listdir(path):

            # Are we a directory? If so process down the tree
            fpath = os.path.join(path, f)
            if os.path.isdir(fpath):
                subcollectors = load_collectors_from_paths([fpath])
                for key in subcollectors:
                    collectors[key] = subcollectors[key]

            # Ignore anything that isn't a .py file
            elif (os.path.isfile(fpath) and
                  len(f) > 3 and
                  f[-3:] == '.py' and
                  f[0:4] != 'test' and
                  f[0] != '.'):

                modname = f[:-3]

                fp, pathname, description = imp.find_module(modname, [path])

                try:
                    # Import the module
                    mod = imp.load_module(modname, fp, pathname, description)
                except (KeyboardInterrupt, SystemExit) as err:
                    logger.error(
                        "System or keyboard interrupt "
                        "while loading module %s"
                        % modname)
                    if isinstance(err, SystemExit):
                        sys.exit(err.code)
                    raise KeyboardInterrupt
                except Exception:
                    # Log error
                    logger.error("Failed to import module: %s. %s",
                                 modname,
                                 traceback.format_exc())
                else:
                    for name, cls in get_collectors_from_module(mod):
                        collectors[name] = cls
                finally:
                    if fp:
                        fp.close()

    # Return Collector classes
    return collectors

func (c *Container) NetNsPath() (string, error) {
	if c.state == nil {
		return "", fmt.Errorf("container state is not populated")
	}

	if c.netns == "" {
		return fmt.Sprintf("/proc/%d/ns/net", c.state.Pid), nil
	}

	return c.netns, nil
}

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


Question:
@param ExtendedFolderInterface $folder

@return MetaSet[]

public function resolve(ExtendedFolderInterface $folder)
    {
        $metaSets = [];
        foreach ($folder->getMetasets() as $metaSetId) {
            $metaSet = $this->metaSetManager->find($metaSetId);
            if ($metaSet) {
                $metaSets[] = $metaSet;
            }
        }

        return $metaSets;
    }

func (inode *Inode) fillXattrFromHead(resp *s3.HeadObjectOutput) {
	inode.userMetadata = make(map[string][]byte)

	if resp.ETag != nil {
		inode.s3Metadata["etag"] = []byte(*resp.ETag)
	}
	if resp.StorageClass != nil {
		inode.s3Metadata["storage-class"] = []byte(*resp.StorageClass)
	} else {
		inode.s3Metadata["storage-class"] = []byte("STANDARD")
	}

	for k, v := range resp.Metadata {
		k = strings.ToLower(k)
		value, err := url.PathUnescape(*v)
		if err != nil {
			value = *v
		}
		inode.userMetadata[k] = []byte(value)
	}
}

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


Question:
Recursively creates VNodes from Glyphs of Sbgn.

@param parent Parent of the glyphs that are passed as second arguement.
@param glyphs Glyphs that are child of parent which is passed as first arguement.

private void createVNodes(VCompound parent,List<Glyph> glyphs)
    {
        for(Glyph glyph: glyphs )
        {
            if (!glyphClazzOneOf(glyph, GlyphClazz.UNIT_OF_INFORMATION, GlyphClazz.STATE_VARIABLE))
            {
//                if(glyph.getClazz().equals(GlyphClazz.PROCESS.getClazz()))
//                {
//                    VCompound v = new VCompound(glyph); //TODO: v is never used; wat's the idea?
//                }

                if(!isChildless(glyph))
                {
                    VCompound v = new VCompound(glyph);
                    idToGLyph.put(glyph.getId(), glyph);
                    glyphToVNode.put(glyph, v);
                    parent.children.add(v);
                    createVNodes(v, glyph.getGlyph());
                }
                else
                {
                    VNode v = new VNode(glyph);
                    idToGLyph.put(glyph.getId(), glyph);
                    glyphToVNode.put(glyph, v);
                    parent.children.add(v);
                }
            }
        }
    }

public function addChild(Step $step)
    {
        if (!$this->children->contains($step)) {
            $this->children->add($step);
            $step->setParent($this);
        }

        return $this;
    }

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


Question:
Quick and dirty implementation that converts thrift DDL to a Properties object by flattening
the parameters
@param prefix
@param properties
@param entity
@throws Exception

@SuppressWarnings({ "rawtypes", "unchecked" })
    public static void setPropertiesFromThrift(String prefix, Properties properties, org.apache.thrift.TBase entity) throws Exception {
        Field field = entity.getClass().getDeclaredField("metaDataMap");
        Map<org.apache.thrift.TFieldIdEnum, org.apache.thrift.meta_data.FieldMetaData> fields = (Map<org.apache.thrift.TFieldIdEnum, FieldMetaData>) field.get(entity);

        for (Entry<org.apache.thrift.TFieldIdEnum, FieldMetaData> f : fields.entrySet()) {
            ThriftTypes type = ThriftTypes.values()[f.getValue().valueMetaData.type];
            Object value = entity.getFieldValue(f.getKey());
            if (value == null)
                continue;

            switch (type) {
            case VOID   :
                break;
            case BOOL   :
            case BYTE   :
            case DOUBLE :
            case I16    :
            case I32    :
            case I64    :
            case STRING :
            case ENUM   :
                if (value instanceof byte[]) {
                    properties.put(prefix + f.getKey().getFieldName(), Base64.encodeBase64String((byte[])value));
                }
                else if (value instanceof ByteBuffer) {
                    properties.put(prefix + f.getKey().getFieldName(), base64Encode((ByteBuffer)value));
                }
                else {
                    properties.put(prefix + f.getKey().getFieldName(), value.toString());
                }
                break;
            case MAP    : {
                String newPrefix = prefix + f.getKey().getFieldName() + ".";
                org.apache.thrift.meta_data.MapMetaData meta = (org.apache.thrift.meta_data.MapMetaData)f.getValue().valueMetaData;
                if (!meta.keyMetaData.isStruct() && !meta.keyMetaData.isContainer()) {
                    Map<Object, Object> map = (Map<Object, Object>)value;
                    for (Entry<Object, Object> entry : map.entrySet()) {
                        properties.put(newPrefix + entry.getKey(), entry.getValue().toString());
                    }
                }
                else {
                    LOG.error(String.format("Unable to serializer field '%s' key type '%s' not supported", f.getKey().getFieldName(), meta.keyMetaData.getTypedefName()));
                }
                break;
            }
            case LIST   : {
                String newPrefix = prefix + f.getKey().getFieldName() + ".";

                List<Object> list = (List<Object>)value;
                org.apache.thrift.meta_data.ListMetaData listMeta = (org.apache.thrift.meta_data.ListMetaData)f.getValue().valueMetaData;
                for (Object entry : list) {
                    String id;
                    if (entry instanceof CfDef) {
                        id = ((CfDef)entry).name;
                    }
                    else if (entry instanceof ColumnDef) {
                        ByteBuffer name = ((ColumnDef)entry).name;
                        id = base64Encode(name);
                    }
                    else {
                        LOG.error("Don't know how to convert to properties " + listMeta.elemMetaData.getTypedefName());
                        continue;
                    }

                    if (listMeta.elemMetaData.isStruct()) {
                        setPropertiesFromThrift(newPrefix + id + ".", properties, (org.apache.thrift.TBase)entry);
                    }
                    else {
                        properties.put(newPrefix + id, entry);
                    }
                }

                break;
            }
            case STRUCT : {
                setPropertiesFromThrift(prefix + f.getKey().getFieldName() + ".", properties, (org.apache.thrift.TBase)value);
                break;
            }
            case SET    :
            default:
                LOG.error("Unhandled value : " + f.getKey().getFieldName() + " " + type);
                break;
            }
        }

public void putPipeProperty(ArrayList<DbPipe> dbPipes) throws DevFailed {
        for (DbPipe dbPipe : dbPipes) database.putDevicePipeProperty(deviceName, dbPipe);
    }

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


Question: // SetOperatingSystemVersion sets the OperatingSystemVersion field's value.

func (s *DescribeDeviceOutput) SetOperatingSystemVersion(v string) *DescribeDeviceOutput {
	s.OperatingSystemVersion = &v
	return s
}

def update_os_version(self):
        """"""
        self.chain.connection.log("Detecting os version")
        os_version = self.driver.get_os_version(self.version_text)
        if os_version:
            self.chain.connection.log("SW Version: {}".format(os_version))
            self.os_version = os_version

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


Question:
Method to get the list of permission action names from the form field value.

@param   mixed  $value  The form field value to validate.
@return  array  A list of permission action names from the form field value.

protected function getValueActions($value)
	{
		// Initialise variables.
		$actions = array();

		// Iterate over the asset actions and add to the actions.
		foreach ((array) $value as $name => $rules)
		{
			$actions[] = $name;
		}

		return $actions;
	}

public function setValidationProperty(array $properties)
    {
        if (Helpers::isKeyExists($properties, 'validation')) {
            $this->validationRules = is_array($properties['validation']) ? $properties['validation'] : Helpers::removeEmptyItems(explode('|', $properties['validation']));
        }

        if (Helpers::isNewerThanOrEqualTo('5.2') && $this->isNullable() && !in_array('nullable', $this->validationRules)) {
            $this->validationRules[] = 'nullable';
        }

        if ($this->isBoolean() && !in_array('boolean', $this->validationRules)) {
            $this->validationRules[] = 'boolean';
        }

        if ($this->isFile() && !in_array('file', $this->validationRules)) {
            $this->validationRules[] = 'file';
        }
        if ($this->isMultipleAnswers() && !in_array('array', $this->validationRules)) {
            $this->validationRules[] = 'array';
        }

        if (in_array($this->getEloquentDataMethod(), ['char', 'string']) && in_array($this->htmlType, ['text', 'textarea'])) {
            if (!in_array('string', $this->validationRules)) {
                $this->validationRules[] = 'string';
            }

            if (!Helpers::inArraySearch($this->validationRules, 'min')) {
                $this->validationRules[] = sprintf('min:%s', $this->getMinLength());
            }

            if (!Helpers::inArraySearch($this->validationRules, 'max') && !is_null($this->getMaxLength())) {
                $this->validationRules[] = sprintf('max:%s', $this->getMaxLength());
            }
        }

        $params = [];

        if (Helpers::isKeyExists($properties, 'data-type-params')) {
            $params = $this->getDataTypeParams((array) $properties['data-type-params']);
        }

        if ($this->htmlType == 'number' || (in_array($this->getEloquentDataMethod(), ['decimal', 'double', 'float'])
            && isset($params[0]) && ($length = intval($params[0])) > 0
            && isset($params[1]) && ($decimal = intval($params[1])) > 0)) {
            if (!in_array('numeric', $this->validationRules)) {
                $this->validationRules[] = 'numeric';
            }

            if (!Helpers::inArraySearch($this->validationRules, 'min') && !is_null($minValue = $this->getMinValue())) {
                $this->validationRules[] = sprintf('min:%s', $minValue);
            }

            if (!Helpers::inArraySearch($this->validationRules, 'max') && !is_null($maxValue = $this->getMaxValue())) {
                $this->validationRules[] = sprintf('max:%s', $maxValue);
            }
        }

        return $this;
    }

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


Question:
Returns a new Pattern with the same +source+, but with +delta+ overriden
 and +metadata+ merged.

 @param delta [Array<Numeric>, Pattern<Numeric>, Numeric]
 @param metadata [Hash]
 @return [Pattern]

def p(*delta, **metadata)
      delta = delta.compact.empty? ? @delta : delta
      Pattern.new(@source, delta: delta, size: @size, **@metadata.merge(metadata))
    end

def mtf_image_transformer_base_cifar():
  """"""
  hparams = mtf_image_transformer_base()
  hparams.mesh_shape = "batch:8"
  hparams.layout = "batch:batch"
  hparams.learning_rate_decay_steps = 13600  # one epoch
  hparams.batch_size = 32
  hparams.num_heads = 4
  hparams.num_decoder_layers = 12
  hparams.block_length = 256
  hparams.hidden_size = 512
  hparams.d_ff = 2048
  hparams.learning_rate = 0.5
  hparams.layer_preprocess_sequence = "none"
  hparams.layer_postprocess_sequence = "dan"
  hparams.layer_prepostprocess_dropout = 0.3
  hparams.unconditional = True
  return hparams

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