Question: // newMetricVec returns an initialized metricVec.

func newMetricVec(desc *Desc, newMetric func(lvs ...string) Metric) *metricVec {
	return &metricVec{
		metricMap: &metricMap{
			metrics:   map[uint64][]metricWithLabelValues{},
			desc:      desc,
			newMetric: newMetric,
		},
		hashAdd:     hashAdd,
		hashAddByte: hashAddByte,
	}
}

public void init(Object workingMemoryContext,
                     Object context,
                     Tuple leftTuple,
                     Declaration[] declarations,
                     WorkingMemory workingMemory) throws Exception {
        ((CollectContext) context).result = this.collect.instantiateResultObject( (InternalWorkingMemory) workingMemory );
    }

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


Question:
<p> As well as supporting q depth threshold event notification,
this method checks that WLM advertisement is consistent with Q depth

@return true if destination is advertised on WLM

@Override
    public void notifyClients()
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "notifyClients");

        long totalItems = getTotalMsgCount();

        synchronized (this)
        {
            if (wlmRemoved && ((_destLowMsgs == -1) || (totalItems <= _destLowMsgs)))
            {
                wlmRemoved = false;

                // re-advertise destination PUT on WLM
                if (!destinationHandler.isTemporary())
                {
                    updatePutRegistration(true);
                    destinationHandler.requestReallocation();
                }
                // Fire event if event notification is enabled
                // Also check for logging of events (510343)
                if (_isEventNotificationEnabled ||
                    (mp.getCustomProperties().getOutputLinkThresholdEventsToLog() && destinationHandler.isLink()) ||
                    (mp.getCustomProperties().getOutputDestinationThresholdEventsToLog() && !destinationHandler.isLink()))
                {
                    fireDepthThresholdReachedEvent(getControlAdapter(),
                                                   false,
                                                   totalItems, _destLowMsgs); // Reached low
                }
            }
            else if (!wlmRemoved
                     && (_destHighMsgs != -1)
                     && (_destLowMsgs != -1)
                     && (totalItems >= _destHighMsgs))
            {
                wlmRemoved = true;

                // remove destination PUT advertisement on WLM
                if (!destinationHandler.isTemporary())
                {
                    updatePutRegistration(false);
                    wlmRemoved = true;
                }
                // Fire event if event notification is enabled
                // Also check for logging of events (510343)
                if (_isEventNotificationEnabled ||
                    (mp.getCustomProperties().getOutputLinkThresholdEventsToLog() && destinationHandler.isLink()) ||
                    (mp.getCustomProperties().getOutputDestinationThresholdEventsToLog() && !destinationHandler.isLink()))
                {
                    fireDepthThresholdReachedEvent(getControlAdapter(),
                                                   true,
                                                   totalItems, _destHighMsgs); // Reached High
                }
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "notifyClients", new Boolean(!wlmRemoved));

    }

def _build_tree_by_level(self, time_qualifier, collection_name, since):

        invalid_tree_records = dict()
        invalid_tq_records = dict()

        try:
            job_records = self.job_dao.get_all(collection_name, since)
            for job_record in job_records:
                tree = self.get_tree(job_record.process_name)
                if tree is None:
                    utils.increment_family_property(job_record.process_name, invalid_tree_records)
                    continue

                job_time_qualifier = context.process_context[job_record.process_name].time_qualifier
                if time_qualifier != job_time_qualifier:
                    utils.increment_family_property(job_record.process_name, invalid_tq_records)
                    continue

                tree.update_node(job_record)

        except LookupError:
            self.logger.warning('No job records in {0}.'.format(collection_name))

        for name, counter in invalid_tree_records.items():
            self.logger.warning('Skipping {0} job records for {1} since no tree is handling it.'
                                .format(counter, name))

        for name, counter in invalid_tq_records.items():
            self.logger.warning('Skipping {0} job records for {1} since the process has different time qualifier.'
                                .format(counter, name))

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


Question:
// GetConnection returns a client.Connection that will be managed by the client.
// Callers should call close() on thier connections when done. The client will also
// close connections if close is called on the client.

func (client *Client) GetConnection() (Connection, error) {
	request := newOpClientRequest(opClientRequestConnection, nil)
	client.opRequests <- request
	response := <-request.response
	switch response.(type) {
	case error:
		return nil, response.(error)
	case Connection:
		return response.(Connection), nil
	}
	panic("unreachable")
}

def _cleanup(self) -> None:
        """"""
        if self._cleanup_handle:
            self._cleanup_handle.cancel()

        now = self._loop.time()
        timeout = self._keepalive_timeout

        if self._conns:
            connections = {}
            deadline = now - timeout
            for key, conns in self._conns.items():
                alive = []
                for proto, use_time in conns:
                    if proto.is_connected():
                        if use_time - deadline < 0:
                            transport = proto.transport
                            proto.close()
                            if (key.is_ssl and
                                    not self._cleanup_closed_disabled):
                                self._cleanup_closed_transports.append(
                                    transport)
                        else:
                            alive.append((proto, use_time))

                if alive:
                    connections[key] = alive

            self._conns = connections

        if self._conns:
            self._cleanup_handle = helpers.weakref_handle(
                self, '_cleanup', timeout, self._loop)

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


Question:
Install modules assets with the given $modules.
$modules should within this format:

[module_name] => module_public_directory

@param array     $modules An array of modules
@param string    $expectedMethod Expected install method

public function install($modules, $expectedMethod = null)
    {
        $publicDir      = $this->getModuleAssetDir();
        $rows           = [];
        $exitCode       = 0;
        $copyUsed       = false;
        $expectedMethod = is_null($expectedMethod) ? self::METHOD_RELATIVE_SYMLINK:$expectedMethod;

        foreach ($modules as $name => $originDir) {
            $targetDir = $publicDir.DIRECTORY_SEPARATOR.$name;
            $message = $name;
            try {
                $this->filesystem->remove($targetDir);
                if (self::METHOD_RELATIVE_SYMLINK == $expectedMethod) {
                    $method = $this->relativeSymlinkWithFallback($originDir, $targetDir);
                } elseif (self::METHOD_ABSOLUTE_SYMLINK == $expectedMethod) {
                    $expectedMethod = self::METHOD_ABSOLUTE_SYMLINK;
                    $method = $this->absoluteSymlinkWithFallback($originDir, $targetDir);
                } else {
                    $expectedMethod = self::METHOD_COPY;
                    $method = $this->hardCopy($originDir, $targetDir);
                }

                if (self::METHOD_COPY === $method) {
                    $copyUsed = true;
                }

                if ($method === $expectedMethod) {
                    $rows[] = array(sprintf('<fg=green;options=bold>%s</>', '\\' === DIRECTORY_SEPARATOR ? 'OK' : "\xE2\x9C\x94" /* HEAVY CHECK MARK (U+2714) */), $message, $method);
                } else {
                    $rows[] = array(sprintf('<fg=yellow;options=bold>%s</>', '\\' === DIRECTORY_SEPARATOR ? 'WARNING' : '!'), $message, $method);
                }
            } catch (\Exception $e) {
                $exitCode = 1;
                $rows[] = array(sprintf('<fg=red;options=bold>%s</>', '\\' === DIRECTORY_SEPARATOR ? 'ERROR' : "\xE2\x9C\x98" /* HEAVY BALLOT X (U+2718) */), $message, $e->getMessage());
            }
        }

        // render this output only on cli environment
        if ($this->isCli()) {
            $this->renderInstallOutput($copyUsed, $rows, $exitCode);
        }
    }

protected function execute(InputInterface $input, OutputInterface $output)
    {
        $migrationsTemplate = base_path().'/storage/migrations';
        $migration = $input->getArgument('migration');

        $file = file($migrationsTemplate);
        $items = '';
        $goahead = false;
        foreach ($file as $fn) {
            $item = $fn;
            $nameexp = explode('_', $item);

            for ($i = 0; $i < 4; $i++) {
                array_shift($nameexp);
            }

            foreach ($nameexp as $key => $i) {
                $nameexp[$key] = ucwords($i);
            }

            $name = str_replace('_', '', str_replace('.php', '', implode('_', $nameexp)));

            $path = base_path().'/database/'.$item;

            if (file_exists(trim($path))) {
                if (empty($migration)) {
                    $goahead = true;
                } else {
                    if ($migration == trim($name)) {
                        $goahead = true;
                    }
                }

                if ($goahead) {
                    // update migrations table
                    if ($this->isMigrated($item, $output)) {
                        $output->writeln('Item: '.trim($name).' is already pushed to the database');
                    } else {
                        $output->writeln('Migrating '.trim($name).' migration');
                        require_once trim($path);
                        $class = '\\'.trim($name);
                        $c = new $class();
                        $c->up();
                        $this->changeMigrationTable($item);
                    }
                }
            }
        }
    }

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


Question: TODO decide whether this is used anymore

function(req, res) {
    var copy = _.extend({}, req.bin);
    copy.sourceOnly = req.sourceOnly;
    this.protectVisibility(
      req.session.user,
      copy,
      function(err, bin) {
        res.contentType('text/plain');
        var file = binToFile(bin, { proto: req.secure ? 'https' : 'http' });
        res.send(file);
      }.bind(this)
    );
  }

function(l) {
			if (l.type === gui.LIFE_ENTER) {
				if (!this.spirit.life.rendered) { // spirit did a manual run?
					this.run.apply(this, this._arguments || []);
				}
				this.spirit.life.remove(l.type, this);
				this._arguments = null;
			}
		}

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


Question:
Switches to window by name if possible
@param $name
@throws DriverException

public function switchToWindow($name = null) {
    $handles = $this->browser->windowHandles();
    if ($name === null) {
      //null means back to the main window
      return $this->browser->switchToWindow($handles[0]);
    }

    $windowHandle = $this->browser->windowHandle($name);
    if (!empty($windowHandle)) {
      $this->browser->switchToWindow($windowHandle);
    } else {
      throw new DriverException("Could not find window handle by a given window name: $name");
    }

  }

