Question: // init initializes global varables.

func (dht *DHT) init() {
	listener, err := net.ListenPacket(dht.Network, dht.Address)
	if err != nil {
		panic(err)
	}

	dht.conn = listener.(*net.UDPConn)
	dht.routingTable = newRoutingTable(dht.KBucketSize, dht)
	dht.peersManager = newPeersManager(dht)
	dht.tokenManager = newTokenManager(dht.TokenExpiredAfter, dht)
	dht.transactionManager = newTransactionManager(
		dht.MaxTransactionCursor, dht)

	go dht.transactionManager.run()
	go dht.tokenManager.clear()
	go dht.blackList.clear()
}

public function __isset($k)
	{
		if (preg_match('#^[A-Z][A-Za-z_0-9]+$#D', $k))
		{
			return isset($this->plugins[$k]);
		}

		return isset($this->registeredVars[$k]);
	}

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


Question:
Filters an array of options by a search term.
@param array $options
@param string $query
@return array

protected function filterOptionsBySearch($options, $query)
    {
        $filteredOptions = [];

        $optionMatchesSearch = function ($words, $option) {
            foreach ($words as $word) {
                $word = trim($word);
                if (!strlen($word)) {
                    continue;
                }

                if (!Str::contains(Str::lower($option), $word)) {
                    return false;
                }
            }

            return true;
        };

        /*
         * Exact
         */
        foreach ($options as $index => $option) {
            if (Str::is(Str::lower($option), $query)) {
                $filteredOptions[$index] = $option;
                unset($options[$index]);
            }
        }

        /*
         * Fuzzy
         */
        $words = explode(' ', $query);
        foreach ($options as $index => $option) {
            if ($optionMatchesSearch($words, $option)) {
                $filteredOptions[$index] = $option;
            }
        }

        return $filteredOptions;
    }

protected function prepareOptions($name)
    {
        return [
            'addc' => $this->additionalCode,
            'dely' => $this->prepareOptionDelay(),
            'ercl' => $this->prepareOption('errorClass'),
            'erst' => $this->prepareOption('errorStyle'),
            'hecl' => $this->prepareOption('headerClass'),
            'hest' => $this->prepareOption('headerStyle'),
            'jsev' => $this->prepareOptionBool('jsEventsCallback'),
            'keyt' => $this->prepareOptionBool('keyTrigger'),
            'loca' => $this->prepareOptionLocal(),
            'locl' => $this->prepareOption('loadingClass'),
            'lost' => $this->prepareOption('loadingStyle'),
            'mabe' => $this->prepareOption('markBegin'),
            'maen' => $this->prepareOption('markEnd'),
            'minq' => $this->prepareOptionMinQuery(),
            'name' => $name,
            'nebe' => $this->prepareOption('nextBegin'),
            'necl' => $this->prepareOption('nextClass'),
            'neen' => $this->prepareOption('nextEnd'),
            'nest' => $this->prepareOption('nextStyle'),
            'nrcl' => $this->prepareOption('noRecordsClass'),
            'nrst' => $this->prepareOption('noRecordsStyle'),
            'onrm' => $this->onRemove,
            'onsl' => $this->onSelect,
            'pabe' => $this->prepareOption('pagerBegin'),
            'paen' => $this->prepareOption('pagerEnd'),
            'prbe' => $this->prepareOption('previousBegin'),
            'prcl' => $this->prepareOption('previousClass'),
            'pren' => $this->prepareOption('previousEnd'),
            'prst' => $this->prepareOption('previousStyle'),
            'prba' => $this->prepareOptionProgressBar(),
            'recl' => $this->prepareOption('recordClass'),
            'rest' => $this->prepareOption('recordStyle'),
            'rmcl' => $this->prepareOption('removeClass'),
            'rmla' => $this->prepareOption('removeLabel'),
            'rmst' => $this->prepareOption('removeStyle'),
            'rscl' => $this->prepareOption('resultClass'),
            'rsst' => $this->prepareOption('resultStyle'),
            'smbt' => $this->prepareOptionBool('singleModeBottom'),
            'smod' => $this->prepareOptionBool('singleMode'),
            'swcl' => $this->prepareOption('switchClass'),
            'swst' => $this->prepareOption('switchStyle'),
            'url'  => $this->source,
        ];
    }

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


Question: // ErrorD implements the method for the KayveeLogger interface.

func (ml *MockRouteCountLogger) ErrorD(title string, data map[string]interface{}) {
	ml.logger.ErrorD(title, data)
}

def execute_job(self, job):
        # type: (Job) -> dict

        try:
            return execute_job(job)

        except KillWorkerException:
            self._app.logger.info("Stopping Gearman worker on demand flag set.")
            self.stop_worker()

        except Exception as e:
            return self.handle_exception(e, job.path)

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


Question:
Returns true if the manager has infos reported, false otherwise
@return true if infos have been reported, false otherwise

public boolean hasInfos(){
		if(this.messageHandlers.containsKey(E_MessageType.INFO)){
			return (this.messageHandlers.get(E_MessageType.INFO).getCount()==0)?false:true;
		}
		return false;
	}

protected function applyBulk( $model, $column, $action, $target, $config = [] ) {

		switch( $column ) {

			case 'status': {

				switch( $action ) {

					case 'confirmed': {

						$this->confirm( $model );

						break;
					}
					case 'approved': {

						$this->approve( $model );

						break;
					}
					case 'rejected': {

						$this->reject( $model );

						break;
					}
					case 'active': {

						$this->activate( $model );

						break;
					}
					case 'frozen': {

						$this->freeze( $model );

						break;
					}
					case 'blocked': {

						$this->block( $model );

						break;
					}
					case 'terminated': {

						$this->terminate( $model );

						break;
					}
				}

				break;
			}
			case 'model': {

				switch( $action ) {

					case 'pinned': {

						$model->pinned = true;

						$model->update();

						break;
					}
					case 'featured': {

						$model->featured = true;

						$model->update();

						break;
					}
					case 'delete': {

						$this->delete( $model );

						break;
					}
				}

				break;
			}
		}
	}

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


Question:
Delete a wlan (using REST)
--------------------------
return true on success
required parameter <wlan_id> = 24 char string; _id of the wlan which can be found with the list_wlanconf() function

public function delete_wlan($wlan_id)
    {
        if (!$this->is_loggedin) {
            return false;
        }

        $this->request_type = 'DELETE';
        $response           = $this->exec_curl('/api/s/' . $this->site . '/rest/wlanconf/' . trim($wlan_id));

        return $this->process_response_boolean($response);
    }

func (id EventID) Format(s string, args ...interface{}) string {
	args = append([]interface{}{id.String()}, args...)
	return fmt.Sprintf(s, args...)
}

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


Question:
依据自构造的查询语句进行查询

@see #buildCountQueryStr(Query)
@see org.beangle.commons.collection.page.Page

public <T> List<T> search(org.beangle.commons.dao.query.Query<T> query) {
    if (query instanceof LimitQuery) {
      org.beangle.commons.dao.query.LimitQuery<T> limitQuery = (org.beangle.commons.dao.query.LimitQuery<T>) query;
      if (null == limitQuery.getLimit()) {
        return QuerySupport.find(limitQuery, getSession());
      } else {
        return new SinglePage<T>(limitQuery.getLimit().getPageIndex(), limitQuery.getLimit().getPageSize(),
            QuerySupport.count(limitQuery, getSession()), QuerySupport.find(query, getSession()));
      }
    } else {
      return QuerySupport.find(query, getSession());
    }
  }

def collections(self):

        import time
        gotten_feed_num = 20
        offset = 0
        data = {
            'method':'next',
            '_xsrf': self.xsrf
        }
        while gotten_feed_num >= 10:
            data['params'] = "{\"answer_url\": %d,\"offset\": %d}" % (self.id, offset)
            res = self._session.post(url=Get_Collection_Url, data=data)
            gotten_feed_num = len(res.json()['msg'])
            offset += gotten_feed_num
            soup = BeautifulSoup(''.join(res.json()['msg']))
            for zm_item in soup.find_all('div', class_='zm-item'):
                url = Zhihu_URL + zm_item.h2.a['href']
                name = zm_item.h2.a.text
                links = zm_item.div.find_all('a')
                owner = Author(links[0]['href'], session=self._session)
                follower_num = int(links[1].text.split()[0])
                yield Collection(url, owner=owner, name=name,
                                 follower_num=follower_num,
                                 session=self._session)

            time.sleep(0.2)

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


Question:
Sets the value of the ColorLightness property.

@param $value array(float, float)  Lightness range.
@return self

public function setColorLightness($value)
    {
        if (!is_array($value) ||
            !array_key_exists(0, $value) ||
            !array_key_exists(1, $value) ||
            !is_numeric($value[0]) ||
            !is_numeric($value[1]) ||
            $value[0] < 0 || $value[0] > 1 ||
            $value[1] < 0 || $value[1] > 1
        ) {
            throw new \InvalidArgumentException(
                "The value passed to setColorLightness was invalid. ".
                "Please check the documentation.");
        }

        $this->colorLightness = array((float)$value[0], (float)$value[1]);
        return $this;
    }

public function initializeArguments()
    {
        parent::initializeArguments();
        $this->registerArgument('results', '\Solarium\QueryType\Select\Result\Result', 'Query results', true);
        $this->registerArgument('document', '\Solarium\QueryType\Select\Result\Document', 'Result document to work on',
            true);
        $this->registerArgument('field', 'string', 'name of field in document to highlight', true);
        $this->registerArgument('alternateField', 'string',
            'name of alternate field in document to use for highlighting', false, null);
        $this->registerArgument('index', 'int', 'if the field is an array: index of the single element to highlight',
            false);
        $this->registerArgument('idKey', 'string', 'name of the field in document that is its ID', false, 'id');
        $this->registerArgument('highlightTagOpen', 'string', 'opening tag to insert to begin highlighting', false,
            '');
        $this->registerArgument('highlightTagClose', 'string', 'closing tag to insert to end highlighting', false,
            '');
        $this->registerArgument('raw', 'boolean', 'whether to not HTML escape the output', false, false);
    }

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


Question: Return the method name for the given method id.

@Override
    public final String getMethodName(Object homeKey, int id, boolean isHome)
    {
        HomeRecord hr = homesByName.get(homeKey); // d366845.3
        return hr.homeInternal.getMethodName(homeKey, id, true);
    }