function namedParameterList()
    {
        return array( $this->AttributeName => array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 2 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ),
                      $this->DumpName =>      array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "show" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 1 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ) );
    }

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


Question:
removeuPortalUID

@param uPortalUID integer key to uPortal data for a user

@Override
    public void removePortalUID(final int uPortalUID) {

        this.transactionOperations.execute(
                new TransactionCallbackWithoutResult() {
                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus arg0) {
                        final String name =
                                jdbcOperations.queryForObject(
                                        "SELECT USER_NAME FROM UP_USER WHERE USER_ID=?",
                                        String.class,
                                        uPortalUID);
                        if (name == null) {
                            log.warn(
                                    "No user exists for id "
                                            + uPortalUID
                                            + " Nothing will be deleted");
                            return;
                        }

                        removePortalUID(name);
                    }
                });
    }

public function setWarehouseId( $warehouseid )
	{
		if ( $warehouseid === $this->getWarehouseId() ) { return; }

		if ( $warehouseid !== null ) {
			$warehouseid = (int) $warehouseid;
		}

		$this->_values['warehouseid'] = $warehouseid;
		$this->setModified();
	}

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


Question:
Sets revalidation counter value

@param string $variableName
@param int    $value

public static function setRevalidationCounter(string $variableName = '_MF_SESSION_REVALIDATION_COUNTER_',
                                                  int $value = 0): void
    {
        static::init();
        $variableName = (string)$variableName;
        $vHandler = Variables::getInstance();
        $vHandler->session->set($variableName, $value);
    }

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

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

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

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

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

		return $this->errorPayload;
	}

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


Question:
// string returns the string corresponding to the most recently
// scanned token. Valid after calling scan().

func (s *scanner) string() string {
	return s.buf[s.start:s.pos]
}

protected function commentOut($search, $from)
    {
        $bounds = $this->getConfigItemBounds($from);
        $file = $this->getFileContents();
        $cutted = substr($file, 0, $bounds[1]);

        preg_match_all(
            '/[\'"]' . preg_quote($search) . '[\'"]/',
            $cutted,
            $matchFacade,
            PREG_OFFSET_CAPTURE | PREG_SET_ORDER
        );
        foreach ($matchFacade as $match) {
            if (!$this->isCharInComment($cutted, $match[0][1])) {
                $commentFrom = $match[0][1];
                $comma = strpos($cutted, ',', $commentFrom);
                while ($this->isCharInComment($cutted, $comma)) {
                    $comma = strpos($cutted, ',', $comma);
                }
                $commentTill = $comma + 1;
                $this->write('*/', ['position' => $commentTill, 'symbol' => '']);
                $this->write('/*', ['position' => $commentFrom, 'symbol' => '']);
            }
        }
    }

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


Question:
Implements the CmsEvent interface,
the FlexCache uses the events to clear itself in case a project is published.<p>

@param event CmsEvent that has occurred

public void cmsEvent(org.opencms.main.CmsEvent event) {

        if (!isEnabled()) {
            return;
        }

        switch (event.getType()) {
            case I_CmsEventListener.EVENT_PUBLISH_PROJECT:
                if (LOG.isDebugEnabled()) {
                    LOG.debug("FlexCache: Received event PUBLISH_PROJECT");
                }
                String publishIdStr = (String)(event.getData().get(I_CmsEventListener.KEY_PUBLISHID));
                if (!CmsUUID.isValidUUID(publishIdStr)) {
                    clear();
                } else {
                    try {
                        CmsUUID publishId = new CmsUUID(publishIdStr);
                        List<CmsPublishedResource> publishedResources = m_cmsObject.readPublishedResources(publishId);
                        boolean updateConfiguration = false;
                        for (CmsPublishedResource res : publishedResources) {
                            if (res.getRootPath().equals(CONFIG_PATH)) {
                                updateConfiguration = true;
                                break;
                            }
                        }
                        CmsFlexBucketConfiguration bucketConfig = m_bucketConfiguration;
                        if (updateConfiguration) {
                            LOG.info("Flex bucket configuration was updated, re-initializing configuration...");
                            try {
                                m_bucketConfiguration = CmsFlexBucketConfiguration.loadFromVfsFile(
                                    m_cmsObject,
                                    CONFIG_PATH);
                            } catch (CmsException e) {
                                LOG.error(e.getLocalizedMessage(), e);
                            }
                            // Make sure no entries built for the old configuration remain in the cache
                            clear();
                        } else if (bucketConfig != null) {
                            boolean bucketClearOk = clearBucketsForPublishList(
                                bucketConfig,
                                publishId,
                                publishedResources);
                            if (!bucketClearOk) {
                                clear();
                            }
                        } else {
                            clear();
                        }

                    } catch (CmsException e1) {
                        LOG.error(e1.getLocalizedMessage(), e1);
                        clear();
                    }
                }
                break;
            case I_CmsEventListener.EVENT_CLEAR_CACHES:
                if (LOG.isDebugEnabled()) {
                    LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHE_RECEIVED_EVENT_CLEAR_CACHE_0));
                }
                clear();
                break;
            case I_CmsEventListener.EVENT_FLEX_PURGE_JSP_REPOSITORY:
                if (LOG.isDebugEnabled()) {
                    LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHE_RECEIVED_EVENT_PURGE_REPOSITORY_0));
                }
                purgeJspRepository();
                break;
            case I_CmsEventListener.EVENT_FLEX_CACHE_CLEAR:
                if (LOG.isDebugEnabled()) {
                    LOG.debug(
                        Messages.get().getBundle().key(Messages.LOG_FLEXCACHE_RECEIVED_EVENT_CLEAR_CACHE_PARTIALLY_0));
                }
                Map<String, ?> m = event.getData();
                if (m == null) {
                    break;
                }
                Integer it = null;
                try {
                    it = (Integer)m.get(CACHE_ACTION);
                } catch (Exception e) {
                    // it will be null
                }
                if (it == null) {
                    break;
                }
                int i = it.intValue();
                switch (i) {
                    case CLEAR_ALL:
                        clear();
                        break;
                    case CLEAR_ENTRIES:
                        clearEntries();
                        break;
                    case CLEAR_ONLINE_ALL:
                        clearOnline();
                        break;
                    case CLEAR_ONLINE_ENTRIES:
                        clearOnlineEntries();
                        break;
                    case CLEAR_OFFLINE_ALL:
                        clearOffline();
                        break;
                    case CLEAR_OFFLINE_ENTRIES:
                        clearOfflineEntries();
                        break;
                    default:
                        // no operation
                }
                break;
            default:
                // no operation
        }
    }

protected function build($template)
    {
        $this->body['flash'] = array();
        if(isset($_SESSION['flash']['message'])) {
            $this->body['flash']['message'] = $_SESSION['flash']['message'];
            $this->body['flash']['type'] = $_SESSION['flash']['type'];
            unset($_SESSION['flash']);
        }

        $body = $this->parse($template, $this->body);

        $page = array(
            'flash' => $this->body['flash'],
            'meta' => $this->meta,
            'links' => $this->links,
            'styles' => $this->styles,
            'scripts' => $this->scripts,
            'title' => $this->title,
            'class' => $this->id,
            'head' => $this->head,
            'body' => $body,
            'foot' => $this->foot);

        $page = $this->parse($this->layout, $page);

        $this->response
            ->set('headers', 'Content-Type', 'text/html; charset=utf-8')
            ->set('body', $page);

        return $page;
    }

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


Question:
Check if a thumbnail has caused an error
@param string $thumbnailPath
@return bool

protected function thumbnailIsError($thumbnailPath)
    {
        $fullPath = temp_path(ltrim($thumbnailPath, '/'));

        return hash_file('crc32', $fullPath) == $this->getBrokenImageHash();
    }

public function getData(array $image_extensions = ['gif'], array $skip = ['unknown.gif', 'recycle.bin.empty.gif', 'recycle.bin.full.gif']): array
    {
        // Cached
        if (isset(self::$data[$this->directory_with_icons])) {
            $data = self::$data[$this->directory_with_icons];
        } else {
            // Scan folder
            $data = [];
            $image_extensions = array_flip($image_extensions);

            foreach (array_diff(scandir(DIR_BASE . $this->directory_with_icons, SCANDIR_SORT_NONE),['.', '..']) as $file) {
                $extension = explode('.', $file);

                if (!isset($image_extensions[array_pop($extension)])) {
                    continue;
                }

                foreach ($extension as $v) {
                    $data[$v] = $file;
                }
            }

            // Save in cache
            self::$data[$this->directory_with_icons] = $data;
        }

        return $skip ? array_diff($data, $skip) : $data;
    }

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


Question: Method returns the java installation path in the windows or Linux environment.

def GetJavaInstallationPath():

		import os, platform

		# Get JavaPath for Ubuntu
		# if os.name == "posix":
		if platform.system() == "Linux":
			path = os.environ.get('JAVA_HOME')
			if not path:
				raise UcsValidationException(
					"Please make sure JAVA is installed and variable JAVA_HOME is set properly.")
			# raise Exception("Please make sure JAVA is installed and variable JAVA_HOME is set properly.")
			else:
				path = os.path.join(path, 'bin')
				path = os.path.join(path, 'javaws')
				if not os.path.exists(path):
					raise UcsValidationException("javaws is not installed on System.")
				# raise Exception("javaws is not installed on System.")
				else:
					return path

		# Get JavaPath for Windows
		# elif os.name == "nt":
		elif platform.system() == "Windows" or platform.system() == "Microsoft":

			path = os.environ.get('JAVA_HOME')

			if path == None:
				path = UcsUtils.CheckRegistryKey(r"SOFTWARE\\JavaSoft\\Java Runtime Environment\\")

			if path == None:  # Check for 32 bit Java on 64 bit machine.
				path = UcsUtils.CheckRegistryKey(r"SOFTWARE\\Wow6432Node\\JavaSoft\\Java Runtime Environment")

			if not path:
				raise UcsValidationException("Please make sure JAVA is installed.")
			# raise Exception("Please make sure JAVA is installed.")
			else:
				path = os.path.join(path, 'bin')
				path = os.path.join(path, 'javaws.exe')
				if not os.path.exists(path):
					raise UcsValidationException("javaws.exe is not installed on System.")
				# raise Exception("javaws.exe is not installed on System.")
				else:
					return path

public static void sleep (int millis)
    {
        if (RunAnywhere.isLinux() && isLoaded()) {
            nativeSleep(millis);
        } else {
            try {
                Thread.sleep(millis);
            } catch (InterruptedException ie) {
                log.info("Thread.sleep(" + millis + ") interrupted.");
            }
        }
    }

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


Question:
Initializes the repository's prepared statements.

@return void

public function init()
    {

        // initialize the prepared statements
        $this->customerVarcharsStmt =
            $this->getConnection()->prepare($this->loadStatement(SqlStatementKeys::CUSTOMER_ADDRESS_VARCHARS));
        $this->customerVarcharByAttributeCodeAndEntityTypeIdAndAndValueStmt =
            $this->getConnection()->prepare($this->loadStatement(SqlStatementKeys::CUSTOMER_ADDRESS_VARCHAR_BY_ATTRIBUTE_CODE_AND_ENTITY_TYPE_ID_AND_VALUE));
    }

public function buildResultSet(Response $response, Query $query): ResultSet
    {
        $resultSet = $this->builder->buildResultSet($response, $query);

        $this->processor->process($resultSet);

        return $resultSet;
    }

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


Question:
Acquires a new access token from the compute engine metadata server.
@throws Exception

public function acquireAccessToken()
  {
    $request = new Request(
        self::METADATA_AUTH_URL,
        'GET',
        array(
          'Metadata-Flavor' => 'Google'
        )
    );
    $request->disableGzip();
    $response = $this->client->getIo()->makeRequest($request);

    if ($response->getResponseHttpCode() == 200) {
      $this->setAccessToken($response->getResponseBody());
      $this->token['created'] = time();
      return $this->getAccessToken();
    } else {
      throw new Exception(
          sprintf(
              "Error fetching service account access token, message: '%s'",
              $response->getResponseBody()
          ),
          $response->getResponseHttpCode()
      );
    }
  }

func (c *CassandraBackend) Get(ctx context.Context, key string) (*physical.Entry, error) {
	defer metrics.MeasureSince([]string{"cassandra", "get"}, time.Now())

	v := []byte(nil)
	stmt := fmt.Sprintf(`SELECT value FROM "%s" WHERE bucket = ? AND key = ? LIMIT 1`, c.table)
	q := c.sess.Query(stmt, c.bucket(key), key)
	if err := q.Scan(&v); err != nil {
		if err == gocql.ErrNotFound {
			return nil, nil
		}
		return nil, err
	}

	return &physical.Entry{
		Key:   key,
		Value: v,
	}, nil
}

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


Question:
Select values from list.

@param value value to select
@return list of entries selected

@SuppressWarnings("serial")
	public List<?> find(Value value) throws AerospikeException {
		Key subKey = makeSubKey(value);
		Record record = client.get(this.policy, subKey, ListElementBinName);
		if (record != null) {
			final Object result = record.getValue(ListElementBinName);
			return new ArrayList<Object>() {{
				add(result);
			}};
		} else {
			return null;
		}
	}

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

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


Question: Returns the payee channel of a given transfer pair or None if it's not found

def get_payee_channel(
        channelidentifiers_to_channels: ChannelMap,
        transfer_pair: MediationPairState,
) -> Optional[NettingChannelState]:

    payee_channel_identifier = transfer_pair.payee_transfer.balance_proof.channel_identifier
    return channelidentifiers_to_channels.get(payee_channel_identifier)

func (h *portForwardProxy) monitorStreamPair(p *httpStreamPair, timeout <-chan time.Time) {
	select {
	case <-timeout:
		err := fmt.Errorf("(conn=%v, request=%s) timed out waiting for streams", h.sourceConn, p.requestID)
		p.printError(err.Error())
	case <-p.complete:
		log.Infof("(conn=%v, request=%s) successfully received error and data streams", h.sourceConn, p.requestID)
	}
	h.removeStreamPair(p.requestID)
}

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


Question: Moves the circle to the point x,y

def moveToPoint(self, xxx_todo_changeme1):

        (x,y) = xxx_todo_changeme1
        self.set_cx(float(self.get_cx()) + float(x))
        self.set_cy(float(self.get_cy()) + float(y))

public void setupCellPositoin(final CellPosition address) {
        ArgUtils.notNull(address, "address");
        setupCellPositoin(address.getRow(), address.getColumn());
    }

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


Question: Eval the JavaScript string

def eval(self, js_str, timeout=0, max_memory=0):

        if is_unicode(js_str):
            bytes_val = js_str.encode("utf8")
        else:
            bytes_val = js_str

        res = None
        self.lock.acquire()
        try:
            res = self.ext.mr_eval_context(self.ctx,
                                           bytes_val,
                                           len(bytes_val),
                                           ctypes.c_ulong(timeout),
                                           ctypes.c_size_t(max_memory))

            if bool(res) is False:
                raise JSConversionException()
            python_value = res.contents.to_python()
            return python_value
        finally:
            self.lock.release()
            if res is not None:
                self.free(res)

function(val) {
      return val === undefined ? (this.length ? this[0].textContent : null) : this.each(function(index, el) {
        el.textContent = val;
      });
    }

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


Question: // newStringEqualsFunc - returns new StringEquals function.

func newStringEqualsFunc(key Key, values ValueSet) (Function, error) {
	valueStrings, err := valuesToStringSlice(stringEquals, values)
	if err != nil {
		return nil, err
	}

	return NewStringEqualsFunc(key, valueStrings...)
}

func (h *Hostname) EqualIP(ip net.IP) bool {
	return h.IP.Equal(ip)
}

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


Question:
Exports a spreadsheet in HTML format

@param drive drive client
@param fileId file id for file to be exported
@return Spreadsheet in HTML format
@throws IOException thrown when exporting fails unexpectedly

public static DownloadResponse exportSpreadsheet(Drive drive, String fileId) throws IOException {
	  try (InputStream inputStream = drive.files().export(fileId, "text/csv").executeAsInputStream()) {
	    CSVRenderer csvRenderer = new CSVRenderer(inputStream, "google-spreadsheet", true);
	    return new DownloadResponse(TEXT_HTML, csvRenderer.renderHtmlTable().getBytes("UTF-8"));
    }
	}

function (response) {
        var contentType = response.headers.get(HEADERS.CONTENT_TYPE),
            contentDisposition = response.headers.get(HEADERS.CONTENT_DISPOSITION),
            mimeInfo = getMimeInfo(contentType, response.stream || response.body),
            fileName = getFileNameFromDispositionHeader(contentDisposition),
            fileExtension = mimeInfo.extension,

            /**
             * @typedef Response~ResponseContentInfo
             *
             * @property {String} mimeType sanitized mime type
             * @property {String} mimeFormat format for the identified mime type
             * @property {String} charset the normalized character set
             * @property {String} fileExtension extension identified from the mime type
             * @property {String} fileName file name extracted from disposition header
             */
            contentInfo = {};

        // if file name is not present in the content disposition headers, use a default file name
        if (!fileName) {
            fileName = DEFAULT_RESPONSE_FILENAME;
            // add extension to default if present
            fileExtension && (fileName += (DOT + fileExtension));
        }

        // create a compacted list of content info from mime info and file name
        mimeInfo.mimeType && (contentInfo.mimeType = mimeInfo.mimeType);
        mimeInfo.mimeFormat && (contentInfo.mimeFormat = mimeInfo.mimeFormat);
        mimeInfo.charset && (contentInfo.charset = mimeInfo.charset);
        fileExtension && (contentInfo.fileExtension = fileExtension);
        fileName && (contentInfo.fileName = fileName);

        return contentInfo;
    }

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


Question:
Run Action

Creates new job, saves it to Elasticsearch and add to SQS

@param Request $request
@return Response

public function runAction(Request $request)
    {
        // Get params from request
        $params = $this->getPostJson($request);

        // check params against ES mapping
        $this->checkMappingParams($params);

        // Create new job
        $job = $this->createJob('run', $params);

        // Add job to Elasticsearch
        try {
            /** @var JobMapper $jobMapper */
            $jobMapper = $this->container->get('syrup.elasticsearch.current_component_job_mapper');
            $jobId = $jobMapper->create($job);
        } catch (\Exception $e) {
            throw new ApplicationException("Failed to create job", $e);
        }

        // Add job to SQS
        $queueName = 'default';
        $queueParams = $this->container->getParameter('queue');

        if (isset($queueParams['sqs'])) {
            $queueName = $queueParams['sqs'];
        }
        $messageId = $this->enqueue($jobId, $queueName);

        $this->logger->info('Job created', [
            'sqsQueue' => $queueName,
            'sqsMessageId' => $messageId,
            'job' => $job->getLogData()
        ]);

        $jobResource = $job->getLogData();
        $jobResource['url'] = $this->getJobUrl($jobId);

        // Response with link to job resource
        return $this->createJsonResponse($jobResource, 202);
    }

public void project_serviceName_alerting_id_PUT(String serviceName, String id, OvhAlerting body) throws IOException {
		String qPath = "/cloud/project/{serviceName}/alerting/{id}";
		StringBuilder sb = path(qPath, serviceName, id);
		exec(qPath, "PUT", sb.toString(), body);
	}

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