func (rd *Resource) generateMethods(r *raml.Resource) {
	rd.addMethod(r, r.Get, "Get")
	rd.addMethod(r, r.Post, "Post")
	rd.addMethod(r, r.Put, "Put")
	rd.addMethod(r, r.Patch, "Patch")
	rd.addMethod(r, r.Delete, "Delete")
	rd.addMethod(r, r.Options, "Options")

	for _, v := range r.Nested {
		rd.generateMethods(v)
	}
}

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


Question:
Creates an event for a SQL query.

        >>> client.captureQuery('SELECT * FROM foo')

def captureQuery(self, query, params=(), engine=None, **kwargs):

        return self.capture(
            'raven.events.Query', query=query, params=params, engine=engine,
            **kwargs)

func (mr *MockEventInterfaceMockRecorder) GetFieldSelector(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFieldSelector", reflect.TypeOf((*MockEventInterface)(nil).GetFieldSelector), arg0, arg1, arg2, arg3)
}

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


Question:
Convert single entity into XML

@param Element $entity Element
@return string XML created

protected function mapSingleEntity(Element $entity)
    {
        $element = new \ReflectionObject($entity);
        $properties = $element->getProperties();
        $xml = '';
        foreach ($properties as $property) {
            $propName = $property->getName();
            $propValue = $entity->$propName;
            if ($propValue !== null) {
                $xml .= '<FL val="' . str_replace(['_', 'N36', 'E5F', '&', '98T'], [' ', '$', '_', 'and', '?'], $propName) . '">';
                // It's a list of entities
                if (is_array($propValue)) {
                    $tag = null;
                    list($key, $list) = each($propValue);
                    if (!is_numeric($key)) {
                        $tag = $key;
                        $propValue = $list;
                    }
                    $xml .= $this->mapEntityList($propValue, $tag);
                }
                // It's an entity
                elseif (is_object($propValue) && (!$propValue instanceof \DateTime)) {
                    $xml .= $this->mapSingleEntity($propValue);
                }
                else {
                    $propValue = (string) $propValue;
                    // Use Character Data for non integers
                    if (!ctype_digit($propValue)) {
                       $propValue = "<![CDATA[$propValue]]>";
                    }
                    $xml .= $propValue;
                }
                $xml .= '</FL>';
            }
        }
        return $xml;
    }

public static void convertRoot(ConfigurationImpl configuration, RootDoc rd,
            DocPath outputdir) {
        new SourceToHTMLConverter(configuration, rd, outputdir).generate();
    }

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


Question:
Resizing the date range of Calendar Item Event or Updating the dates of the Item event
@param array $postValues, this containing the calendar id, date start, date end

@return Array

public function reschedCalendarEvent($postValues)
	{
	    $responseData = array();

	    $calendarTable = $this->getServiceLocator()->get('MelisCalendarTable');

	    $melisCoreAuth = $this->getServiceLocator()->get('MelisCoreAuth');
	    $userAuthDatas =  $melisCoreAuth->getStorage()->read();
	    $userId = (int) $userAuthDatas->usr_id;

	    $resultEvent = $calendarTable->getEntryById($postValues['cal_id']);

	    if (!empty($resultEvent)){

	        $event = $resultEvent->current();

	        if (!empty($event)){
	            if ($postValues['cal_date_end']==''){
	                $postValues['cal_date_end'] = $postValues['cal_date_start'];
	            }
	            $postValues['cal_last_update_by'] = $userId;
	            $postValues['cal_date_last_update'] = date('Y-m-d H:i:s');
	            $calendarTable->save($postValues,$postValues['cal_id']);
	            $responseData['success'] = 1;
	        }
	    }

	    return $responseData;
	}

public function populateUpdateFields($data) {

        $data['id']                 = $this->request->input('id');
        $data['user_id']            = $this->request->input('user_id');
        $data['priority_id']        = $this->request->input('priority_id');

        if (isset($data['from_email_address'])) {
            $data['from_email_address'] = $this->request->input('from_email_address');
        }

        if (isset($data['from_name'])) {
            $data['from_name']          = $this->request->input('from_name');
        }

        if (isset($data['to_email_address'])) {
            $data['to_email_address']   = $this->request->input('to_email_address');
        }

        if (isset($data['to_name'] )) {
            $data['to_name']            = $this->request->input('to_name');
        }

        $data['priority_id']        = $this->request->input('priority_id');
        $data['archived']           = $this->request->input('archived');
        $data['updated_at']         = Carbon::now();
        $data['updated_by']         = Auth::user()->id;

        return $data;
    }

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


Question: ===================================================================== Broadcast a message to all connected sockets.

function broadcast(event, data) {
	HttpSockets.forEach(
		function(socket) {
			socket.emit(event, data);
		});
}

func (v *VoiceConnection) opusSender(udpConn *net.UDPConn, close <-chan struct{}, opus <-chan []byte, rate, size int) {

	if udpConn == nil || close == nil {
		return
	}

	// VoiceConnection is now ready to receive audio packets
	// TODO: this needs reviewed as I think there must be a better way.
	v.Lock()
	v.Ready = true
	v.Unlock()
	defer func() {
		v.Lock()
		v.Ready = false
		v.Unlock()
	}()

	var sequence uint16
	var timestamp uint32
	var recvbuf []byte
	var ok bool
	udpHeader := make([]byte, 12)
	var nonce [24]byte

	// build the parts that don't change in the udpHeader
	udpHeader[0] = 0x80
	udpHeader[1] = 0x78
	binary.BigEndian.PutUint32(udpHeader[8:], v.op2.SSRC)

	// start a send loop that loops until buf chan is closed
	ticker := time.NewTicker(time.Millisecond * time.Duration(size/(rate/1000)))
	defer ticker.Stop()
	for {

		// Get data from chan.  If chan is closed, return.
		select {
		case <-close:
			return
		case recvbuf, ok = <-opus:
			if !ok {
				return
			}
			// else, continue loop
		}

		v.RLock()
		speaking := v.speaking
		v.RUnlock()
		if !speaking {
			err := v.Speaking(true)
			if err != nil {
				v.log(LogError, "error sending speaking packet, %s", err)
			}
		}

		// Add sequence and timestamp to udpPacket
		binary.BigEndian.PutUint16(udpHeader[2:], sequence)
		binary.BigEndian.PutUint32(udpHeader[4:], timestamp)

		// encrypt the opus data
		copy(nonce[:], udpHeader)
		v.RLock()
		sendbuf := secretbox.Seal(udpHeader, recvbuf, &nonce, &v.op4.SecretKey)
		v.RUnlock()

		// block here until we're exactly at the right time :)
		// Then send rtp audio packet to Discord over UDP
		select {
		case <-close:
			return
		case <-ticker.C:
			// continue
		}
		_, err := udpConn.Write(sendbuf)

		if err != nil {
			v.log(LogError, "udp write error, %s", err)
			v.log(LogDebug, "voice struct: %#v\n", v)
			return
		}

		if (sequence) == 0xFFFF {
			sequence = 0
		} else {
			sequence++
		}

		if (timestamp + uint32(size)) >= 0xFFFFFFFF {
			timestamp = 0
		} else {
			timestamp += uint32(size)
		}
	}
}

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


Question: Returns the iden corresponding to a provenance stack and stores if it hasn't seen it before

def getProvIden(self, provstack):
        '''

        '''
        iden = _providen(provstack)
        misc, frames = provstack
        # Convert each frame back from (k, v) tuples to a dict
        dictframes = [(typ, {k: v for (k, v) in info}) for (typ, info) in frames]
        bytz = s_msgpack.en((misc, dictframes))
        didwrite = self.slab.put(iden, bytz, overwrite=False, db=self.db)
        if didwrite:
            self.provseq.save([iden])

        return iden

def actually_mount(self, client):
        """"""
        a_obj = self.config.copy()
        if 'description' in a_obj:
            del a_obj['description']

        try:
            m_fun = getattr(client, self.mount_fun)
            if self.description and a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description,
                      config=a_obj)
            elif self.description:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description)
            elif a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      config=a_obj)
            else:
                m_fun(self.backend,
                      mount_point=self.path)
        except hvac.exceptions.InvalidRequest as exception:
            match = re.match('existing mount at (?P<path>.+)', str(exception))
            if match:
                e_msg = "%s has a mountpoint conflict with %s" % \
                        (self.path, match.group('path'))
                raise aomi_excep.VaultConstraint(e_msg)
            else:
                raise

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


Question:
Has Header With Specific Label?

! headers label are case-insensitive

@param string $label

@return bool

function has($label)
    {
        $r = $this->getIterator()->find( array('label' => strtolower($label)) );
        foreach ($r as $v)
            return true;

        return false;
    }

def _setHeaderLabel(self, col, text):

        model = self.tree.model()
        item = model.horizontalHeaderItem(col)
        if item:
            item.setText(text)
        else:
            model.setHorizontalHeaderItem(col, QtGui.QStandardItem(text))

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


Question:
indent

@param   string $input

@return  string

public function indent($input)
    {
        $this->log = [];

        $input = $this->tempScripts($input);

        $input = $this->removeDoubleWhiteSpace($input);

        $input = $this->tempInlineElements($input);

        $output = $this->doIndent($input);

        $output = $this->restoreScripts($output);

        $output = $this->restoreInlineElements($output);

        return trim($output);
    }

public function apply($testable, array $config = array()) {
		$message = 'Inline HTML should be in the following format: "<?=$var; ?>"';
		$lines = $testable->lines();
		$tokens = $testable->tokens();
		$lineCache = $testable->lineCache();
		$matches = array();
		foreach ($lines as $lineNumber => $line) {
			$lineTokens = isset($lineCache[$lineNumber]) ? $lineCache[$lineNumber] : array();
			if ($this->hasRequiredTokens($tokens, $lineTokens)) {
				preg_match_all($this->findPattern, $line, $matches);
				foreach ($matches as $match) {
					if (isset($match[0]) && preg_match($this->matchPattern, $match[0]) === 0) {
						$this->addViolation(array(
							'message' => $message,
							'line' => $lineNumber,
						));
					}
				}
			}
		}
	}

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


Question:
Add columns to header (if necessary).

@param array $keys