Question:
This method uses the index built in the method above to do some quick
score calculations for each word of the query, versus each word of the
index dictionary.

@param object $result

@return float

protected function getResultScore($result)
    {
        $output = [];

        $corpus = $this->buildResultIndex($result);
        $count = count($corpus['count']);

        // This block iterates the search query words and checks both their
        // existence and frequency in the index.
        //
        // The score is passed through log(x, 2) to reduce the smooth the difference.
        //
        foreach ($this->searchWords as $word) {
            $word = mb_strtolower($word);
            if (isset($corpus['dictionary'][$word])) {
                $entry = $corpus['dictionary'][$word];

                foreach ($entry['postings'] as $field => $posting) {
                    //get term frequency–inverse document frequency
                    $score = $posting['frequency'] * log($count + 1 / $entry['frequency'] + 1, 2);

                    if (isset($output[$field])) {
                        $output[$field] += $score;
                    } else {
                        $output[$field] = $score;
                    }
                }
            }
        }

        // length normalise, we do this to stop smaller amounts of text having
        // a disproportionate effect on the score.
        foreach ($output as $field => $score) {
            $output[$field] = $score / $corpus['count'][$field];
        }

        // Finally this weights by using the field specific weighting value that
        // is set inside `contenttypes.yml` This uses a weighting factor from 0 to
        // 100 that alters the score accordingly.
        $weights = $this->getContentFields();
        foreach ($output as $field => &$score) {
            if (isset($weights[$field]['weight'])) {
                $multiplier = $weights[$field]['weight'] / 100;

                if ($multiplier > 0) {
                    $score *= $multiplier;
                }
            }
        }

        return array_sum($output);
    }

public function parseResults(LoopResult $loopResult)
    {
        foreach ($loopResult->getResultDataCollection() as $filter) {
            $loopResultRow = new LoopResultRow($filter);

            $loopResultRow->set("ID", $filter->getId())
                ->set("IS_TRANSLATED", $filter->getVirtualColumn('IS_TRANSLATED'))
                ->set("LOCALE", $filter->locale)
                ->set("TITLE", $filter->getVirtualColumn('i18n_TITLE'))
                ->set("CODE", $filter->getCode())
                ->set("DESCRIPTION", $filter->getVirtualColumn('i18n_DESCRIPTION'))
                ->set("ACTIVATE", $filter->getActive())
                ->set("TYPE", $filter->getFiltertype());

            $loopResult->addRow($loopResultRow);
        }

        return $loopResult;
    }

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


Question: Sets the background color to use

public function setBackgroundColor($r, $g, $b)
    {
        $this->backgroundColor = array($r, $g, $b);

        return $this;
    }

def _change_to_noFill_bg(self):

        self._remove_bg()
        bg = self.get_or_add_bg()
        bg.add_noFill_bgPr()
        return bg

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


Question:
set the template file.

@param string $templateName template name
@param array  $data         data for template parser

@return View

public function setTemplate($templateName, $data = [])
    {
        if (!empty($templateName)) {
            $this->_templateName = $templateName.$this->_suffix;
        }

        if (!empty($data)) {
            if (is_array($data)) {
                $this->_data = array_merge($this->_data, $data);
            } else {
                $this->_data['__data__'] = $data;
            }
        }

        return $this;
    }

public function setupRules()
    {
        $this->rules->addMany([
            'comment'     => new Rule(new CommentMatcher([], [['{#', '#}']]), ['priority' => 0]),
            'delimiter'   => new Rule(new RegexMatcher('/((\{[{%]|[%}]\}))/')),
            'variable'    => new Rule(new RegexMatcher('/\{\{\s*([a-z]\w*)/')),
            'call'        => new Rule(new RegexMatcher('/\{\{.*?\|([a-z]\w*)/')),
            'call.template-tag' => new Rule(new RegexMatcher('/{%\s*([a-z]\w*)/')),
            'string' => CommonFeatures::strings(['single' => '\'', 'double' => '"'], [
                'context' => ['!string', '!comment']
            ]),
        ]);
    }

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


Question:
Creates a list of parsers by reading the configuration and trying to find
an HolidayParser implementation for by XML class type.

@param aConfig
@return A list of parsers to for this configuration.

@Nonnull
  @ReturnsMutableCopy
  private static ICommonsList <IHolidayParser> _getParsers (@Nonnull final Holidays aConfig)
  {
    final ICommonsList <IHolidayParser> ret = new CommonsArrayList <> ();
    if (!aConfig.getChristianHoliday ().isEmpty ())
      ret.add (ChristianHolidayParser.getInstance ());
    if (!aConfig.getEthiopianOrthodoxHoliday ().isEmpty ())
      ret.add (EthiopianOrthodoxHolidayParser.getInstance ());
    if (!aConfig.getFixed ().isEmpty ())
      ret.add (FixedParser.getInstance ());
    if (!aConfig.getFixedWeekdayBetweenFixed ().isEmpty ())
      ret.add (FixedWeekdayBetweenFixedParser.getInstance ());
    if (!aConfig.getFixedWeekday ().isEmpty ())
      ret.add (FixedWeekdayInMonthParser.getInstance ());
    if (!aConfig.getFixedWeekdayRelativeToFixed ().isEmpty ())
      ret.add (FixedWeekdayRelativeToFixedParser.getInstance ());
    if (!aConfig.getHinduHoliday ().isEmpty ())
      ret.add (HinduHolidayParser.getInstance ());
    if (!aConfig.getIslamicHoliday ().isEmpty ())
      ret.add (IslamicHolidayParser.getInstance ());
    if (!aConfig.getRelativeToFixed ().isEmpty ())
      ret.add (RelativeToFixedParser.getInstance ());
    if (!aConfig.getRelativeToWeekdayInMonth ().isEmpty ())
      ret.add (RelativeToWeekdayInMonthParser.getInstance ());
    return ret;
  }

protected function _loadFeaturesAdapter()
    {
        $config      = $this->_config;
        $browserType = $this->getType();
        if (!isset($config[$browserType]) || !isset($config[$browserType]['features'])) {
            return array();
        }
        $config = $config[$browserType]['features'];

        if (empty($config['classname'])) {

            throw new Zend_Http_UserAgent_Exception('The ' . $this->getType() . ' features adapter must have a "classname" config parameter defined');
        }

        $className = $config['classname'];
        if (!class_exists($className)) {
            if (isset($config['path'])) {
                $path = $config['path'];
            } else {

                throw new Zend_Http_UserAgent_Exception('The ' . $this->getType() . ' features adapter must have a "path" config parameter defined');
            }

            if (false === include_once ($path)) {

                throw new Zend_Http_UserAgent_Exception('The ' . $this->getType() . ' features adapter path that does not exist');
            }
        }

        return call_user_func(array($className, 'getFromRequest'), $this->_server, $this->_config);
    }

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


Question: // NotFound sets the handler to be called when no matching route is found.

func (r *Router) NotFound(mc MiddlewareChain, h Handler) {
	handle := r.adapt(mc, h, "")
	r.hrouter.NotFound = http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		handle(rw, req, nil)
	})
}

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

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

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


Question:
Set focusLeft.

@param float $focusLeft

@return Media

public function setFocusLeft($focusLeft)
    {
        if ($focusLeft !== $this->focusLeft) {
            $this->focusIsEdited = true;
            $this->focusLeft = $focusLeft;
        }

        return $this;
    }

function (oThis) {
                var sParam = "sapUiUx3ToolPopupArrowWidth";
                oThis.sArrowWidth = Parameters.get(sParam);
                oThis.iArrowWidth = parseInt(oThis.sArrowWidth);

                sParam = "sapUiUx3ToolPopupArrowHeight";
                oThis.sArrowHeight = Parameters.get(sParam);
                oThis.iArrowHeight = parseInt(oThis.sArrowHeight);

                sParam = "sapUiUx3ToolPopupArrowRightMarginCorrection";
                oThis.sArrowPadding = Parameters.get(sParam);
                oThis.iArrowPadding = parseInt(oThis.sArrowPadding);

                sParam = "sapUiUx3ToolPopupArrowRightMarginCorrectionInverted";
                oThis.sArrowPaddingInverted = Parameters.get(sParam);
                oThis.iArrowPaddingInverted = parseInt(oThis.sArrowPaddingInverted);
            }

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


Question:
Formats a log message which contains placeholders (i.e. when a template context exists). This
does not format only metadata, only the message and its arguments.

private static StringBuilder formatMessage(LogData logData) {
    SimpleMessageFormatter formatter =
        new SimpleMessageFormatter(logData.getTemplateContext(), logData.getArguments());
    StringBuilder out = formatter.build();
    if (logData.getArguments().length > formatter.getExpectedArgumentCount()) {
      // TODO(dbeaumont): Do better and look at adding formatted values or maybe just a count?
      out.append(EXTRA_ARGUMENT_MESSAGE);
    }
    return out;
  }

function(container_config, x) {

		var i,
			count,
			name;

		if ('event' in x) {

			if (typeof(x.event) != 'object') Lava.t("Malformed x:event attribute");

			container_config.events = {};

			for (name in x.event) {

				container_config.events[name] = Lava.parsers.Common.parseTargets(x.event[name]);

			}

		}

		// Attribute binding. Example: x:bind:src="<any_valid_expression>"
		if ('bind' in x) {

			if (typeof(x.bind) != 'object') Lava.t("Malformed x:bind attribute");

			container_config.property_bindings = this._parseBindingsHash(x.bind);

		}

		if ('style' in x) {

			if (typeof(x.style) != 'object') Lava.t("Malformed x:style attribute");

			container_config.style_bindings = this._parseBindingsHash(x.style);

		}

		if ('classes' in x) {

			var arguments = Lava.ExpressionParser.parse(x.classes, Lava.ExpressionParser.SEPARATORS.SEMICOLON),
				class_bindings = {};

			for (i = 0, count = arguments.length; i < count; i++) {

				class_bindings[i] = arguments[i];

			}

			container_config.class_bindings = class_bindings;

		}

		if ('container_class' in x) {

			container_config['class'] = x.container_class;

		}

	}

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


Question: // GetExtra indicates an expected call of GetExtra

func (mr *MockAccessResponderMockRecorder) GetExtra(arg0 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetExtra", reflect.TypeOf((*MockAccessResponder)(nil).GetExtra), arg0)
}

def method_rules
      [
        Rule.new(:error, 40..41, "Description", "You should include a description for your method.", proc do |json|
          json[:body_md] && json[:body_md].empty?
        end),
        Rule.new(:warning, 43..45, "Params", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
          json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?(nil)
        end),
        Rule.new(:warning, 43..45, "Unknown Param", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
          json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?("Unknown")
        end),
        Rule.new(:warning, 46, "Return Type", "If the function has no useful return value, use ` @return  [void]` - this will be ignored by documentation generators.", proc do |json|
          return_hash = json[:tags].find { |tag| tag[:name] == "return" }
          !(return_hash && return_hash[:types] && !return_hash[:types].first.empty?)
        end)
      ]
    end

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


Question:
// Add ads a new entry to the directory. If there's already an
// entry ith the same name, an error is returned.

func (d *Dir) Add(name string, entry Entry) error {
	// TODO: Binary search
	for ii, v := range d.EntryNames {
		if v > name {
			names := make([]string, len(d.EntryNames)+1)
			copy(names, d.EntryNames[:ii])
			names[ii] = name
			copy(names[ii+1:], d.EntryNames[ii:])
			d.EntryNames = names

			entries := make([]Entry, len(d.Entries)+1)
			copy(entries, d.Entries[:ii])
			entries[ii] = entry
			copy(entries[ii+1:], d.Entries[ii:])

			d.Entries = entries
			return nil
		}
		if v == name {
			return os.ErrExist
		}
	}
	// Not added yet, put at the end
	d.EntryNames = append(d.EntryNames, name)
	d.Entries = append(d.Entries, entry)
	return nil
}

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: // SetApiKeyRequired sets the ApiKeyRequired field's value.

func (s *GetRouteOutput) SetApiKeyRequired(v bool) *GetRouteOutput {
	s.ApiKeyRequired = &v
	return s
}

def get_required_signatures(self):

        headers, data = self._requester.requestJsonAndCheck(
            "GET",
            self.protection_url + "/required_signatures",
            headers={'Accept': Consts.signaturesProtectedBranchesPreview}
        )
        return data["enabled"]

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


Question:
Returns true if the collector is successfully created and started;
false otherwise.

private static boolean createAndStartCollector(CloudWatchMetricConfig config) {
        MetricCollectorSupport collector = new MetricCollectorSupport(config);
        if (collector.start()) {
            singleton = collector;
            return true;
        }
        return false;
    }

public static void if_keepAliveRequest_then_resumeReading_else_closeOnComplete(
            final HttpRequest request, final Channel channel, final ChannelFuture channelFuture
    ) {
        // TODO:
        // Add Connection: Close, or Keep-Alive?
        // res.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        if (HttpUtil.isKeepAlive(request)) {
            channelFuture.addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture future) {
                    resumeReading(channel);
                }
            });
        } else {
            channelFuture.addListener(ChannelFutureListener.CLOSE);
        }
    }

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


Question:
Finds the root thrift files in the graph formed by sources and their recursive includes.

  :basedirs: A set of thrift source file base directories to look for includes in.
  :sources: Seed thrift files to examine.
  :log: An optional logger.

def find_root_thrifts(basedirs, sources, log=None):

  root_sources = set(sources)
  for source in sources:
    root_sources.difference_update(find_includes(basedirs, source, log=log))
  return root_sources

def build_tmp_dir
      base_directory = tmp_path/"etc"/"chef"
      roles_dir = "#{base_directory}/roles"
      FileUtils.rm_rf base_directory # cleanup old chef temp directory
      puts "Copying the chef-repo into the base directory from #{repo}"

      FileUtils.mkdir_p base_directory
      FileUtils.mkdir_p roles_dir # Why do we need this??!?
      if File.directory?(repo)
        if File.exist?(base_directory)
          # First remove the directory
          FileUtils.remove_entry base_directory, :force => true
        end
        cookbook_path = "#{base_directory}/cookbooks"
        FileUtils.mkdir_p cookbook_path
        FileUtils.cp_r "#{repo}/.", cookbook_path
      else
        raise "#{repo} chef repo directory does not exist"
      end
      puts "Creating the dna.json"
      attributes.to_dna [], base_directory/"dna.json", {:run_list => ["role[#{cloud.name}]"]}
      write_solo_dot_rb
      # Make sure the roles directory exists
      FileUtils.mkdir_p roles_dir
      write_chef_role_json "#{roles_dir}/#{cloud.name}.json"
    end

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


Question:
Events are sent here from the CoherentManagerEventQueue after being
converted from a ManagerEvent to an ManagerEvent. This method is called
from a dedicated thread attached to the event queue which it uses for
dispatching events.

public void dispatchEvent(final ManagerEvent event)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("dispatch=" + event.toString()); //$NON-NLS-1$
        }

        // take a copy of the listeners so they can be modified whilst we
        // iterate over them
        // The iteration may call some long running processes.
        final List<FilteredManagerListenerWrapper> listenerCopy;
        synchronized (this.listeners)
        {
            listenerCopy = this.listeners.getCopyAsList();
        }

        try
        {
            final LogTime totalTime = new LogTime();

            CountDownLatch latch = new CountDownLatch(listenerCopy.size());

            for (final FilteredManagerListenerWrapper filter : listenerCopy)
            {
                if (filter.requiredEvents.contains(event.getClass()))
                {
                    dispatchEventOnThread(event, filter, latch);
                }
                else
                {
                    // this listener didn't want the event, so just decrease the
                    // countdown
                    latch.countDown();
                }
            }

            latch.await();

            if (totalTime.timeTaken() > 500)
            {
                logger.warn("Too long to process event " + event + " time taken: " + totalTime.timeTaken()); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }
        catch (InterruptedException e)
        {
            Thread.interrupted();
        }
    }

func (qm *QuotaMonitor) Run(stopCh <-chan struct{}) {
	klog.Infof("QuotaMonitor running")
	defer klog.Infof("QuotaMonitor stopping")

	// Set up the stop channel.
	qm.monitorLock.Lock()
	qm.stopCh = stopCh
	qm.running = true
	qm.monitorLock.Unlock()

	// Start monitors and begin change processing until the stop channel is
	// closed.
	qm.StartMonitors()
	wait.Until(qm.runProcessResourceChanges, 1*time.Second, stopCh)

	// Stop any running monitors.
	qm.monitorLock.Lock()
	defer qm.monitorLock.Unlock()
	monitors := qm.monitors
	stopped := 0
	for _, monitor := range monitors {
		if monitor.stopCh != nil {
			stopped++
			close(monitor.stopCh)
		}
	}
	klog.Infof("QuotaMonitor stopped %d of %d monitors", stopped, len(monitors))
}

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


Question:
Get the content of the json assets file.

@return array

private function readFile()
    {
        $content = @file_get_contents($this->filename);

        if (false === $content) {
            throw new InvalidArgumentException(sprintf('Cannot access "%s" to read the JSON file', $this->filename));
        }

        $content = json_decode($content, true);

        if (JSON_ERROR_NONE !== json_last_error()) {
            throw new InvalidArgumentException(sprintf('Cannot read the JSON content: %s', json_last_error_msg()));
        }

        return \is_array($content) ? $content : [];
    }

public static function toJson(ResourceAbstract $resource, $options = 0, $serializer = DataArraySerializer::class)
    {
        $manager = new Manager();
        $manager->setSerializer(new $serializer());
        return $manager->createData($resource)->toJson($options);
    }

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


Question: // List mocks base method