protected function mergeHeader(array $keys)
    {
        foreach ($keys as $key) {
            if (!isset($this->header[$key])) {
                $this->header[$key] = '';
            }
        }
    }

private function buildAuthorizationHeader($oauth)
    {
        $r      = 'Authorization: OAuth ';
        $values = $this->normalizeParameters($oauth);
        $r .= str_replace('&', ', ', $values);

        return $r;
    }

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


Question: Check if rectangle is infinite.

def isInfinite(self):
        """"""
        return self.x0 > self.x1 or self.y0 > self.y1

public static Function<? super ReactiveSeq<Integer>, ? extends ReactiveSeq<Integer>> skipInts(long skip){

        return a->a.ints(i->i,s->s.skip(skip));
    }

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


Question:
Obtains a configuration value
@param string $name
@throws \InvalidArgumentException
@return mixed

public function getOption($name) {
		$this->validateName($name);
		if (array_key_exists($name, $this->config))
			return $this->config[$name];

		return null;
	}

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

        return $this;
    }

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


Question: // SetReference sets the Reference field's value.

func (s *MovSettings) SetReference(v string) *MovSettings {
	s.Reference = &v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

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


Question:
Dispatches a request. Expects zero or more target handlers
        :param request: The request to dispatch
        :return: None.

def publish(self, request: Request) -> None:

        handler_factories = self._registry.lookup(request)
        for factory in handler_factories:
            handler = factory()
            handler.handle(request)

public void marshall(DescribeCasesRequest describeCasesRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeCasesRequest.getCaseIdList(), CASEIDLIST_BINDING);
            protocolMarshaller.marshall(describeCasesRequest.getDisplayId(), DISPLAYID_BINDING);
            protocolMarshaller.marshall(describeCasesRequest.getAfterTime(), AFTERTIME_BINDING);
            protocolMarshaller.marshall(describeCasesRequest.getBeforeTime(), BEFORETIME_BINDING);
            protocolMarshaller.marshall(describeCasesRequest.getIncludeResolvedCases(), INCLUDERESOLVEDCASES_BINDING);
            protocolMarshaller.marshall(describeCasesRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(describeCasesRequest.getMaxResults(), MAXRESULTS_BINDING);
            protocolMarshaller.marshall(describeCasesRequest.getLanguage(), LANGUAGE_BINDING);
            protocolMarshaller.marshall(describeCasesRequest.getIncludeCommunications(), INCLUDECOMMUNICATIONS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
@param float|int|string $number

@return self

public static function fromNumber($number)
    {
        if (is_float($number)) {
            return self::fromString(sprintf('%.14F', $number));
        }

        if (is_int($number)) {
            return new self($number);
        }

        if (is_string($number)) {
            return self::fromString($number);
        }

        throw new \InvalidArgumentException('Valid numeric value expected');
    }

function parseType (props) {
  const {
    current
  } = props

  // 抛出错误信息
  const throwErrorMsg = type => {
    throw new TypeError(type + ' must be number')
  }

  if (current) isNumber(current) ? '' : throwErrorMsg('current')
}

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


Question: // StdDev returns the standard deviation of the values in the sample.

func (s *UniformSample) StdDev() float64 {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	return SampleStdDev(s.values)
}

private function buildTableComment() {
        /** @var ResultSet $results */
        $results = $this->getConfiguration()->getConnection()->query('SHOW TABLE STATUS WHERE Name="' . $this->getTableName() . '"');
        $result = (object)$results->fetch();
        $this->setComment($result->Comment);
    }

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


Question:
Loads the requested category into the pages categories array.

@param int $categoryid
@throws moodle_exception

protected function load_category($categoryid) {
        global $DB;
        $category = $DB->get_record('course_categories', array('id' => $categoryid));
        if (!$category) {
            throw new moodle_exception('unknowncategory');
        }
        $this->_categories[$category->id] = $category;
        $parentcategoryids = explode('/', trim($category->path, '/'));
        array_pop($parentcategoryids);
        foreach (array_reverse($parentcategoryids) as $catid) {
            $this->_categories[$catid] = null;
        }
    }

public function get_course_module(event_interface $event) {
        if (!$event->get_course_module()) {
            return null;
        }

        $id = $event->get_course_module()->get('id');
        $name = $event->get_course_module()->get('modname');
        $key = $name . '_' . $id;

        if (!isset($this->coursemodules[$key])) {
            $this->coursemodules[$key] = get_coursemodule_from_instance($name, $id, 0, false, MUST_EXIST);
        }

        return $this->coursemodules[$key];
    }

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


Question: // DiffSchemaToArray diffs two schemas and return the schema diffs if there is any.

func DiffSchemaToArray(leftName string, left *tabletmanagerdatapb.SchemaDefinition, rightName string, right *tabletmanagerdatapb.SchemaDefinition) (result []string) {
	er := concurrency.AllErrorRecorder{}
	DiffSchema(leftName, left, rightName, right, &er)
	if er.HasErrors() {
		return er.ErrorStrings()
	}
	return nil
}

func VerifySwaggerDocsExist(kubeTypes []KubeTypes, w io.Writer) (int, error) {
	missingDocs := 0
	buffer := newBuffer()

	for _, kubeType := range kubeTypes {
		structName := kubeType[0].Name
		if kubeType[0].Doc == "" {
			format := "Missing documentation for the struct itself: %s\n"
			s := fmt.Sprintf(format, structName)
			buffer.addLine(s, 0)
			missingDocs++
		}
		kubeType = kubeType[1:] // Skip struct definition

		for _, pair := range kubeType { // Iterate only the fields
			if pair.Doc == "" {
				format := "In struct: %s, field documentation is missing: %s\n"
				s := fmt.Sprintf(format, structName, pair.Name)
				buffer.addLine(s, 0)
				missingDocs++
			}
		}
	}

	if err := buffer.flushLines(w); err != nil {
		return -1, err
	}
	return missingDocs, nil
}

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


Question:
Writes to the file.

@param words
to write
@return the number of written bytes.
@throws IllegalStateException
if file is not writable

public int write(String words) {
    if (mode.isWritable() == false)
      throw new IllegalStateException("IOError: not opened for writing");

    try {
      raFile.write(words.getBytes());
    } catch (IOException e) {
      logger.log(Level.SEVERE, null, e);
      throw new RuntimeException(e);
    }
    return words.getBytes().length;
  }

def write_to_logfile(out, err, logfile, samplelog=None, sampleerr=None, analysislog=None, analysiserr=None):

    # Run log
    with open(logfile + '_out.txt', 'a+') as outfile:
        outfile.write(out + '\n')
    with open(logfile + '_err.txt', 'a+') as outfile:
        outfile.write(err + '\n')
    # Sample log
    if samplelog:
        with open(samplelog, 'a+') as outfile:
            outfile.write(out + '\n')
        with open(sampleerr, 'a+') as outfile:
            outfile.write(err + '\n')
    # Analysis log
    if analysislog:
        with open(analysislog, 'a+') as outfile:
            outfile.write(out + '\n')
        with open(analysiserr, 'a+') as outfile:
            outfile.write(err + '\n')

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


Question: Display the error message that caused the exception.

def display_error_message(ex) # :nodoc:
      trace "#{name} aborted!"
      display_exception_details(ex)
      trace "Tasks: #{ex.chain}" if has_chain?(ex)
      trace "(See full trace by running task with --trace)" unless
         options.backtrace
    end

public static String stackToDebugString(Throwable e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        pw.close();
        String text = sw.toString();

        // Jump past the throwable
        text = text.substring(text.indexOf("at"));
        return text;
    }

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


Question: Get a table representation of a dictionary.

def table_output(data):
    ''''''
    if type(data) == DictType:
        data = data.items()
    headings = [ item[0] for item in data ]
    rows = [ item[1] for item in data ]
    columns = zip(*rows)
    if len(columns):
        widths = [ max([ len(str(y)) for y in row ]) for row in rows ]
    else:
        widths = [ 0 for c in headings ]
    for c, heading in enumerate(headings):
        widths[c] = max(widths[c], len(heading))
    column_count = range(len(rows))
    table = [ ' '.join([ headings[c].ljust(widths[c]) for c in column_count ]) ]
    table.append(' '.join([ '=' * widths[c] for c in column_count ]))
    for column in columns:
        table.append(' '.join([ str(column[c]).ljust(widths[c]) for c in column_count ]))
    return '\n'.join(table)

def save(self) -> sql.Executant:

        r = self._dict_to_SQL(self.modifications)
        self.modifications.clear()
        return r

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


Question:
Turn on/off screen.
        Usage:
        d.screen.on()
        d.screen.off()

        d.screen == 'on'  # Check if the screen is on, same as 'd.screenOn'
        d.screen == 'off'  # Check if the screen is off, same as 'not d.screenOn'

def screen(self):
        '''

        '''
        devive_self = self

        class _Screen(object):
            def on(self):
                return devive_self.wakeup()

            def off(self):
                return devive_self.sleep()

            def __call__(self, action):
                if action == "on":
                    return self.on()
                elif action == "off":
                    return self.off()
                else:
                    raise AttributeError("Invalid parameter: %s" % action)

            def __eq__(self, value):
                info = devive_self.info
                if "screenOn" not in info:
                    raise EnvironmentError("Not supported on Android 4.3 and belows.")
                if value in ["on", "On", "ON"]:
                    return info["screenOn"]
                elif value in ["off", "Off", "OFF"]:
                    return not info["screenOn"]
                raise ValueError("Invalid parameter. It can only be compared with on/off.")

            def __ne__(self, value):
                return not self.__eq__(value)

        return _Screen()

def copy(self, sleep=_unset, stop=_unset, wait=_unset,
             retry=_unset, before=_unset, after=_unset, before_sleep=_unset,
             reraise=_unset):
        """"""
        if before_sleep is _unset:
            before_sleep = self.before_sleep
        return self.__class__(
            sleep=self.sleep if sleep is _unset else sleep,
            stop=self.stop if stop is _unset else stop,
            wait=self.wait if wait is _unset else wait,
            retry=self.retry if retry is _unset else retry,
            before=self.before if before is _unset else before,
            after=self.after if after is _unset else after,
            before_sleep=before_sleep,
            reraise=self.reraise if after is _unset else reraise,
        )

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


Question:
return a dictionary of  parameter names in each parameter group.

        Returns:
            dictionary

def pars_in_groups(self):

        pargp = self.par_groups
        allpars = dict()
        for cpg in pargp:
            allpars[cpg] = [i for i in self.parameter_data.loc[self.parameter_data.pargp == cpg, 'parnme']]
        return allpars

def _param_to_list(self):

        for item in self._params:
            self.__dict__[item] = list(self.__dict__[item])

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


Question:
Get the query object to be processed by dataTables.

@return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder|\Illuminate\Support\Collection

public function query()
    {
        $locale = app()->getLocale();
        $query = app($this->model)->query()->orderBy('sort_order', 'ASC')->orderBy("title->\${$locale}", 'ASC');

        return $this->applyScopes($query);
    }

protected static function boot()
    {
        parent::boot();

        self::$buildQueryScopeDefaults['columns'] = [
            'id',
            'user_id',
            'option_id',
        ];

        self::$buildQueryScopeDefaults['relations'] = [
            'option' => function (BelongsTo $optionQuery) {
                $optionQuery->select(['id', 'poll_id', 'answer']);
            },
        ];
    }

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


Question:
Draw the fold indicator/trigger (arrow).

        :param top: Top position
        :param mouse_over: Whether the mouse is over the indicator
        :param collapsed: Whether the trigger is collapsed or not.
        :param painter: QPainter

def _draw_fold_indicator(self, top, mouse_over, collapsed, painter):

        rect = QtCore.QRect(0, top, self.sizeHint().width(),
                            self.sizeHint().height())
        if self._native:
            if os.environ['QT_API'].lower() not in PYQT5_API:
                opt = QtGui.QStyleOptionViewItemV2()
            else:
                opt = QtWidgets.QStyleOptionViewItem()
            opt.rect = rect
            opt.state = (QtWidgets.QStyle.State_Active |
                         QtWidgets.QStyle.State_Item |
                         QtWidgets.QStyle.State_Children)
            if not collapsed:
                opt.state |= QtWidgets.QStyle.State_Open
            if mouse_over:
                opt.state |= (QtWidgets.QStyle.State_MouseOver |
                              QtWidgets.QStyle.State_Enabled |
                              QtWidgets.QStyle.State_Selected)
                opt.palette.setBrush(QtGui.QPalette.Window,
                                     self.palette().highlight())
            opt.rect.translate(-2, 0)
            self.style().drawPrimitive(QtWidgets.QStyle.PE_IndicatorBranch,
                                       opt, painter, self)
        else:
            index = 0
            if not collapsed:
                index = 2
            if mouse_over:
                index += 1
            QtGui.QIcon(self._custom_indicators[index]).paint(painter, rect)

function matchesFilter (pattern, channel) {
    // If multi-level wildcard is the only character in pattern, then any string will match
    if (pattern==="#") {
        return true;
    }
    // Handle all other multi-level wildcards
    // FROM SPEC: The number sign (‘#’ U+0023) is a wildcard character that matches any number of levels within a topic. The multi-level wildcard represents the parent and any number of child levels. The multi-level wildcard character MUST be specified either on its own or following a topic level separator. In either case it MUST be the last character specified in the Topic Filter
    var p_wo_wildcard = pattern.substring(0, pattern.length-2);
    var str_wo_details = channel.substring(0, pattern.length-2);
    if (pattern.slice(-1)=='#' && p_wo_wildcard==str_wo_details) {
        return true;
    }
    // TODO Handle single-level wildcards (+)
    // FROM SPEC: The single-level wildcard can be used at any level in the Topic Filter, including first and last levels. Where it is used it MUST occupy an entire level of the filter [MQTT-4.7.1-3]. It can be used at more than one level in the Topic Filter and can be used in conjunction with the multilevel wildcard.
    // http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718107
    return false;
}

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


Question:
Effectively removes any function hooks for functions in the global
namespace.

public function restoreGlobalFunctions(): void
    {
        foreach (self::$hooks as $key => $data) {
            self::$hooks[$key]['callback'] = null;
        }
    }

func groupByBindings() ElementHook {
	var f func(st *Statement, ce ConsumedElement) (ElementHook, error)
	f = func(st *Statement, ce ConsumedElement) (ElementHook, error) {
		if ce.IsSymbol() {
			return f, nil
		}
		tkn := ce.Token()
		if tkn.Type == lexer.ItemBinding {
			st.groupBy = append(st.groupBy, tkn.Text)
		}
		return f, nil
	}
	return f
}

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


Question: // SetVolumeKmsKeyId sets the VolumeKmsKeyId field's value.

func (s *DocumentClassifierProperties) SetVolumeKmsKeyId(v string) *DocumentClassifierProperties {
	s.VolumeKmsKeyId = &v
	return s
}

func (c *ClientsetSecretStore) createSecret(s *fi.Secret, name string, replace bool) (*kops.Keyset, error) {
	keyset := &kops.Keyset{}
	keyset.Name = NamePrefix + name
	keyset.Spec.Type = kops.SecretTypeSecret

	t := time.Now().UnixNano()
	id := pki.BuildPKISerial(t)

	keyset.Spec.Keys = append(keyset.Spec.Keys, kops.KeysetItem{
		Id:              id.String(),
		PrivateMaterial: s.Data,
	})

	if replace {
		return c.clientset.Keysets(c.namespace).Update(keyset)
	}
	return c.clientset.Keysets(c.namespace).Create(keyset)
}

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


Question:
<p>
A list of cancellation reasons.
</p>

@param cancellationReasons
A list of cancellation reasons.

@com.fasterxml.jackson.annotation.JsonProperty("CancellationReasons")
    public void setCancellationReasons(java.util.Collection<CancellationReason> cancellationReasons) {
        if (cancellationReasons == null) {
            this.cancellationReasons = null;
            return;
        }

        this.cancellationReasons = new java.util.ArrayList<CancellationReason>(cancellationReasons);
    }

def get_delete_api(self, resource):

        parameters = self.delete_item_parameters(resource)

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

        return get_item_api

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


Question:
Delete document from the index.
@param string $text
@param string|null $field

public function delete($text, $field = null)
    {
        $query = new Term(new IndexTerm($text, $field));
        $hits = $this->luceneIndex->find($query);
        foreach ($hits as $hit) {
            $this->luceneIndex->delete($hit);
        }
    }

public function setValue($value, RequestAbstract $request)
    {
        if (!$request->hasParam($this->getHtmlName() . '_change')) {
            $this->value = false;
        } else if ($request->hasParam($this->getHtmlName() . '_change')) {
            $this->value = true;
        }
    }

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


Question:
Adjusts this index table to contain the reverse sorted index order for
the given list
@param <T> the data type
@param list the list of objects

public <T extends Comparable<T>> void sortR(List<T> list)
    {
        sort(list, getReverse(defaultComp));
    }

public Pair<Boolean, String> property() {
    String name = method.getName();
    if (Modifier.isStatic(method.getModifiers())) return null;
    if (0 == parameterTypes.length) {
      if (name.startsWith("get")) {
        if (name.length() > 3) return of(TRUE, uncapitalize(substringAfter(name, "get")));
      } else if (name.startsWith("is")) {
        if (name.length() > 2) return of(TRUE, uncapitalize(substringAfter(name, "is")));
      }
    } else if (1 == parameterTypes.length) {
      if (name.startsWith("set") && name.length() > 3) return of(FALSE,
          uncapitalize(substringAfter(name, "set")));
    }
    return null;
  }

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


Question:
Make sure that set ids are unique.

    Args:
        gmt (GMT object): list of dicts

    Returns:
        None

def verify_gmt_integrity(gmt):

    # Verify that set ids are unique
    set_ids = [d[SET_IDENTIFIER_FIELD] for d in gmt]
    assert len(set(set_ids)) == len(set_ids), (
        "Set identifiers should be unique. set_ids: {}".format(set_ids))

def user_groups(self, ldap_user, group_search):

        groups = []

        try:
            user_uid = ldap_user.attrs["uid"][0]

            if "gidNumber" in ldap_user.attrs:
                user_gid = ldap_user.attrs["gidNumber"][0]
                filterstr = "(|(gidNumber={})(memberUid={}))".format(
                    self.ldap.filter.escape_filter_chars(user_gid),
                    self.ldap.filter.escape_filter_chars(user_uid),
                )
            else:
                filterstr = "(memberUid={})".format(
                    self.ldap.filter.escape_filter_chars(user_uid)
                )

            search = group_search.search_with_additional_term_string(filterstr)
            groups = search.execute(ldap_user.connection)
        except (KeyError, IndexError):
            pass

        return groups

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


Question:
Override this to customize how the background task is created.

@param task the task to be run in the background
@return the thread of the task

protected Thread newThread(Runnable task) {
    Thread result = new Thread(wrapTask(task));
    result.setDaemon(true);
    return result;
  }

def _register_process_entry(self, process_entry, call_back):

        trigger_frequency = process_entry.trigger_frequency
        if isinstance(process_entry, ManagedProcessEntry):
            handler_key = process_entry.process_name
            handler = ManagedThreadHandler(self.logger, handler_key, trigger_frequency, call_back, process_entry)
            self.managed_handlers[handler.key] = handler
        elif isinstance(process_entry, FreerunProcessEntry):
            handler_key = (process_entry.process_name, process_entry.entry_name)
            handler = FreerunThreadHandler(self.logger, handler_key, trigger_frequency, call_back, process_entry)
            self.freerun_handlers[handler.key] = handler
        else:
            raise ValueError('ProcessEntry type {0} is not known to the system. Skipping it.'
                             .format(process_entry.__class__.__name__))

        if process_entry.is_on:
            handler.activate()
            self.logger.info('Started {0} for {1}.'
                             .format(handler.__class__.__name__, handler.key))
        else:
            self.logger.info('Registered {0} for {1}. Idle until activated.'
                             .format(handler.__class__.__name__, handler.key))

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


Question: // SetSuccess sets the Success field's value.

func (s *TestRoleOutput) SetSuccess(v string) *TestRoleOutput {
	s.Success = &v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

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


Question:
// ExportIntoEnv modifies env to export location of this local LogDog server
// into the environment, so a subprocesses can stream logs.

func (l *logdogServer) ExportIntoEnv(env environ.Env) error {
	if l.serv == nil {
		return fmt.Errorf("not started")
	}

	(&bootstrap.Environment{
		CoordinatorHost: l.CoordinatorHost,
		Project:         l.Project,
		Prefix:          l.Prefix,
		StreamServerURI: l.serv.Address(),
	}).Augment(env)
	return nil
}

def conditions(self, start, last_attempt):

        if time.time() - start > self.timeout:
            yield WaitCondition.Timedout
            return

        if last_attempt is not None and time.time() - last_attempt < self.wait_between_attempts:
            yield WaitCondition.KeepWaiting
            return

        if self.greps is not NotSpecified:
            for name, val in self.greps.items():
                yield 'grep "{0}" "{1}"'.format(val, name)

        if self.file_value is not NotSpecified:
            for name, val in self.file_value.items():
                command = 'diff <(echo {0}) <(cat {1})'.format(val, name)
                if not self.harpoon.debug:
                    command = "{0} > /dev/null".format(command)
                yield command

        if self.port_open is not NotSpecified:
            for port in self.port_open:
                yield 'nc -z 127.0.0.1 {0}'.format(port)

        if self.curl_result is not NotSpecified:
            for url, content in self.curl_result.items():
                yield 'diff <(curl "{0}") <(echo {1})'.format(url, content)

        if self.file_exists is not NotSpecified:
            for path in self.file_exists:
                yield 'cat {0} > /dev/null'.format(path)

        if self.command not in (None, "", NotSpecified):
            for command in self.command:
                yield command

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


Question: Enqueue an arbitrary synchronous function.

async def async_enqueue_sync(self, func, *func_args):
        '''

        '''
        worker = self.pick_sticky(0)  # just pick first always
        args = (func,) + func_args
        await worker.enqueue(enums.Task.FUNC, args)

def on_event(self, event):

        self._queue.append((event))
        if not self._active and self.plot.document:
            self.plot.document.add_timeout_callback(self.process_on_event, 50)
            self._active = True

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


Question: // SetName sets the Name field's value.

func (s *DeleteImageBuilderInput) SetName(v string) *DeleteImageBuilderInput {
	s.Name = &v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

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


Question:
Returns global variables for generating function from ``func_code``. Includes
        compiled regular expressions and imports, so it does not have to do it every
        time when validation function is called.

def global_state(self):

        self._generate_func_code()

        return dict(
            REGEX_PATTERNS=self._compile_regexps,
            re=re,
            JsonSchemaException=JsonSchemaException,
        )

def _validate(self):
        ''''''

        self._validate_fasta_vs_seqres()
        self._validate_mapping_signature()
        self._validate_id_types()
        self._validate_residue_types()

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


Question: Keep track of the files in a project

function CommonJsProject(opts) {
  this.roots = opts.roots;
  this.textPluginPattern = opts.textPluginPattern || /^text!/;

  opts.roots = this.roots.map(function(root) {
    if (!copy.isDirectory(root)) {
      throw new Error('Each commonjs root should be a directory: ' + root);
    }
    return ensureTrailingSlash(root);
  }, this);

  // A module is a Location that also has dep
  this.currentModules = {};
  this.ignoredModules = {};
}

public function list(string $commit, string $path, array $params = [])
    {
        $path = $this->buildFileHistoryPath($commit, ...explode('/', $path));

        return $this->get($path, $params);
    }

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


Question: set store configuration settings

public void setStoreLocation(String location, Job job) throws IOException
    {
        conf = HadoopCompat.getConfiguration(job);
        setLocationFromUri(location);

        if (username != null && password != null)
            ConfigHelper.setOutputKeyspaceUserNameAndPassword(conf, username, password);
        if (splitSize > 0)
            ConfigHelper.setInputSplitSize(conf, splitSize);
        if (partitionerClass!= null)
            ConfigHelper.setOutputPartitioner(conf, partitionerClass);
        if (rpcPort != null)
        {
            ConfigHelper.setOutputRpcPort(conf, rpcPort);
            ConfigHelper.setInputRpcPort(conf, rpcPort);
        }
        if (initHostAddress != null)
        {
            ConfigHelper.setOutputInitialAddress(conf, initHostAddress);
            ConfigHelper.setInputInitialAddress(conf, initHostAddress);
        }

        ConfigHelper.setOutputColumnFamily(conf, keyspace, column_family);
        CqlConfigHelper.setOutputCql(conf, outputQuery);

        setConnectionInformation();

        if (ConfigHelper.getOutputRpcPort(conf) == 0)
            throw new IOException("PIG_OUTPUT_RPC_PORT or PIG_RPC_PORT environment variable not set");
        if (ConfigHelper.getOutputInitialAddress(conf) == null)
            throw new IOException("PIG_OUTPUT_INITIAL_ADDRESS or PIG_INITIAL_ADDRESS environment variable not set");
        if (ConfigHelper.getOutputPartitioner(conf) == null)
            throw new IOException("PIG_OUTPUT_PARTITIONER or PIG_PARTITIONER environment variable not set");

        initSchema(storeSignature);
    }

function config(env /*: ?env */) {
  const isProd = env && env.prod;
  const config = isProd ? prod : dev;
  return config(env);
}

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


Question:
Group URLs by schema.

@param \eZ\Publish\API\Repository\Values\URL\SearchResult $urls
@return array

private function groupByScheme(SearchResult $urls)
    {
        $grouped = [];

        foreach ($urls as $url) {
            $scheme = parse_url($url->url, PHP_URL_SCHEME);
            if (!$scheme) {
                continue;
            }

            if (!isset($grouped[$scheme])) {
                $grouped[$scheme] = [];
            }

            $grouped[$scheme][] = $url;
        }

        return $grouped;
    }

protected function getAllRouteNames($resourceName = null)
    {
        $resourceName = $resourceName ?? $this->resourceName;

        return [
            'index'   => $this->prefix.$this->resourceName.'.index',
            'create'  => $this->prefix.$this->resourceName.'.create',
            'store'   => $this->prefix.$this->resourceName.'.store',
            'show'    => $this->prefix.$this->resourceName.'.show',
            'edit'    => $this->prefix.$this->resourceName.'.edit',
            'update'  => $this->prefix.$this->resourceName.'.update',
            'destroy' => $this->prefix.$this->resourceName.'.destroy',
        ];
    }

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


Question:
// structName takes a resource or property name (e.g. AWS::CloudFront::Distribution.Restrictions)
// and returns an appropriate struct name for the generated struct (e.g. AWSCloudfrontDistributionRestrictions)

func structName(input string) string {

	// Remove ::
	output := strings.Replace(input, "::", "", -1)

	// Remove .
	output = strings.Replace(output, ".", "_", -1)

	return output

}

func (i *ImageService) CreateLayer(container *container.Container, initFunc layer.MountInit) (layer.RWLayer, error) {
	var layerID layer.ChainID
	if container.ImageID != "" {
		img, err := i.imageStore.Get(container.ImageID)
		if err != nil {
			return nil, err
		}
		layerID = img.RootFS.ChainID()
	}

	rwLayerOpts := &layer.CreateRWLayerOpts{
		MountLabel: container.MountLabel,
		InitFunc:   initFunc,
		StorageOpt: container.HostConfig.StorageOpt,
	}

	// Indexing by OS is safe here as validation of OS has already been performed in create() (the only
	// caller), and guaranteed non-nil
	return i.layerStores[container.OS].CreateRWLayer(container.ID, layerID, rwLayerOpts)
}

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


Question:
Gets all of the jobs scheduled to run, now.

@return array array(model => CronJob)

public function getScheduledJobs()
    {
        $jobs = [];
        foreach ($this->jobs as $job) {
            $model = CronJob::find($job['id']);

            // create a new model if this is the job's first run
            if (!$model) {
                $model = new CronJob();
                $model->id = $job['id'];
                $model->save();
            }

            // check if scheduled to run
            $params = new DateParameters($job);
            $date = new CronDate($params, $model->last_ran);

            if ($date->getNextRun() > time()) {
                continue;
            }

            $job = array_replace([
                'successUrl' => '',
                'expires' => 0,
            ], $job);

            $job['model'] = $model;
            $jobs[] = $job;
        }

        return $jobs;
    }

public function initCron($src, $controller, $action) {
        if (!Config::config()['user']['debug']['maintenance']) {
            $this->_routeCron($src, $controller, $action);

            if ($this->_route == true) {
                $this->_setFunction($this->request->src);
                $this->_setEvent($this->request->src);
            }
        }
    }

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


Question:
Validate object
@return bool

protected function validate()
    {
        foreach ($this->_requiredAttr as $attr) {
            if (is_array($attr)) {
                $valid = false;
                foreach ($attr as $sub) {
                    if (!is_null($this->$sub)) {
                        $valid = true;
                        break;
                    }
                }
                if (!$valid) {
                    return false;
                }
            } elseif (is_null($this->$attr)) {
                return false;
            }
        }
        return true;
    }

public function isValid($value)
    {
        $this->_setValue($value);
        if ($this->_max <= $value) {
            $this->_error(self::NOT_LESS);
            return false;
        }
        return true;
    }

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


Question:
Build a Criteria object containing the values of all modified columns in this object.

@return Criteria The Criteria object containing all modified values.

public function buildCriteria()
    {
        $criteria = new Criteria(StructureNodeParentTableMap::DATABASE_NAME);

        if ($this->isColumnModified(StructureNodeParentTableMap::COL_STRUCTURE_NODE_ID)) {
            $criteria->add(StructureNodeParentTableMap::COL_STRUCTURE_NODE_ID, $this->structure_node_id);
        }
        if ($this->isColumnModified(StructureNodeParentTableMap::COL_PARENT_ID)) {
            $criteria->add(StructureNodeParentTableMap::COL_PARENT_ID, $this->parent_id);
        }

        return $criteria;
    }

public function update(Query $query)
    {
        $options = $query->getOptions();

        if (isset($options['cache']) && is_string($options['cache']['key'])) {
            $key = $options['cache']['key'];
        }

        $pk   = $query->getPk($options);
        $data = $options['data'];

        if (empty($options['where'])) {
            // 如果存在主键数据 则自动作为更新条件
            if (is_string($pk) && isset($data[$pk])) {
                $where[$pk] = [$pk, '=', $data[$pk]];
                if (!isset($key)) {
                    $key = $this->getCacheKey($query, $data[$pk]);
                }
                unset($data[$pk]);
            } elseif (is_array($pk)) {
                // 增加复合主键支持
                foreach ($pk as $field) {
                    if (isset($data[$field])) {
                        $where[$field] = [$field, '=', $data[$field]];
                    } else {
                        // 如果缺少复合主键数据则不执行
                        throw new Exception('miss complex primary data');
                    }
                    unset($data[$field]);
                }
            }

            if (!isset($where)) {
                // 如果没有任何更新条件则不执行
                throw new Exception('miss update condition');
            } else {
                $options['where']['AND'] = $where;
                $query->setOption('where', ['AND' => $where]);
            }
        } elseif (!isset($key) && is_string($pk) && isset($options['where']['AND'])) {
            foreach ($options['where']['AND'] as $val) {
                if (is_array($val) && $val[0] == $pk) {
                    $key = $this->getCacheKey($query, $val);
                }
            }
        }

        // 更新数据
        $query->setOption('data', $data);

        // 生成UPDATE SQL语句
        $sql  = $this->builder->update($query);
        $bind = $query->getBind();

        if (!empty($options['fetch_sql'])) {
            // 获取实际执行的SQL语句
            return $this->getRealSql($sql, $bind);
        }

        // 检测缓存
        if ($this->cache && isset($key) && $this->cache->get($key)) {
            // 删除缓存
            $this->cache->rm($key);
        }

        // 执行操作
        $result = '' == $sql ? 0 : $this->execute($sql, $bind, $query);

        if ($result) {
            if (is_string($pk) && isset($where[$pk])) {
                $data[$pk] = $where[$pk];
            } elseif (is_string($pk) && isset($key) && strpos($key, '|')) {
                list($a, $val) = explode('|', $key);
                $data[$pk]     = $val;
            }

            $query->setOption('data', $data);
            $query->trigger('after_update');
        }

        return $result;
    }

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


Question:
Determines content-type of the uploaded file.

@param items
@return the content type

private String getContentType(List<FileItem> items) {
        for (FileItem i : items) {
            if (!i.isFormField() && i.getFieldName().equals(CONTENT_PARAMETER)) {
                return i.getContentType();
            }
        }
        return null;
    }

public function httpOptions(RequestInterface $request, ResponseInterface $response)
    {
        $methods = $this->server->getAllowedMethods($request->getPath());

        $response->setHeader('Allow', strtoupper(implode(', ', $methods)));
        $features = ['1', '3', 'extended-mkcol'];

        foreach ($this->server->getPlugins() as $plugin) {
            $features = array_merge($features, $plugin->getFeatures());
        }

        $response->setHeader('DAV', implode(', ', $features));
        $response->setHeader('MS-Author-Via', 'DAV');
        $response->setHeader('Accept-Ranges', 'bytes');
        $response->setHeader('Content-Length', '0');
        $response->setStatus(200);

        // Sending back false will interrupt the event chain and tell the server
        // we've handled this method.
        return false;
    }

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


Question:
Public modifier `maybe`.

Returns `true` if `predicate` is  `null` or `undefined`,
otherwise propagates the return value from `predicate`.
copied from check-types.js

function maybeModifier(predicate) {
        return function () {
          if (!check.defined(arguments[0]) || check.nulled(arguments[0])) {
            return true;
          }
          return predicate.apply(null, arguments);
        };
      }

func (sf *ScalarFunction) Eval(row chunk.Row) (d types.Datum, err error) {
	var (
		res    interface{}
		isNull bool
	)
	switch tp, evalType := sf.GetType(), sf.GetType().EvalType(); evalType {
	case types.ETInt:
		var intRes int64
		intRes, isNull, err = sf.EvalInt(sf.GetCtx(), row)
		if mysql.HasUnsignedFlag(tp.Flag) {
			res = uint64(intRes)
		} else {
			res = intRes
		}
	case types.ETReal:
		res, isNull, err = sf.EvalReal(sf.GetCtx(), row)
	case types.ETDecimal:
		res, isNull, err = sf.EvalDecimal(sf.GetCtx(), row)
	case types.ETDatetime, types.ETTimestamp:
		res, isNull, err = sf.EvalTime(sf.GetCtx(), row)
	case types.ETDuration:
		res, isNull, err = sf.EvalDuration(sf.GetCtx(), row)
	case types.ETJson:
		res, isNull, err = sf.EvalJSON(sf.GetCtx(), row)
	case types.ETString:
		res, isNull, err = sf.EvalString(sf.GetCtx(), row)
	}

	if isNull || err != nil {
		d.SetValue(nil)
		return d, err
	}
	d.SetValue(res)
	return
}

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


Question: Disable all the widgets in this container

def disable(self):

        self._enabled = False
        for child in self.children:
            if isinstance(child, (Container, Widget)):
                child.disable()

public function getEnabled($typeName)
    {
        if (!$this->contains($typeName)) {
            return null;
        }

        foreach ($this->listByTypeName($typeName) as $typeDescriptor) {
            if ($typeDescriptor->isEnabled()) {
                return $typeDescriptor;
            }
        }

        return null;
    }

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


Question: Auto Generated Code

def threshold_monitor_hidden_threshold_monitor_sfp_apply(self, **kwargs):

        config = ET.Element("config")
        threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
        threshold_monitor = ET.SubElement(threshold_monitor_hidden, "threshold-monitor")
        sfp = ET.SubElement(threshold_monitor, "sfp")
        apply = ET.SubElement(sfp, "apply")
        apply.text = kwargs.pop('apply')

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

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

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

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


Question:
Get Content Trash service.

Trash service allows to perform operations related to location trash
(trash/untrash, load/list from trash...)

@return \eZ\Publish\API\Repository\TrashService

public function getTrashService()
    {
        if (null === $this->trashService) {
            $this->trashService = new TrashService(
                $this->getLocationService(),
                $this->client,
                $this->inputDispatcher,
                $this->outputVisitor,
                $this->requestParser
            );
        }

        return $this->trashService;
    }

func (b *IndicesCreateService) Do(ctx context.Context) (*IndicesCreateResult, error) {
	if b.index == "" {
		return nil, errors.New("missing index name")
	}

	// Build url
	path, err := uritemplates.Expand("/{index}", map[string]string{
		"index": b.index,
	})
	if err != nil {
		return nil, err
	}

	params := make(url.Values)
	if b.pretty {
		params.Set("pretty", "true")
	}
	if b.masterTimeout != "" {
		params.Set("master_timeout", b.masterTimeout)
	}
	if b.timeout != "" {
		params.Set("timeout", b.timeout)
	}

	// Setup HTTP request body
	var body interface{}
	if b.bodyJson != nil {
		body = b.bodyJson
	} else {
		body = b.bodyString
	}

	// Get response
	res, err := b.client.PerformRequest(ctx, PerformRequestOptions{
		Method: "PUT",
		Path:   path,
		Params: params,
		Body:   body,
	})
	if err != nil {
		return nil, err
	}

	ret := new(IndicesCreateResult)
	if err := b.client.decoder.Decode(res.Body, ret); err != nil {
		return nil, err
	}
	return ret, nil
}

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


Question:
只取第一行
@param $sQuery
@param array $aParam
@return mixed
@throws TangoException

public function getRow($sQuery, array $aParam = []) {

		$oResult = $this->_query($sQuery, $aParam, FALSE);

		$aRow = $oResult->fetch();

		if ($aRow) {
			static::_ColumnConvertScan($oResult);
			$aRow = static::_ColumnConvertDo($aRow);
		}

		$oResult->closeCursor();

		return $aRow;
	}

public function initializeArguments()
    {
        parent::initializeArguments();
        $this->registerArgument('results', '\Solarium\QueryType\Select\Result\Result', 'Query results', true);
        $this->registerArgument('document', '\Solarium\QueryType\Select\Result\Document', 'Result document to work on',
            true);
        $this->registerArgument('field', 'string', 'name of field in document to highlight', true);
        $this->registerArgument('alternateField', 'string',
            'name of alternate field in document to use for highlighting', false, null);
        $this->registerArgument('index', 'int', 'if the field is an array: index of the single element to highlight',
            false);
        $this->registerArgument('idKey', 'string', 'name of the field in document that is its ID', false, 'id');
        $this->registerArgument('highlightTagOpen', 'string', 'opening tag to insert to begin highlighting', false,
            '');
        $this->registerArgument('highlightTagClose', 'string', 'closing tag to insert to end highlighting', false,
            '');
        $this->registerArgument('raw', 'boolean', 'whether to not HTML escape the output', false, false);
    }

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


Question:
// humanDurationInt prints the given int as if it were a time.Duration  number
// of seconds.

func humanDurationInt(i interface{}) interface{} {
	switch i.(type) {
	case int:
		return humanDuration(time.Duration(i.(int)) * time.Second)
	case int64:
		return humanDuration(time.Duration(i.(int64)) * time.Second)
	case json.Number:
		if i, err := i.(json.Number).Int64(); err == nil {
			return humanDuration(time.Duration(i) * time.Second)
		}
	}

	// If we don't know what type it is, just return the original value
	return i
}

public function renderOne($name, $round = false)
    {
        $result = $this->getResult($name);

        if ($this->renderOneHandler instanceof \Closure) {
            $closure = $this->renderOneHandler;

            return $closure($name, $result, $round, $this->format);
        }

        if ($round !== false) {
            $result = round($result, $round);
        }

        switch ($this->format) {
            case static::MILLI_SECOND:
                $unit = 'ms';
                break;

            case static::MICRO_SECOND:
                $unit = 'μs';
                break;

            case static::SECOND:
            default:
                $unit = 's';
                break;
        }

        return $name . ' => ' . $result . ' ' . $unit;
    }

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


Question:
// renderMainLanguageRedirect creates a redirect to the main language home,
// depending on if it lives in sub folder (e.g. /en) or not.

func (s *Site) renderMainLanguageRedirect() error {

	if !s.h.multilingual.enabled() || s.h.IsMultihost() {
		// No need for a redirect
		return nil
	}

	html, found := s.outputFormatsConfig.GetByName("HTML")
	if found {
		mainLang := s.h.multilingual.DefaultLang
		if s.Info.defaultContentLanguageInSubdir {
			mainLangURL := s.PathSpec.AbsURL(mainLang.Lang, false)
			s.Log.DEBUG.Printf("Write redirect to main language %s: %s", mainLang, mainLangURL)
			if err := s.publishDestAlias(true, "/", mainLangURL, html, nil); err != nil {
				return err
			}
		} else {
			mainLangURL := s.PathSpec.AbsURL("", false)
			s.Log.DEBUG.Printf("Write redirect to main language %s: %s", mainLang, mainLangURL)
			if err := s.publishDestAlias(true, mainLang.Lang, mainLangURL, html, nil); err != nil {
				return err
			}
		}
	}

	return nil
}

public function loadExtra($name)
    {
        $useCurrent = ZenValidator::config()->use_current;
        $parsleyFolder = 'parsley';
        if($useCurrent) {
            $parsleyFolder = 'parsley_current';
        }
        Requirements::javascript(ZENVALIDATOR_PATH . '/javascript/'.$parsleyFolder.'/extra/validator/' . $name . '.js');

        $lang = i18n::get_lang_from_locale(i18n::get_locale());
        Requirements::javascript(ZENVALIDATOR_PATH . '/javascript/'.$parsleyFolder.'/i18n/' . $lang . '.extra.js');
    }

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


Question:
Suggest tags by given keyword
@param $keyword
@param int $limit
@return array

public static function suggest($keyword, $limit = 20)
    {
        /** @var self[] $tags */
        $tags = self::find()
            ->where(['like', 'name', $keyword])
            ->orderBy('frequency DESC, name')
            ->limit($limit)
            ->all();

        $names = array();

        foreach ($tags as $tag) {
            $names[] = ['word' => Html::encode($tag->name)];
        }

        return $names;
    }

def all(path, options = {}, &block)
      all = []
      list_type, list_item = get_list_types(path)

      result = request('GET', path, options)
      raise RequestError.new result.status if result.status_code != 200 or result.parsed[list_type].nil?

      total = result.parsed[list_type]['totalItems'].to_i
      items = result.parsed[list_type]['itemsInPage'].to_i
      return all if total == 0

      pages = (total / config.page_size) + 1
      (0 .. pages - 1).each do |i|
        options[:query][:pgNum] = i
        result     = request('GET', path, options)
        raise RequestError.new result.status if result.status_code != 200
        list_items = result.parsed[list_type][list_item]
        list_items = [ list_items ] if items == 1
        list_items.each { |item| yield item if block_given? }
        all.concat list_items
      end
      all
    end

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


Question:
@param null|\Zend\Ldap\Dn|string $groupSearchDn

@throws Exception\InvalidArgumentException

public function setGroupSearchDn($groupSearchDn)
    {
        if ($groupSearchDn === null) {
            $this->groupSearchDn = null;
            $this->onConfigChanged();
            return;
        }

        $groupSearchDn = $this->normalizeDn($groupSearchDn, '$groupSearchDn');

        if (Dn::isChildOf($groupSearchDn, $this->baseDn)) {
            $this->groupSearchDn = $groupSearchDn;
        } else {
            throw new Exception\InvalidArgumentException('$groupSearchDn must be a child of baseDn');
        }

        $this->onConfigChanged();
    }

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:
Set a new image
@param string $image
@return sFire\Image\Image

public function setImage($file) {

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

		if(false === is_file($file)) {
			return trigger_error(sprintf('File "%s" passed to %s() does not exists', $file, __METHOD__), E_USER_ERROR);
		}

		if(false === is_readable($file)) {
			return trigger_error(sprintf('File "%s" passed to %s() is not readable', $file, __METHOD__), E_USER_ERROR);
		}

		$info = @getimagesize($file);

		if(false === is_array($info) || count($info) < 3) {
			return trigger_error(sprintf('File "%s" passed to %s() is not an image', $file, __METHOD__), E_USER_ERROR);
		}

		$this -> image 	 	= @imagecreatefromstring(file_get_contents($file));
		$this -> extension 	= pathinfo($file, PATHINFO_EXTENSION);

		return $this;
	}

function (arg) {
    var self = this;

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

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

    return argCode;
  }

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


Question:
Amazon Refund method

@param oxOrder $oOrder             OXID Order object
@param float   $fPrice             Price to refund
@param array   $aRequestParameters Custom parameters to send

@return stdClass
@throws Exception

public function refund($oOrder = null, $fPrice, $aRequestParameters = array())
    {
        //Refund ID
        if ($oOrder !== null) {
            $aRequestParameters['refund_amount'] = $fPrice;
            $this->_mapOrderToRequestParameters(
                $oOrder,
                $aRequestParameters,
                array('amazon_capture_id', 'currency_code', 'refund_reference_id', 'seller_refund_note')
            );
        }

        //Make request
        $this->_addSandboxSimulationParams('refund', $aRequestParameters);
        $oData = $this->_convertResponse($this->_getAmazonClient()->refund($aRequestParameters));

        //Update/Insert Refund info
        if ($oData && $oOrder !== null) {
            $sError = '';
            $sAmazonRefundId = '';

            if (isset($oData->Error)) {
                $sState = 'Error';
                $sError = $oData->Error->Message;
            } else {
                $sState = $oData->RefundResult->RefundDetails->RefundStatus->State;
                $sAmazonRefundId = $oData->RefundResult->RefundDetails->AmazonRefundId;
            }

            $sId = $oOrder->getFieldData('bestitamazonorderreferenceid').'_'.$this->getUtilsDate()->getTime();

            $sQuery = "
                INSERT bestitamazonrefunds SET
                  ID = {$this->getDatabase()->quote($sId)},
                  OXORDERID = {$this->getDatabase()->quote($oOrder->getId())},
                  BESTITAMAZONREFUNDID = {$this->getDatabase()->quote($sAmazonRefundId)},
                  AMOUNT = {$fPrice},
                  STATE = {$this->getDatabase()->quote($sState)},
                  ERROR = {$this->getDatabase()->quote($sError)},
                  TIMESTAMP = NOW()";

            $this->getDatabase()->execute($sQuery);
        }

        return $oData;
    }

def parse_tx_op_return(tx):

    # find OP_RETURN output
    op_return = None
    outputs = tx['vout']
    for out in outputs:
        script_key = out['scriptPubKey']['hex']
        if int(script_key[0:2], 16) == virtualchain.OPCODE_VALUES['OP_RETURN']:
            op_return = script_key.decode('hex')
            break

    if op_return is None:
        msg = 'transaction has no OP_RETURN output'
        log.error(msg)
        log.debug('{}:\n{}'.format(msg, simplejson.dumps(tx)))
        return None, None

    # [0] is OP_RETURN, [1] is the length; [2:4] are 'id', [4] is opcode
    magic = op_return[2:4]

    if magic != blockstack_magic_bytes():
        # not a blockchain ID operation
        msg = 'OP_RETURN output does not encode a blockchain ID operation'
        log.error(msg)
        return None, None

    opcode, payload = op_return[4], op_return[5:]

    return (opcode, payload)

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


Question:
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
// It will return error if the slice isn't 16 bytes long.

func (u *UUID) UnmarshalBinary(data []byte) (err error) {
	if len(data) != Size {
		err = fmt.Errorf("uuid: UUID must be exactly 16 bytes long, got %d bytes", len(data))
		return
	}
	copy(u[:], data)

	return
}

func Dissect(dissect bool, data []byte) {
	if dissect {
		dissectLock.Lock()
		defer dissectLock.Unlock()

		initParser()
		parser.DecodeLayers(data, &cache.decoded)

		for _, typ := range cache.decoded {
			switch typ {
			case layers.LayerTypeEthernet:
				fmt.Println(gopacket.LayerString(&cache.eth))
			case layers.LayerTypeIPv4:
				fmt.Println(gopacket.LayerString(&cache.ip4))
			case layers.LayerTypeIPv6:
				fmt.Println(gopacket.LayerString(&cache.ip6))
			case layers.LayerTypeTCP:
				fmt.Println(gopacket.LayerString(&cache.tcp))
			case layers.LayerTypeUDP:
				fmt.Println(gopacket.LayerString(&cache.udp))
			case layers.LayerTypeICMPv4:
				fmt.Println(gopacket.LayerString(&cache.icmp4))
			case layers.LayerTypeICMPv6:
				fmt.Println(gopacket.LayerString(&cache.icmp6))
			default:
				fmt.Println("Unknown layer")
			}
		}
		if parser.Truncated {
			fmt.Println("  Packet has been truncated")
		}

	} else {
		fmt.Print(hex.Dump(data))
	}
}

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


Question:
Create temporary table from current query

@return string New temporary table name, filled in with query primary
identifiers only

private function createTempTable()
    {
        $query = clone $this->getQuery();
        $query->distinct(false);

        // I am sorry but I have to be punished for I am writing this
        $selectFields = &$query->getFields();
        foreach ($selectFields as $key => $value) {
            unset($selectFields[$key]);
        }
        // Again.
        $tables = &$query->getTables();
        foreach ($tables as $key => $table) {
           unset($tables[$key]['all_fields']);
        }

        $query->fields('s', array('id'));

        // Create a temp table containing identifiers to update: this is
        // mandatory because you cannot use the apb_queue in the UPDATE
        // query subselect
        $cx = $this->backend->getConnection();
        $tempTableName = $cx->queryTemporary((string)$query, $query->getArguments());
        // @todo temporary deactivating this, PostgresSQL does not like it (I
        // have no idea why exactly) - I have to get rid of those temp tables
        // anyway.
        // $cx->schema()->addIndex($tempTableName, $tempTableName . '_idx', array('id'));

        return $tempTableName;
    }

private function generateSQL(&$sql, $from, $joins, $where, $having, $group, $values) {
        $froms = [];
        foreach ($from as $f) {
            $froms [] = $f [0] . ' AS ' . $f [1];
        }
        $sql [] = implode(',', $froms);
        if ($joins) {
            foreach ($joins as $join) {
                $sql [] = $join [2] . ' ' . $join [0] . ' AS ' . $join [3] . ' ON (' . $join [1] . ')';
            }
        }
        if ($where && count($where) > 0) {
            $sql [] = 'WHERE ' . $where->getWhereCondition($this, $values);
        }
        if ($group) {
            $sql [] = 'GROUP BY ' . implode(' , ', $group);
        }
        if ($having) {
            $sql [] = 'HAVING ' . implode(' AND ', $having);
        }
    }

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


Question: // SetBrightness sets the Brightness field's value.

func (s *ImageQuality) SetBrightness(v float64) *ImageQuality {
	s.Brightness = &v
	return s
}

protected function fillPassword(string $password): void
    {
        $this->context->findElement($this->fields['password'], $this->defaultTimeout)->setValue($password);
    }

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


Question: Returns a Java StorageLevel based on a pyspark.StorageLevel.

def _getJavaStorageLevel(self, storageLevel):

        if not isinstance(storageLevel, StorageLevel):
            raise Exception("storageLevel must be of type pyspark.StorageLevel")

        newStorageLevel = self._jvm.org.apache.spark.storage.StorageLevel
        return newStorageLevel(storageLevel.useDisk,
                               storageLevel.useMemory,
                               storageLevel.useOffHeap,
                               storageLevel.deserialized,
                               storageLevel.replication)

def staging_data(self):
        """"""
        if self._staging_data is None:
            staging_data = []
            for staging_file in self.profile.get('data_files') or []:
                if os.path.isfile(staging_file):
                    print(
                        'Staging Data: {}{}{}'.format(c.Style.BRIGHT, c.Fore.MAGENTA, staging_file)
                    )
                    self.log.info('[stage] Staging data file: {}'.format(staging_file))
                    f = open(staging_file, 'r')
                    staging_data.extend(json.load(f))
                    f.close()
                else:
                    print(
                        '{}{}Could not find file {}.'.format(
                            c.Style.BRIGHT, c.Fore.RED, staging_file
                        )
                    )
            self._staging_data = staging_data
        return self._staging_data

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


Question: Return the SEC representation of this key as hex text.

def sec_as_hex(self, is_compressed=None):

        sec = self.sec(is_compressed=is_compressed)
        return self._network.sec_text_for_blob(sec)

public function decrypt($data)
    {
        $c = base64_decode($data);
        $cipher = "AES-256-CBC";
        $ivlen = openssl_cipher_iv_length($cipher);
        $iv = substr($c, 0, $ivlen);
        $hmac = substr($c, $ivlen, $sha2len = 32);
        $ciphertext_raw = substr($c, $ivlen+$sha2len);
        $cleartext = openssl_decrypt($ciphertext_raw, $cipher, $this->saltedKey, $options = OPENSSL_RAW_DATA, $iv);
        $calcmac = hash_hmac('sha256', $ciphertext_raw, $this->saltedKey, $as_binary = true);

        if (hash_equals($hmac, $calcmac)) {
            return $cleartext;
        }

        return false;
    }

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


Question: // change float key value

func (db *RedisDB) stringIncrfloat(k string, delta float64) (float64, error) {
	v := 0.0
	if sv, ok := db.stringKeys[k]; ok {
		var err error
		v, err = strconv.ParseFloat(sv, 64)
		if err != nil {
			return 0, ErrFloatValueError
		}
	}
	v += delta
	db.stringSet(k, formatFloat(v))
	return v, nil
}

func (s *ApiKey) SetLastUpdatedDate(v time.Time) *ApiKey {
	s.LastUpdatedDate = &v
	return s
}

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


Question:
<p>
One or more notification IDs.
</p>

@return One or more notification IDs.

public java.util.List<String> getConnectionNotificationIds() {
        if (connectionNotificationIds == null) {
            connectionNotificationIds = new com.amazonaws.internal.SdkInternalList<String>();
        }
        return connectionNotificationIds;
    }

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

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

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

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

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

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

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


Question:
@inheritdoc

@param $path
@param $method
@param $queryParams
@param null $httpBody
@param array $headers

@return ResponseObject
@throws ApiConnectionException
@throws ApiException
@throws AuthorizeException

public function call($path, $method, $queryParams, $httpBody = null, $headers = array())
    {
        $this->logRequestParams($path, $method, $queryParams, $httpBody, $headers);

        $url = $this->prepareUrl($path, $queryParams);

        $headers = $this->prepareHeaders($headers);

        $this->prepareCurl($method, $httpBody, $headers, $url);

        list($httpHeaders, $httpBody, $responseInfo) = $this->sendRequest();

        if (!$this->keepAlive) {
            $this->closeCurlConnection();
        }

        $this->logResponse($httpBody, $responseInfo, $httpHeaders);

        return new ResponseObject(array(
            'code'    => $responseInfo['http_code'],
            'headers' => $httpHeaders,
            'body'    => $httpBody,
        ));
    }

protected void configureEndpointAccess(final HttpSecurity httpSecurity,
                                           final ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry requests,
                                           final ActuatorEndpointProperties.EndpointAccessLevel access,
                                           final ActuatorEndpointProperties properties,
                                           final EndpointRequest.EndpointRequestMatcher endpoint) throws Exception {
        switch (access) {
            case AUTHORITY:
                configureEndpointAccessByAuthority(requests, properties, endpoint);
                configureEndpointAccessByFormLogin(requests);
                break;
            case ROLE:
                configureEndpointAccessByRole(requests, properties, endpoint);
                configureEndpointAccessByFormLogin(requests);
                break;
            case AUTHENTICATED:
                configureEndpointAccessAuthenticated(requests, endpoint);
                configureEndpointAccessByFormLogin(requests);
                break;
            case IP_ADDRESS:
                configureEndpointAccessByIpAddress(requests, properties, endpoint);
                break;
            case PERMIT:
                configureEndpointAccessPermitAll(requests, endpoint);
                break;
            case ANONYMOUS:
                configureEndpointAccessAnonymously(requests, endpoint);
                break;
            case DENY:
            default:
                configureEndpointAccessToDenyAll(requests, endpoint);
                break;
        }
    }

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


Question: // Shutdown properly cancels pending services in queueLoop

func (s *BatchServiceStateManager) Shutdown() {
	s.lock.Lock()
	defer s.lock.Unlock()
	close(s.shutdown)
	for tenantID, _ := range s.TenantShutDowns {
		s.removeTenant(tenantID)
	}

	s.currentStateLock.Lock()
	defer s.currentStateLock.Unlock()
	for _, thread := range s.currentStateWaits {
		thread.Cancel()
	}

	// Clear the current state wait list
	s.currentStateWaits = make(map[string]*CurrentStateWait)
}

func (sn *SimNode) Stop() error {
	sn.lock.Lock()
	if sn.client != nil {
		sn.client.Close()
		sn.client = nil
	}
	sn.lock.Unlock()
	return sn.node.Stop()
}

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


Question:
Returns the entity object for the given entity identifier
        @type entity_id: string
        @param entity_id: the token identifier
        @rtype: L{Centity}
        @return: the entity object

def get_entity(self,entity_id):

        entity_node = self.map_entity_id_to_node.get(entity_id)
        if entity_node is not None:
            return Centity(node=entity_node,type=self.type)
        else:
            for entity_node in self.__get_entity_nodes():
                if self.type == 'NAF':
                    label_id = 'id'
                elif self.type == 'KAF':
                    label_id = 'eid'
                if entity_node.get(label_id) == entity_id:
                    return Centity(node=entity_node, type=self.type)
            return None

protected function checkSessionKeys(Token\Token $sessionAuth)
    {
        $userEntity = $sessionAuth->getUser();
        $tokenEntity = $sessionAuth->getToken();

        // The auth token is based on hostname, IP and browser user agent
        $key = $this->getAuthToken($userEntity->getId(), $tokenEntity->getSalt());

        if ($key === $tokenEntity->getToken()) {
            return true;
        }

        // Audit the failure
        $event = new AccessControlEvent($this->requestStack->getCurrentRequest());
        $event->setUserName($userEntity->getUsername());
        $this->dispatcher->dispatch(AccessControlEvents::ACCESS_CHECK_FAILURE, $event->setReason(AccessControlEvents::FAILURE_INVALID));

        $this->systemLogger->error("Invalidating session: Recalculated session token '$key' doesn't match user provided token '" . $tokenEntity->getToken() . "'", ['event' => 'authentication']);
        $this->systemLogger->info("Automatically logged out user '" . $userEntity->getUsername() . "': Session data didn't match.", ['event' => 'authentication']);

        return false;
    }

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


Question:
Asserts that an item, identified by it's unique id, is not found in the repository session.

@param session
the session to be searched
@param itemId
the item expected not to be found
@throws RepositoryException

public static void assertNodeNotExistById(final Session session, final String itemId) throws RepositoryException {
        try {
            session.getNodeByIdentifier(itemId);
            fail("ItemNotFoundException expected");
        } catch (final ItemNotFoundException e) { // NOSONAR
            // this was expected
        }
    }

public static MethodInstance getGetter(Class clazz, String prop) throws PageException, NoSuchMethodException {
	String getterName = "get" + StringUtil.ucFirst(prop);
	MethodInstance mi = getMethodInstanceEL(null, clazz, KeyImpl.getInstance(getterName), ArrayUtil.OBJECT_EMPTY);

	if (mi == null) {
	    String isName = "is" + StringUtil.ucFirst(prop);
	    mi = getMethodInstanceEL(null, clazz, KeyImpl.getInstance(isName), ArrayUtil.OBJECT_EMPTY);
	    if (mi != null) {
		Method m = mi.getMethod();
		Class rtn = m.getReturnType();
		if (rtn != Boolean.class && rtn != boolean.class) mi = null;
	    }
	}

	if (mi == null) throw new ExpressionException("No matching property [" + prop + "] found in [" + Caster.toTypeName(clazz) + "]");
	Method m = mi.getMethod();

	if (m.getReturnType() == void.class)
	    throw new NoSuchMethodException("invalid return Type, method [" + m.getName() + "] for Property [" + getterName + "] must have return type not void");

	return mi;
    }

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


Question: Exports current data contained in the Task as JSON

def export_data(self):

        # We need to remove spaces for TW-1504, use custom separators
        data_tuples = ((key, self._serialize(key, value))
                       for key, value in six.iteritems(self._data))

        # Empty string denotes empty serialized value, we do not want
        # to pass that to TaskWarrior.
        data_tuples = filter(lambda t: t[1] is not '', data_tuples)
        data = dict(data_tuples)
        return json.dumps(data, separators=(',', ':'))

public function answerExportAction()
    {
        if ($this->answerExportSnippets) {
            $params = $this->_processParameters($this->answerExportParameters + $this->defaultTokenParameters);

            $this->addSnippets($this->answerExportSnippets, $params);
        }
    }

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