func (m *MockNodeInterface) List(arg0 v10.ListOptions) (*v1.NodeList, error) {
	ret := m.ctrl.Call(m, "List", arg0)
	ret0, _ := ret[0].(*v1.NodeList)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

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

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


Question:
converts the parameters from an ellipse or a circle to a string for a
    Path object d-attribute

def ellipse2pathd(ellipse):
    """"""

    cx = ellipse.get('cx', 0)
    cy = ellipse.get('cy', 0)
    rx = ellipse.get('rx', None)
    ry = ellipse.get('ry', None)
    r = ellipse.get('r', None)

    if r is not None:
        rx = ry = float(r)
    else:
        rx = float(rx)
        ry = float(ry)

    cx = float(cx)
    cy = float(cy)

    d = ''
    d += 'M' + str(cx - rx) + ',' + str(cy)
    d += 'a' + str(rx) + ',' + str(ry) + ' 0 1,0 ' + str(2 * rx) + ',0'
    d += 'a' + str(rx) + ',' + str(ry) + ' 0 1,0 ' + str(-2 * rx) + ',0'

    return d

def parse_profile_from_hcard(hcard: str, handle: str):

    from federation.entities.diaspora.entities import DiasporaProfile  # Circulars
    doc = html.fromstring(hcard)
    profile = DiasporaProfile(
        name=_get_element_text_or_none(doc, ".fn"),
        image_urls={
            "small": _get_element_attr_or_none(doc, ".entity_photo_small .photo", "src"),
            "medium": _get_element_attr_or_none(doc, ".entity_photo_medium .photo", "src"),
            "large": _get_element_attr_or_none(doc, ".entity_photo .photo", "src"),
        },
        public=True if _get_element_text_or_none(doc, ".searchable") == "true" else False,
        id=handle,
        handle=handle,
        guid=_get_element_text_or_none(doc, ".uid"),
        public_key=_get_element_text_or_none(doc, ".key"),
    )
    return profile

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


Question:
Ustawia formularz
@param \Mmi\Form\Form $form
@return \Mmi\Form\Element\File

public function setForm(\Mmi\Form\Form $form)
    {
        parent::setForm($form);
        //nazwa pola
        $namespace = $form->getBaseName();
        $fieldName = $this->getName();
        $files = \Mmi\App\FrontController::getInstance()->getRequest()->getFiles();
        //brak pliku
        if (!isset($files->{$namespace})) {
            return $this;
        }
        foreach (($files->{$namespace})->toArray() as $file){
            //opakowanie w array jeśli plik jest jeden
            if ($file instanceof \Mmi\Http\RequestFile) {
                $this->_files[] = $file;
            }
        }

        return $this;
    }

public function interceptAfterUpload($str) {
	$this->logDebug('interceptAfterUpload', 'Entering function');
	$this->logPHPDebug('interceptAfterUpload', $this->files);

	if (count($this->files) > 0) {
		if (isset($this->classparams['callbackAfterUploadManagement'])) {
			$this->logDebug('interceptAfterUpload', 'Before call of ' .$this->classparams['callbackAfterUploadManagement']);
			$strForFListContent = call_user_func($this->classparams['callbackAfterUploadManagement'], $this, $this->files);
		} else {
			$strForFListContent = $this->defaultAfterUploadManagement();
		}
		$str = preg_replace('/'.$this->classparams['tag_flist'].'/', $strForFListContent, $str);
	}
	return $this->generateAppletTag($str);
}

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


Question:
Convert a YAML string to a JS object.

@param string value A YAML string

@return object A JS object representing the YAML string

function(value)
	{
		var result = null;
		value = this.trim(value);

		if ( 0 == value.length )
		{
			return '';
		}

		switch ( value.charAt(0) )
		{
			case '[':
				result = this.parseSequence(value);
				break;
			case '{':
				result = this.parseMapping(value);
				break;
			default:
				result = this.parseScalar(value);
		}

		// some comment can end the scalar
		if ( value.substr(this.i+1).replace(/^\s*#.*$/, '') != '' ) {
		    console.log("oups "+value.substr(this.i+1));
			throw new YamlParseException('Unexpected characters near "'+value.substr(this.i)+'".');
		}

		return result;
	}

def check_eyaml_data(name, val)
      error = nil
      if val.is_a? String
        err = check_eyaml_blob(val)
        error = "Key #{name} #{err}" if err
      elsif val.is_a? Array
        val.each_with_index do |v, idx|
          error = check_eyaml_data("#{name}[#{idx}]", v)
          break if error
        end
      elsif val.is_a? Hash
        val.each do |k,v|
          error = check_eyaml_data("#{name}['#{k}']", v)
          break if error
        end
      end
      error
    end

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


Question:
Returns true if the current user can access this course.
@return bool

public function can_access() {
        if ($this->canaccess === null) {
            $this->canaccess = can_access_course($this->record);
        }
        return $this->canaccess;
    }

public static function checkFamilyAccess(Family $family = null, $edit = false): void
    {
        if ($family === null) {
            throw new FamilyNotFoundException();
        }

        if (!$family->canShow()) {
            throw new FamilyAccessDeniedException();
        }

        if ($edit && !$family->canEdit()) {
            throw new FamilyAccessDeniedException();
        }
    }

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


Question:
Converts a camelcased string to another separator, using 'infix' as the separator.

@param string $str
@param string $infix
@return string

public static function infix($str, $infix)
    {
        return lcfirst(
            preg_replace_callback(
                '/(?<=.)[A-Z]/',
                function ($m) use ($infix) {
                    return $infix . strtolower($m[0]);
                },
                $str
            )
        );
    }

public function toNamespacedString($namespace, array $aliased_classes, $this_class, $use_phpdoc_format)
    {
        if ($this->fq_classlike_name === 'static') {
            return 'static::' . $this->const_name;
        }

        if ($this->fq_classlike_name === $this_class) {
            return 'self::' . $this->const_name;
        }

        if ($namespace && stripos($this->fq_classlike_name, $namespace . '\\') === 0) {
            return preg_replace(
                '/^' . preg_quote($namespace . '\\') . '/i',
                '',
                $this->fq_classlike_name
            ) . '::' . $this->const_name;
        }

        if (!$namespace && stripos($this->fq_classlike_name, '\\') === false) {
            return $this->fq_classlike_name . '::' . $this->const_name;
        }

        if (isset($aliased_classes[strtolower($this->fq_classlike_name)])) {
            return $aliased_classes[strtolower($this->fq_classlike_name)] . '::' . $this->const_name;
        }

        return '\\' . $this->fq_classlike_name . '::' . $this->const_name;
    }

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


Question: Build the link - keep the date range, reset the rest.

public function AllTagsLink()
    {
        $link = HTTP::setGetVar('tag', null, null, '&');
        $link = HTTP::setGetVar('month', null, $link, '&');
        $link = HTTP::setGetVar('year', null, $link, '&');
        $link = HTTP::setGetVar('start', null, $link, '&');

        return $link;
    }

def clear_provider_links(self):

        # Implemented from template for osid.learning.ActivityForm.clear_assets_template
        if (self.get_provider_links_metadata().is_read_only() or
                self.get_provider_links_metadata().is_required()):
            raise errors.NoAccess()
        self._my_map['providerLinkIds'] = self._provider_links_default

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


Question: // Error returns the fieldError's error message

func (fe *fieldError) Error() string {
	return fmt.Sprintf(fieldErrMsg, fe.ns, fe.Field(), fe.tag)
}

public function main()
    {
        if (null === $this->getFile()) {
            $msg = "JsonValidate: file is not defined.";
            $this->log($msg, Project::MSG_ERR);
            throw new \BuildException($msg);
        }

        if (!file_exists($this->getFile()) || is_dir($this->getFile())) {
            $msg = "JsonValidate: file not found " . $this->getFile();
            $this->log($msg, Project::MSG_ERR);
            throw new \BuildException($msg);
        }

        $decoded = json_decode(file_get_contents($this->getFile()));
        if (null === $decoded) {
            $msg = "JsonValidate: decoding " . $this->getFile() . " failed.";
            $this->log($msg, Project::MSG_ERR);
            throw new \BuildException($msg);
        }
        $this->log($this->getFile() . " is valid JSON", Project::MSG_INFO);
    }

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


Question: {{{ public function buildDemoUI()

public function buildDemoUI(SwatUI $ui)
	{
		$ui->getWidget('medium')->setCurrentPage(4);

		$ui->getWidget('beginning')->setCurrentPage(4);
		$ui->getWidget('middle')->setCurrentPage(49);
		$ui->getWidget('end')->setCurrentPage(94);

		$ui->getWidget('small')->setCurrentPage(50);
	}

protected function addMutatorClose(&$script, Column $column)
    {
        $this->addMutatorCloseBody($script, $column);
        $this->addMutatorCloseClose($script, $column);
    }

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


Question:
Staticly create instance

@return Crophandler

public static function create($baseFolder = null, $cropsFolder = null, $adaptor = null)
    {
        return new static( $baseFolder, $cropsFolder, $adaptor );
    }

public function newFromBuilder($attributes = [], $connection = null)
    {
        $model = $this->newInstance([], true);

        $model->setRawAttributes((array) $attributes, true);

        $model->setConnection($connection ?: $this->getConnectionName());

        $model->fireModelEvent('retrieved', false);

        return $model;
    }

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


Question: // sortStringKeys returns a sorted list of strings given a map[string]*.

func sortStringKeys(m interface{}) []string {
	v := reflect.ValueOf(m)
	t := v.Type()
	if t.Kind() != reflect.Map || t.Key().Kind() != reflect.String {
		panic(fmt.Sprintf(
			"sortStringKeys may be called with a map[string]* only"))
	}

	keys := v.MapKeys()
	sortedKeys := make([]string, 0, len(keys))

	for _, k := range keys {
		key := k.Interface().(string)
		sortedKeys = append(sortedKeys, key)
	}

	sort.Strings(sortedKeys)
	return sortedKeys
}

@SuppressWarnings("unchecked")
  public static <K extends Comparable<K>, V> AtomicSortedMapType<K, V> instance() {
    return INSTANCE;
  }

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


Question: Load roller shutter from JSON.

def load_roller_shutter(self, item):
        """"""
        rollershutter = RollerShutter.from_config(self.pyvlx, item)
        self.add(rollershutter)

public function getIterator()
    {
        $resourcesGetMethod = $this->pageStreamingDescriptor->getResourcesGetMethod();
        foreach ($this->getResponseObject()->$resourcesGetMethod() as $element) {
            yield $element;
        }
    }

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


Question: // TranslateInTreeStorageClassParametersToCSI translates InTree Cinder storage class parameters to CSI storage class

func (t *osCinderCSITranslator) TranslateInTreeStorageClassParametersToCSI(scParameters map[string]string) (map[string]string, error) {
	return scParameters, nil
}

def hildatree2dgparentedtree(self):

        def transform(hilda_tree):
            """Transform a HILDA parse tree into a more conventional parse tree.

            The input tree::

                                  Contrast[S][N]
                         _______________|______________
                  Although they                  they accepted
                did n't like it ,                 the offer .

            is converted into::

                                  Contrast
                         ____________|___________
                        S                        N
                        |                        |
                  Although they            they accepted
                did n't like it ,           the offer .
            """
            if isinstance(hilda_tree, basestring) or not hasattr(hilda_tree, 'label'):
                return hilda_tree
            assert len(hilda_tree) == 2, "We can only handle binary trees."

            match = HILDA_REL_RE.match(hilda_tree.label())
            assert match, "Relation '{}' does not match regex '{}'".format(hilda_tree.label(), HILDA_REL_RE)
            relname, left_child_nuc, right_child_nuc = match.groups()
            hilda_tree._label = relname

            for i, child_nuclearity in enumerate([left_child_nuc, right_child_nuc]):
                child = hilda_tree[i]
                hilda_tree[i] = Tree(child_nuclearity, [transform(child)])
            return hilda_tree

        tree = transform(self.hildafile_tree)
        return DGParentedTree.convert(tree)

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


Question:
Retrieve a new access token and store it in cache
@param mixed $scopes
@param string $cacheKey

private function retrieveToken($scopes, $cacheKey)
  {
    $this->token = AppIdentityService::getAccessToken($scopes);
    if ($this->token) {
      $this->client->getCache()->set(
          $cacheKey,
          $this->token
      );
    }
  }

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

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


Question:
Check that the specified argument is non-null

@param argument The argument
@param name The name of the argument
@throws IllegalArgumentException If argument is null

public static void isNotNull( Object argument,
                                  String name ) {
        if (argument == null) {
            throw new IllegalArgumentException(CommonI18n.argumentMayNotBeNull.text(name));
        }
    }

protected XmlElement buildSqlClause(IntrospectedTable introspectedTable) {

    XmlElement sql = new XmlElement("sql");
    sql.addAttribute(new Attribute("id", IDENTIFIERS_ARRAY_CONDITIONS));

    XmlElement foreach = new XmlElement("foreach");
    foreach.addAttribute(new Attribute("collection", "array"));
    foreach.addAttribute(new Attribute("item", "item"));
    foreach.addAttribute(new Attribute("index", "index"));
    foreach.addAttribute(new Attribute("separator", " and "));

    StringBuilder sb = new StringBuilder();
    for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) {
      XmlElement isEqualElement = new XmlElement("if");
      sb.setLength(0);
      sb.append("item == \'");
      sb.append(introspectedColumn.getJavaProperty());
      sb.append("\'");
      isEqualElement.addAttribute(new Attribute("test", sb.toString()));
      foreach.addElement(isEqualElement);

      sb.setLength(0);
      sb.append(MyBatis3FormattingUtilities.getAliasedEscapedColumnName(introspectedColumn));
      sb.append(" = ");
      sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, PROPERTY_PREFIX));

      isEqualElement.addElement(new TextElement(sb.toString()));
    }

    sql.addElement(foreach);
    return sql;
  }

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


Question:
[geRest get a list of Rest Resouces].

@param bool $rest_status return Rest Resources by status

@return array list of rest resources

public function getRestResources($rest_status = false)
    {
        $config = $this->getRestDrupalConfig();

        $resources = $this->pluginManagerRest->getDefinitions();

        $enabled_resources = array_combine(array_keys($config), array_keys($config));
        $available_resources = ['enabled' => [], 'disabled' => []];

        foreach ($resources as $id => $resource) {
            $status = in_array($id, $enabled_resources) ? 'enabled' : 'disabled';
            $available_resources[$status][$id] = $resource;
        }

        // Sort the list of resources by label.
        $sort_resources = function ($resource_a, $resource_b) {
            return strcmp($resource_a['label'], $resource_b['label']);
        };
        if (!empty($available_resources['enabled'])) {
            uasort($available_resources['enabled'], $sort_resources);
        }
        if (!empty($available_resources['disabled'])) {
            uasort($available_resources['disabled'], $sort_resources);
        }

        if (isset($available_resources[$rest_status])) {
            return [$rest_status => $available_resources[$rest_status]];
        }

        return $available_resources;
    }

private function parse($body)
    {
        $result = array();
        $data = json_decode($body);

        $response = is_array($data->response) ? new \stdClass : $data->response;
        if (null == $response) {
            $response = $data;
        }
        $response->errors = $data->errors;
        $response->test = isset($data->test) ? $data->test : $response->test;

        if ($data->successful == true) {
            if ((isset($response->authorized)
                && $response->authorized == true)
                || (isset($response->id)
                && $response->id !== null)
            ) {
                $response->authorization_id = isset($response->id)
                    ? $response->id
                    : $response->token;
            } else {
                $response->authorization_id = null;
            }

            $response->success = true;
        } else {
            $response->success = false;
            $response->authorization_id = null;
        }

        $response->message = isset($response->message) ? $response->message : $data->errors;

        return (array) $response;

    }

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


Question: Determine URL to view commits for repo.

def get_commit_url(repo_url):
    """"""
    if "github.com" in repo_url:
        return repo_url[:-4] if repo_url.endswith(".git") else repo_url
    if "git.openstack.org" in repo_url:
        uri = '/'.join(repo_url.split('/')[-2:])
        return "https://github.com/{0}".format(uri)

    # If it didn't match these conditions, just return it.
    return repo_url

public static ns_conf_revision_history[] get(nitro_service client) throws Exception
	{
		ns_conf_revision_history resource = new ns_conf_revision_history();
		resource.validate("get");
		return (ns_conf_revision_history[]) resource.get_resources(client);
	}

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


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

func (s *UpdatePresetInput) SetName(v string) *UpdatePresetInput {
	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:
Gets a resource group.

@param resourceGroupName The name of the resource group to get. The name is case insensitive.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ResourceGroupInner object

public Observable<ResourceGroupInner> getAsync(String resourceGroupName) {
        return getWithServiceResponseAsync(resourceGroupName).map(new Func1<ServiceResponse<ResourceGroupInner>, ResourceGroupInner>() {
            @Override
            public ResourceGroupInner call(ServiceResponse<ResourceGroupInner> response) {
                return response.body();
            }
        });
    }

public Observable<ServiceResponse<LuisApp>> exportWithServiceResponseAsync(UUID appId, String versionId) {
        if (this.client.endpoint() == null) {
            throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
        }
        if (appId == null) {
            throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
        }
        if (versionId == null) {
            throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
        }
        String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
        return service.export(appId, versionId, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<LuisApp>>>() {
                @Override
                public Observable<ServiceResponse<LuisApp>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<LuisApp> clientResponse = exportDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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


Question:
Extracts the contents from a TAR file.
@param string $filename TAR file name.
@param string $target   Target path.

@throws Exception\IO\Input\FileCorruptedException

@return bool

protected function extractTarFile($filename, $target)
    {
        $fileHandler = fopen($filename, 'r');
        $hardlinks = [];

        while (false === $this->isEof($fileHandler)) {
            $fields = $this->readBlockHeader($fileHandler, $filename);

            // deal with empty blocks in sparse files
            if (true === $fields['is_empty']) {
                continue;
            }

            if (false === $fields['is_valid_checksum']) {
                throw new Exception\IO\Input\FileCorruptedException($filename);
            }

            $name = $fields['name'];
            $type = $fields['type'];

            $location = $target . DIRECTORY_SEPARATOR . $name;
            switch ($type) {
                case self::TYPE_FILE:
                    $this->doExtractFile($location, $fields, $fileHandler);
                    break;
                case self::TYPE_DIRECTORY:
                    $this->doExtractDir($location);
                    break;
                case self::TYPE_HARD_LINK:
                    $hardlinks[$location] = $fields;
                    break;
                case self::TYPE_SYMBOLIC_LINK:
                    $this->doExtractSymLink($location, $fields);
                    break;
            }
        }

        // This should be done after extract all the files
        foreach ($hardlinks as $location => $fields) {
            $this->doExtractHardLink($location, $fields, $target);
        }

        fclose($fileHandler);

        return true;
    }

public function syst()
	{
		// If native FTP support is enabled lets use it...
		if (FTP_NATIVE)
		{
			if (($ret = @ftp_systype($this->conn)) === false)
			{
				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}
		}
		else
		{
			// Send print working directory command and verify success
			if (!$this->_putCmd('SYST', 215))
			{
				throw new FilesystemException(sprintf('%1$s: Bad response.  Server response: %2$s [Expected: 215]', __METHOD__, $this->response));
			}

			$ret = $this->response;
		}

		// Match the system string to an OS
		if (strpos(strtoupper($ret), 'MAC') !== false)
		{
			$ret = 'MAC';
		}
		elseif (strpos(strtoupper($ret), 'WIN') !== false)
		{
			$ret = 'WIN';
		}
		else
		{
			$ret = 'UNIX';
		}

		// Return the os type
		return $ret;
	}

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


Question:
Returns a promise which resolves with an array of all "progress" events

@param ReadableStreamInterface $stream
@param string                  $progressEventName the name of the event to collect
@return PromiseInterface Promise<array, Exception>

public function deferredStream(ReadableStreamInterface $stream, $progressEventName)
    {
        // cancelling the deferred will (try to) close the stream
        $deferred = new Deferred(function () use ($stream) {
            $stream->close();

            throw new RuntimeException('Cancelled');
        });

        if ($stream->isReadable()) {
            // buffer all data events for deferred resolving
            $buffered = array();
            $stream->on($progressEventName, function ($data) use (&$buffered) {
                $buffered []= $data;
            });

            // error event rejects
            $stream->on('error', function ($error) use ($deferred) {
                $deferred->reject($error);
            });

            // close event resolves with buffered events (unless already error'ed)
            $stream->on('close', function () use ($deferred, &$buffered) {
                $deferred->resolve($buffered);
            });
        } else {
            $deferred->reject(new RuntimeException('Stream already ended, looks like it could not be opened'));
        }

        return $deferred->promise();
    }

public void marshall(StreamInfo streamInfo, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(streamInfo.getDeviceName(), DEVICENAME_BINDING);
            protocolMarshaller.marshall(streamInfo.getStreamName(), STREAMNAME_BINDING);
            protocolMarshaller.marshall(streamInfo.getStreamARN(), STREAMARN_BINDING);
            protocolMarshaller.marshall(streamInfo.getMediaType(), MEDIATYPE_BINDING);
            protocolMarshaller.marshall(streamInfo.getKmsKeyId(), KMSKEYID_BINDING);
            protocolMarshaller.marshall(streamInfo.getVersion(), VERSION_BINDING);
            protocolMarshaller.marshall(streamInfo.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(streamInfo.getCreationTime(), CREATIONTIME_BINDING);
            protocolMarshaller.marshall(streamInfo.getDataRetentionInHours(), DATARETENTIONINHOURS_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 \Generated\Shared\Transfer\QuoteTransfer $quoteTransfer
@param \Generated\Shared\Transfer\CheckoutResponseTransfer $checkoutResponseTransfer

@return bool

public function checkoutConditionalAvailabilityPingPreCondition(QuoteTransfer $quoteTransfer, CheckoutResponseTransfer $checkoutResponseTransfer): bool
    {
        return $this->getFactory()
            ->createConditionalAvailabilityPingPreCondition()
            ->checkCondition($quoteTransfer, $checkoutResponseTransfer);
    }

public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator)
    {
        $classes = [
            'QueryType' =>[
                'namespace' => 'GraphQL\\Query',
                'template' => 'Query.tpl.php',
                'variables' => [
                    'fields' => []
                ]
            ],
            'MutationType' =>[
                'namespace' => 'GraphQL\\Mutation',
                'template' => 'Mutation.tpl.php',
                'variables' => [
                    'fields' => []
                ]
            ],
            'schema' =>[
                'namespace' => 'GraphQL',
                'template' =>'Schema.tpl.php',
                'variables' => []
            ],
        ];

        $configFile = dirname($this->rootDir).'/config/packages/graphql.yaml';
        if(!is_file($configFile)) {
            $generator->generateFile(
                $configFile,
                dirname(dirname(__FILE__)) . '/Resources/skeleton/graphql.tpl.yaml',
                []
            );
        }

        foreach ($classes as $name => $class) {
            $classNameDetails = $generator->createClassNameDetails(
                $name,
                $class['namespace']
            );

            $generator->generateClass(
                $classNameDetails->getFullName(),
                dirname(dirname(__FILE__)) . '/Resources/skeleton/' . $class['template'],
                $class['variables']
            );

            $generator->writeChanges();
        }

        $this->writeSuccessMessage($io);
        $io->text(
            [
                'Next: Create type (able to generate type from existing Entity).',
                'To create type use "maker:graphql:type"',
            ]
        );
    }

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


Question:
Convert the given UTF-8 encoded string to CP437

Same caveats as for cpToUtf8() apply

@param $string
@return string

protected function utf8ToCp($string)
    {
        // try iconv first
        if (function_exists('iconv')) {
            $conv = @iconv('UTF-8', 'CP437//IGNORE', $string);
            if($conv) return $conv; // it worked
        }

        // still here? iconv failed to convert the string. Try another method
        // see http://php.net/manual/en/function.iconv.php#108643

        if (function_exists('mb_convert_encoding')) {
            return mb_convert_encoding($string, 'CP850', 'UTF-8');
        } else {
            return $string;
        }
    }

public function export_translations(EntryTranslations $entry)
    {
        //TODO: warnings for control characters
        return $entry->is_plural ? implode(chr(0), $entry->translations) : $entry->translations[0];
    }

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


Question:
// MustTime always parses with RFC3339 format and returns value without error,
// it returns zero value if error occurs.

func (k *Key) MustTime(defaultVal ...time.Time) time.Time {
	return k.MustTimeFormat(time.RFC3339, defaultVal...)
}

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: Returns whether stable (post-0.x) releases seem to exist.

def has_stable_releases(self):

        nonzeroes = self.stable_families
        # Nothing but 0.x releases -> yup we're prehistory
        if not nonzeroes:
            return False
        # Presumably, if there's >1 major family besides 0.x, we're at least
        # one release into the 1.0 (or w/e) line.
        if len(nonzeroes) > 1:
            return True
        # If there's only one, we may still be in the space before its N.0.0 as
        # well; we can check by testing for existence of bugfix buckets
        return any(
            x for x in self[nonzeroes[0]] if not x.startswith('unreleased')
        )

func NewWorker(
	upgradeComplete gate.Lock,
	agent agent.Agent,
	apiConn api.Connection,
	jobs []multiwatcher.MachineJob,
	openState func() (*state.StatePool, error),
	preUpgradeSteps func(st *state.StatePool, agentConf agent.Config, isController, isMasterServer, isCaas bool) error,
	machine StatusSetter,
	isCaas bool,
) (worker.Worker, error) {
	w := &upgradesteps{
		upgradeComplete: upgradeComplete,
		agent:           agent,
		apiConn:         apiConn,
		jobs:            jobs,
		openState:       openState,
		preUpgradeSteps: preUpgradeSteps,
		machine:         machine,
		tag:             agent.CurrentConfig().Tag(),
		isCaas:          isCaas,
	}
	w.tomb.Go(w.run)
	return w, nil
}

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


Question:
Converts the internal stat type of yappi(which is returned by a call to YFuncStats.get())
    as pstats object.

def convert2pstats(stats):

    if not isinstance(stats, YFuncStats):
        raise YappiError("Source stats must be derived from YFuncStats.")

    import pstats
    class _PStatHolder:
        def __init__(self, d):
            self.stats = d
        def create_stats(self):
            pass
    def pstat_id(fs):
        return (fs.module, fs.lineno, fs.name)

    _pdict = {}

    # convert callees to callers
    _callers = {}
    for fs in stats:
        if not fs in _callers:
            _callers[fs] = {}

        for ct in fs.children:
            if not ct in _callers:
                _callers[ct] = {}
            _callers[ct][pstat_id(fs)] = (ct.ncall, ct.nactualcall, ct.tsub ,ct.ttot)

    # populate the pstat dict.
    for fs in stats:
        _pdict[pstat_id(fs)] = (fs.ncall, fs.nactualcall, fs.tsub, fs.ttot, _callers[fs], )

    return pstats.Stats(_PStatHolder(_pdict))

def chain_specs(specs):

    LOG.info("Parsing %s specs", len(specs))
    # First spec is always an input
    pin = pypein.input_for(specs[0]).__iter__()
    # If only an input spec was provided, then use json for output
    if len(specs) == 1:
        pout = pypeout.output_for("json")
    else:
        # Middle specs are filters that successively wrap input
        for s in specs[1:-1]:
            pin = pypef.filter_for(s).filter(pin)
        # Assume output on last spec, but it may be a filter.
        # If last spec is a filter, use json for output
        try:
            pout = pypeout.output_for(specs[-1])
        except pypeout.NoSuchOutputException:
            pin = pypef.filter_for(specs[-1]).filter(pin)
            pout = pypeout.output_for("json")
    return pout, pin

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


Question:
Run blockstackd.  Optionally daemonize.
    Return 0 on success
    Return negative on error

def run_server(working_dir, foreground=False, expected_snapshots=GENESIS_SNAPSHOT, port=None, api_port=None, use_api=None, use_indexer=None, indexer_url=None, recover=False):

    global rpc_server
    global api_server

    indexer_log_path = get_logfile_path(working_dir)

    logfile = None
    if not foreground:
        if os.path.exists(indexer_log_path):
            logfile = open(indexer_log_path, 'a')
        else:
            logfile = open(indexer_log_path, 'a+')

        child_pid = daemonize(logfile)
        if child_pid < 0:
            log.error("Failed to daemonize: {}".format(child_pid))
            return -1

        if child_pid > 0:
            # we're the parent
            log.debug("Running in the background as PID {}".format(child_pid))
            sys.exit(0)

    server_state = server_setup(working_dir, port=port, api_port=api_port, indexer_enabled=use_indexer, indexer_url=indexer_url, api_enabled=use_api, recover=recover)
    atexit.register(server_shutdown, server_state)

    rpc_server = server_state['rpc']

    blockstack_opts = get_blockstack_opts()
    blockstack_api_opts = get_blockstack_api_opts()

    if blockstack_opts['enabled']:
        log.debug("Begin Indexing")
        while is_running():
            try:
               running = index_blockchain(server_state, expected_snapshots=expected_snapshots)
            except Exception, e:
               log.exception(e)
               log.error("FATAL: caught exception while indexing")
               os.abort()

            # wait for the next block
            deadline = time.time() + REINDEX_FREQUENCY
            while time.time() < deadline and is_running():
                try:
                    time.sleep(1.0)
                except:
                    # interrupt
                    break

        log.debug("End Indexing")

    elif blockstack_api_opts['enabled']:
        log.debug("Begin serving REST requests")
        while is_running():
            try:
                time.sleep(1.0)
            except:
                # interrupt
                break

        log.debug("End serving REST requests")

    server_shutdown(server_state)

    # close logfile
    if logfile is not None:
        logfile.flush()
        logfile.close()

    return 0

public function storeTubeStats(QueueRepo $queue)
    {
        $history = History::firstOrNew(['date' => date('Y-m-d'),
                                        'hour' => date('H'),
                                        'queue_id' => $queue->id]);

        $history->pending_count = $this->getPendingJobsCount($queue);
        $history->failed_count = $this->getFailedJobsCount($queue);

        $history->exception_count += Cache::pull('eyewitness_q_exception_count_'.$queue->id);
        $history->process_count += Cache::pull('eyewitness_q_process_count_'.$queue->id);
        $history->process_time += Cache::pull('eyewitness_q_process_time_'.$queue->id);
        $history->sonar_time += Cache::pull('eyewitness_q_sonar_time_'.$queue->id);
        $history->sonar_count += Cache::pull('eyewitness_q_sonar_count_'.$queue->id);
        $history->idle_time += Cache::pull('eyewitness_q_idle_time_'.$queue->id);

        $deploy = Cache::get('eyewitness_q_sonar_deployed_'.$queue->id, null);
        if (is_null($deploy)) {
            $history->sonar_deployed = null;
        } else {
            $history->sonar_deployed = time()-$deploy;
        }

        $history->save();
    }

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